1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pandas.DataFrame.loc(.iloc)でスライスを用いるときの注意点

Posted at

はじめに

pandas.DataFrame.loc(.iloc)で行の位置指定に用いるスライスは、通常のPythonのスライスと少し違うみたいです。公式ドキュメントにはもちろん書いてありますが、備忘録としてこの記事を書きました。
結論から言うと、行の位置指定のスライスでは、左側(開始)と右側(終了)の両方の値を含む範囲が指定されます。

df.locとdf.ilocについて

pandasのdf.locまたはdf.ilocを用いると、任意の行、列の値を抽出することができます。
df.locでは行ラベルと列ラベルによる絞り込みを行い、
df.ilocでは行インデックス、列インデックスによる絞り込みを行います。
条件式とかも使えますが、ここでは触れません。

以下に例を示します。

# df.loc["行ラベル", "列ラベル"]
# df.iloc["行インデックス", "列インデックス"]

# DataFrame dfのnumber列とstring列を抽出する
# number列は左から1番目、string列は左から2番目の列とする

subset1 = df.loc[:, ["number", "string"]]
subset2 = df.loc[:, [0, 1]]

このように、df.locとdf.ilocではリストやスライスを用いて任意の行と列を抽出することができます。

df.loc(df.iloc)でスライスを用いるときの注意点

列の位置指定にスライスを用いるときは、通常のPythonのスライスとして機能します。
しかし、行の位置指定にスライスを用いるときは、冒頭でも述べた通り左側(開始)と右側(終了)の両方の値を含む範囲が指定されます。

以下に、例を示します。

# DataFrame dfの1から3行目のnumber列とstring列を抽出する

subset1 = df.loc[0:2, ["number", "string"]]
subset2 = df.iloc[0:2, 0:2]

雑な記事になってしまいましたが、以上です。
なぜ行と列でスライスの動き方が違うのかが気になるところなので、ご存じの方がもしいたら教えていただけるとありがたいです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?