I've a python dictionary
dict = {'Name':value,'Name2':value2,'Name3':value3}
And I want to create a DataFrame from there, but if I try this:
df = pd.DataFrame(dict)
I have two problems, first one is the not all items in the dictionary has the same value, second one and more important one, I want a one two column data frame in this format:
Name1 value
Name1 value
Name1 value
Name2 value
Name2 value
Name3 value
Name3 value
Name3 value
Name3 value
Rather than:
Name1 [value,value,value]
Name2 [value,value]
Name3 [value,value,value]
value = 1
value2 = 2
value3 = 3
mydict = {'Name':value,'Name2':value2,'Name3':value3}
df = pd.DataFrame(mydict.items(), columns=['Name', 'Values'])
Gives
Name Values
0 Name2 2
1 Name 1
2 Name3 3
Edited for giving support to lists in dictionary values:
If value
, value2
and value3
are lists:
import pandas as pd
value = [1,2,3]
value2 = [4,5,6]
value3 = [7,8,9]
mydict = {"Name1" : value, "Name2" : value2, "Name3" : value3 }
mydict
is {'Name1': [1, 2, 3], 'Name2': [4, 5, 6], 'Name3': [7, 8, 9]}
Then, assign a key to every single value in the dictionary:
mylist = [(key, x) for key,val in mydict.iteritems() for x in val]
Now, we have mylist
is
[('Name2', 4),
('Name2', 5),
('Name2', 6),
('Name3', 7),
('Name3', 8),
('Name3', 9),
('Name1', 1),
('Name1', 2),
('Name1', 3)]
And, finally, convert to dataframe
df = pd.DataFrame(mylist, columns=['Name', 'Values'])
The result is
df=
Name Values
0 Name2 4
1 Name2 5
2 Name2 6
3 Name3 7
4 Name3 8
5 Name3 9
6 Name1 1
7 Name1 2
8 Name1 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With