Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.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
Indexing 如何访问数据帧的(多)索引?_Indexing_Group By_Pandas - Fatal编程技术网

Indexing 如何访问数据帧的(多)索引?

Indexing 如何访问数据帧的(多)索引?,indexing,group-by,pandas,Indexing,Group By,Pandas,我有一个数据框,并使用它的一些列按分组: grouped = df.groupby(['col1', 'col2']) 现在,我使用mean函数从上面创建的groupby对象中获取一个新的数据帧对象: df_new = grouped.mean() 现在我有两个数据帧(df和df2),我想使用col1和col2合并它们。我现在的问题是df2没有这些列。在groupby操作之后,col1和col2被“移位”到索引。因此,为了解决这个问题,我尝试创建以下列: df2['col1'] = df2[

我有一个数据框,并使用它的一些列按分组:

grouped = df.groupby(['col1', 'col2'])
现在,我使用
mean
函数从上面创建的groupby对象中获取一个新的数据帧对象:

df_new = grouped.mean()
现在我有两个数据帧(
df
df2
),我想使用
col1
col2
合并它们。我现在的问题是
df2
没有这些列。在
groupby
操作之后,
col1
col2
被“移位”到索引。因此,为了解决这个问题,我尝试创建以下列:

df2['col1'] = df2['index'][0]
df2['col2'] = df2['index'][1]

但它不起作用,因为“索引”未被识别为数据帧的列。

您可以使用以下参数的
左索引
(或
右索引
):

左索引
:布尔值,默认为False
使用左侧数据帧中的索引作为联接键。
如果是多索引,则为另一个数据帧(索引或 或列数)必须与级别数匹配

并使用上的右键来确定它应该与哪些列合并索引

所以它会是这样的:

pd.merge(df, df_new, left_on=['col1', 'col2'], right_index=True)

作为Andy Hayden的另一种方法,您可以使用
As_index=False
将列保留为列而不是索引:

df2 = df.groupby(['col1', 'col2'], as_index=False).mean()