Python Pandas - 返回索引选择的值的新索引


要用 Pandas 返回索引选择的值的新索引,请使用 index.take() 函数。首先,导入所需的库 -

import pandas as pd

创建 Pandas 索引 −

index = pd.Index(['Electronics','Accessories','Decor', 'Books', 'Toys'], name ='Products')

显示 Pandas 索引 −

print("Pandas Index...\n",index)

获取索引选择的值的新索引 −

print("\nA new Index of the values selected by the indices...\n",index.take([1,2]))

示例

以下为代码 −

import pandas as pd

# Creating Pandas index
index = pd.Index(['Electronics','Accessories','Decor', 'Books', 'Toys'], name ='Products')

# Display the Pandas index
print("Pandas Index...\n",index)

# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)

# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)

# Getting a new index of the values selected by indices
print("\nA new Index of the values selected by the indices...\n",index.take([1,2]))

输出

这将产生以下输出 −

Pandas Index...
Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], dtype='object', name='Products')

Number of elements in the index...
5

The dtype object...
object

A new Index of the values selected by the indices...
Index(['Accessories', 'Decor'], dtype='object', name='Products')

更新时间:13-Oct-2021

100 次浏览

启动您的事业

完成课程,获取证书

开始
广告
© . All rights reserved.