明确指定数据的类型
df.dtypes (dt.dtype是描述数组的数据类型的)
df = pd.DataFrame({'A':[1,2,3,4],
'B':[2,3,4,5]})
df.dtypes
------------------------------下面是输出结果-------------------------------
A int64
B int64
dtype: object
也可以在定义时明确地指出数据类型
df = pd.DataFrame({'A':[1,2,3,4],
'B':[2,3,4,5]},dtype=int)
df.dtypes
---------------------------------下面是输出结果-------------------------------
A int64
B int64
dtype: object
通过astype()方法强制转换数据的类型
astype(dtype, copy=True, errors='raise', ** kwargs)
dtype:表示数据的类型
copy:是否建立副本,默认为True
errors:错误采取的处理方式,可以取值为raise或ignore,默认为raise。其中,raise表示允许引发异常,ignore表示抑制异常。
df = pd.DataFrame({'A':[1,2,3,4],
'B':['1','2','3','4'],
'C':[4,5,7,'G']})
print(df.dtypes)
# 进行数据类型转换
df['B'].astype(dtype='int')
-------------------------------下面是输出结果-------------------------------
A int64
B object
C object
dtype: object
----------------------------
0 1
1 2
2 3
3 4
Name: B, dtype: int32
通过to_numeric()函数转换数据类型
astype()方法虽然可以转换数据的类型,但它存在着一些局限性,只要待转换的数据中存在数字以外的字符,在使用astype()方法进行类型转换时就会出现错误,而to_numeric()的出现正好解决了这个问题。
to_numeric()可以将传入的参数转换成数值类型。
pandas.to_numeric(arg, errors='raise', downcast=None)
arg:表示要转换的数据,可以是list,tuple,Serise
errors:错误采取的处理方式
ser_obj = pd.Series(['1','1.2','4.2'])
print(ser_obj)
# 将object类型转换为float类型
pd.to_numeric(ser_obj,errors='raise')
# raise表示允许引发异常
-------------------------------下面是输出结果-------------------------------
0 1
1 1.2
2 4.2
dtype: object
0 1.0
1 1.2
2 4.2
dtype: float64

被折叠的 条评论
为什么被折叠?



