获取时间日期范围

时间:2015-12-07 18:50:07

标签: python pandas

我还在学习python的方法,这有点复杂, 有这样的表pandas.DataFrame

           SAMPLE_TIME  TempBottom  TempTop  TempOut    State       Bypass  
0  2015-07-15 16:41:56      48.625   55.812   43.875        1            1   
1  2015-07-15 16:42:55      48.750   55.812   43.875        1            1   
2  2015-07-15 16:43:55      48.937   55.812   43.875        1            1   
3  2015-07-15 16:44:56      49.125   55.812   43.812        1            1   
4  2015-07-15 16:45:55      49.312   55.812   43.812        1            1 

这是一个大数据集,每隔几分钟就会有一些条目。 我试图获得每天的范围,所以基本上忽略了时间和分裂天数

修改

我忘了提到这是使用pd.read_csv()从csv导入的,我认为这意味着SMAPLE_TIME不是DatetimeIndex

2 个答案:

答案 0 :(得分:2)

你可以

df['SAMPLE_TIME'] = pd.to_datetime(df['SAMPLE_TIME'])
df.set_index('SAMPLE_TIME', inplace=True)
df_by_days = df.groupby(pd.TimeGrouper('D')).agg()

应用the docs中描述的各种聚合函数。如果您提供有关您想要汇总的内容以及如何汇总的详细信息,请尽快添加示例。

答案 1 :(得分:2)

您可以尝试:

#set to datetimeindex
df['SAMPLE_TIME'] = pd.to_datetime(df['SAMPLE_TIME'])

print df
          SAMPLE_TIME  TempBottom  TempTop  TempOut  State  Bypass
0 2015-07-05 16:41:56      48.625   55.812   43.875      1       1
1 2015-07-05 16:42:55      48.750   55.812   43.875      1       1
2 2015-07-23 16:43:55      48.937   55.812   43.875      1       1
3 2015-07-23 16:44:56      49.125   55.812   43.812      1       1
4 2015-07-25 16:45:55      49.312   55.812   43.812      1       1

df = df.set_index('SAMPLE_TIME')
g1 =  df.groupby(lambda x: x.day)

for d,g in g1:
    print d
    print g
5
                     TempBottom  TempTop  TempOut  State  Bypass
SAMPLE_TIME                                                     
2015-07-05 16:41:56      48.625   55.812   43.875      1       1
2015-07-05 16:42:55      48.750   55.812   43.875      1       1
23
                     TempBottom  TempTop  TempOut  State  Bypass
SAMPLE_TIME                                                     
2015-07-23 16:43:55      48.937   55.812   43.875      1       1
2015-07-23 16:44:56      49.125   55.812   43.812      1       1
25
                     TempBottom  TempTop  TempOut  State  Bypass
SAMPLE_TIME                                                     
2015-07-25 16:45:55      49.312   55.812   43.812      1       1

或者您可以按天分组并按总和汇总:

df = df.set_index('SAMPLE_TIME')
g1 =  df.groupby(lambda x: x.day).agg(sum)
print g1
    TempBottom  TempTop  TempOut  State  Bypass
5       97.375  111.624   87.750      2       2
23      98.062  111.624   87.687      2       2
25      49.312   55.812   43.812      1       1

或按年份,月份和日期分组并按总和汇总:

df['SAMPLE_TIME'] = pd.to_datetime(df['SAMPLE_TIME'])

df = df.set_index('SAMPLE_TIME')
g1 =  df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day]).agg(sum)
print g1
           TempBottom  TempTop  TempOut  State  Bypass
2015 7 5       97.375  111.624   87.750      2       2
       23      98.062  111.624   87.687      2       2
       25      49.312   55.812   43.812      1       1