在数据框中的每 3 列(列:1-3、4-6、7-9)上应用一个函数
Applying a function on every 3 columns (cols: 1-3, 4-6, 7-9) in dataframe
我有以下具有多索引的 DataFrame:
enter image description here
在每一行上应用 mean/sum/avg 函数的最佳方法是什么,对于每 3 列:a b c,然后:a1 b1 c1 然后是 a2 b2 c2,所以结果将是:在示例 I 中做了 总和
enter image description here
您可以通过 numpy array
使用 groupby
和聚合函数,例如 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
我有以下具有多索引的 DataFrame:
enter image description here
在每一行上应用 mean/sum/avg 函数的最佳方法是什么,对于每 3 列:a b c,然后:a1 b1 c1 然后是 a2 b2 c2,所以结果将是:在示例 I 中做了 总和 enter image description here
您可以通过 numpy array
使用 groupby
和聚合函数,例如 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