示例 DF
df = pd.DataFrame({'Animal': ['Falcon', 'Falcon', 'Falcon',
'Parrot', 'Parrot', 'Parrot'],
'Max Speed': [380., 370., 25., 24., 26., 29.]})
期望的输出
2 (because the smallest difference is between 24 and 26 of Parrot)
更好(这样我可以检查)
'Parrot, 2'
我在想什么
“我需要按动物和最大速度排序,然后是窗口函数,但必须有更好的解决方案......”
最佳答案
我们可以用diff
检查groupby
df['new'] = df.sort_values('Max Speed').groupby('Animal')['Max Speed'].diff().abs()
out = df[df.new==df.new.min()]
Out[249]:
Animal Max Speed new
4 Parrot 26.0 2.0
关于python - 如何找到组内值之间的最小差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67706413/