Choose axis for assignment into NumPy array programmatically
I have a 3D numpy array.
I can modify arbitrary element using simple indexing
D[:,:,0]=myval
D[:,:10,1]=list(range(10))
Sometimes I need to change element(s) at a given index and it is not predetermined at which axis the index refers. I would like to catch the two following cases with a change in variable
D[:,:10,1]=list(range(10)) >axis 1
D[:10,:,1]=list(range(10)) >axis 0
Something like:
f(D,axis=0/1,index=1,newval)
1 answer

I'd use an indexing tuple with slice objects prepared by the helper object
np.s_
. Ifaxis
is 0 or 1, the following has the effect of assigninglist(range(10))
to eitherD[:10, :, 1]
orD[:, :10, 1]
.idx = [np.s_[:], np.s_[:], 1] idx[axis] = np.s_[:10] D[tuple(idx)] = list(range(10))
See also questions close to this topic

Groupby column keep multiple rows with minimum value
I have a dataframe consisting of two columns with id's and one column with numerical values. I want to groupby the first id column and keep all the rows corresponding to the smallest values in the second column, so that I keep multiple rows if needed.
This is my pandas dataframe
id id2 num1 1 1 9 1 1 4 1 2 4 1 2 3 1 3 7 2 6 9 2 6 1 2 6 5 2 9 3 2 9 7 3 2 8 3 4 2 3 4 7 3 4 9 3 4 10
What I want to have is:
id id2 num1 1 1 9 1 1 4 2 6 9 2 6 1 2 6 5 3 2 8
I have tried to keep the max value, find the idxmax() or remove duplicates but this ends up with only one row per id1 and id2.
firstS.groupby('id1')['id2'].transform(min)
Many thanks in advance!

Create RDD or Dataframe using pyspark for list of csv files where 1st row of each file is to be removed
My CSV File looks like this:
"ABC_REPORT (Jan 16, 2019)"
Cid,Aid,Time zone,View,Active,Impressions,Measurable
abc,abc_tea,(GMT05:00) Eastern Time,0,0.00%,0,0.00%
I am using pyspark to remove first line and read schema from second line. I have list of csv files which I have to read all have same schema and first line. But failed to do so.
Any suggestions?
Output I want:
Cid,Aid,Time zone,View,Active,Impressions,Measurable
abc,abc_tea,(GMT05:00) Eastern Time,0,0.00%,0,0.00%
I tried using pyspark but not able to create RDD for list of files. Also, I tried filter and subtract methods to remove first line from Rdd for one file,still not able to.

Python cosine_similarity doesn't work for matrix with NaNs
Need to find python function that works like this R func:
proxy::simil(method = "cosine", by_rows = FALSE)
i.e. finds similarity matrix pairwise calculating cosine distance between dataframe rows. If NaNs are present, it should drop exact columns with NaNs in these 2 rows

ESLint: Assignment to property of function parameter
Given a structure like:
products: { '123': { details: [ { price: 45, unitPrice: 0, productName: 'apples' } ] } }
And a function,
function modifyPriceForApples(coefficient) { const products = cloneDeep(vehicleProductSelector.getAllProducts(store.getStore().getState())); let appleProduct; Object.keys(products).forEach((productId) => { const { details } = vehicleProducts[productId]; details.forEach((detail) => { const { price, productName } = detail; if (productName === 'apples') { detail.unitPrice = coefficient * detail.price; appleProduct = products[productId]; } }); }); return appleProduct; }
I am getting linting error:
Assignment to property of function parameter
How can I resolve that, barring disabling the linting rule?
I keep seeing array destructuring as the answer to this problem, however I'm not too sure what that would look like in practice given that this is a pretty complex structure.

PHP Array  Build in same format as original json_decode
I have an array in
PHP
that looks like this..Array ( [0] => stdClass Object ( [myId] => 55 [mydata] => stdClass Object ( [height] => 6 [weight] => 76 [class] => 45 [skill] => 455 ) [inventory] => stdClass Object ( [food] => stdClass Object ( [bread] => 33 [water] => 27 ) [books] => stdClass Object ( [magic] => 3 [medical] => 122 ) ) ) )
The array is generated by the command..
$myarray = (array)json_decode($results);
My problem is that I am no longer receiving the data in a format that I can
json_decode
.I need to generate this exact array using
PHP
instead, does anyone have an example they can show me? 
JQUERY  remove array from a multidimensional array with key
I am trying to remove an array in a multidimensional array if the id is the same off the given one.
var test_arr = [{"name":"qqq", "city":"it","id":"123456"}, {"name":"ggg", "city":"uk","id":"777456"}]; var result = test_arr.filter(function(v,i) { if (v[0] === '123456'){ test_arr.splice(i,1) } }); //alert( test_arr[0].id) alert(result)
http://jsfiddle.net/ofLg0vq5/2/
How Could I do this?

Convert NaN values in numpy array to mean of values
I have a numpy array called heart_rate of shape (1181,) and dtype float.
In my data there is occasionally the word None.
I would like to get rid of this and replace it with the average of the data values. When I try and run the following code:inds = np.where(np.isnan(heart_rate))
But I am getting TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

value error bad input shape :y(200,2) in SKLEARN.SVM
I am doing NMF decomposition ( training images X(BENIGN100 AND MALIGNANT100) into two nonnegative matrices W and H) to extract fatures .I did the decomposition for each channel of images X(r),X(g),X(b) into W(r),W(g),W(b) and H(r),H(g),H(b) and merge the channel to get W_train(r,g,b) and H_train(r,g,b)
i am getting bad input shape error .pls help and guide me
W_train(200, 30)(NMF decomposition of X into W and H,for training i am passing W in SVM) Y_train(200,2) from sklearn.svm import SVC
classifier = SVC (kernel='linear',random_state=0)
classifier.fit(W_train,Y)
~\Anaconda3\lib\sitepackages\sklearn\svm\base.py in fit(self, X, y, sample_weight) 147 self._sparse = sparse and not callable(self.kernel) 148 > 149 X, y = check_X_y(X, y, dtype=np.float64, order='C', accept_sparse='csr') 150 y = self._validate_targets(y) 151
~\Anaconda3\lib\sitepackages\sklearn\utils\validation.py in check_X_y(X, y, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, warn_on_dtype, estimator) 576 dtype=None) 577 else: > 578 y = column_or_1d(y, warn=True) 579 _assert_all_finite(y) 580 if y_numeric and y.dtype.kind == 'O':
~\Anaconda3\lib\sitepackages\sklearn\utils\validation.py in column_or_1d(y, warn) 612 return np.ravel(y) 613 > 614 raise ValueError("bad input shape {0}".format(shape))
ValueError: bad input shape (200, 2)

how to fix numpy log inf values and RuntimeWarning
I am calculating free energy G = RT ln(1Y/Y)
Y is a numpy ndarray
problem is when element of Y = 1 or 0.
try: log_value = np.log((1Y)/Y) except ZeroDivisionError as e: log_value = 1 except RuntimeWarning: log_value = 1 Z = 0.0083145*X*log_value
if Y = 1 ln gives Runtime error and value as inf (i want ln to return 1)
if Y = 0 ln gives ZeroDivisionError: (i want ln to return 1)