Home > Back-end >  Selecting a range of columns in Python without using numpy
Selecting a range of columns in Python without using numpy

Time:12-04

I want to extract range of columns. I know how to do that in numpy but I don't want to use numpy slicing operator.

import numpy as np

a = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
arr = np.array(a)

k = 0

print(arr[k:, k 1]) # --> [2 7]
print([[a[r][n 1] for n in range(0,k 1)] for r in range(k,len(a))][0]) # --> [2]

What's wrong with second statement?

CodePudding user response:

You're overcomplicating it. Get the rows with a[k:], then get a cell with row[k 1].

>>> [row[k 1] for row in a[k:]]
[2, 7]

CodePudding user response:

a = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
k = 0
print(list(list(zip(*a[k:]))[k 1])) # [2, 7]

CodePudding user response:

Is this what you're looking for?

cols = [1,2,3] # extract middle 3 columns
cols123 = [[l[col] for col in cols] for l in a]
# [[2, 3, 4], [7, 8, 9]]
  • Related