使用 pandas 將平面檔案匯入為 DataFrame(2)
在上一個練習中,你已經能把平面檔案匯入成 pandas 的 DataFrame。進一步來說,你也可以很輕鬆地用 .to_numpy() 方法取得對應的 numpy 陣列。現在你將用 MNIST 資料集來實作,檔名為 digits.csv。
pd.read_csv() 有數個對這題很實用的引數:
nrows可用來指定要從檔案讀取幾列。例如,nrows=10只會匯入前 10 列。header接受要作為欄標籤且標記資料起始的列號。若檔案沒有標頭列,可以設為header=None,pandas會自動從 0 開始指派整數欄標籤(例如 0、1、2、…)。
本練習屬於課程
Python 資料匯入入門
練習說明
- 使用
pd.read_csv()函式將檔案的「前 5 列」匯入為 DataFrame,並指定給data。你需要使用nrows與header這兩個引數。注意,此檔案沒有標頭列。 - 由
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))