【问题标题】:PYTHON > Rearrange item data ("date") within .csv filePYTHON > 在 .csv 文件中重新排列项目数据(“日期”)
【发布时间】:2021-01-09 13:22:52
【问题描述】:

来源 csv:

column a, column b, 2021-01-09, column d
column a, column b, 2021-01-10, column d
column a, column b, 2021-01-11, column d

期望的输出:

09/01/2021, column a, column b, column d
10/01/2021, column a, column b, column d
11/01/2021, column a, column b, column d

python 实现这一目标的最佳方法是什么?
提前致谢!

【问题讨论】:

    标签: python csv


    【解决方案1】:

    假设你在 csv 中的行是这样的

    row = ["column a", "column b", "2021-01-09", "column d"]
    

    你可以做类似的事情

    import datetime
    
    row.sort()
    row[0] = datetime.datetime.strptime(row[0], '%Y-%m-%d').strftime('%d/%m/%y')
    

    将行设为

    >>> row
    ['09/01/21', 'column a', 'column b', 'column d']
    

    【讨论】:

    • 感谢@Jarvis 的简洁回答!
    【解决方案2】:

    使用pandas 的一种方法可以实现这一点,因为您已经使用 csv.DictWriter

    获得了答案
    import pandas as pd
    df = pd.read_csv('source.csv',names=["ColA", "ColB", "Date", "ColD"])
    df['Date'] = pd.to_datetime(df['Date'].str.strip(), format='%Y-%m-%d').dt.strftime('%d/%m/%Y')
    new_df = df[['Date', 'ColA', 'ColB', 'ColD']]
    print(new_df)
    

    输出:

             Date      ColA       ColB       ColD
    0  09/01/2021  column a   column b   column d
    1  10/01/2021  column a   column b   column d
    2  11/01/2021  column a   column b   column d
    

    【讨论】:

    • 很高兴它能以某种方式帮助你:)
    【解决方案3】:

    重新排序,按照:
    Python - re-ordering columns in a csv

    import csv
    
    with open('file.csv', 'r') as infile, open('reordered.csv', 'a') as outfile:
        fieldnames = ['column c', 'column a', 'column b', 'column d']
        writer = csv.DictWriter(outfile, fieldnames=fieldnames)
        writer.writeheader()
        for row in csv.DictReader(infile):
            writer.writerow(row)
            
    

    添加日期:
    In python how to change date format in a csv?

    import datetime
    
    with open("reordered.csv", 'r') as csvfile, open('file.csv', 'w') as temp_file:
    
        for line in csvfile.readlines():
            # Fetch all dates in the csv
            dates = line.split(',')
    
            # Extract date, month and year
            yr, mon, dt = dates[0].split('-')
    
            # Convert the second date and replace
            dates[0] = datetime.datetime.strptime(dates[0], '%y-%b-%d').strftime('%d/%b/%Y')
    
            # Write date to temp file
            temp_file.write(','.join(dates))
    

    【讨论】:

      猜你喜欢
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 2015-11-26
      • 1970-01-01
      • 2015-08-28
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      相关资源
      最近更新 更多