【问题标题】:Pandas: Sort the row counts per group in ascending orderPandas:按升序对每组的行数进行排序
【发布时间】:2021-05-07 08:09:36
【问题描述】:

我有一个df,如下:

In [257]: df
Out[257]: 
   user_id col1       col2
0        1    A    4.00000
1        1    A   22.00000
2        1    A  112.00000
3        1    B   -0.22222
4        1    B    9.00000
5        1    C    0.00000
6        2    A   -1.00000
7        2    A   -5.00000
8        2    K        NaN

我使用Groupby.size 计算每组的行数:

In [258]: df.groupby(['user_id', 'col1'])['col2'].size()
Out[258]: 
user_id  col1
1        A       3
         B       2
         C       1
2        A       2
         K       1
Name: col2, dtype: int64

目前,上面的输出是desc 的顺序。有没有一种以asc 顺序获取输出的熊猫方式?

预期输出:

user_id  col1
1        C       1
         B       2
         A       3
2        K       1
         A       2

【问题讨论】:

  • 为什么不在分组前对数据框进行排序?
  • 这行不通,因为我不想对任何现有列进行排序。我想对Groupby.size的输出进行排序。

标签: python python-3.x pandas sorting


【解决方案1】:

离我最近的是;

df.groupby(['user_id', 'col1'])['col2'].size().to_frame().sort_index(ascending=False)

【讨论】:

  • 不幸的是,这仅适用于样本数据,通常不会,因为不按计数排序,仅按 MultiiIndex
  • 如果替换例如你可以看到它CAAC 在样本数据中,然后解决方案失败。
【解决方案2】:

您需要使用值为Series 的第一级排序,这里是一个列DataFrameDataFrame.sort_values 的解决方案,用于按第一级user_idcol2 排序,最后一个为Series 选择@987654328 @:

s = df.groupby(['user_id', 'col1'])['col2'].size()

s = s.to_frame().sort_values(['user_id', 'col2'])['col2']
print (s)
user_id  col1
1        C       1
         B       2
         A       3
2        K       1
         A       2
Name: col2, dtype: int64

groupby 的另一个想法,如果更大的 DataFrame 应该更慢:

s = df.groupby(['user_id', 'col1'])['col2'].size()

s = s.groupby(level=0, group_keys=False).apply(lambda x: x.sort_values())
print (s)
user_id  col1
1        C       1
         B       2
         A       3
2        K       1
         A       2
Name: col2, dtype: int64

【讨论】:

  • 这里的s 是什么?
  • s = df.groupby(['user_id', 'col1'])['col2'].size()
猜你喜欢
  • 2011-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-01
  • 2012-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多