How to keep every nth item in a list and make the rest zeros

Tags: python list

I am trying to model and fit to noisy data over a long time series and I want to see what happens to my fit if I remove a substantial amount of my data.

I have a long time-series of data and I am only interested in every nth item. However I still want to plot this list over time but with every other unwanted element removed.

For example, for n=4, the list

a = [1,2,3,4,5,6,7,8,9,10...]

Should become

a_new = [1,0,0,0,5,0,0,0,9,0...]

I don't mind if the position of the nth item is at the start or end of the sequence, my series is effectively arbitrary and so long that it won't matter what I delete. For example 'a_new' could also be:

a_new = [0,0,0,4,0,0,0,8,0,0...]

Ideally the solution wouldn't depend on the length of the list, but I can have that length as a variable.

Edit 1:

I actually wanted empty elements, not zero's, (if that's possible?) so:

a_new = [1,,,,5,,,,9...] 

Edit 2:

I needed to remove the corresponding elements from my time series too so that when everything is plotted, each data element has the same index as the time series element.


[0 if i%4 else num for i, num in enumerate(a)]

Here's a working example to filter functions given a certain step K:

def filter_f(data, K=4):
    if K 
By : BPL

Use a list comprehension with a ternary conditional that takes the mod of each element on the number n:

This video can help you solving your question :)
By: admin