处理bed文件,把第四列内容拆分提取出来
去除字符串出现重复的行,保留ENSG后编码最小的数值所在行
例如
import pandas as pd
import json
import os
def bedToJson():
# bed -> json
df = pd.read_csv('Homo_sapiens.GRCh37.75.chr.pc.gene.bed', sep='\t')
df.columns = ['A', 'B', 'C', 'D', 'E', 'F']
df.dropna(axis=0, how='all', inplace=True)
df['D'] = df['D'].apply(lambda x: str(x).replace("\"", "").replace(",", "").replace(" ", ""))
df['D1'] = df['D'].apply(lambda x: str(x).split(":")[0][9:])
df['D2'] = df['D'].apply(lambda x: str(x).split(":")[1])
df['D3'] = df['D'].apply(lambda x: str(x).split(":")[0])
df = df.iloc[df.groupby('D2').apply(lambda o: o['D1'].astype('int').idxmax())]
df = df.loc[:, ['D3', 'D2']]
df_dict = df.set_index('D3')['D2'].to_dict()
json_data = json.dumps(df_dict, separators=(',', ':'), sort_keys=True, indent=2)
if os.path.exists("ENGS_genes.json"):
os.remove("ENGS_genes.json")
with open('ENGS_genes.json', 'a') as f:
f.write(json_data)
def dealTsv():
# 处理之前的tsv
df = pd.read_csv("TCGA-BRCA.htseq_fpkm.tsv", sep="\t")
df['tempOne'] = df['Ensembl_ID'].apply(lambda x: x.split(".")[0])
df['tempTwo'] = df['Ensembl_ID'].apply(lambda x: int(x.split(".")[1]))
df_new = df.iloc[df.groupby('tempOne').apply(lambda o: o['tempTwo'].idxmax())]
json_data = pd.read_json("ENGS_genes.json", typ="series")
json_dict = json_data.to_dict()
json_key_list = list(json_dict.keys())
df_new['Ensembl_ID'] = df_new['Ensembl_ID'].apply(lambda x: x.split(".")[0])
df_new = df_new[df_new['Ensembl_ID'].isin(json_key_list)]
df_new['Ensembl_ID'] = df_new['Ensembl_ID'].apply(lambda x: json_dict[x])
df_new = df_new.drop(['tempOne', 'tempTwo'], axis=1)
df_new.to_csv('pYResult.tsv', sep="\t", index=False)
if __name__ == '__main__':
bedToJson()
dealTsv()
文件发一下我帮你弄下
第四列内容相同的行 其他列内容相同吗?
最好能把完整数据给几条,就能知道该怎么处理数据了。
读出每一列 然后以\t(间距几个tab就用几个\t)分行 然后处理