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

Python Pandas - Thay thế giá trị Index khi điều kiện sai (False)

Để thay thế các giá trị Index nơi điều kiện là False, hãy sử dụng phương thức index.where() kết hợp với index.isin().

Các bước thực hiện

1. Import thư viện cần thiết

import pandas as pd

2. Tạo Pandas Index có tên

index = pd.Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], name='Products')

3. Hiển thị Index

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

4. Thay thế giá trị nơi điều kiện False (giữ 'Decor', thay resto)

print("\nThay thế giá trị Index nơi điều kiện False...\n", index.where(index.isin(['Decor']), 'Miscellaneous'))

Ví dụ hoàn chỉnh

import pandas as pd

# Tạo Pandas Index có tên
index = pd.Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], name='Products')

# Hiển thị Index
print("Pandas Index...\n", index)

# Số lượng phần tử
print("\nSố phần tử (size)...\n", index.size)

# Kiểu dữ liệu
print("\nKiểu dữ liệu (dtype)...\n", index.dtype)

# Thay thế nơi điều kiện False
# Giữ 'Decor', thay các giá trị khác thành 'Miscellaneous'
print("\nThay thế giá trị Index nơi điều kiện False...\n", index.where(index.isin(['Decor']), 'Miscellaneous'))

Kết quả đầu ra

Pandas Index...
Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], dtype='object', name='Products')
Số phần tử (size)...
5
Kiểu dữ liệu (dtype)...
object
Thay thế giá trị Index nơi điều kiện False...
Index(['Miscellaneous', 'Miscellaneous', 'Decor', 'Miscellaneous', 'Miscellaneous'], dtype='object', name='Products')

Giải thích: index.isin(['Decor']) tạo mask [False, False, True, False, False]. where(cond, other) giữ giá trị gốc nơi cond=True, thay bằng 'other' nơi cond=False. Ngược với mask(): index.mask(~index.isin(['Decor']), 'Miscellaneous') cho kết quả tương tự.