首页 > 解决方案 > 从 pd.Series 列表中过滤掉 None / 或在 pd.Series 列表中找出 Nonetype 对象

问题描述

我在删除列表中的 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)))

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

标签: pythonpandaslistnonetype

解决方案


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

  1. 没有任何
  2. [无,1、2、3]

现在,当您进行比较时,None您会得到以下结果

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

现在对于第一种情况,很明显它是 None 但是对于第二种情况,python 会感到困惑,无论您是想将其视为 Nonejust 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]

推荐阅读