我有以下数据集,我想手动检查列Name
中的值与列Factory
中相同行的值是否相同
我通过阅读相关文档开发了以下代码,但并没有完全发挥作用。我想确保有以下特点:
- 如果我输入1,这意味着一切都好,名称匹配,我可以继续下一行
- 如果我输入0,这意味着名称不匹配,但我仍然可以继续到下一行
- 如果我输入9,我已经厌倦了检查,我希望整个循环结束
- 如果我输入的不是1、0或9,循环会要求我重新输入值
data = {'Name': ['Facotry One', 'Second value', 'Match'],
'Factory': ['Footwear Limited', 'Footweat not limited', 'Match']}
df_test = pd.DataFrame (data, columns = ['Name','Factory'])
df_test
english_matches = []
for index, row in df_test.iterrows():
print('Is ', row['Name'], ' the same as ', row['Factory' ])
while True:
try:
match = input("Enter 1 for match, 0 for mistmatch, 9 to exit the loop: ")
if match not in (1, 0, 9):
except ValueError:
print("Sorry, I didn't understand that.")
continue
else:
english_matches.append(match)
break
if match == 9:
Break
else:
print("You are still here")
错误
File "<ipython-input-16-81bdfa6d212f>", line 15
if match not in (1, 0, 9):
^
SyntaxError: invalid syntax
您的代码需要重新排列。
您应该从导入pandas
:开始
import pandas as pd
然后设置变量:
data = {'Name': ['Factry One', 'Second value', 'Match'],
'Factory': ['Footwear Limited', 'Footweat not limited', 'Match']}
df_test = pd.DataFrame(data, columns=['Name', 'Factory'])
english_matches = []
你开始你的循环:
for index, row in df_test.iterrows():
print('Is ', row['Name'], ' the same as ', row['Factory'])
while True:
您需要将match
变量强制转换为int
,否则它稍后将在if condition
:中不匹配
match = int(input("Enter 1 for match, 0 for mismatch, 9 to exit the loop: "))
至于检查,答案在预期范围内,您应该在用条件检查还是用try-except
检查之间做出选择。我保留了一个条件:
if match not in (1, 0, 9):
print("Sorry, I didn't understand that.")
elif match == 9:
break
else:
english_matches.append(match)
break
我不明白你什么时候想打印:
print("You are still here")