Python處理CSV、JSON和XML數據的簡便方法
Python的卓越靈活性和易用性使其成為最受歡迎的編程語言之一,尤其是對于數據處理和機器學習方面來說,其強大的數據處理庫和算法庫使得python成為入門數據科學的首選語言。在日常使用中,CSV,JSON和XML三種數據格式占據主導地位。下面我將針對三種數據格式來分享其快速處理的方法。
CSV數據
CSV是存儲數據的最常用方法。在Kaggle比賽的大部分數據都是以這種方式存儲的。我們可以使用內置的Python csv庫來讀取和寫入CSV。通常,我們會將數據讀入列表列表。
看看下面的代碼。當我們運行csv.reader()所有CSV數據變得可訪問時。該csvreader.next()函數從CSV中讀取一行; 每次調用它,它都會移動到下一行。我們也可以使用for循環遍歷csv的每一行for row in csvreader 。確保每行中的列數相同,否則,在處理列表列表時,最終可能會遇到一些錯誤。
- import csv
- filename = "my_data.csv"
- fields = []
- rows = []
- # Reading csv file
- with open(filename, 'r') as csvfile:
- # Creating a csv reader object
- csvcsvreader = csv.reader(csvfile)
- # Extracting field names in the first row
- fields = csvreader.next()
- # Extracting each data row one by one
- for row in csvreader:
- rows.append(row)
- # Printing out the first 5 rows
- for row in rows[:5]:
- print(row)
在Python中寫入CSV同樣容易。在單個列表中設置字段名稱,并在列表列表中設置數據。這次我們將創建一個writer()對象并使用它將我們的數據寫入文件,與讀取時的方法基本一樣。
- import csv
- # Field names
- fields = ['Name', 'Goals', 'Assists', 'Shots']
- # Rows of data in the csv file
- rows = [ ['Emily', '12', '18', '112'],
- ['Katie', '8', '24', '96'],
- ['John', '16', '9', '101'],
- ['Mike', '3', '14', '82']]
- filename = "soccer.csv"
- # Writing to csv file
- with open(filename, 'w+') as csvfile:
- # Creating a csv writer object
- csvcsvwriter = csv.writer(csvfile)
- # Writing the fields
- csvwriter.writerow(fields)
- # Writing the data rows
- csvwriter.writerows(rows)
我們可以使用Pandas將CSV轉換為快速單行的字典列表。將數據格式化為字典列表后,我們將使用該dicttoxml庫將其轉換為XML格式。我們還將其保存為JSON文件!
- import pandas as pd
- from dicttoxml import dicttoxml
- import json
- # Building our dataframe
- data = {'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())
- # Converting the dataframe to a dictionary
- # Then save it to file
- data_dict = df.to_dict(orient="records")
- with open('output.json', "w+") as f:
- json.dump(data_dict, f, indent=4)
- # Converting the dataframe to XML
- # Then save it to file
- xml_data = dicttoxml(data_dict).decode()
- with open("output.xml", "w+") as f:
- f.write(xml_data)
JSON數據
JSON提供了一種簡潔且易于閱讀的格式,它保持了字典式結構。就像CSV一樣,Python有一個內置的JSON模塊,使閱讀和寫作變得非常簡單!我們以字典的形式讀取CSV時,然后我們將該字典格式數據寫入文件。
- import json
- import pandas as pd
- # Read the data from file
- # We now have a Python dictionary
- with open('data.json') as f:
- data_listofdict = json.load(f)
- # We can do the same thing with pandas
- data_df = pd.read_json('data.json', orient='records')
- # We can write a dictionary to JSON like so
- # Use 'indent' and 'sort_keys' to make the JSON
- # file look nice
- with open('new_data.json', 'w+') as json_file:
- json.dump(data_listofdict, json_file, indent=4, sort_keys=True)
- # And again the same thing with pandas
- export = data_df.to_json('new_data.json', orient='records')
正如我們之前看到的,一旦我們獲得了數據,就可以通過pandas或使用內置的Python CSV模塊輕松轉換為CSV。轉換為XML時,可以使用dicttoxml庫。具體代碼如下:
- import json
- import pandas as pd
- import csv
- # Read the data from file
- # We now have a Python dictionary
- with open('data.json') as f:
- data_listofdict = json.load(f)
- # Writing a list of dicts to CSV
- keys = data_listofdict[0].keys()
- with open('saved_data.csv', 'wb') as output_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或Pandas Dataframe!具體代碼如下:
- import xml.etree.ElementTree as ET
- import xmltodict
- import json
- tree = 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)
- with open('new_data_2.json', 'w+') as json_file:
- json.dump(data_dict, json_file, indent=4, sort_keys=True)