简体   繁体   中英

pandas create new column based on row value (condition)

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM