首页 > 解决方案 > 如何在 pandas 数据框中重复迭代?

问题描述

对 Python 来说非常新,我有一个大数据框,每次用户输入 =“yes”时,我都尝试显示 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:无法在没有频率的情况下将整数值添加到时间戳。”

我很困惑下一步该往哪个方向走。非常感谢帮助,

标签: pythonpandasloops

解决方案


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


推荐阅读