【发布时间】:2020-07-19 01:41:01
【问题描述】:
我正在尝试使用循环来遍历两个列表。不幸的是,第二个 for 循环不起作用:它只检查列表中的第一项,而不是其余的。 你能告诉我为什么吗?
谢谢
列表:
low_cars_engines=['Audi', 'Bentley', 'Bugatti', 'Porsche', 'Skoda']
low_planes_engines=['Pratt & Whitney','Rolls-Royce','GE Aviation']
我想根据 if 语句在我的原始数据集中再添加两列(汽车和飞机):
- 如果列表 'Engine to check' 中的对象在列表 low_cars_engines 中,则它是汽车,否则,它不是;
- 如果列表“Engine to check”中的对象在列表low_planes_engines 中,则它是平面,否则不是。
import re
df['Cars'] = pd.Series(index = df.index, dtype='object')
df['Planes'] = pd.Series(index = df.index, dtype='object')
for index, row in df.iterrows():
value = row['Engine to check']
for x in low_cars_engines:
if x in value:
print(x)
df.at[index,'Cars'] = 'Yes' # need to keep df.at[index, '_']
break
else:
df.at[index,'Cars'] = 'No' # need to keep df.at[index, '_']
break
for index, row in df.iterrows():
value = row['Engine to check']
for x in low_planes_engines:
if x in value:
df.at[index,'Planes'] = 'Yes'
break
else:
df[index,'Planes'] = 'No'
break
print(df)
第一个 for 循环工作正常,但不是第二个:我无法为列表“Engine to check”中的项目分配值,即使它在列表 low_planes_engines 中(它总是给我否)。
您能告诉我哪里出了问题吗?是否可以只使用一个 for 循环而不是两个?我宁愿保持相同的结构,或者保持df.at[index,'_']。现在,第二个循环仅打印/检查列表 low_planes_engines 的第一项(即 Pratt & Whitney),其余的不进行。
由于数据集类似于:
Audi
CFM International
Rolls-Royce
Bentley
Volkswagen
Toyota
Suzuki
Porsche
并且它不包括该元素,Planes 下的所有行都设置为No。
【问题讨论】:
-
你在两个
if分支中都有break,所以循环永远不会继续。 -
“要检查的引擎”列中有什么内容?第二次出现的空格可能是无意的,并阻止了第二次循环的工作。
-
是的,抱歉,这是一个错字。我固定在帖子里。代码中没有空格。复制到这里是我的错
-
你可以用
df["Cars"] = df['Engine to check'].isin(low_cars_engines)替换你的循环 -
我试过了,但它把所有的值都设置为 True
标签: python pandas loops for-loop if-statement