Python 在给定条件下替换 Pandas 系列中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31545183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:12:32  来源:igfitidea点击:

Replace values in Pandas Series Given Condition

pythonpandas

提问by AZhao

This is a trivial question that I just have not been able to find a clear answer on:

这是一个微不足道的问题,我只是无法找到明确的答案:

I have a Series object:

我有一个系列对象:

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

I want to replace all values greater than 1 with 0. How do I do this? I've tried Random.replace() without success and I know you can do this easily in a DataFrame, but how do I do it in a Series object?

我想用 0 替换所有大于 1 的值。我该怎么做?我试过 Random.replace() 没有成功,我知道你可以在 DataFrame 中轻松做到这一点,但我如何在 Series 对象中做到这一点?

采纳答案by Jianxun Li

Why not just try to set s[s > 1] = 0

为什么不尝试设置 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