取 numpy 数组中列的平均值

mcj*_*shi 5 python arrays numpy

我使用 numpy 从 csv 文件中获取数据。numpy 数组的尺寸为:100*20。我如何取列的平均值(例如第 3、5、8 列)并将其替换为包含这 3 列平均值的新列

如果

   col3 = 1,2,3,4
   col5 = 2,3,4,8
   col8 = 3,4,5,6
Run Code Online (Sandbox Code Playgroud)

然后我想删除这 3 列并插入一个新列,其中每个条目包含这 3 列中值的平均值

我想插入一个新列:2,3,4,6,删除前3列,最终数组的尺寸为100*28

有没有 numpy 函数可以做到这一点?

aza*_*lea 4

a = np.arange(100*30).reshape(100,30) # change this to your own data
cols = [2, 4, 7]                      # columns to calculate averages, i.e. 3,5,8
b = a[:, cols]                        # data of the cols
c = b.mean(axis=1)                    # average
a_no_b = np.delete(a, cols, axis=1)   # data without the cols
a_final = np.c_[a_no_b, c]            # final result
Run Code Online (Sandbox Code Playgroud)