熊猫适用,地图和iterrows表现奇怪

问题描述 投票:-1回答:1

我试图根据另一个列表中的文本修剪列表中的文本。直接在两个列表上调用时,以下函数可以正常工作

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'])

任何想法都赞赏。

python-3.x pandas
1个回答
1
投票

你真的想找到textstexts2之间的集合差异。假设它们包含:

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)]
© www.soinside.com 2019 - 2024. All rights reserved.