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
5,900
4,092,927
Generating movie from python without saving individual frames to files
<p>I would like to create an h264 or divx movie from frames that I generate in a python script in matplotlib. There are about 100k frames in this movie.</p> <p>In examples on the web [eg. 1], I have only seen the method of saving each frame as a png and then running mencoder or ffmpeg on these files. In my case, savin...
<p>This functionality is now (at least as of 1.2.0, maybe 1.1) baked into matplotlib via the <code>MovieWriter</code> class and it's sub-classes in the <code>animation</code> module. You also need to install <code>ffmpeg</code> in advance.</p> <pre><code>import matplotlib.animation as animation import numpy as np from...
python|numpy|ffmpeg|matplotlib|x264
57
5,901
8,708,758
Can I force a numpy ndarray to take ownership of its memory?
<p>I have a C function that mallocs() and populates a 2D array of floats. It "returns" that address and the size of the array. The signature is</p> <pre><code>int get_array_c(float** addr, int* nrows, int* ncols); </code></pre> <p>I want to call it from Python, so I use ctypes.</p> <pre><code>import ctypes mylib =...
<p>I just stumbled upon this question, which is still an issue in August 2013. Numpy is really picky about the <code>OWNDATA</code> flag: There is no way it can be modified on the Python level, so ctypes will most likely not be able to do this. On the numpy C-API level - and now we are talking about a completely differ...
python|c|numpy|free|ctypes
6
5,902
55,368,594
How to get indices list for rows starting with lower case letter?
<p>I have a dataframe with one of the columns being df['Names']. How can I locate all the rows whose names start with a lower case letter?</p> <pre><code>col1 Names 1564 abby 2289 Barry </code></pre> <p>etc.</p> <p>I'm trying to accomplish this using regex with no luck.</p>
<p>one way from <code>str.lower</code> </p> <pre><code>df[df.Names.str[0]==df.Names.str[0].str.lower()] Out[173]: col1 Names 0 1564 abby </code></pre> <p>Another way <code>islower</code></p> <pre><code>df[df.Names.str[0].str.islower()] Out[174]: col1 Names 0 1564 abby </code></pre>
python|regex|pandas
2
5,903
56,841,702
How do I group a time series by hour of day?
<p>I have a time series and I want to group the rows by hour of day (regardless of date) and visualize these as boxplots. So I'd want 24 boxplots starting from hour 1, then hour 2, then hour 3 and so on.</p> <p>The way I see this working is splitting the dataset up into 24 series (1 for each hour of the day), creating...
<p>there are 2 steps to achieve this: </p> <ol> <li><p>convert Actual to date time:</p> <pre><code>df.Actual = pd.to_datetime(df.Actual) </code></pre></li> <li><p>Group by the hour:</p> <pre><code>df.groupby([df.Date, df.Actual.dt.hour+1]).Consumption.sum().reset_index() </code></pre></li> </ol> <p>I assumed you wa...
python|pandas|dataframe|time-series
2
5,904
56,633,010
CppFlow on windows 10
<p>I found this interesting project on Github (<a href="https://github.com/serizba/cppflow" rel="nofollow noreferrer">https://github.com/serizba/cppflow</a>) Which is a c++ wrapper for the tensor api written in C. </p> <p>However I have some issues when installing it.. </p> <p>I have installed a c++ compiler, but wh...
<p>Well I'm not enough of a language lawyer to know where the fault lies (the code or the compiler) but it's clear that the intent of the line of code causing the problems is this</p> <pre><code>return std::vector&lt;T&gt;(T_data, T_data + size); </code></pre> <p>With that more old-fashioned style of code it compiles...
c++|tensorflow
1
5,905
26,283,127
Removing numpy meshgrid points outside of a Shapely polygon
<p>I have a 10 x 10 grid that I would like to remove points outside of a shapely Polygon:</p> <pre><code>import numpy as np from shapely.geometry import Polygon, Point from descartes import PolygonPatch gridX, gridY = np.mgrid[0.0:10.0, 0.0:10.0] poly = Polygon([[1,1],[1,7],[7,7],[7,1]]) #plot original figure fig = ...
<p>You're pretty close already; instead of printing True, you could just append the points to a list.</p> <pre><code>output = [] for i in reshaped: if Point(i).within(poly): output.append(i) output = np.array(output) x, y = output[:, 0], output[:, 1] </code></pre> <p>It seems that <code>Point.within</cod...
numpy|shapely
2
5,906
67,027,964
How to select a subset of rows in pandas with a certain starting value and certain ending value
<p>In pandas, it's possible to return subsets of rows using like this:</p> <p><code>df[:6]</code></p> <p>which would with the dataset I'm using return:</p> <pre><code>weekday CO_level ... 0 Monday Very high 1 Tuesday Low 2 Wednesday Low 3 Saturday ...
<p>@Yefet's answer looks good. Here's a different approach:</p> <pre><code>days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] for i in range(len(df)): test_days = df['weekday'][i:i+7].to_list() if test_days == days: week_df = df.iloc[i:i+7,:] break ...
python|pandas|dataframe
1
5,907
67,067,203
How to find difference between rows in a pandas multiIndex, by level 1
<p>Suppose we have a DataFrame like this, only with many, many more index A values:</p> <pre><code>df = pd.DataFrame([[1,2,1,2], [1,1,2,2], [2,2,1,0], [1,2,1,2], [2,1,1,2] ], columns=['A','B','c1','c2']) df.groupby(['A','B']).sum() ## result c1 c2 A B ...
<p>Check <code>diff </code> and <code>dropna</code></p> <pre><code>g = df.groupby(['A','B'])[['c1','c2']].sum() g = g.groupby(level=0).diff().dropna() g Out[25]: c1 c2 A B 1 2 0.0 2.0 2 2 0.0 -2.0 </code></pre>
pandas
0
5,908
66,953,754
How to insert column from a file to another file at multiple places
<p>I would like to insert columns no. 1 and 2 from file no. 2 into file no. 1 after every second column and till the last column.</p> <p>File1.txt (tab-separated, column range from 1-2400 and cell range from 1-4500)</p> <pre><code> ID IMPACT ID IMPACT ID IMPACT 51 0.288 128 0.4557 156 0.85 625 0.858 ...
<pre><code>$ awk ' BEGIN { FS=OFS=&quot;\t&quot; # tab-separated data } NR==FNR { # hash fields of file2 a[FNR]=$1 # index with record numbers FNR b[FNR]=$2 next } { # print file1 records with file2 fie...
pandas|bash
2
5,909
66,959,215
Drop duplicates with condition
<p>I have the following pandas dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>index</th> <th>so_id</th> </tr> </thead> <tbody> <tr> <td>10</td> <td>390</td> </tr> <tr> <td>10</td> <td>395</td> </tr> <tr> <td>10</td> <td>405</td> </tr> <tr> <td>11</td> <td>390</td> </tr> <tr> <td...
<p>We can do it but importantly, pay attention to comment above.</p> <pre><code>df=df.sort_values (by=['so_id'])#Sort df </code></pre> <p>Create temporary column <code>t</code> which is a classification of <code>so_id</code> and <code>resort</code> <code>df</code> back to original <code>df=df.assign(t=df['so_id'].ne...
python|pandas
1
5,910
67,169,344
Unknown error/crash - TensorFlow LSTM with GPU (no output after start of 1st epoch)
<p><strong>I'm trying to train a model using LSTM layers. I'm using a GPU and all needed libraries are loaded.</strong></p> <p>When I'm building the model this way:</p> <pre><code>model = keras.Sequential() model.add(layers.LSTM(256, activation=&quot;relu&quot;, return_sequences=False)) # note the activation function...
<p><strong>I found the solution... kinda.</strong></p> <p>So it works as it should when I downgraded tensorflow to <code>2.1.0</code>, CUDA to <code>10.1</code> and cudnn to <code>7.6.5</code> (at the time 4th combination from <a href="https://www.tensorflow.org/install/source#gpu" rel="nofollow noreferrer">this list o...
python|tensorflow|keras|lstm
0
5,911
47,086,599
parallelising tf.data.Dataset.from_generator
<p> I have a non trivial input pipeline that <code>from_generator</code> is perfect for...</p> <pre class="lang-py prettyprint-override"><code>dataset = tf.data.Dataset.from_generator(complex_img_label_generator, (tf.int32, tf.string)) dataset = dataset.batch(64) iter = dataset....
<p> Turns out I can use <code>Dataset.map</code> if I make the generator super lightweight (only generating meta data) and then move the actual heavy lighting into a stateless function. This way I can parallelise just the heavy lifting part with <code>.map</code> using a <code>py_func</code>.</p> <p>Works; but feels a...
tensorflow|tensorflow-datasets
29
5,912
47,156,680
Regex for amounts in euro
<p>I need to find a regex expression that select only the amounts (in euros) so the value needs to be preceded by a <code>€</code> or <code>euros</code> and that after the <code>,</code> we have the pennies, there can be spaces or dots as well.</p> <pre><code>7 967 59 € - 9847, 48 euros à titre de rappel de salaire s...
<p>You may use</p> <pre><code>\b((?:\d+|\d{1,3}(?:[,.\s]\d{3})*)(?:[,.\s]*\d+)?)\s(?:euros?|€) </code></pre> <p>See the <a href="https://regex101.com/r/0LPXcI/7" rel="nofollow noreferrer">regex demo</a></p> <p><strong>Details</strong></p> <ul> <li><code>\b</code> - a word boundary</li> <li><code>((?:\d+|\d{1,3}(?:[...
python|regex|pandas
3
5,913
11,210,677
Need help to parallelize a loop in python
<p>I have a huge data set and I have to compute for every point of it a series of properties. My code is really slow and I would like to make it faster parallelizing somehow the do loop. I would like each processor to compute the "series of properties" for a limited subsample of my data and then join all the properties...
<p>Parallelizing is not trivial, however you might find <a href="https://code.google.com/p/numexpr/" rel="nofollow">numexpr</a> useful.</p> <p><strong>For numerical work</strong>, you really should look into the utilities numpy gives you (<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.htm...
python|numpy|parallel-processing|multiprocessing
3
5,914
68,212,240
Pandas DataFrame and NumPy array weirdness - df.to_numpy(), np.asarray(df), and np.array(df) give different memory usages
<p>I am working on converting an existing Pandas Dataframe to a Numpy array. The dataframe has no <code>NaN</code> values and is not sparsely populated (read in from a <code>.csv</code> file). In addition, in order to see memory usage, I performed the following:</p> <p><code>sum(df.memory_usage)</code></p> <pre><code>2...
<p>A <code>numpy</code> has attributes like <code>shape</code> and <code>dtype</code>, and a <code>data buffer</code>, which is a flat C array, that stores the values.</p> <pre><code>arr.nbytes # 2400000 </code></pre> <p>is telling you the size of that data buffer. So if the array is (300,10000) float dtype, that w...
pandas|dataframe|numpy|memory|numpy-ndarray
2
5,915
68,177,394
Why we need to save pytorch models with .net extension?
<p>I'm a new learner for Pytorch and I am working on a Character_Level_LSTM_Exercise.</p> <p>Why they save the model with .net extension in the model name?</p> <p>I'm searching for the explanation but I didn't get any good explanation.</p> <pre><code># change the name, for saving multiple files model_name = 'rnn_x_epoc...
<p>You can use whatever extension you like! Just make sure to be consistent.</p> <p>The docu recommends to use .pt extension.</p> <p><a href="https://pytorch.org/docs/stable/generated/torch.save.html" rel="nofollow noreferrer">https://pytorch.org/docs/stable/generated/torch.save.html</a></p> <p>For more explanation and...
python|pytorch
1
5,916
59,382,676
Pandas chain.from_iterable: Error object of type 'itertools.chain' has no len()
<p>Having a dataframe as the following:</p> <pre><code>df_data=pd.DataFrame({'name':[['ABC','DOS','TRES'],['XYZ','MORTGAGE','SOLUTIONS']], 'original': ['ABC DOS TRES','XYZ MORTGAGE SOLUTIONS']}) </code></pre> <p>I am using chain.from_iterable to extract every item in a list and add the result to...
<p>Using <code>chain.from_iterable</code> returns an iterator, not a list/sequence. Older versions of Pandas needs the objects you pass to the data frame constructor to have a <code>len</code> so it knows what size array to allocate on the backend. The <code>chain</code> object does not supply that (nor should it). ...
python|pandas|dataframe
3
5,917
59,402,788
How to make a custom loss function in Keras properly
<p>i am making a mode that the prediction is a metrix from a conv layer. my loss function is</p> <pre><code>def custom_loss(y_true, y_pred): print("in loss...") final_loss = float(0) print(y_pred.shape) print(y_true.shape) for i in range(7): for j in range(14): tl = float(0) ...
<p>To answer some of your concerns,</p> <blockquote> <p>I don't see anyone use loops in the loss function</p> </blockquote> <p>Usually it's a pretty bad practice. Deep nets train on millions of samples usually. Having loops instead of using vectorized operations therefore, will really bring down your model performa...
python|tensorflow|keras|conv-neural-network|loss-function
1
5,918
13,815,719
Creating Grid with Numpy Performance
<p>So here is what I try to do,</p> <pre><code>N=1000 x=np.arange(0,1,1./float(len(N))) XX,YY=np.meshgrid(x,x) l=len(XX) grid=np.array([ ([XX[i,i],YY[j,j],0. ]) for i in xrange(l) for j in xrange(l) ]) </code></pre> <p>the numpy routine is rather fast but I need the grid to be in a different form and this tak...
<p>Take advantage of <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow">broadcasting</a>:</p> <pre><code>z = np.zeros([N, N, 3]) z[:,:,0] = x.reshape(-1,1) z[:,:,1] = x fast_grid = z.reshape(N*N, 3) print np.all( grid == fast_grid ) True </code></pre>
python|numpy|grid
3
5,919
14,298,593
Scipy arpack eigs versus eigsh number of eigenvalues
<p>In scipy's ARPACK bindings, one cannot calculate all of the eigenvalues of a matrix. However, I find that eigsh is able to calculate n - 1 eigenvalues, while eigs is only able to calculate n - 2 eigenvalues. Can anyone verify that this is in fact a fundamental limitation of ARPACK and not a bug in scipy? </p> <p...
<p>It's ARPACK limitation:</p> <p><a href="http://forge.scilab.org/index.php/p/arpack-ng/source/tree/master/SRC/dnaupd.f" rel="nofollow">http://forge.scilab.org/index.php/p/arpack-ng/source/tree/master/SRC/dnaupd.f</a></p> <p><a href="http://forge.scilab.org/index.php/p/arpack-ng/source/tree/master/SRC/dsaupd.f" rel=...
math|numpy|scipy|arpack
2
5,920
44,859,550
Large outputs predicted for the MNIST database in tensorflow
<p>I can't receive result after training of network at a test example. It is a standard example from the help multilayer_perceptron.py</p> <p>I try to receive result in such a way</p> <pre><code>examples_to_show = 5 y_result = sess.run(y_pred, feed_dict={x:mnist.test.images[:examples_to_show]}) print("y_result=",y_re...
<p>Your <code>y_result</code> is calculated here: <code>out_layer = tf.matmul(layer_2, weights['out']) + biases['out']</code>. It is clear that it will not be a one-hot vector but either a matrix or a vector (depending on your <code>layer_2</code> and <code>weight['out']</code>). Looking at your results it is a matrix<...
tensorflow
0
5,921
44,863,067
pandas TimedeltaIndex.join does not take sort arg
<p>The latest pandas 0.20.2 TimedeltaIndex.join method does not take 'sort=...' kwarg, so that it cannot be used as a join index as required in pandas/core/reshape/merge.py line 722. Here's how to reproduce:</p> <pre><code>import pandas as pd import numpy as np tx = pd.timedelta_range('09:30:00', '10:00:00', freq='30s...
<p>This is a known issue. There is an issue report (<a href="https://github.com/pandas-dev/pandas/issues/16541" rel="nofollow noreferrer">here</a>) and a Pull Request that is being worked on (<a href="https://github.com/pandas-dev/pandas/pull/16586" rel="nofollow noreferrer">here</a>) with the hope to complete for <a ...
python|pandas|join
1
5,922
45,149,446
Stop Tensoflow from running on the GPU after a computation
<p>I am running a REST Server in Python, with an access point to retrieve an image and use a tensorflow model to predict what is on that image. After starting the server, I am sending images to the REST endpoint. The model loaded is an Inception model that I trained myself. It is loaded from a tensorflow checkpoint fil...
<p>Let's go over your problems one by one.</p> <p>First, the error about the variable already existing comes from you reusing an existing graph and rerunning the model creation code on every request. Either create a graph per request by adding a <code>with tf.Graph().as_default():</code> context manager inside your <c...
python|tensorflow
2
5,923
45,254,975
tensorflow object detection API ImportError when generating PASCAL TFRecord files
<p>I'm trying to use the Tensorflow Object Detection API and I've successfully tested the installation,but we I try to generate the PASCAL VOC TFRecord files with the given command</p> <pre><code>python object_detection/create_pascal_tf_record.py \ --label_map_path=object_detection/data/pascal_label_map.pbtxt \ --data...
<p>I had the same problem and I solved it by adding :</p> <pre><code>import os import sys sys.path.append(os.path.abspath("./object_detection")) </code></pre> <p>and </p> <pre><code>from object_detection.utils import dataset_util </code></pre> <p>becomes</p> <pre><code>from utils import dataset_util </code></pre>
tensorflow|importerror|object-detection
0
5,924
45,121,382
Tensorflow Autoencoder with custom training examples from binary file
<p>I'm trying to adapt the Tensorflow Autoencoder code found here (<a href="https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/autoencoder.py" rel="nofollow noreferrer">https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/autoencoder.py</a>) ...
<blockquote> <p>My first question is why do I have Tensors of shape (1, 128, 29, 29, 1) when I was expecting (128,29,29,1)? Am I missing something here?</p> </blockquote> <p>You need to remove the bracket in sess.run:</p> <pre><code> batch_xs = sess.run(data_batch) </code></pre> <blockquote> <p>Unfortunately, ...
python|tensorflow|autoencoder
0
5,925
45,226,353
python pandas Transfer the format of the dataframe
<p>I have a dataframe named df like this: (there's no duplicate rows of df)</p> <pre><code>a_id b_id 111111 18 111111 17 222222 18 333333 14 444444 13 555555 18 555555 24 222222 13 222222 17 333333 17 </code></pre> <p>And I wa...
<p>I have a solution: First, make the combinations of <code>a_id</code> that have the same <code>b_id</code>:</p> <pre><code>from itertools import combinations df = df.groupby("b_id").apply(lambda x: list(combinations(x["a_id"], 2))).apply(pd.Series).stack() </code></pre> <p><code>df</code> now is:</p> <pre><code> b...
python|pandas|dataframe
1
5,926
44,828,514
Changing Tensorflow number of convolutional and pooling layers using MNIST dataset
<p>I am using Windows 10 pro, python 3.6.2rc1, Visual Studio 2017, and Tensorflow. I am working with Tensorflow example in its tutorial in the following link:</p> <p><a href="https://www.tensorflow.org/tutorials/layers" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/layers</a></p> <p>I have added anot...
<p>A simple fix for this would be to define a custom checkpoint directory for the model as follows.</p> <pre><code>tf.train.generate_checkpoint_state_proto("/tmp/","/tmp/mnist_convnet_model") </code></pre> <p>This fixes the problem with the MNIST example and also gives you access to a location where you can control c...
python|tensorflow
0
5,927
45,267,202
How to improve curve fitting in matplotlib?
<p>I have a set of data, y is angular orientation, and x is the timestamp for each point of y.</p> <p>The entire data set has many segments for angular orientation. Inorder to do curve fitting, I have split the data into their respective segments, storing each segment as an numpy array. </p> <p>I then find a polynomi...
<h3>Cubic interpolation</h3> <p>What about a cubic interpolation of the data?</p> <pre><code>import numpy as np from scipy.interpolate import interp1d import matplotlib.pyplot as plt x = np.linspace(6, 13, num=40) y = 3 + 2.*x+np.sin(x)/2.+np.sin(4*x)/3.+ np.random.rand(len(x))/3. fig, ax = plt.subplots() ax.scatter(...
python|numpy|matplotlib
1
5,928
57,277,290
Looping through two separate dataFrames, Haversine function, store the values
<p>I have two dataFrames that I want to loop through, apply a Haversine function, and structure the results within a new array. I want to grab the lat, lng coordinates for the first restaurant in da_store apply the Haversine function against all the lat, lng of da_univ, store the results and grab the minimum value. Ult...
<p>If you use loop with pandas and numpy, chances are high that you are doing it wrong. Learn and apply the vectorized functions that these libraries provide:</p> <pre><code># Build an index that contain every pairing of Store - University idx = pd.MultiIndex.from_product([da_store.index, da_univ.index], names=['Store...
python|pandas|dataframe
1
5,929
57,246,380
How to separate Quarter and year data
<p>Need to separate the quarter and year into separate columns</p> <pre><code>df.head() Period Q1/2012 Q2/2012 Q3/2012 Q4/2012 Q1/2013 </code></pre> <p>Want to have the column displayed as:</p> <pre><code>Period Year Q1 2012 Q2 2012 Q3 2012 Q4 2012 Q1 2013 </code></pre>
<pre><code>import pandas as pd import numpy as np df Period 0 Q1/2012 1 Q2/2012 2 Q3/2012 3 Q4/2012 4 Q1/2013 df['Year'] = df['Period'].str.extract(r'(\w{4})', expand=False) df['Period'] = df['Period'].str.extract(r'(.\d{1})',expand=False) df Period Year 0 Q1 2012 1 Q2 2012 2 Q3 ...
pandas|numpy|jupyter-notebook
0
5,930
45,905,103
Insert a predefined array onto large array and shift the position of the smaller array iteratively
<p>I would like to insert a array of size 2*2 filled with zeros onto a larger array. Further, I would like to shift the position of the zero array left to right, top to bottom iteratively.</p> <pre><code>zero_array =[0 0 0 0] large_array =[ 1 2 3 4 5 6 7 8 9 10 11 12 ...
<pre><code>import copy import numpy as np la=np.array(&lt;insert array here&gt;) za=np.zeros((2,2)) ma=copy.deepcopy(la) for i in range(len(la)-len(za)+1): for j in range(len(la)-len(za)+1): la=copy.deepcopy(ma) la[i:i+len(za),j:j+len(za)]=za print la #la=large array #za=zero array </code></...
python|arrays|numpy|insert|iteration
0
5,931
45,968,411
Creating dataframe from tempfile
<p>Trying to load a temporary file into a pandas dataframe and throwing an error. Not sure how to get the parsed data from the temp file into a dataframe to use later on.</p> <pre><code>line = [] for x in readMe: line.append(" ".join(x.split())) with tempfile.NamedTemporaryFile() as temp: for i in line: ...
<p>You didn't show us what <code>readMe</code> contains, in particular what type it causes <code>i</code> to have. If possible, would you please run this under python3? If not, show us some details like <code>type(i)</code>, and do a trivial <code>temp.write('hello')</code> so it's clear the file descriptor is writable...
python|pandas
0
5,932
45,953,344
Getting error on ML-Engine predict but local predict works fine
<p>I have searched a lot here but unfortunately could not find an answer.</p> <p>I am running <code>TensorFlow 1.3</code> (installed via PiP on MacOS) on my local machine, and have created a model using the <a href="https://github.com/tensorflow/models/blob/master/object_detection/g3doc/detection_model_zoo.md" rel="no...
<p>I had a similar <a href="https://stackoverflow.com/q/46889203/7665986">issue</a>. This issue is due to mismatch in Tensorflow versions used for training and inference. I solved the issue by using Tensorflow - 1.4 for both training and inference. </p> <p>Please refer to <a href="https://stackoverflow.com/a/47493624/...
tensorflow|google-prediction
3
5,933
35,561,665
Tensorflow sequence2sequence model padding
<p>In the seq2seq models, paddings are applied to make all sequences in a bucket have the same lengths. And apart from this, it looks like no special handling is applied to the paddings:</p> <p>the encoder encodes the paddings as well the basic decoder w/o attention decodes using the last encoding which encodes the pa...
<p>I think your basic premise is correct: the model does not treat the padding symbol differently than any other symbol. However, when packing the data tensors the padding always shows up at the end of decoder training examples after the 'EOS' symbol, and at the beginning of encoder training examples (because the encod...
tensorflow
1
5,934
35,345,283
Tensorflow Race conditions when chaining multiple queues
<p>I'd like to compute the mean of each of the RGB channels of a set of images in a multithreaded manner.</p> <p>My idea was to have a <code>string_input_producer</code> that fills a <code>filename_queue</code> and then have a second <code>FIFOQueue</code> that is filled by <code>num_threads</code> threads that load i...
<p>Your <code>QueueRunner</code> will start <code>num_threads</code> threads which will race to access your <code>reader</code> and push the result onto the queue. The order of images on <code>queue</code> will vary depending on which thread finishes first.</p> <p><strong>Update Feb 12</strong></p> <p>A simple exampl...
python|multithreading|queue|race-condition|tensorflow
2
5,935
35,763,048
Comparing DataFrames of different lengths
<p>I'm trying to filter one DataFrame by the values of another DataFrame, but can't get it to work as the filter-by-DataFrame has a different size than the to-be-filtered DataFrame. I thought I need to use <code>set_index</code> to align both DataFrames somehow, but that may be wrong.</p> <pre><code>import pandas as p...
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex_like.html" rel="nofollow"><code>reindex_like</code></a> to allign your second dataframe to <code>df1</code> size and then use your attempt with addition of <a href="http://pandas.pydata.org/pandas-docs/stable/genera...
python|pandas
2
5,936
35,589,820
Python 'map' function inserting NaN, possible to return original values instead?
<p>I am passing a dictionary to the <code>map</code> function to recode values in the column of a Pandas dataframe. However, I noticed that if there is a value in the original series that is not explicitly in the dictionary, it gets recoded to <code>NaN</code>. Here is a simple example:</p> <p>Typing...</p> <pre><cod...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html"><code>replace</code></a> instead of <code>map</code>:</p> <pre><code>&gt;&gt;&gt; s = pd.Series(['one','two','three','four']) &gt;&gt;&gt; recodes = {'one':'A', 'two':'B', 'three':'C'} &gt;&gt;&gt; s.map(recodes) 0 A...
python|pandas|map-function
58
5,937
11,971,089
Adding a vector to matrix rows in numpy
<p>Is there a fast way in numpy to add a vector to every row or column of a matrix.</p> <p>Lately, I have been tiling the vector to the size of the matrix, which can use a lot of memory. For example</p> <pre><code> mat=np.arange(15) mat.shape=(5,3) vec=np.ones(3) mat+=np.tile(vec, (5,1)) </code></pre>...
<p>For adding a 1d array to every row, broadcasting already takes care of things for you:</p> <pre><code>mat += vec </code></pre> <p>However more generally you can use <code>np.newaxis</code> to coerce the array into a broadcastable form. For example:</p> <pre><code>mat + np.ones(3)[np.newaxis,:] </code></pre> <p>W...
vector|matrix|numpy
38
5,938
28,482,463
Numpy: Convert array of keys into array of values
<p>I have an array and a dict having the entries of array as keys. How can I get array with entries having values corresponding to keys in the first array? What is the pythonic way without using simple loops.</p> <p>For e.g. I have an array:</p> <pre><code> a = np.array([['1','2','3'],['10','4','5'],['9','34','6']],...
<p>OK found the answer:</p> <pre><code>a_flat = numpy.ndarray.flatten(a) b = [d[x] if d.has_key(x) else 0 for x in a_flat] b = numpy.reshape(c,a.shape) print b </code></pre>
python|arrays|numpy|dictionary
0
5,939
28,834,341
why python failed to use or upgrade package installed by pip?
<p>This problem may seem simple to most of you but I'm really confused. I tried to install numpy &amp; pandas using pip. So initially I just did:</p> <pre><code>sudo pip install pandas. </code></pre> <p>It installed successfully but when i tried:<code>import pandas</code> there's error as:</p> <pre><code>Traceback (...
<p>Uninstall Numpy and then Re-install the newest version of it.</p> <pre><code>pip uninstall numpy pip install numpy </code></pre> <p>I too was facing this problem earlier.</p>
python|numpy|pandas|path|installation
1
5,940
50,947,383
Python - How to fill string value with the modal value for the group
<p>I have a dataset like the below. I want to be able to be able to populate the missing text with what is normal for the group. I have tried using ffil but this doesn't help the ones that are blank at the start, and bfil similarly for the end. How can I do this?</p> <pre><code>Group Name 1 Annie 2 NaN...
<p>Using <code>collections.Counter</code> to create a modal mapping by group:</p> <pre><code>from collections import Counter s = df.dropna(subset=['Name'])\ .groupby('Group')['Name']\ .apply(lambda x: Counter(x).most_common()[0][0]) df['Name'] = df['Name'].fillna(df['Group'].map(s)) print(df) Group ...
python|pandas|dataframe|pandas-groupby
4
5,941
50,899,488
Tensorflow python: reshape input [batchsize] to tensor [batchsize, 2] with specific order
<p>I have a tensor (shape=[batchsize]). I want to reshape the tensor in a specific order and into shape=[-1,2]. But I want to have:</p> <ol> <li>Element at [0,0]</li> <li>Element at [1,0]</li> <li>Element at [0,1]</li> <li>Element at [1,1]</li> <li>Element at [0,2]</li> <li>Element at [0,3]</li> <li>Element at [2,1]</...
<p>You could try</p> <pre><code> tf.reshape(tf.matrix_transpose(tf.reshape(x, [-1, 2, 2])), [-1, 2]) </code></pre>
python|tensorflow|reshape|tensor
0
5,942
50,914,759
does pandas have function similar to rowSums in R
<p>I have dataframe:</p> <p>df:</p> <pre><code>customer sample1 sample2 sample3 sample4 costprice1 10 21 32 43 costprice2 12 24 15 18 costprice3 1 2 15 8 costprice4 16 30 44 58 costprice5 18 33 48 63 costprice6 20 36 52 68 costprice7 22 39 56 73 costprice8 24 42 60 78 costpric...
<pre><code>In [16]: df[df.select_dtypes(['number']).lt(15).sum(axis=1) &lt; 3] Out[16]: customer sample1 sample2 sample3 sample4 0 costprice1 10 21 32 43 1 costprice2 12 24 15 18 3 costprice4 16 30 44 58 4 costprice5 18 ...
python-2.7|pandas
3
5,943
50,719,981
sqlalchemy.exc.ResourceClosedError: This result object does not return rows. It has been closed automatically
<pre><code>sql='delete a from sample a, TEMPLATE b where a.emailid=b.emailid ' df=psql.read_sql_query(sql,con=engine) print df.head() </code></pre> <p>how do i delete common rows using pandas without reading the table or csv. Kinldy please suggest me a best way....as reading of table is taking lot of time i used"p...
<p>Pandas is using sqlalchemy under the hood, simply run your query using the engine.</p> <pre><code>with engine.begin() as conn: conn.execute(sql) # safety checks go here, once the end of the with clause is reached the trans is committed. </code></pre>
mysql|python-2.7|pandas
1
5,944
50,893,052
Pandas pivot_table with pd.grouper and Margins
<p><code>Margins=True</code> will not work in Pandas pivot_table when columns is set as <code>pd.grouper datetime</code>. this is my code which works as expected-- </p> <pre><code>p = df.pivot_table(values='Qty', index=['ItemCode', 'LineItem'],columns=pd.Grouper(key = 'Date', freq='W'), aggfunc=np.sum, fill_value=0) <...
<p>That looks strange! I wonder what causes the pivot table to use the TimeGrouper itself to be used as the index. It's seems like a bug, but I'm not sure. In any case, I think pivottables aren't able to do sub-index margins, so here is a solution with groupby instead:</p> <p><strong>Sample data</strong></p> <pre><co...
python|pandas|pivot-table
1
5,945
50,965,581
Unexpected error when trying to concatenate dataframes with categorical data
<p>I've got two dataframes df1 and df2 that look like this:</p> <pre><code>#df1 counts freqs categories automatic 13 0.40625 manual 19 0.59375 #df2 counts freqs categories Straight Engine 18 0...
<p>try this,</p> <pre><code>pd.concat([df1.reset_index(),df2.reset_index()],ignore_index=True) </code></pre> <p>Output:</p> <pre><code> categories counts freqs 0 automatic 13 0.40625 1 manual 19 0.59375 2 Straight Engine 18 0.56250 3 V engine 14 0.43750 </...
python|pandas|concatenation|categorical-data
2
5,946
33,275,096
Using Pandas to merge 2 list of dicts with common elements
<p>So I have 2 list of dicts..</p> <pre><code>list_yearly = [ {'name':'john', 'total_year': 107 }, {'name':'cathy', 'total_year':124 }, ] list_monthly = [ {'name':'john', 'month':'Jan', 'total_month': 34 }, {'name':'cathy', 'month':'Jan', 'total_month':78 }, {'name':'john', 'month':'Feb', 'total_month': 73 }...
<p>Within pandas, try:</p> <pre><code>df1 = pd.DataFrame(list_yearly) df2 = pd.DataFrame(list_monthly) df = df1.set_index('name').join(pd.DataFrame(df2.groupby('name').apply(\ lambda gp: gp.transpose().to_dict().values()))) </code></pre> <p>Update: with removing names from dicts and converting to a list of dict...
python|list|pandas|dictionary|data-munging
1
5,947
66,577,309
How to find the `True` values' corresponding index and column in a large Pandas DataFrame?
<p>I have a large DataFrame <code>df</code> whose values are mostly <code>False</code>.</p> <p>About 1% of the values of <code>df</code> are <code>True</code>.</p> <p>How can I display the <code>True</code> values' corresponding index and column?</p> <p>Here's the index of <code>df</code></p> <pre><code>df.index Dateti...
<p>Suppose we have this:</p> <pre><code># Test data a b c 2010 True False False 2011 False False True </code></pre> <p>You can try <code>np.where</code>:</p> <pre><code>x,y = np.where(df) indexes = df.index[x] columns = df.columns[y] print(indexes, columns) </code></pre> <p>Output:</p> <pre>...
python|pandas|dataframe
1
5,948
66,425,987
I get this error message: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'
<p>here is my code.</p> <pre><code>import numpy as np from scipy.optimize import minimize import sympy as sp sp.init_printing() from sympy import * from sympy import Symbol, Matrix rom sympy import * def make_Aij(m, n, a='a') : from sympy import Symbol, Matrix # just in case they aren't already loaded A = zero...
<p>The symbolic <code>sympy</code> doesn't mix well with the numeric <code>scipy</code> and <code>numpy</code>. The numeric functions don't understand about <code>sympy</code>'s symbols.</p> <p>To get things to work together, all symbolic functions need to be converted to numpy equivalents. <code>sympy</code>'s <code>l...
python|numpy|scipy|sympy
1
5,949
66,371,405
how do i Determine a Cut-Off or Threshold When Working With Fuzzymatcher in python
<p>Please help on the photo is a screenshot of my output and code as well, how do i use the best_match_score <strong>I NEED TO FILTER BY THE RETURNED &quot;PRECISION SCORE</strong>&quot; THE COLUMN ONLY COMES AFTER THE MERGE (i.e. JUST RETURN EVERYTHING with <strong>'best_match_score'</strong> BELOW -1.06)</p> <pre><co...
<p>This seems very straightforward unless I'm missing something. Be sure to try read the documentation about <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html" rel="nofollow noreferrer">slicing data in pandas</a>.</p> <pre><code>mask = Data_merge['best_match_score'] &lt; .1.06 filtered_data...
python|pandas|dataframe|python-dataclasses|python-datamodel
1
5,950
66,375,749
Check comma from pandas columns and if it exist remove it and divided by 100 Python Pandas
<p>Let us say I have the following simple data frame:</p> <p>df</p> <pre><code>Test 3454,23 65 98,50 </code></pre> <p>I want check whether comma or dot (.) exist and if it exist remove it and divided by 100.</p> <p>The result seems like below.</p> <pre><code>Test 3454.23 65 98.50 </code></pre> <p>I have tried this.</p>...
<p>Use <code>df.str.contains</code> to define condition and then</p> <pre><code>np.where(condition, outcome if condition true, outcome if contion false) </code></pre> <p>code below:</p> <pre><code>df['Test']=np.where(df['Test'].str.contains('\,'),df['Test'].str.replace(',','').astype(int)/100,df['Test']) Test 0 ...
python|pandas
2
5,951
57,512,400
Update a string in a column based on conditions from a function in a Pandas Dataframe
<p>I'm trying to clean up a column that contains strings with more information than necessary. I tried searching for substrings or keywords and if found to replace with new string or keyword. </p> <p>This is my df.</p> <pre><code>var1 = [('Car 1',1), ('Book',2), ('Apple cake',3), ('Tree',4), ...
<p>You nee to <code>apply</code> the method to the <code>Item</code> column. Hence do:</p> <pre><code>df['Item'] = df['Item'].apply(item_check) </code></pre> <p>Output:</p> <pre><code> Item Code 0 Car 1 1 Book 2 2 Apple 3 3 Tree 4 4 Horse 5 5 Car 1 6 Apple 3 7 Book ...
pandas|dataframe
0
5,952
57,318,578
How to iterate over the third array dimension returning a the 2d array
<p>i have got a 3d numpy array, what is the best way to iterate over the third dimension in a for loop returning the 2d array of the current interation?</p>
<p>just loop with its third dim:</p> <pre><code>import numpy as np a = np.arange(24).reshape((2,3,4)) for i in range(a.shape[2]): # index 2 is for 3rd dimension print(a[:, :, i]) # or print(a[..., i]) </code></pre> <p>then you got it.</p> <p>but using loop with numpy array is costly, you should <...
python|arrays|numpy|matrix
0
5,953
24,394,507
empty strings after genfromtxt numpy
<p>Thanks for your patience, as I'm pretty new to python. The input file is a tab-delimited table.</p> <pre><code>import numpy as np #from StringIO import StringIO inputfile=raw_input('Filepath please: ') fieldnames='Reference Position, Type, Length, Reference, Allele, Linkage, Zygosity, \ Count, Coverage, Freq...
<p>But the problem now is that after I print storage, all the cells that are of dtype str are empty strings (''). Why is this?</p> <p>EDIT3: I solved the empty string problem by changing the str types above to |S#, where # is an integer.</p> <p>EDIT4: See comment from Jinan Dangor below.</p>
python|string|numpy
-1
5,954
43,873,620
pivot_table on multi-indexed dataframe
<p>How can I apply pandas.pivot_table to the dataframe:</p> <pre><code>df = pd.DataFrame( [ {'o1_pkid': 645, 'o2_pkid': 897, 'colname': 'col1', 'colvalue': 'sfjdka'}, {'o1_pkid': 645, 'o2_pkid': 897, 'colname': 'col2', 'colvalue': 25}, {'o1_pkid': 645, 'o2_pkid': 159, 'colname': 'col1', 'colvalue': 'laksjd...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow noreferrer"><code>unstack</code></a>:</p> <pre><code>...
pandas|pivot-table
1
5,955
43,877,196
how can i add together the data of two dataframes
<p>I want to add together data from two dataframes in this way:</p> <pre><code> &gt;&gt;&gt; df1 = pd.DataFrame({'col1': [1, 2, 3], 'col2': [2, 3, 2], 'col3': ['aaa', 'bbb', 'ccc']}) &gt;&gt;&gt; df1 col1 col2 col3 0 1 2 aaa 1 2 3 bbb 2 3 2 ccc &gt;&gt;&gt; df2 = pd.DataFrame({'...
<p>Let's use <code>pd.concat</code> and <code>groupby</code> to sum values.</p> <pre><code>pd.concat([df1,df2]).groupby('col3').sum().reset_index().reindex_axis(['col1','col2','col3'],axis=1) </code></pre> <p>Output:</p> <pre><code> col1 col2 col3 0 1 2 aaa 1 2 3 bbb 2 4 4 more 3...
python|pandas
2
5,956
43,856,701
Pandas - inplace, view, copy confusion
<p>I'm having an issue with Pandas dataframes. It seems that Pandas/Python generate a copy of the DF somewhere in my code as opposed to performing the modifications to the original DF.</p> <p>In the code below, "update_df" still sees the DF with a "file_exists" column, which should have been removed by the previous fu...
<p>I think when you do:</p> <pre><code>df = df[df['file_exists'] != False] </code></pre> <p>You've created a copy of the original df.</p> <p>To make it work, you can change your function to:</p> <pre><code>def clean_df2(df): #remove non-existing files from DF df['file_exists'] = True # add column, set all to Tr...
python|pandas|dataframe
1
5,957
43,703,566
Pandas - Group By ID, Get Percentage
<p>Say I have a dataframe like so:</p> <pre><code>import pandas as pd df = pd.DataFrame({'ID': ['3a2b', '2a2b', '1a2b', '1a2b'], 'label': [2, 2, 1, 0]}) </code></pre> <p>df visualized:</p> <pre><code> ID label 3a2b 2 2a2b 2 1a2b 1 1a2b 0 </code></p...
<p>Use <code>get_dummies</code> on <code>label</code>, and groupby on <code>ID</code>, then <code>sum</code>, and apply row-wise percentage calculation.</p> <pre><code>In [48]: (pd.get_dummies(df['label'], prefix='label') .groupby(df['ID']) .sum() .apply(lambda x: x / x.sum() * 100,...
python|python-2.7|pandas
0
5,958
43,534,719
how to convert pd.to_timedelta() to time() object?
<p>I need get <code>0 days 08:00:00</code> to <code>08:00:00</code>.</p> <p>code:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'Slot_no':[1,2,3,4,5,6,7], 'start_time':['0:01:00','8:01:00','10:01:00','12:01:00','14:01:00','18:01:00','20:01:00'], 'end_time':['8:00:00','10:00:00','12:00:00','14:00:00','18:0...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.time.html" rel="nofollow noreferrer"><code>dt.time</code></a>:</p> <pre><cod...
python|pandas|time|timedelta
1
5,959
1,420,235
How can I generate a complete histogram with numpy?
<p>I have a very long list in a <code>numpy.array</code>. I want to generate a histogram for it. However, Numpy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html" rel="nofollow noreferrer" title="numpy.histogram reference">built in histogram</a> requires a pre-defined number of bins....
<p>If you have an array of integers and the max value isn't too large you can use numpy.bincount:</p> <pre><code>hist = dict((key,val) for key, val in enumerate(numpy.bincount(data)) if val) </code></pre> <p>Edit: If you have float data, or data spread over a huge range you can convert it to integers by doing:</p> <...
python|numpy|histogram
8
5,960
73,168,373
Ungroup/Unpivot 1 column in pandas
<p>My data is like this</p> <pre><code>g1 g2 g3 value1 value2 A X True 1 2 A X False 3 4 B Y True 5 6 </code></pre> <p>It was grouped by (g1, g2, g3) and then <code>reset_index</code>. What I am trying to do is to ungroup/unpivot the column <code>g3</code>...
<pre><code># Make the True/False into strings, this helps later. df.g3 = df.g3.astype(str) # Pivot your dataframe. df = df.pivot(index=['g1', 'g2'], columns='g3') # flatten the multiindex columns and join like you wanted. df.columns = df.columns.to_flat_index().str.join('_') print(df.reset_index().fillna(0)) </code><...
pandas
2
5,961
72,999,041
How to rename columns in Pandas automatically?
<p>I have a Dataframe with 240 columns. But they are named by number from 0 to 239.</p> <p>How can I rename it to respectively 'column_1', 'column_2', ........, 'column_239', 'column_240' automatically? <a href="https://i.stack.imgur.com/9pBVT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9pBVT.png...
<p>You can use:</p> <pre><code>df.columns = df.columns.map(lambda x: f'column_{x+1}') </code></pre> <p>Example output:</p> <pre><code> column_1 column_2 column_3 column_4 column_5 column_6 column_7 column_8 column_9 column_10 0 0 1 2 3 4 5 6 7 ...
python|pandas
4
5,962
73,046,416
torch geometric error: FileNotFound: Could not find module '...\.conda\envs\...\Lib\site-packages\torch_sparse\_convert_cuda.pyd'
<p>torch geometric error</p> <pre><code>FileNotFoundError: Could not find module '...\.conda\envs\urop\Lib\site-packages\torch_sparse\_convert_cuda.pyd' Try using the full path with constructor syntax. </code></pre> <p>Versions:</p> <p>torch_geometric==2.0.4</p> <pre><code>pytorch 1.11.0 ...
<p><strong>I solved</strong> my problem with this error. I simply had an <em>old version of Torch</em> and installed torch-scatter and torch-sparse pointing to a wheel with a newer PyTorch version with the -f pip flag (pip install -v torch-scatter -f <a href="https://pytorch-geometric.com/whl/torch-1.12.1+cu116.html" r...
python|pytorch|anaconda|pytorch-geometric
0
5,963
70,567,886
How to made a slice in a pandas dataframe?
<p>I want do a slice a dataframe using a string &quot;PP&quot; that is in my column and get just the numbers that is afeter string:</p> <p>Dataframe:</p> <pre><code>data = {'Serie':['28PP3097', '23228PP3097', '1822343218PP3097', '43642183097'], 'FooBar':[&quot;foo&quot;, &quot;bar&quot;, &quot;foo&quot;, &quot;bar&...
<p>You can do that by splitting and getting the last item after &quot;PP&quot;:</p> <pre><code>data = {'Serie':['28PP3097', '23228PP3097', '1822343218PP3097', '43642183097'], 'FooBar':[&quot;foo&quot;, &quot;bar&quot;, &quot;foo&quot;, &quot;bar&quot;]} df = pd.DataFrame(data) df['Serie']=[i.split('PP')[-1] fo...
python|pandas
1
5,964
70,448,690
Logits and labels must be broadcastable: logits_size=[400,3] labels_size=[16,3]
<p>I am trying to build a model that predicts the facial expression. The model I used: <a href="https://www.kaggle.com/nightfury007/fercustomdataset-3classes" rel="nofollow noreferrer">link</a>.</p> <p>I adjusted the data so that it has three folders: train, test, validation. Each folder contains three subfolders named...
<p>To get more information about the error, you can run in <em>eager</em> mode:</p> <pre><code>model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.Adam(lr=0.001), metrics=['accuracy'], run_eagerly=True) </code></pre> <p>In fact, there was an error with the input shape, wh...
python|tensorflow|keras
0
5,965
70,653,215
Add new column to pandas data frame based on string + value from another column in the data frame
<p>I have created a data frame using the code below:</p> <pre><code>bins = [['0', '50'], ['0', '100'], ['0', '150'], ['0', '200'], ['0', '250'], ['0', '300'], ['0', '350'], ['0', '400']] bins = pd.DataFrame(bins, columns = ['start', 'end']) bins['range'] = bins[['start', 'end']].agg('-'.join, axis=1) bins.start = pd.to...
<p>Use:</p> <pre><code>df['axis'] = 'up to ' + df['end'].astype(str) </code></pre>
python|pandas
2
5,966
42,800,377
Multilabel Classification with Tensorflow
<p>I have the code below for a multilabel classification:</p> <pre><code>import numpy as np import pandas as pd import tensorflow as tf from sklearn.datasets import make_multilabel_classification from sklearn.model_selection import train_test_split X, Y = make_multilabel_classification(n_samples=10000, n_features=200...
<p>The main problem with your code is that you are not using mini-batch gradient descent, and instead you are using the whole training data for each gradient descent update. Additionally 5000 epochs is too many I think, and I guess 50-100 will be enough (you can verify by experiment). Also at the following lines, the ...
tensorflow|gradient-descent|multilabel-classification
1
5,967
42,668,549
How can I plot the duration of a program in python
<p>I'm trying to plot the duration of some programs that is running in the night, I export the program duration data into a CSV file so that later on can be analyzed. (something like this) </p> <p><a href="https://i.stack.imgur.com/wZGiK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wZGiK.png" alt...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a> for creating <code>df</code>, then get difference of columns and <a href="http://pandas.pydata.org/pandas-docs/stable/timedeltas.html#frequency-conversion" rel="no...
python|csv|pandas|matplotlib|dataframe
2
5,968
42,882,721
Preserving a Month and Day as Date Format in Python Pandas
<p>I'm trying to take a column in yyyy-mm-dd format and convert to it mm-dd format (or MON DD, that works too), while preserving a date or numeric format. I've tried to use pd.to_datetime, but it seems that doesn't work because it requires the year, so it ends up padding the new columns with year 1900. I'm not looking ...
<p>Let's say you have:</p> <pre><code>df = pd.DataFrame({"OldDate":["2017-01-02","2015-05-14"]}) df OldDate 0 2017-01-02 1 2015-05-14 </code></pre> <p>Then you can do:</p> <pre><code>from datetime import datetime as dt df['OldDate'] = df.OldDate.apply(lambda s: dt.strptime(s, "%Y-%m-%d")) df['NewDate1']...
python|date|pandas
1
5,969
42,927,841
Trouble reading mnist with tensorflow
<p>So apparently the Yann LeCun's website is down so the following lines for reading mnist with tensorflow don't seem to be working :</p> <pre><code>FROM tensorflow.examples.tutorials.mnist IMPORT input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot = true) </code></pre> <p>Any ideas how can i read th...
<p>You can access the website here: <a href="https://web.archive.org/web/20160117040036/http://yann.lecun.com/exdb/mnist/" rel="nofollow noreferrer">https://web.archive.org/web/20160117040036/http://yann.lecun.com/exdb/mnist/</a> - download the data, and read it in from a local copy...</p> <p><strong>Edit</strong> <a ...
tensorflow|mnist
3
5,970
42,823,357
return a list in a method that is referencing a PD Dataframe
<p>Is there any way to return a list or tuple when referencing a pandas DF? get_df() is a pandas column with a couple hundred float values. The code below is asking to return the values greater than 6000 and less than 7000. Can I return a list to my method? (I know I can print this but that is not what I am trying to d...
<p>in case anyone cared, I figured it out. Had to append the the values as they were being iterated through.</p> <pre><code>def mass_needed(numb_one, numb_two): li = [] for i in get_df(): if i &gt; numb_one and i &lt; numb_two: li.append(i) return li x = pd.DataFrame(mass_need...
python|pandas
0
5,971
14,431,646
How to write Pandas dataframe to sqlite with Index
<p>I have a list of stockmarket data pulled from Yahoo in a pandas DataFrame (see format below). The date is serving as the index in the DataFrame. I want to write the data (including the index) out to a SQLite database. </p> <pre><code> AAPL GE Date 2009-01-02 89.95 14.76 2009-01-05 93.75 14.38 20...
<p>In recent pandas the index will be saved in the database (you used to have to <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.reset_index.html" rel="noreferrer"><code>reset_index</code></a> first).</p> <p>Following the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/io....
python|sqlite|pandas
62
5,972
30,399,147
What's the most pythonic way to load a matrix in ijv/coo/triplet format?
<p>My input file is in ijv/coo/triplet format with string column names, eg:</p> <pre><code>Apple,Google,1 Apple,Banana,5 Microsoft,Orange,2 </code></pre> <p>Should result in this 2x3 matrix:</p> <pre><code>[[1,5,0], [0,0,2]] </code></pre> <p>I can read it manually by putting the column names to dictionaries and cre...
<p>You need to define an unambiguous mapping from the row/column names to some indices (it is not important whether "Apple" is "0", or "1", just that it is represented by a number, hence this won't exactly match your result, but it should not matter). In this example, <code>'info.txt'</code> contains </p> <pre><code>A...
python|pandas|scipy|scikit-learn
1
5,973
39,102,051
Read the picture as a grayscale numpy array, and save it back
<p>I tried the following, expecting to see the grayscale version of source image:</p> <pre><code>from PIL import Image import numpy as np img = Image.open("img.png").convert('L') arr = np.array(img.getdata()) field = np.resize(arr, (img.size[1], img.size[0])) out = field img = Image.fromarray(out, mode='L') img.show()...
<p>When you are creating the <code>numpy</code> array using the image data from your Pillow object, be advised that the default precision of the array is <code>int32</code>. I'm assuming that your data is actually <code>uint8</code> as most images seen in practice are this way. Therefore, you must explicitly ensure t...
image|numpy|image-processing|python-3.3|pillow
4
5,974
39,050,539
How to add multiple columns to pandas dataframe in one assignment?
<p>I'm new to pandas and trying to figure out how to add multiple columns to pandas simultaneously. Any help here is appreciated. Ideally I would like to do this in one step rather than multiple repeated steps...</p> <pre><code>import pandas as pd df = {'col_1': [0, 1, 2, 3], 'col_2': [4, 5, 6, 7]} df = pd....
<p>I would have expected your syntax to work too. The problem arises because when you create new columns with the column-list syntax (<code>df[[new1, new2]] = ...</code>), pandas requires that the right hand side be a DataFrame (note that it doesn't actually matter if the columns of the DataFrame have the same names as...
python|pandas|dataframe
349
5,975
19,732,097
Conversion of 2D cvMat to 1D
<p>How can I convert 2D <code>cvMat</code> to 1D? I have tried converting 2D <code>cvMat</code> to Numpy array then used <code>ravel()</code> (I want that kind of resultant matrix).When I tried converting it back to <code>cvMat</code> using <code>cv.fromarray()</code> it gives an error that the matrix must be 2D or 3D...
<p>Use <code>matrix.reshape((-1, 1))</code> to turn the <em>n</em>-element 1D matrix into an <em>n</em>-by-1 2D one before converting it.</p>
python|opencv|numpy
0
5,976
29,140,233
Comparaison of L value in GrayScale image with Y value in YUV image
<p>In some comments on previous questions, people told me that <code>Y</code> value of a <code>YUV</code> image converted using:</p> <pre><code>image_in_yuv=cv2.cvtColor(image_in_bgr,cv2.COLOR_BGR2YUV) </code></pre> <p>is the same as the <code>L</code> value of the same image in its grayscale color space converted us...
<p>The conversion of an RGB image into grayscale and YUV uses different numerical values. The <code>Y</code> channel <em>is</em> the "grayscale component" in the image, only in the sense that it denotes brightness. In fact, if I recall correct, the range of <code>Y</code> is 16-235.</p> <p>Check out <a href="http://w...
python|opencv|numpy
0
5,977
28,899,920
Numpy : The truth value of an array with more than one element is ambiguous
<p>I am really confused on why this error is showing up. Here is my code:</p> <pre><code>import numpy as np x = np.array([0, 0]) y = np.array([10, 10]) a = np.array([1, 6]) b = np.array([3, 7]) points = [x, y, a, b] max_pair = [x, y] other_pairs = [p for p in points if p not in max_pair] &gt;&gt;&gt;ValueError: The t...
<p>Numpy arrays define a custom equality operator, i.e. they are objects that implement the <code>__eq__</code> magic function. Accordingly, the <code>==</code> operator and all other functions/operators that rely on such an equality call this custom equality function. </p> <p>Numpy's equality is based on element-wise...
python|numpy
8
5,978
29,224,987
Unit Test with Pandas Dataframe to read *.csv files
<p>I am often vertically concatenating many *.csv files in Pandas. So, everytime I do this, I have to check that all the files I am concatenating have the same number of columns. This became quite cumbersome since I had to figure out a way to ignore the files with more or less columns than what I tell it I need. eg. th...
<p>On second thought, instead of chunksize, just read in the first row and count the number of columns, then read and append everything with the correct number of columns. In short:</p> <pre><code>for f in files: test = pd.read_csv( f, nrows=1 ) if len( test.columns ) == 4: df = df.append( pd.read_csv...
unit-testing|python-2.7|pandas|dataframe
1
5,979
33,772,398
sum two pandas dataframe columns, keep non-common rows
<p><a href="https://stackoverflow.com/questions/33771675/pandas-concat-merge-and-sum-one-column#33771793">I just asked a similar question</a> but then realized, it wasn't the <em>right</em> question.</p> <p>What I'm trying to accomplish is to combine two data frames that actually have the same columns, but may or may...
<p>Self answering, there was an error in the comment above that caused a double adding. This is correct:</p> <pre><code>newdata = df2.pop('b') result = df1.combine_first(df2) result['b']= result['b'].add(newdata, fill_value=0) </code></pre> <p>seems to provide the solution to my use-case.</p>
python|pandas|dataframe
0
5,980
23,659,234
How to move my pandas dataframe to d3?
<p>I am new to Python and have worked my way through a few books on it. Everything is great, except visualizations. I really dislike matplotlib and Bokeh requires too heavy of a stack.</p> <p>The workflow I want is:</p> <p>Data munging analysis using pandas in ipython notebook -> visualization using d3 in sublimetext...
<p>Basically there is no best format what will fit all your visualization needs.</p> <p>It really depends on the visualizations you want to obtain.</p> <p>For example, a <a href="http://bl.ocks.org/mbostock/raw/3886208/" rel="nofollow noreferrer">Stacked Bar Chart</a> takes as input a CSV file, and an <a href="http://b...
pandas|d3.js|ipython|data-munging
5
5,981
22,726,498
What's the corresponding multielement operator version of "numpy.logical_or"?
<p>To sum elements up, we have binary operator <code>np.add</code>, and moreover <code>np.sum</code> dealing with multiple elements. Likewise, we have <code>np.multiply</code> and <code>np.product</code> to do the multiplication.</p> <p>But for <code>np.logical_or</code>, what's the corresponding multielement operator...
<p>You're thinking of <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html" rel="nofollow"><code>np.all</code></a> (for <code>logical_and</code>) or <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.any.html" rel="nofollow"><code>np.any</code></a> (for <code>logical_or</code>).</...
python|numpy|operators
1
5,982
22,835,914
Select two random rows from numpy array
<p>I have a numpy array as</p> <pre><code>[[ 5.80084178e-05 1.20779787e-02 -2.65970238e-02] [ -1.36810406e-02 6.85722519e-02 -2.60280724e-01] [ 4.21996519e-01 -1.43644036e-01 2.12904690e-01] [ 3.03098198e-02 1.50170659e-02 -1.09683402e-01] [ -1.50776089e-03 7.22369575e-03 -3.71181228e-02] [ -3.0...
<p>I believe you are simply looking for:</p> <pre><code>#Create a random array &gt;&gt;&gt; a = np.random.random((5,3)) &gt;&gt;&gt; a array([[ 0.26070423, 0.85704248, 0.82956827], [ 0.26840489, 0.75970263, 0.88660498], [ 0.5572771 , 0.29934986, 0.04507683], [ 0.78377012, 0.66445244, 0.088...
python|arrays|random|numpy
10
5,983
29,655,929
Apply function to multilevel columns
<p>Given a <code>pandas</code> dataframe:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({ 'clients': pd.Series(['A', 'A', 'A', 'B', 'B']), 'x': pd.Series([1.0, 1.0, 2.0, 1.0, 2.0]), 'y': pd.Series([6.0, 7.0, 8.0, 9.0, 10.0]), 'z': pd.Series([3, 2, 1, 0, 0]) }) grpd = df.grou...
<p>You can do vectorized versions of the operation:</p> <pre><code>grpd['new_col'] = grpd[('x', 'sum')]/grpd[('y', 'sum')] </code></pre> <p>Or, for consistency (makes the second-level index for <code>new_col</code> <code>sum</code> like it is for <code>x</code> and <code>y</code>):</p> <pre><code>grpd[('new_col','su...
python|pandas|multi-level
0
5,984
29,806,080
Numpy - constructing matrix of Jaro (or Levenshtein) distances using numpy.fromfunction
<p>I am doing some text analysis right now and as part of it I need to get a matrix of Jaro distances between all of words in specific list (so pairwise distance matrix) like this one:</p> <pre><code> │CHEESE CHORES GEESE GLOVES ───────┼─────────────────────────── CHEESE │ 0 0.222 0.177 0.444 CHORES...
<p>As suggested by @xnx I have investigated the <a href="https://stackoverflow.com/questions/18702105/parameters-to-numpys-fromfunction">question</a> and found out that fromfunc is not passing coordinates one by one, but actually passess all of indexies at the same time. Meaning that if shape of array would be (2,2) nu...
python|arrays|numpy|matrix
1
5,985
62,450,156
numpy set value with another multiple dimension array as index
<p>Assume there is a 4 dimension array idx1, stores 5 th dimension index for another 5 dimension array zeros1. like:</p> <pre><code>N,T,H,W = idx1.shape zeros1 = np.zeros( (N,T,H,W, 256) ) # it is guaranteed that idx1's value &lt;256 </code></pre> <p>I want to realize</p> <pre><code>for n in range(N): for t in r...
<p>Use open-range arrays and index to assign -</p> <pre><code>out = np.zeros( (N,T,H,W, 256) ) i,j,k,l = np.ogrid[:N,:T,:H,:W] out[i,j,k,l,idx1] = 1 </code></pre> <p>Alternatively, in one-line -</p> <pre><code>out[tuple((np.ogrid[:N,:T,:H,:W]+[idx1]))] = 1 </code></pre>
python|numpy
2
5,986
62,313,294
Get indices in pandas series while using str.findall
<p>I am working on finding the rows which contain a particular string. the dataset has close to 1 million rows. Here is a simple example; </p> <pre><code>text=['abc USER@xxx.com 123 any@www foo @ bar 78@ppp @5555 aa@111www','anontalk.com'] text=pd.Series(text) srhc=text.str.findall('www') srhc </code></pre> <p>And th...
<p>We can do <code>str</code> <code>contains</code> with <code>nonzero</code></p> <pre><code>srhc=text.str.contains('www').to_numpy().nonzero()[0] srhc Out[66]: array([0], dtype=int64) </code></pre>
python|pandas
1
5,987
62,428,492
how to convert np.double or np.float64 values to real value
<p>I have a binary file consists of multiple sensors data which is written by Catman software(HBM). I am reading that file using guidelines given by Catman Software.</p> <p><a href="https://docs.google.com/spreadsheets/d/1dZOw9L6_ukHNYlcR-n64DuRZ702nBq6jjA169q-aCz0/edit?usp=sharing" rel="nofollow noreferrer">https://d...
<p>this should read the first data value into a numpy array for you:</p> <pre class="lang-py prettyprint-override"><code>with open(file, 'rb') as f: file_id = int.from_bytes(f.read(2), byteorder='little') data_offset = int.from_bytes(f.read(4), byteorder='little') f.seek(data_offset, 0) first_data_value...
python|numpy|file|binary
0
5,988
62,147,370
AttributeError: 'Model' object has no attribute 'trainable_variables' when model is <class 'keras.engine.training.Model'>
<p>I've just started to learn Tensorflow (2.1.0), Keras (2.3.1) and Python 3.7.7.</p> <p>By the way, I'm running all my code on an Anaconda Environment on Windows 7 64bit. I have also tried on an Anaconda Environment on Linux and I get the same error.</p> <p>I'm following this Tensorflow's tutorial: "<a href="https:/...
<p>The problem is that you are using <code>keras</code> library instead of <code>tensorflow.keras</code>. When using tensorflow it is highly recommended to use its own keras implementation. </p> <p>This code should works </p> <pre><code>import tensorflow as tf from tensorflow import keras from tensorflow.keras.models...
python|tensorflow|keras
3
5,989
62,116,344
Convert a series of 2D XY-line plots into a 2D heatmap plot
<p>I'm pretty new to python coding, so apologies if this question has been asked before.</p> <p>I have a piece of code, written by another person, which I cannot show here, but it produces a series of line plots (like this <a href="https://i.stack.imgur.com/kQdVl.png" rel="nofollow noreferrer"><img src="https://i.stac...
<p><img src="https://i.stack.imgur.com/ZXz2h.png" width="100" height="100">It looks like you are trying to draw a <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist2d.html#matplotlib-pyplot-hist2d" rel="nofollow noreferrer">2d histogram</a>, would you like help with that?</p> <pre><code>N=200 t = np.li...
python|numpy|matplotlib|plot
0
5,990
62,441,606
ValueError: could not broadcast input array from shape (424,16,3) into shape (128,160,3)
<p>I was working with the code <a href="https://github.com/coxlab/prednet/blob/master/process_kitti.py" rel="nofollow noreferrer"><code>process_kitti.py</code></a> by coxlab from GitHub in an Anaconda environment. Some of the function was deprecated in Python 3.6. Therefore I have changed the following line:</p> <pre>...
<p>Do note that the <code>size</code> parameter in the <code>imresize</code> function from <code>scipy</code> is a 2-tuple of <code>(height, width)</code> while in <code>Pillow</code> package it is <code>(width, height)</code> so you might need to reverse the order</p> <p>Source: </p> <p><a href="https://docs.scipy.o...
python|numpy
1
5,991
62,185,353
Fill column with nan if sum of multiple columns is 0
<p><strong>Task</strong></p> <p>I have a <code>df</code> where I do some ratios that are groupby <code>date</code> and <code>id</code>. I want to fill column <code>c</code> with <code>NaN</code> if the sum of <code>a</code> and <code>b</code> is 0. Any help would be awesome!!</p> <p><strong>df</strong></p> <pre><cod...
<p>Try this:</p> <pre><code>df['new_c'] = df.c.where(df[['a','b']].sum(1).ne(0)) Out[75]: date id a b c new_c 0 2001-09-06 1 3 1 1 1.0 1 2001-09-07 1 3 1 1 1.0 2 2001-09-08 1 4 0 1 1.0 3 2001-09-09 2 6 0 1 1.0 4 2001-09-10 2 0 0 2 NaN 5 2001-09-11 1 0 0...
python|pandas|dataframe|fill
2
5,992
51,442,273
Assign different values into a new column based on dataframe chunk
<p>I have a dataframe:</p> <pre><code>df = pd.DataFrame({'a':[1,2,3,4,5,6,7,8,9,10],'b':[100,100,100,100,100,100,100,100,100,100]}) a b 0 1 100 1 2 100 2 3 100 3 4 100 4 5 100 5 6 100 6 7 100 7 8 100 8 9 100 9 10 100 </code></pre> <p>I want to create a column <code>c</code>, such...
<p>If your index is a RangeIndex you can use it to create your values for your c column:</p> <pre><code>df['c'] = df.index // 3 + 1 </code></pre>
python|pandas
1
5,993
51,275,683
ImportError: No module named pandas in Zeppelin (EMR)
<p>I have an EMR cluster with Spark/Hive/Zeppelin. In my Zeppelin notebook, I tried to import pandas:</p> <pre><code>import pandas as pd </code></pre> <p>But I got this error:</p> <pre><code>ImportError: No module named pandas </code></pre> <p>How can I resolve this issue? Is this because pandas not installed in th...
<p>It was a matter of installing pandas in the master node:</p> <pre><code>sudo pip install pandas </code></pre>
pandas|amazon-emr|apache-zeppelin
4
5,994
51,359,731
Tensorflow While loop with Variable Creation
<p>Tensorflow While loop with Variable Creation Code here : </p> <pre><code>x = tf.Variable(100) c = tf.Constant(2) n = 100 loops = 50 l1 = tf.Variable(np.random.random(n)) c1 = tf.Variable(np.random.random(n)) x = tf.multiply(c1,tf.exp(-(x-l1)/c)) l2 = tf.Variable(np.random.random(n)) c2 = tf.V...
<p>Can you feed it like this ?</p> <pre><code>l = tf.placeholder(tf.float32, shape=[None, ]) c = tf.placeholder(tf.float32, shape=[None, ]) sess = tf.Session() sess.run(tf.global_variables_initializer()) x = tf.multiply(l,c) #Assume a formula for i in range(50) : arr = np.random.random_sample((i,)) print ...
python|tensorflow
1
5,995
51,420,917
"Upsampling data" of data in Python
<p>I'm newish to Python and brand new to data-science.</p> <p>I've got a large data set that I've been using supervised machine learning (CART with scikit-learn) to classify. I'm using pandas data-frames, for the most part, to operate on the data. The data looks like this:</p> <pre><code>| F00 F01 F02 F03 ... C0 | | ...
<p>Original asker here:</p> <p>For anyone interested, I did the following using the imblearn package:</p> <pre><code>from imblearn.over_sampling import RandomOverSampler, SMOTE, ADASY def organize_data(data, upsample=False, upmethod = None): # entire organizing, cleaning data function ... if upsample: upsa...
python|pandas|machine-learning|scikit-learn|data-science
1
5,996
48,273,907
Pandas- set values to an empty dataframe
<p>I have initialized an empty pandas dataframe that I am now trying to fill but I keep running into the same error. This is the (simplified) code I am using</p> <pre><code>import pandas as pd cols = list("ABC") df = pd.DataFrame(columns=cols) # sett the values for the first two rows df.loc[0:2,:] = [[1,2],[3,4],[5,6]...
<p>Since you have the columns from empty dataframe use it in dataframe constructor i.e </p> <pre><code>import pandas as pd cols = list("ABC") df = pd.DataFrame(columns=cols) df = pd.DataFrame(np.array([[1,2],[3,4],[5,6]]).T,columns=df.columns) A B C 0 1 3 5 1 2 4 6 </code></pre> <p>Well, if you want to ...
python|pandas
5
5,997
48,112,174
TensorFlow Lite: Error converting to .tflite using toco
<p>I am trying to covert my TensorFlow frozen model to a tflite model. When I run toco, I get an error message reads as below</p> <pre><code>F tensorflow/contrib/lite/toco/graph_transformations/propagate_fixed_sizes.cc:982] Check failed: input_dims.size() == 4 (2 vs. 4) </code></pre> <p>Here is how I call toco:</p> ...
<p>After raising this as an issue on the TensorFlow bug tracker on GitHub, the answer boiled down to the fact that TLite for now doesn't completely support ArgMax. <a href="https://github.com/tensorflow/tensorflow/issues/15948" rel="nofollow noreferrer">Link</a></p>
tensorflow|tensorflow-serving|tensorflow-lite
2
5,998
48,038,417
keras stops working on first epoch
<p>I am running an image classification model. This is where I got stuck. Tried downgrading keras version to 1.0.2 and running the script again didn't work.</p> <p>Jupyter notebook just keeps processing and doesn't run anything after the first epoch, running code on keras 1.2 with python 3.5</p> <p>OUTPUT:</p> <pre>...
<p>Try with <code>verbose = 1</code> in your <code>model.fit</code> call, it will print the progress bar. It is probably working, but due to the value of 2 given to the verbose parameter, it will only print one line of output AFTER the epoch has ended, which might take some time depending on your CPU/GPU and quantity o...
tensorflow|keras
4
5,999
48,389,563
Simple Conv1D as first layer in keras
<p>Here is my input</p> <pre><code>x_train.shape # (12, 7) 12 observations each of length 7 x_train # dtype('int32') </code></pre> <p>Here's the architecture I'd like to achieve:</p> <p><a href="https://i.stack.imgur.com/RgbTB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RgbTB.jpg" alt="enter i...
<p>As the error message says, your input is two dimensional while the convolutional layer expects a three dimensional input. </p> <p>With the following</p> <pre><code>docs_sequence = Input(shape=(7,1), ... </code></pre> <p>instead of </p> <pre><code>docs_sequence = Input(shape=(7,), ... </code></pre> <p>Keras acce...
python|tensorflow|keras
5