Pandas 数据帧convert_dtypes()
方法
原文:https://www.studytonight.com/pandas/pandas-dataframe-convert_dtypes-method
在本教程中,我们将学习 PandasDataFrame.convert_dtypes()
的方法。它使用支持pd.NA
的数据类型将数据帧的列转换为最佳可能的数据类型。它返回数据帧,该数据帧是具有新数据类型的输入对象的副本。这里最可能是指最适合保存数值的类型。
下图显示了DataFrame.convert_dtypes()
方法的语法。
句法
DataFrame.convert_dtypes(infer_objects=True, convert_string=True, convert_integer=True, convert_boolean=True, convert_floating=True)
因素
expert _ objects:表示 bool(真或假),默认值为 True。它指示对象数据类型是否应该转换为可能的最佳类型。
convert_string: 表示布尔(真或假),默认值为真。指示对象数据类型是否应转换为StringDtype()
。
convert_integer: 表示 bool(真或假),默认值为 True。如果可能,它指示是否可以转换为整数扩展类型。
convert_boolean: 表示布尔(真或假),默认值为真。指示对象数据类型是否应转换为BooleanDtypes()
。
convert_floating: 表示 bool(真或假),默认值为 True。它指示如果可能的话,是否可以转换为浮动扩展类型。如果 convert_integer 也为 True,那么如果浮点数可以被忠实地转换为整数,那么将优先选择整数数据类型。
示例 1:使用DataFrame.convert_dtypes()
方法将数据帧转换为最佳数据类型
我们可以将数据帧的列转换为可能的最佳数据类型。见下面的例子。
import pandas as pd
df = pd.DataFrame({'A': ['a', 'b', 'c'], 'B': ['d', 'e', 'f']})
print("--------DataType of DataFrame---------")
print(df.dtypes)
print("--------DataType of DataFrame after converting---------")
df1=df.convert_dtypes()
print(df1.dtypes)
一旦我们运行该程序,我们将获得以下输出。
-数据帧的数据类型- A 对象 B 对象 数据类型:对象 -转换后数据帧的数据类型- A 字符串 B 字符串 数据类型:对象
示例 2:使用DataFrame.convert_dtypes()
方法转换数据帧
这个例子与上一个类似,我们只是尝试不同的数据类型。
import pandas as pd
df = pd.DataFrame({'A': [True,True,True], 'B': [True,2,3]})
print("--------DataType of DataFrame---------")
print(df.dtypes)
print("--------DataType of DataFrame after converting---------")
df1=df.convert_dtypes()
print(df1.dtypes)
一旦我们运行该程序,我们将获得以下输出。
-数据帧的数据类型- 布尔 B 对象 数据类型:对象 -转换后数据帧的数据类型- 布尔 B 对象 数据类型:对象
示例 3:使用DataFrame.convert_dtypes()
方法转换数据帧
让我们用不同的数据类型来理解DataFrame.convert_dtypes()
方法。
import pandas as pd
import numpy as np
df = pd.DataFrame({"a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),"b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")),
"c": pd.Series([True, False, np.nan], dtype=np.dtype("O")),"d": pd.Series(["h", "i", np.nan], dtype=np.dtype("O")),
"e": pd.Series([10, np.nan, 20], dtype=np.dtype("float")),"f": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")),})
print("--------DataType of DataFrame---------")
print(df.dtypes)
print("--------DataType of DataFrame after converting---------")
df1=df.convert_dtypes()
print(df1.dtypes)
一旦我们运行该程序,我们将获得以下输出。
-数据帧的数据类型- a int32 b 对象 c 对象 d 对象 e float64 f float64 数据类型:对象 -转换后数据帧的数据类型- a Int32 b 字符串 c 布尔 d 字符串 e Int64 f float64 数据类型:对象
结论
在本教程中,我们学习了 PandasDataFrame.convert_dtypes()
方法。通过解决示例,我们了解了DataFrame.convert_dtypes()
方法如何将数据帧的列转换为可能的最佳数据类型。