python - 如何找到组内值之间的最小差异

标签 python pandas dataframe sorting

示例 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/

相关文章:

python - jira-python 转换 REST API

python - 具有连续色调的 Seaborn 配对图?

r - 根据条件填充多列的行

Python - 创建 2 个新列,其中包含多个行值的第 25 个和第 75 个百分位

r - 使用 R 对大型数据框中的列进行重新排序的便捷方法

python - AWS ECS 上的 PostgreSQL : psycopg2. OperationalError 端口号 5432 无效

python - windows 不允许我替换文件

python-2.7 - 即使 RAM 空闲,内存也会出现错误

python - 在 Pandas 数据框中查找重复行

python - Sklearn 将字符串类标签更改为 int