0

I have a dataframe and a list. The dataframe consists of the column 'CODE' and 'distance'. The list consists of a row of values. I want the value in 'CODE' changed to zero if values from the list are also present in the distance column of the dataframe.

import pandas as pd
df = pd.DataFrame({'CODE': np.arange(0, 220), 
                   'distance': np.arange(0, 1100, 5)})

a = [1080, 1090] #list

I can do the above operation comparing the dataframe with a single value using the code below.

df.loc[df.distance == 1080, 'CODE'] = 0

This results in the following outcome:

     CODE  distance
3       3        15
4       4        20
..    ...       ...
215   215      1075
216     0      1080
217   217      1085
218   218      1090

However, when I try to replace the value 1080 with the list a (see below) it doesn't work. How can I solve this?

df.loc[df.distance == a, 'CODE'] = 0

2 Answers 2

4

You can use pandas.Series.isin:

df.loc[df.distance.isin(a), 'CODE'] = 0
Sign up to request clarification or add additional context in comments.

Comments

1

You can apply a function to df that checks if distance is in a and if it is, change the corresponding CODE to 0:

df['CODE'] = df.apply(lambda x: 0 if x['distance'] in a else x['CODE'], axis=1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.