简体   繁体   English

从字典中创建熊猫df,但格式特殊

[英]create pandas df from dictionary but in a special format

Supposed I have the dictionary d: 假设我有字典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: 我想创建一个带有两个cols的pandas df ,分别标记为nodeidrowid ,如下所示:

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. 我发现的所有示例均由dict创建一个pandas df给出dict关键字作为col的名称,然后行条目是该关键字是否具有特定值,如果该节点不具有该值,则输入NaN

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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