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
351,400
33,169,792
Default numpy vs accelerate in Anaconda
<p>I have just installed numpy-1.10.1 through Anaconda in a Python 2.7.10 environment, in Windows. To my surprise, I discovered that it has MKL out-of-the-box (see the config below). I ran <a href="https://software.intel.com/sites/default/files/m/6/7/1/0/5/41177-Examples.py" rel="nofollow noreferrer">a benchmark</a> ag...
<p>Using the benchmarking script linked in the question, I can see that numpy in accelerate and just numpy in Anaconda provide the same performance. </p> <p><a href="https://i.stack.imgur.com/A6isL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A6isL.png" alt="Numpy with accelerate vs numpy in Anac...
numpy|anaconda|intel-mkl
1
351,401
33,106,318
How to detect and eliminate outliers from a changing dataset
<p>I have a dataset which contains pixel values of a certain object by frame. My code can detect the object accurately most of the time; yet, there are negatives.</p> <p>I plotted first 600 values (x-axis: frame number, y-axis: pixel location of object). In first image, you can see raw data; in second image, you can s...
<p><a href="https://en.wikipedia.org/wiki/RANSAC" rel="nofollow">RANSAC</a> is a technique to ignore outliers and select only inliers for any computation. </p> <p>Since this case does not have a mathematical function to fit in the data, you cannot apply RANSAC directly.</p> <p>But, as a work around, by looking into t...
python|numpy|dataset|computer-vision|outliers
0
351,402
33,385,763
find Markov steady state with left eigenvalues (using numpy or scipy)
<p>I need to find the steady state of Markov models using the left eigenvectors of their transition matrices using some python code.</p> <p>It has already been established in <a href="https://stackoverflow.com/questions/15560905/is-scipy-linalg-eig-giving-the-correct-left-eigenvectors">this question</a> that scipy.lin...
<p>You linked to <a href="https://stackoverflow.com/questions/11953867/how-do-i-find-out-eigenvectors-corresponding-to-a-particular-eigenvalue-of-a-mat">How do I find out eigenvectors corresponding to a particular eigenvalue of a matrix?</a> and said it doesn't compute the left eigenvector, but you can fix that by work...
python|numpy|scipy|eigenvector|markov-chains
6
351,403
33,234,260
Pandas multiindex boolean indexing
<p>So given a multiindexed dataframe, I would like to return only rows that satisfy a condition for all levels of the lower index in a multi index. Here is a small working example:</p> <pre><code>df = pd.DataFrame({'a': [1, 1, 2, 2], 'b': [1, 2, 3, 4], 'c': [0, 2, 2, 2]}) df = df.set_index(['a', 'b']) print(df) </co...
<p>I ended up using <code>groupby</code>:</p> <pre><code>df.groupby(level=0).filter(lambda x: all([c &gt; 1 for v in x['c']])) </code></pre>
python|pandas|boolean|multi-index|booleanquery
0
351,404
33,263,191
Defining a multidimensional field with nonstandard domain
<p>I have an array <code>a</code> in Python, let's say <code>a=np.array([3, 4])</code>, and would like to define an ndarray (or something like that) of type [-3:3, -4:4], in other words, a collection x of real numbers <code>x[-3,-4], x[-3,-3],...,x[3,4]</code>, the i'th coordinate ranging over integers between -a[i] an...
<p>You could generate a list of ranges with</p> <pre><code>[np.arange(-x,x+1) for x in a] </code></pre> <p>I'd have to play around with <code>mgrid</code>, or another function in <code>index_tricks</code> to figure how to use it. I may to make it a <code>tuple</code> or pass it with a <code>*</code>.</p> <hr> <p><...
python|numpy|multidimensional-array
3
351,405
9,164,269
Can you tell if an array is a view of another?
<p>Do numpy arrays keep track of their "view status"?</p> <pre><code>import numpy a = numpy.arange(100) b = a[0:10] b[0] = 100 print a[0] # 100 comes out as it is a view b is a[0:10] # False (hmm how to ask?) </code></pre> <p>What I am looking for is <code>numpy.isview()</code> or something.</p> <p>I want this for c...
<p>the array also has a base attribute:</p> <pre><code>a = np.arange(10) print a.base None b = a[2:9] print b.base is a True c = b[:2] print c.base is b True print c.base is a False </code></pre>
python|numpy
5
351,406
6,015,243
Why is vectorization beneficial for Matlab programs? Is it the same for NumPy and Boost(uBLAS)?
<p>Using vectorization to replace for-loops may increase Matlab programs' speed significantly. Is it because the vectorized codes are runned in parallel?</p> <p>Is vectorization also beneficial for program using NumPy or uBLAS?</p>
<p>"Vectorized" code is usually faster in interpreted environments like Matlab and numpy because the vectorized versions often (but not always) run pre-compiled and optimized code written in C or FORTRAN. Parallel execution may, or may not, play a role in this.</p> <p>Use vectorization in numpy usually results in perf...
matlab|boost|numpy|vectorization|ublas
8
351,407
66,653,357
Error overlapping layer name when loading a keras model
<p>I have trained a composed model on keras, with one training on images using transfer learning from inception_v3 and one training on numerical feature, I had to rename the layers of the two models when creating the composed model to prevent overlapping names and it worked.</p> <pre><code>i=0 for layer in model.layers...
<p>A suggestion would be to change the model names while loading the models. The following code has not been tested.</p> <pre><code>model_1 = keras.models.load_model('tf/pvc_data/train_checkpoints/combined_model.h5') model_1._name = 'inceptionv3_images' model_2 = keras.models.load_model('tf/pvc_data/train_checkpoints/c...
python|tensorflow|keras|neural-network
0
351,408
66,472,530
Generate 8 bit image with numpy
<p>I'm trying to generate an image of all 8 bit colours. And this is the important bit: 1 pixel represents 1 unique colour. That's 2^8 or 256 colours - should be a 32 x 32 image.</p> <p>The plan is to be able to change the bit depth and create a different image. ie 65536 colours for 16 bit.</p> <p>Here's what I have:</...
<p>First of all, your colormap generates an array of values in the following fashion:</p> <pre class="lang-py prettyprint-override"><code>In [71]: mymap = cmap(np.linspace(0, 1, 2 ** bit)) In [72]: mymap Out[72]: array([[0.267004, 0.004874, 0.329415, 1. ], [0.26851 , 0.009605, 0.335427, 1. ], [...
python-3.x|numpy|colors
1
351,409
66,473,092
Complete a string column according to a condition on other columns
<p>Let's take this sample dataframe :</p> <pre><code>df=pd.DataFrame({'V1':[1,2,np.nan,4,np.nan], 'V2':[-9,8,-7,0,np.nan], 'Label':['a','b','c','d','e']}) V1 V2 Label 0 1.0 -9.0 a 1 2.0 8.0 b 2 NaN -7.0 c 3 4.0 0.0 d 4 NaN NaN e </code></pre> <p>I would like to add '_same_sign' to the ...
<p>Your loopy solution with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>DataFrame.apply</code></a> and <code>axis=1</code>:</p> <pre><code>df['Label'] = df.apply(lambda x : x['Label'] + '_same_sign' if x['V1']*x['V2']&gt;0 else x['Label...
python|pandas|dataframe|apply
1
351,410
66,627,143
Condensing 5 lists containing 30 dictionaries each into single dataframe
<p>I have 5 lists that contain 30 dictionaries each. Each dictionary has two key value pairs, team_name and fd_points which represents how many points per game that team gives up to that opposing position, for example:</p> <pre><code>point_guards = [ {'team_name': 'NOR', 'fd_points': '56.15'}, {'team_name': 'ORL', 'fd_...
<p>Apart from your 2 lists of dictionaries I created another list - the source for <em>SF_points</em>:</p> <pre><code>sf_src = [ {'team_name': 'NOR', 'fd_points': '44.01'}, {'team_name': 'ORL', 'fd_points': '49.12'}] </code></pre> <p>The first step is to create individual DataFrames, holding these 3 lists:</p> ...
python|pandas|selenium
0
351,411
66,727,017
How gradients are accumulated in real
<p>‘Gradient will not be updated but be accumulated, and updated every N rounds.’ I have a question that how the gradients are accumulated in the below code snippet: in every round of the below loop I can see a new gradient is computed by loss.backward() and should be stored internally, but would this internally stored...
<p>The first time you call backward, the <code>.grad</code> attribute of the parameters of your model will be updated from <code>None</code>, to the gradients. If you do not reset the gradients to zero, future calls to <code>.backward()</code> will accumulate (i.e. add) gradients into the attribute (see <a href="https:...
pytorch|gradient
1
351,412
66,380,324
Converting data in byte format to Pandas Dataframe
<p>I have an output in the below bytes format. I would like to convert it to a Pandas Dataframe.</p> <p>Actual Data</p> <pre><code>b'{&quot;code&quot;:200,&quot;data&quot;:{&quot;facilities&quot;:[ {&quot;ref_id&quot;:&quot;101&quot;,&quot;ref_name&quot;:&quot;Product A&quot;,&quot;features&quot;:{&quot;features1&quo...
<p>Try <code>json</code> and <code>pd.json_normalize</code>:</p> <pre><code>import json # parse json to a dictionary data = json.loads(s) df = pd.json_normalize(data, record_path=['data','facilities']) </code></pre> <p>Output:</p> <pre><code> ref_id ref_name features.features1 features.features2 0 101 Product ...
python|pandas
1
351,413
66,746,626
ImportError: cannot import name 'download_url_to_file'
<p>I tried to run a <strong>Python</strong> script that uses the <strong>download_url_to_file</strong> method inside the <strong>torch hub</strong>, but I got the following error:</p> <pre><code>Traceback (most recent call last): File &quot;crop-video.py&quot;, line 1, in &lt;module&gt; import face_alignment Fi...
<p>Worked in my Pc<br /> use <code>torch == 1.6</code><br /> <a href="https://i.stack.imgur.com/8BD6v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8BD6v.png" alt="enter image description here" /></a></p>
python|pytorch|torch|python-2.6|torchvision
-1
351,414
66,755,828
Reshaping array with specified indices
<p>Is there any better way to do this? Like replacing that list comprehension with numpy functions? I'd assume that for a small number of elements, the difference is insignificant, but for larger chunks of data it takes too much time.</p> <pre><code>&gt;&gt;&gt; rows = 3 &gt;&gt;&gt; cols = 3 &gt;&gt;&gt; target = [0, ...
<p>Another way:</p> <pre><code>shape = (rows, cols) arr = np.zeros(shape) arr[np.unravel_index(target, shape)] = 1 </code></pre>
python|arrays|numpy|reshape
4
351,415
66,754,904
Replace val in df with boolean indexing - pandas
<p>I'm trying to replace a value in a pandas col using logical operator <code>&amp;</code>. Using below, where <code>Label == A</code> and <code>Value is == np.nan</code>, I want to replace Value with <code>X</code>.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({ 'Time' : [1,1,2,2,...
<h3><code>isna</code></h3> <p>The point of <code>np.nan</code> is that it is <em><strong>N</strong></em>ot <em><strong>A</strong></em> <em><strong>N</strong></em>umber. If you treat it like one, you get <code>False</code>. It isn't even equal to itself, by design.</p> <p>Instead use Pandas <code>isna</code>/<code>not...
python|pandas
2
351,416
66,442,916
Bivariate Poisson Distribution in Python
<p>I would like to draw N times from a bivariate Possion distribution. Is there a Python module similar to the package <code>bivpois</code> in R?</p> <p>In Python, I only know the libraries <code>scipy.stats.poisson</code> and <code>numpy.random.possion</code> which allow me to make draws from a <strong>univariate Pois...
<p>You can do it by yourself pretty easily since I don't see any built-in method:</p> <p><a href="https://en.wikipedia.org/wiki/Poisson_distribution#Bivariate_Poisson_distribution" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Poisson_distribution#Bivariate_Poisson_distribution</a></p> <p>Steps:</p> <ol> <li>...
python|numpy|scipy|poisson
2
351,417
66,378,949
Merging columns with same same using pandas
<p>I have the following data in CSV file:</p> <pre><code>time conc time conc time conc time conc 1:00 10 5:00 11 9:00 55 13:00 1 2:00 13 6:00 8 10:00 6 14:00 4 3:00 9 7:00 7 11:00 8 15:00 3 4:00 8 8:00 1 12:00 11 16:00...
<p>One approach is to cut the dataframe in two-column slices, then re-combine using pd.concat() after renaming. First load the dataframe normally:</p> <pre><code>df = pd.read_csv('time_conc.csv') df </code></pre> <p>Which looks something like the below. Notice that pd.read_csv() has added a suffix to the duplicate colu...
python|pandas|csv|merge|pandas-groupby
0
351,418
66,522,792
AND logical operator on 3 columns with OR in python
<p>So I am trying to make a boolean search program where the user inputs a keyword and it gets searched in my dataframe. I managed to do a 1-word search but I am having trouble with 2 words search input. I am taking 2 words from the user and trying to search and print them out but it doesn't seem to work. I have 4 colu...
<p>You already have everything you need, just chaining up <code>&amp;</code> and <code>|</code>. It could be something like this,</p> <pre><code>found_y = (keyword[&quot;One_key&quot;]==y) | (keyword[&quot;Two_key&quot;]== y) | (keyword[&quot;Third_key&quot;]==y) found_z = (keyword[&quot;One_key&quot;]==z) | (keyword[&...
python|pandas|dataframe
0
351,419
66,486,011
How can I get the count of consecutive positive number in each column in 2 dimensional df in python/ Padas
<pre><code> X y a 1.0 -1.0 b -2.0 2.0 c 3.0 -3.0 d 2.1 4.0 Output: x y a 1.0 -1.0 b -2.0 2.0 c 3.0 -3.0 d 2.1 4.0 Count 2 1 </code></pre> <p>As on the first column, the count is reset to 0 on row b because of -2. The result needs to be a df with the count app...
<p>There is a pure <code>numpy</code> way without <code>groupby</code> (in other words: likely to be very fast). It also counts runs of strictly positive values (excluding 0):</p> <pre class="lang-py prettyprint-override"><code>def countpos(x): return np.diff(np.where(np.hstack((-1, x, -1)) &lt;= 0)[0]).max() - 1 ...
python|pandas|numpy
0
351,420
66,490,497
python category encoders on multiple columns
<p>I need to test several category encoders to different columns containing same values. All the values appear in the columns but not at the same row. For example, I could have:</p> <pre><code>dft = pd.DataFrame({ 'col0':[&quot;a&quot;, &quot;b&quot;, &quot;a&quot;, &quot;c&quot;, &quot;b&quot;, &quot;d&quot;], 'col1'...
<p>You can <strong><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a></strong> the dataframe to reshape then use <strong><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.get_dummies.html" ...
python|pandas|scikit-learn|categorical-data
1
351,421
66,455,097
Tensorflow: How to use a generator for fit() which runs in parallel with multiple processes
<p>I am trying to train a model on a data set which does not fit in my RAM. Therefore I am using a data generator which inherits from <code>tensorflow.keras.utils.Sequence</code> as shown below. This is working. However because I am doing processing on the images my training is CPU bound. When looking in GPU-Z my GPU i...
<p>In the end I needed to make the Data generator use multi processing. To do this, the arrays needed to be stored in shared memory and than used in the sub processes.</p> <pre><code>import multiprocessing as mp import numpy as np from PIL import Image as PImage from PIL import ImageFilter import random import math imp...
python-3.x|multithreading|multiprocessing|tensorflow2.0|keras-2
0
351,422
66,343,010
Iterate and replace NaN values with values from another dataframe
<p>Reading similar posts but don't seem to find the right solution - I'm trying to replace NaN values in a dataframe with the correct ones in a new dataframe. While I'm trying to iterate over the dataframe, I'm running into some errors.</p> <pre><code>masterdataframe |Date | Key | Column1 | Column2 | Column3 ...
<p>You could use <code>.update</code> to update all the values in masterdataframe with the values from df1. To do that you will need to set index to the Key column in both dataframes.</p> <pre><code>masterdataframe = masterdataframe.set_index('Key') df1= df1.set_index('Key') masterdataframe.update(df1) </code></pre> <p...
python|pandas|dataframe
1
351,423
66,723,770
Pandas Characters between two spaces
<p>I have dataframe like one below</p> <pre><code>df = pd.DataFrame({'vals': [1, 2, 3, 4, 5], 'ids': [u'a iball is', u'aaa vcat ll', u'c cnut bb', u'fdfdf qbell l', 'bxyz zbat c']}) </code></pre> <p>I am trying to replace the the first string of characters between the first and second space position with x in ids colum...
<p>use <code>str.replace</code> with capturing groups.</p> <p><code>\1</code> will apply to the first word after a space at the start of a string.</p> <p><code>^</code> asserts a pattern at the start of a line.</p> <p><code>\w</code> matches any word [A-Za-z0-9_]</p> <p><code>+</code> is a greedy match to match the pre...
python|pandas
2
351,424
66,394,626
Neural Network Backpropogation code not working
<p>I need to write a simple neural network that consists of 1 output node, one hidden layer of 3 nodes, and 1 input layer (variable size). For now I am just trying to train on the xor data so lets presume that there are 3 input nodes (one node represents the bias and is always 1). The data is labeled 0,1.</p> <p>I did ...
<p>It appears you are attempting to setup a manual version of stochastic gradient decent with a fixed learning rate (a classic NN problem).</p> <p>Some notes on your code. It is very difficult to follow all the steps you are doing with so much loops and inconsistencies. In general, it defeats the purpose of using np.ar...
python|python-3.x|numpy|machine-learning|neural-network
0
351,425
66,343,862
How to create a 1 to 1 feed forward layer?
<p>I'm familiar with a fully connected layer, but how can I create a custom layer in PyTorch that is just 1 to 1? That is, each neuron is only connected to 1 other neuron.<br /> Example: Layer 1 neurons: a,b,c<br /> Layer 2 neurons d,e,f<br /> Connections:<br /> a-d<br /> b-e<br /> c-f</p>
<p>Linear layers are basically just describing a matrix multiplication. And since this is not what you want you can't use the Pytorch implementation <code>nn.Linear</code>. You want to have each weight correspond to just one input neuron and one output neuron. That would mean that the amount of output neurons must be t...
python|neural-network|pytorch
2
351,426
66,392,238
How to handle wildcard in a raw string in python
<p>I have a script I run daily to compile a bunch of spreadsheets into one. Well after a year of running one of the filenames changed due to it being produced 14 seconds later. I read the filename in like this</p> <pre><code>uproduction = Path(r&quot;\\server\folder\P&quot;+year+month+day+r&quot;235900.xls&quot;) an...
<p>You can use <code>glob</code>:</p> <pre><code>from glob import glob glob(r&quot;\\server\folder\P&quot;+year+month+day+&quot;*.xls&quot;) </code></pre>
python|pandas
3
351,427
66,710,023
Pandas group by two column with swapped values in other 4 columns
<p>I have a large Pandas DataFrame with many columns. I would like to make sure that Column C and Column E contains value in same order.</p> <p>For example: If <code>first two rows shows (red and green) &amp; third row shows (Green and red)</code> then <code>third row should change it to red and green</code> as shown ...
<ul> <li>Simulating your data</li> <li>simulating condition - where an earlier row exists with columns in opposite order</li> <li>swap columns is done using a <strong>mask</strong> and a <code>rename()</code></li> </ul> <pre><code>import itertools colors = [&quot;Red&quot;,&quot;Green&quot;,&quot;Blue&quot;,&quot;Purpl...
python|pandas|numpy|itertools
1
351,428
66,641,829
How to define a “don't care” class in Pytorch?
<p>I have a time series classification task in which I should output a classification of 3 classes for every time stamp <code>t</code>.</p> <p>All data is labeled per frame.</p> <p>In the data set are more than 3 classes [which are also imbalanced].</p> <p>My net should see all samples sequentially, because it uses tha...
<p>Following from <a href="https://discuss.pytorch.org/t/when-to-use-ignore-index/5935" rel="nofollow noreferrer">this discussion</a>, which was not google searchable, there are two options, both are options of the <a href="https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html" rel="nofollow noreferr...
python|deep-learning|pytorch|loss|cross-entropy
1
351,429
66,599,286
Converting MSSQL database to GeoJSON format
<p>I'm trying to use Python to access an MSSQL database and then write the results out to a GeoJSON file. So far I have this code, but I can't get a working end part which saves the file to my directory</p> <pre><code>import pandas as pd import pyodbc import geojson import json from geojson import Feature, FeatureColle...
<p>Try to add json.dump(geojson) before you write it to your file. Also you should not import the modules twice in line 3 and 5.</p>
python|sql|pandas|geojson
0
351,430
66,695,292
When I try to replace a portion of a numpy array, nothing happens
<p>I have the following code</p> <p>currSub is a Dataframe with length 2850, and I extract the timestamps (the numbers 1 to 2850) and a vector of probabilities of the same length.</p> <p>My Goal is to place the vector currProb inside the vector realign, starting at the position 50, and leaving the other zeros unchanged...
<p><code>realign</code> has dtype <code>int64</code>. When you assign floating-point values to it, they get converted to the integer type, which means they are rounded down.</p> <p>Since <code>subProb</code> contains 0.5, you replace existing 0 values by new 0 values.</p> <p>To avoid this, create <code>realign</code> w...
python|arrays|numpy|indexing
0
351,431
66,676,358
Filter judge to include pitches from 2017 only and select the events column. Store the result in a variable called judge_events_2017
<p>I am having trouble with the date. The format of the dates are year-month-day such as '2017-01-01.' I am fairly new to python and am struggling to find out how to get between '2017-01-01' and '2017-12-31.' I know this is how I had done it on previous homeworks when I was looking for &quot;after&quot; a certain date....
<p>Your strings are in a very particular format <code>'YYYY-MM-DD'</code>, which means that fortunately the string sorting of dates is equivalent to how they would be sorted as a numeric. You can obtain all dates in 2017 is a variety of ways (I'd go with the datetime solution).</p> <p>Also avoid the chained selection,...
python|pandas|dataframe|date|methods
0
351,432
66,431,991
How to delete CSV specific row.(like user_name = Max)
<p>I have a CSV file of around 40K rows. And I want to delete 10K rows with conditions(eg: user_name = Max). And my data is like :</p> <pre><code>user1_name,user2_name,distance &quot;Unews&quot;,&quot;CCSSuptConnelly&quot;,&quot;&quot; &quot;Unews&quot;,&quot;GwapTeamFre&quot;,&quot;&quot; &quot;Unews&quot;,&quot;Wilso...
<p>You can use the Pandas library for this kind of problems and then use the .loc[] function. Link to the docs: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer">Loc Function in pandas</a></p> <pre><code>import pandas as pd df = pd.read_csv('name.c...
python|pandas|csv|delete-row
0
351,433
66,626,708
np.insert() into an empty ndarray
<p>This is what I wrote:</p> <pre><code>import numpy as np a = np.array([[]]) np.insert(a, 0, 1, axis=1) </code></pre> <p>My code just ignores the insert line for some reason. I even tried np.put_along_axis() but it's showing an error</p> <p>I just want to insert or append or put a number into an ndarray. This forces...
<p>Referring to the <a href="https://numpy.org/doc/stable/reference/generated/numpy.insert.html" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>Returns: out: ndarray</p> </blockquote> <blockquote> <p>A copy of arr with values inserted. Note that insert does not occur in-place: a new array is returned....
python|numpy-ndarray
0
351,434
66,453,575
Filter rows with more than 1 value in a set and count their occurrence pandas python
<p>Let's assume, I have the following data frame.</p> <pre><code>Id Combinations 1 (A,B) 2 (C,) 3 (A,D) 4 (D,E,F) 5 (F) </code></pre> <p>I would like to filter out <code>Combination</code> column values with more than value in a set. Something like below. AND I would like count the number of ...
<p>First if necessary convert values to lists:</p> <pre><code>df['Combinations'] = df['Combinations'].str.strip('(,)').str.split(',') </code></pre> <p>If need count after filtering only one values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.len.html" rel="nofollow noreferrer"...
python|pandas
2
351,435
66,498,896
Group time Data in Pandas DataFrame
<p><a href="https://i.stack.imgur.com/JvMMx.png" rel="nofollow noreferrer">I have time given in this format and I want to Group them in 6 categories like Early morning, Afternoon, Evening, etc. How can change the time format into categories? Is there any inbuilt library in Python that can help me do it </a></p>
<p>I'd do it somewhat like that I guess.</p> <pre><code>import pandas as pd # obviously you need to import the values from an external file. time_list = [&quot;10:00:00&quot;, &quot;13:30:00&quot;, &quot;09:30:00&quot;, &quot;10:22:00&quot;, &quot;01:00:00&quot;] df = pd.DataFrame({&quot;time&quot;:time_list}) # once...
python|pandas
0
351,436
66,631,388
What is this grammar?
<p><code>(x_train, y_train), (x_test, y_test) = mnist.load_data()</code></p> <p>This is tensorflow example, but I can't understand what it means I know purpose of x_train, y_train, x_test, y_test but I want to know how those are assigned. What kind of mechanism it is. Thank you</p>
<p>It's called tuple or iterable unpacking. <code>mnist.load_data()</code> must return a sequence of two two-tuples:</p> <pre><code>&gt;&gt;&gt; (x_train, y_train), (x_test, y_test) = [(1,2),(3,4)] &gt;&gt;&gt; x_train 1 &gt;&gt;&gt; y_train 2 &gt;&gt;&gt; x_test 3 &gt;&gt;&gt; y_test 4 </code></pre> <p>It can be used ...
python-3.x|tensorflow
5
351,437
66,358,009
Using a key word to mark the beginning of reading a csv
<p>I have a csv with lots of information and then the actual data within the words $$SOE and $$EOE. It looks like this:</p> <pre><code>************************************************ (many lines of info) ************************************************ $$SOE 1978-Jan-01 00:00, , , 52.06147, 20.73814, 1978-Jul-...
<p>Pandas.read_csv has 'skiprows' and 'skipfooter' options, so if you know how many rows that stuff takes up at the top and bottom of your file you can pass the number of rows in to those options when reading the file.</p>
python|pandas|dataframe|csv
0
351,438
66,454,206
Python error arrays used as indices must be of integer (or boolean) type
<p>Hello I have the following script:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt m = int(input(&quot;lenght of t and b. m = &quot;)) t = 27 * np.random.random( (m, 1) ) b = 27 * np.random.random( (m, 1) ) A = np.ones( (m, 1) ) A = np.hstack( (A, t) ) x = np.linalg.solve( np.dot(A.T, A), np...
<p>This error may also happen when the DataFrame or numpy array has NaN values. It can be fixed like this:</p> <pre><code>df.fillna(0) </code></pre> <p>Or any other suitable <code>fillna()</code> strategy</p>
python|numpy|matplotlib
1
351,439
66,340,113
Python: append images in for loop use a lot of memory
<p>I'm actually facing a problem while working on a python project. I'm appending some images in a for loop and it uses a lot of RAM memory.</p> <p>If you guys, have any solution to optimize this for loop, It'll help me a lot.</p> <p>Thanks!</p> <pre><code>augment_img = [] augment_label = [] augment_weight = [] for i i...
<p>Instead of loading all images at once, I would suggest loading them in batches. There are different ways to handle that. In both <code>pytorch</code> and <code>tensorflow</code>, you can save your weights and continue training after some point. So, you can:</p> <ul> <li>iterate through your images in batches</li> <l...
python|python-3.x|pytorch
1
351,440
66,478,030
Why I have two legends ? How to fusion the legends ? Python
<p>I'm plotting 2 dataframes with this method:</p> <pre><code>df.plot(ax=ax, x='x', y='y', label = &quot;first_df&quot;) df2.plot(ax=ax, x='x', y='y', label = &quot;second_df&quot;) </code></pre> <p>And I add some avxspan functions:</p> <pre><code>plt.axvspan(x, y, label = value) </code></pre> <p>Since that I have mult...
<p>In stead of using <code>df.plot</code> which creates a legend whenever it's called, you can use <code>ax.plot</code>:</p> <pre><code>ax.plot(df['x'], df['y'], label='first df') ax.plot(df2['x'], df2['y'], label='second df') ax.legend() </code></pre>
python|pandas|dataframe|matplotlib
1
351,441
66,683,775
Generate QR code by looping through rows in specific dataframe column
<p>I'm a python newbie and the similar questions on stackoverflow regarding this just didn't make sense.</p> <p>I have the following table below. My goal is to create a fourth column, combining the data from the first 3, to create unique URLs. For each row in the fourth column, I need to generate a new QR Code. How can...
<p>This is a way how to loop by rows of 4 column</p> <pre><code>for row in list(df[&quot;FourthColumn&quot;]): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=2, ) qr.add_data(row) qr.make(fit=True) ...
python|pandas
0
351,442
66,342,637
Pytorch N - Beats model throwing error: 'str' object has no attribute '__name__'
<p>I'm trying to replicate pytorch's N - Beats model in colab. I copied the same code from <a href="https://pytorch-forecasting.readthedocs.io/en/stable/tutorials/ar.html" rel="nofollow noreferrer">https://pytorch-forecasting.readthedocs.io/en/stable/tutorials/ar.html</a> to a colab notebook. There is an error showing ...
<p>Ran into a similar issue recently and found that downgraded pandas to 1.2.5 resolved that</p>
machine-learning|pytorch|pytorch-lightning
1
351,443
66,690,233
Why is pytorch softmax function not working?
<p>so this is my code</p> <pre><code>import torch.nn.functional as F import torch inputs = [1,2,3] input = torch.tensor(inputs) output = F.softmax(input, dim=1) print(output) </code></pre> <p>is the reason why the code not working because of the dim? the error here:</p> <pre><code> File &quot;c:\Users\user\Desktop\AI...
<p>Apart from <code>dim=0</code>, there is another issue in your code. <code>Softmax</code> doesn't work on a <code>long tensor</code>, so it should be converted to a <code>float</code> or <code>double</code> tensor first</p> <pre><code>&gt;&gt;&gt; input = torch.tensor([1, 2, 3]) &gt;&gt;&gt; input tensor([1, 2, 3]) ...
python|pytorch
0
351,444
66,552,440
Pandas - assign column values to new columns names
<p>I have this dataframe:</p> <pre><code>player_id scout_occ round scout 812842 2 1 X 812842 4 1 Y 812842 1 1 Z 812842 1 2 X 812842 2 2 Y 812842 2 2 Z </code></pre> <p>And I need to transpose 'scout' va...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html" rel="nofollow noreferrer">pivot_table</a>. For example:</p> <pre><code>df = df.pivot_table(values='scout_occ',index=['player_id','round'],columns='scout') </code></pre> <p>Then if you don't want to use column name(<stron...
pandas
2
351,445
66,605,694
Vectorize row-level matching operation in Pandas DataFrame
<p>I have a pandas DataFrame of basketball play-by-play data of the following format (simplified):</p> <pre><code> Shooter h1 h2 h3 h4 h5 th1 th2 th3 th4 th5 0 K. Irving K. Love K. Irving L. James T. Thompson D. Liggins 0.5 1.4 5.3 4.8 4.3 1 K. Love K....
<p>I couldn't find a straightforward way to do it. So my workaround is:</p> <pre><code>import pandas as pd mask = df[[&quot;h1&quot;,&quot;h2&quot;,&quot;h3&quot;,&quot;h4&quot;,&quot;h5&quot;]].eq(df[&quot;Shooter&quot;],axis=0) </code></pre> <p>mask:</p> <pre><code>h1 h2 h3 h4 h5 False True F...
python|pandas|dataframe
1
351,446
66,419,073
Handle CSV file to txt file
<p>I want to convert many CSV files(for each CSV file, I just need The first five elements of the first column) into a text file. And here is my code.</p> <p>import pandas as pd import os</p> <pre><code>for root, dirs, files in os.walk(&quot;./data_v6/level3/&quot;): count = 1 for dir in dirs: print(dir...
<p>You are trying to use a high power hammer drill where a simple screwdriver would be more appropriate. Pandas is indeed a very powerful library that nicely handles csv files with automatic type detection, but you do not need all of that: you only need the 4 first fields of the first column.</p> <p>Just use the csv mo...
python|pandas|csv
0
351,447
66,665,396
Group by in Python Pandas (Multiple columns join with , )
<p>I have a table in CSV just like this:</p> <p><a href="https://i.stack.imgur.com/nsah3.png" rel="nofollow noreferrer">Base CSV</a></p> <p>And i need to group it just like this:</p> <p>In all my <code>CONCURSO</code> only <code>CIDADE</code> and <code>UF</code> change.</p> <p><a href="https://i.stack.imgur.com/ILUPR.p...
<p>The <code>agg()</code> method of Pandas can take a dictionary for the <code>func</code> parameter. This dict maps the column and its aggregation function.</p> <p>I guess you can then do the following:</p> <pre class="lang-py prettyprint-override"><code>columns_to_aggregate = [&quot;Cidade&quot;, &quot;UF&quot;] colu...
python|pandas|group-by|pandas-groupby
0
351,448
66,498,403
Slicing data frame with datetime columns (Python - Pandas)
<p>Through the loc and iloc methods, Pandas allows us to slice dataframes. Still, I am having trouble to do this when the columns are datetime objects.</p> <p>For instance, suppose the data frame generated by the following code:</p> <pre><code>d = {'col1': [1], 'col2': [2],'col3': [3]} df = pd.DataFrame(data=d) dates =...
<pre> <code> df.iloc[0,[0,1]] </code> </pre> <p>Use iloc or loc , but give column name in second parameter as index of that columns and you are passing strings, just give index</p>
python|pandas|dataframe|datetime|slice
1
351,449
66,595,055
Fastest way of computing binary mask IOU with numpy
<p>I'm looking for the fastest way to compute the intersection over union (Jaccard Index) of two binary masks (2d arrays of 1s and 0s) in numpy of the exact same shape. My code for computing this is:</p> <pre><code>import numpy as np def binaryMaskIOU(mask1, mask2): mask1_area = np.count_nonzero(mask1 == 1) ma...
<p>I initialy posted an answer, realised I'd over complicated it and when I went to edit it found the timings were worse than the original function. That's been deleted.</p> <p>The code in the question performs close to the others.<br /> There's no need for the two <code>maskN == 1</code> in the <code>logical_and</cod...
numpy|optimization
2
351,450
66,479,620
How to implement FocalLoss in Pytorch?
<p><a href="https://arxiv.org/pdf/1708.02002.pdf" rel="nofollow noreferrer">Focal Loss</a> is a loss aimed at addressing class imbalance for a classification task.</p> <p>Here is my attempt</p> <pre><code>class FocalLoss(nn.Module): def __init__( self, weight=None, gamma=2., ...
<p>reduction='none'</p> <p>This is the culprit. Look at CrossEntropyLoss and you will see the default is reduction='mean'. That means that the output of XELoss is a tensor with only one element in it; [1, 2] turns to [1.5]. You can't call .backward() as-is on a tensor with more than one element in it. I suggest changin...
python|machine-learning|deep-learning|pytorch|loss-function
0
351,451
66,679,315
calculate a median value of pd.DataFrame() index based on values in the column
<p>Lets cay I have a pd.DataFrame() object that stores number of people that given age ang gender had stroke in the past. In mor visual way:</p> <pre><code>positive_by_gender.tail() </code></pre> <p>gives us:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">gender</...
<p>To follow your idea of creating an array and getting the median this way:</p> <pre><code>In [235]: df Out[235]: Female Male age 78 9.0 12.0 79 13.0 4.0 80 10.0 7.0 81 8.0 6.0 82 4.0 5.0 In [236]: df = df.astype(int) In [237]: df Out[237]: Female Male age ...
python|pandas|median
1
351,452
66,601,207
Tensorflow 2 Object Detection API - Convert .ckpt file to .pb / any saved model format for simple web app deployment
<p>I am trying to do object detection using TensorFlow Object detection API using ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8 model from TensorFlow model zoo. I'm able to detect single test images using the ckpt file (saved as ckpt-17.data-00000-of-00001)</p> <p>I need to convert this ckpt to some saved model file(.p...
<p>Correcting the file path format resolved the issue:</p> <pre><code>!python /content/RealTimeObjectDetectionStages/Tensorflow/models/research/object_detection/model_main_tf2.py --model_dir=/content/RealTimeObjectDetectionStages/Tensorflow/workspace/models/my_ssd_mobnet --pipeline_config_path=/content/RealTimeObjectDe...
tensorflow|object-detection|ckpt
0
351,453
66,435,981
How to use pandas to further process data in application/csv format
<p>I get a data from api ,the content type is :application/csv . Now I want to load this data into pandas , how can I do this? I try to use pandas.read_csv,but it failed.</p> <pre><code>response = requests.request(&quot;GET&quot;, url, headers=headers, data=payload) dataframe = pd.read_csv(response,sep=';',header=0) </...
<p>The <code>response</code> is just a response object, not the actual <code>content</code> (<code>resonse.content</code> in bytes) or <code>text</code> (<code>response.text</code> in unicode). If you use <code>response.text</code> you get the text from the response. To use this wit <code>pd.read_csv()</code>, you can ...
python|pandas
0
351,454
66,579,317
How to convert the list dictionary from a column value into column in pandas df?
<p>I have different columns and some of the columns contain a list and that list contains a further dictionary. I want to convert that list into the column and I am not sure what technique would be the best...</p> <p>Here is how my df looks:</p> <pre><code>Car Year Conv ...
<p>This is a quick and dirty solution</p> <pre><code>df['Conv - Action_type'] = df['Conv'].apply(lambda x: x[0]['action_type']) </code></pre>
python|pandas|list|dictionary|multidimensional-array
2
351,455
66,735,116
Boolean signature in Numba
<p>I had a go with Numba on some code of mine, and I got quite a performance improvement just by adding some @jit decorators, which was great.</p> <p>Trying to squeeze something more I would like to type the function output, as I need an array booleans only, and one of the function arguments is an integer. Nevertheless...
<p>Your call to <code>np.zeros</code> is breaking because <code>numba</code> requires actual <code>numpy</code>-like types when using the <code>nopython</code> flag. Just switch it to the <code>numpy</code> version and it should work just fine:</p> <pre><code>con = np.zeros(size, dtype=np.bool_) </code></pre> <p>On you...
python|numpy|numba
2
351,456
66,577,548
Average Amplitude (in dB) every second of audio file in Librosa
<p>I want to get an average amplitude of the sound file for every second. For example the average amplitude of 0-1 sec,1-2 sec, and so on. I tried reducing the sample rate to 1 but the value drops to 0 in that case.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from glob import glob import librosa...
<p>This will do average amplitude, which is usually going to be 0.</p> <pre><code>y, sr = lr.load(file) second = [] for s in range(0,len(y),sr): second.append( y[s:s+sr].mean() ) </code></pre> <p>This will do average <code>abs</code> amplitude.</p> <pre><code>y, sr = lr.load(file) second = [] for s in range(0,len(y...
python|numpy|librosa
1
351,457
66,702,428
finance using python DataFrame
<p>here is my code</p> <pre><code>from pandas import Series, DataFrame import datetime import requests import lxml import yfinance as yf import time from requests.exceptions import ConnectionError from bs4 import BeautifulSoup def web_content_div(web_content,class_path): web_content_div = web_content.find_all('d...
<pre><code>stock=['awr','dov','nwn','emr','gpc','pg','ph','mmm','ginf','jnj','ko','lanc','low','fmcb' 'cl','ndsn','hrl','abm','cwt','tr','frt','scl','swk','tgt','cbsh','mo','syy'] while(True): info_timestamp = [] info_price = [] info_change = [] info_exdate = [] info_volume = [] for stock_code...
python|pandas|dataframe
0
351,458
66,466,529
Formatting and summing up numbers with arrays
<p>I am trying to calculate the <code>T_Sum</code> value so that for the values that are greater than the <code>Vals</code> values in <code>Numbers</code> it will just add up to the <code>Vals</code> values for that element. For example, the first element of <code>Vals</code> is 60 and all the values within <code>Numbe...
<p>The end value of <code>np.arange</code> must be greater than 105, because it's not end inclusive.</p> <pre><code>Vals = np.arange(60, 106, 5) T_Sum = (Numbers[:,None] &gt; Vals).sum(axis=0) * Vals </code></pre>
python|arrays|numpy
1
351,459
66,446,115
NumPy efficiency in dataset preprocessing
<p>I am currently working on a research project relating to the use of neural networks operating on EEG datasets. I am using the BCICIV 2a dataset, which consists of a series of files containing trial data from subjects. Each file contains a set of 25 channels and a very long ~600000 time step array of signals. I have ...
<p>This is a partial answer bc the formatting in comments is kind of garbage but</p> <pre><code>def getIndex(raw, tagIndex): return int(raw.annotations[tagIndex]['onset']*250) def isEvent(raw, tagIndex, events): for event in events: if (raw.annotations[tagIndex]['description'] == event): r...
python|arrays|performance|numpy|data-preprocessing
1
351,460
66,513,395
In pandas, how to group row together if any value in the columns (or subset of columns) is common?
<p>I would like to group the row together based on the common value in any column.</p> <p>I have the table that look like this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>index</th> <th>email</th> <th>phone</th> <th>UserID</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>abc@gmail.com</t...
<p>Since you wish to keep working in the same dataframe, and because there is the possibility in overlap between types of groups, I suggest creating two extra columns with numbered groups:</p> <pre><code>df['email_groups'] = df.groupby(df.email).ngroup() df['phone_groups'] = df.groupby(df.phone).ngroup() </code></pre> ...
python|pandas|data-cleaning|data-wrangling
2
351,461
66,479,320
Can I somehow apply incremental values in groups, in Pandas?
<p>If I have a large dataframe in Pandas, let's say <strong>df</strong>:</p> <pre><code>item_serial_number, barcode 12312313-123123123 ABC 12312313-123123124 ABC ... 44312313-123123125 DEF 55512313-123123126 DEF </code></pre> <p>This df lists devices that have different physical sizes. So a different <em>amount</em...
<p>I think this is what you are looking for:</p> <pre><code>df['box_number'] = df.groupby('barcode').cumcount().floordiv(df['barcode'].map(bf.set_index('barcode')['items_per_box'].to_dict()),axis=0).add(1) </code></pre>
python|pandas|dataframe|apply
1
351,462
66,704,090
Pandas read_json() encoding = 'utf-8-sig' option is not working for BytesIO object (file-like object)
<p>When trying to load a <a href="https://jsonlines.org/" rel="nofollow noreferrer">jsonlines</a> file encoded in UTF8-BOM as Bytes data directly into pandas dataframe, getting error 'ValueError' object has no attribute 'message' (this generic error happens when encoding is different). I am trying to read data from Azu...
<p>It looks like a bug in older Pandas versions. With a minimal JsonL bytestring utf-8-sig encoded in <code>bb</code>, I tried:</p> <pre><code>pd.read_json(io.BytesIO(bb), lines=True, encoding='utf-8-sig') (1) pd.read_json(io.StringIO(bb.decode('utf-8-sig')), lines=True) (2) </code></pre> <p>Both work fine on Python 3...
python|pandas
2
351,463
66,613,383
Why can't I import a file.dat using a program in python (I manage to do it only from the console)?
<p>I have a file <code>data1.dat</code> in the same folder as my <code>code.py</code>. This is what I write to import from the data1.dat</p> <pre><code>import pandas as pd #read data as csv to a dataframe x = pd.read_csv('data1.dat', sep=&quot;,&quot;, header=None) print (x) </code></pre> <p>Then i try to convert it t...
<p>By default, the path is relative to the current working directory, which can change, depending where/how you execute your script.</p> <p>If the <code>.dat</code> file will <em>always</em> be present in the same directory as the Python file, make the file path relative to the current file.</p> <pre class="lang-py pre...
python|pandas|csv
0
351,464
66,339,745
Some problem in calculating the meyer wavelet using IFFT
<p>I'm newbie in python and numpy. I have to calculate the meyer wavelet in time domain using spectral analysis. Due to <a href="https://academic.oup.com/gji/article/116/1/119/635254" rel="nofollow noreferrer">https://academic.oup.com/gji/article/116/1/119/635254</a> the wavelet can be estimated in frequency domain by...
<p>Replace this line:</p> <p>st = np.fft.fftshift(np.real(st))</p> <p>with</p> <p>st = np.fft.fftshift(np.real(st)) * fs</p> <p>and you will get the correct scaling, I believe.</p> <p>Dr. Saturn</p>
python|numpy|fft|wavelet
0
351,465
16,158,402
find the distance between a point and a curve python
<p>How can I find the closet distance between my trajectory and <code>(384400,0,0)</code>?</p> <p>Also, how can I the distance from <code>(384400,0,0)</code> to the path at time <code>t = 197465</code>?</p> <p>I understand that the arrays have the data but is there a way to have it check the distance of all the point...
<p>To find the distance along each point in the trajectory:</p> <pre><code>my_x, my_y, my_z = (384400,0,0) delta_x = x - my_x delta_y = y - my_y delta_z = z - my_z distance = np.sqrt(np.power(delta_x, 2) + np.power(delta_y, 2) + np.power(delta_z, 2)) </code></pre> <p>And then ...
python|numpy|scipy|ipython
2
351,466
16,572,513
Easy way to set the position of x-axis in pandas?
<p>I have a chart, created in <a href="http://pandas.pydata.org/" rel="nofollow noreferrer">pandas</a>, where I've set the y-axis to range from -100 to -100.</p> <p>Is there an easy way to have the x-axis cross the y-axis at y=0, instead of crossing at y=-100 (or, how to display the x-axis at the vertical center, ins...
<p>The solution I have so far is indeed using subplots:</p> <pre><code>from pandas import Series s=Series([-25,0,70]) import matplotlib.pyplot as plt fig=plt.figure() ax=fig.add_subplot(111) ax.set_ylabel('percentage') ax.spines['bottom'].set_position('zero') # x-axis where y=0 #ax.spines['bottom'].set_position...
python|matplotlib|pandas
1
351,467
16,414,704
scipy results linear interpolation results inconsistent
<p>I need to perform linear interpolation on a data containing <code>'n'</code> independent variables and a dependent variable. I am currently using <code>scipy.interpolate.LinearNDInterpolator</code> for performing the interpolation. However, when I change the range of the data set by multiplying all values (of a vari...
<p>As Robert Kern states above, the answer is that both answers are correct. They however answer different questions.</p> <p>When interpolating scattered data at, say, point <code>(x, y)</code>, the algorithm must know the answer to the question: "which of the data points are closest to <code>(x, y)</code>. Now, the o...
python|numpy|scipy|interpolation
2
351,468
16,419,685
Multiplying column and row vectors from numpy 2d array with a scalars form a different 1d array
<p><strong>How to multiply each column vector with a scalar from an array?</strong></p> <p>Example</p> <pre><code>a b c x1a x2b x3c a b c x1 x2 x3 -&gt; x1a x2b x3c a b c x1a x2b x3c a b c x1a x2b x3c </code></pre> <hr> <p><strong>How ...
<p>I prefer the following syntax, which is short, but explicit </p> <pre><code>A = np.ones((3,4)) B = np.arange(3) print A * B[:,None] &gt;&gt;&gt; array([[ 0., 0., 0., 0.], [ 1., 1., 1., 1.], [ 2., 2., 2., 2.]]) A = np.ones((4,3)) B = np.arange(3) print A * B[None,:] &gt;&gt;&gt; array([[ 0.,...
python|numpy
4
351,469
16,151,932
Fastest way to create and fill huge numpy 2D-array?
<p>I have to create and fill huge (<em>e.g.</em> 96 Go, 72000 rows * 72000 columns) array with floats in each case that come from mathematical formulas. The array will be computed after. </p> <pre><code>import itertools, operator, time, copy, os, sys import numpy from multiprocessing import Pool def f2(x): # more ...
<p>I know that you can create shared numpy arrays that can be changed from different threads (assuming that the changed areas don't overlap). Here is the sketch of the code that you can use to do that (I saw the original idea somewhere on stackoverflow, edit: here it is <a href="https://stackoverflow.com/a/5550156/1269...
python|matrix|numpy|multiprocessing|multidimensional-array
1
351,470
16,468,717
Iterating over Numpy matrix rows to apply a function each?
<p>I want to be able to iterate over the matrix to apply a function to each row. How can I do it for a Numpy matrix ? </p>
<p>You can use <code>numpy.apply_along_axis()</code>. Assuming that your array is 2D, you can use it like:</p> <pre><code>import numpy as np mymatrix = np.matrix([[11,12,13], [21,22,23], [31,32,33]]) def myfunction(x): return sum(x) print(np.apply_along_axis(myfunction, ...
python|matrix|numpy
85
351,471
57,385,852
Divide specific column(contains) in a dataframe by another dataframe
<p>I have a large dataset that I finding probability on. While there are many columns I only have 2 of interest animal and color. I want to count the occurrence of the animal and print the probability of the colors.</p> <pre><code>animal weight color dog 10 white dog 11 white cat 18 ...
<p>Here are two ways </p> <pre><code>df.groupby(['animal']).color.value_counts(normalize=True) animal color bird white 0.666667 black 0.333333 cat black 0.500000 white 0.500000 dog white 1.000000 Name: color, dtype: float64 pd.crosstab(df.animal,df.color,normalize='index') c...
python|pandas
2
351,472
57,574,604
How do I go from a collection of images, to a full machine learning dataset, that I can then use for transfer learning (resnet50 etc.)?
<p>I'm new to the field of machine learning and just starting to get the hang of it. I was wondering how I can go from an amount of images, to a machine learning dataset. I'm not quite sure on how to store the labels for my data either? A csv format?</p>
<p>This is a rough description on how the full workflow would look like. I can't give much more detail since your question is not very specific.</p> <h1>1. Label your images</h1> <p>There are many tools to label a set of images. You need to find one that fits the deep learning framework you want to use to train your ...
python|tensorflow|machine-learning|computer-vision|resnet
0
351,473
57,720,617
Getting an error while creating a custom function with describe and dtypes
<p>The aim is to create a custom function in python/pandas on giving an output as dataframe. I want to have a summary/describe of a dataframe along with dtypes for a given dataframe.</p> <pre><code>data = {'Name':['Tom', 'Jack', 'nick', 'juli'], 'marks':[99, 98, 95, 90]} df = pd.DataFrame(data, index =['rank1', 'rank...
<p>In pandas 0.25.0 is necessary transpose and add new column by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>DataFrame.assign</code></a>:</p> <pre><code>def inspect(data): return data.describe(include='all').T.assign(Type=data.dty...
python|pandas
1
351,474
57,720,780
How should I compare elements at every position in two lists using numpy?
<p>Suppose there are two lists with the same dimension, let's say <code>[0,1,2,2]</code> and <code>[0,1,2,2]</code>. How should I compare two elements at every position and return a matrix which, in this case, is <code>[[1,0,0,0],[0,1,0,0],[0,0,1,1],[0,0,1,1]]</code>? i.e. <code>f(x,y)=1 if x=y else 0</code>, and x,y a...
<p>You can use <code>np.equal</code> to compare the elements and use <code>np.where</code> to convert it into 1 or 0.:</p> <pre><code>import numpy as np a = np.array([0,1,2,2]) b = np.array([0,1,2,2]) z = np.where(np.equal(a, b[:,np.newaxis]), 1, 0) </code></pre> <p>Output:</p> <pre><code>array([[1, 0, 0, 0], ...
python|python-3.x|numpy|numpy-ndarray
3
351,475
57,704,653
Accuracy reduced when predicting using tfjs from model trained by ML5
<p>I am using <strong>tfjs 1.0.0</strong> on <strong>Google Chrome | 76.0.3809.132 (Official Build) (64-bit)</strong></p> <p>I was using ML5 to train models for image classification in my project. I used the Feature Extractor for transfer learning. I was using <code>mobilenet_v1_0.25</code> as a base model. I wanted t...
<p>In order to predict from a model that was trained using transfer learning (i.e. trained on another, pre-trained model), you need to firstly predict from the base model and then predict from the custom model by passing the base-model predicted tensors to the input of the custom model prediction.</p> <pre><code>async...
javascript|tensorflow|machine-learning|tensor
1
351,476
57,379,074
A question about simple Keras and Tensorflow code performance
<p>I wrote simple Sin function predictors using Keras and Tensorflow with LSTM, but found the performance of Keras code is much slower which runs about 5 min while Tensorflow code runs the model just in 20 seconds. Moreover, the Keras prediction performance is less precide as Keras one. Could anyone help me find the co...
<ol> <li>Your model structure is not same, first has <code>3</code> layers of <code>LSTM</code>, other has <code>2</code>. </li> <li>Tensorflow data API is highly optimized, It preparing the data-set, without wasting any resources.</li> </ol> <p>Note that: You can even more accelerate the training in tensorflow using ...
tensorflow|keras|lstm|recurrent-neural-network
0
351,477
57,452,141
Time difference of time string (only want the calculate the difference of the minutes then convert to seconds)
<p>I have 2 times a start and finish time (lasttime), in the format of (HH:MM:SS). I need to find the difference between in time between the minutes (converted in seconds)</p>
<h2>Data:</h2> <pre><code>StartTime,LastTime 00:02:05,00:03:05 00:02:05,00:05:05 00:07:05,00:10:05 00:07:05,00:15:05 00:12:06,00:30:06 00:12:06,00:35:06 </code></pre> <h2>Create <code>DataFrame</code>:</h2> <h3>from clipboard:</h3> <pre><code>df = pd.read_clipboard(sep=',') </code></pre> <h3>from csv:</h3> <pre><...
python|pandas|datetime
0
351,478
57,414,114
Implement custom loss function in Tensorflow 2.0
<p>I'm building a model for Time series classification. The data is very unbalanced so I've decided to use a weighted cross entropy function as my loss. </p> <p>Tensorflow provides <a href="https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/nn/weighted_cross_entropy_with_logits" rel="noreferrer">tf.nn.weighte...
<p>You can pass the class weights directly to the <code>model.fit</code> function.</p> <blockquote> <p><code>class_weight:</code> Optional dictionary mapping class indices (integers) to a weight (float) value, used for weighting the loss function (during training only). This can be useful to tell the model to "p...
tensorflow|keras|loss-function|tensorflow2.0
5
351,479
57,718,355
How to change the layout of dataframe pivot in python
<p>My data frame looks like below </p> <pre><code>Name | Date | Price | Disc% A | 8/29 | 100.0 | 5 B | 8/29 | 88.80 | 6 A | 8/30 | 99.0 | 4 B | 8/30 | 85.0 | 3 </code></pre> <p>If I use </p> <pre><code>pd.pivot_table(df, index='name',columns='Date',values=['price','disc']...), </code></pre> ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.swaplevel.html" rel="nofollow noreferrer"><code>swaplevels</code></a></p> <pre><code>pivoted.swaplevel(-1,-2, 1).sort_index(axis=1) </code></pre> <hr> <pre><code>Date 8/29 8/30 Disc% Price Disc% Price Nam...
python|pandas|pivot-table
2
351,480
57,512,129
Getting Error while converting tensorflow model to tensorflow lite = ValueError: bad marshal data (unknown type code)
<p>I am using a pre-trained keras based and tensorflow based model with yolov2 architecture for potholes detection and I'm getting an error while converting my tensorflow model to tensorflow lite</p> <blockquote> <p>Error = ValueError: bad marshal data (unknown type code)</p> </blockquote> <p>I'm using tensorflow 1...
<p>Please provide more information. </p> <p>The error was on the last line, but there was no reference on how to get <code>marshal</code> object and how to get <code>raw_code</code>.</p>
python|tensorflow|keras|deep-learning|tensorflow-lite
0
351,481
57,677,439
Insert comma in numeric columns of a pandas dataframe
<p>I have a pandas dataframe containing many different columns, some containing string while others containing numeric data. I want to add commas as a thousands separator. Right now, I am trying the below:</p> <pre><code>df= df.apply('{:,}'.format) </code></pre> <p>But it gives me the following error:</p> <pre><code...
<p>So you can just using <code>select_dtypes</code></p> <pre><code>df.update(df.select_dtypes(include=np.number).applymap('{:,}'.format)) </code></pre>
python-3.x|pandas|dataframe
3
351,482
57,610,949
python pandas pivot_table column level one wrong name
<p>I have the following table:</p> <pre class="lang-py prettyprint-override"><code> ID Metric Level Level(% Change) Level(Diff) Index 0 2016 A 10 NaN NaN 1 2017 A 15 0.5 5 2 2018 A 20 0.3 ...
<p>Use list comprehension with swap <code>a,b</code> and <code>f-strings</code>:</p> <pre><code>df = pd.pivot_table(df, index = 'ID', values = ['Level','Level(% Change)','Level(Diff)'], columns = ['Metric']) df.columns = [f'{b}_{a}' for a, ab in df.column...
python|pandas|dataframe|pivot-table
1
351,483
57,550,770
Combining Groupby function codes, with and without grouper
<p>I have written these two groupby functions on my data sets, the first one grouped my data and seperated datetime for the data as start datetime, end date time.</p> <p>This is the dataset:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">...
<p>This may work for you (i know how your data looks like from your earlier question) You can aggregate all the values into a list with just <code>agg(list)</code></p> <pre><code>df3=df.groupby([pd.Grouper(key = 'Detection_Date&amp;Time', freq = 'H'),df.Detection_Location], sort=False).agg(list).reset_index() </code><...
python|pandas|group-by
1
351,484
57,609,036
pandas normalize simple JSON
<p>I have a simple JSON data like:</p> <pre><code>[{ "load": 1, "results": { "key": "A", "timing": 1.1 } }, { "load": 2, "results": { "key": "B", "timing": 2.2 } }] </code></pre> <p>When trying to load it to pandas:</p> <pre><code>pd.read_json('res.json') </cod...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.json.json_normalize.html" rel="nofollow noreferrer"><code>json.json_normalize</code></a>:</p> <pre><code>data = [{ "load": 1, "results": { "key": "A", "timing": 1.1 } }, { "load": 2, "results": { ...
json|pandas|normalize
0
351,485
57,314,407
Add a column in a pandas df with a repeated sequence of values
<p>I want to add a column to a pandas DataFrame that has a sequence of int or even str.</p> <p>This is the pandas DataFrame:</p> <pre><code>import pandas as pd df = [{"us": "t1"}, {"us": "t2"}, {"us": "t3"}, {"us": "t4"}, {"us": "t5"}, {"us": "t6"}, {"us": "t7"}, {"us": "t8"}, {"us": "t9"}, {"us": "t10"}, {"us": "t1...
<p>You can use <code>np.tile</code>:</p> <pre><code>df['list_int'] = np.tile(list_int, len(df)//len(list_int) + 1)[:len(df)] </code></pre> <p>or simply</p> <pre><code>df['list_int'] = np.tile(list_int, len(df)//len(list_int)] </code></pre> <p>if <code>len(df)</code> is divisible by <code>len(list_int)</code>.</p>
python|pandas
3
351,486
57,494,484
keras for adding two dense layers
<p>There are two inputs, x, and u, that generate the output y. There is a linear relationship between x, u, and y, i.e. y = x wx + u wx. I'm trying to calculate wx and wu from data. Here is the code for model construction / fitting.</p> <pre><code> n_train = 400 n_val = 100 train_u = u[:(n_train+n_val)] ...
<p>Keras categorical accuracy metrics expect the output, &amp; labels, shape as <code>(batch_size,num_classes)</code>. The <code>dim[2]</code> in error message indicates output shape is 3d: <code>(None,50,2)</code></p> <p>The simple fix is to ensure, by whatever means, that the output layer gives <em>one</em> predicti...
python|tensorflow|keras
1
351,487
57,401,286
How to connect convolution layer with lstm layer to in seq2seq tasks?
<p>The seq2seq tasks is to recognize the sentences from video data (also known as visual-only speech recognition/Lip-reading). </p> <p>The model is consisted of convolutional layers and a lstm layer. However, the output of convolutional layers is in the shape of <strong><code>[batch_size, height, width, channel_size]<...
<p>The RNN expects that the input is going to be sequential. Therefore, the input has the shape <code>[time, feature_size]</code> or if you are processing a batch <code>[batch_size, time, feature_size]</code>.</p> <p>In your case, the input has a shape <code>[batch_size, number_of_frames, height, width, num_channels]<...
tensorflow|conv-neural-network|lstm|seq2seq
2
351,488
57,338,219
Append each value in a DataFrame to a np vector, grouping by column
<p>I am trying to create a list, which will be fed as input to the neural network of a Deep Reinforcement Learning model. </p> <p><em>What I would like to achieve:</em> This list should have the properties of this code's output</p> <pre><code>vec = [] lines = open("data/" + "GSPC" + ".csv", "r").read().splitlines() f...
<p>From what I can understand, you just want a flattened version of the DataFrame's values. That can be done simply with the <code>ndarray.flatten()</code> method rather than reshaping it.</p> <pre><code># Creating your DataFrame object a = [[1.26420, 1.263037], [1.26465, 1.263193], [1.26430, 1.263350], ...
python-3.x|numpy
0
351,489
57,564,290
How do I get rid of the outside values in this graph using pandas?
<pre><code>from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = power_current_pd8_on['VDD-CL(V)'] y = power_current_pd8_on['CLK_IN(Hz)'] z = IDCLA_pd8_on ax.scatter(x , y, z, c='r', marker='o') ax.set_xlabel('VDD-CL(V)') ax.set_...
<p>You can always throw out the data you don't want to be plotted.</p> <pre class="lang-py prettyprint-override"><code>... x = power_current_pd8_on['VDD-CL(V)'] y = power_current_pd8_on['CLK_IN(Hz)'] z = IDCLA_pd8_on keepers = (x &lt;= 0.9) &amp; (x &gt;= 0.8) &amp; (y &gt;= 0.0) &amp; (y &lt;= 0.4) ax.scatter(x[k...
python|pandas|jupyter-notebook
0
351,490
57,487,935
Looking to merge/concatenate/groupby different rows in Pandas dataframe
<p>I will be iterating through a large list of dataframes of baseball statistics of different players. This data is indexed by year. What I am looking to do is group year while keeping salary the same and adding WAR. Also, I am looking to drop rows that are not single years. In my data set these entries are strings.</p...
<p>To filter out based on length of column <code>Year</code>, why don't you try creating a mask and then select based on it.</p> <p>Code:</p> <pre><code>mask_df = your_df['Year'].str.len() == 4 your_df_cleaned = your_df.loc[mask_df] </code></pre>
python|python-3.x|pandas
1
351,491
57,699,734
How do I generate observations between two dates using Pandas
<p>I have a dataset in the following format:</p> <pre><code>User ID Start Date End Date 1 '2000-01-01' '2000-03-01' 2 '2002-01-01' '2002-08-01' ... .... .... 10 '2003-03-01' '2004-01-01' </code></pre> <p>How do I generate a dataset with each date between the start date and t...
<p>Use <code>pd.date_range</code> to generate dates from your start date to your end date. I have set the frequency to 30 days by doing <code>freq=30D</code> - choose whatever convenient for you.</p> <pre><code>df['Activity Date'] = df.apply(lambda s: pd.date_range(s['Start Date'], s['End Date'], freq='30D').tolist(),...
python|pandas
5
351,492
57,584,644
Predict from Previously trained Model Tensorflow
<p>I have trained a Regression Model using tensorflow. The model saved file like</p> <ol> <li>model.ckpt-4000.meta </li> <li>model.ckpt-4000.index </li> <li>model.ckpt-4000.data-00001-of-00002</li> </ol> <p>Now if i want to use those file to predict output values from new data set (test data), how can i do that?...
<pre><code>sess=tf.Session() #First load meta graph and restore weights saver = tf.train.import_meta_graph('model.ckpt-4000.meta') saver.restore(sess,tf.train.latest_checkpoint('./')) # create feed-dict to feed new data and specify the y variable to be evaluated sess.run(y,feed_dict) </code></pre>
python-3.x|tensorflow|keras
1
351,493
57,339,315
How to read columns from different files and plot?
<p>I have data of concentrations for every day of year 2005 until 2018. I want to read three columns of three different files and combine them into one, so I can plot them. </p> <p>Data:file 1</p> <pre><code>time, mean_OMNO2d_003_ColumnAmountNO2CloudScreened 2005-01-01,-1.267651e+30 2005-01-02,4.90778397e+15 ... 2018...
<p>This is very doable. I had a similar problem with 3 files all in one plot. My understanding is that you want to compare levels of NO, NO2, and SO2, that each column is in comparable order, and that you want to compare across rows. If you are ok with importing matplotlib and numpy, something like this may work for yo...
python|python-3.x|pandas|plot
0
351,494
57,583,269
Converting a pandas crosstab into a stacked dataframe (a regular table)
<p>Given a pandas crosstab, how do you convert that into a stacked dataframe?</p> <p>Assume you have a stacked dataframe. First we convert it into a crosstab. Now I would like to revert back to the original stacked dataframe. I searched a problem statement that addresses this requirement, but could not find any that h...
<p>You can just do <code>stack</code></p> <pre><code>df[df.astype(bool)].stack().reset_index().drop(0,1) </code></pre>
pandas|data-science
4
351,495
57,727,185
Smoothing data for determining peak values in Python
<p>I have a transect with peaks and trough, and want to determine the peak values of both. The dataset has quite some noise so currently, the peaks do not return as a single value. I tried to smooth the data with a rolling mean, and even though the outcome is better than without smoothing, there are still multiple 'pea...
<p>My first instinct is to use <a href="https://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.signal.savgol_filter.html" rel="nofollow noreferrer">Savitzky-Golay filter</a> for smoothing. The second is to forget the argrelextrema when you have a noisy dataset. I have never had any good results using it this...
python|pandas|csv|smoothing
2
351,496
57,534,418
Display image of 2D Sinewaves in 3D
<p>I've generated a 1D sine wave and then repeated it every row to have a 2D sine wave. I can show this in 2d space, but I need to produce a 3D plot that shows the peaks and valleys as well as the oscillatory patterns between them. </p> <pre><code>import numpy as np import matplotlib.pyplot as plt N = 256 x = np.linsp...
<p>how about, as @Warren Weckesser said, use the <a href="https://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html" rel="nofollow noreferrer">mplot3d toolkit examples gallery</a>, and for instance surface plot of the magnitude of a sinewave as function of time and phase:</p> <pre><code>from mpl_toolkits.mplot3d impor...
python|numpy|matplotlib
3
351,497
57,312,824
How to split a dataframe column based on a character and retain that character?
<p>I'm having trouble figuring out how to split a dataframe column based on a character and retaining that character string. Here's some example data:</p> <pre><code>df = pd.DataFrame( {"sexage" : ['m45', 'f43']} ) </code></pre> <p>What I'd like is a separate column with the male/female letter and a separate col...
<p>Try <code>extract</code></p> <pre><code>df.sexage.str.extract('(\D+)(\d+)') </code></pre> <p>output:</p> <pre><code> 0 1 0 m 45 1 f 43 </code></pre>
python|regex|pandas|character
2
351,498
57,492,139
How to add 'instance keys' to a keras model input for batch prediction in gcloud ai-platform?
<p>I'm trying to add 'keys' to match the batch prediction output from Google AI Platform, however my model input just allows for one input.</p> <p>It looks like that:</p> <pre><code>input = tf.keras.layers.Input(shape=(max_len,)) x = tf.keras.layers.Embedding(max_words, embed_size, weights=[embedding_matrix], traina...
<p>Following your code, you could do something like this:</p> <p>First, get the key value from the input:</p> <pre class="lang-py prettyprint-override"><code>input = tf.keras.layers.Input(shape=(max_len,)) key_raw = tf.keras.layers.Input(shape=(), name='key') </code></pre> <p><a href="https://www.tensorflow.org/api_...
python|tensorflow|gcloud
3
351,499
57,704,412
How to suppress "Future warning" tensorflow?
<p><strong>I am running "./buildTF.sh" which uses TensorFlow, on ubuntu terminal. And getting the error as:</strong></p> <pre><code>/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of nu...
<p>These warnings are classical <code>FutureWarning</code>, which means you can silent them using the <code>warnings</code> module from the python standard library:</p> <pre class="lang-py prettyprint-override"><code>import warnings warnings.filterwarnings(&quot;ignore&quot;, message=r&quot;Passing&quot;, category=Futu...
python|numpy|tensorflow|ubuntu|terminal
10