首页 > 解决方案 > Python中日期时间列的序列问题

问题描述

将多个文件拼接成一个大文件后,日期时间列的顺序并没有按照原文件的顺序排列。

我有许多气象数据的 .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 个月。现在,我的新文件未根据原始文件排序。

任何帮助表示赞赏。

标签: pythonpandasdatetime

解决方案


解决方案应该简化添加参数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)

推荐阅读