開始使用免費開始

使用 pandas 將平面檔案匯入為 DataFrame(2)

在上一個練習中,你已經能把平面檔案匯入成 pandas 的 DataFrame。進一步來說,你也可以很輕鬆地用 .to_numpy() 方法取得對應的 numpy 陣列。現在你將用 MNIST 資料集來實作,檔名為 digits.csv

pd.read_csv() 有數個對這題很實用的引數:

  • nrows 可用來指定要從檔案讀取幾列。例如,nrows=10 只會匯入前 10 列。
  • header 接受要作為欄標籤且標記資料起始的列號。若檔案沒有標頭列,可以設為 header=Nonepandas 會自動從 0 開始指派整數欄標籤(例如 0、1、2、…)。

本練習屬於課程

Python 資料匯入入門

檢視課程

練習說明

  • 使用 pd.read_csv() 函式將檔案的「前 5 列」匯入為 DataFrame,並指定給 data。你需要使用 nrowsheader 這兩個引數。注意,此檔案沒有標頭列。
  • data 這個 DataFrame 建立一個 numpy 陣列,指定給 data_array
  • 執行 print(type(data_array)),印出 data_array 的資料型別。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Assign the filename: file
file = 'digits.csv'

# Read the first 5 rows of the file into a DataFrame: data
data = ____(____, ____, ____)

# Build a numpy array from the DataFrame: data_array
data_array = ____

# Print the datatype of data_array to the shell
print(type(data_array))
編輯並執行程式碼