相关疑难解决方法(0)

pandas groupby在组内排序

我想将数据框分组为两列,然后对组内的聚合结果进行排序.

In [167]:
df

Out[167]:
count   job source
0   2   sales   A
1   4   sales   B
2   6   sales   C
3   3   sales   D
4   7   sales   E
5   5   market  A
6   3   market  B
7   2   market  C
8   4   market  D
9   1   market  E

In [168]:
df.groupby(['job','source']).agg({'count':sum})

Out[168]:
            count
job     source  
market  A   5
        B   3
        C   2
        D   4
        E   1
sales   A   2
        B   4
        C   6
        D   3
        E   7
Run Code Online (Sandbox Code Playgroud)

我现在想在每个组中按降序对count列进行排序.然后只占前三行.得到类似的东西:

            count
job …
Run Code Online (Sandbox Code Playgroud)

python sorting group-by pandas

131
推荐指数
5
解决办法
21万
查看次数

使用 Pandas GroupBy 从多列聚合唯一值

我进入了无数线程(1 2 3 ...),但仍然没有找到解决问题的方法......我有一个这样的数据框:

prop1 prop2 prop3    prop4 
L30   3     bob      11.2
L30   54    bob      10
L30   11    john     10
L30   10    bob      10
K20   12    travis   10 
K20   1     travis   4 
K20   66    leo      10
Run Code Online (Sandbox Code Playgroud)

我想在 prop1 上做一个 groupby,同时,聚合所有其他列,但只使用唯一值。像那样:

prop1  prop2       prop3       prop4
L30    3,54,11,10  bob,john    11.2,10
K20    12,1,66     travis,leo  10,4
Run Code Online (Sandbox Code Playgroud)

我尝试了不同的方法:

  1. df.groupby('prop1')['prop2','prop3','prop4'].apply(np.unique) 返回

AttributeError: 'numpy.ndarray' 对象没有属性 'index' PLUS TypeError: Series.name must be a hashable type

  1. 另外:.apply(lambda x: pd.unique(x.values.ravel()).tolist())它给出了一个列表作为输出,我想要列。

  2. df.groupby('prop1')['prop2','prop3','prop4'].unique() 本身不起作用,因为有多个列。

  3. .apply(f) 其中 f 是:

    def …

python unique dataframe pandas pandas-groupby

10
推荐指数
1
解决办法
7935
查看次数

标签 统计

pandas ×2

python ×2

dataframe ×1

group-by ×1

pandas-groupby ×1

sorting ×1

unique ×1