【问题标题】:Filter Pandas Dataframe based on List of substrings根据子字符串列表过滤 Pandas 数据框
【发布时间】:2019-09-04 09:42:13
【问题描述】:

我有一个包含多列字符串的 Pandas 数据框。 我现在想根据允许的子字符串列表检查某个列,然后得到一个带有结果的新子集。

substr = ['A', 'C', 'D']
df = pd.read_excel('output.xlsx')
df = df.dropna()
# now filter all rows where the string in the 2nd column doesn't contain one of the substrings

我发现的唯一方法是创建相应列的列表,然后执行列表理解,但随后我松开了其他列。我可以使用列表理解作为例如的一部分吗? df.str.contains()?

year  type     value   price
2000  ty-A     500     10000
2002  ty-Q     200     84600
2003  ty-R     500     56000
2003  ty-B     500     18000
2006  ty-C     500     12500
2012  ty-A     500     65000
2018  ty-F     500     86000
2019  ty-D     500     51900

预期输出:

year  type     value   price
2000  ty-A     500     10000
2006  ty-C     500     12500
2012  ty-A     500     65000
2019  ty-D     500     51900

【问题讨论】:

  • 请分享一个示例数据框和预期输出
  • 试试df[df.iloc[:, 2].str.contains('|'.join(substr))]
  • @yatu,有没有一种简单的方法可以将表格格式化为问题?
  • 直接粘贴数据即可。粘贴前请务必按 TAB 键

标签: python pandas


【解决方案1】:

你可以使用pandas.Series.isin

>>> df.loc[df['type'].isin(substr)]
   year type  value  price
0  2000    A    500  10000
4  2006    C    500  12500
5  2012    A    500  65000
7  2019    D    500  51900

【讨论】:

  • 抱歉我的错,我真的需要它是一个子字符串,我相应地编辑了我的表。但结合 Chri 的方法,这成功了! df.loc[df['type].str.contains('|'.join(substr))]
猜你喜欢
  • 2022-01-10
  • 1970-01-01
  • 2015-05-08
  • 2017-12-23
  • 2019-03-04
  • 2017-11-03
  • 1970-01-01
  • 2019-04-24
  • 2019-12-27
相关资源
最近更新 更多