Python – Add a dictionary with a list to the Pandas DataFrame(pd. DataFrame(dict) vs df.append(dict))

Add a dictionary with a list to the Pandas DataFrame(pd. DataFrame(dict) vs df.append(dict))… here is a solution to the problem.

Add a dictionary with a list to the Pandas DataFrame(pd. DataFrame(dict) vs df.append(dict))

I’m having trouble adding a dictionary containing a list to 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 data frame, it adds elements from each list to one row in the data frame, as follows:

test1 = pd. DataFrame(a)

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

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

I’m trying to find out why this is the case. Does it help?

Thank you.

Solution

You can use PD. DataFrame:

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)])

Related Problems and Solutions