我有一个名为stocks.json 的JSON 档案,如下所示(注意源档案中缺少方括号):
{"MSFT": {"exchange": "Nasdaq", "price": 275.79}, "FB": {"exchange": "Nasdaq", "price": 320.22}, "TSLA": {"exchange": "Nasdaq", "price": 990.83}, "GE": {"exchange": "Nasdaq", "price": 83.20}}
我想将此资料转换为如下所示的 Pandas 资料框:
symbol exchange price
MSFT Nasdaq 275.79
FB Nasdaq 320.22
TSLA Nasdaq 990.83
GE NYSE 83.20
我的尝试是:
import pandas as pd
stock_data = pd.read_json('stocks.json', lines=True)
stock_data_normalized = pd.json_normalize(stock_data)
不幸的是,我在呼叫时得到以下信息stock_data_normalized
:
0
1
2
3
任何帮助将不胜感激。谢谢!
uj5u.com热心网友回复:
您可以只使用pd.DataFrame()
建构式,然后转置和重置索引:
df = pd.DataFrame(d).T.reset_index().rename({'index': 'symbol'}, axis=1)
输出:
>>> df
symbol exchange price
0 MSFT Nasdaq 275.79
1 FB Nasdaq 320.22
2 TSLA Nasdaq 990.83
3 GE Nasdaq 83.2
0 评论