
表形式のデータを扱うのに便利なpandas.DataFrame
。
CSVやEXCELのデータを取り込んで、テーブルデータとして条件に合ったデータのみ抽出したりできる。
その抽出時にこのようなエラーが出た。
エラーメッセージを見てもイマイチよくわからない。
一体何が原因なのか。
そこで今回はpandasでUnalignable boolean Series provided as indexerエラーになる原因について紹介する。
この記事を書いている人

記事を読むメリット
pandasでUnalignable boolean Series provided as indexerエラーになる原因がわかり、pandasでのデータ抽出が得意になる
pandasでUnalignable boolean Series provided as indexerエラーになる原因
pandasでUnalignable boolean Series provided as indexerエラーになる原因。
それは条件抽出時にpandas.DataFrameをマスクするために指定しているboolean Seriesの数がDataFrameと合っていないから。
まずはサンプルとなるDataFrameを用意する。
DATA
import pandas as pd data_list1 = [ ["a"], ["b"], ["c"], ["d"] ] col_list1 = ["col"] df1 = pd.DataFrame(data=data_list1, columns=col_list1) print(df1) # col # 0 a # 1 b # 2 c # 3 d
これを .loc[]
で条件指定した行だけ抽出すると以下のようになる。
SAMPLE
df1_part = df1.loc[ df1["col"] == "a" ] print(df1_part) # col # 0 a

では今度は別のDataFrameでやってみる。
DATA
data_list2 = [ ["e"], ["f"], ["g"], ["h"], ["i"], ] col_list2 = ["col"] df2 = pd.DataFrame(data=data_list2, columns=col_list2) print(df2) # col # 0 e # 1 f # 2 g # 3 h # 4 i
そして同じように条件抽出しようとすると、
SAMPLE
df2_part = df2.loc[ df1["col"] == "e" ] print(df2_part) # IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).

原因は df1["col"] == "e"
の部分。
df2に対して一致する条件を指定するはずが、間違えてdf1を使ってしまっている。
df2が5行あるのに対して、df1["col"] == "e"
が返すのは4要素のboolean Series。
数が足りないのでエラーになっている。
修正するには要素数をあわせてやれば良い。
SAMPLE
df2_part = df2.loc[ df2["col"] == "e" ] print(df2_part) # col # 0 e

まとめ
今回はpandasでUnalignable boolean Series provided as indexerエラーになる原因について解説した。
エラーの原因となるポイントは以下の通り。
ココに注意
- 条件抽出で指定するboolean Seriesの数が元のDataFrameの行数と合っていないとエラーになる

Unalignable boolean Series provided as indexer
だと、結構わかりにくいかも…他にもpandas関連の記事もあるので、もし気になるものがあれば見てみて欲しい。