Efficiently replace values from a column to another column Pandas DataFrame

前端 未结 3 481
温柔的废话
温柔的废话 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条回答
  •  -上瘾入骨i
    2020-12-08 05:30

    I'm not sure if it's faster, but you're right that you can slice the dataframe to get your desired result.

    df.col1[df.col1 == 0] = df.col2
    df.col1[df.col1 == 0] = df.col3
    print(df)
    

    Output:

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

    Alternatively if you want it to be more terse (though I don't know if it's faster) you can combine what you did with what I did.

    df.col1[df.col1 == 0] = df.col2.replace(0, df.col3)
    print(df)
    

    Output:

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

提交回复
热议问题