conditional replace based off prior value in same column of pandas dataframe python

后端 未结 2 1855
你的背包
你的背包 2021-01-16 06:51

Feel like I\'ve looked just about everywhere and I know its probably something very simple. I\'m working with a pandas dataframe and looking to fill/replace data in one of

相关标签:
2条回答
  • 2021-01-16 06:56

    Here's a kind of brute-force method. There is probably something more elegant, but you could explicitly loop over the rows like this:

    df = pd.DataFrame([0, -1, -1, -1, 0 , 0, 0, 1, 0])
    df.columns = ['A']
    df['B'] = df['A']
    
    # loop here
    for i in range(1,len(df)):
         if df.A[i] == 0 and df.B[i-1] == -1:
                 df.B[i] = -1
         else:
                 df.B[i] = df.A[i]
    

    This gives you the result you seek:

    >>> df['B']
    0    0
    1   -1
    2   -1
    3   -1
    4   -1
    5   -1
    6   -1
    7    1
    8    0
    
    0 讨论(0)
  • 2021-01-16 06:57

    using Where

    df['B'] = df.A[0:len(df.A)-1].where((df.A==0 ) & (df.B.shift(-1)==-1),-1)
    df['B'] = df['B'].fillna(df.A)
    
    0 讨论(0)
提交回复
热议问题