python - 如何按子类别的不同计数对数据框/数据透视表进行排序?

标签 python pandas dataframe pivot-table

我试图通过与第一列值对应的第二列的不同计数对数据帧的第一列进行排序。

来自数据透视表的未排序数据:

investor  company round roundSize
investor1   Foo     A      10
investor2   Bar     A      10
            Foo     A      10
investor3   Bar     A      10
                    B      15
investor4   Bar     B      15
            Baz     C      100
            Foo     A      10

排序后,表格应该是:

investor  company round roundSize
investor4   Bar     B      15
            Baz     C      100
            Foo     A      10
investor2   Bar     A      10
            Foo     A      10
investor3   Bar     A      10
                    B      15
investor1   Foo     A      10

此处,投资者 4 的第 2 列(公司)非重复计数为 3,因此投资者 4 和匹配值应位于顶部。

investor3 和 Investor1 的计数均为 2,如果对 round 计数或 roundSize 平均值应用辅助(但不是必需)排序,那就太好了。

我对 python/pandas 很陌生 - 但我正在努力寻找应用此方法的示例。 pandas 文档很好,但并没有完全解决此类问题。

https://pandas.pydata.org/pandas-docs/version/0.15.0/reshaping.html

任何帮助将不胜感激!

最佳答案

重置索引以使数据透视表形成 DataFrame

>>> df = df.reset_index(drop=True)
>>> df
    investor company round  roundSize
0  investor1     Foo     A         10
1  investor2     Bar     A         10
2  investor2     Foo     A         10
3  investor3     Bar     A         10
4  investor3     Bar     B         15
5  investor4     Bar     B         15
6  investor4     Baz     C        100
7  investor4     Foo     A         10

创建排序索引并按该列排序

>>> df['sort_idx'] = df.groupby('investor')['company'].transform('nunique')
>>> df.sort_values('sort_idx', ascending=False)
    investor company round  roundSize  sort_idx
5  investor4     Bar     B         15         3
6  investor4     Baz     C        100         3
7  investor4     Foo     A         10         3
1  investor2     Bar     A         10         2
2  investor2     Foo     A         10         2
0  investor1     Foo     A         10         1
3  investor3     Bar     A         10         1
4  investor3     Bar     B         15         1

关于python - 如何按子类别的不同计数对数据框/数据透视表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58674344/

相关文章:

python - Pandas 使用列标题作为值将多个列转换/合并为单个列

r - 在 R 中,在事件之后而不是之前标记 ID 的行

python - OOP 属性定义

python - 迁移学习——尝试在内存不足的 RTX 2070 上重新训练 efficientnet-B07

python - 在 Pandas 中排序两次

python - 检查 Numpy 数组(和 Pandas DataFrame)中的所有元素并有选择地更改

python - 从数据框中选择特定值

python - 将行与之前的所有行进行比较

python - 根据列中的重复值有条件地复制数据

python-3.x - 数据框列的 Pyspark 并行循环