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

Pandas Data Types (dtype and Type Conversion)

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

)

}

)

print

(

"Data type of each column:"

)

print

(

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

print

(

f

"int8 type: {s.dtype}"

)

s

=

pd.

Series

(

[

1.5

,

2.5

,

3.5

]

,

dtype

=

"float32"

)

 

Use float32

print

(

f

"float32 type: {s.dtype}"

)

Use a numpy type

s

=

pd.

Series

(

[

1

,

2

,

3

]

,

dtype

=

np.

int8

)

print

(

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

]

}

)

print

(

"Original type:"

)

print

(

df.

dtypes

)

print

(

)

Convert to string

df

[

"integer_str"

]

=

df

[

"integer"

]

.

astype

(

str

)

print

(

"After converting to string:"

)

print

(

df.

dtypes

)

String to number

df

[

"string_int"

]

=

df

[

"string"

]

.

astype

(

int

)

print

(

"\nString to integer:"

)

print

(

df.

dtypes

)

Number to boolean (nonzero is True)

df

[

"bool_int"

]

=

df

[

"boolean"

]

.

astype

(

bool

)

print

(

"\nInteger to boolean:"

)

print

(

df.

dtypes

)

Float to integer (truncation)

df

[

"float_int"

]

=

df

[

"float"

]

.

astype

(

int

)

print

(

"\nFloat to integer:"

)

print

(

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

)

print

(

"String to number:"

)

print

(

s_numeric

)

print

(

f

"Type: {s_numeric.dtype}"

)

print

(

)

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

print

(

"Handle missing values:"

)

print

(

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"

)

print

(

"Date conversion result:"

)

print

(

dt

)

print

(

f

"Type: {dt.dtype}"

)

print

(

)

Specify a date format

dates2

=

[

"20240101"

,

"20240102"

,

"20240103"

]

dt2

=

pd.

to_datetime

(

dates2

,

format

=

"%Y%m%d"

)

print

(

"Convert with the specified format:"

)

print

(

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

print

(

f

"int64 memory: {s.dtype} -> {s.memory_usage(deep=True) / 1024 / 1024:.2f} MB"

)

Convert to a smaller type

s_int8

=

s.

astype

(

"int8"

)

print

(

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

print

(

f

"\nint8 range: {np.iinfo('int8').min} to {np.iinfo('int8').max}"

)

print

(

f

"int16 range: {np.iinfo('int16').min} to {np.iinfo('int16').max}"

)

print

(

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

print

(

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"

)

print

(

f

"category type memory: {s_cat.dtype} -> {s_cat.memory_usage(deep=True) / 1024 / 1024:.2f} MB"

)

Drawback: some operations become slower

print

(

"\ncategory information:"

)

print

(

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

print

(

"Check whether it is a numeric type:"

)

print

(

df.

dtypes

)

Use is_integer_dtype

print

(

f

"\nInteger column: {pd.api.types.is_integer_dtype(df['integer'])}"

)

print

(

f

"Float column: {pd.api.types.is_float_dtype(df['float'])}"

)

print

(

f

"String column: {pd.api.types.is_object_dtype(df['string'])}"

)

Check whether values can be converted to numbers

print

(

f

"\nCan be converted to numeric: {pd.api.types.is_numeric_dtype(df['integer'])}"

)

print

(

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.