[英]How to unpivot pandas dataframe
我有一個 Pandas 數據框,如下所示:起始表:
科德 | 國家 | 程序 | 男性 | 男性 | 女性 | 女性 |
---|---|---|---|---|---|---|
科德 | 國家 | 程序 | 兩歲 | 三歲 | 兩歲 | 三歲 |
1a | 我們 | proc_1 | 4 | 6 | 3 | 6 |
1a | 英國 | proc_1 | 2 | 3 | 5 | 1 |
1b | 我們 | proc_2 | 15 | 3 | 5 | 2 |
1b | 英國 | proc_2 | 8 | 4 | 7 | 3 |
CSV:
Code;Country;Procedure;male;male;female;female
Code;Country;Procedure;two-year-old;three-year-old;two-year-old;three-year-old
1a;US;proc_1;4;6;3;6
1a;UK;proc_1;2;3;5;1
1b;US;proc_2;15;3;5;2
1b;UK;proc_2;8;4;7;3
我的python代碼:
df = pd.read_csv('test.csv',
header=[0,1],delimiter= ';',
engine='python',
encoding= 'unicode_escape')
事實上,我有兩個行標題如何旋轉熊貓數據框以獲得以下結果?
結果表:
代碼 | 國家 | 程序 | 性別 | 年齡 | 頻率 |
---|---|---|---|---|---|
1a | 我們 | proc_1 | 男性 | 兩歲 | 4 |
1a | 我們 | proc_1 | 男性 | 三歲 | 6 |
1a | 我們 | proc_1 | 女性 | 兩歲 | 3 |
1a | 我們 | proc_1 | 女性 | 三歲 | 6 |
1a | 英國 | proc_1 | 男性 | 兩歲 | 2 |
1a | 英國 | proc_1 | 男性 | 三歲 | 3 |
1a | 英國 | proc_1 | 女性 | 兩歲 | 5 |
1a | 英國 | proc_1 | 女性 | 三歲 | 1 |
1b | ... |
import io
import pandas as pd
piv = pd.read_csv(io.StringIO("""Code;Country;Procedure;male;male;female;female
Code;Country;Procedure;two-year-old;three-year-old;two-year-old;three-year-old
1a;US;proc_1;4;6;3;6
1a;UK;proc_1;2;3;5;1
1b;US;proc_2;15;3;5;2
1b;UK;proc_2;8;4;7;3"""), header=[0, 1], delimiter=";")
unpivoted = piv.melt(id_vars=list(piv.columns[:3]),
var_name=['gender', 'age'],
value_name='frequency')
# cleanup the tupleized columns
unpivoted.columns = [(col[0] if isinstance(col, tuple) else col)
for col in unpivoted.columns]
將“melt”與“pivot_table”結合使用,您可以嘗試以下操作:
df_melt=df.melt(id_vars=['Kode','Country','Procedure'],var_name='Gender')
將兩歲、三歲提取到自己的“Age_group”列中,將“value”列中的非數字行去掉
df_melt['Age_group']=df_melt['value'].str.extract('(.*-year-old)')
df_melt['Age_group']=df_melt['Age_group'].ffill()
df_melt=df_melt[pd.to_numeric(df_melt['value'],errors='coerce').notnull()]
如果原始數據框在編輯器中按原樣顯示為紅色,則名稱相同的列將重命名為male、male.1、female、female.1 等。要刪除“.”之后的字符。 從“性別”列
df_melt['Gender']=df_melt['Gender'].map(lambda x: x[0: x.find('.')] if '.' in x else x)
透視結果
result=df_melt.pivot_table(index=['Kode','Country','Procedure','Gender','Age_group'],values='value')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.