简体   繁体   中英

Pandas: How to replace values of Nan in column based on another column?

Given that, i have a dataset as below:

dict = {
    "A": [math.nan,math.nan,1,math.nan,2,math.nan,3,5],
    "B": np.random.randint(1,5,size=8)
}

dt = pd.DataFrame(dict)

My favorite output is, if the in column A we have an Nan then multiply the value of the column B in the same row and replace it with Nan . So, given that, the below is my dataset:

    A  B
  NaN  1
  NaN  1
  1.0  3
  NaN  2
  2.0  3
  NaN  1
  3.0  1
  5.0  3

My favorite output is:

  A  B
  2  1
  2  1
  1  3
  4  2
  2  3
  2  1
  3  1
  5  3

My current solution is as below which does not work:

dt[pd.isna(dt["A"])]["A"] = dt[pd.isna(dt["A"])]["B"].apply( lambda x:2*x  )

print(dt)

In your case with fillna

df.A.fillna(df.B*2, inplace=True)
df
     A  B
0  2.0  1
1  2.0  1
2  1.0  3
3  4.0  2
4  2.0  3
5  2.0  1
6  3.0  1
7  5.0  3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM