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
2,500
56,818,822
How can I weigh columns in data frame and add them up
<p>I have a data frame with 5 columns, I only want to add the second and the third, but each point in the third column has to be <strong>multiplied by 3</strong>,<br><br> so I need to add a new column called <br> <code>"Total score" which is df['Second'] + 3* df['Third']</code></p> <p>I have tried with sum but I don't...
<p>Make sure your columns is order correctly, then we can using <code>dot</code> </p> <pre><code>df['Total Score'] = df.dot([0,1,3,0,0]) </code></pre> <p>Or to be safe </p> <pre><code>df['Total Score'] = df[['Second','Third']].dot([1,3]) </code></pre>
python|python-3.x|pandas|dataframe
1
2,501
56,841,451
Why is my neural net only predicting one class (binary classification)?
<p>I am having some trouble with my ANN. It is only predicting '0.' The dataset is imbalanced (10:1), ALTHOUGH, I undersampled the training dataset, so I am unsure of what is going on. I am getting 92-93% accuracy on the balanced training set, although on testing (on an unbalanced test set) it just predicts zeroes. Uns...
<p>This is not right:</p> <pre><code>y_pred_bool = np.argmax(y_pred, axis=1) </code></pre> <p>Argmax is only used with categorical cross-entropy loss and softmax outputs. For binary cross-entropy and sigmoid outputs, you should round the outputs, which is equivalent to thresholding predictions > 0.5:</p> <pre><code>...
python|tensorflow|keras|neural-network
2
2,502
56,704,844
How to exclude current date in a group by value rolling window execution in pandas?
<p>I have a dataframe containing IDs, a date and numerical values. I group the data for each ID, and then I calculate the cumulative amount of the previous rows, with a time window of 30 days. In the dataframe below this has been accomplished using the code below (the actual dataframe contains more than one ID and more...
<p>Because you have several values for a same day, I would say you should first <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.resample.html" rel="nofollow noreferrer"><code>resample</code></a> daily to get the <code>sum</code> per day and then <a href="https://pandas.pydata.org/pa...
python|pandas|dataframe
4
2,503
25,464,589
RcppCNPy not usable after Rcpp update
<p>I am trying to use some older code that relies on RcppCNPy, which used to work on my machine. At some point in the past few months I updated Rcpp and now when I try to attach the RcppCNPy library (<code>library() or require()</code>) I get the following:</p> <pre><code>*** caught segfault *** address 0x0, cause 'me...
<p>Recompilation ought to work. Check that you do not have an old version in your <code>.libPath()</code>.</p> <p>CRAN does checks on packages on would alert the respective maintainer (me, in this case) if RcppCNPy were broken on the Mac. See</p> <ul> <li><a href="http://cran.rstudio.com/web/checks/check_results_Rcpp...
r|numpy|rcpp
0
2,504
66,906,422
Unable to create a version in Cloud AI Platform using custom containers for prediction
<p>Because of certain VPC restrictions I am forced to use custom containers for predictions for a model trained on Tensorflow. According to the <a href="https://cloud.google.com/ai-platform/prediction/docs/custom-container-requirements" rel="nofollow noreferrer">documentation</a> requirements I have created a HTTP serv...
<p>Answering this myself after working with the Google Cloud Support Team to figure out the error.</p> <p>Turns out the port I was creating a <code>Version</code> on was conflicting with the Kubernetes deployment on Cloud AI Platform's side. So I changed the <code>Dockerfile</code> to the following and was able to succ...
docker|tensorflow|google-cloud-platform|tensorflow-serving|google-cloud-ml
2
2,505
67,101,069
Efficient Way to Repeatedly Split Large NumPy Array and Record Middle
<p>I have a large NumPy array <code>nodes = np.arange(100_000_000)</code> and I need to rearrange this array by:</p> <ol> <li>Recording and then removing the middle value in the array</li> <li>Split the array into the <code>left</code> half and <code>right</code> half</li> <li>Repeat Steps 1-2 for each half</li> <li>St...
<p>Edit: The question has been updated to have a much smaller input array so I leave the below for historical reasons. Basically it was likely a typo but we often get accustomed to computers working with insanely large numbers and when memory is involved they can be a real problem.</p> <p>There is already a numpy based...
python|performance|numpy
1
2,506
66,922,956
How to convert list of dictionaries from CSV to dataframe?
<p>I have list of dictionaries from CSV with header test as follows:</p> <pre><code>[{'points': 50, 'time': '5:00', 'year': 2010}, {'points': 25, 'time': '6:00', 'month': &quot;february&quot;}, {'points':90, 'time': '9:00', 'month': 'january'}, {'points_h1':20, 'month': 'june'}] </code></pre> <p>when I use pd.DataFr...
<p>The reason your code failed is that your input file is actually <strong>not</strong> any CSV file. It is a <strong>string representation</strong> of your list of dictionaries (not a list of dictionaries).</p> <p>I assume that your input file contains what you put as the first sample.</p> <p>To handle such an input f...
python|pandas|jupyter-notebook
0
2,507
68,132,060
Drop only Nan values from a row in a dataframe
<p>I have a dataframe which looks something like this:</p> <pre><code>Df lev1 lev2 lev3 lev4 lev5 description RD21 Nan Nan Nan Nan Oil Nan RD32 Nan Nan Nan Oil/Canola Nan Nan RD33 Nan Nan Oil/Canola/Wheat Nan Nan RD34 Nan Nan Oil/Canola/Flour N...
<p>You can use stack and groupby like this to find the fist non null value,</p> <pre><code>df['code'] = df[['lev1', 'lev2', 'lev3', 'lev4', 'lev5']].stack().groupby(level=0).first().reindex(df.index) </code></pre> <p>Now, you can select the code column and description column</p> <pre><code>df[['code', 'description']] ...
python|pandas|dataframe
1
2,508
59,309,566
In a Pandas dataframe how do I calculate the median value for each decile within each month
<p>I have a dataframe with 50 data points per month. I'd like to calculate the median value for each decile within each month. In my groupby call I lead with the date, then qcut. But qcut calculates the bins over the whole dataset, not by month. Here's what I have so far:</p> <pre><code>import numpy as np import panda...
<p>First, <code>groupby</code> month to create the quantile labels within month. Then <code>groupby</code> month and quantile to find the median. </p> <pre><code>df['q'] = df.groupby(df.index).Data.apply(lambda x: pd.qcut(x, 10, labels=False)) df.groupby([df.index, 'q']).median() </code></pre> <hr> <pre><code> ...
python|pandas|group-by
0
2,509
59,105,414
Pandas to_html does not show the appended data
<p>When trying to export my pandas DataFrame to a html page, through the to_html() functionality, the output html page does not show the appended data-rows.</p> <pre><code>import pandas as pd df_test = pd.DataFrame(columns=['TEST1', 'TEST2']) df_test.append({'TEST1':11, 'TEST2':22}, ignore_index=True) df_test.append({...
<p>Because pandas <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html" rel="nofollow noreferrer"><code>DataFrame.append</code></a> not working inplace is necessary assign output back:</p> <pre><code>df_test = df_test.append({'TEST1':11, 'TEST2':22}, ignore_index=True) df_tes...
python|pandas
1
2,510
59,416,760
How to write pandas dataframe into Databricks dbfs/FileStore?
<p><a href="https://i.stack.imgur.com/Waxvu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Waxvu.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/YSh53.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YSh53.png" alt="enter image description here"></a>I'm new to the Data...
<p>Try with this in your notebook databricks:</p> <pre><code>import pandas as pd from io import StringIO data = """ CODE,L,PS 5d8A,N,P60490 5d8b,H,P80377 5d8C,O,P60491 """ df = pd.read_csv(StringIO(data), sep=',') #print(df) df.to_csv('/dbfs/FileStore/NJ/file1.txt') pandas_df = pd.read_csv("/dbfs/FileStore/NJ/file1...
python|pandas|dataframe|amazon-s3|databricks
9
2,511
57,170,571
Python - GeoPandas Does Not Work After Opening .DXF With Adobe Illustrator
<p>I'm attempting to plot a CAD file (.dxf) using GeoPandas then save it as a KML file. When I attempt to do so - the CAD file ends up showing up in the wrong place (in the middle of the ocean - when it should be in Florida). The strange part is this only occurs after opening the .dxf then saving it with Adobe Illustra...
<p>The fix / solution to this issue is to use an Adobe Illustrator plugin which allows for the preservation of GIS / Geo-spatial data. We've decided to use: <a href="https://www.avenza.com/mapublisher/" rel="nofollow noreferrer">https://www.avenza.com/mapublisher/</a></p> <p>Thank you to everyone who provided input re...
python|gis|geopandas|epsg
0
2,512
35,568,605
Why cumulative sum is not being carried over in the following numerical integration to calculate the area bewteen two curves?
<p>Description:</p> <p>In the following python code, I am producing a Gaussian PDF, namely p(y). I am trying to find the area confined between the curve and any horizontal line in the range of [min_p, max_p] through the method of rectangular summation. My main problem is in the implementation of the function that is s...
<p>After making quite a few changes here is the code I think you are trying to produce:</p> <pre><code>from scipy.stats import norm import numpy as np import pylab as p %matplotlib inline N = 10 # Number of sigmas away from central value M, K = 2**10, 2**10 ...
python|arrays|for-loop|numpy|sympy
0
2,513
28,505,008
numpy.polyfit: How to get 1-sigma uncertainty around the estimated curve?
<p>I use numpy.polyfit to fit observations. polyfit gives me the estimated coefficients of the polynomial and can also provides me the error covariance matrix of the estimated coefficients. Fine. Now, I would like to know if there is a way to estimate the +/- 1sigma uncertainty around the estimated curve.</p> <p>I kno...
<p>If you have enough data points, you can get with the parameter <code>cov=True</code> an estimated covariance matrix from <code>polyfit()</code>. Remember that you can write a polynomial <code>p[0]*t**n + p[1]*t**(n-1) + ... + p[n]</code> as the matrix product <code>np.dot(tt, p)</code> with <code>tt=[t**n, tt*n-1, ....
python|numpy
8
2,514
28,571,741
Retrieve approximate Hessian inverse from L-BFGS-B
<p>With the L-BFGS-B minimizer in scipy, is it possible to retrieve the approximate inverse Hessian that's calculated internally?</p> <p>Having it in the implicit factored form, so that it's possible to compute arbitrary inverse Hessian matrix - vector products, would be fine.</p>
<p>It doesn't appear so. I'm not an expert on these algorithms but it seems that with L-BFGS specifically it is not possible. According to <a href="http://en.wikipedia.org/wiki/Limited-memory_BFGS" rel="nofollow">Wikipedia</a>:</p> <blockquote> <p>Instead of the inverse Hessian H_k, L-BFGS maintains a history of t...
python|numpy|scipy|mathematical-optimization|hessian-matrix
2
2,515
50,674,011
Replace the year in pandas.datetime column
<p>I have a dataframe with a date column converted using pd.to_datetime(). When I inspected the data I found few of these dates with year mentioned as 2216, which should have been 2016. Can you please help me change the year for these dates from 2216 to 2016</p> <pre><code> Date 0 2216-12-21 1 2216-12-23 2 2...
<p>Use:</p> <pre><code>df['Date'] = df['Date'].mask(df['Date'].dt.year == 2216, df['Date'] + pd.offsets.DateOffset(year=2016)) print (df) Date 0 2016-12-21 1 2016-12-23 2 2016-01-31 3 2016-12-23 4 2016-12-27 5 2016-12-25 6 2016-12-23 </code></pre> <p>For better performance:</p> ...
python|pandas
14
2,516
51,090,580
Pandas dataframe adding zero-padding before the datetime
<p>I'm using Pandas dataframe. And I have a dataFrame <code>df</code> as the following:</p> <pre><code>time id ------------- 5:13:40 1 16:20:59 2 ... </code></pre> <p>For the first row, the time <code>5:13:40</code> has no zero padding before, and I want to convert it to <code>05:13:40</code>. So my expecte...
<p>Use <code>pd.to_timedelta</code>:</p> <pre><code>df['time'] = pd.to_timedelta(df['time']) </code></pre> <p>Before:</p> <pre><code>print(df) time id 1 5:13:40 1.0 2 16:20:59 2.0 df.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 2 entries, 1 to 2 Data columns (total 2 columns): time ...
python|pandas
1
2,517
33,147,411
Adding a pandas column without creating a list
<p>I have 2 datasets of more than 1million rows and I am analyzing it with pandas (therefore they both are <code>pd.Dataframe</code> and noted <code>df1</code> and <code>df2</code>). I need to do add a column to df1 depending on the value of df2. I used the python list, but it is incredibly slow. Any advice to be quick...
<p>It's not so much that you are creating a list, but that you have a nested loop, taking you over all combinations of <code>df1</code> and <code>df2</code>. Roughly</p> <pre><code>for line in np.array(df1): numObs.append([num for i,num,exp in df2 if i==line[0]][0]) </code></pre> <p>expands to</p> <pre><code>fo...
python|list|numpy|pandas
0
2,518
66,685,526
Function to select pandas dataframe rows based on list of tuples of columns and cutoffs?
<p>I´m trying to create a python function that takes 2 arguments: a pandas dataframe, and a list of tuples, where each tuple in the list have 3 elements, a column name, a min value and a max value. So each tuple represent a condition to be applied to a column in the dataframe. And then the function would return a sub d...
<h1>Dynamic Query function</h1> <p>Since you want to check for all the conditions, these will be AND. So we can start filtering them one by one.</p> <pre><code>import pandas as pd def sub_df(dx,cuts): for cx in cuts: col = cx[0] minval = cx[1] maxval = cx[2] dx = dx[(dx[col] &gt;= ...
python|pandas
2
2,519
16,207,023
Python pandas read_csv like functionality from list to a DataFrame?
<p>I have a list with values like the following:</p> <pre><code>[['2013-04-02 19:42:00.474', '1'], ['2013-04-02 19:42:00.529', '2'], ['2013-04-02 19:42:00.543', '3'], ['2013-04-02 19:42:00.592', '4'], ['2013-04-02 19:42:16.671', '5'], ['2013-04-02 19:42:16.686', '6'], ['2013-04-02 19:42:16.708', '7'], ['2013-04-02 19:...
<pre><code>In [40]: df.index = df.index.to_datetime() In [41]: df.index Out[41]: &lt;class 'pandas.tseries.index.DatetimeIndex'&gt; [2013-04-02 19:42:00.474000, ..., 2013-04-02 19:42:58.225000] Length: 13, Freq: None, Timezone: None </code></pre>
python|datetime|csv|pandas
3
2,520
16,329,218
Face Recognition - How to return the correct image?
<p>I am trying to make hand gesture recognition (similar to face recognition) using Principal Component Analysis(PCA) in python. I have a Test image and I want to get its nearest match from a set of Training images.</p> <p>Here is my code:</p> <pre><code>import os, sys import numpy as np import PIL.Image as Image d...
<p><code>dst.argmin()</code> will tell you the index of the element in <code>dst</code> which is smallest.</p> <p>So the closest image would be</p> <pre><code>idx = dst.argmin() closest = a[idx] </code></pre> <p>since <code>a</code> is a list of arrays representing training faces.</p> <p>To display the closest imag...
python|image-processing|numpy|face-recognition|pca
3
2,521
57,662,437
How to check if every item pandas column of lists is an int?
<p>I have a pandas column of lists. I need to check if every item in those lists are ints. </p> <p>For a regular list, I can find if an item is an int using</p> <pre><code>all(isinstance(x, int) for x in lst) </code></pre> <p>and for a regular pandas column, I can check if they're all ints using </p> <pre><code>df....
<p>You can use <code>apply</code> with your current list check:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import random # create random df x = [{'A': [random.randint(0,300) for i in range(10)]} for i in range(10)] df = pd.DataFrame(x) df.A.apply(lambda x: all(isinstance(y, int) for y in...
python|pandas
2
2,522
24,183,101
Pandas: Bar-Plot with two bars and two y-axis
<p>I have a DataFrame looking like this:</p> <pre><code> amount price age A 40929 4066443 B 93904 9611272 C 188349 19360005 D 248438 24335536 E 205622 18888604 F 140173 12580900 G 76243 6751731 H 36859 3418329 I 29304 2758928 J 39768 3201269 K 30350 286...
<p>Using the new pandas release (0.14.0 or later) the below code will work. To create the two axis I have manually created two matplotlib axes objects (<code>ax</code> and <code>ax2</code>) which will serve for both bar plots.</p> <p>When plotting a Dataframe you can choose the axes object using <code>ax=...</code>. A...
python|matplotlib|plot|pandas
96
2,523
43,894,828
Group data based on column name pandas
<p>In the example below, I want to first sort based on UID and then the TSTAMP for each TID.</p> <p>In this context, here is a minimal working example I generated:</p> <pre><code>df = pd.read_csv(dataset_path, names = ['TID','UID','TSTAMP'], delimiter=';') df = df.sort_values(by=['TID'], ascending=[True]) print df #p...
<p>It seems you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>sort_values</code></a>:</p> <pre><code>df = df.sort_values(['TID', 'TSTAMP', 'UID'], ascending=[True, False, True]) print (df) TID UID TSTAMP 22267 7...
python|pandas
2
2,524
43,879,875
concat specific rows of two pandas dataframe using data in two columns as reqs
<p>I have two dataframes DF1 and DF2, where </p> <p>both have subframes "data" and "metadata," and DF1 has substantially more rows than DF2</p> <pre><code>DF1 DATA METADATA 0 1 2 3 4 5 attr1 attr2 .. attrN 11 1 1 1 1 1 1 000 apple 13 1 1 1 1 1 1 140 ora...
<p>It sounds like you want to do a merge on attr1, something like:</p> <pre><code>df1.merge(df2, how='left') </code></pre> <p>For example (slightly tweaked):</p> <pre><code>In [11]: df1 Out[11]: DATA METADATA 0 1 2 3 4 5 attr1 attr2 11 1 1 1 1 1 1 0 bean 13 ...
python|python-3.x|pandas
0
2,525
43,771,023
Interpolate a curve on itself using NumPy
<p>I have the following curve as two arrays, of x and y positions. </p> <p><img src="https://i.stack.imgur.com/yS0Bp.png" alt="curve"></p> <p>Imagine if you were to draw vertical lines going through each point, and add points on the curve wherever these lines intersect the curve. This is what I want. </p> <p>I tr...
<p>According to the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html" rel="nofollow noreferrer">docs</a> the array of X values should be sorted (or periodic), otherwise "the result is nonsense". You can try to split your curve into sections, and then interpolate each part on the others. Y...
python|numpy|interpolation
0
2,526
73,159,568
Multi-channel, 2D mask weights using BCEWithLogitsLoss in Pytorch
<p>I have a set of 256x256 images that are each labeled with nine, binary 256x256 masks. I am trying to calculate the <code>pos_weight</code> in order to weight the <code>BCEWithLogitsLoss</code> using Pytorch.</p> <p>The shape of my masks tensor is <code>tensor([1000, 9, 256, 256])</code> where 1000 is the number of t...
<p>TLDR; This is a broadcasting issue which is surprisingly not handled by PyTorch's <a href="https://pytorch.org/docs/stable/generated/torch.nn.BCEWithLogitsLoss.html?highlight=bce#torch.nn.BCEWithLogitsLoss" rel="nofollow noreferrer"><code>nn.BCEWithLogitsLoss</code></a> namely <a href="https://github.com/pytorch/pyt...
python|deep-learning|pytorch|loss-function|weighted
1
2,527
73,146,875
How to select values out of many in pandas dataframe using conditions?
<p>I have a CSV with multiple values for a single value and I have to filter them out based on several conditions. Below is an example of my data.</p> <pre><code>df1 = pd.DataFrame( data=[['Afghanistan','2.7;2.7','27.0;26.7','','22.9;22.8'], ['Bahrain','6.3;6.3;6.4','13.0;13.0;13.0','16.8;17.0',''], ['Djibouti'...
<p>Use from apply method for each col</p> <pre class="lang-py prettyprint-override"><code>def f(x): a = x.split(';') if cond1: return ... if cond2: return ... if cond3: return ... df['2019']=df['2019'].apply(f) ... </code></pre> <p>For your many cols you can do:</p> <pre class="...
python|pandas|dataframe|data-cleaning
1
2,528
72,866,905
Create line from list of points while ignoring outliers
<p>I have a list of points that almost create a straight line (but they are not perfectly align on that line). I want to create a line that best describes those points.</p> <p>For example, for points:</p> <pre><code>points = [(150, 250),(180, 220), (200, 195), (225, 180), (250, 150), (275, 115), (300, 100)] </code></pr...
<p>Thanks for <code>@Christoph Rackwitz</code>'s answer, I followed sklearn's doc for <a href="https://scikit-learn.org/stable/auto_examples/linear_model/plot_ransac.html" rel="nofollow noreferrer">RANSAC</a>, and created simple script to calculate the <code>RANSAC</code> (of course that it's need to be polished):</p> ...
python-3.x|numpy|opencv|outliers
1
2,529
73,159,673
Using PANDAS to conditionally manipulate specific cells based on another cell and getting it to change original df
<pre><code>andrew_ramirez[andrew_ramirez['Datacenter'].isin(['ATL2','ACT1'])]['payout']*= 0.25 </code></pre> <p>This is not changing my dataframe (named andrew_ramirez) based on the criteria. Am i missing something?</p>
<p>You can use from this code:</p> <pre class="lang-py prettyprint-override"><code>df['payout']=np.select([df.Datecenter.isin(['ATL2', 'ACT1']), [df.payout*0.25], df.payout) </code></pre>
pandas
0
2,530
72,903,643
Filter a string value from a column in Python?
<p>Need to extract Diabetes value from column name chronic from a df in python.</p> <p>Can anyone pls help to retrieve this in python?</p> <pre class="lang-none prettyprint-override"><code>Patients Chronic 1 Diabetes 2 Diabetes 3 Hypertension 4 Hypertension 5 Diabetes </...
<p>If your <code>df</code> is:</p> <pre class="lang-py prettyprint-override"><code> Patients Chronic 0 1 Diabetes 1 2 Diabetes 2 3 Hypertension 3 4 Hypertension 4 5 Diabetes type 1 </code></pre> <p>Then:</p> <pre class="lang-py prettyprint-over...
python|regex|pandas
-1
2,531
10,817,360
Array order in pytables
<p>With <a href="http://www.pytables.org/moin" rel="nofollow">pytables</a>'s <a href="http://pytables.github.com/usersguide/libref.html#carrayclassdescr" rel="nofollow"><code>CArray</code></a>, is there a way to specify the order in which the data is stored on disk (Fortran/C)?</p> <p>I am looking for something simila...
<p>You can use the <code>chunkshape</code> parameter that in effect specifies the data order:</p> <p><a href="http://pytables.github.com/usersguide/libref.html#tables.File.createCArray" rel="nofollow">http://pytables.github.com/usersguide/libref.html#tables.File.createCArray</a></p> <p>For instance, for 2-D data, <co...
python|numpy|pytables
2
2,532
70,733,261
Joining dataframes using rust polars in Python
<p>I am experimenting with <code>polars</code> and would like to understand why using <code>polars</code> is slower than using <code>pandas</code> on a particular example:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import polars as pl n=10_000_000 df1 = pd.DataFrame(range(n), columns=['a']...
<p>A pandas <code>join</code> uses the indexes, which are cached.</p> <p>A comparison where they do the same:</p> <pre class="lang-py prettyprint-override"><code># pandas # CPU times: user 1.64 s, sys: 867 ms, total: 2.5 s # Wall time: 2.52 s df1.merge(df2, left_on=&quot;a&quot;, right_on=&quot;b&quot;) # polars # CP...
python|pandas|dataframe|python-polars|rust-polars
4
2,533
70,514,988
taking out specific indexes from array
<p>I have and array which I am trying to slice/split, small part of the array is as follow:</p> <pre><code>[(2008, b'2-room', 82000, 107000) (2008, b'3-room', 135000, 211000) (2008, b'4-room', 223000, 327000) (2008, b'5-room', 305000, 428000) (2008, b'3-room', 142000, 160000) (2008, b'4-room', 211000, 253000) .........
<p>As suggested in the comment to the question by @Tim Roberts, using fancy indexing can help:</p> <pre class="lang-py prettyprint-override"><code>mask = dataprice['financial_year']==2019 list_2019 = dataprice[mask] list_rest = dataprice[~mask] </code></pre>
python|numpy
-1
2,534
42,875,356
Selection with pandas multiIndexed dataframe
<p>I have a multiIndexed dataframe that looks like this:</p> <pre><code>df.head(): </code></pre> <p><a href="https://i.stack.imgur.com/y2yUo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y2yUo.png" alt="enter image description here"></a></p> <p>How can I select all of the rows where the first in...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="nofollow noreferrer"><code>query</code></a>:</p> <pre><code>print (df.query('ilevel_0 == "School Name" and Month == "Jan"')) </code></pre> <p>Sample:</p> <pre><code>df = pd.DataFrame({'A':['School Name','A...
python-3.x|pandas|dataframe|indexing|multi-index
4
2,535
42,650,230
Pandas pivot on column
<p>my CSV looks like:</p> <pre><code>"a","b","c","d" 1, "x", 1, 1 1, "y", 2, 2 </code></pre> <p>and I want to convert it based on column "b" to</p> <pre><code>"a", "x_c", "y_c", "x_d", "y_d" 1, 1, 2, 1, 2 </code></pre> <p>I've tried it with pivot and unstack. Is there a shortcome in pandas ?</p> <p>EDIT: I have mu...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="noreferrer"><code>pivot_table</code></a>:</p> <pre><code>df = df.pivot_table(index='a',columns='b', values=['c', 'd'], aggfunc=np.mean) #Multiindex to columns df.columns = df.columns.map(lambda x: '{}_{}'.format(x[1], x...
python|csv|pandas
5
2,536
25,057,977
Defining a function with a loop in Theano
<p>I want to define the following function of two variables in Theano and compute its Jacobian:</p> <pre><code>f(x1,x2) = sum((2 + 2k - exp(k*x1) - exp(k*x2))^2, k = 1..10) </code></pre> <p>How do I make a Theano function for the above expression - and eventually minimize it using its Jacobian?</p>
<p>Since your function is scalar, the Jacobian reduces to the gradient. Assuming your two variables <code>x1, x2</code> are scalar (looks like it from the formula, easily generalizable to other objects), you can write</p> <pre><code>import theano import theano.tensor as T x1 = T.fscalar('x1') x2 = T.fscalar('x2') k ...
python|numpy|scipy|theano
3
2,537
25,260,000
scikit-learn's GridSearchCV stops working when n_jobs>1
<p>I have previously asked <a href="https://stackoverflow.com/questions/25249212/scikit-grid-search-for-knn-regression-valueerror-array-contains-nan-or-infinity">here</a> come up with following lines of code:</p> <pre><code>parameters = [{'weights': ['uniform'], 'n_neighbors': [5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 1...
<p><code>libdispatch.dylib</code> from Grand Central Dispatch is used internally by OSX's builtin implementation of BLAS called Accelerate when you do a <code>numpy.dot</code> calls. The GCD runtime does not work when programs call the POSIX <code>fork</code> syscall without using an <code>exec</code> syscall afterward...
python|numpy|scikit-learn
4
2,538
30,471,509
How can I create an array of 1-element arrays from an array?
<p>I would like to be able to convert arrays, such as </p> <pre><code>a = np.array([[1,2], [3,4]]) </code></pre> <p>into the same array BUT each element as a 1-element array instead of a number. The desired output would be: </p> <pre><code>np.array([[np.array([1]), np.array([2])], [np.array([3]), np.array([4])]]) ...
<p>The operation you describe is very rarely useful. More likely, it would be a better idea to add an extra dimension of length 1 to the end of your array:</p> <pre><code>a = a[..., np.newaxis] # or a = a.reshape(a.shape + (1,)) </code></pre> <p>Then <code>a[0, 1]</code> will be a 1D array, but all the nice NumPy fea...
python|arrays|numpy
0
2,539
13,116,394
pandas: flatten df with delimiter
<p>My goal is to load a dataframe into a DB using a stdin pipe to a load statement executed at the command line (e.g. cat {file_loc} | /path/to/sql --command "COPY table FROM STDIN WITH DELIMITER ',';"). I'm aware that this approach is suboptimal; it's a workaround due to pyodbc issues ;)</p> <p>What's the most effici...
<p>Could you describe the pyodbc issues?</p> <p>I created an issue here. To get the ultimate perf you'd want to drop down into C or Cython and build the raw byte string yourself using C string functions. Not very satisfying, I know. At some point we should build a better-performing to_csv for pandas, too:</p> <p><a h...
python|numpy|pandas
0
2,540
28,946,964
How to be a faster Panda with groupbys
<p>I have a Pandas dataframe with 150 million rows. Within that there are about 1 million groups I'd like to do some very simple calculations on. For example, I'd like to take some existing column <code>'A'</code> and make a new column, <code>'A_Percentile'</code> that expresses the values of '<code>A'</code> as percen...
<p>As you are probably aware, the speed of groupby operations can vary tremendously -- especially as the number of groups gets high. Here's a really simple alternate approach that is quite a bit faster on some test datasets I tried (anywhere from 2x to 40x faster). Usually it is faster if you can avoid user-written f...
python|performance|pandas|bigdata|dataframe
2
2,541
23,705,113
How to make random Beta in python like normal between two value ?
<p>I want to make random beta in python like normal between two extreme values (ex : 800 / 1000 ). I use this code with numpy random.beta. My problem, I don't have min and max value with normalize and I want keep shape of value. </p> <pre><code>#!/usr/bin/env python # -*- coding: iso-8859-1 -*- import numpy as np impo...
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.beta.html" rel="nofollow"><code>numpy</code>'s <code>random.beta</code></a> will give a value between zero and one, so to apply the same distribution between <code>x</code> and <code>y</code> you simply do:</p> <pre><code>z = x + (np.random.b...
python|numpy|random
2
2,542
15,149,265
pandas Timedelta error
<p>I'm getting errors when running the code samples from the pandas documentation. </p> <p>I suspect it might be related to the version of pandas I'm using, but I haven't been able to confirm that. </p> <pre><code>pandas VERSION 0.10.1 numpy VERSION 1.7.0 scipy VERSION 0.12.0.dev-14b1e07 </code></pre> <p>The...
<p>If you look at the title of the page (top of your browser window) you are linking to, you can see that it's the development version of pandas: <a href="http://pandas.pydata.org/pandas-docs/dev/timeseries.html#time-deltas" rel="nofollow">http://pandas.pydata.org/pandas-docs/dev/timeseries.html#time-deltas</a></p> <p...
datetime|pandas|time-series|series|timedelta
1
2,543
62,143,149
Plotting sorted data
<p>I would need to plot accounts through time, by sorting opening account. </p> <p>I have the following two columns, one for the Accounts and one for OpenTime (it is datetime):</p> <pre><code>Account Name OpenTime ABC 2002/05/20 BAB 2012/07/24 CMN 2012/07/24 GK...
<p>First we need convert the date to datetime , then <code>sort_values</code></p> <pre><code>df.OpenTime=pd.to_datetime(df.OpenTime) df=df.sort_values('OpenTime') print(df['Account Name'].tolist()) </code></pre>
python|pandas|matplotlib|seaborn
1
2,544
62,083,446
Make date_range of hourly frequency over multiple years for a selected month
<p>I understand how to make a date_range in pandas using the freq option. However, I do not know how to use it to do two frequencies at once (or do I need a loop for this)?</p> <p>I am trying to make an hourly date range for only july for a span over some years.</p> <p>I have tried:</p> <pre><code>In: pd.date_rang...
<p>You can create hours frequency with start and end <code>year</code> and then filter only <code>july</code>s:</p> <pre><code>d = pd.date_range('1951-07-01','1955-07-01',freq='H') d = d[d.month == 7] print (d) DatetimeIndex(['1951-07-01 00:00:00', '1951-07-01 01:00:00', '1951-07-01 02:00:00', '1951-07...
python|pandas|datetime|date-range
2
2,545
62,246,851
Differential Privacy decreases the model performance significantly
<p><strong>Background Information</strong></p> <p>I trained a classifier to predict three labels: COVID/Pneumonia/Healthy based on chest X-Ray images. It's a PyTorch implementation of <a href="https://github.com/lindawangg/COVID-Net" rel="nofollow noreferrer">COVID-Net</a>. I use a training set to train on, validation...
<p>It seems the PyTorch Differential Privacy library from Facebook Research is built on the concept of Renyi differential privacy guarantee that is well-suited for expressing guarantees of privacy-preserving algorithms and for composition of heterogeneous mechanisms. We need to have a good estimation of the heterogenit...
python|machine-learning|pytorch|privacy|confusion-matrix
1
2,546
62,204,867
Pandas Create New Column Based Off of Condition and Value in Other Column
<p>I have a data set like the following:</p> <pre><code>ID Type 1 a 2 a 3 b 4 b 5 c </code></pre> <p>And I'm trying to create the column URL as shown by specifying a different URL based on the "Type" and appending the "ID".</p> <pre><code>ID Type URL 1 a http://example.com/examplea/id=1 2 a ht...
<p>You should alter the command a bit:</p> <pre><code>df.loc[df['Type'] == 'a', 'URL']= 'http://example.com/examplea/id='+df['ID'].astype(str) df.loc[df['Type'] == 'b', 'URL']= 'http://example.com/bbb/id='+df['ID'].astype(str) </code></pre> <p>Or you can use <code>map</code> like this:</p> <pre><code>url_dict = { ...
python|pandas|pandas-loc
2
2,547
62,184,063
Too many values to unpack using apply()
<p>Here is the code I have:</p> <pre><code>def f(row): if row['CountInBedDate'] == 1 and row['CountOutBedDate'] == 1: SleepDate = row['DateInBed'] InBedTimeFinal = row['InBedTime'] OutBedTimeFinal = row['OutBedTime'] else: SleepDate = -1 InBedTimeFinal = -1 OutBedTimeFinal = -1 return Sle...
<p>if <code>f</code> is your real function, then you should consider using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.where.html" rel="nofollow noreferrer"><code>where</code></a> instead of apply, it will be way faster.</p> <pre><code>s1[['SleepDate', 'InBedTimeFinal', 'OutBed...
python|pandas
2
2,548
51,475,435
Python find most common value in array
<pre><code>import numpy as np x = ([1,2,3,3]) y = ([1,2,3]) z = ([6,6,1,2,9,9]) </code></pre> <p>(only positive values) In each array i need to return the most common value, or, if values come up the same amount of times - return the minimum. This is home assignment and I can't use anything but numpy.</p> <p>outputs...
<p>for a numpy exclusive solution something like this will work:</p> <pre><code>occurances = np.bincount(x) print (np.argmax(occurances)) </code></pre> <p>The above mentioned method won't work if there is a negative number in the list. So in order to account for such an occurrence kindly use:</p> <pre><code>not_requ...
python|numpy
2
2,549
48,081,743
Python utilizing file paths
<pre><code>sound_file_paths =[ "/Users/ferhatkaygun/Desktop/UrbanSound8K/audio/fold1/57320-0-0-7.wav", "/Users/ferhatkaygun/Desktop/UrbanSound8K/audio/fold1/24074-1-0-3.wav", "/Users/ferhatkaygun/Desktop/UrbanSound8K/audio/fold1/15564-2-0-1.wav", "/Users/ferhatkaygun/Desktop/UrbanSound8K/audio/fold1/313...
<p>you are getting the error that soundfiles are not defined because the program cannot find the file. Most likely the paths you are using are not from your machine?</p> <p>you need to put the files to a directory, ex <code>/Users/me/files/</code> on your machine and then replace the file paths in your script to point...
python|audio|tensorflow|filepath|librosa
0
2,550
48,325,478
Excel export using While loop
<p>I am new to Python. I am working on a large analytic program, and this is a snippet of it. Right now, this snippet exports multiple excel files. Is it possible to save what is done per loop on a sheet within a single excel document? So basically right now, it exports 5 files, rather than exporting 5 separate files, ...
<p>EDIT (to account for OP using <code>pandas</code> and <code>ExcelWriter</code>):</p> <p>You need to define your target file with <code>ExcelWriter</code> and then write to it with variable sheet names. Also offering some Python clean-up for your iteration:</p> <pre><code>#breaks up df into systems #exports excel f...
python|excel|pandas|while-loop|export-to-excel
1
2,551
48,235,916
Cropping a minibatch of images in Pytorch -- each image differently
<p>I have a tensor named <code>input</code> with dimensions 64x21x21. It is a minibatch of 64 images, each 21x21 pixels. I'd like to crop each image down to 11x11 pixels. So the output tensor I want would have dimensions 64x11x11.</p> <p>I'd like to crop each image around a different "center pixel." The center pixels ...
<p>I raised the question over on the pytorch forums, and got an answer there from smth. The <code>grid_sample</code> function should totally solve the problem.</p> <p><a href="https://discuss.pytorch.org/t/cropping-a-minibatch-of-images-each-image-a-bit-differently/12247" rel="nofollow noreferrer">https://discuss.pyto...
pytorch
2
2,552
48,192,177
keras with tensorflow runs fine, until I add callbacks
<p>I'm running a model using Keras and TensorFlow backend. Everything works perfect:</p> <pre><code>model = Sequential() model.add(Dense(dim, input_dim=dim, activation='relu')) model.add(Dense(200, activation='relu')) model.add(Dense(1, activation='linear')) model.compile(loss='mse', optimizer='Adam', metrics=['mae']...
<p>A <code>tensorboard</code> callback uses <code>tf.summary.merge_all</code> function in order to collect all tensors for histogram computations. Because of that - your summary is collecting tensors from previous models not cleared from previous model runs. In order to clear these previous models try:</p> <pre><code>...
tensorflow|machine-learning|neural-network|keras|tensorboard
2
2,553
48,578,272
Why the model size is in huge different between different optimizer?
<p>With TensorFlow, my model size(model.ckpt.data) is 88M when optimizer is <code>tf.train.GradientDescentOptimizer</code>, but it turned to 220M when the optimizer changed to <code>tf.train.AdamOptimizer</code>.</p> <p>Why is there so huge a difference?</p>
<p>ADAM adds two running means (for gradient and square of gradient) as additional non-trainable parameters for each trainable parameter, meaning it increases the number of total parameters to three times. These non-trainable parameters are also saved as they are required to restart the learning process. That's why the...
tensorflow|neural-network|deep-learning
2
2,554
48,770,411
how to convert columns to numeric while keep those failed intact in pandas
<p>I read my text file into pandas dataframe. All columns are object datatype. What I need to do is convert all those columns that appears 'numeric' to numeric columns. If there are ust a few columns, it's very easy. But my real dataframe has over two hundred columns. I wonder if there is anyway to convert those colum...
<p>Op1. I usually using <code>to_numeric</code> then <code>fillna</code> (The reason : I usually have some mixed dtype within one column )</p> <pre><code>df=df[['a', 'b', 'c', 'd']].apply(pd.to_numeric,errors='coerce').fillna(df) df.dtypes Out[605]: a int64 b object c object d int64 dtype: object </code...
python|pandas
4
2,555
70,883,944
Print multiple columns from a matrix
<p>I have a list of column vectors and I want to print only those column vectors from a matrix. Note: the list can be of random length, and the indices can also be random.</p> <p>For instance, the following does what I want:</p> <pre><code>import numpy as np column_list = [2,3] a = np.array([[1,2,6,1],[4,5,8,2],[8,3,5...
<p>Yes, there's a shorter way. You can pass a list (or numpy array) to an array's indexer. Therefore, you can pass <code>column_list</code> to the columns indexer of <code>a</code>:</p> <pre><code>&gt;&gt;&gt; a[:, column_list] array([[6, 1], [8, 2], [5, 3], [4, 4], [8, 8]]) # This i...
python-3.x|numpy
1
2,556
70,887,198
Pandas assign - passing column in a user defined function
<p>Given an input dataframe and string:</p> <pre><code>df = pd.DataFrame({&quot;A&quot; : [10, 20, 30], &quot;B&quot; : [0, 1, 8]}) colour = &quot;green&quot; #or &quot;red&quot;, &quot;blue&quot; etc. </code></pre> <p>I want to add a new column <code>df[&quot;C&quot;]</code> conditional on the values in <code>df[&quot...
<p>Applying a function like that can be inefficient, especially when dealing with dataframes with many rows. Here is a one-liner:</p> <pre><code>colour = &quot;green&quot; #or &quot;red&quot;, &quot;blue&quot; etc. df['C'] = ((colour == 'red') &amp; df['B'].lt(5)) | ((colour == 'blue') &amp; df['B'].lt(5)) | ((colour ...
python|pandas|dataframe
4
2,557
70,910,193
How can I add CSV logging mechanism in case of Multivariable Linear Regression using TensorFlow?
<p>Suppose, the following is my Multivariable Linear Regression source code in Python:</p> <pre><code>import os os.environ[&quot;TF_CPP_MIN_LOG_LEVEL&quot;] = &quot;2&quot; import sys, random import time import tensorflow as tf from tensorflow import keras from tensorflow.keras.models import Sequential from te...
<p>Just use the <code>tf.keras.callbacks.CSVLogger</code> and any regression metric you want to log during training:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(1, input_dim=40)) model.add(tf.keras.layers.Dense(128)) model.ad...
python|tensorflow|keras|logging|deep-learning
2
2,558
70,824,180
Get array with another array indexing with NumPy
<pre><code>arr_1 = np.array([5, 1, 6, 3, 3, 10, 3, 6, 12]) arr_2 = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90]) arr_idx_num_3 = np.where(arr_1 == 3)[0] print(arr_idx_num_3) ## [3 4 6] </code></pre> <p>#how to i get this array Numpy with &quot;arr_idx_num_3&quot;</p> <pre><code>arr_2 = [40 50 70] </code></pre>
<p>Just use it like:</p> <pre><code>print(arr_2[arr_idx_num_3]) </code></pre> <p>output:</p> <pre><code>&gt;&gt;&gt; [40 50 70] </code></pre>
python|numpy
1
2,559
70,786,121
Why my prediction function is giving error? ValueError: not enough values to unpack (expected 2, got 1)
<p>I'm trying to make prediction using the pre-trained model for binary segmentation using UNET and pytorch. Here is my code: model.eval() # Set model to evaluate mode</p> <pre><code>class SimDataset(Dataset): def __init__(self, path, transform=None, isMask=False): self.m = (&quot;test&qu...
<p>Your code expects <em>two</em> outputs from the data loader:</p> <pre class="lang-py prettyprint-override"><code>inputs, labels = next(iter(test_loader)) </code></pre> <p>However, your <code>__getitem__</code> method in your dataset, returns only a <em>single</em> output:</p> <pre class="lang-py prettyprint-override...
python|testing|pytorch|image-segmentation
0
2,560
51,999,924
Tensorflow Object Detection API - showing loss for training and validation on one graph
<p>I am playing with <a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="nofollow noreferrer">Tensorflow Object Detection API</a> and training the Faster R-CNN network on my own dataset. I am checking the progress of learning at Tensorbord. All metrics are there, but is there a way...
<p>The underlying data for the plots is saved under different tag names (<code>loss</code> vs <code>loss_1</code>). I believe TensorBoard does not natively support displaying different tags in one plot. There might be third-party extensions to do this.</p> <p>If different models used the same tag, the graphs would be ...
tensorflow|tensorboard
1
2,561
51,577,885
Converting list numpy array to normal array for CNN-Keras
<p>I have some images separated by folders. So I imported them and converted to them array of pixels. When I type in:</p> <pre><code>In [9]: X_train.shape out [9]: (7467,60,80,3) </code></pre> <p>I wanted to append this with the no. of classes, create a dataset and save as <code>.json</code> file and import in a fres...
<p>Your <code>np arrays</code> are converted to lists when storing the dataframe as a <code>.json</code>. To feed them to your Keras model, you need to have them in one <code>array</code> of shape <code>(images, height, width, channels)</code>:</p> <pre><code>X_train = np.array(train['images'].tolist()) </code></pre>
python|numpy|keras|deep-learning|conv-neural-network
0
2,562
51,657,913
Tensorflow building error
<p>I got this error while building Tensorflow 1.1.0</p> <pre><code>Starting local Bazel server and connecting to it... ERROR: /home/bishal/.cache/bazel/_bazel_bishal/798d6395d959361055d9b5ddcd7dcd45/external/io_bazel_rules_closure/closure/testing/phantomjs_test.bzl:31:10: name 'set' is not defined ERROR: /home/bishal/...
<p>You'll need to use <a href="https://github.com/bazelbuild/bazel/releases/tag/0.5.4" rel="nofollow noreferrer">Bazel 0.5.4</a> to build Tensorflow 1.1.0. Please note that 0.5.4 is very old -- it's 0.16.0 as of time of writing this answer.</p> <p>Do you need to specifically build Tensorflow 1.1.0?</p>
tensorflow|bazel
2
2,563
64,568,948
Generating a dictionary of column names based on a condition among columns of a dataframe
<p>I have the following data frame :</p> <pre><code> a_11 b_14 c_13 d_12 AC True False False False BA True False False True AA False False False False </code></pre> <p>I want a dictionar...
<p>Use dictioanry comprehension if performance is important with transpose DataFrame and convert columns names to list:</p> <pre><code>d = {k: v.index[v].tolist() for k, v in df.T.items()} print (d) {'AC': ['a_11'], 'BA': ['a_11', 'd_12'], 'AA': []} </code></pre> <p>Another idea with <code>zip</code> and convert values...
python|pandas|dataframe|dictionary
1
2,564
64,603,437
Handyspark Dataframe works on driver or executor
<p>Handyspark dataframe in Pyspark is a bridge between pyspark dataframe and pandas dataframe ,So does it reside on executor node or driver node?</p>
<p>HandySpark isn't a &quot;bridge&quot; - it's a wrapper round a Spark DataFrame which gives it a pandas-like API. Therefore it executes on the executors; there would be little point in the project if it executed on the driver as you could always just to <code>toPandas</code> on your DataFrame to pull it back to the d...
pandas|dataframe|pyspark
0
2,565
64,425,696
Equivalent of np.resize in TensorFlow
<p>I have a 1D array <code>x</code> and want to reshape it to the requested shape in the same way that <a href="https://numpy.org/doc/stable/reference/generated/numpy.resize.html" rel="nofollow noreferrer">np.resize</a> is doing, i.e. if there is too many elements in <code>x</code> they are dropped, if it is too few, t...
<p>I am not sure that this is doable in single operation in TF, but one can write a function using crops or <code>tf.tile</code> and then reshaping the result.</p>
tensorflow|tensor
1
2,566
64,401,900
Python, x-axis title is overlapping the tick labels in matplotlib
<p>I'm plotting a graph and the x-axis label is not visible in the graph.</p> <p><a href="https://i.stack.imgur.com/WDuWN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WDuWN.png" alt="enter image description here" /></a></p> <p>I have tried to solve it by adding the</p> <pre><code>ax.xaxis.labelpad...
<p>You could use &quot;<a href="https://matplotlib.org/tutorials/intermediate/tight_layout_guide.html" rel="nofollow noreferrer">Tight Layout</a>&quot; function in matplotlib to solve the issue.</p> <p>Add the line before you plot the graph, where <code>h_pad</code> will adjust the height, <code>w_pad</code> will adjus...
python|pandas|matplotlib|graph|adjustment
3
2,567
64,212,463
Combine series by date
<p>The following 2 series of stocks in a single excel file:</p> <p><a href="https://i.stack.imgur.com/nY0bj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nY0bj.png" alt="enter image description here" /></a></p> <p>Can be combined using the date as index?</p> <p>The result should be like this:</p> <...
<p>I am trying this:</p> <pre><code>df3 = pd.concat([df1, df2]).sort_values('Date').reset_index(drop=True) </code></pre> <p>or</p> <pre><code>df3 = df1.append(df2).sort_values('Date').reset_index(drop=True) </code></pre>
python|pandas|dataframe|indexing
1
2,568
47,718,865
How to apply a function to mulitple columns of a pandas DataFrame in parallel
<p>I have a pandas DataFrame with hundreds of thousands of rows, and I want to apply a time-consuming function on multiple columns of that DataFrame in parallel.</p> <p>I know how to apply the function serially. For example:</p> <pre><code>import hashlib import pandas as pd df = pd.DataFrame( {'col1': range(10...
<p>The easiest way to do this is using <a href="https://docs.python.org/3/library/concurrent.futures.html" rel="nofollow noreferrer"><code>concurrent.futures</code></a>.</p> <pre><code>import concurrent.futures with concurrent.futures.ProcessPoolExecutor(16) as pool: df['md5'] = list(pool.map(foo, df['col1'], df[...
python|pandas|concurrent.futures
2
2,569
47,898,147
Tensorflow Module Import error: AttributeError: module 'tensorflow.python.ops.nn' has no attribute 'rnn_cell'
<p>When attempting to pass my RNN call, I call tf.nn.rnn_cell and I receive the following error: </p> <pre><code>AttributeError: module 'tensorflow.python.ops.nn' has no attribute 'rnn_cell' </code></pre> <p>Which is odd, because I'm sure I imported everything correctly: </p> <pre><code>from __future__ import print_...
<p>Replace <code>tf.nn.rnn_cell</code> with <code>tf.contrib.rnn</code></p> <p>Since version 1.0, <code>rnn</code> implemented as part of the contrib module.</p> <p>More information can be found here <a href="https://www.tensorflow.org/api_guides/python/contrib.rnn" rel="nofollow noreferrer">https://www.tensorflow.or...
python|tensorflow|python-import|attributeerror|rnn
3
2,570
48,899,041
Separate letters and digits using regex with pandas
<p>I have a column called 'value' from a pandas dataframe, df, that has a mixture of numbers and words. It looks something like this:</p> <pre><code> VALUE 0 done 1 Yes 2 3.45 3 2bc </code></pre> <p>I want to split the column up to 2 columns where the left one only has letters and the right one only numbers...
<p>Fix your pattern, and use <code>str.extractall</code>:</p> <pre><code>(df.VALUE.str.extractall('(\d+(?:\.\d+)?)|([^\d.]+)') .unstack() .groupby(level=0, axis=1) .first()) 0 1 0 NaN done 1 NaN Yes 2 3.45 NaN 3 2 bc </code></pre>
python|regex|string|pandas
3
2,571
58,845,305
Pandas - date range with monthly rollover, weekmask and list of holidays
<p>I was looking for similar problem but I could not have find an answer for my issue. I try to generate date range in Pandas with monthly or quarterly rollover in respect to a weekmask and a list of holidays. So far I managed to make a range but with daily frequency. Is there any way I could make this dates rolling mo...
<p>I think I found a nice solution provided by @MaxU at <a href="https://stackoverflow.com/questions/48454189/pandas-date-range-for-six-monthly-values">Pandas date_range for six-monthly values</a> However it does not behave as expected because it skips start_date in 1) and 2) solution while it returns an error in 3) so...
python|pandas|time-series
0
2,572
58,912,108
Continuously calculating averages over past intervals w/ Pandas DataFrame
<p>I believe that my problem is really straightforward and there must be a really easy way to solve this issue, however as I am don't feel really confident on working with timestamps so I could not sort that problem by my own.</p> <p>I made the following example, which represents a simple case of what I have been work...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.window.Rolling.mean.html#pandas.core.window.Rolling.mean" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.window.Rolling.mean.html#pandas.core.window.Rolling.mean</a></p> <pre><code>data[...
python|pandas|dataframe
1
2,573
58,647,340
Finding intersection of pandas data frame index in groupby
<p>I am using Python and have a data frame with a datetime index, a grouping variable (gvar) and a value variable (x). I would like to find all the common datetimes between the groups.</p> <p>I already have a solution using functools, but I am seeking a way to do it using pandas functionalities only (if possible).</p>...
<p>This should do it:</p> <pre><code>&gt;&gt;&gt; df.reset_index().loc[df['gvar'].reset_index().drop_duplicates().duplicated('index'),'index'].tolist() </code></pre> <p>Returning:</p> <pre><code>[Timestamp('2018-01-03 00:00:00')] </code></pre> <p>And if you need the corresponding groups or values:</p> <pre><code>&...
python|pandas
1
2,574
59,034,759
Count how many times value A exists in dataframe rows, how many times value B and how many times value A and B
<p>I have a dataframe &quot;dfTags&quot; with 140.000 rows (all lowercase), number of comma separated values in column &quot;tags&quot; can range from 71 to 1. But column tags is one single string, Pandas does not know arrays or lists:</p> <pre><code>index tags 0 a, b, c, aa, bb, 2019 1 a, d, 18, gb 2 aa, a...
<p>This is not a complete answer, but it will give you, for every tagTupples(<code>tt</code>) how many times the first element of the <code>tt</code> appears and how many times both of them appear and then you can do your calculations</p> <pre><code>import pandas as pd df = pd.DataFrame({'tags': [['a', 'b', 'c', 'aa']...
string|pandas|dataframe|count|csv
0
2,575
58,808,798
pandas dataframe, regrouping
<p>I have the following sample dataset:</p> <pre><code>import pandas as pd data = {'Sentences':['Sentence1', 'Sentence2', 'Sentence3', 'Sentences4', 'Sentences5', 'Sentences6','Sentences7', 'Sentences8'],\ 'Start_Time':[10,15,77,120,150,160,176,188],\ 'End_Time': [12,17,88,128,158,168,182,190],...
<p>Use:</p> <pre><code>mean_time=df[['Start_Time','End_Time']].mean(axis=1).rename('Interval Time') labels = ["{0}-{1}".format(time_list[i], time_list[i+1]) for i in range(len(time_list)-1)] new_df= ( df.groupby(pd.cut(mean_time,bins=time_list, labels=labels,include_lowest=True)) .Sentences .a...
python-3.x|pandas
2
2,576
58,662,187
Pandas promotes int to float when filtering
<p>Pandas seems to be promoting an <code>int</code> to a <code>float</code> when filtering. I've provided a simple snippet below but I've got a much more complex example which I believe this promotion leads to incorrect filtering because it compares <code>floats</code>. Is there a way around this? I read that this is a...
<p>There is no float comparison happening here. <code>isin</code> is returning <code>NaN</code>'s for missing data, and since you are using <code>numpy</code>'s <code>int64</code>, the result is getting cast to <code>float64</code>.</p> <p>In 0.24, pandas added a <a href="https://pandas.pydata.org/pandas-docs/stable/...
python|pandas|numpy
1
2,577
58,878,953
Convert Mysql.connector dtypes objects to numeric/ string
<p>I have an SQL query with mysql.connector in python 3. I m converting the result of fetchall to a pandas Dataframe.</p> <pre><code>mycursor.execute(sql_query) m_table = pd.DataFrame(mycursor.fetchall()) m_table.columns = [i[0] for i in mycursor.description] </code></pre> <p>Getting dtypes gives me :</p> <pre><c...
<p>This is an easy way to apply this conversion to all columns in case you <strong>are sure</strong> you need them <strong>all</strong> to be transformed into floats except the ones that can't (because they contain strings):</p> <pre><code>import numpy as np import pandas as pd data = {'a':[1,2,3,4],'b':['a','b','aa',...
python|pandas|numpy
1
2,578
58,903,566
Grouping and adding values based on row string with pandas?
<p>I have the following pandas data set:</p> <pre><code>date, pair, value, fruit 2019-11-15 09:35:33,EUR,10,BANANA 2019-11-15 09:35:32,EUR,12,BANANA 2019-11-15 09:35:31,EUR,21,APPLE 2019-11-15 09:35:30,EUR,17,ORANGE 2019-11-15 09:35:28,EUR,19,BANANA 2019-11-14 09:58:05,EUR,37,APPLE 2019-11-14 09:23:42,EUR,41,ORANGE 20...
<p>I think this might help </p> <pre><code>a=your_df.groupby(["fruit"]).sum()["value"] </code></pre>
python|pandas|numpy|data-science
0
2,579
70,330,526
Operations on specific elements of a dataframe in Python
<p>I'm trying to convert kilometer values in one column of a dataframe to mile values. I've tried various things and this is what I have now:</p> <pre><code>def km_dist(column, dist): length = len(column) for dist in zip(range(length), column): if (column == data[&quot;dist&quot;] and dist in data.loc[(...
<p>Instead your solution filter rows with mask and divide column <code>dist</code> by <code>5820</code>:</p> <pre><code>data.loc[data[&quot;dist&quot;] &gt; 25, 'dist'] /= 5820 </code></pre> <p>Working same like:</p> <pre><code>data.loc[data[&quot;dist&quot;] &gt; 25, 'dist'] = data.loc[data[&quot;dist&quot;] &gt; 25, ...
python|pandas
1
2,580
70,356,417
Tensorflowjs - Reshape/slice 4d tensor into image
<p>I am trying to apply style transfer to a webcam capture. I am reading a frozen model I've previously trained in python and converted for TFjs. The output tensor's shape and rank is as follows: <a href="https://i.stack.imgur.com/KIB00.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KIB00.png" alt="...
<p>given your tensor is <code>[1, 15, 20, 512]</code><br /> you can remove any dims with value of 1 (same dim you've added by running <code>expandDims</code>) by running</p> <pre><code>const squeezed = tf.squeeze(tensor) </code></pre> <p>that will give you <strong>shape</strong> of <code>[15, 20, 512]</code></p> <p>but...
tensorflow|deep-learning|tensorflow.js
1
2,581
70,156,578
Color Formating from pandas to excel
<p>I have a pandas dataframe with values and a condition according to previous filtering. I would like to print my dataframe in an excel and color the cell according to the filtering result (if <em>passed</em>: <strong>green</strong> and if <em>not_passed</em>: <strong>red</strong>). Here is an example code and how I w...
<p>Use a for loop to check if the <code>filter value == 'passed'</code><br> If it is, you can apply the green format to this cell, and Vice versa for Red using worksheet.write(row_index,column_index,value,format).</p> <p><em>Note that Pandas data frames use a different indexing method than Excel. Notably, Pandas starti...
python|excel|pandas|dataframe
2
2,582
56,386,719
Keras Tensorflow fails to learn simple linear relationship
<p>I am fairly new to Tensorflow/Keras and am trying to set up an LSTM model. I have successfully run my code already, but my results have failed to give me meaningful results. I, therefore - as a test - let my LSTM network learn one of the features I am inputting. I am aware that the LSTM and relu use nonlinear relati...
<p>A few issues:</p> <p>Typically, LSTM layers go at the start, followed by a few dense layers. </p> <p>Also, the LSTM layer before the dense layer needs to have return_sequence set to False. </p> <p>However, I'm not sure that they are the reason to cause this problem, I'm just pointing out the problems. I think it ...
tensorflow|machine-learning|keras|lstm
0
2,583
55,632,558
Number of days between two successive rows in pandas with timestamp ERROR: dtype('<m8[D]')
<p>i have a pandas dataframe like follows:</p> <pre><code>device_id date 101 2018-10-30 10:42:32 101 2018-12-20 14:14:14 102 2018-09-26 14:21:33 102 2018-10-24 09:12:35 102 2018-11-12 04:52:21 </code></pre> <p>My expected output is</p> <pre><code>device_id date ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.floor.html" rel="nofollow noreferrer"><code>Series.dt.floor</code></a> for datetimes without times, then <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferr...
python|pandas|pandas-groupby
2
2,584
55,664,514
Pandas fillna() not working on DataFrame slices
<p>Pandas <code>fillna</code> is not working on DataFrame slices, here is an example</p> <pre><code>df = pd.DataFrame([[np.nan, 2, np.nan, 0], [3, 4, np.nan, 1], [np.nan, np.nan, np.nan, 5], [np.nan, 3, np.nan, 4]], columns=list('ABCD')) df[["A", 'B']].fi...
<p>If we look at the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer"><code>pandas documentation</code></a> it says you should use the following to <code>fillna</code> on slices:</p> <pre><code>values = {'A':0, 'B':0} df.fillna(value=values, in...
python|pandas|dataframe|fillna
3
2,585
55,953,800
Change case for columns in list
<p>How do I change the case for data frame columns that are in a list? I know how to make all columns upper case but I don't know how to only make specific columns upper case. </p> <pre><code>d = {'name':['bob','john','sue'],'id':[545,689,143],'fte':[1,.5,.75]} df = pd.DataFrame(d) # list of columns I want to make upp...
<p>It won't work the way you're trying to do it, the reason being that indices <em>do not</em> support <strong>mutable operations</strong>. So one thing you could do is to use a list comprehension to generate a new list of column names an reassign it to <code>df.columns</code>:</p> <pre><code>df.columns = [i.upper() i...
python|pandas
5
2,586
64,964,813
replace 2 selected row values based on others
<p>I have a df that looks like this:</p> <pre><code>Id Class Label 0 APPS Item 1 MODEL Item 2 PRICE Money </code></pre> <p>I want to check all <code>Class</code>entries where the Label is <code>Item</code>. Among these classes, I want to replac...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a> with chain 2 conditions by <code>&amp;</code> for bitwise <code>AND</code> - here is assign list with 2 values because selected 2 columns <code>['Class', 'Label']...
python|python-3.x|pandas|dataframe|data-analysis
0
2,587
64,869,905
Serving tensorflow models on GCP?
<p>Recently I've been trying to host a custom image classification tensorflow saved model on GCP and use a REST API to send prediction requests. I've hosted this model on Google's <a href="https://cloud.google.com/ai-platform/prediction/docs/reference/rest/v1/projects/predict" rel="nofollow noreferrer">AI Platform API<...
<p>Firstly, I don't recommend you to publicly open billable resources like this, because you are exposed to attack and huge consumption.</p> <p>But, if you really want to achieve this, you can allow <code>allUsers</code> on your deployed models</p> <pre><code>gcloud ai-platform models add-iam-policy-binding &lt;MY_MODE...
tensorflow|machine-learning|google-cloud-platform|google-ai-platform
1
2,588
64,850,973
remove points located within a specific area - python
<p>I'm trying to remove points that are located within a specific area. Using below, I'm hoping to remove points that are located within the blue box. Ideally, I'd map out a polygon that followed the contour of the circle more closely. This is just a rough description.</p> <p>I'm currently applying a crude subset to th...
<p>I'd suggest to store your polygon (the <code>&lt;Line2D object&gt;</code>) in a variable like this:</p> <pre><code>line = plt.plot(x,y) </code></pre> <p>Which enables you to utilise the <a href="https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D.get_path" rel="nofollow nore...
python|pandas
1
2,589
40,064,587
Image display error after changing dtype of image matrix
<p>I'm using opencv + python to process fundus(retinal images). There is a problem that im facing while converting a float64 image to uint8 image.</p> <p><strong>Following is the python code:</strong></p> <pre><code>import cv2 import matplotlib.pyplot as plt import numpy as np from tkFileDialog import askopenfilename...
<p>Look I executed your code and there are the <a href="http://postimg.org/gallery/1qi7dozn0" rel="nofollow">results</a></p> <p>They seem pretty normal to me... this is the exact <a href="https://pastebin.com/6jwgKi9r" rel="nofollow">code</a> I used</p> <p>Ar is different from the others because when you <code>imShow...
python|opencv|numpy
1
2,590
43,953,594
calculate row difference groupwise in pandas
<p>I need to calculate the difference between two rows groupwise using pandas.</p> <pre><code>| Group | Value | ID | ---------------------- | M1 | 10 | F1 | ---------------------- | M1 | 11 | F2 | ---------------------- | M1 | 12 | F3 | ---------------------- | M1 | 15 | F4 | ------------------...
<p>I think you need custom function with <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#flexible-apply" rel="nofollow noreferrer">apply</a> which return <code>DataFrame</code> for each group, for select by position is used <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.i...
python|pandas|numpy
1
2,591
40,847,809
Pandas aggregation subtraction based on column value
<p>Suppose I have DataFrame</p> <pre><code>'name' 'quantity' 'day' 'A' 1 'Monday' 'A' 10 'Sunday' 'A' 5 'Friday' 'B' 2 'Monday' 'B' 30 'Sunday' 'B' 5 'Thursday' </code></pre> <p>What I need to build is anot...
<p><strong><em>setup</em></strong> </p> <pre><code>import pandas as pd from io import StringIO txt = """name quantity day A 1 Monday A 10 Sunday A 5 Friday B 2 Monday B 30 Sunday B 5 Thursday""" df = pd.r...
python|pandas|group-by
4
2,592
40,895,730
Python DataFrame from a list
<p>So, I have to create a dataframe. I do not mind my source to be a list of dicts or a dict.</p> <pre><code>List of Dict: [{'A': 'First', 'C': 300, 'B': 200}, {'A': 'Second', 'C': 310, 'B': 210}, {'A': 'Third', 'C': 330, 'B': 230}, {'A': 'Fourth', 'C': 340, 'B': 240}, {'A': 'Fifth', 'C': 350, 'B': 250}] </code></pre>...
<p>Also you can use <code>pd.DataFrame.from_records()</code> where you can set a specific column to be index:</p> <pre><code>pd.DataFrame.from_records([{'A': 'First', 'C': 300, 'B': 200}, {'A': 'Second', 'C': 310, 'B': 210}, {'A': 'Third', 'C': 330, 'B': 230}, {'A': 'Fourth', 'C': 340, 'B': 240}, {'A': 'Fifth', 'C'...
python|pandas|dataframe
3
2,593
53,957,213
Tensorflow feed_dict dimension miss match with the neural network input and training input
<p>I have two classes of diseases <code>A</code> and <code>B</code>. My training data has <code>28</code> images including both classes. I have created resize function using opencv.</p> <pre><code>def resize_cv(x,width,height): new_image=cv.resize(x,(width,height)) return new_image </code></pre> <p><code>X</...
<p>The answer was simple the reason the Conversion of <strong>(196,196,3)</strong> happened due to the extra for loop in the scaling function. </p> <p>Instead of using this code </p> <pre><code>def scaling (X): new=[] for i in X: for j in i: new.append(j/255) break return n...
python-3.x|tensorflow|multidimensional-array
0
2,594
53,967,271
Detecting a list type in pandas
<p>Is there a way to see if a field is an array in <code>pandas</code>? For example:</p> <pre><code>&gt;&gt;&gt; data=[{'name':'tom','colors':[1,2,3]}] &gt;&gt;&gt; df = pd.DataFrame(data) colors name 0 [1, 2, 3] tom &gt;&gt;&gt; df['colors']['dtype'] Name: colors, dtype: object </code></pre> <p>Is there a wa...
<p>If the data in the columns is consistent that is lists then use:</p> <pre><code>type(df.loc[0,'colors']) list </code></pre>
python|pandas
0
2,595
53,926,627
Does keras use gpu automatically?
<p>It seems like it uses gpu automatically, but I do not know why.</p> <p>First, I declared as below</p> <pre><code>tf_config = tf.ConfigProto( allow_soft_placement=True ) tf_config.gpu_options.allow_growth = True sess = tf.Session(config=tf_config) keras.backend.set_session(sess) </code></pre> <p>Then I defined so...
<p>According to the <a href="https://www.tensorflow.org/guide/using_gpu" rel="noreferrer">documentation</a> TensorFlow will use GPU by default if it exist:</p> <blockquote> <p>If a TensorFlow operation has both CPU and GPU implementations, <strong>the GPU devices will be given priority</strong> when the operation is...
tensorflow|model|keras|gpu
9
2,596
66,158,638
First 'Group by' then plot/save as png from pandas
<p>first I need to filter data then plot each group separately and save files to directory</p> <pre><code>for id in df[&quot;set&quot;].unique(): df2= df.loc[df[&quot;set&quot;] == id] outpath = &quot;path/of/your/folder/&quot; sns.set_style(&quot;whitegrid&quot;, {'grid.linestyle': '-'}) plt.figure(figs...
<p>This worked for me but it is very slow</p> <pre><code>groups = df.groupby(&quot;set&quot;) for name, group in groups: sns.set_style(&quot;whitegrid&quot;, {'grid.linestyle': '-'}) plt.figure(figsize=(12,8)) ax1=sns.scatterplot(data=group, x=&quot;x&quot;, y=&quot;y&quot;, hue=&quot;result&...
pandas|matplotlib|plot
0
2,597
66,101,687
Reformatting a numpy array
<p>I have come across some code (which may answer <a href="https://stackoverflow.com/questions/65936033/assigning-a-label-to-its-corresponding-grid-cell">this</a> question of mine). Here is the code (from Vivek Maskara's solution to my issue):</p> <pre><code>import cv2 as cv import numpy as np def read(image_path, lab...
<p>I will first create and explain a simplified example, and then explain the part you pointed.</p> <p>First, we create the ndarray named <code>label_matrix</code>:</p> <pre><code>import numpy as np label_matrix = np.ones([2, 3, 4]) print(label_matrix) </code></pre> <p>This code means that you wil get an array containi...
python|python-3.x|numpy|numpy-ndarray
1
2,598
66,181,278
targeting jth-kth element in a matirx using python
<p><a href="https://i.stack.imgur.com/l092C.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l092C.jpg" alt="enter image description here" /></a></p> <p>I would like to implement a matrix that satisfies the conditions shown in the image:</p> <ol> <li>The matrix is an <code>m * n</code> matrix</li> <li...
<p>You're overthinking this. Start with</p> <pre><code>A = np.zeros((m, n)) </code></pre> <p>The condition <code>k = j + 1</code> is just the first diagonal above the main one. You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.fill_diagonal.html" rel="nofollow noreferrer"><code>np.fill_diagona...
python|numpy|matrix
2
2,599
66,296,162
Numpy ravel takes too long after a slight change to a ndarray
<p>I am working with a flatten image (1920x1080x4), in which I need to reshape (e.g. <code>arr.reshape((1920,1080,4))</code>), remove the last channel (e.g. <code>arr[:,:,:3]</code>), convert from BGR to RGB (e.g. <code>arr[:,:,::-1]</code>) and finally flatten again (e.g. <code>arr.ravel()</code>). The problem is with...
<p>This is because all your operations above are producing views for the same data, but the last ravel is required to make a copy.</p> <p>An array in numpy array has an underlying memory, and shape &amp; strides determining where each element lies.</p> <p>Reshaping a contiguous array may be performed by simply changing...
python|arrays|numpy|memory|flatten
2