简体   繁体   English

将列表转换为numpy数组

[英]Converting a list into a numpy array

This code is set up to read two columns of data, and then print the first column into the first numpy array and then the second column into the second numpy array. 此代码设置为读取两列数据,然后将第一列打印到第一个numpy数组中,然后将第二列打印到第二个numpy数组中。

def read2coldata(filename):

    import numpy
    b = []
    f = open(filename,"r")
    lines = f.readlines()
    f.close()
    for line in lines:
        a = line.split()
        for i in a:
            b.append(i)
    return (numpy.array(b[::2]),numpy.array(b[1::2]))

However this gives: 但是这给出了:

(array(['1.5', '8', '16', '17'], dtype='|S3'), array(['4', '5', '6', '6.2'], dtype='|S3'))

How do I get rid of the dtype="|S3" parts to just leave: 如何摆脱dtype="|S3"部分才能离开:

(array(["1.5","8","16","17"], array(["4","5","6","6.2"])

the dtype="S3" you don't want to "go away". dtype="S3"你不想“走开”。 When you print a numpy array it gives you the type of the data in it. 当您打印一个numpy数组时,它会为您提供其中的数据类型。 it isn't part of the data, it is information about how the data is stored and understood by the program. 它不是数据的一部分,它是关于程序如何存储和理解数据的信息。

In your particular example, you read number, so you probably want to use them afterwards in computation or whatever, in which case you'll want the data to be understood as number (floats in you case). 在您的特定示例中,您读取数字,因此您可能希望在计算之后使用它们或其他任何东西,在这种情况下,您将希望数据被理解为数字(在您的情况下浮动)。

For the moment they are stored as strings, and that's why you see dtype="S3" which essentially means string type of size 3 or less. 目前它们被存储为字符串,这就是为什么你看到dtype="S3"这实际上意味着大小为3或更小的字符串类型。 (IIRC) (这个)

I suggest to you an alternative to your function : numpy.genfromtxt is a function to load data from a txt file into a numpy array. 我建议你替换你的函数: numpy.genfromtxt是一个将数据从txt文件加载到numpy数组的函数。

The documentation is quite good and you'll find it very useful if you spend the 20 minutes to understand the parameters. 文档非常好,如果你花20分钟来理解参数,你会发现它非常有用。

array1 = numpy.genfromtxt('path_to_my_file.txt', usecols=0)
array2 = numpy.genfromtxt('path_to_my_file.txt', usecols=1)

This should get you started. 这应该让你开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM