astype() 函数是 Python 中的一个强大方法,主要用于 pandas 库,用于将 DataFrame 或 Series 中的列或数据集转换为特定数据类型。它也可在 NumPy 中用于将数组元素转换为不同类型。
astype() 函数用于将 pandas 对象(如 Series 或 DataFrame)或 NumPy 数组的数据类型转换为另一种类型。
DataFrame.astype(dtype, copy=True, errors='raise')
ndarray.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
要将数据转换为的目标数据类型。可以使用以下方式指定:
import pandas as pd # Example DataFrame df = pd.DataFrame({'A': ['1', '2', '3'], 'B': [1.5, 2.5, 3.5]}) # Convert column 'A' to integer df['A'] = df['A'].astype(int) print(df.dtypes)
输出:
A int64 B float64 dtype: object
# Convert multiple columns df = df.astype({'A': float, 'B': int}) print(df.dtypes)
输出:
DataFrame.astype(dtype, copy=True, errors='raise')
ndarray.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
输出:
import pandas as pd # Example DataFrame df = pd.DataFrame({'A': ['1', '2', '3'], 'B': [1.5, 2.5, 3.5]}) # Convert column 'A' to integer df['A'] = df['A'].astype(int) print(df.dtypes)
A int64 B float64 dtype: object
输出:
# Convert multiple columns df = df.astype({'A': float, 'B': int}) print(df.dtypes)
A float64 B int64 dtype: object
输出:
df = pd.DataFrame({'A': ['1', 'two', '3'], 'B': [1.5, 2.5, 3.5]}) # Attempt conversion with errors='ignore' df['A'] = df['A'].astype(int, errors='ignore') print(df)
A B 0 1 1.5 1 two 2.5 2 3 3.5
输出:
import numpy as np # Example array arr = np.array([1.1, 2.2, 3.3]) # Convert to integer arr_int = arr.astype(int) print(arr_int)
[1 2 3]
优化前(原始内存使用情况):
arr = np.array([1.1, 2.2, 3.3]) # Attempt an unsafe conversion try: arr_str = arr.astype(str, casting='safe') except TypeError as e: print(e)
优化后(优化内存使用):
Cannot cast array data from dtype('float64') to dtype('<u32 according to the rule> <hr> <h3> <strong>说明:</strong> </h3> <ul> <li> <p><strong>原始内存使用情况:</strong></p> <ul> <li>A 列作为 int64 使用 24 个字节(每个元素 8 个字节 × 3 个元素)。</li> <li>B 列作为 float64 使用 24 个字节(每个元素 8 个字节 × 3 个元素)。</li> </ul> </li> <li> <p><strong>优化内存使用:</strong></p> <ul> <li>A 列作为 int8 使用 3 个字节(每个元素 1 个字节 × 3 个元素)。</li> <li>B 列作为 float32 使用 12 个字节(每个元素 4 个字节 × 3 个元素)。</li> </ul> </li> </ul> <h2> 使用较小的数据类型可以显着减少内存使用量,尤其是在处理大型数据集时。 </h2> <h3> <strong>常见陷阱</strong> </h3> <ol> <li> <strong>无效转换</strong>:转换不兼容的类型(例如,当存在非数字值时,将字符串转换为数字类型)。 </li> </ol> <pre class="brush:php;toolbar:false">df = pd.DataFrame({'A': ['2022-01-01', '2023-01-01'], 'B': ['True', 'False']}) # Convert to datetime and boolean df['A'] = pd.to_datetime(df['A']) df['B'] = df['B'].astype(bool) print(df.dtypes)
Errors='ignore'静默错误
:谨慎使用,因为它可能会静默地无法转换。精度损失
:从高精度类型(例如 float64)转换为低精度类型(例如 float32)。A datetime64[ns] B bool dtype: object
输出:
import pandas as pd # Original DataFrame df = pd.DataFrame({'A': [1, 2, 3], 'B': [1.1, 2.2, 3.3]}) print("Original memory usage:") print(df.memory_usage()) # Downcast numerical types df['A'] = df['A'].astype('int8') df['B'] = df['B'].astype('float32') print("Optimized memory usage:") print(df.memory_usage())
Index 128 A 24 B 24 dtype: int64
输出:
DataFrame.astype(dtype, copy=True, errors='raise')
astype() 函数是 pandas 和 NumPy 中数据类型转换的多功能工具。它允许对转换行为、内存优化和错误处理进行细粒度控制。正确使用其参数(例如 pandas 中的错误和 NumPy 中的转换)可确保稳健且高效的数据类型转换。
以上是Python 中的 astype() 函数是什么的详细内容。更多信息请关注PHP中文网其他相关文章!