我知道这可能是一个非常简单的问题,但是我是 python 新手,我不确定如何很好地操作 pandas 数据帧。
让我们举个例子数据:
Job Skill RelationType
Director Manage staff essential
Director Manage staff optional
目标
让我们举个例子数据:
Job Skill RelationType
Director Manage staff essential
Director Manage staff essential
理想情况下,我想编写一个函数,当 RelationType 不同但 Skill 相同时,在这种情况下,它会被覆盖并替换为必需的。因此,对于同一份工作,基本技能总是比可选技能更重要。
已解决
df['RelationType'] = df.groupby(['Jobs', 'Skill'])['RelationType'].transform('min')
最佳答案
Categorical Data对于这项任务很有用。首先将 RelationType
转换为分类系列,首先按优先级更高的值排序。
然后按关键字段执行 GroupBy
操作,使用 min
函数选择最高优先级的类别。
df['RelationType'] = pd.Categorical(df['RelationType'], ordered=True,
categories=['essential', 'optional'])
df['RelationType'] = df.groupby(['Job', 'Skill']).transform('min')
print(df)
Job Skill RelationType
0 Director ManageStaff essential
1 Director ManageStaff essential
关于python - pandas 中的数据操作 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51778590/