Pandas DataFrame 的轉換函式
Pandas 是 Python 中功能最強大的庫之一,它提供高效能的資料操作和分析工具,允許我們使用 DataFrame 處理表格資料,例如電子表格、CSV 和 SQL 資料。
DataFrame 是一種二維帶標籤的資料結構,它以行和列的形式表示資料。每一列中的資料可以具有不同的資料型別。
DataFrame: Integers Floats Strings Dates 0 1.0 1.300 p 2023-05-07 1 2.0 NaN y 2023-05-14 2 5.0 4.600 t 2023-05-21 3 3.0 1.020 h 2023-05-28 4 6.0 0.300 o 2023-06-04 5 NaN 0.001 n 2023-06-11
上面展示的 DataFrame 有 6 行 4 列,每一行中的資料具有不同的資料型別。
而**轉換函式**用於轉換 DataFrame 物件中元素的資料型別。在本文中,我們將討論 Pandas DataFrame 中不同的型別轉換函式。
輸入輸出場景
讓我們看看輸入輸出場景,瞭解如何使用轉換函式進行型別轉換。
假設我們有一個包含幾列不同資料型別的 DataFrame,在輸出中,我們將看到一個列資料型別已更新的 DataFrame。
Input DataFrame: ints strs ints2 floats 0 1 x 10.0 NaN 1 2 y NaN 100.5 2 3 NaN 20.0 200.0 Data Types of the each column is: ints int64 strs object ints2 float64 floats float64 Output DataFrame: ints strs ints2 floats 0 1 x 10 <NA> 1 2 y <NA> 100.5 2 3 <NA> 20 200.0 Data Types of the resultant DataFrame is: ints Int64 strs string ints2 Int64 floats Float64
DataFrame.convert_dtypes() 函式
pandas DataFrame.convert_dtypes() 函式用於使用支援 pd.NA 的 dtypes 將列的資料型別轉換為最佳可能的型別,並返回一個具有更新 dtypes 的新的 DataFrame 物件。
語法
DataFrame.convert_dtypes(infer_objects=True, convert_string=True, convert_integer=True, convert_boolean=True, convert_floating=True)
引數
所有引數的預設值為 True。這些都指示是否應將物件 dtypes 轉換為最佳可能的型別。
示例
在這個例子中,我們將使用 .convert_dtypes() 方法轉換 DataFrame 列的資料型別。
import pandas as pd
import numpy as np
df = pd.DataFrame({"a":[1, 2, 3],
"b": ["x", "y", "z"],
"c": [True, False, np.nan],
"d": ["h", "i", np.nan],
"e": [10, np.nan, 20],
"f": [np.nan, 100.5, 200]})
print("Input DataFrame:")
print(df)
print('Data Types of the each column is: ')
print(df.dtypes)
# Convert the data type of columns
result = df.convert_dtypes()
print("Output DataFrame:")
print(result)
print('Data Types of the resultant DataFrame is: ')
print(result.dtypes)
輸出
Input DataFrame: a b c d e f 0 1 x True h 10.0 NaN 1 2 y False i NaN 100.5 2 3 z NaN NaN 20.0 200.0 Data Types of the each column is: a int64 b object c object d object e float64 f float64 dtype: object Output DataFrame: a b c d e f 0 1 x True h 101 2 y False i 100.5 2 3 z 20 200.0 Data Types of the resultant DataFrame is: a Int64 b string c boolean d string e Int64 f Float64 dtype: object
首先,我們使用 dtypes() 方法檢查 DataFrame 列的資料型別。然後,使用 convert_dtypes() 方法將列“b”的資料型別轉換為字串,將“c”轉換為布林值,“d”轉換為字串,將“e”轉換為 int64。
DataFrame.astype() 函式
pandas DataFrame.astype() 函式用於將 pandas 物件的資料型別轉換為指定的 dtype。以下是語法:
DataFrame.astype(dtype, copy, errors)
引數
dtype:資料型別,或 dict {col: dtype, …},其中 col 是列標籤,dtype 是要將 DataFrame 的一個或多個列轉換為特定資料型別的 numpy.dtype 或 Python 型別。
copy:預設值為 True,是否在原始 DataFrame (False) 中進行更改或建立副本 (True)。
errors:預設值為 'raise'。是在錯誤時忽略錯誤還是引發異常。
示例
在這個例子中,我們將使用 astype() 函式將所有列的資料型別轉換為物件型別。
import pandas as pd
df = pd.DataFrame({'Integers':[1, 2, 5, 3, 6, 0],
'Floats': [1.3, None, 4.6, 1.02, 0.3, 0.001],
'Strings': ['p', 'y', 't', 'h', 'o', 'n'],
'Dates': pd.date_range('2023-05-04', periods=6, freq='W')})
print("Input DataFrame:")
print(df)
print('Data Types of each column is: ')
print(df.dtypes)
# Convert the data type of columns
result = df.astype('object')
print("Output DataFrame:")
print(result)
print('Data Types of the resultant DataFrame is: ')
print(result.dtypes)
輸出
Input DataFrame: Integers Floats Strings Dates 0 1 1.300 p 2023-05-07 1 2 NaN y 2023-05-14 2 5 4.600 t 2023-05-21 3 3 1.020 h 2023-05-28 4 6 0.300 o 2023-06-04 5 0 0.001 n 2023-06-11 Data Types of each column is: Integers int64 Floats float64 Strings object Dates datetime64[ns] dtype: object Output DataFrame: Integers Floats Strings Dates 0 1 1.3 p 2023-05-07 00:00:00 1 2 NaN y 2023-05-14 00:00:00 2 5 4.6 t 2023-05-21 00:00:00 3 3 1.02 h 2023-05-28 00:00:00 4 6 0.3 o 2023-06-04 00:00:00 5 0 0.001 n 2023-06-11 00:00:00 Data Types of the resultant DataFrame is: Integers object Floats object Strings object Dates object dtype: object
所有列的資料型別都轉換為物件型別。
示例
讓我們再舉一個例子,使用字典轉換幾列的 dtype。
import pandas as pd
df = pd.DataFrame({'Integers':[1, 2, 5, 3, 6, 0],
'Floats': [1.3, None, 4.6, 1.02, 0.3, 0.001],
'Strings': ['p', 'y', 't', 'h', 'o', 'n'],
'Dates': pd.date_range('2023-05-04', periods=6, freq='W')})
print("Input DataFrame:")
print(df)
print('Data Types of each column is: ')
print(df.dtypes)
# Convert the data type of columns
result = df.astype({'Floats':'object', 'Strings': 'category'})
print("Output DataFrame:")
print(result)
print('Data Types of the resultant DataFrame is: ')
print(result.dtypes)
輸出
Input DataFrame: Integers Floats Strings Dates 0 1 1.300 p 2023-05-07 1 2 NaN y 2023-05-14 2 5 4.600 t 2023-05-21 3 3 1.020 h 2023-05-28 4 6 0.300 o 2023-06-04 5 0 0.001 n 2023-06-11 Data Types of each column is: Integers int64 Floats float64 Strings object Dates datetime64[ns] dtype: object Output DataFrame: Integers Floats Strings Dates 0 1 1.3 p 2023-05-07 1 2 NaN y 2023-05-14 2 5 4.6 t 2023-05-21 3 3 1.02 h 2023-05-28 4 6 0.3 o 2023-06-04 5 0 0.001 n 2023-06-11 Data Types of the resultant DataFrame is: Integers int64 Floats object Strings category Dates datetime64[ns] dtype: object
浮點數和字串列被轉換為物件和類別 dtype。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP