Python数据框架中的math.log的结果是整数

Python数据框架中的math.log的结果是整数,python,pandas,math,Python,Pandas,Math,我有一个数据帧,所有的值都是整数 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

我有一个数据帧,所有的值都是整数

        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
这是Python3,Jupyter笔记本 我试过数学。日志(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
库进行此类数学运算,由于
numpy
pandas
都来自同一个项目,因此它速度更快,输出结果更易于使用


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

使用
numpy.log
(不带循环)创建一个新列,并用该列进行追加/替换,而不是对现有的整数列进行变异。