【问题标题】:Python pandas conditional column creation with aggregates使用聚合创建 Python pandas 条件列
【发布时间】:2018-01-31 03:07:57
【问题描述】:

如果 P/E 位于我的数据框中所有 P/E 的下四分位数,我正在尝试创建一个返回 True 的列。以下是我到目前为止所做的。

首先我定义了一个函数:

def pe_cond(df):
    if df['P/E'] <= df['P/E'].quantile(0.1):
        return 1
    else:
        return 0

其次,我尝试将它应用到我的数据框

df['pe_cond'] = df.apply(pe_cond, axis=1)

但是我得到以下错误:

AttributeError: ("'float' object has no attribute 'quantile'", u'occurred at index 0')

任何帮助将不胜感激。

谢谢

【问题讨论】:

  • df['pe_cond'] = (df['P/E'] &lt;= df['P/E'].quantile(0.1)).astype(int)
  • 感谢您的评论,这是一种享受

标签: python pandas dataframe


【解决方案1】:

我还不能在 repl 中做到这一点,但这可能对你有用

mask = df['P/E'] <= df['P/E'].quantile(0.1)
df.loc[mask, 'pe_cond'] = 1
df.loc[~mask, 'pe_cond'] = 0

这是使用.loc 来查找满足mask 变量中定义的逻辑的DataFrame 的子集。 ~(一元)运算符否定了这一点。所以本质上,如果条件为真,则给它一个 1。如果条件为假,给它一个 0。

-- 编辑-- 你应该完全使用@djk47463 评论。非常简洁。

df['pe_cond'] = (df['P/E'] <= df['P/E'].quantile(0.1)).astype(int)

【讨论】:

  • 感谢 @djk47463 和 Orenshi,这非常有帮助,而且工作起来就像一个魅力,为我节省了大量时间,而不必定义所有这些函数
猜你喜欢
  • 2021-08-24
  • 2019-01-08
  • 2018-08-21
  • 2018-02-19
  • 2019-08-10
  • 1970-01-01
  • 1970-01-01
  • 2019-06-05
相关资源
最近更新 更多