功能:將pandas對象轉換為指定的dtype
DataFrame.astype(dtype,copy = True,errors = 'raise')
參數:
dtype:data type, or dict of column name -> data type,使用numpy.dtype或Python類型將整個pandas對象轉換為相同類型。或者,使用{col:dtype,…},其中col是列標簽,而dtype是numpy.dtype或Python類型,以將DataFrame的一個或多個列轉換為特定於列的類型
copy:bool, default True,默認情況下返回副本,不要輕易設置 copy=False
errors:{‘raise’, ‘ignore’}, default ‘raise’,raise :允許引發異常,ignore:抑制異常。錯誤時返回原始對象
返回:
轉化的的數據
例子:
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
#將所有列強制轉換為int32
df.astype('int32').dtypes
#使用字典將col1轉換為int32:
df.astype({'col1': 'int32'}).dtypes
#或者直接
df.col1.astype('int32').dtypes
官網:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.astype.html
