如何在panda中将多个json连接为dict?

e3bfsja2  于 2022-12-01  发布在  其他
关注(0)|答案(2)|浏览(123)

我有两个json文件,我想连接成一个。有什么方法来结合这些json?

json1 = {
  "105912": {
    "name": "Avatar - Tocasia, Dig Site Mentor",
    "cardset": "VAN",
    "rarity": "Rare",
    "foil": 0,
    "price": 0.05
  },
  "105911": {
    "name": "Avatar - Yotian Frontliner",
    "cardset": "VAN",
    "rarity": "Rare",
    "foil": 0,
    "price": 0.05
  }
}

json2 = {
  "105912": {
    "name": "Avatar - Tocasia, Dig Site Mentor",
    "cardset": "VAN",
    "rarity": "Rare",
    "foil": 0,
    "price": 0.0007
  },
  "105911": {
    "name": "Avatar - Yotian Frontliner",
    "cardset": "VAN",
    "rarity": "Rare",
    "foil": 0,
    "price": 0.0007
  }
}

import pandas as pd
from glob import glob

arquivos = sorted(glob('price-history\*.json'))

todos_dados = pd.concat((pd.read_json(cont, lines=True, orient='records') for cont in 
arquivos))

print(todos_dados)

返回的错误是ValueError: Expected object or value
预期输出将是能够过滤数据的 Dataframe 。

anauzrmj

anauzrmj1#

试试看:

import pandas as pd

json1 = {
    "105912": {
        "name": "Avatar - Tocasia, Dig Site Mentor",
        "cardset": "VAN",
        "rarity": "Rare",
        "foil": 0,
        "price": 0.05,
    },
    "105911": {
        "name": "Avatar - Yotian Frontliner",
        "cardset": "VAN",
        "rarity": "Rare",
        "foil": 0,
        "price": 0.05,
    },
}

json2 = {
    "105912": {
        "name": "Avatar - Tocasia, Dig Site Mentor",
        "cardset": "VAN",
        "rarity": "Rare",
        "foil": 0,
        "price": 0.0007,
    },
    "105911": {
        "name": "Avatar - Yotian Frontliner",
        "cardset": "VAN",
        "rarity": "Rare",
        "foil": 0,
        "price": 0.0007,
    },
}

jsons = json1, json2

df = pd.DataFrame(
    [v for j in jsons for v in j.values()], index=[k for j in jsons for k in j]
)
print(df)

印刷品:

name cardset rarity  foil   price
105912  Avatar - Tocasia, Dig Site Mentor     VAN   Rare     0  0.0500
105911         Avatar - Yotian Frontliner     VAN   Rare     0  0.0500
105912  Avatar - Tocasia, Dig Site Mentor     VAN   Rare     0  0.0007
105911         Avatar - Yotian Frontliner     VAN   Rare     0  0.0007
5f0d552i

5f0d552i2#

import pandas as pd

json1 = {
  "105912": {
    "name": "Avatar - Tocasia, Dig Site Mentor",
    "cardset": "VAN",
    "rarity": "Rare",
    "foil": 0,
    "price": 0.05
  },
  "105911": {
    "name": "Avatar - Yotian Frontliner",
    "cardset": "VAN",
    "rarity": "Rare",
    "foil": 0,
    "price": 0.05
  }
}

json2 = {
  "105912": {
    "name": "Avatar - Tocasia, Dig Site Mentor",
    "cardset": "VAN",
    "rarity": "Rare",
    "foil": 0,
    "price": 0.0007
  },
  "105911": {
    "name": "Avatar - Yotian Frontliner",
    "cardset": "VAN",
    "rarity": "Rare",
    "foil": 0,
    "price": 0.0007
  }
}

list_jsons = [json1,json2]
todos_dados = pd.concat(([pd.DataFrame.from_dict(json_obj,orient='index') for json_obj in list_jsons]))

todos_dados

相关问题