【问题标题】:ValueError: operands could not be broadcast together with shapes to a vectorized functionValueError:无法将操作数与形状一起广播到矢量化函数
【发布时间】:2020-05-12 17:27:22
【问题描述】:

我正在 Google Colab 中制作一个 python 程序,在这个 Colab 中,我想创建一个函数,将两个 Numpy 数组、一个 panda Dataframe 和一个字符串发送到一个 Numpy 矢量化函数。当我执行这段代码时,我收到以下错误:ValueError: operands could not be broadcast together with shapes (6501398,) (6501398,) (462650,11) ()

这是我使用的代码:

def calc_gem_bouwjaar(postcode_van_ascii, postcode_tot_ascii, BAG_grouped, foo_string):
    if (postcode_van_ascii != postcode_tot_ascii):
    total = 0
    amount = 0
    postcode_van_ascii = add_to_barcode(val=postcode_van_ascii, pos=1) # this just increments the value by one, and handles overflows in postal code format.

    while postcode_van_ascii != postcode_tot_ascii:
      try:
        # at is de snelste manier om data uit de dataframe te halen https://github.com/pandas-dev/pandas/issues/6683#issuecomment-38305770. 
        # df.ix lijkt nog sneller maar is sinds 0.23.4 deprecated https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.ix.html
        total += round(BAG_grouped.at[postcode_van_ascii, foo_string])
        amount += 1
      except:
        pass

      postcode_van_ascii = add_to_barcode(val=postcode_van_ascii, pos=1) # this just increments the value by one, and handles overflows in postal code format.

    try:
      return round(total/amount)
    except:
      # Error in division, probably no excisting data in grouped dataframe
      return 0

  else:
    try:
      return int(round(BAG_grouped.at[postcode_van_ascii, foo_string]))
    except:
      return 0


def foo(foo_string):
    # do other stuff
    BAG_grouped = BAG_df.groupby('postcode_ascii').mean()
    vconvert = np.vectorize(calc_gem_bouwjaar)

    postcode_van_array = np.asarray(Netbeheerders_df["POSTCODE_VAN_ASCII"]).astype(int)
    postcode_tot_array = np.asarray(Netbeheerders_df["POSTCODE_TOT_ASCII"]).astype(int)

    # foo_string = 'bouwjaar'
    result = vconvert(postcode_van_array, postcode_tot_array, BAG_grouped, foo_string).astype(int)  #<--- ValueError: operands could not be broadcast together with shapes (6501398,) (6501398,) (462650,11) ()


foo('bouwjaar')

为什么我的代码会产生这个错误,我该如何解决这个问题?

【问题讨论】:

  • 如果您没有阅读过它的文档或基本的 numpy 介绍,为什么还要使用 np.vectorize
  • 来自vectorize docs:"向量化函数在输入数组的连续元组上评估pyfunc,就像python map 函数一样,除了它使用numpy 的广播规则 。” (我的重点补充)如果你不理解numpy广播,不要使用vectorize

标签: python python-3.x pandas numpy


【解决方案1】:

您的函数calc_gem_bouwjaar 通过广播对您的向量进行操作。由于您的矢量形状不可广播(特别是 (6501398,) (462650,11)()),因此会引发错误。您必须查看您的功能,看看您在哪里尝试进行需要广播的操作并修复相应的形状/操作。没有函数的内容,我们可以添加的东西不多。

【讨论】:

  • 您好 Ehsan,感谢您的留言。我添加了calc_gem_bouwjaar 的全部功能。我对 python 的了解还不是最好的,所以我不知道你对广播的意思。我问过我的uni group,但他们也不知道。你能给我一些信息和资源吗?
  • 嗨,我很难理解你的代码,因为我不知道你的函数/变量。你喜欢使用 np.vectorzie 有什么原因吗?一个函数会不会满足你的目的?
猜你喜欢
  • 2017-09-09
  • 2012-10-31
  • 2013-04-07
  • 2012-08-05
  • 2018-08-18
  • 2020-06-20
  • 2014-08-24
  • 2018-12-26
  • 2018-02-01
相关资源
最近更新 更多