如何根据变量extra及其他列值调整DataFrame中Space列的值?
问题:实现基于refill优先级的空间分配/缩减逻辑
给定如下输入DataFrame和可正可负的变量extra:
input_df
Item Space refill Min Max Apple 0.25 12.53 0.125 0.25 Lemon 0.25 11.2 0.25 0.375 Potato 0.375 10.3 0.375 0.75 Melon 0.375 9.2 0.25 0.75
规则说明
当
extra = 0.25时:- 将额外空间按0.125的倍数拆分
- 优先分配给
refill值更高的项 - 调整后
Space不能超过Max,超出则跳过该项目 - 预期输出:
Item Space refill Min Max Apple 0.25 12.53 0.125 0.25 #item skipped since it exceeds Max limit if extra space added Lemon 0.375 11.2 0.25 0.375 #0.125 from extra space added here Potato 0.5 10.3 0.375 0.75 #remaining 0.125 from extra space added here Melon 0.375 9.2 0.25 0.75 #no more space to be added
当
extra = -0.25时:- 将需缩减的空间按-0.125的倍数拆分
- 优先从
refill值更高的项中缩减 - 调整后
Space不能低于Min,低于则跳过该项目 - 预期输出:
Item Space refill Min Max Apple 0.125 12.53 0.125 0.25 #-0.125 from extra space reduced here Lemon 0.25 11.2 0.25 0.375 #item skipped since it doesn't satisfy Min limit if reduced Potato 0.375 10.3 0.375 0.75 #item skipped since it doesn't satisfy Min limit if reduced Melon 0.25 9.2 0.25 0.75 #rem -0.125 from extra space reduced here
Python解决方案
以下是实现上述逻辑的代码,基于Pandas库:
import pandas as pd def adjust_space(df, extra): # 复制原DataFrame避免修改原始数据 df = df.copy() # 定义每次调整的步长 step = 0.125 if extra > 0 else -0.125 # 计算需要调整的总次数 adjust_times = abs(int(extra / step)) # 按refill降序排序,优先处理高优先级项 sorted_df = df.sort_values('refill', ascending=False).reset_index(drop=True) for _ in range(adjust_times): for idx, row in sorted_df.iterrows(): current_space = row['Space'] new_space = current_space + step # 根据extra正负判断边界条件 if extra > 0: if new_space <= row['Max']: sorted_df.loc[idx, 'Space'] = new_space break else: if new_space >= row['Min']: sorted_df.loc[idx, 'Space'] = new_space break # 恢复原DataFrame的Item顺序 result_df = sorted_df.set_index('Item').reindex(df['Item']).reset_index() return result_df # 测试用例初始化 input_df = pd.DataFrame({ 'Item': ['Apple', 'Lemon', 'Potato', 'Melon'], 'Space': [0.25, 0.25, 0.375, 0.375], 'refill': [12.53, 11.2, 10.3, 9.2], 'Min': [0.125, 0.25, 0.375, 0.25], 'Max': [0.25, 0.375, 0.75, 0.75] }) # 测试extra=0.25的场景 print("extra=0.25时的输出:") print(adjust_space(input_df, 0.25)) # 测试extra=-0.25的场景 print("\nextra=-0.25时的输出:") print(adjust_space(input_df, -0.25))
代码说明
- 先复制原始DataFrame,避免修改源数据
- 根据
extra的正负确定单次调整步长,并计算总调整次数 - 按
refill降序排序,确保高优先级项先被处理 - 循环执行每次调整:遍历排序后的项,检查调整后是否符合边界限制,符合则修改并进入下一次调整
- 最后恢复原DataFrame的Item顺序,保证输出与输入的项顺序一致
内容的提问来源于stack exchange,提问作者user12345
相关产品推荐
相关产品推荐

