通过 transform() :
transform()
def first_last_0(x): x.iloc[0] = 0 x.iloc[-1] = 0 return x df['Value'] = df.groupby('Category')['Value'].transform(first_last_0) 0 0 1 200 2 20 3 0 4 0 5 210 6 0 7 0 8 370 9 0 10 0 11 92 12 0 13 0 14 77 15 0