[英]How to filter out specific data from a CSV via Python?
People OS Games Owned
Anthony Windows 120
Alissa Windows 70
Jordan Windows 20
Khan Mac 47
Benny Mac 23
Anastasia Linux 16
McCurdy Linux 10
I was wondering, How would I go about filtering out people who own over 20 games, and they don't have a Mac OS System.我想知道,我将如何过滤掉拥有 20 多个游戏但他们没有 Mac OS 系统的人。 I need it to be done via a python script, and when run, it outputs its data in a seperate file, like a text file or something.
我需要通过 python 脚本来完成,当运行时,它将数据输出到一个单独的文件中,比如文本文件或其他东西。 Thanks!
谢谢!
I'd suggest using the Pandas library.我建议使用 Pandas 库。
Code is basically as follows:代码基本如下:
import pandas as pd
data = pd.read_csv('put in your csv filename here')
# Filter the data accordingly.
data = data[data['Games Owned'] > 20]
data = data[data['OS'] == 'Mac']
Here's a solution in pure python that writes the filtered output to a textfile (csv) as requested.这是纯python中的解决方案,可根据要求将过滤后的输出写入文本文件(csv)。
import csv
with open('games.csv', 'rb') as csvfile:
# handle header line, save it for writing to output file
header = next(csvfile).strip("\n").split(",")
reader = csv.reader(csvfile)
results = filter(lambda row: row[1] != 'Mac' and int(row[2]) > 20, reader)
with open('output.csv', 'wb') as outfile:
writer = csv.writer(outfile)
writer.writerow(header)
for result in results:
writer.writerow(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.