python - 使用数字计算列的平均值
问题描述
我正在从数据框中计算 column1 的平均值:
df[1].mean
或者
df[:, 1].mean
它显示错误:
'in get_loc
raise KeyError(key) from err
KeyError: 1'
有人知道我该如何解决吗?(平均值应避免考虑标题行)
解决方案
如果列名确实是数字格式,您的代码应该可以工作(除了缺少()
for )。mean
例如:
df = pd.DataFrame({1: [1.0, 2.0, 3.0]})
df[1].mean()
Output:
2.0
这种错误的一种可能性是您的列名实际上是一个字符(1 个字母的字符串)。例如:
df = pd.DataFrame({'1': [1.0, 2.0, 3.0]})
df[1].mean()
Output:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
3079 try:
-> 3080 return self._engine.get_loc(casted_key)
3081 except KeyError as err:
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: 1
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
<ipython-input-58-0fbd35b7b19f> in <module>
----> 1 df[1].mean()
~\anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
3022 if self.columns.nlevels > 1:
3023 return self._getitem_multilevel(key)
-> 3024 indexer = self.columns.get_loc(key)
3025 if is_integer(indexer):
3026 indexer = [indexer]
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
3080 return self._engine.get_loc(casted_key)
3081 except KeyError as err:
-> 3082 raise KeyError(key) from err
3083
3084 if tolerance is not None:
KeyError: 1
在这种情况下,您应该将 括1
在一对括号中:
df['1'].mean()
Output:
2.0
推荐阅读
- c# - 从 Web 应用程序(asp.net 核心)中的视频/音频文件获取持续时间
- spring - 无法从 Spring Boot 应用程序中的浏览器访问 http:inbound-gateway 映射
- php - Laravel/Blade 布局文件中不同内容的切换
- javascript - 如何从数据库 ondelete 重新渲染列表视图
- jsf - p:menuitem 的 url 和结果属性有什么区别?
- php - 无法从目录中删除图像,但数据已成功从 codeigniter 中的数据库中删除
- php - 如何在for循环PHP之外获取字符串
- php - 从字节字符串以 PHP 显示图像
- mysql - mysqldump 出错,在查询期间丢失与 MySQL 服务器的连接
- java - 读取下载的文本文件 - FileNotFoundException