【发布时间】:2021-11-29 10:04:19
【问题描述】:
我有一个复杂的字典来重新映射值。我如何在 python 中实现这一点?
cols_to_check = ["ColA","ColB","ColC"]
dic_string = "{(Type 1 | Type 2) : Type dual,
(Type 3 | Type 4) : Type many,
ELSE: Not listed
}"
df = pd.DataFrame(
{
'ID': ['AB01', 'AB02', 'AB03', 'AB04', 'AB05','AB06','AB07','AB08'],
'ColA': ["Type 1","Undef",np.nan,"Undef",
"Type 1", "","", "Undef"],
'ColB': ["N","Type 2","","",
"Y", np.nan,"", "N"],
'ColC': [np.nan,"Undef","Type 3",np.nan,"Undef",
"Undef", "","Type 2"]
})
如果它是一个简单的字典并且其中没有提到 ELSE,我可以做到。假设我可以将“dic_string”转换为以下内容:
dic = {"Type 1" : "Type dual","Type 2" : "Type dual",
"Type 3" : "Type many", "Type 4" : "Type many",
"ELSE": "Not listed"
}
如何使用新列“结果”制作像这样的最终结果。如何在不硬编码 dic 内容的情况下实现这一点?
【问题讨论】:
标签: python pandas dataframe numpy data-manipulation