Pandas 按年和月汇总并对其他列求和
Pandas aggregate by year and month and sum other column
具有以下代码:
import pandas as pd
data = {
'x': ['2019-07-29', '2019-07-30', '2019-07-31', '2019-08-01', '2019-08-02', '2019-08-03'],
'y': [4, 6, 4, 4, 6, 7]
}
df = pd.DataFrame(data = data, columns = ['x', 'y'])
df
这将输出:
x y
0 2019-07-29 4
1 2019-07-30 6
2 2019-07-31 4
3 2019-08-01 4
4 2019-08-02 6
5 2019-08-03 7
是否可以按年和月对 x 列中的日期进行分组,然后对 x 中的金额求和并将结果放入新的数据框中?像这样:
x y
0 2019-07 13
1 2019-08 17
使用pd.to_datetime
to convert x
to pandas datetime. Then groupby
on Series.dt.year
and Series.dt.month
:
In [181]: df.x = pd.to_datetime(df.x)
In [194]: df = df.groupby([df.x.dt.year, df.x.dt.month]).agg(sum).rename_axis(['year', 'month']).reset_index().rename(columns={'y':'sum'})
In [195]: df
Out[195]:
year month sum
0 2019 7 14
1 2019 8 17
类似这样的方法可能有效:
>>> df.groupby(df['x'].str[:-3])['y'].sum()
x
2019-07 14
2019-08 17
具有以下代码:
import pandas as pd
data = {
'x': ['2019-07-29', '2019-07-30', '2019-07-31', '2019-08-01', '2019-08-02', '2019-08-03'],
'y': [4, 6, 4, 4, 6, 7]
}
df = pd.DataFrame(data = data, columns = ['x', 'y'])
df
这将输出:
x y
0 2019-07-29 4
1 2019-07-30 6
2 2019-07-31 4
3 2019-08-01 4
4 2019-08-02 6
5 2019-08-03 7
是否可以按年和月对 x 列中的日期进行分组,然后对 x 中的金额求和并将结果放入新的数据框中?像这样:
x y
0 2019-07 13
1 2019-08 17
使用pd.to_datetime
to convert x
to pandas datetime. Then groupby
on Series.dt.year
and Series.dt.month
:
In [181]: df.x = pd.to_datetime(df.x)
In [194]: df = df.groupby([df.x.dt.year, df.x.dt.month]).agg(sum).rename_axis(['year', 'month']).reset_index().rename(columns={'y':'sum'})
In [195]: df
Out[195]:
year month sum
0 2019 7 14
1 2019 8 17
类似这样的方法可能有效:
>>> df.groupby(df['x'].str[:-3])['y'].sum()
x
2019-07 14
2019-08 17