python - 如何使用 numpy 从附加的多维数组中删除 'None'

标签 python multidimensional-array numpy extract slice

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

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

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

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

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

coeffsarray = list(csv.reader(open("file.csv")))

coeffsarray = numpy.array(coeffsarray, dtype='object')

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

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

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

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)

如何从每一行中删除那些“无”对象,以便我剩下的是包含我的数据的 5 x11 多维数组?

最佳答案

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

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

在 numpy 中,您基本上有两种处理数据的方法。如果您想轻松访问命名列,请使用结构化数组(或记录数组)。如果你想要一个“正常”的多维数组,只需使用一个 float 、整数等数组。对象数组有特定的用途,但它可能不是你正在做的。

例如: 只需将数据作为普通 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]

要将数据作为结构化数组加载,您可以这样做:

import numpy as np
infile = file('input_filename.txt')

# Read in the names of the columns from the first row...
names = infile.next().strip().split()

# Make a dtype from these names...
dtype = {'names':names, 'formats':len(names)*[np.float]}

# Read the data in...
data = np.loadtxt(infile, dtype=dtype, delimiter=',')

# Note that data is now effectively 1-dimensional. To access a column,
# index it by name
workers = data['workers']

# Note that this is now one-dimensional... You can't treat it like a 2D array
data[1:10, 3:5] # <-- Raises an error!

data[1:10][['inc1', 'inc2']] # <-- Effectively the same thing, but works..

如果您的数据中有非数字值并希望将它们作为字符串处理,则需要使用结构化数组,指定您希望将哪些字段作为字符串,并为 field 。

从您的示例数据来看,第一列“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 模块的灵 active (例如带逗号的文本字段),您可以使用它来读取数据,然后将其转换为具有适当 dtype 的结构化数组。

希望这能让事情变得更清楚......

关于python - 如何使用 numpy 从附加的多维数组中删除 'None',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3427036/

相关文章:

python - 如何使我的测试装置仅在 Django 中测试时加载?

Python,嵌套for循环

c++ - 将两个不同大小的2d数组相乘

php - 通过另一个键和值在多维数组中查找值

python - 如何修复构建可见性图的算法?

python - 是否可以访问 C++ 头文件/库并在 python 控制台中运行 C++ 脚本?

c - 使用函数 findMax(int **a,int m, int n) 在矩阵中查找最大元素

python - TypeError : src is not a numpy array, 既不是标量

python - 使用 numpy 在网格中显示图像的更惯用方式

python - 给定段的长度和段中的偏移量,如何从 Pandas 的开始创建偏移量?