
👋 大家好,欢迎来到我的技术博客! 📚 在这里,我会分享学习笔记、实战经验与技术思考,力求用简单的方式讲清楚复杂的问题。 🎯 本文将围绕NumPy这个话题展开,希望能为你带来一些启发或实用的参考。 🌱 无论你是刚入门的新手,还是正在进阶的开发者,希望你都能有所收获!
文章目录
- 🧠 Python NumPy – 数组的逻辑运算 logical_and 与 logical_or
-
- 🔍 什么是逻辑运算?
- 📚 NumPy中的逻辑运算函数
-
- 🎯 logical_and 函数详解
- 🌟 logical_or 函数详解
- 🎨 广播机制在逻辑运算中的应用
- 📊 实际应用场景
-
- 📈 数据筛选和过滤
- 🎯 复杂条件组合
- 🔄 其他相关逻辑运算函数
-
- 🚫 logical_not 函数
- ⨁ logical_xor 函数
- 📐 性能比较和优化
- 🎯 高级应用技巧
-
- 📊 条件统计分析
- 🎨 图像处理中的应用
- 📋 错误处理和边界情况
- 🧩 组合逻辑运算的实际案例
- 📊 数据验证和质量检查
- 🎯 决策树逻辑模拟
- 📚 与其他库的集成
- 🎯 性能优化技巧
- 🧠 最佳实践总结
- 🔚 总结
🧠 Python NumPy – 数组的逻辑运算 logical_and 与 logical_or
在数据科学和数值计算的世界中,逻辑运算是一个基础而重要的概念。当我们处理大量数据时,经常需要根据某些条件来筛选、过滤或组合数据。NumPy作为Python中最重要的科学计算库之一,提供了强大的逻辑运算功能,其中logical_and和logical_or是两个核心函数。
🔍 什么是逻辑运算?
逻辑运算是一种基于布尔代数的数学运算,它处理的是真(true)和假(false)两种状态。在编程中,我们通常用1表示真,0表示假。逻辑运算包括与(AND)、或(OR)、非(NOT)等基本操作。
- 逻辑与(AND): 只有当所有条件都为真时,结果才为真
- 逻辑或(OR): 当至少有一个条件为真时,结果就为真
import numpy as np
# 基本的逻辑运算示例
print("基本逻辑运算:")
print(f"True AND True = {np.logical_and(True, True)}")
print(f"True AND False = {np.logical_and(True, False)}")
print(f"False AND False = {np.logical_and(False, False)}")
print()
print(f"True OR True = {np.logical_or(True, True)}")
print(f"True OR False = {np.logical_or(True, False)}")
print(f"False OR False = {np.logical_or(False, False)}")
📚 NumPy中的逻辑运算函数
NumPy提供了一系列用于数组逻辑运算的函数,这些函数能够高效地处理大型数组,并且支持广播机制。
🎯 logical_and 函数详解
numpy.logical_and(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
这个函数返回两个数组元素级逻辑与的结果。
import numpy as np
# 创建测试数组
arr1 = np.array([True, False, True, False])
arr2 = np.array([True, True, False, False])
# 使用logical_and
result_and = np.logical_and(arr1, arr2)
print("数组逻辑与运算:")
print(f"数组1: {arr1}")
print(f"数组2: {arr2}")
print(f"结果: {result_and}")
# 数值数组也可以进行逻辑运算
num_arr1 = np.array([1, 0, 3, 0])
num_arr2 = np.array([2, 1, 0, 0])
result_num_and = np.logical_and(num_arr1, num_arr2)
print("\\n数值数组逻辑与运算:")
print(f"数组1: {num_arr1}")
print(f"数组2: {num_arr2}")
print(f"结果: {result_num_and}")
🌟 logical_or 函数详解
numpy.logical_or(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
这个函数返回两个数组元素级逻辑或的结果。
import numpy as np
# 创建测试数组
arr1 = np.array([True, False, True, False])
arr2 = np.array([True, True, False, False])
# 使用logical_or
result_or = np.logical_or(arr1, arr2)
print("数组逻辑或运算:")
print(f"数组1: {arr1}")
print(f"数组2: {arr2}")
print(f"结果: {result_or}")
# 数值数组的逻辑或运算
num_arr1 = np.array([1, 0, 3, 0])
num_arr2 = np.array([2, 1, 0, 0])
result_num_or = np.logical_or(num_arr1, num_arr2)
print("\\n数值数组逻辑或运算:")
print(f"数组1: {num_arr1}")
print(f"数组2: {num_arr2}")
print(f"结果: {result_num_or}")
🎨 广播机制在逻辑运算中的应用
NumPy的强大之处在于其广播机制,这使得不同形状的数组也能进行逻辑运算。
import numpy as np
# 广播机制示例
arr_2d = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
arr_1d = np.array([1, 0, 1])
print("广播机制示例:")
print("二维数组:")
print(arr_2d)
print("一维数组:")
print(arr_1d)
# 逻辑与运算
result_broadcast_and = np.logical_and(arr_2d, arr_1d)
print("\\n广播后的逻辑与结果:")
print(result_broadcast_and)
# 逻辑或运算
result_broadcast_or = np.logical_or(arr_2d, arr_1d)
print("\\n广播后的逻辑或结果:")
print(result_broadcast_or)
📊 实际应用场景
让我们通过一些实际的应用场景来理解这两个函数的重要性。
📈 数据筛选和过滤
在数据分析中,我们经常需要根据多个条件来筛选数据。
import numpy as np
# 模拟学生成绩数据
students_scores = np.array([
[85, 92, 78], # 学生1: 数学、英语、物理
[90, 88, 95], # 学生2
[76, 82, 79], # 学生3
[95, 91, 88], # 学生4
[88, 75, 85] # 学生5
])
subjects = ['Math', 'English', 'Physics']
student_names = ['Alice', 'Bob', 'Charlie', 'David', 'Eve']
print("学生成绩表:")
for i, name in enumerate(student_names):
print(f"{name}: {dict(zip(subjects, students_scores[i]))}")
# 筛选条件:数学成绩大于80分且英语成绩大于85分的学生
math_condition = students_scores[:, 0] > 80 # 数学成绩
english_condition = students_scores[:, 1] > 85 # 英语成绩
qualified_students_and = np.logical_and(math_condition, english_condition)
print(f"\\n数学>80且英语>85的学生:")
for i, qualified in enumerate(qualified_students_and):
if qualified:
print(f"- {student_names[i]}")
# 筛选条件:数学成绩大于90分或物理成绩大于90分的学生
physics_condition = students_scores[:, 2] > 90
qualified_students_or = np.logical_or(students_scores[:, 0] > 90, physics_condition)
print(f"\\n数学>90或物理>90的学生:")
for i, qualified in enumerate(qualified_students_or):
if qualified:
print(f"- {student_names[i]}")
🎯 复杂条件组合
有时候我们需要更复杂的条件组合,这时可以嵌套使用逻辑运算函数。
import numpy as np
# 创建一个更复杂的数据集
data = np.random.randint(0, 100, (10, 3))
print("随机数据集:")
print(data)
# 定义多个条件
condition1 = data[:, 0] > 50 # 第一列大于50
condition2 = data[:, 1] < 70 # 第二列小于70
condition3 = data[:, 2] % 2 == 0 # 第三列为偶数
# 复杂条件:第一列>50 且 (第二列<70 或 第三列为偶数)
complex_condition = np.logical_and(
condition1,
np.logical_or(condition2, condition3)
)
print(f"\\n满足复杂条件的行索引: {np.where(complex_condition)[0]}")
# 显示满足条件的数据
print("\\n满足条件的数据:")
for i in np.where(complex_condition)[0]:
print(f"行{i}: {data[i]}")
🔄 其他相关逻辑运算函数
除了logical_and和logical_or,NumPy还提供了其他相关的逻辑运算函数。
🚫 logical_not 函数
import numpy as np
# logical_not 示例
arr = np.array([True, False, True, False])
not_result = np.logical_not(arr)
print("原数组:", arr)
print("NOT运算:", not_result)
# 数值数组的NOT运算
num_arr = np.array([1, 0, 3, 0])
num_not_result = np.logical_not(num_arr)
print("\\n数值数组:", num_arr)
print("NOT运算:", num_not_result)
⨁ logical_xor 函数
import numpy as np
# logical_xor 示例
arr1 = np.array([True, False, True, False])
arr2 = np.array([True, True, False, False])
xor_result = np.logical_xor(arr1, arr2)
print("数组1:", arr1)
print("数组2:", arr2)
print("XOR运算:", xor_result)
📐 性能比较和优化
让我们比较一下不同的实现方式的性能差异。
import numpy as np
import time
# 创建大型数组进行性能测试
size = 1000000
large_arr1 = np.random.randint(0, 2, size).astype(bool)
large_arr2 = np.random.randint(0, 2, size).astype(bool)
print("性能测试 – 大型数组逻辑运算:")
# 测试NumPy逻辑运算
start_time = time.time()
np_result = np.logical_and(large_arr1, large_arr2)
numpy_time = time.time() – start_time
print(f"NumPy logical_and 耗时: {numpy_time:.6f} 秒")
# 测试纯Python实现
start_time = time.time()
python_result = [a and b for a, b in zip(large_arr1, large_arr2)]
python_time = time.time() – start_time
print(f"Python and 运算耗时: {python_time:.6f} 秒")
print(f"NumPy比纯Python快 {python_time/numpy_time:.2f} 倍")
🎯 高级应用技巧
📊 条件统计分析
结合逻辑运算进行统计分析是非常有用的。
import numpy as np
# 模拟销售数据
np.random.seed(42)
sales_data = np.random.randint(1000, 10000, 100) # 100天的销售额
dates = np.arange(1, 101) # 100天
print("销售数据分析:")
# 分析高销售额的日子
high_sales_threshold = 7000
high_sales_days = sales_data > high_sales_threshold
high_sales_count = np.sum(high_sales_days)
high_sales_percentage = high_sales_count / len(sales_data) * 100
print(f"销售额超过{high_sales_threshold}的天数: {high_sales_count}")
print(f"占比: {high_sales_percentage:.2f}%")
# 分析连续高销售日
consecutive_high = np.logical_and(
high_sales_days[:–1],
high_sales_days[1:]
)
consecutive_count = np.sum(consecutive_high)
print(f"连续两天高销售额的次数: {consecutive_count}")
# 找出最大的连续高销售周期
def find_longest_consecutive(arr):
max_length = 0
current_length = 0
for val in arr:
if val:
current_length += 1
max_length = max(max_length, current_length)
else:
current_length = 0
return max_length
longest_period = find_longest_consecutive(high_sales_days)
print(f"最长连续高销售额周期: {longest_period}天")
🎨 图像处理中的应用
在图像处理中,逻辑运算常用于掩码操作。
import numpy as np
# 模拟简单的二值图像处理
image_height, image_width = 10, 10
image1 = np.random.randint(0, 2, (image_height, image_width)).astype(bool)
image2 = np.random.randint(0, 2, (image_height, image_width)).astype(bool)
print("图像处理示例:")
print("图像1:")
print(image1.astype(int))
print("图像2:")
print(image2.astype(int))
# 图像交集 (AND)
intersection = np.logical_and(image1, image2)
print("交集结果:")
print(intersection.astype(int))
# 图像并集 (OR)
union = np.logical_or(image1, image2)
print("并集结果:")
print(union.astype(int))
# 计算相似度
similarity = np.sum(intersection) / np.sum(union) if np.sum(union) > 0 else 0
print(f"图像相似度: {similarity:.2f}")
📋 错误处理和边界情况
在实际使用中,需要注意各种边界情况和错误处理。
import numpy as np
# 边界情况测试
print("边界情况测试:")
# 空数组
empty_arr = np.array([])
try:
result = np.logical_and(empty_arr, empty_arr)
print(f"空数组运算结果: {result}")
except Exception as e:
print(f"空数组运算错误: {e}")
# 不同形状的数组
arr1 = np.array([True, False, True])
arr2 = np.array([True, False])
try:
# 这会因为形状不匹配而报错
result = np.logical_and(arr1, arr2)
print(result)
except ValueError as e:
print(f"形状不匹配错误: {e}")
# 正确的广播示例
arr3 = np.array([[True, False, True]])
arr4 = np.array([True, False, True])
result = np.logical_and(arr3, arr4)
print(f"正确广播示例:\\n{result}")
# NaN值处理
arr_with_nan = np.array([1, 0, np.nan])
normal_arr = np.array([1, 1, 1])
result_with_nan = np.logical_and(arr_with_nan, normal_arr)
print(f"包含NaN的逻辑运算: {result_with_nan}")
🧩 组合逻辑运算的实际案例
让我们通过一个综合案例来展示如何组合使用这些逻辑运算函数。
import numpy as np
# 模拟电商用户行为数据
np.random.seed(123)
users_count = 1000
# 用户特征数据
user_data = {
'age': np.random.randint(18, 80, users_count),
'income': np.random.randint(20000, 150000, users_count),
'purchase_history': np.random.randint(0, 50, users_count),
'days_since_last_visit': np.random.randint(0, 365, users_count),
'is_premium_member': np.random.choice([True, False], users_count, p=[0.2, 0.8])
}
print("电商用户数据分析:")
# 定义VIP客户的标准:
# 1. 年龄在25-50岁之间
# 2. 收入超过60000 或者 是高级会员
# 3. 购买历史超过10次 且 最近30天内访问过网站
# 条件1:年龄在25-50岁之间
age_condition = np.logical_and(user_data['age'] >= 25, user_data['age'] <= 50)
# 条件2:收入超过60000 或者 是高级会员
income_or_premium = np.logical_or(user_data['income'] > 60000, user_data['is_premium_member'])
# 条件3:购买历史超过10次 且 最近30天内访问过网站
purchase_and_recent_visit = np.logical_and(
user_data['purchase_history'] > 10,
user_data['days_since_last_visit'] <= 30
)
# 综合条件
vip_customers = np.logical_and(
np.logical_and(age_condition, income_or_premium),
purchase_and_recent_visit
)
vip_count = np.sum(vip_customers)
vip_percentage = vip_count / users_count * 100
print(f"VIP客户数量: {vip_count}")
print(f"VIP客户占比: {vip_percentage:.2f}%")
# 分析不同类型VIP客户的特征
premium_vip = np.logical_and(vip_customers, user_data['is_premium_member'])
high_income_vip = np.logical_and(vip_customers, user_data['income'] > 60000)
print(f"\\nVIP客户细分:")
print(f"- 高级会员VIP: {np.sum(premium_vip)}人")
print(f"- 高收入VIP: {np.sum(high_income_vip)}人")
# 计算平均特征
if vip_count > 0:
vip_indices = np.where(vip_customers)[0]
avg_age_vip = np.mean(user_data['age'][vip_indices])
avg_income_vip = np.mean(user_data['income'][vip_indices])
avg_purchase_vip = np.mean(user_data['purchase_history'][vip_indices])
print(f"\\nVIP客户平均特征:")
print(f"- 平均年龄: {avg_age_vip:.1f}岁")
print(f"- 平均收入: ${avg_income_vip:,.0f}")
print(f"- 平均购买次数: {avg_purchase_vip:.1f}次")
📊 数据验证和质量检查
逻辑运算在数据验证中也发挥着重要作用。
import numpy as np
# 模拟传感器数据
sensor_data = np.random.normal(25, 5, 1000) # 温度数据,均值25度,标准差5度
timestamps = np.arange(1000)
# 添加一些异常值
sensor_data[np.random.choice(1000, 10)] = np.nan
sensor_data[np.random.choice(1000, 5)] = 100 # 异常高温
sensor_data[np.random.choice(1000, 5)] = –50 # 异常低温
print("传感器数据质量检查:")
# 检查NaN值
nan_mask = np.isnan(sensor_data)
nan_count = np.sum(nan_mask)
print(f"NaN值数量: {nan_count}")
# 检查异常温度值 (合理范围: -10到50度)
valid_range = np.logical_and(sensor_data >= –10, sensor_data <= 50)
invalid_values = np.logical_and(np.logical_not(valid_range), np.logical_not(nan_mask))
invalid_count = np.sum(invalid_values)
print(f"异常温度值数量: {invalid_count}")
# 综合有效数据掩码
valid_data_mask = np.logical_and(
np.logical_not(nan_mask),
valid_range
)
valid_count = np.sum(valid_data_mask)
print(f"有效数据点数量: {valid_count}")
print(f"数据有效性: {valid_count/len(sensor_data)*100:.2f}%")
# 清理后的统计数据
if valid_count > 0:
clean_data = sensor_data[valid_data_mask]
print(f"\\n清理后统计数据:")
print(f"- 平均温度: {np.mean(clean_data):.2f}°C")
print(f"- 温度标准差: {np.std(clean_data):.2f}°C")
print(f"- 最高温度: {np.max(clean_data):.2f}°C")
print(f"- 最低温度: {np.min(clean_data):.2f}°C")
🎯 决策树逻辑模拟
我们可以用逻辑运算来模拟简单的决策树逻辑。
import numpy as np
# 模拟贷款审批决策系统
customers_count = 100
customer_data = {
'credit_score': np.random.randint(300, 850, customers_count),
'annual_income': np.random.randint(20000, 150000, customers_count),
'debt_to_income_ratio': np.random.uniform(0, 0.6, customers_count),
'employment_years': np.random.randint(0, 30, customers_count),
'has_bankruptcy': np.random.choice([True, False], customers_count, p=[0.1, 0.9])
}
print("贷款审批决策系统模拟:")
# 贷款审批规则:
# 规则1:信用分数>=700 且 年收入>=50000 且 债务收入比<=0.3
rule1_approved = np.logical_and.reduce([
customer_data['credit_score'] >= 700,
customer_data['annual_income'] >= 50000,
customer_data['debt_to_income_ratio'] <= 0.3
])
# 规则2:信用分数>=650 且 就业年限>=2年 且 无破产记录
rule2_approved = np.logical_and.reduce([
customer_data['credit_score'] >= 650,
customer_data['employment_years'] >= 2,
np.logical_not(customer_data['has_bankruptcy'])
])
# 规则3:信用分数>=600 且 年收入>=30000 且 债务收入比<=0.4 且 就业年限>=1年
rule3_approved = np.logical_and.reduce([
customer_data['credit_score'] >= 600,
customer_data['annual_income'] >= 30000,
customer_data['debt_to_income_ratio'] <= 0.4,
customer_data['employment_years'] >= 1
])
# 最终批准:满足任意一条规则
final_approval = np.logical_or.reduce([rule1_approved, rule2_approved, rule3_approved])
approved_count = np.sum(final_approval)
approval_rate = approved_count / customers_count * 100
print(f"总申请人数: {customers_count}")
print(f"批准人数: {approved_count}")
print(f"批准率: {approval_rate:.2f}%")
# 分析各规则的贡献
print(f"\\n各规则批准人数:")
print(f"- 规则1: {np.sum(rule1_approved)}人")
print(f"- 规则2: {np.sum(rule2_approved)}人")
print(f"- 规则3: {np.sum(rule3_approved)}人")
# 找出被多重规则批准的客户
multi_rule_approved = np.sum([
rule1_approved.astype(int),
rule2_approved.astype(int),
rule3_approved.astype(int)
], axis=0) > 1
multi_approved_count = np.sum(multi_rule_approved)
print(f"被多条规则同时批准的客户: {multi_approved_count}人")
#mermaid-svg-NESITItSMQRxpr61{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-NESITItSMQRxpr61 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-NESITItSMQRxpr61 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-NESITItSMQRxpr61 .error-icon{fill:#552222;}#mermaid-svg-NESITItSMQRxpr61 .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-NESITItSMQRxpr61 .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-NESITItSMQRxpr61 .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-NESITItSMQRxpr61 .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-NESITItSMQRxpr61 .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-NESITItSMQRxpr61 .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-NESITItSMQRxpr61 .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-NESITItSMQRxpr61 .marker{fill:#333333;stroke:#333333;}#mermaid-svg-NESITItSMQRxpr61 .marker.cross{stroke:#333333;}#mermaid-svg-NESITItSMQRxpr61 svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-NESITItSMQRxpr61 p{margin:0;}#mermaid-svg-NESITItSMQRxpr61 .label{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;color:#333;}#mermaid-svg-NESITItSMQRxpr61 .cluster-label text{fill:#333;}#mermaid-svg-NESITItSMQRxpr61 .cluster-label span{color:#333;}#mermaid-svg-NESITItSMQRxpr61 .cluster-label span p{background-color:transparent;}#mermaid-svg-NESITItSMQRxpr61 .label text,#mermaid-svg-NESITItSMQRxpr61 span{fill:#333;color:#333;}#mermaid-svg-NESITItSMQRxpr61 .node rect,#mermaid-svg-NESITItSMQRxpr61 .node circle,#mermaid-svg-NESITItSMQRxpr61 .node ellipse,#mermaid-svg-NESITItSMQRxpr61 .node polygon,#mermaid-svg-NESITItSMQRxpr61 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-NESITItSMQRxpr61 .rough-node .label text,#mermaid-svg-NESITItSMQRxpr61 .node .label text,#mermaid-svg-NESITItSMQRxpr61 .image-shape .label,#mermaid-svg-NESITItSMQRxpr61 .icon-shape .label{text-anchor:middle;}#mermaid-svg-NESITItSMQRxpr61 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-NESITItSMQRxpr61 .rough-node .label,#mermaid-svg-NESITItSMQRxpr61 .node .label,#mermaid-svg-NESITItSMQRxpr61 .image-shape .label,#mermaid-svg-NESITItSMQRxpr61 .icon-shape .label{text-align:center;}#mermaid-svg-NESITItSMQRxpr61 .node.clickable{cursor:pointer;}#mermaid-svg-NESITItSMQRxpr61 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-NESITItSMQRxpr61 .arrowheadPath{fill:#333333;}#mermaid-svg-NESITItSMQRxpr61 .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-NESITItSMQRxpr61 .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-NESITItSMQRxpr61 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-NESITItSMQRxpr61 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-NESITItSMQRxpr61 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-NESITItSMQRxpr61 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-NESITItSMQRxpr61 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-NESITItSMQRxpr61 .cluster text{fill:#333;}#mermaid-svg-NESITItSMQRxpr61 .cluster span{color:#333;}#mermaid-svg-NESITItSMQRxpr61 div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-NESITItSMQRxpr61 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-NESITItSMQRxpr61 rect.text{fill:none;stroke-width:0;}#mermaid-svg-NESITItSMQRxpr61 .icon-shape,#mermaid-svg-NESITItSMQRxpr61 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-NESITItSMQRxpr61 .icon-shape p,#mermaid-svg-NESITItSMQRxpr61 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-NESITItSMQRxpr61 .icon-shape .label rect,#mermaid-svg-NESITItSMQRxpr61 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-NESITItSMQRxpr61 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-NESITItSMQRxpr61 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-NESITItSMQRxpr61 :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}
是
是
是
否
否
否
是
是
否
是
是
是
是
否
否
否
否
开始贷款审批
信用分数≥700?
年收入≥50000?
债务收入比≤0.3?
批准 – 规则1
就业年限≥2年?
无破产记录?
批准 – 规则2
信用分数≥600?
年收入≥30000?
债务收入比≤0.4?
就业年限≥1年?
批准 – 规则3
拒绝
结束
📚 与其他库的集成
NumPy的逻辑运算可以很好地与其他Python库集成使用。
import numpy as np
import pandas as pd
# 创建Pandas DataFrame
df = pd.DataFrame({
'product': ['A', 'B', 'C', 'D', 'E', 'F'],
'price': [100, 250, 80, 300, 150, 400],
'rating': [4.5, 3.8, 4.2, 4.8, 3.5, 4.6],
'in_stock': [True, False, True, True, False, True],
'category': ['Electronics', 'Books', 'Electronics', 'Clothing', 'Books', 'Electronics']
})
print("产品数据:")
print(df)
# 使用NumPy逻辑运算进行复杂查询
# 查找电子产品中价格在100-300之间且评分高于4.0且有库存的产品
electronics_filter = df['category'] == 'Electronics'
price_filter = np.logical_and(df['price'] >= 100, df['price'] <= 300)
rating_filter = df['rating'] > 4.0
stock_filter = df['in_stock']
# 综合条件
combined_filter = np.logical_and.reduce([
electronics_filter,
price_filter,
rating_filter,
stock_filter
])
filtered_products = df[combined_filter]
print(f"\\n符合条件的产品:")
print(filtered_products)
# 统计信息
total_products = len(df)
filtered_count = len(filtered_products)
print(f"\\n统计信息:")
print(f"总产品数: {total_products}")
print(f"符合条件产品数: {filtered_count}")
print(f"符合条件比例: {filtered_count/total_products*100:.1f}%")
🎯 性能优化技巧
在处理大数据集时,合理的使用逻辑运算可以显著提升性能。
import numpy as np
import time
# 性能优化示例
def performance_comparison():
# 创建大型数据集
size = 10**7
arr1 = np.random.randint(0, 2, size).astype(bool)
arr2 = np.random.randint(0, 2, size).astype(bool)
arr3 = np.random.randint(0, 2, size).astype(bool)
print("大规模数据逻辑运算性能测试:")
# 方法1:逐步运算
start_time = time.time()
step1 = np.logical_and(arr1, arr2)
result1 = np.logical_or(step1, arr3)
time1 = time.time() – start_time
# 方法2:一次性运算
start_time = time.time()
result2 = np.logical_or(np.logical_and(arr1, arr2), arr3)
time2 = time.time() – start_time
# 方法3:使用reduce
start_time = time.time()
result3 = np.logical_or.reduce([np.logical_and(arr1, arr2), arr3])
time3 = time.time() – start_time
print(f"逐步运算耗时: {time1:.4f}秒")
print(f"一次性运算耗时: {time2:.4f}秒")
print(f"Reduce方法耗时: {time3:.4f}秒")
# 验证结果一致性
print(f"结果一致性检查: {np.array_equal(result1, result2) and np.array_equal(result2, result3)}")
performance_comparison()
🧠 最佳实践总结
通过以上大量的示例和分析,我们可以总结出使用NumPy逻辑运算的最佳实践:
import numpy as np
# 最佳实践示例
class LogicalOperationsBestPractices:
def __init__(self):
self.data = np.random.randint(0, 100, (1000, 5))
def safe_logical_operation(self, arr1, arr2, operation='and'):
"""安全的逻辑运算"""
try:
# 检查输入类型
if not isinstance(arr1, np.ndarray) or not isinstance(arr2, np.ndarray):
raise TypeError("输入必须是NumPy数组")
# 检查形状兼容性
if arr1.shape != arr2.shape:
# 尝试广播
try:
np.broadcast_arrays(arr1, arr2)
except ValueError:
raise ValueError("数组形状不兼容且无法广播")
# 执行运算
if operation == 'and':
return np.logical_and(arr1, arr2)
elif operation == 'or':
return np.logical_or(arr1, arr2)
else:
raise ValueError("不支持的操作类型")
except Exception as e:
print(f"逻辑运算错误: {e}")
return None
def complex_condition_builder(self, conditions_list, logic_operator='and'):
"""复杂条件构建器"""
if not conditions_list:
return np.array([], dtype=bool)
if len(conditions_list) == 1:
return conditions_list[0]
if logic_operator == 'and':
return np.logical_and.reduce(conditions_list)
elif logic_operator == 'or':
return np.logical_or.reduce(conditions_list)
else:
raise ValueError("不支持的逻辑操作符")
# 使用示例
practices = LogicalOperationsBestPractices()
# 创建测试条件
condition1 = practices.data[:, 0] > 50
condition2 = practices.data[:, 1] < 75
condition3 = practices.data[:, 2] % 2 == 0
# 构建复杂条件
complex_conditions = [condition1, condition2, condition3]
# AND操作
and_result = practices.complex_condition_builder(complex_conditions, 'and')
print(f"AND复合条件满足的元素数量: {np.sum(and_result)}")
# OR操作
or_result = practices.complex_condition_builder(complex_conditions, 'or')
print(f"OR复合条件满足的元素数量: {np.sum(or_result)}")
# 安全运算示例
safe_result = practices.safe_logical_operation(condition1, condition2, 'and')
if safe_result is not None:
print(f"安全运算成功,结果长度: {len(safe_result)}")
🔚 总结
NumPy的logical_and和logical_or函数为我们提供了强大而灵活的逻辑运算能力。通过本文的详细介绍和丰富的代码示例,我们可以看到:
在日常的数据科学工作中,熟练掌握这些逻辑运算函数将大大提高我们的工作效率。记住关键点:
- ✅ 优先使用NumPy的向量化运算而不是循环
- ✅ 注意数组形状的兼容性和广播规则
- ✅ 合理组合多个逻辑运算来构建复杂条件
- ✅ 在处理大数据时考虑内存效率
- ✅ 始终进行结果验证确保正确性
随着对NumPy逻辑运算理解的深入,你会发现它们在解决实际问题时的价值远超想象。无论是简单的数据筛选还是复杂的业务逻辑判断,这些工具都能为你提供强有力的支持。
希望这篇详细的介绍能帮助你更好地理解和应用NumPy的逻辑运算功能!🚀
🙌 感谢你读到这里! 🔍 技术之路没有捷径,但每一次阅读、思考和实践,都在悄悄拉近你与目标的距离。 💡 如果本文对你有帮助,不妨 👍 点赞、📌 收藏、📤 分享 给更多需要的朋友! 💬 欢迎在评论区留下你的想法、疑问或建议,我会一一回复,我们一起交流、共同成长 🌿 🔔 关注我,不错过下一篇干货!我们下期再见!✨




