自訂你的 pandas 匯入設定
pandas 套件非常擅長處理你作為資料科學家在匯入資料時常見的各種情況,例如扁平檔中的註解、空白行,以及遺漏值(NA 或 NaN)。作為本章的收尾,你將匯入受損版本的鐵達尼號資料集 titanic_corrupt.txt。此檔案在字元 '#' 之後含有註解,且是以定位字元分隔(tab-delimited)。
pd.read_csv() 的重要參數包含:
sep用來設定預期的分隔符。- 逗號分隔可用
','。 - 定位字元分隔可用
'\t'。
- 逗號分隔可用
comment指定檔案中註解所跟隨的字元,表示從這些字元開始的文字都應被忽略。na_values接受一個字串清單,將其中項目視為NA/NaN。預設情況下,部分值已被視為NA/NaN。提供此參數可額外指定其他值。
本練習屬於課程
Python 資料匯入入門
練習說明
- 完成
pd.read_csv()的參數設定,使用 pandas 正確匯入titanic_corrupt.txt:sep用來設定分隔符,其作用與np.loadtxt()的delimiter參數相同。注意你要匯入的檔案是以定位字元分隔。comment指定檔案中註解所跟隨的字元,此處為'#'。na_values接受一個字串清單,將其視為NA/NaN,此處為字串'Nothing'。
- 執行其餘程式碼,列印結果 DataFrame 的前幾列,並繪製鐵達尼號乘客
'Age'的直方圖。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
# Assign filename: file
file = 'titanic_corrupt.txt'
# Import file: data
data = pd.read_csv(file, sep='____', comment='____', na_values=[____])
# Print the head of the DataFrame
print(data.head())
# Plot 'Age' variable in a histogram
pd.DataFrame.hist(data[['Age']])
plt.xlabel('Age (years)')
plt.ylabel('count')
plt.show()