Python Pandas - 在特定位置插入新索引值

pythonserver side programmingprogramming更新于 2025/12/28 8:44:17

要在特定位置插入新索引值,请使用 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

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

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

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

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

输出

这将产生以下输出 −

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

dtype 对象...
object

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

相关文章


有用资源