整數與浮點數
還記得你可以用 type() 函式來查看物件的資料型別嗎?
不過,在處理 DataFrame 時這樣的資訊不夠用,因為結果只會是:
print(type(some_DataFrame))
<class 'pandas.core.frame.DataFrame'>
如果你想知道 DataFrame 中每個欄位的資料型別,可以使用 .info() 方法或 .dtypes 屬性。若你想變更某個欄位的資料型別,可以在該欄位上呼叫 .astype() 方法,並傳入新型別。例如,將 'column_a' 轉換為整數:
df['column_a'] = df['column_a'].astype(int)
本練習屬於課程
給 R 使用者的 Python
練習說明
- 在終端機查看
tips.dtypes的輸出。 - 將
size欄位轉為int型別。 - 將
tip欄位轉為float型別。 - 再次查看
.dtypes。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Convert the size column
tips['size'] = tips['size']____
# Convert the tip column
____ = ____
# Look at the types
print(____)