[英]Calculate percentage share within rows of dataframe
我有一個數據框,其中包含多個州的GDP數據。 我試圖獲得所有州第一,第二和第三產業占GDP的百分比。 以下是數據框,我不確定該如何處理。
以下是我要達到的結果:
Primary % Contribution = (Primary for that state/ State GSDP )* 100
Secondary % Contribution = (Secondary for that state/ State GSDP )* 100
Tertiary % Contribution = (Tertiary for that state/ State GSDP )* 100
我試圖得到這樣的輸出如下。
您可以嘗試pivot
數據框:
new_df = df.pivot(index='State',columns='Item', values='GSDP')
for item in ['Primary', 'Secondary']:
new_df[item+'_pct'] = new_df[item]/new_df['Gross State']
new_df['Tertiary_pct'] = 1 - new_df[['Primary_pct', 'Secondary_pct']].sum(1)
注意:僅當每對(state, item)
有一行時, pivot
起作用。 否則,請考慮pivot_table
:
new_df = df.pivot_table(index='State',columns='Item', values='GSDP', aggfunc='sum')
解決方案將以state
列為中心,然后您將擁有所有信息來計算百分比。
df_pivot = df.pivot(index='state', columns='item', values='GSDP')
現在,您可以輕松計算出百分比:
df_pivot['PrimaryPercent'] = df_pivot.Primary / df_pivot['Gross State Domestic Product'] * 100
df_pivot['SecondaryPercent'] = df_pivot.Secondary / df_pivot['Gross State Domestic Product'] * 100
等等
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.