Python Pandas - 刪除標籤的指定列表,製作新的索引


要刪除標籤的指定列表,製作新的索引,使用 index.drop() 方法。將其中 標籤列表 傳遞進去。

首先,匯入所需的庫:

import pandas as pd

建立索引:

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

顯示索引:

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

傳遞包含要刪除的標籤的列表:

print("\nUpdated index after deleting labels...\n",index.drop(['Bike', 'Ship']))

示例

以下是程式碼:

import pandas as pd

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

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

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

# Return a tuple of the shape of the underlying data
print("\nA tuple of the shape of underlying data...\n",index.shape)

# a list containing labels to be dropped are passed
print("\nUpdated index after deleting labels...\n",index.drop(['Bike', 'Ship']))

輸出

這將生成以下程式碼:

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

The dtype object...
object

A tuple of the shape of underlying data...
(5,)

Updated index after deleting labels...
Index(['Car', 'Truck', 'Airplane'], dtype='object')

更新於: 13-Oct-2021

瀏覽 299 次

開啟你的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.