【pandas】データのラベリング
Series オブジェクトや DataFrame オブジェクトのラベリングに用いられる Indexオブジェクト は pandas.Index() を使って生成することもできます。
# PANDAS_INDEX_01
# In[1]
# Indexオブジェクトを生成
idx_1 = pd.Index([1, 2, 3])
print(idx_1)
print(type(idx_1))
Int64Index([1, 2, 3], dtype='int64')
実際には Indexオブジェクトという呼び方は総称であり、要素の型に応じて属するクラスは異なります。上のコードで定義した idx_1 はすべての要素が整数なので、numeric.Int64Indexクラスに属しています。
print(type(idx_1))
<class 'pandas.core.indexes.numeric.Int64Index'>
すべての要素が浮動小数点数ならば、numeric.Float64Indexクラスのオブジェクトが生成されます:
# In[2]
Indexオブジェクトを生成
idx_2 = pd.Index([0.1, 0.2, 0.3])
print(idx_2)
print(type(idx_2))
Float64Index([0.1, 0.2, 0.3], dtype='float64') <class 'pandas.core.indexes.numeric.Float64Index'>
その他のオブジェクトを渡すと、base.Indexクラスのオブジェクトが生成され、データ型 (dtype) は "object" になります。
# In[3]
# Indexオブジェクトを生成
idx_3 = pd.Index(["a", "b", "c"])
print(idx_3)
print(type(idx_3))
Index(['a', 'b', 'c'], dtype='object') <class 'pandas.core.indexes.base.Index'>
pandas.Series() に Indexオブジェクトを渡して Seriesオブジェクトを生成できます。
# In[4]
# Indexを渡してSeriesを生成
pd.Series([10, 20, 30], index = idx_3)
a 10 b 20 c 30 dtype: int64
pandas.DataFrame() の index と columns に Indexオブジェクトを渡して DataFrameオブジェクトを生成できます。
# In[5]
# Indexオブジェクトを生成
idx = pd.Index(["a", "b"])
clm = pd.Index([1, 2, 3])
# 2次元配列を定義
x = np.array([[10, 20, 30],
[40, 50, 60]])
# DataFrameオブジェクトを生成
data = pd.DataFrame(x, index = idx, columns = clm)
print(data)
1 2 3 a 10 20 30 b 40 50 60
Index要素へのアクセス
Indexの各要素に対して、リストや配列と同じような方法でアクセスできます。
# PANDAS_INDEX_02
# In[1]
import numpy as np
import pandas as pd
# Indexオブジェクトを生成
idx = pd.Index(["a", "b", "c", "d", "e"])
# idxの4番目の要素を参照
print(idx[3])
d
# In[2]
# 2~4番目の要素をスライス
print(idx[1:4])
Index(['b', 'c', 'd'], dtype='object')
Indexの不変性
Index は immutable (変更不能) なオブジェクトです。
通常の方法で要素を書き換えることはできません。
# PANDAS_INDEX_03
# In[1]
import numpy as np
import pandas as pd
# Indexオブジェクトを生成
idx = pd.Index(["a", "b", "c", "d", "e"])
idx[2] = 1
TypeError: Index does not support mutable operations
Indexのデータ属性
NumPy配列と同様に、Indexオブジェクトも size, shape, dtype, ndim, values などのデータ属性を備えています。
# PANDAS_INDEX_04
# In[1]
import numpy as np
import pandas as pd
# Indexオブジェクトを生成
idx_5 = pd.Index([1, 2, 3, 4, 5])
print("要素の数 {}".format(idx_5.size))
print("形状 {}".format(idx_5.shape))
print("データ型 {}".format(idx_5.dtype))
print("次元数 {}".format(idx_5.ndim))
print("値 {}".format(idx_5.values))
要素の数 5 形状 (5,) データ型 int64 次元数 1 値 [1 2 3 4 5]
順序付き集合
Indexオブジェクトは 順序付き集合 としての性質を備えており、各種の 集合演算 に対応できます。
# PANDAS_INDEX_05
# In[1]
import numpy as np
import pandas as pd
# Indexオブジェクトを生成
idx_1 = pd.Index(["a", "b", "c"])
idx_2 = pd.Index(["c", "d", "e"])
# 積集合
print("積集合", idx_1 & idx_2)
# 和集合
print("和集合", idx_1 | idx_2)
# 対称差
print("対称差", idx_1 ^ idx_2)
積集合 Index(['c'], dtype='object') 和集合 Index(['a', 'b', 'c', 'd', 'e'], dtype='object') 対称差 Index(['a', 'b', 'd', 'e'], dtype='object')
ただし、Python の setオブジェクトとは異なり、Indexオブジェクトは内部に重複要素を含むことができるので、多重集合 (multiset) とよばれることもあります。
コメントを書く