Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a two columns data frame from a dictionary

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]

like image 988
Luis Ramon Ramirez Rodriguez Avatar asked Feb 11 '16 11:02

Luis Ramon Ramirez Rodriguez


1 Answers

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, value2and 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 }

mydictis {'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
like image 141
csmaiz Avatar answered Sep 19 '22 14:09

csmaiz