0

I'm trying to add more rows or records to my data frame, let's say it looks like this:

ID   age   
44   23
31   25 

and I have a CSV file stored in another data frame without headers

33   55
22   23
29   22

now I want a new data frame that looks like this

ID   age   
44   23
31   25 
33   55
22   23
29   22

I have tried using append and concat but I didn't get the result that I wanted

4
  • In what way did you not get the result that you wanted? What did you get instead? Commented Sep 9, 2022 at 13:54
  • Does this answer your question? Pandas Append Not Working Commented Sep 9, 2022 at 13:55
  • 3
    @Att append is now deprecated, concat should be used Commented Sep 9, 2022 at 13:55
  • 1
    Also ignore_index is not going to solve the issue, it just helps having a nice index ;) Commented Sep 9, 2022 at 13:57

3 Answers 3

1

Assuming df1/df2, you can use set_axis to copy the axis of the first DataFrame, then concat:

out = pd.concat([df1, df2.set_axis(df1.columns, axis=1)], ignore_index=True)

output:

   ID  age
0  44   23
1  31   25
2  33   55
3  22   23
4  29   22

NB. ignore_index=True is optional, this is just to avoid having duplicated indices. Without it:

   ID  age
0  44   23
1  31   25
0  33   55
1  22   23
2  29   22
Sign up to request clarification or add additional context in comments.

Comments

0
import pandas as pd

# Your first df will be ‘df’

df_2 = pd.dataframe({“Id”: [33, 22, 29], “Age”: [55, 23, 22]})

df = df.append(df_2, ignore_index=True)

Comments

0

You can use this, and ignore_index if you want.

output = pd.concat([df1, df2.set_axis(df1['columns'], axis=1)])

2 Comments

How is this different from the logic of my answer posted 14 min ago? ;) (and actually this is incorrect)
@mozway. It is my opinion. Please do not go in negative direction

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.