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