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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP