【发布时间】:2020-11-05 00:02:04
【问题描述】:
使用矢量化,我想根据嵌套字典重新映射列,具体取决于第二列的值。在迭代逻辑中,我会遍历行;根据第二列中的值,我会从字典的第一级(又是字典)中选择一个条目,根据该条目映射值。
MWE
我有一个包含两列感兴趣的数据框:country 和 variable:
df= pd.DataFrame({"country": ["AA", "BB", "AA", "AA", "BB", "AA"],
"variable": ["foo/tball", "palace", "bla", "car", "bla", "dog"]})
我还有一个嵌套字典dct(variable 中的值仅与country 结合使用是唯一的,因此我无法取消嵌套字典)。 dct 包含 df['variable'] 中的条目字符串及其子字符串:
dct = {"AA": {'foo': 'NEWFOO', # substring of 'foo/tball'
'bla' : 'NEWBLA',
'cart': 'this value is not in the dataframe'}, # sic! -- not substring of any entry
"BB": {'pal': 'NEWPAL', # substring of palace
'bla': 'DIFFERENT_NEWBLA'},
"CC": {"this": "'CC' dictionary can be ignored"}}
我现在想按照以下规则根据dct[df['country']] 映射df['variable'] 的条目:
- 如果字符串匹配或者字典键是
df['variable']中条目的子字符串(例如dct['AA']中的'foo':根据字典替换条目 - 否则(即如果单元格条目不在字典中(例如
'dog'),则替换为某个预定义值(此处为_some_flag_value_) - 忽略字典中与
'country'列(例如dct["CC"])或'variable'列(例如dct['AA']中的'cart')不匹配的条目。
所需的输出应如下所示:
out = pd.DataFrame({"country": ["AA", "BB", "AA", "AA", "BB", "AA"],
"variable": ["NEWFOO", "NEWPAL", "NEWBLA", "_some_flag_value_",
"DIFFERENT_NEWBLA", "_some_flag_value_"]})
我尝试使用df.mapapply() 和lambda 的几种组合都无济于事 - 有人能指出我正确的方向吗?提前非常感谢。
【问题讨论】:
标签: python pandas dictionary replace apply