【问题标题】:How to use the apply method to check if data df["z"].iloc[i] == df["y"].iloc[i+1]如何使用 apply 方法检查数据 df["z"].iloc[i] == df["y"].iloc[i+1]
【发布时间】:2021-04-20 17:34:45
【问题描述】:

我尝试使用

df["new_col"] = temp_df['y'].apply(lambda x: "True" if x == temp_df["z"].shift[-1] else "False")

但是,我收到错误“TypeError: 'method' object is not subscribable”。

期望的输出

z,y,new_col
3,4,True
4,5,False
6,7,True
7,8,False

【问题讨论】:

  • 你不需要申请,检查series.shift()比较
  • 有一个错字...您使用的是.shift[-1] 而不是.shift(-1)
  • 感谢帮助,上面的更正仍然导致相同的错误,但我看到 ankies 回复并调整代码以使用 numpy.where 代替。

标签: python-3.x pandas apply


【解决方案1】:
df["new_col"] = np.where(temp_df['y'].eq(temp_df["z"].shift(-1)), "True","False")

正常工作

【讨论】:

  • 只需使用df['new_col'] = df['y'] == df['z'].shift(-1)这里不需要np.where或者如果你需要字符串dtype,(df['y'] == df['z'].shift(-1)).astype(str)
猜你喜欢
  • 2022-07-11
  • 2020-12-09
  • 2021-12-02
  • 2017-07-28
  • 2019-11-17
  • 1970-01-01
  • 2021-07-29
  • 2019-07-31
  • 2020-02-17
相关资源
最近更新 更多