How to randomly remove a percentage of items from a list
<p>I have two lists of equal length, one is a data series the other is simply a time series. They represent simulated values measured over time.</p>

<p>I want to create a function that removes a set percentage or fraction from both lists but at random. I.e. if my fraction is 0.2, I want to randomly remove 20% of the items from both lists, but they have to be the same items (same index in each list) removed.</p>

<p>For example, let n = 0.2 (20% to be deleted)</p>

<pre><code>a = [0,1,2,3,4,5,6,7,8,9]
b = [0,1,4,9,16,25,36,49,64,81]
</code></pre>

<p>After the randomly removed 20%, they become</p>

<pre><code>a_new = [0,1,3,4,5,6,8,9]
b_new = [0,1,9,16,25,36,64,81]
</code></pre>

<p>The relationship isn't as straightforward as the example, so I can't just perform this action on one list and then work out the second; they already exist as two lists. And they have to remain in the original order.</p>

<p>Thanks!</p>

<p>You can also operate the <em>zipped</em> a and b sequence, get the random sample of the indexes (to maintain the original order of items) and <em>unzip</em> into <code>a_new</code> and <code>b_new</code> again:</p>

<pre><code>import random


a = [0,1,2,3,4,5,6,7,8,9]
b = [0,1,4,9,16,25,36,49,64,81]

frac = 0.2

c = zip(a, b)  # c = list(zip(a, b)) on Python 3
indices = random.sample(range(len(c)), frac * len(c))
a_new, b_new = zip(*sorted(c[i] for i in sorted(indices)))

print(a_new)
print(b_new)
</code></pre>

<p>It can print:</p>

<pre><code>(0, 2, 3, 5, 6, 7, 8, 9)
(0, 4, 9, 25, 36, 49, 64, 81)
</code></pre>

python list