简体   繁体   中英

create pandas df from dictionary but in a special format

Supposed I have the dictionary d:

d = dict(A =[1,2], B=[1,2,3,4])
print d
{'A': [1, 2], 'B': [1, 2, 3, 4]}

I would like to create a pandas df with two cols labeled nodeid and rowid that looks like this:

nodeid  rowid
A       1 
A       2 
B       1 
B       2 
B       3 
B       4

All the examples I have found that create a pandas df from a dict give the dict key as the name of the col and then row entries are whether that key had a particular value, with a NaN if that node didn't have that value.

Try:

df = pd.DataFrame([(k, v) for (k, l) in d.items() for v in l], 
              columns=['nodeid', 'rowid'])

and it gives:

    nodeid  rowid
0   A   1
1   A   2
2   B   1
3   B   2
4   B   3
5   B   4

Try this :

df = pd.DataFrame([[k,d[k][i]] for k in d for i in range(len(d[k]))], columns= ['nodeid', 'rowid'])

OUTPUT :

  nodeid  rowid
0      A      1
1      A      2
2      B      1
3      B      2
4      B      3
5      B      4

One way

pd.Series(d).apply(pd.Series).stack().reset_index(level=0).\
    rename(columns={'level_0':'nodeid',0:'rowid'})
  nodeid  rowid
0      A    1.0
1      A    2.0
0      B    1.0
1      B    2.0
2      B    3.0
3      B    4.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM