我想读取csv文件,并仅在满足特定条件时才将详细信息添加到txt文件。
请在下面找到csv:
ID,Domain,Reputation_Score,
1,somedomain.domain,50
2,anotherdomain.domain,20
我想只捕获与声誉得分超过30的域名。所以ID为"1“的域应该被复制到txt文件中(只需要域名,其他都不需要)。
请帮帮忙。
你好,米泰什·阿格拉瓦尔
发布于 2020-03-25 09:57:34
熊猫可能是过度杀伤力,但它将是一种快速过滤任何值的方法。
import pandas as pd
df = pd.read_csv('test.csv', index_col="ID")
df = df[df["Reputation_Score"] > 30]
df["Domain"].to_csv("out.txt", header=False, index=False)
输出为:
somedomain.domain
发布于 2020-03-25 09:59:37
您可以使用Python的CSV库来执行此操作,例如:
import csv
with open('input.csv', newline='') as f_input, open('output.txt', 'w') as f_output:
csv_input = csv.reader(f_input)
header = next(csv_input)
for row in csv_input:
if int(row[2]) > 30:
f_output.write(f"{row[1]}\n")
这将为您提供output.txt
为:
somedomain.domain
https://stackoverflow.com/questions/60846355
复制