Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Replace Top 2 rows on a condition match

Tags:

python

pandas

> import pandas as pd
> df = pd.DataFrame({'A':xrange(1,10),'B':xrange(0,9)}) 
> print df   
   A  B
0  1  0
1  2  1
2  3  2
3  4  3
4  5  4
5  6  5
6  7  6
7  8  7
8  9  8

I Need to replace first 2 matches of B (after filtering the condition df.A % 2 == 0) as -1

> print output
   A  B
0  1  0
1  2  -1
2  3  2
3  4  -1
4  5  4
5  6  5
6  7  6
7  8  7
8  9  8  

I tried doing df.B[df.A % 2 == 0][0:2] = -1 or df["B"][df.A % 2 == 0][0:2] = -1 - It is not resulting in error but not even replacing? What could be possibly going wrong?

But, when I tried df.B[df.A %2 == 0] = -1 - It is working (but replacing all the matches by -1).

like image 897
Kartheek Palepu Avatar asked Jul 14 '26 03:07

Kartheek Palepu


1 Answers

You've got that because you use chained slicing and you've got copy of the data but not the original data. From docs:

Since the chained indexing is 2 calls, it is possible that either call may return a copy of the data because of the way it is sliced. Thus when setting, you are actually setting a copy, and not the original frame data. It is impossible for pandas to figure this out because their are 2 separate python operations that are not connected.

You could solve your problem with one slice:

mask = df.A%2 == 0
idx = mask[mask].index
df.B[idx[:2]] = -1

In [91]: df
Out[91]:
   A  B
0  1  0
1  2 -1
2  3  2
3  4 -1
4  5  4
5  6  5
6  7  6
7  8  7
8  9  8

In [92]: mask
Out[92]:
0    False
1     True
2    False
3     True
4    False
5     True
6    False
7     True
8    False
Name: A, dtype: bool

In [93]: idx
Out[93]: Int64Index([1, 3, 5, 7], dtype='int64')
like image 198
Anton Protopopov Avatar answered Jul 17 '26 15:07

Anton Protopopov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!