【问题标题】:Calculate mean of selected columns with multilevel header计算具有多级标题的选定列的平均值
【发布时间】:2021-02-11 10:02:37
【问题描述】:

我有一个带有多级标题的数据框,如下所示:

name   1          2         3        4
       x     y    x    y    x    y   x   y
A      1     4    3    7    2    1   5   2
B      2     2    6    1    4    5   1   7

如何计算 1x、2x 和 3x 而不是 4x 的平均值? 我试过了:

df['mean']= df[('1','x'),('2','x'),('3','x')].mean()

这不起作用,它是键错误。我想得到:

name   1          2         3        4     mean
       x     y    x    y    x    y   x   y  
A      1     4    3    7    2    1   5   2   2
B      2     2    6    1    4    5   1   7   4

有没有办法在将第一列标题保持为整数的同时计算平均值?

【问题讨论】:

    标签: python dataframe multi-level


    【解决方案1】:

    只有一个解决方案:

    import pandas as pd
    
    iterables = [[1, 2, 3, 4], ["x", "y"]]
    array = [
        [1, 4, 3, 7, 2, 1, 5, 2],
        [2, 2, 6, 1, 4, 5, 1, 7]
    ]
    index = pd.MultiIndex.from_product(iterables)
    df = pd.DataFrame(array,  index=["A", "B"], columns=index)
    
    df["mean"] = df.xs("x", level=1, axis=1).loc[:,1:3].mean(axis=1)
    
    print(df)
    
       1     2     3     4    mean
       x  y  x  y  x  y  x  y     
    A  1  4  3  7  2  1  5  2  2.0
    B  2  2  6  1  4  5  1  7  4.0
    

    步骤:

    1. 选择所有带有df.xs("x", level=1, axis=1) 的“x”列
    2. 使用.loc[:,1:3] 仅选择第 1 到 3 列
    3. .mean(axis=1) 计算平均值

    【讨论】:

    • 非常感谢!它说:TypeError: cannot do slice indexing on with these indexers [1] of .确实 1,2,3 是整数
    • 对不起,但您的索引 1,2,3 不是整数!将.loc[:,1:3] 更改为.loc[:,"1":"3"]
    • 经过这个适配后,我得到:TypeError: unorderable types: int() > str()。列标题应该是整数,我从有整数的excel中导入它们。如何检查和更改列标题的数据类型(不是列中的数据类型,这些是我真实数据集中的浮点数)
    • 请像我在回答帖子中所做的那样添加一个运行的最小示例。我需要有关如何加载数据的更多信息。您可以设置列名,如 herehere
    • 我尝试添加一个正在运行的示例,但我发现问题在于导入 excel 文件(我无法在此分享)。有整数和字符串作为标题。当我删除所有字符串时,前面的代码确实有效。我将研究如何分别导入带有字符串头和整数头的数据,然后再融合数据帧。这应该可以解决问题!
    猜你喜欢
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 2022-01-08
    • 2015-09-05
    相关资源
    最近更新 更多