[英]Convert Json Dict object into DataFrame in Python
我從 python 中的 Web 服務中獲得了一些 Json dict 對象格式的嵌套輸出。 輸出是嵌套的 Json dict 對象。 現在,當我嘗試在 python 中將其轉換為 DataFrame 時,父鍵不被視為列。 我在一個鍵下有五個元素。 我希望總共 6 列將出現在數據框中。
import pandas as pd
data = {'2019-04-04 05:59:00':
{'1. open': '1353.5500',
'2. high': '1354.8000',
'3. low': '1353.0500',
'4. close': '1353.0500',
'5. volume': '25924'},
'2019-04-04 05:58:00': {'1. open': '1354.2500',
'2. high': '1354.2500',
'3. low': '1353.4000',
'4. close': '1353.4500',
'5. volume': '38418'}
}
df1=pd.DataFrame(data)
print(df1)
"""
Output --
2019-04-04 05:59:00 2019-04-04 05:58:00
1. open 1353.5500 1354.2500
2. high 1354.8000 1354.2500
3. low 1353.0500 1353.4000
4. close 1353.0500 1353.4500
5. volume 25924 38418
"""
df2=df1.transpose()
print(df2)
"""
Output --
1. open 2. high 3. low 4. close 5. volume
2019-04-04 05:59:00 1353.5500 1354.8000 1353.0500 1353.0500 25924
2019-04-04 05:58:00 1354.2500 1354.2500 1353.4000 1353.4500 38418
"""
這里第一個日期字段被視為索引,所以我的第一列從 (1.open) 開始,但我需要的是第一列應該是日期。
對此的幫助將不勝感激。
結果應該是這樣的:
"""
Index Date 1. open 2. high 3. low 4. close 5. volume
0 2019-04-04 05:59:00 1353.5500 1354.8000 1353.0500 1353.0500 25924
1 2019-04-04 05:58:00 1354.2500 1354.2500 1353.4000 1353.4500 38418
"""
df2.rename_axis(index='Date').reset_index()
給你:
Date 1. open 2. high 3. low 4. close 5. volume
0 2019-04-04 05:58:00 1354.2500 1354.2500 1353.4000 1353.4500 38418
1 2019-04-04 05:59:00 1353.5500 1354.8000 1353.0500 1353.0500 25924
另請注意,有一種使用data
構建df2
的更簡單方法:
df2 = pd.DataFrame.from_dict(data, orient='index')
將兩部分放在一起:
pd.DataFrame.from_dict(data, orient='index').rename_axis(index='Date').reset_index()
要命名索引,您可以將.rename_axis(index='Index')
到末尾:
Date 1. open 2. high 3. low 4. close 5. volume
Index
0 2019-04-04 05:58:00 1354.2500 1354.2500 1353.4000 1353.4500 38418
1 2019-04-04 05:59:00 1353.5500 1354.8000 1353.0500 1353.0500 25924
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.