【问题标题】:While and if looping with pandaswhile 和 if 循环使用 pandas
【发布时间】:2019-05-27 02:26:55
【问题描述】:

我很难理解我的错误在哪里。我正在尝试从用户那里获取输入 > 如果“是” - 显示来自 DataFrame 的一些数据 > 如果“否”继续执行程序。

在 if "yes" 内部还有另一个问题 "Do you want more data?",然后再一次 > if "yes" 继续显示 > if "no" 离开两个循环并继续程序。

def display_data(df):
        n = 0
        raw_in = input('\nWould you like to see some raw data? yes or no.\n').lower()
        while raw_in in ['yes','no']:
            if raw_in == 'yes':
                raw_data = df.iloc[n:n+5,:]
                n += 5
                print(raw_data)
                raw_in = input('\nMore data? yes or no.\n').lower()
                if raw_in not in ['yes','no']:
                    print('\nInvalid option.\n')
                    display_data(df)
                else:
                    pass

这就是我尝试过的。我不断从while 更改为if 或他们的位置,但我没有找到解决方案。

【问题讨论】:

  • 不清楚你在问什么。您似乎没有尝试获取第二批数据。 while 循环在哪里?
  • @roganjosh 感谢您的回复。我已经更改了太多次代码,以至于我忘记了这次我只使用了 IF。我已经修改过了。我想知道如何使双循环工作
  • 你的问题到底是什么?

标签: python pandas loops if-statement while-loop


【解决方案1】:

您不需要while 条件来检查'no'。似乎您希望'no' 停止执行。由于您只需要while raw_in == 'yes',因此您也不需要后续的 if 语句。此外,else, pass 并没有真正的用途。

def display_data(df):
    n = 0
    raw_in = input('\nWould you like to see some raw data? yes or no.\n').lower()
    while raw_in == 'yes':
        raw_data = df.iloc[n:n+5,:]
        n += 5
        print(raw_data)
        raw_in = input('\nMore data? yes or no.\n').lower()
        if raw_in not in ['yes','no']:
            print('\nInvalid option.\n')
            display_data(df)

【讨论】:

    猜你喜欢
    • 2021-03-23
    • 2023-03-22
    • 2014-08-16
    • 2013-06-09
    • 2016-01-12
    • 2013-02-16
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多