【问题标题】:Pandas - Updating value in row based on condition with .apply()Pandas - 使用 .apply() 根据条件更新行中的值
【发布时间】:2020-02-20 02:18:28
【问题描述】:

简化,我想使用一个函数来检查一行的条件并相应地设置值:

def helper(row):
    if row["A"] == "TEST":
         row["B"] = "WOW"
     else:
         row["C"] = "NO_GO"


moddf = df.apply(helper, axis=1)

我可以使用 iterrows() 来做到这一点,但 .apply 在 df 中迭代超过 1M 行应该更快。

【问题讨论】:

  • 只返回该行,尽管apply 在这里可能不是最有效的方式。
  • apply 基本上一样慢,当你不可避免地用axis=1 调用它时,它仍然是一个循环。您可能想使用np.where,而不是在需要以不同方式设置的少量列上循环,而不是 1M 行。
  • apply 是您应该访问的最后资源之一。使用pandasnumpy 方法。

标签: python pandas loops apply


【解决方案1】:

您不需要(也不应该使用)申请:

# toy data
df = pd.DataFrame({'A':['TEST','NO'],
              'B' : ['A','B'],
              'C' :list('12')})

s = df['A']=='TEST'

df.loc[s,'B'] = 'WOW'
df.loc[~s, 'C'] = 'NO_GO'

输出:

      A    B      C
0  TEST  WOW      1
1    NO    B  NO_GO

【讨论】:

  • ? 这样就可以了
猜你喜欢
  • 1970-01-01
  • 2023-02-20
  • 1970-01-01
  • 2014-10-09
  • 2022-01-25
  • 2018-11-14
  • 1970-01-01
  • 2022-07-05
  • 1970-01-01
相关资源
最近更新 更多