使用 Python 載入機器學習專案 CSV 資料的各種方法


為了成功地構建一個機器學習專案,正確地載入資料是最重要也是最具挑戰性的任務之一。CSV 是機器學習專案最常見的格式。它是一種用於儲存表格資料的簡單格式。

以下是在 Python 中使用機器學習專案載入 CSV 資料的三個最常見方法 −

使用 Python 標準庫

為了載入 CSV 資料檔案,Python 標準庫為我們提供了名為csv 模組的內建函式。

示例

在此示例中,我們將載入鳶尾花資料集的 CSV 資料檔案 −

#Importing csv module
import csv

#To convert the data into NumPy array, import numpy module:
import numpy as np

#Providing the full path of the CSV data file which is stored on our local directory:

datafile_path = r"c:/Users/ Desktop/iris.csv"

# Reading data using the csv.reader()function:

with open(datafile_path,'r') as f:
reader = csv.reader(f,delimiter = ',')
data_headers = next(reader)
data = list(reader)
data = np.array(data).astype(float)

#Printing the names of the data headers and the first 5 lines of the data file:
print(data_headers)
print(data[:5])

輸出

['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
[
  [5.1 3.5 1.4 0.2]
  [4.9 3.  1.4 0.2]
  [4.7 3.2 1.3 0.2]
  [4.6 3.1 1.5 0.2]
  [5.  3.6 1.4 0.2]
]

使用 Pandas

我們可以用來載入 CSV 資料檔案是另一個方式是 pandas.read_csv() 函式。此函式將返回一個 pandas.DataFrame,可立即用於繪圖。

示例

在此示例中,我們將載入皮馬印第安人資料集的 CSV 資料檔案 −

#Importing read_csv function from Pandas
from pandas import read_csv

#Providing the full path of the CSV data file which is stored on our local directory:
datafile_path = r"C:/Users/Leekha/Desktop/pima-indians-diabetes.csv"

#Providing header names and reading data using read_csv() function:
headernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
data = read_csv(datafile_path, names=headernames)

#Printing the number of rows and columns in the file and first 5 lines of the data file:
print(data.shape)
print(data[:5])

輸出

(768, 9)
  preg plas pres  skin test  mass  pedi  age  class
0   6   148   72   35    0   33.6  0.627  50     1
1   1    85   66   29    0   26.6  0.351  31     0
2   8   183   64    0    0   23.3  0.672  32     1
3   1    89   66   23   94   28.1  0.167  21     0
4   0   137   40   35  168   43.1  2.288  33     1

更新時間: 2021-11-24

314 次瀏覽

開啟你的職業生涯

完成課程獲取認證

開始
廣告