Skip to content
Advertisement

Convert a Pandas DataFrame with true/false to a dictionary

I would like to transform a dataframe with the following layout:

JavaScript

into a dictionary with the following structure:

JavaScript

Advertisement

Answer

IIUC, you could replace the False to NA (assuming boolean False here, for strings use ‘false’), then stack to remove the values and use groupby.agg to aggregate as list before converting to dictionary:

JavaScript

output:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement