【问题标题】:Pandas checking each value in dataframe and replace it if condition is fullfilled熊猫检查数据框中的每个值并在满足条件时替换它
【发布时间】:2021-06-19 01:02:20
【问题描述】:

我想用零替换小于某个值 (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

代码有效,但我从熊猫那里得到了这个警告: 正在尝试在 DataFrame 中的切片副本上设置值

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: pandas for-loop replace warnings


    【解决方案1】:

    在此处使用numpy.where 和DataFrame 构造函数以避免循环和improve performance:

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-11-09
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      • 2019-07-31
      • 2022-08-11
      • 1970-01-01
      • 2020-06-08
      • 2018-04-06
      相关资源
      最近更新 更多