倒数第二个值(pandas、Python)

Second last value (pandas, Python)

我有以下数据框:

index A B
0 a 3
1 a 4
2 b 9
3 b 6
4 a 2
5 b 1

我想得到每组“A”列的倒数第二个值。 我已经弄清楚如何使用 groupby 获取 min() 值:

df_grouped_last = df.groupby('A').agg({'B': ['min']})

但我需要获取倒数第二个值(“最后一个”),这样我才能得到:

index A 2nd last B
0 a 3
1 b 6

另外一个作品我也需要倒数第三和第四。

有人知道如何编码吗?

非常感谢! 文森特

让我们尝试 sort_values 然后使用位置

out = df.sort_values('B').groupby('A').apply(lambda x : x.iloc[1])
Out[68]: 
   index  A  B
A             
a      0  a  3
b      3  b  6

使用:

df = (df.groupby('A', as_index = False)['B']
        .agg({'2nd last B': lambda x: x.iloc[-2] if len(x) > 1 else x}))

输出:

>>> df
   A  2nd last B
0  a           4
1  b           6

查看您的预期输出,假设列 B 已针对每个组进行排序。如果是这种情况,请使用 sort_values, combined with nth:

(df.sort_values(['A', 'B'])
   .groupby('A', sort = False)
   .B
   .nth(-2) # familiar python construct ... 
            # takes second value from the bottom, per group
   .reset_index()
 )

   A  B
0  a  3
1  b  6