Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to subset list base on array in python

I have following column names in a list:

 vars = ['age','balance','day','duration','campaign','pdays','previous','job_admin.','job_blue-collar']

I have one array which consists of array indexes

(array([1, 5, 7], dtype=int64),)

I want to subset the list based on array indexes

Desired output should be

vars = ['balance','pdays','job_admin.']

I have tried something like this in python

for i, a in enumerate(X):
   if i in new_L:
       print i

But,it does not work.

like image 697
Neil Avatar asked Apr 03 '18 08:04

Neil


2 Answers

Simply use a loop to do that:

result=[]
for i in your_array:
   result.append(vars[i])

or one linear

 [vars[i] for i in your_array]
like image 101
Mehrdad Pedramfar Avatar answered Oct 16 '22 16:10

Mehrdad Pedramfar


If you're using numpy anyway, use its advanced indexing

import numpy as np
vars = ['age','balance','day','duration','campaign','pdays',
        'previous','job_admin.','job_blue-collar']
indices = (np.array([1, 5, 7]),)

sub_array = np.asarray(vars)[indices]  
# --> array(['balance', 'pdays', 'job_admin.'], dtype='<U15')

or if you want a list

sub_list = np.asarray(vars)[indices].tolist()
# --> ['balance', 'pdays', 'job_admin.']
like image 4
FHTMitchell Avatar answered Oct 16 '22 17:10

FHTMitchell