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?

  • 1
    Does this answer your question? [Create a Pandas Dataframe by appending one row at a time](https://stackoverflow.com/questions/10715965/create-a-pandas-dataframe-by-appending-one-row-at-a-time) – Joooeey Feb 01 '23 at 11:02
  • 2
    @Joooeey `append` is being deprecated in pandas. – mozway Feb 01 '23 at 11:03
  • Right, I didn't take a good look at the answers given there. – Joooeey Feb 01 '23 at 11:22

2 Answers2

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
mozway
  • 194,879
  • 13
  • 39
  • 75
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
PaulS
  • 21,159
  • 2
  • 9
  • 26