在Pandas数据框中,我希望将Col1与关键字列表进行匹配,如下所示:
关键字必须不同,位于同一列中且位于3个连续行中(关键字1!=关键字2!=关键字3,例如位于x,x + 1和x + 2行上)
我只希望将关键字作为结果返回(在下面的示例中,“ def”被删除了)
list_keywords = ['abc', 'ghi', 'jkl mnop','blabla']
Index Col1
1 abc def
2 ghi
3 jkl mnop
4 qrstu
5 vw
>>>
1 abc
2 ghi
3 jkl mnop
答案 0 :(得分:0)
您可以使用df.iterrows()
做类似的事情。
for _, row in df.iterrows():
if row['col1'] in list_keywords:
row['col1'] = row['col1']
else:
val = row['col1'].split()
row['col1'] = ' '.join(str(i) for i in val if i in list_keywords)
df
col1
0 abc
1 ghi
2 jkl mnop
3
4
答案 1 :(得分:0)
基于@HTRS的答案,这似乎是我问题的部分答案。 此代码段针对关键字列表过滤“品牌”列,并过滤出与关键字不同的字符串部分。
import pandas as pd
list_filtered = []
list_keywords = ['abc', 'ghi', 'jkl mnop','blabla']
for _, row in df.iterrows():
if row['Brand'] in list_keywords:
row['Brand'] = row['Brand']
list_filtered.append(row['Brand'])
else:
val = row['Brand'].split()
row['Brand'] = ' '.join(str(i) for i in val if i in list_keywords)
list_filtered.append(row['Brand'])
df['Filtered'] = list_filtered
print(df)