淺析python常用數(shù)據(jù)文件處理方法
0.前言
雖說python運行速度慢,但其編程速度,第三方包的豐富度是真的高。
涉及到文件批處理還是會選擇python。
1. 動態(tài)文件名
在文件批處理中,文件名經(jīng)常只有編號是不同的,可以通過給字符串傳遞不同的編號來獲取動態(tài)文件名。
file_num = 324 # file_num = 1 for i in range(file_num): file_name = "正常數(shù)據(jù)\\{}.正常.txt".format(i + 1) ...
2. 將文件轉(zhuǎn)換為csv格式
一般數(shù)據(jù)提供者為了節(jié)省存儲空間,都會通過規(guī)定的格式存儲到txt文件中,這種格式對計算機可能并不友好。而逗號文件csv格式可以輕松被numpy、pandas等數(shù)據(jù)處理包讀取。
首先通過逐行讀取獲取每行數(shù)據(jù)(大部分數(shù)據(jù)文件都是每行格式相同,如果數(shù)據(jù)只有一行,可以全部讀取或者逐字符讀?。?,之后通過line.replace('\n', ‘')將每行的換行符刪除,以免最后得到的csv文件有空行。
使用line.split(':')將字符串分解為多個字段。
通過csv.writer寫入整行。
import csv outFile = open(file_path + outFile_name, 'w', encoding='utf-8', newline='' "") csv_writer = csv.writer(outFile) with open(file_path + file_name, "r") as f: index = 0 for line in f: # 寫入表頭 if index == 0: csv_writer.writerow(['T', 'TimeStamp', 'RangeReport', 'TagID', 'AnchorID', 'ranging', 'check', 'SerialNumber', 'DataID']) index = index + 1 continue line = line.replace('\n', '') str = line.split(':') csv_writer.writerow(str)
3. 初步處理csv文件
一開始得到的csv文件往往是我們不想要的,需要進行簡單的處理。
例如我想將四行數(shù)據(jù)合并為一行。
使用pandas讀取csv文件為一個表df。將希望生成的格式簡單做一個有標題、有一行數(shù)據(jù)的文件,讀取為另一個表df2.
可以使用
del df['T']
來刪除指定的列。
可以通過
df2.loc[row] = list
來確定新文件的一行數(shù)據(jù)。pandas訪問行數(shù)據(jù)
import pandas as pd df = pd.read_csv(file_path + file_name) # 刪除某些列 del df['T'] del df['RangeReport'] del df['TagID'] # 判斷同一DataID對應(yīng)的SerialNumber是否相同 # SerialNumberBegin = df['SerialNumber'][0] # DataIDBegin = df['DataID'][0] # for row in range(df.shape[0]): # c = df['SerialNumber'][row] != (SerialNumberBegin + int(row / 4)) % 256 # d = df['DataID'][row] != DataIDBegin + int(row / 4) # e = df['AnchorID'][row] != row % 4 # if c | d | e: # print('err') del df['AnchorID'] # print(type(df['TimeStamp'][0])) # 進行表合并 df2 = pd.read_csv(file_path + "合并格式.csv") for row in range(int(df.shape[0]/4)): list = [3304,229,90531088,90531088,90531088,90531088,760,760,760,760,760,760,760,760] # DataID,SerialNumber,TimeStamp0,TimeStamp1,TimeStamp2,TimeStamp3,ranging0,check0,ranging1,check1,ranging2,check2,ranging3,check3 list[0] = df['DataID'][row*4] list[1] = df['SerialNumber'][row*4] list[2] = df['TimeStamp'][row*4+0] list[3] = df['TimeStamp'][row*4+1] list[4] = df['TimeStamp'][row*4+2] list[5] = df['TimeStamp'][row*4+3] list[6] = df['ranging'][row*4+0] list[7] = df['check'][row*4+0] list[8] = df['ranging'][row*4+1] list[9] = df['check'][row*4+1] list[10] = df['ranging'][row*4+2] list[11] = df['check'][row*4+2] list[12] = df['ranging'][row*4+3] list[13] = df['check'][row*4+3] df2.loc[row] = list df2.to_csv(file_path+contact_name)
4. 獲取部分數(shù)據(jù)
可以通過
df0 = df.iloc[:, 3:7]
或者
df0 = df[["check0","check1","check2","check3"]]
來獲取一個表的某幾列。
5. 數(shù)據(jù)間的格式轉(zhuǎn)換
一般會在list、numpy、pandas三種格式間進行數(shù)據(jù)轉(zhuǎn)換。
自己創(chuàng)建數(shù)據(jù)時,經(jīng)常使用
y_show = [] y_show.append(n_clusters_)
維度調(diào)整好后,可以是一維或者多維,再轉(zhuǎn)換為numpy或者pandas。
其中轉(zhuǎn)換成numpy的方法如下
y = np.array(y_show)
6. 離群點、重合點的處理
使用DBSCAN算法進行聚類。具體算法描述隨便搜就有。
有兩個重要參數(shù),一個是聚類半徑,另一個是最小鄰居數(shù)。
指定較大半徑以及較大鄰居數(shù)可以篩選出離散點。
指定較小半徑可以篩選出重合點、相似點。
代碼如下,使用一個n*m的numpy矩陣作為輸入,對m維的點進行聚類。
通過一通操作獲取labels,是一個map,key值為int數(shù)值,-1,0,1,2…。-1代表離群點,其他代表第幾簇。value是一個list,代表各簇的點的下標。
from sklearn.cluster import DBSCAN y = df[["d0","d1","d2","d3"]].to_numpy() db = DBSCAN(eps=3, min_samples=2).fit(y) core_samples_mask = np.zeros_like(db.labels_, dtype=bool) core_samples_mask[db.core_sample_indices_] = True labels = db.labels_ # 統(tǒng)計簇中l(wèi)abels的數(shù)量 n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
7. 數(shù)據(jù)繪制
繪制二維的比較簡單,這里只貼上三維繪制代碼
import matplotlib.pyplot as plt import pandas as pd from mpl_toolkits.mplot3d import axes3d df = pd.read_csv(file_path+file_name) x1 = df["x"].to_numpy() y1 = df["y"].to_numpy() z1 = df["z"].to_numpy() df = pd.read_csv(file_path+file_name2) x2 = df["x"].to_numpy() y2 = df["y"].to_numpy() z2 = df["z"].to_numpy() # new a figure and set it into 3d fig = plt.figure() ax = fig.gca(projection='3d') # set figure information # ax.set_title("3D") ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("Z") # draw the figure, the color is r = read # figure1 = ax.plot(x1, y1, z1, c='b') figure2 = ax.plot(x2, y2, z2, c='r') # figure3 = ax.plot(x3, x3, z3, c='g') # figure4 = ax.plot(x4, x4, z4, c='y') ax.set_xlim(0, 7000) # ax.set_ylim(0, 5000) ax.set_zlim(0, 3000) plt.show()
8. numpy的矩陣運算
# 轉(zhuǎn)換數(shù)據(jù)類型 Zk = Zk.astype(float) # 范數(shù) a,b是維度相同的向量 np.linalg.norm(a-b) # 矩陣乘法 np.matmul(A, B) # 矩陣求逆 np.linalg.inv(A) # 單位陣 np.eye(dims) # 轉(zhuǎn)置 Zk = Zk.T
9. 保存文件
可以使用csv writerow存文件,見1.
也可以使用numpy或者pandas保存文件。
如果直接使用pandas的
df2.to_csv(file_path+contact_name)
保存文件,會額外保存一行index。可以通過參數(shù),index=False來控制。
如果還有其他要求可以查閱pd.to_csv
也可使用numpy,將一個numpy類型數(shù)據(jù)通過指定格式存文件。這里一般要指定格式,否則有可能會存成自己不希望的類型。
np.savetxt(file_path + "異常數(shù)據(jù).txt", np.array(y_show,dtype=np.int16), fmt="%d")
到此這篇關(guān)于python常用數(shù)據(jù)文件處理方法的文章就介紹到這了,更多相關(guān)python數(shù)據(jù)文件處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python 設(shè)置文件編碼格式的實現(xiàn)方法
下面小編就為大家分享一篇python 設(shè)置文件編碼格式的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12Python練習(xí)之操作SQLite數(shù)據(jù)庫
這篇文章主要介紹了Python練習(xí)之操作SQLite數(shù)據(jù)庫,主要通過三個問題如何創(chuàng)建SQLite數(shù)據(jù)庫?如何向SQLite表中插入數(shù)據(jù)?如何查詢SQLite表中的數(shù)據(jù)?展開文章主題詳情,需要的朋友可以參考一下2022-06-06