如何在Pandas中自動轉換為最佳資料型別?
Pandas是Python中一個流行的資料處理庫,用於資料清洗和轉換。它提供了各種轉換資料型別的方法,例如`astype()`方法。但是,手動轉換資料型別可能非常耗時且容易出錯。
為了解決這個問題,Pandas在1.0版本中引入了一個新功能`convert_dtypes()`,它允許根據列中的資料自動將列轉換為最適合的資料型別。此功能無需手動型別轉換,並確保資料格式正確。
轉換Pandas Series的資料型別
請考慮以下程式碼,我們將轉換Pandas Series的資料型別。
示例
import pandas as pd
# Create a Series with mixed data types
data = pd.Series(['1', '2', '3.1', '4.0', '5'])
# Print the data types of the Series
print("Original data types:")
print(data.dtypes)
# Convert the Series to the best data type automatically
data = pd.to_numeric(data, errors='coerce')
# Print the data types of the Series after conversion
print("\nNew data types:")
print(data.dtypes)
# Print the updated Series
print("\nUpdated Series:")
print(data)
解釋
使用`import`語句匯入Pandas庫。
建立一個名為`data`的Pandas Series,其中包含混合資料型別,包括整數和字串。
使用`dtypes`屬性列印Series的原始資料型別。
使用`pd.to_numeric()`方法自動將Series轉換為最佳資料型別。
將`errors`引數的值設定為`'coerce'`,以強制將任何無效值轉換為NaN。
使用`dtypes`屬性列印Series的新資料型別。
列印更新後的Series。
要執行以上程式碼,我們需要執行以下命令。
命令
python3 main.py
輸出
Original data types: object New data types: float64 Updated Series: 0 1.0 1 2.0 2 3.1 3 4.0 4 5.0 dtype: float64
轉換Pandas DataFrame的資料型別
請考慮以下程式碼
示例
import pandas as pd
# create a sample dataframe with mixed data types
data = {'name': ['John', 'Marry', 'Peter', 'Jane', 'Paul'],
'age': [25, 30, 40, 35, 27],
'gender': ['Male', 'Female', 'Male', 'Female', 'Male'],
'income': ['$500', '$1000', '$1200', '$800', '$600']}
df = pd.DataFrame(data)
# print the original data types of the dataframe
print("Original data types:\n", df.dtypes)
# convert 'age' column to float
df['age'] = df['age'].astype(float)
# convert 'income' column to integer by removing the dollar sign
df['income'] = df['income'].str.replace('$', '').astype(int)
# print the new data types of the dataframe
print("\nNew data types:\n", df.dtypes)
print("\nDataFrame after conversion:\n", df)
解釋
首先,我們匯入必要的庫:Pandas。
我們建立一個包含混合資料型別的示例DataFrame,包括物件、int64和字串值。
我們使用`dtypes`屬性列印DataFrame的原始資料型別。
我們使用`astype()`方法將'age'列轉換為浮點數,這會將列資料型別轉換為指定型別。
我們使用`str.replace()`方法去除美元符號,然後使用`astype()`方法將'income'列轉換為整數。
我們使用`dtypes`屬性列印DataFrame的新資料型別,以確認資料型別轉換。
最後,我們列印整個DataFrame以檢視轉換後的資料型別。
注意:`astype()`方法用於將Series轉換為指定的資料型別,而DataFrame的`astype()`方法用於轉換多個列的資料型別。
輸出
Original data types:
name object
age int64
gender object
income object
dtype: object
New data types:
name object
age float64
gender object
income int64
dtype: object
DataFrame after conversion:
name age gender income
0 John 25.0 Male 500
1 Marry 30.0 Female 1000
2 Peter 40.0 Male 1200
3 Jane 35.0 Female 800
4 Paul 27.0 Male 600
結論
總之,轉換資料型別是資料分析和處理中一項重要的任務。Pandas為我們提供了各種轉換資料型別的方法,例如在載入資料時指定資料型別,使用`astype()`方法轉換Series或DataFrame,以及使用`infer_objects()`方法自動檢測每列的最佳資料型別。
為每列選擇合適的資料型別對於最佳化記憶體使用和提高資料分析效能至關重要。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP