使用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' }}
通過(guò)python讀取后可以看到其實(shí)json就是dict類(lèi)型的數(shù)據(jù),description和data字段就是key
由于json存在層層嵌套的關(guān)系,示例里面的data其實(shí)也是dict類(lèi)型,那么年份就是key,溫度就是value
現(xiàn)在要做的是把json里的年份和溫度數(shù)據(jù)保存到csv文件里
提取key和value這里我把它們轉(zhuǎn)換分別轉(zhuǎn)換成int和float類(lèi)型,如果不做處理默認(rèn)是str類(lèi)型
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()方法時(shí)不加上index = None,則會(huì)默認(rèn)在csv文件里加上一列索引,這是我們不希望看見(jiàn)的
以上就是使用python把json文件轉(zhuǎn)換為csv文件的詳細(xì)內(nèi)容,更多關(guān)于python json文件轉(zhuǎn)換為csv文件的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. CSS hack用法案例詳解2. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說(shuō)明3. 解決AJAX返回狀態(tài)200沒(méi)有調(diào)用success的問(wèn)題4. PHP設(shè)計(jì)模式中工廠模式深入詳解5. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向6. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法7. Ajax實(shí)現(xiàn)表格中信息不刷新頁(yè)面進(jìn)行更新數(shù)據(jù)8. JSP數(shù)據(jù)交互實(shí)現(xiàn)過(guò)程解析9. ThinkPHP5實(shí)現(xiàn)JWT Token認(rèn)證的過(guò)程(親測(cè)可用)10. .NET中l(wèi)ambda表達(dá)式合并問(wèn)題及解決方法
