zl程序教程

您现在的位置是:首页 >  后端

当前栏目

如此美妙,Python 处理CSV、JSON和XML数据的方法真简便

2023-09-14 09:06:06 时间

Python 尤其是优秀的简洁和易用性成为网络编程语言的首选,是数据和编程语言的首选,其主要的数据库和算法库成为python入门数据科学的首选语言。

在日常使用中,CSV,JSON和XML三种数据格式占据主导地位。下面我将针对三种数据格式来分享其快速处理的方法。欢迎收藏学习,喜欢点赞支持,文末提供技术交流群,尽情畅聊!

CSV数据

CSV 是存储数据最常用的方法。在 Kaggle 比赛的这些数据都是以这种方式存储的。可以使用内置的 Python csv 库来读取和写入 CSV。列表。

看看下面的代码。当我们运行csv.reader()所有CSV数据都可以访问时。该csvreader.next()函数从CSV读取中一行; 每次调用它,它都会移动到下一行。我们也可以使用循环遍历csv的每一行在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和CSV不同。CSV和JSON由于其既简单又快速,可以方便地进行阅读,写JSON解释。而占用更多的内存,传送存储和需要更多的空间,更多的存储空间和更久的运行时间。而且XML还有一些基于JSON和CSV的额外功能:您使用的内部空间来构建和共享结构标准,更好地呈现,以及使用XML、DTD等数据表示的行业标准。

要读入XML数据,我们将使用Python的内置XML模块和子模ElementTree。我们可以使用xmltodict库将ElementTree对象转换为字典。如下:

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)

原文参考

https://towardsdatascience.com/the-easy-way-to-work-with-csv-json-and-xml-in-python-5056f9325ca9


技术交流

欢迎转载、收藏、有所收获点赞支持一下!

在这里插入图片描述

目前开通了技术交流群,群友已超过2000人,添加时最好的备注方式为:来源+兴趣方向,方便找到志同道合的朋友

  • 方式①、发送如下图片至微信,长按识别,后台回复:加群;
  • 方式②、添加微信号:dkl88191,备注:来自CSDN
  • 方式③、微信搜索公众号:Python学习与数据挖掘,后台回复:加群

长按关注