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
358,400
16,000,574
Tie breaking of round with numpy
<p>Standard numpy round tie breaking is following IEEE 754 convention, to round half towards the nearest even number. Is there a way to specify different rounding behavior, e.g. round towards zero or towards -inf? I'm not talking about ceil or floor, I just need different tie breaking.</p>
<p>NumPy doesn't give any control over the internal rounding mode. Here's two alternatives:</p> <ol> <li>Use <code>gmpy2</code>, as outlined in <a href="https://stackoverflow.com/a/15104444/1204143">this answer</a>. This gives you full control over the rounding mode, but using <code>gmpy2</code> for simple float math ...
python|numpy|scipy|rounding
11
358,401
15,505,514
Binary numpy array to list of integers?
<p>I have a binary array, and I would like to convert it into a list of integers, where each int is a row of the array.</p> <p>For example:</p> <pre><code>from numpy import * a = array([[1, 1, 0, 0], [0, 1, 0, 0], [0, 1, 1, 1], [1, 1, 1, 1]]) </code></pre> <p>I would like to convert <code>a</code> to <code>[12, 4, 7...
<p>@SteveTjoa's answer is fine, but for kicks, here's a numpy one-liner:</p> <pre><code>In [19]: a Out[19]: array([[1, 1, 0, 0], [0, 1, 0, 0], [0, 1, 1, 1], [1, 1, 1, 1]]) In [20]: a.dot(1 &lt;&lt; arange(a.shape[-1] - 1, -1, -1)) Out[20]: array([12, 4, 7, 15]) </code></pre> <p>(<code>arange<...
python|numpy|binary
31
358,402
15,951,711
How to compute cluster assignments from linkage/distance matrices
<p>if you have this hierarchical clustering call in scipy in Python:</p> <pre><code>from scipy.cluster.hierarchy import linkage # dist_matrix is long form distance matrix linkage_matrix = linkage(squareform(dist_matrix), linkage_method) </code></pre> <p>then what's an efficient way to go from this to cluster assignme...
<p>If I understand you right, that is what <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.fcluster.html#scipy.cluster.hierarchy.fcluster" rel="noreferrer">fcluster</a> does:</p> <blockquote> <p><code>scipy.cluster.hierarchy.fcluster(Z, t, criterion='inconsistent', depth=2, R=None, ...
python|numpy|scipy|cluster-analysis
28
358,403
12,150,513
Numpy/Scipy modulus function
<p>The Numpy '<strong>modulus</strong>' function is used in a code to check if a certain time is an integral multiple of the time-step.</p> <p>But some weird behavior is seeen. </p> <ul> <li><code>numpy.mod(121e-12,1e-12)</code> returns 1e-12</li> <li><code>numpy.mod(60e-12,1e-12)</code> returns '<strong>a very small...
<p>According to the doc, <code>np.mod(x1,x2)=x1-floor(x1/x2)*x2</code>. The problem here is that you are working with very small values, a dark domain where floating point errors (truncation...) happen quite often and results are often unpredictable... I don't think you should spend a lot of time worrying about that.</...
python|numpy|scipy
0
358,404
12,262,480
Retrieving field formats of numpy record array as list
<p>I am trying regularize the formats of a pytable and recarray for the purposes of appending the recarray to the pytable. To do this I need to get field information from the recarray (i.e. names and field formats) I can easily get a list of the recarray names using: </p> <pre><code>namelist = Myrecarray.dtype.names...
<p>Hmmmm, newbie found an answer to his own question. I needed the "descr" property to turn it into an iterable object</p> <pre><code>print([x[1] for x in img.dtype.descr]) </code></pre>
python|numpy|pytables
2
358,405
12,565,396
How to build numpy for Py4A?
<p>As you have already understood, I can't build numpy as a module for Py4A. <a href="http://code.google.com/p/python-for-android/wiki/BuildingModules">Here's</a> an instruction but I still can't make it. I installed <a href="http://code.google.com/p/python-for-android/wiki/Toolchain_Installation">Toolchain</a>, becaus...
<p>If you installed the py4a module, then add</p> <pre><code>from py4a import patch_distutils patch_distutils() </code></pre> <p>to <code>setup.py</code>, add the <code>setup.cfg</code> and now:</p> <pre><code>python setup.py configure python setup.py build </code></pre>
android|python|numpy
1
358,406
72,053,285
How do I create a 2D matrix with more than 30 bins?
<p>I'm working on a code that takes a list of points from a text file and an input m, to create a frequency distribution of points where m is the number of bins.</p> <pre class="lang-py prettyprint-override"><code>discret = open('testingdisc.txt','w+') x = [] y = [] m = int(input(&quot;Input number of bins:&quot;)) ...
<p>Python's default is not print all entries when you try to print out a very large array. The main reason behind it is probably that it helps no one when you accidentally out an array with millions of entries. You change that behaviour by changing the print options:</p> <pre><code>import sys import numpy numpy.set_pri...
python|numpy|histogram2d
0
358,407
72,083,809
How can I compute the chance of going into a certain state, given the current state?
<p>I am trying to compute the change of going into a certain state, given the current state.</p> <p>I need this for a simulation that I am doing as my machine needs to know what state it go into next, what these chances are and also the length of time before this state change happens.</p> <p>So for now I am not focusin...
<p>The probability is the number of recorded occurrences relative to the total. This is easily done with <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>value_counts</code></a> using the <code>normalize=True</code> parameter:</p> <pre><code>df['Stat...
python|pandas
1
358,408
71,920,559
Take list of values and find biggest combination between certain amount of items in the list
<p>I have a list of values that has a size of 24.</p> <p>What I want to do is find the biggest combination using three values from the list. I only want to use three of the values, the highest ones possible.</p> <p>So if I had a list that looked like:</p> <p><code>vals_list = [5, 3, 5, 5, 5, 4, 2, 1, 2, 4]</code></p> <...
<p>IIUC sorting values and extract last 3 values for top3, last sum them:</p> <pre><code>print (sum(sorted(vals_list)[-3:])) 15 </code></pre>
python|pandas|numpy
2
358,409
72,053,512
How to get results without duplicates array?
<p>How to get results without duplicates ? I have a CSV file shown in the description below, I take all the columns together, to get a random result from all the columns together, but I get results with duplicates.</p> <p>Thank you</p> <pre><code>test.csv </code></pre> <pre><code> d c b a ----------------- 0 ...
<p>Use <a href="http://%5Bandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer"><code>DataFrame.duplicated</code></a> with invert mask by <code>~</code>:</p> <pre><code>a = np.random.choice(df.flatten(), size=(20, 2)) a2 = a[~pd.DataFrame(a).duplicated(keep=False...
arrays|python-3.x|pandas|numpy
0
358,410
72,021,120
Using regex with dataframes to match exact instead of just contains
<p>My code here:</p> <pre><code> for x in validUnitNames: unitDf = df.filter(regex=x) print(unitDf) </code></pre> <p>For the first value of x ('BMP AHU-1') is turning up this:</p> <pre><code>BMP AHU-1\MAT BMP AHU-1\RAT BMP AHU-10\MAT BMP AHU-10\RAT \ 0 66.341175 65.131525 70.789092 ...
<p>Make your regex ends with a backward slash:</p> <pre class="lang-py prettyprint-override"><code>unitDf = df.filter(regex=x + r&quot;\\&quot;) </code></pre>
python|regex|pandas|dataframe
2
358,411
72,095,385
Elements corresponding to indices in Python
<p>I would like to obtain the array elements corresponding to specific indices. The desired output is attached.</p> <pre><code>import numpy as np A=np.array([[1.1, 2.3, 1.9],[7.9,4.9,1.4],[2.5,8.9,2.3]]) Indices=np.array([[0,1],[1,2],[2,0]]) </code></pre> <p>The desired output is</p> <pre><code>array([[2.3],[1.4],[2.5]...
<p>You can use the columns of <code>Indices</code> separately. The first column for the row indices and the second for the column indices:</p> <pre class="lang-py prettyprint-override"><code>out = A[Indices[:, [0]], Indices[:, [1]]] </code></pre> <p>Output:</p> <pre class="lang-py prettyprint-override"><code>array([[2....
python|numpy
2
358,412
71,816,607
Select row only that contain specific value with correlation to another column and group them
<p>so i have this kind of dataframe and i want to select only these websites that have TLSVersion1.2 and 1.3 ONLY. There is already a similar thing <a href="https://stackoverflow.com/questions/56156866/pandas-select-rows-that-contains-both-values-inclusive">Pandas select rows that contains both values (inclusive)</a></...
<p>You can do this using isin():</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({ 'websiteName' : ['website1.lt']*2+['website2.lt']*4+['website3.lt']*4+['website4.lt']*4, 'TLSVersion' : ['TLSv1.2', 'TLSv1.3', 'TLSv1.0', 'TLSv1.1', 'TLSv1.2', 'TLSv1.3', 'TLSv1.0', 'TLSv...
python|pandas|dataframe
1
358,413
71,841,336
Pandas dt accessor returns wrong day and month
<p>My CSV data looks like this -</p> <pre><code>Date Time 1/12/2019 12:04AM 1/12/2019 12:09AM 1/12/2019 12:14AM </code></pre> <p>and so on</p> <p>And I am trying to read this file using pandas in the following way -</p> <pre><code>import pandas as pd import numpy as np data = pd.read_csv('D 2019.csv',parse_d...
<p>The default format is MM/DD, while yours is DD/MM.</p> <p>The simplest solution is to set the <code>dayfirst</code> parameter of <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a>:</p> <blockquote> <p><strong><code>dayfirst</code></strong> ...
python|python-3.x|pandas|dataframe|pandas-datareader
2
358,414
71,995,440
Is there a multi images to 1 image deep learning method? (pix2pix?)
<p>I'm trying to build a video stabilization deep learning model.<br> I want to make the model predict how the frame should be stabilized depending on the last 10 frames</p> <p>I have tried <strong>pix2pix</strong>, which is image to image, but I didn't get a good result<br> so, I want the same as pix2pix but <strong>m...
<p>So, I do not know if you actually need to build this video stabilization using deep learning or if you just want on off-the-shelves solution.</p> <p>For the on-the-shelves solution, you can look into vidgear that has an awesome stabilisation system built-in: <a href="https://abhitronix.github.io/vidgear/latest/gears...
python|tensorflow|deep-learning|pytorch|generative-adversarial-network
1
358,415
71,794,085
Replace np.nans in list with calculated values obtained from polynomial regression
<p>I have two lists of y values:</p> <pre><code>y_list1 = [45,np.nan,np.nan,np.nan, 40,50,6,2,7,np.nan, np.nan,np.nan, np.nan, np.nan] y_list2 = [4,23,np.nan, np.nan, np.nan, np.nan, np.nan,5, np.nan, np.nan, np.nan, np.nan, np.nan] </code></pre> <p>and both of these values were obtained at a set of time points:</p> <...
<p>first you should modify the <code>ab</code> definition as:</p> <pre><code>ab = np.polyfit(x[idx], np.array(y)[idx], idx.sum()) </code></pre> <p><code>ab</code> are your polynomial coefficients, so you have to pass them to <code>np.polyval</code> as:</p> <pre><code>replace_nan = np.polyval(ab,x) print(replace_nan) </...
python|numpy|polynomials
1
358,416
71,940,162
Tensor multiplication in Keras
<p>I have two tensors of size</p> <p>A &lt;tf.Tensor 'sequential_12/my_layer_56/add:0' shape=(?, 300, 2) dtype=float32&gt;</p> <p>and B &lt;tf.Tensor 'input_82:0' shape=(?, 2, 2) dtype=float32&gt;</p> <p>Now, I would like to multiply them in the sense of the usual matrix row-column product to obtain</p> <p>A * B of s...
<p>Maybe try <code>tf.matmul</code>:</p> <pre><code>import tensorflow as tf samples = 1 A = tf.random.normal((samples, 300, 2)) B = tf.random.normal((samples, 2, 2)) print(tf.matmul(A, B).shape) # (1, 300, 2) </code></pre>
python|tensorflow|keras
0
358,417
71,858,923
How to modify values of a column of a 2D tensor based on condition - Tensorflow?
<p>I have a 2D tensor and want values of its last column to be 0 if values &gt; 0 and 1 otherwise. It should behave somewhat similar to the following block of numpy code:</p> <pre><code>x = np.random.rand(8, 4) x[:, -1] = np.where(x[:, -1] &gt; 0, 0, 1) </code></pre> <p>Is there a way to achieve the same behavior for a...
<p>This might not be the most elegant solution, but it works:</p> <pre><code>x=tf.ones((5,10)) rows=tf.stack(tf.range(tf.shape(x)[0])) column=tf.ones_like(rows)*tf.shape(x)[1]-1 idx=tf.stack((rows,column),axis=1) x_new=tf.tensor_scatter_nd_update(x, idx, tf.where(x[:, -1] &gt; 0, 0., 1.)) print(x_new) </code></pre> <...
python|tensorflow|multidimensional-array
2
358,418
72,021,328
Is there a way to convert multiple tiff files to numpy array at once?
<p>I'm doing a convolutional neural network classification and all my training tiles (1000 of them) are in geotiff format. I need to get all of them to a numpy array, but I only found code that will do it for one tiff file at a time.</p> <p>Is there a way to convert a whole folder of tiff files at once?</p> <p>Thanks!<...
<p>Try using a <code>for</code> loop to go through your folder</p>
python|numpy|deep-learning|conv-neural-network|geotiff
0
358,419
71,887,916
Pandas: Pivot dataframe with text and combine columns
<p>I'm working with Python and Pandas and have a table like this:</p> <pre><code> Name Team Fixture Line-up Min IN Min Out 0 Player 1 RAY J1 Starting 68 1 Player 2 RAY J1 Bench 74 2 Player 3 RSO J2 Starting ...
<p>You could modify <code>Line-up</code> column by including the Min value, then <code>pivot</code>:</p> <pre><code>out = (df.assign(**{'Line-up': df['Line-up'] + ' - ' + df.filter(like='Min').bfill(axis=1).iloc[:,0].astype(int).astype(str)}) .pivot(['Name','Team'], 'Fixture','Line-up').rena...
python|pandas|pivot-table
1
358,420
71,892,890
Returning all Data from a CKAN API Request? (Python)
<p>This is my first time using a CKAN Data API. I am trying to download public road accident data from a government website. It is only showing the first 100 rows. On the CKAN documentation it says that the default limit of rows it requests is &quot;100&quot;.I am pretty sure you can write an ckan expression to the end...
<p>There are several interesting fields in the <a href="http://docs.ckan.org/en/latest/maintaining/datastore.html#ckanext.datastore.logic.action.datastore_search" rel="nofollow noreferrer">documentation</a> for <code>ckanext.datastore.logic.action.datastore_search()</code>, but the ones that pop out are <code>limit</co...
python|pandas|request|ckan
4
358,421
72,005,086
Convert dataframe index values into columns
<p>I have a dataframe that looks like this: <img src="https://i.stack.imgur.com/naGqi.png" alt="stats dataframe" /></p> <p>What I would love to do, is to turn the <code>PTS</code> and <code>REB</code> value into respective columns with each value underneath, like</p> <pre><code>PTS | REB ---------- 14.29 | 5.71 </cod...
<p>You could use the transpose functionality.</p> <pre><code>df_transpose = df.T </code></pre> <p>or</p> <pre><code>df_transpose = df.transpose() </code></pre> <p>Here is the link to the doc:<br /> <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.transpose.html" rel="nofollow noreferrer">https://p...
python|pandas|dataframe|indexing
0
358,422
72,108,273
How to use groupby in a dataframe and output only unique group names but contains all rows?
<p>I have data as follows:</p> <pre><code>country state area people India Tamil Nadu urban 194 India Karnataka urban 96 Sri Lanka state1 urban 600 India Chennai urban 302 Sri Lanka state2 urban 213 India Bengaluru rural 34 Sri Lanka state3...
<p>Filter only duplicated values by <code>country</code> column and then sorting by same column, last repalce duplicated values to empty strings:</p> <pre><code>df = df[df.duplicated(['country'], keep=False)].sort_values('country', ignore_index=True) df.loc[df.duplicated(subset=['country']), 'country'] = '' print (df) ...
python|pandas|dataframe|csv|export-to-excel
0
358,423
71,946,130
Separating values in a Panda dataframe
<p>I have a csv file that I am importing in a <code>pandas.DataFrame object</code> through the <code>pandas.read_csv</code> method.</p> <p>The csv file has clubbed data which is separated by comma:</p> <pre><code># Example: Name , Age , Gender , Grade Alpha , 20 , Male , A Beta , 21 , Female , B Gamma , 22 , Mal...
<p>With pandas, you can read pd.read_csv(yourfile.csv) and it should work fine. However, you also can use re, here is an example:</p> <pre><code>import re string = '&quot;first, element&quot;, second element, third element, &quot;fourth, element&quot;, fifth element' out = re.split(r', (?=(?:&quot;[^&quot;]*?(?: [^&qu...
python|pandas
0
358,424
72,122,752
how to do filter on pandas dataframe?
<p><strong>Example Code here :</strong></p> <pre><code>x7 = ['Spammer','Suspicious','Normal','Micro Influencer','Influencer'] rasio_real_spammer = df[(df['Rasio Followers/Followings'] &lt; 0.5) &amp; (df['fake'] == 0)].count() temp = df[(df['Rasio Followers/Followings'] &gt; 0.5) &amp; (df['Rasio Followers/Followings'...
<pre><code>x7 = ['Spammer','Suspicious','Normal','Micro Influencer','Influencer'] rasio_real_spammer = df[(df['Rasio Followers/Followings'] &lt; 0.5) &amp; (df['fake'] == 0)].count() rasio_real_suspicious = df[(df['Rasio Followers/Followings'] &gt; 0.5) &amp; (df['Rasio Followers/Followings'] &lt; 1.0) &amp; (df['fake...
python|pandas|dataframe
0
358,425
71,792,738
How to make a file with combination of multiple files with different extensions(xlsx, csv)?
<p>Hey I'm looking for answers which can be solve my issue.</p> <p>1.I have a csv files in one folder 2.Excel files in other folder 3.I want combine these two folder files as a single file</p> <p>Note : Data is same in both folder files in terms of columns</p>
<ol> <li>For file handling I recommend using the <code>pathlib</code> built-in python module: <a href="https://towardsdatascience.com/why-you-should-start-using-pathlib-as-an-alternative-to-the-os-module-d9eccd994745" rel="nofollow noreferrer">pathlib examples</a>. Use the <code>glob</code> method to fetch all files wi...
python|pandas|jupyter-notebook
0
358,426
71,873,716
How to do merge of these dataframes
<p>I have two dataframes of the form:</p> <pre><code>df1: note_id start_sentence end_sentence 0 476766 328 452 1 476766 941 1065 2 500941 377 522 3 500941 797 963 4 500941 1722 ...
<p>I would just do an inner join, and then use all of your conditions to update the values.</p> <p>Specifically calculate the diff where the diff is &gt;0, and then fill everything but the min diff per group with <code>np.nan</code></p> <pre><code>import pandas as pd df1 = pd.DataFrame({'note_id': [476766, 476766, 500...
python|pandas|merge
3
358,427
71,964,642
How to calculate number of days between 2 months in Python
<p>I have a requirement where I have to find number of days between 2 months where 1st month value is constant and 2nd month value is present in a data frame.</p> <p>I have to subtract 24th Feb with values present in the Data Frame.</p> <pre><code>past_2_month = date.today() def to_integer(dt_time): return 1*dt_tim...
<p>If need number of days between datetime column and 2 months shifted values use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.tseries.offsets.DateOffset.html" rel="nofollow noreferrer"><code>offsets.DateOffset</code></a> and convert timedeltas to days by <a href="http://pandas.pydata.org/p...
python|python-3.x|pandas
1
358,428
71,810,939
pandas manual way of one hot encode
<p>I have a dataframe as given below and trying to convert one hot encode it (kind of)</p> <pre><code>pd.DataFrame( {0: {0: 'eng', 1: 'eng', 2: 'mat', 3: 'fre', 4: 'soc', 5: 'eng', 6: 'eng', 7: 'mat', 8: 'fre', 9: 'soc'}, 1: {0: 'mat', 1: 'phy', 2: 'bio', 3: 'phy', 4: 'mat', 5: 'mat', 6: 'phy...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.get_dummies.html" rel="nofollow noreferrer"><code>pandas.get_dummies</code></a> on the stacked DataFrame, then get the max per level 0:</p> <pre><code>(pd .get_dummies(df.stack()) .groupby(level=0) .max() ) </code></pre> <p>Another approach is to <...
python|pandas|dataframe
1
358,429
71,885,845
How to dynamically loop over a numpy Nd-array's layers and save into a pandas dataframe
<p>I have a <code>NumPy Nd-array</code> and the shape of the array is <code>(3, 3, 2)</code>. I want to calculate the <code>mean</code> and <code>sd</code> of the array over each <code>set/layer</code> and want to save them in a pandas <code>dataframe</code>. I can do this using the following code</p> <pre><code>import...
<p>You can use the <code>axis</code> argument to take the means and stds over the appropriate axes of your array so you only need to write each once. Then join the results to one big DataFrame (can do all within <code>concat</code>, but split out here for clarity).</p> <pre><code>import numpy as np import pandas as pd ...
python|python-3.x|pandas|dataframe|numpy
0
358,430
71,916,159
Implement own function
<p>I am trying to implement my own function with the data set below:</p> <pre><code>import pandas as pd import numpy as np data = { 'sales': ['0','1','2','2','6','5','6'], } df = pd.DataFrame(data, columns = ['sales']) df </code></pre> <p>Now I want to apply my func...
<p>One way to fix it is to use <code>!=</code> instead of <code>&lt;&gt;</code> and use two comparisons. (I also changed the condition sequence to match what you described in the text of your question):</p> <pre class="lang-py prettyprint-override"><code>((sales != '6') &amp; (sales != '2')) </code></pre> <p>Full test ...
python|pandas
1
358,431
72,131,495
Unnesting json data from a DataFrame with missing values
<p>I'm new to python. I have a simple DataFrame with a .json string I'd like to unnest.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame([None, {'name': 'Charlie'}], columns=['A']) pd.json_normalize(df, record_path=['A'], meta=['name']) </code></pre> <p>The following is giving m...
<p>Try:</p> <pre><code>df = pd.json_normalize(df[&quot;A&quot;].fillna(&quot;&quot;).apply(dict).tolist()) </code></pre>
python|pandas
1
358,432
72,026,106
Given a (5,2) tensor, delete rows that have duplicates in the second column
<p>So, let's assume I have a tensor like this:</p> <pre><code>[[0,18], [1,19], [2, 3], [3,19], [4, 18]] </code></pre> <p>I need to delete rows that contains duplicates in the second column only by using tensorflow. The final output should be this:</p> <pre><code>[[0,18], [1,19], [2, 3]] </code></pre>
<p>You should be able to solve this with <code>tf.math.unsorted_segment_min</code> and <code>tf.gather</code>:</p> <pre><code>import tensorflow as tf x = tf.constant([[0,18], [1,19], [2, 3], [3,19], [4, 18]]) y, idx = tf.unique(x[:, 1]) indices = tf...
python|tensorflow|machine-learning|deep-learning
3
358,433
71,809,558
Efficient way to find row in df2 based on condition from value in df1
<p>I have two dataframes. df1 has ~31,000 rows, while df2 has ~117,000 rows. I want to add a column to df1 based on the following conditions.</p> <p>(df1.id == df2.id) and (df2.min_value &lt; df1.value &lt;= df2.max_value)</p> <p>I know that df2 will return either 0 or 1 rows satisfying the condition for each value of ...
<p>You can merge df1 and df2 based on the id column:</p> <pre class="lang-py prettyprint-override"><code>merged_df = df1.merge(df2, on='id', how='left') </code></pre> <p>Now, any row in DF1 for which the id matches an id of a row in DF2 will have all the DF2 columns placed alongside it. Then, you can simply filter the ...
python|pandas|dataframe|append
1
358,434
71,994,506
Exception: URL fetch failure for cifar10 dataset
<p>I've written a small python 2.8 set of code where I'm attempting to read the cifar10 images, but consistently get an Exception error. Here is my code:</p> <pre><code>import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras import datasets from tensorflow.keras.da...
<p>I think your problem is caused by the support of the <em>version</em> of <code>Python</code> that you are running, since if you do it in a more recent one <code>(3.7)</code> it does not return any error</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf # ver 2.x print(tf.version) from tenso...
python|tensorflow
0
358,435
72,069,254
Pandas to_excel( ) output float point is not right
<p>I have some a weird situation trying to get the output in to_excel pandas function.</p> <p>I tried to read a xlsx excel file with the number &quot;21631706.9893399&quot;, but when a try to write in a new xlsx excel file gives me the output &quot;21631706.98934&quot;. I tested with openpyxl and xlsxwriter but I got t...
<p>Set the format of the float as per your requirement</p> <pre><code>format = workbook.add_format({'num_format':'0.0000000'}] </code></pre> <p>For more details: <a href="https://xlsxwriter.readthedocs.io/example_pandas_column_formats.html" rel="nofollow noreferrer">https://xlsxwriter.readthedocs.io/example_pandas_colu...
excel|pandas|openpyxl|xlsxwriter|xlwt
1
358,436
71,972,459
ModuleNotFoundError: No module named 'numpy' AWS SageMaker Studio Lab
<p>I installed the numpy with Conda, pip and pip3, also tried installing from the requirements.txt file but I am still getting the following issue. Has anyone encountered this before and could please kindly suggest something?</p> <hr /> <p>ModuleNotFoundError Traceback (most recent call last) /tmp...
<p>numpy is built-in the default:Python environment in Studio Lab. If you open a new notebook with the File -&gt; New -&gt; Notebook, and choose the <code>default:Python</code> kernel, you should be able to import numpy without having to install the package. <a href="https://i.stack.imgur.com/U4pdq.png" rel="nofollow n...
numpy|amazon-sagemaker
0
358,437
71,851,749
Include tensorflow lite libraries in CMakeLists.txt of C++ project giving errors "undefined reference to `ruy::ScopedSuppressDenormals"
<p>I'm trying to include TensorFlow lite libraries in CMakeLists.txt of C++ project. I followed the instructure in <a href="https://www.tensorflow.org/lite/guide/build_cmake" rel="nofollow noreferrer">https://www.tensorflow.org/lite/guide/build_cmake</a></p> <blockquote> <ol> <li>git clone <a href="https://github.com/t...
<p>I found this repo that contains all needed libs for the project <a href="https://github.com/muhammedakyuzlu/tflite-cpp-package" rel="nofollow noreferrer">https://github.com/muhammedakyuzlu/tflite-cpp-package</a></p>
cmake|tensorflow-lite
0
358,438
72,120,322
python dataframe using nested for loop to get cost sum for flagged combination of 2 columns
<p>Supposed this is the first 3 rows of the dataset, rest looks similar. And there can be more than 3 books. lets say 6 books.</p> <pre><code>a=[['a',1,1,0,123],['b',1,0,1,153],['c',0,1,1,126]] df= pd.DataFrame(a,columns=['id','book1','book2','book3','cost']) print(df) id book_1 book_2 book_3 cost a 1 ...
<p>I think this is what you are after:</p> <pre><code>df[&quot;Total&quot;] = df[&quot;cost&quot;] * (df[&quot;book1&quot;]+df[&quot;book2&quot;]+df[&quot;book3&quot;]) df[&quot;Total&quot;].sum() </code></pre>
python|pandas|dataframe|for-loop
1
358,439
72,018,898
What is the best way to find y coordinates of point with specified x value in numpy array
<p>I am, usinf python an numpy array. I want to find all y coordinates of point with specified x coordinate. I use this:</p> <pre><code>[it[1] for it in arrP if it[0] == specX] </code></pre> <p>is there better way?</p>
<pre><code>arr = np.array([[1,2],[1,3],[2,3]]) # select x in arr with x[0] == 1, and slice out x[1] arr[arr[:, 0] == 1][:, 1] </code></pre> <p>Outputs</p> <pre><code>array([2, 3]) </code></pre>
python|numpy
2
358,440
71,842,514
Making an executable from python does not work
<p>I have for the past 6 hours been trying to make my code into an executable. I have used pyinstaller and have also tried auto-py-to-exe. However when I proceed to convert the file there is a bunch of missing modules etc. I have a couple import:</p> <pre><code>from calendar import Calendar from datetime import date im...
<p>Ok, so I made your code work on my side as an executable. I'd say the trick when using auto-py-to-exe for the first 'conversion to exe' time is to select 'Console Based' then once you have the output, launch it from the command line - so in case of errors you can see what is going on and adapt.</p> <p>Anyways, here'...
python|pandas|numpy|pyinstaller
1
358,441
72,002,445
Biweekly pandas data with period label
<p>I'm trying to create a biweekly periods from pandas data frame. For instance like that</p> <pre><code>import pandas as pd date_range = pd.date_range(&quot;2022-04-01&quot;, &quot;2022-04-30&quot;, freq=&quot;B&quot;) test_data = pd.DataFrame(np.arange(len(date_range)), index=date_range) </code></pre> <p>I'd like to...
<p>You can try <a href="https://pandas.pydata.org/docs/reference/api/pandas.Grouper.html" rel="nofollow noreferrer"><code>pandas.Grouper</code></a></p> <pre class="lang-py prettyprint-override"><code>df = test_data.groupby(pd.Grouper(freq='2W')).last() </code></pre> <pre><code>print(df) 0 2022-04-03 0 2...
python|pandas
0
358,442
71,900,317
No module named 'tensorflow.keras'
<p>I am trying to play around with a custom object detection model that builds of a pretrained model. All I want is for my model is to detect a specific logo in a picture. The problem is, the guide that I am following is having problems with the libraries.</p> <pre><code>import tensorflow as tf from imageai.Detection.C...
<p>Seems to be an issue with the latest <code>tensorflow==2.8.0</code>. <a href="https://github.com/tensorflow/tensorflow/issues/53144" rel="nofollow noreferrer">git issue</a></p> <p>For now, you can revert back to the older version of tensorflow</p> <pre><code>pip install tensorflow==2.7 </code></pre> <p>And upgrade i...
python|tensorflow|keras
1
358,443
71,939,604
Azure dataset .to_pandas_dataframe() error
<p>I am following an azure ml course on udemy and cannot get around the following error:</p> <p>Execution failed in operation 'to_pandas_dataframe' for Dataset(id='id', name='Loan Applications Using SDK', version=1, error_code=None, exception_type=PandasImportError)</p> <p>Here is the code for Submitting the Script:</p...
<p>When doing an experiment a new azure environment was created without pandas installed. To install pandas (if using anaconda nav) go onto environments in the anaconda nav window, click the azure env, go to uninstalled packages and search pandas, click install. It worked once this was done.</p>
python|pandas|azure|machine-learning|azure-machine-learning-service
1
358,444
71,995,105
How to export Pandas DataFrame to HTML but without any formatting?
<p>I want to export a DF with Pandas to an HTML formatted table, but I don't want any of the default styling that Pandas does to its tables, and would prefer just a bone-stock table. Is there an easy way to do this when using the to_html function?</p> <p>There isn't really a Minimal Reproducible Example since it is jus...
<p>For me working remove attributes after generate <code>html</code>:</p> <pre><code>df = pd.DataFrame( { &quot;a&quot;: [1] }) from bs4 import BeautifulSoup soup = BeautifulSoup(df.to_html(), features=&quot;lxml&quot;) for tag in soup.find_all(True): tag.attrs.clear() </code></pre> <hr /> <pre>...
python|python-3.x|pandas
0
358,445
71,833,085
Drop rows in a data frame that exist in another data frame
<p>I have data frame 1 that is my dataset, and data frame 2 that has the rows that I need to drop from df1 but that also currently exist in df 1.</p> <p>I am using the code <code>trades = trades[~trades_out3].reset_index(drop=True)</code> but that comes with the error TypeError: bad operand type for unary ~: 'DatetimeA...
<p>Here:</p> <pre><code>trades[trades.merge(trades_out3, on=list(trades.columns), how='left', indicator=True)[&quot;_merge&quot;] == 'left_only'] </code></pre> <p>The logic: merge the dataframes, only keep those that are in the left (first) dataframe.</p>
python|pandas|dataframe
0
358,446
71,985,492
Getting error appending into mysql database
<p>I am running into a weird error trying to append dataframe to MySQL table using pandas to_sql function. I have not been able to find answer to this anywhere. Here is a test example:</p> <pre><code>test_df = pd.DataFrame(['a','b','c','d'], columns = ['char']) with engine.begin() as connection: test_df.to_sql(nam...
<p>Thanks to the comment by Rouhollah. I made the &quot;append' to work by replacing</p> <pre><code>engine = create_engine(f&quot;mysql://{user}:{password}@{host}:{port}&quot;) </code></pre> <p>with</p> <pre><code>engine = create_engine(f&quot;mysql://{user}:{password}@{host}:{port}/{database}&quot;) </code></pre> <p>p...
python|mysql|pandas|sqlalchemy
0
358,447
71,932,616
Unpacking lists within a data frame into multiple TensorFlow inputs
<p>So I have a pandas data frame similar to this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>col1</th> <th>col2</th> <th>col3</th> </tr> </thead> <tbody> <tr> <td>[0,1,0]</td> <td>1</td> <td>0</td> </tr> <tr> <td>[1,0,0]</td> <td>0</td> <td>1</td> </tr> </tbody> </table> </div> <p>and ...
<p>You can try merging the lists with <code>pandas</code>:</p> <pre><code>import pandas as pd df = pd.DataFrame(data = {'col1': [[0,1,0], [1,0,0] ], 'col2': [1, 0], 'col3': [0, 1]}) df['col1-1'], df['col1-2'], df['col1-3'] = zip(*list(df['col1'].values)) df = df.drop('col1', axis=1) print(df) </code></pre> <pre><code...
python|list|tensorflow
1
358,448
72,121,591
Join 2 conditions using & operator
<p>i have 2 queries in pandas and need to join them together.</p> <pre><code>b.loc[b['Speed']=='100.0'] b.loc[b['Month']=='2022-01'] </code></pre> <p>I need to join them using &amp; but getting error of unsupported operand type.</p>
<p>You are comparing your data having different datatype with comparison value of <code>str</code>, while it should be float 64 and period M respectively as you have mentioned in your comment.</p> <p>Try to match your comparison with correct data type. try this:</p> <pre><code>b.loc[(b['Speed'] == 100.0) &amp; (b['Mont...
python|pandas|dataframe
0
358,449
71,797,106
Why are the indicators on my chart delayed by at least 1 day, making them not flush on the blue line? Is it because the time frame is too wide?
<p><a href="https://i.stack.imgur.com/td0yR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/td0yR.png" alt="" /></a></p> <p>Why are the up triangles, when the program is supposed to buy, not on the line when it crosses under, or in the other scenario, the down triangle, when the program is supposed t...
<p>The problem with this is that the point of intersection occurs between days, not on a specific day. As the data is not continuous, but rather just one point per business day, it is not possible to put the arrow on the intersection itself. I have enlarged a portion of the graph here so you can see what I mean. The...
python|pandas|numpy|matplotlib
1
358,450
71,924,127
Simulating expectation of continuous random variable
<p>Currently I want to generate some samples to get expectation &amp; variance of it.</p> <p>Given the probability density function: f(x) = {2x, 0 &lt;= x &lt;= 1; 0 otherwise}</p> <p>I already found that E(X) = 2/3, Var(X) = 1/18, my detail solution is from here <a href="https://math.stackexchange.com/questions/443016...
<p>You are generating the mean and variance of Y = 2X, when you want the mean and variance of the X's themselves. You know the density, but the <a href="https://en.wikipedia.org/wiki/Cumulative_distribution_function" rel="nofollow noreferrer">CDF</a> is more useful for random variate generation than the <a href="https:...
python|numpy|statistics|simulation|distribution
3
358,451
72,073,014
How to create a for loop with multiple constraints while appending to a new df?
<p>I tried to create a for loop with if statements that would append to a new df, but it's not working out. I am very new to this.</p> <p>This code is my try at an algorithm that decides whether ride is being shared or not, while following a number of constraints.</p> <pre><code>match = [] for all rows in d12: if ...
<p><strong>UPDATED:</strong></p> <p>Here is a way to:</p> <ul> <li>collect all matching rows with a configurable upper limit (in your original question you specified that a &quot;match can only be combined with two rows of the data&quot;, but it's not clear if you meant that only 2 rows in total can be included in a ma...
python|pandas|for-loop|if-statement
1
358,452
71,937,613
argmax index relatively to row
<p>I have following numpy array:</p> <pre><code>a = array([[0.25077832, 0.42227767, 0.43744429], [0.28539526, 0.44163316, 0.40298769], [0.35807141, 0.2856717 , 0.33536935], [0.55462028, 0.53807624, 0.38644028], [0.18301549, 0.26485082, 0.1366992 ], [0.26986122, 0.4...
<p>IIUC, you can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.divmod.html" rel="nofollow noreferrer"><code>np.divmod</code></a>:</p> <pre><code>np.divmod(a.argmax(), a.shape[1]) </code></pre> <p>or <a href="https://numpy.org/doc/stable/reference/generated/numpy.nditer.html" rel="nofollow noreferr...
python|numpy
2
358,453
71,835,359
Why would Pandas return blank cells after the dataframe is saved by Openpyxl?
<p>I have a large data set that I pull into pandas with read-excel. I use the data to create a new column then write the new column to Excel with openpyxl. The issue is that if I read that file again, the original data will be read as blank values. The only way around this I have found so far is to re-write the origina...
<p>Neither <code>openpyxl</code> nor <code>pandas</code> evaluate excel formulas. Opening a file in <code>pandas</code> is equivalent to opening the file with <code>openpyxl</code> in <code>data_only=True</code> mode.</p> <p>So here, when you save the file that you've written, a bunch of NaNs appear because excel never...
pandas|openpyxl
0
358,454
71,931,486
Strange performance from NumPy array2string
<p>I'm using NumPy's <code>array2string</code> function to convert the values in arrays into a string format for writing to a ascii file. It's simple and relatively quick for large arrays, and out performs a native python operating of string formatting in loop or with <code>map</code>.</p> <pre><code>aa = np.array2stri...
<p>A sample of using <code>savetxt</code> with small 2d array:</p> <pre><code>In [87]: np.savetxt('test.txt', np.arange(24).reshape(3,8), fmt='%5d') In [88]: cat test.txt 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 In [...
python|arrays|string|numpy|data-conversion
0
358,455
72,119,777
How do I create an if statement that checks for sheetnames that startwith a certain string in Python?
<p>My final objective is to create a column called 'Status' that indicates if active or cancelled based on the name of a sheet. I need it to check if the sheetname start with the word 'Full Member List'. If so then Active, else the Status column should be Cancelled. How do I do this below? I only need help with the one...
<p>In case you want to check for full string &quot;Full Member List&quot; in start of your sheetname.</p> <pre><code>temp['Status'] = &quot;Active&quot; if ws.startswith(&quot;Full Member List&quot;) else &quot;Cancelled&quot; </code></pre> <p>To check, if either of words &quot;Full&quot;, &quot;Member&quot;, &quot;Lis...
python|pandas|startswith
1
358,456
16,888,736
pandas assigning series view to a series view doesn't work?
<p>I'm trying to take a slice view from a series (logically indexed by a conditional), process it then assign the result back to that logically-indexed slice. The LHS and RHS in the assign are Series with matching indices, but the assign ends up being scalar for some unknown reason (see bottom). How to get the desired ...
<pre><code>In [21]: df = pd.DataFrame(data={'x': range(1,20)}) In [22]: df['cond'] = df.x.apply(lambda xx: ((xx%3)==1) ) In [23]: df Out[23]: x cond 0 1 True 1 2 False 2 3 False 3 4 True 4 5 False 5 6 False 6 7 True 7 8 False 8 9 False 9 10 True 10 11 False 11 12 ...
python|pandas|dataframe|slice|series
1
358,457
16,844,494
How to import itertools in Python 3.3.2
<p>I'm running python (through IDLE, though I'm not sure what that is) on a Mac, version 3.3.2, and for some reason when I type <code>from itertools import *</code> it doesn't allow me to then use commands like <code>chain</code> and <code>combinations</code>. Additionally I can't seem to import <code>numpy</code> so I...
<p>Firstly, you don't actually have a problem here. <code>itertools.chain()</code> does not return a list, it returns an iterable object. This is preferable as it is lazy (the values are not computed until they are needed) which is more memory-efficient.</p> <p>It's worth noting if this had been an issue with importin...
python|numpy|module
4
358,458
17,116,115
Row manipulation in python
<p>I'm trying to get a csv into a .gexf format file for a dynamic gephi graph. The idea is to have all the parallel edges (edges with the same source and target but different post dates) contained in the attribute data. In the example, all of the dates in the attribute correspond to the posting dates for John answering...
<p>Look at the <a href="http://pandas.pydata.org/" rel="nofollow">Python pandas</a> project, which is designed to simplify this kind of operation. An example of how it can group and parse your data....</p> <pre><code># Load your CSV as a pandas 'DataFrame'. In [13]: df = pd.read_csv('your file', names=['source', 'targ...
python|csv|pandas|gephi
3
358,459
16,920,653
How to read a float from a raw binary file written with numpy's tofile()
<p>I am writing a <code>float32</code> to a file with numpy's <code>tofile()</code>.</p> <pre><code>float_num = float32(3.4353) float_num.tofile('float_test.bin') </code></pre> <p>It can be read with numpy's <code>fromfile()</code>, however that doesn't suit my needs and I have to read it as a raw binary with the hel...
<p>The problem is that numpy's <code>float32</code> is stored as little endian and bitstrings default implementation is bigendian. The solution is to specify little endian as the data type.</p> <pre><code>my_file = open('float_test.bin', 'rb') raw_data = ConstBitStream(my_file) float_num_ = raw_data.readlist('floatle:...
python|numpy|bitstring
5
358,460
17,037,433
fillna : how to pad values over the next x days
<p>I have a dataframe with several columns and indexed by dates. I would like to pad missing values but only for the next x days. It means that a missing value will not be padded if its difference in index is more than x days with the previous non missing value in this column.</p> <p>I did something with a loop but it...
<p>You can use the <code>limit</code> argument of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="noreferrer"><code>fillna</code></a>:</p> <pre><code>df.fillna(method='ffill', limit=3) # ffill is equivalent to pad </code></pre> <p><em>The same argument is available f...
pandas
7
358,461
17,092,671
Python pandas: output dataframe to csv with integers
<p>I have a <code>pandas.DataFrame</code> that I wish to export to a CSV file. However, pandas seems to write some of the values as <code>float</code> instead of <code>int</code> types. I couldn't not find how to change this behavior.</p> <p>Building a data frame:</p> <pre><code>df = pandas.DataFrame(columns=['a','b'...
<p>The answer I was looking for was a slight variation of what @Jeff proposed in his answer. The credit goes to him. This is what solved my problem in the end for reference:</p> <pre class="lang-py prettyprint-override"><code>import pandas df = pandas.DataFrame(data, columns=['a','b','c','d'], index=['x','y','z']) df =...
python|csv|dataframe|pandas
18
358,462
18,945,563
Pandas Dataframe merging columns
<p>I have a pandas dataframe like the following</p> <pre><code>Year Month Day Securtiy Trade Value NewDate 2011 1 10 AAPL Buy 1500 0 </code></pre> <p>My question is, how can I merge the columns <code>Year</code>, <code>Month</code>, <code>Day</code> into column <code>NewDate</code> so that t...
<p>df['Year'] + '-' + df['Month'] + '-' + df['Date']</p>
pandas
1
358,463
19,070,057
Python show a two-dimensional PDF function
<p>Is there any elegant way of showing a two-dimensional PDF function?</p> <p>I have a function F(x,y) and I want to illustrate it.</p> <p>Here is one solution:</p> <p>Generate a meshgrid and calculate the value of each point, then use imshow()</p> <pre><code> 1 1.5 2 2.5 3 3.5 ----------------------- ...
<p>You can use <code>meshgrid</code> to make the coordinates:</p> <pre><code>import numpy as np x = np.linspace(1, 3.5, 6) y = np.linspace(1, 3, 5) X, Y = np.meshgrid(x, y) </code></pre> <p>And then apply your <code>F</code> at each point:</p> <pre><code>z = np.array([F(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))]...
python|numpy|matplotlib|plot
3
358,464
19,214,922
sampling pandas dataframe by different frequencies
<p>I have a multi-index series/dataframe with ID and timestamp as key. This data structure has daily data for various IDs. Can I use the resample function to look at end of the month snapshot of this data structure ? </p> <pre><code>ID ts value 1 2001-01-30 1 2001-01-31 2 2001-02-01 3 2 2001-0...
<p>Why do you need to resample? Just set the index to <code>ts</code> and then slice, like so:</p> <pre><code>from cStringIO import StringIO raw = """id ts value 1 2001-01-30 1 1 2001-01-31 2 1 2001-02-01 3 2 2001-01-30 3 2 2001-01-31 2 2 2001-02-01 4""" sio = StringIO(raw) df = read_csv(sio, se...
python|pandas
1
358,465
18,760,903
Fit a curve using matplotlib on loglog scale
<p>I am plotting simple 2D graph using loglog function in python as follows:</p> <pre><code>plt.loglog(x,y,label='X vs Y'); </code></pre> <p>X and Y are both lists of floating numbers of <code>n</code> size.</p> <p>I want to fit a line on the same graph. I tried numpy.polyfit , but I am getting nowhere.</p> <p>How ...
<p>Numpy doesn't care what the axes of your matplotlib graph are. </p> <p>I presume that you think <code>log(y)</code> is some polynomial function of <code>log(x)</code>, and you want to find that polynomial? If that is the case, then run <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html#...
python|numpy|matplotlib
19
358,466
19,010,774
combining pandas dataframes of different sampling rates
<p>I have three pandas dataframes containing data that was recorded during a test. One frame is for temperature, the other for vacuum, and the other for voltage.</p> <p>The data was captured independently, so that time values for each frame don't line up. Only occasionally does a time stamp from one frame have a dupli...
<pre><code>import pandas as pd import numpy as np rng1 = pd.date_range( '1/1/2012', periods=10, freq='H' ) s1 = pd.Series( np.arange(10), index=rng1 ) df1 = pd.DataFrame( {'temp': s1} ) s2 = pd.Series( np.arange(5, 10), index=['1/1/2012 01:20:00', '1/1/2012 01:40:00', ...
python|pandas
6
358,467
19,126,120
extra rows to extra columns with pandas
<p>EDIT I figured it out - was easier than I thought - just had to set index to true - see below</p> <pre><code>import numpy as npg import pandas as pd original_data = np.array([[1,0,0,10,1530,0.1,2,-49.0756686364,163.856504545], [1,0,0,10,8250,0.1,2,-84.7795213636,264.205363636], [1,0,0,10,20370,0.1,...
<p>This code works for me!</p> <pre><code>import numpy as np import pandas as pd original_data = np.array([[1,0,0,10,1530,0.1,2,-49.0756686364,163.856504545], [1,0,0,10,8250,0.1,2,-84.7795213636,264.205363636], [1,0,0,10,20370,0.1,2,-245.585863636,662.467227273], [1,0,0,10,33030,0.1,2,-290.468136364,1...
python|pandas
2
358,468
19,182,466
Vectorizing ndimage functions for my code
<p>I want to be able to vectorize this code:</p> <pre><code>def sobHypot(rec): a, b, c = rec.shape hype = np.ones((a,b,c)) for i in xrange(c): x=ndimage.sobel(abs(rec[...,i])**2,axis=0, mode='constant') y=ndimage.sobel(abs(rec[...,i])**2,axis=1, mode='constant') hype[...,i] = np.hy...
<p>Here's how you can avoid the for-loop with the sobel filter:</p> <pre><code>import numpy as np from scipy.ndimage import sobel def sobHypot_vec(rec): r = np.abs(rec) x = sobel(r, 0, mode='constant') y = sobel(r, 1, mode='constant') h = np.hypot(x, y) h = np.apply_over_axes(np.mean, h, [0,1]) ...
python|python-2.7|numpy|scipy
0
358,469
22,232,566
Join Two Dataframes
<p>I have two data sets which I get into two data frames</p> <pre><code> NAB.AX CBA.AX Close Volume Close Date Date 2013-10-02 06:52:32 36.51 49...
<p>You could reassign the second DataFrame's index to numpy <code>datetime64[s]</code> values:</p> <pre><code>df2.index = df2.index.values.astype('datetime64[s]') </code></pre> <hr> <p>For example,</p> <pre><code>In [58]: df1 = pd.DataFrame({'Close':36.51}, index=pd.DatetimeIndex(['2013-10-02 06:52:32'])); df1 ...
python|join|pandas|time-series|dataframe
1
358,470
22,412,309
Set color per point 3d plot numpy/scipy
<p>I have a set of data points from a kinect in the form of [x,y,z,r,g,b] and I want to plot [x,y,z] setting the point to [r,g,b]. The only thing I've been able to accomplish so far is to change the color per row as plot requires a distribution as far as I can tell.</p> <p>This is my code so far:</p> <pre><code>i = 0...
<p>the <code>c</code> argument of <code>scatter</code> can receive a array of shape (N, 3) with values between 0 to 1 which represent color in RGB:</p> <pre><code>from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax = fig.gca(projection='3d') x = np.random....
python-3.x|numpy|matplotlib|scipy
1
358,471
22,104,658
Image registration, construction of Composite Image
<p>I'm working in an image registration algorithm. I have the <strong>reference image(I1)</strong> and the <strong>sensed image(I2)</strong>. The images are numpy arrays. </p> <p>I implemented an fft algorithm that take <strong>I1</strong> and <strong>I2</strong> and returns a new image(<strong>I3</strong>) that is th...
<p>Use <code>skimage.transform.AffineTransform</code> to represent the transformations. Apply them to the individual images using <code>skimage.transform.warp</code>. While you can implement your own blending algorithms, I'd recommend Enblend (<a href="http://enblend.sf.net" rel="nofollow">http://enblend.sf.net</a>)....
python|image-processing|numpy
0
358,472
22,071,116
Converting Pandas dates to Chaco compliant dates
<p>[EDIT </p> <ul> <li>here is the source file <a href="https://www.dropbox.com/s/gyem3zgjzl6jtou/AAPL_result.pickle" rel="nofollow noreferrer">https://www.dropbox.com/s/gyem3zgjzl6jtou/AAPL_result.pickle</a></li> </ul> <p>EDIT]</p> <p>I want to plot the dates from my pandas DataFrame on the axes in my Chaco plot</p...
<p>I think the following represents something like the current best practice for plotting Pandas DataFrames with DateTime indices:</p> <pre><code>import numpy as np from pandas import DataFrame, date_range from chaco.api import ArrayPlotData, PlotAxis from chaco.shell.scaly_plot import ScalyPlot from chaco.scales.api...
python|pandas|chaco
0
358,473
22,251,001
TypeError when trying to join Pandas dataframe by index
<p>I'm trying to join a column from one <code>pandas dataframe</code> to another using its date as the index. However my code produces a <code>TypeError</code>. Please could somebody explain why this error's being produced and what I can do to fix it?</p> <p>Thanks in advance.</p> <pre><code>"""Balsjo THg, MeHg, TOC ...
<p>I think you should have done this instead:</p> <pre><code>cln_df22 = cln_df2.append(df3[['MeHg (ng/L)']]) ^ ^ you need to use brackets/parentheses instead of square brackets </code></pre>
join|pandas
0
358,474
22,037,360
KeyError when writing NumPy values to GEXF with NetworkX
<p>Hi everyone I 'd like to compute node coordinates and then export graph to GEXF and process it with Gephi. However when I run the following code</p> <pre><code>import networkx as nx import numpy as np .... area_ratios = [np.sum(new[:,0])/Stotal, np.sum(new[:,1])/Stotal, np.sum(new[:,2])/Stotal] X = np.array([0, -sq...
<p>Looks like this was solved a long time ago but I found that my code was having a similar problem using float values from a pandas data frame. The solution was in the comments but it took me a while to figure it out so I thought I might clarify. </p> <p>If you are making your nodes from a dataframe like this:</p> ...
python|numpy|networkx
5
358,475
18,058,744
Passing a numpy pointer (dtype=np.bool) to C++
<p>I'd like to use a numpy array of type bool in C++ by passing its pointer via Cython. I already know how to do it with other datatypes like uint8. Doing it the same way with boolean it does not work. I am able to compile but there is the following Exception during runtime:</p> <pre><code>Traceback (most recent call ...
<p>It looks like the problem is with the array type declaration. According to the documentation at <a href="https://cython.readthedocs.org/en/latest/src/tutorial/numpy.html" rel="noreferrer">https://cython.readthedocs.org/en/latest/src/tutorial/numpy.html</a> boolean arays aren't yet supported, but you can use them by ...
c++|python|numpy|boolean|cython
12
358,476
17,926,273
How to count distinct values in a column of a pandas group by object?
<p>I have a pandas data frame and group it by two columns (for example <code>col1</code> and <code>col2</code>). For fixed values of <code>col1</code> and <code>col2</code> (i.e. for a group) I can have several different values in the <code>col3</code>. I would like to count the number of distinct values from the third...
<pre><code>df.groupby(['col1','col2'])['col3'].nunique().reset_index() </code></pre>
python|group-by|pandas
27
358,477
4,523,267
NumPy Under Xen Client System
<p>I am working on a project built on NumPy, and I would like to take advantage of some of NumPy's optional architecture-specific optimizations. If I install NumPy on a paravirtualized Xen client OS (Ubuntu, in this case - a Linode), can I take advantage of those optimizations?</p>
<p>Yes. The optimizations run in userland and so shouldn't cause any PV traps.</p>
python|ubuntu|numpy|virtualization|xen
1
358,478
4,375,617
numpy: compute x.T*x for a large matrix
<p>In <code>numpy</code>, what's the most efficient way to compute <code>x.T * x</code>, where <code>x</code> is a large (200,000 x 1000) dense <code>float32</code> matrix and <code>.T</code> is the transpose operator?</p> <p>For the avoidance of doubt, the result is 1000 x 1000.</p> <p><strong>edit</strong>: In my o...
<p>This may not be the answer you're looking for, but one way to speed it up considerably is to use a gpu instead of your cpu. If you have a decently powerful graphics card around, it'll outperform your cpu any day, even if your system is very well tuned.</p> <p>For nice integration with numpy, you could use theano (i...
python|numpy|scipy|matrix-multiplication|transpose
10
358,479
8,918,773
'Memory leak' when calling openopt SNLE in a loop
<p>Whenever I run the solver 'interalg' (in the SNLE function call from OpenOpt) in a loop my memory usage accumulates until the code stops running. It happen both in my Mac Os X 10.6.8 and in Slackware Linux. I would really appreciate some advice, considering that I am not extremely literate in python.</p> <p>Thank y...
<p>Yes, there is clearly a memory leak here. I ran the nlsp demo, that uses SNLE with interalg, using valgrind and found that 295k has been leaked from running the solver once. This should be reported to them.</p>
python|memory-leaks|numpy|scipy
2
358,480
55,167,858
Plotting equations as lines in Bokeh - Python
<p>I'm creating an XY chart in Bokeh with a 1:1 line and ideally two more lines for +/- 10% error and +/- 20% errors. At the moment my chart works but seems unpythonic and shows too many legend entries. The code at present:</p> <pre><code>import pandas as pd from bokeh.plotting import figure, output_file, save from b...
<p>You can't multiply a list by a float. If I understand correctly, something like this should get the result you want:</p> <pre><code>q = [0, 10000] r = [q[0],q[1]*1.1] </code></pre> <p>And replace the * 1.1 with 0.9, 1.2 and 0.8 for the other variations you wish to reference to q.</p>
python|pandas|numpy|bokeh
1
358,481
55,385,547
Split value in Pandas dataframe into to values and make rows for new values
<p>I am trying to split the volume for a billing line by source. The billing line data volume is reported as one value, but I know that 55% of the volume originates from Source A, and 45% originates from Source B. How would I create new rows in my Pandas dataframe to split the row into two rows, one for each source?</p...
<p>We using <a href="https://stackoverflow.com/questions/53218931/how-do-i-unnest-explode-a-column-in-a-pandas-dataframe/53218939#53218939">unnest</a> </p> <pre><code>before['pct']=[[0.45,0.55]]*len(before) before['Source']=[['a','b']]*len(before) unnesting(before,['pct','Source']).eval('Count=Count*pct') Out[395]: ...
python-3.x|pandas
0
358,482
55,438,743
how to create the new df from the existing df with only specific column
<p>i am having the one data frame called matches and which contains the following column: <code>id,season,city,date,team 1,team 2,toss_winner,toss_decision,result,DL_applied winner,win_by_runs,win_by_wickets,player_of_match,venue,umpire 1,umpire 2, umpire 3</code>.</p> <p>from this i need to create the new data frame...
<pre><code>matches_compact=matches[['id','season','date','winner']] </code></pre>
pandas
1
358,483
55,351,982
Is there a way to permute a subset of a matrix?
<p>I'm working on a way to find the lowest 1-Norm of a given Matrix using a permutation of its rows. The problem is that the permutation can't be fully random. There are 4 subsets of rows in the Matrix having a special parameter. I want to permute just the rows having this one parameter and keeping those on the same sp...
<p>You just have to carefully define your permutations. Fancy indexing will then do the job :</p> <p>Example :</p> <pre><code>from numpy.random import randint M0 = randint(10,size=(5,5)) after=[4,2,3,1,0] M0 = M[after] print(M0) print(M) [[4 9 3 0 0] [3 1 7 6 0] [6 6 5 0 9] [0 4 7 1 3] [0 0 1 0 6]] [[0 0 1 0 6]...
python|numpy|scipy|permutation
0
358,484
55,215,067
Jupyter Notebook output inconsistent across browsers
<p>I'm trying to draw a table on Jupyter Notebook, but the outputs are not consistent across browser. For instance, the spacing works well in Chrome, but not in firefox. Also I can't use pandas Dataframe's <code>display()</code> due to some limitations and have to draw it manually. Any ideas on how to make it print pro...
<p>The difference between browsers is probably because they have different default monospace font settings. </p> <p>But if you're looking to produce the exact same styling across browsers, <a href="https://stackoverflow.com/a/27031060/7315159">this answer</a> about adding custom CSS to ipython notebooks may be what yo...
python|pandas|jupyter-notebook
4
358,485
55,143,375
Concat excel files and worksheets into one using python
<p>I have many excel files in a directory, all of them has the same header row. Some of these excel files has multiple worksheets which again have the same headers. I'm trying to loop through the excel files in the directory and for each one check if there are multiple worksheets to concat them as well as the rest of t...
<p>Your <code>for</code> statement is setting <code>excel_names</code> to each filename in turn (so a better variable name would be <code>excel_name</code>):</p> <pre><code>for excel_names in glob.glob('*.xlsx'): </code></pre> <p>But inside the loop your code does</p> <pre><code>df = pd.read_excel(excel_names[i], sh...
python|excel|pandas|concat
1
358,486
55,369,147
Another work around this "TypeError: Cannot iterate over a scalar tensor" for matplotlib?
<p>TypeError: Cannot iterate over a scalar tensor.</p> <p>Two tensor scalars are input for plt.bar() for the (x, y) values. (Converting CamDavidsonPilon Bayesian-Hackers to tensorflow2.0)</p> <p>This is specifically for the "def plot_artificial_sms_dataset():" function. I tried in the code block above and it works i...
<p>x.numpy(), y.numpy() converts 'x' and a 'y' to numpy arrays</p>
python-3.x|tensorflow2.0
2
358,487
55,573,383
AttributeError: 'module' object has no attribute 'ceil'
<p>I have installed the module onnx_tf from this <a href="https://www.tensorflow.org/install#installing_from_sources" rel="nofollow noreferrer">link</a>.</p> <p>After that when I am verifying the installation as <code>python -c "import onnx_tf"</code> I am encountering the following error. How do I resolve it? Thank y...
<p>The following resolved this issue for me:</p> <ol> <li>pip uninstall onnx-tf</li> <li>pip install git+https://github.com/onnx/onnx-tensorflow.git</li> <li>pip install tensorflow-addons</li> </ol> <p>(Using TensorFlow 2.3 and Python 3.8)</p>
tensorflow|pip|installation|onnx
1
358,488
55,330,912
Pandas dataframe multi-index selecting first index first element
<p>This must be a simple question, but its taking too much time to slice a pandas multi-index dataframe for me. So I seek for help.</p> <p>I have a dataframe like this: (incomplete)</p> <pre><code>Product_Category Category_001 Category_002 Category_003 Category_004 \ Warehouse Year ...
<p>Try with <code>.loc</code> </p> <pre><code>df.loc[['Whse_A']] </code></pre>
python|pandas
2
358,489
55,529,044
Forecasting apple stock
<p>I'm trying to create a machine learning model to forecast apple stocks, first time trying and really based most from YouTube videos. But I don't really understand the cause of the error. I already try separated the function but that asked to reshape the arrays and use numpy arrays.</p> <pre><code>import pandas as p...
<p>The errors that I spot (please, provide error log):</p> <p>This is obviously an error</p> <pre><code>dates = np.reshape,(len(dates),1) </code></pre> <p>which should be something like: </p> <pre><code>dates = np.reshape(dates, (len(dates),1)) </code></pre> <p>Also, when you fit the SVRs you are giving as X the d...
python|pandas|machine-learning|scikit-learn|non-linear-regression
0
358,490
55,349,129
Python Pandas keep the first occurence of a specific value and drop the rest of rows with the same specific value
<p>I cannot figure out how to get rid of rows (but keep the first occurence and get rid of every row that has the value) with some condition. </p> <p>I tried using drop_duplicate but this will get rid of everything. I just want to get rid of some rows with a specific value (Within the same column)</p> <p>Data is for...
<p>Use <code>idxmax</code> and check the index. This of course assumes your index is unique.</p> <pre><code>m = df.Col_A.eq(1) # replace 1 with your desired bad value df.loc[~m | (df.index == m.idxmax())] </code></pre> <p></p> <pre><code> Col_A Col_B 0 5 1 1 5 2 2 ...
python|pandas
1
358,491
55,267,538
PyTorch specify model parameters
<p>I am trying to create a convolutional model in PyTorch where</p> <ul> <li><strong>one layer is fixed</strong> (initialized to prescribed values)</li> <li><strong>another layer is learned</strong> (but initial guess taken from prescribed values).</li> </ul> <p>Here is a sample code for model definition:</p> <pre><...
<p>Just wrap the learnable parameter with <code>nn.Parameter</code> (<code>requires_grad=True</code> is the default, no need to specify this), and have the fixed weight as a Tensor without <code>nn.Parameter</code> wrapper.</p> <p>All <code>nn.Parameter</code> weights are automatically added to <code>net.parameters()<...
model|pytorch
2
358,492
55,301,343
Plotly: How to define the structure of a sankey diagram using a pandas dataframe?
<p>This may sound like a very broad question, but if you'll let me describe some details I can assure you it's <strong><em>very specific</em></strong>. As well as discouraging, frustrating and rage-inducing.</p> <hr> <p>The following plot describes a scottish election and is based on code from <a href="https://plot.l...
<p>This problem looks really strange, but only until you will analyze how the sankey plot in <code>plotly</code> is created:</p> <p>When you create the sankey plot, you send to it:</p> <ol> <li>Nodes list</li> <li>Links list</li> </ol> <p>These lists are bounded with each other. When you create the 5-length node lis...
python|pandas|jupyter-notebook|plotly|sankey-diagram
22
358,493
55,244,562
add data to dataframe in pandas
<p>I'm trying to add data of a specific datatype to a new dataframe, however, the code returns an empty dataframe. I tried doing it with just one entry to see if that's the problem</p> <pre><code>date = pd.DataFrame(columns=['Date']) date.append(pd.Series(report2.loc[1,'Serv']), ignore_index=True) print(date) </code>...
<p>You have to reassign <code>date</code>: </p> <pre><code>date = pd.DataFrame(columns=['Date']) date = date.append(pd.Series(report2.loc[1,'Serv']), ignore_index=True) print(date) </code></pre> <p>Indeed, according to the documentation, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Data...
python|pandas
0
358,494
55,505,516
Is there a reason a ML model would converge quickly on a substantial amount of training data?
<p>I am building a simple machine learning model using keras. I'm hoping to set the model up to perform scalar regression. The model I built reached convergence on the training loss incredibly quickly, after approximately 9 epochs. The training data consists of around 84000 examples consisting of 6 features.</p> <p>I ...
<p>By "speed" I assume you mean the <em>number of steps</em> to convergence. In this case, convergence speed has nothing to do with the hardware used -- that just improves the <em>time</em> (leaving aside the small effects that accelerators may have on numerical accuracy). The code you posted looks like a very simple m...
python|tensorflow|keras
1
358,495
55,442,330
How do I count how often a column value changes in a pandas dataframe
<p>I have a pandas data frame like this:</p> <pre><code> id some_value 0 tag1 v1 1 tag1 v2 2 tag1 v1 3 tag2 v2 4 tag2 v2 5 tag2 v3 </code></pre> <p>and I would like to know how often for each id the value in <code>some_value</code> changed. So for <code>tag1</code> that would be twic...
<p>One way to achieve this would be:</p> <pre><code>def numChanges(x): return sum(x.iloc[:-1] != x.shift(-1).iloc[:-1]) df.groupby('id').agg({ 'some_value' : numChanges }) </code></pre> <p>Please note that if the id column is unsorted, the results would differ, so your solution may produce incorrect results,...
python|pandas
2
358,496
55,245,859
pivot headers into rows
<p>I have an excel file with 2 rows as headers that looks like this:</p> <pre><code> Day1 Day2 X Y Z X Y Z product1 10 12 5 18 22 6 product2 9 100 88 123 4 56 </code></pre> <p>If I read this file with pandas, what can I do to make it appear like ...
<p>This is how to do it:</p> <pre><code>df = pd.read_excel('data_to_pivot.xlsx', index_col=0, header=[0,1]) print(df) </code></pre> <pre><code> Day1 Day2 X Y Z X Y Z product1 10 12 5 18 22 6 product2 9 100 88 123 4 56 </code></pre> <pre><code>df ...
python|pandas
0
358,497
55,425,356
Convert a string which is list to list
<p>I have a data frame like</p> <pre><code>query ----------- [] [(apple,10),(orange,15)] [(apple,2),(orange,5)] </code></pre> <p>python is reading this as a string instead of a list because when I do <code>df['query'].apply(lambda x: len(x))</code> I get 2 instead of 0 for the first row. Is there a way to convert th...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.apply.html" rel="nofollow noreferrer">apply()</a>:</p> <pre><code>df['query'] = df['query'].apply(lambda x: x.strip('[]').split(',')) </code></pre> <p>os, by list comprehension:</p> <pre><code>df['query'] = [x.strip('[]'...
python|pandas|dataframe
1
358,498
55,154,276
DLL load failed(unable to import tensorflow)
<p>This's my first time to ask question on stack overflow, thanks for the browse of my question! While I'm trying to debug a program(written in python) in Visual Studio Code, as I enter "python .\dnn_example.py", it doesn't output the result, but blocked out this message(the white frame, and it means "which software ...
<p>It seems like you have not installed tensorflow. Try installing it using conda by <code>conda install tensorflow</code> or if you don't use conda, install it using pip by <code>pip install tensorflow</code>. If you want to run tensorflow on GPU then follow <a href="https://medium.com/@soumyadipmajumder/complete-gui...
python|tensorflow
0
358,499
55,454,575
creating dataframe from csv file having lists as entries in one of the columns
<p>I have a <code>csv</code> file which looks like this -</p> <pre><code>id genres 1 [{'id': 35, 'name': 'Comedy'}] 2 [{'id': 35, 'name': 'Comedy'}, {'id': 18, 'name': 'Drama'}, {'id': 10751, 'name': 'Family'}, {'id': 10749, 'name': 'Romance'}] 3 [1,2,3] 4 [{'id':31, 'name':'Comedy'}] </code></pre> <p>When I...
<p>Use:</p> <pre><code>import ast, json df['genres'] = df['genres'].apply(ast.literal_eval) </code></pre> <p>Or:</p> <pre><code>df['genres'] = df['genres'].apply(json.loads) </code></pre>
python|pandas
2