牧羊人nacy
这是您的函数,这假设索引是范围索引:def check_limit(df, limit): s = df['Value'].cumsum() df['within_limit'] = np.where(s.le(limit), 'Yes', 'No') # Nothing off limit if s.iloc[-1] < limit: return df.append(pd.Series([np.nan, limit-s.iloc[-1],'Extra'], index=df.columns, name=len(df)) ) # all sum even to limit if s.iloc[-1] == limit: return df # find where the limit is exceeded idx = s.gt(limit).idxmax() # exceed limit exceed_limit = s.loc[idx] - limit new_df = df.loc[[idx,idx]].copy() new_df['Value'] = [df.loc[idx,'Value'] - exceed_limit, exceed_limit] new_df['within_limit'] = ['Yes','No'] return pd.concat((df.drop(idx), new_df)).sort_index().reset_index(drop=True)# test datadf1 = pd.DataFrame({'Item':['A','B','C', 'D'],'Value':[4,3,7,2]})df2 = pd.DataFrame({'Item':['A','B','C'],'Value':[4,3,2]})输出:# check_limit(df1, 10) Item Value within_limit0 A 4 Yes1 B 3 Yes2 C 3 Yes3 C 4 No4 D 2 No# check_limit(df2, 10) Item Value within_limit0 A 4 Yes1 B 3 Yes2 C 2 Yes3 NaN 1 Extra