【问题标题】:Python to modify a csv file, duplicate and format a column, and save outputPython 修改 csv 文件,复制和格式化列,并保存输出
【发布时间】:2020-11-18 06:38:44
【问题描述】:

我正在尝试使用 pandas 库找出一种方法来获取 3 列 csv 文件并将其转换为 5 列 csv 文件,并为最后一列设置格式。然后我需要保存输出。我可以在 powershell 中编写它,但我无法在 python 中弄清楚它,我需要它非常高效。我正在使用一个 3 列 1.4 亿行的文件。我想做什么的例子:

测试数据 1234567 123456789

测试数据 1234567 123456789

到->

测试数据 1234567 123456789 123-45-6789 123/45/6789

测试数据 1234567 1234667890 123-45-6789 123/45/6789

提前感谢您的帮助。

【问题讨论】:

  • 你是否要为跨行的两个新列分配相同的值??
  • 不,它们将基于第 3 列中的值

标签: python pandas performance csv formatting


【解决方案1】:

这是一个示例解决方案

import pandas as pd

chunksize = 10 ** 6
for chunk in pd.read_csv("sample_data.csv", chunksize=chunksize, engine="c", header=None, sep=" ", dtype="string"):
    chunk[3] = chunk[2].map(lambda x: x[:3] + "-" + x[3:5] + "-" + x[5:])
    chunk[4] = chunk[2].map(lambda x: x[:3] + "/" + x[3:5] + "/" + x[5:])
    print(chunk.head(10))

    chunk.to_csv("sample_output.csv", header=None, mode='a')

我使用以下内容作为参考点:

Writing large Pandas Dataframes to CSV file in chunks

How do I read a large csv file with pandas?

【讨论】:

    猜你喜欢
    • 2017-04-27
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多