【问题标题】:Select subset of dataframe using condition on multi index使用多索引上的条件选择数据帧的子集
【发布时间】:2018-10-20 23:34:09
【问题描述】:

全部,

我有一个格式如下的数据框:

ind date value1 value2 x1 23-04-2018 1.3 7.2 x1 03-05-2018 4.6 3.5 x2 04-04-2018 2.0 8.5

inddate 是索引。如果 ind 的一个值有多行,我只想保留最新日期。

因此,在我的示例中,首选结果是:

ind date value1 value2 x1 03-05-2018 4.6 3.5 x2 04-04-2018 2.0 8.5

日期列采用日期时间格式,因此可以找到组内的最大日期。但是是否可以使用这样的条件,例如与 groupby 结合使用(如 SQL 中的 GROUPBY 和 HAVING)。还是有更好的方法?

有没有人有解决方案或提示?

编辑:我稍微改变了我的例子。多行不一定是重复的。

【问题讨论】:

    标签: python pandas filter group-by multi-index


    【解决方案1】:

    您可以使用 sort_index 并删除重复项。

    df一开始没有索引:

    print(df)
    
      ind       date  value1  value2
    0  x1 2018-04-23     1.3     7.2
    1  x1 2018-03-05     1.3     7.2
    2  x2 2018-04-04     2.0     8.5
    
    df.set_index(['ind','date']).sort_index(level=[1], ascending=[False]).drop_duplicates()
    

    或者正如@piRSquare 所说:

    df.set_index(['ind','date']).sort_index(level=[1]).drop_duplicates(keep='last')
    

    输出:

                    value1  value2
    ind date                      
    x1  2018-04-23     1.3     7.2
    x2  2018-04-04     2.0     8.5
    

    【讨论】:

    • 可以跳过升序参数并使用keep='last'。喜欢头像的变化。
    • @piRSquared 谢谢。我今天感受到了一些校风。
    • 谢谢!这暂时有效。行不一定是重复的,因此对于这些情况也有一个解决方案会很好。抱歉没有给出明确的例子
    • @Rob 传递您要评估重复性的列。 drop_duplicates('ind')
    【解决方案2】:

    一种不需要排序的有点冗长的方法:

    # Gets the row indices as list of lists
    idx = df.reset_index('date', drop=False) \
        .groupby('ind', sort=False)['date'] \
        .max() \
        .iteritems()
    
    df.loc(axis=0)[list(idx)]
    

    这取决于['idx', 'date']df 中的顺序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-24
      • 2021-02-02
      • 1970-01-01
      • 2021-11-01
      • 2017-03-12
      • 1970-01-01
      • 1970-01-01
      • 2020-09-05
      相关资源
      最近更新 更多