Skip to main content
 首页 » 编程设计

python之将不同结构的json文件转换为python 3.6中的数据帧

2024年10月01日7over140

请告诉我如何将以下格式的 json 文件转换为数据框。

json文件数据:

{ 
"series_id":"STEO", 
"f":"A", 
"data":[["2018",5.8400705041],["2017",3.5671511014],["2016",2.3014617486],["2015",2.4989178082],["2014",2.2089452055]] 
} 

我试过下面的代码:

sourcePath = r'D:\source\STEO.txt' 
data = pd.read_json(sourcePath, lines=True) 

我需要上面 json 的以下输出:

series_id   f   date    value 
STEO        A   2018    5.840070504 
STEO        A   2017    3.567151101 
STEO        A   2016    2.301461749 
STEO        A   2015    2.498917808 
STEO        A   2014    2.208945206 

请您参考如下方法:

一种方式可能如下:

读取Json:

import pandas as pd 
df = pd.read_json('input.txt') 
print(df) 

输出:

                   data  f series_id 
0  [2018, 5.8400705041]  A      STEO 
1  [2017, 3.5671511014]  A      STEO 
2  [2016, 2.3014617486]  A      STEO 
3  [2015, 2.4989178082]  A      STEO 
4  [2014, 2.2089452055]  A      STEO 

拆分

# splitting into multiple columns for list 
# https://stackoverflow.com/a/35491399/5916727 
df[['Date','Value']] = pd.DataFrame([item for item in df.data]) 
# removing initial data column now 
del df['data'] 
print(df) 

输出:

   f series_id  Date     Value 
0  A      STEO  2018  5.840071 
1  A      STEO  2017  3.567151 
2  A      STEO  2016  2.301462 
3  A      STEO  2015  2.498918 
4  A      STEO  2014  2.208945