You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Pandas需求:将John的10工时职位改为Restaurant Manager

修改Pandas DataFrame中John累计工时达标记录的职位字段

核心思路

先筛选员工John的记录,计算累计工时,定位到累计工时达到10小时的目标行,再通过这些行的索引直接修改原DataFrame的position字段。

步骤与代码示例

假设你的原始DataFrame结构如下(可替换为实际业务数据):

import pandas as pd

data = {
    'employee': ['John', 'John', 'John', 'Jane', 'John'],
    'hours': [3, 4, 3, 5, 2],
    'position': ['Burger flipper'] * 5
}
df = pd.DataFrame(data)
  1. 筛选John的记录并计算累计工时
    提取John的子集并计算累计工时,用copy()避免链式赋值警告:

    john_subset = df[df['employee'] == 'John'].copy()
    john_subset['cumulative_hours'] = john_subset['hours'].cumsum()
    
  2. 定位目标行的索引
    根据实际需求选择判断逻辑:

    • 若要修改累计工时≤10小时的所有行(包括最后一行使总和刚好达到10的记录):
      target_indices = john_subset[john_subset['cumulative_hours'] <= 10].index
      
    • 若要修改首次累计达到≥10小时的行及之前的所有记录:
      # 找到首次累计工时≥10的行索引
      first_reach_idx = john_subset[john_subset['cumulative_hours'] >= 10].index[0]
      # 取该行及之前的所有索引
      target_indices = john_subset.loc[:first_reach_idx].index
      
  3. 修改原DataFrame的职位字段
    通过索引直接修改原DataFrame:

    df.loc[target_indices, 'position'] = 'Restaurant Manager'
    

注意事项

  • 若John的总工时不足10小时,上述第一种逻辑会修改他的所有记录,可添加判断避免:
    if john_subset['cumulative_hours'].max() >= 10:
        df.loc[target_indices, 'position'] = 'Restaurant Manager'
    
  • 必须使用.copy()处理子集,防止触发Pandas的SettingWithCopyWarning。

内容的提问来源于stack exchange,提问作者KaiserFluff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 00:10:33