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 结果 DataFrame 的数据类型为: 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('结果 DataFrame 的数据类型为:') 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 101 2 y False i 100.5 2 3 z 20 200.0 结果 DataFrame 的数据类型为: 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:数据类型,或字典 {col:dtype,…},其中 col 是列标签,dtype 是 numpy.dtype 或 Python 类型,用于将 DataFrame 的一个或多个列转换为特定数据类型。
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('结果 DataFrame 的数据类型为:') 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 结果 DataFrame 的数据类型为: Integers object Floats object Strings object Dates object dtype: object
所有列的数据类型都转换为对象类型。
示例
我们再举一个例子,使用字典转换几列的数据类型。
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('结果 DataFrame 的数据类型为:') 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 结果 DataFrame 的数据类型为: Integers int64 Floats object Strings category Dates datetime64[ns] dtype: object
浮点数、字符串列被转换为对象和类别数据类型。