Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用genfromtxt分割数据_Python_Numpy_Genfromtxt - Fatal编程技术网

Python 使用genfromtxt分割数据

Python 使用genfromtxt分割数据,python,numpy,genfromtxt,Python,Numpy,Genfromtxt,对于Python,我使用genfromtxt(来自numpy)将文本文件读入数组: y = np.genfromtxt("1400list.txt", dtype=[('mystring','S20'),('myfloat','float')]) 它工作正常,只是它似乎无法将我的2列读入2D数组。我得到: [('string001',123.0),('string002',456.0),('string002',789.0)] 但我想我会: [[string001',123.0],'strin

对于Python,我使用
genfromtxt
(来自numpy)将文本文件读入数组:

y = np.genfromtxt("1400list.txt", dtype=[('mystring','S20'),('myfloat','float')])
它工作正常,只是它似乎无法将我的2列读入2D数组。我得到:

[('string001',123.0),('string002',456.0),('string002',789.0)]

但我想我会:

[[string001',123.0],'string002',456.0],'string002',789.0]


基本上,我希望每一条信息都作为一个单独的元素,然后我可以对其进行操作。

返回的内容称为结构化数组。它给出一个元组的1d数组,每个元组都有您指定的
dtype

一旦你学会了如何使用它们,它们实际上是非常有用的。不能使用带有浮点数和字符串的二维数组,但使用结构化数组,可以

例如:

import numpy as np
from StringIO import StringIO
s = """string001 123
       string002 456
       string002 789"""
f = StringIO(s)
y = np.genfromtxt(f, dtype=[('mystring', 'S20'), ('myfloat', float)])
这就是你目前所拥有的。现在,您可以按以下方式访问
y
。可以使用字段名将列获取为1d数组:

>>> y['mystring']
array(['string001', 'string002', 'string002'], 
  dtype='|S20')

>>> y['myfloat']
array([ 123.,  456.,  789.])
请注意,
y['myfloat']
给出了
float
s,因为
dtype
参数,即使在文件中它们是
int
s

或者,您可以使用整数获取一行,作为具有给定
dtype
tuple

>>> y[1]
('string002', 456.0)
如果您正在对这样的数据结构进行大量操作,您可能需要研究