簡體   English   中英

如何從 json 元素快速創建二維 numpy 數組?

[英]How to quickly create a two dimension numpy array from json elements?

我嵌套了類似於以下內容的 json 數據:

[{'game':'001', 'animals': [{'name':'Dog', 'colour':'Red'}, {'name':'Horse', 'age':'6'},{'name':'Ostrich', 'location':'Africa'}]},{'game':'002', 'animals': [{'name':'Cat', 'colour':'Green'}, {'name':'Bison', 'location':'North America'},{'name':'Parrot', 'location':'Southeast Asia'}]}]

我的目標是為與變量“animal_list”中的項目對應的每個動物(包含在“名稱”中)創建一個指標數組條目:

animal_list = ['Bison', 'Cat', 'Dog', 'Elephants', 'Horse', 'Ostrich', 'Parrot']

所以所需的結構將類似於(表示為 csv ......但這只是說明性的,因為我正在尋找 numpy 位置數組):

Game, Bison, Cat, Dog, Elephants, Horse, Ostrich, Parrot
"001",0,0,1,0,1,1,0
"002",1,1,0,0,0,0,1

我傳統上使用“雙循環”來形成這個 - 首先是“游戲”項目; 然后是一個掃描“名稱”項目的內部循環。 問題是,我有一個很長的 json 列表,它需要幾個小時才能運行。

謝謝你的幫助!

下面是表格的 pandas 版本。

您始終可以將ndarray稱為df.values

import numpy as np
import pandas as pd

data = [{'game': '001', 'animals': [{'name':'Dog', 'colour':'Red'}, {'name':'Horse', 'age':'6'},{'name':'Ostrich', 'location':'Africa'}]},
        {'game': '002', 'animals': [{'name':'Cat', 'colour':'Green'}, {'name':'Bison', 'location':'North America'},{'name':'Parrot', 'location':'Southeast Asia'}]}]
animal_list = ['Bison', 'Cat', 'Dog', 'Elephants', 'Horse', 'Ostrich', 'Parrot']

games = [d['game'] for d in data]

df = pd.DataFrame(np.zeros((len(games), len(animal_list))),
                  index=games, columns=animal_list)

for ix, g in enumerate(games):
    a = [a['name'] for a in data[ix]['animals']]
    df.loc[g, a] = 1

print(df)


       Bison  Cat  Dog  Elephants  Horse  Ostrich  Parrot
001    0.0  0.0  1.0        0.0    1.0      1.0     0.0
002    1.0  1.0  0.0        0.0    0.0      0.0     1.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM