我是python的新手,我目前正在尝试解决一个问题,该问题使我可以获取每一列的平均值,但列数未知。
我知道如果知道多少列并分别进行每个计算,该怎么做。我应该通过创建一个空列表并将各列循环回去来做到这一点。
import numpy as np
#average of all data not including NAN
def average (dataset):
return np.mean (dataset [np.isfinite (dataset)])
#this is how I did it by each column separate
dataset = np.genfromtxt("some file")
print (average(dataset [:,0]))
print (average(dataset [:,1]))
#what I'm trying to do with a loop
def avg (dataset):
for column in dataset:
lst = []
column = #i'm not sure how to define how many columns I have
Avg = average (column)
return Avg
答案 0 :(得分:0)
您可以使用numpy.mean()函数:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html
具有:
my_matrix.shape[1]
轴表示您是沿列还是行取平均值(轴= 0表示您要取每一列的平均值,即您要执行的操作)。输出将是一个向量,其长度与沿其取平均值的列(或行)的长度相同,并且每个元素是对应列(或行)的平均值。您不需要事先知道矩阵的形状。
您可以使用for循环来执行此操作,但这不是一个好主意-在numpy中循环处理矩阵很慢,而使用np.mean()之类的矢量化操作非常快。因此,通常在使用numpy时,人们会尝试使用这些类型的内置操作,而不是至少在可能的情况下循环遍历所有内容。
此外-如果您想要矩阵中的列数-是
my_matrix.shape[0]
返回列数;
getPizzas$ = this.actions$.pipe(
ofType<GetAllPizzas>(PizzaTypes.GetPizzas,
withLatestFrom(
this.store$.pipe(select(fromRootStore.getPizzaId))
),
take(1),
exhaustMap(([customAction, pizzaId]): any => { // << assuming this is correct
if (!pizzaId) {
map(() => new BigProductError({ . /// <<< is this how we approach this? just map? or should we return something?
appmessage : "Boom"
}));
} . /// <<< will control go beyond this point or is this more of an if-else condition?
return this.pizzaService.getPizzas(customAction.orderDetails, pizzaId)
.pipe(
map((pizzas) => new LoadPizzasSuccess(pizzas)),
catchError(error => of(new LoadPizzasFailure(error)))
);
})
);```
是行数。