python - Python:当字典具有错误值时,“NoneType”对象没有属性“键”
问题描述
我正在尝试使用 json_normalize 将嵌套字典转换为 DataFrame。我能够成功地做到这一点,直到我忽略了一些结果的错误。
长话短说 - 我在 python 中使用 Youtube-dl 来抓取一个 youtube 频道,然后我将结果数据转换为 DF。每当 youtube 视频出现错误时,我都会在 youtube-dl 中忽略它并继续下一个。我认为这是创建一个错误的字典条目,导致我的 json_normalize 失败。
这是我获取频道数据的方式
!pip install --upgrade youtube-dl
import youtube_dl
import pandas as pd
import json
church = input('enter the name of the church')
method = 'y'
channelID = input('enter channel url ending in videos')
with youtube_dl.YoutubeDL({'ignoreerrors' : True}) as ydl:
result = ydl.extract_info(
str(channelID),
download=False,
)
result
然后我使用以下代码段转换为 DF
import json
data = pd.json_normalize(
result,
record_path =['entries'],
errors='ignore'
)
但是,由于某些视频由于 youtube 错误而被跳过,所以每次运行 json_normalize 函数时都会出现以下错误
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-101-e3aa31b503f3> in <module>()
19 result,
20 record_path =['entries'],
---> 21 errors='ignore'
22 )
4 frames
pandas/_libs/lib.pyx in pandas._libs.lib.fast_unique_multiple_list_gen()
/usr/local/lib/python3.7/dist-packages/pandas/core/internals/construction.py in <genexpr>(.0)
635 """
636 if columns is None:
--> 637 gen = (list(x.keys()) for x in data)
638 sort = not any(isinstance(d, dict) for d in data)
639 columns = lib.fast_unique_multiple_list_gen(gen, sort=sort)
AttributeError: 'NoneType' object has no attribute 'keys'
有人可以建议我需要做些什么来解释那些糟糕的字典条目吗?
解决方案
您能否不使用以下内容预先筛选您的数据列表:
data = [x for x in data if x is not None]
推荐阅读
- python-3.x - 如何根据 json 文件中的内容在不同的屏幕上显示不同的问题和答案?
- laravel - 如何在 laravel 中使用 Bootstrap-vue 将分页包含到表格中
- javascript - 流中的未细化铸造,在对象(以及所述对象的数组)中具有嵌套类型
- python - Python TensorFlow DQN 后续步骤
- c++ - c++中的腐蚀函数没有给出任何输出
- tensorflow - 深度学习,如何表示零到多个项目?
- php - php忽略来自ssh的ssl证书
- xml - ROS Remap 主题不起作用 - 多个机器人
- python-3.x - 没有这样的选项:尝试从 Git 安装 discord.py 时在 Heroku 上使用 -U
- vue.js - 有没有办法使用firebase实时数据库(vuejs)进行分页?