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

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

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 :

  1. l = ['A','b','A','A','C']

I know that :

  1. id value
  2. 1 'A'
  3. 2 'B'
  4. 3 'C'
  5. 4 'D'

I want to map the ids to the elements so that the output would be

  1. out = [1,2,1,1,3]

答案1

得分: 1

假设df是你的DataFrame,使用列表推导和一个映射的Series或字典:

  1. elems = ['A','b','A','A','C']
  2. s = df.set_index('value')['id']
  3. # 或者
  4. # s = dict(zip(df['value'], df['id']))
  5. out =
    展开收缩

或者使用pandas和map

  1. out = pd.Series(elems).str.upper().map(s).tolist()

输出:[1, 2, 1, 1, 3]

使用的df

  1. 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:

  1. elems = ['A','b','A','A','C']
  2. s = df.set_index('value')['id']
  3. # or
  4. # s = dict(zip(df['value'], df['id']))
  5. out =
    展开收缩

Or with pandas and map:

  1. out = pd.Series(elems).str.upper().map(s).tolist()

Output: [1, 2, 1, 1, 3]

Used df:

  1. df = pd.DataFrame({'id': [1, 2, 3, 4], 'value': ['A', 'B', 'C', 'D']})

答案2

得分: 1

你可以使用 zip,例如:

  1. ids = [1, 2, 3, 4]
  2. values = ['A', 'B', 'C', 'D']
  3. value_dict = {value: id for id, value in zip(ids, values)} # 或者:dict(zip(values, ids))
  4. l = ['A', 'B', 'A', 'A', 'C']
  5. out = [value_dict[value] for value in l]

完整示例在此

英文:

You can use zip for example:

  1. ids = [1, 2, 3, 4]
  2. values = ['A', 'B', 'C', 'D']
  3. value_dict = {value: id for id, value in zip(ids, values)} # or: dict(zip(values, ids))
  4. l = ['A', 'B', 'A', 'A', 'C']
  5. out = [value_dict[value] for value in l]

Full example here

答案3

得分: 1

  1. x = ['A', 'B', 'C', 'D'] #your elements
  2. ids = [1, 2, 3, 4] #their corresponding ids
  3. d = dict(zip(x, ids)) # you can create a dictionary d
  4. # {'A': 1, 'B': 2, 'C': 3, 'D': 4} # this is d
  5. l = ['A', 'B', 'A', 'A', 'C']
  6. print([d[x] for x in l])
  7. #output
  8. [1, 2, 1, 1, 3]
英文:
  1. x = ['A','B','C','D'] #your elements
  2. ids = [1,2,3,4] #their corresponding ids
  3. d=dict(zip(x,ids)) # you can create a dictionary d
  4. #{'A': 1, 'B': 2, 'C': 3, 'D': 4} # this is d
  5. l = ['A','B','A','A','C']
  6. print([d[x] for x in l ])
  7. #output
  8. [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:

确定