[英]Pandas - Column Header to Row value
我正在嘗試實現對熊貓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
目標數據框:
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
目標DataFrame的順序並不重要。
Date標頭從本質上講擴展為多行,我們每月獲得一個條目,而不是每月一個列
這是一個典型的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
我相信融化功能也可以滿足這一要求。 熊貓博士說,wide_to_long更加用戶友好,但是melt函數提供了更大的靈活性。 隨着融化:
df.melt(id_vars=['Food','Type'],var_name = 'Month', value_name = 'Eaten')
id_vars值表示要保留的列。 其余的列將向下旋轉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.