在Pandas中将每月数据转换为季度

时间:2017-10-07 10:48:08

标签: python pandas

我有按ID分组的月度数据,ID也有父ID。数据如下所示:

data = pd.DataFrame({'parent_id': [1, 1, 1, 1, 1, 1, -99999, -99999, -99999],
                     'id': [123, 123, 123, 123, 123, 123, 123, 123, 123],
                     'data_1': [10, 20, 30, 40, 50, 60, 0, 0, 0],
                     'data_2': [10, 20, 30, 40, 50, 60, 0, 0, 0],
                     'period': [0, 1, 2, 3, 4, 5, 6, 7, 8],
                     'date': ['2017-06-30', '2017-07-31', '2017-08-31',
                              '2017-09-30', '2017-10-31', '2017-11-30',
                              '2017-12-31', '2018-01-31', '2018-02-28'],
                     'quarter': [0, 0, 0, 1, 1, 1, 2, 2, 2]})

data_2 = pd.DataFrame({'parent_id': [1, 1, 1, 1, 1, 1, -99999, -99999, -99999],
                     'id': [234, 234, 234, 234, 234, 234, 234, 234, 234],
                     'data_1': [10, 20, 30, 40, 50, 60, 0, 0, 0],
                     'data_2': [10, 20, 30, 40, 50, 60, 0, 0, 0],
                     'period': [0, 1, 2, 3, 4, 5, 6, 7, 8],
                     'date': ['2017-06-30', '2017-07-31', '2017-08-31',
                              '2017-09-30', '2017-10-31', '2017-11-30',
                              '2017-12-31', '2018-01-31', '2018-02-28'],
                     'quarter': [0, 0, 0, 1, 1, 1, 2, 2, 2]})

data = data.append(data_2)
data = data.reindex()

我有一个函数,当我有一个id时可以工作,但是当我引入多个ID时,求和并不是唯一的ID。

def convert_to_quarterly(df, date):
    """Aggregates 3 months of data to a quarterly value."""
    columns = ['data_1', 'data_2']
    df['date'] = pd.to_datetime(df['date'])
    df = df.set_index('date')
    df_quarterly = df.resample('Q')[columns].sum()
    df_quarterly['date'] = df_quarterly.index
    df['date'] = df.index
    df.drop(columns, axis=1, inplace=True)
    df = pd.merge(df, df_quarterly)

    return df

convert_to_quarterly(data, date=pd.to_datetime('2017-06-30'))

我需要做些什么才能使Pandas仅对各个ID组进行求和?

1 个答案:

答案 0 :(得分:2)

如果您还没有这样做,则需要将日期列正式设置为日期时间类型。然后你可以使用groupby然后重新采样。

Print