使用python把json文件轉(zhuǎn)換為csv文件
這里有一段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' }}
通過python讀取后可以看到其實(shí)json就是dict類型的數(shù)據(jù),description和data字段就是key
由于json存在層層嵌套的關(guān)系,示例里面的data其實(shí)也是dict類型,那么年份就是key,溫度就是value
現(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)
import pandas as pd# 構(gòu)建 dataframeyear_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則是豎向拼接最終效果
注意如果在調(diào)用to_csv()方法時不加上index = None,則會默認(rèn)在csv文件里加上一列索引,這是我們不希望看見的
以上就是使用python把json文件轉(zhuǎn)換為csv文件的詳細(xì)內(nèi)容,更多關(guān)于python json文件轉(zhuǎn)換為csv文件的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. python中scrapy處理項(xiàng)目數(shù)據(jù)的實(shí)例分析2. Python中讀取文件名中的數(shù)字的實(shí)例詳解3. 在idea中為注釋標(biāo)記作者日期操作4. 通過Ajax方式綁定select選項(xiàng)數(shù)據(jù)的實(shí)例5. JSP頁面的靜態(tài)包含和動態(tài)包含使用方法6. ASP.Net Core對USB攝像頭進(jìn)行截圖7. ASP.NET MVC使用Boostrap實(shí)現(xiàn)產(chǎn)品展示、查詢、排序、分頁8. .net如何優(yōu)雅的使用EFCore實(shí)例詳解9. 使用AJAX(包含正則表達(dá)式)驗(yàn)證用戶登錄的步驟10. ajax動態(tài)加載json數(shù)據(jù)并詳細(xì)解析
