在Python中,astype()函數(shù)是pandas庫的一個(gè)方法,用于將數(shù)據(jù)轉(zhuǎn)換為指定的數(shù)據(jù)類型。
astype()方法的用法如下:
df['column_name'] = df['column_name'].astype(int)
df['column_name'] = df['column_name'].astype(float)
df['column_name'] = df['column_name'].astype(str)
df['column_name'] = pd.to_datetime(df['column_name'])
df['column_name'] = df['column_name'].astype(bool)
df['column_name'] = df['column_name'].astype('category')
需要注意的是,astype()方法會(huì)創(chuàng)建一個(gè)新的Series或DataFrame對象,并將數(shù)據(jù)類型轉(zhuǎn)換為指定類型。如果數(shù)據(jù)轉(zhuǎn)換失?。ɡ纾址疅o法轉(zhuǎn)換為數(shù)字),則會(huì)引發(fā)類型錯(cuò)誤。如果要在原始DataFrame上進(jìn)行更改,請使用inplace參數(shù):
df['column_name'].astype(int, inplace=True)