Home > Enterprise >  Shifting rows based on current column values in pandas
Shifting rows based on current column values in pandas

Time:08-12

I'm trying to shift all rows that have an E in colB to be blank in colA and then the values of colA and colB shifted over 1.

Everything I search on shift or adjusting has to do with moving columns up or down. I haven't found this solution yet.

df =
   colA colB colC
0   1    2    A
1   3    E    
2   8    7    B
3   3    E    
4   6    7    C

# Desired Output:

df_shifted =
   colA colB colC
0   1    2    A
1        3    E    
2   8    7    B
3        3    E    
4   6    7    C

I've tried using Shift commands or even splitting my base data differently. I can't seem to find a better solution than what I'm looking for here.

CodePudding user response:

Building on this answer, you can use where:

df[['colA','colB','colC']] = df[['colC','colA','colB']].where(df['colB'] == "E", df[['colA','colB','colC']].values)

prints:

  colA colB colC
0    1    2    A
1  NaN    3    E
2    8    7    B
3  NaN    3    E
4    6    7    C

CodePudding user response:

I'd suggest shift along the column axis and subsequent filling of NaNs, i.e.

df[df['colB'] == 'E'] = df[df['colB'] == 'E'].shift(1, axis=1).fillna('')

which yields

df
>  colA colB colC
 0    1    2    A
 1         3    E
 2    8    7    B
 3         3    E
 4    6    7    C
  • Related