[英]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.我需要根据条件创建一个新列,如果 a[i] 和 a[i-1] 相同,则值为 0,否则为 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
:通过 sompare 为不等于
ne
与shift
ed Series
创建布尔掩码并shift
为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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.