【问题标题】:How to remove row, that contains letters or words如何删除包含字母或单词的行
【发布时间】:2017-01-13 12:59:46
【问题描述】:

我正在做一个项目,我们首先必须过滤数据,以便删除无效数据。这意味着如果我们加载的数据中的一行包含字母/单词,则必须将其删除。 我的以下代码是否足以做到这一点?

import numpy as np
def dataLoad(filename):
#The data is loaded and the variables are defined:
    rawData=np.loadtxt('test.txt')
    rawTemperature, rawGrowthrate, rawBacteria=np.loadtxt('test.txt',unpack=True)
    print("You have choosen to work with the file {:s}".format(filename))
    # Removeing unvalid data:
    # Empty vector to save the invalid data in:
    InvalidData=[]
    # Vector with ones:
    Erase=np.ones(len(rawData))

    # The loop looks trough every datapoint in the matrix:
    for i in range(len(rawData)):
        # The rows in the Data that contains invalid data is inserted in Invalid Data
        # And the ones in I'th place is switched to a zeroes.
        if rawTemperature[i]<10 or rawTemperature[i]>60 or rawTemperature[i]==(""):
            InvalidData.insert(i,'In line %d invalid Temperature' % (i+1))
            Erase[i]=0
        if rawGrowthrate[i]<0 or rawGrowthrate[i]==(""):
            InvalidData.insert(i,'In line %d invalid Growth rate' % (i+1))
            Erase[i]=0
        if rawBacteria[i]<0 or rawBacteria[i]>4 or rawBacteria[i]==(""):
            InvalidData.insert(i,'In line %d invalid Bacteria' % (i+1))            
            Erase[i]=0

【问题讨论】:

  • 你测试了吗?它通过了这些测试吗?
  • test.txt 包含什么?

标签: python python-3.5


【解决方案1】:

我不明白你是要删除整行还是只删除一个字母而不是数字或其他字符

要检查一行是否包含字母或单词,您可以使用 regex [a-zA-Z] Regex to match only letters

https://docs.python.org/2/library/re.html

如果你想简单地删除字符,你可以使用re.sub 并将字符替换为空格''

import re
s = "ExampleString123"
replaced = re.sub('[a-zA-Z]', '', s)
print replaced 

numpy 示例Numpy array Regex sub

如果你想删除 numpy 数组中的整行,你可以选择它 使用正则表达式[a-zA-Z] (Selecting elements in numpy array using regular expressions) 然后删除它 (@ 987654325@)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    相关资源
    最近更新 更多