Reputation: 1445
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]
Upvotes: 1
Views: 1763
Reputation: 32095
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
Upvotes: 6