Python Pandas - 建立一個既包含原始索引又包含名稱的 Series


要建立一個同時包含原始索引和名稱的 Series,請在 Pandas 中使用 index.to_series() 方法。首先,匯入所需的庫 -

import pandas as pd

建立 Pandas 索引

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

將索引轉換為 Series −

print("\nIndex to series...\n",index.to_series())

示例

以下是程式碼 −

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)

# convert index to series
print("\nIndex to series...\n",index.to_series())

輸出

這將產生以下輸出 −

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

Number of elements in the index...
5

The dtype object...
object

Index to series...
Products
Electronics  Electronics
Accessories  Accessories
Decor              Decor
Books              Books
Toys                Toys
Name: Products, dtype: object

更新於: 2021 年 10 月 13 日

142 次瀏覽

開啟你的 職業

透過完成本課程取得認證

立即開始
廣告
© . All rights reserved.