Home > Enterprise >  Appending rows to existing pandas dataframe
Appending rows to existing pandas dataframe

Time:02-01

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?

CodePudding user response:

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

CodePudding user response:

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
  • Related