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
349,700
59,648,370
Is there a way to convert a grayscale image array into a Tensor to feed to a model
<p>I'm a real starter in machine learning. But I'm trying to deploy the MNIST character recognition example with a Flask server. I already set up the model, trained it and set up Flask.</p> <p>I've created a simple HTML canvas where I can draw numbers from 0-9. These are sent via AJAX to my python backend. </p> <p>In...
<p>Here is some code that should work.</p> <pre><code>import numpy as np import tensorflow as tf data = [138, 102, 160, 120, 54, 173, 105, 214, 173, 106, 41, 154, 129, 239, 233, 158, 6, 218, 177, 238, 184, 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 1, 144, 0, 0, 1, 144, 8, 6, 0, 0, 0, 128, 191...
python|tensorflow|keras
0
349,701
59,506,486
Format text alignment within Bokehs HoverTool/tooltips - Python
<p>I have the hover function on in Pandas Bokehs.</p> <p>How do I justify the text to the left hand side of the box rather than the right? See the <a href="https://i.stack.imgur.com/HJOiV.png" rel="nofollow noreferrer">attached image</a></p> <p>This is my current code for my tooltips</p> <pre><code>tooltips=[('Time'...
<p>The basic convenience auto-tooltip always and only ever formats as shown in the image. If you want something more sophisticated, you would use a <a href="https://docs.bokeh.org/en/latest/docs/user_guide/tools.html#custom-tooltip" rel="nofollow noreferrer">custom tooltip</a>, which allows you to supply a small HTML t...
python|pandas|bokeh
3
349,702
59,635,570
Keras backend K.switch for loss function error
<p>I want to implement a custom loss function in keras using keras.backend.switch for a conditional statement, I get this error and really do not know how to solve it, '''</p> <pre><code>from keras import backend as K #q_low and q_high are parameters def quantile_loss(q_low,q_high, y_p, y): e = y_p-y loss_lo...
<p>Looking at <a href="https://www.tensorflow.org/api_docs/python/tf/keras/backend/switch?version=stable" rel="nofollow noreferrer">the documentation for switch</a> we can see that this ValueError occurs when the rank of condition is greater than rank of expressions. As far as I know, switch works by checking the value...
tensorflow|keras|deep-learning|switch-statement|backend
1
349,703
59,763,844
Sum column values based on part of index names in dataframe
<p>I have the following dataframe which is the result of a groupby operation.</p> <pre><code>Gender F M Grade letter D NaN 1.0 D+ 7.0 2.0 C- 3.0 2.0 C 3.0 4.0 C+ 9.0 12.0 B- 8.0 10.0 B 6.0 3.0 B+ 5.0 7.0 A- ...
<p>You can aggregate <code>sum</code>, also for first letter is possible omit <code>.to_series()</code>:</p> <pre><code>df1 = df.groupby(df.index.str[0], sort=False).sum() print (df1) F M Gender D 7.0 3.0 C 15.0 18.0 B 19.0 20.0 A 10.0 8.0 </code></pre>
python|pandas
4
349,704
59,592,290
Optimized way for multiple conditions on pandas dataframe columns value
<p>I am applying multiple filters on a dataframe at the same time.</p> <pre><code>data_df[(data_df['1']!=0) &amp; (data_df['2']==0) &amp; (data_df['3']==0) &amp; (data_df['4']==0) &amp; (data_df['5']==0)] </code></pre> <p>I needed to know is there any optimized way to do this? As I want to compare one column's value ...
<p>Based on the below statements:</p> <blockquote> <p>Looking for a short and optimized method</p> </blockquote> <p>and</p> <blockquote> <p>I want to compare one column's value as !=0 and others value as =0</p> </blockquote> <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pand...
pandas|dataframe
2
349,705
59,689,389
numpy.nan_to_num - 'nan' keyword not recorgnized
<p>When you try to replace nan value with a custom numeric value using following code,</p> <pre><code>np.nan_to_num(exp_allowance,nan=9999.99) </code></pre> <p>it produces following error:</p> <pre><code>typeerror: nan_to_num() got an unexpected keyword argument 'nan' </code></pre>
<p>After going through several blogs and no answers to it, I discovered that I was using obsolete numpy version.This specific argument is only supported in numpy version 1.17 and above. Those who are facing this issue, check your numpy version:</p> <pre><code>import numpy numpy.version.version </code></pre> <p>if it...
python-3.x|numpy
12
349,706
59,663,326
Why replace doesn't work (doesn't replace the values)
<p>I'm using python <code>3.6.8</code> and <code>pandas</code>.</p> <p>I'm loading csv file and tying to replace strings in one of the colums with other strings.</p> <pre><code>import pandas as pd INPUT_FILE = "input.csv" df = pd.read_csv(INPUT_FILE, error_bad_lines=False, engine='python') print(df.columns) print ("...
<p>Because in keys of dictionary are used special regex values is possible escape them before replace and also add <code>regex=True</code> for subtrings replacement:</p> <pre><code>import re dic = {re.escape(k):v for k, v in dic.items()} print (dic) {':\\-\\)': 'happy-smiley', ':\\)': 'happy-smiley', ':\\-\\(...
python|pandas
2
349,707
59,632,905
Numpy fancy indexing resulting in selection with different shape
<p>From the following snippet:</p> <pre><code>&gt;&gt;&gt; palette = np.array( [ [0,0,0], # black ... [255,0,0], # red ... [0,255,0], # green ... [0,0,255], # blue ... [255,255,...
<p>Because your mask (in this case the array <code>image</code>) is an array with a shape <code>(2,4)</code>. Each element picked by the mask is 1d array with <code>3</code> elements. So, <code>brush</code> will have the shape <code>(2,4,3)</code>.</p> <p>This might help you see the shape of the array <code>brush</cod...
numpy
1
349,708
59,769,447
How to get the first smallest 5 values in a python Ndarray and get their position in the ndarray
<p>i can't still figure out how to do this the best possible way with less code, i have a Ndarray called X : array([0.5 , 2 , 3.2 , 0.16 , 3.3 , 10 , 12 , 2.5 , 10 , 1.2 ]) and i want somehow to get the smallest 5 values with their position in X as in i want ( 0.5 , 0.16 , 1.2, 2 ,2.5 ) and to know that they are the f...
<p>You can use <code>ndarray.argpartition</code>:</p> <pre><code>X = np.array([0.5 , 2 , 3.2 , 0.16 , 3.3 , 10 , 12 , 2.5 , 10 , 1.2 ]) n = 5 arg = X.argpartition(range(n))[:n] print(arg) # [3 0 9 1 7] print(X[arg]) # [0.16 0.5 1.2 2. 2.5 ] </code></pre>
python|arrays|numpy|multidimensional-array|numpy-ndarray
2
349,709
59,814,655
Problem converting a saved_model.pb file to .tflite file with custom shapes
<p>I am using Tensorflow 2 on Windows 10 and I download a model from <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md" rel="nofollow noreferrer">TensorFlow Detection Model Zoo.</a></p> <p>The model I am using is <strong>ssd.mobilenetv2.oid4</strong></p> ...
<p>Currently tensorflow Lite doesn't support converting dynamic shape except for first dimension. Consider setting the exact shape instead of 'None'</p>
tensorflow2.0|tensorflow-lite
0
349,710
59,875,172
TypeError when trying to use EarlyStopping with f1-metric as stopping criterion
<p>I want for training a CNN with Early Stopping and want to use the f1-metric as stopping criterion. When I compile the code for the CNN model I get the a <code>TypeError</code> as error message. I'm still using Tensorflow 1.4 would like to avoid an upgrade to 2.0, because I have in mind that my previous code doesn't...
<p>As the error message suggests, </p> <p><strong>Error 1)</strong> You are doing a len() operation on symbolic tensor. You cannot do that operation on symbolic tensor. You can find difference between a variable tensor and symbolic tensor <a href="https://stackoverflow.com/questions/60338842/how-to-print-value-of-tens...
tensorflow|keras|conv-neural-network|metrics|early-stopping
0
349,711
59,490,619
Creating an interactive plot with pandas and ipywidgets, using values from dataframe column as inputs
<p>I have a Pandas dataframe which lists a number of companies, the number of consumer complaints which they have received within the month, and the month when they were received:</p> <p><a href="https://i.stack.imgur.com/kLX99.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kLX99.png" alt="Company ...
<p>I have figured out a way to (kind of) achieve it, although ideally I would like that 'column' dropdown to not be visible:</p> <p><a href="https://i.stack.imgur.com/Dkj75.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dkj75.png" alt="Possible solution"></a></p>
python|pandas|matplotlib|ipywidgets
2
349,712
59,537,390
How to seemlessly blend (B x C x H x W) tensor tiles together to hide tile boundaries?
<p>For completeness this is a text summary of what I am trying to do:</p> <ol> <li>Split the image into tiles.</li> <li>Run each tile through a new copy of the model for a set number of iterations.</li> <li>Feather tiles and put them into rows.</li> <li>Feather rows and put them back together into the original image/t...
<p>You are looking for <a href="https://pytorch.org/docs/stable/nn.functional.html#unfold" rel="nofollow noreferrer"><code>torch.nn.functional.unfold</code></a> and <a href="https://pytorch.org/docs/stable/nn.functional.html#fold" rel="nofollow noreferrer"><code>torch.nn.functional.fold</code></a>. These functions allo...
python|image-processing|pytorch|tensor|tile
1
349,713
59,714,605
python vtk tube filter returns empty array
<p>I am trying to use the vtkTubeFilter object to get a tube around a line of points. As I have my own specialized rendering code, I want to get the vertices directly, not just the filter object. I am trying the following to convert between <code>numpy</code> arrays and the VTK data structures</p> <pre><code>field = v...
<p>With <a href="https://github.com/marcomusy/vtkplotter" rel="nofollow noreferrer">vtkplotter</a>:</p> <pre class="lang-py prettyprint-override"><code>from vtkplotter import Tube center_line = [ [-36.78, 19.78, -37.82], [-37.65, 20.04, -35.89], [-38.85, 20.39, -32.84], ...
python|numpy|type-conversion|vtk
1
349,714
59,650,246
Dataframe group by value, remove duplicates, but save non similar entries? Python
<p>Is there a way to scan through a dataframe in python to create a new dataframe that groups by a certain column, removes duplicates, while simultaneously saving none-similar entries, say into a list?</p> <p>So if I have a dataframe that looks something like this...</p> <pre><code>Genre Rating CustomRating Thr...
<p>You can do <code>groupby</code> and then <code>agg</code>:</p> <pre><code>df.groupby('Genre', sort=False).agg(lambda x: list(set(x))).reset_index() </code></pre> <p>and you'll get</p> <pre><code> Genre Rating CustomRating 0 Thriller [5] [5] 1 Comedy [9] [9] 2 Action [2, 3] ...
python|pandas|dataframe
5
349,715
59,734,555
Create pandas dataframe from multiple part-dataframes
<p>I'm trying to create a Pandas dataframe that is created of multiple smaller dataframes. All dataframes got the same Index variable but sometimes have different coloums, wich should be added if non existent.</p> <p>So basically a join (outer i guess) would be the right thing. But instead of creating a new column in ...
<pre><code>pd.concat([A,B,C]) </code></pre> <p>does this work for you?</p>
python|pandas
0
349,716
59,691,434
How can I add a record for each missing date per entity (multiple categorical fields), and forward fill added entries from a value field?
<p>For each plant/product, I would like to add a record for each missing date within a date range. The range is based on the min/max dates regardless of Plant/Product. Then, for each Plant/Product, I would like to forward fill the Qty for each new record. </p> <p>Here's a sample of the my initial pandas dataframe. I...
<p>Convert <code>Date</code> column to datetime dtype. The <code>unstack</code> and <code>stack</code> solution could be adapted to double <code>unstack</code> as follows</p> <pre><code>df['Date'] = pd.to_datetime(df['Date']) df_filled = (df.set_index(['Date', 'Plant', 'Product'])['Qty'] .unstack([1,2]...
python|pandas
1
349,717
59,665,876
Fast Approach to add rows for all dates between two columns in Dataframe
<p>I need a fast approach to add rows for all the dates between two columns. I have already tried the following approaches:</p> <p>df.index.repete: <a href="https://stackoverflow.com/questions/54128640/add-rows-for-all-dates-between-two-columns">add rows for all dates between two columns?</a></p> <p>pd.melt: <a href...
<p>Calendrical calculation (<code>pd.date_range</code>) is a lot slower than generating a sequence of integers (<code>np.arange</code>). The answers you listed are pretty simple &amp; elegant, but they are not very fast. Your volume of data calls for a different solution.</p> <p>This answer assumes that <code>ID</code...
python|pandas
1
349,718
59,722,493
Compare two classes with range of Marks
<p>I have a dataframe with two classes (A or B) and marks and I want to present the mark ranges per class.</p> <p>Dataframe:</p> <pre><code>Class Mark Department A 74.0 1 A 73.0 2 B 72.0 1 A 75.0 1 B 64.0 2 </code></pre> <p>What I want to achieve:</p> <pre><code>Class Mark Range...
<p>We can use <code>GroupBy.apply</code> and get the <code>max</code> and <code>min</code> per group and represent them as string with <code>f-strings</code>:</p> <pre><code>df = ( df.groupby('Class')['Mark'].apply(lambda x: f'{x.min()}-{x.max()}') .reset_index(name='Mark Range') ) Class Mark Range 0 A ...
python-3.x|pandas|group-by
3
349,719
59,830,876
Syntax error while trying to build dataframe in python
<p>I am trying to create a function in python 3 that builds a dataframe from a csv file. However, I keep getting a syntax error when I call</p> <pre><code>y = (data_df["Status"].replace("underperform",0).replace("outperform",1).values.tolist()) </code></pre> <p>This line of code is not running, because I never actual...
<p>You're missing a closing parenthesis in your <code>X = np.array(data_df[features].values#.tolist())</code> - it's there, but it's commented out of the code with the # sign.</p> <p>Your python interpreter does not know that you actually wanted to end that line there and continues to search for a closing parenthesis....
python|pandas|csv|dataframe
1
349,720
59,797,059
Find first day of the month previous to a random date with Pandas pd.DateOffset
<p>I want to find the first day of a given month an average 90 days previous to a random date. For instance:</p> <p>December 15 -- returns August 30<br> December 30 -- returns August 30<br> December 1st -- returns August 30 </p> <p>I know this can be done with <code>Pandas</code> pd.DateOffset:</p> <pre><code>print...
<p>Assume that the date in question is:</p> <pre><code>dat = pd.Timestamp('2019-12-15') </code></pre> <p>To compute the date 90 days before, run:</p> <pre><code>dat2 = dat - pd.DateOffset(days=90) </code></pre> <p>getting <code>2019-09-16</code>.</p> <p>And finally, to get the start of this month, run:</p> <pre><...
python|pandas
1
349,721
59,900,638
Removing rows in csv using Python
<p>I have a column called <strong>key_resp_5_rt</strong> and in it I would like to remove any rows that are under 300ms (it is a reaction time column)</p> <pre><code>for filename in files: try: df=pd.read_csv(filename) df['key_resp_5.rt'] </code></pre> <p>Can someone tell me if this code underneath can remov...
<p>You need to assign the return value to the same variable again in order to replace it. This does not happen in-place:</p> <pre class="lang-py prettyprint-override"><code>df = df[df['key_resp_5.rt'] &gt; 0.3] </code></pre>
python|python-3.x|pandas
0
349,722
59,755,220
What is the best way to crop a scene from a numpy array of 3D points. I.e. find points in point cloud that lay within certain bounds
<p>this question might be phrased way more convoluted than it is, since I am rather sure the solution is rather generic. </p> <p>The Situation is as follows. We are given a numpy array of (n, 3), where n is the number of points specified in 3D coordinates (x,y,z). I now want to produce a slice of this array, that cont...
<p>You can use <code>np.where</code> to analyse multiple comparisons like so:</p> <p>import numpy as np</p> <pre><code>a = np.array([[0, 0, 0], [1, 2, 3], [6, 7, 7], [9, 0, 0], [0, 9, 0], [0, 0, 9], [-10, 0, 0]]) print(a[(a[:, 0] &lt...
python|arrays|numpy|coordinates|slice
1
349,723
59,604,623
C++ library with Tensorflow on Android
<p>I'm trying to build a native C++ library for the Android app. This lib uses Tensorflow C++ API (version 1.9.0 and 1.10.0) and OpenCV(3.3.0) inside. For generating wrapper I'm using Swig. I'm using Android NDK to build *.so files (I've tried with different versions of the NDK versions 10, 14, 15, 17). I've built *.a ...
<p>I had this problem before, it's the poop library</p>
android|c++|tensorflow|android-ndk|tensorflow-android
-2
349,724
59,671,679
Extract number frollowing a specific string with special chars in a large text file using python
<p>I have large data files (CSV type) that I read with pandas. Each files has a information column that has many names and numbers seperated by ;. Below how this column looks like:</p> <pre><code>0 Acid: 74.1 [°C];LeakRate [Bar/Min]: 103 ;P: ... 1 Acid: 73.9 [°C]; LeakRate [µBar/Min]: 371 ; ... 2 Acid: 73...
<p>This sounds like you want to figure out the column index beforehand.</p> <p>This could be done as:</p> <pre class="lang-py prettyprint-override"><code>firstRow = ... leakRateCols = [i for i, val in enumerate(firstRow["Information"].str.split(";")) if 'LeakRate' in val] if len(leakRateCols) &gt; 1: # Raise some ...
python|pandas|csv
0
349,725
59,840,411
Error with keras using TensorFlow as backend
<p>I'm at the beginning of my project and I've just imported the packages that I need:</p> <pre><code>from keras.models import Sequential from keras.layers import Dense </code></pre> <p>Obviously both TensorFlow and keras are already installed. Anyway, if I run the code I get this error:</p> <pre><code>Using TensorF...
<p>You may want to try keras which comes with tensorflow. This keras uses only tensorflow as backend, which is what you need:</p> <pre><code>import tensorflow as tf from tf.keras import Sequential from tf.keras.layers import Dense </code></pre> <p>Reference: <a href="https://www.tensorflow.org/guide/keras/overview" r...
python|python-3.x|tensorflow|keras
0
349,726
59,737,875
Keras: change learning rate
<p>I'm trying to <strong>change</strong> the learning rate of my model after it has been trained with a different learning rate.</p> <p>I read <a href="https://github.com/keras-team/keras/issues/888" rel="noreferrer">here</a>, <a href="https://github.com/keras-team/keras/issues/898" rel="noreferrer">here</a>, <a href=...
<p>You can change the learning rate as follows:</p> <pre><code>from keras import backend as K K.set_value(model.optimizer.learning_rate, 0.001) </code></pre> <p>Included into your complete example it looks as follows:</p> <pre><code>from keras.models import Sequential from keras.layers import Dense from keras import...
python|tensorflow|keras
46
349,727
59,770,565
Replace comma with semicolon when creating Csv Dataframe
<p>I have a code that creates a csv file, when I first open it I everything is in one column so I have to do the usual</p> <p>Go to Data and do the following. The data is then spplited into columns.</p> <p><a href="https://i.stack.imgur.com/DtVOv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/...
<p>If you already want to transform an existing file you can do it like that:</p> <pre><code>with open('created.csv', 'r', encoding='utf-8') as f_in, open("outfile.csv", 'w') as f_out: for line in f_in: line = line.split(",") line = ";".join(line) f_out.write(line) </code></pre> <p>In case...
python|pandas|csv
2
349,728
59,901,247
Get the count of elements in column of arrays based on commas and turning the count into its own column
<p>I have a dataframe in which one of the columns outputs the following when I ask for unique values (I was originally thinking of manually mapping the counts if there were less combinations):</p> <pre><code>df.amenities.unique() </code></pre> <pre><code>array(['{TV,Wifi,Kitchen,Elevator,Heating,Washer,"First aid kit...
<p>As your sample, counting <code>','</code> plus one and assign it to new column</p> <pre><code>df['amenities_count'] = df.amenities.str.count(',').add(1) Out[1274]: Apt Counties amenities amenities_count 0 S1 C1 {TV, "Kitchen", "WiFi"} 3 1 S1 C1 ...
python|pandas|numpy|dataframe
2
349,729
59,617,755
Training a BERT-based model causes an OutOfMemory error. How do I fix this?
<p>My setup has an NVIDIA P100 GPU. I am working on a Google BERT model to answer questions. I am using the SQuAD question-answering dataset, which gives me questions, and paragraphs from which the answers should be drawn, and my research indicates this architecture should be OK, but I keep getting OutOfMemory errors d...
<p><strong>Edit</strong>: I have edited my response in place rather than increasing the length of the already long response.</p> <p>After looking at the issue rises from the final layer in your model. And I was able to get it to work with the following fixes/changes.</p> <blockquote> <p>ResourceExhaustedError: OOM ...
python|tensorflow|keras
9
349,730
59,570,956
How to make conditional statements in Tensorflow
<p>I am using Tensorflow 1.14.0 and trying to write a very simple function that includes conditional statements for Tensorflow. The regular (non-Tenslorflow) version of it is:</p> <pre><code>def u(x): if x&lt;7: y=x+x else: y=x**2 return y </code></pre> <p>It seems that I cannot use this d...
<p>This is a bug in TF (Related Github issue: <a href="https://github.com/tensorflow/tensorflow/issues/32106" rel="nofollow noreferrer">Here</a>). For example, the following scenarios work</p> <h1>What works</h1> <h2>Changing <code>tf.Variable</code> to <code>tf.constant</code></h2> <pre><code>x=tf.constant(3,name='...
python|tensorflow
1
349,731
59,804,286
How to return index of a row 60 seconds before current row
<p>I have a large (>32 M rows) Pandas dataframe. In column 'Time_Stamp' I have a Unix timestamp in seconds. These values are not linear, there are gaps, and some timestamps can be duplicated (ex: 1, 2, 4, 6, 6, 9,...). I would like to set column 'Result' of current row to the index of the row that is 60 seconds before ...
<p>So with the precious help of ALollz, I managed to achieve what i wanted to do in the end, here's my code:</p> <pre><code>#make copy of dataframe df2 = df[['Time_Stamp','Value']].copy() #add Time_gap to Time_Stamp in df2 df2['Time_Stamp'] = df2.Time_Stamp +Time_gap #sort df2 on Time_Stamp df2.sort_values(by = 'Time...
python-3.x|pandas|dataframe
1
349,732
59,670,011
How to plot local variable of loop using Plotly
<p>I am working on a .csv file. I write script to split sub-columns of <strong>column y</strong> on the basis of ";" and only print the values of a. The code is correctly printing the desired values. <strong>I want to plot the values stored in var (i.e.=23,21,25,12,18,91,21) by using plotly.</strong> I am attaching ...
<p>I took a closer look at your issue, look out for your dataset, the following line is faulty: <code>lifelock a=25;b=2.c=0 USD</code> (a dot appeared instead of a semicolon).</p> <p>Here is a version of what I guess you were attempting:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd # ...
python|pandas|plotly
0
349,733
32,368,895
Slicing Pandas DataFrame with an array of integers specifying location
<p>I have two Pandas DataFrames, one where each column is a cumulative distribution (all entries between <code>[0,1]</code> and monotonically increasing) and second with the values associated to each cumulative distribution.</p> <p>I need to access the values associated to different points in the cumulative distributi...
<p>try this:</p> <pre><code>df1.values[spots, [0, 1]] </code></pre>
python|arrays|numpy|pandas
1
349,734
32,557,858
How to add strings as a new column to Pandas Dataframe?
<p>Let say I have a dataframe, 3 rows, index and 1 column and separate 3 strings. How can I add those strings as a 2nd column to existing dataframe?</p> <p>I have: dataframe and 3 strings</p> <pre><code>1 Qwe 2 Asd 3 Zxc s1 = Poi; s2 = Lkj; s3 = Mnb </code></pre> <p>I want:</p> <pre><code>1 Qwe Poi 2 Asd Lkj 3 Zxc...
<pre><code>dataframe['new_col'] = [s1,s2,s3] </code></pre>
python|pandas
3
349,735
32,399,461
Remove tuples in a 2D numpy array that satisfy 2 conditions
<p>So I have a numpy array of tuples and I want to remove all tuples where the first value is less than 0 or the second element is greater than a number, n.<br> So if n = 10 and we had this array:</p> <p><code>[[-1, 5], [3, 11], [-4, 20]]</code></p> <p>It would become this:</p> <p><code>[[]]</code></p> <p>I'm guess...
<p>You can use something like the following:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; A = np.array([[-1, 5], [3, 11], [-4, 20]]) &gt;&gt;&gt; mask = (A[:,0]&gt;0) &amp; (A[:,1] &gt; 10) &gt;&gt;&gt; A[mask] array([[ 3, 11]]) </code></pre> <p>The idea is to express your condition using an expression...
python|arrays|numpy
1
349,736
32,439,264
Processing a select range of values in a numpy array
<p>Suppose I have a 5x5 array:</p> <pre><code>import numpy as np arr = np.random.rand(5,5) </code></pre> <p>If i want to sum the entire array I can simply have:</p> <pre><code>np.sum(arr) </code></pre> <p>How would i go about summing the values in a box defined by the upper left corner (2,2) and lower right corner ...
<p>Use slicing like this:</p> <pre><code>import numpy as np arr = np.random.rand(5,5) # Top left 2*2 grid np.sum(arr[:2, :2]) </code></pre> <p>To sum the array in your diagram, use:</p> <pre><code>np.sum(arr[1:4, 1:3]) </code></pre>
python|numpy
6
349,737
32,291,922
Pandas - understanding output of pivot table
<p>Here is my example:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'Student': ['A', 'B', 'B'], 'Assessor': ['C', 'D', 'D'], 'Score': [72, 19, 92]}) df = df.pivot_table( index='Student', columns='Assessor', values='Score', aggfunc=lambda x: x) print(df) </code></pre> <p>The ou...
<p><a href="http://pandas.pydata.org/pandas-docs/version/0.16.2/reshaping.html#pivot-tables-and-cross-tabulations" rel="nofollow"><code>pivot_table</code></a> finds the unique values of the index/columns and aggregates if there are multiple rows in the original <code>DataFrame</code> in a particular cell.</p> <p>Index...
pandas|pivot-table
0
349,738
32,242,869
initialising class with numpy.ndarray attribute
<p>I'm trying to define a wrapper class having an attribute of type <code>numpy.ndarray</code>. That attribute must be initialised by calling <code>__init__()</code>.</p> <p>The script runs as expected for 1D arrays. However, in the case of multi-dimensionnal arrays, python returns the following error : <code>only len...
<p>If you just want to have an attribute of type <code>ndarray</code> is there any specific reason you inherit from it?</p> <p>I'd say that by subclassing <code>ndarray</code> and overriding <code>__init__</code> you're messing with numpy's initialisation process, thus generating the error you're seeing.</p> <p>See t...
python|class|numpy|multidimensional-array
1
349,739
32,554,673
Combine dataframe values based on repeated index labels
<p>I've got a single-column dataframe with an index of integers represented as strings that has repeated values in it. The values are integers and I would like to have a dataframe with an index with no repeats in it and whose values are the sum of all the values that originally had the given index label. Here's a sampl...
<p>Try resetting your index and then using <code>groupby</code>:</p> <pre><code>verts = pd.Series([54, 34, 33, 28, 23, 22, 15, 15, 15, 9, 2, 1, 1, 1], index=["3", "3", "0", "4", "4", "2", "2", "5", "5", "0", "1", "6", "1", "6"]) &gt;&gt;&gt; verts.reset_index().groupby('index').sum() 0 inde...
python|pandas
2
349,740
32,567,270
Assigning color on Creating Stacked Column chart with xlsxwriter Pandas Python
<p>I was successfully able to generate Stacked Column charts in the newly created Excel sheet using pandas dataframe with xlsxwriter of Python Pandas. But, I can't figure out how to assign color yet. </p> <p>Here is the picture. <a href="https://i.stack.imgur.com/OgoSb.png" rel="nofollow noreferrer"><img src="https...
<p>You need to set the <code>fill</code> color for the series.</p> <p>See the following Pandas-XlsxWriter <a href="http://pandas-xlsxwriter-charts.readthedocs.org/en/latest/chart_stacked_column_farms.html" rel="nofollow">stacked charts with colors example</a>. The example uses brew colors but you can replace those wit...
python|pandas|xlsxwriter
0
349,741
32,348,170
Pandas describe() behaviour for numeric dtypes
<p>The output of the function DataFrame.describe() depends on the datatype.</p> <p>When used on a numeric dtype, it will return the following output:</p> <pre><code>f.ID.describe() count 7583.000000 mean 704013.191613 std 1192979.985253 min 10575.000000 25% 10575.000000 50% 10864...
<p>I'd be somewhat inclined to just do as you did and convert to strings on the fly to get your desired output. I don't think the performance penalty is going to be very severe and doubt you are going to be using <code>describe()</code> often enough for that to matter anyway.</p> <p>That said, it is worth thinking ab...
python|python-3.x|pandas
1
349,742
32,198,019
Python numpy: Dimension [0] in vectors (n-dim) vs. arrays (nxn-dim)
<p>I'm currently wondering how the numpy array behaves. I feel like the dimensions are not consistent from vectors (<code>Nx1</code> dimensional) to 'real arrays' (<code>NxN</code> dimensional).</p> <p><strong>I dont get, why this isn't working:</strong></p> <pre><code>a = array(([1,2],[3,4],[5,6])) concatenate((a[:,...
<p>There are two overall issues here. First, <code>b</code> is <em>not</em> an <code>(N, 1)</code> shaped array, it is an <code>(N,)</code> shaped array. In numpy, 1D and 2D arrays are different things. 1D arrays simply have no direction. Vertical vs. horizontal, rows vs. columns, these are 2D concepts.</p> <p>The...
python|arrays|numpy
2
349,743
32,403,285
Applying pandas Timestamp() call to each item of a numpy array
<p>I have a numpy array which is composed of numpy.datetime64 values. I'd like to convert these to pandas Timestamps using pandas.Timestamp(). </p> <p>I could do an explicit for-loop like</p> <pre><code>import numpy as np import pandas as pd stamps = [pd.Timestamp(t) for t in my_arr] </code></pre> <p>but this isn't ...
<p>If my_arr is a numpy ndarray, I would suggest doing :</p> <pre><code>my_arr.astype(pd.Timestamp) </code></pre> <p>That would create a copy of the array and cast it to the type you want.</p>
python|arrays|numpy|pandas
2
349,744
40,643,639
Creating numpy array from list gives wrong shape
<p>I'm creating several numpy arrays from a list of numpy arrays, like so:</p> <pre><code>seq_length = 1500 seq_diff = 200 # difference between start of two sequences # x and y are 2D numpy arrays x_seqs = [x[i:i+seq_length,:] for i in range(0, seq_diff*(len(x) // seq_diff), seq_diff)] y_seqs = [y[i:i+seq_length,:] f...
<p>The items in <code>x_seqs</code> vary in length. When they are all the same length, <code>np.array</code> can make a 3d array from them; when they differ it makes an object array of lists. Look at the <code>dtype</code> of <code>x_test</code>. Look at the <code>[len(i) for i in x_test]</code>.</p> <p>I took your...
python|numpy|machine-learning
4
349,745
40,577,730
When does pandas output a series vs a dataframe?
<p>I'm working on the pandas tutorial at <a href="https://github.com/brandon-rhodes/pycon-pandas-tutorial/blob/master/Exercises-3.ipynb" rel="nofollow noreferrer">https://github.com/brandon-rhodes/pycon-pandas-tutorial/blob/master/Exercises-3.ipynb</a>. It has exercises on the <code>cast</code> dataframe, a sample of w...
<p>If you pass a list of columns, you get a DataFrame. It doesn't matter how many elements the list has. It would be confusing if it returned a Series just in the case of a one-item list, because sometimes your list might be programmatically generated. For instance, suppose you had:</p> <pre><code>columns_to_use = ...
python|pandas|dataframe
1
349,746
40,704,161
How to calculate averages and SEM in a multi-indexed pandas dataframe?
<p>I have some data in a pandas dataframe which has a triple multi-index: </p> <pre><code>Antibody Time Repeats Customer_Col1A2 0 1 0.657532 2 0.639933 3 0.975302 5 1 0.628196 2 0.66...
<p>You can group by the level of multi-index by specifying the <code>level</code> parameter, and calculate the average and SD using <code>DataFrame.mean()</code> and <code>DataFrame.std()</code> methods correspondingly:</p> <pre><code>df1.groupby(level=[0,1]).agg({'avg': 'mean', 'sd': 'std'}) </code></pre> <p><a href...
python|pandas|multi-index
2
349,747
40,760,561
Testing accuracy 0.5 TensorFlow RNN variable length strings
<p>After having adapted the following code that you find in the link at the end of the post, that is, reading from the variable length strings file with alphabet 0-1 and ability to set the number of layers through <code>LSTMCell</code> and <code>MultiRNNCell</code> I get a value of accuracy 0.5.</p> <p>In particular, ...
<p>It is difficult to answer this question without more information. I will address each parameter independently from a general point of view:</p> <ul> <li>n_classes: from your description I understand that you are solving a binary classification problem. Therefore, n_classes=2.</li> <li>seq_max_len denotes the maxima...
tensorflow|artificial-intelligence|deep-learning|recurrent-neural-network|lstm
0
349,748
40,647,203
Copy column with a length greater than the column where I want to place the data - python Pandas
<p>I have 2 .csv files, let's say files A and B, one of the columns in file 'A' has 7 things, like this:</p> <pre><code>ID 12 23 23 12 23 23 23 </code></pre> <p>I want to copy this whole column and paste it into file 'B' in column 'ID'. File B contains 2 rows of hard coded data like this:</p> <pre><code>CODE ID SSN...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow noreferrer"><code>drop</code></a> for removing column <co...
pandas|dataframe|copy|multiple-columns
1
349,749
40,535,572
Pandas series manipulation - change x and y
<p>I have a <code>pandas.core.series.Series</code> object <code>x</code> that outputs the following when I do <code>print x</code>:</p> <pre><code>2 681 1 575 3 573 4 381 0 340 </code></pre> <p>How can I change <code>x</code> to <code>x2</code> so that <code>print x2</code> outputs:</p> <pre><cod...
<p>You can use <code>Series</code> constructor, if necessary can add parameter <code>name</code>:</p> <pre><code>print (pd.Series(x.index, index=x.values)) 681 2 575 1 573 3 381 4 340 0 dtype: int64 print (pd.Series(x.index, index=x.values, name='a')) 681 2 575 1 573 3 381 4 340 0 Name: ...
python|pandas
2
349,750
40,711,347
How to replace inf in a numpy array with zero
<p>I am trying to eliminate an inf from a pandas DataFrame, caused by a division by zero. I have tried several techniques using both DataFrame and ndarray structures:</p> <pre><code>df_fund['dly_retn'].replace(np.inf, 0) na_fund['dly_retn'].replace(np.inf, 0) na_dly_retn(~isfinite(na_dly_retn))=0 </code></pre> <p>Tak...
<p>You have to save the operation in your dataframe. One way is to use the parameter <code>inplace=True</code>:</p> <pre><code>df_fund['dly_retn'].replace(np.inf, 0, inplace=True) na_fund['dly_retn'].replace(np.inf, 0, inplace=True) </code></pre>
pandas
19
349,751
40,690,598
Can Keras with Tensorflow backend be forced to use CPU or GPU at will?
<p>I have Keras installed with the Tensorflow backend and CUDA. I'd like to sometimes on demand force Keras to use CPU. Can this be done without say installing a separate CPU-only Tensorflow in a virtual environment? If so how? If the backend were Theano, the flags could be set, but I have not heard of Tensorflow f...
<p>If you want to force Keras to use CPU</p> <h2>Way 1</h2> <pre><code>import os os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152 os.environ["CUDA_VISIBLE_DEVICES"] = "" </code></pre> <p>before Keras / Tensorflow is imported.</p> <h2>Way 2</h2> <p>Run your script as</p> <pre><code>$ CUDA_VISIBLE_...
python|machine-learning|tensorflow|keras
116
349,752
40,497,102
Adding new operations in Tensorflow using an approach different from tutorial
<p>Here is a tutorial about <a href="https://www.tensorflow.org/versions/master/how_tos/adding_an_op/index.html" rel="nofollow noreferrer">how to add a new operation in TensorFlow</a>. It talks about how to create a shared object and load it in python.</p> <p>However, there are some operations, which located in core/k...
<p>The core operators are in <code>_pywrap_tensorflow.so</code>. If you plan on contributing to the core, that's where they would go. Typically, though, we would first accept them into the <code>contrib</code> directory, then at a later stage move into the core. It's best to file a <a href="https://www.github.com/tenso...
python|machine-learning|tensorflow
2
349,753
40,683,391
Pandas outer merge two versions of the same DataFrame
<p>I want to merge two dataframes that look like this:</p> <pre><code>In[14]: test1=pd.DataFrame({'col1':[1,2,3, 6,4,5], 'col2':['First','Second','Third', 'Sixth','Fourth','Fifth']}) test1 Out[14]: col1 col2 0 ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> followed by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer"><code>drop_duplicates</code></a>...
python|pandas|merge
2
349,754
40,392,892
Convert retrained data into .pb format for ios camera example?
<p>I retrained image data using the tutorial at ((<a href="https://www.tensorflow.org/versions/r0.9/how_tos/image_retraining/index.html" rel="nofollow noreferrer">https://www.tensorflow.org/versions/r0.9/how_tos/image_retraining/index.html</a>)) I did all the steps until </p> <blockquote> <p>bazel build tensorflow/e...
<p>I believe it's a two step process.</p> <ol> <li><p>Export model definition and weights:</p> <p>a. The graphdef (*.pb) using tf.train.write_graph: <a href="https://www.tensorflow.org/versions/r0.11/api_docs/cc/index.html" rel="nofollow noreferrer">https://www.tensorflow.org/versions/r0.11/api_docs/cc/index.html</a>...
ios|tensorflow
1
349,755
40,337,466
Toy example of training on my own dataset in TensorFlow
<p>I am trying to create a toy example of training a small network on my own images. The network is identical with <a href="https://www.tensorflow.org/versions/r0.11/tutorials/mnist/pros/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.11/tutorials/mnist/pros/index.html</a></p> <p>And this is the code...
<p><code>filename_queue=tf.train.string_input_producer(filenames)</code> build a queue with your filenames. So you should start the queue before calling : </p> <p><code>image_batch_eval, label_batch_eval=image_batch.eval(), label_batch.eval()</code>.</p> <p>Just add before :</p> <pre><code>tf.train.start_queue_runne...
tensorflow
0
349,756
40,679,586
Using Seaborn to plot time series dataframe
<p>I am trying to plot a pandas data frame that looks like below using Seaborn:</p> <pre><code>Date | Size | Volatility |Liquidity |Value |Growth |Medium-Term Momentum Leverage |Exchange Rate Sensitivity 2015-12-01 |0.544913 |0.148974 |0.054775 |0.022000 |0.017445 |0.016755 -0.036878 ...
<p>As you can see on the <a href="http://seaborn.pydata.org/installing.html#installing" rel="nofollow noreferrer">Seaborn installation page</a>, matplotlib is a mandatory dependency of seaborn. </p> <p>In fact, seaborn (at the most basic level) merely changes the default style of matplotlib plots, so won't work withou...
pandas|data-visualization|seaborn
1
349,757
40,664,182
pandas fill created sheet row by row
<p>I have the following python code</p> <pre><code>sheet_a = pd.read_excel(open('c:\\upload\\' + f,'rb'), skiprows=1, sheetname='a') sheet_b = pd.read_excel(open('c:\\upload\\' + f,'rb'), skiprows=1, sheetname='b') </code></pre> <p>Within these two sheets, I have two columns that I am creating from scratch, <code>Tea...
<p>This should work:</p> <pre><code>In [1]: import pandas as pd In [2]: df = pd.DataFrame({'First Name': ['Harry', 'Hermione'], 'Last Name': ['P ...: otter', 'Granger']}) In [3]: df Out[3]: First Name Last Name 0 Harry Potter 1 Hermione Granger In [4]: df['Full Name'] = df['First Name'] + ' ' + df[...
python|pandas
3
349,758
40,431,547
Constructing an SQL query with a list of variable length with sqlalchemy and pandas in python
<p>I would like to construct a SQL statement with an <code>IN</code> operator that works on a list of arbitrary length. I am working with python, pandas, and sqlalchemy. </p> <p>For example, If the query I'd like to execute is</p> <pre><code>SELECT * FROM users WHERE age IN (25, 26, 27)" </code></pre> <p>I have trie...
<p>Consider a dynamic SQL string build for the placeholders and a dynamic dictionary build using dictionary comprehension for the parameters. Below assumes your RDMS is SQLite with the colon named parameters:</p> <pre><code>import pandas as pd from sqlalchemy.sql import text ages = (25, 26, 27) placeholders = ', '.jo...
python|sql|pandas|sqlalchemy
1
349,759
40,627,467
How to replace specific punctuation with new name?
<p>My data sample is:</p> <pre><code> comment sarc_majority 0 [?, ?] sarc 1 [0] non-sarc 2 [!, !, !] sarc 3 [0] non-sarc 4 [?] sarc </code></pre> <p>I want to replace the punctuation with a new name. Such as ? = punct1, ! = punct2, '...
<p>Most punctuation characters have a special meaning in regular expressions. Here you end up with, eg: <code>\b?\b</code>, which means an optional boundary followed by a boundary. Not what you meant.</p> <p>For passing arbitrary strings into a regexp, it must be escaped using <a href="https://docs.python.org/3/librar...
python|pandas
1
349,760
40,383,100
regarding caffe to tensorflow
<p>Currently, there are a lot of deep learning models developed in Caffe instead of tensorflow. If I want to re-write these models in tensorflow, how to start? I am not familiar with Caffe structure. It seems to me that there are some files storing the model architecture only. My guess is that I only need to understand...
<p>I have already asked <a href="https://stackoverflow.com/questions/37572948/extracting-weights-from-caffemodel-without-caffe-installed-in-python">a similar question</a>. </p> <p>To synthetise the possible answers : </p> <ol> <li><p>You can either use pre-existing tools like <a href="https://github.com/ethereon/ca...
tensorflow|deep-learning|caffe
3
349,761
40,745,954
How to train images in CNN with Tensorflow
<p>I am a beginner of TensorFlow, and I am trying to build to CNN model. Here is the sample code I refer to: <a href="https://github.com/MorvanZhou/tutorials/blob/master/tensorflowTUT/tf18_CNN3/full_code.py" rel="nofollow noreferrer">https://github.com/MorvanZhou/tutorials/blob/master/tensorflowTUT/tf18_CNN3/full_code....
<pre><code> image_batch = tf.train.batch([resized_image], batch_size=100) </code></pre> <p>This is the main problem. When you are inserting image into input queue, you did not specify the label together with it. </p> <p>If you look at Tensorflow tutorial example, <a href="https://github.com/tensorflow/tensorflow/b...
tensorflow|conv-neural-network
0
349,762
40,393,501
How many neurons are going into each layer of VGG?
<p>Can you give me a run down of how many neurons are going into each layer. I feel this will improve my understanding of what is going on in VGG.</p> <p>Let's use this code here just to have something concrete. </p> <p><a href="https://github.com/machrisaa/tensorflow-vgg/blob/master/vgg19.py#L46" rel="nofollow noref...
<p>The debug information you posted is the dimensions for the outputs of each op/layer. It's related to the number of "neurons", but it is not the same.</p> <h2>Where do the output dimensions come from?</h2> <p>There's only two types of layers in VGG-19 (excluding softmax and fully connected):</p> <ul> <li><strong>C...
tensorflow|machine-learning|conv-neural-network|vgg-net
2
349,763
40,573,311
How to find which input value in a loop yielded the output min?
<p>I am trying to solve a min value problem, I could obtain the min values from two loops but, what I really need is also the exact values that correspended to output min.</p> <pre><code>from __future__ import division from numpy import* b1=0.9917949 b2=0.01911 b3=0.000840 b4=0.10175 b5=0.000763 mu=1.66057*10**(-24) #...
<p>The big advantage of numpy over using python lists is <em>vectorized operations</em>. Unfortunately your code fails completely in using them. For example the whole inner loop that has <code>Z</code> as index can easily be vectorized. You instead are computing the single elements using python <code>float</code>s and ...
python|numpy
1
349,764
40,686,167
Slice the data for each unique id in python
<pre><code>id val a 1 a 1 a 2 a 2 a 1 a 2 a 2 b 1 b 1 b 2 b 2 b 1 b 1 b 2 b 2 b 3 </code></pre> <p>I am trying to slice the data for each <code>id</code> and based on length of <c...
<p>You can create a <code>subgroup</code> variable which denotes a different group for every four rows and then you can group by both <code>id</code> and <code>subgroups</code> variable and analyze each group separately:</p> <pre><code>df['subgroups'] = df.groupby('id').cumcount() // 4 for _, g in df.groupby(['id', '...
python|loops|pandas|slice
1
349,765
40,635,435
Rolling window Pandas
<p>I need to create a dataset out of my time series which contains samples made out of rolling, overlapping windows. That is, to split my dataframe with a certain window size and a certain step.</p> <p>How to do this using Pandas? I see that there is a rolling window, but it is used to perform some aggregations over t...
<p>I don't think there is a any pandas function that would help you. A simple implementation is:</p> <pre><code>A = pd.DataFrame(index=range(1,10), data=['a','b','c','d','e','f','g','h','i'], columns=['letters']) step = 2 size = 3 n_examples = len(A) dataframes = [] k=0 while(k *...
python|pandas
0
349,766
40,592,449
Pandas dataframe average truly unique values
<p>I'm working with a number of measurementsets, each measurementset contains two values: the datetime and the temperature. Example:</p> <pre><code># measurement 1: time | value 00:00:00 | 10.1 00:00:10 | 10.12 00:00:20 | 10.14 00:00:30 | 10.12 00:00:40 | 10.11 00:00:50 | 10.13 # measurement 2: time | value 0...
<p>To get the value1, value2 and value3 on the same col, I used:</p> <pre><code>df = pd.concat([df1, df2, df3]) </code></pre> <p>The example below looks like yours:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'Time': ['00:00:00', '00:00:10', '00:00:20', '00:00:30', '00:00:40', '00:00:50'], ...
python|pandas|join|merge
0
349,767
40,361,282
How to get nd array from np.where() in python?
<p>My problem has different moving objects. We calculate distance between these objects in different time frame.</p> <p>I have a nd array <strong>A</strong> with shape <strong>(a,b)</strong> which stores distances. a is the number of fames and b is the number of coordinates on which this distance is calculated.</p> <...
<p>I just did some minor edits from your code and here's the result:</p> <pre><code>A = np.array([[1,2,2,6],[3,4,5,1],[3,1,17,4],[2,3,1,5]]) L = [('cat','dog'),('lion','elephant'),('man','women'),('fish','shark')] list_to_array = np.array(L) array_of_names_meeting_criteria = list_to_array[np.where(A==1)[1]] </code></p...
python|arrays|python-3.x|numpy
0
349,768
40,696,158
How to mask with 3d array and 2d array numpy
<p>How do you select a group of elements from a 3d array using a 1d array. </p> <pre><code>#These are my 3 data types # A = numpy.ndarray[numpy.ndarray[float]] # B1 = numpy.ndarray[numpy.ndarray[numpy.ndarray[float]]] #B2=numpy.ndarray[numpy.ndarray[numpy.ndarray[float]]] #I want to choose values from A based on value...
<p>Here's a vectorized approach with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.reduceat.html" rel="nofollow noreferrer"><code>np.add.reduceat</code></a> -</p> <pre><code>idx = np.argwhere((B == A[:,None,None]).all(-1)) B2_indexed = B2[idx[:,1],idx[:,2]] _,start, count = np.unique(idx[:,...
python|numpy
0
349,769
40,773,842
Pandas - assign histogram bucket to each row
<p>Here is my dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame({'A': [1, 2, 3, 4, 6, 4, 3, 2, 7]}) buckets = [(0,3),(3,5),(5,9)] </code></pre> <p>I also have histogram buckets stated above. Now I would like to assign each row of dataframe to buckets index. So I would like to get new column with the fol...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow noreferrer"><code>pd.cut</code></a>, with <code>labels=False</code> if you only want the index:</p> <pre><code>buckets = [0,3,5,9] df['bucket'] = pd.cut(df['A'], bins=buckets) df['bucket_idx'] = pd.cut(df['A'],...
python|performance|pandas|histogram|vectorization
3
349,770
18,567,268
Numpy division error
<p>I get <code>Numpy Operands could not be broadcast together with shape (200,1,25,25) (200,1)</code> <strong>error</strong> by the division of two array with the following dimention</p> <pre><code>a=numpy.ones((200,1,25,25)) b=numpy.ones((200,1)) c=a/b </code></pre> <p><strong>But I can get the right result with the...
<p>The second example doesn't do what you think it does. Numpy matches up axes for broadcasting starting from the right; <code>(25, 25)</code> gets matched up with <code>(200, 1)</code> in the first example and fails to broadcast, but <code>(4, 4)</code> matches up with <code>(4, 1)</code> and broadcasts successfully.<...
python|numpy
3
349,771
18,367,877
Change subplot color in DataFrame?
<p>I would like to change color of individual subplot:<br> 1. Specifying desired color of plots by hand<br> 2. Using random colors </p> <p>Basic code (taken from <a href="http://pandas.pydata.org/pandas-docs/dev/visualization.html" rel="nofollow noreferrer">1</a>)</p> <pre class="lang-py prettyprint-override"><code> ...
<p>You can easlity do this by providing the <code>style</code> parameter with a list of color abbrevations:</p> <pre><code>from pandas import Series, DataFrame, date_range import matplotlib.pyplot as plt import numpy as np ts = Series(np.random.randn(1000), index=date_range('1/1/2000', periods=1000)) ts = ts.cumsum()...
python|matplotlib|pandas
5
349,772
18,677,429
Elegant way to print formatted list together with index values in python?
<p>While there are a few questions and answers out there which come close to what I am looking for, I am wondering if there isn't a more elegant solution to this specific problem: I have a numpy (2D) array and want to print it row by row together with the row number up front - and of course nicely formatted.</p> <p>Th...
<p>You can convert the numpy array to a list with <code>tolist()</code> first.</p> <pre><code>for i in range(2): print fmt % tuple([i] + A[i].tolist()) </code></pre> <p>The reason for your error is that extending a list yields no return value. </p> <pre><code>&gt;&gt;&gt; x = range(5) &gt;&gt;&gt; x.extend([5, ...
python|numpy|formatting|pretty-print
1
349,773
18,359,671
Fastest method to create 2D numpy array whose elements are in range
<p>I want to create a 2D numpy array where I want to store the coordinates of the pixels such that numpy array looks like this</p> <pre><code>[(0, 0), (0, 1), (0, 2), ...., (0, 510), (0, 511) (1, 0), (1, 1), (1, 2), ...., (1, 510), (1, 511) .. .. .. (511, 0), (511, 1), (511, 2), ...., (511, 510), (511, 511)] </co...
<p>Can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.indices.html"><code>np.indices</code></a> or <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html"><code>np.meshgrid</code></a> for more advanced indexing:</p> <pre><code>&gt;&gt;&gt; data=np.indices((512,512)).sw...
numpy|range
12
349,774
18,702,105
Parameters to numpy's fromfunction
<p>I haven't grokked the key concepts in <code>numpy</code> yet.</p> <p>I would like to create a 3-dimensional array and populate each cell with the result of a function call - i.e. the function would be called many times with different indices and return different values.</p> <p><strong><em>Note: Since writing this ...
<p>The documentation is <em>very</em> misleading in that respect. It's just as you note: instead of performing <code>f(0,0), f(0,1), f(1,0), f(1,1)</code>, numpy performs </p> <pre><code>f([[0., 0.], [0., 1.]], [[1., 0.], [1., 1.]]) </code></pre> <p>Using ndarrays rather than the promised integer coordinates is quite...
python|arrays|numpy
50
349,775
61,659,439
python time stamp convert to datetime without a year specified
<p>I have a csv file of a years worth of time series data where the time stamp looks like the code insert below. One thing to mention about the data its a <em>30 year averaged hourly weather data, so there isnt a year specified</em> with the time stamp.</p> <pre><code>Date 01-01T01:00:00 01-01T02:00:00 01-01T03:00:00 ...
<p>You can pass <code>date_parser</code> argument (<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer">check docs</a>), e.g.</p> <pre><code>import pandas as pd from datetime import datetime df = pd.read_csv('weather_cleaned.csv', index_col='Date', parse_...
python|pandas|python-datetime
1
349,776
61,953,760
Bokeh showing empty diagramm
<p>Hey guys so I have the problem that when I try to run my Code that my created diagram is empty. So I dont see my temperature and my time date.</p> <p>If it helps here is my database: <code>id hum temp time date<br> 1 59 18 10:03:06 2020-05-16<br> ...
<p>Are you not getting an error? because it looks like you did not import <code>pandas</code> at all.. </p>
python|pandas|bokeh|pandas-bokeh
0
349,777
61,920,265
python3: Split time series by diurnal periods
<p>I have the following dataset:</p> <pre><code>01/05/2020,00,26.3,27.5,26.3,80,81,73,22.5,22.7,22.0,993.7,993.7,993.0,0.0,178,1.2,-3.53,0.0 01/05/2020,01,26.1,26.8,26.1,79,80,75,22.2,22.4,21.9,994.4,994.4,993.7,1.1,22,2.0,-3.54,0.0 01/05/2020,02,25.4,26.1,25.4,80,81,79,21.6,22.3,21.6,994.7,994.7,994.4,0.1,335,2.3,-3....
<p>You can use <code>pd.cut</code>:</p> <pre><code>bins = [-1,5,11,17,24] labels = ['morning', 'afternoon', 'evening', 'night'] df['day_part'] = pd.cut(df['hour'], bins=bins, labels=labels) </code></pre>
python-3.x|pandas|numpy
1
349,778
61,663,400
DLL load failed _multiarray_unmath when importing numpy
<p>I installed Numpy v. 1.18.4 and Python 3.8. These are the latest as of 5/2020 I think. I get the error:</p> <pre><code>Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troublesho...
<p>This happens when you launch VS Code outside of Anaconda Navigator.</p>
numpy
1
349,779
61,928,756
matplot:problem displaying labels in matplotlib
<p>I am trying to graph multiple lines in <a href="https://matplotlib.org/" rel="nofollow noreferrer">matplotlib</a>.</p> <p>I have used to the label function but it is not displaying it. </p> <p>Here is my code.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np from matplotli...
<p>You need to add the following command after plotting</p> <pre><code>plt.legend() </code></pre>
python|pandas|matplotlib
0
349,780
61,662,237
How to print sample records from tf.dataset?
<p>I have a tensorflow dataset called imdb. How can I print top 5 records of this dataset (including header)? I am looking for something similar to <code>dataframe.head()</code> in pandas. Some of the datasets can have images as well.</p> <pre><code> import tensorflow_datasets as tfds imdb, info = tfds.load("imdb...
<p>Assuming you have eager execution enabled, this will show the first five examples:</p> <pre><code>for x in imdb['train'].take(5): print(x) </code></pre>
python|tensorflow|tensorflow2.0
3
349,781
61,675,121
TensorFlow 2.1 with NVidia GPU returning Warnings and Errors on: missing libraries, NUMA, Convolution operation
<p>I ma trying to train a Neural Network in <code>tensorflow 2.1.0</code>. I have installed all the necessary software to configure my NVidia RTX 2070 GPU. In fact, when I type: <code>tf.test.is_gpu_available()</code> I get <code>True</code>.</p> <p>However, this is what started to happened to me when I <code>import t...
<h2>1) Cannot dlopen some TensorRT libraries.</h2> <p>You either did not install the TensorRT libraries (they are independent from Tensorflow and CUDA and offer some specific - and optional - acceleration capabilities. You can safely ignore this for now, look into how to install the libraries (on <a href="https://www....
python|tensorflow|gpu
1
349,782
61,986,165
Create feature columns from a single column of lists
<p>I have a df that has a column whose values are either: np.nan or a variable length list of strings.</p> <p>Simply put, what I want is exactly the same as the accepted answer here (from <code>@Emre</code>): <a href="https://datascience.stackexchange.com/questions/11797/split-a-list-of-values-into-columns-of-a-dataf...
<p>If you are on <code>pandas</code> 0.25+, you can use <code>explode</code>:</p> <pre><code>df = pd.DataFrame({ 'Text': [['a','b','c'], ['b','c','d'],np.nan] }) new_df = (df.Text.explode() .groupby(level=0).value_counts() .unstack(fill_value=0) .reindex(df.index, fill_value=0) ) ret = df.join(new_df) <...
python-3.x|pandas|numpy
0
349,783
61,674,033
pytrend.interest_over_time() - what does the value returned represent? 100s of searches, 1000s of seaches, 100,000s of searches?
<p>Edit: Found the answer - posted below:</p> <p>I'm using pytrend.interest_over_time() to get the number of google searches for 'fires near me' during the Australian Bushfire season. I'm trying to find out what the value returned represents. EG - first row below for 30 Nov 2019, shows 7. Is this 700, 7000, 70,000,...
<p>From Google Trends website:</p> <p>Interest over time</p> <p>Numbers represent search interest relative to the highest point on the chart for the given region and time. A value of 100 is the peak popularity for the term. A value of 50 means that the term is half as popular. A score of 0 means there was not enough ...
python|pandas|google-trends
2
349,784
61,712,916
Convert floats to ints of a column with numbers and nans
<p>I'm working with Python 3.6 and Pandas 1.0.3.</p> <p>I would like to convert the floats from column "A" to int... This column has some nan values.</p> <p>So i followed this <a href="https://stackoverflow.com/questions/57656860/pandas-convert-objects-with-numbers-and-nans-to-ints-or-floats">post</a> with the soluti...
<p>Your problem is that you have <em>true</em> float numbers, not integers in the float form. So for safety reasons pandas will not convert them, because you would be obtained <strong>other</strong> values.</p> <p>So you need first <em>explicitely round them to integers,</em> and only then use the<code>.astype()</code...
python-3.x|pandas|dataframe
3
349,785
61,829,407
Use Object detection model as feature extractor
<p>I have mask-rcnn model that was trained using Object Detection API to detect some objects. Now I have other task that needs to do regression on those images (and also other features). Is is possible to use the trained mask-rcnn model as feature extractor (similarly to how transfer learning works) and change the las...
<p>Mask r-cnn creates a shared feature map which is used for predictions on the RPN regions. With some slight tweaking to the object detection API, you could pull out the tensor containing the features for a given region. Normally these features are used for the box/mask prediction but you could use it for whatever els...
tensorflow|machine-learning|object-detection-api|transfer-learning
1
349,786
61,964,521
TensorFlow 2 documentation for graph-mode
<p>When I check the TensorFlow documentation (<a href="https://www.tensorflow.org/api_docs/python/" rel="nofollow noreferrer">Python API docs</a> or <a href="https://www.tensorflow.org/guide" rel="nofollow noreferrer">guides</a>), it all seems exclusively for eager-mode. Almost all the examples don't even mention this....
<p>Graph mode in TensorFlow 2 is different from graph mode in TensorFlow 1. Instead of using sessions and placeholders, TensorFlow 2 uses functions annotated with <a href="https://www.tensorflow.org/api_docs/python/tf/function" rel="nofollow noreferrer">tf.function</a>. The eager mode examples you see can be executed i...
tensorflow|tensorflow2.0
2
349,787
61,833,301
Error on tensorflow cannot import name 'export_saved_model'
<p>I keep getting this error when importing tensorflow as tf with the below error text:</p> <blockquote> <p>ImportError: cannot import name 'export_saved_model' from 'tensorflow.python.keras.saving.saved_model'</p> </blockquote> <p>Code used is simply:</p> <pre><code>import tensorflow as tf </code></pre> <p>I h...
<p>Uninstalling and install again worked for me. </p> <pre><code>conda activate tf pip uninstall -y tensorflow-gpu pip install tensorflow-gpu </code></pre> <p>However, am still looking for the cause of this error. It was working just a few minutes ago but suddenly I have faced this error.</p>
python|tensorflow
2
349,788
61,837,481
Pandas, how to calculate mean values of the past n years for every month
<p>I have a dataframe with data for 20 years with the time as datatime index.</p> <p><strong>EDIT</strong></p> <p><code>Time value<br> 1999-01-01 00:00:00 7 1999-01-01 01:00:00 4 1999-01-01 02:00:00 9 1999-01-01 03:00:00 4 1999-01-01 04:00:00 2 ... 2018-12-31 19:00:00 8 2018...
<p>Groupby can certainly do the trick. Here is another approach using <code>stack</code> and <code>unstack</code> to achieve vectorization, </p> <pre><code>(df.set_index(['Year', 'Month'])['value'] # set up indexed-series .unstack('Month') # reshape into matrix .rolling(3) ...
python|pandas|time-series
0
349,789
61,674,380
Numpy elementwise greater (for each element in another array)
<p>I struggle to write find the best "question" so please feel free to suggest another title.</p> <p>Lets say I have <code>a=np.array([5,3,2,4])</code> and <code>b=np.array([1,2])</code> - I want to get a list of list (or np.arrays) with the value of <code>a&gt;b[i]</code> i.e it can be written as a list comprehension...
<p>You can use <code>numpy</code> broadcasting for this, you just need to add an extra dimension into each of your arrays:</p> <pre><code>&gt;&gt;&gt; a[None,:] &gt; b[:,None] array([[ True, True, True, True], [ True, True, False, True]]) </code></pre>
python|numpy|list-comprehension
4
349,790
61,991,541
Graphing a normal distribution with panda rolling standard deviations?
<p>I am trying to take the distribution of a dataframe based on the rolling standard deviations.</p> <p>I though about using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.count.html" rel="nofollow noreferrer">pd.count</a>, but then I realized that it didn't allow for a changing s...
<p>I found a better way of doing this, using the zscore:</p> <pre><code>data['zscore'] = (data['Adj Close'] - data.ma) / data.stan_dev bins = [-3, -2, -1, 0, 1, 2, 3] cut_df = pd.cut(data.zscore, bins=bins) ax = cut_df.value_counts(sort=False, normalize=True) * 100 ax.plot.bar() plt.show() </code></pre>
python|python-3.x|pandas|matplotlib|statistics
0
349,791
61,903,137
Gridding/binning data
<p>I have a dataset with three columns: lat, lon, and wind speed. My goal is to have a 2-dimensional lat/lon gridded array that sums the wind speed observations that fall within each gridbox. It seems like that should be possible with groupby or cut in pandas. But I can't puzzle through how to do that.</p> <p>Here is ...
<p>It sounds like you are using pandas. Are the data already binned? If so, something like this should work</p> <pre><code>data.groupby(["lat_bins", "lon_bins"]).sum() </code></pre> <p>If the lat and lon data are not binned yet, you can use <code>pandas.cut</code> to create a binned value column like this</p> <pre><...
pandas|pandas-groupby|python-xarray|gridding
0
349,792
61,647,870
Dataframe Column is not Read as List in Lambda Function
<p>I have a dataframe which contains list value, let us call it df1:</p> <pre><code>Text ------- ["good", "job", "we", "are", "so", "proud"] ["it", "was", "his", "honor", "as", "well", "as", "guilty"] </code></pre> <p>And also another dataframe, df2:</p> <pre><code>Word Value ------------- good 7.47 proud 8....
<p>Giving the first df1, and df2 with <code>explode</code> and <code>map</code> , Notice <code>explode</code> is after pandas 0.25</p> <pre><code>#import ast #df1.Text=df1.Text.apply(ast.literal_eval) #If the list is string type , we need bring the format list back with fast s=df1.Text.explode().map(dict(zip(df2.Wor...
pandas|function|dataframe|lambda|apply
1
349,793
61,741,331
Tensorflow Estimator Hook access to features labels passed to model_fn and graph operations built during model_fn
<p>I am trying to understand a model built with the tensorflow Estimator framework. I'd like to use the Hooks API to add ops that process the input during evaluation, or prediction. </p> <p>It seems I should be able to leave the <code>model_fn</code> used during training alone, and implement my own <code>SessionRunHoo...
<p>I would suggest you looking at <code>TF Serve</code> for predictions. You can use the provided gRPC/REST API to call your saved model to get the prediction.</p> <p>And, you can perform any required pre-processing before you generate the JSON request for REST call. This example from TF covers <code>Serve</code>: <a...
tensorflow|tensorflow-estimator
0
349,794
61,891,990
How to load .npy files from different directories in tensorflow data pipeline from a list containing filenames?
<p>I am trying to load numpy array (x, 1, 768) and labels (1, 768) into tf.data. my code is as below:</p> <pre><code>import pandas as pdb import pdb import numpy as np import os, glob import tensorflow as tf #from tensorflow import keras from tensorflow.keras import layers, initializers from tensorflow.keras.layers i...
<p>The function passed to <code>dataset.map</code> will be traced and executed as a Tensorflow graph. The arguments passed to the function will be <code>Tensor</code>s. That is why you get the </p> <pre class="lang-py prettyprint-override"><code>TypeError: expected str, bytes or os.PathLike object, not Tensor </code><...
python|tensorflow|keras|tensorflow2.0|tensorflow-datasets
3
349,795
62,026,570
Error: Failed to compile fragment shader. while slice() with Tensorflow.js
<p>I am developing a web application for image classification using <strong>Tensorflow.js</strong>. I take an image with my <strong>webcam</strong> and I want to <strong>extract</strong> a part of the image using the coordinates of a bounding box that I previously got. The bounding box structure is : <code>[x, y, width...
<p>Instead of using Tensors, why not just use Canvas directly if you want to crop the image? </p> <p>Remove all the tf.browser.fromPixels stuff and instead pass canvas to function that holds the drawn image, and then take a crop of that. Eg:</p> <p>Use the method getImageData with bounding box data:</p> <pre><code>v...
javascript|tensorflow|tensorflow.js
1
349,796
61,923,715
Python - the best way to create a new dataframe from two other dataframes with different shapes?
<p>Essentially, I'm trying to build a new dataframe from two others but the situation is a little complicated and I'm not sure what the best way to do this is. </p> <p>In DF1, each row is data about objects defined by IDs, and it looks something like this:</p> <pre><code>ID Name datafield1 datafield2 1 Foo inf...
<p>Check if below lines can help you to add columns from DF1 to new frame, I have taken frame through excel you can use your own way...data used is displayed in image</p> <pre><code>import pandas as pd df1 = pd.read_excel('frame1.xlsx') df2 = pd.read_excel('frame2.xlsx') df = pd.merge(df2, df1[['ID','datafield1','dat...
python|pandas|dataframe
0
349,797
61,779,537
Sort numpy data by array of indices (both data and indices may contain `np.nan`!)
<p>I want to reorganize this array </p> <pre><code>values = np.array([[-0.00127687, -0.0384767 , -0.99925868], [-0.16354917, 0.075218 , 0.98366352], [-0.64543092, 0.75546703, -0.11264323], [ nan, nan, nan], [ ...
<p>A solution to this is to initalize an array of <code>nan</code>s and then copy the values into the new array only at the positions where the value in the <code>order</code> array is valid and not <code>nan</code>.</p> <pre><code>result = np.empty_like(values) result[:] = np.nan valid_indices = ~np.isnan(order) resu...
python|arrays|performance|numpy|nan
0
349,798
61,938,155
Problem with using inner-join to merge two dataframes
<p>I have the following code below:</p> <pre><code>universitytowns = pd.merge(houses,unitowns,how='inner',on=['State','RegionName']) </code></pre> <p>However, my output is:</p> <pre><code>Empty DataFrame Columns: [State, RegionName, 2000q1, 2000q2, 2000q3, 2000q4, 2001q1, 2001q2, 2001q3, 2001q4, 2002q1, 2002q2, 2002...
<p>It's working for me. Are you sure the 2 dataframes have a common <code>state</code> and <code>RegionName</code>. I just modified the <code>unitowns</code> dataframe to include New York and New York and it worked, or there might be some extra characters, space, etc.</p> <pre><code>universitytowns = pd.merge(houses,u...
python|pandas|dataframe|join|merge
1
349,799
61,883,831
How to create a new column based on Date Values & Condition in Pandas dataframe
<p>Table 1:</p> <p>Item Type Order Date Ship Date Purchase Cost</p> <p>0 Example 2014-08-10 2014-08-10 850.7544</p> <p>1 Snacks 2014-08-10 2014-08-10 NaN</p> <p>2 Cosmetics 2/22/2015 2/22/2015 ...
<p>I assume that all "date" columns have been converted to <em>datetime</em> type. Otherwise start from converting them.</p> <p>Generate an auxiliary <em>Series</em>:</p> <pre><code>wrk = pricing.assign(year=pricing['Start Date'].dt.year)\ .drop_duplicates(subset=['Item', 'year'])\ .set_index(['Item', 'year']...
python|pandas|dataframe|numpy
0