在 pandas 中转换类型有四个主要选项:
-
to_numeric() - 提供安全地将非数字类型(例如字符串)转换为合适的数字类型的功能。 (另见to_datetime() 和to_timedelta()。)
-
astype() - 将(几乎)任何类型转换为(几乎)任何其他类型(即使这样做不一定明智)。还允许您转换为categorial 类型(非常有用)。
-
infer_objects() - 如果可能的话,将包含 Python 对象的对象列转换为 pandas 类型的实用方法。
-
convert_dtypes() - 将 DataFrame 列转换为支持pd.NA 的“最佳”dtype(pandas 的对象表示缺失值)。
继续阅读以了解这些方法的更详细说明和用法。
1。 to_numeric()
将 DataFrame 的一列或多列转换为数值的最佳方法是使用pandas.to_numeric()。
此函数将尝试将非数字对象(如字符串)更改为适当的整数或浮点数。
基本用法
to_numeric() 的输入是一个系列或 DataFrame 的单列。
>>> s = pd.Series(["8", 6, "7.5", 3, "0.9"]) # mixed string and numeric values
>>> s
0 8
1 6
2 7.5
3 3
4 0.9
dtype: object
>>> pd.to_numeric(s) # convert everything to float values
0 8.0
1 6.0
2 7.5
3 3.0
4 0.9
dtype: float64
如您所见,返回了一个新系列。请记住将此输出分配给变量或列名以继续使用它:
# convert Series
my_series = pd.to_numeric(my_series)
# convert column "a" of a DataFrame
df["a"] = pd.to_numeric(df["a"])
您还可以通过apply() 方法使用它来转换DataFrame 的多个列:
# convert all columns of DataFrame
df = df.apply(pd.to_numeric) # convert all columns of DataFrame
# convert just columns "a" and "b"
df[["a", "b"]] = df[["a", "b"]].apply(pd.to_numeric)
只要您的值都可以转换,这可能就是您所需要的。
错误处理
但是如果有些值不能转换成数值类型呢?
to_numeric() 还采用 errors 关键字参数,允许您将非数字值强制为 NaN,或直接忽略包含这些值的列。
这是一个使用一系列字符串 s 的示例,该字符串具有对象 dtype:
>>> s = pd.Series(['1', '2', '4.7', 'pandas', '10'])
>>> s
0 1
1 2
2 4.7
3 pandas
4 10
dtype: object
如果无法转换值,默认行为是引发。在这种情况下,它无法处理字符串'pandas':
>>> pd.to_numeric(s) # or pd.to_numeric(s, errors='raise')
ValueError: Unable to parse string
我们可能希望“熊猫”被视为缺失/错误的数值,而不是失败。我们可以使用 errors 关键字参数将无效值强制转换为 NaN,如下所示:
>>> pd.to_numeric(s, errors='coerce')
0 1.0
1 2.0
2 4.7
3 NaN
4 10.0
dtype: float64
errors 的第三个选项只是在遇到无效值时忽略该操作:
>>> pd.to_numeric(s, errors='ignore')
# the original Series is returned untouched
最后一个选项对于转换整个 DataFrame 特别有用,但不知道我们的哪些列可以可靠地转换为数字类型。在这种情况下,只需写:
df.apply(pd.to_numeric, errors='ignore')
该函数将应用于 DataFrame 的每一列。可以转换为数字类型的列将被转换,而不能转换为数字类型的列(例如,它们包含非数字字符串或日期)将被保留。
向下转型
默认情况下,使用to_numeric() 进行转换将为您提供int64 或float64 dtype(或您的平台原生的任何整数宽度)。
这通常是您想要的,但是如果您想节省一些内存并使用更紧凑的 dtype,例如 float32 或 int8,该怎么办?
to_numeric() 让您可以选择向下转换为 'integer'、'signed'、'unsigned'、'float'。以下是整数类型的简单系列s 的示例:
>>> s = pd.Series([1, 2, -7])
>>> s
0 1
1 2
2 -7
dtype: int64
向下转换为 'integer' 使用可以容纳值的最小可能整数:
>>> pd.to_numeric(s, downcast='integer')
0 1
1 2
2 -7
dtype: int8
向下转换为 'float' 同样会选择比正常浮动类型更小的:
>>> pd.to_numeric(s, downcast='float')
0 1.0
1 2.0
2 -7.0
dtype: float32
2。 astype()
astype() 方法使您能够明确说明您希望 DataFrame 或 Series 具有的 dtype。它用途广泛,您可以尝试从一种类型转换为任何其他类型。
基本用法
只需选择一种类型:您可以使用 NumPy dtype(例如 np.int16)、一些 Python 类型(例如 bool)或 pandas 特定类型(例如 categorical dtype)。
在你想转换的对象上调用方法,astype() 会尝试为你转换:
# convert all DataFrame columns to the int64 dtype
df = df.astype(int)
# convert column "a" to int64 dtype and "b" to complex type
df = df.astype({"a": int, "b": complex})
# convert Series to float16 type
s = s.astype(np.float16)
# convert Series to Python strings
s = s.astype(str)
# convert Series to categorical type - see docs for more details
s = s.astype('category')
注意我说的是“尝试” - 如果astype() 不知道如何转换 Series 或 DataFrame 中的值,它将引发错误。例如,如果您有 NaN 或 inf 值,尝试将其转换为整数时会出错。
从 pandas 0.20.0 开始,可以通过传递 errors='ignore' 来抑制此错误。您的原始对象将原封不动地返回。
小心
astype() 功能强大,但它有时会“错误地”转换值。例如:
>>> s = pd.Series([1, 2, -7])
>>> s
0 1
1 2
2 -7
dtype: int64
这些都是小整数,那么转换成无符号的8位类型如何节省内存呢?
>>> s.astype(np.uint8)
0 1
1 2
2 249
dtype: uint8
转换成功,但 -7 被环绕成 249(即 28 - 7)!
尝试使用pd.to_numeric(s, downcast='unsigned') 向下转换可能有助于防止出现此错误。
3。 infer_objects()
pandas 0.21.0 版引入了 infer_objects() 方法,用于将 DataFrame 中具有对象数据类型的列转换为更具体的类型(软转换)。
例如,这是一个包含两列对象类型的 DataFrame。一个保存实际整数,另一个保存表示整数的字符串:
>>> df = pd.DataFrame({'a': [7, 1, 5], 'b': ['3','2','1']}, dtype='object')
>>> df.dtypes
a object
b object
dtype: object
使用infer_objects(),您可以将列'a'的类型更改为int64:
>>> df = df.infer_objects()
>>> df.dtypes
a int64
b object
dtype: object
列 'b' 被单独留下,因为它的值是字符串,而不是整数。如果你想强制两列都为整数类型,你可以改用df.astype(int)。
4。 convert_dtypes()
1.0 及更高版本包含一个方法convert_dtypes(),用于将Series 和DataFrame 列转换为支持pd.NA 缺失值的最佳dtype。
这里的“最好的”是指最适合保存值的类型。例如,这是一个pandas整数类型,如果所有的值都是整数(或缺失值):Python整数对象的一个对象列转换为Int64,NumPy的一个int32值列,将成为pandas dtype Int32.
使用我们的object DataFrame df,我们得到以下结果:
>>> df.convert_dtypes().dtypes
a Int64
b string
dtype: object
由于列 'a' 保存整数值,它被转换为 Int64 类型(它能够保存缺失值,与 int64 不同)。
“b”列包含字符串对象,因此已更改为 pandas'string dtype。
默认情况下,此方法将根据每列中的对象值推断类型。我们可以通过 infer_objects=False 来改变它:
>>> df.convert_dtypes(infer_objects=False).dtypes
a object
b string
dtype: object
现在列“a”仍然是一个对象列:pandas 知道它可以被描述为一个“整数”列(在内部它运行 infer_dtype)但没有准确推断它应该具有什么 dtype 的整数所以没有转换它。列 'b' 再次转换为 'string' dtype,因为它被识别为包含 'string' 值。