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.