Python Pandas - 建立帶有原始索引和名稱的資料框


要建立同時帶有原始索引和名稱的資料框,請在 Pandas 中使用 **index.to_frame()** 方法。

首先,匯入所需的庫 -

import pandas as pd

建立 Pandas 索引 -

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

顯示 Pandas 索引 -

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

將索引轉換為資料框 -

print("\nIndex to DataFrame...\n",index.to_frame())

示例

以下是程式碼內容 -

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 DataFrame
print("\nIndex to DataFrame...\n",index.to_frame())

輸出

將生成以下輸出 -

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 DataFrame...
                Products
Products
Electronics  Electronics
Accessories  Accessories
Decor              Decor
Books              Books
Toys                Toys

更新於:13-Oct-2021

133 次瀏覽

開啟職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.