[英]Pandas - Column Header to Row value
I'm trying to achieve the following transformation to a pandas DataFrame: 我正在尝试实现对熊猫DataFrame的以下转换:
Source DataFrame: 源数据帧:
Food Type Eaten 2018-01 Eaten 2018-02 Eaten 2018-03
0 Apple Fruit 3 4 0
1 Pizza Fast Food 2 1 3
2 Cake Desert 3 6 7
Target DataFrame: 目标数据框:
Food Type Month Eaten
0 Apple Fruit 2018-01 3
1 Apple Fruit 2018-02 4
2 Apple Fruit 2018-03 0
3 Pizza Fast Food 2018-01 2
4 Pizza Fast Food 2018-02 1
5 Pizza Fast Food 2018-03 3
6 Cake Desert 2018-01 3
7 Cake Desert 2018-02 6
8 Cake Desert 2018-03 7
The ordering of the target DataFrame is not important. 目标DataFrame的顺序并不重要。
The Date headers are essenssially beign expanded to multiple rows and we get an entry per month instead of one column per month Date标头从本质上讲扩展为多行,我们每月获得一个条目,而不是每月一个列
This is a typical wide_to_long
question 这是一个典型的wide_to_long
问题
pd.wide_to_long(df,'Eaten ',i=['Food','Type'],j='Month').reset_index()
Out[38]:
Food Type Month Eaten
0 Apple Fruit 2018-01 3
1 Apple Fruit 2018-02 4
2 Apple Fruit 2018-03 0
3 Pizza Fast Food 2018-01 2
4 Pizza Fast Food 2018-02 1
5 Pizza Fast Food 2018-03 3
6 Cake Desert 2018-01 3
7 Cake Desert 2018-02 6
8 Cake Desert 2018-03 7
I believe the melt function also satisfies this. 我相信融化功能也可以满足这一要求。 Pandas doc says wide_to_long is more user friendly but the melt function allows more flexibility. 熊猫博士说,wide_to_long更加用户友好,但是melt函数提供了更大的灵活性。 With melt: 随着融化:
df.melt(id_vars=['Food','Type'],var_name = 'Month', value_name = 'Eaten')
The id_vars value represents which columns you want to stay put. id_vars值表示要保留的列。 The remaining columns will be rotated down. 其余的列将向下旋转。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.