json 将python链接 Dataframe 转换为字典

jxct1oxe  于 2023-07-01  发布在  Python
关注(0)|答案(2)|浏览(152)

我有一个dataframe,看起来像这样:
| 到| To |
| --| ------------ |
| 分析| Analytics |
| 集群| Cluster |
| 聚集性集群| AgglomerativeCluster |
| 社区结构| CommunityStructure |
| 图表| Graph |
| 社区结构| CommunityStructure |
| 链接距离| LinkDistance |
| 数据| Data |
...
我需要它看起来完全就像下面的链接中的echart要产生的这种格式:https://github.com/andfanilo/streamlit-echarts-demo/blob/master/data/flare.json
转换为普通字典不起作用。它需要被格式化为具有多级父子关系的分层字典。

{
  "name": "flare",
  "children": [
    {
      "name": "analytics",
      "children": [
        {
          "name": "cluster",
          "children": [
            {
              "name": "AgglomerativeCluster",
              "value": 3938
            }, ...

这是为了让我可以像中那样制作可扩展的树图:https://echarts.streamlit.app/

to94eoyn

to94eoyn1#

这可以用Pandas来实现。使用import pandas as pd导入pandas
并将dataframe转换为dictionary
dictionary = dataframe.to_dict()

hfwmuf9z

hfwmuf9z2#

管理它。需要添加一个级别列和一个值
如果我根据层(0,1,2)添加一个级别列
df.columns=[“parent_id”,“child_id”,“level”]
st.write(hs_input_output_hs_df)def recurse(parent_id,level):# create the base result result = {“name”:parent_id} #,“level”:int(level)

# get all of the children of this parent, one level below this one
children = df[(df.parent_id == parent_id) & (df["level"] == level + 1)]

# if there are no such children, then return without a _children key
if children.empty:
    result["value"]=1
    return result

# otherwise, recurse on each child_id
result["children"] = [recurse(child_id, level + 1) for child_id in sorted(children.child_id.unique())]

return result

tree = [recurse(parent_id,0)for parent_id in sorted(df[df[“level”] == 1].parent_id.unique())]
st.write(tree[0])

相关问题