gpt4 book ai didi

python - 根据阈值替换系列值

转载 作者:行者123 更新时间:2023-12-01 09:31:26 26 4
gpt4 key购买 nike

我有一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com