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
368,400
72,607,739
applying a function to a pair of pandas series
<p>Suppose I have two series:</p> <pre><code>s = pd.Series([20, 21, 12] t = pd.Series([17,19 , 11] </code></pre> <p>I want to apply a two argument function to the two series to get a series of results (as a series). Now, one way to do it is as follows:</p> <pre><code>df = pd.concat([s, t], axis=1) result = df.apply(lam...
<p>There are many ways to do what you want.</p> <p>Depending on the function in question, you may be able to apply it directly to the series. For example, calling <code>s + t</code> returns</p> <pre><code>0 37 1 40 2 23 dtype: int64 </code></pre> <p>However, if your function is more complicated than simple ari...
python|pandas|numpy
4
368,401
72,704,311
Merging pandas dataframes to fill in the gaps
<p>Have been struggling with this for a bit today. I've got a master dataframe that is missing some values, and a secondary one that has these values which I would like to add in. The key to match on is column 1.</p> <pre><code>d1 = {1:['Test','Test1','Test2'], 2:['A','B','C']} d2 = {1:['Something','Test','Test1','Test...
<p>You can use a <code>map</code> and <code>fillna</code>:</p> <pre><code>df2[2] = df2[2].fillna(df2[1].map(df1.set_index(1)[2])) </code></pre> <p>Output:</p> <pre><code> 1 2 3 0 Something z Blah 1 Test A Blah 2 Test1 B Blah 3 Test2 C Blah 4 Test3 x Blah 5 Test4 y Bl...
python|pandas
1
368,402
72,721,618
geopandas read_file function causes ImportError
<p>I just got a new computer and after downloading the newest version of the anaconda distribution I tried to install geopandas and run my script. However, the gpd.read_file command causes an ImportError. I have been trying to reinstall everything but nothing changed. Does anybody know how to figure this out?</p> <pre>...
<p><a href="https://github.com/Toblerity/Fiona/issues/1043#issuecomment-1025197010" rel="nofollow noreferrer">git issue comment</a></p> <p>python -m pip install git+https://github.com/Toblerity/Fiona.git</p> <p>working for me</p>
python|geopandas|fiona
0
368,403
72,516,622
Cannot set tensor: Dimension mismatch
<p>I'm a little new to Tensor Flow and would like to understand why the following codes does not accept my input and how to resolve it. Prior to this, I was using <code>mode_save</code> but I have now converted this model to TFLite and would like to use it to predict the category of the inputted text.</p> <p>I first lo...
<p>Your input tensor is the wrong size. The <a href="https://www.tensorflow.org/api_docs/python/tf/lite/Interpreter#sample_execution" rel="nofollow noreferrer">docs</a> show that your input data should be of shape <code>1,1</code>:</p> <pre><code>input_data = tf.constant(1., shape=[1, 1]) interpreter.set_tensor(input['...
python|python-3.x|tensorflow
1
368,404
72,532,094
Interpolation for 3D surface
<p>I have my data in an ndarray of size 21 by 30; it contains velocity values at each point. I have made a 3D surface plot to visualize it but the data is not so smooth. In order to interpolate the data, so that I have smooth peaks, I tried the function <code>griddata</code> but it does not seem to work.</p> <p>Here is...
<p>From what I can understand from the question, what you need to do is grid interpolation. It is possible to do that using RegularGridInterpolator from scipy <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.RegularGridInterpolator.html" rel="nofollow noreferrer">here</a>. Just make a fin...
python|numpy|scipy|filtering
0
368,405
72,585,139
importing for loop output to another for loop
<p>I am facing problem while importing the output of a for-loop to another for loop.</p> <p><code>My python script</code></p> <pre><code>import pandas as pd import numpy as np a=list(np.sort(np.random.uniform(low=2, high=3, size=(3,)))) a = [ round(elem, 1) for elem in a ] #print(a) for i,b in enumerate(a): c=[b,...
<p>Your problem is that you keep over writting the value if <code>c</code> which is why you only ever get the last value calculated in the next loop. You need to store the values in a list then read them back as needed.</p> <p>Here I've created an empty list <code>c = []</code> &amp; then in the 3rd loop read out the v...
python|dataframe|numpy
0
368,406
72,761,350
Pandas function to create multiple columns based on a single column
<p>I have a dataset which looks like this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>A</th> <th>B</th> <th>C</th> </tr> </thead> <tbody> <tr> <td>A1</td> <td>1</td> <td>1.3</td> </tr> <tr> <td>A1</td> <td>2</td> <td>1.4</td> </tr> <tr> <td>A1</td> <td>3</td> <td>1.3</td> </tr> <tr> <td...
<p>You can iterate over using number of elements (assuming all combos have same number of elements) as follows:</p> <pre><code>dfx = df.pivot_table(index='A', columns='B', values='C', aggfunc=list) pd.concat([dfx.applymap(lambda x:x[idx]) for idx in range(dfx.apply(lambda x: len(x)).max())]) </code></pre> <div class="s...
python|pandas|dataframe|pivot|pandas-groupby
2
368,407
72,579,818
Creating a class from df.iterrows() is painfully slow
<p>I'm wondering if I am doing this the correct way - I am new to Python, and tried to figure this out as best I could, but now I've almost completed my project, part of it is painfully slow.</p> <p>I have pulled down daily OHLC bars, filtered through them to find the gappers, and then I have created a Class which goes...
<p>Thanks to CodeMonkey for pointing me in the right direction. I didn't test the speed difference but it's huge, so thank you. I will look into trying Zaero's suggestions in the future when I have time:</p> <pre><code># get the dates for our gaps import os.path import glob import numpy as np import pandas as pd from p...
python|pandas|numpy|jupyter
0
368,408
72,773,473
Is there a way to vectorize a conditional sum with numpy?
<p>array I have:</p> <pre><code>a = np.array([0, 1, 3, 0, 0, 5, 12, 1, 0, 6]) </code></pre> <p>array I need:</p> <pre><code>b = np.array([0, 1, 4, 0, 0, 5, 17, 18, 0, 6]) </code></pre> <p>for loop that gives me array b</p> <pre><code>b = np.zeros(a.size) b[0] = a[0] for i in range(1, a.size): if a[i] &gt; 0: ...
<p>It is not exactly vectorized, but maybe useful nevertheless</p> <pre><code>import numpy as np a = np.array([0, 1, 3, 0, 0, 5, 12, 1, 0, 6]) b = np.r_[*[np.cumsum(c) for c in np.split(a, np.where(a==0)[0])]] print(b) </code></pre>
python|numpy|sum|conditional-statements|vectorization
1
368,409
72,511,613
Speed up python looping with numpy
<p>I've tried as much as possible to find a suitable solution/answer on the forum but I'm pulling blanks - most probably due to incorrect terminology.</p> <p>I currently have the following block of code that performs very poorly when performing the below operations on the array areas[] - the size of the array is upto 1...
<p>Your implementation complexity is O(n²)</p> <p>I would recommend using <code>zip: O(n)</code> then <code>sort: O(n*log(n))</code> and a simple loop <code>O(n)</code> resulting in <code>O(n*log(n))</code> complexity</p> <p>Even though I'm not using numpy, a faster algorithm is usually faster than just move the logic ...
python|python-3.x|numpy|performance
1
368,410
72,805,124
*Not Iterate* Rows in Dataframe and insert column based on values in list of dictionaries
<p>I have a DataFrame and a list of dictionaries. The DataFrame has 84k rows. Each row is an account for a specific client.</p> <p>Each dict in the list belongs to a specific client. They can have up to 50 keys and as few as 2 keys. The dictionaries also need to be applied in the order they are listed. The first key/va...
<p>EDIT:</p> <p>Based on your comments, I'd first create a mapping <code>ClientID -&gt; List of Dictionaries</code>:</p> <pre class="lang-py prettyprint-override"><code>lst = [ { &quot;client&quot;: &quot;Client #1&quot;, &quot;Billing Code&quot;: &quot;TNL&quot;, &quot;Bank&quot;: 1, ...
python|pandas|list|dictionary|list-comprehension
1
368,411
72,619,137
How to add an indexing level to a subset of columns in a dataframe in pandas
<p>I found how to add levels to all the columns but not on specific subsets.</p> <p>I explain my problem: say that I have a pandas dataframe like this</p> <pre><code> a b c d myIndex 0.0 0.1 0.2 -2.0 -0.8 0.1 0.7 1.1 9.0 0.8 0.2 -0.3 1.0 2.3 -0.6 </code>...
<h2>General Solution</h2> <p>Define a mapping dictionary which maps the level zero column values to level 1 column values, then flatten the dictionary into tuples and create a multiindex</p> <pre><code>d = {'A': ('a', 'b'), 'B': ('c', 'd')} df.columns = pd.MultiIndex.from_tuples((k, c) for k, v in d.items() for c in v)...
python|pandas
1
368,412
72,527,026
tf.image.sobel_edges: InvalidArgumentError: The first dimension of paddings must be the rank of inputs[4,2], [400,400,3] [Op:MirrorPad]
<p>Please I need help</p> <p>I am using tensorflow for a computer vision task. My function works fine without <code>tf.image.sobel_edges()</code>, but when I use it I get this error. I need to achieve two things from this function</p> <ol> <li>have contours around my images</li> <li>have shape of 4 dimensions</li> </ol...
<p>Tensorflow model usually expects a batch of images. Thank means, after your preprocess step, you need to add one more dimension for the batch and add the image as first in the set. You can use numpy and do this by:</p> <pre><code>x = np.expand_dims(x, axis=0) </code></pre>
python|tensorflow|deep-learning|computer-vision|face-recognition
0
368,413
72,629,684
Convert excel to Json file using pandas
<p>I'm trying to convert attached sample csv to json file. It is workng fine for single server but finding issue when it is more than 1 server <a href="https://i.stack.imgur.com/YgX07.png" rel="nofollow noreferrer">excel example</a></p> <pre><code>,How many servers are required?* ,3,,, ,,,,, ,,,,, ,,,Server 1,Serv...
<pre><code>import pandas as pd # We read the file and remove empty rows and columns. df = pd.read_csv('test.csv').dropna(how='all', axis=1).dropna(how='all') # We remove the unnecessary column and replace the remaining none with 0. df = df.drop(df.columns[[0]], axis=1).fillna(0) # We replace the indexes and names o...
python|json|pandas
0
368,414
72,831,331
How to do operations inside pandas dataframe based on conditions
<p>I have this pandas dataframe:</p> <p><a href="https://i.stack.imgur.com/2yxDU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2yxDU.png" alt="dataframe i have" /></a></p> <p>I want that</p> <p>IF there is a day that a row of condition_2 is 'True' BEFORE a row of condition_1, then, change the row o...
<p>You can groupby <code>date</code> column and compare the <code>condition</code> by shift</p> <pre class="lang-py prettyprint-override"><code>m = (df.groupby('date', as_index=False, group_keys=False) .apply(lambda g: g['condition_2'].eq('True') &amp; g['condition_1'].shift(-1).eq('True'))) df['condition_2'] = d...
python|pandas|dataframe
0
368,415
72,491,507
Why isn't replace working in pandas dataframe?
<p>I'm trying to parse some data and I cannot seem to use <code>.replace</code> to remove the junk i.e. <code>[Bluray]</code> and other data that is not year or resolution. My end goal is end up with columns of: Movie Name, Year and Resolution</p> <pre><code>,Movie Name,others 0,James Bond The Spy Who Loved Me ,1977) [...
<p>Given:</p> <pre><code> Movie Name others 0 James Bond The Spy Who Loved Me 1977) [1080p] 1 James Bond Live And Let Die 1973) [1080p] 2 No Time...
python|pandas|dataframe
1
368,416
72,703,563
Read a Pandas dataframe into R
<p>I have used <code>reticulate</code> package to source python code in R.</p> <pre><code>source_python(&quot;data_loading.py&quot;) df = my_data() str(df) 'data.frame': 268 obs. of 13 variables: $ DKF: num 1.352 1.283 1.246 0.73 0.784 ... $ GDT: num NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... $ GSB: num 1.4...
<p>If we are using a dictionary, then after sourcing the python file</p> <pre><code>library(reticulate) library(dplyr) library(tidyr) source_python(&quot;pytest1.py&quot;) out &lt;- bind_rows(py$df, .id = 'grp') %&gt;% pivot_longer(cols = -grp) %&gt;% pivot_wider(names_from = grp, values_from = value) %&gt;% e...
python|r|pandas|dataframe|reticulate
4
368,417
72,557,754
How to save interpolated data in a CSV file?
<p>I would like to save the newly interpolated grid in a CSV file with the structure: Lat, Long, Value.</p> <p>The code I have written so far looks like this:</p> <pre><code>import numpy as np from pykrige.ok import OrdinaryKriging from pykrige.kriging_tools import write_asc_grid import pykrige.kriging_tools as kt de...
<p>Your global <code>grid</code> variable has different sizes for <code>grid[&quot;x&quot;]</code> and <code>grid[&quot;y&quot;]</code>. That is because <code>data[&quot;lats&quot;]</code> in <code>genareate_grid</code> does not neccessarily span values with a difference of 360 between the min and max.</p> <p>I suspect...
python|pandas|numpy|scipy
1
368,418
59,654,681
Does model.reset_states for LSTM affect any other non-LSTM layers in the model?
<p>I am using the Stateful mode of LSTMs in <code>tf.keras</code> where I need to manually do <code>reset_states</code> when I have processed my sequence data, as described <a href="https://stackoverflow.com/a/46331227/3711266">here</a>. It seems that normally people do <code>model.reset_states()</code>, but in my case...
<p><strong>TLDR</strong>: Layers like <code>LSTM</code>/<code>GRU</code> have weights and states, where layers like <code>Conv</code>/<code>Dense</code>/<code>Embedding</code> have only weights. <code>reset_state()</code> only affects layers with states.</p> <p>What <code>reset_states()</code> does is that for an LSTM...
python|tensorflow|keras|lstm|tf.keras
1
368,419
59,807,578
Creating a secondary/inner index from scratch
<p>I need to create a new index from scratch <code>i</code> and then use it as an inner index part of a multi index. I am using an example df below.</p> <pre><code>#example df df = pd.DataFrame({"a":[11,11,22,22,22,33],"b":[1,2,3,4,5,6]}) # creating the i index df["i"]=0 def createIndex(grouped_df): newIndex = li...
<p>There is <code>cumcount</code></p> <pre><code>df['i']=df.groupby('a').cumcount() df a b i 0 11 1 0 1 11 2 1 2 22 3 0 3 22 4 1 4 22 5 2 5 33 6 0 </code></pre>
python|python-3.x|pandas|pandas-groupby
0
368,420
59,633,972
Matplotlib graph x ticks are after all x data points
<p>I am graphing timestamps against integers on a binary step graph, but it had all the timestamps on the x axis that are plotted instead of intervals, so I tried manually setting the x ticks to every 15 minutes throughout a day, but all the ticks seem to be after the data points: <a href="https://i.stack.imgur.com/N4V...
<p>Calling <a href="https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.xticks.html" rel="nofollow noreferrer"><code>plt.xticks</code></a> with just one parameter of strings isn't a good approach. The first parameter to <code>xticks</code> should be a list of numbers, places in the x-axis where you want a tick. ...
python|numpy|matplotlib
0
368,421
59,726,639
How to sample a pandas dataframe selecting X rows from group 1 but Y rows from group2
<p>Imagine a Students/Grades dataframe such that</p> <p><a href="https://i.stack.imgur.com/ZYt7Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZYt7Y.png" alt="dataframe with students and grades"></a></p> <p>Using pandas, how can I create multiple groups such that each group has 1 student with an ...
<p>You can do that by using a dictionary to store the number of samples from each group, as shown below: </p> <pre><code>import pandas as pd import numpy as np # create the dataframe df = pd.DataFrame(zip(['Person'+ str(i+1) for i in range(30)], np.random.choice(['A','B', 'C'], 30, replace=True)), ...
python|pandas|distribution
2
368,422
59,826,670
Make PyTorch variables to float64
<p>How to make all the variables created in a PyTorch file to float64? Is there a single line of code which can do that? </p>
<p>You can set the default tensor type using this one-liner:</p> <pre><code>torch.set_default_tensor_type(torch.DoubleTensor) </code></pre>
python|pytorch
2
368,423
59,677,256
Check each value in one column with each value of other column in one dataframe
<p>I have following dataframe: </p> <pre><code>import pandas as pd dict = {'val1':["3.2", "2.4", "-2.3", "-4.9","0"], 'class': ["1", "0", "0", "0", "1"], 'val2':["3.2", "2.7", "1.7", "-7.1", "0"]} df = pd.DataFrame(dict) df val1 class val2 0 3.2 1 3.2 1 2.4 0 2.7 2 -...
<p>First convert values to floats if necessary and then set sign with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.sign.html" rel="nofollow noreferrer"><code>numpy.sign</code></a> and then for second use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.between.html...
python|pandas|dataframe
3
368,424
59,599,579
Sample covariance matrix far from truth even for large sample size with 2D gaussian
<p>Here is a very simple script generating a 2D gaussian with 10000 points. The covariance matrix estimated by np.cov seems really far from the generating one. What is the explanation and are there solutions ?</p> <pre><code>import numpy as np import matplotlib.pyplot as plt center=[0,0] npoints=10000 data_covmat = n...
<p>The array [[1, 1], [1, 0.5]] is not positive semidefinite. One of its eigenvalues is negative. The description of the <code>cov</code> argument in the docstring of <code>multivariate_normal</code> says "Covariance matrix of the distribution. It must be symmetric and positive-semidefinite for proper sampling."</p> ...
python|numpy|statistics|covariance
1
368,425
59,755,899
Remove prefix with special characters in Python Pandas Series
<p>How do I remove the <code>Bale + Damon -</code> prefix in the series below?</p> <pre><code>import pandas as pd x = pd.Series(['Bale + Damon - Le Mans 66', 'Bale + Damon - Ford', 'Bale + Damon - vs.', 'Bale + Damon - Ferrari']) print(x) 0 Bale + Damon - Le Mans 66 1 Bale + Damon - Ford 2 Bale + Damon - vs. ...
<p>In your case </p> <pre><code>x.str.split(' - ',n=1).str[-1] 0 Le Mans 66 1 Ford 2 vs. 3 Ferrari dtype: object </code></pre>
pandas|replace|series
1
368,426
59,905,021
Efficient STAR selection in pandas
<p>There is a type of selection called <a href="https://en.wikipedia.org/wiki/STAR_voting" rel="nofollow noreferrer">STAR</a> which is an acronym for "Score then Automatic Runoff". This is used in a number of algorithmic methods but the typical example is voting. In pandas, this is use to select a single column under t...
<p>Here my take on it</p> <p>Sample <code>df</code></p> <pre><code>Out[1378]: A B C D 0 5 5 1 5 1 0 1 5 5 2 3 3 1 3 3 4 5 0 4 4 5 5 1 1 </code></pre> <p><strong>Step 1</strong>: Use <code>sum</code>, <code>nlargest</code>, and slice columns for <code>Score step</code></p> <pre><code>df_top...
python|pandas|sum
1
368,427
59,538,544
Having an issue loading a TFLite model into Flutter (issue with file-path)
<p>I'm trying to load a TFLite model / it's labels into flutter but I keep getting a file not found error. Is it possibly a mistake in my code for loading the model: </p> <p><strong>Code:</strong></p> <pre><code>loadModel() async{ String res = await Tflite.loadModel( model: "lib\assets\image_classifier.tflite...
<p>You should use <code>/</code> in file path instead of <code>\</code></p> <pre class="lang-dart prettyprint-override"><code>loadModel() async{ String res = await Tflite.loadModel( model: "lib/assets/image_classifier.tflite", labels: "lib/assets/image_labels.txt", ); } </code></pre>
tensorflow|flutter
1
368,428
59,728,402
flatten array of arrays json object column in a pandas dataframe
<pre><code>0 [{'review_id': 4873356, 'rating': '5.0'}, {'review_id': 4973356, 'rating': '4.0'}] 1 [{'review_id': 4635892, 'rating': '5.0'}, {'review_id': 4645839, 'rating': '3.0'}] </code></pre> <p>I have a situation where I want to flatten such json as solved here: <a href="https://stackoverflow.com/questions/...
<p>Try using:</p> <pre><code>print(pd.DataFrame(s.apply(lambda x: {a: b for i in [{x + str(i): y for x, y in v.items()} for i, v in enumerate(x, 1)] for a, b in i.items()}).tolist())) </code></pre> <p>Output:</p> <pre><code> rating1 rating2 review_id1 review_id2 0 5.0 4.0 4873356 4973356 1 5.0...
python|arrays|json|pandas
1
368,429
59,866,151
Limit Dask CPU and Memory Usage (Single Node)
<p>I am running Dask on a single computer where running <code>.compute()</code> to perform the computations on a huge parquet file will cause dask to use up all the CPU cores on the system.</p> <pre><code>import dask as dd df = dd.read_parquet(parquet_file) # very large file print(df.names.unique().compute()) </code...
<p>Dask.distributed.Client creates a LocalCluster for which you can explicitly set the memory use and the number of cores. </p> <pre><code>import numpy as np import pandas as pd from dask.distributed import Client from dask import dataframe as dd def names_unique(x): return x['Names'].unique() client = Client(me...
python|python-3.x|pandas|dask|dask-distributed
2
368,430
59,725,546
Pandas: Reading in several large .bz2 files and appending it
<p>I have 30 .bz2 files that i want to read in. Each file is too large to be read in, so x size chunk is sufficient from each file. I then want to join all these 30 files together. </p> <pre><code>import pandas as pd import numpy as np import glob path = r'/content/drive/My Drive/' # use your path ...
<pre><code>import os, json import pandas as pd import numpy as np import glob pd.set_option('display.max_columns', None) temp = pd.DataFrame() path_to_json = '/content/drive/My Drive/' json_pattern = os.path.join(path_to_json,'*.bz2') file_list = glob.glob(json_pattern) for file in file_list: chunks = pd.read_...
python|json|pandas|for-loop|glob
0
368,431
59,878,951
Convolving a each row of a 2D matrix with a vector
<p>I have a 1000000x1000 (MxN) matrix <strong>A</strong>. I have another vector <strong>b</strong> of size L. I need to convolve each row of the 2D matrix <strong>A</strong> with the vector <strong>b</strong>. How can I do this in python?</p> <p>I tried, <code>C = np.convolve(A, b)</code></p> <p>But I get an error sa...
<p>Try <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.convolve2d.html" rel="nofollow noreferrer">scipy's convolve2d</a></p> <pre><code>C = scipy.signal.convolve2d(A, b) </code></pre> <p>just make sure <code>len(b.shape) == 2</code> (meaning it is a 2 dimensional array, with one dimension o...
python|numpy|convolution
1
368,432
59,691,639
Object Counting from image using TensorFlow.js
<p>I am working on a pre-trained model coco-SSD for object detection. I have been successful to detect objects from the image but now I have to count the number of a specific object can anyone help</p> <pre><code>public async predictWithCocoModel() { const model = await cocoSSD.load(); this.detectFrame(this.vi...
<p>The prediction object contains the class of the box predicted. A counter can be used along with a conditional statement for counting detecting objects of a certain class.</p> <pre><code>let i = 0 predictions.forEach(prediction =&gt; { const x = prediction.bbox[0]; const y = prediction.bbox[1]; const wid...
javascript|tensorflow|machine-learning|tensorflow.js
0
368,433
59,881,364
Get the percentile of a column ordered by another column
<p>I have a dataframe with two columns, <code>score</code> and <code>order_amount</code>. I want to find the score Y that represents the Xth percentile of <code>order_amount</code>. I.e. if I sum up all of the values of <code>order_amount</code> where <code>score &lt;= Y</code> I will get X% of the total <code>order_am...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.searchsorted.html" rel="nofollow noreferrer"><code>Series.searchsorted</code></a>:</p> <pre><code>idx = df_order['percentile_value'].searchsorted(50) print (df_order.iloc[idx, df.columns.get_loc('score')]) 0.4 </code></pre> <p>Or ...
python|pandas
3
368,434
59,902,482
A fast way to group column values within a certain range and assign a value to a new column
<p>I have a huge data frame. I would like to group the values in one column based on a certain criterion and add a new value to another column: For all values in column <code>number</code> from 1000 to 1999 assign 1 to the <code>group</code> column. From 2000 to 2999 assign 2, etc.</p> <p>For better understanding an e...
<p>Try use <code>//</code> (it is floor div)</p> <pre><code>df['groups'] = df.number // 1000 Out[1326]: number groups 0 1200 1 1 1300 1 2 1450 1 3 1555 1 4 2300 2 5 2341 2 6 2355 2 7 2800 2 8 3003 3 9 4010 4 </code></pre>
python|pandas|dataframe
5
368,435
59,569,973
Make several columns using for loop?
<p>The below code (calculation of moving average over N-days) works for well. But I want to replace other numbers (e.g., 5, 10, 20, etc.) with 50. Not sure if I can turn the below code into something in for loop. Could anybody please help me?</p> <pre><code>df['ma50pfret']= df['ret'] df.loc[df.adjp &gt;= df.ma50, 'ad...
<p>Do you just mean to replace the 50's with 5, 10, 20, etc? If so, that could be done by always using brackets to access columns, and using f-strings (or some other string formatting method) to replace 50 with the other numbers, like this: </p> <pre><code>for num in [5, 10, 20, 50]: df[f'ma{num}pfret']= df['ret']...
python|python-3.x|pandas|dataframe|for-loop
0
368,436
59,794,517
HASHBYTES, sha2_256 in sql introduce bad characters when called from python
<p>One of our old sql legacy code, converts a numerical column in sql using the HASHBYTES function and sha2_256.</p> <p>The entire process is moving to python as we are putting in some advanced usage on top of the legacy work. However, when using connector, we are calling the same sql code, the HASHBYTES('sha2_256',co...
<p>You are getting the right result but is displayed as raw bytes (This is why you have the b in <code>b"..."</code>).</p> <p>Looking at the result from <strong>SQL</strong> you have the data encoded with <strong>hexadecimal</strong>.</p> <p>So to transform the python result you can do:</p> <pre class="lang-py prett...
python|sql|pandas|connector|hashbytes
5
368,437
59,887,913
2D numpy array of 0's and 1's - where cells are 1 set the surrounding 12x12 cells to 1 as well
<p>have a large 2d numpy array, dimensions 1500x1500, which represents a maze. Cells contain 0 and 1, where 0 is open space and 1 is occupied. I want to account for dimensions of robot, so poss easy way to do this is amend the map so that where original cells are 1, set surrounding cells up to 3 cells away in any direc...
<p>What you're doing is called binary dilation and can be done simply with <code>scipy.ndimage.morphology.binary_dilation</code></p> <pre><code>from scipy.ndimage.morphology import binary_dilation output = binary_dilation(input, structure = np.ones((7,7))) </code></pre> <p>This also allows you to do things like lop ...
python|arrays|numpy
2
368,438
59,613,946
Problem during prediction on tensorflow js prediction
<p>I have a problem on my tensorflow js model, I followed a course (<a href="https://codelabs.developers.google.com/codelabs/tfjs-training-classfication/index.html?index=..%2F..index#0" rel="nofollow noreferrer">link to the course</a>) where I learned to create a tensorflow model and everything worked fine but the cour...
<p>The image should be predicted only when it has completed to load</p> <pre><code>const img = document.getElementById('imageResult') img.onload = function(){ let inputTensor = tf.browser.fromPixels(document.getElementById('imageResult'), 1)// imageResult is an &lt;img/&gt; tag .reshape([1, 28, 28, 1]) .cast...
javascript|tensorflow|tensorflow2.0|tensorflow.js
1
368,439
59,506,372
Exporting Pandas DataFrame cells directly to excel/csv (python)
<p>I have a Pandas DataFrame that has sports records in it. All of them look like this: "1-2-0", "17-12-1", etc., for wins, losses and ties. When I export this the records come up in different date formats within Excel. Some will come up as "12-May", others as "9/5/2001", and others will come up as I want them to.</p> ...
<p>I don't think its a python issue, but Excel auto detecting dates in your data. But, see below to convert your scores to strings. </p> <p>Try this, import pandas as pd</p> <pre><code>df = pd.DataFrame({"lakers" : ["10-0-1"],"celtics" : ["11-1-3"]}) print(df.head()) </code></pre> <p>here is the dataframe with...
python|pandas|dataframe|date|export-to-csv
1
368,440
59,517,617
How to obtain the encoder from the make_csv_dataset?
<p>I used this code from the tutorial:</p> <pre><code>def get_train_dataset(file_path, **kwargs): dataset = tf.data.experimental.make_csv_dataset( file_path, batch_size=10, # Artificially small to make examples easier to show. label_name=LABEL_COLUMN, na_value="?", num_epochs=1, i...
<p><a href="https://www.tensorflow.org/api_docs/python/tf/data/experimental/make_csv_dataset?version=stable" rel="nofollow noreferrer">tf.data.experimental.make_csv_dataset</a> does not make any encoding. It is about:</p> <blockquote> <p>Reads CSV files into a dataset, where each element is a (features, labels) tu...
tensorflow|keras|tensorflow2.0
1
368,441
59,830,030
How to find a mean between these 2 numbers in 1 column?
<p>How to find a mean between these 2 numbers in 1 column and update column <code>built_up</code> with mean value? And also ignore the number that not in range.</p> <pre><code> built_up 0 1498-1602 1 1022-1187 2 1713-1970 3 2305-3396 4 1420 5 - </code></pre> <p>Here is my data - <a href="https://gist.github.com/dato...
<p><strong>Edit</strong>: For you real data, you should use <code>str.findall</code> as follows</p> <pre><code>df['b_median'] = [np.median(pd.to_numeric(x if bool(x) else np.nan, errors='coerce')) for x in df['built_up'].str.findall('\d+')] </code></pre> <hr> <p><strong>Original</strong>:</...
python|python-3.x|pandas
1
368,442
59,581,489
Merge 2 csv files rows
<p>So i'm trying to predict the winner of a sport game, and i have 2 CSV files. One with the current year statistics and the other with last years statistics. </p> <p>I would like to merge them but only with the colums from the first file: </p> <p>So that if the first table has columns ['Away','Home','Result'] </p> ...
<p>To block <em>data2.Match-Rating</em> from appending, invoke <em>append</em> passing <em>data2</em> with column names to be included:</p> <pre><code>data.append(data2[['Away', 'Home']], ignore_index=True, sort=False)\ .replace(np.nan, '') </code></pre> <p>As you can see, I added <em>ignore_index=True</em> to av...
python|pandas|csv
2
368,443
59,632,221
Finding error difference row wise between two dataframes in python
<p>Is there an easier way to find the percent difference between two dataframes.</p> <p>For example:</p> <pre><code>df1((row1,col1) -df2(row1, col1))/average(df1(row1,col1), df2(row1,col1)) </code></pre> <p><a href="https://i.stack.imgur.com/Bnid1.png" rel="nofollow noreferrer">The picture</a> shows the original dat...
<p>You can calculate the element-wise difference between two data frames like this:</p> <pre><code>diff_df = df1 - df2 </code></pre> <p>The same way, you can add them together and divide them by 2. And multiply them by 100:</p> <pre><code>avg_df = (df1 + df2) / 2 </code></pre> <p>You can divide <code>diff_df</code>...
python|pandas|numpy|dataframe|difference
0
368,444
59,666,063
How to normalize and standardscaler to string data
<p>how can i do normalize() or StandardScaler() if the data is still in string format? is the parameter need to be tfidf? and how can i manually transform string to tfidf when im not use pipeline ? i got error like this: ValueError: could not convert string to float: 'お気に入り の Ubuntu : 無償 OS &amp; amp ; 無償 ソフト で 何 でも 揃う...
<p>You can't standard scale or normalize string data, you can only do that to numbers. For most common algorithms you need to turn your string data into numbers somehow so that you can use them in your algorithm. It's not clear to me what your text is. If it is a limited number of predefined inputs you could treat it a...
python|algorithm|machine-learning|sklearn-pandas
1
368,445
59,583,022
Pandas Groupby result into a separate dataframe
<p>Say there is a dataframe with 100 records containing 4(or n) columns, example of dataframe below:</p> <pre><code> id target col3 col4 00 0 .. .. 00 0 .. .. 00 0 .. .. 01 1 .. .. 01 1 .. .. 01 0 .. .. 01 1 .. .. ...
<p>Here's a way to do:</p> <pre><code>df = (df .groupby('id') .apply(lambda f: f['target'].value_counts().to_frame()) .unstack() .reset_index()) df.columns = ['id', 0, 1] print(df) id 0 1 0 0 3.0 NaN 1 1 1.0 3.0 2 2 2.0 2.0 </code></pre>
python|pandas|dataframe|pandas-groupby
2
368,446
59,610,318
Pandas DataFrame checking condition before a specific row
<p><a href="https://i.stack.imgur.com/y4SpL.png" rel="nofollow noreferrer">DataFrame</a></p> <p>I have the above DataFrame with millions of rows and wish to groupby(['Instrument', 'Date']) for some data analysis. </p> <p>I wish to compare the last row of each group with the Value before, which is the first to be equa...
<p>This should work,</p> <pre><code>def f(grp): return grp.loc[(grp&gt;=grp.iloc[-1])].iloc[0] res = df.groupby(['Instrument', 'Date'])['Value'].agg(lambda x: f(x)) res.head() </code></pre> <p>If you are not certain that always there's going to be a value higher than last row, use the following <code>f()</code>.<...
python|pandas|dataframe|conditional-statements
0
368,447
59,684,791
Visualize Trees and OOB error: 'numpy.ndarray' object is not callable
<p>I want to visualize the number of trees and the oob error for my RandomForestRegresser and GradietBoostRegressor. So I have coded this lines, but of some reason there 'numpy.ndarray' object is not callable. Is here anybody that knows why this did not worked? I hope you have a nice day and thank you!</p> <pre><code>...
<p>Have a look <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html#sklearn.ensemble.RandomForestRegressor" rel="nofollow noreferrer">here</a>. <code>oob_prediction_</code> is an array containing the oob-predictions on your training set.</p> <p>Your code should therefo...
python|numpy|matplotlib|random-forest|mse
1
368,448
59,602,418
len() of np.array gives TypeError: len() of unsized object
<p>I need to update a rather large python 2.7 project to python 3. Disclaimer, I'm new to python and this is a task I was given to learn the ins and outs of this language. The tricky part is the following:</p> <pre><code>assert ((nzis is None and shape is not None) or (nzis is not None and shape is None)) ...
<p>Searching the web I found </p> <p><a href="https://github.com/vicariousinc/schema-games/blob/master/schema_games/utils.py" rel="nofollow noreferrer">https://github.com/vicariousinc/schema-games/blob/master/schema_games/utils.py</a></p> <pre><code>def shape_to_nzis(shape): """ Convert a shape tuple (int, in...
python|arrays|python-3.x|python-2.7|numpy
1
368,449
59,584,981
<lambda>() takes 1 positional argument but 2 were given
<p>I am trying to implement the same Sage code here: <a href="https://math.stackexchange.com/questions/409217/how-to-find-the-centre-of-vectors-in-3-dimensional-space">find vector center</a> in python, as follows:</p> <pre><code>import numpy as np from scipy.optimize import minimize def norm(x): return x/np.linalg...
<p>The algorithm of the answer that you indicate is not written in python, so which obviously can fail, considering <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html" rel="noreferrer">the official docs</a> I have implemented the following solution:</p> <pre class="lang-py prett...
python|numpy|lambda|constraints|minimize
5
368,450
59,844,737
Python- how do I remove timestamp from datetime data throughout the dataframe?
<p>I found a similar thread but it dosent seem to work for me</p> <p><a href="https://stackoverflow.com/questions/45858155/removing-the-timestamp-from-a-datetime-in-pandas-dataframe">Removing the timestamp from a datetime in pandas dataframe</a></p> <p>say, My dataframe is of the following format: </p> <p><a href="h...
<p>I tried with an example on my own with the help from <a href="https://stackoverflow.com/a/47752555/8660907">https://stackoverflow.com/a/47752555/8660907</a></p> <p><a href="https://i.stack.imgur.com/iRWsH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iRWsH.png" alt="enter image description here...
python|pandas|dataframe|datetime
1
368,451
59,604,918
Pytorch mask tensor with boolean numpy array
<p>I have a <code>84x84</code> pytorch tensor named <code>target</code>. I need to mask it with an <code>84x84</code> boolean numpy array which consists of <code>True</code> and <code>False</code>. </p> <p>When I do <code>target = target[mask]</code>, I get the error <code>TypeError: can't convert np.ndarray of type n...
<p>I think there is some confusion with the types. But this works.</p> <pre><code>import torch tensor = torch.randn(84,84) c = torch.randn(tensor.size()).bool() c[1, 2:5] = False x = tensor[c].size() </code></pre> <p>For testing I created a tensor with random values. Afterwards 3 elements are set to False. In the las...
python|numpy|pytorch|torch
2
368,452
59,729,634
In tensorflow 2.0, how to compute gradients of loss to input variables?
<p>In tensorflow 2.0, tf.gradients is not supported, and GradientTape only compute gradients to trainable weights, so how to get gradients to input as TF1.0 can do? thanks, correct me if i'm wrong.</p>
<p>Since you have already mentioned the answer, providing the explanation and code details below for the community. </p> <p>For TensorFlow 2 you need to use GradientTape to compute gradients of loss for input. </p> <p>Here is the explanation of how GradientTape works. </p> <p>Let's create some sample toy function...
tensorflow
0
368,453
59,652,245
matplotlib.lineCollection from pandas dataframe. Slow performance of current iterrows solution
<p>I have a large dataframe which contains coordinates with a value. I want to plot this in matplotlib with a different color for each value.</p> <p>I have a working solution now that plots this as a lineCollection. I am using iterrows as that is easy to understand for me, but it is very slow.</p> <p>I merge with ano...
<p>I changed this:</p> <pre><code>for _, row in dff.iterrows(): point = (row['x'], row['y']) color = row['color'] </code></pre> <p>to this:</p> <pre><code>dff['point'] = list(zip(dff['x'], dff['y'])) for point, color in zip(dff['point'], dff['ctable']): ... </code></pre> <p>This small change made it ru...
python|pandas|performance|dataframe|matplotlib
0
368,454
59,873,517
Working with 2 arrays to populate a third one in numpy
<p>I am trying to work with two arrays in a certain way in python. Lets say</p> <pre><code>A = np.array([5, 10, 30, 50]) B = np.array([2, 3, 4, 5]) </code></pre> <p>now I have a target array <code>C = [2, 7, 15, 25, 40]</code>. I want to find a output value (say <code>Y</code>) for each element in <code>C</code> (say...
<p>Check this question <a href="https://stackoverflow.com/questions/35215161/most-efficient-way-to-map-function-over-numpy-array/35216364">Most efficient way to map function over numpy array </a>. You can create an array of indices <code>np.arange(C.size)</code>, make a function with all the logic of combining <code>A<...
python|arrays|numpy
1
368,455
59,838,206
Push data to google sheet from dataframe
<p>I'm trying to push data into my google sheet with the following code, how can i change the code so that it will print in the 2nd row at the correct column base on the header that I've created. </p> <p>First code:</p> <pre><code>class Header: def __init__(self): self.No_DOB_Y=1 self.No_DOB_M=2 self.N...
<p>You need to change the <a href="https://gspread.readthedocs.io/en/latest/api.html#gspread.models.Worksheet.range" rel="nofollow noreferrer">range() parameters</a>:</p> <blockquote> <pre><code>first_row (int) – Row number first_col (int) – Row number last_row (int) – Row number last_col (int) – Row number </code><...
python|pandas|dataframe|google-sheets
2
368,456
59,524,716
KNN: TypeError: iteration over a 0-d array
<p>I'm using KNN code from (<a href="https://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html#sphx-glr-download-auto-examples-neighbors-plot-classification-py" rel="nofollow noreferrer">sklearn.org</a>) with my own data. (I'm not using the Iris dataset.) I've cut the data way down for this post...
<p>It looks like your cmaps only have 3 colors in them, but there are 6 classes that each need a color assigned to them. Try listing 6 colors in the ListedColormaps rather than 3.</p>
python|pandas|scikit-learn|knn
0
368,457
59,857,596
Change a string representation of a list into a numpy array?
<p>I have a string representation of a list, such as the result of <code>str([[1,2,3],[4,5,6]])</code>; <code>'[[1, 2, 3], [4, 5, 6]]'</code>. How can I convert this to a numpy array? I have tried the below code.</p> <pre><code>import numpy as np a = [[1,2,3],[4,5,6]] b = str(a) c = np.array(b, dtype=float) </code></...
<p>Assuming this is really what you want to do, and not just <code>np.array(a)</code>, you could use <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow noreferrer"><code>ast.literal_eval()</code></a> to convert <code>b</code> back to a list as follows:</p> <pre><code>&gt;&gt;&gt; impor...
python|python-3.x|list|numpy|numpy-ndarray
0
368,458
59,690,310
How to get the original variable name from a list of pandas dataframes
<p>I have a list of pandas data frames and want to iterate over it and get the original variable names. I've tried the following but print line throws an error ('DataFrame' object has no attribute 'name'):</p> <pre><code>import pandas as pd testFrame1 = pd.DataFrame(columns=["test1"]) testFrame2 = pd.DataFrame(column...
<p>You can actually set a name method for your dataframes.</p> <pre><code>testFrame1 = pd.DataFrame(columns=["test1"]) testFrame1.name = 'testFrame1' testFrame2 = pd.DataFrame(columns=["test2"]) testFrame2.name = 'testFrame2' listOfFrames = [testFrame1,testFrame2] for frame in listOfFrames: print(frame.name) </...
python|pandas
0
368,459
59,520,545
Multi-threaded image processing with openCV in python
<p>I am quite new to python and have problems to parallize a part of my algorithm. Consider an input image thats need to be threshold in a certain way on pixel level. Since the algorithm only considers a specific area to calculate the threshold values, I'd like to run each chunk of the image in a seperate thread/proces...
<p>You are not taking advantage of any of Numpy's vectorization techniques which can decrease processing time significantly. I'm assuming this is why you want to multiprocess operations on windows/chunks of the image(s) - I don't know what Docker is so I don't know whether that is a factor in your multiprocess approach...
python|python-3.x|numpy|opencv|python-multithreading
3
368,460
59,643,474
Numpy : index 2 dimensions at once
<p>I want to assign new values to an array, on positions given by some indexes. An exemple will be more clear : </p> <pre><code>import numpy as np #Dimensions N = 25 n = 50 d = 100 k = 3 p = 7 A = np.random.uniform(size=(N,n,d,d)) A_new_values = np.random.uniform(size=(N,n,k,p)) indexes_new_values = np.random.choic...
<p>If I understand correctly, I think you can do what you want with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.put_along_axis.html" rel="nofollow noreferrer"><code>np.put_along_axis</code></a>:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np #Dimensions N = 25 n = 50 d ...
numpy|indexing
1
368,461
59,535,296
Groupby and filter in pandas where all columns remain upon completion
<p>I have been attempting to filter a pandas dataframe after a groupby call, and have yet to achieve my desired results. </p> <p>My data which is named rd_test_AM: <a href="https://i.stack.imgur.com/tKGUb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tKGUb.png" alt="enter image description here">...
<p>As long as your instantaneous_peak values are unique (which they seem they will all be) you can do the following:</p> <pre><code>rd_test_AM[rd_test_AM['instantaneous_peak'].isin(rd_test_AM.groupby(['Year','Month','Day','DOW'])['instantaneous_peak'].max().tolist())] </code></pre>
python|pandas
1
368,462
59,886,145
How to correctly use pandas sort_index with level and axis arguments?
<p>Regarding this df:</p> <pre><code> Amount type Month_year 2019-06-01 2019-07-01 2019-06-01 2019-07-01 TYPE_ID 1 2 1 2 1 2 1 2 ID 100 ...
<p>Essentially,</p> <p><strong><code>sort_index</code> with <code>axis=1</code> sorts the column headers, and this ordering is then used to set the order of the columns.</strong></p> <p>And, the corollary,</p> <p><strong><code>sort_index</code> with <code>axis=0</code> sorts the index, and this ordering is then used...
python|pandas|dataframe|multi-index
6
368,463
59,832,929
How to replace column value by for loop and def function?
<p>I want to replace column value for multiple columns by def function. <code>If value &gt; 8 = 100, if value &gt; 6 = 0, if value &lt; 7 = 0, if NaN = NaN</code></p> <p>My data is below.</p> <pre><code>ID MONTH COUNTRY Brand A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 1 201906 USA Apple 10 7 10 0 NaN NaN...
<p>I'd suggest that instead of looping inside your function, move it outside and loop through the columns:</p> <pre><code>list = ['A1', 'A3', 'A4', 'A7', 'A10'] def f(x): if x &gt; 8: value = 100 elif x &gt; 6: value = 0 elif x &lt; 7: value = -100 else: value = np.nan ...
python|pandas|dataframe
2
368,464
59,699,910
How to apply the same function with different input arguments to create new columns in pandas dataframe?
<p>So i've this sample dataframe:</p> <pre><code> x_mean x_min x_max y_mean y_min y_max 1 85.6 3 264 75.7 3 240 2 105.5 6 243 76.4 3 191 3 95.8 19 287 48.4 8 134 4 85.5 50 ...
<p>This is the concept that you need to follow to make this happen. First you need to have your ranges stored in a dictionary to enable access to them through names. </p> <pre><code>range_dict = {} range_dict['x_range'] = x_range range_dict['y_range'] = y_range </code></pre> <p>Also, you need to have the columns that...
python|pandas|function|dataframe
1
368,465
59,667,756
Adding data to pandas dataframe with no header
<p>I am trying to add a row(list of int) to pandas dataframe but i am somehow unable to append it. The thing is the dataframe has no header and everywhere the put data through specifying column names. I dont understand how to do it without header. Below is my dataframe named <strong>sheet</strong></p> <pre><code>sheet...
<p>Does the following work?</p> <pre><code>sheet = sheet.append(pd.DataFrame([[1,2,3,4,2,1,1,1]]), ignore_index=True) </code></pre>
python|pandas|numpy
1
368,466
59,723,451
Query table with compound primary keys
<p>I'm using <code>pyodbc</code> to connect to a machine database, and query a number of tables in that database using </p> <p><code>pandas.read_sql(tbl,cnxn), where tbl = "SELECT * FROM TABLE", cnxn is pyodbc.connect('DSN=DATASOURCE;UID=USERID;PWD=PASSWORD').</code> </p> <p>It works on most tables, but some tables r...
<p>Before anything, understand MS Access is a <a href="https://meta.stackexchange.com/questions/33216/ms-access-or-mdb-or-access-database-engine-or-ms-jet-ace">unique</a>, GUI tool that maintains its own default database, JET/ACE Engine, but can connect to other databases as well including Oracle, SQL Server, Postgres,...
sql|database|pandas|pyodbc
0
368,467
32,577,939
Dynamically naming DataFrames in Pandas
<p>Imagine I have 2 data frames as such:</p> <pre><code>foo = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]}) bar = pd.DataFrame({'c':[7,8,9], 'd':[10,11,12]}) </code></pre> <p>I want to subset each of these data frames and put them in a new data frame with a dynamic name. When I look up anything on dynamic naming in pyth...
<p>I can't think of any reason you couldn't use a dictionary of <code>DataFrame</code>s. This will let you avoid needing to treat the variable names as data:</p> <pre><code>whole_dataframes = {"foo": foo, "bar": bar} first_dataframes = {name: value[:1] for name, value in whole_dataframes.items()} </code></pre> <p>I'm...
python|python-2.7|pandas
4
368,468
32,218,712
Neural network dimension mis-match
<p>I have a neural network setup for the MNIST digits dataset in Keras that looks like this:</p> <pre><code>input_size = features_train.shape[1] hidden_size = 200 output_size = 9 lambda_reg = 0.2 learning_rate = 0.01 num_epochs = 50 batch_size = 30 model = Sequential() model.add(Dense(input_size, hidden_size, W_regul...
<p>I've been training 2 class classification models for so long that I'm used to dealing with labels that are just single values. For this problem (classifying more than 1 outcome) I just had to change the labels to be vectors themselves.</p> <p>This solved my problem:</p> <pre><code>from keras.utils.np_utils import ...
python|numpy|machine-learning|neural-network|keras
0
368,469
32,346,516
Python Pandas: Lookup table by searching for substring
<p>I have a dataframe with a column for app user-agents. What I need to do is to identify the particular app from this column. For example, </p> <p><code>NewWordsWithFriendsFree/2.3 CFNetwork/672.1.15 Darwin/14.0.0</code> will be categorized in <code>Words With Friends</code>. </p> <pre><code>iPhone3,1; iPhone OS 7.1...
<pre><code>df = pd.DataFrame({'date' : ['2015-09-02 13:45:56' , '2015-08-31 23:04:21'] , 'user-agent' : ['NewWordsWithFriendsFree/2.3 CFNetwork/672.1.15 Darwin/14.0.0' , 'iPhone3,1; iPhone OS 7.1.2; com.fingerarts.sudoku2; 143441-1,24'] }) map_df = pd.DataFrame({'Keyword' : ['NewWordsWithFriends' , 'com.fingerarts.s...
python|python-2.7|pandas|lookup|string-search
1
368,470
32,519,730
Python - Need to get last date for each ID in Pandas
<p>Probably this is easy, but I'm new in Pandas: I have DataFrame consists of "id" (int64) and "datetime" (datetime64):</p> <pre><code>d = {'id' : Series([1., 2., 3., 2., 3., 1., 1., 3., 1., 2.]), 'datetime' : Series(['01.02.2015', '01.02.2015', '01.03.2015', '03.01.2015', '06.02.2015', '01.04.2015', '18.03.2015', ...
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort.html#pandas.DataFrame.sort" rel="nofollow noreferrer"><code>sort</code></a> on 'datetime' and then call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html#pandas.DataFrame.drop_dupli...
python|datetime|pandas
7
368,471
32,333,765
Numpy item faster than operator[]
<p>I have a following code in python that at least for me produces strange results:</p> <pre><code>import numpy as np import timeit a = np.random.rand(3,2) print timeit.timeit('a[2,1] + 1', 'from __main__ import a', number=1000000) print timeit.timeit('a.item((2,1)) + 1', 'from __main__ import a', number=1000000) </...
<p>In this case, they don't return quite the same thing. <code>a[2,1]</code> returns a <code>numpy.float64</code>, while <code>a.item((2,1))</code> returns a native python float. </p> <h2>Native vs <code>numpy</code> <em>scalars</em> (<code>float</code>, <code>int</code>, etc)</h2> <p>A <code>numpy.float64</code> s...
python|performance|numpy
18
368,472
32,344,524
How to play sound from samples contained in NumPy array?
<p>I'm trying to find a function which corresponds to <code>soundsc()</code> and <code>sound()</code> in Matlab. Basically, I'd like to listen to sound by playing samples contained in NumPy array. Are there some functions for doing this?</p>
<p>This pertains to Linux &amp; Mac</p> <p>Most of Linux computers come pre-installed with <code>vox</code> library which let's you play audio from the command line.</p> <p>So assume you write an array to wave file using <code>scipy.io.write</code>, you can play it from within Python program using the <code>subproces...
matlab|audio|numpy|scipy
1
368,473
32,154,985
Are Scipy operations done row-by-row rather than column-by-column as in Matlab?
<p>I'm a novice at NumPy, SciPy. Previously, I've used Matlab/Octave for a long time.</p> <p>It seems like <code>scipy.fftpack.fft</code> works row-by-row for 2-Dimensional array. For me, it's very confusing, since, with Matlab, such operations were done column-by-column. Are all other operations in scipy also perform...
<p>Numpy's <code>fft()</code> accepts an "axis" argument, so you can ask for column-wise FFT rather than the default row by row FFT.</p> <p>E.g., the following returns the 16-point FFT of every column in <code>x</code>: (you can specify <code>None</code> for the 2nd argument if you don't know the number of rows):</p> ...
python|matlab|numpy
4
368,474
32,559,502
matrix multiplication error in numpy
<p>I have the following two numpy arrays:</p> <pre><code>np.random.seed(1) y2=np.random.standard_normal((50,1)) lambda_=np.zeros((100,2)); lambda_[0]=np.random.gamma(1,1,2); </code></pre> <p>but when I try to do </p> <pre><code>np.dot(y2,lambda_[0]) </code></pre> <p>or its transposed version:</p> <pre><code>np.dot...
<p><code>y2</code> has the shape <code>(50, 1)</code>, and <code>lambda_[0]</code> has the shape <code>(2,)</code>, so <code>dot()</code> treats it as a matrix-vector multiplication and, consequently, throws an error. If you want the second argument to be treated as a <code>(1,2)</code> matrix, you need to reshape it:<...
python|numpy
2
368,475
40,353,549
Numpy: filling the non-maximum elements of ndarray with zeros
<p>I have a ndarray, and I want to set all the non-maximum elements in the last dimension to be zero.</p> <pre><code>a = np.array([[[1,8,3,4],[6,7,10,6],[11,12,15,4]], [[4,2,3,4],[4,7,9,8],[41,14,15,3]], [[4,22,3,4],[16,7,9,8],[41,12,15,43]] ]) print(a.shape) (3,3,4) </code></p...
<p>Here's one way that uses broadcasting:</p> <pre><code>In [108]: (a == a.max(axis=2, keepdims=True)).astype(int) Out[108]: array([[[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 0]], [[1, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0]], [[0, 1, 0, 0], [1, 0, 0, 0], [0, 0...
python|arrays|numpy|argmax
1
368,476
40,342,938
Indexing a 1D tensor in tensorflow
<p>Is it possible to get the element from a tensor at a given index in order to obtain a scalar? For example given an image I can retrieve its shape with <code>shape = tf.shape(image)</code>, but how can I retrieve its height, width and depth?</p> <p>The only way I found is the following:</p> <pre><code>height = tf.r...
<p>The slice syntax (i.e. using the <code>[]</code> operator) is based on NumPy slicing, and gives a slightly more concise way of getting the height, width and depth from a <code>shape</code> tensor:</p> <pre><code>shape = tf.shape(image) height = shape[0] # returns a scalar width = shape[1] # returns a scalar dept...
python|indexing|tensorflow
1
368,477
40,586,212
Trying to pass a custom C++ matrix to a numpy array
<p>I am trying to do some Python wrapping to use custom C++ stuff. The main type we use is a 2D gray image type with data allocated in a 1D buffer. I try to wrap it this way (following an example <a href="https://ubuntuforums.org/showthread.php?t=1266059" rel="nofollow noreferrer">in an ubuntu forum</a>):</p> <pre><co...
<p>Ok so I thought the <code>PyArray_SimpleNewFromData</code> function was copying data but it seems it doesn't. My mistake was to free the <code>tmp_img</code> 2D array.</p>
python|c++|arrays|numpy|wrapper
1
368,478
40,413,664
Most efficient way to pass data from one pandas DataFrame to another
<p>I'm trying to find a more efficient way of transferring information from one DataFrame to another by iterating rows. I have 2 DataFrames, one containing unique values called 'id' in a column and a value called 'region' in another column:</p> <pre><code>dfkey = DataFrame({'id':[1122,3344,3467,1289,7397,1209,5678,179...
<p><code>pandas.merge</code> could be another solution.</p> <pre><code>newdf = pandas.merge(df2, dfkey, on='id') In [22]: newdf Out[22]: id other region 0 1792 3 8 1 1122 2 1 2 1122 4 1 3 3344 3 2 4 3467 3 3 5 1289 5 4 6 7397 7 ...
python|python-3.x|pandas|dataframe
1
368,479
40,639,759
Python pandas: Adding different dataframes with different length to a dataframe using name of columns
<p>Suppose I have a main dataframe with three columns </p> <pre><code> A B C 0 7 7 7 </code></pre> <p>And I have three other dataframes, each one has only one column but with different length.</p> <pre><code>df_A = pd.DataFrame([2,3,4,6,7,11],columns = ['A']) df_B = pd.DataFrame([2,3,4],columns = ['B'])...
<p>try this:</p> <pre><code>In [187]: pd.concat([df, df_A.join(df_B, how='outer').join(df_C, how='outer')]) Out[187]: A B C 0 7.0 7.0 7 0 2.0 2.0 2 1 3.0 3.0 3 2 4.0 4.0 4 3 6.0 NaN 5 4 7.0 NaN 6 5 11.0 NaN 7 6 NaN NaN 8 7 NaN NaN 9 8 NaN NaN 10 </code></pre>
python|pandas|dataframe|add
1
368,480
40,355,123
h2o tensorflow deep learning demo fails
<p>I watched the video demo <a href="http://www.lectoro.com/index.php?action=search&amp;ytq=H2O%20TensorFlow%20Deep%20Learning%20Demo" rel="nofollow">http://www.lectoro.com/index.php?action=search&amp;ytq=H2O%20TensorFlow%20Deep%20Learning%20Demo</a></p> <p>I am able to set up the env using the same spark and sparklin...
<p>yes, right now demo is Python 2 specific. However, we will update it to match Python 3 syntax. I meantime feel free to modify code or look at DeepWater which introduces Deep Learning on top of MxNet (and TF, and Caffe - in progress) <a href="https://github.com/h2oai/deepwater" rel="nofollow noreferrer">https://githu...
python-2.7|python-3.x|tensorflow|jupyter|h2o
1
368,481
40,683,394
sklearn SGDClassifier fit() vs partial_fit()
<p>I am confused about <code>fit()</code> and <code>partial_fit()</code> method of <code>SGDClassifier</code>. Documentation says for both, "Fit linear model with Stochastic Gradient Descent.".</p> <p>What I know about stochastic gradient descent is, it takes one (or a fraction of whole) training example to update par...
<p>I think the <code>partial_fit</code> method is useful for updating a model that has already been trained, whereas the <code>fit</code> method will re-train the model from scratch.</p> <p>As for manually selecting how much of the data is included in each weight update, I can't seem to find an argument for this in th...
machine-learning|scikit-learn|logistic-regression|sklearn-pandas
3
368,482
40,455,033
python - add indicator for 10 most recent dates
<p>I'm using Python, and I have data with a team name and dates of games that have been played, it looks something like this (except there are a few hundred rows): </p> <pre><code> team date 0 TOR 2016/10/15 1 LAK 2016/10/20 2 CGY 2016/11/03 3 BUF 2016/10/30 4 PIT 2016/1...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.nsmallest.html" rel="nofollow noreferrer"><code>SeriesGroupBy.nsmallest</code></a> with <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow noreferrer">...
python|pandas
1
368,483
40,553,670
Sklearn regression input "Found array with dim 3. Estimator expected <= 2"
<p>I'm trying to parse this file <a href="http://www4.stat.ncsu.edu/~boos/var.select/diabetes.rwrite1.txt" rel="nofollow noreferrer">http://www4.stat.ncsu.edu/~boos/var.select/diabetes.rwrite1.txt</a> to run multi feature regression, but i'm getting an "ValueError: Found array with dim 3. Estimator expected &lt;= 2." ....
<p>If you want to predict a continuous variable then use LinearRegression. If you want to predict categories then you need to use a classifier such as LogisticRegression or RandomForestClassifier.</p> <p>In sklearn these nearly always have "classifier" in the name.</p>
python|numpy|scikit-learn
0
368,484
40,610,637
split - ValueError: need more than 1 value to unpack
<p>I am reading a text file which has data in this format: </p> <pre><code>column : row </code></pre> <p>This is some sample data:</p> <pre><code>Name of the Property : North Kensington Upcycling Store and Cafe Availability : Now Interest Level : 74 people are looking right now Area : 1,200 sqft Retail Type : No...
<p>If a line of the input file is empty or missing the colon, <code>split</code> returns only 1 element and you get that error.</p> <p>To play it safe, I would do a size check to avoid the exception, and print an explicit message when parsing is not possible (I added empty line skip to avoid crashing in that case)</p>...
python|pandas
1
368,485
40,634,813
Convert String to Date [With Year and Quarter]
<p>I have a pandas dataframe, where one column contains a string for the year and quarter in the following format:</p> <pre><code>2015Q1 </code></pre> <p><strong>My Question:</strong> ​How do I convert this into two datetime columns, one for the year and one for the quarter.</p>
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="noreferrer"><code>split</code></a>, then cast column <code>year</code> to <code>int</code> and if necessary add <code>Q</code> to column <code>q</code>:</p> <pre><code>df = pd.DataFrame({'date':['2015Q1','2...
python|date|pandas
10
368,486
40,766,730
Ensure parallel reduction of numpy array operation mapping to repeated position
<p>Is there a way for numpy to ensure that an array operation mapping to repeated positions undergo a reduction, i.e. they are both performed on the result of each other?</p> <pre><code>a = numpy.zeros([4], int) # [0 0 0 0] b = numpy.arange(0, 8) # [0 1 2 3 4 5 6 7] positions = [0, 0, 1, 1, 2, 2, 3, 3] a[position...
<p>When there are repeated indices, the behavior of in-place addition in a numpy array is undefined. To ensure the behavior that you want, use <code>numpy.add.at</code>. (All numpy "ufuncs" have the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.at.html" rel="nofollow noreferrer"><code>at</...
python|arrays|numpy|reduction
3
368,487
40,595,468
Retraining Open Images pretrained Inception v3 model
<p>Is there a way to retrain Open Images pretrained inception v3 model <a href="https://github.com/openimages/dataset" rel="nofollow noreferrer">https://github.com/openimages/dataset</a>?</p> <p>Here is what I've tried:<br> 1. Inception approach <a href="https://github.com/tensorflow/models/tree/master/inception" rel...
<p>There is a detailed description available on TensorFlow site: <a href="https://www.tensorflow.org/tutorials/image_retraining" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/image_retraining</a></p> <p>It describes how to retrain the Inception-v3 model to recognize the new classes according to applie...
dataset|tensorflow
0
368,488
40,741,744
Reading default output of Fortran in Python
<p>I have an output from old code in Fortran 77. The output is written with </p> <pre><code>write(NUM,*) </code></pre> <p>line. So basically, default format. Following is part of output:</p> <pre><code>1.25107598E-67 1.89781536E-61 1.28064971E-94 5.85754394-118 8.02718071E-94 </code></pre> <p>I had a post-proc...
<p>You can post-process your output efficiently with a regular expression:</p> <pre><code>import re r = re.compile(r"(?&lt;=\d)\-(?=\d)") output_line = "1.25107598E-67 1.89781536E-61 1.28064971E-94 5.85754394-118 8.02718071E-94 " print(r.sub("E-",output_line)) </code></pre> <p>result:</p> <pre><code>1.25107598...
python|numpy|fortran
4
368,489
40,477,940
Pixel wise classification using Convolutional Neural Network?
<p>The question is conceptual. I basically understand how MNIST example works, the feedforward net takes an image as input and output a predicted label 0 to 9. </p> <p>I'm working on a project that ideally will take an image as the input, and for every pixel on that image, I will output a probability of that pixel bei...
<p>Although it wouldn't be very efficient, a naive method could be to color a window (say, 5px x 5px) of pixels black, record the probabilities for each output class, then slide the window over a bit, then record again. This would be repeated until the window passed over the whole image.</p> <p>Now we have some intere...
image-processing|machine-learning|tensorflow|deep-learning|convolution
2
368,490
40,563,150
Tensorflow : Pinning Variables to CPU in Multigpu training not working
<p>I am training my first multi-gpu model using tensorflow. As the tutorial states the variables are pinned onto the CPU and ops on every GPU using name_scope.</p> <p>As i am running a small test and logging the device placement, i can see the ops being placed onto respective GPU with TOWER_1/TOWER_0 prefix but the va...
<p>Try with: </p> <pre><code>with slim.arg_scope([slim.model_variable, slim.variable], device='/cpu:0'): </code></pre> <p>This was taken from: <a href="https://github.com/tensorflow/models/blob/master/slim/deployment/model_deploy.py" rel="nofollow noreferrer">model_deploy</a></p>
tensorflow|multi-gpu
0
368,491
40,549,953
Grouping Pandas DataFrame by n days starting in the begining of the day
<p>I have just discovered the power of Pandas and I love it, but I can't figure out this problem:</p> <p>I have a DataFrame <code>df.head()</code>:</p> <pre><code> lon lat h filename time 0 19.961216 80.617627 -0.077165 60048 2002-05-15 12:59:31.717467 1 19.923916 80.614847 -0.018...
<p><strong><em>Dropping first time row:</em></strong></p> <p>Your best bet would be to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.normalize.html" rel="nofollow noreferrer"><code>normalize</code></a> the first row of the <code>datetime</code> column so that the time is reset to <cod...
python|pandas
3
368,492
40,515,970
Issues appending numpy arrays during for loop
<p>I'm a bit lost at the moment. I correctly initialized an empty numpy array and I believe i'm using the <code>np.append</code> function correctly</p> <pre><code>Preds = np.empty(shape = (X_test.shape[0],10)) kf = KFold(n = X_train.shape[0], n_folds=10, shuffle = True) for kf_train, kf_test in kf: X_train_kf =...
<p>If <code>Preds</code> is (9649,10), then you can do one of 2 kinds of concatenation</p> <pre><code> newPreds = np.concatenate((Preds, np.zeros((N,10))), axis=0) newPreds = np.concatenate((Preds, np.zeros((9649,N)), axis=1) </code></pre> <p>The first produces a (9649+N, 10) array, the second (9646,10+N).</p> <p><...
python|arrays|numpy
1
368,493
40,709,870
Changing accuracy value and no change in loss value in binary classification using Tensorflow
<p>am trying to use a deep neural network architecture to classify against a binary label value - 0 and +1. Here is my code to do it in tensorflow. Also this question carries forward from the discussion in a <a href="https://stackoverflow.com/questions/40709074/binary-classification-in-tensorflow-unexpected-large-value...
<p>Once you pre-process your data into the wrong shape or range in a ML training task, the rest of the data flow will go wrong. You do this multiple times in different ways in the code in the question.</p> <p>Taking things in order that the processing occurs. The first problems are with pre-processing. Your goals here...
python|machine-learning|neural-network|tensorflow|logistic-regression
6
368,494
18,262,962
Setting DataFrame column headers to a MultiIndex
<p>How do I convert an existing dataframe with single-level columns to have hierarchical <strike>index</strike> columns (MultiIndex)?</p> <p>Example dataframe:</p> <pre><code>In [1]: import pandas as pd from pandas import Series, DataFrame df = DataFrame(np.arange(6).reshape((2,3)), index=['A','B'], ...
<p>You were close, just set the columns directly to a new (equal sized) index-like (which if its a list-of-list will convert to a multi-index)</p> <pre><code>In [8]: df Out[8]: one two three A 0 1 2 B 3 4 5 In [10]: df.columns = [['odd','even','odd'],df.columns] In [11]: df Out[11]: o...
python|pandas|multi-index
23
368,495
18,270,618
TypeError when passing 2d numpy array to C++
<p>I have two-dimensional data in a numpyarray and C++-code that I want to perform some action on this data. Using swig and distutils and the <code>numpy.i</code> I managed to compile everything into a python extension "goldstein", that provides a function <code>unwrap2d</code>. I test it using </p> <pre><code>import ...
<p>@Jaimie is right of course. 'float' like 'double' is 64-bit in numpy, thats why I didnt check again, I just remembered it does not matter. But float in c++ obviously needs 32-bit, which in numpy is <code>'float32'</code>. Thank you!</p>
arrays|numpy|swig
0
368,496
18,748,836
Extend and Embed Python (and NumPy) with C++ (and GSL): pass gsl_matrix to python and back
<p>my problem "should" be simple but I am still not able to solve it.</p> <p>I am currently working on a project that requires some heavy computations (done in C++) and some post-simulations data analysis (done in Python).</p> <p>However, now I am changing the main algorithm and I will need to "cycle" some computatio...
<p>I think you don't need to implement yourself the wrapper, because you may use <a href="http://sourceforge.net/projects/pygsl/" rel="nofollow">pygsl</a>. If you really want to implement your own version, here is the routine from pygsl that might be worth to you </p> <pre><code>%{ #include &lt;gsl/gsl_matrix_double.h...
c++|python|numpy|gsl
1
368,497
18,521,037
pandas: iterative filtering a DataFrame's rows
<p>Suppose I have a <code>DataFrame</code> like so,</p> <pre><code>df = pd.DataFrame([['x', 1, 2], ['x', 1, 3], ['y', 2, 2]], columns=['a', 'b', 'c']) </code></pre> <p>To select all rows where <code>c == 2</code> and <code>a == 'x'</code>, I could do something like,</p> <pre><code>df[(df['a'] == '...
<p>While this isn't a solution for now, in pandas version 0.13 you'll be able to do</p> <pre><code>df.query('a == "x"').query('c == 2') </code></pre> <p>to achieve what you want.</p> <p>You'll also be able to do</p> <pre><code>df['a == "x"']['c == 2'] </code></pre> <p>and </p> <pre><code>df['a == "x" and c == 2']...
python|pandas|dataframe
1
368,498
18,419,962
How to compute weighted sum of all elements in a row in pandas?
<p>I have a pandas data frame with multiple columns. I want to create a new column <code>weighted_sum</code> from the values in the row and another column vector dataframe <code>weight</code> </p> <p><code>weighted_sum</code> should have the following value:</p> <p><code>row[weighted_sum] = row[col0]*weight[0] + row[...
<p>The problem is that you're multiplying a frame with a frame of a different size with a different row index. Here's the solution:</p> <pre><code>In [121]: df = DataFrame([[1,2.2,3.5],[6.1,0.4,1.2]], columns=list('abc')) In [122]: weight = DataFrame(Series([0.5, 0.3, 0.2], index=list('abc'), name=0)) In [123]: df O...
python|pandas|dataframe|calculated-columns|weighted-average
14
368,499
18,551,342
How to rearrange table in pandas in a format suitable for analysis in R?
<p>In pandas:</p> <pre><code>df = pd.DataFrame({'row1':['a','b','a','a','b','b','a','b','b','a'], 'row2':['x','x','y','y','y','x','x','y','x','y'],'col':[1,2,1,2,2,1,2,1,1,2],'val':[34,25,22,53,33,19,42,38,33,61]}) p = pd.pivot_table(df,values='val',rows=['row1','row2'],cols='col') col 1 2 row1 row2 ...
<p>One way is to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a>:</p> <pre><code>In [11]: p.stack() Out[11]: row1 row2 col a x 1 34 2 42 y 1 22 2 57 b x 1 ...
python|r|pandas|dataframe|reshape
3