当前位置: 首页 > 科技观察

CSV是一种常用的数据存储方式

时间:2023-03-18 13:00:26 科技观察

Python出色的灵活性和易用性使其成为最流行的编程语言之一,尤其是在数据处理和机器学习方面,其强大的数据处理库和算法库使python成为最流行的语言数据科学入门的选择。在日常使用中,CSV、JSON和XML三种数据格式占主导地位。下面我将分享三种数据格式的快速处理方法。CSV数据CSV是最常用的数据存储方法。Kaggle比赛中的大部分数据都是这样存储的。我们可以使用内置的Pythoncsv库来读写CSV。通常,我们会将数据读入列表的列表中。看看下面的代码。当我们运行csv.reader()时,所有CSV数据都可以访问。csvreader.next()函数从CSV中读取一行;每次调用时,它都会移动到下一行。我们还可以在csvreader中使用for循环遍历csv的每一行。确保每行中的列数相同,否则,在处理列表列表时可能会出现一些错误。importcsvfilename="my_data.csv"fields=[]rows=[]#Readingcsvfilewithopen(filename,'r')ascsvfile:#Creatingacsvreaderobjectcsvcsvreader=csv.reader(csvfile)#Extractingfieldnamesinthefirstrowfields=csvreader.next()#Extractingeachdatarowonebyoneforrowincsvreader(:rows.row)#Printingoutthefirst5rowsforrowinrows[:5]:print(row)用Python写入CSV文件同样简单。在单个列表中设置字段名称,在列表列表中设置数据。这次我们将创建一个writer()对象,并使用它以与我们读取它的方式大致相同的方式将我们的数据写入文件。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:#Creatingacsvwriteobjectcsvcsvwriter=csv.writer(csvfile)#Writingthefieldscsvwriter.writerow(fields)#Writingthedatarowscsvwriter.writerrows(rows)我们可以使用Pandas将CSV转换为字典快速单行列表。将数据格式化为字典列表后,我们将使用dicttoxml库将其转换为XML格式。我们还将其保存为JSON文件!importpandasaspfromdicttoxmlimportdicttoxmlimportjson#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模块,让读写变得非常简单!当我们将CSV作为字典读取时,我们会将字典格式的数据写入文件。importjsonimportpandasasspd#Readthedatafromfile#WenowhaveaPythondictionarywithopen('data.json')asf:data_listofdict=json.load(f)#Wecandothesamethingwithpandasdata_df=pd.read_json('data.json',orient='records')#WecanwriteadictionarytoJSONlikeso#Use'indent'排序键'使JSON#filelooknicewithopen('new_data.json','w+')asjson_file:json.dump(data_listofdict,json_file,indent=4,sort_keys=True)#Andagainthesamethingwithpandaseexport=data_df.to_json('new_data.json',orient='records')正如我们之前看到的,一旦我们有了数据,就可以通过pandas或使用内置的PythonCSV模块轻松地将其转换为CSV。转换为XML时,可以使用dicttoxml库。具体代码如下:importjsonimportpandasasspdimportcsv#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的额外特性:您可以使用命名空间来构建和共享结构标准、更好的继承以及使用XML、DTD等的行业标准化数据表示方法。要读入XML数据,我们我们将使用Python的内置XML模块和子模块ElementTree。我们可以使用xmltodict库将ElementTree对象转换为字典。一旦我们有了字典,我们就可以转换为CSV、JSON或PandasDataframe!具体代码如下: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)