英文:
map id of elements to the values
问题
我有一个ids [1,2,3,4]
的列表和一个重复的元素列表:
l = ['A', 'b', 'A', 'A', 'C']
我知道:
id value
1 'A'
2 'B'
3 'C'
4 'D'
我想将这些id映射到元素,以便输出是:
out = [1, 2, 1, 1, 3]
英文:
I have a list of ids [1,2,3,4]
and a list of elements duplicated :
l = ['A','b','A','A','C']
I know that :
id value
1 'A'
2 'B'
3 'C'
4 'D'
I want to map the ids to the elements so that the output would be
out = [1,2,1,1,3]
答案1
得分: 1
假设df
是你的DataFrame,使用列表推导和一个映射的Series或字典:
elems = ['A','b','A','A','C']
s = df.set_index('value')['id']
# 或者
# s = dict(zip(df['value'], df['id']))
out = 展开收缩
或者使用pandas和map
:
out = pd.Series(elems).str.upper().map(s).tolist()
输出:[1, 2, 1, 1, 3]
使用的df
:
df = pd.DataFrame({'id': [1, 2, 3, 4], 'value': ['A', 'B', 'C', 'D']})
英文:
Assuming df
your DataFrame, use a list comprehension and a mapping Series/dictionary:
elems = ['A','b','A','A','C']
s = df.set_index('value')['id']
# or
# s = dict(zip(df['value'], df['id']))
out = 展开收缩
Or with pandas and map
:
out = pd.Series(elems).str.upper().map(s).tolist()
Output: [1, 2, 1, 1, 3]
Used df
:
df = pd.DataFrame({'id': [1, 2, 3, 4], 'value': ['A', 'B', 'C', 'D']})
答案2
得分: 1
你可以使用 zip,例如:
ids = [1, 2, 3, 4]
values = ['A', 'B', 'C', 'D']
value_dict = {value: id for id, value in zip(ids, values)} # 或者:dict(zip(values, ids))
l = ['A', 'B', 'A', 'A', 'C']
out = [value_dict[value] for value in l]
英文:
You can use zip for example:
ids = [1, 2, 3, 4]
values = ['A', 'B', 'C', 'D']
value_dict = {value: id for id, value in zip(ids, values)} # or: dict(zip(values, ids))
l = ['A', 'B', 'A', 'A', 'C']
out = [value_dict[value] for value in l]
答案3
得分: 1
x = ['A', 'B', 'C', 'D'] #your elements
ids = [1, 2, 3, 4] #their corresponding ids
d = dict(zip(x, ids)) # you can create a dictionary d
# {'A': 1, 'B': 2, 'C': 3, 'D': 4} # this is d
l = ['A', 'B', 'A', 'A', 'C']
print([d[x] for x in l])
#output
[1, 2, 1, 1, 3]
英文:
x = ['A','B','C','D'] #your elements
ids = [1,2,3,4] #their corresponding ids
d=dict(zip(x,ids)) # you can create a dictionary d
#{'A': 1, 'B': 2, 'C': 3, 'D': 4} # this is d
l = ['A','B','A','A','C']
print([d[x] for x in l ])
#output
[1, 2, 1, 1, 3]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论