[英]Creating columns out of categorical variables with values from two other columns in pandas
您可以執行兩個單獨的樞軸,然后連接結果,或者預先進行一些堆疊,然后僅執行一個樞軸。
import pandas as pd
df = pd.DataFrame({'Area': ['A', 'A','A','A','A'],
'IndCode': [3, 6, 10, 11, 12],
'Industry': ['blah', 'foo', 'bar', 'baz', 'boo'],
'2016': [2306, 2270, 5513, 7730, 35621],
'2017': [2409, 3391, 5438, 7890, 36397]
})
pd.concat([pd.pivot_table(df, index='Area', columns='Ind'+df.IndCode.astype(str)+'_2016', values='2016'),
pd.pivot_table(df, index='Area', columns='Ind'+df.IndCode.astype(str)+'_2017', values='2017')],axis=1)
輸出:
IndCode Ind10_2016 Ind11_2016 Ind12_2016 Ind3_2016 Ind6_2016 Ind10_2017 Ind11_2017 Ind12_2017 Ind3_2017 Ind6_2017
Area
A 5513 7730 35621 2306 2270 5438 7890 36397 2409 3391
df2 = df.set_index(['Area', 'IndCode'])[['2016', '2017']].stack().reset_index()
pd.pivot_table(df2, index='Area',
columns='Ind'+df2.IndCode.astype('str')+'_'+df2.level_2.astype(str),
values=0).reset_index()
輸出:
Area Ind10_2016 Ind10_2017 Ind11_2016 Ind11_2017 Ind12_2016 Ind12_2017 Ind3_2016 Ind3_2017 Ind6_2016 Ind6_2017
0 A 5513 5438 7730 7890 35621 36397 2306 2409 2270 3391
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.