多次分组后如何将熊猫数据从索引移到列

发布于 2021-01-29 15:06:05

我有以下熊猫数据框:

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像这样:

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

我不想在索引中包含“令牌”和“年”字段,而是将它们返回到列中并具有整数索引。

关注者
0
被浏览
92
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    方法1reset_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]
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看