我认为这个确切的问题还没有得到回答,所以就这样做了。
我有一个Pandas数据框架,我想选择A列或B列中包含字符串的所有行。
假设dataframe如下所示:
d = {'id':["1", "2", "3", "4"],
'title': ["Horses are good", "Cats are bad", "Frogs are nice", "Turkeys are the best"],
'description':["Horse epitome", "Cats bad but horses good", "Frog fancier", "Turkey tome, not about horses"],
'tags':["horse, cat, frog, turkey", "horse, cat, frog, turkey", "horse, cat, frog, turkey", "horse, cat, frog, turkey"],
'date':["2019-01-01", "2019-10-01", "2018-08-14", "2016-11-29"]}
dataframe = pandas.DataFrame(d)这意味着:
id title description tag date
1 "Horses are good" "Horse epitome" "horse, cat" 2019-01-01
2 "Cats are bad" "Cats bad" "horse, cat" 2019-10-01
3 "Frogs are nice" "Frog fancier, horses good" "horse, frog" 2018-08-14
4 "Turkey are best" "Turkey tome" "turkey, horse" 2016-11-29假设我想要创建一个新的数据create,其中包含horse字符串的行(忽略大写)在列title或列description中,而不是在列tag (或任何其他列)中。
结果应该是(第2行和第4行被删除):
id title description tag date
1 "Horses are good" "Horse epitome" "horse, cat" 2019-01-01
3 "Frogs are nice" "Frog fancier, horses good" "horse, frog" 2018-08-14我看到了一个专栏的几个答案,比如:
dataframe[dataframe['title'].str.contains('horse')]但我不确定(1)如何向该语句中添加多个列,以及(2)如何使用类似于string.lower()的内容来修改它,以删除字符串匹配的列值中的大写。
提前感谢!
发布于 2019-10-25 13:49:02
您可以在对应于每一列的系列中使用“逻辑或”操作符|:
filtered = df[df['title'].str.contains('horse', case=False) |
df['description'].str.contains('horse', case=False)]如果有许多列,则可以使用减缩操作:
import functools
import operator
colnames = ['title', 'description']
mask = functools.reduce(operator.or_, (df[col].str.contains('horse', case=False) for col in colnames))
filtered = df[mask] https://stackoverflow.com/questions/58559581
复制相似问题