numpy.genfromtxt没有解包 [英] numpy.genfromtxt is not unpacking

查看:74
本文介绍了numpy.genfromtxt没有解包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对软件包 numpy遇到了奇怪的问题.genfromtxt .我用它来读取具有多个列的数据文件(可在此处),但是即使在以下情况下也无法将其解压缩 unpack 设置为 True .

I'm having a strange issue with the package numpy.genfromtxt. I use it to read a data file with a number of columns (available here) but these are not being unpacked even when unpack is set to True.

这是 MWE :

import numpy as np
f_data = np.genfromtxt('file.dat', dtype=None, unpack=True)

print f_data[3]
(237, 304.172, 2017.48, 15.982, 0.005, 0.889, 0.006, -2.567, 0.004, 1.205, 0.006)

(我使用 dtype = None ,因为文件中可能散布着字符串)

(I use dtype=None because the file can have strings scattered around)

如您所见,它返回一行而不是未打包的列.

As you can see it returns a line instead of an unpacked column.

如果我使用 np.loadtxt ,它将按预期工作:

If I use np.loadtxt it works as expected:

f_data = np.loadtxt('file.dat', unpack=True)

print f_data[3]
[ 16.335  16.311  15.674  15.982  16.439  15.903  15.313  18.35   15.643  14.081  16.578  11.477]

我在做什么错了?

推荐答案

这是您想要的吗?

In [448]: i=3
     ...: d=np.genfromtxt(fname, None) #d is a recorded array (or structured array)
     ...: d['f%d'%i] #Addressing Array Columns by Name
Out[448]: array([ 16.335,  16.311,  15.674,  15.982,  16.439,  15.903])

请参阅:

http://wiki.scipy.org/Cookbook/Recarray

http://docs.scipy.org/doc/numpy/user/basics.rec.html#module-numpy.doc.structured_arrays

我在以下数据上测试了 d = np.genfromtxt('a.x',dtype = None,unpack = True):

I tested d=np.genfromtxt('a.x', dtype=None, unpack=True) on the following data:

144     a578.06 873.72  16.335  0.003 
#-------^--------
180     593.41  665.748 16.311  0.003 
147     868.769 908.472 15.674  0.003
237     asdf.172 2017.48 15.982  0.005
#-------^--------

具有 dtype = None ,解压缩确实失败:

with dtype=None, unpack indeed fails:

In [538]: d=np.genfromtxt('a.x', dtype=None, unpack=True)
     ...: print d[3]
     ...: print d[1]
(237, 'asdf.172', 2017.48, 15.982, 0.005)
(180, '593.41', 665.748, 16.311, 0.003)

使用默认dtype dtype = str 时,解压缩工作:

while with default dtype or dtype=str, unpack works:

In [539]: d=np.genfromtxt('a.x',  unpack=True)
     ...: print d[3]
     ...: print d[1]
[ 16.335  16.311  15.674  15.982  16.439  15.903]
[      nan   593.41    868.769       nan  1039.71    385.864]

In [540]: d=np.genfromtxt('a.x', dtype=str, unpack=True)
     ...: print d[3]
     ...: print d[1]
['16.335' '16.311' '15.674' '15.982' '16.439' '15.903']
['a578.06' '593.41' '868.769' 'asdf.172' '1039.71' '385.864']

这篇关于numpy.genfromtxt没有解包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆