概要
Series の値を取得、設定する方法について解説します。
関連記事 pandas – DataFrame のインデックス操作まとめ – pystyle
Series のインデックスを取得する
pandas.Series.index または pandas.Series.keys() で Series のインデックスを取得できます。また、Series を iterate すると、インデックスが返ります。
In [1]:
a 11 b 12 c 13 d 14 e 15 dtype: int64
In [2]:
Index(['a', 'b', 'c', 'd', 'e'], dtype='object') Index(['a', 'b', 'c', 'd', 'e'], dtype='object') 11 12 13 14 15
Series の要素を1つずつ iterate する
pandas.Series.iteritems() 及び pandas.Series.items() で、(インデックス, 値) を返す iterable オブジェクトを取得できます。
In [3]:
<class 'zip'> a 11 b 12 c 13 d 14 e 15 <class 'zip'> a 11 b 12 c 13 d 14 e 15
Series の選択した範囲の値を取得または設定する
範囲の選択方法はインデックスに基づく選択と位置に基づく選択があります。
at
、loc
、__getitem__()
、iat
、iloc
は選択範囲に値を設定することもできます。
In [4]:
a 11 b 100 c 13 d 14 e 15 dtype: int64 a 11 b 100 c 100 d 100 e 15 dtype: int64
In [5]:
a 11 b 100 c 13 d 14 e 15 dtype: int64 a 11 b 100 c 100 d 14 e 15 dtype: int64
インデックスに基づく選択
取得 | 代入 | Indexing | Slice | Bool Indexing | Fancy Indexing | |
---|---|---|---|---|---|---|
pandas.Series.at | ◯ | ◯ | s.at[index] | |||
pandas.Series.get() | ◯ | ✕ | s.get(index) | |||
pandas.Series.xs() | ◯ | ✕ | s.xs(index) | |||
pandas.Series.loc | ◯ | ◯ | s.loc[index] | s.loc[slice] | s.loc[bools] | s.loc[indices] |
__getitem__() |
◯ | ◯ | s[index] | s[slice] | s[bools] | s[indices] |
In [6]:
12
get() は指定したインデックスが存在しない場合は None を返します。存在しない場合に返す値を default
に指定できます。
In [7]:
None -1
list のスライスと異なり、インデックスのスライスは終端も含みます。
In [8]:
b 12 c 13 d 14 e 15 dtype: int64 a 11 b 12 c 13 d 14 dtype: int64 b 12 c 13 d 14 dtype: int64 a 11 c 13 e 15 dtype: int64
In [9]:
a 11 c 13 e 15 dtype: int64
In [10]:
a 11 c 13 e 15 dtype: int64
位置に基づく選択
取得 | 代入 | Indexing | Slice | Fancy Indexing | |
---|---|---|---|---|---|
pandas.Series.iat | ◯ | ◯ | s.iat[position] | ||
pandas.Series.take() | ◯ | ✕ | s.take(positions) | ||
pandas.Series.iloc | ◯ | ◯ | s.iloc[position] | s.iloc[slice] | s.iloc[positions] |
In [11]:
12
list のスライスと同様、位置のスライスは終端は含みません。
In [12]:
b 12 c 13 d 14 e 15 dtype: int64 a 11 b 12 c 13 dtype: int64 b 12 c 13 dtype: int64 a 11 c 13 e 15 dtype: int64
In [13]:
a 11 c 13 e 15 dtype: int64 a 11 c 13 e 15 dtype: int64
コメント