2

I have a pandas dataframe df1

    a    b
0   1    2

1   3    4

I have another dataframe in the form of a dictionary

dictionary = {'2' : [5, 6], '3' : [7, 8]}

I want to append the dictionary values as rows in dataframe df1. I am using pandas.DataFrame.from_dict() to convert the dictionary into dataframe. The constraint is, when I do it, I cannot provide any value to the 'column' argument for the method from_dict().

So, when I try to concatenate the two dataframes, the pandas adds the contents of the new dataframe as new columns. I do not want that. The final output I want is in the format

    a    b
0   1    2

1   3    4

2   5    6

3   7    8

Can someone tell me how do I do this in least painful way?

3
  • 1
    Does this answer your question? Create a Pandas Dataframe by appending one row at a time Commented Feb 1, 2023 at 11:02
  • 2
    @Joooeey append is being deprecated in pandas. Commented Feb 1, 2023 at 11:03
  • Right, I didn't take a good look at the answers given there. Commented Feb 1, 2023 at 11:22

2 Answers 2

3

Use concat with help of pd.DataFrame.from_dict, setting the columns of df1 during the conversion:

out = pd.concat([df1,
                 pd.DataFrame.from_dict(dictionary, orient='index',
                                        columns=df1.columns)
                 ])

Output:

   a  b
0  1  2
1  3  4
2  5  6
3  7  8
Sign up to request clarification or add additional context in comments.

Comments

0

Another possible solution, which uses numpy.vstack:

pd.DataFrame(np.vstack([df.values, np.array(
    list(dictionary.values()))]), columns=df.columns)

Output:

   a  b
0  1  2
1  3  4
2  5  6
3  7  8

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.