I am having some trouble working on grouped objects in pandas. Specifically, I want to be able to set the first row in a column to 0 while keeping other rows unchanged.
For example:
df = pd.DataFrame({'A': ['foo', 'bar', 'baz'] * 2,
'B': rand.randn(6),
'C': rand.rand(6) > .5})
gives me
A B C
0 foo 1.624345 False
1 bar -0.611756 True
2 baz -0.528172 False
3 foo -1.072969 True
4 bar 0.865408 False
5 baz -2.301539 True
and I group them by A and sort them by B:
f = lambda x: x.sort('B', ascending=True)
sort_df = df.groupby('A',sort=False).apply(f)
to get this:
A B C
A
foo 3 foo -1.072969 True
0 foo 1.624345 False
bar 1 bar -0.611756 True
4 bar 0.865408 False
baz 5 baz -2.301539 True
2 baz -0.528172 False
Now that I have the groups, I want to be able to set the first element in each group to 0. How do I do that?
Something like this would work, but I want a more optimized way of doing it:
for group in sort_df.groupby(level=0).groups:
sort_df.loc[(group,sort_df.loc[group].index[0]),'B']=0
Any help would be appreciated, thanks!