Inverse Split Sequence and Plot

Viewed 22

I have a time series:

            Close
2018-01-01  66.659485
2018-01-02  66.659485
2018-01-03  65.877713
2018-01-04  66.791399
2018-01-05  67.968765
2018-01-06  96.900002
2018-01-07  96.900002
2018-01-08  96.900002
2018-01-09  96.349998
2018-01-10  95.519997

I split into n-day sequences (3 days for example)

        Col_0       Col_1       Col_2
0   66.659485   66.659485   65.877713
1   66.659485   65.877713   66.791399
2   65.877713   66.791399   67.968765
3   66.791399   67.968765   96.900002
4   67.968765   96.900002   96.900002
5   96.900002   96.900002   96.900002
6   96.900002   96.900002   96.349998

Using a clustering algorithm, such as KMeans, I manage to assign each sequence to a clusters (this is an example):

        Col_0       Col_1       Col_2    Cluster
0   66.659485   66.659485   65.877713          0 
1   66.659485   65.877713   66.791399          0
2   65.877713   66.791399   67.968765          1
3   66.791399   67.968765   96.900002          0
4   67.968765   96.900002   96.900002          1
5   96.900002   96.900002   96.900002          0
6   96.900002   96.900002   96.349998          0

My question is: how can I plot the original time series with the clusters in different colors? I have been trying using the transpose .T but with no success.

1 Answers

I would use to get a sliding_window_view:

from numpy.lib.stride_tricks import sliding_window_view

out = pd.DataFrame(sliding_window_view(df['Close'], 3)).add_prefix('Col_')

output:

       Col_0      Col_1      Col_2
0  66.659485  66.659485  65.877713
1  66.659485  65.877713  66.791399
2  65.877713  66.791399  67.968765
3  66.791399  67.968765  96.900002
4  67.968765  96.900002  96.900002
5  96.900002  96.900002  96.900002
6  96.900002  96.900002  96.349998
7  96.900002  96.349998  95.519997
Related