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')
廣告