I have the following information.
Let’s say I have the following list.
JavaScript
x
2
1
my_list = [2,3,4,5]
2
My dataframe is as follows:
df
JavaScript
1
7
1
Col1 Value
2
[1,3,6] Hot
3
[7] Mild
4
[10,11,2] Cool
5
[5,9] Cool
6
[2,5,6] Mild
7
I would like to check if one of the value from the list my_list
exist in the column Col1
. If it exist, change the value in Value
column to Hot
in the corresponding row.
I would like to see something like below.
JavaScript
1
7
1
Col1 Value
2
[1,3,6] Hot
3
[7] Mild
4
[10,11,2] Cool
5
[5,9] Hot
6
[2,5,6] Hot
7
I am just looking for a simple script that can iterate and check in every row and change a value in another column the corresponding row.
Can any one help on this?
Advertisement
Answer
You can use a combination of explode
, isin
, agg
, and .loc
:
JavaScript
1
2
1
df.loc[df['Col1'].explode().isin(my_list).groupby(level=0).any(), 'Value'] = 'Hot'
2
Output:
JavaScript
1
8
1
>>> df
2
Col1 Value
3
0 [1, 3, 6] Hot
4
1 [7] Mild
5
2 [10, 11, 2] Hot
6
3 [5, 9] Hot
7
4 [2, 5, 6] Hot
8