將 NumPy 陣列轉換為 csv 檔案


Numpy 是 Python 程式語言中的一個庫,縮寫為 Numerical Python。它用於在較短的時間內進行數學、科學和統計計算。numpy 函式的輸出將是一個數組。使用名為 savetxt() 的函式,可以將 numpy 函式建立的陣列儲存在 CSV 檔案中。

將 NumPy 陣列轉換為 .csv 檔案

CSV 是逗號分隔值 (Comma Separated Values) 的縮寫。這是資料科學中最廣泛使用的檔案格式。它以表格格式儲存資料,其中列儲存資料欄位,行儲存資料。

CSV 檔案中的每一行都用逗號或分隔符字元分隔,使用者可以自定義分隔符。在資料科學中,我們需要使用 pandas 庫來處理 csv 檔案。

還可以使用 numpy 庫的 loadtxt() 函式將 csv 檔案中的資料恢復為 numpy 陣列格式。

語法

以下是使用 **savetxt()** 函式將 numpy 陣列轉換為 csv 檔案的語法。

numpy.savetxt(file_name,array,delimiter = ‘,’)

其中,

  • **numpy** 是庫的名稱。

  • **savetxt** 是用於將陣列轉換為 .csv 檔案的函式。

  • **file_name** 是 csv 檔案的名稱。

  • **array** 是需要轉換為 .csv 檔案的輸入陣列。

示例

為了將陣列元素轉換為 csv 檔案,我們必須將檔名和輸入陣列作為輸入引數傳遞給 **savetxt()** 函式,並附帶 delimiter = ‘,’ ,然後陣列將轉換為 **csv** 檔案。以下是一個示例。

import numpy as np
a = np.array([23,34,65,78,45,90])
print("The created array:",a)
csv_data = np.savetxt("array.csv",a,delimiter = ",")
print("array converted into csv file")
data_csv = np.loadtxt("array.csv",delimiter = ",")
print("The data from the csv file:",data_csv)

輸出

The created array: [23 34 65 78 45 90]
array converted into csv file
The data from the csv file: [23. 34. 65. 78. 45. 90.]

示例

讓我們再看一個示例,其中我們將二維陣列資料轉換為 CSV 檔案,使用 numpy 庫的 savetxt() 函式。

import numpy as np
a = np.array([[23,34,65],[78,45,90]])
print("The created array:",a)
csv_data = np.savetxt("2d_array.csv",a,delimiter = ",")
print("array converted into csv file")
data_csv = np.loadtxt("array.csv",delimiter = ",")
print("The data from the csv file:",data_csv)

輸出

The created array: [[23 34 65]
[78 45 90]]
array converted into csv file
The data from the csv file: [[23. 34. 65.]
[78. 45. 90.]]

示例

在下面的示例中,我們使用“_”作為 CSV 檔案的分隔符,而不是“,”。

import numpy as np
a = np.array([[23,34,65,87,3,4],[78,45,90,53,5,3]],int)
print("The created array:",a)
csv_data = np.savetxt("2d_array.csv",a,delimiter = "_")
print("array converted into csv file")
data_csv = np.loadtxt("2d_array.csv",delimiter = "_")
print("The data from the csv file:",data_csv)

輸出

以下是陣列轉換為 csv 檔案後的輸出。

The created array: [[23 34 65 87 3 4]
[78 45 90 53 5 3]]
array converted into csv file
The data from the csv file: [[23. 34. 65.]
[78. 45. 90.]]

更新於: 2023年8月9日

648 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告