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
355,400
42,912,234
Restore TensorFlow model with Dropout applied
<p>I'm having problems restoring TF models which I've trained using dropout. How do I set the <code>keep_prob</code> to <code>1.0</code>?</p> <p>The code which I've tried below is not working, and I think it's due to the fact that I create a new <code>tf.placeholder</code> when I restore the model. But how do I restor...
<p>You've correctly observed the problem. The <code>keep_prob = tf.placeholder(tf.float32)</code> tensor is unconnected to the graph that you import with <a href="https://www.tensorflow.org/api_docs/python/tf/import_graph_def" rel="nofollow noreferrer"><code>tf.train.import_meta_graph()</code></a>, so feeding that tens...
python|tensorflow
1
355,401
27,062,652
pandas rolling sum of last five minutes
<p>Assume I have below data frame</p> <pre><code>Date, A 2014-11-21 11:00:00, 1 2014-11-21 11:03:00, 4 2014-11-21 11:04:00, 1 2014-11-21 11:05:00, 2 2014-11-21 11:07:00, 4 2014-11-21 11:08:00, 1 2014-11-21 11:12:00, 1 2014-11-21 11:13:00, 2 </code></pre> <p>First column is datetime object and second column is an inte...
<p>In general, if the dates are completely arbitrary, I think you would be forced to use a Python <code>for-loop</code> over the rows or <a href="https://stackoverflow.com/q/14300768/190597">use <code>df.apply</code></a>, (which under the hood, also uses a Python loop.)</p> <p>However, if your Dates share a common fre...
python|pandas|sum|time-series
21
355,402
27,156,758
Convert value to row index in NumPy array
<p>I have an array in which the first row is a category, the second row is a subcategory, and the third row is a value that I would like to condense.</p> <p>I'm trying to rearrange array A</p> <pre><code>[[ 4 4 19 19 20 21 25 26 26 27 27 29] # category [ 1 2 1 2 1 2 1 1 2 1 2 2] # subcategory [ 1 1 ...
<p>This should do the trick:</p> <pre><code>cat_index = np.searchsorted(categories, A[0]) B[A[1], cat_index] = A[2] </code></pre>
python|arrays|numpy
1
355,403
27,054,368
Reverse sort a 2d numpy array in python
<p>I have a numpy array like:</p> <pre><code>A = array([[-inf, 4, 5, 10, -inf, 1], [-inf, 2, 6, 8, -inf, 1], [-inf, 4, -inf, 10, -inf, 100] ]) I need to sort in a decreasing order: A = array ([ 10,5,4,1,-inf,-inf], [8,6,2,1,-inf,-inf], [100,10,4,-inf,-inf,...
<p>How about</p> <pre><code>A.sort() A[:,::-1] </code></pre> <p>?</p> <p>References :</p> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.sort.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.sort.html</a></p> <p><a href="http://docs.scipy.org/doc...
python|numpy
5
355,404
27,407,034
Find largest difference between adjacent floats in ordered array
<p>Say I have an <em>ordered</em> array/list like this one:</p> <pre><code>a = [0.2, 0.35, 0.88, 1.2, 1.33, 1.87, 2.64, 2.71, 3.02] </code></pre> <p>I want to find the largest difference between adjacent elements efficiently. In this case it would be <code>(2.64 - 1.87) = 0.77</code>.</p> <p>I could use a <code>for<...
<p>A numpy solution:</p> <pre><code>np.diff(a).max() </code></pre>
python|arrays|performance|numpy
5
355,405
26,983,026
Adding up all columns with multiindex on axis 0
<p>I have a multiIndexed pandas dataframe called <code>df</code> looking like this: </p> <pre><code> Rh 0.1 0.2 0.3 x y z 0 0 0 0.125 0.126 0.127 1 0.134 0.135 0.137 1 0 ... </code></pre> <p>I want to keep the x,y,z multiIndex and sum up all columns. The call <code>df...
<p>Works on my end:</p> <pre><code>from io import StringIO import pandas datafile = StringIO("""\ x y z A B C 0 0 0 0.125 0.126 0.127 0 0 1 0.134 0.135 0.137 """) df = pandas.read_table(datafile, index_col=['x', 'y', 'z'], sep='\s+') df.sum(axis=1) x y z 0 0 0 0.378 1 ...
python|pandas|dataframe
1
355,406
27,397,151
All operations that will result in nan values(python)
<p>This may be a simple question but i could not get all the answers in one place, so any help and answer are welcome :) . I am trying to debug a program, But then I realize I don't know what are all the possible operation that may result in a NAN value in python. so here is the question what are all the possible opera...
<p>NaNs are part of the IEEE 754 standards. Operation like but not limited to inf * 0, inf / inf or any operation involving a NaN, e.g. nan * 1, return a NaN.</p> <p><a href="http://en.m.wikipedia.org/wiki/IEEE_754-1985" rel="nofollow">http://en.m.wikipedia.org/wiki/IEEE_754-1985</a></p>
python|numpy|nan
1
355,407
27,273,428
Pandas: dropping all columns with nans, 0, and NA from DataFrame
<p>I have a DataFrame that looks like this:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'A': [1, 2.1, np.nan, 4.7, 5.6, 6.8], 'B': [0, np.nan, np.nan, 0, 0, 0], 'C': [0, 0, 0, 0, 0, 0.0], 'D': [5, 5, 5, 5, 5.6, 6.8], 'E': ['N...
<p>You could try using <code>df.isin()</code> and <code>all()</code> to find an array of columns which don't contain only null values and then use this array to select the relevant columns of <code>df</code>:</p> <pre><code>&gt;&gt;&gt; df[df.columns[(~df.isin([NaN, 'NA', 0])).all().values]] A D 0 1.0 5.0 1 ...
python|pandas|dataframe|nan
3
355,408
27,025,788
Fast iteration over vectors in a multidimensional numpy array
<p>I'm writing some python + numpy + cython code, and am trying to find the most elegant and efficient way of doing the following kind of iteration over an array:</p> <p>Let's say I have a function f(x, y) that takes a vector x of shape (3,) and a vector y of shape (10,) and returns a vector of shape (10,). Now I have...
<p>You are describing what Numpy calls a Generalized Universal FUNCtion, or gufunc. As it name suggests, it is an extension of ufuncs. You probably want to start by reading these two pages:</p> <ul> <li><a href="http://docs.scipy.org/doc/numpy/user/c-info.ufunc-tutorial.html" rel="noreferrer">Writing your own ufunc</a...
python|arrays|numpy|iterator|cython
5
355,409
14,904,743
how to manipulate numpy arrays for use with ESRI's arcpy.da.NumPyArrayToTable
<p>ESRI gives access to moving data from tables to arrays and back. I have a script that takes census data from an api call and converts it into arrays, does some simple math, and then, ideally, puts it out into a table. To do the math, the array cannot be a rec array. No combination of vstack, hstack, or concatenate s...
<p>You should be able to use the structured arrays (technically you're not using <a href="http://www.scipy.org/Cookbook/Recarray" rel="nofollow">recarrays</a>) to do the "simple math." I'm not sure if you're showing the math you'd like to do, but for example if you want to do:</p> <pre><code>HHsize_array = Tpop_array...
python|numpy|arcgis|arcpy
1
355,410
14,391,504
Using Array to Store Pixels of Window
<p>Is it possible (in terms of performance) to have a single multi-dimensional array that contains one 8-bit integer per pixel, for each pixel in the game window? I need to update the game window in a timely manner based on this array. </p> <p>I'm aiming for something like the following:</p> <pre><code>import numpy w...
<p>I have never used pygame, so take my anwser with a grain of salt...</p> <p>That said, it seems very unlikely that you are going to get any decent frame rate if you are iterating over 360,000 pixels with a python loop and doing a python function call at each one.</p> <p>I learned from <a href="https://stackoverflow...
python|arrays|numpy|pixel
0
355,411
14,586,898
pandas.DataFrame.load/save between python2 and python3: pickle protocol issues
<p>I haven't figure out how to do pickle load/save's between python 2 and 3 with pandas DataFrames. There is a 'protocol' option in the pickler that I've played with unsuccessfully but I'm hoping someone has a quick idea for me to try. Here is the code to get the error:</p> <p>python2.7</p> <pre><code>&gt;&gt;&gt; im...
<p>I had the same problem. You can change the protocol of the dataframe pickle file with the following function in python3:</p> <pre><code>import pickle def change_pickle_protocol(filepath,protocol=2): with open(filepath,'rb') as f: obj = pickle.load(f) with open(filepath,'wb') as f: pickle.dum...
python|pandas
8
355,412
25,107,116
getting indices when comparing multidimensional arrays
<p>I have two numpy arrays, one an <code>RGB</code> image, one a lookup table of pixel values, for example:</p> <pre><code>img = np.random.randint(0, 9 , (3, 3, 3)) lut = np.random.randint(0, 9, (1,3,3)) </code></pre> <p>What I'd like is to know the <code>x,y</code> coordinate in <code>lut</code> of pixels whose valu...
<pre><code>img = np.random.randint(0, 9 , (3, 3, 3)) lut2 = img[1,2,:] # so that we know exactly the answer # compare two matrices img == lut2 array([[[False, False, False], [False, False, False], [False, True, False]], [[False, False, False], [False, False, False], [ True, T...
python|arrays|numpy|multidimensional-array|indexing
1
355,413
25,159,806
Performing calculations on specific rows in dataframe and using the results to perform additonal calculations
<p>Provided an example table below (In reality, this table would have many more experiments for a given subject, many more samples, and variable numbers of replicates):</p> <pre><code>SujectID Experiment Sample Results A 1 neg 1 A 1 neg 2 A ...
<p>One approach - filter your dataframe to just the negative samples before you do the groupby, then combine back with your larger frame using <code>merge</code></p> <pre><code>neg_sample = df['Sample'] == 'neg' neg_means = df[neg_sample].groupby(['SujectID', 'Experiment']).mean() neg_means.columns = ['Adj'] df = df....
python|pandas
1
355,414
25,218,465
Working on multidimensional arrays
<p>I'm trying to scale the colors of images to predefined ranges. Based on least-squared error from palette's range of colors, a color is assigned to output pixel.</p> <p>I have written the code in python loops is there a better vectorized way to do this?</p> <pre><code>import numpy as np import skimage.io as io pal...
<p>Don't loop over all pixels, but over all colors:</p> <pre class="lang-py prettyprint-override"><code>import pylab as pl palette = pl.array([[180, 0, 0], [255, 150, 0], [255, 200, 0], [0, 128, 0]]) img = pl.imread('lena.jpg')[:, :, :3].astype('float') R, G, B = img[:, :, 0].copy(), img[:, :, 1].copy(), img[:, :, 2...
python|image-processing|numpy|scikit-image
0
355,415
30,341,089
matrix operation using numpy pandas
<p>I am trying to test same example given on <a href="https://stackoverflow.com/questions/30293881/matrix-search-operation-using-numpy-and-pandas">Matrix search operation using numpy and pandas</a></p> <p>on <code>3.5.0-17-generic #28-Ubuntu SMP Tue Oct 9 19:32:08 UTC 2012 i686 i686 i686 GNU/Linux</code> with <code>py...
<p>I agree with @Anthony Lethuillier 's answer and I just guess the <code>IndexError</code> may be caused by different version. It seem's in @nlper 's situation, <code>C</code> is <code>(array([], dtype=int32),)</code> which means nothing found in <code>ds1.values.ravel()[:, None] == ds2.values[:, 0]</code>, and this i...
python|numpy|matrix|pandas
2
355,416
30,547,102
Running complex calculations (using python/pandas) in a Django server
<p>I have developed a RESTful API using the Django-rest-framework in python. I developed the required models, serialised them, set up token authentication and all the other due diligence that goes along with it.</p> <p>I also built a front-end using Angular, hosted on a different domain. I setup CORS modifications so ...
<p>I assume your question is about "how do I do these calculations in the restful framework for django?", but I think in this case you need to move away from that idea.</p> <p>You did everything correctly but RESTful APIs serve resources -- basically your model.</p> <p>A computation however is nothing like that. As I...
python|django|python-2.7|numpy
2
355,417
30,340,277
How to use variables inside query in Pandas?
<p>I have problem quering the data frame in panda when I use variable instead of value.</p> <pre><code>df2 = pd.read_csv('my.csv') query=df2.query('cc_vehicle_line==7') </code></pre> <p>works fine but</p> <pre><code>df2 = pd.read_csv('my.csv') query=df2.query('cc_vehicle_line==variable_name') </code></pre> <p>It th...
<p>You should use <code>@variable_name</code> with <code>@</code></p> <pre><code>query=df2.query('cc_vehicle_line==@variable_name') </code></pre>
python|variables|indexing|pandas
22
355,418
30,634,812
pandas matplotlib .plot(kind='hist') vs .plot(kind='bar') issue
<p>I have a pandas dataframe named <code>firstperiod</code> and a column named <code>megaball</code>. The range of the values in <code>megaball</code> are from 1 to 25, and this line of code:</p> <pre><code>print firstperiod.megaball.value_counts().sort_index() </code></pre> <p>gives me this, which is what I want to ...
<p>That's because the "hist" plot is not just plotting data, but actually first estimating the empirical distribution of the raw data and then plotting the result. That is, "hist" is going to bin the data, count the instances per bin and plot that, so there is no need of doing the <code>value_counts()</code> ourselves....
python|pandas|matplotlib|histogram|bar-chart
3
355,419
30,385,868
Populating Lists or Vectors dynamically
<p>Using Python 3.4 and numpy</p> <p>Hey all, Spent about an hour looking, and not sure if this is possible. </p> <p>I am creating a dynamic model with 1000 iterations. I can write a transition function from state 1 to state 2, state 2 to state 3, etc.</p> <p>After I have the 1000 iteration I am using np.arange to f...
<p>Just use Numpy arrays indexing to store the data of your dynamic model,</p> <pre><code>import numpy as np dtype = 'float128' abs_tolerance = 1.0 y = np.arange(0.001, 2, 0.02).astype(dtype) N = y.shape[0] x = np.zeros(N, dtype=dtype) z = np.zeros(N, dtype=dtype) x[0] = 2 z[0] = 1 # initialize the first step for...
python|numpy
1
355,420
30,568,304
How to expand the data based on the single column in python(transpose)?
<p>I have a dataset like below and i need all the different weights for each category in single row and the count</p> <pre><code>Sample_data category weights 1 aa 3.2 2 aa 2.2 3 aa 4.2 4 bb 3.5 5 bb 4.5 6 aa 0.5 7 cc 0.6 8 bb 7.5 9 cc 6.6 10 d...
<p>I could probably shorten this but the following works:</p> <pre><code>In [51]: cat = df.groupby('category')['weights'].agg({'count':'count', 'weight_cat':lambda x: list(x)}).reset_index() cat Out[51]: category count weight_cat 0 aa 5 [3.2, 2.2, 4.2, 0.5, 3.3] 1 bb 4 ...
python|pandas
2
355,421
30,596,041
Scikit-learn labeled dataset creation from segmented time series
<h2>INTRO</h2> <p>I have a Pandas DataFrame that represents a <strong>segmented</strong> time series of different users (i.e., user1 &amp; user2). I want to train a scikit-learn classifier with the mentioned DataFrames, but I can't understand the shape of the scikit-learn dataset that I must create. Since my series ar...
<p>This is not trivial and there might be several way of formulating the problem for consumption by a ML algorithm. You should try them all and find how you get the best results.</p> <p>As you already found you need two things, a matrix X of shape <code>n_samples * n_features</code> and a column vector <code>y</code> ...
python|pandas|dataset|scikit-learn|classification
2
355,422
30,697,974
numpy adaptive threshold formula
<p>I'm trying to compute a threshold value based on a grayscale image (numpy 2D array with point values between 0 and 255).</p> <p>The formula is the following :</p> <p><a href="https://i.stack.imgur.com/DJ6ih.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DJ6ih.png" alt="equation"></a><br> <sub>(...
<p>Well the average value for all the cells in your matrix is:</p> <pre><code>avg = np.sum(sMap) / (w * h) </code></pre> <p>And in the extreme case, all cells are equal to 255, such that</p> <pre><code>avg = 255 </code></pre> <p>For example</p> <pre><code>In [8]: M = 255 * np.ones(4).reshape((2,2)) In [12]: M Out...
python|numpy
1
355,423
30,684,364
Python variable scope approach
<p>I currently have this python code (I'm using Apache Spark, but pretty sure that it doesn't matter for this question).</p> <pre><code>import numpy as np import pandas as pd from sklearn import feature_extraction from sklearn import tree from pyspark import SparkConf, SparkContext ## Module Constants APP_NAME = "My ...
<p>You can use the variable df in your main() (or any other function) and it will work just fine but if you try to assign value to it in a function (like you are doing in main() under #train data), it will give the unboundlocalerror exception. It will consider that variable as local variable and will therefore throw th...
python|pandas|apache-spark
1
355,424
26,726,950
Summation of every row, column and diagonal in a 3x3 matrix numpy
<p>My assignment is Tic-Tac_Toe using pygame and numpy. I Have almost all of the program done. I just need help understanding how to find if a winner is found. I winner is found if the summation of ANY row, column, or diagonal is equal to 3. </p> <p>I have two 3x3 matrices filled with 0's. Let's call them xPlayer and ...
<p>To index a matrix in numpy, just use the notation A[y,x] to reference row y and column x of matrix A. If you would like to select multiple values from a matrix at once, you can use standard python list slicing. For example, to select the leftmost column of A you would use A[:,0]. </p> <p>In your case, to find the s...
python|numpy|matrix|indexing|pygame
2
355,425
26,571,085
ploting subplot in matplotlib with pandas issue
<p>i am try to plot subplot in matplotlib with pandas but there are issue i am facing. when i am plot subplot not show the date of stock...there is my program</p> <pre><code>import pandas as pd import datetime import matplotlib.pyplot as plt import pandas.io.data df = pd.io.data.get_data_yahoo('goog', start=datetime...
<p>When you're calling <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot" rel="nofollow">matplotlib's plot()</a>, you are only giving it one array (e.g. df['Close'] in the first case). When there's only one array, matplotlib doesn't know what to use for the x axis data, so it just uses the index...
python|matplotlib|pandas
1
355,426
26,879,295
Using pandas pd.cut to generate a categorical variable with statsmodels
<p>I have tried to use pd.cut to create a categorical variable from a continuous variable. I'd like to use this in a subsequent statsmodel defined regression including this dummy variable. When I create a categorical variable created in this way, I get an error </p> <pre><code>TypeError: data type not understood. ...
<p>I'm not sure exactly where statsmodels is at in terms of including support for the new <code>Categorical</code> type in pandas. For the moment, you may have to convert the categorical back into an object type for it to work (please check that the resulting ols fit is sensible, I don't know the full details of what y...
python|pandas|statsmodels|categorical-data
3
355,427
26,500,435
Glitch in Pandas? Cannot overwrite value
<p>So I tried running a code I had developed previously, which has run numerous times nicely using pandas.</p> <p>My dataframe has a custom index (with unique string values as the index, representing a unique identifier, in this case, individual proteins), and file names as the columns. I then use an iterative procedu...
<p>Try: <code>df.ix[my_filename,my_protein] = value</code></p> <p>The reason for this (from my understanding) is that df['x']['y'] returns a copy of the data frame. So you ARE changing a value, but you're changing the value of a copy, that's not placed back into it.</p> <p>Edit: DSM notes, <code>.loc</code> and <code...
python|pandas|protein-database
4
355,428
39,251,485
Error with Protobuf while compiling Tensorflow
<p>I am currently trying use Tensorflow's shared libraries in a non-bazel project. </p> <p>So I built the .so file using: </p> <blockquote> <p>bazel build //tensorflow:libtensorflow.so</p> </blockquote> <p>Then I loaded the dependencies as described <a href="https://github.com/tensorflow/tensorflow/tree/master/ten...
<p>I think the problem is resolved as described here: <a href="https://groups.google.com/a/tensorflow.org/forum/#!msg/discuss/CtrurAAnglI/Mu9JHr6kAQAJ" rel="nofollow">Google Groups discussion</a></p> <p>Just add a new CFLAG:</p> <pre><code>-DPROTOBUF_DEPRECATED_ATTR="" </code></pre>
c++|makefile|tensorflow
1
355,429
39,125,819
sklearn and Tensorflow with dual CPU machine
<p>I am thinking about building a dual-CPU machine for machine learning. I already have a fast GPU in my current rig but I am limited to 32GB of DDR3, I have an i7-4790k and I am planning to upgrade to dual E5 2683 v3's. </p> <p>I need CPU computing power for sklearn and grid search. Does Sklearn work on 2 cpu's the s...
<p>From what I read even if you add an instruction like</p> <pre><code>with tf.Session() as sess: with tf.device("/cpu:0"): ... </code></pre> <p>It treats it as a recommendation and might use the GPU when it sees fit. I guess it might use the other CPU</p>
scikit-learn|tensorflow|cpu
0
355,430
39,067,839
Rename pandas column values from unstacked pivot table
<p>I have pandas pivot table <code>merge2</code> that looks like:</p> <pre><code> Site TripDate Volume Early_Vol Percent_Vol 0 024l 2004-12-02 1117.134948 1117.134948 0.000000 1 024l 2005-05-07 390.980708 1117.134948 -0.650015 2 024l 2006-10-07 321.110175 1117.134948 -0.712559 3 024...
<p>try this:</p> <pre><code>t.columns = t.columns.droplevel() </code></pre>
python|pandas|rename
1
355,431
39,111,373
Tensorflow: chaining tf.gather() produces IndexedSlices warning
<p>I'm running into an issue where chaining <code>tf.gather()</code> indexing produces the following warning:</p> <pre><code>/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/gradients.py:90: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of ...
<p>The gradient <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/array_grad.py#L277" rel="noreferrer">function</a> of the <code>tf.gather</code> operation returns <code>IndexedSlices</code> typed value. In your program, the input the second <code>tf.gather</code> is the result of a <c...
python|neural-network|tensorflow
9
355,432
39,016,405
Pandas dataframe If else with logical AND involving two columns
<p>How to add logical <code>AND</code> in a control statement involving two columns of a pandas dataframe i.e.</p> <p>This works:</p> <pre><code>def getContinent(row): if row['Location'] in ['US','Canada']: val = 'North America' elif row['Location'] in['UK', 'Germany']: val = 'Europe' else...
<p>You need use <code>and</code> instead <code>&amp;</code>:</p> <pre><code>df = pd.DataFrame({'Sales': {0: 400, 1: 20, 2: 300}, 'Location': {0: 'US', 1: 'UK', 2: 'Slovakia'}}) print (df) Location Sales 0 US 400 1 UK 20 2 Slovakia 300 def getContinent(row): if row...
python|pandas|if-statement|dataframe|apply
4
355,433
39,055,530
Is searchsorted faster than get_loc to find label location in a DataFrame Index?
<p>I need to find the integer location for a label in a Pandas index. I know I can use get_loc method, but then I discovered searchsorted. Just wondering if I should use the latter for speed improvement, as I need to search for thousands of labels.</p>
<p>It will depend on your usecase. using @ayhan's example.</p> <p>With <code>get_loc</code> there is a big upfront cost of creating the hash table on the first lookup.</p> <pre><code>In [22]: idx = pd.Index(['R{0:07d}'.format(i) for i in range(10**7)]) In [23]: to_search = np.random.choice(idx, 10**5, replace=False) ...
python|pandas
6
355,434
39,317,373
' | ' operator between python set objects
<p>Recently while making changes to a python module someone else wrote which does some processing on Pandas dataframe I came across a line of code which looks like this :</p> <p><code> indices_invalid_entries = \ list(set(indices_invalid_entries) | set(list(df[pd.isnull(df[i])].index))) </code></p> <p>where indices_i...
<p>As explained in the <a href="https://docs.python.org/2/library/sets.html" rel="noreferrer">documentation</a>, the | operator is the <strong>union operator</strong>.</p> <p>So as you mentioned in you answer, </p> <pre><code>indices_invalid_entries &lt;-- union(indices_invalid_entries,df[pd.isnull(df[i])].index) </c...
python|pandas|numpy
5
355,435
39,052,266
groupby python TypeError: unorderable types: tuple() < str()
<p>I initially wrote some code in python 2.7, but now I switched to python 3.5. I want to aggregate numeric data from a couple of columns and grouping by the rest of them or at least one.</p> <p>Here's my initial dataframe "testdf":</p> <pre><code>testdf PROD_TAG BRAND Market ('VAL', 'Per1') ('VAL',...
<p>I think you need to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow"><code>groupby.agg</code></a> and pass a function to aggregate the sum of each group as shown:</p> <pre><code>df = pd.DataFrame({'PROD_TAG':["P_1", "P_2", "P_3", "P_3",...
python-3.x|pandas
2
355,436
39,303,378
Tensorflow: Ran out of memory trying to allocate 1.5KiB
<p>I am running tensorflow in a loop with 300 random structures to find a good network structure. After the first epoch on the data are finished, I remove the worst 10% of them and start the second epoch on the networks. But, it fails in iteration ~350. I am running it on Tesla K80 with 11.25 GiB of memory. I also ha...
<p>I cleared the utilized GPU memory by deleting the the session objects for every new network and it works.</p>
memory|tensorflow
0
355,437
19,682,521
sorting numpy structured and record arrays is very slow
<p>it looks like sorting numpy structured and record arrays by a single column is much slower than doing a sort on a similar standalone array: </p> <pre><code>In [111]: a = np.random.rand(1e4) In [112]: b = np.random.rand(1e4) In [113]: rec = np.rec.fromarrays([a,b]) In [114]: timeit rec.argsort(order='f0') 100 loo...
<p>What´s slowing you is the use of <code>order</code>, not the fact that you have a record array. If you want to sort by a single field, do it like this:</p> <pre><code>In [12]: %timeit np.argsort(rec['f0']) 1000 loops, best of 3: 829 us per loop </code></pre> <p>Once <code>order</code> is used, performance goes sou...
python|arrays|sorting|numpy
4
355,438
19,572,560
Numpy's dtype conversion algorithm
<p>How does numpy scale values, when you convert an array from a float dtype to an integer dtype, if you have an array with a max value higher than what the integer type can hold?</p> <pre><code>In [9]: data_array.dtype Out[9]: dtype('&lt;f4') In [11]: data_array.max() Out[11]: 32767.0 In [16]: test = np.asarray(dat...
<p>They're not the same element of the array.</p> <p>Numpy converts from floating to integer types by converting to int and then truncating the binary representation, so 32767.0 will convert to the integer 32767 (0x7fff) and then to 0xff, which is -1 in int8.</p> <p>The 127 is coming from another array element whose ...
python|numpy|type-conversion
3
355,439
19,488,930
Plot lines in different colors from color dictionary in Python
<p>I'm trying to plot the path of 15 different storms on a map in 15 different colors. The color of the path should depend on the name of the storm. For example if the storm's name is AUDREY, the color of the storm's path should be red on the map. Could some please help/point me in the right direction?</p> <p>Here's t...
<p>You're accessing the dictionary entries incorrectly. First off you do this <code>names = list(data.Name)</code>. So names is of type <code>lists</code>. Then you call dictionary like this: <code>color_dict[names]</code>. The problem is not setting the colour but how you try to access the dictionary (<code>list</code...
python|matplotlib|pandas|matplotlib-basemap
1
355,440
19,549,634
Find where a NumPy array is equal to any value in a list of values
<p>I have an array of integers and want to find where that array is equal to any value in a list of multiple values.</p> <p>This can easily be done by treating each value individually, or by using multiple "or" statements in a loop, but I feel like there must be a better/faster way to do it. I'm actually dealing with ...
<p>The function <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html" rel="noreferrer">numpy.in1d</a> seems to do what you want. The only problems is that it only works on 1d arrays, so you should use it like this:</p> <pre><code>In [9]: np.in1d(fake, [0,2,6,8]).reshape(fake.shape) Out[9]: arr...
python|arrays|numpy
17
355,441
19,835,033
How to get mean of each list inside the list avoiding certain value?
<p>How to calculate mean of values of each list separately inside the list avoiding a special value (-999)?</p> <pre><code>A = [[4,5,7,8,-999],[3,8,5,7,-999]] M = [sum(x)/len(x) for x in [y for y in A if y!= -999] print (M) </code></pre> <p>Any idea ???</p> <p>For best speed: can someone correct the following code? ...
<pre><code>A = [[4,5,7,8,-999],[3,8,5,7,-999]] M = [sum(z)/float(len(z)) for z in [[x for x in y if x != -999] for y in A]] print M </code></pre> <p><strong>Output</strong></p> <pre><code>[6.0, 5.75] </code></pre>
python|numpy
3
355,442
19,681,703
Average time for datetime list
<p>Looking for fastest solution of time averaging problem.</p> <p>I've got a list of datetime objects. Need to find average value of time (excluding year, month, day). Here is what I got so far:</p> <pre><code>import datetime as dtm def avg_time(times): avg = 0 for elem in times: avg += elem.second + ...
<p>Here's a short and sweet solution (perhaps not the fastest though). It takes the difference between each date in the date list and some arbitrary reference date (returning a datetime.timedelta), and then sums these differences and averages them. Then it adds back in the original reference date. </p> <pre class="lan...
python|datetime|pandas|average
8
355,443
19,312,796
Add and Subtract multiple element of numpy array
<p>Hi I have a python code as: </p> <pre><code>import numpy as np a = np.array([[1,2,3],[4,5,6],[7,8,9]]) b = a[0,1]+a[2,2]-a[1,1] &gt;&gt;&gt; b &gt;&gt;&gt; 6 </code></pre> <p>Is there any other faster way to add/subtract a list of specific elements of an array?</p>
<p>If you simply want to retrieve the values in an array from a list of indices, and sum them, you can do:</p> <pre><code>import numpy as np a = np.array([[1,2,3],[4,5,6],[7,8,9]]) ind = [[0,1],[2,2],[1,1]] values = a[zip(*ind)] b = values.sum() # b = 2+9+5 = 16 </code></pre> <p>Note that I set indices <code>ind</cod...
python|numpy
2
355,444
19,405,508
Extracting data from Pandas dataframe as dataframe
<p>One of the biggest problems I have experienced in Python's Pandas is the continual defaulting to pandas.core.series.Series type. e.g.</p> <pre><code>import numpy as np import pandas as pd a = pd.DataFrame( np.random.randn(5,5),columns=list('ABCDE') ) b = a.mean(axis=0) &gt;&gt;&gt; b A 0.399677 B 0...
<p>You can just construct a DataFrame from the series easily like so:</p> <pre><code>c = DataFrame(a.mean(axis=0), columns=['mean']) c Out[91]: mean A -0.210582 B -0.742551 C 0.347408 D 0.276034 E 0.399468 </code></pre> <p>Still I don't see what this really achieves for you that is better than the original...
python|pandas
2
355,445
13,032,819
Python - interpolating/pcolor unevenly spaced numpy matrix
<p>I currently have a a roughly 100x120 2d numpy matrix. The indices refer to "coordinates" and the value in the matrix is the "height" I'm trying to plot this data using pcolor similar to the "Two dimensional spline representation" shown here:</p> <p><a href="http://docs.scipy.org/doc/scipy-0.7.x/reference/tutorial...
<p>What's the problem? You just need to extract the indexes of the cells with values and pass those to the interpolate function with the 'height' values. There's some code that does this below.</p> <pre><code>import numpy as np from numpy import nan from scipy import interpolate import matplotlib.pyplot as plt a = np...
python|numpy|matplotlib|scipy|mayavi
4
355,446
12,961,279
Numpy standard deviation under a mask
<p>How do I take the standard deviation <em>under a mask</em> along a specific axis in a numpy array?</p> <pre><code>data = array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]]) M = array([[0, 1, 0,...
<p>You can use a numpy <a href="http://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html" rel="nofollow">masked array</a>:</p> <pre><code>In [19]: from numpy import ma In [20]: data Out[20]: array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], ...
python|numpy
5
355,447
13,142,245
How to define atom for Pytables EArray creation
<p>Trying to create a Pytables EArray on the run based on one column from a numpy recarray. This seems to work if I am using createArray as I can simply pass it the numpy array extracted from the recarray. However, for the createEArray I need to define the atom - which is causing problems </p> <p>In the example MyR...
<p>I believe using the function:</p> <pre><code>tables.Atom.from_dtype(afieldtype, dflt=-9999) </code></pre> <p>will allow you to create an atom without going the subroutine route. The shape is contained in the dtype "afieldtype" (eg. <code>dtype([('col1', '&lt;f8', (10,))])</code>)</p>
python|numpy|pytables
1
355,448
13,003,706
How do I turn this into a numpy matrix?
<p>How do I turn the array <code>a = [[[[1, 2, 3, 4], [5, 6, 7, 8]], [[9, 10, 11, 12], [13, 14, 15, 16]]]]</code> into a numpy matrix of the form </p> <pre><code>[[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]] </code></pre> <p>? I have tried <code>np.bmat(a)</code> to no avail. When I do that, I get a 2x6 matrix....
<p>Use <code>np.array</code> to construct the array, then <code>reshape</code> to mold it into the right shape:</p> <pre><code>&gt;&gt;&gt; np.array([[[[1, 2, 3, 4], [5, 6, 7, 8]], [[9, 10, 11, 12], [13, 14, 15, 16]]]]).reshape((4,4)) array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [1...
python|matrix|numpy
3
355,449
13,030,488
Using pandas to plot barplots with error bars
<p>I'm trying to generate bar plots from a DataFrame like this:</p> <pre><code> Pre Post Measure1 0.4 1.9 </code></pre> <p>These values are median values I calculated from elsewhere, and I have also their variance and standard deviation (and standard error, too). I would like to plot the results a...
<p>What is your data shape?</p> <p>For an n-by-1 data vector, you need a n-by-2 error vector (positive error and negative error): </p> <pre class="lang-python prettyprint-override"><code>import pandas as pd import matplotlib.pyplot as plt df2 = pd.DataFrame([0.4, 1.9]) df2.plot(kind='bar', yerr=[[0.1, 3.0], [3.0, 0...
python|matplotlib|pandas
8
355,450
28,888,725
equivalent of ave in pandas
<p>My post is similar to another SO post: <a href="https://stackoverflow.com/questions/28318398/equivalent-of-r-function-ave-in-python-pandas">equivalent-of-r-function-ave-in-python-pandas</a>, but I am getting an error. </p> <p>Suppose: </p> <p>I have a dataframe <code>df</code>:</p> <pre><code> A B C ...
<p>I think <code>transform</code> is the right approach, but you need to grab the column directly:</p> <pre><code>&gt;&gt;&gt; df["E"] = df.groupby("A")["C"].transform("mean") &gt;&gt;&gt; df A B C D E 0 foo one -2.0 0.5 -0.7 1 bar one -1.5 -1.5 0.0 2 foo two -0.5 -0.8 -0.7 3 bar thr...
python|python-3.x|pandas
2
355,451
28,911,726
Is there a way to save image data as a list/array in Python 2.7 or numpy?
<p>I want to save image data as a list/array in memory so I can read it somewhere else. The default scripting language is Python 2.7 with numpy added so I have to do can be done with those.</p>
<p>Creates a list of tuples</p> <pre><code>from PIL import Image img = Image.open('ubuntu.jpg') imglist = list(img.getdata()) print imglist </code></pre> <p>For <code>numpy</code></p> <pre><code>import numpy print numpy.array(img.getdata(), numpy.uint8).reshape(img.size[1], img.size[0], 3) </code></pre>
python|image|list|python-2.7|numpy
1
355,452
28,939,915
List comprehension with cython
<p>I am trying to speed up my Python code with Cython, and so far it is working great. I am having however one single problem: dealing with lists.</p> <p>Using <code>cython -a myscript.pyx</code>, I can see that the only parts of my code that call Python routines are when I'm dealing with lists.</p> <p>For example, I...
<p>Manipulating lists in Cython is inherently more expensive than using numpy arrays or typed memoryviews, since the former necessitates making Python API calls, whereas with the latter it's possible to directly address the underlying C memory buffers. The best way to avoid this overhead is to simply not use lists wher...
python-2.7|numpy|cython
4
355,453
29,260,404
create a multidimensional random matrix in spark
<p>With the python API of Spark I am able to quickly create an RDD vector with random normal number and perform a calculation with the following code: </p> <pre><code>from pyspark.mllib.random import RandomRDDs RandomRDDs.uniformRDD(sc, 1000000L, 10).sum() </code></pre> <p>where <code>sc</code> is an available SparkC...
<p>Spark evolved a bit since this question was asked and Spark will probably have better support still in the future. </p> <p>In the meantime you can be a bit creative with the <code>.zip</code> method of RDD's as well as DataFrames to get close to what numpy can do. It is a bit more verbose, but it works. </p> <pre>...
python|numpy|multidimensional-array|apache-spark
1
355,454
29,257,995
Attach label information when averaging predictions across users
<p>I have 3 datasets that contains predictions, usernames and labels, respectively. Using the code below I average the predictions across users (based on help from Jaime and ali_m from <a href="https://stackoverflow.com/questions/29243982/average-using-grouping-value-in-another-vector-numpy-python">Average using groupi...
<p>You can do this by passing <code>return_index=True</code> to <code>np.unique</code>. From <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow noreferrer">the docs</a>:</p> <blockquote> <p>return_index : bool, optional</p> <p>If True, also return the indices of <em>ar</em> th...
python|numpy
1
355,455
28,961,246
numpy.bincount and numpy.argmax function pseudocodes
<p>I need to make a code generation from Python to Matlab, and I'm new to Python.</p> <p>Although there are some websites which give definitions of what <code>numpy.bincount</code> and what <code>numpy.argmax</code> are, they don't give a simple example which is understandable for new beginners.</p> <p>There is such ...
<p><code>numpy.argmax(numpy.bincount(dlabel))</code> returns the most common value found in <code>dlabel</code>.</p> <p>To break it down, <code>np.bincount()</code> will return the count of each value in an array of non-negative integers and return an array with the count at the appropriate index (Python arrays are in...
python|arrays|matlab|numpy
2
355,456
29,080,348
Using numpy arrays with lpsolve?
<p>In the docs, it says you can use numpy arrays:</p> <blockquote> <p>numpy package</p> <p>In the above section Maximum usage of matrices with lpsolve the package numpy was already mentioned. See <a href="http://numpy.scipy.org/" rel="nofollow">http://numpy.scipy.org/</a> for a brief overview. This package ...
<p>You can use PyLPSolve if you are having trouble with lpsolve. It is a wrapper for lpsolve that allowed me to use numpy arrays.</p> <p><a href="http://www.stat.washington.edu/~hoytak/code/pylpsolve/" rel="nofollow">http://www.stat.washington.edu/~hoytak/code/pylpsolve/</a></p>
python|numpy|lpsolve
0
355,457
29,122,417
Combination of elements with numpy.array and scalars
<p>I have a <code>tuple</code> which contains a <code>numpy.array</code> of arbitrary length along with scalars. Something like this:</p> <pre><code>(array([ 31.5, 31.6, 31.7, 31.8, 31.9, 32. , 32.1, 32.2, 32.3, 32.4, 32.5, 32.6, 32.7, 32.8, 32.9, 33. , 33.1, 33.2, 33.3, 33.4, 33.5, 33.6, 3...
<p>If you don't know the position of the <code>array</code>, you'll just have to find it. I would simply code it as follows:</p> <pre><code>from numpy import array, ndarray a = (array([ 31.5, 31.6, 31.7, 31.8, 31.9, 32. , 32.1, 32.2, 32.3, 32.4, 32.5, 32.6, 32.7, 32.8, 32.9, 33. , 33.1, 33.2, 3...
python|numpy
2
355,458
29,158,760
image stack population is slow in numpy
<p>I am reading stack of separate tiff's into single 3D array via numpy/python. When files are just read and plugged into some variable, speed scales linearly with number of files, for example, loading 100 files takes 0.2s, loading 1000 files takes 2.46s and so on.</p> <p>However, when I try to create a 3D stack out o...
<p>You can solve this problem by changing the order of your indexing, making the image index first. Like this:</p> <pre><code>i_max = 1000 sx, sy = 1000,1000 t = time.time() for i in range(0,i_max): im = np.ones((sx,sy)) if i&gt;0: #stack[:,:,i] = im stack[i,:,:] = im else: #stack ...
python|image|numpy
4
355,459
33,578,747
Using weight for Random forest of sklearn
<p>I want to use weight for RandomForestClassifier of sklearn. In fact, I have an imbalanced dataset. class 1 with 600, class2 90, class3 60 and class4 96 sample data!!!</p> <p>I want to use weight to make the dataset balanced. This is my code that generated an error.</p> <pre><code>cfr = RandomForestClassifier(n_est...
<p>The first two arguments of </p> <pre><code>cfr = RandomForestClassifier(n_estimators=100,n_jobs =5,{1:1,2:3,3:3,4:3}) </code></pre> <p>are keyword arguments, where you are specifying the arguments out of order by using the syntax "arg=value". As you move from left to right in the argument list, once you start giv...
python|numpy|import|machine-learning|scikit-learn
0
355,460
33,658,423
Weight for BaggingClassifier in python
<p>I want to use different weight for BaggingClassifier in sklearn. For Type with value 1,2,3 and for i need weight 1, 30, 30 and 30 respectedly. <a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.BaggingClassifier.html#sklearn.ensemble.BaggingClassifier.fit" rel="nofollow">http://scikit-learn.o...
<p>The shape of <code>sample_weight</code> needs to be <a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.BaggingClassifier.html#sklearn.ensemble.BaggingClassifier.fit" rel="nofollow">equal to the number of items</a> in <code>XTrain</code></p> <pre><code>sample_weight : array-like, shape = [n_s...
python|python-2.7|numpy|import|scikit-learn
0
355,461
33,703,923
Limit on Number of Columns Pandas Will Print in Python
<p>If I have a list of headers and I am using pandas:</p> <pre><code>[u'GAME_ID', u'TEAM_ID', u'TEAM_ABBREVIATION', u'TEAM_CITY', u'PLAYER_ID', u'PLAYER_NAME', u'START_POSITION', u'COMMENT', u'MIN', u'SPD', u'DIST', u'ORBC', u'DRBC', u'RBC', u'TCHS', u'SAST', u'FTAST', u'PASS', u'AST', u'CFGM', u'CFGA', u'CFG_PCT', u'...
<p>It's done on purpose, more specifically through pandas' <a href="http://pandas.pydata.org/pandas-docs/stable/options.html" rel="nofollow">Options and Settings</a>.</p> <p>You can change it through <code>display.max_columns</code> which is set by default to <code>20</code>, as well as <code>display.max_colwidth</cod...
python|list|pandas
1
355,462
33,833,901
TypeError: Unsupported type <type 'list'> in write()
<p>I am trying to dump a bunch of <code>dicts</code> to an <code>.xlsx</code> file by means of the following lines:</p> <pre><code>H=0.5 #Used to name the xlsx file fail_thre=0.2 #Used to name the xlsx file dict_list=[dict1,dict2,dict3] #The list of dictionaries to be dumped myindex=['event 1','event 2','event 3'] #Us...
<p>Your <code>mydf</code> dataframe has elements of type <code>list</code> in the dataframe cells. It is likely due to how you built <code>stats_matrix</code>. See the <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/dsintro.html#dataframe" rel="nofollow">the pandas docs</a> for the appropriate ways to ca...
python|excel|pandas|dataframe|typeerror
3
355,463
33,964,825
Change cell values in numpy 2D array to match a number
<pre><code>import numpy as np np.random.random((5,5)) array([[ 0.26045197, 0.66184973, 0.79957904, 0.82613958, 0.39644677], [ 0.09284838, 0.59098542, 0.13045167, 0.06170584, 0.01265676], [ 0.16456109, 0.87820099, 0.79891448, 0.02966868, 0.27810629], [ 0.03037986, 0.31481138, 0.064770...
<p>Numpy's index magic is fun to program with:</p> <pre><code>import numpy as np aa = np.random.random((5, 5)) m = np.mean(aa) d = 0.8 - m # value to add bb = aa + d if d &gt; 0: # Modify values != 1 ii = aa + d &gt; 1 d2 = np.sum(bb[ii] - 1) bb[ii] = 1 bb[~ii] = bb[~ii] + d2/np.sum(~ii) elif d &l...
python|numpy
2
355,464
33,839,314
`LinAlgError: SVD did not converge` when attempting to rescale a 4D array using `skimage.transform.rescale`
<p>I want to rescale a 4D array of MNIST data by a factor of 0.5. I get an error using <code>skimage.transform.rescale</code>:</p> <pre><code>LinAlgError: SVD did not converge </code></pre> <p>I have a feeling it might be related to image dimensions but the documentation doesn't mention image dimensions.</p> <pre><c...
<p>From <a href="http://scikit-image.org/docs/dev/api/skimage.transform.html#rescale" rel="nofollow">the documentation</a>:</p> <blockquote> <p><strong><code>skimage.transform.rescale(image, scale, order=1, mode='constant', cval=0, clip=True, preserve_range=False)</code><a href="http://github.com/scikit-image/scikit...
python|image|numpy|scikit-image|rescale
1
355,465
33,773,271
Graph visualisaton is not showing in tensorboard for seq2seq model
<p>I build a seq2seq model using the seq2seq.py library provided with tensorflow. Before training anything I wanted to visualize the graph network of my untrained model in tensorboard, but it does not want to display this.</p> <p>Below a minimal example to reproduce my problem. Anybody an idea why this does not work?...
<p>It looks like this might be related to a bug where the graph visualization does not work in the firefox browser. Try using chrome or safari if possible.</p> <p><a href="https://github.com/tensorflow/tensorflow/issues/650" rel="nofollow">https://github.com/tensorflow/tensorflow/issues/650</a></p>
neural-network|deep-learning|tensorflow|tensorboard
3
355,466
33,908,811
Some elements in the result of braycurtis dissimilarity matrix(numpy array) contains 'nan'
<p>I calculated braycurtis dissimilarity matrix for the below matrix. Rows are communities ans columns are species</p> <pre><code>[[ 0 0 0 0] [ 13 110 0 0] [ 6 3 0 0] [ 0 5 0 0] [ 0 128 0 0] [ 0 0 0 0] [ 11 76 11 0] [ 8 29 3 0] [ 0 58 5 0] [ 1 3 0 0]...
<p>Yes, the output is correct.</p> <p>It is easy to verify yourself: the <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html#scipy.spatial.distance.pdist" rel="nofollow">documentation on pdist</a> has the actual formulae for the Bray-Curtis distance:</p> <blockquote> <p>d(...
python-3.x|numpy|scipy
1
355,467
33,709,489
Python3 comparing row by row values from csv
<p>I'm using python3.5</p> <p>After importing my csv file I want these operations: IN:</p> <pre><code>ULIM LLIM High Low CLO $RNG U-OCT MID L-OCT ------------------------------------------- 12785 125300 127840 127500 127475 1275 127532 126575 125618 </code></pre> <p>OUT:</p> <pre><code>Dir ULIM LLIM High Low CLO $...
<p>You can iterate each line and check from the retrieved dictionary like this:</p> <pre><code>import csv output = open('csv_file_out.txt', 'w') with open('csv_file.txt') as csvfile: reader = csv.DictReader(csvfile, delimiter=' ') writer = csv.writer(output, delimiter=' ') T = False S = 'S' for i,...
python|csv|python-3.x|pandas
0
355,468
33,934,255
Applying a function for all pairwise rows in two matrices under Numpy
<p>I have two matrices:</p> <pre><code>import numpy as np def create(n): M = array([[ 0.33840224, 0.25420152, 0.40739624], [ 0.35087337, 0.40939274, 0.23973389], [ 0.40168642, 0.29848413, 0.29982946], [ 0.17442095, 0.50982272, 0.31575633]]) return np.concat...
<p>You can extend <code>I</code>'s dimensions to a <code>3D</code> array version at various places to bring in <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>powerful broadcasting</code></a> into play. We keep <code>A</code> as it is, because it's a huge array and we don't ...
python|arrays|numpy|matrix
2
355,469
33,673,687
EOFError: ran out of input. Getting this error when trying to pickle.loads from a socket
<p>I have a <code>numpy ndarray</code> that I'm trying to send via socket connection. When I try to load it on the server, using <code>pickle.loads</code> I get <code>EOFError: ran out of input</code>. </p> <h1>client.py</h1> <pre><code>import numpy as np import socket, pickle import struct HOST = "192.168.143.xxx" P...
<p><code>conn.recv(length)</code> does not necessarily read <code>length</code> bytes, if there are less than that number available. You need to loop until you have enough.</p> <p>See <a href="https://stackoverflow.com/q/7174927/243712">When does socket.recv(recv_size) return?</a></p> <pre><code>data = b'' l = length...
python|sockets|numpy|pickle
3
355,470
23,507,229
Set no title for pandas boxplot (groupby)
<p>When drawing a pandas boxplot, grouped by another column, pandas automatically adds a title to the plot, saying 'Boxplot grouped by....'. Is there a way to remove that? I tried using </p> <pre><code>suptitle('') </code></pre> <p>as per <a href="https://stackoverflow.com/questions/17984948/pandas-boxplot-of-one-col...
<p>Make sure your calling <code>suptitle('')</code> on the right figure.</p> <pre><code>In [23]: axes = df.boxplot(by='g') In [24]: fig = axes[0][0].get_figure() In [25]: fig.suptitle('') Out[25]: &lt;matplotlib.text.Text at 0x109496090&gt; </code></pre>
python|pandas|title|boxplot
37
355,471
23,727,408
How to avoid using "no data" in image stacking
<p>I am new in using python. My problem might seems easy but unfortunately I could not find a solution for it. I have a set of images in Geotiff format which are at the same size, their pixel values range between 0 to 5 and their non values are -9999. I would like to do kind of image stacking using Numpy and Gdal. I a...
<p><a href="http://docs.scipy.org/doc/numpy/reference/maskedarray.html" rel="nofollow">Masked arrays</a> are a good way to deal with missing or invalid values. Masked arrays have a <code>.data</code> attribute, which contains the numerical value for each element, and a <code>.mask</code> attribute that specifies which ...
python-2.7|image-processing|numpy|gdal
2
355,472
23,844,476
How to convert this string to datetime and date alone
<p>This question is far from unique, but i cannot find a way to convert the strings that are contained in this df column to datetime and date alone objects in order to use them as the index of my dataframe.</p> <p>How can i convert this string to datetime or date format to use it as an index on my df? </p> <p>The for...
<p>Use <code>to_datetime</code> to convert to a string to a datetime, you can pass a formatting string but in this case it seems to handle it fine, then if you wanted a date then call <code>apply</code> and use a lambda to call <code>.date()</code> on each datetime entry:</p> <pre><code>In [59]: df = pd.DataFrame({'D...
date|datetime|pandas
2
355,473
23,614,075
Fitting a curve to a set of data points for time series prediction
<p>I currently have a set of data points (hit counts), which are structured as a time series. The data is something like:</p> <pre><code>time hits 20 200 32 439 57 512 </code></pre> <p>How can I fit a curve to this data or find a formula so that I can predict points in the future? Ideally, I can answer ...
<p>As other people have said it is difficult to give an answer with so few information. </p> <p>I suggest you to define some new variable like time, time*time, time*time*time and to fit a LinearRegression model using this as input variable. </p> <p>I will start with these and then in case using something of more comp...
python|numpy|scipy|scikit-learn
1
355,474
22,764,021
Installation of Compatible version of Numpy and Scipy on Abaqus 6.13-2 with python 2.6.2
<p>Can anyone give inputs/clue/direction on installation of compatible version of numpy and scipy in abaqus python 2.6.2? I tried installing numpy-1.6.2, numpy-1.7.1 and numpy-1.8.1. But all gives an error of unable to find vcvarsall.bat. because it doesn't have a module named msvccomplier. based on the some of the an...
<p>What you should do is: install python 2.6.2 separately onto your system (it looks like you are using windows, right?), and then install scipy corresponding to python 2.6.2, and then copy the site-packages to the abaqus folder.</p> <p>Note that 1) you can't use matplotlib due to the tkinter problem; 2) the numpy is ...
python|numpy|scipy
0
355,475
22,671,192
Inverse of numpy's bincount function
<p>Given an array of integer counts <code>c</code>, how can I transform that into an array of integers <code>inds</code> such that <code>np.all(np.bincount(inds) == c)</code> is true?</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; c = np.array([1,3,2,2]) &gt;&gt;&gt; inverse_bincount(c) # &lt;-- what I need array(...
<p>using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html"><code>numpy.repeat</code></a> :</p> <pre><code>np.repeat(np.arange(c.size), c) </code></pre>
python|numpy
12
355,476
22,897,597
Read entire group in an HDF5 file using a pandas.HDFStore
<p>I have an HDF file like that:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; dataset.store ... &lt;class 'pandas.io.pytables.HDFStore'&gt; ... File path: ../data/data_experiments_01-02-03.h5 ... /exp01/user01 frame_table (typ-&gt;appendable,nrows-&gt;221,ncols-&gt;124,indexers-&gt;[index]) ......
<p>This is not implemented, though could be a nice feature. (and FYI I would not have it set by default in <code>.get(...)</code> because its not explicit enough (e.g. should it ALWAYS read ALL the tables, too much guessing), but could have an argument to control which sub-tables I suppose. If you are interested in imp...
python|pandas|hdfstore
4
355,477
22,514,896
error in using curve_fit function to sympy function
<p>I have a problem in using curve_fit function. The task is to solve symbolic a cubic equation and then to use this solution in fitting function.</p> <pre><code>import numpy as np import pylab import matplotlib.pyplot as plt from scipy.optimize import curve_fit from sympy import * from sympy.utilities.lambdify import...
<p>curve_fit() requires the objective function (your 'funct' or 'fit_funct') to have its first argument be an ndarray of variables. That is, you have to pack E1, E2, k1, and k2 into a single ndarray.</p>
python|numpy|curve-fitting|sympy|equation-solving
1
355,478
22,631,124
Integration of the tail of a Gaussian function with Scipy, giving zero instead of 8.19e-26
<p>I am trying to integrate a Gaussian function, the limits are way inside the Gaussian tail, so trying the integrate.quad gave me zero. Is there a way to integrate a Gaussian function that suppose to give extremely small answer?</p> <p>The function's integrand is:</p> <pre><code>sigma = 9.5e-5 integrand = lambda del...
<p>Let <code>F(x; s)</code> be the CDF of the normal (i.e. Gaussian) distribution with standard deviation <code>s</code>. You are computing <code>F(x1;s) - F(x0;s)</code>, where <code>x0 = 1e-3</code> and <code>x1 = 0.3</code>.</p> <p>This can be rewritten as <code>S(x0;s) - S(x1;s)</code> where <code>S(x;s) = 1 - F(...
python|python-2.7|numpy|scipy
3
355,479
22,720,349
Can I select rows based on group size with pandas? Or do I have to use SQL?
<p>With pandas I can do grouping using <code>df.groupby('product_name').size()</code>. But if I'm only interested rows whose "product_name" is unique, i.e. those records with groupby.size equal to one, how can I filter the df to see only such rows? In other words, can I perform filtering on a database using pandas, bas...
<p>I have found <code>transform</code> to be much more efficient than <code>filter</code> for very large dataframes:</p> <pre><code>row_group_sizes = ( df['product_name'] .groupby(df['product_name']) .transform('size') ) df[row_group_sizes==1] </code></pre> <p>Or, in one line:</p> <pre><code>df[df['prod...
python|pandas
2
355,480
22,817,415
How to install numpy for PyPy on Windows?
<p>I've just installed <a href="http://www.pypy.org/" rel="nofollow noreferrer">PyPy</a> on Windows and seen an approximately 10x speed improvement in some simulation code I'm running. I'd like to see similar on code using numpy, too. I'm not an experienced Python programmer however and I'm finding the <a href="http://...
<p>For the first option you should download pip from </p> <blockquote> <p><a href="https://sites.google.com/site/pydatalog/python/pip-for-windows" rel="nofollow">https://sites.google.com/site/pydatalog/python/pip-for-windows</a> </p> </blockquote> <p>After that you should add in enviroment variable PATH the path...
python|windows|numpy|pypy
1
355,481
15,047,944
np.savetxt from a created list error
<p>consider the code:</p> <pre><code>dd21 = [] a = [1, 2, 3, 4] for i in range(len(a)): for j in range(i+1, len(a)): dd21.append(a[i]-a[j]) r = (a[i] -a[j]) j = j + 1 data1=np.column_stack((i,j,r)) np.savetxt('lol.dat', data1) print i, j, r </code></pre> <p>output:</p>...
<p>To save multiple arrays into one file, you can open the file first and call <code>np.savetxt()</code> with the file object:</p> <pre><code>dd21 = [] a = [1, 2, 3, 4] with open("lol.dat", "w") as f: for i in range(len(a)): for j in range(i+1, len(a)): dd21.append(a[i]-a[j]) r = (a[...
numpy|python-2.7
1
355,482
14,969,552
Error when freezing pandas/NumPy 1.7.0 code with cx_Freeze
<p>I am trying to freeze a Python script with cx_Freeze. The script makes use of pandas. When I run the executable created by cx_Freeze, I get the following Traceback: </p> <pre><code>[...] File "C:\Python27\lib\site-packages\pandas\__init__.py", line 6, in &lt;module&gt; from . import hashtable, tslib, lib Fil...
<p>I just looked at the /numpy/core/<strong>init</strong>.py and noticed at the second last line:</p> <p>there is "del sys"</p> <p>if you comment out this line, it works as expected. I also noticed there was no "del sys" in numpy 1.6.2</p> <p>you may try to contact numpy to check why they need to do this.</p>
python|numpy|pandas|cx-freeze
5
355,483
15,149,868
Python (numpy): drop columns by index
<p>I've got a numpy array and would like to remove some columns based on index. Is there an in-built function for it or some elegant way for such an operation?</p> <p>Something like: </p> <pre><code>arr = [234, 235, 23, 6, 3, 6, 23] elim = [3, 5, 6] arr = arr.drop[elim] output: [234, 235, 23, 3] </code></pre>
<p>use <code>numpy.delete</code>, it will return a new array:</p> <pre><code>import numpy as np arr = np.array([234, 235, 23, 6, 3, 6, 23]) elim = [3, 5, 6] np.delete(arr, elim) </code></pre>
python|numpy
11
355,484
13,519,521
Elementwise mean of dot product in Python (numpy)
<p>I have two numpy matrixes (or sparse equivalents) like:</p> <pre><code>&gt;&gt;&gt; A = numpy.array([[1,0,2],[3,0,0],[4,5,0],[0,2,2]]) &gt;&gt;&gt; A array([[1, 0, 2], [3, 0, 0], [4, 5, 0], [0, 2, 2]]) &gt;&gt;&gt; B = numpy.array([[2,3],[3,4],[5,0]]) &gt;&gt;&gt; B array([[2, 3], [3, 4]...
<p>Why you need <code>replace_zeros_with_ones</code>? I delete this line and run your code and get the right result.</p> <p>You can do this by only one line if all the numbers are not negtaive:</p> <pre><code>np.dot(A, B)/np.dot(np.sign(A), np.sign(B)) </code></pre>
python|numpy|scipy
1
355,485
13,465,047
Dot product of ith row with ith column
<p>In NumPy:</p> <pre><code>A = np.array([[1,2,3],[4,5,6]]) array([[1, 3, 5], [2, 4, 6]]) B = np.array([[1,2],[3,4],[5,6]]) array([[1, 2], [3, 4], [5, 6]]) A.dot(B) array([[35, 44], [44, 56]]) </code></pre> <p>I only care about getting <code>A.dot(B).diagonal() = array([35, 56])</code></...
<p>This is just matrix multiplication for 2D arrays:</p> <pre><code>C[i, j] = sum(A[i, ] * B[, j]) </code></pre> <p>So since you just want the diagonal elements, looks like you're after</p> <pre><code>sum(A[i, ] * B[, i]) # for each i </code></pre> <p>So you could just use list comprehension:</p> <pre><code>[np.do...
numpy
6
355,486
29,671,726
Efficient way to Calculate h-index (impact/productivity of author publication) in pandas DataFrame
<p>I'm very new to pandas, but I've been reading about it and how much faster it is when dealing with big data.</p> <p>I managed to create a dataframe, and I now have a pandas dataframe that looks something like this:</p> <pre><code> 0 1 0 1 14 1 2 -1 2 3 1817 3 3 29 4 3 25 5 3 ...
<p>I renamed your columns to 'author' and 'citations' here, we can groupby the authors and then apply a lambda, here the lambda is comparing the number of citations against the value, this will generate a 1 or 0 if true, we can then sum this:</p> <pre><code>In [104]: df['h-index'] = df.groupby('author')['citations']....
python|pandas|python-2.7|dataframe
6
355,487
29,541,777
Python Pandas overlapping data with TimeGrouper
<p>I'm trying to efficiently divide long-term data into 8 intervals for each day. The intervals are 3 hours each, but the edges overlap:</p> <pre><code>00.00 - 03.00 03.00 - 06.00 06.00 - 09.00 09.00 - 12.00 12.00 - 15.00 15.00 - 18.00 18.00 - 21.00 21.00 - 24.00 </code></pre> <p>I tried to following:</p> <pre><code...
<p>This is a bit of a hack, but I think it probably has to be given that you are going to have duplicate timestamps by design (and want them in different groups). Note that this of course will only work with regularly spaced rows.</p> <p>First, just use advanced/fancy indexing to duplicate every third row:</p> <pre>...
python|numpy|data-structures|pandas
0
355,488
29,700,954
Pandas skipping x tick labels
<p>I have a plot with 15 axis labels and Pandas automatically defaults to showing every other category name. How do I get it to show ALL of the x-axis labels without skipping items?</p> <pre><code>rows = [] for x in range(0,14): rows.append(['a',14-x]) df = pd.DataFrame(rows) df = df.set_index(0) df.plot(xticks=...
<p>You can define the axes first, create your plot using the keyword <code>ax</code> and set the ticks and tick labels manually using <code>ax.set_xticks()</code> (<a href="http://matplotlib.org/api/axes_api.html" rel="noreferrer">http://matplotlib.org/api/axes_api.html</a>):</p> <pre><code>import matplotlib.pyplot as...
python|pandas|matplotlib
6
355,489
29,374,009
Matplotlib griddata fails
<p>I am trying to write a function which makes a contour plot from a text data file (or a numpy array) formatted as "x, y, z". However, when I try to use griddata to interpolate the data, I get a "type" error: </p> <pre><code> if not len(x)==len(y)==len(z): TypeError: object of type 'numpy.float64' has no len() </c...
<p>I suppose you are using an older version of matplotlib? Where are you importing your griddata from? Have a look at the griddate function in your matplotlib/mlab.py file and look whether there is a line similar to </p> <pre><code>if not len(x)==len(y)==len(z): raise TypeError("inputs x,y,z must all be 1D arrays ...
python|numpy|matplotlib
0
355,490
29,451,165
Backpropagation with Rectified Linear Units
<p>I have written some code to implement backpropagation in a deep neural network with the logistic activation function and softmax output.</p> <pre><code>def backprop_deep(node_values, targets, weight_matrices): delta_nodes = node_values[-1] - targets delta_weights = delta_nodes.T.dot(node_values[-2]) wei...
<p>Although I have determined the source of the problem, I'm going to leave this up in case it might be of benefit to someone else.</p> <p>The problem was that I did not adjust the scale of the initial weights when I changed activation functions. While logistic networks learn very well when node inputs are near zero ...
python|numpy|neural-network|backpropagation
5
355,491
29,729,185
Python cannot import DataFrame
<p>I am trying to use Pandas in Python to import and manipulate some csv file.</p> <p>my code is like:</p> <pre><code>import pandas as pd from pandas import dataframe data_df = pd.read_csv('highfrequency2.csv') print(data_df.columns) </code></pre> <p>But there is an error :</p> <pre><code>ImportError: cannot impo...
<p>You have to use it exactly with '<strong>DataFrame</strong>' this is really important to pay attention to the upper and lowercase characters</p> <pre><code>import pandas as pd data_df = pd.DataFrame('highfrequency2.csv') print(data_df.columns) </code></pre>
python|pandas
7
355,492
62,263,365
Get data where timestamp is 30th minute - pandas
<p>I have a sample dataframe,</p> <pre><code>id name value date time 1 box 4 2020-06-08 15:15:00 2 box 44 2020-06-08 15:30:00 3 box 42 2020-06-08 15:45:00 4 box 41 2020-06-08 16:00:00 5 car 55 2020-06-08 ...
<p>One idea is to create datetimes and compare them to the value of 30 minutes:</p> <pre><code>df = df[pd.to_datetime(df['time'].astype(str)).dt.minute.eq(30)] print (df) id name value date time 1 2 box 44 2020-06-08 15:30:00 5 6 car 33 2020-06-08 15:30:00 </code></pre>
pandas|dataframe
1
355,493
62,076,473
Get dataframe from confusing dictionary data structure
<p>I have a dictionary like on below :</p> <pre><code> {1: ds yhat yhat_lower yhat_upper 30 2015-08-09 49.908927 31.632462 66.742083 31 2015-08-16 49.750056 34.065527 67.069122 32 2015-08-23 49.591185 32.620258 67.403908 33 2015-08-30 49.432314 32.257891 67.541757 34 2015-09-0...
<p>Let us try <code>pd.concat</code> </p> <pre><code>yourdf=pd.concat(d).reset_index(level=0) </code></pre>
python|pandas|dictionary
0
355,494
62,202,317
How to count repeated label between given RFMin and RFMax
<p>I am reading the following CSV file that have three columns and multiple rows: </p> <pre><code>Notation RFMin RFMax AA100 1000 3333 BB200 3300 4500 </code></pre> <p>Currently my output file looks like this:</p> <pre><code> Notation RFRange Label AA100 1000 ...
<p>Try this, merge the 2 dataframes, convert label to list, add the range filter, groupby notation and concatenate all the Labels together into 1 list per notation and then use the <code>Counter</code> from <code>collections</code> to count each element in the list:</p> <pre><code>from collections import Counter df2[...
python|pandas
0
355,495
62,466,516
Add multiple index levels to existing pandas index
<p>I have a <code>df</code> with a regular datetime index. I need to add multiple index levels. What's a pythonic way to achieve this?</p> <pre><code>import numpy as np import pandas as pd idx = pd.date_range(start="2020-01-01", end="2020-01-10") vals = {"values": np.random.randint(low=1, high=100, size=10)} df = pd....
<p>Create new columns by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>DataFrame.assign</code></a>, append to existing index by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofo...
pandas|multi-index
2
355,496
62,158,872
How do I pivot over date in pandas?
<p>I have a df that looks like this</p> <pre><code>date lat long 1/2/12 30 30 2/2/12 31 12 2/2/12 30 29 2/2/12 30 30 3/2/12 31 21 3/2/12 31 10 3/2/12 nan nan .... 5/15/20 31 21 5/16/20 21 05 5/18/20 nan nan </code></pre> <p>I want to get a table that looks like the followi...
<p>Looks like a <code>crosstab</code>:</p> <pre><code>pd.crosstab([df['lat'],df['long']], df.date).reset_index() </code></pre> <p>Output:</p> <pre><code>date lat long 1/2/12 2/2/12 3/2/12 5/15/20 5/16/20 0 21.0 5.0 0 0 0 0 1 1 30.0 29.0 0 1 0 ...
python|pandas|pandas-groupby
0
355,497
62,175,337
How to fetch next 5 records based on given index in pandas Dataframe
<p>I want to fetch the next 5 records after the specific index.</p> <p>For example, this is my dataframe:</p> <pre><code> Id Name code 1 java 45 2 python 78 3 c 65 4 c++ 25 5 html 74 6 css 63 7 javascript 45 ...
<p>You are close, need also add <code>5</code> to first position, so use:</p> <pre><code>#if Id is not index #df = df.set_index('Id') p = df.index.get_loc(3) df = df.iloc[p:p+5] print (df) Name code Id 3 c 65 4 c++ 25 5 html 74 6 css 63 7 ...
pandas|pandas-groupby|sklearn-pandas|pandas-datareader
1
355,498
62,354,299
Pandas Change Default Style of Excel
<p>I am running <code>df.to_excel(writer, sheet_name=NAME, index=False)</code> to output a dataframe to an Excel spreadsheet.</p> <p>The <a href="https://xlsxwriter.readthedocs.io/format.html" rel="nofollow noreferrer">Format Default</a> for xlsxwriter is Calibri 11 with all other properties turned off. Is there a way...
<p>Use <code>cell_format.set_font_name()</code> for example:</p> <pre><code>cell_format = workbook.add_format() cell_format.set_font_name('Times New Roman') </code></pre> <p><a href="https://xlsxwriter.readthedocs.io/format.html#set_font_name" rel="nofollow noreferrer">https://xlsxwriter.readthedocs.io/format.html#se...
python|excel|pandas|formatting|xlsxwriter
0
355,499
62,302,185
How can i filter through this dataframe using conditions
<p>I want to filter though my dataset using conditions. I tried using .isin() function but i got an empty dataframe when filtering an np.array float list. Here is my code</p> <pre><code>f1 = [] f2 = [] f3 = [] f4 = [] for c in range(100): x = (2 * c) + 28 y = ((9 * c)/5) + 32 z = abs(x-y) f1.append(x) ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.query.html" rel="nofollow noreferrer"><code>pandas.query</code></a>:</p> <pre><code>print( df.query('0.1 &lt;= `Absolute Diff btw formulas` &lt;= 0.9') ) </code></pre> <p>Prints:</p> <pre><code> Temp in Celsius No...
python|pandas|numpy
1