Skip to main content
 首页 » 编程设计

python之按多列唯一排序,然后合并不匹配列中的值

2025年05月04日16sxdcgaq8080

考虑一个包含遗传变异的床文件:

CHR START STOP RSID REF/ALT PHENOTYPE PVALUE
1 987654321 987654322 rs123456 A/T Height 6E-9
1 987654321 987654322 rs123456 A/T Stroke 8E-15

我想按前 5 列进行唯一排序,然后合并具有唯一值的列中的内容:

示例输出:

CHR START STOP RSID REF/ALT PHENOTYPE PVALUE
1 987654321 987654322 rs123456 A/T Height,Stroke 6E-9,8E-15

这在 Python 或 Unix 中可行吗?还是需要写脚本?

如果在 Python 或 Unix 中可行,什么函数允许我这样做?


这个问题已在 here 上得到解决,但从未解决。

请您参考如下方法:

python

使用 Python,可以使用 pandas.dataframe.groupby 和 agg 以及自定义 lambda 函数 lambda x: ','.join(x)

import pandas as pd 
from io import StringIO 
 
text='''CHR START STOP RSID REF/ALT PHENOTYPE PVALUE 
1 987654321 987654322 rs123456 A/T Height 6E-9 
1 987654321 987654322 rs123456 A/T Stroke 8E-15''' 
 
df = pd.read_csv(StringIO(text), sep=' ', dtype={'PVALUE': str}) 
print(df) 
   CHR      START       STOP      RSID REF/ALT PHENOTYPE PVALUE 
0    1  987654321  987654322  rs123456     A/T    Height   6E-9 
1    1  987654321  987654322  rs123456     A/T    Stroke  8E-15 
 
df_res = (df.groupby(['CHR', 'START', 'STOP', 'RSID', 'REF/ALT']) 
          .agg({'PHENOTYPE': lambda x: ','.join(x), 
                'PVALUE': lambda x: ','.join(x)}) 
          .reset_index()) 
print(df_res) 
   CHR      START       STOP      RSID REF/ALT      PHENOTYPE      PVALUE 
0    1  987654321  987654322  rs123456     A/T  Height,Stroke  6E-9,8E-15 

使用 sort_values 以您想要的顺序对 df_res 进行排序。