Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何计算熊猫的百分比';数据帧_Python_Pandas - Fatal编程技术网

Python 如何计算熊猫的百分比';数据帧

Python 如何计算熊猫的百分比';数据帧,python,pandas,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 Te

如何使用百分比将另一列添加到熊猫的数据帧中?这本词典的大小可以改变

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

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

 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]

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

与joe的版本相比,我更喜欢这个版本,因为它更简单,而且因为我不叫任何Lambda,所以速度更快(我假设)。事实上,我试图得到真实的百分比,例如15分之9=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,实际上,我试图得到真实的百分比,例如15的9=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,请参见我编辑的答案。它汇总了
score
列,并将其作为您上面的评论所暗示的完美分数。并且,不再使用
lambda
函数。为了清晰起见,我写下了完整的函数。我认为你至少应该描述一下你试图实现的目标。
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