我正在尝试使用 Pandas 中的 agg 函数生成描述性统计数据。我在使用 lambda 函数的一行时遇到问题。当我将它们作为单独的代码行运行时它们会起作用,但是当我将它们作为单行运行时会出现错误。
非常感谢任何指导。
以下两行代码在我单独运行时起作用。
第一行代码:
bh_df.groupby('CAT.MEDV').agg(
avg_Nox=('NOX', 'mean'))
第二行带有 lambda 函数。
bh_df.groupby('CAT.MEDV').agg(
rng=("NOX", lambda x: (max(x) - min(x))))
但是,当我将它们组合成一行代码时:
bh_df.groupby('CAT.MEDV').agg(
avg_Nox=('NOX', 'mean'),
rng=("NOX", lambda x: (max(x) - min(x))))
我收到一大堆错误:
文件“”,第 4 行,在
rng=("NOX", λ x: (max(x) - min(x))))
文件“C:\Users\pdile\Anaconda3\lib\site-packages\pandas\core\groupby\generic.py”,第 1455 行,总计返回 super().aggregate(arg, *args, **kwargs)
文件“C:\Users\pdile\Anaconda3\lib\site-packages\pandas\core\groupby\generic.py”,第 264 行,汇总结果 = 结果 [顺序]
文件“C:\Users\pdile\Anaconda3\lib\site-packages\pandas\core\frame.py”,第 2986 行,在getitem indexer = self.loc._convert_to_indexer(key, axis=1, raise_missing=True)
文件“C:\Users\pdile\Anaconda3\lib\site-packages\pandas\core\indexing.py”,第 1285 行,在 _convert_to_indexer 中返回 self._get_listlike_indexer(obj, axis, **kwargs)[1]
文件“C:\Users\pdile\Anaconda3\lib\site-packages\pandas\core\indexing.py”,第 1092 行,在 _get_listlike_indexer keyarr、indexer、o._get_axis_number(axis)、raise_missing=raise_missing
_validate_read_indexer 中的文件“C:\Users\pdile\Anaconda3\lib\site-packages\pandas\core\indexing.py”,第 1185 行
最终错误:
raise KeyError("{} 不在索引中".format(not_found))
KeyError:“[('NOX','')]不在索引中”



