7.2.1. Converting and copying TimeSeries#
We now know how to create a TimeSeries from scratch. We can also create a TimeSeries from other variables or even from other TimeSeries.
import kineticstoolkit.lab as ktk
import numpy as np
import pandas as pd
7.2.1.1. Converting a variable to a TimeSeries#
Any list, NumPy array, Pandas Series or Pandas DataFrame can be converted to a TimeSeries.
7.2.1.1.1. List to TimeSeries#
example_list = [1, 2, 3, 4, 5]
example_list
[1, 2, 3, 4, 5]
ts = ktk.TimeSeries(example_list)
ts
TimeSeries with attributes:
time: array([0., 1., 2., 3., 4.])
data: {'data': array([1, 2, 3, 4, 5])}
events: []
info: {'Time': {'Unit': 's'}}
7.2.1.1.2. Array to TimeSeries#
example_array = np.array([1, 2, 3, 4, 5])
example_array
array([1, 2, 3, 4, 5])
ts = ktk.TimeSeries(example_array)
ts
TimeSeries with attributes:
time: array([0., 1., 2., 3., 4.])
data: {'data': array([1, 2, 3, 4, 5])}
events: []
info: {'Time': {'Unit': 's'}}
7.2.1.1.3. Series to TimeSeries#
example_series = pd.Series([1, 2, 3, 4, 5])
example_series
0 1
1 2
2 3
3 4
4 5
dtype: int64
ts = ktk.TimeSeries(example_series)
ts
TimeSeries with attributes:
time: array([0., 1., 2., 3., 4.])
data: {'data': array([1, 2, 3, 4, 5])}
events: []
info: {'Time': {'Unit': 's'}}
7.2.1.1.4. DataFrame to TimeSeries#
example_dataframe = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8]], columns=["x", "y"])
example_dataframe
| x | y | |
|---|---|---|
| 0 | 1 | 2 |
| 1 | 3 | 4 |
| 2 | 5 | 6 |
| 3 | 7 | 8 |
ts = ktk.TimeSeries(example_dataframe)
ts
TimeSeries with attributes:
time: array([0, 1, 2, 3])
data: {'x': array([1, 3, 5, 7]), 'y': array([2, 4, 6, 8])}
events: []
info: {'Time': {'Unit': 's'}}
7.2.1.2. Copying a TimeSeries#
As for most types in Python, a TimeSeries is a mutable type, which means that simply writing ts2 = ts1 does not create a second TimeSeries ts2 based on TimeSeries ts1. Instead, it creates a new variable that addresses the same TimeSeries. As a consequence, modifying ts2 would also modify ts1. To create an independent copy of ts1, we use ts2 = ts1.copy().
Note
This same phenomenon also happens with most Python types, including NumPy arrays and Pandas DataFrames. This is why they also include a copy method.
The ktk.TimeSeries.copy method has different arguments to select which attributes to copy. For instance, if we want to create TimeSeries with the same time and events as another one, but without its data or info, we would use:
ts2 = ts1.copy(copy_data=False, copy_info=False)