我有一个如下所示的数据集:
id col1 col2 col3
123 10 0 82
456 0 90 16
987 0 0 0
我想将不是 id 的列中的所有非零值替换为 1。
我已经尝试过:
df.col1 = df.where(df.col1 != 0, 1)
但这会用 1 替换非零,用 id 替换零。
然后我尝试为此函数设置一个新的 df:
df2 = df.col1 = df.where(df.col1 != 0, 1)
除了将 id 列更改为 1(其中将非零值更改为 1)之外,这也是有效的。
任何帮助解决不起作用的代码或其他方法的问题将不胜感激!
最佳答案
选项 1
astype
df
col1 col2 col3
id
123 10 0 82
456 0 90 16
987 0 0 0
df.astype(bool).astype(int)
col1 col2 col3
id
123 1 0 1
456 0 1 1
987 0 0 0
或者,使用 gt
创建 mask :
df.gt(0).astype(int)
col1 col2 col3
id
123 1 0 1
456 0 1 1
987 0 0 0
如果 id
不是索引,先设置它!:
df = df.set_index('id')
选项 2
掩码
df.mask(df > 0, 1)
col1 col2 col3
id
123 1 0 1
456 0 1 1
987 0 0 0
选项 3
df.where
(注意与您的方法的区别)
df.where(df == 0, 1)
col1 col2 col3
id
123 1 0 1
456 0 1 1
987 0 0 0
与np.where
类似的解决方案:
pd.DataFrame(np.where(df > 0, 1, 0), index=df.index, columns=df.columns)
col1 col2 col3
id
123 1 0 1
456 0 1 1
987 0 0 0
关于python - 将非零值替换为 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47382933/