jonboy
jonboy

Reputation: 368

Resample time series - Python

I'm trying to resample a time series. I just can't seem to get it working. Based off other examples I don't understand why this isn't returning a time series:

df1 = pd.DataFrame({'Time': ['2019-08-02 09:50:10.100','2019-08-02 09:50:10.200','2019-08-02 09:50:10.400''2019-08-02 09:50:10.100','2019-08-02 09:50:10.200','2019-08-02 09:50:10.400'], 
                   'Object': ['A','A','A','B','B','B'],
                    })

df1['Time'] = pd.to_datetime(df1['Time'])

df1 = df1.set_index(['Time']).resample('100ms')

print(df1)

Out:

DatetimeIndexResampler [freq=<100 * Millis>, axis=0, closed=left, label=left, convention=start, base=0]

Intended output:

                     Time Object
0 2019-08-02 09:50:10.100      A
1 2019-08-02 09:50:10.200      A
2 2019-08-02 09:50:10.300      Nan
3 2019-08-02 09:50:10.400      A
4 2019-08-02 09:50:10.100      B
5 2019-08-02 09:50:10.200      B
6 2019-08-02 09:50:10.300      Nan
7 2019-08-02 09:50:10.400      B

Upvotes: 0

Views: 159

Answers (1)

Roy2012
Roy2012

Reputation: 12493

I believe what you're trying to do is:

df1['Time'] = pd.to_datetime(df1['Time'])

df1.set_index(['Time'], inplace = True)
df1.groupby("Object").resample("100ms").asfreq()

The output is:

                               Object
Object Time                          
A      2019-08-02 09:50:10.100      A
       2019-08-02 09:50:10.200      A
       2019-08-02 09:50:10.300    NaN
       2019-08-02 09:50:10.400      A
B      2019-08-02 09:50:10.100      B
       2019-08-02 09:50:10.200      B
       2019-08-02 09:50:10.300    NaN
       2019-08-02 09:50:10.400      B

You can now drop the first level of the index if you'd like to:

df1 = df1.groupby("Object").resample("100ms").asfreq()
df1.index = df1.index.droplevel(0)

Output:

                        Object
Time                          
2019-08-02 09:50:10.100      A
2019-08-02 09:50:10.200      A
2019-08-02 09:50:10.300    NaN
2019-08-02 09:50:10.400      A
2019-08-02 09:50:10.100      B
2019-08-02 09:50:10.200      B
2019-08-02 09:50:10.300    NaN
2019-08-02 09:50:10.400      B

Upvotes: 3

Related Questions