Pandas DataFrame 的转换函数


Pandas 是 Python 中功能最强大的库之一,它提供高性能的数据操作和分析工具,允许我们使用 DataFrame 处理表格数据,例如电子表格、CSV 和 SQL 数据。

DataFrame 是一种二维带标签的数据结构,它以行和列的形式表示数据。每一列中的数据可以具有不同的数据类型。

DataFrame:
	Integers	Floats		Strings	Dates
0	1.0		1.300		p		2023-05-07
1	2.0		NaN		    y		2023-05-14
2	5.0		4.600		t		2023-05-21
3	3.0		1.020		h		2023-05-28
4	6.0		0.300		o		2023-06-04
5	NaN		0.001		n		2023-06-11

上面展示的 DataFrame 有 6 行 4 列,每一行中的数据具有不同的数据类型。

而**转换函数**用于转换 DataFrame 对象中元素的数据类型。在本文中,我们将讨论 Pandas DataFrame 中不同的类型转换函数。

输入输出场景

让我们看看输入输出场景,了解如何使用转换函数进行类型转换。

假设我们有一个包含几列不同数据类型的 DataFrame,在输出中,我们将看到一个列数据类型已更新的 DataFrame。

Input DataFrame:
   ints strs  ints2  floats
0     1    x   10.0     NaN
1     2    y    NaN   100.5
2     3  NaN   20.0   200.0

Data Types of the each column is: 
ints        int64
strs       object
ints2     float64
floats    float64

Output DataFrame:
   ints  strs  ints2  floats
0     1     x     10    <NA>
1     2     y   <NA>   100.5
2     3  <NA>     20   200.0

Data Types of the resultant DataFrame is: 
ints        Int64
strs       string
ints2       Int64
floats    Float64

DataFrame.convert_dtypes() 函数

pandas DataFrame.convert_dtypes() 函数用于使用支持 pd.NA 的 dtypes 将列的数据类型转换为最佳可能的类型,并返回一个具有更新 dtypes 的新的 DataFrame 对象。

语法

DataFrame.convert_dtypes(infer_objects=True, convert_string=True, convert_integer=True, convert_boolean=True, convert_floating=True)

参数

所有参数的默认值为 True。这些都指示是否应将对象 dtypes 转换为最佳可能的类型。

示例

在这个例子中,我们将使用 .convert_dtypes() 方法转换 DataFrame 列的数据类型。

import pandas as pd
import numpy as np

df = pd.DataFrame({"a":[1, 2, 3],
   "b": ["x", "y", "z"],
   "c": [True, False, np.nan],
   "d": ["h", "i", np.nan],
   "e": [10, np.nan, 20],
   "f": [np.nan, 100.5, 200]})
print("Input DataFrame:")
print(df)
print('Data Types of the each column is: ')
print(df.dtypes)

# Convert the data type of columns
result = df.convert_dtypes()
print("Output DataFrame:")
print(result)
print('Data Types of the resultant DataFrame is: ')
print(result.dtypes)

输出

Input DataFrame:
   a  b      c    d     e      f
0  1  x   True    h  10.0    NaN
1  2  y  False    i   NaN  100.5
2  3  z    NaN  NaN  20.0  200.0

Data Types of the each column is: 
a      int64
b     object
c     object
d     object
e    float64
f    float64
dtype: object

Output DataFrame:
   a  b      c     d     e      f
0  1  x   True     h    10   
1  2  y  False     i    100.5
2  3  z         20  200.0

Data Types of the resultant DataFrame is: 
a      Int64
b     string
c    boolean
d     string
e      Int64
f    Float64
dtype: object

首先,我们使用 dtypes() 方法检查 DataFrame 列的数据类型。然后,使用 convert_dtypes() 方法将列“b”的数据类型转换为字符串,将“c”转换为布尔值,“d”转换为字符串,将“e”转换为 int64。

DataFrame.astype() 函数

pandas DataFrame.astype() 函数用于将 pandas 对象的数据类型转换为指定的 dtype。以下是语法:

DataFrame.astype(dtype, copy, errors)

参数

  • dtype:数据类型,或 dict {col: dtype, …},其中 col 是列标签,dtype 是要将 DataFrame 的一个或多个列转换为特定数据类型的 numpy.dtype 或 Python 类型。

  • copy:默认值为 True,是否在原始 DataFrame (False) 中进行更改或创建副本 (True)。

  • errors:默认值为 'raise'。是在错误时忽略错误还是引发异常。

示例

在这个例子中,我们将使用 astype() 函数将所有列的数据类型转换为对象类型。

import pandas as pd
df = pd.DataFrame({'Integers':[1, 2, 5, 3, 6, 0],
   'Floats': [1.3, None, 4.6, 1.02, 0.3, 0.001],
   'Strings': ['p', 'y', 't', 'h', 'o', 'n'],
   'Dates': pd.date_range('2023-05-04', periods=6, freq='W')})
print("Input DataFrame:")
print(df)
print('Data Types of each column is: ')
print(df.dtypes)

# Convert the data type of columns
result = df.astype('object')
print("Output DataFrame:")
print(result)
print('Data Types of the resultant DataFrame is: ')
print(result.dtypes)

输出

Input DataFrame:
   Integers  Floats Strings      Dates
0         1   1.300       p 2023-05-07
1         2     NaN       y 2023-05-14
2         5   4.600       t 2023-05-21
3         3   1.020       h 2023-05-28
4         6   0.300       o 2023-06-04
5         0   0.001       n 2023-06-11

Data Types of each column is: 
Integers             int64
Floats             float64
Strings             object
Dates       datetime64[ns]
dtype: object

Output DataFrame:
  Integers Floats Strings                Dates
0        1    1.3       p  2023-05-07 00:00:00
1        2    NaN       y  2023-05-14 00:00:00
2        5    4.6       t  2023-05-21 00:00:00
3        3   1.02       h  2023-05-28 00:00:00
4        6    0.3       o  2023-06-04 00:00:00
5        0  0.001       n  2023-06-11 00:00:00

Data Types of the resultant DataFrame is: 
Integers    object
Floats      object
Strings     object
Dates       object
dtype: object

所有列的数据类型都转换为对象类型。

示例

让我们再举一个例子,使用字典转换几列的 dtype。

import pandas as pd
df = pd.DataFrame({'Integers':[1, 2, 5, 3, 6, 0],
   'Floats': [1.3, None, 4.6, 1.02, 0.3, 0.001],
   'Strings': ['p', 'y', 't', 'h', 'o', 'n'],
   'Dates': pd.date_range('2023-05-04', periods=6, freq='W')})
print("Input DataFrame:")
print(df)
print('Data Types of each column is: ')
print(df.dtypes)

# Convert the data type of columns
result = df.astype({'Floats':'object', 'Strings': 'category'})
print("Output DataFrame:")
print(result)
print('Data Types of the resultant DataFrame is: ')
print(result.dtypes)

输出

Input DataFrame:
   Integers  Floats Strings      Dates
0         1   1.300       p 2023-05-07
1         2     NaN       y 2023-05-14
2         5   4.600       t 2023-05-21
3         3   1.020       h 2023-05-28
4         6   0.300       o 2023-06-04
5         0   0.001       n 2023-06-11

Data Types of each column is: 
Integers             int64
Floats             float64
Strings             object
Dates       datetime64[ns]
dtype: object

Output DataFrame:
   Integers Floats Strings      Dates
0         1    1.3       p 2023-05-07
1         2    NaN       y 2023-05-14
2         5    4.6       t 2023-05-21
3         3   1.02       h 2023-05-28
4         6    0.3       o 2023-06-04
5         0  0.001       n 2023-06-11

Data Types of the resultant DataFrame is: 
Integers             int64
Floats              object
Strings           category
Dates       datetime64[ns]
dtype: object

浮点数和字符串列被转换为对象和类别 dtype。

更新于:2023年5月30日

浏览量 236 次

开启你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.