如何使用apply()添加标准偏差条件下的新列?



我有一个函数和一个规则要应用在df上。

def apply_rule(df, rule):
df['legal'] = df.apply(rule)
def greater_than_mean_plus_1_std():
return df['col1']>df['col1'].mean()+df['col1'].std()
apply_rule(df, greater_than_mean_plus_1_std)

我想在df上应用一个规则,它可以生成一个新列,告诉我row的值是否大于mean+std

但是对于df.apply(),我不能在这里使用df.mean()和df.std()。

AttributeError: 'float' object has no attribute 'mean'

有办法吗?或者我必须使用df.apply()以外的方法?

编辑:

print(df.head())
col1
0   7.2
1   7.2
2   7.2
3   7.2
4   7.2

预期输出:

col1  legal
0   7.2  False
1   7.2  False
2   7.2  False
3   7.2  False
4   7.2  False

这里不需要使用apply

df['legal'] = df['col1'] > (df['col1'].mean()+df['col1'].std())

如果你想使用apply,你可以使用DataFrame。

df['legal'] = df.apply(lambda row: row['col1'] > (df['col1'].mean()+df['col1'].std()), axis=1)
# or
df['legal'] = df['col1'].apply(lambda x: x > (df['col1'].mean()+df['col1'].std()))

您可以使用:

def apply_rule(df, rule):
df['legal'] = rule(df)  # <- change here
def greater_than_mean_plus_1_std(df):  # <- change here
return df['col1'] > df['col1'].mean() + df['col1'].std()
apply_rule(df, greater_than_mean_plus_1_std)

输出:

# df = pd.DataFrame({'col1': range(10)})
>>> df
col1  legal
0     0  False
1     1  False
2     2  False
3     3  False
4     4  False
5     5  False
6     6  False
7     7  False
8     8   True
9     9   True

先计算平均值和STD值,

col1_mean = df["col1"].mean()
col1_std = df["col1"].std()

然后像这样使用这些预先计算的值

df["legal"] = df["col1"].apply(lamdba x: x > col1_mean + col1_std)

,如果你想让它函数化,你可以使用lambda:

col1_mean = df["col1"].mean()
col1_std = df["col1"].std()
greater_than_mean_plus_1_std = lambda x: x > col1_mean + col1_std
def apply_rule(df, rule, column):
df['legal'] = df[column].apply(rule)

现在调用apply_rule

apply_rule(df, greater_than_mean_plus_1_std, "col1")

最新更新