了解json整體格式
這里有一段json格式的文件,存著全球陸地和海洋的每年異常氣溫(這里只選了一部分):global_temperature.json
{
"description": {
"title": "Global Land and Ocean Temperature Anomalies, January-December",
"units": "Degrees Celsius",
"base_period": "1901-2000"
},
"data": {
"1880": "-0.1247",
"1881": "-0.0707",
"1882": "-0.0710",
"1883": "-0.1481",
"1884": "-0.2099",
"1885": "-0.2220",
"1886": "-0.2101",
"1887": "-0.2559"
}
}
通過(guò)python讀取后可以看到其實(shí)json就是dict類型的數(shù)據(jù),description和data字段就是key
![](http://img.jbzj.com/file_images/article/202103/2021313143945566.png?2021213143954)
由于json存在層層嵌套的關(guān)系,示例里面的data其實(shí)也是dict類型,那么年份就是key,溫度就是value
![](http://img.jbzj.com/file_images/article/202103/2021313144014863.png?2021213144022)
轉(zhuǎn)換格式
現(xiàn)在要做的是把json里的年份和溫度數(shù)據(jù)保存到csv文件里
提取key和value
這里我把它們轉(zhuǎn)換分別轉(zhuǎn)換成int和float類型,如果不做處理默認(rèn)是str類型
year_str_lst = json_data['data'].keys()
year_int_lst = [int(year_str) for year_str in year_str_lst]
temperature_str_lst = json_data['data'].values()
temperature_int_lst = [float(temperature_str) for temperature_str in temperature_str_lst]
print(year_int)
print(temperature_int_lst)
![](http://img.jbzj.com/file_images/article/202103/2021313144104046.png?2021213144112)
使用pandas寫(xiě)入csv
import pandas as pd
# 構(gòu)建 dataframe
year_series = pd.Series(year_int_lst,name='year')
temperature_series = pd.Series(temperature_int_lst,name='temperature')
result_dataframe = pd.concat([year_series,temperature_series],axis=1)
result_dataframe.to_csv('./files/global_temperature.csv', index = None)
axis=1
,是橫向拼接,若axis=0
則是豎向拼接
最終效果
![](http://img.jbzj.com/file_images/article/202103/2021313144206377.png?2021213144213)
注意
如果在調(diào)用to_csv()
方法時(shí)不加上index = None
,則會(huì)默認(rèn)在csv文件里加上一列索引,這是我們不希望看見(jiàn)的
![](http://img.jbzj.com/file_images/article/202103/2021313144259374.png?202121314437)
以上就是使用python把json文件轉(zhuǎn)換為csv文件的詳細(xì)內(nèi)容,更多關(guān)于python json文件轉(zhuǎn)換為csv文件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:- Python pandas讀取CSV文件的注意事項(xiàng)(適合新手)
- 使用Python pandas讀取CSV文件應(yīng)該注意什么?
- python 如何把classification_report輸出到csv文件
- Python批量將csv文件轉(zhuǎn)化成xml文件的實(shí)例
- python刪除csv文件的行列
- python 如何讀、寫(xiě)、解析CSV文件
- python讀寫(xiě)數(shù)據(jù)讀寫(xiě)csv文件(pandas用法)
- Python將list元素轉(zhuǎn)存為CSV文件的實(shí)現(xiàn)
- 利用python 讀寫(xiě)csv文件
- Python如何讀寫(xiě)CSV文件
- 如何運(yùn)用python讀寫(xiě)CSV文件