【问题标题】:Applying a function on every 3 columns (cols: 1-3, 4-6, 7-9) in dataframe在数据框中的每 3 列(列:1-3、4-6、7-9)上应用一个函数
【发布时间】:2016-12-07 11:26:44
【问题描述】:

我有以下带有多索引的 DataFrame:

enter image description here

在每行上应用 mean/sum/avg 函数的最佳方法是什么,每 3 列:a b c,然后:a1 b1 c1 和 a2 b2 c2,所以结果将是:在示例中我做了 总和 enter image description here

【问题讨论】:

  • 您能提供您的数据框的可复制版本吗?

标签: function pandas apply


【解决方案1】:

您可以使用groupby by numpy array 和聚合函数,如sum

df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (df)
   A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3

print (np.arange(len(df.columns)) // 3)
[0 0 0 1 1 1]

print (df.groupby(np.arange(len(df.columns)) // 3, axis=1).sum())
    0   1
0  12  13
1  15  10
2  18  14

【讨论】:

    猜你喜欢
    • 2022-10-08
    • 2021-05-30
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    相关资源
    最近更新 更多