[英]Pandas replace all items in a row with NaN if one value is NaN
I want to get rid of some records with NaNs.我想用 NaN 去掉一些记录。 This works perfectly:
这完美地工作:
df.dropna(axis=0, how='any',inplace=True)
However, it changes the shape of my dataframe, and the index is no longer uniformly spaced.但是,它改变了我的数据框的形状,并且索引不再均匀间隔。 Therefore, I'd like to replace all items in these rows with
np.nan
.因此,我想用
np.nan
替换这些行中的所有项目。 Is there a simple way to do this?有没有一种简单的方法可以做到这一点?
I was thinking about resampling the dataframe after dropna
, but that only seems to work with a prescribed interval, whereas I would rather use the original index.我正在考虑在
dropna
之后重新采样数据帧,但这似乎只适用于规定的间隔,而我宁愿使用原始索引。 Another approach would be to loop over the dataframe with iterrows
, but that also feels cumbersome.另一种方法是使用
iterrows
循环遍历数据帧,但这也感觉很麻烦。
下面的命令选择具有等于 Nan 的任何值的所有行,并将 NaN 分配给这些行的其余部分。
df.loc[df.isnull().any(axis=1), :] = np.nan
使用此代码也无需切片df = df.replace('nan',np.nan)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.