I have a time-series consisting of numeric data points, say in form of a list:
x = [924, -5, 24, 1, 0, 242, -5, 42, 5, 1, -9, 50, 3, 432, 0, -5, 4]
Now I would like to achieve the following aim that I describe in three steps:
- The first two values from the list, x(1) and x(2), namely 924 and -5, should be added to the two lists below, respectively.
x_list = []
y_list = []
This is to say that x(1) (=924) should be added to x_list
and x(2) (=-5) to y_list
.
This would be managable for me, but since my aim continues as follows, I am currently unable to solve this in Python.
The second aim is to take the next two values or "pairs" of the list
x
, namely x(2) and x(3), and add again them tox_list
andy_list
, respectively. Now (x2) goes tox_list
, and x(3) toy_list
.Finally, I would like to repeat this step, i.e., adding x(3) to
x_list
and x(4) toy_list
and so on, until the end of the time-seriesx
is reached.
I assume that I have to program a function using def
. But I don't understand how to set up the code for this aim. Here is the current state of my code.
import numpy as np
import matplotlib.pyplot. as plt
x = [924, -5, 24, 1, 0, 242, -5, 42, 5, 1, -9, 50, 3, 432, 0, -5, 4]
x_results = []
y_results = []
for t in Timeseries:
next_n = # This is where I am stuck, struggling to find the correct code
next_y =
x_results.append(next_x)
y_results.append(next_y)
plt.plot(x_results, y_results, "bo")
plt.show()
CodePudding user response:
You can use two slices:
mylist = [924, -5, 24, 1, 0, 242, -5, 42, 5, 1, -9, 50, 3, 432, 0, -5, 4]
x_list = mylist[:-1]
y_list = mylist[1:]
CodePudding user response:
for python ≥ 3.10, this is the job of itertools.pairwise
:
from itertools import pairwise
x, y = zip(*pairwise(mylist))
output:
x
(924, -5, 24, 1, 0, 242, -5, 42, 5, 1, -9, 50, 3, 432, 0, -5),
y
(-5, 24, 1, 0, 242, -5, 42, 5, 1, -9, 50, 3, 432, 0, -5, 4)
for python < 3.10, the recipe for pairwise is:
from itertools import tee
def pairwise(iterable):
a, b = tee(iterable)
next(b, None)
return zip(a, b)