Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
2,400
42,460,530
How do I make keras predict something other than a one-hot matrix?
<p>I have a dictionary of 122 unique values. I'm feeding the program over 45,000 records with 33 data points to refer to when making a prediction about what the output should be. What I've noticed is that it's only predicting <code>[[1.]...]</code>. I need it to predict 1's 2's 3's ... up until 122. All are floats as w...
<p>Your model is wrong in this case, change it to:</p> <pre><code>model = Sequential() model.add(Dense(12, input_dim=7, init='uniform', activation='relu')) model.add(Dense(7, init='uniform', activation='relu')) model.add(Dense(122, init='uniform', activation='softmax')) model.compile(loss='categorical_crossentropy', ...
python|pandas|numpy|keras
6
2,401
42,250,340
RuntimeError: No C++ shape function registered for standard op: NearestNeighbors
<p>Update:- Please try this code:-</p> <pre><code>from tensorflow.contrib.learn.python.learn.estimators import kmeans as kmeans_lib import random import numpy as np x = np.array([[random.random() for i in range(198)] for j in range(2384)]) km = kmeans_lib.KMeansClustering(num_clusters=200) km.fit(x) </code></pre> <p>...
<p>Open "Lib\site-packages\tensorflow\contrib\factorization\python\ops\gen_clustering_ops.py"</p> <p>Add</p> <pre><code>ops.RegisterShape("NearestNeighbors")(None) </code></pre> <p>For any error like this, fix it in this way.</p>
python|python-3.x|machine-learning|tensorflow|k-means
0
2,402
69,946,381
Python data data conversion
<p>Please help with the below request:</p> <p>need to clean up below df to df_1: 'SKU' has multiple required data, and this column needs to be exploded to multiple rows</p> <pre><code>df = pd.DataFrame([[1,'NaN','abj','1/1/2021'], [2,'[{&quot;Result&quot;:&quot;00018&quot;},{&quot;Result&quot;:&quot;0006...
<p>If all records are following the same pattern, this should clean it for you.</p> <p>Beware that the code below is modifying <em>df</em>.</p> <pre><code>import pandas as pd import json import numpy as np def clean_SKU(x): if pd.isna(x) or x == &quot;&quot; or x == &quot;NaN&quot;: return x else: ...
python|pandas
0
2,403
69,758,754
Sum all elements in a column in pandas
<p>I have a data in one column in Python dataframe.</p> <pre><code>1-2 3-4 8-9 4-5 6-2 3-1 4-2 1-4 </code></pre> <p>The need is to sum all the data available in that column.</p> <p>I tried to apply below logic but it's not working for list of list.</p> <pre><code>lst=[] str='5-7 6-1 6-3' str2 = str.split(' ') for ele i...
<p>I think we can do a split</p> <pre><code>df.col.str.split(' |-').map(lambda x : sum(int(y) for y in x)) Out[149]: 0 27 1 17 2 15 Name: col, dtype: int64 </code></pre> <p>Or</p> <pre><code>pd.DataFrame(df.col.str.split(' |-').tolist()).astype(float).sum(1) Out[156]: 0 27.0 1 17.0 2 15.0 dtype: flo...
python-3.x|pandas|dataframe
3
2,404
69,959,127
I want to 2 decimal points result for predicts on Python
<p>My outputs have too much decimal points. But I want to 2 points float results. Can you help me?</p> <p>EX: <code>42.44468745 -&gt; 42.44 </code></p> <pre><code>y_pred=ml.predict(x_test) print(y_pred) </code></pre> <p>Output:</p> <pre><code>[42.44468745 18.38280575 7.75539511 19.05326276 11.87002186 26.89180941 18....
<p>Use <code>round(num, round_decimal)</code> For example:</p> <pre><code>num = 42.44468745 print(round(num, 2)) </code></pre> <p>Output:</p> <pre><code>42.44 </code></pre>
python|scikit-learn|floating-point|predict|sklearn-pandas
0
2,405
43,390,222
One sided t-test for linear regression?
<p>I have problems with this. I am trying to do a linear regression and test the slope. The t-test checks if the slope is far away from 0. The slope can be negative or positive. I am only interested in negative slopes.</p> <p>In this example, the slope is positive which I am not interested in, so the P value should be...
<p>p-value for the two-way t-test is calculated by:</p> <pre><code>import scipy.stats as ss df = regression_results.df_resid ss.t.sf(regression_results.tvalues[0], df) * 2 # About the same as (1 - cdf) * 2. # see @user333700's comment Out[12]: 0.02903685649821508 </code></pre> <p>Your modification would just be:</p> ...
python|pandas|scikit-learn|statsmodels|t-test
3
2,406
43,094,084
hdf to ndarray in numpy - fast way
<p>I am looking for a fast way to set my collection of hdf files into a numpy array where each row is a flattened version of an image. What I exactly mean:</p> <p>My hdf files store, beside other informations, images per frames. Each file holds 51 frames with 512x424 images. Now I have 300+ hdf files and I want the im...
<p>Do you really wan't to load all Images into the RAM and not use a single HDF5-File instead? Accessing a HDF5-File can be quite fast if you don't make any mistakes (unnessesary fancy indexing, improper chunk-chache-size). If you wan't the numpy-way this would be a possibility:</p> <pre><code>os.chdir(os.getcwd()+"\\...
python|numpy|hdf5|h5py
1
2,407
43,317,675
How to generate a cyclic sequence of numbers without using looping?
<p>I want to generate a cyclic sequence of numbers like: <code>[A B C A B C]</code> with arbitrary length <code>N</code> I tried:</p> <pre><code>import numpy as np def cyclic(N): x = np.array([1.0,2.0,3.0]) # The main sequence y = np.tile(x,N//3) # Repeats the sequence N//3 times return y </code></pre> <...
<p>You can just use <code>numpy.resize</code></p> <pre><code>x = np.array([1.0, 2.0, 3.0]) y = np.resize(x, 13) y Out[332]: array([ 1., 2., 3., 1., 2., 3., 1., 2., 3., 1., 2., 3., 1.]) </code></pre> <p>WARNING: This is answer does not extend to 2D, as <code>resize</code> flattens the array before repeat...
python|numpy|vectorization
5
2,408
72,200,158
How can i set the right shape to make predictions for my CNN model?
<p>i'm having some problem with prediction phase of my image Classiffier Model in Python. With the input image size of 128x128 i created model with a model like this:</p> <pre><code>model = Sequential() model.add(Conv2D(32,3,padding=&quot;same&quot;, activation=&quot;relu&quot;, input_shape=(128,128,3))) model.add(MaxP...
<p>You are using a (128,128, 1) image as input. Indeed, you use <code>cv2.COLOR_BGR2GRAY</code> converting your image to grayscale (hence 1 channel).</p> <p>The error tells you it cannot reshape 16384 (=128x128) into (128,128,3).</p>
python|tensorflow|keras|reshape|image-classification
0
2,409
50,556,642
Remembering original image after patch extraction
<p>I apologize if this is too general. I am using the PatchExtractor function in scikit-learn to convert images - an array of size = (n_images x image_height x image_width) - into patches, so the resulting array has size = (n_patches, patch_height, patch_width). </p> <p>However, with this function I lose track of whic...
<p>The patches are extracted from images in sequence, so, if you know the count of images, and patches, you can know which patch if from which image:</p> <pre><code>import numpy as np from sklearn.feature_extraction import image images = np.zeros((5, 4, 4, 3)) images[:] = np.arange(5).reshape(-1, 1, 1, 1) patches = im...
python|image|numpy|scikit-learn
1
2,410
50,475,183
Converting a numpy array into a dict of values mapped to rows
<p>Consider that I have a 2D numpy array where each row represents a unique item and each column within the row represents a label assigned to this item. For example, a 10 x 25 array in this instance would represent 10 items, each of which have up to 25 labels each.</p> <p>What would be most efficient way to convert t...
<p><strong>UPDATE</strong>: added ordering by length.</p> <p>We can use advanced indexing to create a grid indexed by items and labels. We can then iterate over columns and use <code>flatnonzero</code> to get the item id's:</p> <pre><code>&gt;&gt;&gt; ex = [[1, 2, 3], ... [1, 0, 0], ... [1, 3, 0]] &gt;&gt...
python|arrays|numpy|dictionary|scipy
4
2,411
50,395,651
Why accessing values in dataframe and list are different?
<p>Suppose I have a list a defined as: <code>a =[[1,2,3,4],[5,6,7,8]]</code>; then <code>a[0]</code> returns the first element in the list: <code>[1,2,3,4]</code>.</p> <pre><code>df = pd.DataFrame([[1,2,3,4],[5,6,7,8]]) </code></pre> <p><code>df</code> is represented as</p> <pre><code>0 | 1 2 3 4 1 | 5 6 7 8 </code>...
<p><code>df[x]</code> accesses column(s) named <code>x</code>.</p> <p><code>df.loc[y]</code> access row(s) with index <code>y</code>.</p> <p>This is an issue with syntax, not how data is stored internally by <code>pandas</code>.</p> <p>You should read <a href="https://pandas.pydata.org/pandas-docs/stable/indexing.ht...
python|pandas|dataframe
3
2,412
50,658,884
Why this numba code is 6x slower than numpy code?
<p>Is there any reason why the following code run in 2s,</p> <pre><code>def euclidean_distance_square(x1, x2): return -2*np.dot(x1, x2.T) + np.expand_dims(np.sum(np.square(x1), axis=1), axis=1) + np.sum(np.square(x2), axis=1) </code></pre> <p>while the following numba code run in 12s?</p> <pre><code>@jit(nopytho...
<blockquote> <p>It is quite weird that numba can be so much slower. </p> </blockquote> <p>It's not too weird. When you call NumPy functions inside a numba function you call the numba-version of these functions. These can be faster, slower or just as fast as the NumPy versions. You might be lucky or you can be unluck...
python|numpy|numba
29
2,413
62,528,153
How to convert text table to dataframe
<p>I am trying to scrape the &quot;PRINCIPAL STOCKHOLDERS&quot; table from the link<a href="https://www.sec.gov/Archives/edgar/data/1034239/0000950124-97-003372.txt" rel="nofollow noreferrer">text file</a>and convert it to a csv file. Right now I am only half successful. Namely, I can locate the table and parse it but ...
<p>I think what you need to do is</p> <pre><code>pd.DataFrame.from_dict(dict_table) </code></pre> <p>instead of</p> <pre><code>pd.DataFrame(dict_table) </code></pre>
python|pandas|dataframe|parsing
0
2,414
62,702,691
ValueError: Input contains NaN, infinity or a value too large for dtype('float64'). sklearn
<p>Here is my My code:</p> <pre><code>import pandas as pd df = pd.read_csv('train.csv') gender_dict = {&quot;male&quot;: 1, &quot;female&quot;: 2} eye_color_dict = {&quot;amber&quot;: 1, &quot;blue&quot;: 2, &quot;brown&quot;: 3, &quot;gray&quot;: 4, &quot;green&quot;: 5, &quot;hazel&quot;: 6} race_dict = {&quot;blac...
<p>Looks like the column <code>hours_worked_each_week</code> contains nulls.</p> <p>Do you get the same error if you drop that column:</p> <pre><code>X = df.drop(['infected', 'hours_worked_each_week'], axis=1).values </code></pre> <p>Alternatively, you can replace nulls with 0</p> <pre><code>df.fillna(0,inplace=True) <...
python|pandas|scikit-learn|jupyter-notebook
0
2,415
54,351,641
Skip the first group in a grouped dataframe
<p>I have a pandas df that I have grouped, like so:</p> <p><code>gQ = df.groupby('Date', as_index=False)['Quantity']</code></p> <p>and it returns:</p> <p><code> 0 0 135.68 1 1054.68 2 101.12 1 3 131.74 4 1025.47 5 97.40 2 6 1078.07 7 101.93 3 8 1075.92 ...
<p>Use MultiIndex and levels - see <a href="https://pandas.pydata.org/pandas-docs/stable/advanced.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/advanced.html</a> - there are many examples: choose the best for your needs. BR</p>
python|pandas|dataframe|pandas-groupby
0
2,416
73,625,459
What does self(variable) do in Python?
<p>I'm trying to understand someone else's code in Python and I stumbled across a line I don't quite understand and which I can't find on the internet:</p> <pre><code>x=self(k) </code></pre> <p>with k being a torch-array. I know what self.something does but I haven't seen self(something) before.</p>
<p><code>self</code>, for these purposes, is just a variable like any other, and when we call a variable with parentheses, it invokes the <code>__call__</code> magic method. So</p> <pre><code>x = self(k) </code></pre> <p>is effectively a shortcut for</p> <pre><code>x = self.__call__(k) </code></pre> <hr /> <p>Footnote:...
python|oop|pytorch|self
3
2,417
73,610,419
Taking multiple slices of numpy 1d array from given indices, copying result into 2d array
<p>New to Python. Given in the code snippet below is a numpy 1d array called <em>randomWalk</em>. Given indices (which can be interpreted as start dates and end dates, both of which may vary from item to item), I want to do take multiple slices from that 1d array <em>randomWalk</em> and arrange the results in a 2d arra...
<p>If the vectorization is the goal, so it is done by <a href="https://stackoverflow.com/a/73616900/13394817">Pig answer</a>, If it is not matter (as it is mentioned by the OP in the <a href="https://stackoverflow.com/questions/73610419/taking-multiple-slices-of-numpy-1d-array-from-given-indices-copying-result-into#com...
python|arrays|numpy|performance|vectorization
0
2,418
71,240,439
Reindexing only valid with uniquely valued Index objects
<p>Irun this code</p> <pre><code>esg_fm_barron = pd.concat([barron_clean.drop(columns = &quot;10 year return&quot;, inplace = False),ESG_fixed.drop(columns = 'Name',inplace = False), financial_clean.drop(columns = 'Name',inplace = False)], axis = 'columns', join = 'inner') esg_fm_barron.rename(columns={'Average (Curren...
<p>When you run <em>pd.concat</em>, each source DataFrame must have unique index.</p> <p>First identify which source DataFrame has a non-unique index. For each source DataFrame (assuming it is <em>df</em>) run:</p> <pre><code>df.index.is_unique </code></pre> <p>(this is a <strong>property</strong>, not a method, so put...
pandas|indexing|merge|concatenation|drop
3
2,419
71,260,909
Pandas dataframe writing to excel as list. But I don't want data as list in excel
<p>I have a code which iterate through excel and extract values from excel columns as loaded as list in dataframe. When I write dataframe to excel, I am seeing data with in [] and quotes for string ['']. How can I remove [''] when I write to excel. Also I want to write only first value in product ID column to excel. ho...
<pre><code>df_t['id'] = df_t['id'].str[0] # this is a shortcut for if you only want the 0th index df_t['other_columns'] = df_t['other_columns'].apply(lambda x: &quot; &quot;.join(x)) # this is to &quot;unlist&quot; the lists of lists which you have fed into a pandas column </code></pre>
python|pandas
0
2,420
71,348,855
return Cosine Similarity not as single value
<p>How can I make a pure NumPy function that will return an array of the shape of the 2 arrays with the cosine similarities of all the pairwise comparisons of the rows of the input array?</p> <p>I don't want to return a single value.</p> <pre><code>dataSet1 = [5, 6, 7, 2] dataSet2 = [2, 3, 1, 15] def cosine_similarity...
<p>You can use <code>scipy</code> for this as stated in <a href="https://stackoverflow.com/questions/18424228/cosine-similarity-between-2-number-lists">this answer</a>.</p> <pre><code>from scipy import spatial dataSet1 = [5, 6, 7, 2] dataSet2 = [2, 3, 1, 15] result = 1 - spatial.distance.cosine(dataSet1, dataSet2) </c...
python|numpy
0
2,421
71,422,177
Squeeze dataframe rows with missing values
<p>I'd like to squeeze a dataframe like this:</p> <pre><code>import pandas as pd import numpy as np df1 = pd.DataFrame([[1,pd.NA,100],[2,20,np.nan],[np.nan,np.nan,300],[pd.NA,&quot;bla&quot;,400]], columns=[&quot;A&quot;,&quot;B&quot;,&quot;C&quot;]) df1 A B C 0 1 &lt;NA&gt; 100.0 1 2 20 ...
<p>You can <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>apply</code></a> a function with <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.dropna.html" rel="nofollow noreferrer"><code>dropna</code></a> to remove the NaN and <a href...
python|pandas|dataframe
4
2,422
71,140,439
add suffix based on multiple conditions from string values in another column
<p>I would like to add a suffix to strings in one column when a condition is met in another column. If a value is present in &quot;Market&quot; column, &quot;Symbol&quot; column corresponding value is updated to include current ticker but I would like to add a suffix to it representing its market place. I guess I could...
<p>You need to proceed in 3 steps</p> <ol> <li><p>You need to define an exhaustive suffix_list - a dictionary that holds information only once for each market</p> <p><code>suffix_list = pd.DataFrame({'Market': ['Oslo', 'Paris'], 'suffix':['OL','PA']})</code></p> </li> <li><p>You want to merge the <code>suffix_list</cod...
python|pandas|dataframe|multiple-conditions|suffix
0
2,423
60,642,537
Report training loss for a specific sample in train dataset, not the average one in the training process (TensorFlow)
<p>I'm training an LSTM model using TensorFlow. We know that in the process of training, the is a report for <code>loss</code> and <code>val_loss</code> for every epoch which are the average of losses for train and test datasets. I'm intended to follow the loss of a specific sample in the train dataset (specific date)....
<p>Here is the code for tracking loss for a single sample: </p> <pre><code>import tensorflow as tf import numpy as np import keras x = tf.Variable(initial_value=np.ndarray(shape=(10, 10), dtype=np.float32)) # your sample input y =np.random.randint(0, 9, size=(10, )) # your sample label y_labels = keras.utils.to_c...
python|tensorflow|keras|lstm|epoch
1
2,424
72,762,543
Sort index list in same way as list of pandas dataframes is sorted by length in python?
<p>Based on my question <a href="https://stackoverflow.com/questions/72760325/sort-or-remove-elements-from-corresponding-list-in-same-way-as-in-reference-list#72760325">here</a> and <a href="https://stackoverflow.com/questions/72761755/sort-list-of-pandas-dataframes-by-row-count/72761757#72761757">here</a> I want to so...
<p>Found some more or less complicated solution:</p> <pre><code>import pandas as pd import numpy as np df1 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['a', 'b', 'c']) df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [11, 12, 13]]), columns=['a...
python|pandas|dataframe|sorting
1
2,425
72,704,462
Find and replace using * equivalent in pandas dataframe
<p>I want to replace the string &quot;Private room in house&quot; with &quot;Private&quot; in a column in a dataframe</p> <p>I have tried</p> <pre><code>df['room'] = df['room'].str.replace(&quot;Private[]&quot;,&quot;Private&quot;) </code></pre> <p>putting all the various regular expression characters in the [] but no...
<p>You can use:</p> <pre><code>df['room'] = df['room'].str.replace('Private.*','Private', regex=True) </code></pre> <p>Or with a look behind:</p> <pre><code>df['room'] = df['room'].str.replace('(?&lt;=Private).*', '', regex=True) </code></pre>
python|pandas|string
3
2,426
72,712,975
keras target_size and PIL resize inconsistency issue
<p>do anyone have idea why the two outputs below are different</p> <p>in 1st code block image is loaded and PIL resize used. while in 2nd block keras load_img parameter: target_size is used. for same steps it is giving different output.</p> <pre><code>from keras.preprocessing.image import load_img import numpy as np p...
<p>thanks I'mahdi. but target_size is also intended to load an resized image. <br> got the solution: Keras load_img default interpolation is NEAREST(0) and that of PIL.resize is BICUBIC(3). hence that ambiguity.</p> <p>change in code block 1:</p> <pre><code>image = image.resize(target_size, resample=0) </code></pre> <p...
python|tensorflow|image-processing|keras
0
2,427
72,792,586
Replace None in pandas data frame with Null
<p>I have a pandas dataframe and I am getting None for many values. I need to write it to SQL server DB and want to update it with Null. How can i do that?</p> <p>I cannot use df.to_sql to write to DB, it is very slow. So I use pymsql. I convert the dataframe values as a tuple and form a sql insert statement. Hence i c...
<p>try replacing None with explicit NULLs</p> <pre><code>df['col'] = df['col'].fillna('NULL') </code></pre>
python|pandas|nullable|nonetype
0
2,428
59,882,667
Why does date_range give a result different from indexing [] for DataFrame Pandas dates?
<p>Here is a simple code with <code>date_range</code> and indexing [ ] I used with Pandas</p> <pre><code>period_start = '2013-01-01' period_end = '2019-12-24' print(pd.DataFrame ({'close':aapl_close, 'returns':aapl_returns},index=pd.date_range(start=period_start,periods=6))) print(pd.DataFrame ({'close':aapl...
<p>As I'm a beginner in Python and its libraries, I didn't understand that this question refers to the Quantopian library, not to Pandas. </p> <p>I got a solution on their forum. All the times returned by methods on Quantopian are timezone aware with a timezone of 'UTC'. By default, the date_range method returns timez...
python|pandas|dataframe
1
2,429
59,899,052
How can I match values on a matrix on python using pandas?
<p>I'm trying to match values in a matrix on python using pandas dataframes. Maybe this is not the best way to express it.</p> <p>Imagine you have the following dataset:</p> <pre><code>import pandas as pd d = {'stores':['','','','',''],'col1': ['x','price','','',1],'col2':['y','quantity','',1,''], 'col3':['z','',1,'...
<p>You can fill the whole column at once, like this:</p> <pre><code>df["stores"] = df[["col1", "col2", "col3"]].rename(columns=df.loc[0]).eq(1).idxmax(axis=1) </code></pre> <p>This first creates a version of the dataframe with the columns renamed "x", "y", and "z" after the values in the first row; then <code>idxmax(...
python|pandas|dataframe|matrix
0
2,430
32,525,345
Converting 3D matrix to cascaded 2D Matrices
<p>I have a <code>3D</code> matrix in python as the following:</p> <pre><code>import numpy as np a = np.ones((2,2,3)) a[0,0,0] = 2 a[0,0,1] = 3 a[0,0,2] = 4 </code></pre> <p>I want to convert this <code>3D</code> matrix to a set of <code>2D</code> matrices. I have tried <code>np.reshape</code> but it did not solve m...
<p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html" rel="nofollow"><code>transpose</code></a> alongwith <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="nofollow"><code>reshape</code></a> -</p> <pre><code>a.transpose([0,2,1]).reshape(a.shape[0]...
python|numpy|matrix|reshape
2
2,431
40,331,510
How to stack multiple lstm in keras?
<p>I am using deep learning library keras and trying to stack multiple LSTM with no luck. Below is my code</p> <pre><code>model = Sequential() model.add(LSTM(100,input_shape =(time_steps,vector_size))) model.add(LSTM(100)) </code></pre> <p>The above code returns error in the third line <code>Exception: Input 0 is inc...
<p>You need to add <code>return_sequences=True</code> to the first layer so that its output tensor has <code>ndim=3</code> (i.e. batch size, timesteps, hidden state).</p> <p>Please see the following example:</p> <pre><code># expected input data shape: (batch_size, timesteps, data_dim) model = Sequential() model.add(L...
tensorflow|deep-learning|keras|lstm|keras-layer
149
2,432
40,641,561
Error with arrays/matrix operations
<p>I am trying to run the following code. For those who know it, this is a try of the Ehrenfest Urn simulation.</p> <pre><code>import numpy as np import random C=5 L=2 # Here I create a matrix to be filled with zeros and after with numbers I want b=np.zeros( (L,C) ) # line x column A=[] # here I creat 2 lists to pu...
<p>The error implies that <code>b.shape[1]</code> (axis 1) is 5; but <code>i</code> is 5. Remember indexing starts at 0.</p> <p>In the broader picture:</p> <pre><code>while i&lt;5: #here I want to choose random numbers between 1 and 10, ... i=i+1 b[j,i] ... </code></pre> <p>at the last iteration <co...
python|python-3.x|numpy|runtime-error
1
2,433
61,806,725
Iterate over a pandas data frame or groupby object
<p>df_headlines = </p> <p><img src="https://i.imgur.com/OnLfhQ5.png" alt="https://i.imgur.com/OnLfhQ5.png"></p> <p>I want to group by the <code>date</code> column and then count how many times <code>-1</code>, <code>0</code>, and <code>1</code> appear by date and then whichever has the highest count, use that as the ...
<p>As Ch3steR hinted as a comment, you can iterate through your groups in the following way: </p> <pre><code>for name, group in headlines.groupby('date'): daily_pos = len(group[group['score'] == 1]) daily_neg = len(group[group['score'] == -1]) daily_neu = len(group[group['score'] == 0]) print(name, daily_...
python|pandas
0
2,434
61,856,322
traversing a tree from a list in python to do calculations?
<p>I have this list:</p> <pre><code>new_tree = {'cues': 'glucose_tol', 'directions': '&lt;=', 'thresholds': '122.5', 'exits': 1.0, 'children': [{'cues': True}, {'cues': 'mass_index', 'directions': '&lt;=', 'thresholds': '30.8', 'exits': 1.0, 'children': [{'cues': 'pedigree', 'direction...
<p>This looks like a decision tree. </p> <p>The way it works is that at each step you are either on a final decision state ('cues': True, or 'cues': false) or you need to make a decision.</p> <p>To make the decision you need to get the field named in 'cues' from your dataframe, then using direction and threshold you ...
python|pandas|list
1
2,435
61,721,285
Vectorizing a function in Python
<p>I have a function that I am trying to vectorize:</p> <pre><code>import pandas as pd import numpy as np import random import statsmodels.api as sm data = pd.DataFrame({ 'state': ['a', 'b', 'c']*200, 'read': [random.uniform(10,50) for i in range(600)], 'write': [random.uniform(0,10) for i in range(600)],...
<p>try in this way</p> <p>same as your code:</p> <pre><code>import statsmodels.api as sm data = pd.DataFrame({ 'state': ['a', 'b', 'c']*200, 'read': [random.uniform(10,50) for i in range(600)], 'write': [random.uniform(0,10) for i in range(600)], 'cansu': [random.uniform(11,20) for i in range(600)], ...
python|pandas|numpy|vectorization
0
2,436
61,913,458
Pandas info for 100+ features
<p>I have the dataset in my disposal which consists of around 500 columns which I need to explore and keep only relevant columns. Pandas <code>info(verbose = True)</code> method does not even display this number properly. I also used missingno library to visualise nulls. However, it uses a lot of RAM. What to use inste...
<p>Regarding the issue of useless features, you could easily estimate some metrics associated with feature effectiveness and filter it out using some threshold. Check out the <a href="https://scikit-learn.org/stable/modules/feature_selection.html" rel="nofollow noreferrer">sklearn feature selection docs</a>.</p> <p>Of...
python|pandas
0
2,437
61,968,787
What is the purpose of this 'a' in this array slicing in Python ( W[: , : , : , a] )?
<p>Here is the code example:</p> <pre><code>weights = W[:,:,:,a] </code></pre> <p><strong>Here, a is an integer number</strong></p> <p>In array slicing, I need a good explanation (references are a plus) on Python's slice notation. I don't understand what is the purpose of this 'a'. We know that a 3D array is like a sta...
<h1>Shapes:</h1> <p>Let <strong>M</strong> to be the your <strong>n</strong>-dimensional array:</p> <blockquote> <p>Reference image: <a href="https://fgnt.github.io/python_crashkurs_doc/_images/numpy_array_t.png" rel="nofollow noreferrer">https://fgnt.github.io/python_crashkurs_doc/_images/numpy_array_t.png</a></p> </b...
python|arrays|numpy-slicing
3
2,438
58,021,252
Generating data associated with a trend
<p>I want to create 3 different datasets with a column each having dates (dd/mm/yyyy). These dates need to be in a range of 3 months like January 2019 to April 2019. The count for each date needs to represent the number of searches. The dataset should have 2000 entries and dates can be repititive as well. All 3 dataset...
<p>you can do it like below.</p> <p>trend function defines your trend if start is higher than end it is downward trend and vice versa. you can also control the rate of trend by changing difference between start and end</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd dates =...
python|pandas|numpy
1
2,439
58,092,004
How to do sequence classification with pytorch nn.Transformer?
<p>I am doing a sequence classification task using <code>nn.TransformerEncoder()</code>. Whose pipeline is similar to <code>nn.LSTM()</code>.</p> <p>I have tried several temporal features fusion methods:</p> <ol> <li><p>Selecting the final outputs as the representation of the whole sequence.</p></li> <li><p>Using an ...
<p>The accuracy you mentioned indicates that something is wrong. Since you are comparing LSTM with TransformerEncoder, I want to point to some crucial differences. </p> <ol> <li><p><strong>Positional embeddings</strong>: This is very important since the Transformer does not have recurrence concept and so it doesn't ca...
machine-learning|deep-learning|pytorch|text-classification|transformer-model
3
2,440
55,013,861
Create new column with sum of vector column in pandas
<p>I have a dataframe that looks like this:</p> <pre><code>df = pd.DataFrame({'A':[[1,2,3],[4,5,6,7],[8,9]]}) </code></pre> <p>All entries are integers. </p> <p>I want to make a make a new column, 'B', that would read <code>[5,22,17]</code>.</p> <p>I can do this with a loop, but is there a one-line solution? Thanks...
<p>To extract the rows from your DataFrame and sum each row as a builtin python list:</p> <pre><code>res = [sum(x[0]) for x in df.values.tolist()] res [6, 22, 17] </code></pre> <p>To assign the row sums into a new column:</p> <pre><code>df['B'] = [sum(x[0]) for x in df.values.tolist()] df A B 0 [...
python|pandas
1
2,441
49,413,824
Modifying an existing excel workbook's multiple worksheets based on pandas dataframe
<p>I currently have an excel file with, for minimally viable example, say 3 sheets. I want to change 2 of those sheets to be based on new values coming from 2 pandas dataframes (1 dataframe for each sheet). </p> <p>This is the code I currently have:</p> <pre><code>from openpyxl.writer.excel import ExcelWriter from op...
<p>If you execute on your Python command line the command 'help(pd.ExcelWriter)' you will see the parameters on the first lines:</p> <pre><code>class ExcelWriter(builtins.object) | Class for writing DataFrame objects into excel sheets, default is to use | xlwt for xls, openpyxl for xlsx. See DataFrame.to_excel fo...
python|python-3.x|pandas|openpyxl|pandas.excelwriter
1
2,442
73,239,947
How do I remove duplicates where one has a null value in Python?
<p><strong>Problem</strong></p> <p>Sorry to all who have helped, but I have had to rephrase the question. I have a dataframe with duplicates for most of the columns, except the last column. Where I have duplicates, I want to apply the following rule:</p> <ol> <li>If both have valid entries in the last column, then keep...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> and drop <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.dropna.html" rel="nofollow noreferrer"><code>NaN</code></a> values</p> <pre><code>df.grou...
python|pandas|duplicates
1
2,443
73,454,400
concatenate every n rows into one row pandas and keep other data
<p>I have a data frame that contains &quot;userid&quot;, &quot;gender&quot; and &quot;tweet&quot;, each user has 100 tweets:</p> <p><a href="https://i.stack.imgur.com/w0qdy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w0qdy.png" alt="enter image description here" /></a></p> <p>link to demo dataset...
<h2>Short answer</h2> <pre><code>data = pd.DataFrame([[1,1,'Hi'],[1,1,'my name is'], [1,1,'Hal'],[1,1,'my name is'], [1,1,'Hal'],[2,0,'Ich bin'], [2,0,'ein kartoffeln'],[2,0,'!'], [2,0,'ein kartoffeln'],[2,0,'!'],[1,1,'my name is'], [1,1,'Obama'],[1,1,'president of USA'], [1,1,'Obama'],[1,1,'president of USA'],[2,0,'Hi...
python|pandas
1
2,444
73,194,756
Convert dictionary keys and values into rows and columns
<p>I have a list of dictionaries with multiple rows. I need to store the keys as columns and value as rows.</p> <pre><code> date model 22/01/2022 [{'vehicles': {'engine': 0, 'status': 5, 'size': 0, 'warranty': 2, 'type': 3, }}] . . . 23/01/2022 [{'vehicles': {'engine': 3, 'status': 4, 's...
<pre><code>df = pd.DataFrame({'date': ['22/01/2022', '23/01/2022'], 'model': [[{'vehicles': {'engine': 0, 'status': 5, 'size': 0, 'warranty': 2, 'type': 3, }}], [{'vehicles': {'engine': 3, 'status': 4, 'size': 1, 'warranty': 5, 'type': 1, }}]]}) df = df.explode('model') df.model = [m['vehicles'] for m in df.model] pd.c...
python|python-3.x|pandas
1
2,445
35,301,262
Thresholded pixel indices of a NumPy array
<p>I'm sure this question is Googleable, but I don't know what keywords to use. I'm curious about a specific case, but also about how to do it in general. Lets say I have a RGB image as an array of shape <code>(width, height, 3)</code> and I want to find all the pixels where the red channel is greater than 100. I feel ...
<p>To detect for red-channel only, you can do something like this -</p> <pre><code>np.argwhere(image[:,:,0] &gt; threshold) </code></pre> <p><strong>Explanation :</strong></p> <ol> <li>Compare the <code>red-channel</code> with the <code>threshold</code> to give us a boolean array of same shape as the input image withou...
python|arrays|numpy|vectorization
3
2,446
30,998,305
Weird numpy.sum behavior when adding zeros
<p>I understand how mathematically-equivalent arithmentic operations can result in different results due to numerical errors (e.g. summing floats in different orders).</p> <p>However, it surprises me that adding zeros to <code>sum</code> can change the result. I thought that this always holds for floats, no matter wha...
<p><strong>Short answer:</strong> You are seeing the difference between</p> <pre><code>a + b + c + d </code></pre> <p>and</p> <pre><code>(a + b) + (c + d) </code></pre> <p>which because of floating point inaccuracies is not the same.</p> <p><strong>Long answer:</strong> Numpy implements pair-wise summation as an o...
python|numpy|sum|numerical-stability
10
2,447
67,523,574
Sort a data frame in python with duplicates by a string list
<p>I have a data frame with a 250 names with values imported in python via pandas read_csv. It reads in the data:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>name</th> <th>val1</th> <th>val2</th> <th>val3</th> </tr> </thead> <tbody> <tr> <td>George</td> <td>2.5</td> <td>1.1</td> <td>1.0...
<p>Create a lookup dictionary for your sort somehow:</p> <pre class="lang-py prettyprint-override"><code>name_order = {'Sally':1, ... , 'George':12, 'Tom':13} # hand-numbered </code></pre> <pre class="lang-py prettyprint-override"><code>neworder = ['Sally', ... , 'George', 'Tom'] name_order = {nm:ix for ix,nm in enumer...
python|pandas|sorting
3
2,448
67,212,324
merge two DataFrame with two columns and keep the same order with original indexes in the result
<p>I have two pandas data frames. Both data frames have two key columns and one value column for merge. I want to keep the same order with original indexes in the merged result.</p> <ul> <li>The keys and values might be missing or changed in the other data frame.</li> <li>The order of data are important. You can't sort...
<p>when constructing the merged dataframe, get the index values from each dataframe.</p> <pre><code>merged_df = pd.merge(df1, df2, how=&quot;outer&quot;, on=['key1', 'key2']) </code></pre> <p>use <code>combine_first</code> to combine <code>index_x</code> &amp; <code>index_y</code></p> <pre><code>merged_df['combined_ind...
pandas
1
2,449
34,480,630
Simple Torch7 equivalent to numpy.roll
<p>Is there any simple way of rolling a tensor in torch7 like numpy.roll and numpy.rollaxis in python?</p> <p>Thanks!</p>
<p>You can achieve the effects of numpy's <code>rollaxis</code> with torch's <a href="https://github.com/torch/torch7/blob/master/doc/tensor.md#tensor-permutedim1-dim2--dimn" rel="nofollow">permute</a>. While <code>rollaxis</code> requires the start and end position of the one axis to move, <code>permute</code> require...
python|numpy|lua|torch
0
2,450
60,217,992
Sort dataframe by month and find the first non-zero value in each column for each month
<p>I need to load a CSV with 200 columns, the first column is a date, into a pandas dataframe in python. I need to sort through the data and return the first non-zero value for each month. Should I make separate dataframes or each month, and then search? What's the best way to approach this problem?</p> <pre><code>df...
<p>You got an error for <code>Feb</code>, column <code>Data_2</code>: the first non-zero is 1, not 7.</p> <hr> <p>Here's one way to do it:</p> <pre><code>def first_non_zero(col): """Return the first non-zero value of a column, or nan if the column is all-zero""" head = col[col != 0].head(1) return np.nan...
python|pandas|dataframe|datetime|pandas-groupby
0
2,451
60,221,426
How to produce an array with values in a specific shape?
<p>I would like to create an array with values that range from 0.0 to 1.0 as shown here: <a href="https://i.stack.imgur.com/d2yBN.png" rel="nofollow noreferrer">weighting matrix</a></p> <p>Basically, the left and top edges should remain close to 1.0 but slowly decay to 0.5 in the corners. The bottom and right edges sh...
<p>This is the simplest function I can think of:</p> <pre><code>tune_me = 101 x = np.linspace(0, 1, tune_me) y = np.linspace(0, 1, tune_me) xv, yv = np.meshgrid(x, y) sig = 1/(1 + np.exp(tune_me - xv - yv)) plt.matshow(sig) </code></pre> <p>But if you want something specific, you should probably figure out your ...
python|numpy|matrix
0
2,452
60,079,496
python (pandas) creating a new column based on values from different rows
<p>I have a data frame from a cvs file looking like this:</p> <pre><code> #F E G 0 1 n.e. 153 1 1 60 15 2 1 99 10 3 1 S 23 4 2 n.e. 190 5 2 60 44 6 2 99 22 7 2 S 67 </code></pre> <p>I would like to add a new column to this. </p> ...
<pre><code>df.loc[df['E'] == 'n.e.', 'G_ne'] = df['G'] df['G_ne'] = df['G_ne'].fillna(method='ffill') df['rel'] = df['G'] / df['G_ne'] print(df) </code></pre> <p>Output:</p> <pre><code> #F E G G_ne rel 0 1 n.e. 153 153.0 1.000000 1 1 60 15 153.0 0.098039 2 1 99 10 153.0 0.065...
python|pandas|function|rows
0
2,453
59,938,154
numpy where - how to set condition on whole column?
<p>How to implement :</p> <pre><code>t=np.where(&lt;exists at least 1 zero in the same column of t&gt;,t,np.zeros_like(t)) </code></pre> <p>in the "pythonic" way?</p> <p>this code should set all column to zero in t if t has at least 1 zero in that column</p> <p>Example :</p> <pre><code>1 1 1 1 1 1 0 1 1 1 1 1 1 1 ...
<p><code>any</code> is what you need</p> <p><code>~(arr == 0).any(0, keepdims=True) * arr</code></p> <pre><code>0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 </code></pre>
python|numpy
1
2,454
65,450,185
Fill np.nan with values based on other columns
<p>I try to match the <code>offer_id</code> to the corresponding transaction. This is the dataset:</p> <pre><code> time event offer_id amount 2077 0 offer received f19421c1d4aa40978ebb69ca19b0e20d NaN 15973 6 offer viewed f19421c1d4aa40978ebb69ca19b0e20d ...
<p>Example code:</p> <pre><code>import pandas as pd import numpy as np d = {'time': [0, 6, 6, 12, 12, 108, 144, 150, 168, 258], 'event': [&quot;offer received&quot;, &quot;offer viewed&quot;, &quot;transaction&quot;, &quot;transaction&quot;, &quot;offer completed&quot;, &quot;transaction&quot;, &quot;transaction...
python|pandas
1
2,455
65,128,134
How to flip half of a numpy array
<p>I have a numpy array:</p> <pre><code>arr=np.array([[1., 2., 0.], [2., 4., 1.], [1., 3., 2.], [-1., -2., 4.], [-1., -2., 5.], [1., 2., 6.]]) </code></pre> <p>I want to flip the second half of this array upward. I mean I want to have:</p> <pre>...
<p>You can simply concatenate rows below the <code>n</code>th row (included) with <a href="https://numpy.org/doc/stable/reference/generated/numpy.r_.html" rel="nofollow noreferrer">np.r_</a> for instance, with row index <code>n</code> of your choice, at the top and the other ones at the bottom:</p> <pre><code>import nu...
python|numpy|flip
3
2,456
50,217,206
How to manage subplots in Pandas?
<p>My DataFrame is:</p> <pre><code>df = pd.DataFrame({'A': range(0,-10,-1), 'B': range(10,20), 'C': range(10,30,2)}) </code></pre> <p>and plot:</p> <pre><code>df[['A','B','C']].plot(subplots=True, sharex=True) </code></pre> <p>I get one column with 3 subplots, each even height.</p> <p>How to plot it this way that ...
<p>Use <code>subplots</code> with <code>gridspec_kw</code> parmater to setup your grid then use the <code>ax</code> paramter in pandas plot to use those axes defined in your subplots statement:</p> <pre><code>f, ax = plt.subplots(2,2, gridspec_kw={'height_ratios':[1,2]}) df[['A','B','C']].plot(subplots=True, sharex=Tr...
python|pandas|matplotlib
2
2,457
49,851,375
list and array is global by default in python3.6?
<p>Just a simple code below: </p> <pre><code>import numpy as np x=np.array([1,2]) y=[1,2] L=1 def set_L(x,y,L): x[0]+=1 y[0]+=1 L+=1 print(id(x)) print(id(y)) print(id(L)) </code></pre> <p>I found that array x and list y is the same in the function set_L(), does this mean by default list and ...
<p>x[0]+=1 and y[0]+=1 just modify the existing object, while L+=1 is an assignment and creates a new local reference. See <a href="https://stackoverflow.com/a/11867500/7662112">https://stackoverflow.com/a/11867500/7662112</a></p>
python|arrays|list|numpy|global-variables
0
2,458
50,208,918
Python Pandas find statistical difference between 2 distributions
<p>i have 2 columns with similar data. I plot them to compare their distributions and i want to quantify their difference.</p> <pre><code>df = pd.DataFrame({'a':['cat','dog','bird','cat','dog','dog','dog'], 'b':['cat','cat','cat','bird','dog','dog','dog']}) </code></pre> <p>I then plot the 2 columns of m...
<p>It is very common to use the <a href="https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test#Two-sample_Kolmogorov%E2%80%93Smirnov_test" rel="nofollow noreferrer">two-sided Kolmogorov-Smirnov test</a> for this. </p> <p>In Python, you can do so with <a href="https://docs.scipy.org/doc/scipy-0.14.0/reference/g...
python|pandas|numpy|scipy
4
2,459
50,094,633
Keras TimeDistributed Not Masking CNN Model
<p>For the sake of example, I have an input consisting of 2 images,of total shape (2,299,299,3). I'm trying to apply inceptionv3 on each image, and then subsequently process the output with an LSTM. I'm using a masking layer to exclude a blank image from being processed (specified below).</p> <p>The code is:</p> <pre...
<p>It seems to be working as intended. Masking in Keras doesn't produce zeros as you would expect, it instead skips the timesteps that are masked in upstream layers such as LSTM and loss calculation. In case of RNNs, Keras (at least tensorflow) is implemented such that the states from the previous step are carried over...
tensorflow|deep-learning|keras|conv-neural-network
3
2,460
64,152,916
How to add row name to cell in pandas dataframe?
<p>How do I take data frame, like the following:</p> <pre><code>d = {'col1': [1, 2], 'col2': [3, 4]} df = pd.DataFrame(data=d) df col1 col2 row0 1 3 row1 2 4 </code></pre> <p>And produce a dataframe where the row name is added to the cell in the frame, like the following:</p> <pre><code> col1 ...
<p>You can convert the dtype to string and add the index to the dataframe:</p> <pre><code>print(df,'\n') print(df.astype(str).add(&quot;,&quot;+df.index,axis=0)) </code></pre> <hr /> <pre><code> col1 col2 row0 1 3 row1 2 4 col1 col2 row0 1,row0 3,row0 row1 2,row1 4,row1 </code></p...
python|python-3.x|pandas
3
2,461
63,836,145
Run a function for each element in two lists in Pandas Dataframe Columns
<p><strong>df</strong>:</p> <pre><code>col1 ['aa', 'bb', 'cc', 'dd'] ['this', 'is', 'a', 'list', '2'] ['this', 'list', '3'] col2 [['ee', 'ff', 'gg', 'hh'], ['qq', 'ww', 'ee', 'rr']] [['list', 'a', 'not', '1'], ['not', 'is', 'this', '2']] [['this', 'is', 'list', 'not'], ['a', 'not', 'list', '2']] </code></pre> <p><stro...
<p>This works:</p> <pre><code># Generate DataFrame df = pd.DataFrame (data, columns = ['col1','col2']) # Clean Data (strip out trailing commas on some words) df['col1'] = df['col1'].map(lambda lst: [x.rstrip(',') for x in lst]) # 1. List comprehension Technique # zip provides pairs of col1, col2 rows result = [[get_t...
python|pandas
2
2,462
32,701,977
calculating the curl of u and v wind components in satellite data - Python
<p>I am not sure how to take derivatives of the u and v components of the wind in satellite data. I thought I could use numpy.gradient in this way:</p> <pre><code> from netCDF4 import Dataset import numpy as np import matplotlib.pyplot as plt GridSat = Dataset('analysis_20040713_v11l30flk....
<p>As <code>@moarningsun</code> commented, changing how you call <code>np.gradient</code> should correct the <code>ValueError</code></p> <pre><code>dv_dx, dv_dy = np.gradient(vwind, dx,dy) du_dx, du_dy = np.gradient(uwind, dx,dy) </code></pre> <p>How you got <code>vwind</code> from the file is not particularly import...
python|numpy|vector|signal-processing|weather
1
2,463
38,592,523
Checkbox to select/unselect all series in c3.js
<p>I have a fairly big amount of data displayed on graphs using c3.js and I was wondering if it was possible to implement a checkbox for each graph with the option to select or unselect all.</p> <p>I couldn't find anything related on the documentation.</p> <p>Thanks in advance</p>
<p>If I understand well, you want the possibility to hide or show all data at once.<br> In some of my charts I have buttons to show or hide all data </p> <p>In a basic html/js example:</p> <pre><code>&lt;div id='mychart'&gt;&lt;/div&gt; &lt;button onclick="chart.show()"&gt;Show All&lt;/button&gt; &lt;button onclick=...
pandas|c3.js
1
2,464
63,030,561
Get nearest value that is out of datetime range if there is only one record in group
<p>Have such dataframe:</p> <p><a href="https://i.stack.imgur.com/dOnXs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dOnXs.png" alt="enter image description here" /></a></p> <p>I need first to filter data by <em>date_op</em> and then group by <em>key</em> column:</p> <p><a href="https://i.stack.im...
<p>Maybe the following can help you:</p> <pre><code>data[&quot;Appearance&quot;] = data.groupby(&quot;key&quot;).cumcount() df2 = data[(data[&quot;date_op&quot;]&gt;'2020-07-15 00:01:00')].copy() df2[&quot;filter&quot;] = int(1) df3 = pd.merge(data,df2[[&quot;key&quot;,&quot;filter&quot;]],on=&quot;key&quot;, how = &qu...
python|pandas
1
2,465
62,983,600
Plotting by groupby and average
<p>I have a dataframe with multiple columns and rows. One column, say 'name' has several rows with names, the same name used multiple times. Other rows, say, 'x', 'y', 'z', 'zz' have values. I want to group by name and get the mean of each column (x,y,z,zz)for each name, then plot on a bar chart.</p>
<p>Using the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>pandas.DataFrame.groupby</code></a> is an important data-wrangling stuff. Let's first make a dummy Pandas data frame.</p> <pre><code>df = pd.DataFrame({&quot;name&quot;: [&quot...
pandas|matplotlib|pandas-groupby
1
2,466
62,982,528
How to Count Occurence of Matrix in List of Matrices?
<p>I have a list of matrices, for example a list of numpy arrays:</p> <pre><code>list = [np.array([[0,1],[1,1]]), np.array([[1,0],[0,0]]), np.array([[0,1],[1,1]])] </code></pre> <p>and I would like to count the occurence of each matrix. Thus, the desirable output is something like:</p> <pre><code>np.arr...
<p>You can do:</p> <pre><code>pd.Series(my_list).astype(str).value_counts() </code></pre> <hr /> <pre><code>[[0 1]\n [1 1]] 2 [[1 0]\n [0 0]] 1 dtype: int64 </code></pre> <p>Or:</p> <pre><code>from collections import defaultdict d = defaultdict(int) for arr in my_list: d[str(arr)] += 1 d = dict(d) print...
python|pandas|numpy|matrix
2
2,467
63,041,906
Python xlsx insert columns at cell location
<p>I am trying to copy data from a column and insert that data into another column at a specific cell location preserving the data above it, while shifting right the other column data.</p> <p>I have been trying to do this in Openpyxl and with Pandas with no luck. I'm attaching pictures of the desired outcome to help cl...
<p>let's say you have this dataframe:</p> <pre><code> a b c 0 1 2 3 1 4 5 6 2 7 8 9 </code></pre> <p>and you are trying to copy A[1:2] to C[1:2] like this:</p> <pre><code> a b c 0 1 2 3 1 4 5 4 2 7 8 7 </code></pre> <p>Here is how you do this:</p> <pre><code>df['c'].iloc[1:2] = df[...
python|pandas|openpyxl
1
2,468
32,116,900
Python: numpy.var yields unknown number
<p>numpy.var yields this number: 6.0037250324777306e-28.</p> <p>I suppose by looking at the data that this number is close to 0. Am I correct? If so, how could I interpret this number? </p>
<p>It is indeed a number very very close to 0. For example:</p> <pre><code>import numpy as np list_to_check_var = [2,2,2,2,2.00000000001] np.var(list_to_check_var) </code></pre> <p>yields</p> <pre><code>1.6000002679246418e-23 </code></pre> <p>As you intuitively know, the variance of the list is very small. The <cod...
python|numpy
2
2,469
41,663,885
How to translate a simple MATLAB equation to Python?
<p>I need to understand how I can translate these few lines of MATLAB code. I don't understand how to create a vector <code>n1</code> of <code>n</code> elements and how to fill it using the same formula as in MATLAB.</p> <p>Here's the MATLAB code: </p> <pre><code>nc = 200; ncmax = 600; dx = 0.15e-04; r = (dx/2):dx:...
<p>You have a beautifully vectorized solution in MATLAB. One of the main reason for using NumPy is that it also allows for vectorization - so you shouldn't be introducing loops.</p> <p>As suggested in comments by lucianopaz, there is a <a href="https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html" rel...
python|matlab|numpy
1
2,470
61,259,680
Change value of a column in a multi index dataframe
<p>I have a dataframe like this:</p> <pre><code> holiday YEAR MONTH DAY TIME 2012 10 2 00:00:00 0 06:00:00 0 12:00:00 0 18:00:00 0 2012 10 3 00:00:00 1 06:00:00 0 12:00:...
<p>Let us do </p> <pre><code>df['holiday']=df.groupby(level=[0,1,2]).cumsum().values </code></pre>
python|pandas
2
2,471
68,608,755
How can I solve this problem? (vs code error)
<pre><code>from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import check_util.checker as checker from IPython.display import clear_output from PIL import Image import os import time import re from glob import glob impo...
<p>Please try again by restarting the <strong>VS code</strong> or by changing the <strong>jupyter</strong> virtual environment (Change kernel for the notebook) while executing this code in <strong>VS code</strong>.</p> <p>(I tried the same code as mentioned above in <strong>VS code</strong> using <code>python 3.7.10</c...
python-3.x|tensorflow|visual-studio-code|deep-learning|conv-neural-network
0
2,472
68,586,063
Python pandas add value to same row
<p>How to: in a for loop, insert value at specific column by name, on the same row each time. So I have a few hundred columns. And I want each value to be put on the same row (Using the DATE) in the appropriate column. Here are my dataframe columns:</p> <pre><code>DATE, ABC, BGF, ATR </code></pre> <p>Here is my example...
<p>Edit a specific ROW (mod_df.Date)</p> <p>ONLY where a specific value appears (== currentDate),</p> <p>on the col (, col)</p> <p>with this value (= aMrket[-3])</p> <pre><code>mod_df.loc[mod_df.Date == currentDate, col] = aMrket[-3] </code></pre>
python|pandas
0
2,473
68,787,654
Keras Sequential model input: How significant are the dimensions?
<p>I am trying to build a multioutput classifier on 3D data structured like <code>[sampleID, timestamp, deviceID, sensorID]</code> with one-hot labels like <code>[sampleID, deviceID]</code> to determine which device &quot;wins&quot;.</p> <p>In a nutshell, it is a massive collection of timeseries readings from five sens...
<p>IIUC, you are asking if using 1000 timesteps for 20 objects (device X sensor) is better than using 1000 timesteps for 4 devices for 5 sensors.</p> <p>There is no way of actually determining which would better model your problem, but, we can quickly build some tests to see which models capture the complexity of the p...
tensorflow|keras
1
2,474
36,270,864
Append a row to a dataframe
<p>Fairly new to pandas and I have created a data frame called rollParametersDf:</p> <pre><code> rollParametersDf = pd.DataFrame(columns=['insampleStart','insampleEnd','outsampleStart','outsampleEnd'], index=[]) </code></pre> <p>with the 4 column headings given. Which I would like to hold the reference dates for a s...
<p>You give key-values pairs to append</p> <pre><code>df = pd.DataFrame({'insampleStart':[], 'insampleEnd':[], 'outsampleStart':[], 'outsampleEnd':[]}) df = df.append({'insampleStart':[1,2], 'insampleEnd':[5,6], 'outsampleStart':[6,7], 'outsampleEnd':[8,9]}, ignore_index=True) </code></pre>
python|python-3.x|pandas
2
2,475
36,532,390
How to avoid automatic pseudo coloring in matplotlib.pyplot imshow()
<p>I have a 28x28 numpy ndarray that I want to print out as an image. Since it is a grayscale picture, it only has one color value per pixel. These values are scaled from -0.5 to 0.5. I use plt.imshow(array). When I do that, the image gets printed out with the jet colormap, instead of grayscale.</p> <p>If I apply cmap...
<p>To prevent matplotlib from using the "jet" colormap as default you need to modify the line corresponding to the default cmap in the matplotlibrc file, usually found in ~/.config/matplotlib/matplotlibrc:</p> <pre><code>image.cmap : gray # gray | jet etc... </code></pre> <p>Also, I encourage everybod...
python|numpy|matplotlib
1
2,476
53,231,882
Populating a dict with a list in the same loop
<p>I am trying to populate a dict with column-wise occurences of characters in pandas sereis. The sereis is as follows:</p> <pre><code>&gt;&gt;&gt; jkl 1 ATGC 2 GTCA 3 CATG Name: 0, dtype: object </code></pre> <p>I want a dict in a way that contains all the characters as keys and list of their column-...
<p>Using <code>crosstab</code> after re-create your dataframe </p> <pre><code>S=pd.DataFrame(s.map(list).tolist()).melt() pd.crosstab(S.value,S.variable) Out[338]: variable 0 1 2 3 value A 1 1 0 1 C 1 0 1 1 G 1 0 1 1 T 0 2 1 0 </code></pre> <p>after addi...
python|python-3.x|pandas|dictionary
5
2,477
52,994,435
PyTorch: create non-fully-connected layer / concatenate output of hidden layers
<p>In PyTorch, I want to create a hidden layer whose neurons are not fully connected to the output layer. I try to concatenate the output of two linear layers but run into the following error:</p> <blockquote> <p>RuntimeError: size mismatch, m1: [2 x 2], m2: [4 x 4]</p> </blockquote> <p>my current code:</p> <pre><...
<p>It turned out to be a simple comprehension problem with the concatenation function. Changing <code>x = torch.cat((xLeft, xRight))</code> to <code>x = torch.cat((xLeft, xRight), dim=1)</code> did the trick. Thanks @dennlinger</p>
python|neural-network|pytorch
2
2,478
52,952,905
python increment version number by 0.0.1
<p>We are using versioning. The current version is 0.2.3 i would like to increment by 0.0.1 using python. Getting below error.</p> <p>tagNumber = 0.2.3 ^ SyntaxError: invalid syntax</p>
<p>You could do something like this:</p> <pre><code>def increment_ver(version): version = version.split('.') version[2] = str(int(version[2]) + 1) return '.'.join(version) </code></pre>
python|python-3.x|python-2.7|numpy
3
2,479
65,631,306
Python: How do I resolve this ImportError?
<p>I installed Tensorflow through <code>pip install</code> and it was successful but when i try to use it I have this ImportError:</p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\AKIN\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\pywrap_tensorflow.py&quot;, line 64, ...
<p>After hundreds of Google searches and Youtube videos, I found the solution to this problem about a month ago. Unlike other third-party modules in python (e.g. Pandas, Matplotlib, etc.)- which require <code>pip</code> install - there are a different set of steps including installing NVIDIA with a Cuda-enabled GPU or ...
python|windows|tensorflow|pip|python-import
1
2,480
63,586,976
Finding min values in a 3D array across one axis and replacing the non-corresponding values in another 3D array with 0 without loops in python
<p>Let's say we have two 3D arrays, A(x,y,z) and B(x,y,z) that x,y,z are dimensions. I want to identify all the minimum values across the z-axis in the A array and then based on those values and their indices choose the corresponding values in the B, keep them and replace other values with zero.</p>
<p>You can think of it a little differently. Finding the locations of the minima in <code>A</code> is straightforward:</p> <pre><code>ind = np.expand_dims(np.argmin(A, axis=2), axis=2) </code></pre> <p>You can do one of the following things:</p> <ol> <li><p>Simplest: create a replacement of <code>B</code> and populate ...
python|numpy|indexing|min|substitution
1
2,481
63,619,153
How to reduce used memory for a repetitive optimization constraint in python?
<p>I have a mathematical optimization problem of the following simplified form:</p> <pre><code>min ∑Pxy s.t. Pxy≥Pyz, ∀x,y,z Pxy ∈ {0,1} </code></pre> <p>This problem has X<em>Y</em>Z constraints. I write the following code to perform the optimization. The only way that came to my mind was introducing two new matrices ...
<p>Thanks to the comment of @sascha I have re-wrote the code using <code>scipy.sparse.coo_matrix</code> and the memory problem has solved.</p> <p>I post the modified code here:</p> <pre><code>import cvxpy as cp import numpy as np import scipy.sparse as sp np.random.seed(55) X_max, Y_max, Z_max = 70, 70, 50 P_yz = np...
python|numpy|optimization|ram|cvxpy
1
2,482
63,545,659
Numpy array: Remove and append values
<p>I have a 3D numpy array of the shape <code>(1, 60, 1)</code>. Now I need to remove the first value of the second dimension and instead append a new value at the end.</p> <p>If it was a list, the code would look somewhat like this:</p> <pre class="lang-py prettyprint-override"><code>x = [1, 2, 3, 4] x = x[1:] x.appen...
<pre><code>import numpy as np arr = np.arange(60) #creating a nd array with 60 values arr = arr.reshape(1,60,1) # shaping it as mentiond in question arr = np.roll(arr, -1) # use np.roll to circulate the array left or right (-1 is 1 step to the left) #Now your last value is in the second last position, the seco...
python|numpy|numpy-ndarray
3
2,483
21,533,706
Resolving Reindexing only valid with uniquely valued Index objects
<p>I have viewed many of the questions that come up with this error. I am running pandas '0.10.1'</p> <pre><code>df = DataFrame({'A' : np.random.randn(5), 'B' : np.random.randn(5),'C' : np.random.randn(5), 'D':['a','b','c','d','e'] }) #gives error df.take([2,0,1,2,3], axis=1).drop(['C'],axis=1) #works fine df.t...
<p>Firstly, I believe you meant to test for duplicates using the following command:</p> <pre><code>df.take([2,0,1,2,3],axis=1).columns.get_duplicates() </code></pre> <p>because if you used index instead of columns, then it would obviously returned an empty array because the random float values don't repeat. The abov...
python|pandas
9
2,484
53,799,537
seaborn heatmap from pandas dataframe with NaNs
<p>Hi I really want to create a heatmap but am struggling:</p> <pre><code># correlations between undergrad studies and occupation data_uni = n.groupby(['Q5','Q6'])['Q6'].count().to_frame(name = 'count').reset_index() # some participants did not answer the question in the survey data_uni.fillna('Unknown', inplace=True)...
<p>As per issue <a href="https://github.com/mwaskom/seaborn/issues/375" rel="noreferrer">GH375</a>, you can specify a mask, where data will not be shown for those cells whose mask values are <code>True</code>.</p> <pre><code>sns.heatmap(data_uni, cmap="YlGnBu", mask=data_uni.isnull()) </code></pre>
python|pandas|seaborn|nan|heatmap
8
2,485
53,367,575
float object not subscriptable (python)
<p>So I am creating 10 dictionaries from a data-frame.</p> <p>I have already done 3 for each row, but I have decided to do one for every column in my data-frame. When I add the 7 additional dictionaries, I get a float object not subscriptable error. What's confusing is, I had already added the additional 7 dictionary ...
<p>You should check if the <code>bList</code> is a list object.According to your description,the <code>bList</code> may be a float in your code:</p> <pre><code>&gt;&gt;&gt; a=1.0 &gt;&gt;&gt; a[1] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'float' object is not subs...
python|pandas|error-handling|jupyter|jupyter-lab
0
2,486
53,644,937
Combine two columns in a DataFrame pandas
<p>I am having Dataframe which has multiple columns in which some columns are equal (Same key in trailing end eg: column1 = 'a/first', column2 = 'b/first'). I want to merge these two columns. Please help me out to solve the problem.</p> <p>My Dataframe looks like</p> <pre><code>name g1/column1 g1/column2 g1/g2/col...
<p>Use:</p> <pre><code>#create index by all columns with no merge df = df.set_index('name') #MultiIndex by split last / df.columns = df.columns.str.rsplit('/', n=1, expand=True) #aggregate first no NaN values per second level of MultiIndex df = df.groupby(level=1, axis=1).first() print (df) column1 column2 name...
python|pandas
2
2,487
53,399,550
Remove string from dataframe index values
<p>I want to remove strings from my index values:</p> <pre><code>df.index.get_values().str.replace("and over", "").astype(int) </code></pre> <p>Doing this returns the following error:</p> <pre><code>AttributeError: 'numpy.ndarray' object has no attribute 'str' </code></pre> <p>I've tried to find a similar function ...
<p>Something like the following code should work. But first, you would have to delete the 'All ages' entry.</p> <pre><code>arr = np.array([x.replace(' and over', '') for x in arr]).astype(int) </code></pre>
numpy
0
2,488
17,166,601
Summing across rows of Pandas Dataframe
<p>I have a DataFrame of records that looks something like this:</p> <pre><code>stocks = pd.Series(['A', 'A', 'B', 'C', 'C'], name = 'stock') positions = pd.Series([ 100, 200, 300, 400, 500], name = 'positions') same1 = pd.Series(['AA', 'AA', 'BB', 'CC', 'CC'], name = 'same1') same2 = pd.Series(['AAA', 'AAA', 'BBB', '...
<p>Step 1. Use [['positions']] instead of ['positions']:</p> <pre><code>In [30]: df2 = df.groupby(['stock','same1','same2'])[['positions']].sum() In [31]: df2 Out[31]: positions stock same1 same2 A AA AAA 300 B BB BBB 300 C CC CCC ...
python|pandas|dataframe
10
2,489
19,865,974
Overflow in numpy
<p>I am implementing Harris corner detection and having overflow error:</p> <pre><code>harris.py:27: RuntimeWarning: overflow encountered in ubyte_scalars Mat[0][1]=Ix[i][j]*Iy[i][j] harris.py:28: RuntimeWarning: overflow encountered in ubyte_scalars Mat[1][0]=Ix[i][j]*Iy[i][j] </code></pre> <p>This is the whole ...
<p>What's happening is that your input data is <code>uint8</code>. Because you're multiplying two <code>uint8</code>'s, the result is a <code>uint8</code>, even though it will be upcasted when you assign it to an item in the float array <code>Mat</code>.</p> <p>As an example:</p> <pre><code>In [1]: import numpy as n...
python|numpy
4
2,490
15,835,358
how to solve this exercise with python numpy vectorization?
<p>how to solve this exercise 4.5 on page 2 with python Numpy vectorization?</p> <p>Link to download:</p> <p><a href="https://dl.dropbox.com/u/92795325/Python%20Scripting%20for%20Computational%20Scien%20-%20H.P.%20%20Langtangen.pdf" rel="nofollow">https://dl.dropbox.com/u/92795325/Python%20Scripting%20for%20Computati...
<p>To <em>"vectorize"</em> using <code>numpy</code>, all this means is that instead of doing an explicit loop like,</p> <pre><code>for i in range(1, n): c = c + f(i) </code></pre> <p>Then instead you should make <code>i</code> into a numpy array, and simply take its sum:</p> <pre><code>i = np.arange(1,n) c = i.s...
numpy
0
2,491
71,949,077
How to do append based on multiple filter on pandas dataframe more effectively
<p>Here's my dataset <code>df1</code></p> <pre><code>Id Value month Year 1 672 4 2020 1 356 6 2020 2 682 6 2019 3 366 4 2021 </code></pre> <p>Here's my dataset <code>df2</code></p> <pre><code>Id Value month Year 1 671 4 2020 1 353 6 ...
<p>Another option is to use <code>mask</code>:</p> <pre><code>df = df1.mask((df1['month'].ge(5) &amp; df1['Year'].eq(2020)) | df1['Year'].ge(2021), df2) </code></pre> <p>Output:</p> <pre><code> Id Value month Year 0 1 672 4 2020 1 1 353 6 2020 2 2 682 6 2019 3 3 363 4 20...
python|pandas|dataframe
3
2,492
72,099,844
mat1 and mat2 shapes cannot be multiplied (19x1 and 19x1)
<p>I have a handmade dataset and all want to do is set a linear regression model with Pytorch. These are the codes I wrote:</p> <pre><code>from torch.autograd import Variable train_x = np.asarray([1,2,3,4,5,6,7,8,9,10,5,4,6,8,5,2,1,1,6]) train_y = train_x * 2 X = Variable(torch.from_numpy(train_x).type(torch.FloatTen...
<p>If you are using a <a href="https://pytorch.org/docs/stable/generated/torch.nn.Linear.html" rel="nofollow noreferrer"><code>torch.nn.Linear(a,b)</code></a> as part of a network, then the input must be of shape <code>(n, a)</code>, and the output will be of shape <code>(n, b)</code>. Therefore you need to make sure t...
python|deep-learning|pytorch|tensor
0
2,493
17,003,034
Missing data in pandas.crosstab
<p>I'm making some crosstabs with pandas:</p> <pre><code>a = np.array(['foo', 'foo', 'foo', 'bar', 'bar', 'foo', 'foo'], dtype=object) b = np.array(['one', 'one', 'two', 'one', 'two', 'two', 'two'], dtype=object) c = np.array(['dull', 'dull', 'dull', 'dull', 'dull', 'shiny', 'shiny'], dtype=object) pd.crosstab(a, [b,...
<p>The crosstab function has a parameter called dropna which is set to True by default. This parameter defines whether empty columns (such as the one-shiny column) should be displayed or not.</p> <p>I tried calling the funcion like this:</p> <pre><code>pd.crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c'], dropn...
python|pandas
7
2,494
18,831,732
Error on trying to use Dataframe.to_json method
<p>I'm trying to export a pandas dataframe to JSON with no luck. I've tried:</p> <p>all_data.to_json("spdata.json") and all_data.to_json()</p> <p>I get the same attribute error on both: <strong>'DataFrame' object has no attribute 'to_json'</strong>. Just to make sure something isn't wrong with the DataFrame, i tested...
<p>The <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_json.html" rel="nofollow"><code>to_json</code></a> method was <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#i-o-enhancements" rel="nofollow">introduced to 0.12</a>, so you'll need to <a href="http://pandas.pyd...
json|python-2.7|pandas
3
2,495
22,127,051
Noise while altering audio data
<p>I am playing audio with python and i don't understand why i hear noise on the ouptut when executing code like this: </p> <pre><code>import pyaudio import wave import numpy as np f = wave.open('blabla.wav',"r") p = pyaudio.PyAudio() # open stream stream = p.open(format = p.get_format_from_width(f.getsamp...
<p>I think 16 bit PCM is usually signed. Try using <code>int16</code> instead of <code>uint16</code></p>
python|audio|numpy|stream|real-time
1
2,496
22,053,050
Difference between numpy.array shape (R, 1) and (R,)
<p>In <code>numpy</code>, some of the operations return in shape <code>(R, 1)</code> but some return <code>(R,)</code>. This will make matrix multiplication more tedious since explicit <code>reshape</code> is required. For example, given a matrix <code>M</code>, if we want to do <code>numpy.dot(M[:,0], numpy.ones((1, R...
<h3>1. The meaning of shapes in NumPy</h3> <p>You write, "I know literally it's list of numbers and list of lists where all list contains only a number" but that's a bit of an unhelpful way to think about it.</p> <p>The best way to think about NumPy arrays is that they consist of two parts, a <em>data buffer</em> whi...
python|numpy|matrix|multidimensional-array
674
2,497
55,373,997
How to set the default parameters of Conv2D in tf.keras?
<p>Support i have a network with 5 convolution. I write it by Keras.</p> <pre class="lang-py prettyprint-override"><code>x = Input(shape=(None, None, 3)) y = Conv2D(10, 3, strides=1)(x) y = Conv2D(16, 3, strides=1)(y) y = Conv2D(32, 3, strides=1)(y) y = Conv2D(48, 3, strides=1)(y) y = Conv2D(64, 3, strides=1)(y) </cod...
<p>Keras provides no way to change the defaults, so you can just make a wrapper function:</p> <pre><code>def myConv2D(filters, kernel): return Conv2D(filters, kernel, strides=1, kernel_initializer=tf.glorot_uniform_initializer()) </code></pre> <p>And then use it as:</p> <pre><code>x = Input(shape=(None, None, 3)...
python|tensorflow|keras|tf.keras
3
2,498
55,320,491
Pandas export to_excel error: 'DataFrame' object has no attribute 'data'
<p>I use the following code to try and make a dataframe from a Tf-Idf vectorizer. The output of the vectorizer's fit_transform is a sparse matrix so I use toarray() to convert to array, and then pandas.DataFrame to convert to dataframe. I also extract the list of features using vectorizer.get_feature_names() and use th...
<p>Solved it by passing column names as header parameter for the pandas.to_excel() rather than including it in the dataframe as column names. Still not sure how to overcome this problem at the root and make it consider "render" as a proper column heading.</p> <pre><code>df2 = pd.DataFrame(X.toarray()) df2.to_excel("te...
python|pandas|scikit-learn|tfidfvectorizer
1
2,499
55,461,990
Fetching information from the different links on a web page and writing them to a .xls file using pandas,bs4 in Python
<p>I am a beginner to Python Programming. I am practicing web scraping using bs4 module in python.</p> <p>I have extracted some fields from a web page but it is extracting only 13 items whereas the web page has more than 13 items. I cannot understand why are the rest of the items not extracted. </p> <p>Another thing ...
<p>I am convinced that the emails are no where in the DOM. I made some modification to @drec4s code to instead go until there are no entries (dynamically).</p> <pre><code>import requests from bs4 import BeautifulSoup as bs import pandas as pd import itertools headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Wi...
python|pandas|web-scraping|beautifulsoup
0