多次分组后如何将 pandas 数据从索引移到列 [英] How to move pandas data from index to column after multiple groupby

查看:39
本文介绍了多次分组后如何将 pandas 数据从索引移到列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下熊猫数据框:

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

我汇总具有重复的tokenyears的行,如下所示:

I aggregate the rows with duplicate token and years like so:

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

我不想在索引中包含令牌"和年份"字段,而是希望将它们返回到列中并具有整数索引.

Instead of having the 'token' and 'year' fields in the index, I would like to return them to columns and have an integer index.

推荐答案

方法1 : 方法2 :不要首先使用

Method #2: don't make the index in the first place, using 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]

这篇关于多次分组后如何将 pandas 数据从索引移到列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆