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
15,000
62,013,721
How to solve DLL load failed:A dynamic link library (DLL) initialisation routine failed. of Tensorflow?
<p>I am using Python 3.7.3 and pip version 20.1 and I installed tensorflow 2.0 using pip. I've successfully installed tensorflow. But when I try to run import tensorflow as tf it shows error as ImportError: DLL load failed: A dynamic link library (DLL) initialisation routine failed.</p> <p>Failed to load the native Te...
<p>New version of tensorflow (for example I am using tensorflow v2.2) windows installation needs <code>Microsoft Visual C++ 2019 Redistributable</code></p> <p><a href="https://www.tensorflow.org/install/source_windows#install_visual_c_build_tools_2019" rel="nofollow noreferrer">https://www.tensorflow.org/install/sourc...
python|python-3.x|tensorflow|pip|tensorflow2.0
1
15,001
61,627,797
Logloss metric in Fastai
<p>i'm doing a competition in zindi plateform which they are using The evaluation metric for this challenge as Log Loss.</p> <p>so i'm working with fastai library and i want the metric log loss .. i didn't find LogLoss as metric in this library ! i tried some codes like the function provided by sklearn <code>from skl...
<p>if needed as a metric (typically mostly used as a loss) you should be able to use cross_entropy function from pytorch:</p> <blockquote> <p>import torch.nn.functional as F</p> <p>metrics=[F.cross_entropy,(plus other metrics if needed)]</p> <p>model= cnn_learner(data, model, metrics=metrics,...)</p> </blo...
pytorch|metrics|fast-ai
2
15,002
61,763,344
Getting memory error for graph clustering even for 128 GB of memory. Why?
<p>I am using <strong>python</strong> language on a Linux server with <strong>128 GB memory</strong>. I am doing graph clustering using <strong>Markov algorithm</strong>. The details of the process are as follows:</p> <pre><code>Graphtype = nx.Graph() G = nx.from_pandas_edgelist(df, 'source','target', edge_attr='weigh...
<p>I'd assume from your code that you're using 32 bit Python, which means that regardless of hardware, you won't be able to make use of more that 4GB of RAM.</p> <p>Upgrading to a 64 bit Python will let you use up to 16EB of RAM which will allow you to use the additional space you have on a server.</p> <p>You could s...
python|pandas|graph|cluster-analysis|networkx
3
15,003
57,884,655
How can I group the rows in one column and name them?
<p>I have a data set as the following:</p> <pre><code>Zipcodes Population Precipitation 10 10 100 45 20 200 58 30 300 11 40 400 22 50 500 19 60 600 </code></pre> <p>and I want to group some Zipcodes (i.g, 10, 22, 1...
<p>If each zipcode are defined in list, e.g. in dictionary:</p> <pre><code>d = {'a':[10, 22, 19], 'b':[45,58,11]} #swap key values in dict #http://stackoverflow.com/a/31674731/2901002 d1 = {k: oldk for oldk, oldv in d.items() for k in oldv} df['Zipcodes'] = df['Zipcodes'].map(d1) df = df.groupby('Zipcodes', as_...
pandas|pandas-groupby
0
15,004
58,159,274
How can I extract and further test the list of dates from pandas DatetimeIndex?
<p>There are really two parts to this Question as I am still learning. </p> <pre><code>date_list = pd.date_range(2019-09-24, 2019-09-26) </code></pre> <p>will return an object</p> <blockquote> <p>DatetimeIndex(<strong>['2019-09-24', '2019-09-25']</strong> , dtype='datetime64[ns]', freq='D')</p> </blockquote> <p...
<p>You can create a list of dates in string format using this method</p> <pre><code>[i.strftime(&quot;%Y-%m-%d&quot;) for i in pd.date_range(start=start_date, end=end_date)] </code></pre>
python|pandas|python-unittest
0
15,005
57,782,908
Match data in two columns and add match to the dataframe
<p>I have two dataframe : First dataframe </p> <blockquote> <pre><code> Column1 Column2 Column3 0 A1 B1 C1 1 A2 B2 C2 2 A3 B3 C3 2 A4 B4 C4 </code></pre> </blockquote> <p>Second dataframe</p>...
<p>The following code do the job on your example:</p> <pre class="lang-py prettyprint-override"><code>result_df = ( df1.merge( df2.rename({'Column2': 'Column4'}, axis='columns'), how='left', on=['Column1'] ) .merge( df2.rename({'Column2': 'Column5'}, axis='columns'), how='left', ...
python|python-3.x|pandas|dataframe
1
15,006
54,901,241
Anaconda connection failed when changing python version
<p>I'm in trouble concerning my Anaconda set up. I want to install keras for R using Anaconda. But when i try to install TensorFlow (using Anaconda), it says me conflicts happend. I found it was because of my python version (3.7) which is not supported by TensorFlow.</p> <p>So I tried to change the version of python u...
<p>Fixed :</p> <p>I downgraded Anaconda to 3.5, it was conflicts with Anaconda 2018 and windows 10. Probably not the best way but the fastes one !</p>
python|http|tensorflow|anaconda
0
15,007
54,896,846
Tensorflow : How to perform an operation parallel on every n elements?
<p>What should I do if I want to get the sum of every 3 elements?</p> <pre><code>test_arr = [1,2,3,4,5,6,7,8] </code></pre> <p>It sounds like a map function </p> <pre><code>map_fn(arr, parallel_iterations = True, lambda a,b,c : a+b+c) </code></pre> <p>and the result of <code>map_fn(test_arr)</code> should be </p> ...
<p>It's even easier: use a list comprehension. Slice the list into 3-element segments and take the sum of each. Wrap those in a list.</p> <pre><code>[sum(test_arr[i-2:i+1]) for i in range(2, len(test_arr))] </code></pre>
python|numpy|tensorflow
1
15,008
73,243,735
understanding pytorch quantization model output
<p>Here's two ways to use pytorch's <code>mobilenet_v3_large</code>.</p> <p>The first <strong>not</strong> using quantization:</p> <pre class="lang-py prettyprint-override"><code>import torchvision import torch model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True) model.eval() x = [torch.rand(3...
<p>You are importing the wrong module/weights. If you want to perform object detection, you have to import your models from the <code>torchvision.models.detection</code> module.</p> <p>In your second code snippet, you are loading weights of only MobileNet network and using it on a MobileNet network, not an object detec...
python|pytorch|torch|torchvision
0
15,009
73,360,681
Wanting to compare two data frames to check if username and password are correct from the data saved in my excel file, using pandas only
<p>I am trying to make a login page with Tkinter, and pandas only, trying to store all the data in excel file and am having trouble with reading the excel file.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd def USPchecker():# method name obt_Username = UsrInp.get() # storring input fr...
<p>Not sure why you are storing the obt data in a dataframe. The below function will return True or False regarding the obt fields:</p> <pre><code>def check_login(df2, obt_Username, obt_Password): df = df2[df2['username']==obt_Username] &amp; df2['password']==obt_Password] if len(df) &gt; 0: return True...
python|pandas|dataframe
0
15,010
73,499,414
Save a list of dictionaries with numpy arrays
<p>I have a dataset composed as:</p> <pre><code>dataset = [{&quot;sample&quot;:[numpy array (2048,3) shape], &quot;category&quot;:&quot;Cat&quot;}, ....] </code></pre> <p>Each element of the list is a dictionary containing a key &quot;sample&quot; and its value is a numpy array that has shape (2048,3) and the category...
<p>Creating an example specific to your data requires more details about the dictionaries in the list. I created an example that assumes every dictionary has:</p> <ul> <li>A unique value for the <code>category</code> key. The value is used for the dataset name.</li> <li>There is a <code>sample</code> key with the array...
python|numpy|hdf5|h5py
1
15,011
67,344,068
TensorFlow 2 - does NumPy numerical values and arrays cause new graphs for TF Function?
<p>Does &quot;<strong>numerical Python values</strong>&quot; stated in the <a href="https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/" rel="nofollow noreferrer">Hands on ML 2</a> include NumPy int, float, and array? Do we need to explicitly create a TF Tensor or a TF DataSet from a NumPy con...
<p>I dont think changing the values inside numpy arrays will generate a new graph. Consider the following minimal code exampls:</p> <pre><code>@tf.function def test(input): print(&quot;Tracing with input= &quot;, input) tf.print(&quot;Executing with input = &quot;, input) </code></pre> <p>The first print is only ...
python|numpy|tensorflow2.0
2
15,012
67,202,190
Calculate Statistical Metrics On Time-Series Data
<p>I have a dataframe that looks like this:</p> <pre><code> ID DATE QTD 0 71896517 2020-07-25 1 1 71896517 2020-09-14 2 2 72837949 2020-09-21 1 3 72848188 2020-11-03 1 4 73307986 2020-11-04 1 5 72848188 2020-11-16 1 6 71896517 20...
<p>There's usually an iterative solution.</p> <pre><code>import pandas as pd import numpy as np def monthdelta(a,b): a1,a2,a3 = (int(k) for k in a.split('-')) b1,b2,b3 = (int(k) for k in b.split('-')) return (a1*12+a2) - (b1*12+b2) data = [ [ 71896517, &quot;2020-07-25&quot;, 1 ], [ 71896517, &quot;2020-0...
python|pandas|numpy|jupyter-notebook|time-series
0
15,013
67,196,334
Save the file in a different folder using python
<p>I have a pandas dataframe and I would like to save it as a text file to another folder. What I tried so far?</p> <pre><code>import pandas as pd df.to_csv(path = './output/filename.txt') </code></pre> <p>This does not save the file and gives me an error. How do I save the dataframe (df) into the folder called outpu...
<p>the first arguement name of <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html" rel="nofollow noreferrer"><code>to_csv()</code></a> is <code>path_or_buf</code> either change it or just remove it</p> <pre><code>df.to_csv('./output/filename.txt') </code></pre>
pandas|dataframe|directory|path|save
0
15,014
67,602,696
Keep rows of a pandas dataframe based on both row and column conditions
<p>Hello I have a pandas dataframe that I want to clean.Here is an example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>IDBILL</th> <th>IDBUYER</th> <th>BILL</th> <th>DATE</th> </tr> </thead> <tbody> <tr> <td>001</td> <td>768787</td> <td>45</td> <td>1897-07-24</td> </tr> <tr> <td>001</t...
<p>One solution:</p> <pre><code>df = df.sort_values('BILL') df.loc[df.assign(cc = df.groupby(['DATE','IDBUYER',df.groupby(['DATE','IDBUYER'])['IDBILL'].transform(lambda x: x.diff().gt(1).cumsum())]).cumcount(),cc2 = df.groupby(['DATE','IDBUYER','IDBILL']).transform('count'),floor = lambda x: ~(x['cc'].floordiv(x['cc2']...
python|pandas|dataframe
1
15,015
67,270,653
Creating new numpy array using another "template" array
<p>Suppose i have:</p> <pre><code>x1 = [1, 3, 2, 4] </code></pre> <p>and:</p> <pre><code>x2 = [0, 1, 1, 0] </code></pre> <p>with the same shape</p> <p>now i want to &quot;put x2 ontop of x1&quot; and sum up all the numbers of x1 corresponding to the numbers of x2</p> <p>so the end result is:</p> <pre><code>end = [1+4 ,...
<p>We can get the <code>unique</code> values in the array <code>x2</code> then for each unique value in <code>x2</code> compare it with <code>x2</code> to create a boolean mask, then apply this boolean mask on <code>x1</code> to filter the elements and take the <code>sum</code> of all filtered elements</p> <pre><code>x...
python|numpy
1
15,016
60,074,481
ImportError: cannot import name 'Session' from 'tensorflow'
<p>I'm struggle with running module.</p> <pre><code>from tensorflow import Session, ConfigProto, GPUOptions gpuoptions = GPUOptions(allow_growth=True) session = Session(config=ConfigProto(gpu_options=gpuoptions)) K.set_session(session) classifier = Sequential() </code></pre> <p>I don't know why it's not working.</p> ...
<p>I guess you're using TensorFlow 2.x. In that case, use tf.compat.v1.--function--() instead.</p> <pre><code>import tensorflow as tf gpuoptions = tf.compat.v1.GPUOptions(allow_growth=True) session = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(gpu_options=gpuoptions)) K.set_session(session) classifier = Sequen...
python|tensorflow
2
15,017
60,121,693
Python combines multiple column in one
<p>I have a pandas dataframe as below:</p> <pre><code>data = {'A' :[1,2,3], 'B':[2,17,17], 'C1' :["C1",np.nan,np.nan], 'C2' :[np.nan,"C2",np.nan]} # Create DataFrame df = pd.DataFrame(data) df A B C1 C2 0 1 2 C1 NaN 1 2 17 NaN C2 2 3 17 NaN NaN </co...
<p>Try this</p> <pre><code>df1 = df.filter(regex='^C\d+') df['C'] = df1[df1.isin(df1.columns)].bfill(1).iloc[:,0] Out[117]: A B C1 C2 C 0 1 2 C1 NaN C1 1 2 17 NaN C2 C2 2 3 17 NaN NaN NaN </code></pre> <hr> <p>If you want to strictly compare values matching to its own column name, Us...
python-3.x|pandas
3
15,018
59,988,185
How to produce a variable size distance matrix in keras?
<p>What I am trying to achieve now is to create a custom loss function in Keras that takes in two tensors <code>(y_true, y_pred)</code> with shapes <code>(None, None, None)</code> and <code>(None, None, 3)</code>, respectively. However, the <code>None</code>'s are so, that the two shapes are always equal for every <cod...
<p>Assuming that dimension 0 is the batch size as usual and you don't want to mix samples.<br> Assuming that dimension 1 is the one you want to make pairs<br> Assuming that the last dimension is 3 for all cases although your model returns <code>None</code>.</p> <p>Iterating tensors is a bad idea. It might be better ju...
python|tensorflow|keras|loss-function|distance-matrix
0
15,019
65,242,200
'draw' a random rhombus (diamond) on a numpy array (testing harris corner detection)
<p>I'm trying to create a random test for a &quot;harris_corner_detector&quot; function implementation (VERY GENERALLY AND SLIGHTLY INCORRECTLY: a function that finds corners in an image) In the test, I want to create random simple shapes in a binary numpy matrix (it's easy to know the coordinates of their corners) (e....
<p>There are a number of questions here, but the main one is how to create a numpy array of a filled rhombus given the corners. I'll answer that, and leave other questios, like creating random rhombuses, etc.</p> <p>To fill a convex polygon, one can find the line specified by subsequent corners and fill above or below ...
python|numpy|testing|draw|corner-detection
2
15,020
65,085,555
Pandas groupby and pivot table plotting
<p><a href="https://i.stack.imgur.com/bIsSb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bIsSb.png" alt="enter image description here" /></a></p> <p>I have a data set as such and I want to plot a bar graph showing popluation differences between <code>rural and urban</code> states of all states men...
<p>Remove unwanted total row from the data and get the rows which are states</p> <pre><code>Literacy_States = Literacy_States[(Literacy_States.TRU != 'Total') &amp; (Literacy_States.Level == 'State')].copy() </code></pre> <p>Create a column for the total population</p> <pre><code>Literacy_States['population'] = Literac...
python|pandas|dataframe|data-analysis
1
15,021
49,879,569
String function on a pandas series
<p>I wanted to used the below string functions text.lower for a Pandas series instead of from a text file. Tried different methods to convert the series to list and then string,, but no luck. Still I am not able to use the below function directly. Help is much appreciated.</p> <pre><code>def words(text): return r...
<p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow noreferrer"><code>apply</code></a> by your function:</p> <pre><code>s = pd.Series(['Aasa dsad d','GTH rr','SSD']) print (s) 0 Aasa dsad d 1 GTH rr 2 SSD dtype: object def words(...
python|string|pandas|series
0
15,022
50,187,342
TensorFlow gradient with tf.where returns NaN when it shouldn't
<p>Below is reproducible code. If you run it, you will see that in the first sess run, the result is nan, whereas the second case gives the correct gradient value of 0.5. But per tf.where and condition specified, they should return the same value. I also simply don't understand why the tf.where function gradient is nan...
<p>As explained in the <a href="https://github.com/tensorflow/tensorflow/issues/2540" rel="nofollow noreferrer">github issue</a> provided by @mikkola, the problem stems from the internal implementation of <code>tf.where</code>. Basically, both alternatives (and their gradient) are computed, and only the correct part is...
python|tensorflow|gradient
3
15,023
50,122,799
empty document error: scikit learn
<p>I am trying to fit SVM model for text classification but the line <code>x = text_clf_svm.fit(file_name, target_file)</code> is giving error. I tried various ways but could not solve it.</p> <pre><code>from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransf...
<p>In line</p> <p><code>count_vect = CountVectorizer(stop_words=None, input='file')</code></p> <p>you set <code>input</code> parameter to 'file'. From docs</p> <p><code>If ‘file’, the sequence items must have a ‘read’ method (file-like object) that is called to fetch the bytes in memory.</code></p> <p>You can:<br> ...
python|numpy|scikit-learn|svm
1
15,024
49,924,634
Pandas: Setting values in GroupBy doesn't affect original DataFrame
<pre><code>data = pd.read_csv("file.csv") As = data.groupby('A') for name, group in As: current_column = group.iloc[:, i] current_column.iloc[0] = np.NAN </code></pre> <p>The problem: 'data' stays the same after this loop, even though I'm trying to set values to np.NAN .</p>
<p>As @ohduran suggested:</p> <pre><code>data = pd.read_csv("file.csv") As = data.groupby('A') new_data = pd.DataFrame() for name, group in As: # edit grouped data # eg group.loc[:,'column'] = np.nan new_data = new_data.append(group) </code></pre>
python|pandas|dataframe|set|pandas-groupby
0
15,025
49,897,802
Resampling on non-time related buckets
<p>Say I have a df looking like this:</p> <pre><code> price quantity 0 100 20 1 102 31 2 105 25 3 99 40 4 104 10 5 103 20 6 101 55 </code></pre> <p>There are no time intervals here. I need to calculate a Volume Weighted Average Price for every 50 items in quantity. Ever...
<p>I struck out on my first at-bat facing this problem. Here's my next plate appearance. Hopefully I can put the ball in play and score a run.</p> <p>First, let's address some of the comments related to the expected outcome of this effort. The OP posted what he thought the results should be using the small sample data...
python-3.x|pandas|numpy|pandas-groupby
1
15,026
64,087,545
Error when resampling olhc dataframe with python
<p>When trying to resample OHLC dataframe from 1m to hourly i am getting this error:</p> <p><strong>Dataframe</strong></p> <pre><code>df.info() # Column Dtype --- ------ ----- 0 Date_Time datetime64[ns] 1 Open float64 2 High float64 3 Low float...
<p>Next version of code worked for me, I did only 2 mins aggregation due to few rows provided by you.</p> <p>I think the reason of non-working is due to that your data being in string format, instead of the need for date-time column to be in date-time format, and the rest in float numbers format, not strings. I did the...
python|pandas|dataframe
1
15,027
64,080,576
Join two dataframes based on common value in column (which is array)
<p>I have one dataframe - <code>df_similar_strings</code>, which looks like this:</p> <pre><code>|---------------------| | string_values | |---------------------| | ['catish', 'cat'] | |---------------------| | ['doggo', 'dogy'] | |---------------------| </code></pre> <p>and the other one - <code>df_source</c...
<p>You can solve it by first doing a cartesian-product between your two dataframes and then dropping from that dataframe all rows which doesn't have any shared value.</p> <p>For simplicity, I assume the columns on both datasets have the same name (&quot;values&quot;). Also, I assume the lists doesn't have repeated valu...
pandas|dataframe|join
1
15,028
63,946,824
Python pandas: Calculating percentage with groups using groupby
<p>I have a data frame which contains the information of customer type. I used <code>groupby</code> to count the type of customer within each category using following command:</p> <pre><code>df.groupby('Classification')['customer'].count() </code></pre> <p>It produces following result:</p> <pre><code>Classification Agr...
<p>The following should work:</p> <pre><code>df.groupby('Classification')['customer'].count()/df['customer'].count() </code></pre>
python|python-3.x|pandas
2
15,029
63,974,675
Setting y-axis labels, range, limit on bar graph python
<p>So I am trying to plot a bar graph of this dataframe, Teams consists of strings, Mentions consists of ints. Trying to plot Teams on x-axis, and Mentions on y-axis. But I am getting problems with the y-axis labels where the increments and labels are in decimals and I want them in integers/whole numbers:</p> <pre><cod...
<p>One of possible options is to use <em>MultipleLocator</em>, where you specify multiples of <em>y</em> value where ticks are to be printed (<code>import matplotlib.ticker as tck</code> required).</p> <p>Another detail is that the drawing code can be more concise when you:</p> <ul> <li>set the column to act as <em>x</...
python|numpy|matplotlib|plot|graph
0
15,030
64,147,923
Issues installing Geopandas
<p>I tried <code>pip install geopandas</code></p> <p>When I run that, I get this error:</p> <pre><code>Collecting geopandas Using cached geopandas-0.8.1-py2.py3-none-any.whl (962 kB) Collecting pyproj&gt;=2.2.0 Using cached pyproj-2.6.1.post1-cp37-cp37m-win_amd64.whl (17.2 MB) Requirement already satisfied: pandas&...
<p>For me this installation worked (even without Anaconda). Get the GDAL package from <a href="https://www.lfd.uci.edu/%7Egohlke/pythonlibs/#gdal" rel="nofollow noreferrer">here (Gohlke)</a></p> <p>Install it with <code>pip install GDAL_..._.whl</code></p> <p>Upon installing the same error will occur, but no problem! G...
python|python-3.x|conda|geopandas
0
15,031
46,636,849
pandas .boxplot properties not working
<p>I am trying to customise a boxplot created from a dataframe, using <code>whiskerprops</code>, <code>capprops</code>, <code>medianprops</code> but the parameters I set are not working. </p> <p>e.g.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df=pd.DataFrame(index = [x for x in range(0,10)]) ...
<p>Instead of calling out each property and trying to change the color, just use the <code>color</code> parameter and change the colors of each property there:</p> <pre><code>test = df.plot.box(color = {'whiskers' : 'black', 'caps' : 'black', 'medians' : 'black',...
python|pandas|parameters|styles|boxplot
3
15,032
47,034,287
Conditional Sum of 2D Numpy Arrays
<p>I have 4 (but in reality an arbitrary amount of) 2D arrays like so:</p> <pre><code>import numpy as np c1 = np.ones((75, 100)) c2 = np.ones((75, 100)) c3 = np.ones((75, 100)) c4 = np.ones((75, 100)) c1[22:42, 5:35] = np.random.rand(20, 30) / 2 c2[25:45, 25:55] = np.random.rand(20, 30) / 2 c3[28:48, 45:75] = np.ran...
<p>Here's a recursive method that I think fits your requirements:</p> <pre><code>def condsum(*arrs, r = 1): if len(arrs) == 1: return arrs[0] else: a = condsum(*arrs[1:], r = r) return np.where(a == r, arrs[0], a) </code></pre> <p>Then you'd just need to do</p> <pre><code>plt.imshow(c...
python|numpy
1
15,033
38,779,262
Random Forest handle negation
<p>I'm using Random Forest to apply a sentiment to a string. So basically after cleaning the reviews, which essentially means that stop words (<code>nltk.corpus -&gt; stopwords</code> from where I remove words as <em>no, not, nor, won, wasn, weren</em>) are removed, as well as non-letter characters, and everything is p...
<p>I believe this question is better suited for the Cross Validated stack exchange, but anyhow.</p> <p>There are several things that might improve your results:</p> <ol> <li><p>For sentiment analysis it doesn't feel right to remove negation stopwords like 'no', 'not', etc. since they can change totally the positive/n...
python|scikit-learn|random-forest|sklearn-pandas
2
15,034
38,956,089
Spike centered on zero in fast Fourier transform
<p>I have time associated data that I would like to perform a Fourier transform on. Data is located at <a href="http://pastebin.com/2i0UGJW9" rel="nofollow">http://pastebin.com/2i0UGJW9</a>. The problem is that the data is not uniformly spaced. To solve this, I attempted to interpolate the data and then perform the Fas...
<p>As I don't have enough reputation to post a comment, I'll post my suggestions as an answer and hope one of them does lead to answer.</p> <h2>Interpolation</h2> <p>It's probably wiser to interpolate onto a grid that is quite a bit finer than what you are doing. Otherwise your interpolation will smooth the noisy dat...
python|numpy|scipy|fft
6
15,035
38,825,562
time in strings format: python
<p>I am using a function to bring my date consistent in a column, it goes like this</p> <pre><code>from dateutil.parser import parse def dateconv1(x): c = parse(x) return c </code></pre> <p>so if i will use it as, it works fine </p> <pre><code>In[15]:dateconv1("1 / 22 / 2016 15:03") Out[15]:datetime.datetime(...
<p>assuming that <a href="https://stackoverflow.com/questions/38825562/time-in-strings-format-python/38826094#comment65017630_38825656">you are talking about pandas dataset</a>, you can use pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer">to_dateti...
python|string|datetime|pandas|dataframe
1
15,036
63,178,087
Error with tensorflow.js and reactjs only on mobile browsers
<p>I created an object detection model that I use on my react app and on desktop it works perfectly but when tried on mobile browsers getting the following error. Error: Requested texture size [4988x4989] greater than WebGL maximum on this browser / GPU [4096x4096].</p> <p><img src="https://i.stack.imgur.com/373R6.png"...
<p>There is not much you can do. This is the limitation of the browser and on the phone browser, the WebGL does not have much memory available.</p> <p>You can read more about this issue raised in <a href="https://github.com/tensorflow/tfjs/issues/689#issuecomment-503590183" rel="nofollow noreferrer">Tensorflowjs</a>.</...
reactjs|tensorflow|webgl|object-detection-api
0
15,037
63,145,173
Assigning values to new column based on multiple string conditions
<h3>What I have:</h3> <pre><code>| ID | Possible_Size | Actual_Size | |:------: |:------------------:|:-----------------:| | 1234 | BIG | BIG | | 5678 | MEDIUM | BIG | | 9876 | SMALL | SMALL | | 1092 | ...
<p>For this multiple if/elif statements you could use <code>np.select</code>:</p> <pre><code>choices = ['True Positive','False Negative','False Positive'] conditions = [ ((df['Actual_Size'].isin(['BIG']))&amp;(df['Possible_Size'].isin(['BIG']))), ((df['Actual_Size'].isin(['BIG']))&amp;(df['Possible_Size'...
python|pandas|function|dataframe|keyerror
1
15,038
31,883,134
How to make pandas python render with d3 and leaflet.js
<p>I'm a newbie desperately trying to develop a workflow between pandas in python and d3 to improve my visualisation skills. Can someone explain how to access columns of data in d3?</p> <p>My effort is: <a href="http://jsbin.com/pizakerove/edit?html,output" rel="nofollow">http://jsbin.com/pizakerove/edit?html,output</...
<p>I managed to fix it by using the 'orient' parameter of 'records' instead of 'index'.</p> <p>I then used this block <a href="http://bl.ocks.org/d3noob/9267535" rel="nofollow">http://bl.ocks.org/d3noob/9267535</a> to get a working map.</p>
python|d3.js|pandas|visualization
0
15,039
27,603,093
ValueError: Found array with dim 34644. Expected 80841
<p>I tried this tutorial to classify text within a new project: <a href="http://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html" rel="nofollow">http://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html</a> It helps us to automatically choose a suitable category for a...
<p>Found the problem, I had to reset the array inside the loop. It was just adding values to train_data.data so the number differed from train_data.target:</p> <p><code>train_data = Traindata() train_data.data = [] </code></p> <p>It expected train_data.target to have a length of 80841, cause train_data.data contained...
python|numpy
0
15,040
68,810,149
is it possible to use fnmatch.filter on a pandas dataframe instead of regex?
<p>I have a dataframe as below for example, i want to have only tests with certain regex to be part of my updated dataframe. I was wondering if there is a way to do it with fnmatch instead of regex?</p> <pre><code>data = {'part1':[0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1], 'part2':[0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1]...
<p>Import <code>fnmatch.filter</code> and filter on the index:</p> <pre><code>from fnmatch import filter In [7]: df.loc[filter(df.index, '*g*')] Out[7]: part1 part2 part3 part4 part5 part6 part7 part8 part9 part10 part11 part12 test_gt1 0 0 0 0 1 1 1 1 ...
python|pandas|dataframe|fnmatch
1
15,041
68,657,177
Recursively create a new Data Frame using for loop
<p>I have a below code which i wrote It creates a new data frame for different SerialNumber character length and at the end I append all the dataframe together to get the final Output.</p> <p>I am trying to find a better way writing this code. Can I do this using a for loop ?</p> <pre><code>data[&quot;Serial Number&quo...
<p>LOOP</p> <pre><code>data = {} i = 28 data1 = [] while i &lt;= 34: data[&quot;Serial Number&quot;] = data['Serial Number'].str.zfill(i) print(&quot;Fetch Serial Number with&quot; + i + &quot;characters&quot;) data[&quot;Output&quot;] = data['Serial Number'].apply(lambda x: fetch_by_ser_no(x)) data.to_...
python|pandas
0
15,042
68,480,108
Execute chain of functions in Python
<p>I am doing data pre-processing using Python and Pandas. For that reason, I wrote several functions for cleaning data, which should be executed one after another in sequence.</p> <p>I don't want to manually execute all functions every time I open Jupyter. So I am searching for something similar to a trigger, where I ...
<p>Write a driver function - lets call it <code>start()</code> and call all your data cleaning functions one after the other in this function.</p> <pre><code>def start(): data_cleaning_1() data_cleaning_2() data_cleaning_3() . . </code></pre> <p>Call the <code>start()</code> function.</p>
python|pandas|jupyter-notebook|data-analysis|data-processing
0
15,043
68,754,415
Import all csv files existing in a folder and group them based on their names?
<p>I have around 1000 csv files in a directory, each 4 of them have the same name with a different number at the end. For example:</p> <pre><code>ABC_0.csv ABC_1.csv ABC_2.csv ABC_3.csv ... DIJ_0.csv DIJ_1.csv DIJ_2.csv DIJ_3.csv </code></pre> <p>I can import them all and put each file in its own data frame, so I ...
<p>First off I want to say that my solution is only robust given the fact that there will always be 4 files that belong grouped together and there won't be missing anything. If you want to make it more robust filenameparsing should be used.</p> <p>As far as I understand the question you want to get the data from four c...
python|pandas|csv|import
1
15,044
68,678,727
Efficiently filter DataFrame by looking for NumPy array match in row
<p>Given</p> <pre><code>df = pd.DataFrame({'x': [np.array(['1', '2.3']), np.array(['30', '99'])]}, index=[pd.date_range('2020-01-01', '2020-01-02', freq='D')]) </code></pre> <p>I would like to filter for <code>np.array(['1', '2.3'])</code>. I can do</p> <pre><code>df[df['x'].apply(lambda x: np.array_e...
<p>You can rely on list comprehension for performance:</p> <pre><code>df[np.array([np.array_equal(x,np.array([1, 2.3])) for x in df['x'].values])] </code></pre> <p>Performance via <code>timeit</code>(on my system currently using 4gb ram) :</p> <pre><code>%timeit -n 2000 df[np.array([np.array_equal(x,np.array([1, 2.3]))...
pandas|numpy
1
15,045
36,250,068
Rolling mean is not shown on my graph
<p>I am running on python pandas, and cant figure out, why the rolling mean with window size of 40 is not shown along with a stock price graph of yahoo</p> <p>First I get the data(with passed dates):</p> <pre><code>def get_data(dates): """Read stock data (adjusted close) for given symbols from CSV files.""" df = pd.D...
<p>Please see if this helps you: </p> <pre><code>from pandas_datareader import data def get_rolling_mean(values, window): """Return rolling mean of given values, using specified window size.""" return values.rolling(center=False, window=window).mean() def get_rolling_std(values, window): """Return rolli...
python|pandas
1
15,046
36,653,266
Does TensorFlow allocate new memory for results when `Session.run` is called?
<p>In tensorflow, I can use <code>Session.run</code> to map my inputs to my outputs. Suppose I do:</p> <blockquote> <p>b = sess.run(B, {A:a})</p> </blockquote> <p>Is the tensor associated with <code>b</code> reallocated every time I make this call? Could I just store a pointer to <code>b</code> and expect it to be ...
<p>The result tensor is allocated each time you call <code>sess.run()</code>, as a NumPy array. There's no way in the current API to share storage between Python and the TensorFlow backend, but if you want to allocate storage once and update it, you might be able to use a <code>tf.Variable</code>:</p> <pre><code>A = ....
tensorflow
4
15,047
36,274,014
Combine Rows of Multiindex DataFrame into Comma Separated Lists
<p>Given a multi-index DataFrame, I would like to combine repeated index pairs and list their values as comma-separated lists. For example, the input:</p> <pre><code>df = pd.DataFrame({'Last Name' : ['Deere','Deere','Foo' ,'Foo' ,'Man' ], 'First Name': ['John' ,'Jane' ,'Kung' ,'Kung' ,'Karate'...
<p>You can first convert column <code>Value1</code> to <code>string</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>astype</code></a>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow...
python|pandas|dataframe|multi-index
3
15,048
36,633,059
Make a pandas series by running a function on all adjacent values
<p>I have a pandas series, s1, and I want to make a new series, s2, by applying a function that takes two inputs to create one new value. This function would be applied to a 2-value window on s1. The resulting series, s2, should have one fewer value than s1. There are many ways to accomplish this but I'm looking for a ...
<p>In response to your edit, we could try and use a similar .rolling method, but pandas does not currently support non-numeric types in rolls.</p> <p>So, we can use a list comprehension:</p> <pre><code>[music21.interval.Interval(music21.note.Note(s1[i]),\ music21.note.Note(s1[i + 1])).name\...
python|pandas|music21
1
15,049
36,585,243
Coloring only the inside of a shape
<p>Lets say that you are given this image</p> <p><a href="https://i.stack.imgur.com/JBYQp.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JBYQp.gif" alt="Circle"></a></p> <p>and are given the instruction to programmatically color only the inside of it the appropriate color, but the program would ha...
<p>You can use <a href="https://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.ndimage.measurements.label.html" rel="nofollow"><code>scipy.ndimage.measurements.label</code></a> to do all the heavy lifting for you:</p> <pre><code>import scipy.ndimage import scipy.misc data = scipy.misc.imread(...) assert da...
python|algorithm|numpy|machine-learning|computer-vision
1
15,050
65,507,362
opencv dnn module load tensorflow .pb file error
<p>I trained a mnist_fashion model with tensorflow2.4, and then used opencv to call the generated .pb file and the following error occurred.</p> <pre><code>Net net = readNetFromTensorflow(weightFile); </code></pre> <p>String field 'tensorflow.FunctionDef.Node.ret' contains invalid UTF-8 data when parsing a protocol buf...
<p>I found a solution, just convert saved_model.pb to frozen_graph.pb. [https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py][1]</p>
c++|tensorflow|opencv
0
15,051
65,788,700
Add new column in a dataframe based on a condition on the content of another column in the same dataframe
<pre><code>import requests from bs4 import BeautifulSoup import pandas as pd import re header = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-C...
<p>You can set column to another one by mask, similar like filtration, if no matching get missing values:</p> <pre><code>mask = df['links'].str.contains('financial|investors|investor|Investors|Investor|INVESTORS|INVESTOR|relations|relation|Relations|Relation|report|filings') df.loc[mask, 'segments'] = 'Finance' </code>...
python|pandas|dataframe
2
15,052
65,798,502
How to quickly cut slices from cuda tensor wrt to another tensors values
<p>I have a torch cuda tensor <code>A</code> of shape <code>(100, 80000, 4)</code>, and another cuda tensor <code>B</code> of shape <code>(1, 80000, 1)</code>. What I want to do, is for each element <code>i</code> in the second dimension (from <code>0</code> to <code>79999</code>), take the value of tensor <code>B</cod...
<p>Something similar to this can work if k = 1. (requires <code>torch&gt;1.7</code>)</p> <pre><code>a = torch.rand((10, 20, 4)) b = torch.randint(10, (20, 1)) b2 = torch.cat((b-1, b, b+1), dim=1) b2 = torch.minimum(9*torch.ones_like(b2), b2) b2 = torch.maximum(0*torch.ones_like(b2), b2) a[:, b2, :] </code></pre> <p>and...
python|python-3.x|numpy|pytorch
0
15,053
63,624,679
First-difference certain columns in generalised code
<pre><code>df fruit date price cost var1 0 apple 2017-01-01 2 2 20 1 apple 2017-01-02 3 3 40 2 banana 2017-01- 02 4 4 20 2 banana 2017-01-02 4 4 10 </code></pre> <p>Is the...
<p>IIUC, you can <code>set_index</code> the column you want to keep as it is and use <code>groupby.diff</code> on fruit, then <code>reset_index</code> to get the index back as columns.</p> <pre><code>df_ = (df.set_index(['fruit','date','var1']) .groupby(level='fruit').diff() .reset_index() ) pri...
python|python-3.x|pandas|list|dataframe
3
15,054
63,440,235
Using multiple images per data point in a binary classification CNN
<p>I'm making a CNN model to categorise MRI brain scans into Alzheimer's and Healthy groups.</p> <p>It currently seems as though it's overfitting, and we have tried a lot of tricks in the book to fix this issue.</p> <p>One method I'd now like to try - but have no experience in - is using multiple images of the brain sc...
<p>In order to incorporate multiple images in your model now, you can take your multiple images for each data point, the easiest thing would be to average them and you can try that. But, a better approach will be to apply dimensionality reduction on the multiple images.</p> <p>First, it will consolidate all the feature...
python|tensorflow|keras|deep-learning|conv-neural-network
0
15,055
24,596,207
Matplotlib line collection and additional line
<p>I have a line collection added to a plot</p> <p><a href="https://stackoverflow.com/a/24593105/1127601">https://stackoverflow.com/a/24593105/1127601</a></p> <p>How can I add a second line to such a plot with a secondary y-axis? I want to display more than just the line collection in the plot. The data is based on...
<p>These additional lines will do:</p> <pre><code>#df['another']=np.random.random(some_number) ax2=ax.twinx() ax2.bar(left=x, height=df.another, width=0.02) </code></pre> <p>Don't mix <code>pandas.plot</code> and <code>matplotlib</code> together when plotting time series, as they treat the date-time value differently...
python|matplotlib|plot|pandas
3
15,056
29,879,340
reshaping an arbitrary collection numpy arrays
<p>I have a relatively small number <em>k</em> of length <em>N</em> numpy arrays, where <em>k</em> is of order 10, and <em>N</em> is very large, of order 10^7. I am trying to create a single, two-dimensional <em>N</em> x <em>k</em> array that bundles this data in a specific way.</p> <p>For definiteness, here is a spec...
<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.column_stack.html" rel="nofollow"><code>column_stack</code></a>:</p> <pre><code>&gt;&gt;&gt; np.column_stack([x, y, z]) array([[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]) </code></pre> <p><a href="https://github....
python|arrays|performance|numpy|scientific-computing
3
15,057
30,067,183
selecting numpy array axis by int
<p>I am trying to access systematically a numpy array's axis. For example, suppose I have an array</p> <pre><code>a = np.random.random((10, 10, 10, 10, 10, 10, 10)) # choosing 7:9 from axis 2 b = a[:, :, 7:9, ...] # choosing 7:9 from axis 3 c = a[:, :, :, 7:9, ...] </code></pre> <p>Typing colons gets very repetitive...
<p>Sounds like you may be looking for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.take.html" rel="noreferrer">take</a>:</p> <pre><code>&gt;&gt;&gt; a = np.random.randint(0,100, (3,4,5)) &gt;&gt;&gt; a[:,1:3,:] array([[[61, 4, 89, 24, 86], [48, 75, 4, 27, 65]], [[57, 55, 55, 6,...
python|arrays|numpy|multidimensional-array
7
15,058
30,067,051
Python - What are the major improvement of Pandas over Numpy/Scipy
<p>I have been using numpy/scipy for data analysis. I recently started to learn Pandas. </p> <p>I have gone through a few tutorials and I am trying to understand what are the major improvement of Pandas over Numpy/Scipy. </p> <p>It seems to me that the key idea of Pandas is to wrap up different numpy arrays in a Data...
<p>Pandas is not particularly <em>revolutionary</em> and does use the NumPy and SciPy ecosystem to accomplish it's goals along with some key Cython code. It can be seen as a simpler API to the functionality with the addition of key utilities like joins and simpler group-by capability that are particularly useful for ...
python|numpy|pandas|scipy|data-analysis
14
15,059
53,635,522
pandas resample: forcing specific start time of time bars
<p>I have some time series <code>data</code> (<code>pandas.DataFrame</code>) and I resample it in <code>'600S'</code> bars:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np data.resample('600S', level='time').aggregate({'abc':np.sum}) </code></pre> <p>I get something like this:</p> <pre class="...
<p>You can add <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.floor.html" rel="nofollow noreferrer"><code>Series.dt.floor</code></a> to your code:</p> <pre><code>df.time = df.time.dt.floor('10 min') time abc 0 2018-12-05 09:30:00 19836 1 2018-12-05 09:40:00 8577 2...
python|pandas|dataframe|resampling
4
15,060
53,529,678
Pandas throws ParserError on one computer but not on another
<p>Here's the code I have, which works perfectly fine on my friend's computer: </p> <pre><code>#!/usr/bin/python import pandas as pd df = pd.read_csv("report.csv") df = df.drop("Agent Name", axis=1) df.to_csv("agent_report_updated.csv") </code></pre> <p>Here's the error I receive on mine: </p> <pre><code>Traceback...
<p>I believe this is a problem with encoding </p> <p>try this :</p> <pre><code>import pandas as pd df = pd.read_csv("report.csv",encoding='cp1252') df = df.drop("Agent Name", axis=1) df.to_csv("agent_report_updated.csv") </code></pre> <p>There are other encoding options you can try utf-8 instead of cp1252. <a href="...
python|python-3.x|pandas
0
15,061
53,461,728
Output a pandas dataframe to .XLSB (Excel Binary Workbook) format
<p>Is it possible to output a pandas dataframe with extension as <code>.XLSB</code> using <code>Python 3</code> (my version is 3.7.1)? These are huge files (1,000,000+ rows and 60+ columns). </p> <p>Any guidance on if at all this is possible would be greatly appreciated.</p>
<p>Support for xlsb is not available - <a href="https://github.com/pandas-dev/pandas/issues/8540" rel="nofollow noreferrer">https://github.com/pandas-dev/pandas/issues/8540</a> </p>
python|python-3.x|pandas
-1
15,062
53,646,319
Tensorflow Error: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables
<p>I'm facing a trouble with tensorFlow. Following codes is OK.</p> <p>from <strong>future</strong> import division, print_function, absolute_import</p> <pre><code>import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import tensorflow.contrib.slim as slim from tensorflow.contrib.layers.python.l...
<p>As the error already tells you, there is an operation (op) for wich tensorflow cannot compute a gradient. In your case, the op <code>tf.arg_max</code> is the problem. This function is not differentiable (i.e. no derivative exists and hence no gradient can be computed). Tensorflow can therfore not create gradients fo...
python|tensorflow
0
15,063
53,657,322
CSV file from txt using pandas
<p>I have a txt file with info inside of it, separated for every deal with \n symbol.</p> <pre><code>DEAL: 896 CITY: New York MARKET: Manhattan PRICE: $9,750,000 ASSET TYPE: Rental Building SF: 8,004 PPSF: $1,218 DATE: 11/01/2017 </code></pre> <p>Is there any way to make a csv (or another) table with headers, specifi...
<p>Updated to navigate around using <code>:</code> as a delimiter:</p> <pre><code>import pandas as pd new_temp = open('temp.txt', 'w') # writing data to a new file changing the first delimiter only with open('fun.txt') as f: for line in f: line = line.replace(':', '|', 1) # only replace first instance of :...
python|pandas|csv
1
15,064
53,374,005
python 3 ,ssh tunnel with sql query using panda not working
<p>I have a problem getting result from mysql database using ssh connection. The sql statement is correct but why dont i have any data in it ?</p> <pre><code>from sshtunnel import SSHTunnelForwarder import MySQLdb as db import pandas as pd from pandas import DataFrame # ssh variabler host = "192.168.99.101" localhos...
<p>I think you need to use the paramiko key in the ssh tunnel:</p> <pre><code>import paramiko localhost = &quot;127.0.0.1&quot; ssh_username = &quot;user&quot; ssh_password = &quot;password&quot; ssh_private_key = '/path/to/key.pem' pkey = paramiko.RSAKey.from_private_key_file(ssh_private_key, password=ssh_password) ...
python|mysql|pandas
0
15,065
53,582,799
Find how many random points lie inside ellipse centered at a point
<p>The below code generates set of random x,y coordinates and uses the equation of an ellipse to compare how many of those points lie inside ellipse centered at (1,1) and a rectangle of area 2a*2b constructed around the ellipse whose semimajor and semiminor axis are a and b but b is variable and takes a value from the ...
<p>If I understood your problem correctly, here's a vectorized solution.</p> <p>It creates a binary mask for points inside the ellipse, counts where the mask is <code>True</code> and divides it by the total number of points.</p> <pre><code># np.random.seed(42) N = 10000 x = np.random.uniform(0, 2, N) #generates rando...
python|list|loops|numpy
0
15,066
53,439,656
Create lists with 3 levels, containing every combination of sub list(s) values
<p>I am currently stuck with the following problem (I could not find solution already on here that really fitted this):</p> <p>I have three lists <code>a = [a, b, c]</code>, <code>b = [1, 2, 3]</code> and <code>c = [0.1, 0.2, 0.3]</code>.</p> <p>I would like to create a lists of list of lists (maybe I should be using...
<p>A generator seems a good approach, to avoid cluttering up the memory. </p> <pre><code>import itertools as it bc=list(it.product(b,c)) #[(1, 0.1), (1, 0.2), (1, 0.3), (2, 0.1), (2, 0.2), (2, 0.3), (3, 0.1), (3, 0.2), (3, 0.3)] res = ([[u,*v] for u,v in zip(a,bc3)] for bc3 in it.product(*[bc]*3)) </code></pre> <p>y...
python-3.x|python-2.7|list|numpy|itertools
1
15,067
17,575,357
How to average over a 2-D array?
<p>I have a 2-D numpy array of shape <code>(256,128)</code> and I would like to average every 8 rows of the 256 together so I end up with a numpy array of shape <code>(32,128)</code> Is there any way to average just the one dimension?</p>
<p>You can <code>reshape</code> and then average over an axis:</p> <pre><code> averaged = a.reshape((32,8,128)).mean(axis=1) </code></pre> <p>The result is an (32,128) array.</p>
python|arrays|numpy|multidimensional-array|indexing
6
15,068
15,910,019
Annotate data points while plotting from Pandas DataFrame
<p>I would like to annotate the data points with their values next to the points on the plot. The examples I found only deal with x and y as vectors. However, I would like to do this for a pandas DataFrame that contains multiple columns. </p> <pre><code>ax = plt.figure().add_subplot(1, 1, 1) df.plot(ax = ax) plt.show(...
<p>Here's a (very) slightly slicker version of <a href="https://stackoverflow.com/a/15911372/2071807">Dan Allan's answer</a>:</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd import numpy as np import string df = pd.DataFrame({'x':np.random.rand(10), 'y':np.random.rand(10)}, index...
matplotlib|pandas
57
15,069
72,039,680
Setting some 2d array labels to zero in python
<p>My goal is to set some labels in 2d array to zero without using a for loop. Is there a faster numpy way to do this without the for loop? The ideal scenario would be <code>temp_arr[labeled_im not in labels] = 0</code>, but it's not really working the way I'd like it to.</p> <pre><code>labeled_array = np.array([[1,2,3...
<p>You can use define <code>labels</code> as a set and use <code>temp_arr = np.where(np.isin(labeled_array, labels), labeled_array, 0)</code>. Although, the difference for such a small array does not seem to be significant.</p> <pre><code>import numpy as np import time labeled_array = np.array([[1,2,3], ...
python|numpy|label
0
15,070
72,030,775
How to use np.select but with multiples conditions?
<p>I have this kind of dataframe (only have 1.0 or 2.0) :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">column_1</th> <th style="text-align: center;">column_2</th> <th style="text-align: right;">column_3</th> </tr> </thead> <tbody> <tr> <td style="text-align: lef...
<p>You need to remove the <code>loc</code> part in your <code>sum_x</code> variable and <code>np.select</code> check condition in sequence, so you need to put stricter condition to front</p> <pre class="lang-py prettyprint-override"><code>sum_1 = (df.column_1 == 1.0) | (df.column_2 == 1.0) | (df.column_3 == 1.0) sum_2 ...
python|pandas|numpy
1
15,071
71,971,107
Modify pandas multiindex value for a particular group
<p>Assume I have a pandas MultiIndex DataFrame with three different levels:</p> <pre><code>arrays = [['2020-03-30', '2020-03-30', '2020-03-30', '2020-04-15', '2020-04-15', '2020-04-15', '2020-05-10', '2020-05-10', '2020-06-10'], ['Firm1', 'Firm1', 'Firm2', 'Firm1', 'Firm2', 'Firm2', 'Firm1', 'Firm1', 'Firm1'], ['2022-0...
<p>Here's one way using <code>set_index</code> and append a new index level with the required modifications. Also used <code>groupby.transform</code> to get the max dates:</p> <pre><code>max_dates = df.reset_index(level='Sell_date').groupby(level=[0,1])['Sell_date'].transform('max') df = df.set_index(df.index.get_level...
python|python-3.x|pandas|dataframe|multi-index
4
15,072
19,084,369
Iteratively find minimum values in sub-lists
<p>I need to find and store in a new list the minimum values in each sub-list of a main list. This is what I have so far:</p> <pre><code># Main list. list_a = [[0.2,0.4,0.6,1.1], [1.2,0.1,0.7,0.9], [0.3,0.5,0.9,0.7], [0.5,0.2,0.6,0.3]] # List that stores all the minimum values. list_b = [] # Iterate through all sub-...
<p>Just use a list comprehension and the <code>min</code> function</p> <pre><code>[min(x) for x in list_a] </code></pre>
python|performance|numpy
3
15,073
55,430,086
2d gaussian function does not produce correct results
<p>I would like to write a function that returns an <code>np.array</code> of size <code>nx</code> x <code>ny</code> that contains a centered gaussian distribution with mean <code>mu</code> and sd <code>sig</code>. The code below works in certain cases but in many not - what's wrong or what else should I write to get wh...
<p>There is a confusion with the mean in what you propose. In the 1D case, saying it is centered is exactly saying its mean is <code>0</code>. For a 2D gaussian there are so to speak two means, defined as the expectation of <code>x</code> and of <code>y</code>. Again saying it is centered is exactly saying they are bot...
python|numpy|gaussian
2
15,074
55,396,500
I am getting NaN when I subtract two pandas dataframe columns
<p>I have a dataframe with several columns, I want to get the difference in time between two of the columns containing time. To start I have converted the two columns to DateTime objects using pd.to_datetime, but when I subtract the two columns and assign the result to the new column ends up with NaN values.</p> <pre>...
<p>I think your problem is usage of <code>loc</code> when you are accessing just a column from the dataframe. You can eliminate the problem just by removing <code>loc</code> from the code.</p> <p>See the following toy example,</p> <pre><code>ops_data_clean_1 = pd.DataFrame() ops_data_clean_1['Package committed-time'...
pandas|datetime|dataframe
1
15,075
55,149,205
How do I change Index in a CSV file through pandas in python?
<p>I'm trying to Make "ID" as Index, it throws error mentioned below and image:</p> <p><a href="https://i.stack.imgur.com/HIt3x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HIt3x.png" alt="enter image description here"></a></p> <pre><code>obj= pd.read_csv("Supermarkets.csv") obj ID Address ...
<p>I think the problem is you have trailing spaces in the 'ID' column name. I reproduced your data but trimmed off any excess spaces on import. You'll notice how the column names are all right justified. Your ID column appears not to be, likely because there are trailing spaces in the name. This also appears to be true...
python|pandas|keyerror
2
15,076
55,257,039
How to integrate LIME with PyTorch?
<p>Using this mnist image classification model : </p> <pre><code>%reset -f import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms import torch.utils.data as data_utils import nu...
<p>Here's my solution:</p> <p>Lime expects an image input of type numpy. This is why you get the attribute error and a solution would be to convert the image (from Tensor) to numpy before passing it to the explainer object. Another solution would be to select a specific image with the <code>test_loader_subset</code> a...
pytorch
2
15,077
56,565,422
Perform multiple operations in a single groupby call with pandas?
<p>I'd like to produce a summary dataframe after grouping by date. I want to have a column that shows the mean of a given column as it is and the mean of that same column after filtering for instances that are greater than 0. I figured out how I can do this (below), but it requires doing two separate <code>groupby</cod...
<p>IIUC, you could use the following code:</p> <pre><code>&gt;&gt;&gt; data['avg_delay'] = data.pop('delay') &gt;&gt;&gt; data['avg_delay_pos'] = data.loc[data['avg_delay'].gt(0), 'avg_delay'] &gt;&gt;&gt; data day month year avg_delay avg_delay_pos 0 1 1 2013 0 NaN 1 1 2 2...
python|pandas|pandas-groupby
1
15,078
25,610,592
How to set dtypes by column in pandas DataFrame
<p>I want to bring some data into a pandas DataFrame and I want to assign dtypes for each column on import. I want to be able to do this for larger datasets with many different columns, but, as an example:</p> <pre><code>myarray = np.random.randint(0,5,size=(2,2)) mydf = pd.DataFrame(myarray,columns=['a','b'], dtype=...
<p>I just ran into this, and the pandas issue is still open, so I'm posting my workaround. Assuming <code>df</code> is my DataFrame and <code>dtype</code> is a dict mapping column names to types:</p> <pre><code>for k, v in dtype.items(): df[k] = df[k].astype(v) </code></pre> <p>(note: use <code>dtype.iteritems()<...
python|pandas|types
26
15,079
67,031,038
tensorflow/keras - does each layer run concurrently all the time?
<h1>Question</h1> <p>Does each layer in a Tensorflow/Keras sequential neural network (NN) work all the time? In a CPU, there are multiple pipeline stages and each stage keeps working and not waiting for the previous stage.</p> <p><a href="https://i.stack.imgur.com/giN7W.png" rel="nofollow noreferrer"><img src="https://...
<p>@mon<br /> Excellent question! AFAIK, TensorFlow doesn't execute layers separately. Once the model is compiled, the graph is executed all at once in CPU, without any parallel processing. In GPU environments, the parts of the graph which can be processed in parallel are in fact processed in parallel. The image that y...
tensorflow|keras
1
15,080
66,975,415
How to deal with images with decimal values before and after performing CNN?
<p>I am trying to perform CNN for regression using grayscale images with continues pixel value in float32 data types. The value ranges for predictors:</p> <pre><code>img1= 0 to 790.65 img2= -2.74174 to 2.4126 img3= 150.87 to 260.45 </code></pre> <p>The value range for response image:</p> <pre><code>resp_img= -32.927 to...
<p>not sure what you are trying to do. pixel values are normally in the range 0 to 255. Typically the pixel values are rescale between 0 and 1 using img=img/255 this produce floats. To convert back to range 0 to 255 as floats just do img=img * 255 or if you want an integer value img=int(img*255)</p>
python|tensorflow|conv-neural-network
0
15,081
66,882,207
length of np.cumsum(input) is longer than input array -- how is this possible?
<p>Running the below code in Colab. Have two separate instances running (separate files). In one instance the code works, in the other, it does not. In the case where it's not working, the funciton np.cumsum() appears to be returning an array twice as long as the input array, which is creating a ValueError: &quot;ope...
<p>Your array is likely multi-dimensional:</p> <pre><code>eye3 = np.eye(3) print(len(eye3)) # 3 (3 rows) print(len(np.cumsum(eye3))) # 9 (3 rows * 3 columns = 9 elements once flattened) print(len(np.cumsum(eye3, axis=1))) # 3 (3 rows) </code></pre>
python|numpy|cumsum
0
15,082
67,070,201
How to replace pandas plot xticks with days?
<p>I've got a pandas hist plot like shown below. As you can see the xticks are currently set to 0-6 (Sunday - Saturday). I'd like to replace the tick label to the actual days so the days are showing instead of numbers. 0 - Sunday 1 - Monday 2 - Tuesday 3 - Wednesday . .</p> <pre><code>ax_by_day = df['Day Of Week'].hist...
<p>Using one of the many useful features of <a href="https://docs.python.org/fr/3/library/calendar.html" rel="nofollow noreferrer"><code>calendar</code></a>:</p> <pre class="lang-py prettyprint-override"><code>import calendar days = calendar.day_name ax_by_day.set_xticklabels(days[6:] + days[:6]) </code></pre>
python|pandas|matplotlib|jupyter
3
15,083
67,121,461
CTypes: Numpy Array Always has Different Values
<p>I'm trying to get an array from CTypes but it always has diffirent values. Here is my simple code:</p> <p>C++:</p> <pre><code>struct OutArray { int array_len; float* array; }; extern &quot;C&quot; // required when using C++ compiler __declspec(dllexport) void getArray(OutArray *ret) { std::vector&...
<p>Listing <a href="https://docs.python.org/library/ctypes.html#module-ctypes" rel="nofollow noreferrer">[Python.Docs]: ctypes - A foreign function library for Python</a>.</p> <p>There are several issues with your code (as mentioned in the comments). <br>The main one is that you rely on the existence of an object when ...
python|c++|c|numpy|ctypes
1
15,084
47,091,529
Pyspark: sum error with SparseVector
<p>Suppose I have a <code>SparseVector</code> and I want to sum its values, e.g.</p> <pre><code>v = SparseVector(15557, [3, 40, 45, 103, 14356], np.ones(5)) v.values.sum() 5.0 </code></pre> <p>This works well. Now I want to do the same thing by means of a <code>udf</code>, because I have a <code>DataFrame</code> wit...
<p>This happens because <code>udf</code> doesn't support NumPy types as return type. </p> <pre><code>&gt;&gt;&gt; type(v.values.sum()) &lt;class 'numpy.float64'&gt; </code></pre> <p>You should cast the result to standard Python type:</p> <pre><code>df = spark.createDataFrame([(v, )], ["v"]) @udf("double") def sum_v...
python|numpy|apache-spark|pyspark|user-defined-functions
0
15,085
47,527,957
Pandas GroupBy - How to Keep Rows Up to Percentage of Cumulative Sum?
<p>I have a dataframe which is not ordered:</p> <pre><code>df A B Moves 0 E1 E2 10 1 E1 E3 20 2 E1 E4 15 3 E2 E1 9 4 E2 E3 8 5 E2 E4 7 6 E3 E1 30 7 E3 E2 32 8 E3 E4 40 9 E4 E1 5 10 E4 E2 20 11 E4 E3 3 </code></pre> <p>I wan...
<p>you can use <code>groupby.apply</code> with a custom function</p> <pre><code>def select(group, pct=50): # print(group) moves = group['Moves'].sort_values(ascending=False) cumsum = moves.cumsum() / moves.sum() # print(cumsum) # `cumsum` is the cumulative contribution of the sorted moves idx =...
python|pandas|group-by|sum|percentage
2
15,086
47,404,076
Structure of input and neural net to predict likelihood of multiple independent classes
<p>For the problem I'm solving, the following is true:</p> <ul> <li>I'm trying to predict the probabilities for the input belonging to each of 12 classes.</li> <li>It's possible that the input belongs to none of the 12 classes, which means all 12 outputs (probabilities) would be low.</li> <li>The output probabilities ...
<p>This is called multi-label classification, and it can be easily implemented by making two changes in the model:</p> <ul> <li>Use a sigmoid activation at the output</li> <li>Use the binary_crossentropy loss which can handle multi-label classification.</li> </ul> <p>And then just train your model.</p>
tensorflow|neural-network|keras|conv-neural-network|feature-selection
0
15,087
47,528,125
pivot_table values missing
<p><a href="https://i.stack.imgur.com/xebg8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xebg8.jpg" alt="enter image description here"></a></p> <p>I just simply reshape the <code>dataframe</code> as my wish. index is userid, and columns are subgameID, filled with rating as values. But all values ...
<p>Just for the record - if you only check 2 columns like that, why don't you use pd.crosstab?</p> <pre><code>pd.crosstab(ratings_data.userID, ratings_data.subgameId, margins=True) </code></pre> <p>If you need pivot_table, then try to add argument <code>fillna = 0</code>.</p> <p>You can also try to do it on small su...
python|pandas|pivot-table
0
15,088
47,273,577
Pull data from Tableau Server into Pandas Dataframe
<p>My goal is to join three datasources that are only available to me through Tableau Server (no direct database access). The data is too large to efficiently use Tableau's Data Blending.</p> <p>One way forward is to pull the data from the three Tableau Server Datasources into a Pandas dataframe, do the necessary mani...
<p>Tabcmd does not require admin privileges. Anyone with permissions to Server can use it, but it will respect the privileges you do have. You can install tabcmd on computers other than your server without needing extra license keys.</p> <p>That being said, it's very simple to automate data downloading. Take the URL t...
python|pandas|automation|tableau-api
2
15,089
47,188,012
How to build Tensorflow 1.4 with CUDNN 5.0?
<p> I'm trying to install Tensorflow 1.4 from sources with CUDA 8.0 and CUDNN 5.0.5, on Centos 7. It's indicated in the documentation that it should work with CUDNN 3 and higher. I'm working in a virtual env with Python 3.4.5, using Bazel 0.7.0, with GCC 4.9. During the configuration, I've set CUDNN version to 5.0.5 an...
<p>The problem was a bug in Tensorflow where they were indeed using CUDNN V6 functions in a V5 build. This is now fixed by applying <a href="https://github.com/tensorflow/tensorflow/pull/13255" rel="nofollow noreferrer">PR #12355</a> to the branch 1.4 (the PR is only applied to master). </p>
tensorflow|cudnn
1
15,090
47,121,397
Python 3.x pandas how to compare duplicates and drop the rows with the higher values in csv?
<p>Hi I'm new to python and currently using python version 3.x. I have a very large set of data needed to be filtered in csv. I searched online and many recommended loading it into pandas DataFrame (done).</p> <p>My columns can be defined as: "ID", "Name", "Time", "Token", "Text"</p> <p>I need to check under "Token" ...
<p>Use <code>sort_values</code> + <code>drop_duplicates</code>:</p> <pre><code>df = df.sort_values('Time')\ .drop_duplicates('Token', keep='first').sort_index() df ID Name Time Token Text 1 2 Mary 233 Hiiii xxxx 2 3 Jame 222 Hello xxxx </code></pre> <p>The final <code>sort_index</code> c...
python|pandas|csv|dataframe|duplicates
1
15,091
11,004,659
What is the difference between numpy "type identifiers" and "types" within Cython?
<p>What is confusing is that if you want to create an array you use </p> <pre><code>chunk = np.array ( [[94.,3.],[44.,4.]], dtype=np.float64) </code></pre> <p>But if you want to define the type inside a <code>buffer</code> reference , you use </p> <pre><code>cdef func1 (np.ndarray[np.float64_t, ndim=2] A): prin...
<p>in your cython code, you do:</p> <pre><code>import numpy as np cimport numpy as np </code></pre> <p>the first line import numpy module in python space, but the second line just include numpy.pxd in cython space.</p> <p>you can found numpy.pxd in you cython install folder. It define float64_t as:</p> <pre><code>c...
python|numpy|cython
7
15,092
68,122,491
Convert tensorflow 1 contrib to tensorflow 2 Keras version
<p>I was in the process of Migrating my code from tf1 to tf2 and I think I managed have to fix most of the issues for running it with tf2. But Got Stuck while migrating it to Tf2 compatible with tfa.seq2seq.LuongAttention and tfa.seq2seq.AttentionWrapper Already replaced contrib to v2 but not sure why its not working.<...
<p>Few of the libraries in Tensorflow 2.x are moved to some other repository like addons and operation.</p> <p>Replace <code>tf.contrib.rnn.DropoutWrapper</code> with <code>tf.compat.v1.nn.rnn_cell.DropoutWrapper</code> for more information about library find <a href="https://www.tensorflow.org/api_docs/python/tf/compa...
tensorflow|keras|tensorflow2.0|tensor
0
15,093
68,132,802
how to replace NAN with some other value in pandas (python)
<p>for example i want to replace 'NAN' with 'dog' and 'cat'. like from 1-30 'Nan' should be replaced with 'dog' and from 40-100 it should be replaced by 'cat'. how am i supposed to do it</p>
<p>Spilt your problem into smaller ones:</p> <p>How to select the data? 1-30, 40-100</p> <pre><code>dataframe.iloc[0:30] dataframe.iloc[30:100] </code></pre> <p>How to replace NaN?</p> <pre><code>dataframe.fillna('dog') </code></pre>
python|pandas
1
15,094
68,278,515
Pandas translating column of a dataframe with a lookup dataframe
<p>I have a dataframe that looks like:</p> <pre><code>df = pd.DataFrame({'ISIN': ['A1kT23', '4523', 'B333', '49O33'], 'Name': ['Example A', 'Name Xy', 'Example B', 'Test123'], 'Sector': ['Energy', 'Industrials', 'Utilities', 'Real Estate'], 'Country': ['UK', 'USA', 'Germany', 'China']}) </code></pre> <p>I would like t...
<p>This line will do the merge and DataFrame cleanup:</p> <pre class="lang-py prettyprint-override"><code>df.merge(Sector_EN_DE, left_on='Sector', right_on='Sector_EN').drop(['Sector', 'Sector_EN'], axis=1).rename(columns={'Sector_DE': 'Sector'}) </code></pre> <p>Explanation:</p> <ul> <li>The <code>merge</code> functio...
python|pandas|dataframe
0
15,095
68,131,178
Is there a possibility for a segmentation of a 3d-np.array (boolean variables)
<p>I have a 3D-numpy-array which is exclusively filled with boolean variables (True/False). Is there a possibility or library that implements a segmentation of all entries with &quot;True&quot; in the N6 neighbourhood? In my research, I unfortunately only found something for image processing with openCV.</p> <p>The goa...
<p>Seems common for me to answer my own questions:</p> <p>Following library is necessary:</p> <p><a href="https://pypi.org/project/connected-components-3d/#description" rel="nofollow noreferrer">connected-components-3d</a></p> <p>My Code:</p> <pre><code>import cc3d connectivity = 6 #18, 26 labels_out = cc3d.connected_c...
python|numpy|3d|boolean|image-segmentation
0
15,096
1,025,379
Decimal alignment formatting in Python
<p>This <em>should</em> be easy.</p> <p>Here's my array (rather, a method of generating representative test arrays):</p> <pre><code>&gt;&gt;&gt; ri = numpy.random.randint &gt;&gt;&gt; ri2 = lambda x: ''.join(ri(0,9,x).astype('S')) &gt;&gt;&gt; a = array([float(ri2(x)+ '.' + ri2(y)) for x,y in ri(1,10,(10,2))]) &gt;&g...
<p>Sorry, but after thorough investigation I can't find any way to perform the task you require without a minimum of post-processing (to strip off the trailing zeros you don't want to see); something like:</p> <pre><code>import re ut0 = re.compile(r'(\d)0+$') thelist = [ut0.sub(r'\1', "%12f" % x) for x in a] print '...
python|formatting|numpy|code-golf
10
15,097
59,186,114
How to train only front part of a neural network?
<p>I'm using pytorch to train part of the network. For example, I have a model structure</p> <pre><code>hidden1 = Layer1(x) hidden2 = Layer2(hidden1) out = Layer3(hidden2) </code></pre> <p>If I want to train Layer3 only, I can use</p> <pre><code>hidden1 = Layer1(x) hidden2 = Layer2(hidden1).detach() out = Layer3(hid...
<p><code>detach</code> will not really "freeze" your layer.<br> If you don't want to train a layer, you should use <code>requires_grad=False</code> instead.</p> <p>For example:<br></p> <pre><code>hidden2.weight.requires_grad = False hidden2.bias.requires_grad = False </code></pre> <p>Then to unfreeze, you do the sam...
neural-network|pytorch
1
15,098
59,460,404
Convolutional layer after embedding layer shapes problem in Keras
<p>I want to train a model that has 3 input channels. Every channel starts with embedding (as lambda) and a convolution next. However, I can't deal with shapes.</p> <pre class="lang-py prettyprint-override"><code># Build network def swish(x): return K.sigmoid(x) * x def make_model(): embed_size = 512 #must be...
<p>This is a common misunderstanding when using the <code>Conv1D</code> layers in Keras. According to the <a href="https://keras.io/layers/convolutional/" rel="nofollow noreferrer">documentation</a>, the expected <code>input_shape</code> is <code>(batch, steps, channels)</code>.</p> <p>In general for 10 rows with 20 f...
python|tensorflow|keras
0
15,099
59,426,593
Replace a string containing parentheses with a float in pandas
<p>I have a dataset with a column of strings which I want to convert to floats. However the column has a single entry containing a number within parentheses (which means to be a negative number). I tried different ways --indirect and direct-- to replace the value with a representation that would enable me to convert ...
<p>Use <code>rstrip</code> for remove last <code>)</code>, then replace <code>(</code> and last convert to floats:</p> <pre><code>df = pd.DataFrame({'Amount': ['(29.29)', '(39.39)', '12.5', '340']}) df['Amount'] = df['Amount'].str.strip(')').str.replace('\(', '-').astype(float) print (df) Amount 0 -29.29 1 -39.39...
regex|python-3.x|pandas|replace
3