Python 3.x Python基于数据类型转换数据
我创建了一个熊猫系列,如下所示:Python 3.x Python基于数据类型转换数据,python-3.x,pandas,Python 3.x,Pandas,我创建了一个熊猫系列,如下所示: txt = pd.Series(['1', '2', '3', '4', '5', ""]) print(txt) 结果: 0 1 1 2 2 3 3 4 4 5 5 dtype: object 找出每个项目的类型,并给我“str”作为结果 type(txt[0]) type(txt[5]) 尝试使用.astype()将每个项转换为“int”类型,但失败 txt.astype('int') V
txt = pd.Series(['1', '2', '3', '4', '5', ""])
print(txt)
结果:
0 1
1 2
2 3
3 4
4 5
5
dtype: object
找出每个项目的类型,并给我“str”作为结果
type(txt[0])
type(txt[5])
尝试使用.astype()将每个项转换为“int”类型,但失败
txt.astype('int')
ValueError: invalid literal for int() with base 10: ''
尝试使用自定义函数将每个项转换为“int”类型,但出现错误
txt.apply(lambda num: int(num))
ValueError: invalid literal for int() with base 10: ''
有人请告诉我如何在这种情况下进行数据类型转换。我的计划是创建两个熊猫系列,并对这两个系列执行数学运算。使用
到\u numeric
:
import pandas as pd
txt = pd.Series(['1', '2', '3', '4', '5', ""])
print(txt)
print(txt.dtypes)
txt_int = pd.to_numeric(txt, errors='coerce').astype('Int64')
print(txt_int)
print(txt_int.dtypes)
输出:
0 1
1 2
2 3
3 4
4 5
5
dtype: object
object
0 1
1 2
2 3
3 4
4 5
5 <NA>
dtype: Int64
Int64
01
1 2
2 3
3 4
4 5
5.
数据类型:对象
对象
0 1
1 2
2 3
3 4
4 5
5.
数据类型:Int64
Int64
提示:不能将空的str
转换为typeint
使用pd.to\u numeric(txt,errors='concurve')。astype('Int64')