如何识别嵌套 json 文件并将其分解为数据框的列?

2024-05-27

我再次重新组织我的问题,以便更清楚。 我的数据看起来像这样。

{
    "Research": {
        "@xmlns": "http://www.xml.org/2013/2/XML",
        "@language": "eng",
        "@createDateTime": "2022-03-25T10:12:39Z",
        "@researchID": "abcd",
        "Product": {
            "@productID": "abcd",
            "StatusInfo": {
                "@currentStatusIndicator": "Yes",
                "@statusDateTime": "2022-03-25T12:18:41Z",
                "@statusType": "Published"
            },
            "Source": {
                "Organization": {
                    "@primaryIndicator": "Yes",
                    "@type": "SellSideFirm",
                    "OrganizationID": [
                        {
                            "@idType": "L1",
                            "#text": "D827C98E315F"
                        },
                        {
                            "@idType": "TR",
                            "#text": "3202"
                        },
                        {
                            "@idType": "TR",
                            "#text": "SZA"
                        }
                    ],
                    "OrganizationName": {
                        "@nameType": "Legal",
                        "#text": "Citi"
                    },
                    "PersonGroup": {
                        "PersonGroupMember": {
                            "@primaryIndicator": "Yes",
                            "@sequence": "1",
                            "Person": {
                                "@personID": "tr56",
                                "FamilyName": "Wang",
                                "GivenName": "Bond",
                                "DisplayName": "Bond Wang",
                                "Biography": "Bond Wang is a",
                                "BiographyFormatted": "Bond Wang",
                                "PhotoResourceIdRef": "AS44556"
                            }
                        }
                    }
                }
            },
            "Content": {
                "Title": "Premier",
                "Abstract": "None",
                "Synopsis": "Premier’s solid 1H22 result .",
                "Resource": [
                    {
                        "@language": "eng",
                        "@primaryIndicator": "Yes",
                        "@resourceID": "9553",
                        "Length": {
                            "@lengthUnit": "Pages",
                            "#text": "17"
                        },
                        "MIMEType": "text/html",
                        "URL": "https://www.DFKJG.com/rendition/eppublic"
                    },
                    {
                        "@language": "eng",
                        "@primaryIndicator": "No",
                        "@resourceID": "4809",
                        "Length": {
                            "@lengthUnit": "Pages",
                            "#text": "17"
                        },
                        "MIMEType": "ABS/pdf",
                        "Name": "asdf.pdf",
                        "Comments": "fr5.pdf"
                    },
                    {
                        "@language": "eng",
                        "@primaryIndicator": "No",
                        "@resourceID": "6d13a965723e",
                        "Length": {
                            "@lengthUnit": "Pages",
                            "#text": "17"
                        },
                        "MIMEType": "text/html",
                        "URL": "https://www.dfgdfg.com/"
                    },
                    {
                        "@primaryIndicator": "No",
                        "@resourceID": "709c7bdb1c99",
                        "MIMEType": "tyy/image",
                        "URL": "https://ir.ght.com"
                    },
                    {
                        "@primaryIndicator": "No",
                        "@resourceID": "gfjhgj",
                        "MIMEType": "gtty/image",
                        "URL": "https://ir.gtty.com"
                    }
                ]
            },
            "Context": {
                "@external": "Yes",
                "IssuerDetails": {
                    "Issuer": {
                        "@issuerType": "Corporate",
                        "@primaryIndicator": "Yes",
                        "SecurityDetails": {
                            "Security": {
                                "@estimateAction": "Revision",
                                "@primaryIndicator": "Yes",
                                "@targetPriceAction": "Increase",
                                "SecurityID": [
                                    {
                                        "@idType": "RIC",
                                        "@idValue": "PMV.AX",
                                        "@publisherDefinedValue": "RIC"
                                    },
                                    {
                                        "@idType": "Bloomberg",
                                        "@idValue": "PMV@AU"
                                    },
                                    {
                                        "@idType": "SEDOL",
                                        "@idValue": "6699781"
                                    }
                                ],
                                "SecurityName": "Premier Investments Ltd",
                                "AssetClass": {
                                    "@assetClass": "Equity"
                                },
                                "AssetType": {
                                    "@assetType": "Stock"
                                },
                                "SecurityType": {
                                    "@securityType": "Common"
                                },
                                "Rating": {
                                    "@rating": "NeutralSentiment",
                                    "@ratingType": "Rating",
                                    "@aspect": "Investment",
                                    "@ratingDateTime": "2020-07-31T08:24:37Z",
                                    "RatingEntity": {
                                        "@ratingEntity": "PublisherDefined",
                                        "PublisherDefinedValue": "Citi"
                                    }
                                }
                            }
                        },
                        "IssuerID": {
                            "@idType": "PublisherDefined",
                            "@idValue": "PMV.AX",
                            "@publisherDefinedValue": "TICKER"
                        },
                        "IssuerName": {
                            "@nameType": "Legal",
                            "NameValue": "Premier Investments Ltd"
                        }
                    }
                },
                "ProductDetails": {
                    "@periodicalIndicator": "No",
                    "@publicationDateTime": "2022-03-25T12:18:41Z",
                    "ProductCategory": {
                        "@productCategory": "Report"
                    },
                    "ProductFocus": {
                        "@focus": "Issuer",
                        "@primaryIndicator": "Yes"
                    },
                    "EntitlementGroup": {
                        "Entitlement": [
                            {
                                "@includeExcludeIndicator": "Include",
                                "@primaryIndicator": "No",
                                "AudienceTypeEntitlement": {
                                    "@audienceType": "PublisherDefined",
                                    "@entitlementContext": "TR",
                                    "#text": "20012"
                                }
                            },
                            {
                                "@includeExcludeIndicator": "Include",
                                "@primaryIndicator": "No",
                                "AudienceTypeEntitlement": {
                                    "@audienceType": "PublisherDefined",
                                    "@entitlementContext": "TR",
                                    "#text": "2001"
                                }
                            }
                        ]
                    }
                },
                "ProductClassifications": {
                    "Discipline": {
                        "@disciplineType": "Investment",
                        "@researchApproach": "Fundamental"
                    },
                    "Subject": {
                        "@publisherDefinedValue": "TREPS",
                        "@subjectValue": "PublisherDefined"
                    },
                    "Country": {
                        "@code": "AU",
                        "@primaryIndicator": "Yes"
                    },
                    "Region": {
                        "@primaryIndicator": "Yes",
                        "@emergingIndicator": "No",
                        "@regionType": "Australasia"
                    },
                    "AssetClass": {
                        "@assetClass": "Equity"
                    },
                    "AssetType": {
                        "@assetType": "Stock"
                    },
                    "SectorIndustry": [
                        {
                            "@classificationType": "GICS",
                            "@code": "25201040",
                            "@focusLevel": "Yes",
                            "@level": "4",
                            "@primaryIndicator": "Yes",
                            "Name": "Household Appliances"
                        },
                        {
                            "@classificationType": "GICS",
                            "@code": "25504020",
                            "@focusLevel": "Yes",
                            "@level": "4",
                            "@primaryIndicator": "Yes",
                            "Name": "Computer & Electronics Retail"
                        },
                        {
                            "@classificationType": "GICS",
                            "@code": "25504040",
                            "@focusLevel": "Yes",
                            "@level": "4",
                            "@primaryIndicator": "Yes",
                            "Name": "Specialty Stores"
                        },
                        {
                            "@classificationType": "GICS",
                            "@code": "25504030",
                            "@focusLevel": "Yes",
                            "@level": "4",
                            "@primaryIndicator": "Yes",
                            "Name": "Home Improvement Retail"
                        },
                        {
                            "@classificationType": "GICS",
                            "@code": "25201050",
                            "@focusLevel": "Yes",
                            "@level": "4",
                            "@primaryIndicator": "Yes",
                            "Name": "Housewares & Specialties"
                        }
                    ]
                }
            }
        }
    }
}

我想将其所有元素分解为数据框。 具有类似列表结构的列的数量也可以改变。 基本上我们不会知道下一个输入是否会有几列或更多列要分解。

这是我到目前为止所尝试过的,但看起来它没有给我正确的答案。 另外,我已经对列值进行了硬编码,但它应该识别然后爆炸。

import xmltodict as xmltodict
from pprint import pprint
import pandas as pd
import json
from tabulate import tabulate

dict =(xmltodict.parse("""xml data"""))

json_str = json.dumps(dict)
resp = json.loads(json_str)
print(resp)
df = pd.json_normalize(resp)
    
cols=['Research.Product.Source.Organization.OrganizationID','Research.Product.Content.Resource','Research.Product.Context.IssuerDetails.Issuer.SecurityDetails.Security.SecurityID','Research.Product.Context.ProductDetails.EntitlementGroup.Entitlement','Research.Product.Context.ProductClassifications.SectorIndustry']
    
def expplode_columns(df, cols):
    df_e = df.copy()
    for c in cols:
        df_e = df_e.explode(c, ignore_index=True)
    return df_e


df2 = expplode_columns(df, cols)
print(tabulate(df2, headers="keys", tablefmt="psql"))
# df2.to_csv('dataframe.csv', header=True, index=False)

正如评论中所建议的,您可以在纯 Python 中定义一个辅助函数来递归地展平数据的嵌套值。

因此,使用您提供的 json 文件,这是一种方法:

def flatten(data, new_data):
    """Recursive helper function.

    Args:
        data: nested dictionary.
        new_data: empty dictionary.

    Returns:
        Flattened dictionary.

    """
    for key, value in data.items():
        if isinstance(value, dict):
            flatten(value, new_data)
        if isinstance(value, str) or isinstance(value, int) or isinstance(value, list):
            new_data[key] = value
    return new_data

进而:

import json

import pandas as pd

with open("file.json") as f:
    content = json.load(f)

df = pd.DataFrame.from_dict(flatten(content, {}), orient="index").T

从这里,您可以通过分解它们并重复其他值来处理包含具有相同键但不同值的字典列表的列,如下所示:

cols_with_lists = [col for col in df.columns if isinstance(df.loc[0, col], list)]

for col in cols_with_lists:
    temp_df = pd.concat(
        [pd.DataFrame(item, index=[i]) for i, item in enumerate(df.loc[0, col])],
        axis=0,
    )
    df = pd.concat([df.drop(columns=[col]), temp_df], axis=1).fillna(method="ffill")

这样,最后,json 文件就完全扁平化了:

print(df)
# Output
                          @xmlns @language  ... @primaryIndicator                           Name
0  http://www.xml.org/2013/2/XML       eng  ...               Yes           Household Appliances
1  http://www.xml.org/2013/2/XML       eng  ...               Yes  Computer & Electronics Retail
2  http://www.xml.org/2013/2/XML       eng  ...               Yes               Specialty Stores
3  http://www.xml.org/2013/2/XML       eng  ...               Yes        Home Improvement Retail
4  http://www.xml.org/2013/2/XML       eng  ...               Yes       Housewares & Specialties

[5 rows x 73 columns]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何识别嵌套 json 文件并将其分解为数据框的列? 的相关文章

随机推荐

  • 如何在google colaboratory上使用GPU升级tensorflow

    目前google colaboratory使用tensorflow 1 4 1 我想升级到1 5 0版本 每次当我执行时 pip install upgrade tensorflow命令 notebook实例成功将tensorflow版本升
  • Active Record 和 DAO 之间的区别?

    数据访问对象和 Active Record 之间有什么区别 它们看起来非常相似 因为都在应用程序和持久层之间构建了一个层 并使用 SQL 查询抽象出直接数据库访问 数据访问对象 DAO 是指数据层中负责在域中保存单独实体的对象 Active
  • 在cmake中设置PKG_CONFIG_PATH

    我已经在本地构建了 opencv 并将其安装到本地目录 不是系统默认目录 opencv pc存在于该本地文件夹中的 pkgconfig 文件夹下 我怎样才能找到这个opencv pc来自 cmake 因为我想从我的程序链接并包含 openc
  • 使用 OpenNLP 获取句子的解析树。陷入困境。

    OpenNLP 是一个关于自然语言处理的 Apache 项目 NLP 程序的目标之一是解析一个句子 并给出其语法结构的树 例如 天空是蓝色的 这句话 可能会被解析为 S NP VP The sky is blue where S是句子 NP
  • Python Flask 不更新图像[重复]

    这个问题在这里已经有答案了 这里有一些关于图像的 Flask 问题 但没有一个能解决我的问题 我有一个应用程序可以创建图像 保存它 然后显示它 一次 它应该多次执行此操作 每次更改图像时 它应该加载新图像 它不是 它只显示与其显示的文件名关
  • Laravel 解析错误:语法错误,意外的 T_CLASS,期望 T_STRING 或 T_VARIABLE

    安装laravel后出现错误 解析错误 语法错误 意外的 T CLASS 第 50 行 C xampp htdocs laravel public index php 中期望 T STRING 或 T VARIABLE 或 Laravel
  • 在 NServiceBus 3+ 中将超时管理器与分配器一起使用的正确方法是什么?

    3 之前的版本建议在集群上除了分发器之外将超时管理器作为独立进程运行 详细说明如下 http support nservicebus com customer portal articles 965131 deploying nservic
  • Android 多点触控

    因此 我尝试使用 onTouchEvent 检查多个屏幕触摸 但它似乎仍然只读取第一次触摸 有人可以帮忙吗 这是我的代码 public boolean onTouchEvent MotionEvent e int num e getPoin
  • Push 和 Pop 对堆栈意味着什么?

    长话短说 我的讲师很糟糕 他通过投影仪向我们展示前缀堆栈的中缀 他的大影子挡住了一切 所以我错过了重要的东西 他指的是push和pop push 0 pop x 他举了一个例子 但我根本看不出他是如何得到答案的 2 3 2 1 5 4 1
  • python散景中的反转轴

    我正在尝试反转 y 轴并在散景散点图中设置 x 和 y 的范围 我在用 BokehPlot bokeh scatter data df x range min utc max utc y range min val max val 我收到错
  • 无法识别的选择器发送到类

    我已经看到 这是一个常见问题 但我自己找不到任何解决方案 这是代码 class ButtonViewController UIViewController override func viewDidLoad super viewDidLoa
  • JSF - 实施受限页面过滤器

    我正在关注 BalusC 的回答JSF 2 0 如何获取在浏览器地址栏中输入的 URL https stackoverflow com questions 4105263 jsf 2 0 how to get the url that is
  • 删除数组中的重复元素[重复]

    这个问题在这里已经有答案了 可能的重复 在 JavaScript 数组中查找重复值的最简单方法 https stackoverflow com questions 840781 easiest way to find duplicate v
  • R:变换不规则时间字符串

    我有两个不同的时间序列 来自不同的数据帧 具有不同的不规则格式 但问题是相同的 我只想提取小时 分钟 秒和毫秒 时代系列看起来像这样 ts1 08 27 23 445 08 27 24 280 08 27 25 115 I tried st
  • nginx 解析器——dns

    请原谅一个非常初学者的问题 我无法理解 nginx 的 解析器 参数及其工作原理 我已阅读文档 搜索教程和帖子 使用解析器 nginx 和 dns 等关键字 但我仍然不确定如何应用解析器 http nginx org en docs htt
  • 同时运行 x 个网络请求

    我们公司有一个网络服务 我想通过我自己的服务发送 XML 文件 存储在我的驱动器上 HTTPWebRequestC 中的客户端 这已经有效了 Web服务同时支持5个同步请求 一旦服务器上的处理完成 我就会从Web服务获得响应 每个请求的处理
  • localhost/test.php 不返回任何内容

    我正在遵循教程构建一个网络应用程序 我创建了一个简单的test php网络空间中的文件 var www html 问题是当我输入localhost test php在浏览器地址窗口中 它返回一个空页面 我试过localhost php in
  • 如何设置 commons-logging 来使用 logback?

    我们使用 slf4j logback 并且碰巧有一些使用 commons logging 的第三方库 如何设置它以使用 logback 答案是不要使用 commons logging jar 因为 SLF4J 的设计目的与 commons
  • PowerShell 解锁/卸载导入的 CSV

    早晨 我想问题就在标题里 我有一个脚本 它通过导入 CSV 的文件夹结构运行 与每个脚本一起工作 然后在完成后尝试删除它们 遗憾的是 其中很多都锁定在 PowerShell 上 而我删除它们的唯一方法就是关闭 PS 有什么方法可以卸载csv
  • 如何识别嵌套 json 文件并将其分解为数据框的列?

    我再次重新组织我的问题 以便更清楚 我的数据看起来像这样 Research xmlns http www xml org 2013 2 XML language eng createDateTime 2022 03 25T10 12 39Z