我有一个 tsv 文件(第 1 列 = 唯一 id,第 2 列 = 组关联(,如下所示:
BC187 1
L1374 1
YJM1332 1
YPS128 2
YPS606 2
YJM1273 2
UWOPS03.461.4 3
UWOPS05.217.3 3
UWOPS05.227.2 3
基本上BC187,L1374和YJM1332都属于第1组,等等。
我生成的输出是另一个唯一个体列表,如下所示:
Y12
DBVPG604
GE14S01.7B
我可以通过以下方式将第二个列表附加到 tsv 文件中:
with open('~/clade.file.txt', 'a') as f:
divergedstrain.to_csv(f, header = False, index = False)
获取以下列表:
BC187 1
L1374 1
YJM1332 1
YPS128 2
YPS606 2
YJM1273 2
UWOPS03.461.4 3
UWOPS05.217.3 3
UWOPS05.227.2 3
Y12
DBVPG604
GE14S01.7B
但是现在我需要给三个新的独特的个体(Y12,DBVPG604,GE14S01.7B(自己独特的关联,如下所示:
BC187 1
L1374 1
YJM1332 1
YPS128 2
YPS606 2
YJM1273 2
UWOPS03.461.4 3
UWOPS05.217.3 3
UWOPS05.227.2 3
Y12 4
DBVPG604 5
GE14S01.7B 6
我不确定通过 python 或 bash 做到这一点的最佳方法是什么。任何建议
这里有一种方法可以做到这一点:
from pandas import DataFrame as df
from pandas import read_csv
file_path = 'clade.file.txt'
divergedstrain = df(["Y12", "DBVPG604", "GE14S01.7B", "Y12"])
with open(file_path, 'a') as f:
divergedstrain.to_csv(f, header=False, index=False)
df = read_csv(file_path, header=None, delimiter=' ', skipinitialspace=True, usecols=[0, 1])
ids = {}
for index, row in df.iterrows():
if row[0] not in ids and row[1] == row[1]:
ids[row[0]] = row[1]
def set_and_save(curr_row):
if curr_row[1] != curr_row[1]:
if curr_row[0] in ids:
curr_row[1] = ids[curr_row[0]]
else:
new_id = max(ids.values()) + 1
ids[curr_row[0]] = new_id
curr_row[1] = new_id
return curr_row
df = df.apply(set_and_save, axis=1)
print(df)
输出:
0 1
0 BC187 1.0
1 L1374 1.0
2 YJM1332 1.0
3 YPS128 2.0
4 YPS606 2.0
5 YJM1273 2.0
6 UWOPS03.461.4 3.0
7 UWOPS05.217.3 3.0
8 UWOPS05.227.2 3.0
9 Y12 4.0
10 DBVPG604 5.0
11 GE14S01.7B 6.0
12 Y12 4.0