Python - 選擇具有特定資料型別的列
要選擇具有特定資料型別的列,請使用select_dtypes() 方法和 include 引數。首先,建立一個包含 2 列的 DataFrame −
dataFrame = pd.DataFrame(
{
"Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'],"Roll Number": [ 5, 10, 3, 8, 2, 9, 6]
}
)現在,選擇具有各自特定資料型別的 2 列 −
column1 = dataFrame.select_dtypes(include=['object']).columns column2 = dataFrame.select_dtypes(include=['int64']).columns
示例
以下是程式碼 −
import pandas as pd
# Create DataFrame
dataFrame = pd.DataFrame(
{
"Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'],"Roll Number": [ 5, 10, 3, 8, 2, 9, 6]
}
)
print"DataFrame ...\n",dataFrame
print"\nInfo of the entire dataframe:\n"
# get the description
print(dataFrame.info())
# select columns with specific datatype
column1 = dataFrame.select_dtypes(include=['object']).columns
column2 = dataFrame.select_dtypes(include=['int64']).columns
print"Column 1 with object type = ",column1
print"Column 2 with int64 type = ",column2輸出
這將產生以下輸出 −
DataFrame ... Roll Number Student 0 5 Jack 1 10 Robin 2 3 Ted 3 8 Marc 4 2 Scarlett 5 9 Kat 6 6 John Info of the entire dataframe: <class 'pandas.core.frame.DataFrame'> RangeIndex: 7 entries, 0 to 6 Data columns (total 2 columns): Roll Number 7 non-null int64 Student 7 non-null object dtypes: int64(1), object(1) memory usage: 184.0+ bytes None Column 1 with object type = Index([u'Student'], dtype='object') Column 2 with int64 type = Index([u'Roll Number'], dtype='object')
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP