您可以通过以下方式实现您想要的目标:
index_list = ["green", "yellow", "red", "pink", "purple"]
replace_dict = {True: 'Yes', False: 'No', np.nan:'Empty'}
df_test.loc[list(d.keys())].apply(lambda x : pd.Series(x.index.isin(d[x.name]),
index=x.index), axis=1).reindex(index_list).replace(replace_dict)
bear dog cat
green Yes Yes No
yellow Yes No No
red Yes No No
pink Empty Empty Empty
purple Empty Empty Empty
解释
您可以通过检查数据框的列是否存在于字典的相应字段中来实现所需的内容:
df_test.loc[list(d.keys())].apply(lambda x : pd.Series(x.index.isin(d[x.name]),
index=x.index), axis=1)
bear dog cat
green True True False
yellow True False False
red True False False
然后根据字典的键重新索引,以查找缺失的颜色并用空值填充:
index_list = ["green","yellow","red","pink", "purple"]
df_test.loc[list(d.keys())].apply(lambda x : pd.Series(x.index.isin(d[x.name]),
index=x.index), axis=1).reindex(index_list)
bear dog cat
green True True False
yellow True False False
red True False False
pink NaN NaN NaN
purple NaN NaN NaN
接着,如果你想要改变值,可以使用类似于以下的字典进行替换:
replace_dict = {True: 'Yes', False: 'No', np.nan:'Empty'}
df_test.loc[list(d.keys())].apply(lambda x : pd.Series(x.index.isin(d[x.name]),
index=x.index), axis=1).reindex(index_list).replace(replace_dict)
bear dog cat
green Yes Yes No
yellow Yes No No
red Yes No No
pink Empty Empty Empty
purple Empty Empty Empty
NaN
值? - jezrael