SkytechCEO
SkytechCEO

Reputation: 91

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. 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. Thanks!

Upvotes: 2

Views: 16262

Answers (2)

Paul Back
Paul Back

Reputation: 1319

Here's a solution in pure python that writes the filtered output to a textfile (csv) as requested.

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)

Upvotes: 3

ericmjl
ericmjl

Reputation: 14694

I'd suggest using the Pandas library.

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

Upvotes: 7

Related Questions