如何使用numpy从追加的多维数组中删除“None”

2024-10-04 09:30:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要获取一个csv文件并将此数据导入python中的多维数组中,但是我不确定在将数据附加到空数组之后如何从数组中剥离“None”值。在

我首先创建了这样的结构:

storecoeffs = numpy.empty((5,11), dtype='object')

这将返回一个由“None”填充的5行x 11列数组。在

接下来,我打开csv文件并将其转换为数组:

^{pr2}$

然后,我附加了两个数组:

newmatrix = numpy.append(storecoeffs, coeffsarray, axis=1)

结果是一个数组,由'None'值填充,后跟我想要的数据(显示的前两行可以让您了解我的数据的性质):

array([[None, None, None, None, None, None, None, None, None, None, None,
    workers, constant, hhsize, inc1, inc2, inc3, inc4, age1, age2,
    age3, age4],[None, None, None, None, None, None, None, None, None, None, None,
    w0, 7.334, -1.406, 2.823, 2.025, 0.5145, 0, -4.936, -5.054, -2.8, 0],,...]], dtype=object)

如何从每一行中删除那些“None”对象,这样剩下的就是包含数据的5x11多维数组?在


Tags: 文件csv数据numpynoneobject数组结构
3条回答

@Gnibbler的答案在技术上是正确的,但是没有理由首先创建初始的storecoeffs数组。只需加载您的值,然后从中创建一个数组。但是,正如@Mermoz指出的,您的用例看起来足够简单numpy.loadtxt文件(). 在

除此之外,为什么要使用对象数组??这可能不是你想要的。。。现在,您将数值存储为字符串,而不是浮点!在

基本上有两种方法来处理numpy中的数据。或者使用结构化数组(如果您希望使用命名数组,则使用结构化数组)。如果你想要一个“普通”的多维数组,只需使用一个float、int等数组。对象数组有特定的用途,但它可能不是你要做的。在

例如: 要以普通2D numpy数组的形式加载数据(假设所有数据都可以轻松表示为float):

import numpy as np
# Note that this ignores your column names, and attempts to 
# convert all values to a float...
data = np.loadtxt('input_filename.txt', delimiter=',', skiprows=1)

# Access the first column 
workers = data[:,0]

要将数据作为结构化数组加载,可以执行以下操作:

^{pr2}$

如果数据中有非数字值,并希望将其作为字符串处理,则需要使用结构化数组,指定要作为字符串的字段,并为字段中的字符串设置最大长度。在

从您的示例数据来看,它看起来像第一列,“workers”是一个非数字值,您可能希望将其存储为字符串,而所有其他列看起来都像float。如果是这样的话,你可以这样做:

import numpy as np
infile = file('input_filename.txt')
names = infile.next().strip().split()

# Create the dtype... The 'S10' indicates a string field with a length of 10
dtype = {'names':names, 'formats':['S10'] + (len(names) - 1)*[np.float]}
data = np.loadtxt(infile, dtype=dtype, delimiter=',')

# The "workers" field is now a string array
print data['workers']

# Compare this to the other fields
print data['constant']

如果您确实需要csv模块的灵活性(例如带有逗号的文本字段),您可以使用它来读取数据,然后将其转换为具有适当数据类型的结构化数组。在

希望能让事情更清楚一点。。。在

从空数组开始?在

storecoeffs = numpy.empty((5,0), dtype='object')

为什么要分配一个完整的Nones数组并附加到这个数组中?coeffsarray不是您想要的数组吗?在

编辑

哦。使用^{}。在

import numpy
coeffsarray = numpy.reshape( coeffsarray, ( 5, 11 ) )

相关问题 更多 >