gpt4 book ai didi

python - 如何在Python pandas中进行除法

转载 作者:行者123 更新时间:2023-11-30 22:19:05 24 4
gpt4 key购买 nike

考虑下面是我的数据框,我想通过将各个标记除以总计来获取百分比来填充“百分比”列。

    Name  Marks
0 Total 100
1 Name1 45
2 Name2 65
3 name3 93
4 name4 89

我写的代码是这样的

for i in range(0,5):
pcnt=(df['Marks'][i])/(df['Marks'][0])
df['Percentage']=pcnt*100

但是百分比列只为所有行生成 0。上面的代码只是一个例子,但我的实际数据会产生一些错误,如下所示

Traceback (most recent call last):
File "C:/Users/USER/.PyCharmCE2017.2/config/scratches/scratch.py", line 24, in <module>
share=df2['W/E 17/11/2013'][i]/df2['W/E 17/11/2013'][0]
File "C:\Python27\lib\site-packages\pandas\core\series.py", line 623, in __getitem__
result = self.index.get_value(self, key)
File "C:\Python27\lib\site-packages\pandas\core\indexes\base.py", line 2560, in get_value
tz=getattr(series.dtype, 'tz', None))
File "pandas/_libs/index.pyx", line 83, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 91, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 139, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 811, in pandas._libs.hashtable.Int64HashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 817, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 74L

我在这里做错了什么?

最佳答案

我相信你可以使用Series.divloc 选择的第一行然后乘以 mul :

s = df['Marks'].div(df.loc[0, 'Marks']).mul(100)
print (s)
0 100.0
1 45.0
2 65.0
3 93.0
4 89.0
Name: Marks, dtype: float64

如果真实数据在第一行没有索引0,则使用通用解决方案 - 按位置选择 ilocget_loc对于列标记的位置:

print (df.iloc[0, df.columns.get_loc('Marks')])
100

s = df['Marks'].div(df.iloc[0, df.columns.get_loc('Marks')]).mul(100)

关于python - 如何在Python pandas中进行除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49210557/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com