【问题标题】:Map a dictionary to lists in dataframe column将字典映射到数据框列中的列表
【发布时间】:2021-07-14 01:13:01
【问题描述】:

给定一个包含countrytopicindustry 列的数据框,当列由列表组成时,我如何将字典映射到每一列?

例如,国家/地区的字典包含数百个国家和地区代码的映射:

>> cnt_dict = {'AARCT': 'ANTARTICA', 'ABDBI': 'ABU DHABI', 'AFGH': 'AFGHANISTAN' ... 'ZAIRE': 'DEMOCRATIC REPUBLIC OF THE CONGO', 'ZAMBIA': 'ZAMBIA', 'ZIMBAB': 'ZIMBABWE'}

df 对应的一列是国家代码列表:

>>df['country'].head(5)
country
[ANDO, COOKIS, INDOCH]
[IRAN]
[MALAG, BERM, WESTW, USAWI]
[]
[ECU, FALK, OMAN]

我如何将 cnt_dic 映射到 df['country'] 以将每个列表中的每个值转换为其映射的字典值,以便输出将是(使用伪代码):

>> df['country'] = df['country'].map(cnt_dic to lists)
>> df['country'].head(5)
country
[ANDORRA, COOK ISLANDS, INDO-CHINA]
[IRAN]
[MADAGASCAR, BERMUDA, WESTERN WORLD, UNITED STATES WISCONSIN]
[]
[ECUADOR, FALKLAND ISLANDS, OMAN]

我尝试了df['country'] = df['country'].apply(lambda x: list(map(lambda y:cnt_dic.get(y, None), x))),但我只在所有列表中获得了None 值,并且没有其他任何工作。

另外,如果可能的话,最终的数据帧非常大,所以速度很重要。

【问题讨论】:

  • 你试过df['country'] = df['country'].apply(lambda x: [cnt_dict.get(i) for i in x])

标签: python pandas dictionary mapping


【解决方案1】:

@trianta2 @DrakeMurdoch 只是为了确保我尝试制作一个示例,并且它工作正常

import pandas as pd
df = pd.DataFrame({'d': [['A', 'B'], ['B', 'C'], ['A']]})
df
        d
0  [A, B]
1  [B, C]
2     [A]
d = {'A':2, 'B':0, 'C':4}
df['k'] = df['d'].apply(lambda x: [d[i] for i in x])

#output
df
        d       k
0  [A, B]  [2, 0]
1  [B, C]  [0, 4]
2     [A]     [2]

【讨论】:

  • 所以,出于某种原因,当我这样做时,它只填写列表中的第一个值,其余的保留为None。你知道为什么会这样吗?例如:['ARGENTINA', None, None]
  • 我能想到的唯一原因是你的字典没有正确的键,你能仔细检查一下吗?
  • 好的,我发现了一些搞砸了的空格。但现在它完美地工作了!谢谢!
【解决方案2】:

问题是您的country 列是一系列列表,因此您需要遍历每个行列表中的元素,并将该元素用作cnt_dict 中的键。 @nidabdella 的评论就是这样做的。但是,列表不可散列,因此您应该得到 TypeError 而不是 None...

【讨论】:

  • 即使我使用@nidabella 的想法,我仍然在我的所有列表中得到None
猜你喜欢
  • 2018-05-03
  • 1970-01-01
  • 2018-08-13
  • 1970-01-01
  • 2010-12-31
  • 1970-01-01
  • 2020-08-25
  • 1970-01-01
  • 2015-07-24
相关资源
最近更新 更多