簡體   English   中英

在熊貓數據框中設置兩列作為索引以進行時間序列分析

[英]set two columns as the index in a pandas dataframe for time series analysis

對於天氣或股票市場數據,在任何給定日期都在多個站點或股票行情指示器中測量溫度和股票價格。

因此,設置包含兩個字段的索引的最有效方法是什么?

對於天氣:weather_station,然后單擊日期

對於庫存數據:stock_code然后是Date

以這種方式設置索引將允許過濾,例如:

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

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

該功能當前存在。 請參考文檔以獲取更多示例。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM