Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract specific columns from list

Tags:

python

I have a list that contain the column indexes as follows:

list1 = [0 ,2]

Another list of list would contain the file contents of a csv file as follows:

list2=[["abc", 1, "def"], ["ghi", 2, "wxy"]]

What can be the best way to create a new list that would only contain the values from list2 with the column numbers that are contained in list1 i.e.

newList = [["abc", "def"], ["ghi", "wxy"]]

I am having a hard time creating the sublists

like image 369
name_masked Avatar asked Sep 26 '12 20:09

name_masked


People also ask

How do I extract a column from a list in R?

Data Visualization using R Programming Therefore, we can use lapply function for this extraction. For example, if we have a list called LIST that store two data frames then column 3 of each data frame can be extracted by using the command lapply(LIST,"[",3).

How do you get a specific column in a list Python?

Using numpy.ndarray.tolist() From the dataframe we select the column “Name” using a [] operator that returns a Series object and uses Series. Values to get a NumPy array from the series object. Next, we will use the function tolist() provided by NumPy array to convert it to a list.

How do you extract a column from a Dataframe in a list in R?

$ operator in R is used to extract a specific part of data or access a variable in a dataset. We can pass data frame column to a list by using $ operator. The columns to be selected are to be passed with dataframe name separated by $.


2 Answers

You can use List Comprehension : -

newList = [[each_list[i] for i in list1] for each_list in list2]
like image 176
Rohit Jain Avatar answered Oct 07 '22 23:10

Rohit Jain


If you are happy with a list of tuples, you can use operator.itemgetter

import operator
list1 = [0,2]
my_items = operator.itemgetter(*list1)
new_list = [ my_items(x) for x in list2 ]

(or you could use map here):

new_list = map(my_items, list2)

and as a 1 liner:

new_list = map(operator.itemgetter(*list1), list2)

operator.itemgetter probably has a slight performance advantage over nested list-comprehensions, but it's likely to be small enough that it's not worth worrying about.

like image 43
mgilson Avatar answered Oct 07 '22 23:10

mgilson