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 次浏览

开启您的职业

通过完成课程获得认证

开始
广告