Search code examples
pythonpandasfillna

Replace selected row values based on certain column


I would like to find rows in df where C contains X1 and replace value in A with value in C and, replace value in C with value in result1(shift values in C and result1 to the leftmost).

df:

   A        C      result1   result2
0  NaN      X1     10/10/10  NaN
1  TEXT:    >1     TEXT       <1
2  NaN      X1     10/11/11  <10

Expected output:

   A        C         result1    result2
0  X1       10/10/10  NaN        NaN         
1  TEXT:    >1        TEXT       <1
2  X1       10/11/11  NaN        <10

Solution

  • With mask and shift:

    subset = df.loc[:, "A":"result1"]
    df.loc[:, "A":"result1"] = subset.mask(df.C.eq("X1"), subset.shift(-1, axis=1))
    

    For the rows that C equals to "X1", the locations in the subset are filled with shifted subset.

    to get

    >>> df
    
           A         C result1 result2
    0     X1  10/10/10     NaN     NaN
    1  TEXT:        >1    TEXT      <1
    2     X1  10/11/11     NaN     <10