Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if a value exist in a column and change in another Pandas

I have the following information.

Let’s say I have the following list.

my_list = [2,3,4,5]

My dataframe is as follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df

Col1      Value
[1,3,6]    Hot
[7]        Mild
[10,11,2]  Cool
[5,9]      Cool
[2,5,6]    Mild

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.

Col1      Value
[1,3,6]    Hot
[7]        Mild
[10,11,2]  Cool
[5,9]      Hot
[2,5,6]    Hot

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?

>Solution :

You can use a combination of explode, isin, agg, and .loc:

df.loc[df['Col1'].explode().isin(my_list).groupby(level=0).any(), 'Value'] = 'Hot'

Output:

>>> df
          Col1 Value
0    [1, 3, 6]   Hot
1          [7]  Mild
2  [10, 11, 2]   Hot
3       [5, 9]   Hot
4    [2, 5, 6]   Hot
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading