Python Pandas - 在某一特定位置插入一個新的索引值


要向某個檔案中插入新索引值,請在 Pandas 中使用 index.insert() 方法。首先,匯入必要的庫 -

import pandas as pd

建立 Pandas 索引 −

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

顯示索引 −

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

使用 insert() 方法在特定位置插入一個新值。insert() 中的第一個引數是將新索引值放置的位置。此處中的 2 表示將新索引值插入到索引 2,即位置 3。第二個引數是要插入的新索引值。

print("\nAfter inserting a new index value...\n", index.insert(2, 'Suburban'))

示例

以下是程式碼 −

import pandas as pd

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

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

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

# Insert a new value at a specific position using the insert() method
# The first parameter in the insert() is the location where the new index value is placed.
# The 2 here means the new index value gets inserted at index 2 i.e. position 3
# The second parameter is the new index value to be inserted.
print("\nAfter inserting a new index value...\n", index.insert(2, 'Suburban'))

輸出

這會生成以下輸出 −

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

The dtype object...
object

After inserting a new index value...
Index(['Car', 'Bike', 'Suburban', 'Airplane', 'Ship', 'Truck'], dtype='object')

更新於: 13-Oct-2021

2K+ 瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.