與 Stata 比較#

對於來自 Stata 的潛在使用者,此頁面旨在說明如何於 pandas 中執行不同的 Stata 作業。

如果您是 pandas 的新手,您可能想要先閱讀 10 Minutes to pandas 以熟悉此函式庫。

依慣例,我們會匯入 pandas 和 NumPy,如下所示

In [1]: import pandas as pd

In [2]: import numpy as np

資料結構#

一般用語翻譯#

pandas

Stata

DataFrame

資料集

變數

觀察

groupby

bysort

NaN

.

DataFrame#

pandas 中的 DataFrame 類似於 Stata 資料集,是一個具有標籤欄且可以是不同類型的二維資料來源。如本文檔所示,幾乎所有可以在 Stata 中套用至資料集的作業,也可以在 pandas 中完成。

Series#

Series 是表示 DataFrame 一欄的資料結構。Stata 沒有針對單一欄位設定獨立的資料結構,但一般而言,使用 Series 類似於在 Stata 中參照資料集的一欄。

索引#

每個 DataFrameSeries 都有一個 Index – 資料上的標籤。Stata 沒有完全類似的概念。在 Stata 中,資料集的列基本上是沒有標籤的,只有一個隱含的整數索引,可以使用 _n 存取。

在 pandas 中,如果沒有指定索引,預設也會使用整數索引(第一列 = 0,第二列 = 1,以此類推)。雖然使用標籤化的 IndexMultiIndex 可以進行複雜的分析,而且最終是了解 pandas 的重要部分,但為了進行此比較,我們基本上會忽略 Index,並將 DataFrame 視為一組欄位。請參閱 索引文件,以進一步了解如何有效使用 Index

複製與原地操作#

大部分的 pandas 操作會傳回 Series/DataFrame 的副本。若要讓變更「生效」,你需要指派給新變數

sorted_df = df.sort_values("col1")

或覆寫原始變數

df = df.sort_values("col1")

註解

您會看到一些方法提供 inplace=Truecopy=False 關鍵字參數

df.replace(5, inplace=True)

目前正積極討論棄用並移除 inplacecopy,適用於大多數方法(例如 dropna),但少數方法除外(包括 replace)。在寫入時複製的背景下,這兩個關鍵字都不再必要。提案可在此處找到 連結

資料輸入/輸出#

從數值建構 DataFrame#

Stata 資料集可透過在 input 陳述式後放置資料並指定欄位名稱來建構。

input x y
1 2
3 4
5 6
end

pandas DataFrame 可用許多不同的方式建構,但對於少數值,通常建議將其指定為 Python 字典,其中鍵為欄位名稱,而值為資料。

In [3]: df = pd.DataFrame({"x": [1, 3, 5], "y": [2, 4, 6]})

In [4]: df
Out[4]: 
   x  y
0  1  2
1  3  4
2  5  6

讀取外部資料#

與 Stata 類似,pandas 提供了從多種格式讀取資料的工具程式。tips 資料集位於 pandas 測試中 (csv),將用於以下許多範例。

Stata 提供 import delimited 將 csv 資料讀取至記憶體中的資料集。如果 tips.csv 檔案位於目前的作業目錄中,我們可以如下匯入。

import delimited tips.csv

pandas 方法為 read_csv(),其運作方式類似。此外,如果提供網址,它會自動下載資料集。

In [5]: url = (
   ...:     "https://raw.githubusercontent.com/pandas-dev"
   ...:     "/pandas/main/pandas/tests/io/data/csv/tips.csv"
   ...: )
   ...: 

In [6]: tips = pd.read_csv(url)

In [7]: tips
Out[7]: 
     total_bill   tip     sex smoker   day    time  size
0         16.99  1.01  Female     No   Sun  Dinner     2
1         10.34  1.66    Male     No   Sun  Dinner     3
2         21.01  3.50    Male     No   Sun  Dinner     3
3         23.68  3.31    Male     No   Sun  Dinner     2
4         24.59  3.61  Female     No   Sun  Dinner     4
..          ...   ...     ...    ...   ...     ...   ...
239       29.03  5.92    Male     No   Sat  Dinner     3
240       27.18  2.00  Female    Yes   Sat  Dinner     2
241       22.67  2.00    Male    Yes   Sat  Dinner     2
242       17.82  1.75    Male     No   Sat  Dinner     2
243       18.78  3.00  Female     No  Thur  Dinner     2

[244 rows x 7 columns]

import delimited 類似,read_csv() 可以採用多個參數來指定資料的剖析方式。例如,如果資料改為以 tab 分隔、沒有欄位名稱,且存在於目前的作業目錄中,則 pandas 指令會是

tips = pd.read_csv("tips.csv", sep="\t", header=None)

# alternatively, read_table is an alias to read_csv with tab delimiter
tips = pd.read_table("tips.csv", header=None)

pandas 也可以使用 read_stata() 函數讀取 .dta 格式的 Stata 資料集。

df = pd.read_stata("data.dta")

除了文字/csv 和 Stata 檔案,pandas 還支援其他各種資料格式,例如 Excel、SAS、HDF5、Parquet 和 SQL 資料庫。這些都是透過 pd.read_* 函式讀取。有關更多詳細資料,請參閱 IO 文件

限制輸出#

預設情況下,pandas 會將大型 DataFrame 的輸出截斷,以顯示第一列和最後一列。這可以用 變更 pandas 選項,或使用 DataFrame.head()DataFrame.tail() 來覆寫。

In [8]: tips.head(5)
Out[8]: 
   total_bill   tip     sex smoker  day    time  size
0       16.99  1.01  Female     No  Sun  Dinner     2
1       10.34  1.66    Male     No  Sun  Dinner     3
2       21.01  3.50    Male     No  Sun  Dinner     3
3       23.68  3.31    Male     No  Sun  Dinner     2
4       24.59  3.61  Female     No  Sun  Dinner     4

Stata 中的等效方式為

list in 1/5

匯出資料#

Stata 中 import delimited 的反向操作是 export delimited

export delimited tips2.csv

類似地,在 pandas 中,read_csv 的反向操作是 DataFrame.to_csv()

tips.to_csv("tips2.csv")

pandas 也可以使用 DataFrame.to_stata() 方法匯出為 Stata 檔案格式。

tips.to_stata("tips2.dta")

資料操作#

欄位的操作#

在 Stata 中,任意數學運算式可用於 generatereplace 指令,針對新欄位或現有欄位。 drop 指令會從資料集中刪除欄位。

replace total_bill = total_bill - 2
generate new_bill = total_bill / 2
drop new_bill

pandas 透過指定 DataFrame 中的個別 Series 來提供向量化操作。新欄位可以同樣的方式指派。 DataFrame.drop() 方法會從 DataFrame 中刪除欄位。

In [9]: tips["total_bill"] = tips["total_bill"] - 2

In [10]: tips["new_bill"] = tips["total_bill"] / 2

In [11]: tips
Out[11]: 
     total_bill   tip     sex smoker   day    time  size  new_bill
0         14.99  1.01  Female     No   Sun  Dinner     2     7.495
1          8.34  1.66    Male     No   Sun  Dinner     3     4.170
2         19.01  3.50    Male     No   Sun  Dinner     3     9.505
3         21.68  3.31    Male     No   Sun  Dinner     2    10.840
4         22.59  3.61  Female     No   Sun  Dinner     4    11.295
..          ...   ...     ...    ...   ...     ...   ...       ...
239       27.03  5.92    Male     No   Sat  Dinner     3    13.515
240       25.18  2.00  Female    Yes   Sat  Dinner     2    12.590
241       20.67  2.00    Male    Yes   Sat  Dinner     2    10.335
242       15.82  1.75    Male     No   Sat  Dinner     2     7.910
243       16.78  3.00  Female     No  Thur  Dinner     2     8.390

[244 rows x 8 columns]

In [12]: tips = tips.drop("new_bill", axis=1)

篩選#

Stata 中的篩選是使用一個或多個欄位上的 if 子句來完成。

list if total_bill > 10

資料框可以用多種方式篩選;最直觀的方式是使用 布林索引

In [13]: tips[tips["total_bill"] > 10]
Out[13]: 
     total_bill   tip     sex smoker   day    time  size
0         14.99  1.01  Female     No   Sun  Dinner     2
2         19.01  3.50    Male     No   Sun  Dinner     3
3         21.68  3.31    Male     No   Sun  Dinner     2
4         22.59  3.61  Female     No   Sun  Dinner     4
5         23.29  4.71    Male     No   Sun  Dinner     4
..          ...   ...     ...    ...   ...     ...   ...
239       27.03  5.92    Male     No   Sat  Dinner     3
240       25.18  2.00  Female    Yes   Sat  Dinner     2
241       20.67  2.00    Male    Yes   Sat  Dinner     2
242       15.82  1.75    Male     No   Sat  Dinner     2
243       16.78  3.00  Female     No  Thur  Dinner     2

[204 rows x 7 columns]

上述陳述只是將一個 SeriesTrue/False 物件傳遞到資料框,傳回所有具有 True 的列。

In [14]: is_dinner = tips["time"] == "Dinner"

In [15]: is_dinner
Out[15]: 
0      True
1      True
2      True
3      True
4      True
       ... 
239    True
240    True
241    True
242    True
243    True
Name: time, Length: 244, dtype: bool

In [16]: is_dinner.value_counts()
Out[16]: 
time
True     176
False     68
Name: count, dtype: int64

In [17]: tips[is_dinner]
Out[17]: 
     total_bill   tip     sex smoker   day    time  size
0         14.99  1.01  Female     No   Sun  Dinner     2
1          8.34  1.66    Male     No   Sun  Dinner     3
2         19.01  3.50    Male     No   Sun  Dinner     3
3         21.68  3.31    Male     No   Sun  Dinner     2
4         22.59  3.61  Female     No   Sun  Dinner     4
..          ...   ...     ...    ...   ...     ...   ...
239       27.03  5.92    Male     No   Sat  Dinner     3
240       25.18  2.00  Female    Yes   Sat  Dinner     2
241       20.67  2.00    Male    Yes   Sat  Dinner     2
242       15.82  1.75    Male     No   Sat  Dinner     2
243       16.78  3.00  Female     No  Thur  Dinner     2

[176 rows x 7 columns]

如果/然後邏輯#

在 Stata 中,if 子句也可以用來建立新欄位。

generate bucket = "low" if total_bill < 10
replace bucket = "high" if total_bill >= 10

在 pandas 中,相同的運算可以使用 numpy 中的 where 方法來完成。

In [18]: tips["bucket"] = np.where(tips["total_bill"] < 10, "low", "high")

In [19]: tips
Out[19]: 
     total_bill   tip     sex smoker   day    time  size bucket
0         14.99  1.01  Female     No   Sun  Dinner     2   high
1          8.34  1.66    Male     No   Sun  Dinner     3    low
2         19.01  3.50    Male     No   Sun  Dinner     3   high
3         21.68  3.31    Male     No   Sun  Dinner     2   high
4         22.59  3.61  Female     No   Sun  Dinner     4   high
..          ...   ...     ...    ...   ...     ...   ...    ...
239       27.03  5.92    Male     No   Sat  Dinner     3   high
240       25.18  2.00  Female    Yes   Sat  Dinner     2   high
241       20.67  2.00    Male    Yes   Sat  Dinner     2   high
242       15.82  1.75    Male     No   Sat  Dinner     2   high
243       16.78  3.00  Female     No  Thur  Dinner     2   high

[244 rows x 8 columns]

日期功能#

Stata 提供多種功能來對日期/日期時間欄位進行運算。

generate date1 = mdy(1, 15, 2013)
generate date2 = date("Feb152015", "MDY")

generate date1_year = year(date1)
generate date2_month = month(date2)

* shift date to beginning of next month
generate date1_next = mdy(month(date1) + 1, 1, year(date1)) if month(date1) != 12
replace date1_next = mdy(1, 1, year(date1) + 1) if month(date1) == 12
generate months_between = mofd(date2) - mofd(date1)

list date1 date2 date1_year date2_month date1_next months_between

等效的 pandas 運算如下所示。除了這些功能之外,pandas 還支援 Stata 中沒有的其他時間序列功能(例如時區處理和自訂偏移)– 請參閱 時間序列文件 以取得更多詳細資訊。

In [20]: tips["date1"] = pd.Timestamp("2013-01-15")

In [21]: tips["date2"] = pd.Timestamp("2015-02-15")

In [22]: tips["date1_year"] = tips["date1"].dt.year

In [23]: tips["date2_month"] = tips["date2"].dt.month

In [24]: tips["date1_next"] = tips["date1"] + pd.offsets.MonthBegin()

In [25]: tips["months_between"] = tips["date2"].dt.to_period("M") - tips[
   ....:     "date1"
   ....: ].dt.to_period("M")
   ....: 

In [26]: tips[
   ....:     ["date1", "date2", "date1_year", "date2_month", "date1_next", "months_between"]
   ....: ]
   ....: 
Out[26]: 
         date1      date2  date1_year  date2_month date1_next    months_between
0   2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>
1   2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>
2   2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>
3   2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>
4   2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>
..         ...        ...         ...          ...        ...               ...
239 2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>
240 2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>
241 2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>
242 2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>
243 2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>

[244 rows x 6 columns]

欄位選取#

Stata 提供關鍵字來選取、刪除和重新命名欄位。

keep sex total_bill tip

drop sex

rename total_bill total_bill_2

相同的運算在 pandas 中如下所示。

保留特定欄位#

In [27]: tips[["sex", "total_bill", "tip"]]
Out[27]: 
        sex  total_bill   tip
0    Female       14.99  1.01
1      Male        8.34  1.66
2      Male       19.01  3.50
3      Male       21.68  3.31
4    Female       22.59  3.61
..      ...         ...   ...
239    Male       27.03  5.92
240  Female       25.18  2.00
241    Male       20.67  2.00
242    Male       15.82  1.75
243  Female       16.78  3.00

[244 rows x 3 columns]

刪除欄位#

In [28]: tips.drop("sex", axis=1)
Out[28]: 
     total_bill   tip smoker   day    time  size
0         14.99  1.01     No   Sun  Dinner     2
1          8.34  1.66     No   Sun  Dinner     3
2         19.01  3.50     No   Sun  Dinner     3
3         21.68  3.31     No   Sun  Dinner     2
4         22.59  3.61     No   Sun  Dinner     4
..          ...   ...    ...   ...     ...   ...
239       27.03  5.92     No   Sat  Dinner     3
240       25.18  2.00    Yes   Sat  Dinner     2
241       20.67  2.00    Yes   Sat  Dinner     2
242       15.82  1.75     No   Sat  Dinner     2
243       16.78  3.00     No  Thur  Dinner     2

[244 rows x 6 columns]

重新命名欄位#

In [29]: tips.rename(columns={"total_bill": "total_bill_2"})
Out[29]: 
     total_bill_2   tip     sex smoker   day    time  size
0           14.99  1.01  Female     No   Sun  Dinner     2
1            8.34  1.66    Male     No   Sun  Dinner     3
2           19.01  3.50    Male     No   Sun  Dinner     3
3           21.68  3.31    Male     No   Sun  Dinner     2
4           22.59  3.61  Female     No   Sun  Dinner     4
..            ...   ...     ...    ...   ...     ...   ...
239         27.03  5.92    Male     No   Sat  Dinner     3
240         25.18  2.00  Female    Yes   Sat  Dinner     2
241         20.67  2.00    Male    Yes   Sat  Dinner     2
242         15.82  1.75    Male     No   Sat  Dinner     2
243         16.78  3.00  Female     No  Thur  Dinner     2

[244 rows x 7 columns]

依據數值排序#

在 Stata 中,排序是透過 sort 完成的。

sort sex total_bill

pandas 有 DataFrame.sort_values() 方法,它會接收要排序的欄位清單。

In [30]: tips = tips.sort_values(["sex", "total_bill"])

In [31]: tips
Out[31]: 
     total_bill    tip     sex smoker   day    time  size
67         1.07   1.00  Female    Yes   Sat  Dinner     1
92         3.75   1.00  Female    Yes   Fri  Dinner     2
111        5.25   1.00  Female     No   Sat  Dinner     1
145        6.35   1.50  Female     No  Thur   Lunch     2
135        6.51   1.25  Female     No  Thur   Lunch     2
..          ...    ...     ...    ...   ...     ...   ...
182       43.35   3.50    Male    Yes   Sun  Dinner     3
156       46.17   5.00    Male     No   Sun  Dinner     6
59        46.27   6.73    Male     No   Sat  Dinner     4
212       46.33   9.00    Male     No   Sat  Dinner     4
170       48.81  10.00    Male    Yes   Sat  Dinner     3

[244 rows x 7 columns]

字串處理#

尋找字串長度#

Stata 使用 strlen()ustrlen() 函數分別判斷 ASCII 和 Unicode 字串的長度。

generate strlen_time = strlen(time)
generate ustrlen_time = ustrlen(time)

你可以使用 Series.str.len() 找出字串的長度。在 Python 3 中,所有字串都是 Unicode 字串。 len 包含尾隨空白。使用 lenrstrip 排除尾隨空白。

In [32]: tips["time"].str.len()
Out[32]: 
67     6
92     6
111    6
145    5
135    5
      ..
182    6
156    6
59     6
212    6
170    6
Name: time, Length: 244, dtype: int64

In [33]: tips["time"].str.rstrip().str.len()
Out[33]: 
67     6
92     6
111    6
145    5
135    5
      ..
182    6
156    6
59     6
212    6
170    6
Name: time, Length: 244, dtype: int64

尋找子字串位置#

Stata 使用 strpos() 函數判斷字串中字元的順序。它會使用第一個參數定義的字串,並搜尋你提供為第二個參數的子字串的第一個位置。

generate str_position = strpos(sex, "ale")

你可以使用 Series.str.find() 方法找出字串欄中字元的順序。 find 會搜尋子字串的第一個位置。如果找到子字串,方法會傳回其位置。如果找不到,它會傳回 -1。請記住 Python 的索引是從 0 開始的。

In [34]: tips["sex"].str.find("ale")
Out[34]: 
67     3
92     3
111    3
145    3
135    3
      ..
182    1
156    1
59     1
212    1
170    1
Name: sex, Length: 244, dtype: int64

依據位置擷取子字串#

Stata 使用 substr() 函數根據字串的位置擷取子字串。

generate short_sex = substr(sex, 1, 1)

使用 pandas 可以使用 [] 符號根據位置位置從字串中擷取子字串。請記住,Python 索引是從 0 開始的。

In [35]: tips["sex"].str[0:1]
Out[35]: 
67     F
92     F
111    F
145    F
135    F
      ..
182    M
156    M
59     M
212    M
170    M
Name: sex, Length: 244, dtype: object

擷取第 n 個字#

Stata word() 函數從字串傳回第 n 個字。第一個引數是要剖析的字串,第二個引數指定要擷取的字。

clear
input str20 string
"John Smith"
"Jane Cook"
end

generate first_name = word(name, 1)
generate last_name = word(name, -1)

在 pandas 中擷取字詞最簡單的方法是使用空白分割字串,然後根據索引參照字詞。請注意,如果有需要,還有更強大的方法。

In [36]: firstlast = pd.DataFrame({"String": ["John Smith", "Jane Cook"]})

In [37]: firstlast["First_Name"] = firstlast["String"].str.split(" ", expand=True)[0]

In [38]: firstlast["Last_Name"] = firstlast["String"].str.rsplit(" ", expand=True)[1]

In [39]: firstlast
Out[39]: 
       String First_Name Last_Name
0  John Smith       John     Smith
1   Jane Cook       Jane      Cook

變更大小寫#

Stata strupper()strlower()strproper()ustrupper()ustrlower()ustrtitle() 函數分別變更 ASCII 和 Unicode 字串的大小寫。

clear
input str20 string
"John Smith"
"Jane Cook"
end

generate upper = strupper(string)
generate lower = strlower(string)
generate title = strproper(string)
list

等效的 pandas 方法為 Series.str.upper()Series.str.lower()Series.str.title()

In [40]: firstlast = pd.DataFrame({"string": ["John Smith", "Jane Cook"]})

In [41]: firstlast["upper"] = firstlast["string"].str.upper()

In [42]: firstlast["lower"] = firstlast["string"].str.lower()

In [43]: firstlast["title"] = firstlast["string"].str.title()

In [44]: firstlast
Out[44]: 
       string       upper       lower       title
0  John Smith  JOHN SMITH  john smith  John Smith
1   Jane Cook   JANE COOK   jane cook   Jane Cook

合併#

下列表格將用於合併範例

In [45]: df1 = pd.DataFrame({"key": ["A", "B", "C", "D"], "value": np.random.randn(4)})

In [46]: df1
Out[46]: 
  key     value
0   A  0.469112
1   B -0.282863
2   C -1.509059
3   D -1.135632

In [47]: df2 = pd.DataFrame({"key": ["B", "D", "D", "E"], "value": np.random.randn(4)})

In [48]: df2
Out[48]: 
  key     value
0   B  1.212112
1   D -0.173215
2   D  0.119209
3   E -1.044236

在 Stata 中,若要執行合併,一個資料集必須在記憶體中,另一個必須作為磁碟上的檔案名稱來參照。相反地,Python 必須已將兩個 資料框 放入記憶體中。

預設情況下,Stata 會執行外部連接,其中兩個資料集的所有觀察值在合併後會留在記憶體中。使用者可以使用 _merge 變數中建立的值,僅保留來自初始資料集、合併資料集或兩者的交集的觀察值。

* First create df2 and save to disk
clear
input str1 key
B
D
D
E
end
generate value = rnormal()
save df2.dta

* Now create df1 in memory
clear
input str1 key
A
B
C
D
end
generate value = rnormal()

preserve

* Left join
merge 1:n key using df2.dta
keep if _merge == 1

* Right join
restore, preserve
merge 1:n key using df2.dta
keep if _merge == 2

* Inner join
restore, preserve
merge 1:n key using df2.dta
keep if _merge == 3

* Outer join
restore
merge 1:n key using df2.dta

pandas 資料框有一個 merge() 方法,提供類似的功能。資料不必事先排序,而且不同的連接類型是透過 how 關鍵字來完成。

In [49]: inner_join = df1.merge(df2, on=["key"], how="inner")

In [50]: inner_join
Out[50]: 
  key   value_x   value_y
0   B -0.282863  1.212112
1   D -1.135632 -0.173215
2   D -1.135632  0.119209

In [51]: left_join = df1.merge(df2, on=["key"], how="left")

In [52]: left_join
Out[52]: 
  key   value_x   value_y
0   A  0.469112       NaN
1   B -0.282863  1.212112
2   C -1.509059       NaN
3   D -1.135632 -0.173215
4   D -1.135632  0.119209

In [53]: right_join = df1.merge(df2, on=["key"], how="right")

In [54]: right_join
Out[54]: 
  key   value_x   value_y
0   B -0.282863  1.212112
1   D -1.135632 -0.173215
2   D -1.135632  0.119209
3   E       NaN -1.044236

In [55]: outer_join = df1.merge(df2, on=["key"], how="outer")

In [56]: outer_join
Out[56]: 
  key   value_x   value_y
0   A  0.469112       NaN
1   B -0.282863  1.212112
2   C -1.509059       NaN
3   D -1.135632 -0.173215
4   D -1.135632  0.119209
5   E       NaN -1.044236

遺失資料#

pandas 和 Stata 都有一個遺失資料的表示方式。

pandas 使用特殊浮點值 NaN(非數字)表示遺失資料。許多語意相同;例如遺失資料會透過數值運算傳播,且在聚合時預設會略過。

In [57]: outer_join
Out[57]: 
  key   value_x   value_y
0   A  0.469112       NaN
1   B -0.282863  1.212112
2   C -1.509059       NaN
3   D -1.135632 -0.173215
4   D -1.135632  0.119209
5   E       NaN -1.044236

In [58]: outer_join["value_x"] + outer_join["value_y"]
Out[58]: 
0         NaN
1    0.929249
2         NaN
3   -1.308847
4   -1.016424
5         NaN
dtype: float64

In [59]: outer_join["value_x"].sum()
Out[59]: -3.5940742896293765

其中一個差異是遺失資料無法與其哨兵值相比較。例如,在 Stata 中,您可以這樣做來篩選遺失值。

* Keep missing values
list if value_x == .
* Keep non-missing values
list if value_x != .

在 pandas 中,Series.isna()Series.notna() 可用於篩選列。

In [60]: outer_join[outer_join["value_x"].isna()]
Out[60]: 
  key  value_x   value_y
5   E      NaN -1.044236

In [61]: outer_join[outer_join["value_x"].notna()]
Out[61]: 
  key   value_x   value_y
0   A  0.469112       NaN
1   B -0.282863  1.212112
2   C -1.509059       NaN
3   D -1.135632 -0.173215
4   D -1.135632  0.119209

pandas 提供 多種處理遺失資料的方法。以下是幾個範例

刪除有遺失值的列#

In [62]: outer_join.dropna()
Out[62]: 
  key   value_x   value_y
1   B -0.282863  1.212112
3   D -1.135632 -0.173215
4   D -1.135632  0.119209

從前一列向前填入#

In [63]: outer_join.ffill()
Out[63]: 
  key   value_x   value_y
0   A  0.469112       NaN
1   B -0.282863  1.212112
2   C -1.509059  1.212112
3   D -1.135632 -0.173215
4   D -1.135632  0.119209
5   E -1.135632 -1.044236

用指定值取代遺失值#

使用平均值

In [64]: outer_join["value_x"].fillna(outer_join["value_x"].mean())
Out[64]: 
0    0.469112
1   -0.282863
2   -1.509059
3   -1.135632
4   -1.135632
5   -0.718815
Name: value_x, dtype: float64

GroupBy#

聚合#

Stata 的 collapse 可用於依一個或多個關鍵變數進行分組,並對數值欄位計算聚合。

collapse (sum) total_bill tip, by(sex smoker)

pandas 提供一個彈性的 groupby 機制,允許類似的聚合。請參閱 groupby 文件 以取得更多詳細資料和範例。

In [65]: tips_summed = tips.groupby(["sex", "smoker"])[["total_bill", "tip"]].sum()

In [66]: tips_summed
Out[66]: 
               total_bill     tip
sex    smoker                    
Female No          869.68  149.77
       Yes         527.27   96.74
Male   No         1725.75  302.00
       Yes        1217.07  183.07

轉換#

在 Stata 中,如果群組聚合需要與原始資料集一起使用,通常會使用 bysort 搭配 egen()。例如,依據吸菸者群組減去每個觀測值的平均值。

bysort sex smoker: egen group_bill = mean(total_bill)
generate adj_total_bill = total_bill - group_bill

pandas 提供一個 轉換 機制,允許這些類型的運算在一個運算中簡潔地表達。

In [67]: gb = tips.groupby("smoker")["total_bill"]

In [68]: tips["adj_total_bill"] = tips["total_bill"] - gb.transform("mean")

In [69]: tips
Out[69]: 
     total_bill    tip     sex smoker   day    time  size  adj_total_bill
67         1.07   1.00  Female    Yes   Sat  Dinner     1      -17.686344
92         3.75   1.00  Female    Yes   Fri  Dinner     2      -15.006344
111        5.25   1.00  Female     No   Sat  Dinner     1      -11.938278
145        6.35   1.50  Female     No  Thur   Lunch     2      -10.838278
135        6.51   1.25  Female     No  Thur   Lunch     2      -10.678278
..          ...    ...     ...    ...   ...     ...   ...             ...
182       43.35   3.50    Male    Yes   Sun  Dinner     3       24.593656
156       46.17   5.00    Male     No   Sun  Dinner     6       28.981722
59        46.27   6.73    Male     No   Sat  Dinner     4       29.081722
212       46.33   9.00    Male     No   Sat  Dinner     4       29.141722
170       48.81  10.00    Male    Yes   Sat  Dinner     3       30.053656

[244 rows x 8 columns]

依群組處理#

除了聚合之外,pandas groupby 可用於複製 Stata 中大多數其他 bysort 處理。例如,下列範例會列出依性別/吸菸者群組當前排序順序中的第一個觀測值。

bysort sex smoker: list if _n == 1

在 pandas 中,這會寫成

In [70]: tips.groupby(["sex", "smoker"]).first()
Out[70]: 
               total_bill   tip   day    time  size  adj_total_bill
sex    smoker                                                      
Female No            5.25  1.00   Sat  Dinner     1      -11.938278
       Yes           1.07  1.00   Sat  Dinner     1      -17.686344
Male   No            5.51  2.00  Thur   Lunch     2      -11.678278
       Yes           5.25  5.15   Sun  Dinner     2      -13.506344

其他考量#

磁碟與記憶體#

pandas 和 Stata 都只在記憶體中運作。這表示能載入 pandas 的資料大小會受到電腦記憶體的限制。如果需要核心外處理,其中一個可能性是 dask.dataframe 函式庫,它提供一個 pandas 功能子集,用於磁碟上 DataFrame