首页 > 解决方案 > 在整个 Numpy 库中读取文件

问题描述

我正在尝试text file通过使用Numpy这些数据来读取数据,如下所示:

# Student data collected on 17 July 2014
# Researcher: Dr Wicks, University College Newbury

# The following data relate to N = 20 students. It
# has been totally made up and so therefore is 100%
# anonymous.

Subject  Sex    DOB     Height  Weight   BP     VO2max
(ID)     M/F dd/mm/yy     m       kg    mmHg   mL.kg-1.min-1
JW-1     M   19/12/95    1.82    92.4  119/76    39.3
JW-2     M   11/1/96     1.77    80.9  114/73    35.5
JW-3     F    2/10/95    1.68    69.7  124/79    29.1
JW-6     M    6/7/95     1.72    75.5  110/60    45.5
# JW-7   F   28/3/96     1.66    72.4  101/68      -
JW-9     F   11/12/95    1.78    82.1  115/75    32.3
JW-10    F   7/4/96      1.60      -    -/-      30.1
JW-11    M   22/8/95     1.72    77.2  97/63     48.8
JW-12    M   23/5/96     1.83    88.9  105/70    37.7
JW-14    F   12/1/96     1.56    56.3  108/72    26.0
JW-15    F   1/6/96      1.64    65.0  99/67     35.7
JW-16    M   10/9/95     1.63    73.0  131/84    29.9
JW-17    M   17/2/96     1.67    89.8  101/76    40.2
JW-18    M   31/7/96     1.66    75.1   -/-        -
JW-19    F   30/10/95    1.59    67.3  103/69    33.5
JW-22    F   9/3/96      1.70     -    119/80    30.9
JW-23    M   15/5/95     1.97    89.2  124/82      -
JW-24    F   1/12/95     1.66    63.8  100/78      -
JW-25    F   25/10/95    1.63    64.4   -/-      28.0
JW-26    M   17/4/96     1.69      -   121/82    39.

我阅读了sexandHeight columns我在下面的代码中没有遇到任何问题:

import numpy as np

fname = 'D:\\NumpyTutorial.txt'
datatype1 = np.dtype([('sex','|S1'),('height','f8')])
a = np.loadtxt(fname, dtype=datatype1, skiprows=9, usecols=(1,3))
print(a)

但是当我尝试Weight column使用下面的代码阅读时:

import numpy as np

fname = 'D:\\NumpyTutorial.txt'
datatype1 = np.dtype([('sex','|S1'),('height','f8'),('Weight','f8')])
a = np.loadtxt(fname, dtype=datatype1, skiprows=9, usecols=(1,3,4))
print(a)

我收到了这个错误:

ValueError: could not convert string to float: '-'.

1- 我该如何处理。如何sign(-)阅读本专栏?

2- For sex columnI used'|S1'和 for heightused 'f8',什么是syntax直到Subject, BOD and BP columns阅读它们?

3 - 我怎样才能显示这个文件中的所有内容?

标签: pythonnumpyfile-read

解决方案


https://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html

您可以使用np.genfromtxt它的missing_valuesfilling_values参数。我在 中制作了以下形式的一些虚拟数据data.txt,其中缺少一个条目。

ID      Value
0       10
1       58
2       -
3       27

np.genfromtxt然后我使用如下代码块所示加载了这些数据。请注意,这只会使用所需格式检索数据——您需要自己对数据进行后处理,以确保您没有不当使用无效或丢失的条目。

在此示例中,我将缺失条目中的填充值设置为,-1因为我希望我的所有值都是正数。filling_values为了数据处理,另一个简单的选择是np.nan.

import numpy as np

fname = './data.txt'
data = np.genfromtxt(fname, skip_header=1, \
        missing_values='-', filling_values=-1.) 

print(data)


###  Output:
###    [[ 0. 10.]
###     [ 1. 58.]
###     [ 2. -1.]
###     [ 3. 27.]]

您应该能够对您的体重和最大摄氧量柱使用相同的技术。由于它的格式,我不确定如何处理 BP 列——这个选择取决于你,但技术是一样的。


推荐阅读