Python pandas DataFrame中math.log的结果是整数



我有一个DataFrame,所有值都是整数

Millage  UsedMonth  PowerPS
1        261500        269      101
3        320000        211      125
8        230000        253      101
9        227990        255      125
13       256000        240      125
14       153000        242      150
17       142500        215      101
19       220000        268      125
21       202704        260      101
22       350000        246      101
25       331000        230      125
26       250000        226      125

我想计算log(Millage(所以我用了代码

x_trans=copy.deepcopy(x)
x_trans=x_trans.reset_index(drop=True)
x_trans.astype(float)
import math
for n in range(0,len(x_trans.Millage)):
x_trans.Millage[n]=math.log(x_trans.Millage[n])
x_trans.UsedMonth[n]=math.log(x_trans.UsedMonth[n])

我得到了所有的整数

Millage UsedMonth   PowerPS
0   12  5   101
1   12  5   125
2   12  5   101
3   12  5   125
4   12  5   125
5   11  5   150

这是python 3,Jupyter笔记本我试过数学.log(100(并获得4.605170185988092

我认为原因可能是DataFrame数据类型。如何将log((结果作为float感谢

一个解决方案是简单地进行

x_trans['Millage'] = np.log(x_trans['Millage'])

转换为astype(float)不是就地操作。分配回你的数据帧,你会发现你的日志系列将是类型float:

x_trans = x_trans.astype(float)

但是,在这种情况下,math.log是低效的。相反,您可以通过NumPy:使用矢量化功能

x_trans['Millage'] = np.log(x_trans['Millage'])
x_trans['UsedMonth'] = np.log(x_trans['UsedMonth'])

使用此解决方案,您不需要显式地将数据帧转换为float

此外,请注意,深度复制在Pandas中是原生的,例如x_trans = x.copy(deep=True)

首先,我强烈建议使用numpy库进行此类数学运算,因为numpypandas都来自同一项目,所以它速度更快,输出结果也更容易使用。

现在,考虑到您是如何创建数据帧的,它会自动假设您的数据类型是整数,在创建数据帧时尝试将其定义为float,并添加参数dtype = float,如果您使用的是numpy包(import numpy as np(dtype = np.float64,则更好。

最新更新