我正在尝试找到进行n维表查找的最佳方法。在本例中,有一个dataframe,它包含一个人的状态和年份,我想通过在表(可以是数组、数据帧或字典)中查找相关税率来查找。首先,考虑通过一个数组来实现:nobs = 4
df = DataFrame( { 'state' : np.tile( [ 'tx', 'ny'], nobs/2 ),
'year' : np.tile( [ 2008, 2008, 2009, 2009 ], nobs/4 ) } )
dct = { 'tx':0, 'ny':1 }
# rows are 2008 and 2009, columns are 'tx' and 'ny'
rate_arr = np.array( [[.05,.06],
[.08,.09]] )
df['rate1'] = rate_arr[ df.year-2008, df.state.map(dct) ]
state year rate1
0 tx 2008 0.05
1 ny 2008 0.06
2 tx 2009 0.08
3 ny 2009 0.09
以上正是我想要的,我只想看看有没有更好的方法。比如,有什么好的方法来标记numpy数组?在
使用dataframe作为查找似乎可以自动转换状态和年份值,但我只能使其适用于一个维度,而不是两个维度:
^{pr2}$
或者,也许是嵌套字典?同样,我可以在一个维度而不是两个维度上实现:rate_dict = { 'tx': { 2008: .05, 2009: .08 },
'ny': { 2008: .06, 2009: .09 } }
# doesn't work
df['rate2'] = df.year.map( df.state.map(rate_dict) )