我有一个包含多列字符串的 Pandas Dataframe。 我现在想根据允许的子字符串列表检查特定列,然后获取包含结果的新子集。
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
最佳答案
您可以使用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
关于python - 根据子字符串列表过滤 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57785687/