Skip to content
Advertisement

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

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

Advertisement

Answer

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']}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement