你可以通过做得到你想要的:
# You can use elements that are not in the original dataframe
# and the row will be filled with empty
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
说明
您可以通过检查数据框的列是否存在于dict的相应字段中来完成您想要的:
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
然后根据dict的key重新索引来填充找到缺失的颜色并用空填充:
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