我试图基于数据帧中的映射表来映射列表中的元素。我的列表如下所示:
List1 = [('a','b'), ('a','c'), ('a','d'), ('b','c'), ('b','d')]
像这样映射表
mapping = {'name': ['a', 'b', 'c', 'd'],'ID': [1,2,3,2]}
df = pd.DataFrame(mapping)
我要实现的目标
Mappedlist = [(1,2), (1,3), (1,2), (2,3), (2,2)]
答案 0 :(得分:3)
尝试此嵌套列表理解:
print([[df.loc[df['name'] == x, 'ID'].item() for x in i] for i in List1])
输出:
[[1, 2], [1, 3], [1, 2], [2, 3], [2, 2]]
要修改:
print([[df.loc[df['ID'] == x, 'name'].item() for x in i] for i in List1])
输出:
[['a','b'], ['a','c'], ['a','d'], ['b','c'], ['b','d']]
答案 1 :(得分:1)
最好在Mappedlist
中迭代一次,而不要嵌套循环:
[(df['ID'].loc[df.name == x].item(), df['ID'].loc[df.name == y].item()) for (x, y) in List1]
# Result: [(1, 2), (1, 3), (1, 2), (2, 3), (2, 2)]
答案 2 :(得分:-1)
您可以在列表中调用变量而不是字符串,但是请确保变量应在List1之前
a = 1
b = 2
c = 3
d = 2
List1 = [(a,b), (a,c), (a,d), (b,c), (b,d)]
print(List1)
输出
[(1, 2), (1, 3), (1, 2), (2, 3), (2, 2)]