【问题标题】:How do I repeat an iteration across a pandas data frame?如何在 pandas 数据框中重复迭代?
【发布时间】:2020-03-15 21:17:03
【问题描述】:

对 Python 非常陌生,我有一个很大的数据框,每次用户输入时我都尝试显示 5 行原始数据 =“是”我希望每次用户输入是时数据前进 5 行.

我已尝试使用 .iloc 和 .iterrows,但我不知道如何使输出超出我在 iloc 中定义的行。

这是我迄今为止尝试过的。

def raw_data(df):
    """
    Asks user if they want to see 5 lines of raw data.
    Then returns 5 lines of raw data if user inputs `yes`. Iterates until user response with a `no`
    """

    data = df 
    while True:
        answer = input('Would you like to see 5 lines of raw data? Enter yes or no: ')
        if answer.lower() == 'yes':
            print(data.iloc[:5])
            data += 5
        else:
            break

我试图使用data += 5 进行进度,但它触发“ValueError:无法在没有频率的情况下将整数值添加到时间戳。”

我不知道下一步该往哪个方向走。 非常感谢您的帮助,

【问题讨论】:

    标签: python pandas loops


    【解决方案1】:

    DataFrame.iloc 将行索引作为第一个索引,将要显示的列索引作为第二个索引。

    因此,如果您只想显示 5 行和所有列的块,请使用:

    df.iloc[idx:idx+5, :]
    

    完整示例:

    def raw_data(df):
        """
        Asks user if they want to see 5 lines of raw data.
        Then returns 5 lines of raw data if user inputs `yes`. Iterates until user response with a `no`
        """
    
        idx = 0
        while True:
            answer = input('Would you like to see 5 lines of raw data? Enter yes or no: ')
            if answer.lower() == 'yes':
                print(df.iloc[idx:idx+5, :])
                idx += 5
            else:
                break
    

    另见https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html

    【讨论】:

      【解决方案2】:

      如果我想要五行,然后再多五行,然后继续...

      ,这对我有用
      import pandas as pd
      
      df = pd.read_csv('~/Documents/python/api.csv')
      
      def raw_data(df):
          """
          Asks user if they want to see 5 lines of raw data.
          Then returns 5 lines of raw data if user inputs `yes`. Iterates until user response with a `no`
          """
          position = 5
          data = df 
          while True:
              answer = input('Would you like to see 5 lines of raw data? Enter yes/y or no/n: ')
              if (answer.lower() == 'yes') | (answer.lower() == 'y'):
                  print(data.iloc[position-5:position])
                  position += 5
              else:
                  break
      
      raw_data(df)
      

      【讨论】:

        猜你喜欢
        • 2019-01-14
        • 2018-02-24
        • 2017-01-04
        • 1970-01-01
        • 2017-11-05
        • 2023-01-14
        • 2020-01-03
        • 2021-02-26
        • 1970-01-01
        相关资源
        最近更新 更多