python - 根据阈值替换系列值

标签 python pandas series

我有一个 pandas 系列,如果值 < 3,我想用 0 替换这些值,如果值 >=3,我想用 1 替换这些值

se = pandas.Series([1,2,3,4,5,6])
se[se<3]=0
se[se>=3]=1

有更好的/Python式的方法吗?

最佳答案

在我看来,这是最好/快速地将 bool 掩码转换为整数:

se = (se >= 3).astype(int)

或者使用numpy.where ,但是 Series 构造函数是必要的,因为返回 numpy 数组:

se = pd.Series(np.where(se < 3, 0, 1), index=se.index)

print (se)
0    0
1    0
2    1
3    1
4    1
5    1
dtype: int32

关于python - 根据阈值替换系列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49937365/

相关文章:

python - 如何将数据框中一列的所有元素与另一个数据框中为该列指定的值相乘?

python - 如何在特定窗口聚合和滚动后应用自定义函数(使用 apply 方法)

python - 如果 pandas series 的值是一个列表,如何获取每个元素的子列表?

c# - 在图表系列中累积值 - WPF DevExpress

python - Cron 作业无法运行

python - 在 numba 的 jitclass 中索引多维 numpy 数组

python - 将多个函数应用于多个 groupby 列

python - 如何在 Macosx 10.9 上安装 PIL?

python - 在python中从表转换为矩阵

系列算法计算内部最大下降?