如果一个值是 NaN,Pandas 用 NaN 替换一行中的所有项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36985737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas replace all items in a row with NaN if one value is NaN
提问by Peter9192
I want to get rid of some records with NaNs. This works perfectly:
我想用 NaN 去掉一些记录。这完美地工作:
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
. Is there a simple way to do this?
但是,它改变了我的数据框的形状,索引不再均匀间隔。因此,我想将这些行中的所有项目替换为np.nan
. 有没有一种简单的方法可以做到这一点?
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. Another approach would be to loop over the dataframe with iterrows
, but that also feels cumbersome.
我正在考虑在 之后重新采样数据帧dropna
,但这似乎只能在规定的间隔内工作,而我宁愿使用原始索引。另一种方法是使用 循环遍历数据框iterrows
,但这也感觉很麻烦。
采纳答案by Alexander
The command below selects all rows with any value equal to Nan, and assigns NaNs to the rest of those rows.
下面的命令选择具有等于 Nan 的任何值的所有行,并将 NaN 分配给这些行的其余部分。
df.loc[df.isnull().any(axis=1), :] = np.nan