如何使用Numpy对两个同尺寸0-1 CSV矩阵执行自定义逻辑运算?
Hey there! Let's break this down step by step. First, I spotted a small inconsistency between the rules you listed and your example output—so I’ll start by clarifying the actual working logic from your sample data, then show you how to implement this cleanly with NumPy (way faster than manual loops!).
First, Clarify the Correct Rule
From your example:
A = [ [1, 0, 1], [1, 1, 1] ]
B = [ [1, 0, 0], [1, 0, 0] ]
C = [ [0, 0, 1], [0, 1, 1] ]
We can deduce the real rule for matrix C:
- C[i][j] = 1 if and only if A[i][j] is 1 AND B[i][j] is 0
- C[i][j] = 0 in all other cases (A=1&B=1, A=0&B=0, A=0&B=1)
Your original rule had a typo for the A=1&B=0 case—no worries, we’ve got the right logic now!
Step 1: Load Your CSV Files into NumPy Arrays
First, we’ll read your CSV files into NumPy arrays. This is straightforward with np.genfromtxt:
import numpy as np # Replace with your actual file paths matrix_a = np.genfromtxt("matrix_a.csv", delimiter=",", dtype=int) matrix_b = np.genfromtxt("matrix_b.csv", delimiter=",", dtype=int)
The dtype=int ensures we’re working with integers (0s and 1s) instead of floats.
Step 2: Generate Matrix C with Vectorized Operations
NumPy’s superpower is vectorized operations—no slow Python loops needed! Here are a few clean ways to implement the rule:
Method 1: Boolean Indexing (Most Intuitive)
We’ll initialize C as a zero matrix, then set the positions where A=1 and B=0 to 1:
# Create a zero matrix with the same shape as A/B matrix_c = np.zeros_like(matrix_a) # Find all positions where A is 1 AND B is 0, set those to 1 matrix_c[(matrix_a == 1) & (matrix_b == 0)] = 1
Method 2: Bitwise Operations (Shorter)
Since we’re working with 0s and 1s, we can use bitwise operations. The rule translates to A AND (NOT B)—we just need to make sure we end up with 0/1 values (not negative numbers from the bitwise NOT):
matrix_c = (matrix_a & (~matrix_b)) & 1
Method 3: np.where (Explicit Conditional)
If you prefer a more explicit "if-else" style, np.where is perfect:
matrix_c = np.where((matrix_a == 1) & (matrix_b == 0), 1, 0)
Step 3: Verify with Your Example
Let’s test this with your sample data to confirm it works:
a = np.array([[1, 0, 1], [1, 1, 1]]) b = np.array([[1, 0, 0], [1, 0, 0]]) c = np.where((a == 1) & (b == 0), 1, 0) print(c) # Output matches your example exactly: # [[0 0 1] # [0 1 1]]
Step 4: Save the Result to CSV
If you need to export matrix C back to a CSV file, use np.savetxt:
np.savetxt("matrix_c.csv", matrix_c, delimiter=",", fmt="%d")
The fmt="%d" ensures we save integers instead of floats.
Why use NumPy instead of manual loops? For large matrices, NumPy’s vectorized operations run orders of magnitude faster than Python loops (since they’re implemented in C under the hood), and the code is much cleaner and easier to maintain.
内容的提问来源于stack exchange,提问作者Andrii

