我试图通过与第一列值对应的第二列的不同计数对数据帧的第一列进行排序。
来自数据透视表的未排序数据:
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/