【问题标题】:Unable to set column names after a group by pandas?无法在熊猫分组后设置列名?
【发布时间】:2018-06-21 23:00:21
【问题描述】:

我运行了一个 pymongo 查询并将这些信息提取到一个名为“crime”的 pandas 数据框中。我现在正在尝试按“主要类型”和“年份”分组并计算记录并将计数显示为数据框中的标题以进行绘图。我尝试了以下方法,但我无法获得计数的标题出现。

new = crime.drop('_id', axis=1)
g = crime.drop('Date', axis=1)
g = new.groupby(['Primary Type', 'Year'])
g.columns = ['Count', 'Primary Type', 'Year']

我也试过了:

g = new.groupby(['Primary Type', 'Year']).
['_id']count().reset_index(name="Count")


File "<ipython-input-100-5d65646da11c>", line 3
g = new.groupby(['Primary Type', 'Year']).
['_id']count().reset_index(name="Count")
                                          ^
SyntaxError: invalid sy

【问题讨论】:

    标签: python pandas pymongo


    【解决方案1】:

    我相信你需要因为很长的代码()前后或在末尾使用\

    g = (new.groupby(['Primary Type', 'Year'])['_id']
            .count()
            .reset_index(name="Count")
            .reindex(columns=['Count', 'Primary Type', 'Year']))
    
    g = new.groupby(['Primary Type', 'Year'])['_id'] \
           .count()  \
           .reset_index(name="Count") \
           .reindex(columns=['Count', 'Primary Type', 'Year'])
    

    还省略了drop 代码,并添加了reindex 以更改列名称排序。

    示例:

    new = pd.DataFrame({'Primary Type':list('aaabbb'),
                       'Year':[2001,2001,2002,2002,2002,2002],
                       '_id':[7,8,9,4,2,3],
                       'Date':[1,3,5,7,1,0]})
    
    print (new)
       Date Primary Type  Year  _id
    0     1            a  2001    7
    1     3            a  2001    8
    2     5            a  2002    9
    3     7            b  2002    4
    4     1            b  2002    2
    5     0            b  2002    3
    
    g = (new.groupby(['Primary Type', 'Year'])['_id']
            .count()
            .reset_index(name="Count")
            .reindex(columns=['Count', 'Primary Type', 'Year']))
    print (g)
       Count Primary Type  Year
    0      2            a  2001
    1      1            a  2002
    2      3            b  2002
    

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-19
      • 2016-12-16
      • 2021-03-04
      • 1970-01-01
      • 2018-08-08
      相关资源
      最近更新 更多