pandas series astype() 方法如何工作?


在pandas series中,astype()方法用於轉換pandas series物件的型別。astype()方法將返回具有轉換後的資料型別的系列物件。

在pandas.Series中使用此astype()方法,我們可以將系列物件的datatype轉換為指定的資料型別,要實現此目的,我們需要將numpy.dtype或Python型別作為引數傳送給astype()方法。

示例 1

# importing required packages
import pandas as pd

# create a pandas Series object
series = pd.Series([1,2,4,3,1,2])
print(series)

result = series.astype('category')
print("Output: ",result)

說明

在此示例中,我們使用一個整數值列表初始化一個pandas series物件。之後,我們應用astype()方法,其中引數值為“類別”。

輸出

0 1
1 2
2 4
3 3
4 1
5 2
dtype: int64

Output:
0 1
1 2
2 4
3 3
4 1
5 2
dtype: category
Categories (4, int64): [1, 2, 3, 4]

在此輸出塊中,我們可以看到初始系列物件的資料型別為int64,以及astype()方法輸出了轉換後的資料型別。結果系列物件的資料型別為類別。結果系列物件中有 4 個分類值。

示例 2

# importing required packages
import pandas as pd
import numpy as np

# creating pandas Series object
series = pd.Series(np.random.randint(1,20,5))
print(series)

# change the astype
result = series.astype('float64')
print("Output: ",result)

說明

使用範圍為 1、20、5 的隨機整數值建立另一個熊貓系列物件。此處目標是將原始系列物件的資料型別轉換為“float64”型別,以便將 astype() 方法應用於具有“float64”引數的系列物件。

輸出

0 15
1  2
2 10
3  1
4 15
dtype: int32

Output:
0 15.0
1  2.0
2 10.0
3  1.0
4 15.0
dtype: float64

對於原始系列物件,dtype 為“int32”,而轉換後的系列物件具有 float64 資料型別。

更新於: 2022-03-09

225 views

開啟你的職業生涯

獲得課程認證

開始
廣告