![](/img/trans.png)
[英]how to create a Dataframe (multi-index) with sub-columns from a nested Dictionary?
[英]How to create a multi index dataframe from a nested dictionary?
我有一個嵌套字典,它的第一級鍵是 [0, 1, 2...] 並且每個鍵的對應值是以下形式:
{
"geometry": {
"type": "Point",
"coordinates": [75.4516454, 27.2520587]
},
"type": "Feature",
"properties": {
"state": "Rajasthan",
"code": "BDHL",
"name": "Badhal",
"zone": "NWR",
"address": "Kishangarh Renwal, Rajasthan"
}
}
我想制作以下形式的熊貓數據框:
Geometry Type Properties
Type Coordinates State Code Name Zone Address
0 Point [..., ...] Features Rajasthan BDHL ... ... ...
1
2
我無法理解網上關於多索引/嵌套數據框/透視的示例。 他們似乎都沒有將第一級鍵作為所需數據幀中的主索引。
我如何從我擁有的數據中獲取,以使其成為這個格式化的數據幀?
我建議將列創建為"geometry_type"
、 "geometry_coord"
等。以便將這些列與您命名為"type"
的列區分開來。 換句話說,使用您的第一個鍵作為前綴,使用子鍵作為名稱,從而創建一個新名稱。 之后,只需像這樣解析和填充您的數據框:
import json
j = json.loads("your_json.json")
df = pd.DataFrame(columns=["geometry_type", "geometry_coord", ... ])
for k, v in j.items():
if k == "geometry":
df = df.append({
"geometry_type": v.get("type"),
"geometry_coord": v.get("coordinates")
}, ignore_index=True)
...
您的輸出可能如下所示:
geometry_type geometry_coord ...
0 [75.4516454, 27.2520587] NaN ...
PS:如果你真的想要你的初始選項,你可以在這里檢查: 給一個列多個索引/標題
我想你有一個嵌套字典的列表。
使用json_normalize
讀取JSON數據,並使用當前列索引分成2部分str.partition
:
import pandas as pd
import json
data = json.load(open('data.json'))
df = pd.json_normalize(data)
df.columns = df.columns.str.partition('.', expand=True).droplevel(level=1)
輸出:
>>> df.columns
MultiIndex([( 'type', ''),
( 'geometry', 'type'),
( 'geometry', 'coordinates'),
('properties', 'state'),
('properties', 'code'),
('properties', 'name'),
('properties', 'zone'),
('properties', 'address')],
)
>>> df
type geometry properties
type coordinates state code name zone address
0 Feature Point [75.4516454, 27.2520587] Rajasthan BDHL Badhal NWR Kishangarh Renwal, Rajasthan
您可以使用pd.json_normalize()
將嵌套字典規范化為數據幀df
。
然后,使用參數expand=True
df.columns
的列名拆分為多索引,使用Index.str.split
將df.columns
為參數expand=True
,如下所示:
第 1 步:將嵌套的 dict 規范化為數據幀
j = {
"geometry": {
"type": "Point",
"coordinates": [75.4516454, 27.2520587]
},
"type": "Feature",
"properties": {
"state": "Rajasthan",
"code": "BDHL",
"name": "Badhal",
"zone": "NWR",
"address": "Kishangarh Renwal, Rajasthan"
}
}
df = pd.json_normalize(j)
第 1 步結果:
print(df)
type geometry.type geometry.coordinates properties.state properties.code properties.name properties.zone properties.address
0 Feature Point [75.4516454, 27.2520587] Rajasthan BDHL Badhal NWR Kishangarh Renwal, Rajasthan
步驟 2:創建多索引列標簽
df.columns = df.columns.str.split('.', expand=True)
第 2 步(最終)結果:
print(df)
type geometry properties
NaN type coordinates state code name zone address
0 Feature Point [75.4516454, 27.2520587] Rajasthan BDHL Badhal NWR Kishangarh Renwal, Rajasthan
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.