根据其他列的唯一值重命名列值

时间:2019-11-18 23:01:35

标签: python pandas numpy

给出一个数据框:

df = 

  id_easy   ordinal   weekday
0       0         1   Tuesday
1       0         2   Monday
2       0         3   Monday
3       1         1   Saturday
4       1         2   Tuesday

我要检查:

  • 在每个唯一的id_easy值中,当weekdayordinal时,将1列重命名为其值。

所需的输出:

df = 

  id_easy   ordinal   weekday
0       0         1   Tuesday       # as this is Tuesday
1       0         2   Tuesday       # so this became Tuesday as well
2       0         3   Tuesday       # so this became Tuesday as well
3       1         1   Saturday      # as this is Saturday
4       1         2   Saturday      # so this became Saturday as well

1 个答案:

答案 0 :(得分:1)

您可以使用groupby

df.weekday = df.groupby('id_easy')['weekday'].transform('first') 

输出:

   id_easy  ordinal   weekday
0        0        1   Tuesday
1        0        2   Tuesday
2        0        3   Tuesday
3        1        1  Saturday
4        1        2  Saturday