Closed2

ヒットしたデータ数によってPandasの`.loc`の返却値の型が異なる

bilzardbilzard

問題

.loc[x]のxにiterableでない値を指定した場合、ヒットした行数によって返却値の型が異なる。
具体的にはヒットした行数が1の場合はpd.Seriesを、それ以外の場合はpd.DataFrameを返却する。

解決方法

同じ型で欲しい場合はxをiterableにして指定する

コード例
df = pd.DataFrame({"index": [1, 2, 2], "value": [4, 5, 6], "v2": [1, 1, 1]}).set_index(
    "index"
)
print(df)
print(type(df.loc[1]))
print(type(df.loc[2]))
print(type(df.loc[[1]]))
print(type(df.loc[[2]]))
       value  v2
index           
1          4   1
2          5   1
2          6   1
<class 'pandas.core.series.Series'>
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
bilzardbilzard

なお、公式ドキュメント[1]には「単一ラベルの場合はSeriesを返す」と書かれている。
インデックスが重複している場合は想定してないんだろうか?

df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
     index=['cobra', 'viper', 'sidewinder'],
     columns=['max_speed', 'shield'])
df
            max_speed  shield
cobra               1       2
viper               4       5
sidewinder          7       8

Single label. Note this returns the row as a Series.

脚注
  1. https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html ↩︎

このスクラップは2023/01/12にクローズされました