【问题标题】:Rename column names of groupby and count result with Pandas重命名 groupby 的列名并使用 Pandas 计算结果
【发布时间】:2020-06-22 01:12:32
【问题描述】:

给定以下数据框:

import numpy as np
df = pd.DataFrame({'price': np.random.random_integers(0, high=100, size=100)})
ranges = [0,10,20,30,40,50,60,70,80,90,100]
df.groupby(pd.cut(df.price, ranges)).count()

输出:

          price
 price  
(0, 10]     9
(10, 20]    11
(20, 30]    11
(30, 40]    9
(40, 50]    16
(50, 60]    7
(60, 70]    10
(70, 80]    9
(80, 90]    14
(90, 100]   4

我如何reset_index 结果并将列名重命名为binscounts?谢谢。

      bins    counts
0   (0, 10]     9
1   (10, 20]    11
2   (20, 30]    11
3   (30, 40]    9
4   (40, 50]    16
5   (50, 60]    7
6   (60, 70]    10
7   (70, 80]    9
8   (80, 90]    14
9   (90, 100]   4

【问题讨论】:

    标签: python pandas dataframe rename


    【解决方案1】:

    此代码有效但不够简洁,如果您有其他选择,欢迎分享:

    df.groupby(pd.cut(df.price, ranges)).count()\
    .rename(columns={'price' : 'counts'})\
    .reset_index()\
    .rename(columns={'price': 'bins'})
    

    输出:

          bins    counts
    0   (0, 10]     9
    1   (10, 20]    11
    2   (20, 30]    11
    3   (30, 40]    9
    4   (40, 50]    16
    5   (50, 60]    7
    6   (60, 70]    10
    7   (70, 80]    9
    8   (80, 90]    14
    9   (90, 100]   4
    

    【讨论】:

      【解决方案2】:

      一个想法是使用rename 用于来自pd.cut 的系列,因此如果选择列price 用于处理组输出为Series,则添加Series.reset_indexname 参数为2 columns DataFrame

      df1 = (df.groupby(pd.cut(df.price, ranges).rename('bins'))['price'].count()
               .reset_index(name='counts'))
      print (df1)
              bins  counts
      0    (0, 10]      13
      1   (10, 20]      13
      2   (20, 30]       9
      3   (30, 40]       9
      4   (40, 50]       7
      5   (50, 60]       9
      6   (60, 70]       9
      7   (70, 80]      12
      8   (80, 90]       9
      9  (90, 100]       9
      

      【讨论】:

      • 谢谢,你的解决方案好多了。
      猜你喜欢
      • 2018-12-12
      • 2013-10-31
      • 2021-02-24
      • 2021-12-13
      • 2016-07-28
      • 2017-03-28
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多