(pandas) Create new column based on first element in groupby object

Solution 1:

You need transform with first:

print (df.groupby('Person')['Color'].transform('first'))
0      blue
1     green
2    orange
3      blue
4     green
5    orange
Name: Color, dtype: object

df['First_Col'] = df.groupby('Person')['Color'].transform('first')
print (df)
    Color Person First_Col
0    blue    bob      blue
1   green    jim     green
2  orange    joe    orange
3  yellow    bob      blue
4    pink    jim     green
5  purple    joe    orange

Solution 2:

use transform() method:

In [177]: df['First_Col'] = df.groupby('Person')['Color'].transform('first')

In [178]: df
Out[178]:
    Color Person First_Col
0    blue    bob      blue
1   green    jim     green
2  orange    joe    orange
3  yellow    bob      blue
4    pink    jim     green
5  purple    joe    orange