gpt4 book ai didi

python Pandas : Filter Dataframe by applying regular expression

转载 作者:行者123 更新时间:2023-11-28 21:20:55 27 4
gpt4 key购买 nike

我可以像这样根据列表的元素过滤数据框;

import pandas as pd
W1 = ['Animal','Ball','Cat','Derry','Element','Lapse','Animate this']
W2 = ['Krota','Catch','Yankee','Global','Zeb','Rat','Try']
df = pd.DataFrame({'W1':W1,'W2':W2})

l1 = ['Animal','Zeb','Q']
print df[df['W1'].isin(l1) | df['W2'].isin(l1)]

W1 W2
0 Animal Krota
4 Element Zeb

但是有没有办法通过应用正则表达式进行过滤? 例如;

 l1 = ['An','Cat']

Intended result;
W1 W2
0 Animal Krota
1 Ball Catch
2 Cat Yankee
6 Animate this Try

最佳答案

试试这个:

df[df['W1'].str.contains("|".join(l1)) | df['W2'].str.contains("|".join(l1))]


W1 W2
0 Animal Krota
1 Ball Catch
2 Cat Yankee
6 Animate this Try

关于 python Pandas : Filter Dataframe by applying regular expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22093006/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com