为什么iterrows不能做数学 - 而是返回整数值,其中这些应该是浮点数

时间:2017-03-04 08:28:19

标签: pandas dataframe integer

我想循环一个数据框,然后用复杂计算中的利率填充框架的一列。显然,循环框架的最佳方法是使用iterrows - 但是当我使用iterrows时,我只得到整数值:

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。

以下示例给出了正确的结果:

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

如上所述,使用这种方法并不容易,因为计算很复杂。

我可以使用iterrows生成正确的结果吗?

1 个答案:

答案 0 :(得分:1)

您似乎需要使用locatix)分配标量值:

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

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