如何利用Pandas的数据框架计算百分比

2024-05-19 22:11:24 发布

您现在位置:Python中文网/ 问答频道 /正文

如何用百分比将另一列添加到Pandas的数据框中?听写可以根据大小改变。

>>> 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]

Tags: columns数据testimportdataframepandasasitems
2条回答

如果您确实需要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

首先,将字典的键设置为数据帧的索引:

 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]

相关问题 更多 >