【问题标题】:How to remove 'None' from an Appended Multidimensional Array using numpy如何使用 numpy 从附加的多维数组中删除“无”
【发布时间】:2011-03-26 12:24:51
【问题描述】:

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

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

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

这将返回一个由“无”填充的 5 行 x 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 多维数组?

【问题讨论】:

    标签: python multidimensional-array numpy extract slice


    【解决方案1】:

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

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

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

    例如: 只需将数据加载为普通的 2D numpy 数组(假设您的所有数据都可以轻松表示为浮点数):

    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..
    

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

    从您的示例数据来看,它看起来像第一列,“workers”是一个非数字值,您可能希望将其存储为字符串,其余的看起来像浮点数。在这种情况下,你会做这样的事情:

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

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

    【讨论】:

    • 乔,你完美地解决了我的困境。我的问题是这个数组包含浮点数和非数字的混合,但我需要使用非数字(单词)来引用数字(浮点数)。理想情况下,我想将单词存储在字典中以引用关联的数字数据,其中每个单词 = 列标题。这对我来说一直很沮丧,因为我对 python 很陌生。
    【解决方案2】:

    从一个空数组开始?

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

    【讨论】:

    • 嗯...我在创建 storecoeffs = numpy.empty((5,11), dtype = 'object') 时没有这样做吗?
    • @myClone - 不,您创建了一个 5x11 对象数组,其中填充了内存中的任何内容(实际上对于您在上面创建的对象数组,它只是用None 填充它)。您根本不需要初始化数组。只需将从文件中读取的内容转换为数组即可。
    • 好的,谢谢。我想我对 python 如何在结构方面处理第一个数组感到困惑,这就是我采取额外步骤的原因。只是作为一个典型的 n00b 使生活变得更加困难。 :)
    【解决方案3】:

    你为什么要分配整个Nones 数组并附加到它上面? coeffsarray不是你想要的数组吗?

    编辑

    哦。使用numpy.reshape

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

    【讨论】:

    • 是的,但它在开始时并未结构化为多维数组。我需要它的结构,以便有 11 列乘 5 行。
    【解决方案4】:

    为什么不简单地使用numpy.loadtxt()

    newmatrix = numpy.loadtxt("file.csv", dtype='object') 
    

    应该做的工作,如果我理解你的问题。

    【讨论】:

    • 您能否具体说明一下为什么这样更好?
    猜你喜欢
    • 2021-03-26
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    相关资源
    最近更新 更多