在 Pandas Series 中根据条件替换数值

11

这是一个我一直没有找到清晰答案的琐碎问题:

我有一个Series对象:

random = pd.Series(np.random.randint(10, 10)))

我希望将所有大于1的值替换为0。我该如何做?我尝试使用Random.replace()但没有成功,我知道你可以在DataFrame中轻松完成这个任务,但我该如何在Series对象中实现呢?

1个回答

18

为什么不尝试将s[s > 1] = 0设置为零?

import pandas as pd
import numpy as np

# your data
# ============================
np.random.seed(0)
s = pd.Series(np.random.randn(10))
s

0    1.7641
1    0.4002
2    0.9787
3    2.2409
4    1.8676
5   -0.9773
6    0.9501
7   -0.1514
8   -0.1032
9    0.4106
dtype: float64


# ============================
s[s>1] = 0
s

0    0.0000
1    0.4002
2    0.9787
3    0.0000
4    0.0000
5   -0.9773
6    0.9501
7   -0.1514
8   -0.1032
9    0.4106
dtype: float64

1
你会收到这个警告:__main__:1: SettingWithCopyWarning: 尝试在DataFrame的切片副本上设置值。 请改用 s = s.mask(s > 1, 0) - Martien Lubberink
请参考此答案:https://dev59.com/ZGEi5IYBdhLWcg3wIJPc - Martien Lubberink

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接