如何基于列表索引条件删除Pandas DataFrame中的行
问题:删除DataFrame中列表前两个元素均为NaN的行
现有如下DataFrame:
import pandas as pd import numpy as np df = pd.DataFrame({"A": [[np.nan, np.nan, 0], [np.nan, 1, 1], [1, np.nan, 2], [np.nan, np.nan, 3]]}) print(df)
输出结果:
A 0 [nan, nan, 0] 1 [nan, 1, 1] 2 [1, nan, 2] 3 [nan, nan, 3]
需求:删除列表前两个元素均为NaN的行,得到如下结果:
A 1 [nan, 1, 1] 2 [1, nan, 2]
尝试的代码(无法正常运行):
df.drop(df[np.isnan(df.A[0]) & np.isnan(df.A[1])].index)
解决方案
你之前的代码逻辑错误:df.A[0]是取A列的第一行数据,而非每行列表的第一个元素,因此无法实现批量判断。以下是两种无需拆分列表为多列的可行方法:
方法1:使用apply结合lambda函数
filtered_df = df[~df['A'].apply(lambda x: np.isnan(x[0]) and np.isnan(x[1]))] print(filtered_df)
方法2:使用列表推导式生成布尔掩码
mask = [not (np.isnan(x[0]) and np.isnan(x[1])) for x in df['A']] filtered_df = df[mask] print(filtered_df)
两种方法都会输出目标结果:
A 1 [nan, 1, 1] 2 [1, nan, 2]
内容的提问来源于stack exchange,提问作者jamesB
相关产品推荐
相关产品推荐

