如何通过Python从CSV中筛选特定的数据?

2024-06-01 07:45:47 发布

您现在位置: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

我在想,我该如何过滤那些拥有超过20款游戏,却没有Mac操作系统的人呢。我需要通过一个python脚本来完成,当运行时,它将数据输出到一个单独的文件中,比如一个文本文件或其他东西。谢谢!


Tags: 游戏oslinuxwindowsmacpeoplegamesanthony
2条回答

我建议使用熊猫图书馆。

代码基本如下:

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']

这里有一个纯python的解决方案,它根据请求将过滤后的输出写入一个textfile(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)

相关问题 更多 >