【问题标题】:Generating an interactive loop to check if columns match in pandas [closed]生成一个交互式循环来检查熊猫中的列是否匹配[关闭]
【发布时间】:2020-12-26 09:51:58
【问题描述】:

我有以下数据集,我想手动检查 Name 列中的值是否与同一行的 Factory 列中的值相同。
我开发了以下代码阅读文档,但不能完全工作。我想确保有以下特点:

  1. 如果我输入 1 表示一切正常,名称匹配,我可以继续下一行
  2. 如果我输入 0,则表示名称不匹配,但无论如何我都可以进入下一行
  3. 如果我输入 9,我会厌倦检查,我希望整个循环结束。
  4. 如果我输入的不是 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

【问题讨论】:

标签: python pandas loops


【解决方案1】:

您的代码需要重新排列。

你应该从导入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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 2021-09-02
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    相关资源
    最近更新 更多