【问题标题】:python: loop through txt files and delete first few rows of stringspython:遍历txt文件并删除前几行字符串
【发布时间】:2018-03-16 05:17:42
【问题描述】:

我有文本文件,其中每个文件都有 90 列长度不同的时间序列数据。在这 90 列之前,我要删除 6 行垃圾字符串数据。从第 7 行开始,数据都是浮点类型。

我尝试了以下方法,但对我的文件没有任何改变:

folder = '/Users/LR/Desktop/S2'
files = os.listdir(folder)
for filename in files:
       lines = open(filename).readlines()
       open(filename, 'w').writelines(lines[6:])

我还尝试加载文件并跳过前 6 行,但 numpy.loadtxt 不起作用,除非我设置 dtype = 'str'。它成功地删除了前 6 行。但它作为字符串 ndarray 对象导入,我不知道如何将其转换为浮点数组。

data = np.loadtxt('STS2.txt', delimiter = '\t', skiprows=6, dtype='str')
data = data.astype(float) # this gives the error: ValueError: could not convert string to float: 

当我设置 dtype = float 时,我得到相同的 ValueError:

data_float = np.loadtxt('STS2.txt', delimiter='\t', dtype=float, skiprows=7) # this gives the error: ValueError: could not convert string to float: 

有人知道解决这个问题的方法吗?

【问题讨论】:

  • 你可能想使用os.path.join(folder, filename)
  • 我应该在哪里将它添加到我的代码中?抱歉,我是 python 和一般编码的新手
  • open(os.path.join(folder, filename))open(os.path.join(folder, filename), 'w')
  • 这有助于删除前 6 行,谢谢!但是当我尝试读取文本文件时,我仍然得到相同的值错误:无法将字符串转换为浮点数,即使数据只是数字
  • 我认为您必须至少分享该文件的部分内容以供任何人帮助。

标签: python numpy text valueerror


【解决方案1】:

您可以使用pandas 来帮助您。使用下面的代码:

import pandas as pd
import numpy as np

df = pd.read_csv('STS1.txt', delimiter='\t', skiprows=[0,1,2], index_col=0)
df = df.T.set_index(np.nan, append=True).T

我能够加载下表:

请注意,您的列现在是分层的。您可以检查您的类型:

df.dtypes

输出:

1      float64
2      float64
3      float64
4      float64
...

您还可以轻松地转换数据,例如给int

df = df.fillna(0).astype(int)

【讨论】:

    【解决方案2】:

    每行的最后一个字段是一个空字符串,因此numpy 无法将其解析为float。反正你只对前 90 列感兴趣,所以添加usecols=range(90)

    np.loadtxt('STS2.txt', skiprows=6, usecols=range(90))
    

    (当然,如果您已经删除了前六行,您现在可以删除skiprows=6。)

    编辑

    由于第一列似乎只是一个索引,您可以使用usecols=range(1, 90) 忽略它。

    【讨论】:

    • 完美。谢谢。然后我将如何用清理过的文件覆盖旧的 txt 文件?
    • 我不确定我明白你的意思。什么清理了文件?
    • @thymeandspace 我猜你想要numpy.savetxt
    • 如何保存不包含顶部 6 个垃圾行或额外列的新 numpy 数组,以便它们覆盖旧文件?
    • 我编辑了我的帖子以显示我的问题所在。再次感谢您的帮助。
    猜你喜欢
    • 2021-02-01
    • 2015-02-18
    • 2018-08-22
    • 1970-01-01
    • 2021-03-17
    • 2015-04-10
    • 1970-01-01
    • 2018-10-18
    • 2015-05-29
    相关资源
    最近更新 更多