【问题标题】:filtering a pandas dataframe for the max date and symbol为最大日期和符号过滤熊猫数据框
【发布时间】:2019-02-22 17:16:44
【问题描述】:

我在这里问了一个问题,我没有收到错误,而是一个带有列的空数据框。我做错了什么?

我的原始数据框在下面

               Date    Symbol
     49     2018-11-27  0
     50     2018-12-10  0
     51     2018-12-17  0
     52     2018-12-27  XLK
     53     2018-12-27  XLV
     54     2018-12-28  VTV
     55     2019-01-09  0
     56     2019-01-09  0
     57     2019-01-16  0
     58     2019-02-04  0
     59     2019-02-04  0
     61     2019-02-05  SPY
     62     2019-02-05  0
     60     2019-02-05  TLT
     63     2019-02-07  TLT
     64     2019-02-09  0

下面的语句有效,但给了我一个空数据框:

df.loc[(df['Symbol'] == "TLT") & (df['Date'] == df['Date'].max())] 

链接 unsupported operand type(s) for &: 'str' and 'Timestamp'

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    通过to_datetime 将列转换为日期时间,也不需要loc,因此应该删除:

    df['Date'] = pd.to_datetime(df['Date'])
    df[(df['Symbol'] == "TLT") & (df['Date'] == df['Date'].max())] 
    

    【讨论】:

      【解决方案2】:

      只是补充一些想法。你也可以使用idxmax()idxmin()

      df.loc[df.groupby('Date')['Symbol'].idxmax()]
      

      这将为您提供每个 Symbol 类别的最大 Date

      【讨论】:

      • 好建议,但不起作用。 'SeriesGroupBy' 对象没有属性 '_aggregate_item_by_item
      • @JohnJohn 先做这个? df['Date'] = pd.to_datetime(df['Date'])
      猜你喜欢
      • 1970-01-01
      • 2020-05-05
      • 2013-06-09
      • 2014-06-04
      • 2018-01-18
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多