Converting dictionary to dataframe

Viewed 59

In the following code, I have defined a dictionary and then converted it to a dataframe

my_dict = {
'A' : [1,2],
'B' : [4,5,6]
}
df = pd.DataFrame()
df = df.append(my_dict, ignore_index=True)

The output is a [1 rows x 2 columns] dataframe which looks like

         A         B
0    [1,2]   [4,5,6]

However, I would like to reshape it as

     A     B
0    1     4
1    2     5
2          6

How can I fix the code for that purpose?

4 Answers

You might use pandas.Series.explode as follows

import pandas as pd
my_dict = {
'A' : [1,2],
'B' : [4,5,6]
}
df = pd.DataFrame()
df = df.append(my_dict, ignore_index=True)
df = df.apply(lambda x:x.explode(ignore_index=True))
print(df)

output

     A  B
0    1  4
1    2  5
2  NaN  6

I apply explode to each column with ignore_index=True which prevent duplicate indices.

This will give you the results you are looking for if you don't mind changing your code a little

my_dict = {
'A' : [1,2,''],
'B' : [4,5,6]
}
df = pd.DataFrame(my_dict)
df

Another way of doing this is:

df = pd.DataFrame.from_dict(my_dict, 'index').T
print(df)

Output:

     A    B
0  1.0  4.0
1  2.0  5.0
2  NaN  6.0

Try this instead. you need to assign the dictionary to the dataframe. I've run it. It should give you the output you desire. don't use the append. It's to append one dataframe to another

import pandas as pd 

my_dict = {
'A' : [1,2,''],
'B' : [4,5,6]
}
df = pd.DataFrame(data=my_dict)
#df = df.append(my_dict, ignore_index=True)

print(df)
Related