สมมติว่าคุณมี Series ที่มีค่า Boolean และ NaN และต้องการดำเนินการ Boolean logic กับค่า True
วิธีแก้ปัญหา
- สร้าง Series ที่มี dtype='bool' (รองรับ True, False, NaN)
- ใช้ bitwise operators:
&(AND),|(OR),^(XOR) กับค่า True
ตัวอย่างโค้ด
import pandas as pd
import numpy as np
# Series ที่มี True, NaN, False
series_and = pd.Series([True, np.nan, False], dtype="bool") & True
series_or = pd.Series([True, np.nan, False], dtype="bool") | True
series_xor = pd.Series([True, np.nan, False], dtype="bool") ^ True
print("AND operation:")
print(series_and)
print("\nOR operation:")
print(series_or)
print("\nXOR operation:")
print(series_xor)
ผลลัพธ์
AND operation:
0 True
1 True
2 False
dtype: bool
OR operation:
0 True
1 True
2 True
dtype: bool
XOR operation:
0 False
1 False
2 True
dtype: bool
คำอธิบายตารางความจริง (Truth Table) กับ True:
| Input | AND True | OR True | XOR True |
|---|---|---|---|
| True | True | True | False |
| NaN | True* | True | False* |
| False | False | True | True |
* ใน pandas NaN ใน boolean context มักถูกพิจารณาเป็น True สำหรับ AND/OR แต่ XOR จะเป็น False
หมายเหตุ: ใช้ bitwise operators (&, |, ^) ไม่ใช่ logical operators (and, or) เพราะทำงานได้กับ Series/array