Python

pandasでUnalignable boolean Series provided as indexerエラーになる原因

Share this for your friends.

pandasでUnalignable boolean Series provided as indexerエラーになる原因

pandasで「Unalignable boolean Series provided」って出たけど、どういうこと?


表形式のデータを扱うのに便利なpandas.DataFrame

CSVやEXCELのデータを取り込んで、テーブルデータとして条件に合ったデータのみ抽出したりできる。

その抽出時にこのようなエラーが出た。

IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).

エラーメッセージを見てもイマイチよくわからない。

一体何が原因なのか。

そこで今回はpandasでUnalignable boolean Series provided as indexerエラーになる原因について紹介する。

この記事を書いている人


システムエンジニア、AIエンジニアと、IT業界で10年以上働いている中堅。PythonとSQLが得意。

記事を読むメリット

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


1行抽出できてるね。


では今度は別の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関連の記事もあるので、もし気になるものがあれば見てみて欲しい


Share this for your friends.

ITipsと同じようなブログを作る方法

ブログに興味がありますか?

もしブログに興味がある場合は↓このページ↓を参考にすれば、ITipsと同じ構成でブログを作ることができます

サーバー、ドメイン、ASPと【ブログに必要なものは全て】このページに書きました。
同じ構成でブログ作るのはいいけど、記事はマネしないでネ (TДT;)

ランキング参加中

にほんブログ村 IT技術ブログへ

他にもブログやSNSで紹介してくれると励みになります。

はてブのコメントで酷評されると泣きます(´;ω;`)

-Python
-,

© 2024 ITips