[英]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
.我最喜欢的 output 是,如果在
A
列中我们有一个 Nan 然后乘以同一行中B
列的值并将其替换为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:我最喜欢的 output 是:
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
在您使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.