当列中的值更改时,Python Dataframe产生二进制输出

I came across this answer Determining when a column value changes in pandas dataframe about finding when the value in a data frame changes. I have a similar problem but want to produce a binary output.

我的代码:

df = 
      A
0    10 
1    20
2    20
3    50
4    50
5    30


df['B'] =  df['A'].diff()

df = 
      A    B
0    10    Nan 
1    20    10
2    20    0
3    50    30
4    50    0
5    30    -20

我期望输出这样的东西

df = 
      A    B     C
0    10    Nan   1 
1    20    10    1
2    20    0     0
3    50    30    1
4    50    0     0
5    30    -20   1
评论
  • Finn
    Finn 回复

    You just need an additional step to check if B equals 0:

    df['B'] = df.A.diff()
    df['C'] = df.B.ne(0).view('i1')
    
    print(df)
    
        A     B  C
    0  10   NaN  1
    1  20  10.0  1
    2  20   0.0  0
    3  50  30.0  1
    4  50   0.0  0
    5  30 -20.0  1