pandas 處理什麼類型的資料?#
我想開始使用 pandas
In [1]: import pandas as pd
若要載入 pandas 套件並開始使用,請匯入套件。社群同意的 pandas 別名為
pd
,因此將 pandas 載入為pd
被假設為所有 pandas 文件的標準做法。
pandas 資料表表示#
我想儲存鐵達尼號的乘客資料。對於許多乘客,我知道姓名(字元)、年齡(整數)和性別(男性/女性)資料。
In [2]: df = pd.DataFrame( ...: { ...: "Name": [ ...: "Braund, Mr. Owen Harris", ...: "Allen, Mr. William Henry", ...: "Bonnell, Miss. Elizabeth", ...: ], ...: "Age": [22, 35, 58], ...: "Sex": ["male", "male", "female"], ...: } ...: ) ...: In [3]: df Out[3]: Name Age Sex 0 Braund, Mr. Owen Harris 22 male 1 Allen, Mr. William Henry 35 male 2 Bonnell, Miss. Elizabeth 58 female
若要手動將資料儲存在表格中,請建立
DataFrame
。當使用 Python 字典清單時,字典金鑰將用作欄位標頭,而每個清單中的值則用作DataFrame
的欄位。
DataFrame
是一個 2 維資料結構,可以在欄位中儲存不同類型的資料(包括字元、整數、浮點值、分類資料等)。它類似於試算表、SQL 表格或 R 中的 data.frame
。
表格有 3 個欄位,每個欄位都有欄位標籤。欄位標籤分別為
Name
、Age
和Sex
。欄位
Name
包含文字資料,每個值都是字串,欄位Age
是數字,而欄位Sex
是文字資料。
在試算表軟體中,資料的表格表示法看起來會非常類似

DataFrame
中的每個欄位都是 Series
#
我只對處理欄位
Age
中的資料有興趣In [4]: df["Age"] Out[4]: 0 22 1 35 2 58 Name: Age, dtype: int64
選取 pandas
DataFrame
的單一欄位時,結果會是 pandasSeries
。若要選取欄位,請在方括號[]
中間使用欄位標籤。
注意
如果您熟悉 Python 字典,則選取單一欄位與根據鍵選取字典值非常類似。
您也可以從頭建立 Series
In [5]: ages = pd.Series([22, 35, 58], name="Age")
In [6]: ages
Out[6]:
0 22
1 35
2 58
Name: Age, dtype: int64
pandas Series
沒有欄位標籤,因為它只是 DataFrame
的單一欄位。Series 有列標籤。
使用 DataFrame 或 Series 執行某項操作#
我想知道乘客的最大年齡
我們可以在
DataFrame
中選取Age
欄位並套用max()
來執行此操作In [7]: df["Age"].max() Out[7]: 58
或套用至
Series
In [8]: ages.max() Out[8]: 58
如 max()
方法所示,您可以對 DataFrame
或 Series
執行 某項操作。pandas 提供許多功能,每個功能都是您可以套用至 DataFrame
或 Series
的 方法。由於方法是函數,請記得使用括號 ()
。
我對資料表的數值資料的一些基本統計資料感興趣
In [9]: df.describe() Out[9]: Age count 3.000000 mean 38.333333 std 18.230012 min 22.000000 25% 28.500000 50% 35.000000 75% 46.500000 max 58.000000
方法
describe()
提供DataFrame
中數值資料的快速概觀。由於Name
和Sex
欄位是文字資料,因此方法describe()
預設不會將這些欄位納入考量。
許多 pandas 作業會傳回 DataFrame
或 Series
。方法 describe()
是 pandas 作業傳回 pandas Series
或 pandas DataFrame
的範例。
在使用者指南有關 使用 describe 進行聚合 的章節中,查看 describe
的更多選項。
注意
這只是一個起點。與試算表軟體類似,pandas 將資料表示為有欄和列的表格。除了表示方式外,pandas 也支援試算表軟體中會進行的資料處理和計算。繼續閱讀後續教學課程,開始學習!
請記住
匯入套件,亦即
import pandas as pd
資料表格儲存在 pandas
DataFrame
中在
DataFrame
中的每個欄位都是Series
您可以透過將方法套用至
DataFrame
或Series
來執行操作
有關 DataFrame
和 Series
的更詳細說明,請參閱 資料結構簡介。