我已经搜索了如何在整个堆栈溢出和其他站点上“使用另一个数据框的多列创建一个行数据框”,但是我只遇到诸如“如何合并列”或“如何连接数据框”之类的主题。但是我还没有看到如何合并列名。
我有tsv
个文件,这些文件是我使用Pandas
在python中导入的。数据帧是这样的:
min_mz_parent | max_mz_parent | mz_bin | intensity
405 | 415 | 999 | 750
405 | 515 | 1000 | 5482
405 | 515 | 1001 | 6487
...
705 | 715 | 999 | 847
705 | 715 | 1000 | 12546
我有160个这样的文件。我想遍历所有这些对象,然后将column 1, 2 and 3
的值连接起来,以在新数据帧中创建新列的名称,并且对应于该新列的值将为the value of the 4th column
第一个数据帧。
最后,我希望最终的数据帧是这样的(如果有一个文件,如果有更多文件,则有更多行):
405_415_999 | 405_415_1000 | 405_415_1001 | ... | 705_715_999 | 705_715_1000_12546
750 | 5482 | 6487 | ... | 847 | 12546
我已经有一个功能代码。它适用于小型文件(500ko),但是当我想将其应用于大型文件时会花费很多时间:修改然后串联每个120Mo的160个tsv文件。
我听说使用iterrows()
可能会浪费很多时间,应该使用vectorization
,但我仍然不知道如何解决问题。
这是我现在拥有的代码(我没有导入检查args
的第一个if语句,因为它不涉及我的dataframe问题:
tsv_list = glob.glob(args.dir + '*.tsv')
concat_tsv = pd.DataFrame()
count_file = 1
elif args.MS == 'MS2':
for file in tsv_list:
name = {'sample': file.split('/')[-1]}
if 'high_J' in name['sample']:
continue
# Define target class name
if name['sample'].split('_')[0:1][0] in ['UP', 'SS', 'SM', 'SH','SE','SA','PM','PA','KP','KO','EF','EA','CF']:
target_class = [name['sample'].split('_')[0:1][0]]
elif name['sample'].split('_')[0:1][0] in ['SAu', 'ECl']:
target_class = name['sample'].split('_')[0:1][0]
elif 'Blanc' in name['sample']:
target_class = ['Blank']
else :
target_class = ['']
print('Wrong name : '+name['sample'])
print('Currently converting and adding : ' + name['sample'] + ' ### File n°' + str(count_file))
tsv = pd.read_csv(file, sep='\t')
# Create temporary pandas dataframe for each file
tmp = pd.DataFrame(name, index=[0])
tmp['target'] = target_class
# Iterate on each dataframe file and extract information
for index, row in tsv.iterrows():
mz = str(row['min_mz_parent']) + "_" + str(row['max_mz_parent']) + '_' + str(row['mz_bin'])
row_df = [row['intensity']]
tmp[mz] = row_df
concat_tsv = pd.concat([concat_tsv, tmp], axis=0, ignore_index=True)
count_file += 1
如果您想获得更多信息来帮助我,请告诉我。 祝你有美好的一天。
ElsaC