BillyJo_rambler
BillyJo_rambler

Reputation: 583

Adding Dictionaries with lists to a Pandas DataFrame (pd.DataFrame(dict) vs df.append(dict))

I am having a problem with adding a dictionary which contains lists into a pandas data-frame. My data looks like this:

a = {'id':[0,1,2,3,4,5,6],
 'value':[354,324,211,78,644,198,342]}

When you add a dictionary to a pandas dataframe, it adds the elements of each list to a row in the dataframe, like this:

test1 = pd.DataFrame(a)

But then, when I try to append a dictionary (the same dictionary in this case), each column then contains a list.

test1 = test1.append(a, ignore_index = True)

I have tried to find out why this is the case. Any help?

Thanks.

Upvotes: 3

Views: 1055

Answers (1)

Scott Boston
Scott Boston

Reputation: 153460

You could use pd.DataFrame again:

test1.append(pd.DataFrame(a), ignore_index=True)

Output:

    id  value
0    0    354
1    1    324
2    2    211
3    3     78
4    4    644
5    5    198
6    6    342
7    0    354
8    1    324
9    2    211
10   3     78
11   4    644
12   5    198
13   6    342

Or use pd.concat

pd.concat([test1,pd.DataFrame(a)])

Upvotes: 3

Related Questions