在下面的代码中,在 A 列下,foo 和 tog 在 B 列中只有缺失值。但是,我不能简单地使用is_na()
过滤所有缺失值,因为有一个条具有缺失值。
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'tog', 'bar', 'bar'],
'B' : [np.nan, 2, np.nan, 4, np.nan, 6, np.nan],
'C' : [2.0, 5., 8., 1., 2., 9., 3.]})
我试过df.groupby('A').filter(df['B'] == 'NaN')
,但返回一个错误:
“系列”对象不可调用。
如何过滤或选择 foo 和 tog?非常感谢!
编辑:我正在清理一个有一些缺失值但分布在很多行中的数据集。因此,我不能只是简单地选择与 A 列对应的命名元素(例如 foo 和 tog)。
换句话说,我需要以下内容
A B C
1 bar 2.0 5.0
3 bar 4.0 1.0
5 bar 6.0 9.0
6 bar NaN 3.0
filter
需要一个函数,你可以传递一个函数来检查是否不是所有的值B
都是NaN
:
df.groupby("A").filter(lambda x: ~x.B.isna().all())
得到
A B C
1 bar 2.0 5.0
3 bar 4.0 1.0
5 bar 6.0 9.0
6 bar NaN 3.0
wherefoo
和tog
被过滤掉,因为它们在 B 列中包含所有 NaN。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句