Python Pandas:比较两列和返回字符串值,如果第一列包含字符中的字符
我首先有2列,其中包括X或F在内的字符串,第二列为空。 如果第1列中有任何X 每次我运行代码时,都将值分配给所有这些
我的代码:
for row in df['Column2']:
if df['Column1'].str.contains('X').any():
df['Column2'] = 'YES'
else:
df['Column2'] = 'NO'
I have 2 columns first with string including X or F and second is empty.
If there is any X in column 1 I want to assign 'YES' to second column if there is no X assign 'NO'
Every time I run my code it is assigning value 'YES' to all of them
This example how it should look like:
My code:
for row in df['Column2']:
if df['Column1'].str.contains('X').any():
df['Column2'] = 'YES'
else:
df['Column2'] = 'NO'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您每次通过循环执行矢量化操作。每次通过循环,您都将
'是''
分配给整个column2
。使用
numpy
您可以做:结果
You are executing vectorized operation each time through the loop. Every time through the loop you are assigning
'YES'
to the entireColumn2
.Using
numpy
you could do:Result
您可以使用Regex查找“ X”,
甚至可以避免循环如下
you can use regex to find 'X'
you can even avoid the loop as follows