Python Pandas - 多級索引基礎



多級索引也稱為分層索引,它是 pandas 中一個強大的功能,允許您在低維結構(如 Series(一維)和 DataFrame(二維))中處理高維資料。使用多級索引,pandas 物件具有多個級別的索引標籤。使用多級索引,您可以表示和操作具有多個索引級別的資料,從而更容易有效地處理複雜的資料集。

在本教程中,我們將學習多級索引的基礎知識,包括如何建立具有多級索引的 Series 和 DataFrame,如何在多級索引軸上執行基本索引,以及如何使用多級索引對齊資料。

建立具有多級索引的 Pandas 物件

在 pandas 中建立多級索引物件有多種方法,包括從陣列列表、元組、可迭代物件的乘積或直接從 DataFrame 建立。

以下是構建新的多級索引的輔助方法列表:

  • MultiIndex.from_arrays()

  • MultiIndex.from_product()

  • MultiIndex.from_tuples()

  • MultiIndex.from_frame()

從陣列列表建立多級索引

透過使用pandas.MultiIndex.from_arrays()方法,我們可以從陣列列表建立多級索引。

示例:從列表列表建立具有多級索引的 Series

以下示例演示了使用pandas.MultiIndex.from_arrays()方法建立具有多級索引的 Series 物件。

import pandas as pd
import numpy as np

# Create a 2D list
list_2d = [["BMW", "BMW", "Lexus", "Lexus", "foo", "foo", "Audi", "Audi"],
["1", "2", "1", "2", "1", "2", "1", "2"]]

# Create a MultiIndex object
index = pd.MultiIndex.from_arrays(list_2d, names=["first", "second"])

# Creating a MultiIndexed Series
s = pd.Series(np.random.randn(8), index=index)

# Display the output Series 
print("Output MultiIndexed Series:\n",s)

以下是上述程式碼的輸出:

Output MultiIndexed Series:
First Second
BMW1-1.334159
2-0.233286
Lexus11.167558
2-0.875364
foo1-0.338715
20.021517
Audi1-0.272688
20.588359
dtype: float64

從元組建立多級索引

Pandas MultiIndex.from_tuples()方法用於將元組列表轉換為多級索引。

示例:從元組建立具有多級索引的 DataFrame

此示例演示瞭如何使用pandas.MultiIndex.from_tuples()方法建立具有多級索引的 DataFrame 物件。

import pandas as pd
import numpy as np

# Create a 2D list
list_2d = [["BMW", "BMW", "Lexus", "Lexus", "foo", "foo", "Audi", "Audi"],
["1", "2", "1", "2", "1", "2", "1", "2"]]

# Create a MultiIndex object
tuples = list(zip(*list_2d ))
index = pd.MultiIndex.from_tuples(tuples, names=["first", "second"])

# Creating a MultiIndexed DataFrame
df = pd.DataFrame(np.random.randn(8, 4), index=index, columns=["A", "B", "C", "D"])

# Display the output Series 
print("Output MultiIndexed DataFrame:\n", df)

以下是上述程式碼的輸出:

Output MultiIndexed DataFrame:
A B C D
FirstSecond
BMW1-0.3478461.011760-1.224244-1.225259
20.237115-1.3164330.962960-1.008623
Lexus1-1.8062091.0389730.246994-1.596616
2-0.325284-0.264822-0.7350290.377645
foo10.243560-0.4087180.717466-1.446259
2-0.8177040.7112992.567860-1.054871
Audi10.583519-0.0075770.828928-0.826645
22.4546261.5580450.981507-0.148554

使用 from_product() 建立多級索引

Pandas MultiIndex.from_product()方法使用多個可迭代物件的笛卡爾積來建立多級索引。當您需要來自兩個或多個可迭代物件的每個可能的元素組合時,它非常有用。

示例:使用 from_product() 建立具有多級索引的 DataFrame

此示例演示瞭如何使用 pandas MultiIndex.from_product()方法建立具有多級索引的 DataFrame。

import pandas as pd
import numpy as np

# Create a list of lits 
iterable = [[1, 2, 3], ['green', 'black']]

# Create a MultiIndex object
index = pd.MultiIndex.from_product(iterable, names=["number", "color"])

# Creating a MultiIndexed DataFrame
df = pd.DataFrame(np.random.randn(6, 3), index=index, columns=["A", "B", "C"])

# Display the output Series 
print("Output MultiIndexed DataFrame:\n", df)

以下是上述程式碼的輸出:

Output MultiIndexed DataFrame:
A B C
NumberColor
1green-1.174910-0.861695-0.026601
black-2.8242890.6748701.132675
2green-0.285381-0.1041881.993371
black-0.926109-0.579404-1.119692
3green-3.278989-0.873407-1.359360
black0.7354920.066735-0.099568

從 DataFrame 建立多級索引

Pandas MultiIndex.from_frame()方法用於從 DataFrame 建立多級索引。

示例:從 DataFrame 建立多級索引

此示例使用pd.MultiIndex.from_frame()方法直接從 DataFrame 建立多級索引物件。

import pandas as pd
import numpy as np

# Create a DataFrame
df = pd.DataFrame([["BMW", 1], ["BMW", 2], ["Lexus", 1],["Lexus", 2]], 
 columns=["first", "second"])

# Create a MultiIndex object
index = pd.MultiIndex.from_frame(df)

# Creating a MultiIndexed DataFrame
df = pd.DataFrame(np.random.randn(4, 3), index=index, columns=["A", "B", "C"])

# Display the output Series 
print("Output MultiIndexed DataFrame:\n", df)

以下是上述程式碼的輸出:

Output MultiIndexed DataFrame:
A B C
FirstSecond
BMW1-0.662779-0.2707750.129462
2-0.2513081.9208960.756204
Lexus1-0.4661330.5908720.252439
2-1.226775-0.239043-0.023214

具有多級索引的軸的基本索引

使用多級索引進行索引用於以比常規索引更靈活的方式切片和選擇資料。

示例:按索引級別選擇資料

這是一個基本示例,演示瞭如何使用.loc[]方法索引具有多級索引的 Series 物件。

import pandas as pd
import numpy as np

# Creating MultiIndex from arrays
arrays = [["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
["one", "two", "one", "two", "one", "two", "one", "two"]]

# Creating a list of tuples from the arrays
tuples = list(zip(*arrays))

# Creating a MultiIndex from tuples
index = pd.MultiIndex.from_tuples(tuples, names=["first", "second"])

# Creating a Series with MultiIndex
s = pd.Series([2, 3, 1, 4, 6, 1, 7, 8], index=index)

print("MultiIndexed Series:\n", s)

# Indexing the MultiIndexed Series using .loc[]
print("\nSelecting data at index ('bar', 'one') and column 'A':")
print(s.loc[('bar', 'one')])

以下是上述程式碼的輸出:

MultiIndexed Series:
First Second
barone2
two2
one11
two4
one16
two1
one17
two8
dtype: int64 Selecting data at index ('bar', 'one') and column 'A': 2
廣告