Stacey
Stacey

Reputation: 5097

ValueError: operands could not be broadcast together with shapes (1521,) (1521,1522) ()

I have a large data-frame df where a sample of the frame is:

           A       B
0          0    4140
1   0.142857    1071
2          0    1196
3   0.090909    2110
4   0.083333    1926
5   0.166667    1388
6          0    3081
7          0    1149
8          0    1600
9   0.058824    1873
10         0    3960
:          :       :
19         0    4315
20         0    2007
21  0.086957    3323
22  0.166667    1084
23       0.5    2703
24         0    1214
25         0    1955
26         0    6750
27         0    3240
28         0    1437
29         0    1701

I am dividing column A by column B using:

df['new_column'] = np.where(df['A'] = 0, 0.0, df['A'].divide(df['B']))*90.0

However I am getting an error:

ValueError: operands could not be broadcast together with shapes (1521,) (1521,1522) () 

The shape of column A using df.A.shape is (1521,) The shape of column B using df.B.shape is (1521, 1)

I see that the shapes are different; would changing the shape fix the issue? If so, how do I change the shapes to be the same?

Upvotes: 0

Views: 344

Answers (1)

Andy L.
Andy L.

Reputation: 25239

Your errors looks very similar when mistakenly passing dataframe to np.where. Could you check that you pass df['A'] and 'df['B'], not df[['A']] and 'df[['B']]. Because passing mixing series and dataframe to np.where` will cause those errors.

Example: (I only use part of your sample data, so my df has only 11 rows)

np.where(df['A'] == 0, 0.0, df[['A']].divide(df['B']))*90.0

return error:

ValueError: operands could not be broadcast together with shapes (11,) () (11,12)`

and:

np.where(df['A'] == 0, 0.0, df['A'].divide(df[['B']]))*90.0

return error:

TypeError: 'int' object is not iterable

Upvotes: 1

Related Questions