Python 如何从矩阵到数据帧获取值
我将此数组作为json.loads的输出,我需要获取标题和持续时间,但不是视频,只有轨迹列表:Python 如何从矩阵到数据帧获取值,python,dataframe,Python,Dataframe,我将此数组作为json.loads的输出,我需要获取标题和持续时间,但不是视频,只有轨迹列表: `[{'styles': ['Latin', 'Ballad'], 'genres': ['Latin', 'Pop'], 'videos': [{'duration': 285, 'embed': True, 'title': 'Crazy', 'description': '', 'uri': 'https://www.youtube.com/watch?v
`[{'styles': ['Latin', 'Ballad'],
'genres': ['Latin', 'Pop'],
'videos': [{'duration': 285,
'embed': True,
'title': 'Crazy',
'description': '',
'uri': 'https://www.youtube.com/watch?v=p7QYo-9SlP0'},
{'duration': 247,
'embed': True,
'title': 'Crazy2',
'description': '',
'uri': 'https://www.youtube.com/watch?v=8BkYKwHLXiU'},
{'duration': 226,
'embed': True,
'title': 'Crazy4',
'description': '',
'uri': 'https://www.youtube.com/watch?v=rf2jwgSXJVM'},
{'duration': 189,
'embed': True,
'title': 'ricky martin - por arriba por abajo',
'description': 'ricky martin - por arriba por abajo',
'uri': 'https://www.youtube.com/watch?v=WHiCWAtSjT8'}],
'num_for_sale': 272,
**'title': 'Vuelve',**
'most_recent_release': 12264616,
'main_release': 9625486,
'main_release_url': 'https://api.discogs.com/releases/9625486',
'year': 1998,
'uri': 'https://www.discogs.com/Ricky-Martin-Vuelve/master/138279',
'versions_url': 'https://api.discogs.com/masters/138279/versions',
**'tracklist': [{'duration': '3:07',**
'position': '1',
'type_': 'track',
'extraartists': [{'join': '',
'name': 'Peter Wenger',
'anv': 'Peter "Yussi" Wenger',
'tracks': '',
'role': 'Acoustic Guitar [Guitarras Acusticas]',
'resource_url': 'https://api.discogs.com/artists/5484416',
'id': 5484416},strong text`
如何获取数据帧的所有标题和持续时间
import pandas as pd
test = {'styles': ['Latin', 'Ballad'], 'genres': ['Latin', 'Pop'], 'videos': [
{'duration': 285, 'description': 'Crazy (Spanish Video Remastered)', 'embed': True,
'uri': 'https://www.youtube.com/watch?v=p7QYo-9SlP0', 'title': 'Crazy2 (Spanish Video Remastered)'},
{'duration': 247, 'description': 'Crazy3', 'embed': True, 'uri': 'https://www.youtube.com/watch?v=8BkYKwHLXiU',
'title': 'Crazy4'}]}
df = pd.DataFrame(test["videos"])
df= df[["title", "duration"]]
在该代码的末尾,df如下所示:
title duration
0 Crazy2 (Spanish Video Remastered) 285
1 Crazy4 247
{
"Name": Jhon,
"Pet": {
"Animal": dog
}
}
# to
Name Pet_Animal
----------------------------------
Jhon Dog
您可以使用pandas函数jo
json\u normalize
,然后更轻松地处理数据帧
json_将dict标准化为如下数据帧:
title duration
0 Crazy2 (Spanish Video Remastered) 285
1 Crazy4 247
{
"Name": Jhon,
"Pet": {
"Animal": dog
}
}
# to
Name Pet_Animal
----------------------------------
Jhon Dog
发布预期结果谢谢,但我得到了这个错误:-->8 df=pd.DataFrame(matriz[“videos”])9 df=df[“title”,“duration”]]10 df indexer错误:仅整数、切片(
:
)、省略号(…
)、numpy.newaxis(无
)整数或布尔数组是有效的指示符。您复制并通过了这个示例还是使用了您的数据?我使用了部分数据,因为它很长。我是从json.loadsy获得的。我们的数据是另一种格式。它似乎是一个列表中的一本词典,但如果没有它的全部,我就说不出来了。如果您可以像示例中那样访问字典部分,则此代码将正常工作谢谢,我已经尝试了您的解决方案,现在我遇到了以下问题:KeyError:“尝试使用errors='ignore'运行,因为键'duration'并不总是存在”。。。在某些歌曲中,“持续时间”似乎是空的,您知道如何避免此错误吗?