如何将异构数据(np.genfromtxt)作为2D数组加载?

时间:2016-04-07 19:36:50

标签: python numpy genfromtxt

我从numpy.genfromtxt produces array of what looks like tuples, not a 2D array—why?了解到numpy.genfromtxt如果数据不均匀则返回结构化 ndarray。 如何将异构数据加载为2D阵列?

例如,文本文件的内容为:(除标题之外的所有项目均为int

# c1    c2  c3  c4  c5
3   4   8   6   8
10  7   6   7   10
5   10  2   1   3
7   6   5   3   6
5   8   5   2   7
1   2   2   10  8
10  5   9   3   8
5   2   4   4   2

使用np.genfromtxt

加载数据
# load data from a text file
table = np.genfromtxt('table.dat', dtype=int, delimiter='\t', names=True, filling_values=0)
print(table.shape)
print(table)

# output
(8,)
[(3, 4, 8, 6, 8) (10, 7, 6, 7, 10) (5, 10, 2, 1, 3) (7, 6, 5, 3, 6)
 (5, 8, 5, 2, 7) (1, 2, 2, 10, 8) (10, 5, 9, 3, 8) (5, 2, 4, 4, 2)]

# expecting result
(8, 5)
[[ 7  2  4  9  2]
 [ 5  8  1  6  4]
 [ 6  3  1  4 10]
 [10 10  6  5  5]
 [10  4  7  7  1]
 [ 1  9  8  6  2]
 [ 3  2  3  4  4]
 [ 7  5  9 10  6]]

PS:我想保留header = table.dtype.names用于其他目的。

3 个答案:

答案 0 :(得分:2)

在这种情况下,使用pandas然后将pandas dataframe转换为numpy矩阵会更容易。

import pandas as pd
foo = pd.read_csv('table.dat', sep='\t')
type(foo)
<class 'pandas.core.frame.DataFrame'>
bar = foo.as_matrix()
array([[10,  7,  6,  7, 10],
       [ 5, 10,  2,  1,  3],
       [ 7,  6,  5,  3,  6],
       [ 5,  8,  5,  2,  7],
       [ 1,  2,  2, 10,  8],
       [10,  5,  9,  3,  8],
       [ 5,  2,  4,  4,  2]])
bar.shape
(7,5)

答案 1 :(得分:1)

我得到了这个:

import numpy as np

table = np.genfromtxt('table.dat',
                      dtype=None,
                      skip_header=1)

以下是其工作原理:

  • 您应该将连续的空格作为分隔符(默认值)而非标签(除非您发布的代码段丢失了格式)。
  • 您应该让NumPy推断dtype,而不是使用默认的float
  • 要在问题中获得所需的输出,您只需跳过标题列,而不是让函数创建结构化dtype

查看文档:{​​{3}}了解更多详情。

我同意如果您基本上在csv文件中阅读,Pandas DataFrame可能更合适。

答案 2 :(得分:1)

您的数据看起来是同质的 - 除了标题之外的所有int。但是通过说header=True,你强制它将它作为结构化数组加载。查看dtype

尝试skip_header=1(检查语法)。省略names(或使其成为假)。

换句话说,你想加载整数,忽略标题行。

制表符分隔符似乎正常工作。

我从评论中看到您发现了转换结构化数组的view方法。这为您提供了标题名称和2d视图。

相关问题