【问题标题】:An issue with the sequence of datetime column in PythonPython中日期时间列的序列问题
【发布时间】:2019-07-02 18:03:20
【问题描述】:

多个文件拼接成一个大文件后,datetime列的顺序并没有跟原来的文件一致。

我有许多气象数据的 .csv 文件。一日一档。间隔5分钟。原始文件使用此日期时间格式:24.03.2016 18:35。

我使用以下方法连接所有文件:

    globbed_files = glob.glob(path + "\*Raw2*.csv")
    data = []

    for csv in globbed_files:
       df = pd.read_csv(csv, encoding = "ISO-8859-1", header = 0, 
       low_memory=False)
       data.append(df) 

    combined = pd.concat(data, ignore_index=True, sort=True)
    combined['DateTime'] = pd.to_datetime(combined['DateTime'])
    combined.set_index('DateTime', inplace=True)
    combined.index = combined.index.map(lambda t: t.strftime('%d/%m/%Y %H:%M:%S'))

    combined.to_csv(path + "\year1.txt", sep='\t', header=True, index=True)

结果是三个文件。每个文件都包含特定年份的数据。我根据原始文件检查了所有文件的日期时间顺序是否正确。

因为我不知道如何把原来的datetime格式转成Python可以理解的DateTime格式,所以我手动做了。我将日期时间列复制到记事本中,添加第二个(:00),删除不必要的空格,替换所有“。”使用“/”,最后将其复制粘贴回 csv。为了确保在 csv 上,我再次将 ecxel 内置日期格式用于 datetime 列。新的日期时间格式为:24/03/2016 18:35:00。

接下来,使用新的日期时间格式,我将“年度文件”连接成一个最终的大文件。

但是发生了什么? Python 通过交换日期和月份来读取日期时间不一致。因此,08/03/2016 18:35:00 可能被错误地读取为第 8 个月和第 3 天,或者正确读取为第 8 天第 3 个月。现在,我的新文件未按照原始文件排序。

感谢任何帮助。

【问题讨论】:

    标签: python pandas datetime


    【解决方案1】:

    解决方案应该简化为read_csv添加参数,最后通过DatetimeIndex.strftime将索引转换为自定义格式:

    globbed_files = glob.glob(path + "\*Raw2*.csv")
    data = []
    
    for csv in globbed_files:
       df = pd.read_csv(csv, 
                        encoding = "ISO-8859-1", 
                        header = 0, 
                        low_memory=False,
                        parse_dates=['DateTime'], #convert column to datetimes
                        dayfirst=True,  #avoid inconsistency  for specify first value is day
                        index_col=['DateTime'] #create DatetimeIndex
                        )
       data.append(df) 
    
    combined = pd.concat(data, sort=True)
    
    combined.index = combined.index.strftime.strftime('%d/%m/%Y %H:%M:%S')
    
    combined.to_csv(path + "\year1.txt", sep='\t', header=True, index=True)
    

    【讨论】:

    • 你节省了我的时间。谢谢。您的代码有效,但由于此处出现错误,我必须删除倒数第二行。
    猜你喜欢
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 2016-05-08
    • 2020-07-15
    • 1970-01-01
    • 2021-06-17
    • 2012-08-14
    • 1970-01-01
    相关资源
    最近更新 更多