使用Pandas从Start Date提取年份新增DataFrame列时报错
问题核心背景
目标为现有DataFrame新增名为year的列,从类型为datetime64[ns]的Start Date列提取年份值。已尝试两种提取写法:
df["year"] = pd.DatetimeIndex(df["Start Date"]).yeardf["year"] = df["Start Date"].dt.year
两种写法执行时均无法成功新增列并抛出异常,但单独执行df2 = df["Start Date"].dt.year无报错,生成的df2包含正确年份值,特征为Name: Start Date, Length: 132, dtype: int64。
原始DataFrame样例(df.head()输出)
Runs Mins BF 4s 6s SR Pos Dismissal Inns Opposition Ground Start Date 0 12 33 22 1 0 54.54 2 lbw 1 v Sri Lanka Dambulla 2008-08-18 1 37 82 67 6 0 55.22 2 caught 2 v Sri Lanka Dambulla 2008-08-20 2 25 40 38 4 0 65.78 1 run out 1 v Sri Lanka Colombo (RPS) 2008-08-24 3 54 87 66 7 0 81.81 1 bowled 1 v Sri Lanka Colombo (RPS) 2008-08-27 4 31 45 46 3 1 67.39 1 lbw 2 v Sri Lanka Colombo (RPS) 2008-08-29
完整报错信息
> KeyError Traceback (most recent python > last) ~\anaconda3\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: 'Year' > > During handling of the above exception, another exception occurred: > > KeyError Traceback (most recent python > last) ~\anaconda3\lib\site-packages\pandas\core\internals\managers.py > in set(self, item, value) 1070 try: > -> 1071 loc = self.items.get_loc(item) 1072 except KeyError: > > ~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in > get_loc(self, key, method, tolerance) 2647 except > KeyError: > -> 2648 return self._engine.get_loc(self._maybe_cast_indexer(key)) 2649 > indexer = self.get_indexer([key], method=method, tolerance=tolerance) > > 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: 'Year' > > During handling of the above exception, another exception occurred: > > AttributeError Traceback (most recent python > last) <ipython-input-53-212e4faa5daa> in <module> > 1 #Your code here > ----> 2 df["Year"] = pd.DatetimeIndex(df["Start Date"]).year > > ~\anaconda3\lib\site-packages\pandas\core\frame.py in > __setitem__(self, key, value) 2936 else: 2937 # set column > -> 2938 self._set_item(key, value) 2939 2940 def _setitem_slice(self, key, value): > > ~\anaconda3\lib\site-packages\pandas\core\frame.py in _set_item(self, > key, value) 2999 self._ensure_valid_index(value) 3000 > value = self._sanitize_column(key, value) > -> 3001 NDFrame._set_item(self, key, value) 3002 3003 # check if we are modifying a copy > > ~\anaconda3\lib\site-packages\pandas\core\generic.py in > _set_item(self, key, value) 3622 3623 def _set_item(self, key, value) -> None: > -> 3624 self._data.set(key, value) 3625 self._clear_item_cache() 3626 > > ~\anaconda3\lib\site-packages\pandas\core\internals\managers.py in > set(self, item, value) 1072 except KeyError: 1073 > # This item wasn't present, just insert at end > -> 1074 self.insert(len(self.items), item, value) 1075 return 1076 > > ~\anaconda3\lib\site-packages\pandas\core\internals\managers.py in > insert(self, loc, item, value, allow_duplicates) 1192 if > loc == self._blklocs.shape[0]: 1193 # np.append is a > lot faster, let's use it if we can. > -> 1194 self._blklocs = np.append(self._blklocs, 0) 1195 self._blknos = np.append(self._blknos, > len(self.blocks)) 1196 else: > > <__array_function__ internals> in append(*args, **kwargs) > > ~\anaconda3\lib\site-packages\numpy\lib\function_base.py in > append(arr, values, axis) 4689 if arr.ndim != 1: 4690 > arr = arr.ravel() > -> 4691 values = ravel(values) 4692 axis = arr.ndim-1 4693 return concatenate((arr, values), axis=axis) > > <__array_function__ internals> in ravel(*args, **kwargs) > > ~\anaconda3\lib\site-packages\numpy\core\fromnumeric.py in ravel(a, > order) 1792 1793 """ > -> 1794 if isinstance(a, np.matrix): 1795 return asarray(a).ravel(order=order) 1796 else: > > AttributeError: module 'numpy' has no attribute 'matrix'
根因定位
- 提取年份的逻辑本身无错误:单独执行年份提取语句可正常返回结果,说明两种提取写法的语法、数据源访问都没有问题。
- 核心报错来源是pandas与numpy版本不兼容:最终行报错
AttributeError: module 'numpy' has no attribute 'matrix'显示,当前安装的高版本numpy已移除旧版的np.matrix属性,但使用的低版本pandas内部代码仍在调用该属性,导致在执行新增列的插入流程时崩溃。 - 报错中出现的
KeyError: 'Year'是新增不存在列时的正常前置流程触发,并非Start Date列访问错误。
可行解决方法
- 调整版本匹配关系
- 升级pandas到兼容当前numpy版本的版本:执行
pip install --upgrade pandas - 降级numpy到适配当前pandas的低版本(numpy<2.0,保留
np.matrix属性):执行pip install "numpy<2.0"
- 升级pandas到兼容当前numpy版本的版本:执行
- 临时绕开兼容问题
不要直接用赋值语句新增列,先提取好年份Series后与原表横向拼接,避开pandas内部触发np.append的逻辑:year_series = df["Start Date"].dt.year year_series.name = "year" df = pd.concat([df, year_series], axis=1)
内容的提问来源于stack exchange,提问作者JackAss
相关产品推荐
相关产品推荐

