为什么Iterrows不能做数学运算-而是返回整数值,而这些值应该是浮点数 [英] Why can't iterrows do math - and instead returns integer values where these should be floats
问题描述
我想遍历数据框,然后用复杂计算中的利率填充框的一列。显然,循环遍历框架的最佳方法是使用 iterrows
-但是当我使用 iterrows
时,我得到整数仅值:
I want to loop through a data frame and then fill a column of the frame with interest rates from a complex calculation. Apparently, the best way to loop through a frame is to use iterrows
- But when I use iterrows
, I get integer values only:
import pandas
df = pandas.DataFrame({"A": [1,2,3,4,5]})
df['B']=0
for index, row in df.iterrows():
row['B']=row['A']*10.05
df
返回
A B
0 1 10
1 2 20
2 3 30
3 4 40
4 5 50
这是不正确的,因为A中的所有值都乘以10.05。
Which is incorrect, given that all values in A were multiplied by 10.05.
下面的示例给出了正确的结果:
The example below, gives the correct results:
df['B']=df['A']*10.05
A B
0 1 10.05
1 2 20.10
2 3 30.15
3 4 40.20
4 5 50.25
如上所述,使用此方法并不容易,因为计算很复杂。
As said, it is not easy to use this method, because the calculations are complex.
我可以使用 iterrows
产生正确的结果吗?
Can I use iterrows
to produce the correct result?
推荐答案
It seems you need assign scalar values with loc
(at
, ix
):
for index, row in df.iterrows():
df.loc[index, 'B'] =row['A']*10.05
print (df)
A B
0 1 10.05
1 2 20.10
2 3 30.15
3 4 40.20
4 5 50.25
但更好使用 apply $具有自定义功能的c $ c>
:
But better is use apply
with custom function:
df = pandas.DataFrame({"A": [1,2,3,4,5]})
def f(x):
x['B'] = x.A * 10.05
#another code
return x
df = df.apply(f, axis=1)
print (df)
A B
0 1.0 10.05
1 2.0 20.10
2 3.0 30.15
3 4.0 40.20
4 5.0 50.25
这篇关于为什么Iterrows不能做数学运算-而是返回整数值,而这些值应该是浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!