对pandas中的列使用唯一值

时间:2019-02-28 17:04:45

标签: python pandas sorting unique

我在熊猫中有一个数据框,其中有五列:重叠群,长度,同一性,百分比和命中率。此数据是从BLAST输出中解析出来的,并按重叠群长度和匹配百分比排序。我的目标是让输出为每个唯一重叠群只写一行。输出示例:

   contig        length  identity     percent  hit                                                                             
   contig-100_0  5485    [1341/1341]  [100.%]  ['hit1']
   contig-100_0  5485    [5445/5445]  [100.%]  ['hit2']
   contig-100_0  5485        [59/59]  [100.%]  ['hit3']
   contig-100_1  2865    [2865/2865]  [100.%]  ['hit1']
   contig-100_2  2800    [2472/2746]  [90.0%]  ['hit1']
   contig-100_3  2417    [2332/2342]  [99.5%]  ['hit1']
   contig-100_4  2204    [2107/2107]  [100.%]  ['hit1']
   contig-100_4  2000    [1935/1959]  [98.7%]  ['hit2']

我希望以上内容看起来像这样:

   contig        length  identity     percent  hit                                                                             
   contig-100_0  5485    [1341/1341]  [100.%]  ['hit1']
   contig-100_1  2865    [2865/2865]  [100.%]  ['hit1']
   contig-100_2  2800    [2472/2746]  [90.0%]  ['hit1']
   contig-100_3  2417    [2332/2342]  [99.5%]  ['hit1']
   contig-100_4  2204    [2107/2107]  [100.%]  ['hit1']

这是我用来产生以上输出的代码:

df = pd.read_csv(path+i,sep='\t', header=None, engine='python', \ 
     names=['contig','length','identity','percent','hit'])
df = df.sort_values(['length', 'percent'], ascending=[False, False])
top_hits = df.to_string(justify='left',index=False)
with open ('sorted_contigs', 'a') as sortedfile:
    sortedfile.write(top_hits+"\n")

我知道pandas中的unique()方法,并认为我需要使用的语法是df.contig.unique(),但是我不确定该将其放置在代码中的哪个位置。我仍在学习熊猫,因此我们将不胜感激!谢谢。

1 个答案:

答案 0 :(得分:3)

您可以使用DataFrame.groupby(<colname>).head(<num_of_rows>)来做到这一点:

df.groupby('contig').head(1)

输出:

          contig    length  identity    percent hit
0   contig-100_0    5485    [1341/1341] [100.%] ['hit1']
3   contig-100_1    2865    [2865/2865] [100.%] ['hit1']
4   contig-100_2    2800    [2472/2746] [90.0%] ['hit1']
5   contig-100_3    2417    [2332/2342] [99.5%] ['hit1']
6   contig-100_4    2204    [2107/2107] [100.%] ['hit1']