- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我目前正在对这个字典文件进行扁平化处理,遇到了一些障碍。我正在尝试使用 json_normalize
来展平这些数据。如果我对单个实例进行测试,它可以工作,但如果我想展平所有数据,它将返回一个错误,指出 key error '0'
我不确定如何解决这个问题。
数据示例-
data = {1:{
'Name': "Thrilling Tales of Dragon Slayers",
'IDs':{
"StoreID": ['123445452543'],
"BookID": ['543533254353'],
"SalesID": ['543267765345']},
2:{
'Name': "boring Tales of Dragon Slayers",
'IDs':{
"StoreID": ['111111', '1121111'],
"BookID": ['543533254353', '4324232342'],
"SalesID": ['543267765345', '4353543']}}
我的代码
d_flat = pd.io.json.json_normalize(data, meta=['Title', 'StoreID', 'BookID', 'SalesID'])
最佳答案
您的数据结构不便。我想关注:
'IDs'
中的列表放入字典列表中,这样会方便得多。您的数据
:
{1: {'Name': 'Thrilling Tales of Dragon Slayers',
'IDs': {'StoreID': ['123445452543'],
'BookID': ['543533254353'],
'SalesID': ['543267765345']}},
2: {'Name': 'boring Tales of Dragon Slayers',
'IDs': {'StoreID': ['111111', '1121111'],
'BookID': ['543533254353', '4324232342'],
'SalesID': ['543267765345', '4353543']}}}
我希望它看起来像什么:
[{'Name': 'Thrilling Tales of Dragon Slayers',
'IDs': [{'StoreID': '123445452543',
'BookID': '543533254353',
'SalesID': '543267765345'}]},
{'Name': 'boring Tales of Dragon Slayers',
'IDs': [{'StoreID': '111111',
'BookID': '543533254353',
'SalesID': '543267765345'},
{'StoreID': '1121111',
'BookID': '4324232342',
'SalesID': '4353543'}]}]
简单的循环,不要乱来。这让我们得到了我上面展示的内容
new = []
for v in data.values():
temp = {**v} # This is intended to keep all the other data that might be there
ids = temp.pop('IDs') # I have to focus on this to create the records
temp['IDs'] = [dict(zip(ids, x)) for x in zip(*ids.values())]
new.append(temp)
new = [{**v, 'IDs': [dict(zip(v['IDs'], x)) for x in zip(*v['IDs'].values())]} for v in data.values()]
pd.json_normalize
创建DataFrame
在调用 json_normalize
时,我们需要指定记录的路径,即在 'IDs'
键中找到的 id 字典列表。 json_normalize
将为该列表中的每个项目在数据框中创建一行。这将通过 record_path
参数完成,我们传递一个 tuple
来描述路径(如果它在更深的结构中)或一个字符串(如果键在顶层,对我们来说就是顶层)。
record_path = 'IDs'
然后我们要告诉 json_normalize
哪些键是记录的元数据。如果像我们一样有多个记录,那么元数据将为每条记录重复。
meta = 'Name'
所以最终的解决方案是这样的:
pd.json_normalize(new, record_path='IDs', meta='Name')
StoreID BookID SalesID Name
0 123445452543 543533254353 543267765345 Thrilling Tales of Dragon Slayers
1 111111 543533254353 543267765345 boring Tales of Dragon Slayers
2 1121111 4324232342 4353543 boring Tales of Dragon Slayers
如果我们无论如何都要重组,不妨进行重组,这样我们就可以将其传递给数据框构造函数。
pd.DataFrame([
{'Name': r['Name'], **dict(zip(r['IDs'], x))}
for r in data.values() for x in zip(*r['IDs'].values())
])
Name StoreID BookID SalesID
0 Thrilling Tales of Dragon Slayers 123445452543 543533254353 543267765345
1 boring Tales of Dragon Slayers 111111 543533254353 543267765345
2 boring Tales of Dragon Slayers 1121111 4324232342 4353543
当我们在做的时候。关于每个 id 类型是否具有相同数量的 id,数据是不明确的。假设他们没有。
data = {1:{
'Name': "Thrilling Tales of Dragon Slayers",
'IDs':{
"StoreID": ['123445452543'],
"BookID": ['543533254353'],
"SalesID": ['543267765345']}},
2:{
'Name': "boring Tales of Dragon Slayers",
'IDs':{
"StoreID": ['111111', '1121111'],
"BookID": ['543533254353', '4324232342'],
"SalesID": ['543267765345', '4353543', 'extra id']}}}
然后我们可以使用 itertools
中的 zip_longest
from itertools import zip_longest
pd.DataFrame([
{'Name': r['Name'], **dict(zip(r['IDs'], x))}
for r in data.values() for x in zip_longest(*r['IDs'].values())
])
Name StoreID BookID SalesID
0 Thrilling Tales of Dragon Slayers 123445452543 543533254353 543267765345
1 boring Tales of Dragon Slayers 111111 543533254353 543267765345
2 boring Tales of Dragon Slayers 1121111 4324232342 4353543
3 boring Tales of Dragon Slayers None None extra id
关于python - 使用 pd.json_normalize 展平字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66464851/
您好,我有一个使用 JSON.Stringify 输出到此的对象 {"0":["test1","ttttt","","","","","","","",""],"1":["test2","ghjgjh
我有以下数据框,它是执行 groupby + 聚合总和的结果: df.groupby(['id', 'category']).agg([pd.Series.sum])
我有一个 3D 三角形带(见插图)。三角形不在一个平面内。 我想展平三角形带,使所有三角形都位于第一个三角形的平面内。 计划是围绕与第一个三角形的连接边旋转第二个三角形,使其与第一个三角形在同一平面内
简单地说,我正在寻找可在 iOS 上使用的与 NSBezierPath 的 -bezierPathByFlatteningPath 等效的方法。这对我来说是直接处理 CGPath 的函数还是 UIBe
假设我有以下 JToken: @"{ ""data"": [ { ""company"": { ""ID"": ""12
如果我在多个分支中处理单个功能,我会使用 git pull branch1 branch2 branch3 将所有更改 pull 入我的主分支。但是,每个分支的所有提交日志也会被复制。如何将提交日志扁
这个问题在这里已经有了答案: How do I make a flat list out of a list of lists? (33 个答案) 关闭6年前。 假设我们有一个返回列表(或有限迭代器)
给定如下模式: root |-- first_name: string |-- last_name: string |-- degrees: array | |-- element: struc
我有一个包含多个列的表,其中一些列是相同长度的数组。我想解除它们的嵌套,以获得包含来自不同行中的数组的值的结果。 所以有这样一张 table : 我想去: 这是其中一个数组列的工作方式: WITH d
我最近买了一台 RICOH THETA S,用于在 360 vr 中录制足球比赛。 我想使用 ffmpeg 将我用我的相机录制的鱼眼电影展平,这可能吗? enter image description
这是我的 question 的后续.是否可以将表格展平为如下所示,而不是数据透视表: data = {'year': ['2016', '2016', '2015', '2014', '2013'],
我目前正在将我的 jruby/java2d 图形绘制/布局应用程序移植到 macruby/cocoa。因此我需要获取开放的 NSBezierPath 与封闭的 NSBezierPath 的交点。 在
是否有一种简单的方法来展平一组 try 以给出尝试值的成功或失败? 例如: def map(l:List[Int]) = l map { case 4 => Failure(new Excepti
我有一个包含数百万行的“服务”表。每行对应于工作人员在给定日期和时间间隔内提供的服务(每行都有一个唯一的 ID)。在某些情况下,工作人员可能会在重叠的时间范围内提供服务。我需要编写一个查询来合并重叠的
我在使用Elastic Search(ES)检索JSON对象时遇到问题。现在,当我尝试使用下面的请求正文从ES查询一些数据时, "_source": [ "data.id", "dat
我有一个订单流(来源是订单列表)。每个订单都有一个 Customer 和一个 OrderLine 列表。 我想要实现的是拥有一个以客户为键的 map ,以及属于该客户的所有订单行,在一个简单的列表中作
给定一个如下所示的复杂对象: case class Complex ( id: Long, name: String, nested: Seq[Complex] ) 实际上,这可能会变成这
我很好奇你如何将数组 Promise 映射的结果展平。我有一个函数 Promise.maps 一组值,它们本身就是 promise (需要解析)并返回一个数组。所以,我得到类似的结果: [ [1, 2
我是 CouchDB 的新手,我只是想评估它在常见任务中的实用性。其中一项任务是生成报告。我的问题是:如果我有这样的文档结构: { "_id": "29763f342ab34fd7b579fd4
假设我们有这样的 map : %{"a": %{"b": 2, "c":5}, "d": 1} 有没有类似this function的东西(js回答同一问题)内置elixr? 最终结果应该是: %{"
我是一名优秀的程序员,十分优秀!