将功能应用于熊猫数据框的单列

时间:2020-03-04 15:15:07

标签: python pandas

我正在尝试将函数应用于数据框的单个列(特别是规范化)。

数据框如下所示:

     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

谢谢

3 个答案:

答案 0 :(得分:3)

如果仅是一列,则无需使用apply。直接使用最大列将其除。

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

答案 1 :(得分:1)

由于单列不需要max = discrepancies['Volume'].max() discrepancies['some col']=discrepancies['Volume']/max ,因此我们需要将其分配回

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

还可以使用地图系列

REINDEX TABLE guacamole_user_history;

答案 2 :(得分:1)

您的代码存在的问题是pandas.apply将结果作为新的数据帧返回。 (有很多熊猫功能的inplace属性,但没有apply的属性)

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

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

,或者您可以使用@YOBEN_S答案。