关于python:来点干货3招Python-处理CSVJSON和XML数据的简便方法

6次阅读

共计 3434 个字符,预计需要花费 9 分钟才能阅读完成。

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 
    csvreader = 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 
    csvwriter = 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)

正文完
 0