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')
广告