Python Pandas - 重複索引元素


要在 Pandas 中重複索引元素,請使用 index.repeat() 方法。將重複數作為引數設定。首先,匯入所需的庫 −

import pandas as pd

建立 Pandas 索引 −

index = pd.Index(['Car','Bike','Airplane', 'Ship','Truck','Suburban'], name ='Transport')

顯示 Pandas 索引 −

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

重複索引元素 −

print("\nResult after repeating each index element twice...\n",index.repeat(2))

示例

以下是程式碼 −

import pandas as pd

# Creating Pandas index
index = pd.Index(['Car','Bike','Airplane', 'Ship','Truck','Suburban'], name ='Transport')

# 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)

# repeat elements of the index
print("\nResult after repeating each index element twice...\n",index.repeat(2))

輸出

這將產生以下輸出 −

Pandas Index...
Index(['Car', 'Bike', 'Airplane', 'Ship', 'Truck', 'Suburban'], dtype='object', name='Transport')

Number of elements in the index...
6

The dtype object...
object

Result after repeating each index element twice...
Index(['Car', 'Car', 'Bike', 'Bike', 'Airplane', 'Airplane', 'Ship', 'Ship',
'Truck', 'Truck', 'Suburban', 'Suburban'],
dtype='object', name='Transport')

更新於: 13-10-2021

449 次瀏覽

開啟您的 職業生涯

完成課程,獲得認證

入門
廣告
© . All rights reserved.