在Pandas DataFrame中按规则分配to_update数据并处理剩余项
Pandas DataFrame 位置分配实现方案
需求明确
- 允许分配的位置:
positions_allowed = ['top','bottom'] - 把
status为"to_update"的条目,填充到top、bottom所有行的new_account、new_status字段 - 原
top、bottom中非"to_update"的条目,填充到center位置的对应字段 - 当
top、bottom位置用完后停止分配,输出剩余未分配的to_update条目(例:leftover: 2, numbers 16, 17)
高效实现代码(替代循环)
示例输入DataFrame
先假设你的输入数据结构如下(可根据实际情况调整):
import pandas as pd df = pd.DataFrame({ 'position': ['top', 'top', 'bottom', 'bottom', 'center', 'center'], 'account': [1, 15, 16, 4, 5, 6], 'status': ['active', 'to_update', 'to_update', 'active', 'active', 'active'], 'new_account': [None]*6, 'new_status': [None]*6 }) positions_allowed = ['top', 'bottom']
核心实现逻辑
# 1. 拆分需要处理的两类数据 # 待分配的to_update条目 to_update_list = df[df['status'] == 'to_update'].copy() # 原top/bottom中不需要更新的条目(要转到center) top_bottom_normal = df[(df['position'].isin(positions_allowed)) & (df['status'] != 'to_update')].copy() # 2. 计算允许分配的总位置数 total_available_slots = len(df[df['position'].isin(positions_allowed)]) # 3. 分配to_update到top/bottom,处理剩余项 assigned_entries = to_update_list.head(total_available_slots) leftover_entries = to_update_list.iloc[total_available_slots:] # 填充top/bottom的new_account和new_status allowed_rows = df[df['position'].isin(positions_allowed)] df.loc[allowed_rows.index[:len(assigned_entries)], ['new_account', 'new_status']] = assigned_entries[['account', 'status']].values # 4. 填充center位置的字段 center_rows = df[df['position'] == 'center'] df.loc[center_rows.index[:len(top_bottom_normal)], ['new_account', 'new_status']] = top_bottom_normal[['account', 'status']].values # 输出剩余未分配项 if not leftover_entries.empty: leftover_nums = ', '.join(map(str, leftover_entries['account'].tolist())) print(f"leftover: {len(leftover_entries)}, numbers {leftover_nums}") else: print("All to_update entries are assigned successfully.") # 打印最终结果 print(df)
代码说明
- 避免了复杂循环,用Pandas的布尔索引和向量操作实现,效率更高
- 先拆分数据,明确待分配的两类内容,再按位置数量限制分配
- 通过
head()和iloc快速切割可分配和剩余的to_update条目 - 用
loc精准定位需要填充的行和字段,保证数据对应正确
内容的提问来源于stack exchange,提问作者DearDeer
相关产品推荐
相关产品推荐

