理解 Python 中的 astype()
astype() 函数是 Python 中的一个强大方法,主要用于 pandas 库,用于将 DataFrame 或 Series 中的列或数据集转换为特定数据类型。它也可在 NumPy 中用于将数组元素转换为不同类型。
astype() 的基本用法
astype() 函数用于将 pandas 对象(如 Series 或 DataFrame)或 NumPy 数组的数据类型转换为另一种类型。
pandas 的语法:
DataFrame.astype(dtype, copy=True, errors='raise')
NumPy 语法:
ndarray.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
关键参数
1.数据类型
要将数据转换为的目标数据类型。可以使用以下方式指定:
- 单一类型(例如 float、int、str)。
- 将列名映射到类型的字典(对于 pandas DataFrames)。
2.复制(pandas 和 NumPy)
- 默认:True
- 用途:是否返回原始数据的副本(如果为True)或就地修改(如果为False)。
3.错误(仅限熊猫)
-
选项:
- 'raise'(默认):如果转换失败则引发错误。
- 'ignore':默默地忽略错误。
4.顺序(仅限 NumPy)
- 控制输出数组的内存布局。选项:
- 'C':C-连续顺序。
- 'F':Fortran 连续顺序。
- 'A':如果输入是 Fortran 连续的,则使用 Fortran 顺序,否则使用 C 顺序。
- 'K':匹配输入数组的布局。
5.铸造(仅限 NumPy)
- 控制投射行为:
- 'no':不允许转换。
- 'equiv':仅允许字节顺序更改。
- “安全”:只允许保留值的强制转换。
- 'same_kind':仅允许安全强制转换或某种类型内的强制转换(例如,float -> int)。
- '不安全':允许任何数据转换。
6. subok(仅限 NumPy)
- 如果为 True,则传递子类;如果为 False,则返回的数组将是基类数组。
示例
1. pandas 的基本转换
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
2.多列的字典映射
# Convert multiple columns df = df.astype({'A': float, 'B': int}) print(df.dtypes)
输出:
DataFrame.astype(dtype, copy=True, errors='raise')
3.使用错误='忽略'
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)
- “two”的转换失败,但不会引发错误。
4.在 NumPy 中使用 astype()
A int64 B float64 dtype: object
输出:
# Convert multiple columns df = df.astype({'A': float, 'B': int}) print(df.dtypes)
5.在 NumPy 中使用casting='safe'进行铸造
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)
6.处理 pandas 中的非数字类型
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)
7.使用 astype() 进行内存优化
代码:
[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)。
高级示例
1.复杂数据类型转换
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())
2.在 NumPy 中使用 astype() 来处理结构化数组
Index 128 A 24 B 24 dtype: int64
输出:
DataFrame.astype(dtype, copy=True, errors='raise')
总结
astype() 函数是 pandas 和 NumPy 中数据类型转换的多功能工具。它允许对转换行为、内存优化和错误处理进行细粒度控制。正确使用其参数(例如 pandas 中的错误和 NumPy 中的转换)可确保稳健且高效的数据类型转换。
以上是Python 中的 astype() 函数是什么的详细内容。更多信息请关注PHP中文网其他相关文章!

pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)他们areStoredIncoNtiguulMemoryBlocks,mayrequireRealLealLocationWhenAppendingItems,EmpactingPerformance.2)LinkesedlistSwoldOfferefeRefeRefeRefeRefficeInsertions/DeletionsButslowerIndexeDexedAccess,Lestpypytypypytypypytypy

pythonoffersFourmainMethodStoreMoveElement Fromalist:1)删除(值)emovesthefirstoccurrenceofavalue,2)pop(index)emovesanderturnsanelementataSpecifiedIndex,3)delstatementremoveselemsbybybyselementbybyindexorslicebybyindexorslice,and 4)

toresolvea“ dermissionded”错误Whenrunningascript,跟随台词:1)CheckAndAdjustTheScript'Spermissions ofchmod xmyscript.shtomakeitexecutable.2)nesureThEseRethEserethescriptistriptocriptibationalocatiforecationAdirectorywherewhereyOuhaveWritePerMissionsyOuhaveWritePermissionsyYouHaveWritePermissions,susteSyAsyOURHomeRecretectory。

ArraysarecrucialinPythonimageprocessingastheyenableefficientmanipulationandanalysisofimagedata.1)ImagesareconvertedtoNumPyarrays,withgrayscaleimagesas2Darraysandcolorimagesas3Darrays.2)Arraysallowforvectorizedoperations,enablingfastadjustmentslikebri

ArraySaresificatificallyfasterthanlistsForoperationsBenefiting fromDirectMemoryAcccccccCesandFixed-Sizestructures.1)conscessingElements:arraysprovideconstant-timeaccessduetocontoconcotigunmorystorage.2)iteration:araysleveragececacelocality.3)

ArraySareBetterForlement-WiseOperationsDuetofasterAccessCessCessCessCessCessAndOptimizedImplementations.1)ArrayshaveContiguucuulmemoryfordirectAccesscess.2)列出sareflexible butslible dueTopotentEnallymideNamicizing.3)forlarargedAtaTasetsetsetsetsetsetsetsetsetsetsetlib

在NumPy中进行整个数组的数学运算可以通过向量化操作高效实现。 1)使用简单运算符如加法(arr 2)可对数组进行运算。 2)NumPy使用C语言底层库,提升了运算速度。 3)可以进行乘法、除法、指数等复杂运算。 4)需注意广播操作,确保数组形状兼容。 5)使用NumPy函数如np.sum()能显着提高性能。

在Python中,向列表插入元素有两种主要方法:1)使用insert(index,value)方法,可以在指定索引处插入元素,但在大列表开头插入效率低;2)使用append(value)方法,在列表末尾添加元素,效率高。对于大列表,建议使用append()或考虑使用deque或NumPy数组来优化性能。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

禅工作室 13.0.1
功能强大的PHP集成开发环境

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

Dreamweaver CS6
视觉化网页开发工具

Atom编辑器mac版下载
最流行的的开源编辑器

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)