如何在 pandas .groupby 之后访问列

Zaf*_*rmk 9 python pandas pandas-groupby

我有一个数据框,我使用了 .groupby() 和 .agg() 函数。

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

这是创建新数据框的代码。但是我似乎无法再以相同的方式访问列了。如果我尝试,movieProperties['genres']我总是会收到 KeyError。如何再次访问这个新数据框中的列?

iha*_*nny 10

在您进行分组之后,您分组所依据的列现在称为index

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)
Run Code Online (Sandbox Code Playgroud)

如果您对此不满意,请将它们重置回常规列:

movieProperties.reset_index()
Out[16]: 
  movie title rating     
               count mean
0     x    tx      2  3.5
1     y    ty      1  3.0
Run Code Online (Sandbox Code Playgroud)

进而

movieProperties.reset_index()["movie"]
Out[17]: 
0    x
1    y
Run Code Online (Sandbox Code Playgroud)