我有一个 pandas.Series 对象,其分层索引由两个级别组成:(代码,日期)。我还有一张 map {日期 -> 代码}。我想获得一个仅按日期索引的系列,这样对于每个日期,都会在提供的 map 中查找代码,然后在原始系列中查找该对(代码,日期)。在 Pandas 中实现这一目标的最佳方法是什么? 非常感谢您的帮助。
最佳答案
简短回答:通常 NDFrame(例如 Series)通过标签进行索引。但也可以通过索引来索引 NDFrame。也就是说,您可以使用索引对 NDFrame 建立索引!
因此,将字典转换为 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
关于python - pandas 中的花式索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29234631/