Python Pandas - 從最後一個索引開始插入新的索引值到第一個位置
要從最後一個索引開始插入新的索引值到第一個位置,可以使用 **index.insert()** 方法。將最後一個索引值 -1 和要插入的值作為引數設定。
首先,匯入所需的庫 -
import pandas as pd
建立 Pandas 索引 -
index = pd.Index(['Car','Bike','Airplane','Ship','Truck'])
顯示索引 -
print("Pandas Index...\n",index)使用 insert() 方法在最後一個索引的第一個位置插入一個新值。insert() 中的第一個引數是放置新索引值的位置。這裡的 -1 表示新索引值將插入到最後一個索引的第一個位置。第二個引數是要插入的新索引值。
index.insert(-1, '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 the first index from the last using the insert() method.
# The first parameter in the insert() is the location where the new index value is placed.
# The -1 here means the new index value gets inserted at the first index from the last.
# The second parameter is the new index value to be inserted.
print("\nAfter inserting a new index value...\n", index.insert(-1, 'Suburban'))輸出
這將產生以下輸出 -
Pandas Index... Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck'], dtype='object') The dtype object... object After inserting a new index value... Index(['Car', 'Bike', 'Airplane', 'Ship', 'Suburban', 'Truck'], dtype='object')
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP