【问题标题】:Retrieve value associated with max date from list of tuples in a series从系列中的元组列表中检索与最大日期关联的值
【发布时间】:2021-03-09 11:35:17
【问题描述】:

概述

我有一个熊猫系列中的元组列表,每个元组中都包含价格和相关日期。

测试数据

SeriesDict = {0: [(0.9919, '2002-05-31 21:00:00+00:00'),
  (0.9898, '2002-09-30 21:00:00+00:00'),
  (0.9905, '2002-10-31 22:00:00+00:00')],
 1: [(1.01195, '2002-06-30 21:00:00+00:00'),
  (1.013, '2002-10-31 22:00:00+00:00')]}
TestSeries = pd.Series(SeriesDict)

我尝试了什么?

我可以从元组列表中获取最大日期,如下所示:

TestSeries.apply(lambda x: max([y[1] for y in x])).iloc[0]

返回'2002-10-31 22:00:00+00:00'。稍后我将使用它为新数据框中的每一行创建一个带有max date 的新列。

我现在如何使用 apply 或类似方法检索与 max date 关联的价格(价格是元组中的 y[0])?

Desired output 是一个新列,其中包含与每个日期相关联的价格,即本示例应返回 0.9905

【问题讨论】:

    标签: pandas


    【解决方案1】:

    使用itemgetter:

    from operator import itemgetter
    
    print (TestSeries.apply(lambda x: max([y[1] for y in x])))
    0    2002-10-31 22:00:00+00:00
    1    2002-10-31 22:00:00+00:00
    
    
    print (TestSeries.apply(lambda x: max(x,key=itemgetter(1))[0]))
    0    0.9905
    1    1.0130
    dtype: float64
    

    另一个想法是创建DataFrame然后处理:

    s = TestSeries.explode()
    
    df = pd.DataFrame(s.tolist(), columns=['a','b'], index=s.index)
    print (df)
             a                          b
    0  0.99190  2002-05-31 21:00:00+00:00
    0  0.98980  2002-09-30 21:00:00+00:00
    0  0.99050  2002-10-31 22:00:00+00:00
    1  1.01195  2002-06-30 21:00:00+00:00
    1  1.01300  2002-10-31 22:00:00+00:00
    
    
    df = df.sort_values('b')
    df = df[~df.index.duplicated(keep='last')]
    print (df)
            a                          b
    0  0.9905  2002-10-31 22:00:00+00:00
    1  1.0130  2002-10-31 22:00:00+00:00
    

    或者:

    s = TestSeries.explode()
    
    df = pd.DataFrame(s.tolist(), columns=['a','b']).assign(g = s.index)
    
    df = df.sort_values('b').drop_duplicates(subset=['g'], keep='last')
    print (df)
            a                          b  g
    2  0.9905  2002-10-31 22:00:00+00:00  0
    4  1.0130  2002-10-31 22:00:00+00:00  1
    

    【讨论】:

      猜你喜欢
      • 2022-12-09
      • 2011-06-17
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      • 2020-06-14
      • 2018-07-04
      • 2014-07-20
      相关资源
      最近更新 更多