如何访问pandas.groupby之后的列

2024-10-01 07:48:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: 数据函数代码dftitlecount方式mean
1条回答
网友
1楼 · 发布于 2024-10-01 07:48:37

groupby之后,按其分组的列现在称为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)

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

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

相关问题 更多 >