Python - 以不同的方式重複 Pandas 系列中的每個元素


要以不同的方式重複 Pandas 系列中的每個元素,請使用 index.repeat() 方法。首先,匯入所需的庫 -

import pandas as pd

建立 Pandas 索引 −

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

顯示 Pandas 索引 −

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

以不同的方式重複索引中的每個元素 −

print("\nResult after repeating each index element in a different way...\n", index.repeat([2,3,5,7]))

示例

以下為程式碼 −

import pandas as pd

# Creating Pandas index
index = pd.Index(['Car','Bike','Airplane', 'Ship'], 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 each element of the index in a dissimilar way
print("\nResult after repeating each index element in a different way...\n", index.repeat([2,3,5,7]))

輸出 

這將產生以下輸出 −

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

Number of elements in the index...
4

The dtype object...
object

Result after repeating each index element in a different way...
Index(['Car', 'Car', 'Bike', 'Bike', 'Bike', 'Airplane', 'Airplane',
'Airplane', 'Airplane', 'Airplane', 'Ship', 'Ship', 'Ship', 'Ship',
'Ship', 'Ship', 'Ship'],
dtype='object', name='Transport')

更新於: 13-10-2021

134 次瀏覽

開啟您的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.