Skip to main content
 首页 » 编程设计

python之查找表错误

2025年05月04日11shihaiming

我创建了一个 DataFrame,用于按年份和单位类型确定抵押贷款限额。

year    one_unit    two_unit    three_unit  four_unit   seconds 
1999    240000      307100       371200      461350     120000 
2000    252700      323400       390900      485800     126350 
2001    275000      351950       425400      528700     137500 
2002    300700      384900       465200      578150     150350 
2003    322700      413100       499300      620500     161350 
2004    333700      427150       516300      641650     166850 
2005    359650      460400       556500      691600     179825 
2006    417000      533850       645300      801950     208500 
2007    417000      533850       645300      801950     208500 

使用以下代码导入:

conform1999to2007_df = pd.read_csv("C:/conform1999to2007.csv", dtype=int, index_col='year') 

但是,当我尝试执行查找时:

conform1999to2007_df.lookup(1999,'one_unit') 

或

conform1999to2007_df.lookup('1999','one_unit') 

我分别收到以下错误消息:

Traceback (most recent call last): 
 
File "<ipython-input-145-3acef6361d09>", line 1, in <module> 
conform1999to2007_df.lookup(1999,'one_unit') 
 
File "/data/unixhome/anaconda3/lib/python3.4/site packages/pandas/core/frame.py", line 2431, in lookup 
n = len(row_labels) 
 
TypeError: object of type 'int' has no len() 

和

Traceback (most recent call last): 
 
File "<ipython-input-146-51bdd8eebaab>", line 1, in <module> 
conform1999to2007_df.lookup('1999','one_unit') 
 
File "/data/unixhome/anaconda3/lib/python3.4/site-packages/pandas/core/frame.py", line 2433, in lookup 
raise ValueError('Row labels must have same size as column labels') 
 
ValueError: Row labels must have same size as column labels 

我希望得到值“240000”。我知道这可能是一个微不足道的问题,但如果您能提供任何帮助,我们将不胜感激。

请您参考如下方法:

来自 docs :

DataFrame.lookup(row_labels, col_labels)


Akin to:

result = [] 
for row, col in zip(row_labels, col_labels): 
     result.append(df.get_value(row, col)) 

在第一个参数中,您应该传递 row_labels,即索引。您应该将 year 列作为索引,或者您可以使用 set_index('year') 来做到这一点:

df = df.set_index('year') 

在 lookup 方法中,您将标签传递给 zip 函数,它们应该是可迭代的。如果您传递 list 或 tuple,就可以这样做。

In [142]: df.lookup((1999,), ('one_unit',)) 
Out[142]: array([240000]) 
 
In [143]: df.lookup([1999], ['one_unit']) 
Out[143]: array([240000]) 

顺便说一句,如果您只需要在 one_unit 列中查找 year 列等于 1999 的值,您可以执行以下操作(如果您的 year列不是索引):

In [152]: df[df.year==1999].one_unit 
Out[152]:  
0    240000 
Name: one_unit, dtype: int64