Pandas根据日期

时间:2016-12-02 02:59:22

标签: python python-3.x pandas dataframe

我有一个像这样的pandas数据集:

                Date      WaterTemp   Discharge AirTemp        Precip  
0       2012-10-05 00:00       10.9      414.0    39.2           0.0   
1       2012-10-05 00:15       10.1      406.0    39.2           0.0   
2       2012-10-05 00:45       10.4      406.0    37.4           0.0   
...
63661   2016-10-12 14:30       10.5      329.0    15.8           0.0   
63662   2016-10-12 14:45       10.6      323.0    19.4           0.0   
63663   2016-10-12 15:15       10.8      329.0      23           0.0   

我想扩展每一行,以便得到一个看起来像这样的数据集:

              Date    WaterTemp 00:00    WaterTemp 00:15 .... Discharge 00:00 ...
0       2012-10-05                10.9              10.1                414.0

每个日期最多会有72个读数,所以除了日期和索引列之外我还应该有288个列,最多我应该有1460行(4年* 365天 - 可能还有一些日期)。最后,我将在分类任务中使用288列数据集(稍后我将添加标签),因此我需要将此数据帧转换为2d数组(无日期时间)以输入分类器,因此我可以'只需按日期分组,然后访问该组。我确实尝试了基于日期的分组,但我不确定如何将每个组更改为单行。我也考虑过加入。看起来加入可以满足我的需求(例如基于(日,月,年)的连接)但是我不确定如何将事物分成不同的pandas数据帧,以便连接起作用。有什么方法可以做到这一点?

PS。我已经知道如何将我的日期列中的日期时间更改为没有时间的日期。

1 个答案:

答案 0 :(得分:0)

我明白了。我按阅读时间对读数进行分组。每个组本身都是一个数据框架,因此我需要根据日期连接数据框架。我的整个功能代码如下。

import pandas

def readInData(filename):
    #read in files and remove missing values
    ds = pandas.read_csv(filename) 
    ds = ds[ds.AirTemp != 'M']
    #set index to date
    ds['Date'] = pandas.to_datetime(ds.Date, yearfirst=True, errors='coerce')
    ds.Date = pandas.DatetimeIndex(ds.Date)
    ds.index = ds.Date
    #group by time (so group readings by time of day of reading, i.e. all readings at midnight)
    dg = ds.groupby(ds.index.time)

    #initialize the final dataframe
    df = pandas.DataFrame()
    for name, group in dg: #for each group
        #each group is a dateframe
        try:
            #set unique column names except for date
            group.columns = ['Date', 'WaterTemp'+str(name), 'Discharge'+str(name), 'AirTemp'+str(name), 'Precip'+str(name)]
            #ensure date is the index            
            group.index = group.Date
            #remove time from index
            group.index = group.index.normalize()
            #join based on date
            df = pandas.concat([df, group], axis=1)
        except: #if the try catch block isn't here, throws errors! (three for my dataset?)
            pass
    #remove duplicate date columns
    df = df.loc[:,~df.columns.duplicated()]
    #since date is index, drop the first date column
    df = df.drop('Date', 1)
    #return the dataset
    return df