Efficiently replace values from a column to another column Pandas DataFrame

前端 未结 3 483
温柔的废话
温柔的废话 2020-12-08 04:52

I have a Pandas DataFrame like this:

   col1 col2 col3
1   0.2  0.3  0.3
2   0.2  0.3  0.3
3     0  0.4  0.4
4     0    0  0.3
5     0    0    0
6   0.1  0.         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 05:39

    approach using pd.DataFrame.where and pd.DataFrame.bfill

    df['col1'] = df.where(df.ne(0), np.nan).bfill(axis=1).col1.fillna(0)
    df
    

    Another approach using np.argmax

    def pir2(df):
        slc = (df.values != 0).argmax(axis=1)
        return df.values[np.arange(slc.shape[0]), slc]
    

    I know there is a better way to use numpy to slice. I just can't think of it at the moment.

提交回复
热议问题