【问题标题】:How to select dataframe columns using string keys when the column names are timestamps?当列名是时间戳时,如何使用字符串键选择数据框列?
【发布时间】:2018-05-11 18:13:15
【问题描述】:

在 pandas 中,可以通过传递可解释为日期的字符串来索引时间序列。这也适用于 DataFrame:

>>> dates = pd.date_range('2000-01-01', periods=8, freq='M')
>>> df = pd.DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])
>>> df
                   A         B         C         D
2000-01-31  0.096115  0.069723 -1.546733 -1.661178
2000-02-29  0.256296  1.838310  0.227132  1.765269
2000-03-31  0.315862  0.167007 -1.340888  1.005260
2000-04-30  1.238728 -2.325420  1.371134 -0.373232
2000-05-31  0.639211 -0.209961 -1.006498  0.005214
2000-06-30  0.091590 -0.664554 -2.037539 -1.335070
2000-07-31  0.275373 -0.398758  0.402848  0.441035
2000-08-31  2.189259 -1.236159 -0.579680  0.878355
>>> df['2000-05']
                   A         B         C         D
2000-05-31  0.639211 -0.209961 -1.006498  0.005214

当时间戳是列名时,我正在寻找执行此操作的方法。

>>> df = df.T
>>> df['2000-05']

这会产生TypeError: only integer scalar arrays can be converted to a scalar index

>>> df.loc[:, '2000-05']

我能想到的最直接的解决方案是

>>> df.T['2000-05'].T
   2000-05-31
A    0.639211
B   -0.209961
C   -1.006498
D    0.005214

但我想知道是否还有其他好的解决方案。我想,对于非常大的 DataFrame,进行转置可能会对性能产生影响,而这里可以避免。

【问题讨论】:

    标签: python pandas dataframe indexing timestamp


    【解决方案1】:

    嗯,总是filter 选项。

    df = df.T
    df.filter(like='2000-05')
    
       2000-05-31
    A    1.884517
    B    0.258133
    C    0.809360
    D   -0.069186
    

    filter 为您提供更大的灵活性,例如,使用正则表达式:

    df.filter(regex='2000-.*-30')
    
       2000-04-30  2000-06-30
    A   -2.968870    2.064582
    B   -0.844370    0.093393
    C    0.027328    0.033193
    D   -0.270860   -0.455323
    

    【讨论】:

      【解决方案2】:

      也许你可以试试strcontains

      df[df.index.str.contains('2000-05')].T
      Out[163]: 
         2000-05-31
      A    0.639211
      B   -0.209961
      C   -1.006498
      D    0.005214
      

      【讨论】:

      • 当我尝试这个时,我得到AttributeError: Can only use .str accessor with string values (i.e. inferred_type is 'string', 'unicode' or 'mixed')
      【解决方案3】:

      还有truncate,它允许您使用日期时间对象,而不是将列名视为字符串。

      这需要两个日期,不过 - beforeafter 参数充当您想要保留的时间段的书挡。

      df_t = df.T
      df_t.columns = pd.to_datetime(df_t.columns)
      
      df_t.truncate(after="2000-03", before="2000-02", axis=1)
      
         2000-02-29
      A    0.256296
      B    1.838310
      C    0.227132
      D    1.765269
      

      【讨论】:

      • 这似乎适用于 after="2000-06", before="2000-05" 作为原始示例的参数。
      猜你喜欢
      • 2021-07-15
      • 1970-01-01
      • 2017-06-19
      • 1970-01-01
      • 2017-08-26
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 2021-02-28
      相关资源
      最近更新 更多