python - 熊猫多索引数据框中一列的平均值
问题描述
我有一个与此类似的多索引数据框。
arrays = [np.array(['bar', 'bar', 'bar','baz', 'baz', 'baz', 'foo', 'foo', 'foo']),
np.array(['one', 'two', 'three', 'one', 'two', 'three','one', 'two','three'])]
s = pd.Series(np.random.randn(9), index=arrays)
df = pd.DataFrame(np.random.randn(9, 2), index=arrays,columns=['C1','C2'])
df
我想在数据框的末尾添加一个新列,该列将按 level=0 ('bar','baz','foo') 分组,并对这些组的 C2 列中的数字进行平均。我想在一个场景中(或者在每个级别 = 0 的顶行)位置显示级别 = 0 的 3 个单独行中的每一行的相同平均数
解决方案
尝试transform
mean
df.groupby(level=0).transform('mean')
C1 C2
bar one 0.473968 -0.454709
two 0.473968 -0.454709
three 0.473968 -0.454709
baz one 0.731266 -0.437691
two 0.731266 -0.437691
three 0.731266 -0.437691
foo one 0.061087 -0.326533
two 0.061087 -0.326533
three 0.061087 -0.326533
更新
df['C3']=df.groupby(level=0).C2.transform('mean')
推荐阅读
- google-oauth - Nuxtjs 谷歌身份验证
- linux - 是否可以让 nvidia-smi 命令从任何位置(如 Linux)在 Windows 上运行?
- azure-hdinsight - HDInsight 群集如何作为 HDFS 映射到 Azure 存储?
- java - 我收到此错误原因:java.lang.ClassNotFoundException: javafx.scene.Node 在 Ubuntu Tomcat 服务器中部署战争
- node.js - 创建新项目时 JSON 输入错误意外结束
- reactjs - 我们应该为 Redux 状态使用 PropTypes 吗?
- python-3.x - 升级到 Ubuntu 20.04 后,python 3.7 venv 损坏
- javascript - 如何以在 javascript 中创建的表单中获取表单 foreach 循环选项值?
- python - Django 无法使用 ForeinKey 保存记录
- php - PHP 登录系统适用于本地,但不适用于 Hostgator PHP 7.2