Replace values in Pandas Series Given Condition

别来无恙 提交于 2021-02-08 12:35:58

问题


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?


回答1:


Why not just try to set 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


来源:https://stackoverflow.com/questions/31545183/replace-values-in-pandas-series-given-condition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!