计算数据帧行内的百分比份额

问题描述 投票:0回答:2

我有一个数据框,其中各州的GDP数据分为多个部门。我试图让所有州的初级,二级和三级部门占总GDP的百分比贡献。以下是数据框架,我不确定如何处理这个问题。 DataFrame

以下是我想要实现的结果:

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 

我试图获得如下的输出。

Expected Result

python pandas dataframe
2个回答
1
投票

你可以尝试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)

注意:pivot只有在每对(state, item)有一行时才有效。否则,请考虑pivot_table

new_df = df.pivot_table(index='State',columns='Item', values='GSDP', aggfunc='sum')

0
投票

解决方案将通过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

等等

© www.soinside.com 2019 - 2024. All rights reserved.