Python中pandas如何将某一列大于0的数字全部置为1

date rtn 0 2016-01-01 0.101536 1 2016-01-02 0.055109 2 2016-01-03 -0.163625 3 2016-01-04 0.086756 4 2016-01-05 0.035907 5 2016-01-06 0.047619 6 2016-01-07 0.018717 7 2016-01-08 -0.036290

这样子的 df

大佬帮帮忙,实在搞不出来了


Python中pandas如何将某一列大于0的数字全部置为1
7 回复

df[‘rtn’] = df[‘rtn’].apply(lambda x: 1 if x>0 else x)


import pandas as pd
import numpy as np

# 创建示例数据
df = pd.DataFrame({
    'A': [3, -2, 5, 0, -1, 8],
    'B': [0, 4, -3, 2, 0, -5],
    'C': [1, 0, -2, 7, 0, 3]
})

print("原始数据:")
print(df)

# 方法1:使用布尔索引直接赋值(最常用)
df['A'] = (df['A'] > 0).astype(int)

# 方法2:使用np.where
df['B'] = np.where(df['B'] > 0, 1, df['B'])

# 方法3:使用apply(适用于复杂逻辑)
df['C'] = df['C'].apply(lambda x: 1 if x > 0 else x)

print("\n处理后的数据:")
print(df)

代码解释:

  1. 方法1(推荐)(df['A'] > 0) 生成布尔序列,.astype(int) 将 True/False 转为 1/0
  2. 方法2np.where(条件, 满足时的值, 不满足时的值),这里保留原值不变
  3. 方法3apply 逐元素应用函数,适合需要更复杂判断的情况

如果想处理整个DataFrame所有列:

# 将所有列中大于0的值设为1
df = df.applymap(lambda x: 1 if isinstance(x, (int, float)) and x > 0 else x)

如果想处理特定多列:

cols_to_process = ['A', 'B']
df[cols_to_process] = df[cols_to_process].applymap(lambda x: 1 if x > 0 else x)

用方法一最直接。

df.loc[df[‘rtn’]>0,‘rtn’]=1

直接改为 true,false 矩阵

x = x**0

写错,请忽略。。。

df[‘rtn’] = np.where(df[‘rtn’]>0, 1, df[‘rtn’])

回到顶部