pandas 类型错误:无法解包不可迭代的 int 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/57722456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 06:24:33  来源:igfitidea点击:

TypeError: cannot unpack non-iterable int objec

pythonpandasnumpyscipypython-xarray

提问by user11036847

how can I solve this error After running my code as follows . I am using the function below and implementin running window for loop on it but end up getting the error below. The for loop works and hungs at a point.

我如何解决这个错误运行我的代码如下。我正在使用下面的函数并在运行窗口中实现循环,但最终得到以下错误。for 循环起作用并挂在某个点上。

def get_grps(s, thresh=-1, Nmin=3):
                """
                Nmin : int > 0
                    Min number of consecutive values below threshold.
                """
                m = np.logical_and.reduce([s.shift(-i).le(thresh) for i in range(Nmin)])
                if Nmin > 1:
                    m = pd.Series(m, index=s.index).replace({False: np.NaN}).ffill(limit=Nmin - 1).fillna(False)
                else:
                    m = pd.Series(m, index=s.index)

                # Form consecutive groups
                gps = m.ne(m.shift(1)).cumsum().where(m)

                # Return None if no groups, else the aggregations
                if gps.isnull().all():
                    return 0
                else:

                    agg = s.groupby(gps).agg([list, sum, 'size']).reset_index(drop=True)
                    # agg2 = s2.groupby(gps).agg([list, sum, 'size']).reset_index(drop=True)

                    return agg, gps


data_spi = [-0.32361498 -0.5229471   0.15702732  0.28753752   -0.01069884 -0.8163699
  -1.3169327   0.4413181   0.75815576  1.3858147   0.49990863-0.06357133
-0.78432    -0.95337325 -1.663739    0.18965477  0.81183237   0.8360347
  0.99537593 -0.12197364 -0.31432647 -2.0865853   0.2084263    0.13332903
 -0.05270813 -1.0090573  -1.6578217  -1.2969246  -0.70916456   0.70059913
 -1.2127264  -0.659762   -1.1612778  -2.1216285  -0.8054617    -0.6293912
 -2.2103117  -1.9373081  -2.530625   -2.4089663  -1.950846    -1.6129876]
lon = data_spi.lon
lat = data_spi.lat
print(len(data_spi))

n=6


for x in range(len(lat)):
for y in range(len(lon)):
    if data_spi[0, x, y] != 0:

        for i in range(len(data_spi)-70):
                ts = data_spi[i:i+10, x, y].fillna(1)
                print(ts)
                # print(np.array(ts))



                agg, gps = get_grps(pd.Series(ts), thresh=-1, Nmin=3)

                duration = np.nanmean(agg['sum'])
                frequency = len(agg['sum'])
                severity = np.abs(np.mean(agg['sum']))
                intensity = np.mean(np.abs(agg['sum'] / agg['size']))
                print(f'intensity {intensity}')

I get this error

我收到这个错误

 Traceback (most recent call last):
 File "/Users/mada0007/PycharmProjects/Research_ass /FREQ_MEAN_INT_DUR_CORR.py", line 80, in <module>
 agg, gps = get_grps(pd.Series(ts), thresh=-1, Nmin=3)
 typeError: cannot unpack non-iterable int object

How can I resolve this error ?

我该如何解决这个错误?

回答by olinox14

Just replace return 0 by return 0, 0, or better: raise an error instead of returning 0

只需将 return 0 替换为 return 0、0 或更好:引发错误而不是返回 0

When your ifcondition is True, you only return 0. Then later, when you do agg, gps = get_grps(...), you tell python to unpack the result of the function. Then, python is expecting a 2-length iterable, and try to unpack it, but as it says: it 'cannot unpack non-iterable int object'...

当您的if条件为 True 时,您只返回0。然后,当你这样做时agg, gps = get_grps(...),你告诉 python 解包函数的结果。然后,python 期待一个 2 长度的可迭代对象,并尝试解压缩它,但正如它所说:它“无法解压缩不可迭代的 int 对象”......

So a quick workaround is to return a tuple (0, 0) with return 0, 0, but it is quite bad because you return integers where objects are expected. your script will crash on the next line duration = np.nanmean(agg['sum'])(since aggis 0).

所以一个快速的解决方法是用 返回一个元组 (0, 0) return 0, 0,但它很糟糕,因为你在预期对象的地方返回整数。您的脚本将在下一行崩溃duration = np.nanmean(agg['sum'])(因为agg是 0)。

Some cleaner solutions to handle this case would be to unpack in a second time:

处理这种情况的一些更清洁的解决方案是再次打开包装:

def get_grps(s, thresh=-1, Nmin=3):
    # ...
    if gps.isnull().all():
        return None
    else:
        # ...
        return agg, gps

    for i in range(len(data_spi)-70):
        ts = data_spi[i:i+10, x, y].fillna(1)

        result = get_grps(pd.Series(ts), thresh=-1, Nmin=3)
        if result is None:
            break

        agg, gps = result

        duration = np.nanmean(agg['sum'])
        frequency = len(agg['sum'])