简体   繁体   English

熊猫从字典创建数据帧将元组转换为索引

[英]Pandas create dataframe from dict converting tuple to index

Is there a convenient way to implement a function make_dataframe , used as follows有没有方便的方法实现一个函数make_dataframe ,使用如下

mydict = {
    ('tom', 'gray') : [1,2,3,4,5],
    ('bill', 'ginger') : [6,7,8,9,10],
}

make_dataframe(mydict, tupleLabels=['catname', 'catcolor'], valueLabel='weight')

Expected result预期结果

| catname | catcolor | weight |
| tom | gray | 1 |
| tom | gray | 2 |
| tom | gray | 3 |
| tom | gray | 4 |
| tom | gray | 5 |
| bill | ginger | 6 |
| bill | ginger | 7 |
| bill | ginger | 8 |
| bill | ginger | 9 |
| bill | ginger | 10 |

It does not sound too difficult, I just don't want to reinvent the wheel听起来不太难,我只是不想重新发明轮子

You can create your own function using dataframe unstack after renaming the labels using rename_axis :您可以使用数据帧创建自己的功能unstack重命名使用的标签后rename_axis

def make_dataframe(dictionary , tupleLabels , valueLabel):
    return (pd.DataFrame(dictionary).rename_axis(tupleLabels,axis=1)
            .unstack().reset_index(tupleLabels,name=valueLabel))

out = make_dataframe(mydict, tupleLabels=['catname', 'catcolor'], valueLabel='weight')

print(out)

  catname catcolor  weight
0     tom     gray       1
1     tom     gray       2
2     tom     gray       3
3     tom     gray       4
4     tom     gray       5
0    bill   ginger       6
1    bill   ginger       7
2    bill   ginger       8
3    bill   ginger       9
4    bill   ginger      10

Your dictionary is misformatted for easy conversion to a Pandas DataFrame.您的字典格式错误,无法轻松转换为 Pandas DataFrame。

I suggest doing the following:我建议执行以下操作:


mydict = {
    ('tom', 'gray') : [1,2,3,4,5],
    ('bill', 'ginger') : [6,7,8,9,10],
}

l = [ [ k[0], k[1], val ] for k, v in mydict.items() for val in v ]

df = pd.DataFrame(l, columns=['catname', 'catcolor', 'weight'])

Which yields:其中产生:

  catname catcolor  weight
0     tom     gray       1
1     tom     gray       2
2     tom     gray       3
3     tom     gray       4
4     tom     gray       5
5    bill   ginger       6
6    bill   ginger       7
7    bill   ginger       8
8    bill   ginger       9
9    bill   ginger      10

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

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