为什么这个熊猫计算会返回错误

问题描述 投票:0回答:1

我几个小时前开始学习Python并遇到了这个问题下面的脚本可以正确运行,并生成预期的输出

import pandas as pd
brics = pd.read_csv('G:/brics.csv', index_col = 0)
brics

但是,当我使用此代码(用于计算密度)时

brics["density"] = brics["population"] / brics["area"] * 1000000

我在下面收到错误消息:

d:\python\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2645             try:
-> 2646                 return self._engine.get_loc(key)
   2647             except KeyError:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'population'
During handling of the above exception, another exception occurred:
KeyError                                  Traceback (most recent call last)
<ipython-input-7-7f590cb7a5d0> in <module>
      1 import pandas as pd
      2 brics = pd.read_csv("G:/brics.csv", index_col = 0)
----> 3 brics["density"] = brics["population"] / brics["area"] * 1000000
      4 brics
d:\python\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2798             if self.columns.nlevels > 1:
   2799                 return self._getitem_multilevel(key)
-> 2800             indexer = self.columns.get_loc(key)
   2801             if is_integer(indexer):
   2802                 indexer = [indexer]
d:\python\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2646                 return self._engine.get_loc(key)
   2647             except KeyError:
-> 2648                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2649         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2650         if indexer.ndim > 1 or indexer.size > 1:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'population'
python pandas jupyter
1个回答
0
投票

尝试这样的事情

brics.info()
© www.soinside.com 2019 - 2024. All rights reserved.