Python Pandas - 根據原索引建立 DataFrame,但強制執行新索引


要根據原索引建立 DataFrame,但強制執行新索引,請使用 index.to_frame()。將引數index設定為False

首先,匯入必需的庫 -

import pandas as pd

建立 Pandas 索引 -

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

顯示 Pandas 索引

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

強制執行新索引並將索引轉換為 DataFrame。在此,實際索引將被另一個索引替換 -

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

示例

以下是程式碼 -

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)

# Enforce new index and convert index to DataFrame
# Here, the actual index gets replaced by another index
print("\nIndex to DataFrame...\n",index.to_frame(index=False))

輸出

這將產生以下輸出 -

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
0  Electronics
1  Accessories
2        Decor
3        Books
4         Toys

更新於: 13-Oct-2021

205 次瀏覽

開始你的職業生涯

透過完成該課程來獲得認證

入門
廣告