Python处理CSV、JSON和XML数据的简便方法来了

Python的卓越灵活性和易用性使其成为最受欢迎的编程语言之一尤其是对于数据处理和机器学习方面来说其强大的数据处理库和算法库使得python成为入门数据科学的首选语言。在日常使json解析用中,CSV,JSON和XML三种数据格式占据主导地位。下面我将针对三种数据格式来分享其快速处理的方法。

CSV数据

CSV是存储数据的最常用方法。在K系统/运维aggle比赛的大部分数据都是以这种方式存储的。我们可以使用内置的Pylinux操作系统基础知识thon csv库来读取和写入CSV。通常,我们会将数据读入列

看看下面的代码。当我们运行csv.reader(linux创建文件)所有CSV数据变得可linux访问时。该csvreader.next()函数从星门老鹰CSV中读取一行;每次调用它,它都会移动到下一行。我们也可以使用for循环遍历csv的每一行for row in数据透视 csvreader 。json确保linux系统每行中的列数相同,否则,在处理列表列表时,最终可能会遇到一些错误。

importcsvfilename="my_data.csv"fields=[]rows=[]#Readingcsvfilewithopen(filename,'r')ascsvfile:#Creatingacsvreaderobjectcsvreader=csv.reader(csvfile)#Extractingfieldnamesinthefirstrowfields=csvreader.next()#Extractingeachdatarowonebyoneforrowincsvreader:rows.append(row)#Printingoutthefirst5rowsforrowinrows[:5]:print(row)

在Py西门龙霆thon中写入CSlinux必学的60个命令V同样容易。在单个列表中设置字段名称,并在列表列表中设置数据。这次我们将创建一个w数据透视表riter()对象并使用它数据恢复将我们linux除文件命令数据写入文件,与读取时的方法基本一样。

importcsv#Fieldnamesfields=['Name','Goals','Assists','Shots']#Rowsofdatainthecsvfilerows=[['Emily','12','18','112'],['Katie','8','24','96'],['John','16','9','101'],['Mike','3','14','82']]filename="soccer.csv"#Writingtocsvfilewithopen(filename,'w+')ascsvfile:#Creatingacsvwriterobjectcsvwriter=csv.writer(csvfile)#Writingthefieldscsvwriter.writerow(fields)#Writingthedatarowscsvwriter.writerows(rows)

我们可以使用Pandas将CSV转换为快速单行的字典列表。将数据格式化为字典列表后,我们将使用该dicttoxml库将其转换数据结构为XML格式。我们还将其保存为JSON文件!

importpandasaspdfromdicttoxmlimportdicttoxmlimportjson#Buildingourdataframedata={'Name':['Emily','Katie','John','Mike'],'Goals':[12,8,16,3],'Assists':[18,24,9,14],'Shots':[112,96,101,82]}df=pd.DataFrame(data,columns=data.keys())#Convertingthedataframetoadictionary#Thensaveittofiledata_dict=df.to_dict(orient="records")withopen('output.json',"w+")asf:json.dump(data_dict,f,indent=4)#ConvertingthedataframetoXML#Thensaveittofilexml_data=dicttoxml(data_dict).decode()withopen("output.xml","w+")asf:f.write(xml_data)

JSON数据

JSON提供了一种简洁且易于阅读的格式,它保持了字典式结构。就像CSV一样,Python有一个数据库内置的JSON模块,使阅读和json是什意思写作变得非常简单!我们以字典的形系统运维面试题及答案式读取CSV时,然后我们将该字典格式数据写入文件。

importjsonimportpandasaspd#Readthedatafromfile#WenowhaveaPythondictionarywithopen('data.json')asf:data_listofdict=json.load(f)#Wecandothesamethingwithpandasdata_df=pd.read_json('data.json',orient='records')#WecanwriteadictionarytoJSONlikeso#Use'indent'and'sort_keys'tomaketheJSON#filelooknicewithopen('new_data.json','w+')asjson_file:json.dump(data_listofdict,json_file,indent=4,sort_keys=True)#Andagainthesamethingwithpandasexport=data_df.to_json('new_data.json',orient='records')

正如我们之前看到的,一旦我们获得了数据,就可以通过pandas或使用内置的Py数据恢复thon CSV模块轻松转换为CSV。转换为XML时,可以使用dictt数据漫游是什意思oxml库。具体代码如下:

importjsonimportpandasaspdimportcsv#Readthedatafromfile#WenowhaveaPythondictionarywithopen('data.json')asf:data_listofdict=json.load(f)#WritingalistofdictstoCSVkeys=data_listofdict[0].keys()withopen('saved_data.csv','wb')asoutput_file:dict_writer=csv.DictWriter(output_file,keys)dict_writer.writeheader()dict_writer.writerows(data_listofdict)

XML数据

XML与CSV和JSON有点不同。CSV和JSON由于其既简单又快速小毛驴简谱,可以方便人们进行阅读,编写和数据科学与大数据技术解释。而XML占用更多的内存空间,传送和储存需要更大的带宽,更多存储空间和更久的运行时间。但是XML也有一些基于JSON和系统/运维CSV的额外功linux是什么操作系统能:您可以使用命名空间来构建和共json是什么意思享结构标准,更好地传承,以及使用XML、Dlinux操作系统基础知识TD等数据表示的行业标准化方法。

要读入XML数据,我们将使用Pythxmlon的内置XML模块和子模ElementTree。我们可以使用xmltodict库将ElementT数据结构ree对象转换为字典。一旦我系统运维包括哪些内容们有了字典,我们就可以转换为CSV,JSON或Pandas Dataframe!具体代码如下:

importxml.etree.ElementTreeasETimportxmltodictimportjsontree=ET.parse('output.xml')xml_data=tree.getroot()xmlstr=ET.tostring(xml_data,encoding='utf8',method='xml')data_dict=dict(xmltodict.parse(xmlstr))print(data_dict)withopen('new_data_2.json','w+')asjson_file:json.dump(data_dict,json_file,indent=4,sort_keys=True)