从pd.Series的列表中过滤掉None/或在pd.Series的列表中找出None类型的对象

Filtering out None from the list of pd.Series / or finding out Nonetype objects in the list of pd.Series

我在删除列表中的 Nonetype 对象时遇到问题。 ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

这是在以下情况发生的:

import pandas as pd
#List of pd.Series with some of the objects are None
results = [pd.Series([1,2,3,4]), None, pd.Series([2,3,4,5])]
print(list(filter(None, results)))

如何过滤掉列表中的非类型对象? 我知道我可以使用循环,但它不会是 pythonic 方式。

你收到错误是因为,请考虑以下 2 种情况

  1. None
  2. [None, 1, 2, 3]

现在当你比较什么是 None 你会得到以下内容

  1. 正确(因为 None 是 None)
  2. [对,错,错,错]

第一种情况很明显None 但是对于第二种情况,python 很困惑你是想将它视为 None just because there is one None 还是你认为 there is not all None 没问题,这就是错误的根源。 any 表示如果至少有一个 None 则将其视为 None 并且 all 表示应该有所有 None

#List of pd.Series with some of the objects are None
results = [pd.Series([1,2,3,4]), None, pd.Series([2,3,4,5])]

def is_none(x):
  try:
    return return any(x == None)
  except:
    return x is None

print(list(filter(is_none, results)))

# [0    1
# 1    2
# 2    3
# 3    4
# dtype: int64, None, 0    2
# 1    3
# 2    4
# 3    5
# dtype: int64]

filter函数为None时,python将对每一项(bool(item))进行真值检验。那么,什么时候 pd.Series 应该是 True?是当它所有的值都是True的时候吗?任何值?也许就在系列不为空的时候。关键是,一个系列有很多可能是真实的。这就是错误消息告诉您的内容。

由于您的目标是过滤掉 None,并且无论如何列表理解都是比 filter 更好的选择,您可以只测试 None.

print([value for value in results if value is not None])

好吧,如果问题出在列表中的 'None' 个元素,您总是可以创建另一个没有它们的列表并覆盖第一个列表:

results=[i for i in results if i is not None ].

这也避免了任何“显式”循环,尽管很明显,在内部,有一个循环正在进行。

在这种情况下,您可以使用内置 python 方法 isinstance 来检查您的元素是否是 pandas.Series:

的实例
import pandas as pd
#List of pd.Series with some of the objects are None
results = [pd.Series([1,2,3,4]), None, pd.Series([2,3,4,5])]
[i for i in results if isinstance(i, pd.Series)]

list(filter(lambda x: isinstance(x, pd.Series), results))

输出:

[0    1
 1    2
 2    3
 3    4
 dtype: int64,
 0    2
 1    3
 2    4
 3    5
 dtype: int64]