【发布时间】:2019-01-07 17:20:40
【问题描述】:
找不到类似的问题。 假设我有 grouped_price 和 Multiindex (City, Month),看起来像这样:
City Month Price Sales
LA 2017-01 10 10
2017-02 15 20
2017-05 20 35
2017-07 25 40
NY 2017-01 10 5
2017-03 15 30
2017-05 20 40
2017-06 25 45
CH 2017-01 7 10
2017-02 11 22
2017-07 30 41
OL 2017-01 9 10
2017-02 17 10
2017-05 20 30
2017-07 25 41
2017-08 30 47
所以对于“正常”循环顺序 City -> Month I did:
Cities = grouped_price.index.levels[0]
for city in Cities:
labels = grouped_price.loc[city].index.labels
levels = grouped_price.loc[city].index.levels
Months = levels[0][labels[0]].unique() # for each City get a list of existing Months
for mon in Months:
# do things here
x = grouped_price.loc[city, mon] # ERROR here!
它有效。但是对于反向循环:
Months = grouped_price.index.levels[1]
Cities = grouped_price.index.levels[0]
for mon in Months:
# Here I should get the list of Cities for specific Month
for city in Cities:
# do things here
x = grouped_price.loc[city, mon] # ERROR here!
给出错误,因为 MultiIndex 中并不存在所有的 city-mon 对。 我应该找到特定月份的城市列表,存在哪些配对,但我不明白如何。
Cities = grouped_price.loc[:, mon] - doesn't work
附:我知道我可以旋转表格,或者以相反的顺序对它们进行分组,但我不想这样做。
【问题讨论】:
标签: python pandas indexing pandas-groupby multi-index