Python中辨析type/dtype/astype用法
阿新 • • 發佈:2018-11-08
Python中與資料型別相關函式及屬性有如下三個:type/dtype/astype。
名稱 | 描述 |
---|---|
type() | 返回引數的資料型別 |
dtype | 返回陣列中元素的資料型別 |
astype() | 對資料型別進行轉換 |
- type()用於獲取資料型別
#type用於獲取資料型別
import numpy as np
a=[1,2,3]
print(type(a))
#>>><class 'list'>
b=np.array(a)
print(type(b))
#>>><class 'numpy.ndarray'>
- dtype用於獲取陣列中元素的型別
#dtype用於獲取陣列中元素的型別
print(b.dtype)
#>>>int64
x,y,z=1,2,3
c=np.array([x,y,z])
print(c.dtype)
#>>>int64
d=np.array([1+2j,2+3j,3+4j])
print(d.dtype)
#>>>complex128
- astype()修改資料型別
Array中用法
#astype修改資料型別
e=np.linspace(1,5,20)
print(e)
#>>>
'''
[1. 1.21052632 1.42105263 1.63157895 1.84210526 2.05263158
2.26315789 2.47368421 2.68421053 2.89473684 3.10526316 3.31578947
3.52631579 3.73684211 3.94736842 4.15789474 4.36842105 4.57894737
4.78947368 5. ]
'''
print(e.dtype)
#>>>float64
e=e.astype(int)
print(e)
#>>>[1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 5]
print(e.dtype)
#>>>int64
Dataframe中用法:轉換指定欄位資料的型別
import pandas as pd
e=np.linspace(1,5,20)
edf=pd.DataFrame(e)
edf[0].head(3)
#>>>
0 1.000000
1 1.210526
2 1.421053
Name: 0, dtype: float64
print(edf[0].dtype)
#>>>float64
edf[0]=edf[0].astype(int)
edf[0].head(3)
#>>>
0 1
1 1
2 1
Name: 0, dtype: int64
print(edf[0].dtype)
#>>>int64