'Converting dictionary to dataframe
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?
Solution 1:[1]
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
Solution 2:[2]
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.
Solution 3:[3]
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
Solution 4:[4]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | BeRT2me |
Solution 2 | Daweo |
Solution 3 | ArchAngelPwn |
Solution 4 | Janet |