Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas - Lặp lại các phần tử của Index


Để lặp lại các phần tử của một Index, hãy sử dụng phương thức index.repeat() trong Pandas. Thiết lập số lần lặp lại làm đối số. Trước tiên, nhập các thư viện cần thiết:

import pandas as pd

Tạo Pandas Index:

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

Hiển thị Pandas Index:

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

Lặp lại các phần tử của index:

print("\nKết quả sau khi lặp lại từng phần tử index 2 lần...\n", index.repeat(2))

Ví dụ

Dưới đây là mã hoàn chỉnh:

import pandas as pd
# Tạo Pandas Index
index = pd.Index(['Car','Bike','Airplane', 'Ship','Truck','Suburban'], name='Transport')
# Hiển thị Pandas Index
print("Pandas Index...\n", index)
# Trả về số lượng phần tử trong Index
print("\nSố lượng phần tử trong index...\n", index.size)
# Trả về kiểu dữ liệu
print("\nĐối tượng dtype...\n", index.dtype)
# Lặp lại các phần tử của index
print("\nKết quả sau khi lặp lại từng phần tử index 2 lần...\n", index.repeat(2))

Kết quả

Đoạn mã trên sẽ cho ra kết quả sau:

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