【问题标题】:Python to Remove Column in CSV and Write new CSV filePython 删除 CSV 中的列并写入新的 CSV 文件
【发布时间】:2020-06-10 12:04:24
【问题描述】:

输入的 CSV 文件如下。

Elements,FileID,Loadcase,Step,Layer,CornerID,E-Strain components IP:E11
41,2,1,0,SectionPoint 1,0,0
41,2,1,0,SectionPoint 1,5,0
41,2,1,0,SectionPoint 1,35,0

在此文件中,我想删除整个CornerID 列并编写一个新的 CSV 文件。
注意:脚本应该使用标题名称并删除该列。不像列索引级别删除的方式。因为像这样我有多个文件,在某些文件中列号不会相同。

谁能帮我获取python代码?

导入 csv

inputf = "D:\PyLe\csvinput\Report_E-应变组件 IP_E11_2_1.csv" outfile = "D:\PyLe\csvinput\Report_E-Strain 组件 IP_E11_2_1_new.csv"

import csv

    with open(inputf, newline='') as csvfile:
        outfile1 = open (outfile , 'w')
        reader = csv.DictReader(csvfile)

for row in reader:
      del (row['CornerID'])
      spamwriter = csv.writer(outfile1, delimiter=' ',
                        quotechar='|', quoting=csv.QUOTE_MINIMAL)
      spamwriter.writerow(row)
      print (type(row))

此代码正在读取 csv 文件并删除该列。但它没有用 csv 格式写出新文件。

【问题讨论】:

  • df.drop(['CornerID'], axis=1, inplace=True) 然后保存为 csv 怎么样?
  • 请给我完整的代码..:)

标签: python python-3.x csv


【解决方案1】:

最简单的方法是使用pandas。它是处理表格数据的常用python模块。

import pandas as pd

csv = pd.read_csv("pathtoyourcsvfile.csv")
csv = csv.drop("CornerID", axis=1)
csv.to_csv("pathtoyournewcsvfile.csv")

【讨论】:

【解决方案2】:

Pandas installation

您可以先read_csv,然后drop 列,然后使用to_csv 将其保存为csv

import pandas as pd
df = pd.read_csv('your_CSV_file_name')
df.drop(['CornerID'], axis=1, inplace=True)
df.to_csv('path_or_buf_to_save_new_csv')

【讨论】:

  • 可能是。我不知道这一点。您还应该记住,这不是一个代码编写平台。如果你想要一个不使用 Pandas 的代码,那么我建议你编写你的代码,如果出现任何问题,你可以在这里发布问题
  • import csv inputf = "D:\\PyLe\\csvinput\\Report_E-Strain 组件 IP_E11_2_1.csv" outfile = "D:\\PyLe\\csvinput\\Report_E-Strain 组件 IP_E11_2_1_new。 csv" import csv with open(inputf, newline='') as csvfile: outfile1 = open (outfile , 'w') reader = csv.DictReader(csvfile) for row in reader: del (row['CornerID']) spamwriter = csv.writer(outfile1, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow(row) print (type(row)) inputf.close() outfile.close()
  • 通过所有关于为此目的使用这个库的博客文章,他们都没有关键的最后一个方法调用“df.to_csv('path')”
猜你喜欢
  • 2018-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-28
  • 1970-01-01
  • 2012-05-21
  • 1970-01-01
  • 2017-05-17
相关资源
最近更新 更多