簡體   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

我想知道,我將如何過濾掉擁有 20 多個游戲但他們沒有 Mac OS 系統的人。 我需要通過 python 腳本來完成,當運行時,它將數據輸出到一個單獨的文件中,比如文本文件或其他東西。 謝謝!

我建議使用 Pandas 庫。

代碼基本如下:

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中的解決方案,可根據要求將過濾后的輸出寫入文本文件(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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM