首页 > 解决方案 > 如何遍历列并在 Pandas 中只返回一个变量

问题描述

我一直在尝试将 DataFrame 中的列与列表进行比较并找出差异。唯一的问题是,当我这样做时,它会给出差异列表,但会为每一列添加一个条目。

例如:

def Type():
    list1=['Dog','Cat','Monkey','Horse', 'Giraffe']
    list2=Zoo['Animal'].values.tolist()     
    new_list = (set(list1).difference(set(list2)))
    return new_list    

Zoo['Animal Type'] = Zoo.apply(lambda row: Type(), axis = 1)
Zoo['Animal Type']

返回

34     {Cat, Monkey, Dog, Horse}
38     {Cat, Monkey, Dog, Horse}
39     {Cat, Monkey, Dog, Horse}
41     {Cat, Monkey, Dog, Horse}
46     {Cat, Monkey, Dog, Horse}
47     {Cat, Monkey, Dog, Horse}
48     {Cat, Monkey, Dog, Horse}
49     {Cat, Monkey, Dog, Horse}

而不是最后的差异列表,例如:

0 Cat
1 Monkey
2 Dog
3 Horse

我只希望每个差异在输出中说明一次。任何帮助都是极好的。

标签: pythonpandasnumpy

解决方案


推荐阅读