n维表查找:数组、数据框还是字典?

2 投票
1 回答
958 浏览
提问于 2025-04-20 22:50

我正在寻找最好的方法来进行多维表格查找。在这个例子中,有一个数据框,里面包含了一个人的州和年份,我想通过查找一个表格(可以是数组、数据框或字典)来找到相关的税率。首先,考虑用数组来实现:

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

1 个回答

2

你在寻找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才能正确显示。

撰写回答