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

时间:2014-05-08 10:59:21

标签: python pandas

如何将另一列添加到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]

3 个答案:

答案 0 :(得分:15)

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

答案 1 :(得分:4)

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

 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]

答案 2 :(得分: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