的结果数学.log在Python中,数据帧是integ

2024-06-25 23:47:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

        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

我认为原因可能是数据帧数据类型。 如何将log()结果设为float 谢谢


Tags: 数据log密码transindex整数mathfloat
3条回答

转换为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。你知道吗

此外,请注意,深度复制是熊猫特有的,例如x_trans = x.copy(deep=True)。你知道吗

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

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

一个解决办法就是

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

相关问题 更多 >