我试图根据另一个列表中的文本修剪列表中的文本。直接在两个列表上调用时,以下函数可以正常工作
def remove_texts(texts, texts2):
to_remove = []
for i in texts2:
if i in texts:
to_remove.append(i)
texts = [j for j in texts if j not in to_remove]
return texts
但是,以下什么都不做,我没有错误
df_other.texts = df_other.texts.map(lambda x: remove_texts(x, df_other.to_remove_split))
以下也不是。再次没有返回错误
for i, row in df_other.iterrows():
row['texts'] = remove_texts(row['texts'], row['to_remove_split'])
任何想法都赞赏。
你真的想找到texts
和texts2
之间的集合差异。假设它们包含:
texts = [ 'AAA', 'BBB', 'DDD', 'EEE', 'FFF', 'GGG', 'HHH' ]
texts2 = [ 'CCC', 'EEE' ]
然后,最短的解决方案是仅计算设置差异,而不使用Pandas:
set(texts).difference(texts2)
得到:
{'AAA', 'BBB', 'DDD', 'FFF', 'GGG', 'HHH'}
或者如果您只想要一个列表(未设置),请写:
sorted(set(texts).difference(texts2))
如果由于某种原因你想使用Pandas,那么从两个DataFrame的creting开始:
df = pd.DataFrame(texts, columns=['texts'])
df2 = pd.DataFrame(texts2, columns=['texts'])
然后,您可以将集合差异计算为:
df.query('texts not in @df2.texts')
要么
df.texts[~df.texts.isin(df2.texts)]