Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

使用resample如何保留表中的字段供后续使用

  1. User

    使用resample如何保留表中的字段供后续使用

  2. Assistant

    可以使用pandas的resample()方法将时间序列的频率进行转换,并且保留指定的列。

    例如,如果我们有一个名为df的数据表,其包含一个日期时间索引(DatetimeIndex)和多列数据,我们想要按照每个月的最后一天对数据进行重新采样,并且保留列'A'和列'B',则可以使用以下代码:

    import pandas as pd
    
    # 生成一个示例数据表
    dates = pd.date_range(start='2020-01-01', end='2021-12-31', freq='D')
    df = pd.DataFrame({'A': range(len(dates)), 
                       'B': range(len(dates)), 
                       'C': range(len(dates)), 
                       'D': range(len(dates))}, 
                      index=dates)
    
    # 按照每个月的最后一天对数据进行重新采样
    df_resampled = df.resample('M').last()[['A', 'B']]
    

    在上面的代码中,resample('M')将数据按照每个月的最后一天进行重新采样,last()将相应的样本转换为该月的最后一天的数据,[['A', 'B']]将保留列'A'和列'B',并将其作为新的数据表df_resampled输出。