【发布时间】: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