NumPy - BroadcastingWhich numpy code snippet correctly adds a 1D array to each row of a 2D array using broadcasting?Anp.array([[1,2],[3,4]]) + np.array([1,2])Bnp.array([[1,2],[3,4]]) + np.array([[1,2]])Cnp.array([[1,2],[3,4]]) + np.array([[1],[2]])Dnp.array([[1,2],[3,4]]) + np.array([1,2,3])Check Answer
Step-by-Step SolutionSolution:Step 1: Understand shapes involvedThe 2D array has shape (2,2). The 1D array with shape (2,) can broadcast across rows.Step 2: Check each option's shape compatibilitynp.array([[1,2],[3,4]]) + np.array([1,2]) adds (2,2) + (2,) which broadcasts correctly. np.array([[1,2],[3,4]]) + np.array([[1,2]]) is (2,2) + (1,2) also works but is less common. np.array([[1,2],[3,4]]) + np.array([[1],[2]]) shape (2,1) adds column-wise. np.array([[1,2],[3,4]]) + np.array([1,2,3]) shape (3,) incompatible.Final Answer:np.array([[1,2],[3,4]]) + np.array([1,2]) -> Option AQuick Check:Adding 1D array to 2D rows = np.array([[1,2],[3,4]]) + np.array([1,2]) [OK]Quick Trick: 1D array shape matches columns to add to rows [OK]Common Mistakes:Using incompatible shapes causing errorsConfusing row-wise and column-wise additionAdding arrays with different lengths
Master "Broadcasting" in NumPy9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More NumPy Quizzes Aggregation Functions - Aggregation along specific axes - Quiz 5medium Array Data Types - Boolean type - Quiz 7medium Array Data Types - Specifying dtype during creation - Quiz 8hard Array Manipulation - np.split() for dividing arrays - Quiz 2easy Array Operations - Type promotion in operations - Quiz 13medium Broadcasting - Broadcasting rules - Quiz 6medium Indexing and Slicing - 2D array indexing (row, col) - Quiz 9hard Indexing and Slicing - 2D array indexing (row, col) - Quiz 1easy Indexing and Slicing - Slicing with start:stop:step - Quiz 12easy Indexing and Slicing - np.where() for conditional selection - Quiz 3easy