1

I have dataframe that is shown below,

    type  label
0      0      0
1      0      0
2      0      0
3      0      0
4      2      1
5      2      1
6      2      1
7      2      1
8      2      1
9      2      1
10     0      0
11     0      0
12     0      0
13     0      0
14     0      0
15     0      0
16     0      0
17     0      0
18     0      0
19     0      0 

(Need some magic to be done)

The change should be made in type column such that, in a row if label is 0 and type is 0 then next row of type should be assigned 2.

Full dataframe should look like this:

    type  label
0      0      0
1      2      0
2      2      0
3      0      0
4      2      1
5      2      1
6      2      1
7      2      1
8      2      1
9      2      1
10     0      0
11     2      0
12     2      0
13     2      0
14     2      0
15     2      0
16     2      0
17     2      0
18     2      0
19     2      0 

2 Answers 2

1

Using .eq() to mask row which has type and label columns value is 0 and .shift() to shift index by desired number of periods with an optional time freq.

Ex.

m = df['type'].eq(0) & df['label'].eq(0)
df.loc[m == m.shift(1),'type'] = 2
print(df)

O/P:

    type  label
0      0      0
1      2      0
2      2      0
3      2      0
4      2      1
5      2      1
6      2      1
7      2      1
8      2      1
9      2      1
10     0      0
11     2      0
12     2      0
13     2      0
14     2      0
15     2      0
16     2      0
17     2      0
18     2      0
19     2      0
Sign up to request clarification or add additional context in comments.

Comments

0

Similar approach

df['Condition']=(df==0).all(axis=1)
df['Condition']=df['Condition'].shift(periods=1).fillna(False)
df['Type'] = np.where(df['Condition'], 2, df['Type'])

Type  label  Condition
0      0      0      False
1      2      0       True
2      2      0       True
3      2      0       True
4      2      1       True
5      2      1      False
6      2      1      False
7      2      1      False
8      2      1      False
9      2      1      False
10     0      0      False
11     2      0       True
12     2      0       True
13     2      0       True
14     2      0       True
15     2      0       True
16     2      0       True
17     2      0       True
18     2      0       True
19     2      0       True

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.