I have a dataframe with a list as one of the columns. The list is common to the label.
df = pd.DataFrame({'label': ['cell_1', 'cell_1', 'cell_1', 'cell_1', 'cell_2', 'cell_2', 'cell_2'],
'index': [1, 2, 5, 6, 1, 18, 5],
'item': [121, 989, 222, 333, 878, 777, 878],
'list': [[121, 454, 989], [121, 454, 989], [121, 454, 989], [121, 454, 989], [111, 777, 999], [111, 777, 999], [111, 777, 999]]})
label index item list
0 cell_1 1 121 [121, 454, 989]
1 cell_1 2 989 [121, 454, 989]
2 cell_1 5 222 [121, 454, 989]
3 cell_1 6 333 [121, 454, 989]
4 cell_2 1 878 [111, 777, 999]
5 cell_2 18 777 [111, 777, 999]
6 cell_2 5 878 [111, 777, 999]
I would like to check if the value in the item column is in the list. If it is I would like to pop the row into its own dataframe:
popped_df
label index item
0 cell_1 1 121
1 cell_1 2 989
2 cell_2 18 777
And remove the item value from the list in the remaining dataframe:
df
label index item list
0 cell_1 5 222 [454]
1 cell_1 6 333 [454]
2 cell_2 1 878 [111, 999]
3 cell_2 5 878 [111, 999]
I have tried many things, all of which run into big problems. I think maybe the solution is going to be putting the data in nested dictionaries (with label as the key, and each index as a value) and iterating through. I would rather not go from dataframe to dictionary and back even if it means slow performance.
Thank you in advance!