How to pass another entire column as argument to pandas fillna()

后端 未结 6 2184
太阳男子
太阳男子 2020-11-22 07:01

I would like to fill missing values in one column with values from another column, using fillna method.

(I read that looping through each row would be

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 07:22

    I know this is an old question, but I had a need for doing something similar recently. I was able to use the following:

    df = pd.DataFrame([["1","cat","mouse"],
        ["2","dog","elephant"],
        ["3","cat","giraf"],
        ["4",np.nan,"ant"]],columns=["Day","Cat1","Cat2"])
    
    print(df)
    
      Day Cat1      Cat2
    0   1  cat     mouse
    1   2  dog  elephant
    2   3  cat     giraf
    3   4  NaN       ant
    
    df1 = df.bfill(axis=1).iloc[:, 1]
    df1 = df1.to_frame()
    print(df1)
    

    Which yields:

      Cat1
    0  cat
    1  dog
    2  cat
    3  ant
    

    Hope this is helpful to someone!

提交回复
热议问题