【问题标题】:Combine columns in CSV file with Python将 CSV 文件中的列与 Python 合并
【发布时间】:2015-07-16 19:28:14
【问题描述】:

我有一个包含 3 列的 csv 文件。使用 Python,我想将第 3 列的数据合并到第 1 列并删除第 3 列。

例子:

这是我所拥有的:

date, time, date
1/10, 5:30, 
    , 6:00, 1/10
1/11, 4:30, 
1/11, 5:00

这就是我想要的:

date, time
1/10, 5:30 
1/10, 6:00
1/11, 4:30 
1/11, 5:00

任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 当你说合并时,你的意思是如果存在就覆盖?
  • 我投票结束这个问题作为题外话,因为 SO 不是代码编写服务!
  • 您只是想这样做(在这种情况下您可以只使用 Excel),还是打算将其作为更大程序中的一个小步骤?
  • @TigerhawkT3 是的,我可以在 excel 中轻松做到这一点,但尝试在 python 的程序中做到这一点
  • 然后准备使用csv 模块度过一些有趣的时光。

标签: python csv merge


【解决方案1】:

这是一种方法:

import csv

with open('in.csv') as infile, open('out.csv', 'wb') as outfile:
    reader = csv.reader(infile)
    next(reader)  # Skip the header
    writer =csv.writer(outfile)
    writer.writerow(['date', 'time'])  # Write the header

    for row in reader:
        # Remove white spaces in each field and assign to vars
        date1, time, date2 = [x.strip() for x in row]
        writer.writerow([date1 or date2, time])

注意事项

  • 我打开了输入和输出文件,分别从这些文件中创建了一个 CSV 读取器和写入器。
  • 对于读者,我跳过了标题;对于作家,我写了一个新的标题。简单的操作。
  • 我假设输入中的每一行始终包含 3 个字段:日期 1、时间和日期 2。
  • 表达式date1 or date2返回两者之间的非空字符串。

【讨论】:

    猜你喜欢
    • 2014-12-23
    • 2020-07-30
    • 2016-03-25
    • 2014-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多