Ошибка valueerror shape mismatch objects cannot be broadcast to a single shape

If you get this error, as the error says, the shapes of the objects being operated on cannot be broadcast to be the same shape. An example is:

x = np.array([1, 2, 3])
y = np.array([4, 5])

a = np.broadcast_arrays(x, y)             # ValueError: shape mismatch
b = np.broadcast_arrays(x, y[:, None])    # OK; calling `np.add.reduce()` on it also OK

In the first case (a), numpy couldn’t coerce both arrays to have the same shape. However, in the second case (b), since one is an 1D array (shape=(3,)) and the other is a 2D array (shape=(2,1)), both can be broadcast into an array of shape=(2,3).


No function in scipy.stats produces this error anymore; for example, pearsonr performs data validation to check if the sample lengths match, which shows a more helpful message.

One popular function that shows this error is when plotting a bar plot using matplotlib. For example,

x = ['a', 'b']
y = [1, 2, 3]
plt.bar(x, y);       # ValueError: shape mismatch
plt.barh(x, y);      # ValueError: shape mismatch

A common error is to filter one array using some boolean condition but don’t apply the same boolean array to the other array. For example:

x = np.array(['a', 'b', 'c'])
y = np.array([1, 2, 3])
plt.bar(x, y);             # OK
plt.bar(x, y[y>1]);        # ValueError: shape mismatch
plt.bar(x[y>1], y[y>1]);   # OK

So make sure both arrays have the same length.

Why is valueerror shape mismatch objects cannot be broadcastValueerror: shape mismatch: objects cannot be broadcast to a single shape error might occur when you perform an arithmetic operation on differently shaped variables. Moreover, another reason can be an attempt to plot the vectors having different lengths. Don’t worry if the causes have confused you even more because this article will explain to you the same in detail. Read more to dive into the details of the causes and get the best solution to eliminate the stated error.

Contents

  • Why Is ValueError: Shape Mismatch: Objects Cannot Be Broadcast To a Single Shape Occurring?
    • – Performing Arithmetic Operation on Differently Shaped Variables
    • – Plotting Vectors of Different Lengths
  • How To Fix the Above Error?
    • – Adjust the Shapes of Variables To Remove ValueError: Shape Mismatch: Objects Cannot Be Broadcast To a Single Shape
    • – Align the Lengths of the Vectors To Be Plotted
  • Solving Your Query
    • – Why Does the Error Targeting Mismatched Shapes Pops Up While Using str.len()?
  • Conclusion

The above error is occurring because you are trying to compute differently shaped variables. Also, the given value error might appear when you plot the vectors that don’t have similar lengths. Please read the cause descriptions for more clarity.

– Performing Arithmetic Operation on Differently Shaped Variables

The line of code that attempts to calculate differently shaped variables will throw the error mentioned above. It is because the given variables won’t be compatible with each other. Consequently, they won’t be able to produce an output irrespective of the type of arithmetic operator being used.

The issue was once noticed while using SciPy’s pearsonr(x,y) method. The erroneous code inside the said method looked like this: res = n*(np.add.reduce(xm*ym)).

So, here the issue seemed to be related to the x and y variables. The different shapes of x and y don’t allow the multiplication of both the variables resulting in the above error.

– Plotting Vectors of Different Lengths

Are you getting the above error while working with matplotlib and numpy libraries? Well, then a possible reason can be the different lengths of the vectors to be plotted. It is because the matplotlib doesn’t know about the procedure of plotting such vectors.

The example erroneous code can be seen here:

import matplotlib.pyplot as plt
import numpy as np
vector1 = np.arange(9)
vector2 = np.arange(8)
plt.bar(vector1, vector2)

How To Fix the Above Error?

You can fix the value error stated in the title by adjusting the shapes of the variables and the lengths of the vectors accordingly. So, once you’ve figured out the erroneous code in your program, opt for any of the given solutions to resolve the error:

– Adjust the Shapes of Variables To Remove ValueError: Shape Mismatch: Objects Cannot Be Broadcast To a Single Shape

You should adjust the shapes of the variables before performing any arithmetic operation on the same. Indeed, it is important to ensure that the variables are compatible with each other. Well, the error might go away even if you manipulate the variables on the same line that performs an arithmetic operation on the same. Here, you only need to ensure that the manipulation is carried out before the calculation.

– Align the Lengths of the Vectors To Be Plotted

Did your coding mistake resemble the second cause shared above? If yes, then the solution is super-easy and simplest. You only have to adjust the lengths of the vectors to make them the same, not even one number up or down. Consequently, you’ll see the error go away and the vectors will be plotted perfectly.

Solving Your Query

Here is a common question that relates to the above error:

– Why Does the Error Targeting Mismatched Shapes Pops Up While Using str.len()?

The stated error might occur when you improperly specify a condition that compares the lengths of two or more variables by using str.len(). Here, you should look for any extra parenthesis and remove them. Also, wrapping each sub-condition inside individual parenthesis can make the code work for you and eliminate the error.

Here is an example code that works:

(str1.str.len() != str2.str.len())
((str1.str.len() != 7) & (str2.str.len() == 10))

Conclusion

You have now understood enough about the value error that targetted the shapes of the variables and indirectly, the lengths of the vectors as well. Please see the below list to have a quick revision of the solutions discussed above:

  • The error is occurring because you are trying to compute differently shaped variables.
  • Adjusting the shapes of the variables before using them in a mathematical expression can help you in resolving the error.
  • You should ensure that the lengths of the vectors are the same before plotting them to solve the above error.

Valueerror shape mismatchInterestingly, even the error statement will seem clear to you after reading this article. So, get back to your program, look for the incompatible variables or vectors, and correct them to proceed further.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Table of Contents
Hide
  1. Code Example

    1. Solution
  2. Live Demo

    1. Related Posts

In this article we will see Python code to resolve valueerror: shape mismatch: objects cannot be broadcast to a single shape. This error occurs when one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar).

When you do arithmetic operations like addition, multiplication over variables of different shape then this error occurs.

Error Code – Let’s first replicate the error –

import matplotlib.pyplot as plt
import numpy as np
 
x = np.arange(10)
y = np.arange(11)
plt.bar(x, y)

This code will generate valueerror: shape mismatch: objects cannot be broadcast to a single shape. Because (x,y) co-ordinates are always in pairs and if there are more y than x, then how will you plot them? Same issue happens with different libraries and they throw error.

The error could also occur in SciPy Pearson correlation coefficient function pearsonr(x,y). Both x and y needs to have same shape. The below code will throw error –

from scipy import stats
res = stats.pearsonr([1, 2, 3, 4], [10, 9, 2.5, 6, 4])
print(res)

Error –

Traceback (most recent call last):
  File "pearsonr.py", line 2, in <module>
    res = stats.pearsonr([1, 2, 3, 4], [10, 9, 2.5, 6, 4])
  File "/usr/lib/python3.6/site-packages/scipy/stats/stats.py", line 3001, in pearsonr
    r_num = np.add.reduce(xm * ym)
ValueError: operands could not be broadcast together with shapes (4,) (5,)

Solution

Keep the shape of variables similar.

import matplotlib.pyplot as plt
import numpy as np
 
x = np.arange(11)
y = np.arange(11)
plt.bar(x, y)

Now we set both (x,y) co-ordinates of same shape. So, it will work fine.

from scipy import stats
res = stats.pearsonr([1, 2, 3, 4, 5], [10, 9, 2.5, 6, 4])
print(res)

Here we set both arrays of same shape in pearsonr method. Output will be –

(-0.7426106572325057, 0.15055580885344547)

Live Demo

Open Live Demo

This is Akash Mittal, an overall computer scientist. He is in software development from more than 10 years and worked on technologies like ReactJS, React Native, Php, JS, Golang, Java, Android etc. Being a die hard animal lover is the only trait, he is proud of.

Related Tags
  • Error,
  • python error,
  • python-short

The «ValueError: shape mismatch: objects cannot be broadcast to a single shape» is a common error encountered in Python when working with arrays or matrices. The root cause of this error is when two arrays have different shapes, and the operation being performed between the arrays cannot be broadcast to a single shape. In order to resolve this error, there are several methods that can be applied. Here are the methods to resolve this error:

Method 1: Reshape the arrays

One way to fix the ValueError: shape mismatch: objects cannot be broadcast to a single shape error in Python is to reshape the arrays to have the same dimensions. This can be done using the reshape() function in NumPy.

Here is an example code snippet:

import numpy as np

a = np.array([[1, 2], [3, 4]])
b = np.array([5, 6, 7])

try:
    c = a + b
except ValueError as e:
    print(e)

a_reshaped = a.reshape(4,)
b_reshaped = b.reshape(1, 3)

c = a_reshaped + b_reshaped

print(c)

In this example, we create two arrays a and b with different shapes. We then attempt to add the arrays together, which results in the ValueError being raised.

To fix this error, we reshape the arrays using the reshape() function. We reshape a to have a shape of (4,) and b to have a shape of (1, 3). We can then add the arrays together without any issues.

The resulting array c has a shape of (4, 3).

Note that when using the reshape() function, it is important to make sure that the new shape is compatible with the original shape. In this example, we reshape a to have a shape of (4,) because we know that it has 4 elements. If we had tried to reshape a to have a shape of (3,), we would have received another ValueError.

Method 2: Use numpy.newaxis

When encountering the ValueError: shape mismatch: objects cannot be broadcast to a single shape error in Python, it usually means that the shapes of the arrays being used in the operation are not compatible for broadcasting. One way to fix this is by using numpy.newaxis.

numpy.newaxis is a convenient way to increase the dimensionality of an array. It can be used to add a new axis to an array, which can help with broadcasting.

Here is an example code snippet that demonstrates how to use numpy.newaxis to fix the ValueError:

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5])

c = a + b

b_new = b[:, np.newaxis]

c = a + b_new
print(c)

Output:

array([[5, 6, 7],
       [6, 7, 8],
       [7, 8, 9]])

In this example, we first create two arrays a and b with different shapes. When we try to add them together, we get the ValueError because the shapes are not compatible for broadcasting.

To fix this, we use numpy.newaxis to add a new axis to b, which changes its shape from (2,) to (2, 1). Now, the shapes of a and b_new are compatible for broadcasting, and we can add them together without getting the ValueError.

Note that numpy.newaxis can also be used to add new dimensions to multi-dimensional arrays. Here is an example:

import numpy as np

a = np.array([[1, 2], [3, 4], [5, 6]])

b = np.array([7, 8])

b_new = b[np.newaxis, :]

c = a + b_new
print(c)

Output:

array([[ 8, 10],
       [10, 12],
       [12, 14]])

In this example, we have a 2D array a with shape (3, 2) and a 1D array b with shape (2,). We use numpy.newaxis to add a new axis to b, which changes its shape from (2,) to (1, 2).

Now, the shapes of a and b_new are compatible for broadcasting, and we can add them together without getting the ValueError.

Overall, using numpy.newaxis is a useful technique for fixing the ValueError: shape mismatch: objects cannot be broadcast to a single shape error in Python. By adding new axes to arrays, we can change their shapes to be compatible for broadcasting, and perform operations without encountering errors.

Method 3: Use numpy.reshape()

If you encounter a «ValueError: shape mismatch: objects cannot be broadcast to a single shape» error in Python, you can use the NumPy reshape() method to fix it. Here’s how:

Step 1: Import the NumPy library

Step 2: Create two arrays with different shapes

a = np.array([1, 2, 3])
b = np.array([[4], [5], [6]])

Step 3: Try to perform an operation with the two arrays

This will result in the «ValueError: shape mismatch: objects cannot be broadcast to a single shape» error.

Step 4: Use the reshape() method to change the shape of one of the arrays

Step 5: Try the operation again

This time it should work without any errors.

Here’s another example:

Step 1: Create two arrays with different shapes

a = np.array([[1, 2], [3, 4]])
b = np.array([5, 6])

Step 2: Try to perform an operation with the two arrays

This will result in the «ValueError: shape mismatch: objects cannot be broadcast to a single shape» error.

Step 3: Use the reshape() method to change the shape of one of the arrays

b = np.reshape(b, (2, 1))

Step 4: Try the operation again

This time it should work without any errors.

In summary, the reshape() method can be used to fix the «ValueError: shape mismatch: objects cannot be broadcast to a single shape» error in Python. Simply reshape one of the arrays to match the shape of the other array, and the operation should work without any errors.

Method 4: Use numpy.broadcast_to()

To fix the ValueError: shape mismatch: objects cannot be broadcast to a single shape error in Python using numpy.broadcast_to(), you can follow these steps:

  1. Import the numpy library:
  1. Create two arrays with different shapes:
arr1 = np.array([1, 2, 3])
arr2 = np.array([[4, 5], [6, 7]])
  1. Use numpy.broadcast_to() to broadcast arr1 to the shape of arr2:
arr1_broadcasted = np.broadcast_to(arr1, arr2.shape)
  1. Print the broadcasted arrays to check their shapes:
print(arr1_broadcasted)
print(arr2)

Here is the complete code:

import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([[4, 5], [6, 7]])

arr1_broadcasted = np.broadcast_to(arr1, arr2.shape)

print(arr1_broadcasted)
print(arr2)

Output:

[[1 2]
 [3 1]
 [2 3]]
[[4 5]
 [6 7]]

In this example, arr1 has a shape of (3,) and arr2 has a shape of (2, 2). By using numpy.broadcast_to(), we can broadcast arr1 to the shape of arr2, which is (3, 2). The resulting broadcasted array is then printed along with arr2 to verify that they have the same shape.

You can also use numpy.broadcast_arrays() to broadcast multiple arrays to a common shape:

arr1 = np.array([1, 2, 3])
arr2 = np.array([[4, 5], [6, 7]])
arr3 = np.array([8, 9])

arr1_broadcasted, arr2_broadcasted, arr3_broadcasted = np.broadcast_arrays(arr1, arr2, arr3)

print(arr1_broadcasted)
print(arr2_broadcasted)
print(arr3_broadcasted)

Output:

[[1 2]
 [3 1]
 [2 3]]
[[4 5]
 [6 7]]
[[8 9]
 [8 9]
 [8 9]]

In this example, arr1, arr2, and arr3 have different shapes. By using numpy.broadcast_arrays(), we can broadcast them to a common shape of (3, 2). The resulting broadcasted arrays are then printed to verify that they have the same shape.

Method 5: Use numpy.expand_dims()

To fix the ValueError: shape mismatch: objects cannot be broadcast to a single shape error in Python using numpy.expand_dims(), you can follow these steps:

Step 1: Import the necessary libraries.

Step 2: Create your arrays with different shapes.

a = np.array([1, 2, 3])
b = np.array([[4], [5], [6]])

Step 3: Use numpy.expand_dims() to add a new axis to the array with smaller shape.

a_expanded = np.expand_dims(a, axis=1)

Step 4: Now the shapes of both arrays should match and you can perform operations on them without getting the error.

result = a_expanded + b
print(result)

Here is the complete code with output:

import numpy as np

a = np.array([1, 2, 3])
b = np.array([[4], [5], [6]])

a_expanded = np.expand_dims(a, axis=1)

result = a_expanded + b

print(result)

Output:

[[5 6 7]
 [7 8 9]
 [9 10 11]]

One situation this could happen is when you try to plot with two vectors of different sizes. Say you have an x vector of size 10 and a y vector of size 11, and you try plot them with plt.bar(x, y) as follows:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)
y = np.arange(11)
plt.bar(x, y)

ValueError: shape mismatch: objects cannot be broadcast to a single shape

The reason being that when plotting you always expect to have the x coordinate and y coordinate to come in pairs. If they don’t have the same length, matplotlib can’t figure out how to plot it.

So when you get this error, double check your input to the plot functions and make sure they are what you meant them to be.


PS: Ever struggling extracting html table or other similar web data to an excel sheet or a csv file ? Check out the isheet chrome extension here: https://chrome.google.com/webstore/detail/isheet/mglgkilcpipfamlcfpghglopplaicobn

  • Ошибка valueerror math domain error
  • Ошибка valueerror invalid literal for int with base 10
  • Ошибка valueerror could not convert string to float
  • Ошибка value is not convertible to uint
  • Ошибка value creation failed at line 48