python - 在 Python 中将 JSON 文件平铺到 Pandas Dataframe 中

标签 python json pandas dataframe json-flattener

我有这种格式的 json:

{
    "fields": {
        "tcidte": {
            "mode": "required",
            "type": "date",
            "format": "%Y%m%d"
        },
        "tcmcid": {
            "mode": "required",
            "type": "string"
        },
        "tcacbr": {
            "mode": "required",
            "type": "string"
        }
    }
}

我希望它采用数据帧格式,其中三个字段名称中的每一个都是单独的行。如果一行有一列(例如“格式”),而其他列为空,则应假定为 NULL。

我尝试使用我在此处找到的 flatten_json 函数,但未按预期工作,但仍包含在此处:

def flatten_json(nested_json, exclude=['']):
    """Flatten json object with nested keys into a single level.
        Args:
            nested_json: A nested json object.
            exclude: Keys to exclude from output.
        Returns:
            The flattened json object if successful, None otherwise.
    """
    out = {}

    def flatten(x, name='', exclude=exclude):
        if type(x) is dict:
            for a in x:
                if a not in exclude: flatten(x[a], name + a + '_')
        elif type(x) is list:
            i = 0
            for a in x:
                flatten(a, name + str(i) + '_')
                i += 1
        else:
            out[name[:-1]] = x

    flatten(nested_json)
    return out

flatten_json_file = pd.DataFrame(flatten_json(nested_json))
pprint.pprint(flatten_json_file)

额外的复杂性 JSON:

{
    "fields": {
        "action": {
            "type": {
                "field_type": "string"
            },
            "mode": "required"
        },
        "upi": {
            "type": {
                "field_type": "string"
            },
            "regex": "^[0-9]{9}$",
            "mode": "required"
        },
        "firstname": {
            "type": {
                "field_type": "string"
            },
            "mode": "required"
        }
    }
}

最佳答案

data = {
    "fields": {
        "tcidte": {
            "mode": "required",
            "type": "date",
            "format": "%Y%m%d"
        },
        "tcmcid": {
            "mode": "required",
            "type": "string"
        },
        "tcacbr": {
            "mode": "required",
            "type": "string"
        }
    }
}

这个

df = pd.DataFrame(data["fields"].values())

结果

       mode    type  format
0  required    date  %Y%m%d
1  required  string     NaN
2  required  string     NaN

这是你的目标吗?

如果您想要data["fields"]的键作为索引:

df = pd.DataFrame(data["fields"]).T

df = pd.DataFrame.from_dict(data["fields"], orient="index")

两者都会导致

            mode    type  format
tcidte  required    date  %Y%m%d
tcmcid  required  string     NaN
tcacbr  required  string     NaN

data = {
    "fields": {
        "action": {
            "type": {
                "field_type": "string"
            },
            "mode": "required"
        },
        "upi": {
            "type": {
                "field_type": "string"
            },
            "regex": "^[0-9]{9}$",
            "mode": "required"
        },
        "firstname": {
            "type": {
                "field_type": "string"
            },
            "mode": "required"
        }
    }
}

你可以这样做

data = {key: {**d, **d["type"]} for key, d in data["fields"].items()}
df = pd.DataFrame.from_dict(data, orient="index").drop(columns="type")

df = pd.DataFrame.from_dict(data["fields"], orient="index")
df = pd.concat(
    [df, pd.DataFrame(df.type.to_list(), index=df.index)], axis=1
).drop(columns="type")

结果如下(列位置可能不同)

               mode field_type       regex
action     required     string         NaN
upi        required     string  ^[0-9]{9}$
firstname  required     string         NaN

关于python - 在 Python 中将 JSON 文件平铺到 Pandas Dataframe 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70259322/

相关文章:

python - 如何在python中引用类变量

python - Django select_related 不返回外表数据

c# - Json.NET 版本 4 中的 CamelCase 重大更改

python - Pandas DataFrame 列连接

python - 如何对行进行分组以便在使用 pandas 创建的组上使用 value_counts ?

python - 如何在 SliTaz 或 Haiku 上使用 AES 或 DES 算法

python - Pycharm - 在远程解释器中配置 PYTHONPATH

python - 如何在 Google App Engine 上使用 Python 发送 JSON 格式的 cookie 数据?

json - 交换键和数组值,将旧键转换为新数组值,使用 jq

Python Pandas lambda 函数更改列的所有值?