vel*_*ssa 4 python dataframe pandas
我正在尝试对 Pandas 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
Run Code Online (Sandbox Code Playgroud)
目标数据帧:
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
Run Code Online (Sandbox Code Playgroud)
目标 DataFrame 的顺序并不重要。
日期标题本质上被扩展为多行,我们每月获得一个条目而不是每月一列
这是一个典型的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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1756 次 |
| 最近记录: |