溫馨提示×

python中astype的用法有哪些

小億
569
2023-08-16 19:14:26
欄目: 編程語言

在Python中,astype()函數(shù)是pandas庫的一個(gè)方法,用于將數(shù)據(jù)轉(zhuǎn)換為指定的數(shù)據(jù)類型。

astype()方法的用法如下:

  1. 將數(shù)據(jù)轉(zhuǎn)換為整數(shù)類型:
df['column_name'] = df['column_name'].astype(int)
  1. 將數(shù)據(jù)轉(zhuǎn)換為浮點(diǎn)數(shù)類型:
df['column_name'] = df['column_name'].astype(float)
  1. 將數(shù)據(jù)轉(zhuǎn)換為字符串類型:
df['column_name'] = df['column_name'].astype(str)
  1. 將數(shù)據(jù)轉(zhuǎn)換為日期類型:
df['column_name'] = pd.to_datetime(df['column_name'])
  1. 將數(shù)據(jù)轉(zhuǎn)換為布爾類型:
df['column_name'] = df['column_name'].astype(bool)
  1. 將數(shù)據(jù)轉(zhuǎn)換為分類類型:
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)

0