pandas.to_numeric转化数据为数字型

简介:
to_numeric(arg, errors='raise', downcast=None)
    Convert argument to a numeric type.
    
    Parameters
    ----------
    arg : list, tuple, 1-d array, or Series
    errors : {'ignore', 'raise', 'coerce'}, default 'raise'
        - If 'raise', then invalid parsing will raise an exception
        - If 'coerce', then invalid parsing will be set as NaN
        - If 'ignore', then invalid parsing will return the input
    downcast : {'integer', 'signed', 'unsigned', 'float'} , default None
        If not None, and if the data has been successfully cast to a
        numerical dtype (or if the data was numeric to begin with),
        downcast that resulting data to the smallest numerical dtype
        possible according to the following rules:
    
        - 'integer' or 'signed': smallest signed int dtype (min.: np.int8)
        - 'unsigned': smallest unsigned int dtype (min.: np.uint8)
        - 'float': smallest float dtype (min.: np.float32)
    
        As this behaviour is separate from the core conversion to
        numeric values, any errors raised during the downcasting
        will be surfaced regardless of the value of the 'errors' input.
    
        In addition, downcasting will only occur if the size
        of the resulting data's dtype is strictly larger than
        the dtype it is to be cast to, so if none of the dtypes
        checked satisfy that specification, no downcasting will be
        performed on the data.
    
        .. versionadded:: 0.19.0
    
    Returns
    -------
    ret : numeric if parsing succeeded.
        Return type depends on input.  Series if Series, otherwise ndarray
    
    Examples
    --------
    Take separate series and convert to numeric, coercing when told to
    
    >>> import pandas as pd
    >>> s = pd.Series(['1.0', '2', -3])
    >>> pd.to_numeric(s)
    0    1.0
    1    2.0
    2   -3.0
    dtype: float64
    >>> pd.to_numeric(s, downcast='float')
    0    1.0
    1    2.0
    2   -3.0
    dtype: float32
    >>> pd.to_numeric(s, downcast='signed')
    0    1
    1    2
    2   -3
    dtype: int8
    >>> s = pd.Series(['apple', '1.0', '2', -3])
    >>> pd.to_numeric(s, errors='ignore')
    0    apple
    1      1.0
    2        2
    3       -3
    dtype: object
    >>> pd.to_numeric(s, errors='coerce')
    0    NaN
    1    1.0
    2    2.0
    3   -3.0
    dtype: float64
    
    See also
    --------
    pandas.DataFrame.astype : Cast argument to a specified dtype.
    pandas.to_datetime : Convert argument to datetime.
    pandas.to_timedelta : Convert argument to timedelta.
    numpy.ndarray.astype : Cast a numpy array to a specified type.
目录
相关文章
|
2月前
|
Python
如何使用Python的Pandas库进行数据透视图(melt/cast)操作?
Pandas的`melt()`和`pivot()`函数用于数据透视。基本步骤:导入pandas,创建DataFrame,然后使用这两个函数变换数据。示例代码:导入pandas,定义一个包含'Name'和'Age'列的DataFrame,使用`melt()`转为长格式,再用`pivot()`恢复为宽格式。
60 1
|
2月前
|
数据处理 Python
如何使用Python的Pandas库进行数据排序和排名
【4月更文挑战第22天】Pandas Python库提供数据排序和排名功能。使用`sort_values()`按列进行升序或降序排序,如`df.sort_values(by='A', ascending=False)`。`rank()`函数用于计算排名,如`df['A'].rank(ascending=False)`。多列操作可传入列名列表,如`df.sort_values(by=['A', 'B'], ascending=[True, False])`和分别对'A'、'B'列排名。
40 2
|
2月前
|
存储 Python
使用Pandas库对非数值型数据进行排序和排名
在Pandas中,支持对非数值型数据排序和排名。可按以下方法操作:1) 字符串排序,使用`sort_values()`,如`sorted_df = df.sort_values(by='Name', ascending=False)`进行降序排序;2) 日期排序,先用`to_datetime()`转换,再排序,如`sorted_df = df.sort_values(by='Date')`;3) 自定义排序,结合`argsort()`和自定义规则。
44 2
|
2月前
|
索引 Python
如何使用Python的Pandas库进行数据合并和拼接?
Pandas的`merge()`函数用于数据合并,如示例所示,根据'key'列对两个DataFrame执行内连接。`concat()`函数用于数据拼接,沿轴0(行)拼接两个DataFrame,并忽略原索引。
63 2
|
2月前
|
数据挖掘 索引 Python
如何在Python中,Pandas库实现对数据的时间序列分析?
【4月更文挑战第21天】Pandas在Python中提供了丰富的时间序列分析功能,如创建时间序列`pd.date_range()`,转换为DataFrame,设置时间索引`set_index()`,重采样`resample()`(示例:按月`'M'`和季度`'Q'`),移动窗口计算`rolling()`(如3个月移动平均)以及季节性调整`seasonal_decompose()`。这些工具适用于各种时间序列数据分析任务。
34 2
|
2月前
|
存储 JSON 数据处理
从JSON数据到Pandas DataFrame:如何解析出所需字段
从JSON数据到Pandas DataFrame:如何解析出所需字段
107 1
|
2天前
|
存储 消息中间件 数据挖掘
Python实时数据分析:利用丰富的库(如Pandas, PySpark, Kafka)进行流处理,涵盖数据获取、预处理、处理、存储及展示。
【7月更文挑战第5天】Python实时数据分析:利用丰富的库(如Pandas, PySpark, Kafka)进行流处理,涵盖数据获取、预处理、处理、存储及展示。示例代码展示了从Kafka消费数据,计算社交媒体活跃度和物联网设备状态,并可视化结果。适用于监控、故障检测等场景。通过学习和实践,提升实时数据分析能力。
8 0
|
2天前
|
机器学习/深度学习 数据可视化 搜索推荐
Python在社交媒体分析中扮演关键角色,借助Pandas、NumPy、Matplotlib等工具处理、可视化数据及进行机器学习。
【7月更文挑战第5天】Python在社交媒体分析中扮演关键角色,借助Pandas、NumPy、Matplotlib等工具处理、可视化数据及进行机器学习。流程包括数据获取、预处理、探索、模型选择、评估与优化,以及结果可视化。示例展示了用户行为、话题趋势和用户画像分析。Python的丰富生态使得社交媒体洞察变得高效。通过学习和实践,可以提升社交媒体分析能力。
10 0
|
2天前
|
数据采集 数据挖掘 大数据
Pandas是Python数据分析的核心库,基于NumPy,提供DataFrame结构处理结构化数据
【7月更文挑战第5天】Pandas是Python数据分析的核心库,基于NumPy,提供DataFrame结构处理结构化数据。它支持缺失值处理(dropna()、fillna())、异常值检测(Z-Score、IQR法)和重复值管理(duplicated()、drop_duplicates())。此外,数据转换包括类型转换(astype())、数据标准化(Min-Max、Z-Score)以及类别编码(get_dummies())。这些功能使得Pandas成为大数据预处理的强大工具。