• 用python读取各种数据格式(全代码)


    进入物联网和大数据时代,数据无处不在,如图像、语音、文字、天气信息、不断变化的股票价格等等。这些海亮的数据会被存储起来,并以各种格式提供给用户。学习如何读取、保存和处理一些流行的数据格式至关重要。
    本文用python实现读取写入各种数据格式,包括txt、csv、JSON、HDP5、SQL、NoSQL

     

    TXT格式

    TXT格式是最简单、最常见的数据存储格式之一,许多IoT传感器以简单的.txt文件格式记录具有不同时间戳的传感器读数。Python提供了创建、读写TXT文件的内置函数。
    如果要处理的是字符串数据(文本),直接用python是最佳选择。如果TXT文件包含数字数据,最好使用NumPy;如果数据是混合数据,pandas是最好的选择。

    data_folder = '......'
    data_file = 'alllines.txt'
    f = open(data_file)
    contents = f.read()
    print(contents[:1000])
    
    # f.write() 写入数据
    # f.close() 关闭文件
    
    # np.load()  用 NumPy读
    # pd.read_csv() 用 pandas读
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

     

    CSV格式

    逗号分隔值(CSV)文件是用于存储物联网系统生成的表格数据的最常用文件格式。在.csv文件中,记录的值存储在纯文本行中,每行包含字段的值,并用分隔符分隔。CSV格式文件默认使用逗号作为分隔符,也可以使用任何其他字符。
    想快速读取CSV文件中的数据,可以使用Python的csv模块。但是,如果需要将数据解释成时间和数字数据字段的组合,那么最好使用pandas包。如果数据只是数字数据,NumPy则是最合适的包。

    python

    import csv
    import os
    with open (os.path.join(data_folder, data_file), newline='') as csvfile:
    	csvreader = csv.reader(csvfile, delimiter=',')
    	for row in csvreader:
    		print(row)
    
    # csv.writer()  写入数据
    #csvwriter.writerow(...)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    numpy

    # 读取第3和第4列
    arr = np.loadtxt('temp.csv',skiprow=1,usecols=(2,3),delimiter=',')
    
    • 1
    • 2

    pandas

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    data = pd.read_csv("10.csv")
    x = data["timestamp"]  #获取一列,用一维数据
    x = np.array(x)
    y = data["V"]  #获取一列,用一维数据
    y = np.array(y)
    plt.plot(x, y)  # 绘制x,y的折线图
    plt.show()  # 显示折线图
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    XLSX格式

    Excel是Microsoft Office包中的一个组件,是常用的数据存储和可视化格式之一。从2010年起,Office开始支持.xlsx文件格式。可以使用OpenPyXl和pandas函数读取XLSX文件。

    openpyxl

    #Creating and writing into xlsx file
    from openpyxl import Workbook
    from openpyxl.compat import range
    from openpyxl.utils import get_column_letter
    
    wb = Workbook()
    
    dest_filename = 'empty_book.xlsx'
    
    ws1 = wb.active
    ws1.title = "range names"
    
    for row in range(1, 40):
         ws1.append(range(0,100,5))
    
    ws2 = wb.create_sheet(title="Pi")
    ws2['F5'] = 2 * 3.14
    ws2.cell(column=1, row=5, value= 3.14)
    
    ws3 = wb.create_sheet(title="Data")
    for row in range(1, 20):
         for col in range(1, 15):
             _ = ws3.cell(column=col, row=row, value="{0}".format(get_column_letter(col)))
    print(ws3['A10'].value)
    
    wb.save(filename = dest_filename)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    #Reading from xlsx file
    from openpyxl import load_workbook
    wb = load_workbook(filename = 'empty_book.xlsx')
    sheet_ranges = wb['range names']
    print(wb.get_sheet_names())
    print(sheet_ranges['D18'].value)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    pandas

    import pandas as pd
    df = pd.read_excel("empty_book.xlsx", sheet_name=0)
    df.describe()
    result = df * 2
    result.describe()
    result.to_excel("empty_book_modified.xlsx")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    JSON格式

    JSON(JavaScript Object Notation)是物联网系统中另一种流行的数据格式,它以{key : value}的字典形式存储数据。

    python

    import os
    import json
    from pprint import pprint
    
    with open (os.path.join(data_folder,data_file)) as json_file:
    	for line, i in zip(json_file,range(10)):
    		json_data=json.loads(line)
    		pprint(json_data)
    
    #json.loads()函数将字符串对象作为输入,而json.load()函数将文件对象作为输入。两个函数都对JSON对象进行解码,并将其作为一个Python字典对象加载到json_data文件中。
    #json.dumps()函数接收一个对象并产生一个JSON字符串,而json.dump()函数接收一个对象并将JSON字符串写到文件中。因此,这两个函数的作用与json.loads()和json.load()函数相反。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    pandas

    JSON字符串或文件可以通过pandas.read_json()函数读取,该函数返回一个DataFrame或series对象。例如,下面的代码读取zips.json文件:

    df = pd.read_json(os.path.join(data_folder,data_file), lines=Ture)
    print(df)
    
    #DataFrame.to_json()函数的功能是将pandas DataFrame或系列对象保存为JSON文件或字符串。
    
    • 1
    • 2
    • 3
    • 4

    HDF5格式

    层次数据格式(Hierarchical Data Format,HDF)是由HDF集团制定的规范,在HDF5文件中,数据被组织成组和数据集。组是一个集合的组或数据集的集合。数据集是一个多维同质数组。在Python中,PyTables和h5py是操作HDF5文件的两个主要库。这两个库都需要安装HDF5。

    PyTables

    import numpy as np
    arr = np.random.rand(5,4)
    np.savetxt('temp.csv', arr, delimiter=',')
    arr = np.loadtxt('temp.csv', skiprows=1, usecols=(2,3),
                delimiter=',')
    import tables
    h5filename = 'pytable_demo.hdf5'
    with tables.open_file(h5filename,mode='w') as h5file:
        root = h5file.root
        h5file.create_array(root,'global_power',arr)
        h5file.close()
        
    with tables.open_file(h5filename,mode='r') as h5file:
        root = h5file.root
        for node in h5file.root:
            ds = node.read()
            print(type(ds),ds.shape)
            print(ds)
    	
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    pandas

    #用pandas来创建一个包含global_power值的HDF5文件
    import numpy as np
    import pandas as pd
    arr = np.loadtxt('temp.csv', skiprows=1, usecols=(2,3),delimiter=',')
    store = pd.HDFstore('hdfstore_demo.hdf5')
    print(store)
    store['global_power']=pd.DataFrame(arr)
    store.close()
    
    #读取刚创建的HDF5文件并打印数组
    store=pd.HDFStore('hdfstore_demo.hdf5')
    print(store)
    print(store['global_power'])
    store.close()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    h5py

    #用h5py打开一个HDF5文件,然后打印出存储在/global_power组中的数组
    import h5py
    hdf5file = h5py.File('pytable_demo.hdf5')
    ds = hdf5file['/global_power']
    print(ds)
    for i in range(len(ds)):
    	print(arr[i])
    hdf5file.close()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    SQL格式

    大多数数据库都是采用关系型数据库的组织方式。一个关系型数据库由一个或多个相关的信息表组成,不同表的信息之间的关系用键来描述。通常情况下,这些数据库是通过数据库管理系统(Database ManagementSystem,DBMS)来管理的。DBMS是一个可以与最终用户、不同的应用程序和数据库本身进行交互的软件,用来捕获和分析数据。目前的商用DBMS使用结构化查询语言(Structured Query Language,SQL)来访问和操作数据库,我们也可以使用Python来访问关系型数据库。

    SQLite

    SQLite(https://sqlite.org/index.html)是一个独立的、高可靠性的、嵌入式的、全功能的、公共领域的SQL数据库引擎。SQLite针对嵌入式应用进行了优化。它使用起来简单且速度非常快。可使用Python sqlite3模块将SQLite与Python集成。sqlite3模块是和Python 3捆绑在一起的,所以无须安装。

    import sqlite3 
    import pandas as pd
    connection = sqlite3.connect('database.sqlite')
    print("Database opened successfully")
    
    tables = pd.read_sql("SELECT * FROM sqlite_master WHERE type='table';", connection)
    print(tables)
    
    countries = pd.read_sql("SELECT * FROM Country;", connection)
    countries.head()
    
    players = pd.read_sql_query("SELECT * FROM Player", connection)
    players.head()
    
    selected_players = pd.read_sql_query("SELECT * FROM Player WHERE height >= 180 AND weight >= 170 ", connection)
    print(selected_players)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    MySQL

    虽然用户可以用SQLite来操作大型数据库,但一般来说,MySQL是首选。MySQL除了对大型数据库具有可扩展性之外,在数据安全方面也很有用。在使用MySQL之前,需要安装Python MySQL连接器。目前有许多可选的PythonMySQL连接器,如MySQLdb、PyMySQL和MySQL。

    import mysql.connector 
    connection = mysql.connector.connect(host="127.0.0.1",  # your host 
                        user="root",                        # username
                        password="reddel17R" )              # password 
    print(connection)
    mycursor = connection.cursor()
    mycursor.execute("SHOW DATABASES")
    for x in mycursor:
      print(x) 
    
    connection = mysql.connector.connect(host="127.0.0.1",  # your host 
                        user="root",                        # username
                        password="reddel17R" ,
                        database = 'mysql') 
    mycursor = connection.cursor()
    mycursor.execute("SHOW TABLES")
    for x in mycursor:
      print(x) 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    NoSQL格式

    非结构化查询语言(Not Only Structured Query Language,NoSQL)数据库不是关系型数据库。相反,其中的数据可以以键值、JSON、文档、柱状或图形格式存储,它们经常用在大数据和实时应用程序中。这里将学习如何使用MongoDB访问NoSQL数据,并且假设已正确配置了MongoDB服务器。

    !pip install pymongo
    
    import pymongo
    client = pymongo.MongoClient()
    db = client.test
    from sklearn.datasets import load_breast_cancer
    import pandas as pd
    
    cancer = load_breast_cancer()
    data = pd.DataFrame(cancer.data, columns=[cancer.feature_names])
    import json
    data.head()
    
    data_in_json = data.to_json(orient='split')
    rows = json.loads(data_in_json)
    db.cancer_data_2.insert(rows)
    
    cursor = db['cancer_data_2'].find({})
    df = pd.DataFrame(list(cursor))
    print(df)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
  • 相关阅读:
    如何搭建npm私服以及发布包
    接口的细节:成员特点和接口的几种关系
    python显示神经网络训练时的1batch数据
    机器学习中基本符号表示和常用术语
    深入理解AVLTree【旋转控制平衡(单旋、双旋)】
    【函数式编程】函数式编程、纯函数、高阶函数以及函数柯里化
    卷积神经网络原理及其C++/Opencv实现(3)
    Win10系统怎么安装cab文件?
    低代码助力企业数字化升级
    什么是数字展会系统?数字展会系统如何带动线上线下共享“云展会”?
  • 原文地址:https://blog.csdn.net/weixin_45116099/article/details/127712820