0

Coming from R to Python and I see why so many people love Python for data science. One useful feature of R is the quick subsetting. For example:

my_data = c(11,34,67,134,45,8,99,3543,1)
my_subset = c(3,8,1,6,4)
print(my_data[my_subset])
[1]  67  3543  11  8  134

One can programmatically generate subsets that satisfy various conditions and filter the data to that subset with a single instruction. How does one accomplish this in python?

2
  • 1
    If you have NumPy array, arr = np.array([11,34,67,134,45,8,99,3543,1]); idx = np.array([3,8,1,6,4]); arr[idx-1] should do it, Output -> array([ 67, 3543, 11, 8, 134]) Commented Feb 27, 2021 at 4:21
  • Beautiful! Thanks Commented Feb 27, 2021 at 4:23

1 Answer 1

1

I'll go ahead and point out the obvious one-liner:

data = (11,34,67,134,45,8,99,3543,1)
indices = (3,8,1,6,4)
subset = [data[i] for i in indices]
print(subset)

Output:

[134, 1, 34, 99, 45]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.