Search code examples
pythonnumpyarray-broadcasting

ValueError: operands could not be broadcast together with shapes (3,) (2,)


I have the following scenario:

  • I have a list of list of numbers, for example:
day_list = [
  [317, 331, 344],
  [305, 326, 340],
  [317],
  [290, 323],
  [311, 325, 345],
  [289, 303, 323],
  [274, 281, 294, 325]
  ...
]
  • I want to subtract the previous element from the next element of each inner list, so that appending the results in a "result" list. Example:

First list: [317, 331, 344]

331 - 317 = 14
344 - 331 = 13

Result list: [14, 13]

My code is:

result = []
sub_result = []
for index, i in enumerate(day_list):
  if len(i) > 1:
    result = []
    for j in range(len(i)-1):
        subtract = np.subtract(np.array(day_list[index][j+1]), np.array(day_list[index][j]))
        result.append(subtract)
    sub_result.append(result)
  else:
    sub_result.append(0)

I'm getting the follow error:

ValueError: operands could not be broadcast together with shapes (3,) (2,)

I see it has to do with the code part in which I change the array position (j+1). And I have no idea how to fix the code and have the proper result.

I've already read a bunch of similar questions, but I could not find a solution.

Could you please help?

Tks

===================================

Adding more details:

I'm creating a list from the following data frame:


        key day_list
    0   1078|11498  [317, 331, 344]
    1   1078|11749  [305, 326, 340]
    2   1078|11778  [317]
    3   1078|13974  [290, 323]
    4   1078|15866  [311, 325, 345]
    ... ... ...
    25337   96|426860   [302, 326]
    25338   96|443060   [310]
    25339   96|445134   [301, 303, 310]
    25340   96|445237   [301, 309, 310, 324]
    25341   96|447416   [301, 310]
    25342 rows × 2 columns

    def load_data(data):
        df = pd.DataFrame(data)
        day_list = []
        for i in range(len(df)):
            day_list.append(df.day_list.loc[i])
        return day_list

    day_list = load_data(df_dayofyear)


Solution

  • Maybe it was indentation error in the code which i corrected, I tried this code now and not getting any error:

    day_list = [[317, 331, 344],
    [305, 326, 340],
    [317],
    [290, 323],
    [311, 325, 345],
    [289, 303, 323]]
    
    result = []
    sub_result = []
    for index, i in enumerate(day_list):
        if len(i) > 1:
            result = []
            for j in range(len(i)-1):
                subtract = np.subtract(np.array(day_list[index][j+1]), np.array(day_list[index][j]))
                result.append(subtract)
            sub_result.append(result)
        else:
            sub_result.append(0)
    

    Output:

    [[14, 13], [21, 14], 0, [33], [14, 20], [14, 20]]