python - 将非零值替换为 1

标签 python pandas

我有一个如下所示的数据集:

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/

相关文章:

python - 有没有办法知道一个对象内部是否有不可迭代的 NoneType 对象

python - 如何以正确的顺序转置和聚合此数据框?

python - 如何在 python 中将未处理的字符串添加到 DataFrame 中?

python - Flask/Mongo/Jinja - 切片 ListField 并显示数据库的最后条目

python - Pandas 选择至少一列中具有特定值的行

python - 优化用于更改列表的最小函数

python - 从 Python 函数调用 `dt.` 类型

python - 遍历 for 循环并将检索到的数据保存在每个循环的唯一 csv 文件中 | Python

python - 如何根据不同列的条件返回一列

javascript - Bokeh 小部件为单个事件调用 CustomJS 和 Python 回调?