根据多个组合条件创建新列

时间:2018-04-01 00:16:22

标签: python python-3.x pandas numpy dataframe

我希望此df中的新列具有以下条件。列education是一个从1到5的分类值(1是较低的教育水平,5是较高的教育水平)。我想用以下逻辑创建一个函数(以便在df中创建一个新列)

首先,对于任何身份检查,如果至少有一个毕业的教育水平,那么新专栏必须具有更高的教育水平。

其次,如果某个特定身份证没有毕业教育水平(必须在“课程中”具有所有教育水平)。因此,必须检查最高教育水平并减去一个。

df
id  education stage
1   2         Graduated
1   3         Graduated
1   4         In course
2   3         In course
3   2         Graduated
3   3         In course
4   2         In course

预期产出:

id  education stage       new_column
1   2         Graduated   3
1   3         Graduated   3
1   4         In course   3
2   3         In course   2
3   2         Graduated   2
3   3         In course   2
4   2         In course   1

3 个答案:

答案 0 :(得分:4)

你可以这样做:

import pandas as pd
df = pd.DataFrame({'id': [1, 1, 1, 2, 3, 3, 4], 'education': [2, 3, 4, 3, 2, 3, 2],
                   'stage': ['Graduated', 'Graduated', 'In course', 'In course', 'Graduated', 'In course', 'In course']})


max_gr = df[df.stage == 'Graduated'].groupby('id').education.max()
max_ic = df[df.stage == 'In course'].groupby('id').education.max()

# set all cells to the value from max_ed
df['new_col'] = df.id.map(max_gr)
# set cells that have not been filled to the value from max_ic - 1
df.loc[df.new_col.isna(), ['new_col']] = df.id.map(max_ic - 1)

series.map(other_series)返回一个新系列,其中series的值已被other_series中的值替换。

答案 1 :(得分:2)

这是一种方式。

df['new'] = df.loc[df['stage'] == 'Graduated']\
              .groupby('id')['education']\
              .transform(max).astype(int)

df['new'] = df['new'].fillna(df.loc[df['stage'] == 'InCourse']\
                               .groupby('id')['education']\
                               .transform(max).sub(1)).astype(int)

<强>结果

   id  education      stage  new
0   1          2  Graduated    3
1   1          3  Graduated    3
2   1          4   InCourse    3
3   2          3   InCourse    2
4   3          2  Graduated    2
5   3          3   InCourse    2
6   4          2   InCourse    1

<强>解释

  • 首先,映射到最大教育中按ID分组的“分级”数据集。
  • 其次,映射到“InCourse”数据集,按最大教育减去1的ID分组。

答案 2 :(得分:2)

替代解决方案基于MarkusLöffler。

max_ic = df[df.stage.eq('In course')].groupby('id').education.max() - 1
max_gr = df[df.stage.eq('Graduated')].groupby('id').education.max()

# Update with max_gr
max_ic.update(max_gr)

df['new_col'] = df.id.map(max_ic)