【问题标题】:(Pandas) Group by one column and keep only the rows where another column is the max(熊猫)按一列分组,只保留另一列最大的行
【发布时间】:2020-06-11 19:29:57
【问题描述】:

我有一个包含 6 列的 pandas 数据框,其中两列是“日期”和“时间”。对于每个日期,我只想保留具有最大时间值的行。 例如,日期在左侧,时间在右侧。 我只想保留时间为 1925 年的所有行。

20200109    1925
20200109    1925
20200109    1925
20200109    1925
20200109    1925
20200109    1925
20200109    1830
20200109    1830
20200109    1830
20200109    1830
20200109    1830

我尝试了很多排序和使用groupby的解决方案,例如dataframe.groupby('date').apply(lambda x: x.loc[x.time == x.time.max(),['date','time']])

但这仅返回日期和时间列。我想要结果中的所有 6 列

编辑:我想保留所有与最长时间相关的日期。

【问题讨论】:

  • df.sort_values('time').drop_duplicates('date', keep='last')
  • 这只返回一个日期和一个时间值。我想保留与最长时间相关的所有日期。我应该澄清这一点
  • df[df['time'] == df.groupby('date')['time'].transform('max')]
  • 还是一样的问题:(
  • 1.如果您想要所有 6 列,为什么在您的 loc 中包含 ['date','time']? 2. 我上面的评论保留了所有具有最大时间的行在一个日期内。如果您想要所有具有(全局)最大时间的日期,那么只需执行 df[df['time']==df['time'].max()]?

标签: python pandas dataframe sorting group-by


【解决方案1】:

试试这样的 -

dates = [20200109, 20200109, 20200109, 20200109, 20200109, 20200109, 20200109, 20200109, 20200109, 20200109, 20200109, 20200110]
times = [1925, 1925, 1925, 1925, 1925, 1925, 1830, 1830, 1830, 1830, 1830, 1930]
df = pd.DataFrame({'dates':dates, 'times':times})

filt = df.groupby(['dates'])['times'].max().to_frame().reset_index()
final = pd.merge(df,filt,on=['dates','times'])

final 
      dates  times
  0  20200109   1925
  1  20200109   1925
  2  20200109   1925
  3  20200109   1925
  4  20200109   1925
  5  20200109   1925
  6  20200110   1930

我认为即使您向df 添加更多列,final 也会拥有您想要的额外列。

【讨论】:

    猜你喜欢
    • 2021-07-07
    • 2022-07-14
    • 1970-01-01
    • 2023-03-28
    • 2017-11-27
    • 2022-11-10
    • 2016-06-04
    • 2021-10-11
    • 2020-12-12
    相关资源
    最近更新 更多