【发布时间】: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 键