gpt4 book ai didi

python - 通过标签元组选择二级索引

转载 作者:太空宇宙 更新时间:2023-11-03 17:34:27 25 4
gpt4 key购买 nike

我在 ('dt', 'product_id') 上索引了一些销售数据像这样:

In [43]: sub.head()
Out[43]:
income
dt product_id
2015-01-15 10016 23
2015-01-15 10017 188
2015-01-15 10018 NaN
2015-01-16 10016 188
2015-01-17 10025 1000
# this goes on and on...

如何查看产品10016的收入和10025之间2015-01-152015-01-16 ?我尝试了解 pandas 切片机 here但无法得到正确的结果:

In [44]: sub.loc[idx[start:end,[10016,10018]]]

KeyError: 'None of [[10055, 10158]] are in the [columns]'

原始数据

import pandas as pd

product_order = pd.DataFrame.from_csv('order.csv')
odr = product_order.set_index(['dt','product_id'])
dt,product_id,subsidy
2015-03-03 00:39:08+08:00,10029,50.00
2015-03-09 00:47:00+08:00,10016,55.00
2015-03-13 01:00:12+08:00,10029,23.00
2015-03-15 01:03:40+08:00,10016,21.00
2015-03-16 02:18:45+08:00,10016,52.00

最佳答案

假设这里 gp 是您的 groupby 对象,您已经可以像下面这样进行切片:

In [146]:
idx = pd.IndexSlice
gp.loc[idx['2015-01-15':'2015-01-16'], idx[10016:10025]]

Out[146]:
dt product_id
2015-01-15 10016 23
10017 188
10018 NaN
2015-01-16 10016 188
Name: income, dtype: float64

所以你需要定义一个IndexSlice对于要执行行选择标准的每个级别

关于python - 通过标签元组选择二级索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31404165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com