在保留数据框时,在列中选择第二个(或nth)最小值
我正在使用此代码在给定df的列中选择最小的行(从在这里):
data = pd.DataFrame({'A': [1,1,1,2,2,2], 'B':[4,5,2,7,4,6], 'C':[3,4,10,2,4,6]})
min_value = data.groupby('A').B.min()
data = data.merge(min_value, on='A',suffixes=('', '_min'))
data = data[data.B==data.B_min].drop('B_min', axis=1)
我想修改它,以便我获得该列的第二个(或nth)最低值。
I am using this code to select the smallest row in a column of a given df (got this appraoch from here):
data = pd.DataFrame({'A': [1,1,1,2,2,2], 'B':[4,5,2,7,4,6], 'C':[3,4,10,2,4,6]})
min_value = data.groupby('A').B.min()
data = data.merge(min_value, on='A',suffixes=('', '_min'))
data = data[data.B==data.B_min].drop('B_min', axis=1)
I would like to modify this such that I get the 2nd (or nth) lowest value for that column.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以找到每个A和滤波器数据的最低b。
您可以通过将等级转换为ARG来选择任何
nth
。You can find the nth lowest B per A and filter data.
You can select any
nth
by passing the rank to transform as arg.尝试:
打印:
Try:
Prints:
如果您的数据很大,则可以避免对数据进行排序(这很昂贵),而是使用
iDxmin
的组合(如您所引用的解决方案所示)和nsmallest
::If your data is large, you could avoid sorting the data(which can be expensive), and instead use a combination of
idxmin
( as shown in the solution you referenced) andnsmallest
: