Python Pandas - 為已建立的索引物件設定索引名稱


要為已建立的索引物件設定索引名稱,請在 Pandas 中使用 index.set_names() 方法。首先,匯入所需的庫 -

import pandas as pd

建立 Pandas 索引 -

index = pd.Index(["Electronics", "Mobile Phones", "Accessories", "Home Decor", "Books"])

顯示 Pandas 索引 -

print("Pandas Index...\n",index)

設定索引名稱 -

print("\nSet the index name...\n",index.set_names('Products'))

示例

以下是程式碼 -

import pandas as pd

# Creating Pandas index
index = pd.Index(["Electronics", "Mobile Phones", "Accessories", "Home Decor", "Books"])

# Display the Pandas index
print("Pandas Index...\n",index)

# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)

# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)

# set the name of index
print("\nSet the index name...\n",index.set_names('Products'))

輸出

這將產生以下輸出 -

Pandas Index...
Index(['Electronics', 'Mobile Phones', 'Accessories', 'Home Decor', 'Books'], dtype='object')

Number of elements in the index...
5

The dtype object...
object

Set the index name...
Index(['Electronics', 'Mobile Phones', 'Accessories', 'Home Decor', 'Books'], dtype='object', name='Products')

更新於: 13-Oct-2021

215 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

馬上開始
廣告
© . All rights reserved.