[英]How to calculate the mean of n consecutive columns?
I have a dataframe like this: 我有一个这样的数据框:
import pandas as pd
df = pd.DataFrame({'A_1': [1, 2], 'A_2': [3, 4], 'A_3': [5, 6], 'A_4': [7, 8],
'B_1': [0, 2], 'B_2': [4, 4], 'B_3': [9, 6], 'B_4': [5, 8]})
A_1 A_2 A_3 A_4 B_1 B_2 B_3 B_4
0 1 3 5 7 0 4 9 5
1 2 4 6 8 2 4 6 8
which I would like to convert into a dataframe that looks like this: 我想将其转换为如下所示的数据框:
A_G1 A_G2 B_G1 B_G2
0 2 6 2 7
1 3 7 3 7
Thereby, A_G1
is the mean
of the columns A_1
and A_2
, A_G2
is the mean
of the columns A_3
and A_4
; 由此, A_G1
是mean
列A_1
和A_2
, A_G2
是mean
列A_3
和A_4
; the same applies to B_G1
and B_G2
. B_G1
和B_G2
。 So what I would like to do is to calculate the mean of two consecutive columns and add the result as a new column into a dataframe. 所以我想做的是计算两个连续列的平均值,并将结果作为新列添加到数据框中。
A straightforward implementation could look like this: 一个简单的实现可能看起来像这样:
res_df = pd.DataFrame()
for i in range(0, len(df.columns), 2):
temp_df = df[[i, i + 1]].mean(axis=1)
res_df = pd.concat([res_df, temp_df], axis=1)
which gives me the desired output (except for the column names): 这给了我想要的输出(除了列名):
0 0 0 0
0 2 6 2 7
1 3 7 3 7
Is there any better way of doing this ie a vectorized way? 有没有更好的方法可以做到这一点,即矢量化方法?
This might work for you: 这可能对您有用:
In [15]: df.rolling(window=2,axis=1).mean().iloc[:,1::2]
Out[15]:
A_2 A_4 B_2 B_4
0 2.0 6.0 2.0 7.0
1 3.0 7.0 3.0 7.0
But I haven't tested it against your "straightforward" implementation. 但我尚未针对您的“直接”实现对它进行测试。
Here's a NumPy based vectorized solution using reshaping
- 这是使用reshaping
基于NumPy的矢量化解决方案-
pd.DataFrame(df.values.reshape(-1,df.shape[1]//n,n).mean(2))
Sample runs - 样品运行-
In [65]: df
Out[65]:
A_1 A_2 A_3 A_4 B_1 B_2 B_3 B_4
0 1 3 5 7 0 4 9 5
1 2 4 6 8 2 4 6 8
In [66]: n = 2
In [67]: pd.DataFrame(df.values.reshape(-1,df.shape[1]//n,n).mean(2))
Out[67]:
0 1 2 3
0 2.0 6.0 2.0 7.0
1 3.0 7.0 3.0 7.0
In [68]: n = 4
In [69]: pd.DataFrame(df.values.reshape(-1,df.shape[1]//n,n).mean(2))
Out[69]:
0 1
0 4.0 4.5
1 5.0 5.0
Runtime test - 运行时测试-
In [71]: df = pd.DataFrame(np.random.randint(0,9,(200,800)))
In [72]: %timeit df.rolling(window=2,axis=1).mean().iloc[:,1::2]
100 loops, best of 3: 11 ms per loop # @juanpa.arrivillaga's soln
In [73]: n = 2
In [74]: %timeit pd.DataFrame(df.values.reshape(-1,df.shape[1]//n,n).mean(2))
100 loops, best of 3: 2.6 ms per loop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.