在用于时间序列分析的pandas数据帧中设置两列作为索引

2024-05-13 12:08:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

天气:天气预报,然后是日期

对于股票数据:股票代码,然后是日期

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

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

Tags: 数据方法dfdate站点情况温度start
2条回答

如安东所述,您需要使用多索引,如下所示:

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'])

该功能当前存在。有关更多示例,请参阅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

相关问题 更多 >