自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

CSV是存儲(chǔ)數(shù)據(jù)的常用方法

開(kāi)發(fā) 后端
在日常使用中,CSV,JSON和XML三種數(shù)據(jù)格式占據(jù)主導(dǎo)地位。下面我將針對(duì)三種數(shù)據(jù)格式來(lái)分享其快速處理的方法。

[[441350]]

 Python的卓越靈活性和易用性使其成為最受歡迎的編程語(yǔ)言之一,尤其是對(duì)于數(shù)據(jù)處理和機(jī)器學(xué)習(xí)方面來(lái)說(shuō),其強(qiáng)大的數(shù)據(jù)處理庫(kù)和算法庫(kù)使得python成為入門(mén)數(shù)據(jù)科學(xué)的首選語(yǔ)言。在日常使用中,CSV,JSON和XML三種數(shù)據(jù)格式占據(jù)主導(dǎo)地位。下面我將針對(duì)三種數(shù)據(jù)格式來(lái)分享其快速處理的方法。

CSV數(shù)據(jù)

CSV是存儲(chǔ)數(shù)據(jù)的最常用方法。在Kaggle比賽的大部分?jǐn)?shù)據(jù)都是以這種方式存儲(chǔ)的。我們可以使用內(nèi)置的Python csv庫(kù)來(lái)讀取和寫(xiě)入CSV。通常,我們會(huì)將數(shù)據(jù)讀入列表列表。

看看下面的代碼。當(dāng)我們運(yùn)行csv.reader()所有CSV數(shù)據(jù)變得可訪問(wèn)時(shí)。該csvreader.next()函數(shù)從CSV中讀取一行; 每次調(diào)用它,它都會(huì)移動(dòng)到下一行。我們也可以使用for循環(huán)遍歷csv的每一行for row in csvreader 。確保每行中的列數(shù)相同,否則,在處理列表列表時(shí),最終可能會(huì)遇到一些錯(cuò)誤。 

  1. import csv   
  2. filename = "my_data.csv"  
  3. fields = []   
  4. rows = []     
  5. # Reading csv file   
  6. with open(filename, 'r') as csvfile:   
  7.     # Creating a csv reader object   
  8.     csvcsvreader = csv.reader(csvfile)   
  9.     # Extracting field names in the first row   
  10.     fields = csvreader.next()   
  11.     # Extracting each data row one by one   
  12.     for row in csvreader:   
  13.         rows.append(row)    
  14. # Printing out the first 5 rows   
  15. for row in rows[:5]:   
  16.     print(row) 

在Python中寫(xiě)入CSV同樣容易。在單個(gè)列表中設(shè)置字段名稱,并在列表列表中設(shè)置數(shù)據(jù)。這次我們將創(chuàng)建一個(gè)writer()對(duì)象并使用它將我們的數(shù)據(jù)寫(xiě)入文件,與讀取時(shí)的方法基本一樣。 

  1. import csv   
  2. # Field names   
  3. fields = ['Name', 'Goals', 'Assists', 'Shots']   
  4. # Rows of data in the csv file   
  5. rows = [ ['Emily', '12', '18', '112'],   
  6.          ['Katie', '8', '24', '96'],   
  7.          ['John', '16', '9', '101'],   
  8.          ['Mike', '3', '14', '82']]  
  9. filename = "soccer.csv"  
  10. # Writing to csv file   
  11. with open(filename, 'w+') as csvfile:   
  12.     # Creating a csv writer object   
  13.     csvcsvwriter = csv.writer(csvfile)   
  14.     # Writing the fields   
  15.     csvwriter.writerow(fields)   
  16.     # Writing the data rows   
  17.     csvwriter.writerows(rows) 

我們可以使用Pandas將CSV轉(zhuǎn)換為快速單行的字典列表。將數(shù)據(jù)格式化為字典列表后,我們將使用該dicttoxml庫(kù)將其轉(zhuǎn)換為XML格式。我們還將其保存為JSON文件! 

  1. import pandas as pd  
  2. from dicttoxml import dicttoxml  
  3. import json  
  4. # Building our dataframe  
  5. data = {'Name': ['Emily', 'Katie', 'John', 'Mike'],  
  6.         'Goals': [12, 8, 16, 3],  
  7.         'Assists': [18, 24, 9, 14],  
  8.         'Shots': [112, 96, 101, 82]  
  9.         }  
  10. df = pd.DataFrame(data, columns=data.keys())  
  11. # Converting the dataframe to a dictionary  
  12. # Then save it to file  
  13. data_dict = df.to_dict(orient="records" 
  14. with open('output.json', "w+") as f:  
  15.     json.dump(data_dict, f, indent=4 
  16. # Converting the dataframe to XML  
  17. # Then save it to file  
  18. xml_data = dicttoxml(data_dict).decode()  
  19. with open("output.xml", "w+") as f:  
  20.     f.write(xml_data) 

JSON數(shù)據(jù)

JSON提供了一種簡(jiǎn)潔且易于閱讀的格式,它保持了字典式結(jié)構(gòu)。就像CSV一樣,Python有一個(gè)內(nèi)置的JSON模塊,使閱讀和寫(xiě)作變得非常簡(jiǎn)單!我們以字典的形式讀取CSV時(shí),然后我們將該字典格式數(shù)據(jù)寫(xiě)入文件。 

  1. import json  
  2. import pandas as pd  
  3. # Read the data from file  
  4. # We now have a Python dictionary  
  5. with open('data.json') as f:  
  6.     data_listofdict = json.load(f)  
  7. # We can do the same thing with pandas  
  8. data_df = pd.read_json('data.json', orient='records' 
  9. # We can write a dictionary to JSON like so  
  10. # Use 'indent' and 'sort_keys' to make the JSON  
  11. # file look nice  
  12. with open('new_data.json', 'w+') as json_file:  
  13.     json.dump(data_listofdict, json_file, indent=4sort_keys=True 
  14. # And again the same thing with pandas  
  15. export = data_df.to_json('new_data.json', orient='records'

正如我們之前看到的,一旦我們獲得了數(shù)據(jù),就可以通過(guò)pandas或使用內(nèi)置的Python CSV模塊輕松轉(zhuǎn)換為CSV。轉(zhuǎn)換為XML時(shí),可以使用dicttoxml庫(kù)。具體代碼如下: 

  1. import json  
  2. import pandas as pd  
  3. import csv  
  4. # Read the data from file  
  5. # We now have a Python dictionary  
  6. with open('data.json') as f:  
  7.     data_listofdict = json.load(f)  
  8. # Writing a list of dicts to CSV  
  9. keys = data_listofdict[0].keys()  
  10. with open('saved_data.csv', 'wb') as output_file:  
  11.     dict_writer = csv.DictWriter(output_file, keys)  
  12.     dict_writer.writeheader()  
  13.     dict_writer.writerows(data_listofdict) 

XML數(shù)據(jù)

XML與CSV和JSON有點(diǎn)不同。CSV和JSON由于其既簡(jiǎn)單又快速,可以方便人們進(jìn)行閱讀,編寫(xiě)和解釋。而XML占用更多的內(nèi)存空間,傳送和儲(chǔ)存需要更大的帶寬,更多存儲(chǔ)空間和更久的運(yùn)行時(shí)間。但是XML也有一些基于JSON和CSV的額外功能:您可以使用命名空間來(lái)構(gòu)建和共享結(jié)構(gòu)標(biāo)準(zhǔn),更好地傳承,以及使用XML、DTD等數(shù)據(jù)表示的行業(yè)標(biāo)準(zhǔn)化方法。

要讀入XML數(shù)據(jù),我們將使用Python的內(nèi)置XML模塊和子模ElementTree。我們可以使用xmltodict庫(kù)將ElementTree對(duì)象轉(zhuǎn)換為字典。一旦我們有了字典,我們就可以轉(zhuǎn)換為CSV,JSON或Pandas Dataframe!具體代碼如下: 

  1. import xml.etree.ElementTree as ET  
  2. import xmltodict  
  3. import json 
  4. tree = ET.parse('output.xml')  
  5. xml_data = tree.getroot()  
  6. xmlstr = ET.tostring(xml_data, encoding='utf8'method='xml' 
  7. data_dict = dict(xmltodict.parse(xmlstr))  
  8. print(data_dict)  
  9. with open('new_data_2.json', 'w+') as json_file:  
  10.     json.dump(data_dict, json_file, indent=4sort_keys=True 

 

責(zé)任編輯:龐桂玉 來(lái)源: 馬哥Linux運(yùn)維
相關(guān)推薦

2009-10-21 09:50:46

Linux數(shù)據(jù)備份操作系統(tǒng)

2010-04-19 09:06:24

Oracle的方法

2021-11-11 12:45:36

PythonCSVJSON

2020-03-17 23:08:32

數(shù)據(jù)Elasticsear存儲(chǔ)

2018-11-02 09:16:05

數(shù)據(jù)存儲(chǔ)磁帶

2017-11-01 14:29:38

2024-12-16 17:02:58

MySQLInnoDB數(shù)據(jù)庫(kù)

2017-11-27 08:17:38

存儲(chǔ)數(shù)據(jù)位置

2009-07-02 15:12:39

2014-05-13 09:56:24

數(shù)據(jù)挖掘

2019-09-18 11:03:01

數(shù)據(jù)存儲(chǔ)數(shù)據(jù)庫(kù)

2017-11-29 08:38:58

存儲(chǔ)陣列

2010-01-25 15:57:34

Android保存數(shù)據(jù)

2022-09-07 15:47:21

數(shù)據(jù)分析對(duì)比分析大數(shù)據(jù)

2018-05-14 10:56:36

MySQL數(shù)據(jù)庫(kù)存儲(chǔ)

2021-05-31 09:00:00

數(shù)據(jù)存儲(chǔ)存儲(chǔ)系統(tǒng)工具

2017-07-17 09:04:09

2010-08-26 10:12:54

2024-11-08 12:36:35

2020-12-08 10:27:04

數(shù)據(jù)分析技術(shù)IT
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)