【问题标题】:Python : Adding conditional column to pandas dataframe, more pythonic solution?Python:向熊猫数据框添加条件列,更多pythonic解决方案?
【发布时间】:2019-02-02 02:24:52
【问题描述】:

我正在向数据框中添加一列,其中列值是通过比较数据框中的两个 other 列来确定的。添加列的代码是:

lst = []
for x in range(len(df)):
    if df['ColumnA'][x] > df['ColumnB'][x]:
        lst.append(df['ColumnB'][x])
    else:
        lst.append(df['ColumnA'][x])

df['ColumnC'] = lst

我的问题是,有没有更有效/pythonic 的方式来做到这一点?过去有人建议我要小心,如果我每次都循环遍历数据框的每一行,所以想看看我是否遗漏了一些东西。谢谢!

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

是的,只取最小值:

df['ColumnC'] = df[['ColumnA', 'ColumnB']].min(1)

【讨论】:

  • 你知道这与性能相比如何。明智的 np.where 顶部?如果没有,不用担心,很好的解决方案!
  • 可能是np.where,但不要过早优化.. 编写好的、可理解的代码。然后发现瓶颈并优化它们。
【解决方案2】:

使用numpy.where

df['ColumnC'] = np.where(df['ColumnA'] > df['ColumnB'], df['ColumnB'], df['ColumnA'])

【讨论】:

    【解决方案3】:

    比其他解决方案更多的代码,但可以说更通用

    mask = df[ColumnA] > df[ColumnB]
    df[ColumnC] = pd.Series(index=df.index)
    df[ColumnC].loc[mask] = df[ColumnA].loc[mask]
    df[ColumnC].loc[~mask] = df[ColumnB].loc[~mask]
    

    【讨论】:

      猜你喜欢
      • 2019-08-29
      • 2019-12-21
      • 2021-06-11
      • 2021-06-27
      • 2019-03-12
      • 2017-08-21
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多