cool_beans
cool_beans

Reputation: 141

Making a list based on a criteria of another list

I have an empty list called 'label', where depending on which bucket is more appropriate, it will fill the 'label' list with 0,1,or 2.

'label' is associated to the 3 'buckets':

# Bucket 0: 0 -7 Days --------------------------> 0
# Bucket 1: 1 - 6 Weeks (8 - 42 Days) ----------> 1
# Bucket 2: 7+ Weeks (49+ Days) ----------------> 2

I have another list has a length of 23411. This list's contents consist of 0 days to 1099 days. So based on this list's contents, it should populate the 'label' list.

I have tried this for-loop & if-else statement to do what I want, however it is giving me a IndexError: list assignment index out of range:

label = []
for i in range(23411):
    if ageNew[i] <= 7:
        label[i] = 0
    elif ageNew[i] <= 42:
        label[i] = 1
    else:
        label[i] = 2

For example:

list: [0, 8, 14, 14, 45, 1056, 1]
label: [0, 1, 1, 1, 2, 2, 0]

Upvotes: 0

Views: 279

Answers (4)

fernandezcuesta
fernandezcuesta

Reputation: 2448

You can use np.where with a numpy array. For your example:

i = np.arange(23411)
label = np.where(i<=7, 0, np.where(i<=42, 1, 2))

Upvotes: 0

YOLO
YOLO

Reputation: 21709

Try this:

label = []
for i in lists:
    if i <= 7:
        label.append(0)
    elif i >= 8 and i <= 42:
        label.append(1)
    else:
        label.append(2)
#output
[0, 1, 1, 1, 2, 2, 2, 0]

label

Upvotes: 0

Pierluigi
Pierluigi

Reputation: 1118

Your list is empty so [i] won't work the way you expecting because that index does not exist. What about:

label = []
for i in range(23411):
    val = None
    if ageNew[i] <= 7:
        val = 0
    elif ageNew[i] <= 42:
        val = 1
    else:
        val = 2
    label.append(val)

This should work.

Upvotes: 1

Eran Moshe
Eran Moshe

Reputation: 3208

You cannot make the assignment label[i] = something because it doesn't exist. Use .append() instead

label = []
for i in range(23411):
    if ageNew[i] <= 7:
        res = 0
    elif ageNew[i] <= 42:
        res = 1
    else:
        res = 2
    label.append(res)

Upvotes: 1

Related Questions