【发布时间】:2020-02-12 05:34:56
【问题描述】:
我查看了有关在 Python 中切片 DF 的类似问题,但它们没有解释我在练习中看到的不一致。
该代码适用于已知的菱形数据框。数据框的顶行是:
carat cut color clarity depth table price x y z
0 0.23 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43
1 0.21 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31
2 0.23 Good E VS1 56.9 65.0 327 4.05 4.07 2.31
我必须创建一个带有 4 个参数的切片函数:DataFrame 'df',该 DataFrame 的一列 'col',另一列'label'的标签和两个值'val1'和'val2'。该函数将获取帧并输出由 'label' 参数指示的列的条目,其中列 'col' 的行大于数字 'val1' 且小于 'val2'。
下面这段独立的代码给了我正确的答案:
diamonds.loc[(diamonds.carat > 1.1) & (diamonds.carat < 1.4),['price']]
我从克拉值在 1.1 到 1.4 之间的行中获取价格。
但是,当我尝试在函数中使用此语法时,它不起作用并且出现错误。
功能:
def slice2(df,col,output_label,val1,val2):
res = df.loc[(col > val1) & (col < val2), ['output_label']]
return res
函数调用:
slice2(diamonds,diamonds.carat,'price',1.1,1.4)
错误:
"None of [['output_label']] are in the [columns]"
完整的回溯消息:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-64-adc582faf6cc> in <module>()
----> 1 exercise2(test_df,test_df.carat,'price',1.1,1.4)
<ipython-input-63-556b71ba172d> in exercise2(df, col, output_label, val1, val2)
1 def exercise2(df,col,output_label,val1,val2):
----> 2 res = df.loc[(col > val1) & (col < val2), ['output_label']]
3 return res
/Users/jojo/Library/Enthought/Canopy/edm/envs/User/lib/python3.5/site-packages/pandas/core/indexing.py in __getitem__(self, key)
1323 except (KeyError, IndexError):
1324 pass
-> 1325 return self._getitem_tuple(key)
1326 else:
1327 key = com._apply_if_callable(key, self.obj)
/Users/jojo/Library/Enthought/Canopy/edm/envs/User/lib/python3.5/site-packages/pandas/core/indexing.py in _getitem_tuple(self, tup)
839
840 # no multi-index, so validate all of the indexers
--> 841 self._has_valid_tuple(tup)
842
843 # ugly hack for GH #836
/Users/jojo/Library/Enthought/Canopy/edm/envs/User/lib/python3.5/site-packages/pandas/core/indexing.py in _has_valid_tuple(self, key)
187 if i >= self.obj.ndim:
188 raise IndexingError('Too many indexers')
--> 189 if not self._has_valid_type(k, i):
190 raise ValueError("Location based indexing can only have [%s] "
191 "types" % self._valid_types)
/Users/jojo/Library/Enthought/Canopy/edm/envs/User/lib/python3.5/site-packages/pandas/core/indexing.py in _has_valid_type(self, key, axis)
1416
1417 raise KeyError("None of [%s] are in the [%s]" %
-> 1418 (key, self.obj._get_axis_name(axis)))
1419
1420 return True
KeyError: "None of [['output_label']] are in the [columns]"
我在 Python 方面不是很先进,在查看这段代码一段时间后,我无法弄清楚问题所在。也许我在这里对一些明显的东西视而不见,如果有人指出如何让函数工作或如何重做它,以便它给出与单行代码相同的结果,我将不胜感激。
谢谢
【问题讨论】:
标签: python pandas dataframe slice