python - 从 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 方式。
解决方案
您收到错误是因为,请考虑以下两种情况
- 没有任何
- [无,1、2、3]
现在,当您进行比较时,None
您会得到以下结果
- 真(因为 None 是 None)
- [对,错,错,错]
现在对于第一种情况,很明显它是 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]
推荐阅读
- sql - SQL - 添加一列计数超过另一列
- angular - 错误类型错误:this.remember.forEach 不是 AuthFormComponent.ngAfterContentInit 的函数
- spring - 其他端点无法访问 Cookie
- javascript - 新文档的firestore更新计数器
- playwright - 我如何在 Playwright-java 中上传文件?
- docker - docker nginx 端口 80 权限在 ubuntu 16 上被拒绝
- json - 使用 jq group_by 和 count 将 JSON 输出从 curl 排序到排序和计数列表
- facebook - 我可以通过图形 api 关注 Facebook 页面吗?
- python - Python从没有重复的列表中创建排列
- javascript - 单击嵌入的 YouTube 播放列表时,如何隐藏文本 div?