【问题标题】:Filter CSV File Program using Pandas and Python使用 Pandas 和 Python 过滤 CSV 文件程序
【发布时间】:2018-03-29 12:43:04
【问题描述】:

我目前的任务涉及下载 CSV 主文件,删除 A 列 - B 列

  • 导入 CSV 文件
  • 删除 A 列 - B 列
  • 要求输入以过滤 C 列中的一个或多个短语
  • 将 CSV 导出到新文件中

到目前为止,我已经确定最好的方法是使用 Pandas 的数据框功能,因为我之前使用它对 CSV 文件执行其他操作:

import pandas as pd

file = read_csv("sourcefile.csv")
file['NewColumn'] = file['A'] - file['B']
file = file[file.NewColumn > 0]
columns = ['ColumnsIWantToRemove']
file.drop(columns, inplace=True, axis=1)
phrases = input('What phrases are you filtering for? ')
file = file[file.C = phrases]
file.to_csv('export.csv')

我的问题是,如何过滤 C 列的多个短语?我希望程序采用一个或多个短语,并且只显示 C 列的值等于其中一个值的行。任何指导都会很棒。谢谢!!

【问题讨论】:

    标签: python pandas csv dataframe


    【解决方案1】:

    我只要求输入以逗号分隔:

    phrases = phrases.split(",")
    file = file[file.C.isin(phrases)]
    

    【讨论】:

    • 我试过这个,但它似乎没有过滤,当我导出数据文件时它出现空白。有什么想法吗?
    • @dner print statements are youfriend here,你应该尝试在拆分前后打印短语,然后你可以看看你是否可以在repl中复制它(例如ipython)。
    【解决方案2】:

    也许这可以帮助你:

    import csv
    
    input = open(sourcefile.csv, 'rb')
    output = open(out_sourcefile, 'wb')
    writer = csv.writer(output)
    for row in csv.reader(input):
        if (phrases you want C column not to be,and you can add here multiple phrases):
            continue
            writer.writerow(row)
    input.close()
    output.close()
    

    【讨论】:

    • 这似乎不起作用,因为我们有数百个不想保留的短语
    猜你喜欢
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 2013-07-23
    • 2023-04-10
    • 1970-01-01
    相关资源
    最近更新 更多