Pandas DataFrame.to_numeric()函数
Python Pandas DataFrame.to_numeric() 函数将传递的参数转换为数字类型。
pandas.DataFrame.to_numeric()
的语法
DataFrame.to_numeric(arg, errors="raise", downcast=None)
参数
arg |
它是一个标量、列表、元组、一维数组或 Series 。它是我们要转换为数值的参数。 |
errors |
它是一个字符串参数。它有三个选项。ignore 、raise 或 coerce 。如果它被设置为 raise ,那么一个无效的参数将引发一个异常。如果设置为 coerce ,那么一个无效的参数将被设置为 NaN。如果设置为 ignore ,那么一个无效的参数将返回输入。 |
downcast |
它是一个字符串参数。它有四个选项:integer 、signed 、unsigned 或 float 。 |
返回值
如果解析成功,它将返回一个数值。如果传递了一个系列,那么它将返回一个系列;否则,它将返回 ndarray
。
示例代码:DataFrame.to_numeric()
方法将一个 Series
转换为数值
import pandas as pd
series = pd.Series(['1.0', '2', '-3', '4', '5.5', '6.7'])
print("The Original Series is: \n")
print(series)
series1 = pd.to_numeric(series)
print("The Numeric Series is: \n")
print(series1)
输出:
The Original Series is:
0 1.0
1 2
2 -3
3 4
4 5.5
5 6.7
dtype: object
The Numeric Series is:
0 1.0
1 2.0
2 -3.0
3 4.0
4 5.5
5 6.7
dtype: float64
函数返回数值 Series
示例代码:DataFrame.to_numeric()
将一个 Series
转换为整数的方法
import pandas as pd
series = pd.Series(['1.0', '2', '-3', '4', '5', '6'])
print("The Original Series is: \n")
print(series)
series1 = pd.to_numeric(series, downcast='signed')
print("The Numeric Series is: \n")
print(series1)
输出:
The Original Series is:
0 1.0
1 2
2 -3
3 4
4 5
5 6
dtype: object
The Numeric Series is:
0 1
1 2
2 -3
3 4
4 5
5 6
dtype: int8
函数返回 int8 型 Series
。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串