比循环整个文件更好的正则表达式实现?

使用ge( >=) 进行比较DataFrame。然后使用所有Trues byall和 last use获取布尔掩码loc,因为过滤列:


df = df.loc[:, df.ge(0).all()]

print (df)

   Age  Fare

0   21    10

1   35     9

2   28    12

详情:


print (df.ge(0))

    Age  Fare    Dev

0  True  True  False

1  True  True  False

2  True  True   True


print (df.ge(0).all())

Age      True

Fare     True

Dev     False

dtype: bool


月关宝盒
浏览 146回答 3
3回答

宝慕林4294392

你的shell实现可以更短,grep可以-c选择让你计数,不需要匿名管道和wc:grep -c " 1 " examplefile您的 shell 代码只是为您提供1找到模式的行数,但您的 Python 代码还保留了与模式匹配的行的索引列表。只获取行数,可以使用sum和genexp/list comprehension,也不需要Regex;简单的字符串__contains__检查会做,因为字符串是可迭代的:with open('examplefile') as f:    count = sum(1 for line in f if ' 1 ' in line)    print(count)  如果你也想保留索引,你可以坚持你的想法,只用re测试替换str测试:count = 0indexes = []with open('examplefile') as f:    for idx, line in enumerate(f):        if ' 1 ' in line:            count += 1            indexes.append(idx)此外,做一个空的except几乎总是一个坏主意(至少你应该使用except Exception遗漏SystemExit,KeyboardInterrupt就像异常一样),只捕获你知道可能会引发的异常。此外,在解析结构化数据时,您应该使用特定工具,例如此处csv.reader以空格作为分隔符(line.split(' ')在这种情况下也应该这样做)并且检查索引 4 将是最安全的。通过' 1 ' in line测试,如果任何其他列包含1.考虑到上述情况,这是awk用于匹配第 5 个字段的 shell 方式:awk '$5 == "1" {count+=1}; END{print count}' examplefile

桃花长相依

您有 CSV 数据,您可以使用该csv模块:import csvwith open('your file', 'r', newline='', encoding='utf8') as fp:    rows = csv.reader(fp, delimiter=' ')    # generator comprehension    errors = (row for row in rows if row[4] == '1')for error in errors:    print(error)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python