Skip to main content
 首页 » 编程设计

python之为什么 str.replace (在索引上)给出 KeyError

2024年11月24日17tuyile006

我正在尝试使用下面的代码来替换国家/地区名称中的括号,其中国家/地区是 DataFrame 的索引:

energy['Country'] = energy['Country'].str.replace(r"\s+\(.*\)","") 

我在这里和那里尝试了各种变体,但无论我做什么,我都会收到以下错误:

KeyError                                  Traceback (most recent call last) 
/opt/conda/lib/python3.6/site-packages/pandas/indexes/base.py in get_loc(self, key, method, tolerance) 
   2133             try: 
-> 2134                 return self._engine.get_loc(key) 
   2135             except KeyError: 

接着是:

KeyError: 'Country' 
 
During handling of the above exception, another exception occurred: 
 
KeyError                                  Traceback (most recent call last) 
<ipython-input-45-740ea96e825f> in <module>() 
     23  
     24 #energy['Country'] = energy['Country'].str.replace("A","B") 
---> 25 energy['Country'] = energy['Country'].str.replace(r"\s+\(.*\)","") 
     26  
     27 #energy['Country'] = energy['Country'] 

然后它继续前进。

有人可以解释错误以及我需要更正的地方吗?

谢谢。

请您参考如下方法:

如果“国家/地区”在您的索引中,您无法使用 df['Country'] 语法访问它。这仅适用于表列。但是,您还有其他选择。

为了简单起见,我使用了以下测试 DataFrame。

df = pd.DataFrame([('abb', 1, 2), ('abc', 2, 4), ('abd', 3, 7), ('abe', 4, 8), ('abg', 5, 6), ('abh', 6, 3)], columns=['Country', 'b', 'c']) 

如果“国家/地区”在索引(和单级索引)中,您可以按如下方式执行替换。请注意,这不会在 MultiIndex 上工作。

df = df.set_index('Country') 
df.index = df.index.str.replace(r"a","") 

或者,您可以使用 .reset_index 将所有内容移出索引并移回列中。然后,您可以按原样进行索引编制。

df = df.set_index(['Country', 'b'])  # Move 2 columns into the index. 
df = df.reset_index()  # Country & b are now back out of the index, as a normal columns. 
df['Country'] = df['Country'].str.replace(r"a","")  # Normal indexing works. 

在这两种情况下,您都应该得到以下输出

  Country  b  c 
0      bb  1  2 
1      bc  2  4 
2      bd  3  7 
3      be  4  8 
4      bg  5  6 
5      bh  6  3