Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change value in a pandas series based on condition

Tags:

python

pandas

I have a pandas series with only binary values

    0
0   1
1   0
2   0
3   0
4   1
5   0
6   1
7   0
8   0
9   1
10  0
11  1
12  0
13  1
14  0

I want to covert the value in series where it is zero and around it has one's i.e basically change 1, 0, 1 to 1, 1, 1.

Output I need is :

0     1
1     0
2     0
3     0
4     1
5     1
6     1
7     0
8     0
9     1
10    1
11    1
12    1
13    1
14    0

What I have tried here is to create a rolling window of 3 and check if the values are what I need. Is there any better way to go around doing this?

>>> window = df.rolling(3, center=True)
>>> (df[0] | window.apply(lambda x: 1 if (x == [1,0,1]).all() else 0)[0].fillna(0)).astype(int)

NOTE: I have tried shift function too.

like image 319
Vishnudev Avatar asked Dec 22 '25 21:12

Vishnudev


1 Answers

Use shift for boolean masks and set 1 by numpy.where:

m1 = df[0].shift() == 1
m2 = df[0].shift(-1) == 1
m3 = df[0] == 0

df[0] = np.where(m1 & m2 & m3, 1, df[0])

print (df)
    0
0   1
1   0
2   0
3   0
4   1
5   1
6   1
7   0
8   0
9   1
10  1
11  1
12  1
13  1
14  0
like image 65
jezrael Avatar answered Dec 24 '25 09:12

jezrael



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!