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

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

我有以下场景:

day_list = [
  [317, 331, 344],
  [305, 326, 340],
  [317],
  [290, 323],
  [311, 325, 345],
  [289, 303, 323],
  [274, 281, 294, 325]
  ...
]

第一个列表: [317, 331, 344]

331 - 317 = 14
344 - 331 = 13

结果列表: [14, 13]

我的代码是:

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)

我收到以下错误:

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

我发现它与我更改数组位置的代码部分有关 (j+1)。而且我不知道如何修复代码并获得正确的结果。

我已经阅读了一堆类似的问题,但找不到解决方案。

你能帮忙吗?

感谢

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

添加更多详细信息:

我正在根据以下数据框创建列表:


        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)

可能是我更正的代码中的缩进错误,我现在尝试了这段代码并且没有收到任何错误:

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)

输出:

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