Home > Net >  Compare two lists and write for each item corresponding X column value
Compare two lists and write for each item corresponding X column value

Time:01-19

Let's say I have a list of users

resource = ['A', 'B', 'C']

then I have a table

| Date     |   |  Resource    |
| -------- |   | ------------ |
| 2022-11-01   | ['A', 'B', 'C']   |
| 2022-11-12   | ['A', 'B']   |
| 2022-11-13   | ['B', 'C']   |

What I want is: to have a list of Date for each Resource A, B, C

So desired output could be a dictionary:

A: 2022-11-01
   2022-11-12
B: 2022-11-01
   2022-11-12
   2022-11-13
C: 2022-11-01   
   2022-11-13

CodePudding user response:

You can use explode then use groupby and agg(list) at the end get the result as dict with to_dict.

dct = df.explode('Resource').groupby('Resource')['Date'].agg(list).to_dict()
print(dct)

Output:

{'A': ['2022-11-01', '2022-11-12'],
 'B': ['2022-11-01', '2022-11-12', '2022-11-13'],
 'C': ['2022-11-01', '2022-11-13']}
  • Related