将元素的标识映射到数值。

huangapple go评论63阅读模式
英文:

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]

Full example here

答案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]

huangapple
  • 本文由 发表于 2023年3月15日 18:36:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75743523.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定