gpt4 book ai didi

python - 从基于另一个列表的列表列中删除列表值

转载 作者:行者123 更新时间:2023-12-02 07:16:38 25 4
gpt4 key购买 nike

假设我有一个 DataFrame,其中一列是一列列表。我将如何删除那些列表中的所有元素,这些元素也在另一个指定列表中找到?原始列应保持完整,同时将新列添加到 DataFrame 中,并从每个行值中删除指定的列表元素。

df = pd.DataFrame({ 'Values': [['a', 'b', 'c'], ['a', 'b', 'c', 'd'], ['a', 'b'], ['c']]})

removal_list = ['a', 'b']

生成

Index   Values
0 ['a', 'b', 'c']
1 ['a', 'b', 'c', 'd']
2 ['a', 'b']
3 ['c']

想要的输出是……

Index   Values               Cleaned_Values
0 ['a', 'b', 'c'] ['c']
1 ['a', 'b', 'c', 'd'] ['c', 'd']
2 ['a', 'b'] []
3 ['c'] ['c']

最佳答案

理解

df.assign(Cleaned_Values=[[x for x in y if x not in removal_list] for y in df.Values])

Values Cleaned_Values
0 [a, b, c] [c]
1 [a, b, c, d] [c, d]
2 [a, b] []
3 [c] [c]

设置

df.assign(Cleaned_Values=df.Values.map(set).sub({*removal_list}).map(list))

Values Cleaned_Values
0 [a, b, c] [c]
1 [a, b, c, d] [c, d]
2 [a, b] []
3 [c] [c]

同样的事情,但要快一点,因为我们一起处理所有的转换。

df.assign(Cleaned_Values=df.Values.map(lambda x: [*{*x} - {*removal_list}]))

关于python - 从基于另一个列表的列表列中删除列表值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61468401/

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