Pandas Data Types (dtype and Type Conversion)
Pandas provides a rich data type system, and understanding and using data types correctly is the foundation of efficient data analysis. This section describes Pandas' type system, type inference, and type conversion methods in detail.
Overview of Pandas Data Types
| dtype | Description | Python type | Example |
|---|---|---|---|
int64 |
64-bit integer | int | 1, 2, 100 |
float64 |
64-bit float | float | 1.5, 3.14 |
object |
String or mixed type | str | "hello" |
bool |
Boolean | bool | True, False |
datetime64[ns] |
Date and Time | datetime | 2024-01-01 |
timedelta64[ns] |
Time delta | timedelta | 1 days |
category |
Categorical type | - | Finite set |
Example
import
pandas
as
pd
import
numpy
as
np
Create a DataFrame with various data types
df
=
pd.
DataFrame
(
{
"integer"
:
[
1
,
2
,
3
]
,
"float"
:
[
1.5
,
2.5
,
3.5
]
,
"string"
:
[
"a"
,
"b"
,
"c"
]
,
"boolean"
:
[
True
,
False
,
True
]
,
"date"
: pd.
date_range
(
"2024-01-01"
,
periods
=
3
)
}
)
(
"Data type of each column:"
)
(
df.
dtypes
)
Type inference and specification
Automatic type deduction
Example
import
pandas
as
pd
Type inference when reading CSV
pandas tries to infer the most suitable type for each column
df
=
pd.
read_csv
(
"data.csv"
)
or explicitly specify types with the dtype parameter
df
=
pd.
read_csv
(
"data.csv"
,
dtype
=
{
"Age"
:
"int32"
,
Specify 32-bit integers to save memory
"Salary"
:
"float32"
,
Specify 32-bit floats
"Name"
:
"string"
Use PyArrow strings
}
)
Specify types at creation time
Example
import
pandas
as
pd
import
numpy
as
np
Create a Series with a specified data type
s
=
pd.
Series
(
[
1
,
2
,
3
]
,
dtype
=
"int8"
)
Use a smaller integer type
(
f
"int8 type: {s.dtype}"
)
s
=
pd.
Series
(
[
1.5
,
2.5
,
3.5
]
,
dtype
=
"float32"
)
Use float32
(
f
"float32 type: {s.dtype}"
)
Use a numpy type
s
=
pd.
Series
(
[
1
,
2
,
3
]
,
dtype
=
np.
int8
)
(
f
"np.int8 type: {s.dtype}"
)
Type Conversion
Convert with astype
Example
import
pandas
as
pd
import
numpy
as
np
Create sample data
df
=
pd.
DataFrame
(
{
"integer"
:
[
1
,
2
,
3
]
,
"float"
:
[
1.5
,
2.5
,
3.5
]
,
"string"
:
[
"1"
,
"2"
,
"3"
]
,
"boolean"
:
[
1
,
0
,
1
]
}
)
(
"Original type:"
)
(
df.
dtypes
)
(
)
Convert to string
df
[
"integer_str"
]
=
df
[
"integer"
]
.
astype
(
str
)
(
"After converting to string:"
)
(
df.
dtypes
)
String to number
df
[
"string_int"
]
=
df
[
"string"
]
.
astype
(
int
)
(
"\nString to integer:"
)
(
df.
dtypes
)
Number to boolean (nonzero is True)
df
[
"bool_int"
]
=
df
[
"boolean"
]
.
astype
(
bool
)
(
"\nInteger to boolean:"
)
(
df.
dtypes
)
Float to integer (truncation)
df
[
"float_int"
]
=
df
[
"float"
]
.
astype
(
int
)
(
"\nFloat to integer:"
)
(
df
)
Convert with pd.to_numeric
Example
import
pandas
as
pd
import
numpy
as
np
Handle numeric strings containing special characters
s
=
pd.
Series
(
[
"$1,000"
,
"$2,500"
,
"$3,200"
]
)
Clean and convert
s_cleaned
=
s.
str
.
replace
(
"$"
,
""
,
regex
=
False
)
.
str
.
replace
(
","
,
""
,
regex
=
False
)
s_numeric
=
pd.
to_numeric
(
s_cleaned
)
(
"String to number:"
)
(
s_numeric
)
(
f
"Type: {s_numeric.dtype}"
)
(
)
Handle missing values
s_with_na
=
pd.
Series
(
[
"1"
,
"2"
,
"NA"
,
"4"
]
)
s_numeric
=
pd.
to_numeric
(
s_with_na
,
errors
=
"coerce"
)
Convert invalid values to NaN
(
"Handle missing values:"
)
(
s_numeric
)
Convert dates with pd.to_datetime
Example
import
pandas
as
pd
Convert various date formats
dates
=
[
"2024-01-01"
,
"2024/01/02"
,
"01/03/2024"
,
"20240104"
]
Convert dates
dt
=
pd.
to_datetime
(
dates
,
errors
=
"coerce"
)
(
"Date conversion result:"
)
(
dt
)
(
f
"Type: {dt.dtype}"
)
(
)
Specify a date format
dates2
=
[
"20240101"
,
"20240102"
,
"20240103"
]
dt2
=
pd.
to_datetime
(
dates2
,
format
=
"%Y%m%d"
)
(
"Convert with the specified format:"
)
(
dt2
)
Memory Optimization
Choosing appropriate data types can significantly reduce memory usage.
Choosing integer types
Example
import
pandas
as
pd
import
numpy
as
np
Create a Series with a large amount of data
s
=
pd.
Series
(
np.
random
.
randint
(
0
,
100
,
1000000
)
)
Default int64
(
f
"int64 memory: {s.dtype} -> {s.memory_usage(deep=True) / 1024 / 1024:.2f} MB"
)
Convert to a smaller type
s_int8
=
s.
astype
(
"int8"
)
(
f
"int8 memory: {s_int8.dtype} -> {s_int8.memory_usage(deep=True) / 1024 / 1024:.2f} MB"
)
Choose a type based on the data range
Use np.iinfo to check integer ranges
(
f
"\nint8 range: {np.iinfo('int8').min} to {np.iinfo('int8').max}"
)
(
f
"int16 range: {np.iinfo('int16').min} to {np.iinfo('int16').max}"
)
(
f
"int32 range: {np.iinfo('int32').min} to {np.iinfo('int32').max}"
)
Use the category type
Example
import
pandas
as
pd
import
numpy
as
np
Create a Series with many repeated values
s
=
pd.
Series
(
np.
random
.
choice
(
[
"Beijing"
,
"Shanghai"
,
"Guangzhou"
,
"Shenzhen"
]
,
1000000
)
)
String type
(
f
"object type memory: {s.dtype} -> {s.memory_usage(deep=True) / 1024 / 1024:.2f} MB"
)
Convert to the category type
s_cat
=
s.
astype
(
"category"
)
(
f
"category type memory: {s_cat.dtype} -> {s_cat.memory_usage(deep=True) / 1024 / 1024:.2f} MB"
)
Drawback: some operations become slower
(
"\ncategory information:"
)
(
s_cat.
cat
.
categories
)
Type checking and inspection
Example
import
pandas
as
pd
import
numpy
as
np
df
=
pd.
DataFrame
(
{
"integer"
:
[
1
,
2
,
3
]
,
"float"
:
[
1.5
,
2.5
,
3.5
]
,
"string"
:
[
"a"
,
"b"
,
"c"
]
}
)
Check data types
(
"Check whether it is a numeric type:"
)
(
df.
dtypes
)
Use is_integer_dtype
(
f
"\nInteger column: {pd.api.types.is_integer_dtype(df['integer'])}"
)
(
f
"Float column: {pd.api.types.is_float_dtype(df['float'])}"
)
(
f
"String column: {pd.api.types.is_object_dtype(df['string'])}"
)
Check whether values can be converted to numbers
(
f
"\nCan be converted to numeric: {pd.api.types.is_numeric_dtype(df['integer'])}"
)
(
f
"Is datetime: {pd.api.types.is_datetime64_any_dtype(pd.Series(pd.date_range('2024', periods=3)))}"
)
Common questions
1. Floating-point values appear in an integer column
Mixing them into a DataFrame automatically converts them to float64; use the Nullable Integer type to preserve integer null values.
2. Inconsistent date formats
Use pd.to_datetime and specify the format parameter to handle non-standard formats.
3. Wrong types when reading CSV
Use dtype parameter to explicitly specify types, or use converters to convert them.
For large datasets, prioritize smaller data types (such as int8, int16, float32) and the category type to reduce memory usage.