Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas df.astype() Function

Pandas df.astype() Function

Pandas Common Functions Common Pandas functions


df.astype() is a function in Pandas used to convert the data type of a DataFrame or Series.

During data processing, data type mismatches are a common problem. For example, numbers stored as strings, dates stored as text, and so on.astype() allows you to explicitly convert data to the desired type, such as integer, float, string, date, etc., ensuring that the data can be correctly calculated and analyzed.


Basic syntax and parameters

astype() It is a member function of both DataFrame and Series; use the dot operator . to call it.

Syntax format



DataFrame.astype(dtype, copy=True, errors='raise')

Series.astype(dtype, copy=True, errors='raise')

Parameter Description

Parameters Type Required Description Default value
dtype Python dtype or numpy dtype Required The target data type. It can be a Python type (such as int、str), a NumPy type (such as np.int64、np.float32) or a Pandas type (such as 'int64'、'float64'、'category')。 None
copy bool Optional If it is True, always returns a new object; if False, the original object is modified in place when possible. True
errors str Optional Controls error handling.'raise' means an exception is raised when conversion fails;'ignore' means the original data is returned when conversion fails, without raising an exception. 'raise'

Return value description


Example

Let us thoroughly master astype() through a series of examples from simple to complex.

Example 1: Convert the data type of a single column

Convert a column of a Series or DataFrame to a specified type.

Example

import

pandas

as

pd

Create a DataFrame with numbers stored as strings

data

=

{

   

'Name'

:

[

'Zhang San'

,

'Li Si'

,

'Wang Wu'

,

'Zhao Liu'

]

,

   

'Age'

:

[

'25'

,

'30'

,

'35'

,

'28'

]

,

 

stored as strings

   

'Salary'

:

[

'5000'

,

'6000'

,

'5500'

,

'7000'

]

 

stored as strings

}

df

=

pd.

DataFrame

(

data

)

print

(

"Original data types:"

)

print

(

df.

dtypes

)

print

(

"="

50

)

Convert the "Age" column to integer type

df

[

'Age'

]

=

df

[

'Age'

]

.

astype

(

int

)

print

(

"Data types after converting the Age column:"

)

print

(

df.

dtypes

)

print

(

"="

50

)

Convert the "Salary" column to float type

df

[

'Salary'

]

=

df

[

'Salary'

]

.

astype

(

float

)

print

(

"Data types after converting the Salary column:"

)

print

(

df.

dtypes

)

print

(

"="

50

)

print

(

"Converted data:"

)

print

(

df

)

Expected output:



Primitive data types:

姓名     object

年龄    object  # 字符串类型

薪资    object  # 字符串类型

==================================================

Change the data type after converting the age column:

姓名      object

年龄     int64  # 整数类型

薪资    object

==================================================

Convert the data type after transforming the salary column:

姓名      object

年龄     int64

薪资    float64  # 浮点数类型

==================================================

转换后的数据:

    姓名  年龄    薪资

0  张三   25  5000.0

1  李四   30  6000.0

2  王五   35  5500.0

3  赵六   28  7000.0

Code analysis:

  1. In the original data, both Age and Salary are string types (object)。
  2. Use df['列名'].astype(int) Convert strings to integers.
  3. After conversion, numerical calculations such as sum and mean can be performed.

Example 2: Convert the data types of the entire DataFrame

You can specify data types for the entire DataFrame at once.

Example

import

pandas

as

pd

Create a DataFrame

data

=

{

   

'A'

:

[

1

,

2

,

3

,

4

]

,

   

'B'

:

[

1.5

,

2.5

,

3.5

,

4.5

]

,

   

'C'

:

[

'a'

,

'b'

,

'c'

,

'd'

]

}

df

=

pd.

DataFrame

(

data

)

print

(

"Original data types:"

)

print

(

df.

dtypes

)

print

(

"="

50

)

Convert column A to float64 and column B to int64

df_converted

=

df.

astype

(

{

'A'

:

'float64'

,

'B'

:

'int64'

}

)

print

(

"Converted data types:"

)

print

(

df_converted.

dtypes

)

print

(

"="

50

)

print

(

"Converted data:"

)

print

(

df_converted

)

Expected output:



Primitive data types:

A      int64

B    float64

C     object

==================================================

Converted data type:

A    float64

B      int64  # 小数部分被截断

C     object

==================================================

转换后的数据:

     A  B  C

0  1.0  2  a

1  2.0  2  b

2  3.0  3  c

3  4.0  4  d

Code analysis:

Example 3: Convert to categorical data type

Categorical data type (category) can save memory and is especially suitable for columns with a limited number of values.

Example

import

pandas

as

pd

Create a DataFrame with many repeated values

data

=

{

   

'City'

:

[

'Beijing'

,

'Shanghai'

,

'Guangzhou'

,

'Shenzhen'

,

'Beijing'

,

'Shanghai'

,

'Guangzhou'

,

'Shenzhen'

]

1000

,

   

'ID'

:

range

(

8000

)

}

df

=

pd.

DataFrame

(

data

)

print

(

"Original data types:"

)

print

(

df.

dtypes

)

print

(

f

"Memory usage: {df.memory_usage(deep=True).sum() / 1024:.2f} KB"

)

print

(

"="

50

)

Convert the "City" column to categorical type

df

[

'City'

]

=

df

[

'City'

]

.

astype

(

'category'

)

print

(

"Converted data types:"

)

print

(

df.

dtypes

)

print

(

f

"Memory usage: {df.memory_usage(deep=True).sum() / 1024:.2f} KB"

)

Expected output:



Primitive data types:

城市    object

编号    int64

内存使用: ~456 KB

==================================================

Converted data type:

城市    category

编号     int64

内存使用: ~120 KB  # 内存使用大幅减少

Code analysis:

Example 4: Convert to datetime type

Convert strings to datetime type to perform date-related operations.

Example

import

pandas

as

pd

Create a DataFrame containing date strings

data

=

{

   

'Date'

:

[

'2024-01-01'

,

'2024-01-02'

,

'2024-01-03'

,

'2024-01-04'

]

,

   

'Sales'

:

[

100

,

150

,

120

,

180

]

}

df

=

pd.

DataFrame

(

data

)

print

(

"Original data types:"

)

print

(

df.

dtypes

)

print

(

"="

50

)

Convert the "Date" column to datetime type

df

[

'Date'

]

=

pd.

to_datetime

(

df

[

'Date'

]

)

print

(

"Converted data types:"

)

print

(

df.

dtypes

)

print

(

"="

50

)

print

(

"Converted data:"

)

print

(

df

)

Now date-related operations can be performed

print

(

"nExtract month:"

)

print

(

df

[

'Date'

]

.

dt

.

month

)

Expected output:



Primitive data types:

日期    object  # 字符串类型

销量     int64

==================================================

Converted data type:

日期    datetime64[ns]  # 日期时间类型

销量     int64

==================================================

转换后的数据:

        日期   销量

0 2024-01-01  100

1 2024-01-02  150

2 2024-01-03  120

3 2024-01-04  180



Extract month:

0    1

1    1

2    1

3    1

Name: 日期, dtype: int64

Code analysis:

Example 5: Handle conversion errors

Use errors='ignore' The parameter can handle conversion failures.

Example

import

pandas

as

pd

Create a Series containing values that cannot be converted to integers

s

=

pd.

Series

(

[

'1'

,

'2'

,

'hello'

,

'4'

,

'world'

]

)

print

(

"Original data:"

)

print

(

s

)

print

(

"="

50

)

Attempt conversion; using errors='raise' (the default) raises an exception

try

:

    s_converted

=

s.

astype

(

int

)

except

ValueError

as

e:

   

print

(

f

"Conversion failed: {e}"

)

print

(

"="

50

)

Using errors='ignore', the original data is returned when conversion fails

s_converted

=

s.

astype

(

int

,

errors

=

'ignore'

)

print

(

"Data after conversion with errors='ignore':"

)

print

(

s_converted

)

print

(

"="

50

)

Using errors='coerce', failed conversions are filled with NaN

s_converted2

=

s.

astype

(

float

,

errors

=

'coerce'

)

print

(

"Data after conversion with errors='coerce':"

)

print

(

s_converted2

)

Expected output:



Original data:

0       1

1       2

2    hello  # 无法转换为整数

3       4

4    world  # 无法转换为整数

==================================================

转换失败: invalid literal for int() with base 10: 'hello'

==================================================

Data converted using errors='ignore':

0       1

1       2

2    hello  # 保持原值

3       4

4    world  # 保持原值

==================================================

Data after conversion using errors='coerce':

0    1.0

1    2.0

2    NaN  # 无法转换,设为 NaN

3    4.0

4    NaN  # 无法转换,设为 NaN

Code analysis:

Example 6: Convert to boolean type

Convert data to boolean type, commonly used for conditional filtering and logical operations.

Example

import

pandas

as

pd

Create a DataFrame containing 0 and 1

data

=

{

   

'Is Member'

:

[

0

,

1

,

1

,

0

,

1

]

,

   

'Is Active'

:

[

'Yes'

,

'No'

,

'Yes'

,

'Yes'

,

'No'

]

}

df

=

pd.

DataFrame

(

data

)

print

(

"Original data:"

)

print

(

df

)

print

(

"Original data types:"

)

print

(

df.

dtypes

)

print

(

"="

50

)

Convert 0/1 to boolean type

df

[

'Is Member'

]

=

df

[

'Is Member'

]

.

astype

(

bool

)

print

(

"Data types after converting the Is Member column:"

)

print

(

df.

dtypes

)

print

(

df

)

print

(

"="

50

)

Convert "Yes"/"No" to boolean type

df

[

'Is Active'

]

=

df

[

'Is Active'

]

.

map

(

{

'Yes'

:

True

,

'No'

:

False

}

)

print

(

"Data after converting the Is Active column:"

)

print

(

df

)

print

(

df.

dtypes

)

Expected output:



Original data:

  是否会员  是否激活

0       0       是

1       1       否

2       1       是

3       0       是

4       1       否

==================================================

Convert the data type after the 'is_member' column:

是否会员      bool

是否激活    object

==================================================

Data after converting the activation column:

  是否会员  是否激活

0    True    True

1   True   False

2    True    True

3   False   True

4    True   False

Code analysis:


Notes


Pandas Common Functions Common Pandas functions