如何使用Pandas的DataFrame计算百分比

17
如何在 Pandas 的 DataFrame 中添加另一列表示百分数?字典大小可能会发生变化。
>>> import pandas as pd
>>> a = {'Test 1': 4, 'Test 2': 1, 'Test 3': 1, 'Test 4': 9}
>>> p = pd.DataFrame(a.items())
>>> p
        0  1
0  Test 2  1
1  Test 3  1
2  Test 1  4
3  Test 4  9

[4 rows x 2 columns]
4个回答

43

如果您确实需要百分之十的10,最简单的方法是稍微调整数据的输入:

>>> p = pd.DataFrame(a.items(), columns=['item', 'score'])
>>> p['perc'] = p['score']/10
>>> p
Out[370]: 
     item  score  perc
0  Test 2      1   0.1
1  Test 3      1   0.1
2  Test 1      4   0.4
3  Test 4      9   0.9

对于真实的百分比,可以使用以下方法:

>>> p['perc']= p['score']/p['score'].sum()
>>> p
Out[427]: 
     item  score      perc
0  Test 2      1  0.066667
1  Test 3      1  0.066667
2  Test 1      4  0.266667
3  Test 4      9  0.600000

我更喜欢这个版本,因为它更简单,而且我没有调用任何lambda,所以速度应该更快(我猜)。 - FooBar
实际上,我试图获得真实的百分比,例如 9/15 = 60%。0 测试2 1 0.1 6.66, 1 测试3 1 0.1 6.66, 2 测试1 4 0.4 26.66, 3 测试4 9 0.9 60, - user977828

7
首先,将字典的键设置为数据框的索引:
 import pandas as pd
 a = {'Test 1': 4, 'Test 2': 1, 'Test 3': 1, 'Test 4': 9}
 p = pd.DataFrame([a])
 p = p.T # transform
 p.columns = ['score']

然后,计算百分比并将其分配给一个新列。

 def compute_percentage(x):
      pct = float(x/p['score'].sum()) * 100
      return round(pct, 2)

 p['percentage'] = p.apply(compute_percentage, axis=1)

这将为您提供:
         score  percentage
 Test 1      4   26.67
 Test 2      1    6.67
 Test 3      1    6.67
 Test 4      9   60.00

 [4 rows x 2 columns]

实际上,我尝试获取真实的百分比,例如 9/15 = 60%。0 测试2 1 0.1 6.66, 1 测试3 1 0.1 6.66, 2 测试1 4 0.4 26.66, 3 测试4 9 0.9 60, - user977828
请查看我的修改后的答案。它汇总了“score”列,并将其作为您上面评论中所示的满分。 - joemar.ct
而且,不再使用“lambda”函数。为了清晰起见,我写出了完整的函数。 - joemar.ct

1
import pandas as pd
 
data = {'A': [1, 2, 3, 4, 5], 'B': [10, 20, 30, 40, 50]}
df = pd.DataFrame(data)
# calculate percentage using apply() method and lambda function
 
df['B_Percentage'] = df['B'].apply(lambda x: (x / df['B'].sum()) * 100)
 
print(df)

使用lambda可以很有用。可以通过多种方法完成。也许这个链接会有所帮助:http://www.pythonpandas.com/how-to-calculate-the-percentage-of-a-column-in-pandas/

0
df=pd.read_excel("regional cases.xlsx")
df.head()

REGION  CUMILATIVECOUNTS    POPULATION

GREATER         12948       4943075
ASHANTI         4972        5792187
WESTERN         2051        2165241
CENTRAL         1071        2563228



df['Percentage']=round((df['CUMILATIVE COUNTS']/ df['POPULATION']*100)*100,2)
df.head()



REGION  CUMILATIVECOUNTS    POPULATION  Percentage

GREATER 12948               4943075      26.19
ASHANTI 4972                5792187      8.58
WESTERN 2051                2165241      9.47

我认为你至少应该描述一下你想要实现什么。 - ismetguzelgun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接