首页 > 解决方案 > 根据条件在熊猫数据框的每一行中分配值

问题描述

我编写了如下所示的代码:

for ind in df.index:
  X=df['POG_X'][ind]
  Y=df['POG_Y'][ind]
  if -960<X<0 and -540<Y<0:
     df.loc[df.index[ind],'Is_ROI']='TRUE'
  else:
     df.loc[df.index[ind],'Is_ROI']='FALSE'

所以,基本上我想要实现的是在 pandas df 的“Is_ROI”列上分配一个“TRUE”或“FALSE”值。我可以读取每行的 X、Y 值,但 TRUE 或 FALSE 的分配不能按预期工作。无论 if 语句如何,我都会在整个“Is_ROI”列中获得 TRUE 或 FALSE 值。我在这里缺少什么?

标签: pythonpandasdataframe

解决方案


将您的条件直接存储在列中:

df['Is_ROI']=(df['POG_X'].between(0,-960,inclusive='neither')) & (df['POG_X'].between(0,-540,inclusive='neither'))

或者

没有between()

df['Is_ROI']=(df['POG_X'].gt(-960) & df['POG_X'].lt(0)) & (df['POG_Y'].gt(-540) & df['POG_X'].lt(0))

笔记:

  • 如果您不需要布尔 True/False 并且您需要字符串 True/False 则只需astype(str)在末尾链接
  • 如果您不想在比较中包含边界,则传入inclusive='neither'方法between(),如果您想包含这些边界,则删除inclusive参数

推荐阅读