Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am trying to resample the time series. I just can't seem to get it working. Based on other examples I don't understand why this is not returning the 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

1 Answer

0 votes
by (36.8k points)

I believe what you are 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

Do check out Data Science with Python course which helps you understand from scratch.

Related questions

0 votes
1 answer
asked Feb 8, 2021 in Python by ashely (50.2k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...