简体   繁体   English

如何通过 Python 从 CSV 中过滤掉特定数据?

[英]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.

相关问题 仅通过 python 使用 csv 模块从 csv 文件中过滤掉特定数据 - filter out specific data from csv file only using csv module via python 如何使用 python 从 csv 文件中过滤掉可用数据? - How to filter out useable data from csv files using python? Python cProfile:如何从分析数据中过滤出特定的调用? - Python cProfile: how to filter out specific calls from the profiling data? 如何在 Python 中从 API 生成的数据中过滤掉特定值 - How to Filter Out Specific Value from API Generated Data in Python 如何根据csv文件的python中的日期过滤掉数据 - How to filter out data based on date in python of a csv file 在Python中从CSV文件的特定列中提取数据 - Pulling out data from CSV files' specific columns in Python 如何从 csv 中过滤出符合特定规则的所有行并将它们写入 Python 中的新 csv? - How do I filter all lines out of a csv that comply a specific rule and write them to a new csv in Python? 如何使用python过滤和排序特定的csv - How to filter and sort specific csv using python Python:如何从网页中的CSV数据中过滤列? - Python: How to filter columns from a csv data within a webpage? 如何使用 python 从带有 Sendgrid 的 csv 文件中通过电子邮件发送数据 - How to email out data from a csv file with Sendgrid using python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM