【问题标题】:Selecting rows from Pandas Dataframe with same values in one column that have only missing in another从 Pandas Dataframe 中选择一列中具有相同值但在另一列中仅缺失的行
【发布时间】:2021-04-23 14:26:31
【问题描述】:

在下面的代码中,在 A 列下,foo 和 tog 在 B 列中只有缺失值。但是,我不能简单地使用 is_na() 过滤所有缺失值,因为有一个 bar 有缺失值.

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

【问题讨论】:

  • df[df['A'].isin(['foo', 'tog'])]?
  • 这个问题的预期输出是什么?
  • df[df.B.isna()]?? df[df.B.notna()]??

标签: python pandas missing-data


【解决方案1】:

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

其中footog 被过滤掉,因为它们在B 列中包含所有NaN。

【讨论】:

  • 非常感谢,就是这样!但是,我目前的问题是,这并没有真正转化为我的原始数据集>。~x.B.isna().all() 中的 B 时,它返回“一元操作数类型错误〜:'方法'"
  • @Erthrall 你忘记all 末尾的()了吗?
猜你喜欢
  • 2019-05-31
  • 2017-02-14
  • 2022-01-01
  • 2012-05-25
  • 2015-07-17
  • 1970-01-01
  • 2017-12-24
  • 1970-01-01
  • 2017-12-31
相关资源
最近更新 更多