【问题标题】:Lambda function inside DataFrame ApplyDataFrame 中的 Lambda 函数应用
【发布时间】:2021-12-23 02:26:50
【问题描述】:

我在 Pandas 中有以下 DataFrame:

import pandas as pd
import numpy as np

df = pd.DataFrame([(1, 1, 1, 0),
                   (2, 0, 0, 2),
                   (3, 0, 1, 3),
                   (4, 5, 3, 0)],
                  columns=list('abcd'))

我需要在该 DataFrame 中实现以下功能:

我正在尝试使用下面的apply() 函数:

dfs = df.apply(lambda x: np.mean(x)+2*np.std(x) if x > np.mean(x)+2*np.std(x) else x, axis = 0, result_type='broadcast')
dfs

我收到以下错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

不太确定这意味着什么,或者我应该在哪里使用a.empty, a.bool()... 来修复它。

【问题讨论】:

  • 这是因为现在,您的 lambda 中的 x 代表一列(一个系列),而操作 x > np.mean(x)+2*np.std(x) 也是一个系列。问题是使用if series 会返回此错误。有关此错误发生的不同情况的更多说明,请参阅this

标签: pandas dataframe apply


【解决方案1】:

如果您想逐行检查,则可以在程序中使用np.where 而不是if else。第一个参数是你的条件。当它为真时,它在同一索引处采用第二个参数。如果错误,则在同一索引处取第三个参数。

df.apply(lambda x:np.where(x > np.mean(x)+2*np.std(x), np.mean(x)+2*np.std(x), x), axis=0)

【讨论】:

    【解决方案2】:

    您可以在一次计算整个数据帧上的meanstd 后使用clip

    df.clip(upper=df.mean()+2*df.std(), axis=1)
    

    使用当前输入,它不会改变任何东西,这是一种查看方式:

    # calcualte the current upper bound
    _upper = df.mean() + 2*df.std()
    print(_upper)
    # a    5.081989
    # b    6.260952
    # c    3.766611
    # d    4.250000
    # dtype: float64
    
    # then replace two values above the bound
    df.loc[2,['a','b']] = [12,9]
    print(df)
    # dtype: float64
    #     a  b  c  d
    # 0   1  1  1  0
    # 1   2  0  0  2
    # 2  12  9  1  3 # see the values in column a and b
    # 3   4  5  3  0
    
    # see what clip does for the values in column a and b, index 2
    print(df.clip(upper=_upper, axis=1))
    #           a         b  c  d
    # 0  1.000000  1.000000  1  0
    # 1  2.000000  0.000000  0  2
    # 2  5.081989  6.260952  1  3  # 12 and 9 replaced by the upper bound of the column
    # 3  4.000000  5.000000  3  0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 2018-07-26
      • 2016-02-18
      • 1970-01-01
      相关资源
      最近更新 更多