我有一个包含网络的tsv文件。这里有一个片段。列 0 包含唯一 ID,列 1 包含备用 ID(不一定是唯一)。之后的每一对列都包含一个"交互器"和一个交互分数。
11746909_a_at A1CF SHPRH 0.11081568 TRIM10 0.11914056
11736238_a_at ABCA5 ANKS1A 0.1333185 CCDC90B 0.14495682
11724734_at ABCB8 HYKK 0.09577321 LDB3 0.09845833
11723976_at ABCC8 FAM161B 0.15087105 ID1 0.14801268
11718612_a_at ABCD4 HOXC6 0.23559235 LCMT2 0.12867001
11758217_s_at ABHD17C FZD7 0.46334574 HIVEP3 0.24272481
例如,A1CF
连接到SHPRH
和TRIM10
,分数分别为0.11081568
和0.11914056
。我正在尝试使用熊猫将这些数据转换为"平面"格式,如下所示:
11746909_a_at A1CF SHPRH 0.11081568
TRIM10 0.11914056
11736238_a_at ABCA5 ANKS1A 0.1333185
CCDC90B 0.14495682
...... and so on........ ........ ....
请注意,每行可以有任意数量的(interactor, score)
对。
我尝试将列 0 和 1 设置为索引,然后df.colnames = ['Interactor', Weight']*int(df.shape[1]/2)
然后使用pandas.groupby
为列命名,但到目前为止,我的尝试还没有成功。有人可以提出一种方法吗?
生成上面指定的输出数据帧应该不会太难
from collections import OrderedDict
import pandas as pd
def open_network_tsv(filepath):
"""
Read the tsv file, returning every line split by tabs
"""
with open(filepath) as network_file:
for line in network_file.readlines():
line_columns = line.strip().split('t')
yield line_columns
def get_connections(potential_conns):
"""
Get the connections of a particular line, grouped
in interactor:score pairs
"""
for idx, val in enumerate(potential_conns):
if not idx % 2:
if len(potential_conns) >= idx + 2:
yield val, potential_conns[idx+1]
def create_connections_df(filepath):
"""
Build the desired dataframe
"""
connections = OrderedDict({
'uniq_id': [],
'alias': [],
'interactor': [],
'score': []
})
for line in open_network_tsv(filepath):
uniq_id, alias, *potential_conns = line
for connection in get_connections(potential_conns):
connections['uniq_id'].append(uniq_id)
connections['alias'].append(alias)
connections['interactor'].append(connection[0])
connections['score'].append(connection[1])
return pd.DataFrame(connections)
也许您可以在之后对输出进行dataframe.set_index(['uniq_id', 'alias'])
或dataframe.groupby(['uniq_id', 'alias'])