如果一个值为NaN,则熊猫用NaN替换连续的所有项目

问题描述:

我想摆脱一些使用NaN的记录.效果很好:

I want to get rid of some records with NaNs. This works perfectly:

df.dropna(axis=0, how='any',inplace=True)

但是,它改变了我的数据框的形状,并且索引不再均匀地间隔.因此,我想用np.nan替换这些行中的所有项目.有没有简单的方法可以做到这一点?

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?

我正在考虑在dropna之后重新采样数据帧,但这似乎只能以规定的间隔工作,而我宁愿使用原始索引.另一种方法是使用iterrows遍历数据帧,但这也很麻烦.

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.

下面的命令选择所有值等于Nan的所有行,并将NaN分配给其余行.

The command below selects all rows with any value equal to Nan, and assigns NaNs to the rest of those rows.

df.loc[df.isnull().any(axis=1), :] = np.nan