7

I have a dataframe and i need to add data only to a specific column

DF

A  B  C
1  2  3
2  3  4
a  d  f
22 3  3

output :

A  B  C
1  2  3
2  3  4
a  d  f
22 3  3
32
      34

I tried : df['A'].append(pd.DataFrame([valuetoadd]), ignore_index=True) where valuetoadd is a variable

3
  • 1
    What value do you want to add and to which column? Please share the expected output and sample input. Commented Nov 15, 2018 at 10:50
  • Edited... please check Commented Nov 15, 2018 at 10:51
  • 2
    You want to add 32 to column 'A' and 34 to Column 'C'? Commented Nov 15, 2018 at 10:53

3 Answers 3

12

You can use pandas.DataFrame.append with a dictionary (or list of dictionaries, one per row):

>> df.append({'A':32}, ignore_index=True)

    A    B    C
0   1    2    3
1   2    3    4
2   a    d    f
3  22    3    3
4  32  NaN  NaN


>> df.append([{'A':32}, {'C':34}], ignore_index=True)

     A    B    C
0    1    2    3
1    2    3    4
2    a    d    f
3   22    3    3
4   32  NaN  NaN
5  NaN  NaN   34
Sign up to request clarification or add additional context in comments.

7 Comments

It is not adding
Instead of 32 I need value from a a variable to beadded
I am trying to add into empty dataframe
After checking both answers, I realized you will need to have df=df.append({'A':32}, ignore_index=True), so that you can have your df assigned the appended version.
unfortunately it is deprecated now
|
7

You can use pandas.DataFrame.append with a dictionary (or list of dictionaries, one per row):

df=df.append({'a':variable1}, ignore_index=True)
df=df.append({'a':variable1,'b':variable2}, ignore_index=True)

Comments

1

As .append is deprecated now, another solution using pd.concat would be:

df = pd.concat([df, pd.DataFrame({"A":[32]})], ignore_index=True)

I'd prefer the old syntax, though.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.