Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫:无法从以前合并的多级数据帧中寻址列_Python_Pandas_Dataframe_Multi Level - Fatal编程技术网

Python 熊猫:无法从以前合并的多级数据帧中寻址列

Python 熊猫:无法从以前合并的多级数据帧中寻址列,python,pandas,dataframe,multi-level,Python,Pandas,Dataframe,Multi Level,使用group by进行数据帧聚合后,我尝试将标题“展平”为一个,以正确地将数据导出为CSV: df.columns = [' '.join(col).strip() for col in df..columns.values] df.columns 输出如下所示: Index(['count', 'average', 'mean', 'sum'], dtype='object') 如果我直接调用数据帧,我会得到不同的信息: df 输出:

使用group by进行数据帧聚合后,我尝试将标题“展平”为一个,以正确地将数据导出为CSV:

df.columns = [' '.join(col).strip() for col in df..columns.values]
df.columns
输出如下所示:

Index(['count', 'average', 'mean',
       'sum'],
      dtype='object')
如果我直接调用数据帧,我会得到不同的信息:

df
输出:

                 count average mean sum
col1 col2 col3 
...
AssertionError: axis must be a MultiIndex
看起来熊猫合并了列名,但我仍然有两个级别的列描述。如果我尝试处理第二级列,则会引发错误:

df.drop('col1', axis = 'columns', level = 0)
输出:

                 count average mean sum
col1 col2 col3 
...
AssertionError: axis must be a MultiIndex

输出

KeyError: "['col1'] not found in axis"
看来我被夹在中间了。如果我将数据帧导出为CSV并再次导入,则一切正常:

df.to_csv('data.csv')


那么,我在这里误解了什么,做错了什么?

您可能想在
df.groupby
语句之后执行
df.reset\u index()
,以按要求“展平”标题。请看

它工作起来很有魅力,非常感谢!