Skip to main content
 首页 » 编程设计

python之n维表查找: array,数据框,还是字典

2024年10月25日11zhenyulu

我正在尝试找到执行 n 维表查找的最佳方法。在这个例子中,有一个包含一个人的州和年份的数据框,我想通过在表(可以是数组、数据框或字典)中查找它来找到相关的税率。首先,考虑通过数组来实现:

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 数组吗?

使用数据框作为查找似乎可以自动转换状态和年份值,但我只能让它在一个维度上工作,而不是两个维度:

rate_df = DataFrame( { 2008: [ .05, .06 ], 
                       2009: [ .08, .09 ] } , index=(['tx','ny']) ) 
 
# doesn't work 
df['rate3'] = rate_df[ df.year, df.state ] 

或者,也许是嵌套字典?同样,我可以让它在一维而不是二维工作:

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) ) 

请您参考如下方法:

您正在寻找 lookup :

In [21]: rate_df.lookup(df['state'], df['year']) 
Out[21]: array([ 0.05,  0.06,  0.08,  0.09]) 
 
In [22]: df['rate2'] = res.lookup(df['state'], df['year']) 
 
In [23]: df 
Out[23]: 
  state  year  rate1  rate2 
0    tx  2008   0.05   0.05 
1    ny  2008   0.06   0.06 
2    tx  2009   0.08   0.08 
3    ny  2009   0.09   0.09 

注意:您可以指定索引 和 列以从 numpy 数组中获取带标签的 DataFrame:

In [11]: rate_df = pd.DataFrame(rate_arr.T, index=['tx', 'ny'], columns=[2008, 2009]) 
 
In [12]: rate_df 
Out[12]: 
    2008  2009 
tx  0.05  0.08 
ny  0.06  0.09 

更新:我需要转置 numpy 数组,以便 rate_df 的方向正确。