需求:讀取一個csv文件,根據文件內容進行數據處理,將處理結果寫入另一個csv文件。
實現:用Python導入pandas庫,將csv文件讀入一個DataFrame,然后將這DataFrame的內容寫入另一個csv文件。
1. 導入pandas庫。
numReportCube=0 # 776
2. 定義若干變量並賦初值用於后續數據處理。本示例中定義numReportCube用來統計某一種類型的數據的數量,初值為0。
numReportCube=0 # 776
3. 將csv文件的內容讀入一個DataFrame。本示例中將這個DataFrame賦值給cube
for index in range(numCube): cubeType=cube.iloc[index,3] if cubeType==776: numReportCube=numReportCube+1 else: print('Unrecognized cube type in line '+str(index))
4. 因為數據處理的需求,需要知道cube里的內容一共有多少行(不包括表頭),用cube.shape[0]即可得到cube的行數,類似地,用cube.shape[1]即可得到cube的列數。
5. 用range(numCube)得到一個取值范圍用於for循環。
通過cube.iloc[index,3]取得第index行,第3列的單元格數據。
如果數值符合要求,則numReportCube計數器加1;
否則,打印警告信息:在第index行發現未識別的cube type信息。
for index in range(numCube): cubeType=cube.iloc[index,3] if cubeType==776: numReportCube=numReportCube+1 else: print('Unrecognized cube type in line '+str(index))
6. 將結果存入另一個DataFrame,即本示例中的resultItem。
結果為1行2列數據:第1列為cube數據的總行數numCube,第2列為某一種特定類型的數據的行數numReportCube。
resultItem=pd.DataFrame([[numCube,numReportCube]])
本示例中使用了DataFrame的一種定義方式:以列表形式定義DataFrame。舉例說明:
某表格為3行2列,數據內容為:
a b
c d
e f
用DataFrame可以表示為:
df=([['a','b'],['c','d'],['e','f']])
7. 將結果resultItem寫入另一個csv文件。
在以下示例中,第一個參數是待寫入的文件路徑。
第二個參數header是指是否保留表頭,保留則為True,不保留則為False。
第三個參數index是指是否保留列的索引,保留則為True,不保留則為False。
第四個參數mode是指以何種模式寫入數據,"a"是append的縮寫,表示以“追加”的方式寫入數據。
resultItem.to_csv('E:\Result.csv',header=False,index=False,mode="a")