【问题标题】:remove selected csv column in python在python中删除选定的csv列
【发布时间】:2023-03-06 05:18:01
【问题描述】:

我有一个包含以下字符串的变量:

fruit_wanted = 'banana,apple'

我还有一个 csv 文件

fruit,'orange','grape','banana','mango','apple','strawberry'
number,1,2,3,4,5,6
value,3,2,2,4,2,1
price,3,2,1,2,3,4

现在如何删除“fruit_wanted”变量中未列出“fruit”的列?

这样输出文件看起来像

fruit,'banana','apple'
number,3,5
value,2,2
price,1,3

谢谢。

【问题讨论】:

  • 您应该在发帖前用谷歌搜索或搜索 Stackoverflow。 Other question with proper answer
  • 您的 csv 文件是横向的。如果你的 csv 在第一行有标题 fruit,number,value,price 然后每一行代表一个水果,这将是微不足道的。
  • @StevenRumbalski:他可能对此没有任何控制权。了解如何处理横向 CSV 文件很有用(无需阅读整个内容,因此您可以 zip 转置)。

标签: python csv


【解决方案1】:

使用DictReader() class读取csv文件,忽略不需要的列:

fruit_wanted = ['fruit'] + ["'%s'" % f for f in fruit_wanted.split(',')]
outfile = csv.DictWriter(open(outputfile, 'wb'), fieldnames=fruit_wanted)
fruit_wanted = set(fruit_wanted)

for row in csv.DictReader(open(inputfile, 'rb')):
    row = {k: row[k] for k in row if k in fruit_wanted}
    outfile.writerow(row)

【讨论】:

  • +1,除了您可能想要使用csv.DictWritercsv.Writer 而不是print row,否则您的输出将是dict 的str 表示而不是逗号分隔的列表正确的顺序……
  • 实际上,作者只要求'outfile')
  • @alexvassel: 'outfile',我现在明白了。所以我更新了答案(并包括一个更正,第一个fruit 列也是需要的)。
  • 这仅在我将 fields=fruit_wanted 替换为 fieldnames=fruit_wanted 后才对我有用
【解决方案2】:

这是一些伪代码:

open the original CSV for input, and the new one for output
read the first row of the original CSV and figure out which columns you want to delete
write the modified first row to the output CSV
for each row in the input CSV:
    delete the columns you figured out before
    write the modified row to the output CSV

【讨论】:

    猜你喜欢
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多