Home > Software design >  Converting dictionary to dataframe
Converting dictionary to dataframe

Time:05-14

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?

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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