Create dictionary from results of DataFrame in pandas

前端 未结 5 1445
旧时难觅i
旧时难觅i 2021-01-16 16:35

I have a dataframe with results as below. Sample dataframe shown actual one is much larger. I want to get a dictionary (or another structure if it will be faster) with the

5条回答
  •  野的像风
    2021-01-16 17:03

    You can get the dot product of mask and columns and then use string operations i.e

    df.notna().dot(df.columns+',').str.strip(',').str.split(',').to_dict()
    
    {1: ['MSFT'], 2: ['GOOG', 'AMZN'], 3: ['AAPL', 'AMZN', 'FB'], 4: ['FB']}
    

提交回复
热议问题