我有以下 Pandas 数据框:
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
我像这样聚合具有重复 token
和 years
的行:
dfalph = dfalph[['token','year','uses','books']].groupby(['token', 'year']).agg([np.sum])
dfalph.columns = dfalph.columns.droplevel(1)
uses books
token year
xanthos 1830 3 3
1840 3 3
1867 2 2
1868 2 2
1875 1 1
我不想在索引中包含“token”和“year”字段,而是希望将它们返回到列并拥有一个整数索引。
最佳答案
方法#1:reset_index()
>>> g
uses books
sum sum
token year
xanthos 1830 3 3
1840 3 3
1868 2 2
1875 1 1
[4 rows x 2 columns]
>>> g = g.reset_index()
>>> g
token year uses books
sum sum
0 xanthos 1830 3 3
1 xanthos 1840 3 3
2 xanthos 1868 2 2
3 xanthos 1875 1 1
[4 rows x 4 columns]
方法#2:首先不要创建索引,使用as_index=False
>>> g = dfalph[['token', 'year', 'uses', 'books']].groupby(['token', 'year'], as_index=False).sum()
>>> g
token year uses books
0 xanthos 1830 3 3
1 xanthos 1840 3 3
2 xanthos 1868 2 2
3 xanthos 1875 1 1
[4 rows x 4 columns]
关于python - 多个groupby后如何将pandas数据从索引移动到列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21767900/