當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Pandas Index.to_frame()用法及代碼示例

Python是進行數據分析的一種出色語言,主要是因為以數據為中心的python軟件包具有奇妙的生態係統。 Pandas是其中的一種,使導入和分析數據更加容易。

Pandas Index.to_frame()函數根據給定索引創建一個dataFrame,其中包含包含Index的列。默認情況下,原始索引將在新數據幀中重用。為了增強新創建的 DataFrame 的新索引,我們將函數的index參數設置為false。

用法: Index.to_frame(index=True)

參數:
index:將返回的DataFrame的索引設置為原始索引。

返回:包含原始Index數據的DataFrame。

範例1:采用Index.to_frame()函數將索引轉換為數據幀。

# importing pandas as pd 
import pandas as pd 
  
# Creating the index 
idx = pd.Index(['Alice', 'Bob', 'Rachel', 'Tyler', 
                        'Louis'], name ='Winners') 
  
# Print the Index 
idx

輸出:

讓我們將索引轉換為 DataFrame 。

# convert the index into a dataframe 
idx.to_frame()

輸出:

該函數已將索引轉換為數據幀。默認情況下,該函數已使用原始Index的值創建了 DataFrame 的索引。

範例2:采用Index.to_frame()函數將索引轉換為 DataFrame ,以便創建的 DataFrame 使用新的索引值。

# importing pandas as pd 
import pandas as pd 
  
# Creating the index 
idx = pd.Index([22, 54, 85, 45, 69, 33]) 
  
# Print the Index 
idx

輸出:

讓我們將索引轉換為 DataFrame 。

# convert the index into a dataframe 
idx.to_frame(index = False)

輸出:



相關用法


注:本文由純淨天空篩選整理自Shubham__Ranjan大神的英文原創作品 Python | Pandas Index.to_frame()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。