【问题标题】:set two columns as the index in a pandas dataframe for time series analysis将两列设置为 pandas 数据框中的索引以进行时间序列分析
【发布时间】:2016-05-21 17:54:53
【问题描述】:

在天气或股市数据的情况下,温度和股票价格都是在多个站点或股票代码中测量任何给定日期的。

那么设置包含两个字段的索引最有效的方法是什么?

天气:weather_station,然后是日期

对于股票数据:stock_code 然后是日期

以这种方式设置索引将允许过滤,例如:

  • stock_df["code"]["start_date":"end_date"]
  • weather_df["station"]["start_date":"end_date"]

【问题讨论】:

  • Multiindex 呢?

标签: python pandas indexing time-series


【解决方案1】:

该功能当前存在。更多示例请参考documentation

stock_df = pd.DataFrame({'symbol': ['AAPL', 'AAPL', 'F', 'F', 'F'], 
                         'date': ['2016-1-1', '2016-1-2', '2016-1-1', '2016-1-2', '2016-1-3'], 
                         'price': [100., 101, 50, 47.5, 49]}).set_index(['symbol', 'date'])

>>> stock_df
                 price
symbol date           
AAPL   2016-1-1  100.0
       2016-1-2  101.0
F      2016-1-1   50.0
       2016-1-2   47.5
       2016-1-3   49.0

>>> stock_df.loc['AAPL']
          price
date           
2016-1-1    100
2016-1-2    101

>>> stock_df.loc['AAPL', '2016-1-2']
price    101
Name: (AAPL, 2016-1-2), dtype: float64

【讨论】:

    【解决方案2】:

    正如 Anton 所说,您需要按如下方式使用 MultiIndex:

    stock_df.index = pd.MultiIndex.from_arrays(stock_df[['code', 'date']].values.T, names=['idx1', 'idx2'])
    
    weather_df.index = pd.MultiIndex.from_arrays(weather_df[['station', 'date']].values.T, names=['idx1', 'idx2'])
    

    【讨论】:

      猜你喜欢
      • 2014-10-05
      • 1970-01-01
      • 2013-09-19
      • 2020-12-21
      • 2019-06-18
      • 1970-01-01
      • 2022-01-04
      • 2020-04-30
      • 2015-09-04
      相关资源
      最近更新 更多