将函数应用于数据帧的单列

2024-10-06 14:23:09 发布

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

我正试图将一个函数应用于我的数据帧的一列(特别是规范化)

数据帧如下所示:

     Euclidian        H         N       Volume
222   0.012288  0.00518  0.011143   85203000.0
99    1.296833 -0.80266  1.018583   17519400.0
98    1.618482 -0.60979  1.499213   16263900.0
211   2.237388  0.38073 -2.204757   38375400.0
175   2.313548  0.35656 -2.285907   66974200.0
102   3.319342  3.01295 -1.392897   33201000.0
7     3.424589 -0.31313  3.410243   97924700.0
64    3.720370 -0.03526  3.720203  116514000.0
125   3.995138  0.27396  3.985733   80526200.0
210   4.999969  0.46453  4.978343   70612100.0

数据帧名为“差异”,我的代码如下:

max = discrepancies['Volume'].max()
discrepancies['Volume'].apply(lambda x: x/max)
return discrepancies

但列值不会更改。我在文档中找不到适用于单列的任何地方,它们只涉及应用于所有列或所有行:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html

多谢各位


Tags: 数据lambda函数代码文档pandasreturn差异
3条回答

代码的问题是pandas.apply将结果作为新数据帧返回。(很多函数都有inplace属性,但没有apply

要更正代码,应执行以下操作:

max = discrepancies['Volume'].max()
discrepancies['Volume'] = discrepancies['Volume'].apply(lambda x: x/max)
return discrepancies

或者你可以使用@YOBEN_的答案

因为单列不需要apply,所以我们需要将其重新分配

max = discrepancies['Volume'].max()
discrepancies['some col']=discrepancies['Volume']/max

你也可以使用地图

max = discrepancies['Volume'].max()
discrepancies['Volume'].map(lambda x: x/max)

如果它只是一个列,则不需要使用apply。使用列的最大值直接划分列即可

discrepancies['Volume'] = discrepancies['Volume'] / discrepancies['Volume'].max()

相关问题 更多 >