1

I have a numpy array that looks like the following:

np.array([
[23, 12, 4, 103, 87, 0.6],
[32, 18, 3, 120, 70, 0.6],
[43, 12, 8, 109, 89, 0.4],
[20, 13, 7, 111, 77, 0.8]
])

I want to transform this array where the last column becomes its own array, such that it will look like this:

np.array([
[[23, 12, 4, 103, 87], [0.6]],
[[32, 18, 3, 120, 70], [0.6]],
[[43, 12, 8, 109, 89], [0.4]],
[[20, 13, 7, 111, 77], [0.8]]
])

What would be the best way to go about this? I am relatively new to Python and have tried out some loops but to no avail. Thanks!

1
  • It seems like what you really want is a list, not a np.array Commented Apr 8, 2017 at 21:55

1 Answer 1

1

numpy requires consistent dimensions in its array; that would give two different sizes. You can either use two separate variables (i.e. parallel arrays):

X = data[:, :-1]
y = data[:, -1]

X = np.array([
[23, 12, 4, 103, 87],
[32, 18, 3, 120, 70],
[43, 12, 8, 109, 89],
[20, 13, 7, 111, 77],
])


y = np.array([
0.6, 0.6, 0.4, 0.8
])

Or you can store a list of pairs:

my_list = [(row[:-1], [row[-1]]) for row in data]
my_list = [
([23, 12, 4, 103, 87], [0.6]),
([32, 18, 3, 120, 70], [0.6]),
([43, 12, 8, 109, 89], [0.4]),
([20, 13, 7, 111, 77], [0.8])
]

The best strategy depends on your use case.

Sign up to request clarification or add additional context in comments.

3 Comments

This question isn't an exact duplicate, so there's some additional insight to be found here: stackoverflow.com/questions/3386259/…
I tried using this, but it didn't print the last column as its own array. This is what I got: [ ([23, 12, 4, 103, 87], 0.6), ([32, 18, 3, 120, 70], 0.6), ([43, 12, 8, 109, 89], 0.4), ([20, 13, 7, 111, 77], 0.8) ]
Be sure to include the brackets: [row[-1]]. They're critical.

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.