Data-frame filter according to a condition

  • A+
Category:Languages

I have a data-frame like

colA  colB  colC  A      B    C   A      D    C   B      B    E   A      D    C   C      B    C  

I want to filter them in a priority like this: If colC == E then return E, after that check colB == D return D otherwise return colA The output is

colA  colB  colC   final  A      B    C      A   A      D    C      D  B      B    E      E   A      D    C      D  C      B    C      C 

 


Create the condition Series, the chain with bfill and fillna

s=pd.Series({'colB':'D','colC':'E'}) df['New']=df.where(df.eq(s)).bfill(1).iloc[:,0].fillna(df.colA)  >>> df   colA colB colC New 0    A    B    C   A 1    A    D    C   D 2    B    B    E   E 3    A    D    C   D 4    C    B    C   C 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: