简体   繁体   English

如何在Dataframe中查找字段的百分比份额?

[英]How to find the percentage share of a field in Dataframe?

I have a Pandas DataFrame like below 我有一个像下面这样的Pandas DataFrame

df = pd.DataFrame({"ID" : [1,2,3,4],
                   "Amt" : [100, 200,  300, 400]})

My obejective is to find the percentage share of each amount and create a new field in this dataframe with it. 我的目标是找到每个金额的百分比份额,并在此数据框中创建一个新的字段。 My final DataFrame should look like 我的最终DataFrame看起来应该是这样的

ID Amt Avg
1  100 10
2  200 20
3  300 30
4  400 40

To achieve this, I concatenated the Amt field to same DF. 为了达到这个目的,我将Amt字段连接到同一个DF。 Then renamed it to Avg. 然后将其重命名为Avg。 and then calculated the perc using iterator 然后使用迭代器计算perc

   df = pd.concat([df, df['Amt']], axis=1)
   df.columns=(['ID', 'Amt', 'Avg'])
   for i in range(0,len(df)):
       df['Avg'] = ((df['Avg']/df['Amt'].sum())*100)

I'm new to this. 我是新手。 I've seen many achieve difficult objective with much simpler code. 我见过许多人用更简单的代码实现了难以实现的目标。
So can someone please help me to know the better approach than this one? 那么有人可以帮助我知道比这个更好的方法吗?

I believe you need: 我相信你需要:

df['Avg'] = df['Amt']/df['Amt'].sum()*100
print (df)
   ID  Amt   Avg
0   1  100  10.0
1   2  200  20.0
2   3  300  30.0
3   4  400  40.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM