小编Sal*_*lly的帖子

ValueError:在 groupby 对象上调用 pandas value_counts() 时,操作数无法与形状一起广播

我知道对此错误消息有很多疑问。然而我还没有找到一个有这个确切问题的人。

我正在尝试对 pandas DataFrame 进行分组并计算值:

allfactor = dataframe.groupby(factor)[reference_area].value_counts()
Run Code Online (Sandbox Code Playgroud)

其中factor和reference_area是数据框中的列名称。这适用于某些列,例如DGD015,但不适用于包括factor在内的其他列。
它给了我错误:

ValueError: operands could not be broadcast together with shape (421,) (419,)
Run Code Online (Sandbox Code Playgroud)

我将把完整的错误消息放在这个问题的末尾。
分组本身有效:

In: grouped = data.groupby(factor)[reference_area]
    grouped
Out: <pandas.core.groupby.generic.SeriesGroupBy object at 0x0000000B39D0F5F8>
Run Code Online (Sandbox Code Playgroud)

我可以看到这是一个 numpy 广播错误,因为尺寸不具有相同的形状而发生。并且有一些解决方法,例如在尝试乘以不“适合”且无法从中得到任何维度的维度时,使用[:, np.newaxis](地球科学研究计算)或[:,None](如何像计算机科学家一样思考:使用 Python 3 学习)伸展。

但是,当numpy中发生错误时,我不知道如何执行此操作,这是由pandas调用的,而pandas是通过调用value_counts()来调用的。

有人在这里有解决方法的想法吗?

我如何在这里访问 numpy 来告诉它只添加包含 NAN 的新轴以使尺寸适合?

这是完整的错误消息:

ValueError          Traceback (most recent call last)
ipython-input-5-013b5262b34f> in module>()
----> 1 trial = get_positives_threshold(data, 'SHB23D', 'HV001', threshold=90)
      2 print(trial)
ipython-input-3-80d69965e883> in get_positives_threshold(dataframe, factor, reference_area, …
Run Code Online (Sandbox Code Playgroud)

python numpy broadcasting pandas

3
推荐指数
1
解决办法
3482
查看次数

标签 统计

broadcasting ×1

numpy ×1

pandas ×1

python ×1