1

I would like to replace an entire row in a data, subject to one column in that row satisfying the condition. i.e. where red is the dataframe

['1' 0.0 ' P']
['2' 0.0 ' S']
['3' 64  ' M']
['4' 70  ' M']



red=red.replace(to_replace=' M', value=0)

returns the result:

['1' 0.0 ' P']
['2' 0.0 ' S']
['3' 64  0]
['4' 70  0]

but I would like it to return:

['1' 0.0 ' P']
['2' 0.0 ' S']
['3' 0  0]
['4' 0  0]

1 Answer 1

6

Use loc to filter out the part of the DataFrame you want to zero, and then assign the value to it. Below, it selects all lines where c column value is 'M' and it takes all columns from b to c, and set the value of this selection to 0:

df = pd.DataFrame([['1', 0.0, 'P'],
    ...: ['2', 0.0, 'S'],
    ...: ['3', 64,  'M'],
    ...: ['4', 70,  'M'],], columns=['a', 'b', 'c'])

df.loc[df['c']=='M','b':'c'] = 0

df
Out[54]: 
   a  b  c
0  1  0  P
1  2  0  S
2  3  0  0
3  4  0  0
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer, but how to select values in a range ? df.loc[ df['c']>0 and df['c']<1,'b':'c'] = 0 will raise an error
You forget the parenthesis, please see link here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.