Pandas 检查数据框中的每个值并在满足条件时替换它

Pandas checking each value in dataframe and replace it if condition is fullfilled

我想将数据框中小于某个值 (b) 的所有值(227 行,397 列)替换为零,其余的应该是现有值 - b 。它是一种基线校正。 我有一个有效的解决方案:遍历每个值检查条件并替换它。

import pandas as pd
b = 20
    
for index, row in df.iterrows():
    for col in df.columns:
        if df.loc[index, col] <= b:
            df.loc[index, col] = 0.0
        else:
            df.loc[index, col] = df.loc[index, col] - b

代码有效,但我从 pandas 收到此警告: 试图在 DataFrame

的切片副本上设置一个值

有更好的方法吗?

使用numpy.where here with DataFrame constructor for avoid looping and improve performance:

df = pd.DataFrame(np.where(df <= b, 0, df - b), index=df.index, columns= df.columns)

或减去值并设置 0DataFrame.mask:

df = df.sub(b).mask(df <= b, 0)