Python 如何在多个groupby之后将数据从索引移动到列
我有以下数据帧:Python 如何在多个groupby之后将数据从索引移动到列,python,pandas,pandas-groupby,multi-index,Python,Pandas,Pandas Groupby,Multi Index,我有以下数据帧: dfalph.head() token year uses books 386 xanthos 1830 3 3 387 xanthos 1840 1 1 388 xanthos 1840 2 2 389 xanthos 1868 2 2 390 xanthos 1875 1 1 我使用重复的标记和年份聚集行,如下所示: dfalph = d
dfalph.head()
token year uses books
386 xanthos 1830 3 3
387 xanthos 1840 1 1
388 xanthos 1840 2 2
389 xanthos 1868 2 2
390 xanthos 1875 1 1
我使用重复的标记
和年份
聚集行,如下所示:
dfalph = dfalph[['token','year','uses','books']].groupby(['token', 'year']).agg([np.sum])
dfalph.columns = dfalph.columns.droplevel(1)
dfalph.head()
uses books
token year
xanthos 1830 3 3
1840 3 3
1867 2 2
1868 2 2
1875 1 1
我不想在索引中包含“token”和“year”字段,而是希望将它们返回到列中,并使用整数索引 方法#1:
方法#2:首先不要使用
我推迟了被接受的答复。 虽然有两种方法可以做到这一点,但它们不一定会产生相同的输出。特别是当您在
groupby
index=False
reset\u index()
df
+---------+---------+-------------+------------+
| column1 | column2 | column_date | column_sum |
+---------+---------+-------------+------------+
| A | M | 26-10-2018 | 2 |
| B | M | 28-10-2018 | 3 |
| A | M | 30-10-2018 | 6 |
| B | M | 01-11-2018 | 3 |
| C | N | 03-11-2018 | 4 |
+---------+---------+-------------+------------+
它们的工作方式不同
df = df.groupby(
by=[
'column1',
'column2',
pd.Grouper(key='column_date', freq='M')
],
as_index=False
).sum()
以上将给出
+---------+---------+------------+
| column1 | column2 | column_sum |
+---------+---------+------------+
| A | M | 8 |
| B | M | 3 |
| B | M | 3 |
| C | N | 4 |
+---------+---------+------------+
而
df = df.groupby(
by=[
'column1',
'column2',
pd.Grouper(key='column_date', freq='M')
]
).sum().reset_index()
将给予
+---------+---------+-------------+------------+
| column1 | column2 | column_date | column_sum |
+---------+---------+-------------+------------+
| A | M | 31-10-2018 | 8 |
| B | M | 31-10-2018 | 3 |
| B | M | 30-11-2018 | 3 |
| C | N | 30-11-2018 | 4 |
+---------+---------+-------------+------------+
您需要添加
drop=True
:
df.reset_index(drop=True)
df = df.groupby(
by=[
'column1',
'column2',
pd.Grouper(key='column_date', freq='M')
]
).sum().reset_index(drop=True)
+---------+---------+-------------+------------+
| column1 | column2 | column_date | column_sum |
+---------+---------+-------------+------------+
| A | M | 31-10-2018 | 8 |
| B | M | 31-10-2018 | 3 |
| B | M | 30-11-2018 | 3 |
| C | N | 30-11-2018 | 4 |
+---------+---------+-------------+------------+
df.reset_index(drop=True)
df = df.groupby(
by=[
'column1',
'column2',
pd.Grouper(key='column_date', freq='M')
]
).sum().reset_index(drop=True)