3 回答
TA贡献1829条经验 获得超7个赞
也许您正在寻找这样的东西:
val = {'A': ['arylpolyene', 'hserlactone', 'hserlactone', 'nrps', 'siderophore', 't1pks-nrps', 'terpene', 'thiopeptide', 'transatpks-nrps'],
'B': ['hserlactone', 'hserlactone-arylpolyene', 'nrps', 'siderophore', 'thiopeptide'],
'C': ['nrps', 'nrps', 'nrps', 'siderophore', 't1pks-nrps', 't1pks-nrps'],
'D': ['nrps', 'siderophore', 't1pks-nrps']}
all_val = []
for k in val:
for v in val[k]:
all_val.append((k,v))
df = pd.DataFrame(all_val,columns=['key','val']).set_index('key')
df_count = df.pivot_table(index='key',columns='val',aggfunc=len)
输出:
val arylpolyene hserlactone hserlactone-arylpolyene nrps siderophore \
key
A 1.0 2.0 NaN 1.0 1.0
B NaN 1.0 1.0 1.0 1.0
C NaN NaN NaN 3.0 1.0
D NaN NaN NaN 1.0 1.0
val t1pks-nrps terpene thiopeptide transatpks-nrps
key
A 1.0 1.0 1.0 1.0
B NaN NaN 1.0 NaN
C 2.0 NaN NaN NaN
D 1.0 NaN NaN NaN
TA贡献2051条经验 获得超10个赞
这应该可以完成您的工作(我正在使用Python3):
my_dict = {
'A': ['arylpolyene', 'hserlactone', 'hserlactone', 'nrps', 'siderophore', 't1pks-nrps', 'terpene', 'thiopeptide', 'transatpks-nrps'],
'B': ['hserlactone', 'hserlactone-arylpolyene', 'nrps', 'siderophore', 'thiopeptide'],
'C': ['nrps', 'nrps', 'nrps', 'siderophore', 't1pks-nrps', 't1pks-nrps'],
'D': ['nrps', 'siderophore', 't1pks-nrps']
}
rows_list=list(my_dict.keys())
values=list(my_dict.values())
rows_size=len(rows_list)
columns_list = []
for sublist in values:
for item in sublist:
if item not in columns_list:
columns_list.append(item)
columns_size = len(columns_list)
#initialize adjacent matrix
print('Initial adjacent matrix')
adjacent = [ [0]*columns_size for i in range(rows_size) ]
for row in adjacent:
print(row)
for key, value in my_dict.items():
for v in value:
adjacent[rows_list.index(key)][columns_list.index(v)] += 1
print('-'*50)
print('Final adjacent matrix')
for row in adjacent:
print(row)
在第一个循环中,for sublist in values:我创建一个列表,其中包含您想要的值作为没有重复项的列。
在“adjacent = [ [0]*columns_size for i in range(rows_size) ]我创建的列表”中,元素与字典键的数量一样多。每个元素都是一个列表,其中元素的数量与列值的数量一样多。
添加回答
举报