python - 如何对使用 multiIndex 索引的 Dataframe 的 DataFrame 中的 DataFrame 执行操作
问题描述
我有一个包含许多其他数据框的数据框。这些都使用两个“级别”的索引进行索引。
现在我想对这些子数据帧进行一些操作(例如,取一行中所有值的平均值并将其添加到新行中)。由于我想迭代地执行此操作,因此我开始编写以下循环:
dfs_frame = pd.read_pickle(DATAFRAMESOUT + 'dfs_frame.pkl')
for name,video in dfs_frame.groupby(level=1):#returns tuple of (vid_name, dataframe)
for frames in video[0]:
print(frames)
这将返回一个帧列表。但是,一旦我尝试执行任何操作,例如,甚至只打印其中一列:
dfs_frame = pd.read_pickle(DATAFRAMESOUT + 'dfs_frame.pkl')
for name,video in dfs_frame.groupby(level=1):#returns tuple of (vid_name, dataframe)
for frames in video[0]:
print(frames['neutral'])
我收到以下错误:
Traceback (most recent call last):
File "C:\Users\chazzers\FER\venv\lib\site-packages\pandas\core\indexes\base.py", line 3361, in get_loc
return self._engine.get_loc(casted_key)
File "pandas\_libs\index.pyx", line 76, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 5198, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 5206, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'neutral'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "D:\PyCharm 2020.1.4\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "D:\PyCharm 2020.1.4\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/chazzers/FER/r-squared.py", line 145, in <module>
print(frames['neutral'])
File "C:\Users\chazzers\FER\venv\lib\site-packages\pandas\core\frame.py", line 3455, in __getitem__
indexer = self.columns.get_loc(key)
File "C:\Users\chazzers\FER\venv\lib\site-packages\pandas\core\indexes\base.py", line 3363, in get_loc
raise KeyError(key) from err
KeyError: 'neutral'
非常感谢任何帮助。我希望这是足够的细节,可以让你理解我的问题。如果需要,很高兴澄清任何事情。
解决方案
推荐阅读
- c# - 我想添加由 Field Asana Api 创建的故事(评论)
- r - 如何(有效地)从访问过的地方列表中构建边缘列表?
- ios - 单击段控制表单元格内的按钮时无法执行 segue
- javascript - 柱形图水平刻度的透明背景
- apache-flink - 共享的检查点非常大
- jquery - Jquery - 多个下拉列表,禁用其他列表中的选定条目
- python - 如何使用 python 访问演示文稿的形状或文本运行中存在的 url?
- r - 在绘图前整理出小于 10 的计数
- ruby-on-rails - 我可以将现有的 Redis 用于自定义 Rails 缓存吗?
- c++ - 如何在类层次结构中传递智能指针