Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas - แทนที่ค่าดัชนีเมื่อเงื่อนไขเป็น False (index.where + isin)

ในการแทนที่ค่าดัชนี (Index) ที่เงื่อนไขเป็น False ให้ใช้เมธอด index.where() ร่วมกับ index.isin() ใน Pandas

ขั้นตอนการทำงาน

1. นำเข้าไลบรารีที่จำเป็น

import pandas as pd

2. สร้างดัชนี

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

3. แสดงดัชนี

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

4. แทนที่ค่าที่ไม่ใช่ 'Decor'

print("\nReplace index vales where condition is False...\n", index.where(index.isin(['Decor']), 'Miscellaneous'))

ตัวอย่างโค้ดสมบูรณ์

import pandas as pd

# สร้างดัชนี
index = pd.Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], name='Products')

# แสดงดัชนี
print("Pandas Index...\n", index)

# แสดงจำนวนองค์ประกอบ
print("\nNumber of elements in the index...\n", index.size)

# แสดง dtype ของข้อมูล
print("\nThe dtype object...\n", index.dtype)

# แทนที่ค่าที่ไม่ใช่ 'Decor' ด้วย 'Miscellaneous'
print("\nReplace index vales where condition is False...\n", index.where(index.isin(['Decor']), 'Miscellaneous'))

ผลลัพธ์

Pandas Index... Index(['Electronics', 'Accessories', 'Decor', 'Books', 'Toys'], dtype='object', name='Products')
Number of elements in the index... 5
The dtype object... object
Replace index vales where condition is False... Index(['Miscellaneous', 'Miscellaneous', 'Decor', 'Miscellaneous', 'Miscellaneous'], dtype='object', name='Products')

คำอธิบาย

where(condition, other) คงค่าเดิมเมื่อ condition เป็น True แทนที่ด้วย other เมื่อเป็น False ที่นี่ isin(['Decor']) เป็น True เฉพาะ 'Decor' ดังนั้นค่าอื่นๆ ถูกแทนที่ด้วย 'Miscellaneous'