[英]Fill NaNs in a column with the column max
My data: 我的数据:
df = pd.DataFrame({'a':[2, np.nan, 2, np.nan],
'b':[np.nan, np.nan, 3, 3]})
a b
2 np.nan
np.nan np.nan
2 3
np.nan 3
looking to get 期待着
a b
2 3
2 3
2 3
2 3
Tried forwardfill 尝试向前填充
df = df.ffill()
a b
2 np.nan
2 np.nan
2 3
2 3
Tried forward fill but because i had nan as the first row in b
, i got nan still in b
. 尝试向前填充,但因为我有
b
作为b
的第一行,我仍然在b
得到了nan。 How can i go about filling with unique values of each row instead? 我怎样才能填写每行的唯一值? (the columns all have repeating values or np.nan)
(列都有重复值或np.nan)
Chain a bfill
call: 链接一个
bfill
电话:
df.ffill().bfill()
a b
0 2.0 3.0
1 2.0 3.0
2 2.0 3.0
3 2.0 3.0
To allow pandas to downcast to int
s if possible, use 如果可能,允许pandas向下转换为
int
,请使用
df.ffill().bfill(downcast='infer')
a b
0 2 3
1 2 3
2 2 3
3 2 3
Another option is fillna
with max
. 另一个选择是
fillna
with max
。
df.fillna(df.max(), downcast='infer')
a b
0 2 3
1 2 3
2 2 3
3 2 3
max
ignores NaNs, so is a good alternative. max
忽略NaNs,因此是一个很好的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.