一般社団法人 全国個人事業主支援協会

COLUMN コラム

MultiIndex

まずは公式ドキュメントから
https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html

arrays = [
["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
["one", "two", "one", "two", "one", "two", "one", "two"],
]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=["first", "second"])
二つのリストから組み合わせに基づいてMultiIndexを作成する場合、MultiIndex.from_product()が便利

以下で、最初の①と同じような結果が得られる

iterables = [["bar", "baz", "foo", "qux"], ["one", "two"]]
pd.MultiIndex.from_product(iterables, names=["first", "second"])
MultiIndex.from_frame()でDataFrameから作成する

df = pd.DataFrame(
[[“bar”, “one”], [“bar”, “two”], [“foo”, “one”], [“foo”, “two”]],
columns=[“first”, “second”],
)
pd.MultiIndex.from_frame(df)
よく使う方法として、SeriesやDataFrameの引数のindexとして直接作成したい、2次元配列などを渡すやり方

arrays = [
[“bar”, “bar”, “baz”, “baz”, “foo”, “foo”, “qux”, “qux”],
[“one”, “two”, “one”, “two”, “one”, “two”, “one”, “two”],
]
s = pd.Series(np.random.randn(8), index=arrays)
MultiIndexにはnamesというコンストラクタがあり、指定しないとNoneが割り当てられる
The following two tabs change content below.

WATANABE REN

千葉県在住のエンジニアです。最近はPythonやってます。

この記事をシェアする

  • Twitterでシェア
  • Facebookでシェア
  • LINEでシェア