簡體   English   中英

從python中的json提取列表鍵和每一行的值列表

[英]Extract list keys and list of values for each row from json in python

我正在嘗試從json提取鍵的列表和每個條目的所有值的列表。 考慮以下json:

[{'height': 1.2 , 'width':2.5, 'weight':5 },{'height': 1.7 , 'width':4.5, 'weight':2 },{'height': 3.2 , 'width':4.5, 'weight':7 }]

我希望輸出為:

['height','width','weight']

[[1.2,2.5,5],[1.7,4.5,2],[3.2,4.5,7]]

基本上我需要將其加載到pandas Dataframe。 我相信直接加載行和列會更容易。 我無法將json直接加載到DataFrame,也找不到如上所述的提取行和列的有效方法。

假設您已將json加載到變量(如文本)中,則只需執行以下操作:

In [13]: import json, pandas

In [14]: text = json.dumps([{'height': 1.2 , 'width':2.5, 'weight':5 },{'height': 1.7 , 'width':4.5, 'weight':2 },{'height': 3.2 , 'width':4.5, 'weight':7 }])
    ...: 

In [15]: df = pandas.read_json(text)

In [16]: df
Out[16]: 
   height  weight  width
0     1.2       5    2.5
1     1.7       2    4.5
2     3.2       7    4.5

In [17]: df.columns.values
Out[17]: array([u'height', u'weight', u'width'], dtype=object)

In [18]: df.as_matrix()
Out[18]: 
array([[ 1.2,  5. ,  2.5],
       [ 1.7,  2. ,  4.5],
       [ 3.2,  7. ,  4.5]])

正如評論所提到的,您可以將字典直接傳遞給DataFrame構造函數。 但是,如果由於某些原因您確實想要描述的格式,則可以使用:

>>> x = [{'height': 1.2 , 'width':2.5, 'weight':5 },{'height': 1.7 , 'width':4.5, 'weight':2 },{'height': 3.2 , 'width':4.5, 'weight':7 }]

>>> list(map(lambda l:list(l.keys()), x))
[['height', 'width', 'weight'], ['height', 'width', 'weight'], ['height', 'width', 'weight']]


>>> list(map(lambda l:list(l.values()), x))
[[1.2, 2.5, 5], [1.7, 4.5, 2], [3.2, 4.5, 7]]

暫無
暫無

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

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