如何在员工历史记录中检查以前的经理(Python)

问题描述 投票:0回答:2

我有一个包含所有员工记录的数据集,需要找到最近的(我有)和之前的前任经理。我想使用轮班功能,但不幸的是并非所有员工都有相同的历史布局。 这是一个小例子:

 ID    Job_Title       Mananger 
 1       Sales         John Doe
 1       Sales         Kobe Bryant  
 1       Sales         Phil Knight
 2       Tech          Michael Jordan 
 2       Tech          Michael Jordan 
 2       Tech          Larry Bird 
 3       Sales         Magic Johnson 
 3       Sales         Magic Johnson
 3       Sales         Magic Johnson 

这就是我需要的:

ID    Job_Title     Manager       Previous Manager 
 1     Sales        John Doe         Kobe Bryant 
 1     Sales        Kobe Bryant      Kobe Bryant 
 1     Sales        Phil Knight      Kobe Bryant
 2     Tech         Michael Jordan   Michael Jordan   
 2     Tech         Michael Jordan   Michael Jordan 
 2     Tech         Larry Bird       Michael Jordan 
 3     Sales        Magic Johnson    Magic Johnson
 3     Sales        Magic Johnson    Magic Johnson 
 3     Sales        Magic Johnson    Magic Johnson

我尝试使用 shift 功能,但只能看到变化,我希望能够映射前任经理。

python shift
2个回答
0
投票

您可以使用 pandas groupby 和 shift 函数来实现这一点。这是适用于您的数据集的示例代码:

import pandas as pd

# Read the dataset into a pandas dataframe
df = pd.read_csv("employee_records.csv")

# Sort the dataframe by ID and Date to ensure the shift operation is performed correctly
df = df.sort_values(by=["ID", "Date"])

# Group the dataframe by ID and Job_Title
grouped = df.groupby(["ID", "Job_Title"])

# Add a new column with the previous manager for each row
df["Previous Manager"] = grouped["Manager"].shift(1)

# Display the updated dataframe
print(df)

此代码应向名为“Previous Manager”的数据框添加一个新列,其中包含同一职位和 ID 组中每位员工之前工作记录的经理姓名。请注意,这假设记录按日期(或类似的时间戳)排序,以便移位操作正常工作。


0
投票

尝试使用 apply 函数将行应用到当前表,如下所示:

import pandas
import numpy

def find_num(row):
    if row in data:
        return data[row]
    else:
        return numpy.NaN

df['Previous Manager'] = df['ID'].apply(find_num)
© www.soinside.com 2019 - 2024. All rights reserved.