删除Python系列中元组的na

2024-04-26 10:57:09 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个系列

 a = pd.Series([(1,2), (3,4), (float('NaN'),float('NaN'))])

如何从系列中删除(nan,nan)

问候,


Tags: nanfloatseriespd问候
3条回答

许多好答案,但您也可以尝试以下方法:

pd.Series([(x,y) for (x,y) in a if ~np.isnan(x) and ~np.isnan(y)])

如果你想通过熊猫,首先过滤一个分解的数据帧

df[['x', 'y']] = pd.DataFrame(a.tolist(), index=a.index)  
df.dropna(how='all', inplace=True)

然后返回元组列表

new_tuples = [tuple(x) for x in df.to_numpy()]

假设您只希望保留不包含NaN值的对,则可以执行以下操作:

a = a[~ a.apply(lambda x: np.isnan(x[0] or np.isnan(x[1])))]

相关问题 更多 >