我有一个多索引数据帧,我希望根据索引值和布尔条件提取一个子集。我希望使用多索引键和布尔索引器覆盖特定新值的值以选择要修改的记录。在
import pandas as pd
import numpy as np
years = [1994,1995,1996]
householdIDs = [ id for id in range(1,100) ]
midx = pd.MultiIndex.from_product( [years, householdIDs], names = ['Year', 'HouseholdID'] )
householdIncomes = np.random.randint( 10000,100000, size = len(years)*len(householdIDs) )
householdSize = np.random.randint( 1,5, size = len(years)*len(householdIDs) )
df = pd.DataFrame( {'HouseholdIncome':householdIncomes, 'HouseholdSize':householdSize}, index = midx )
df.sort_index(inplace = True)
我能够使用索引和列标签成功地查询数据帧。在
这个例子给出了1996年住户3的户主规模
df.loc[ (1996,3 ) , 'HouseholdSize' ]
=> 1
pandas docs on Multi-indexing表示有一种方法可以将布尔索引和多重索引结合起来,并给出了一个示例。。。在
In [52]: idx = pd.IndexSlice
In [56]: mask = dfmi[('a','foo')]>200
In [57]: dfmi.loc[idx[mask,:,['C1','C3']],idx[:,'foo']]
Out[57]:
lvl0 a b
lvl1 foo foo
A3 B0 C1 D1 204 206
C3 D0 216 218
D1 220 222
B1 C1 D0 232 234
D1 236 238
C3 D0 248 250
D1 252 254
…我似乎无法在我的数据帧上复制
idx = pd.IndexSlice
housholdSizeAbove2 = ( df.HouseholdSize > 2 )
df.loc[ idx[ housholdSizeAbove2, 1996, :] , 'HouseholdSize' ]
Traceback (most recent call last):
File "python", line 1, in <module>
KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (3), lexsort depth (2)'
在本例中,我希望看到1996年住户规模大于2的所有家庭
Pandas.query()在这种情况下应该有效:
演示:
^{pr2}$更新:
更新2:
相关问题 更多 >
编程相关推荐