python - 根据条件在熊猫数据框的每一行中分配值
问题描述
我编写了如下所示的代码:
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 值。我在这里缺少什么?
解决方案
将您的条件直接存储在列中:
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
参数
推荐阅读
- postgresql - 为什么没有 ST_GeographyFromWKB() 函数?
- javascript - 使用带有偏移圆的 atan2
- javascript - 如何在Vue中将数据从一个组件传递到另一个槽window.href?
- r - STRINGdb r 环境;plot_network 中的错误
- java - Tomcat DataSourceRealm 未显示任何日志记录
- express - Express Rate Limit 的许多实例是否会导致问题?
- python - 给定从 Selenium webdriver 获得的 HTML 数据时,BeautifulSoup 如何从 HTML 汤中获取文本
- docker - 从没有发行版存储库的旧 linux 发行版创建 docker 映像
- linux - 为什么有与我要创建的目录同名的文件时无法创建目录?
- python-3.x - 使用 sympy 函数“solve”求解包含 PYroMat 值的方程