使用value_counts对数据帧进行排序

时间:2017-11-20 18:12:02

标签: python pandas

我有一个数据框,在“component_id”列下,我有几次重复的component_ids。 这是df的样子:

In [82]: df.head()
Out[82]:
   index  molregno      chembl_id  assay_id     tid     tid  component_id  
0      0    942606  CHEMBL1518722    688422  103668  103668          4891
1      0    942606  CHEMBL1518722    688422  103668  103668          4891
2      0    942606  CHEMBL1518722    688721      78      78           286
3      0    942606  CHEMBL1518722    688721      78      78           286
4      0    942606  CHEMBL1518722    688779  103657  103657          5140

  component_synonym
0              LMN1
1              LMNA
2              LGR3
3              TSHR
4              MAPT

可以看出,相同的component_id可以链接到各种component_synonyms(基本上是相同的基因,但名称不同)。我想找出每个基因的频率,因为我想找出前20个最常见的基因,因此,我在“component_id”列上执行了value_counts。我得到这样的东西。

In [84]: df.component_id.value_counts()
Out[84]:
5432    804
3947    402
5147    312
3       304
2693    294
75      282
Name: component_id, dtype: int64

我有没有办法根据出现次数最多的component_id来订购整个数据帧? 而且,我的数据帧是否可能只包含每个component_id的第一次出现?

非常感谢任何建议!

1 个答案:

答案 0 :(得分:1)

我认为您可以使用count对行进行排序,然后删除计数列,即

df['count'] = df.groupby('component_id')['component_id'].transform('count')
df_sorted = df.sort_values(by='count',ascending=False).drop('count',1)