python - 使用python更改CSV文件中列的值

标签 python csv

我是 python 的新手,只需要一点帮助。

我们有一个管道分隔的 CSV 文件,看起来像这样

DATE|20160101
ID | Name | Address | City | State | Zip   | Phone | OPEID  | IPEDS |
10 | A... | 210 W.. | Mo.. | AL... | '31.. | 334.. | '01023 | 10063 |
20 | B... | 240 N.. | Ne.. | Ut... | '21.. | 335.. | '01024 | 10064 |

Zip 和 OPEID 列的每个值开头都有撇号

因此我们希望创建一个新的 CSV 文件,其中从这两列的每个值中删除撇号。

新文件应该如下所示:

DATE|20160101
ID | Name | Address | City | State | Zip  | Phone | OPEID | IPEDS |
10 | A... | 210 W.. | Mo.. | AL... | 31.. | 334.. | 01023 | 10063 |
20 | B... | 240 N.. | Ne.. | Ut... | 21.. | 335.. | 01024 | 10064 |

此代码适用于在不删除撇号的情况下复制数据

import os
import csv

file1 = "D:\CSV\File1.csv"
with open(file1, 'rb') as csvfile:

         reader = csv.reader(csvfile, delimiter = '|')

         path = "D:/CSV/New"
         if not os.path.exists(path):
             os.makedirs(path)

         writer = csv.writer(open(path+"File2"+".csv", 'wb'), delimiter = '|')

         for row in reader:
             writer.writerow(row)

csvfile.close()

最佳答案

您可以使用 Pandas 非常高效地完成此操作——如果您的文件非常大,这会很好:

import pandas as pd
import sys

with open('t.txt') as infile:
    title = next(infile)
    infile.seek(0)
    table = pd.read_csv(infile, '|', header=1, dtype=str)

table.rename(columns={'Unnamed: 9':''}, inplace=True)

table[' Zip   '] = table[' Zip   '].str.replace("'", "")
table[' OPEID  '] = table[' OPEID  '].str.replace("'", "")

sys.stdout.write(title)
table.to_csv(sys.stdout, '|', index=False)

关于python - 使用python更改CSV文件中列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39165533/

相关文章:

python - 在 canopy venv 中安装软件包

python - seaborn husl 或 hsl 调色板不工作 : remains default black and white colors

python - 用于编辑 numpy 计数数组的一行解决方案? (Python)

python - 如何将 csv 文件的第二列转换为 float 列表?

python - 对多个 csv 文件重复相同的过程

python - 如何使用递归实现插入排序,哪种效率更高?

python - 如何在网络浏览器中将 Kivy GUI 应用程序部署为网络应用程序?

java - Camel : How to skip multiple header lines in CSV files

scala - 使用 pyspark 读取 csv 文件时获取格式错误记录的列名称

python - 过滤具有整数列表的python输出