pandas, python - how to select specific times in timeseries

后端 未结 4 1239
予麋鹿
予麋鹿 2020-12-12 17:58

I worked now for quite some time using python and pandas for analysing a set of hourly data and find it quite nice (Coming from Matlab.)

Now I am kind of stuck. I cr

相关标签:
4条回答
  • 2020-12-12 18:07

    Here's an example that does what you want:

    In [32]: from datetime import datetime as dt
    
    In [33]: dr = p.DateRange(dt(2009,1,1),dt(2010,12,31), offset=p.datetools.Hour())
    
    In [34]: hr = dr.map(lambda x: x.hour)
    
    In [35]: dt = p.DataFrame(rand(len(dr),2), dr)
    
    In [36]: dt 
    
    Out[36]: 
    <class 'pandas.core.frame.DataFrame'>
    DateRange: 17497 entries, 2009-01-01 00:00:00 to 2010-12-31 00:00:00
    offset: <1 Hour>
    Data columns:
    0    17497  non-null values
    1    17497  non-null values
    dtypes: float64(2)
    
    In [37]: dt[(hr >= 10) & (hr <=16)]
    
    Out[37]: 
    <class 'pandas.core.frame.DataFrame'>
    Index: 5103 entries, 2009-01-01 10:00:00 to 2010-12-30 16:00:00
    Data columns:
    0    5103  non-null values
    1    5103  non-null values
    dtypes: float64(2)
    
    0 讨论(0)
  • 2020-12-12 18:07

    As it looks messy in my comment above, I decided to provide another answer which is a syntax update for pandas 0.10.0 on Marc's answer, combined with Wes' hint:

    import pandas as pd
    from datetime import datetime
    
    dr = pd.date_range(datetime(2009,1,1),datetime(2010,12,31),freq='H')
    dt = pd.DataFrame(rand(len(dr),2),dr)
    hour = dt.index.hour
    selector = ((10 <= hour) & (hour <= 13)) | ((20<=hour) & (hour<=23))
    data = dt[selector]
    
    0 讨论(0)
  • 2020-12-12 18:12

    Pandas DataFrame has a built-in function pandas.DataFrame.between_time

    df = pd.DataFrame(np.random.randn(1000, 2),
                      index=pd.date_range(start='2017-01-01', freq='10min', periods=1000))
    

    Create 2 data frames for each period of time:

    df1 = df.between_time(start_time='10:00', end_time='13:00') 
    df2 = df.between_time(start_time='20:00', end_time='23:00')
    

    Data frame you want is merged and sorted df1 and df2:

    pd.concat([df1, df2], axis=0).sort_index()
    
    0 讨论(0)
  • 2020-12-12 18:13

    In upcoming pandas 0.8.0, you'll be able to write

    hour = ts.index.hour
    selector = ((10 <= hour) & (hour <= 13)) | ((20 <= hour) & (hour <= 23))
    data = ts[selector]
    
    0 讨论(0)
提交回复
热议问题