Python 如何在pandas.groupby之后访问列

Python 如何在pandas.groupby之后访问列,python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,我有一个数据帧,我在上面使用了.groupby()和.agg()函数 movieProperties=combined_df.groupby(['movieId','title','genres']).agg({'rating':['count','mean']}) 这是创建新数据帧的代码。然而,我似乎不能再以同样的方式访问列了。如果我尝试movieProperties['genres']我总是会得到一个键错误。如何在此新数据框中再次访问列?在按分组后,按分组的列现在称为索引: moviePro

我有一个数据帧,我在上面使用了.groupby()和.agg()函数

movieProperties=combined_df.groupby(['movieId','title','genres']).agg({'rating':['count','mean']})


这是创建新数据帧的代码。然而,我似乎不能再以同样的方式访问列了。如果我尝试
movieProperties['genres']
我总是会得到一个键错误。如何在此新数据框中再次访问列?

在按分组后,按分组的列现在称为
索引

movieProperties = pd.DataFrame({"movie": ["x", "x", "y"], "title":["tx", "tx", "ty"], "rating": [3, 4, 3]}).groupby(["movie", "title"]).agg({"rating":["count", "mean"]})
movieProperties.index.values
Out[13]: array([('x', 'tx'), ('y', 'ty')], dtype=object)
如果对此不满意,请将其重置为常规列:

movieProperties.reset_index()
Out[16]: 
  movie title rating     
               count mean
0     x    tx      2  3.5
1     y    ty      1  3.0
然后

movieProperties.reset_index()["movie"]
Out[17]: 
0    x
1    y

你不能那样访问该组。例如,你必须做
movieProperties['crime']
movieProperties['traic']
。但是,按照您分组的方式,每部电影将是一个单独的组,因为没有两部电影具有相同的
ID
s是“标题”
groupby([…],因为_index=False)
将使分组列成为普通列,否则它们是索引。