社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python的小技巧(三)根据表格第一列的值,整合后面几列内容

Robin唔系肉饼 • 5 年前 • 266 次点击  

以前在华大记得有一个同事是让我用Perl写过一次,如今Perl放下一段时间了,还是用Python写吧~

目的:

根据第一列的值,将多个对应的第2、3、4列的内容分别进行整合,以分号分隔

思路(仅以第二列进行说明)

  • 遍历每行,提取第一列和第二列
  • 第一列作为唯一索引key,构建字典。
  • 如果该字典第一次出现该key,则字典的值为第二列值构造出的列表(只有一个值)
  • 遍历字典,格式构造,输出文件
#!/usr/bin/env python
#encoding:utf-8
# catch all column2 data into 1 cell by unique column1
#Author Robin 2020/01/18

temp2 = dict()
temp3 = dict()
temp4 = dict()
with open("/share/nas1/Data/luohb/rawdata.mouse.tsv") as f:
    for line in f:
        line = line.strip('\n')
        key, col2, col3, col4 = line.split("\t")
        if key in temp2:
            temp2[key].append(col2)
        else:
            temp2[key] = [col2]

        if key in temp3:
            temp3[key].append(col3)
        else:
            temp3[key] = [col3]

        if key in temp4:
            temp4[key].append(col4)
        else:
            temp4[key] = [col4]

with open("./new_trrust_rawdata.mouse.tsv",  'w') as f:
    for key in temp2:
        col2 = ';'.join(temp2[key])
        col3 = ';'.join(temp3[key])
        col4 = ';'.join(temp4[key])
        line = "%s\t%s\t%s\t%s\n" % (key, col2, col3, col4)
        f.writelines(line)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53147
 
266 次点击