熊猫:从一列简单的数字减去

时间:2016-06-13 21:03:22

标签: python pandas

我需要简单地从DataFrame中的一列中减去2。 df中有更多列需要保持不变。

以下内容无效。我做错了什么?

func = lambda x: x - 2

df["customer"].apply(func)

1 个答案:

答案 0 :(得分:1)

apply()函数返回已更改的数据框,但它不会更改您的DF

In [49]: df
Out[49]:
   a  b  c
0  2  9  1
1  0  5  9
2  1  5  6
3  6  3  4
4  8  0  8

In [50]: df["a"].apply(func)
Out[50]:
0    0
1   -2
2   -1
3    4
4    6
Name: a, dtype: int64

In [51]: df
Out[51]:
   a  b  c
0  2  9  1
1  0  5  9
2  1  5  6
3  6  3  4
4  8  0  8

你想要的是:df["customer"] -= 2,它会更快地运作,看起来会更好,而且更加惯用

In [53]: df['a'] -= 2

In [54]: df
Out[54]:
   a  b  c
0  0  9  1
1 -2  5  9
2 -1  5  6
3  4  3  4
4  6  0  8