【发布时间】: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? -
来自
vectorizedocs:"向量化函数在输入数组的连续元组上评估pyfunc,就像python map 函数一样,除了它使用numpy 的广播规则 。” (我的重点补充)如果你不理解numpy广播,不要使用vectorize。
标签: python python-3.x pandas numpy