Python Pandas - 設定索引的名稱


要設定索引名稱,請使用 index.set_names() 並將索引名稱作為引數包含在內。

首先,匯入所需的庫 -

import pandas as pd

建立索引 -

index = pd.Index(['Car','Bike','Truck','Car','Airplane'])

顯示索引 -

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

設定索引名稱 -

print("\nIndex name...\n",index.set_names('Vehicle'))

示例

以下是程式碼 -

import pandas as pd

# Creating the index
index = pd.Index(['Car','Bike','Truck','Car','Airplane'])

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

# Return an array representing the data in the Index
print("\nArray...\n",index.values)

# Set the index name
print("\nIndex name...\n",index.set_names('Vehicle'))

輸出

這將生成以下程式碼 -

Pandas Index...
Index(['Car', 'Bike', 'Truck', 'Car', 'Airplane'], dtype='object')

Array...
['Car' 'Bike' 'Truck' 'Car' 'Airplane']

Index name...
Index(['Car', 'Bike', 'Truck', 'Car', 'Airplane'], dtype='object', name='Vehicle')

更新於: 13-10-2021

3K+ 瀏覽

啟動您的職業

完成課程獲得認證

立即開始
廣告
© . All rights reserved.