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 |
---|---|
|
データセット |
列 |
変数 |
行 |
観測 |
groupby |
bysort |
|
|
DataFrame
#
pandasのDataFrame
は、Stataのデータセットと同様のものです。これは、異なる型を持つ可能性のあるラベル付き列を持つ2次元データソースです。このドキュメントで示すように、Stataでデータセットに適用できるほとんどすべての操作は、pandasでも実行できます。
Series
#
Series
は、DataFrame
の1つの列を表すデータ構造です。Stataには単一の列のための個別のデータ構造はありませんが、一般的に、Series
の操作は、Stataでデータセットの列を参照することに似ています。
Index
#
すべてのDataFrame
とSeries
には、データの行のラベルであるIndex
があります。Stataには正確に類似した概念はありません。Stataでは、データセットの行は、_n
でアクセスできる暗黙的な整数インデックス以外は、本質的にラベル付けされていません。
pandasでは、インデックスが指定されていない場合、デフォルトで整数インデックスも使用されます(最初の行= 0、2番目の行= 1など)。ラベル付きのIndex
またはMultiIndex
を使用すると、高度な分析が可能になり、最終的にはpandasを理解する上で重要な部分となりますが、この比較では、基本的にIndex
を無視し、DataFrame
を列のコレクションとして扱います。 Index
を効果的に使用する方法の詳細については、インデックス作成ドキュメントを参照してください。
コピー対インプレース操作#
ほとんどのpandas操作は、Series
/DataFrame
のコピーを返します。変更を「永続化」するには、新しい変数に代入するか
sorted_df = df.sort_values("col1")
元の変数を上書きする必要があります
df = df.sort_values("col1")
注
一部のメソッドでは、inplace=True
またはcopy=False
キーワード引数が利用可能です
df.replace(5, inplace=True)
replace
を含む非常に小さいメソッドのサブセットを除いて、ほとんどのメソッド(たとえば、dropna
)のinplace
とcopy
を非推奨にして削除することについて活発な議論があります。Copy-on-Writeのコンテキストでは、両方のキーワードはもはや必要ありません。提案はこちらにあります。
データの入出力#
値から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は多くの形式のデータを読み込むためのユーティリティを提供しています。 pandasテスト(csv)内にあるtips
データセットは、以降の多くの例で使用されます。
Stataは、csvデータをメモリ内のデータセットに読み込むためにimport delimited
を提供しています。tips.csv
ファイルが現在の作業ディレクトリにある場合、次のようにインポートできます。
import delimited tips.csv
pandasのメソッドはread_csv()
で、同様に機能します。さらに、URLが提示された場合、データセットを自動的にダウンロードします。
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()
は、データの解析方法を指定するための多数のパラメーターを受け入れることができます。たとえば、データが代わりにタブ区切りで、列名がなく、現在の作業ディレクトリに存在する場合、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()
関数を使用して、Stataデータセットを.dta
形式で読み込むこともできます。
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では、generate
コマンドとreplace
コマンドを使用して、新規または既存の列に対して任意の数式を使用できます。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でのフィルタリングは、1つ以上の列に対するif
句を使用して行われます。
list if total_bill > 10
DataFrameは複数の方法でフィルタリングできます。最も直感的な方法は、ブールインデックスを使用することです。
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]
上記のステートメントは、True
/False
オブジェクトのSeries
をDataFrameに渡すだけであり、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]
If/thenロジック#
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は、それぞれASCIIおよびUnicode文字列に対して、strlen()
関数とustrlen()
関数を使用して、文字列の長さを決定します。
generate strlen_time = strlen(time)
generate ustrlen_time = ustrlen(time)
Series.str.len()
を使用して、文字列の長さを検索できます。Python 3では、すべての文字列がUnicode文字列です。len
には、末尾の空白が含まれます。末尾の空白を除外するには、len
とrstrip
を使用します。
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()
関数を使用して、文字列内の文字の位置を決定します。これは、最初の引数で定義された文字列を受け取り、2番目の引数として指定した部分文字列の最初の位置を検索します。
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番目の単語を返します。最初の引数は解析する文字列で、2番目の引数は抽出する単語を指定します。
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では、マージを実行するには、1つのデータセットがメモリ内にある必要があり、もう1つのデータセットはディスク上のファイル名として参照する必要があります。対照的に、Pythonでは、両方のDataFrame
がすでにメモリ内にある必要があります。
デフォルトでは、Stataは外部結合を実行し、両方のデータセットのすべての観測値がマージ後にメモリに残されます。最初のデータセット、マージされたデータセット、または_merge
変数で作成された値を使用して、2つのデータセットの交差からの観測値のみを保持できます。
* 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 DataFrameには、同様の機能を提供する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
1つの違いは、欠損データをそのセンチネル値と比較できないことです。たとえば、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
を使用して、1つ以上のキー変数でグループ化し、数値列で集計を計算できます。
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は、これらのタイプの操作を1つの操作で簡潔に表現できる変換メカニズムを提供します。
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にロードできるデータのサイズがマシンのメモリによって制限されることを意味します。コア外処理が必要な場合、1つの可能性は、ディスク上のDataFrame
に対してpandas機能のサブセットを提供するdask.dataframeライブラリです。