Reputation: 676
i have a column like this,
A
1.0
1.0
2.0
3.0
4.0
5.0
5.0
5.0
i need to create a new column based on a condition, if the a[i] and a[i-1] is same, then value is 0 else 1.
result should look something like this:
A B
1.0 1
1.0 0
2.0 1
3.0 1
4.0 1
5.0 1
5.0 0
5.0 0
The right pandas way to do it?
Upvotes: 4
Views: 381
Reputation: 862441
Create boolean mask by sompare for not equal by ne
with shift
ed Series
and cast to integer
:
df['B'] = df['A'].ne(df['A'].shift()).astype(int)
print (df)
A B
0 1.0 1
1 1.0 0
2 2.0 1
3 3.0 1
4 4.0 1
5 5.0 1
6 5.0 0
7 5.0 0
Detail:
print (df['A'].ne(df['A'].shift()))
0 True
1 False
2 True
3 True
4 True
5 True
6 False
7 False
Name: A, dtype: bool
Upvotes: 5