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
13,600
44,842,656
FileNotFoundError: using Pandas
<p>I ran an example, I get the following errors and don't know why.</p> <pre><code># Import pandas as pd import pandas as pd # Import the cars.csv data: cars cars = pd.read_csv('cars.csv') # Print out cars print(cars) </code></pre> <p>And when I run, I get: </p> <pre><code>Traceback (most recent call last): File...
<p>You have to save both your program and cars.csv in same folder if you are using this. <code>cars = pd.read_csv('cars.csv')</code> or you can give full path to your csv file like this <code>(r'C:\Users\Vikas Chauhan\Desktop\cars.csv')</code>. Your code is correct.</p> <pre><code>import pandas as pd cars = pd.read_c...
python|pandas
3
13,601
44,853,319
to make a llist that have all zeros except the one column which should be value 1
<p>can anyone help on this? if i try this code,</p> <pre><code> a = np.array([2,1,5],[2,5,3]) b = np.zeros_like(a) c=b[np.arange(len(a)), a.argmax()] = 1 print(c) </code></pre> <p>It gives error<code>too many Indices for array</code> my motive is to make a list that gives me all columns zeros except the one that i...
<p>Code:</p> <pre><code>matrix = np.array([[2, 1, 5], [2, 5, 3]]) imax = matrix.argmax(1) n_labels = np.size(matrix, 1) onehot = np.eye(n_labels)[imax] </code></pre> <p>How it works, line by line:</p> <ol> <li>Define the numpy array.</li> <li>Get the index of the maximum value in each row.</li> <li>Get the size of t...
python|numpy
0
13,602
45,018,601
Decimal TO Binary in Dataframe Pandas
<p>I have a dataset and trying to read by Pandas dataframe. I want to transform one of the columns decimal values to binary. I have three columns and want the values of second column to be changed to binary. I have tried <code>format(n, 'b')</code> function like below but doesn't work out! Can anyone tell me what shoul...
<p>This should work:</p> <p><code>health.iloc[:,1].astype(int).map('{:b}'.format)</code></p>
python|pandas|dataframe|binary|decimal
0
13,603
57,130,915
Python: Replace all column by output of reg
<p>In my dataset, i have a feature (called <code>Size</code>) like this one:</p> <pre><code>import pandas as pd dit={"Size" : ["0","0","5mm","12-15","3-10"] } dt = pd.DataFrame(data=dit) </code></pre> <p>This feature specifies a size in a range (with minimum and maximum) or by a specific number.</p> <p>Now, i wish...
<p>You may use</p> <pre><code>import pandas as pd import re dit={"Size" : ["0","0","5mm","12-15","3-10"] } dt = pd.DataFrame(data=dit) rx = r'(\d+)(?:mm)?-(\d+)(?:mm)?' dt['Size']=dt['Size'].apply(lambda x: re.sub(rx, lambda z: str(max(int(z.group(1)), int(z.group(2)))) + "mm", x)) </code></pre> <p>Output:</p> <pre...
python|regex|pandas
3
13,604
35,510,289
Interpolation when no datarow exists
<p>I have a dataframe that looks like this</p> <pre><code> Idnumber Parent Date Other variables 1 a 2005 x 1 a 2007 x 2 b 2005 x 2 b 2006 x 2 b 2007 ...
<p>For overall approach, you could first define which rows <em>should</em> exist and then merge with the original dataset.</p> <pre><code>&gt;&gt;&gt; orig Idnumber Parent Date Other 0 1 a 2005 x 1 1 a 2007 x 2 2 b 2005 x 3 2 b 2006 x 4 ...
python|pandas
1
13,605
11,483,863
Python: intersection indices numpy array
<p>How can I get the indices of intersection points between two numpy arrays? I can get intersecting values with <code>intersect1d</code>:</p> <pre><code>import numpy as np a = np.array(xrange(11)) b = np.array([2, 7, 10]) inter = np.intersect1d(a, b) # inter == array([ 2, 7, 10]) </code></pre> <p>But how can I get...
<p>You could use the boolean array produced by <code>in1d</code> to index an <code>arange</code>. Reversing <code>a</code> so that the indices are different from the values:</p> <pre><code>&gt;&gt;&gt; a[::-1] array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) &gt;&gt;&gt; a = a[::-1] </code></pre> <p><code>intersec...
python|arrays|numpy
46
13,606
28,450,367
Why Fortran is slow in the julia benchmark "rand_mat_mul"?
<p>Benchmark test results on the home page of Julia (<a href="http://julialang.org/" rel="nofollow">http://julialang.org/</a>) shows that Fortran is about 4x slower than Julia/Numpy in the "rand_mat_mul" benchmark.</p> <p><strong>I can not understand that why fortran is slower while calling from the same fortran libra...
<p>I have changed the timing function to system_clock() and result turns out to be (I run it five times in one program)</p> <blockquote> <p>Time for Multiplication: 92ms</p> <p>Time for Multiplication: 92ms</p> <p>Time for Multiplication: 89ms</p> <p>Time for Multiplication: 85ms</p> <p>Time for Multiplication: 94...
numpy|fortran|julia|blas
1
13,607
50,985,481
pandas how to add details to csv before writing a data frame
<p>I need to write to a csv file that have 3-5 lines(rows) of details about the file, following which 3 rows of blank lines before I can append to data frame. </p> <p>Here is how the file looks like. (Note: lines having '#' are comments for demonstration)</p> <pre><code>some details some more details some details th...
<p>You could use a string template and leave <code>{}</code> to insert the dataframe into. The whole thing becomes more readable. Useful things to do: 1) Use <code>"""</code> for multi-line strings and 2) Use comments to remember why you do something.</p> <pre><code>import pandas as pd df = pd.DataFrame({ "A": [1...
python|pandas|export-to-csv
1
13,608
50,687,403
Simulate new rows, Python is much slower than SAS, How to speed up?
<p>Here is the problem and it is for a model implementation task. Given I have some data. I need to simulate some new data,some of the variable values are dependent on the values of previous row and a random number r. </p> <p>For example, say I have</p> <pre><code>AsOfDate Var1 Var2 r 6/4/2018 A 0.3 0.2...
<p>The most straightforward answer is: because you have chosen the most inefficient way : )</p> <p>I.e. this code (not really optimised):</p> <pre><code>import time import pandas as pd tick=time.time() n=0 a = { 'id': 1, 'val': 2, } data = [] for n in range(10000): a['id'] = a['id']+1 a['val'] = a['va...
python|pandas|sas
1
13,609
50,895,234
HDF5 reading and fit_generator multiprocessing error
<p>I'm trying to multiprocess the fit_generator. </p> <p>These are the problems that I face.</p> <pre><code>trainable_model.fit_generator(load_random_cached_bottlenecks(BATCH_SIZE, label_map, training_addr_label_map, train_npy_dir, 'h5py', h5py_file_train),epochs = EPOCHS, steps_per_epoch=iterations_per_epoch_t, vali...
<p>This is not a solution per-se but this solved this problem for me.</p> <p>I got the a similar error: <code>OSError: Can't read data (wrong B-tree signature) </code> when trying to use <code>fit_generator</code> when this one reads data from a <code>hdf5_file</code>, also inside an <code>anaconda3</code> virtual env...
multithreading|tensorflow|parallel-processing|keras|deep-learning
1
13,610
51,022,577
Deleting consecutive RGB values from a numpy array
<p>I initially created a subarray from the initial array for a greyscale image from this: <a href="https://stackoverflow.com/questions/50743769/deleting-consecutive-numbers-from-a-numpy-array">Deleting consecutive numbers from a numpy array</a> and <a href="https://stackoverflow.com/questions/37839928/remove-following-...
<p>This should do it: </p> <pre><code>columns_mask = np.insert(np.any(np.any(np.diff(a, axis=0).astype(np.bool), axis=1), axis=1), 0, True) rows_mask = np.insert(np.any(np.any(np.diff(a, axis=1).astype(np.bool), axis=0), axis=1), 0, True) print(a[np.ix_(columns_mask, rows_mask)]) </code></pre> <p>Output: </p> <pre...
python|arrays|numpy|image-processing|python-imaging-library
3
13,611
51,062,526
Calculate the maximum difference in rolling pandas - improve performance
<p>I have a Dataframe with one column.</p> <p>I need to calculate the <strong>average</strong> of the <strong>difference</strong> between the <strong>min and max values</strong> over 600 seconds period (10 minutes). Or more clearly this :</p> <pre><code>np.average(originalData[sensor1].rolling(600) .apply(lambda myli...
<p>You can use the <code>resample</code> method with <code>'10min'</code> as argument to group by 10 minute intervals. It is more efficient than using <code>rolling</code> for large sets of time series data, assuming it is set as the index.</p> <h2>Sample data</h2> <pre><code>rng = pd.date_range('2000-01-01', periods...
python|pandas|dataframe
0
13,612
50,847,386
Sklearn NN regression Attendance prediction
<p>I asked a question about the same problem earlier, but because my approach has changed I now have different questions.</p> <p>My current code:</p> <pre><code>from sklearn import preprocessing from openpyxl import load_workbook import numpy as np from numpy import exp, array, random, dot from sklearn.model_selectio...
<p>Your question is really general, however I have some suggestions. You could use <code>cross-validation</code> and try different models. Personnaly, I would try <code>SVR</code>,<code>RandomForests</code> and as last choice I would use a <code>MLPR</code>.</p> <p>I modified a bit your code to show a simple example:<...
python|numpy|scikit-learn|neural-network|prediction
1
13,613
51,041,014
How to stack layers in Keras without using Sequential()?
<p>If I have a keras layer L, and I want to stack N versions of this layer (with different weights) in a keras model, what's the best way to do that? Please note that here N is large and controlled by a hyper param. If N is small then this not a problem (we can just manually repeat a line N times). So let's assume N > ...
<p>Not sure if I've got your question right, but I guess that you could use the functional API and <code>concatenate</code> or <code>add</code> layers as it is shown in Keras applications, like, <a href="https://github.com/keras-team/keras/blob/keras-2/keras/applications/resnet50.py#L74" rel="nofollow noreferrer">ResNe...
python|tensorflow|keras
4
13,614
20,860,846
using pandas to parse a section inside a JSON document
<p>I'm trying to analyze my electric bill usage (hourly data downloaded in JSON format! woot!) with pandas. I can do it, but it's klunkier than I expected:</p> <pre><code>import pandas as pd import json with open('test1.json') as f: j = json.load(f) j2 = j['DailyBillingUsage']['RegisterCollections']['Channel'] s ...
<p>You can use my ObjectPath query language to do that:</p> <p><strong>Python way:</strong></p> <pre><code>$ sudo pip install objectpath $ python &gt;&gt;&gt; from objectpath import * &gt;&gt;&gt; with open('test1.json') as f: ... j = json.load(f) &gt;&gt;&gt; tree=Tree(j) &gt;&gt;&gt; tree.execute("$.DailyBilling...
python|json|pandas
1
13,615
33,424,203
How to merge rows with same index on a single data frame?
<p>I have a dataframe that looks like this:</p> <pre><code>A B C 1 1234 Win 1 2345 Win 2 1987 Loss 3 3456 Win 3 4567 Win </code></pre> <p>And I want this to become:</p> <pre><code>A B C 1 12...
<p>You can <code>groupby</code> on 'A' and 'C' seeing as their relationship is the same, cast the 'B' column to str and <code>join</code> with a comma:</p> <pre><code>In [23]: df.groupby(['A','C'])['B'].apply(lambda x: ','.join(x.astype(str))).reset_index() Out[23]: A C B 0 1 Win 1234,2345 1 2 L...
python|pandas
26
13,616
33,356,001
if (data[i,1] == 1): IndexError: index 869 is out of bounds for axis 0 with size 869
<p>I have the following code:</p> <pre><code>def findingGroups(data,i=0): findingGroupsMatrix1=np.zeros(1) findingGroupsMatrix2=np.zeros(1) findingGroupsMatrix3=np.zeros(1) findingGroupsMatrix4=np.zeros(1) z=np.zeros(1) print ("i",i) while True: if (data[i,1] == 1): z[0]=i findingGroupsMatrix1=np....
<p>If the shape is (869, 10), then the first subscripts run from 0-868. Your loop control is faulty. Since you know how many times you're going through the loop, use a "for". The loop you have checks after it's too late.</p> <pre><code>for i in len(data): .... </code></pre> <p>You don't have to increment i any...
python|numpy|import
1
13,617
66,531,898
Rename unique values pandas column in ascending order
<p>I have a pandas DataFrame that looks similar to the one below:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({ 'label': [0, 0, 2, 3, 8, 8, 9], 'value1': [2, 1, 9, 8, 7, 4, 2], 'value2': [0, 1, 9, 4, 2, 3, 1], }) &gt;&gt;&gt; df label value1 value2 0 0 2 0 1 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.factorize.html" rel="nofollow noreferrer"><code>factorize</code></a> for improve performance:</p> <pre><code>df['label'] = pd.factorize(df['label'])[0] + 1 print (df) label value1 value2 0 1 2 0 1 1 1 ...
python|pandas
3
13,618
66,619,632
Pandas groupby create new column based on a condition
<p>In the table below, I want to produce the column <strong>new area</strong> for the group created by address related fields X,Y,Z (Groupby XYZ). If in the code column, if the value is A, just count that area only once and add the remaining area for other codes.</p> <p>So for this group, the new area should be 100(A)+...
<p>So this works, but not sure if it's the most efficient way. Since you didn't specify <em>which</em> code you wanted to take when there were multiple, I assumed they would hold the same value for <code>area</code> and so dropped duplicates.</p> <pre><code>import pandas as pd df = pd.DataFrame() df['X'] = ['222 Nort...
python|pandas|group-by
3
13,619
66,679,829
Python add missing rows to dataframe
<p>I have a dataframe which can sometime have incomplete data. For example this one below stops at Hour 22 instead of 23</p> <pre><code> Date Hour Interval Source ID Number of Messages 0 2020-05-19 0 0 1 413379290 23 1 2020-05-19 0 15 ...
<p>The approach I would take is to find the min and max of date, then create a range of dates with 15 minute interval. Use df.merge to add all values from df to the newly created dataframe.</p> <p>Note here that the date starts from 2020-05-19 01:00:00 and not 00:00:00. So the final output will also start from 01:00:00...
python|pandas
2
13,620
66,602,757
How do I capture all complying values using a mask in Pandas?
<p>Value_counts performed in one specific data frame column shows visually that there are 441 values lower than 10. When I run a mask (boolean indexing) in order to access those values it only gets 12 of the 441.</p> <p>I thought it was a datatype issue. However, right before the operations above I changed the column d...
<p>I used the function astype(float) all along for masking and value_counts operations. This catches all the numeric values complying the filter and not only a few str values present in the data.</p>
pandas|boolean-indexing
0
13,621
16,239,678
How to use dorpi5 or dop853 in Python
<p>I have looked through <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.ode.html" rel="nofollow noreferrer">scipy.integrate.ode</a> but I am unable to find out how to actually use these integration methods, <code>dorpi5</code> and <code>dop853</code>.</p> <p>I would like to try integratin...
<p>You call the method <code>set_integrator</code> on the <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.ode.html" rel="noreferrer"><code>ode</code></a> class with either <code>'dopri5'</code> or <code>'dop853'</code> as its argument.</p> <p>Here's an example:</p> <pre><code>import numpy...
python|numpy|scipy|integration|differential-equations
14
13,622
24,237,658
Faster alternative to numpy.einsum for taking the "element-wise" dot product of two lists of vectors?
<p>Let's say you're given two arrays of vectors:</p> <p><code>v1 = np.array([ [1, 2], [3, 4] ])</code> <code>v2 = np.array([ [10, 20], [30, 40]])</code></p> <p>We would like to generate an array that is equivalent to:</p> <p><code>v3 = np.array([ np.dot(v1[0], v2[0]), np.dot(v1[1], v2[1]) ])</code></p> <p>Currently...
<p><code>einsum</code> does the best of 3 options that I can think of:</p> <pre><code>In [73]: timeit v3=np.einsum('ij,ij-&gt;i',v1,v2) 100000 loops, best of 3: 5.14 us per loop In [74]: timeit np.diag(np.dot(v1,v2.T)) 100000 loops, best of 3: 7.43 us per loop In [75]: timeit np.sum(v1*v2,axis=1) 100000 loops, best ...
python|numpy
2
13,623
43,912,218
How to install scipy in Python3.5 virtual env | windows 10?
<p>I have Anaconda (Python 3.6) in my Windows 10. This includes Scipy. I am also using a virtual Python 3.5 env to support TensorFlow. Now, the problem is that I cannot import Scipy while I'm inside this virtual env.</p> <p>I have tried: pip install scipy (didn't work) easy-install scipy (didn't work) I also v...
<p>Once you're inside your virtual environment for TensorFlow, try</p> <pre><code>conda install -c anaconda scipy=0.19.0 </code></pre>
python|tensorflow|scipy|jupyter-notebook
3
13,624
43,906,085
rationale behind the evaluation in tensorflow's tutorial code cifar10_eval.py
<p>In TF's official tutorial code 'cifar10', there is an evaluation snippet:</p> <pre><code>def evaluate(): with tf.Graph().as_default() as g: # Get images and labels for CIFAR-10. eval_data = FLAGS.eval_data == 'test' images, labels = cifar10.inputs(eval_data=eval_data) ...
<ol> <li><p>You can see the following line in "inputs" def of cifar10_input.py</p> <pre><code>filename_queue = tf.train.string_input_producer(filenames) </code></pre> <p>More about tf.train.string_input_producer : </p> <pre><code>string_input_producer( string_tensor, num_epochs=None, shuffle=True, ...
tensorflow
1
13,625
43,585,988
python pandas sum by hour of day
<p>I'm working with the following dataset with hourly counts (df): The datframe has 8784 rows (for the year 2016, hourly).</p> <p><a href="https://i.stack.imgur.com/4wvBM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4wvBM.png" alt="dataframe (df)"></a></p> <p>I'd like to see if there are daily trends (e....
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="noreferrer"><code>groupby</code></a> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.hour.html" rel="noreferrer"><code>hour</code></a> and <code>weekday</code> and...
python|pandas|matplotlib|time-series
21
13,626
73,023,645
pandas read excel without unnamed columns
<p>Trying to read excel table that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th><strong>B</strong></th> <th>C</th> </tr> </thead> <tbody> <tr> <td><strong>A</strong></td> <td>data</td> <td>data</td> </tr> <tr> <td>data</td> <td>data</td> <td>data</td> </tr> </t...
<p>A similar question was asked/solved <a href="https://stackoverflow.com/questions/43983622/remove-unnamed-columns-in-pandas-dataframe">here</a>. So basically the easiest thing would be to either drop the first column (if thats always the problematic column) with</p> <pre><code>df = pd.read_csv('data.csv', index_col=0...
python|excel|pandas
0
13,627
72,913,364
Substract multiple columns of dataframe based on condition with three columns in Python
<p>I have two dataframes, A and B. Each has the same dimensions and same columns. Lets say I want to substract both dataframes (dfB-dfA) if the values of the rows in the first three columns match. Below is an example.</p> <p>dfA</p> <p><a href="https://i.stack.imgur.com/dpzR6.png" rel="nofollow noreferrer"><img src="ht...
<p>Pandas is smart enough to take the indices into account. Just convert the columns you want to match into the index and perform your operation as NewDF = dfA-dfB</p>
python|pandas|dataframe
1
13,628
72,867,694
Extract max distance for IDs that visited multiple (lat,lon)
<p>I have a table with this format :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>User</th> <th>lat</th> <th>lon</th> </tr> </thead> <tbody> <tr> <td>u1</td> <td>x1</td> <td>y1</td> </tr> <tr> <td>u1</td> <td>x2</td> <td>y2</td> </tr> <tr> <td>u1</td> <td>x3</td> <td>y3</td> </tr> <tr> <...
<h1>Summary</h1> <p>Implemented a fast algorithm which works in linear time</p> <ul> <li>US Cities Dataset (30, 409 records): 0.103 seconds</li> <li>Animal tracking dataset (89,867 records): 0.325 seconds</li> <li>Timings on 10+ year old windows desktop (i7 920 CPU @ 2.67GHz)</li> </ul> <h1>Approach</h1> <p>Has linear ...
python|pandas|geolocation|distance|geopandas
2
13,629
10,460,295
Efficient way of extracting from an array of objects
<p>I have a an array of objects in python:</p> <pre><code>meshnodearray = ['MeshNode object', 'MeshNode object', 'MeshNode object', ...] </code></pre> <p>Where for example first 'MeshNode object' is:</p> <pre><code>({'coordinates': (15.08, 273.01, 322.61), 'instanceName': None, 'label': 1}) </code></pre> <p>I need ...
<p>Try extracting the coordinates into a python list of coordinates and converting it into a numpy array in one go. If the label values are sequential from 1 to <code>nnod</code>, it's as simple as this:</p> <pre><code>coords = [ n['coordinates'] for n in meshnodearray ] NODEcoo = np.array(coords) </code></pre> <p>It...
python|arrays|multidimensional-array|numpy
1
13,630
3,652,866
difficulty in installing SciPy and Numpy in Ubuntu(9.04)?
<p>HI folks. I have difficulty in installing these items in Ubuntu.......plz help me as soon as possible.iam experiencing errors such as no module name found......sometimes certain libraries are not found.......plz folks can all of u state the basic libraries required for installing these items and where to find th...
<p>Let's start at the beginning - do you have Python installed and running on Ubuntu? If not, you won't have NumPy or SciPy, either.</p> <p>Did you download NumPy and SciPy and unpack them to your hard drive? Do you see directories that contain setup.py somewhere?</p> <p>Usually it's <code>python setup.py install</...
python|ubuntu|numpy|scipy
2
13,631
70,613,546
Using pandas dataframe to replace values with certain starting string indices
<p>I am creating a data table with an assortment of columns and values. At times, if a column value is equal to a certain value, I wish to change another value in a different column. An example is listed below.</p> <pre><code>df1.loc[df1.DISCREP=='True','Number'] = 1200 </code></pre> <p>Basically, if something in my co...
<p>here you can use this <code>df1['DISCREP'].str.startswith('HY')</code> instead of <code>df1.DISCREP=='True'</code> because the first code sample will generate a boolean mask that will put <code>True</code> to the strings which begin with <code>'HY'</code>.</p> <p>Sample of a boolean mask :</p> <pre class="lang-sh pr...
python|pandas|dataframe
0
13,632
42,997,497
How to expand (extract) information from highly nets JSON with Pandas
<p>I'm reading JSON file with Pandas and some of my rows contains things like these:</p> <pre><code>In[37]: df Out[37]: 66 {u'test_date': {u'$date': 1465513200000}, u'se... 81 {u'test_date': {u'$date': 1463958000000}, u'se... 155 {u'Nancy Index': 1, u'test_date': {u'$date': 1... 163 {u'Nancy Index': 2, ...
<p>jSon files are sometimes deeply nested. You can serialise these cell values again.</p> <p>These serialiser is documented at <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.json.json_normalize.html" rel="nofollow noreferrer">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.jso...
python|json|pandas|nested
1
13,633
43,018,711
About numpy's concatenate, hstack, vstack functions?
<p>See some examples</p> <pre><code>import numpy as np a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) print(np.concatenate((a,b), axis=0)) # [1,2,3,4,5,6] print(np.hstack((a,b))) # [1,2,3,4,5,6] print(np.vstack((a,b))) # [[1,2,3],[4,5,6]] print(np.concatenate((a,b), axis=1)) # IndexError: axis 1 out of bounds [0, 1...
<p>Look at the actual code for <code>hstack</code>:</p> <pre><code>arrs = [atleast_1d(_m) for _m in tup] # As a special case, dimension 0 of 1-dimensional arrays is "horizontal" if arrs[0].ndim == 1: return _nx.concatenate(arrs, 0) else: return _nx.concatenate(arrs, 1) </code></pre> <p>I don't see anything in...
python|numpy
0
13,634
42,806,173
Plotting with matplotlib does not give desired datetime format
<p>the data i used are derived from an excel file using <code>pd.read_excel</code>.</p> <p>The objective: To plot DateTime vs Value with x axis values in the format <code>%Y-%m-%d %H:%M:%S</code>.</p> <p>The problem: The X axis format is not the desired <code>%Y-%m-%d %H:%M:%S</code>. </p> <p>Below is a snippet of t...
<p>You can use <a href="https://matplotlib.org/api/dates_api.html#matplotlib.dates.DateFormatter" rel="nofollow noreferrer"><code>matplotlib.dates.DateFormatter</code></a> to achieve this:</p> <pre><code>import matplotlib.dates as dates df['DateTime'] = pd.to_datetime(df['DateTime'], format='%Y-%m-%d %H:%M:%S') df.plo...
python|python-3.x|pandas|datetime|matplotlib
3
13,635
42,848,041
tensorflow kernel code modification
<p>I want to measure time which is spent in each function. So I modified tensorflow/core/kernel/conv_ops.cc as below.</p> <pre><code>.... #include &lt;ctime&gt; .... void Compute(OpKernelContext* context) override { // Input tensor is of the following dimensions: // [ batch, in_rows, in_cols, in_depth ] std::clock...
<p>Use <code>LOG(INFO) &lt;&lt; &quot;Message&quot;;</code> instead of <code>std::cout</code>.</p> <p>For adding custom operation, <a href="https://github.com/tensorflow/custom-op" rel="nofollow noreferrer">This</a> will help.</p>
c++|tensorflow
0
13,636
14,864,895
Distributing Cython based extensions using LAPACK
<p>I am writing a Python module that includes Cython extensions and uses <code>LAPACK</code> (and <code>BLAS</code>). I am open to using either <code>clapack</code> or <code>lapacke</code>, or some kind of <code>f2c</code> or <code>f2py</code> solution if necessary. What is important is that I am able to call <code>l...
<p>If I have understood the question correctly, you could make use of SciPy's Cython wrappers for BLAS and LAPACK routines. These wrappers are documented here:</p> <ul> <li><a href="https://docs.scipy.org/doc/scipy-0.18.0/reference/linalg.cython_blas.html" rel="nofollow noreferrer">BLAS</a></li> <li><a href="https://d...
python|numpy|cython|lapack|blas
6
13,637
24,991,270
How to get average of a column inside a time era?
<p>I need to get the average of a column (which I will set in the input of my function) during a precise era : In my case the date is the index, so I can get the week with <code>index.week</code>. Then I would like to compute some basic statistics each <code>2</code> weeks for instances</p> <p>So I will need to "slice...
<p>Welcome to Stackoverflow. Please note that your question is not very specific and is difficult to supply you with exactly what you want. Optimally, you would supply code to recreate your dataset and also post the expected outcome. I'll post regarding two parts: (i) Working with dataframes sliced using time-specific ...
python|pandas
1
13,638
25,225,922
Pandas: what is a simple way to group by two columns and build a new flat dataframe
<p>Say I have a data frame <code>df1</code> with columns A,B,C,D. I want to group by A,B and then have a new data frame <code>df2</code> with columns set to size of df1["B"] for each df["A"] and index rows set to df1["A"]. </p> <p>Here's a code I currently have to solve this, but I wonder if there's a simple way:</p> ...
<p>I think this could be a much cleaner way of doing it...</p> <pre><code>output = data.groupby(["A", "B"]).size()#dont have to call the constructor again output = output.unstack('B').fillna(0) </code></pre> <p><strong>output</strong></p> <pre><code>B b1 b2 A a1 1 0 a2 1 1 a3 0 1 </code></pre>
python|pandas
2
13,639
26,706,090
Python Pandas Data Formatting
<p>I am in some sort of Python Pandas datetime purgatory and cannot seem to figure out why the below throws an error. I have a simple date, a clear format string, and a thus far unexplained ValueError. I've done quite a bit of searching, and can't seem to get to the bottom of this. </p> <p>On top of the issue below...
<p><code>%Y</code> is a <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow">four-digit year</a>. You should find that <code>%y</code> will work.</p>
python|datetime|pandas
2
13,640
26,781,933
Create arrays in array in a loop using numpy
<p>I have to lists: </p> <pre><code>a=[1,2,3] </code></pre> <p>and </p> <pre><code>b=[4,5,6] </code></pre> <p>I would like to create and array containing arrays of the two lists so I did</p> <pre><code>c=np.array([[a],[b]]) </code></pre> <p>My question is:How can implement it in a loop? To create an empty array a...
<p>Do you want this?</p> <pre><code>a = [1,2,3]; b = [4,5,6]; c = [a,b]; c[1][1] # Gives you 5 </code></pre> <p>To do it in a loop</p> <pre><code>for z in [a,b]: c.append(z) # continue as usual...... </code></pre> <p>Also, you don't really need numpy to do this. If you do, follow @Taha s answer above.</p>
python|arrays|numpy
1
13,641
26,626,964
Pandas SparseDataFrame from list of dicts
<p>I'm trying to convert a list of Python dicts into a Pandas <code>DataFrame</code>. Since every dict has different keys, it takes up too much memory. Since most of the values are NaN, a <code>SparseDataFrame</code> should be helpful in this case.</p> <pre><code>import pandas df = pandas.DataFrame(keyword_data).to_s...
<p>As of pandas v1.0.0, <code>SparseDataFrame</code> and <code>SparseSeries</code> <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/sparse.html#migrating" rel="nofollow noreferrer">were removed</a>.</p> <p>There is no need for them anymore. Quoting <a href="https://pandas.pydata.org/pandas-docs/stable/u...
python|numpy|pandas
1
13,642
39,376,560
How to call Tensorflow in Azure ML
<p>I've so far seen people using tensorflow in Azure using in this <a href="http://www.mikelanzetta.com/tensorflow-on-azure-using-docker.html" rel="nofollow">link</a>. Also using the advantage of ubuntu in windows tensorflow can be run on windows pc as well.Here is the <a href="http://www.hanselman.com/blog/PlayingWith...
<p>Quick update for you. As of TensorFlow r0.12 there is now a native TensorFlow package for Windows. I have it running successfully on my Windows 10 laptop. See this <a href="https://developers.googleblog.com/2016/11/tensorflow-0-12-adds-support-for-windows.html" rel="nofollow noreferrer">blog post</a> from Google for...
tensorflow|azure-machine-learning-studio
1
13,643
13,042,390
how do I remove rows/columns from this matrix using python
<p>My matrix looks like this.</p> <pre><code> ['Hotel', ' "excellent"', ' "very good"', ' "average"', ' "poor"', ' "terrible"', ' "cheapest"', ' "rank"', ' "total reviews"'] ['westin', ' 390', ' 291', ' 70', ' 43', ' 19', ' 215', ' 27', ' 813'] ['ramada', ' 136', ' 67', ' 53', ' 30', ' 24', ' 149', ' 49', ' 310 '] ...
<p>If you have a list of lists, then:</p> <pre><code>new_list = [row[1:] for row in current_list[1:]] </code></pre> <p>So, create a new matrix ignoring the first row, and for each row after, ignore the first column.</p> <p>If it happened to be a <code>numpy.array</code>, then you could use:</p> <pre><code>your_arra...
python|csv|matrix|numpy|scipy
5
13,644
28,981,059
Creating a size specific Numpy Array, and then filling it with values at a steped rate
<p>I am a totally lost newbie, whose goal is to write a script that creates a random integer grid, where user input specifies the number of rows, the number of columns, the high and low values, and the step at which the values between the high and low are counted (for instance count from 0 to 10 by twos). Using that in...
<p>Your <code>user_raster</code> array is only 5 elements long in your example, when you resize it to 5x5 <code>np.ndarray.resize</code> fills the extra space with zeros. You could use <code>np.resize</code> (emphasis added for <code>ndarray.resize</code> behaviour):</p> <blockquote> <p>Definition: np.resize(a, new...
python|arrays|numpy
1
13,645
33,714,050
GeoPandas plotting - any way to speed things up?
<p>I'm running a gradient descent algorithm on some geo data. The goal is to assign different areas to different clusters to minimize some objective function. I am trying to make a short movie showing how the algorithm progresses. Right now my approach is to plot the map at each step, then use some other tools to make ...
<p>I think two aspects can possibly improve the performance: 1) using a matplotlib Collection (the current geopandas implementation is plotting each polygon separately) and 2) only updating the color of the polygons and not plotting it again each iteration (this you already do, but with using a collection this will be ...
python|pandas|matplotlib|geopandas|drawnow
5
13,646
33,804,658
Prevent scientific notation in seaborn boxplot
<p>I'm using pandas version 0.17.0 , matplotlib version 1.4.3 and seaborn version 0.6.0 to create a boxplot. I want all values on the x-axis in float notation. Currently the two smallest values (0,00001 and 0,00005) are formatted in scientific notation. </p> <p><img src="https://i.stack.imgur.com/URAYQ.png" alt=""></p...
<p>This might be an ugly solution, but it works, so who cares</p> <pre><code>fig, ax = plt.subplots(1, 1) boxplot = sns.boxplot(x="Regularisierungsparameter", y="F1", data=data.sort("Regularisierungsparameter"), ax=ax) labels = ['%.5f' % float(t.get_text()) for t in ax.get_xticklabels()] ax.set_xticklabels(labels) </c...
python|pandas|matplotlib|seaborn
1
13,647
22,924,564
Pandas dataframe transpose, to_csv
<p>In the code below, in line 4 I can transpose the dataframe, but in line 5, when I use to_csv, the new CSV file is created, it remains the original version and not the transposed one. What might have gone wrong? </p> <pre><code>import numpy as np import pandas as pd df = pd.read_csv('~/N.csv') df2 = df.T df2 = d...
<p>No need to use df2 = </p> <p>This is enough..</p> <pre><code>df2.to_csv('~/N_transposed.csv') </code></pre>
python|pandas|dataframe|transpose
7
13,648
15,197,510
bin width according to custom function
<p>I would like to bin my data in a non-uniform way.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def fun(x): return &gt;some function of x&lt; </code></pre> <p>What I want now is to make somehing looking like:</p> <pre><code>np.linespace(0.,200.,fun(x)) </code></pre> <p>Is there a convenien...
<p>Create a range of x-values, define your custom function, then call your function on each of the array elements. Numpy makes this quite easy:</p> <pre><code>fun = lambda x: x**2 # Example function N = 10 # Number of data points x = np.linspace(0., 200., N) # Creates an array of N points bins = fun(x) # Applies fun t...
python|numpy|matplotlib
3
13,649
13,664,097
Unlink a new array from older one: python
<p>My problem is as follows. I have a 2D array. From the 2D array I take out one row as an 1D array and work with it and make changes, but it also changes the original entries in the 2D array, but I want them to remain constant. How do I solve this in python?</p>
<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.copy.html#numpy.copy" rel="nofollow"><code>ndarray.copy()</code></a>:</p> <pre><code>In [17]: A = array([[1, 1], [3, 2], [-4, 1]]) In [18]: b = A[1].copy() In [19]: b Out[19]: array([3, 2]) In [20]: b[0] = 4 In [21]: b Out[21]: arr...
python|numpy
3
13,650
13,740,275
Individual Numpy types do not seem to preserve Endianness
<p>Numpy version: 1.6.2</p> <p>Can somebody explain why individual scalars of an array do not maintain the endianness set in the dtype? How do I get them to output with the right endianness?</p> <pre><code>&gt;&gt;&gt; numpy_type1 = numpy.uint32 &gt;&gt;&gt; numpy_type2 = numpy.dtype(numpy_type1).newbyteorder('&gt;')...
<p>For single values you can probably just as well use <code>struct</code> package. Scalars simply do not have an endianess in numpy (always system) for simplicity. However you can also use a 0-d array which will preserve the endianess. But for most results numpy converts 0-d arrays to scalars, since they are typically...
python|numpy|endianness
1
13,651
13,531,717
vectorising linalg.eig() in numpy
<p>I have an m*m*n numpy array (call it A) and I would like to find the eigenvalues of every submatrix <code>A[:,:,n]</code> in this array. I could do it with <code>linalg.eig()</code> in a loop with relative ease, but there really ought to be a way to vectorise this. Something like a <code>ufunc</code>, but that can p...
<p>The computation of the eigenvalues and eigenvectors can not be vectorised in the sense that there's no way in general to share work for different matrices. <code>np.linalg.eig</code> (for real input) is just a wrapper for <a href="http://www.netlib.no/netlib/lapack/double/dgeev.f" rel="nofollow noreferrer"><code>dge...
optimization|numpy|linear-algebra
2
13,652
29,799,043
Standard deviation for DF, pandas
<p>for example I have a pandas DataFrame, which looks as:</p> <pre><code>a b c 1 2 3 4 5 6 7 8 9 </code></pre> <p>I want to calculate the standard deviation for all values in this DF. The function <code>df.std()</code> get me back the values pro column.</p> <p>Of course I can create the next code:</p> <pre><code>sd...
<p><code>df.values</code> returns a NumPy array containing the values in <code>df</code>. You could then apply <code>np.std</code> to that array:</p> <pre><code>In [52]: np.std(sd) Out[52]: 2.5819888974716112 In [53]: np.std(df.values) Out[53]: 2.5819888974716112 </code></pre>
python|pandas|dataframe
5
13,653
62,230,507
Multiple Columns for HUE parameter in Seaborn violinplot
<p>I am working with tips data set, and here is the head of data set.</p> <pre><code> total_bill tip sex smoker day time size 0 16.99 1.01 Female No Sun Dinner 2 1 10.34 1.66 Male No Sun Dinner 3 2 21.01 3.50 Male No Sun Dinner 3 3 23.68 3.31 Male No Sun Dinner 2 ...
<p>The faceting approach suggested by <a href="https://stackoverflow.com/a/62230987">the accepted answer</a> is probably nicer in this case, but might not be easily applicable to other kinds of Seaborn plots (e.g. in my case, <code>ecdfplot</code>). So I just wanted to share that I figured out a solution which does wha...
python|pandas|seaborn|data-visualization|violin-plot
12
13,654
62,336,002
What exactly is Orchestrators in ML?
<p>Actually, in ML pipeline components we are specifying inputs and outputs clearly .</p> <p>For example in TFX statisticgen take input from examplegen and outputs some statistics.so input and output is clear which is same in all components .so why we need orchestrators .if anyone knows please help me?</p>
<p>In real-life projects, everything can be much more complicated:</p> <ul> <li>the input data can be from the different sources: database, file system, third-party services. So we need to do classical ETL before we can start working with data.</li> <li><p>you can use different technologies in the one pipeline. For in...
tensorflow|machine-learning|orchestration|tfx
1
13,655
62,366,235
Problem installing TensorFlow through pip
<p>I used the command <code>pip install tensorflow</code> and it always ends with this error message:</p> <pre><code>ERROR: Could not install packages due to an EnvironmentError: [Errno2] No such file or directory: 'C:\\Users\\xgxbr\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\\LocalC...
<p>Try using this:</p> <pre><code>pip install --upgrade tensorflow </code></pre>
python|windows|tensorflow|pip|tensorflow2.0
0
13,656
62,132,538
multiply 2 time discrete vectors using numpy library (python)
<p>I need to Write a function with the next inputs:</p> <p><code>n1</code>, <code>x1</code>, <code>n2</code>, <code>x2</code> and the function return two outputs <code>n</code>, <code>y</code>.</p> <p><code>n1</code> is discrete time array of the signal <code>x1</code>. (Discrete time means that the sample of time ar...
<p>You say you would like to multiply them, but your desired result does not show a multiplication. Do you mean to say the vector <code>y</code> should contain ones for those values where n1 and n2 "meet", and zeros otherwise?</p> <p>Will vectors n1 and n2 always contain ordered consecutive integers, as in your examp...
python|python-3.x|numpy|python-requests|jupyter-notebook
0
13,657
62,446,116
Numpy: negative dimensions are not allowed
<p>Using GeFolki for the coregistration of different satellite datasets I receive the following ValueError trying to manipulate the data.</p> <p>Could you explain what am I doing wrong? Please Help me</p> <pre><code>from skimage.transform import resize nx = int(round(dimx/fdecimation)) ny = int(round(dimy/fdecimatio...
<p>Apparently one of <code>nx-nsx-1</code>,<code>ny-nsy-1</code> is negative, but you cannot create an array of 0s with negative number of rows/columns. I suggest printing out those values and see where they get negative to fix it.</p>
numpy|dimensions|valueerror|negative-number
1
13,658
62,370,947
convert VGG16 shape output from 4096 features to 2048
<p>I'm trying to do image classification using VGG16 pre-trained model and dumb the features into csv file, but im facing the issue with the number of features, I'm trying to get 2048 features instead of 4096 features I have read little thing that said I can remove one layer from vgg16 model and then I can get 2048 fea...
<p>I'm not sure if I understand your question, You can use <code>pop()</code> on <code>model.layers</code> and then use <code>model.layers[-1].output</code> to create new layers.</p> <pre><code>vgg16_model = keras.applications.vgg16.VGG16() model = Sequential() for layer in vgg16_model.layers[:-1]: model.add(lay...
numpy|keras|deep-learning|neural-network|conv-neural-network
0
13,659
62,468,820
How to use NumPy to directly create an a array that is made up of a few python nested loop of a uniform sized tuple/list?
<p>I have a tuple/list like so:</p> <pre><code>tup = (1, 2, 3, 4, 5) f = [ (e, d, c, b, a) for a in tup for b in tup for c in tup for d in tup for e in tup ] </code></pre> <p>How do I create an equivalent array directly from NumPy without using <code>np.array( f )</code>? Is there some slicing technique that I should...
<p>you can use itertools. </p> <pre><code>import itertools tup = (1,2,3,4,5) list(itertools.product(tup, repeat=5)) </code></pre>
python|numpy
0
13,660
51,417,508
Multiple IF statements comparing 2 dataframes and populating dataframe based on result
<p>I have 2 dataframes, one with a list of systems and versions and another with a list of all the systems/versions and whether they are obsolete, and I'm struggling to perform some sort of multi-if statement (including comparators) and populate the data in the first df with the data from the second.</p> <p>The datafr...
<p>I think it should be like:</p> <pre><code>l = [] for i in range(len(obsolete_df)): s_row = system_df[i] o_row = obsolete_df[i] if s_row[2] == o_row[1]: # compare SIS_TYPE if s_row[2] == o_row[1] or o_row[1] == '*': # compare EDITION l.append((s_row[1], s_row[2], ...)) </code></pre> ...
python|pandas|if-statement
1
13,661
48,004,171
Pandas- Unnecessay values included while converting a column into datetime format
<p>I made a column by concatenating integers and converting into string format. Later I am converting the string column into datetime, everything is working just fine except an additional day field is added to the new datetime column. Here is what I mean to say.</p> <pre><code> I am making a column of type string like...
<pre><code>import datetime df[date_column] = df[date_column].apply(lambda x : datetime.datetime.strftime(x, "%Y-%m")) </code></pre>
python|pandas|datetime|machine-learning
0
13,662
48,038,422
3d plot of list of (hist, bin_edges) where histogram bar chart or lines are in the z-y plane
<p>EDIT - reworked question</p> <p>I need to print a 3D histogram of fitness data for 50 generations of computer programmes. This data is in calculated and stored in a logbook using the DEAP framework. The form of the plot needs to be with the fitness frequency on the z axis, generation on the x axis and bin_edges o...
<p>I use <code>mplot3d</code> and <code>bar</code> to plot <code>3d-hist</code> as follow:</p> <p><a href="https://i.stack.imgur.com/hikNN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hikNN.png" alt="enter image description here"></a></p> <hr> <pre><code>#!/usr/bin/python3 # 2017.12.31 18:46:42...
python|numpy|matplotlib
2
13,663
48,684,755
Tensorboard doesn't show scalars anymore
<p>I decided to update tensorboard because it wasn't showing the graph, on the graph panel all I could see was a blank page with no error message. Now that I have updated the graph, is the only thing my tensorboard shows. Now I cannot see scalars or histograms. I have the:</p> <pre><code>No scalar data was found. </co...
<p>Solved! In case someone is in the same situation, the solution was to uninstall conda tensorflow and install it through pip. It gaves you later an error requesting for an specific cuda and cudnn. Once you install these two it should work.</p>
tensorflow|anaconda|jupyter-notebook|tensorboard
2
13,664
48,876,481
Count missing instances in subgroups
<p>I have a dataframe in Pandas with collected data;</p> <pre><code>import pandas as pd df = pd.DataFrame({'Group': ['A','A','A','A','A','A','A','B','B','B','B','B','B','B'], 'Subgroup': ['Blue', 'Blue','Blue','Red','Red','Red','Red','Blue','Blue','Blue','Blue','Red','Red','Red'],'Obs':[1,2,4,1,2,3,4,1,2,3,6,1,2,3]}) ...
<p>Simple enough, you'll need <code>groupby</code> here: </p> <ol> <li>Using <code>groupby</code> + <code>diff</code>, figure out how many observations are missing per <code>Group</code> and <code>SubGroup</code></li> <li>Group <code>df</code> on <code>Group</code>, and compute the <code>size</code> and <code>sum</cod...
python|pandas|grouping|sequence|data-science
4
13,665
48,843,882
how to generate sequence number for repeating rows
<p>I have a pandas dataframe (df) where I have to generate sequence numbers for repeated rows (i.e., rows with similar values). For example, following is my df:</p> <pre><code>P_Id Time_Point Date B001 0 2015-07-22 B001 0 2015-07-22 B001 0 2015-07-22 B001 0 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></...
python|pandas
4
13,666
48,585,490
Try to assign twice to the same array variable in Tensorflow
<p>I created a simple array variable in Tensorflow and I am trying to find a way to do assignment more then one time. I know that in order to do assignments in TF you need to use <code>tf.assign</code> function. The problem is that it returns a "sliced type" and not a variable type.</p> <p>Code example: </p> <pre><co...
<p>Simply don't reuse the same python variable <code>c</code> for different operations:</p> <pre class="lang-py prettyprint-override"><code>a = [-1.2, -5, 30.0, -7.5, 0.75] c = tf.get_variable("v", shape=[5], initializer=tf.constant_initializer(a)) assign55 = c[0].assign(55) assign66 = c[0].assign(66) assign77 = c[...
python|arrays|tensorflow|variable-assignment
0
13,667
48,638,398
Numpy rounds in a different way than python
<p>The code</p> <pre><code>import numpy as np a = 5.92270987499999979065 print(round(a, 8)) print(round(np.float64(a), 8)) </code></pre> <p>gives</p> <pre><code>5.92270987 5.92270988 </code></pre> <p>Any idea why?</p> <p>Found nothing relevant in numpy sources.</p> <p><strong>Update:</strong><br> I know that the ...
<p><a href="https://github.com/python/cpython/blob/v3.6.4/Objects/floatobject.c#L905" rel="nofollow noreferrer"><code>float.__round__</code></a> takes special care to produce correctly-rounded results, using a correctly-rounded double-to-string algorithm.</p> <p>NumPy does not. The <a href="https://docs.scipy.org/doc/...
python|numpy|rounding-error|rounding
5
13,668
70,886,218
Torchscript/C++ jit::trace model - Accessing layers parameters
<p>I have a model I trained in python, traced using <code>torch.jit.trace</code>, and load into C++ using <code>torch::jit::load</code>.</p> <p>Is there a way to access the last layer to pull the value for the models required output depth (for example, if it is a Conv2D layer going from 16 -&gt; 2, I want to predefine ...
<p>Not the most elegant way of solving this, but the most straightforward was just passing a dummy tensor through and accessing the shape. Another way I did try was accessing the parameter list and looking for &quot;softmax&quot;, unfortunately I couldn't guarantee everyones model will spell it the same way when search...
c++|parameters|pytorch|layer|torchscript
0
13,669
70,961,408
Python Pandas Dataframe How to repeat a value in one column based on length of another column
<p>How do I repeat the values in one column multiple times based on the length of another column? Example: names = [Jack, Bob] and pets=[fish, cat, dog, bird]. I would like the dataframe to be:</p> <pre><code> names pets 0 Jack fish 1 Jack cat 2 Jack dog 3 Jack bird 4 Bob fish 5 Bob ...
<p>Using <code>itertools.product</code>:</p> <pre><code>import itertools pd.DataFrame(itertools.product(names,pets), columns = ['names', 'pets']) </code></pre>
python|pandas
1
13,670
51,791,790
Identifying Outliers with Quantile Regression and Python
<p>I am trying to identify outliers in a dataset using the 5th and 95th percentiles of a regression line so I'm using quantile regression in Python with statsmodel, matplotlib and pandas. Based on <a href="https://stackoverflow.com/questions/42538533/calculate-and-plot-95-range-of-data-on-scatter-plot-in-python">this a...
<p>You need to figure out if certain point are above the 95% quantile line or below the 5% quantile line. This you can do using the cross product, see <a href="https://stackoverflow.com/questions/45766534/finding-cross-product-to-find-points-above-below-a-line-in-matplotlib">this answer</a> for a straightforward implem...
python|pandas|matplotlib|statsmodels|quantile-regression
1
13,671
51,971,388
Looking for a cleaner way to implement this solution with Pandas
<p>I'm new to Pandas and trying to put together training data for a neural net problem. </p> <p>Essentially, I have 2 DataFrames:</p> <p>One DataFrame has a column for the primary_key and 3 columns for 3 different positions (sports positions, for this example assume First Base, Second Base, Third Base if you'd like)...
<pre><code>height_dict = {k:v for k, v in zip(dict_2['position_ID'], dict_2['Height'])} weight_dict = {k:v for k, v in zip(dict_2['position_ID'], dict_2['Weight'])} positions = pd.DataFrame(dict_1) positions['p1_height'] = positions['position_ID1'].map(height_dict) </code></pre> <p>Similar steps for all the 3 i...
python|pandas|dataframe
0
13,672
51,862,324
create column name repeats for column values when particular columns have duplicate rows
<p>I have a dataframe that I need to spin around (am not sure if this involves stacking or pivoting..)</p> <p>So, where I have duplicate values in columns "Year", "Month and "Group" , I want to shift the follow columns names to be repeated for the Variable </p> <p>So if this is the original DF:</p> <pre><code>Year ...
<p>IIUC, if you want to convert it back from long to wide , you can using <code>cumcount</code> get the <code>addtional</code> key , then reshape.(Notice this reverse of <code>wide_to_long</code>)</p> <pre><code>df['New']=(df.groupby(['Year','Month','Group']).cumcount()+1).astype(str) w=df.set_index(['Year','Month','G...
python|pandas|dataframe|stack|pivot
2
13,673
51,958,352
Python Looping Through Lists and Creating Dynamic Variables
<p>I am looping through elements of lists that vary in length and content. Here is the object (<code>keys</code>) that I use:</p> <pre><code>keys: key dims 1 ['site', 'channel', 'fiscal_week'] 2 ['site', 'dude', 'other', 'fiscal_week'] 3 ['site', 'eng', 'dude', 'somethin...
<p>IIUC</p> <pre><code>df=pd.DataFrame(data=yourdf.dims.values.tolist(),index=yourdf.key) df.columns+=1 df=df.add_prefix('D') df['D1'] Out[537]: key 1 site 2 site 3 site Name: D1, dtype: object df Out[538]: D1 D2 D3 D4 D5 key ...
python|list|pandas|for-loop
1
13,674
41,774,766
Reverse DataFrame Column, But Maintain the Index
<p>Consider the following</p> <pre><code>In [214]: df = pd.DataFrame(index=range(4,8), data=[33,22,11,00]) In [215]: df Out[215]: 0 4 33 5 22 6 11 7 0 </code></pre> <p>I'd like to reverse the order of the first column, but maintain the index in its current order, so <code>df</code> will look like</p> <pre...
<p>use <code>iloc</code> and slice appropriately</p> <pre><code>df.iloc[::-1] 0 7 0 6 11 5 22 4 33 </code></pre> <hr> <p>In order to preserve the index</p> <p><strong><em>use <code>iloc</code></em></strong> </p> <pre><code>df.iloc[:] = df.iloc[::-1].values </code></pre> <p><strong><em>use <code>numpy</...
python|pandas
9
13,675
64,315,905
Average of column value over all values before
<p>my dataframe looks like this:</p> <pre><code>Time Amount 2020-01-01 63 2020-01-02 200 2020-01-03 342 2020-01-04 91 2020-01-05 500 2020-01-06 200 </code></pre> <p>What I would like to do is compute the average for every row including the amounts of all the rows above.</p> <p>o...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.expanding.html" rel="noreferrer"><code>Series.expanding</code></a> with <code>mean</code> and then if necessary set <code>NaN</code> to first value:</p> <pre><code>df['new'] = df['Amount'].expanding().mean() df.loc[0, 'new'] = np.na...
python|pandas
6
13,676
64,195,264
Difference between : and , in numpy
<p>Some resources have mentioned that in <code>numpy</code>'s array slicing, <code>array[2,:,1]</code> results in the same as <code>array[2][:][1]</code> , but I do not get the same ones in this case:</p> <pre><code>array3d = np.array([[[1, 2], [3, 4]],[[5, 6], [7, 8]], [[9, 10], [11, 12]]]) array3d[2,:,1] out: array([...
<p><strong>some resources</strong> is wrong!</p> <pre><code>In [1]: array3d = np.array([[[1, 2], [3, 4]],[[5, 6], [7, 8]], [[9, 10], [11, 12 ...: ]]]) In [2]: array3d Out[2]: array([[[ 1, 2], [ 3, 4]], [[ 5, 6], [ 7, 8]], [[ 9, 10], [11, 12]]]) </code></pre> <p>When the i...
numpy|numpy-ndarray
3
13,677
64,409,948
Using a `tf.Tensor` as a Python `bool` is not allowed in Graph execution - when I do not use it as a bool
<p>That is the issue I am getting, but I don't use it as a bool anywhere. Or at least not where I can find. I have read similar questions, they were resolved because there was in fact an instance where it is being treated as a bool. However, I have not used it si a bool.</p> <p>Functions:</p> <pre><code>def compile_cnn...
<p>This was solved by adding <code>@tf.function</code> to the custom loss function:</p> <pre><code>@tf.function def contrastive_loss(label, embedding, margin = 0.4): </code></pre>
python|tensorflow|keras
0
13,678
47,622,680
TensorFlow Trained Model Predicts Always Zero
<p>I have one simple TensorFlow model and accuracy for that is 1. But when I try to predict some new inputs it always returns Zero(0).</p> <pre><code>import numpy as np import tensorflow as tf sess = tf.InteractiveSession() # generate data np.random.seed(10) #inputs = np.random.uniform(low=1.2, high=1.5, size=[500...
<p>There are multiple mistakes in your code.</p> <p>Starting with this lines of code:</p> <pre><code>correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(sess.run(accuracy, feed_dict={x: inputs, y: labels})) # print accuracy </code>...
python-3.x|tensorflow|neural-network
1
13,679
49,110,776
Creating a matplotlib multi-series line plot with pandas
<p>I want to create a multi series line plot showing how the occurrences of a data-frame element change over time:</p> <p>I have two lists in which I have joined in a dataframe:</p> <pre><code>df = pd.DataFrame( {'Date': datelist, 'Category': catlist }) </code></pre> <p>I have then grouped the dataframe to show the...
<p>You can try with:</p> <pre><code>plot_df = df.unstack('Category') plot_df.index = pd.PeriodIndex(plot_df.index.tolist(), freq='D') plot_df.plot() plt.show() </code></pre> <p>Or with <code>subplot</code>:</p> <pre><code>plot_df.plot(subplots=True) </code></pre> <p>Example: For the dataframe:</p> <pre><code>Date...
python|pandas|matplotlib|line
2
13,680
58,834,534
How to compare a list with dataframe column headers and substitute the header's name?
<p>There is a df</p> <pre><code>df_example = id city street house flat 0 NY street_ny 111 01 1 LA street_la 222 02 2 SF street_sf 333 03 3 Vegas street_vg 444 04 4 Boston street_bs 555 05 </code></pre> <p>And in a database exists a tabl...
<p>Use <code>rename</code> with dictionary created by <code>zip</code>:</p> <pre><code>df_example = df_example.rename(columns=dict(zip(df['column_name'], df['column_id']))) print (df_example) id 0 1 2 3 0 0 NY street_ny 111 1 1 1 LA street_la 222 2 2 2 SF street_sf 33...
python|pandas|list
2
13,681
58,803,538
Add missing dates to a Multiindex from a dt series
<p>Attempting to add missing datetimes to a MultiIndex. Datetimes are in a series (named 'ndx'). Simply doing this does not work:</p> <pre><code>df.reindex(index=ndx, level=0, fill_value=np.nan) </code></pre> <p>What I have:</p> <pre><code> Column1 Date Name 2016-11-01 AAA 25 B...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>DataFrame.merge</code></a> with left join, only first convert <code>MultiIndex</code> to columns:</p> <pre><code>ndx = pd.Series(pd.date_range('2016-11-01','2016-11-07')) df = ndx.to_...
python|pandas
2
13,682
58,771,477
Jitter almost duplicate rows in pandas dataframe
<p>I have a dataframe with coordinate values:</p> <pre><code>data = [ ['c', 2.2, 3.4], ['b', 2.2, 3.41], ['a', 1.05, 1.0], ['a', 2.2, 3.39], ] df = pd.DataFrame(data, columns=['T', 'x', 'y']) </code></pre> <pre><code> T x y 0 c 2.20 3.40 1 b 2.20 3.41 2 a 1.05 1.00 3 a 2.20 ...
<h3><code>scipy</code>'s <code>pdist</code></h3> <p>Please look up each of these functions to learn what they do.</p> <ul> <li><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html" rel="nofollow noreferrer"><code>scipy.spatial.distance.pdist</code></a></li> <li><a href="http...
python|pandas
1
13,683
70,044,412
How to return 3 columns above and below the specified cell in a pandas dataframe?
<p>This is my data frame. If I search for Iowa, the code should return the country name (the USA in this case) and 3 states above it (Hawaii, California, Missouri)-Iowa- and 3 below it (colorado, Alaska, texas in this case). How to do this?</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th ...
<p>Try this:</p> <pre><code>import pandas as pd # prepare the df c = ['India', '', '', '', '', '', 'USA', '', '', '', '', '', '', ''] s = ['Banglore', 'Pune', 'Delhi', 'Maharasthra', 'Hyderabad', 'Gujarat', 'Arizona', 'Hawaii', 'California', 'Missouri', 'Iowa', 'Colorado', 'Alaska', 'Texas'] df = pd.DataFrame(c,...
python|pandas|dataframe|pandas-groupby|numpy-ndarray
1
13,684
70,176,293
Numpy array: iterate through column and change value depending on the next value
<p>I have a numpy array like this:</p> <pre><code>data = np.array([ [1,2,3], [1,2,3], [1,2,101], [4,5,111], [4,5,6], [4,5,6], [4,5,101], [4,5,112], [4,5,6], ]) </code></pre> <p>In the third column, I want the value to be replaced with <code>10001</code> if the n...
<pre><code>indices_of_101 = np.where(data[:, 2] == 101)[0] if indices_of_101[0] = 0: # taking into accound boundary problem indices_of_101 = indices_of_101[1:] data[:, indices_of_101-1] = 10001 </code></pre>
python|numpy|iteration
1
13,685
56,284,107
How can I get predictions from these pretrained models?
<p>I've been trying to generate human pose estimations, I came across many pretrained models (ex. <a href="https://github.com/liruilong940607/Pose2Seg" rel="nofollow noreferrer">Pose2Seg</a>, <a href="https://github.com/leoxiaobin/deep-high-resolution-net.pytorch" rel="nofollow noreferrer">deep-high-resolution-net</a> ...
<p>Im not doing skeleton detection research, but your problem seems to be general. </p> <p>(1) I dont think other people should teaching you from begining on how to load data and run their code from begining. </p> <p>(2) For running other peoples code, just modify their test script which is provided e.g</p> <p><a ...
machine-learning|computer-vision|pytorch
1
13,686
56,276,488
Replace entire dataframe value , if the existing value starts with substring
<p>A pandas <code>dataframe</code> has values starting with keyword '<code>make</code>'. If the values starts with '<code>make</code>', then it should be replaced as value '<code>Yes</code>'. How to achieve this using <code>python 3.x</code> code.</p> <p>Thanks in advance.</p>
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer"><code>DataFrame.replace</code></a> with <code>^</code> for start of string:</p> <pre><code>df = df.replace('^make', 'Yes', regex=True) </code></pre>
python|python-3.x|pandas|dataframe
0
13,687
56,051,954
Convert a list of pandas series with the same index into a dictionary
<p>I have a list of pandas Series, each having the same index. I want to convert this list into a dictionary, where the keys are the index values (which is the same across all Series, and values is a list of values in the Series objects). Here is an example:</p> <pre><code>series_1: A 1 B 2 C 3 series_2: A 11 B 22 C ...
<p>The best performance is converting to dictionary of numpy arrays instead of dictionary of lists and using the <code>np.array</code> of the series to construct dictionary. </p> <p>Besides, if you really need dictionary of lists, using <code>dict</code> and <code>zip</code> on <code>s.index</code> and <code>np.arra...
pandas|list|series
1
13,688
55,783,617
Cannot feed value of shape (0,) for Tensor 'Placeholder_1:0', which has shape '(?, 4)'
<p>I can't seem to resolve the issue as I am new to tensorflow I think the issue is the graph mismatching but cant resolve it please help. I want to resolve this as i will be using this for android app.</p> <h1>Defining placeholders</h1> <pre><code>x = tf.placeholder(tf.float32,shape=[None,80,80,3]) y_true = tf.placeho...
<p>I'd say most likely you're feeding in the data wrong.<br> I would look at what is actually in Y, and make sure that it has the shape <code>(?,4)</code>. At each step I'd print out <code>Y[j:j+step_size]</code>.</p> <p>To fit into your graph, it would have to be an array containing sub arrays of size 4<br> e.g <cod...
python|tensorflow|conv-neural-network
0
13,689
55,923,791
Autoencoder: Decoder has not same size as encoder
<p>If I build the decoder as a mirror of encoder the output size of the last layer does not match.</p> <p>This is the model summary:</p> <pre><code>Model: "model" _________________________________________________________________ Layer (type) Output Shape Param # =======================...
<p>as you can see in <code>reshape_out (Lambda)</code> you have shape 1, so by doing operations like <code>UpSampling2</code> you can just get to size <code>2, 4, 8, 16, 32.</code> To do your way you may have to do <code>UpSampling2</code> until size <code>32</code>, then reshape by doing for instance two <code>Conv2D<...
python|tensorflow|keras|deep-learning|autoencoder
2
13,690
55,699,481
Pandas first 5 and last 5 rows in single iloc operation
<p>I need to check <code>df.head()</code> and <code>df.tail()</code> many times. When using <code>df.head(), df.tail()</code> jupyter notebook dispalys the ugly output.</p> <p>Is there any single line command so that we can select only first 5 and last 5 rows: </p> <p>something like:<br> <code>df.iloc[:5 | -5:] ?</c...
<p>Try look at <code>numpy.r_</code></p> <pre><code>df.iloc[np.r_[0:5, -5:0]] Out[358]: 0 1 0 0.899673 0.584707 1 0.443328 0.126370 2 0.203212 0.206542 3 0.562156 0.401226 4 0.085070 0.206960 15 0.082846 0.548997 16 0.435308 0.669673 17 0.426955 0.030303 18 0.327725 0.340572 ...
python|pandas
6
13,691
64,983,008
How to encode one or multiple categorical variables into one feature
<p>I am trying to train a machine learning model on some categorical data I have, however I am unsure how to encode it. If I have a table like the following, what is the best way to encode &quot;var_3&quot;?</p> <pre><code>| var_1 | var_2 | var_3 | |-------|-------|----------...
<p>You can try to encode as binary column for each attribute in var_3. So:</p> <pre><code> var1 var_2 var_3 attr_1 attr_2 attr_3 attr_4 0 32 0 'attr_1' 1 0 0 0 1 15 1 'attr_1, attr_2, attr_3, attr_4' 1 1 ...
pandas|machine-learning|scikit-learn|categorical-data
0
13,692
64,811,632
Keras custom data generator giving dimension errors with multi input and multi output( functional api model)
<p>I have written a generator function with Keras, before returning X,y from <code>__getitem__</code> I have double check the shapes of the X's and Y's and they are alright, but generator is giving dimension mismatch array and warnings.</p> <p>(Colab Code to reproduce: <a href="https://colab.research.google.com/drive/1...
<p>I had a similar issue with a custom generator that just had to pass a numpy array of size 10 as input and one single output.</p> <p>To solve this problem i had to trasform the shape of the 2 vectors passed to the neural network like this:</p> <pre><code>def slides_generator(integer_list): # stuff happens ...
python|tensorflow|keras|deep-learning|lstm
0
13,693
40,254,510
How to speed up this code with Numpy?
<p>Currently I am using the following code to convert all non-black pixels to white:</p> <pre><code>def convert(self, img): for i in range(img.shape[0]): for j in range(img.shape[1]): if img.item(i, j) != 0: img.itemset((i, j), 255) return img </code></pre> <p>How can I spe...
<p>All elements that are not 0 should change to 255:</p> <pre><code>a[a != 0] = 255 </code></pre>
python-3.x|numpy|opencv3.0
2
13,694
40,052,912
Retuning Inception Models with retrain.py
<p>I've converted the inception_v3 and inception_resnet_v2 .ckpt files found at <a href="https://research.googleblog.com/2016/08/improving-inception-and-image.html" rel="nofollow">https://research.googleblog.com/2016/08/improving-inception-and-image.html</a> to a frozen .pb file and i'm trying to use it with the tensor...
<p>these values should work:</p> <pre><code>bottleneck_tensor_name = 'InceptionResnetV2/Logits/Flatten/Reshape:0' bottleneck_tensor_size = 1536 resized_input_tensor_name = 'InputImage:0' </code></pre>
python|tensorflow
0
13,695
69,298,405
ValueError in numba vectorize for accumulate
<p>I'm trying to write a ufunc with Numba. I read <a href="https://stackoverflow.com/a/27912352/13560598">this</a> and incorporated into into my code. So, my basic code which runs is</p> <pre><code>import numpy as np arr = np.arange(15).reshape((3,5)) def myadd(x, y): return x+y myadd = np.frompyfunc(myadd, 2, 1) pri...
<p>I figured adding signature and removing dtype will resolve the error.</p> <p>I dont have exact answer as to why adding signature works. But hope this will get things running and help you find answer. (My opinion, arr is of int type and myadd wants float....not sure)</p> <pre class="lang-py prettyprint-override"><cod...
python-3.x|numpy|vectorization|numba|numpy-ufunc
1
13,696
41,037,650
How to restore session in tensorflow?
<p>I want to use my neural network without training the net again. I read about </p> <pre><code>save_path = saver.save(sess, "model.ckpt") print("Model saved in file: %s" % save_path) </code></pre> <p>and now I have 3 files in the folder: <code>checkpoint</code>, <code>model.ckpt</code>, and <code>model.ckpt.meta</c...
<p>To save the model you can do like this:</p> <pre><code>model_checkpoint = 'model.chkpt' # Create the model ... ... with tf.Session() as sess: sess.run(tf.initialize_all_variables()) # Create a saver so we can save and load the model as we train it tf_saver = tf.train.Saver(tf.all_variables()) # ...
python|machine-learning|tensorflow
2
13,697
41,188,901
Swap columns of an ndarray
<p>I am trying to swap two columns from a 2d array such that</p> <pre><code>a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) </code></pre> <p>becomes:</p> <pre><code>b = array([[1, 3, 2], [4, 6, 5], [7, 9, 8]]) </code></pre> <p>How can I do that?</p>
<p>This would do it:</p> <pre><code>b = a[:, [0, 2, 1]] </code></pre> <p>It works by providing a <code>list</code> of column indices in the second-dimension position. As always in Python, the indices are zero-based, so the first (leftmost) column is 0 and the third (rightmost, last) column is 2.</p>
python|numpy|multidimensional-array
6
13,698
65,971,597
Pandas filter grouped data and aggregate
<p>I want to group data in a <code>DataFrame</code>, filter out outliers in each group (e.g. quantile(0.95)) and then aggregate the results for each group.</p> <p>I tried to do it like this:</p> <pre><code>import pandas as pd import numpy as np dff = pd.DataFrame({&quot;A&quot;: np.arange(8), &quot;B&quot;: list(&quot...
<p>This could be done by grouping again on &quot;B&quot;. Note that to do this the index will need to be reset (with <code>drop = True</code> to avoid duplicating &quot;B&quot; in the dataframe), or the <code>groupby</code> function will produce an error stating that &quot;B&quot; is both an index level and a column la...
python|pandas
1
13,699
66,225,863
Merge on multiindex
<p>How do I merge 2 multi-index dataframes? I get the error below.</p> <pre><code>df1 cola_df1 colb_df1 Fruit 1/1/20 2 3 1/2/20 4 5 Apple 1/1/20 8 9 1/2/20 10 11 df2 cola_df2 colb_df2 Fruit 1/1/20 2 3 ...
<p>First is possible upgrade pandas? Because if using changed sample data like bellow I got different error if using your solution:</p> <pre><code>df = pd.concat([df1,df2], keys=['x','y'], axis=1).swaplevel(0,1,axis=1).sort_index(axis=1) print (df) </code></pre> <blockquote> <p>ValueError: Reindexing only valid with un...
python|python-3.x|pandas
2