Python Pandas - 在倒数第一个索引处插入新索引值

pythonserver side programmingprogramming更新于 2025/12/28 9:48:17

要在倒数第一个索引处插入新索引值,请使用 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

# 创建 Pandas 索引
index = pd.Index(['Car','Bike','Airplane','Ship','Truck'])

# 显示索引
print("Pandas Index...\n",index)

# 返回数据的 dtype
print("\ndtype 对象...\n",index.dtype)

# 使用 insert() 方法在倒数第一个索引处插入新值。
# insert() 中的第一个参数是放置新索引值的位置。
# 这里的 -1 表示新索引值插入到倒数第一个索引处。
# 第二个参数是要插入的新索引值。
print("\nAfter inserting a new index value...\n", index.insert(-1, 'Suburban'))

输出

这将产生以下输出 −

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

dtype 对象...
object

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

相关文章


有用资源