Can I append specific values from one array to another? - python

I have successfully imported a CSV file into a multi-dimensional array in python. What I want to do now is pick specific values from the array and put them into a new single array. For instance if my current arrays were:
[code1, name1, number 1]
[code2, name2, number 2]
I want to select only the code1 and code 2 values and insert them into a new array, because I need to compare just those values to a user input for validation. I have tried using the following:
newvals=[]
newvals.append oldvals([0],[0])
where newvals is the new array for just the codes, oldvals is the original array with all the data and the index [0],[0] refers to code 1, but I'm getting a syntax error. I can't use any add ons as they will be blocked by my admin.

newvals = []
for i in oldvals:
newvals.append(i[0])

Usually you can get the first Element in an array a with a[0].
You can create a new array based on another by using the "array for in" syntax
oldData = [[1,2,3],[4,5,6]]
newData = [x[0] for x in oldList]
# newData is now [1,4]

Related

How to find a specific column from a list of arrays

I have a list of multidimensional arrays and need to calculate the mean for each dimension. I want to extract column[1] data as a list and send it as a parameter to a method in python. Here is my data:
[array([2.33700000e+06, 4.16779479e-01, 9.31000000e-04, 1.99000000e-13,0.00000000e+00, 0.00000000e+00]), array([2.33700000e+06,4.16779479e-01, 9.31000000e-04, 1.99000000e-13,0.00000000e+00, 0.00000000e+00])]
and I want to do some operations for column[1] data like doing an operation on [4.16779479e-01,4.16779479e-01]. How can I do it in python?
You question looks like you are just trying to process the columns of a matrix. If it is an N by M matrix and you have your matrix stored in a variable called my_mat you could do something like
for i in range(len(my_mat[0])):
col = [arr[i] for arr in my_mat]
# process your column.

How to index from a list nested in an array?

I have a variable which returns this:
array(list([0, 1, 2]), dtype=object)
How do I index from this? Everything I have tried throws an error.
For reference, some code that would produce this variable.
import xarray as xr
x = xr.DataArray(
[[0,1,2],
[3,4]]
)
x
I guess before anyone asks, I am trying to test if xarray's DataArrays is a suitable way for me to store session-based data containing multiple recordings saved as vectors/1D arrays, but each recording/array can vary in length. That is why the DataArray doesn't have even dimensions.
Thanks
I used the code given by you to create the x variable. I was able to retrieve the lists using following code:
for arr in x:
print(arr.item())
Basically, you have to call .item() on that array to retrieve the inner list.

Iterating over for loop & apply np.union1d

I would like to do np.union1d by iterating over a for loop.
Here is the code I'm using:
arr = np.empty((1,), dtype=np.int32)
for i in range(2):
arr = np.union1d(arr, data[df.iloc[i,7]])
data is a dictionary, from which I want to pull value based on keys defined in 8th column of my data frame df. Sorry, I won't able to provide you more details for data & df because of business confidentiality. After running this loop I'm seeing arr is showing empty array while data[df.iloc[i,7]] is generating array of around 10K size for each iteration. Can you please let me know what I'm doing wrong?
Just to be sure, check that your code isn't actually something like this:
for i in range(2):
arr=np.empty((1,), dtype=np.int32)
arr=np.union1d(arr, data[df.iloc[i,7]])
If not, I'd debug in the following way
for i in range(2):
new_arr = data[df.iloc[i,7]]
print(type(new_arr)) # check that it's an array
print(new_arr.shape) # check that first dim > 1, second dim = 1
Once you get this working I'd also suggest initializing arr = [] because np.empty initializes the array by placing a very very small value as a placeholder so it will be present in your final concatenated array!

How can I access an array with an array of indexes in python?

I would like to access a multidimensional python array with an array of indexes, using the whole array to index the target element.
Let me explain it better:
A = np.arange(4).reshape(2,2)
a = [1,1]
>>> A[a[0],a[1]]
3
My intention is to pass the array without hard-coding the indexes values and get the same result, that is the value A[1,1]. I tried but the only way I found is working differently:
>>> A[a]
array([[2, 3],
[2, 3]])
What results is the construction of a new array where each value of the index array selects one row from the array being indexed and the resultant array has the resulting shape (number of index elements, size of row).
Thank you.
Pass a tuple (not a list) to __getitem__ (the [..] indexer).
A[tuple(a)]
3

Python - split matrix data into separate columns

I have read data from a file and stored into a matrix (frag_coords):
frag_coords =
[[ 916.0907976 -91.01391344 120.83596334]
[ 916.01117655 -88.73389753 146.912555 ]
[ 924.22832597 -90.51682575 120.81734705]
...
[ 972.55384732 708.71316138 52.24644577]
[ 972.49089559 710.51583744 72.86369124]]
type(frag_coords) =
class 'numpy.matrixlib.defmatrix.matrix'
I do not have any issues when reordering the matrix by a specified column. For example, the code below works just fine:
order = np.argsort(frag_coords[:,2], axis=0)
My issue is that:
len(frag_coords[0]) = 1
I need to access the individual numbers of the first row individually, I've tried splitting it, transforming it into a list and everything seems to return the 3 numbers not as columns but rather as a single element with len=1. I need help please!
Your problem is that you're using a matrix instead of an ndarray. Are you sure you want that?
For a matrix, indexing the first row alone leads to another matrix, a row matrix. Check frag_coords[0].shape: it will be (1,3). For an ndarray, it would be (3,).
If you only need to index the first row, use two indices:
frag_coords[0,j]
Or if you store the row temporarily, just index into it as a row matrix:
tmpvar = frag_coords[0] # shape (1,3)
print(tmpvar[0,2]) # for column 2 of row 0
If you don't need too many matrix operations, I'd advise that you use np.arrays instead. You can always read your data into an array directly, but at a given point you can just transform an existing matrix with np.array(frag_coords) too if you wish.

Categories