[英]How to sort a dataframe/pivot-table by a distinct count of subcategory?
我正在尝试通过与第一列值对应的第二列的不同计数对数据框的第一列进行排序。
数据透视表中未排序的数据:
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
此处,investor4 的第 2 列(公司)不同计数为 3,因此investor4 和匹配值应位于顶部。
投资者 3 和投资者 1 的计数均为 2,最好对轮数或平均轮数应用二次(但不是必需的)排序。
我对 python/pandas 很陌生——但我正在努力寻找一个应用它的例子。 pandas 文档很好,但并没有完全触及这类问题。
https://pandas.pydata.org/pandas-docs/version/0.15.0/reshaping.html
任何帮助将不胜感激!
重置索引以使 pivot 表形成 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
创建sort index
并按该列排序
>>> 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
使用DataFrame.groupby + DataFrame.sort_values和DataFrame.reindex :
df['order']=df.groupby(level=0).round.transform('size')
df=df.sort_values('order',ascending=False).reindex(columns=df.columns[:-1])
print(df)
round roundSize
investor company
investor4 Bar B 15
Baz C 100
Foo A 10
investor2 Bar A 10
Foo A 10
investor3 Bar A 10
Bar B 15
investor1 Foo A 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.