Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: cannot unpack non-iterable int objec

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.

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 ?

like image 432
user11036847 Avatar asked Aug 30 '19 07:08

user11036847


People also ask

How do I unpack a non-iterable object in Python?

Conclusion # The Python "TypeError: cannot unpack non-iterable function object" occurs when we try to unpack a function object instead of an iterable. To solve the error, make sure to call the function with parentheses, e.g. my_function() and return an iterable from the function.

What does cannot unpack non-iterable int object?

The Python "TypeError: cannot unpack non-iterable int object" occurs when we try to unpack an integer value. To solve the error, track down where the variable got assigned an integer and correct the assignment to an iterable, e.g. a list or a tuple of integers.

What is non-iterable int object?

If you are running your Python code and you see the error “TypeError: 'int' object is not iterable”, it means you are trying to loop through an integer or other data type that loops cannot work on. In Python, iterable data are lists, tuples, sets, dictionaries, and so on.

How do I fix TypeError Cannot unpack non-iterable NoneType object in Python?

How to Fix “TypeError: Cannot Unpack Non-iterable NoneType Object” Error in Python. This error was raised because we tried to unpack a None object. The simplest way around this is to not assign names. sort() as the new value of your list.


Video Answer


3 Answers

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

When your if condition 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'...

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 agg is 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'])
like image 164
olinox14 Avatar answered Oct 16 '22 20:10

olinox14


Similar error has appeared, so to resolve this I am posting one eg. hoping it will help out.

Reason: since int does not have __itr__ method inside it, we can't iterate it over like we do in list or tuple or dict{}.

x,y,z,n = input() # NOT CONVERTING THE INPUT TO 'INT' HERE  

l = []  

for a in range(0,int(x)): # converting the input to INT  
    for b in range(0,int(y)): # converting the input to INT  
        for c in range(0,int(z)): # converting the input to INT  
            if a+b+c!= n:  
                l.append([a,b,c])  
print(l)
like image 4
TUSHAR SINHA Avatar answered Oct 16 '22 21:10

TUSHAR SINHA


(DJANGO) In my case, I was trying get a item without set which parameter for search:

 schooling = Schooling.objects.get(randint(1, 10)) #Error


 schooling = Schooling.objects.get(id=randint(1, 10)) #OK set id=
like image 1
Diego Venâncio Avatar answered Oct 16 '22 21:10

Diego Venâncio