我想在MLB数据集中获取每个投手每场比赛的最后一次投球,并将其标记为True。但是,在GroupBy对象中添加列或修改数据帧时遇到了问题。我怎样才能有效地添加这个专栏呢?
data['last_pitch'] = False
g = data.groupby(['gameString', 'pitcherId'])
for x, pitcher in g:
pitcher.iloc[-1]['last_pitch'] = True
发布于 2018-08-13 11:04:56
使用GroupBy
来实现这一点很有诱惑力。但是,当您不想实际聚合数据时,通常还有其他方法。在这里,您可以在keep='last'
中使用pd.Series.duplicated
# data from gyoza
df['last_pitch'] = ~df['pitcherId'].duplicated(keep='last')
print(df)
gameString pitcherId last_pitch
0 a c False
1 a c True
2 b d False
3 b d False
4 b d True
如果您确实希望使用GroupBy
,可以使用last
方法:
idx = df.reset_index().groupby('pitcherId')['index'].last().values
df['last_pitch'] = df.index.isin(idx)
发布于 2018-08-13 10:57:32
一种方法是找到要使用tail
更改的行的所有索引,然后使用loc
在原始数据帧中更改它们:
last_rows = data.groupby(['gameString', 'pitcherId']).tail(n=1)
data.loc[last_rows.index, 'last_pitch'] = True
https://stackoverflow.com/questions/51812382
复制相似问题