genfromtxt和numpy [英] genfromtxt and numpy
问题描述
我在"file.csv"之类的文件中有数据.我想用np.genfromtxt读取它们,并对某些列(X, Y, Z)
进行一些统计,例如平均值,方差等.但是我想对X > 1, Y > 3 Z > 2
等进行统计.这是一个简单的示例.
I have data in files such as "file.csv". I would like to read them with np.genfromtxt and do some statistics like average, variance etc. on some columns (X, Y, Z)
. However I want to make the statistics on for X > 1, Y > 3 Z > 2
etc. This is a simple example here.
这段代码几乎可以产生正确的结果,但是它包含所有X,Y和Z,我想这样做,但要符合上面指定的X,Y,Z条件.
This code produces almost correct results but it includes ALL Xs, Ys and Zs, I want to do the same but with the X,Y,Z conditions i specified above.
#file.csv
X,Y,Z
1,2,3
4,2,5
15,9,1
#
data = np.genfromtxt(file.csv, delimiter=',', dtype=float, unpack=True, skiprows = 0)
X=data[0];Y=data[1];Z=data[2]
Mean = np.average(X)
->努力取得平均值.但是,我希望只有在X> 1的情况下才能获得平均水平.例如,如何做到这一点?
--> Doing a great job getting the average. However, I want i to get average ONLY IF X > 1 (for example)... How do I make it do so?
推荐答案
您可以使用所谓的"fancy-indexing"(X[X>1]
)来选择所需的数组部分:
You could use so-called "fancy-indexing", X[X>1]
, to select the part of the array you want:
import numpy as np
X,Y,Z = np.genfromtxt('file.csv', delimiter=',', dtype=float, unpack=True, skiprows = 0)
print(X)
# [ nan 1. 4. 15.]
print(X[X>1])
# [ 4. 15.]
print(np.average(X[X>1]))
# 9.5
要将两个掩码(布尔数组)与按位逻辑和相结合,请使用&
运算符:
To combine two masks (boolean arrays) with bit-wise logical-and, use the &
operator:
print(np.average(X[(X>1)&(X<10)]))
# 4.0
这篇关于genfromtxt和numpy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!