Drop duplicates of one column based on value in another column, Python, Pandas

被刻印的时光 ゝ 提交于 2019-12-04 08:12:34

Sort by distances and drop by dates:

df.sort_values('Distance').drop_duplicates(subset='Date', keep='first')
Out: 
                   Date      PlumeO  Distance
0   2014-08-13 13:48:00  754.447905  5.844577
13  2014-08-13 16:59:00  754.447905  5.844577

The advantage of these approaches is that it does not require a sort.

Option 1
You can identify the index values for the minimum values with idxmin and you can use it within a groupby. Use these results to slice your dataframe.

df.loc[df.groupby('Date').Distance.idxmin()]

                   Date      PlumeO  Distance
0   2014-08-13 13:48:00  754.447905  5.844577
13  2014-08-13 16:59:00  754.447905  5.844577

Option 2
You can use pd.DataFrame.nsmallest to return the rows associated with the smallest distance.

df.groupby('Date', group_keys=False).apply(
    pd.DataFrame.nsmallest, n=1, columns='Distance'
)

                   Date      PlumeO  Distance
0   2014-08-13 13:48:00  754.447905  5.844577
13  2014-08-13 16:59:00  754.447905  5.844577

I would say sort the data first and then drop the duplicate dates:

stripped_data = df.sort_values('distance').drop_duplicates('date', keep='first')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!