python - numpy - Python - 有选择地导入 .txt 文件的部分内容

标签 python numpy analysis

在我的 data.txt 文件中,有 2 种类型的行。

  1. 普通数据:16个数字,以空格分隔,末尾附加“\n”。

  2. 数据不完整:在向data.txt写入数据的过程中,最后一行的写入总是被STOP命令中断。因此,它总是不完整的,例如它可以有 10 个数字,但没有 '\n'

两个问题:

a.如何将除最后一个不完整行之外的整个文件导入到 Python 中?

我注意到

# Load the .txt file in
myData = np.loadtxt('twenty_z_up.txt')

相当“严格”,因为当最后一个不完整行存在时,无法导入该文件。导入的 .txt 文件必须是一个很好的矩阵。

b. 有时,出于实验目的,我会在一行的第一个条目上添加时间戳。假设我的第一个时间戳位于第 2 行开头,第二个时间戳位于第 5 行开头。如何仅将第 2 行到第 5 行导入到 Python 中?

==================================更新:问题已解决=========== =====================

myData = np.genfromtxt('fast_walking_pocket.txt', skip_footer=1)

将帮助丢弃最后不完整的行

最佳答案

您可以尝试pandas提供了使用函数read_csv更轻松地加载数据。

示例数据:

a b c d e f g h i j k l m n o p
a b c d e f g h i j k l m n o p
a b c d e f g h i j k l m n o p
a b c d e f g h i j k l m n o p
a b c d e f g h i j k l m n o p
a b c d e f g h i j

对于第一季度,您可以通过以下方式加载数据:

In [27]: import pandas as pd

In [28]: df = pd.read_csv('test.txt', sep=' ', header=None, skipfooter=1)

DataFrame是一个有用的结构,可以帮助您 处理数据更容易。要获取 numpy 数组,只需获取 DataFramevalues 属性即可。

In [33]: df.values
Out[33]: 
array([['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
        'n', 'o', 'p'],
       ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
        'n', 'o', 'p'],
       ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
        'n', 'o', 'p'],
       ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
        'n', 'o', 'p'],
       ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
        'n', 'o', 'p']], dtype=object)

对于您的 Q2,您可以通过以下方式获得第二行和第五行

In [36]: df.ix[[1, 4]]
Out[36]:
  0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15
1  a  b  c  d  e  f  g  h  i  j  k  l  m  n  o  p
4  a  b  c  d  e  f  g  h  i  j  k  l  m  n  o  p

关于python - numpy - Python - 有选择地导入 .txt 文件的部分内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16804513/

相关文章:

c++ - 这个给定算法中的 "basic operation"究竟是什么

python - 使用python计算FWHM

python - 在列表中第一个传递条件的元素后面添加一个元素

Python MySQL 插入重复键

python - 函数内列表的各个元素

python - 查找由不规则数据点定义的体积 - python

vim - vim 的生产力分析器

python - 如果我想通过串口向arduino发送数据,我应该一次发送一个长字符串,还是单独发送每个变量?

python - 添加 numpy 数组时避免溢出

python - 如何使用 matplotlib 将 x 轴上的秒数转换为小时数?