Python TypeError:无法解包非可迭代int对象的问题解决
TypeError: cannot unpack non-iterable int object in Your Group Detection Function The root cause here is inconsistent return values from your get_grps function: when no valid groups are found, you return a single integer 0, but your calling code expects to unpack two values (agg and gps). Python can't split an integer into two variables, hence the error.
Here are the cleanest ways to fix this:
1. Enforce Consistent Return Structure (Recommended)
Make sure your function always returns a two-element tuple, even when no groups exist. This keeps your calling code predictable and avoids type mismatches.
Modified Function Code
import numpy as np import pandas as pd 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 consistent tuple structure if gps.isnull().all(): # Option A: Return None for both values return None, None # Option B: Return empty pandas objects (more pandas-idiomatic) # return pd.DataFrame(), pd.Series(dtype='int64') else: agg = s.groupby(gps).agg([list, sum, 'size']).reset_index(drop=True) return agg, gps
Updated Calling Code
Handle the "no groups" case explicitly:
agg, gps = get_grps(pd.Series(ts), thresh=-1, Nmin=3) # If using Option A (returning None) if agg is None: print("No groups of consecutive values below the threshold were found.") else: # Process your valid groups here print("Aggregated group data:\n", agg) print("Group labels:\n", gps) # If using Option B (returning empty pandas objects) if agg.empty: print("No valid groups found.") else: # Process your data ...
2. Use Try-Except to Catch the Error
If you prefer not to modify the function's return logic (not recommended for long-term maintainability), you can catch the TypeError when unpacking:
try: agg, gps = get_grps(pd.Series(ts), thresh=-1, Nmin=3) # Process valid groups here except TypeError: # Handle the case where return value was 0 (no groups) print("No valid groups detected.") agg, gps = None, None
Why This Works
By ensuring your function always returns a tuple (even with empty/None values), you eliminate the type mismatch that triggers the error. The first approach is better because it makes your code self-documenting—anyone reading get_grps will immediately know it returns two values, no matter the input.
内容的提问来源于stack exchange,提问作者user11036847

