如何在Pandas 1.1.2中获得多个标签?

2024-10-03 21:25:26 发布

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

我有一个脚本,只要我没有升级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,但是它与单索引相关,而不是多索引

任何提示都将不胜感激


Tags: the数据df列表rangelocpddates
1条回答
网友
1楼 · 发布于 2024-10-03 21:25:26

使用^{}的解决方案使用转换后的值到日期时间进行匹配,然后使用IndexSlice和第一个:来匹配第二级MultiIndex中的所有值,第二个:来匹配所有列:

idx = pd.IndexSlice

selected_dates = pd.to_datetime(selected_dates)
df = df.loc[idx[selected_dates,:], :] 
print (df)
                  metric1  metric2
2020-09-02 prod1        3       30
           prod2        4       40
           prod3        5       50
2020-09-05 prod1       12      120
           prod2       13      130
           prod3       14      140

或者在^{}中使用^{}^{}

selected_dates = pd.to_datetime(selected_dates)
df = df[df.index.get_level_values(0).isin(selected_dates)]
print (df)
                  metric1  metric2
2020-09-02 prod1        3       30
           prod2        4       40
           prod3        5       50
2020-09-05 prod1       12      120
           prod2       13      130
           prod3       14      140

相关问题 更多 >