我有一个脚本,只要我没有升级Pandas(0.24-->;1.1.2),它就可以正常工作。我必须从数据框中选择一个日期列表,它有一个包含日期和产品的多索引,列是度量
到目前为止,我已经做到了这一点,而且效果很好:df.loc[selected_dates]
其中selected_dates
是日期列表。某些日期可能丢失,这没关系,因为nan值将被删除
现在我不得不牺牲一只山羊来实现同样的the method suggested by the guide(使用重新索引),它仍然容易出错
如何使用新的API重新获取这些行
下面是一个示例数据框:
import pandas as pd
from random import randint
selected_dates = ['2020-09-02', '2020-09-05', '2020-09-10']
idx = pd.MultiIndex.from_product([pd.date_range('2020-09-01', '2020-09-07'), ['prod1', 'prod2', 'prod3']])
metric1 = [i for i in range(len(idx))]
metric2 = [10*i for i in range(len(idx))]
df = pd.DataFrame(dict(metric1=metric1, metric2=metric2), index=idx)
df.loc[selected_dates] # KeyError
df
数据帧将如下所示:
metric1 metric2
2020-09-01 prod1 0 0
prod2 1 10
prod3 2 20
2020-09-02 prod1 3 30
prod2 4 40
prod3 5 50
...
请用大角度思考!这些框架相当大,而且要进行多次选择。 我已经研究了this SO answer,但是它与单索引相关,而不是多索引
任何提示都将不胜感激
使用^{} 的解决方案使用转换后的值到日期时间进行匹配,然后使用
IndexSlice
和第一个:
来匹配第二级MultiIndex
中的所有值,第二个:
来匹配所有列:或者在^{} 中使用^{} 和^{} :
相关问题 更多 >
编程相关推荐