開始使用免費開始

匯入不同的資料型別

檔案 seaslug.txt

  • 有文字標頭,由字串組成。
  • 定位字元(tab)分隔

這份資料記錄在特定時間區間內,海蛞蝓幼體已經完成變態的比例。想了解更多,請見這裡

由於有標頭,如果你直接用 np.loadtxt() 匯入,Python 會丟出 ValueError,並告訴你 could not convert string to float。有兩種處理方式:第一,你可以將資料型別參數 dtype 設為 str(字串)。

或者,如同先前所見,你也可以使用 skiprows 參數來略過第一列。

本練習屬於課程

Python 資料匯入入門

檢視課程

練習說明

  • 在第一次呼叫 np.loadtxt() 時,將 file 作為第一個引數傳入以完成程式碼。
  • 執行 print(data[0]) 來列印 data 的第一個元素。
  • 完成第二次呼叫 np.loadtxt()。你要匯入的 file定位字元分隔,資料型別為 float,而且你要略過第一列。
  • 參考前一個 print() 呼叫,完成指令以列印 data_float 的第 10 個元素。
  • 執行其餘程式碼來視覺化資料。

動手互動練習

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

# Assign filename: file
file = 'seaslug.txt'

# Import file: data
data = np.loadtxt(____, delimiter='\t', dtype=str)

# Print the first element of data
print(data[0])

# Import file as floats and skip the first row: data_float
data_float = np.loadtxt(____, delimiter='____', dtype=____, skiprows=____)

# Print the 10th element of data_float
print(____)

# Plot a scatterplot of the data
plt.scatter(data_float[:, 0], data_float[:, 1])
plt.xlabel('time (min.)')
plt.ylabel('percentage of larvae')
plt.show()
編輯並執行程式碼