【问题标题】:pandas: drop subset of dataframe using ~熊猫:使用〜删除数据帧的子集
【发布时间】:2017-05-05 22:20:18
【问题描述】:

我正在尝试根据几个条件过滤数据框。然后,我想从一个单独的、更大的数据框中删除该子集。

df = pd.DataFrame({ 'A' : ['UNKNOWN','UNK','TEST','TEST'],
                    'E' : pd.Categorical(["test","train","test","train"]),
                    'F' : 'foo' })

df2 = pd.DataFrame({ 'A' : ['UNKNOWN','UNK','TEST','TEST','UNKOWN','UNKKK'],
                    'E' : pd.Categorical(["test","train","test","train",'train','train']),
                    'D' : np.array([3] * 6,dtype='int32'),
                    'F' : 'foo' })

rgx = r'UNKNOWN|UNK'
df_drop = df.loc[df['A'].str.contains(rgx, na=False, flags=re.IGNORECASE, regex=True, case=False)]
df2 = df2[~df_drop]

我想要 df2 的以下输出:

         A  D      E    F
2     TEST  3   test  foo
3     TEST  3  train  foo

相反,我收到以下错误:

TypeError: 一元操作数类型错误 ~: 'str'

我不直接过滤 df2 的原因是我想让 df_drop 成为自己单独的数据帧,以保留我删除的记录。

我想我误解了一元应该如何工作。或者我犯了语法错误。但我找不到它,以前的解决方案(例如,removing NaNs from the dataframe)似乎都不适用于这里。

【问题讨论】:

  • 我的部分原始评论仍然有效,您传递的不是布尔掩码,而是 df。如果您使用基于df 的掩码,它仍然会失败,因为掩码长度与df2 的长度不同
  • 这是有道理的。我没有意识到我需要一个布尔掩码,而不是数据框。我现在看到了问题。谢谢!

标签: python pandas


【解决方案1】:

我认为您需要在大数据框中进行过滤:

rgx = r'UNKNOWN|UNK'
mask = df2['A'].str.contains(rgx, na=False, flags=re.IGNORECASE, regex=True, case=False)
print (mask)
0     True
1     True
2    False
3    False
4     True
5     True
Name: A, dtype: bool

print (df2[~mask])
      A  D      E    G
2  TEST  3   test  foo
3  TEST  3  train  foo

【讨论】:

  • 实际上这是查看 OP 所需答案后的语义正确答案。 +1
  • @EdChum - 谢谢。
  • 这太完美了,谢谢!我会尽快接受你的回答!
猜你喜欢
  • 2020-11-15
  • 1970-01-01
  • 2019-10-15
  • 2020-01-13
  • 2016-03-28
  • 2019-10-28
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
相关资源
最近更新 更多