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