Skip to main content
 首页 » 编程设计

python之Pandas 中的花式索引

2024年10月25日14oomusou

我有一个 pandas.Series 对象,其层次索引由两个级别组成:(代码,日期)。我还有一张 map {date -> code}。我想得到一个仅按日期索引的系列,这样对于每个日期,都会在提供的 map 中查找代码,然后在原始系列中查找 (code, date) 对。在 Pandas 中实现这一目标的最佳方式是什么? 非常感谢您的帮助。

请您参考如下方法:

简答:通常 NDFrame(例如系列)由标签索引。但也可以通过索引来索引 NDFrame。也就是说,您可以使用索引索引 NDFrame!

因此,将 dict 转换为 MultiIndex。使用 MultiIndex 从中选择行 系列:系列[索引]。


假设您的系列看起来像这样:

import numpy as np 
import pandas as pd 
np.random.seed(0) 
 
N, M = 3, 5 
big_dates = pd.date_range('2000-1-1', periods=M, freq='D') 
index = pd.MultiIndex.from_product([np.arange(N), big_dates]) 
series = pd.Series(np.random.randint(10, size=N*M), index=index) 
print(series) 
# 0  2000-01-01    5 
#    2000-01-02    0 
#    2000-01-03    3 
#    2000-01-04    3 
#    2000-01-05    7 
# 1  2000-01-01    9 
#    2000-01-02    3 
#    2000-01-03    5 
#    2000-01-04    2 
#    2000-01-05    4 
# 2  2000-01-01    7 
#    2000-01-02    6 
#    2000-01-03    8 
#    2000-01-04    8 
#    2000-01-05    1 
# dtype: int64 

假设字典(我们称它为 codemap)如下所示:

dates = pd.date_range('2000-1-1', periods=N, freq='D') 
codes = np.arange(N) 
np.random.shuffle(codes) 
codemap = dict(zip(dates, codes)) 
# {Timestamp('2000-01-01 00:00:00', offset='D'): 0, 
#  Timestamp('2000-01-02 00:00:00', offset='D'): 1, 
#  Timestamp('2000-01-03 00:00:00', offset='D'): 2} 

然后你可以从 codemap 字典中形成第二个 MultiIndex:

codemap_index = pd.MultiIndex.from_arrays([codemap.values(), codemap.keys()]) 

并用它来索引系列:

result = series[codemap_index] 
# 0  2000-01-01    5 
# 1  2000-01-02    3 
# 2  2000-01-03    8 
# dtype: int64 

最后,使用droplevel去除索引中的代码层级:

result.index = result.index.droplevel(0) 
print(result) 

产量

2000-01-01    5 
2000-01-02    3 
2000-01-03    8 
dtype: int64