I am trying to access the last index of an array in an array.
this is my code:
aray = np.genfromtxt(input_file, skip_header=1)
#everything but the last index
input_array = aray[:,:-1]
#the last index
price_array = aray[:,-1]
This is the original array:
[
[ 25. 2. 50. 1. 500. 127900.]
[ 39. 3. 10. 1. 1000. 222100.]
[ 13. 2. 13. 1. 1000. 143750.]
[ 82. 5. 20. 2. 120. 268000.]
[ 130. 6. 10. 2. 600. 460700.]
[ 115. 6. 10. 1. 550. 407000.]
]
This is everything but the last index:
[
[ 25. 2. 50. 1. 500. 127900.]
[ 39. 3. 10. 1. 1000. 222100.]
[ 13. 2. 13. 1. 1000. 143750.]
[ 82. 5. 20. 2. 120. 268000.]
[ 130. 6. 10. 2. 600. 460700.]
[ 115. 6. 10. 1. 550. 407000.]
]
This is what I get when I try to get the last index of every array in the array:
[127900. 222100. 143750. 268000. 460700.]
As you can see I lose the last number for some reason. How do I avoid losing the it?
I tried changing
price_array = aray[:,-1]
to
price_array = aray[:,:-1]
So that it would remove everthing other than the last index of the array, Which did not work as it returned everything but the last index of every array while also removing the last sub-array.
[[ 25. 2. 50. 1. 500.]
[ 39. 3. 10. 1. 1000.]
[ 13. 2. 13. 1. 1000.]
[ 82. 5. 20. 2. 120.]
[ 130. 6. 10. 2. 600.]]
You have a 2D NumPy array, you're actually extracting the last column of the 2D array, not the last element of each sub-array. Here's how you can do it.
price_array = aray[:, -1]
price_array = price_array.flatten()
price_list = price_array.tolist()