Pandas df.astype() Function
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
- Returns a new DataFrame or Series in which the data types of all specified columns have been converted to the target type.
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
)
(
"Original data types:"
)
(
df.
dtypes
)
(
"="
50
)
Convert the "Age" column to integer type
df
[
'Age'
]
=
df
[
'Age'
]
.
astype
(
int
)
(
"Data types after converting the Age column:"
)
(
df.
dtypes
)
(
"="
50
)
Convert the "Salary" column to float type
df
[
'Salary'
]
=
df
[
'Salary'
]
.
astype
(
float
)
(
"Data types after converting the Salary column:"
)
(
df.
dtypes
)
(
"="
50
)
(
"Converted data:"
)
(
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:
- In the original data, both Age and Salary are string types (
object)。 - Use
df['列名'].astype(int)Convert strings to integers. - 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
)
(
"Original data types:"
)
(
df.
dtypes
)
(
"="
50
)
Convert column A to float64 and column B to int64
df_converted
=
df.
astype
(
{
'A'
:
'float64'
,
'B'
:
'int64'
}
)
(
"Converted data types:"
)
(
df_converted.
dtypes
)
(
"="
50
)
(
"Converted data:"
)
(
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:
- Using a dictionary
{'列名': '类型'}You can specify conversion types for multiple columns at once. - When converting the floats in column B to integers, the fractional part is truncated (2.5 becomes 2).
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
)
(
"Original data types:"
)
(
df.
dtypes
)
(
f
"Memory usage: {df.memory_usage(deep=True).sum() / 1024:.2f} KB"
)
(
"="
50
)
Convert the "City" column to categorical type
df
[
'City'
]
=
df
[
'City'
]
.
astype
(
'category'
)
(
"Converted data types:"
)
(
df.
dtypes
)
(
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:
- The categorical data type assigns an integer identifier to each unique value, saving a great deal of memory compared to storing full strings.
- The original data has 8000 rows and uses about 456 KB of memory; after conversion it uses about 120 KB, saving about 75% of the memory.
- This approach is especially suitable for categorical variables with few distinct values.
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
)
(
"Original data types:"
)
(
df.
dtypes
)
(
"="
50
)
Convert the "Date" column to datetime type
df
[
'Date'
]
=
pd.
to_datetime
(
df
[
'Date'
]
)
(
"Converted data types:"
)
(
df.
dtypes
)
(
"="
50
)
(
"Converted data:"
)
(
df
)
Now date-related operations can be performed
(
"nExtract month:"
)
(
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:
- Use
pd.to_datetime()Convert strings to datetime type. - After conversion, you can use the
.dtaccessor for date operations, such as extracting the month, day of the week, and so on. - Note: Although you can also use
astype('datetime64[ns]'), butpd.to_datetime(), it is more powerful and flexible.
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'
]
)
(
"Original data:"
)
(
s
)
(
"="
50
)
Attempt conversion; using errors='raise' (the default) raises an exception
try
:
s_converted
=
s.
astype
(
int
)
except
ValueError
as
e:
(
f
"Conversion failed: {e}"
)
(
"="
50
)
Using errors='ignore', the original data is returned when conversion fails
s_converted
=
s.
astype
(
int
,
errors
=
'ignore'
)
(
"Data after conversion with errors='ignore':"
)
(
s_converted
)
(
"="
50
)
Using errors='coerce', failed conversions are filled with NaN
s_converted2
=
s.
astype
(
float
,
errors
=
'coerce'
)
(
"Data after conversion with errors='coerce':"
)
(
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:
- When a string contains a value that cannot be converted to a number, an exception is raised by default, while
ValueErrorexception. errors='ignore'the original data is left unchanged.errors='coerce'sets values that cannot be converted toNaN, which is a common approach for handling dirty data.
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
)
(
"Original data:"
)
(
df
)
(
"Original data types:"
)
(
df.
dtypes
)
(
"="
50
)
Convert 0/1 to boolean type
df
[
'Is Member'
]
=
df
[
'Is Member'
]
.
astype
(
bool
)
(
"Data types after converting the Is Member column:"
)
(
df.
dtypes
)
(
df
)
(
"="
50
)
Convert "Yes"/"No" to boolean type
df
[
'Is Active'
]
=
df
[
'Is Active'
]
.
map
(
{
'Yes'
:
True
,
'No'
:
False
}
)
(
"Data after converting the Is Active column:"
)
(
df
)
(
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:
- 0 can be converted to
False, and 1 toTrue。 - For strings such as "Yes"/"No", you need to use
map()to convert them. - After conversion, boolean indexing can be used for fast filtering.
Notes
astype()A new object is returned by default without modifying the original data. To modify in place, you can use thecopy=Falseparameter, but this may affect the original data.- When converting floats to integers, the fractional part is truncated rather than rounded.
- When converting strings to numbers, ensure the string is a valid numeric format, otherwise an exception will be raised.
- Use
errors='coerce'is the recommended approach for handling dirty data, converting invalid values toNaN, then usefillna()for filling. - For columns with many repeated values, converting to categorical type can significantly reduce memory usage.
Common Pandas functions