Python 列列表中的Dataframe筛选器空值
所以,我有一个类似这样的Python 列列表中的Dataframe筛选器空值,python,python-2.7,Python,Python 2.7,所以,我有一个类似这样的df ID,A,B,C,D,E,F,G 1,123,30,3G,1,123,30,3G 2,456,40,4G,NaN,NaN,NaN,4G 3,789,35,5G,NaN,NaN,NaN,NaN 我还有一个列表,它包含df头列表的一个子集 header_list = ["D","E","F","G"] 现在我想从df中获取那些记录,这些记录包含标题列表中所有列名的空值。 预期产出: ID,A,B,C,D,E,F,G 3,789,35,5G,NaN,NaN,NaN,N
df
ID,A,B,C,D,E,F,G
1,123,30,3G,1,123,30,3G
2,456,40,4G,NaN,NaN,NaN,4G
3,789,35,5G,NaN,NaN,NaN,NaN
我还有一个列表,它包含df头列表的一个子集
header_list = ["D","E","F","G"]
现在我想从df
中获取那些记录,这些记录包含标题列表中所有列名的空值。
预期产出:
ID,A,B,C,D,E,F,G
3,789,35,5G,NaN,NaN,NaN,NaN
我试过了,
new\u df=df[df[header\u list].isnull()]
但这会引发error,ValueError:该条件需要布尔数组,而不是float64
我知道我可以做这样的事
new_df = df[(df['D'].isnull()) & (df['E'].isnull()) & (df['F'].isnull()) & (df['G'].isnull())]
但我不想这样硬编码。有更好的方法吗?您可以使用以下方法进行过滤:
df[df[header_list].isnull().all(axis=1)]
因此,如果该行的所有列都是True
,则返回该行的True
,否则返回False
。对于给定的样本输入,我们得到:
>>> df[header_list]
D E F G
1 1.0 123.0 30.0 3G
2 NaN NaN NaN 4G
3 NaN NaN NaN NaN
>>> df[header_list].isnull()
D E F G
1 False False False False
2 True True True False
3 True True True True
>>> df[header_list].isnull().all(axis=1)
1 False
2 False
3 True
dtype: bool
>>> df[header_list]
D E F G
1 1.0 123.0 30.0 3G
2 NaN NaN NaN 4G
3 NaN NaN NaN NaN
>>> df[header_list].isnull()
D E F G
1 False False False False
2 True True True False
3 True True True True
>>> df[header_list].isnull().all(axis=1)
1 False
2 False
3 True
dtype: bool