I have dataframe. I need to create a dictionary with row as the key and columns which has 'True' as the values of the dictionary

Question:

     0    1      2      3      4      5      6      7      8      9  
3  False   True  False   True   True  False   True   True   True  False      
4  False   True  False   True   True   True   True   True  False  False      

I need to create something like this

dict= {3: [1,3,4,6,7,8], 4: [0,1,3,4,5,6,7]}

Asked By: Image Privacy

||

Answers:

I hope I’ve understood your question right:

out = dict(
    df.apply(lambda x: [int(i) for i, v in zip(x.index, x) if v], axis=1)
)
print(out)

Prints:

{3: [1, 3, 4, 6, 7, 8], 4: [1, 3, 4, 5, 6, 7]}
Answered By: Andrej Kesely
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.