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,600
54,265,374
tensorflow ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients
<p>I got an error on tensorflow. The code is like this: <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>from sklearn import datasets import random import tensorflow as tf wine=da...
<p>You got this problem because the arguments you passed into <code>tf.nn.softmax_cross_entropy_with_logits</code> are not what it wants. From the <a href="https://www.tensorflow.org/api_docs/python/tf/nn/softmax_cross_entropy_with_logits" rel="nofollow noreferrer">doc of tf.nn.softmax_cross_entropy_with_logits</a>:</p...
python|tensorflow
0
15,601
54,426,725
Getting size error in opencv while working on MNIST dataset
<p>I am training an MLP using OpenCV and ML modules. I am getting an unknown error that i m not able to fix it:</p> <blockquote> <p>"error: OpenCV(3.4.3) /io/opencv/modules/ml/src/data.cpp:257: error: (-215:Assertion failed) samples.type() == CV_32F || samples.type() == CV_32S in function 'setData'"</p> </blockq...
<p>The images need to be 1D vectors, but they are being put in with shape [28,28]. For example, this will reshape the images and will work:</p> <pre><code>mlp.train(X_train_pre.reshape(60000,-1), cv2.ml.ROW_SAMPLE, y_train_pre) </code></pre>
python|opencv|tensorflow|machine-learning|keras
1
15,602
54,599,633
Selecting a subset of a dataframe with each variable having N years worth of data
<p>I have a dataset showing yearly growth indicators for more than a 100 countries, from the year 1970 until 2013. Not all the countries have data for all the years, the country with the least years having 30 years of data. I want to level things out and have all countries show me 30 years of data, removing years from ...
<p>You can create a list of recent years from the unique values in year column and use Boolean indexing to index dataframe using that list.</p> <pre><code>recent_years = df.Year.unique()[-3:] df[df.Year.isin(recent_years)] Country Year Value 3 Israel 2001 2.8 4 Denmark 2001 1.1 5 Israel 2002 2...
python|pandas|dataframe
3
15,603
54,689,096
How to install Keras with gpu support?
<p>I installed Tensorflow for GPU using: <code>pip install tensorflow-gpu</code> But when I tried the same for <strong>Keras</strong> <code>pip install keras-gpu</code>, it pulled me an error: <em>could not find the version that satisfies the requirements</em>.</p>
<p>Adding to the answer below which is the correct answer in terms of recommending to use Anaconda package manager, but out of date in that <strong>there is</strong> now a <em>keras-gpu</em> package on <a href="https://anaconda.org/anaconda/keras-gpu" rel="nofollow noreferrer">Anaconda Cloud</a>.</p> <p>So once you hav...
tensorflow|keras|pip|anaconda|gpu
27
15,604
73,813,527
Pandas dataframe with identical date, add seconds to differentiate the rows
<p>I have a pandas dataframe as following:</p> <pre><code>Date time LifeTime1 LifeTime2 LifeTime3 LifeTime4 LifeTime5 2020-02-11 17:30:00 6 7 NaN NaN 3 2020-02-11 17:30:00 NaN NaN 3 3 NaN 2020-02-12 15:30:00 2 2 ...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>groupby.cumcount</code></a> combined with <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>pandas.to_datetime</cod...
python|pandas|dataframe
1
15,605
73,720,138
How do I export a timedelta operation result to Excel?
<p>So, I have a column with a start date, and one with a closed date. I want the difference between them so I use:</p> <pre><code>`df1['Time Resolved'] = abs(df['Closed Datetime']-df['Start Datetime'])` </code></pre> <p>Then I would like the median value from the Time Resolved column, so I use:</p> <pre><code>`time_re...
<p>It looks like you're getting an error because the <code>to_excel()</code> function is meant to be called on a DataFrame, not a TimeDelta.</p> <p>You could create a very basic DataFrame and write it:</p> <pre><code>df2 = pd.DataFrame({'result': [df1['Time Resolved'].median()]}) df2.to_excel(writer, sheet_name=&quot;1...
python|excel|pandas|timedelta
0
15,606
73,738,504
How to label-encode comma separated text in a Dataframe column in Python?
<p>I have dataframe(df) that looks like something like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Shape</th> <th style="text-align: left;">Weight</th> <th style="text-align: left;">Colour</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">Cir...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;Colour&quot;] = df[&quot;Colour&quot;].str.split(r&quot;\s*,\s*&quot;, regex=True) x = df.explode(&quot;Colour&quot;) df_out = ( pd.concat( [df.set_index(&quot;Shape&quot;), pd.crosstab(x[&quot;Shape&quot;], x[&quot;Colour&quot;])], axis=...
python|pandas|dataframe|csv|encode
3
15,607
73,579,333
How to check pair of string values in a column, after grouping the dataframe using ID column?
<p><a href="https://i.stack.imgur.com/i4kXc.png" rel="nofollow noreferrer">My Doubt in a Table/Dataframe view</a>I have a dataframe containing 2 columns: ID and Code.</p> <pre><code>ID Code Flag 1 A 0 1 C 1 1 B 1 2 A 0 2 B 1 3 A 0 4 C 0 </code></pre> <p>Within each ID, if Code 'A' exists wit...
<p>You can do the following:</p> <p>First use <code>pd.groupby('ID')</code> and concatenate the codes using <code>'sum'</code> to create a new column. Then assing the value <code>1</code> if a row contains <code>A</code> or <code>B</code> as <code>Code</code> and when the new column contains an <code>A</code>:</p> <pre...
pandas|filter|group-by|series
0
15,608
52,132,599
pandas apply list of function to data frame
<p>Lets take boston data set available in the <code>from sklearn.datasets import load_boston</code></p> <pre><code>boston = load_boston() X = pd.DataFrame(boston["data"]) 0 1 2 3 4 5 6 7 8 9 10 11 12 0 0.00632 18.0 2.31 0.0 0.538 6.575 65.2...
<p>In the latest version of <code>pandas</code>, <code>df.agg</code> should be able to do exactly this.</p> <p>Unfortunately it appears to be broken for the current version when <code>axis=1</code>: <a href="https://github.com/pandas-dev/pandas/issues/16679" rel="nofollow noreferrer">https://github.com/pandas-dev/pand...
python|pandas|dataframe|scikit-learn
2
15,609
60,687,490
Running training the discriminator with more examples
<p>As I understand what of the diff between regular GAN to WGAN is that we train the discriminator/critic with more examples in each epoch. If in the regular gan we have in each epoch one batch for both modules, in WGAN we will have 5 batches (or more) for the discriminator and one for the generator.</p> <p>So basicall...
<p>Yes, it does sound reasonable typically <strong>increasing batch_size</strong> during training, typically decreases the training time with a cost of using <strong>more memory</strong> and <strong>lower accuracy</strong> <em>(lower generalization ability)</em>. </p> <p>Having said this you should do always do trial ...
tensorflow|keras|generative-adversarial-network
2
15,610
60,470,501
Filling in null values in one column based on aggregate of a different column
<p>I'm learning some basic data science, and I am working on the titanic dataset. The 'Age' column has null values which I'd like to fill with the average of a different column, say 'Pclass' or 'Sex'. </p> <p>'Pclass' refers to Passenger Class and has three values (1,2,3) based on the whether the passenger had a 1st, ...
<p>You shouldn't call the function inside <code>apply</code>, instead pass the function and the arguments via <code>args=()</code> or keyword arguments:</p> <pre><code>df['Age'] = df.apply(fill_age, col1='Age', col2='Pclass', axis=1) </code></pre> <p>But there's a better way to do this, via vectorization:</p> <pre><...
python|pandas
2
15,611
60,375,100
Columns Not Assigned Properly in Pandas (Python)
<p>I have a dataset in a .csv file, which I am trying to extract and name its columns. I use the following code: </p> <pre><code>data_name = 'housing.csv' column_names = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', ...
<p>It looks like your text data is separated by spaces instead of commas.</p> <p>You can try to explicitly tell <code>read_csv</code> to use one or more spaces as the field delimiter:</p> <pre><code>data = pd.read_csv(data_name, names=column_names, error_bad_lines=False, header=None, sep='\s+') </cod...
python|pandas|dataframe
0
15,612
72,696,017
PIL Image library load and save changing pixel values
<p>I am currently working on an Image segmentation problem. As part of preprocessing, I'm trying to create mask values for 2 classes [0, 1]. <br>While, saving the processed tensor and loading them back produces different mask values.<br> My current guess is under the hood PIL normalizing pixel values. <br> If so how do...
<p>For this simple case (only 2 classes), you need to work with <code>png</code> and not <code>jpeg</code> since <code>jpeg</code> is a lossy compression and <code>png</code> is lossless.</p> <pre class="lang-py prettyprint-override"><code>tensor_img = torch.where(torch.Tensor(250,250,3) &gt; 0, 1, 0) img_arr = tensor_...
pytorch|computer-vision|python-imaging-library|image-segmentation|fast-ai
1
15,613
59,483,878
pandas_profiling taking way too long to run
<p>If anyone experimented with <a href="https://github.com/pandas-profiling/pandas-profiling" rel="nofollow noreferrer">pandas-profiling package</a>, help me with any insights you might have with making it run faster. The output report from the package is very neat and detailed, but creating the report takes way too lo...
<p>Depending on what you are interested in, you can disable other functionalities of pandas-profiling that consume most time, because it is modular. This is currently your go-to solution in speeding up, together with sampling your dataset.</p> <p>There are several related issues here:</p> <ul> <li><a href="https://gi...
pandas|pandas-profiling
4
15,614
61,710,633
Plot data from dataframe to understand much better it - Pandas, matplotlib
<p>I'm using <code>pandas</code> with some data like the following,</p> <pre><code> User Code Group Task Type Time 0 u00 G00 1D 3.378195 1 u00 G00 1D 3.032764 2 u00 G00 1D 3.391991 3 u00 G00 2D 4.035652 4 u00 ...
<p>Your <code>groupby</code> operation works fine. The reason for <code>Time</code> being one row above the other labels is that the <code>groupby</code> has created a structure called a <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html" rel="nofollow noreferrer">MultiIndex</a>. I suppose t...
python|pandas|matplotlib
1
15,615
61,617,952
slider.value values not getting updated using ColumnDataSource(Dataframe).data
<p>I have been working on COVID19 analysis for a <a href="https://covid19analysis.live" rel="nofollow noreferrer">dashboard</a> and am using a JSON data source. I have converted the json to dataframe. I am working on plotting bar chart for "Days to reach deaths" over a "States" x-axis (categorical values). I am trying...
<p>Your code has 2 issues</p> <ul> <li>(critical) <code>source.data</code> must be a dictionary, but you're assigning it an array</li> <li>(minor) <code>from_df</code> is a class method, you don't have to construct an object of it</li> </ul> <p>Try using <code>source.data = ColumnDataSource.from_df(days_death_count)<...
python-3.x|bokeh|pandas-bokeh
0
15,616
61,669,632
Given a 3D image array, return a list of indices with a value above a threshold and a minimum distance between all selected indices?
<p>I have a 3D numpy array that represents a 3D image and I want to create a list from it with all the (x,y,z) coordinates/index tuples that are both above a certain value, and within a certain distance from other coordinates also above that certain value. So if coords (3,4,5) and (3,3,3) were both above the value, but...
<p>You can replace your threshold checking with:</p> <p>import numpy as np</p> <pre><code>arr = np.argwhere(original_array&gt; threshold) </code></pre> <p>The rest depends on your <code>arr</code> size and data type(please provide image size and dtype to assist better). If the number of points above the threshold is...
python|numpy
0
15,617
57,909,596
Custom loss in keras produces misleading outputs during training of an autoencoder
<p>I have rank-3 tensors of size (100,100,4) that I try to compress and reconstruct with an autoencoder. I use a physically motivated loss function. Mathematically it is</p> <p>L = - overlap(y_true,y_pred) + |1 - norm(y_pred)^2|</p> <p>In code it reads:</p> <pre class="lang-py prettyprint-override"><code>def physica...
<p>I think I figured it out, the problem is that keras/tensorflow is expecting an already vectorized function. The above definition is intended for rank-3 tensors, but keras/tensorflow is always dealing with batches, so "lists" of rank-3 tensors that are not actually lists but rank-4 tensors (first dimension is the "li...
python|tensorflow|machine-learning|keras|deep-learning
0
15,618
54,907,933
Pandas GroupBy and Calculate Z-Score
<p>So I have a dataframe that looks like this:</p> <pre><code>pd.DataFrame([[1, 10, 14], [1, 12, 14], [1, 20, 12], [1, 25, 12], [2, 18, 12], [2, 30, 14], [2, 4, 12], [2, 10, 14]], columns = ['A', 'B', 'C']) A B C 0 1 10 14 1 1 12 14 2 1 20 12 3 1 25 12 4 2 18 12 5 2 30 14 6 2 ...
<p>Do with <code>transform</code></p> <pre><code>Mean=test.groupby(['A', 'C']).B.transform('mean') Std=test.groupby(['A', 'C']).B.transform('std') </code></pre> <p>Then</p> <pre><code>(test.B - Mean) / Std </code></pre> <hr /> <p>One function <code>zscore</code> from <code>scipy</code></p> <pre><code>from scipy.sta...
python|pandas
12
15,619
49,455,722
Sums of points per date grouped by additional column in a form of a list
<p>I would like to obtain sum of points of some technologies per date from pandas data frame. A reproducible example:</p> <pre><code>data = pd.DataFrame( {'date': ['2017-01-31', '2017-02-28', '2017-02-28'], 'tech': [['c++', 'python'], ['c++', 'c', 'java'], ['java']], 'score': [1, 4, 2]} ...
<p>We can convert your original data to this format </p> <pre><code>s=data.tech.str.len() newdf=pd.DataFrame({'date':data.date.repeat(s),'score':data.score.repeat(s),'tech':np.concatenate(data.tech.values)}) newdf Out[477]: date score tech 0 2017-01-31 1 c++ 0 2017-01-31 1 python 1 2017...
python|pandas|list|pivot-table
4
15,620
49,390,950
Python Pandas -- mapping the values in two data frames
<p>I have two dataframes <code>df1</code> and <code>df2</code>. </p> <p>I am trying to figure out the best way to perform a mapping that for each row in <code>df1</code>, I would like to search for a match (<code>id</code>, <code>time_by_hour</code>) in <code>df2</code> and then fill the corresponding value in <code>d...
<p>You can look at <code>merge</code></p> <pre><code>df1['value']=df1[['time_by_hour','id']].merge(df2,how='left').value </code></pre>
python|pandas|merge|mapping|vectorization
6
15,621
73,237,898
Numerical instabilities when bounding GPFlow hyperparameters
<p>in <a href="https://stackoverflow.com/questions/59504125/bounding-hyperparameter-optimization-with-tensorflow-bijector-chain-in-gpflow-2">Bounding hyperparameter optimization with Tensorflow bijector chain in GPflow 2.0</a>, I found an excellent explanation of how to set boundaries to my hyperparameters.</p> <p>Unfo...
<p>Another way to constrain a parameter in GPflow is to place a prior on it. For example:</p> <pre class="lang-py prettyprint-override"><code>k = gpflow.kernels.Matern32() k.variance.prior = tfp.distributions.Gamma(to_default_float(2), to_default_float(3)) </code></pre> <p>See more <a href="https://gpflow.github.io/GPf...
tensorflow|tensorflow-probability|gpflow
0
15,622
73,250,835
Exception: URL fetch failure on https://www.manythings.org/anki/ita-eng.zip: 406 -- Not Acceptable
<p>I am trying to run a seq2seq model in google colab but when I try to load the dataset with the following command:</p> <pre><code>def download_NMT(): path_to_zip = tf.keras.utils.get_file( fname='ita-eng.zip', origin='https://www.manythings.org/anki/ita-eng.zip', extract=True) path_to_file = os.path.dirn...
<p>Sometimes this happens when, on server side is checked whether you're a bot, or not. The server tries to get from which browser you’re making the request, and since you are not on any browser (even though you’re on google Colab, you’re making the request from python), it gives you the 406 error.</p> <p>Usually, in o...
python|tensorflow|dataset
1
15,623
73,512,302
Cannot append list with condition
<p>im trying to export two lists to an excel file using pandas, but i cannot append my data using this method.</p> <pre><code>product_list1 = [&quot;apple&quot;, &quot;pear&quot;, &quot;oragne&quot;, &quot;melon&quot;] product_list2 = [&quot;bread&quot;, &quot;sugar&quot;, &quot;flour&quot;, &quot;salt&quot;] list_code...
<p>The <em>input</em> function returns a string.<br /> You first need to cast the result into a number before checking if the choice is contained in the range.</p> <pre class="lang-py prettyprint-override"><code>def quantity_check(list_type, list_number): choise = input(&quot;Quantity:&quot;) try: choi...
python|pandas|list|append
1
15,624
67,318,510
Pandas remove common prefix or suffixes of column names
<p>When importing data from a financial system, the columns have this unnecessary common prefix. This prefix changes from table to table.</p> <p><strong>Question</strong>: How can I automatically find the common prefix and remove it from my column names, keeping in mind that this prefix changes?</p> <p><strong>Example<...
<h3>Using <a href="https://docs.python.org/3/library/os.path.html#os.path.commonprefix" rel="nofollow noreferrer"><code>os.path.commonprefix</code></a> with <a href="https://docs.python.org/3/library/os.path.html#os.path.commonprefix" rel="nofollow noreferrer"><code>Series.str.replace</code></a></h3> <p>We can use <cod...
python|pandas
3
15,625
60,232,334
PyTorch tensor indexing or conditional selection?
<pre><code> for c in range(self.n_class): target[c][label == c] = 1 </code></pre> <p>self.n_class is 32. and target is 32 x 1024 x 2048 tensor.</p> <p>I know that target[c] select the each one of 1 x 1024 x 2048. But I don't understand [label == c].</p> <p>Because by thumb of rule, an integer should go i...
<p>PyTorch supports "Advanced Indexing." It implements the ability to accept a tensor argument to the <code>[]</code> operator.</p> <p>The result of the <code>==</code> operator is a boolean mask. The <code>[]</code> operator is using that mask to select elements. This example below might help clarify:</p> <pre><code...
python|pytorch
3
15,626
60,034,688
How can I drop repeating values in a column while keeping the data for its rows?
<p>I have a dataframe that has column of repeating values/indexes and I want to group it by the 'Name' column but without performing any aggregation to it. I've looked at the <code>Dataframe.groupby()</code> function but from what I've searched, you are kind of forced to perform an aggregation. I've also tried <code>Da...
<p>If want replace duplicated values to empty strings use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.duplicated.html" rel="nofollow noreferrer"><code>Series.duplicated</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mask.html" rel="n...
python|pandas|dataframe|multi-index
3
15,627
60,013,192
Can I display a pandas data frame over a range of index values (multiple rows)?
<p>A way to display a table including the first row of a data frame (index = 0) and all columns is the following:</p> <pre><code> some_variable = df.loc[0, :] </code></pre> <p>Is there a way to so this same thing over multiple index values (displaying a range of rows)?</p>
<p>If I understand correctly, you want to print some top rows. </p> <ol> <li>If you want top n rows</li> </ol> <pre><code> print(df.head(n)) </code></pre> <ol start="2"> <li>If you want to print a set of rows.</li> </ol> <pre><code> print(df.loc[[id1,id2,id3],:]) </code></pre>
python-3.x|pandas|dataframe
3
15,628
65,160,040
Performing regression while dividing sample
<p>Let's take data</p> <pre><code>import pandas as pd import numpy as np from sklearn.model_selection import StratifiedKFold from sklearn.linear_model import LogisticRegression df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data', header=None) </code></pre> <p>...
<p>X is a DataFrame so you need to use <code>.iloc</code> to select the indices:</p> <pre><code>for train_index, validation_index in kfold.split(X, y): # Fit the model X_train = X.iloc[train_index] y_train = y[train_index] clf.fit(X_train, y_train) </code></pre>
python|pandas|numpy|scikit-learn
1
15,629
65,142,275
The index on the time dimension must be either numeric or date-like error
<p>I am trying to do a panel regression with</p> <pre><code>from linearmodels.panel import PooledOLS import statsmodels.api as sm </code></pre> <p>but I encountered a problem with my index. For the regression I need a Multiindex, so I have a Dummy variable and the time (see below). The two indicies are a_c ( a dummy va...
<p>The time dimension index in the example provided looks like a string. Converting it to a date format or a numerical format should work.</p> <p>Also note that the entity index comes first in order and the time dimension is second in the multi-index, like the example provided has correctly done.</p> <p>A small oversig...
python|pandas|jupyter-notebook|regression|linearmodels
1
15,630
65,257,158
Cumulative sum in Python without the current row
<p>I need to find the cumulative sum of the 3 previous rows without calculate the current one, here a short example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>SUM</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>10</td> </tr> <tr> <td>B</td> <td>5</td> </tr> <tr> <td>B</td>...
<p>You can try:</p> <pre><code>df['SUM'] = (df.groupby('ID')['SUM'] .transform(lambda x: x.rolling(4,min_periods=1).sum()) .sub(df['SUM']) ) </code></pre> <p>Output:</p> <pre><code> ID SUM 0 A 0 1 B 0 2 B 5 3 B 9 4 B 10 5 C 0 6 C 1 </code></pre>
python|pandas|dataframe|rolling-computation
1
15,631
65,290,820
Cannot create a numpy array using numpy's `full()` method and a python list
<p>I can create a numpy array from a python list as follows:</p> <pre><code>&gt;&gt;&gt; a = [1,2,3] &gt;&gt;&gt; b = np.array(a).reshape(3,1) &gt;&gt;&gt; print(b) [[1] [2] [3]] </code></pre> <p>However, I don't know what causes error in the following code:</p> <p>Code :</p> <pre><code>&gt;&gt;&gt; a = [1,2,3] &gt;&...
<p>Numpy is unable to broadcast the two shapes together because your list is interpreted as a 'row vector' (<code>np.array(a).shape = (3,)</code>) while you are asking for a 'column vector' (shape = <code>(3, 1)</code>). If you are set on using <code>np.full</code>, then you can shape your list as a column vector init...
python-3.x|numpy
1
15,632
65,470,008
Example for Tensorflow prediction with more than one independent variable
<p>I am searching for an example to predict data with Tensorflow. I already tried some codes but I am a beginner in Tensorflow and Python. For example I predict a stock price by training and testing with old stock prices. Now I would like to integrate more than only the old stock prices, like trade volume, to predict f...
<p>Your question is very broad, so it's hard to give specific advice. If you're a beginner in python, I would not recommend Tensorflow as the place to start. I would assume that if you're using historical prices to predict future prices, then you're trying to make predictions as a time series? I'd recommend you chec...
python|tensorflow|linear-regression|tensorflow2.0|prediction
2
15,633
63,003,363
Trying to implement basic subtraction function between two rows of dataframe based on the months of datetime
<p>I'm trying to find the average monthly gap between stock closing and opening prices which are in dataframe.<br /> The basic function looks like this</p> <pre><code>for i in range(1,len(df)): #difference between today's opening price minus yesterday's closing price gap+=(df['Open'][i]-df['Close'][i-1]) </cod...
<p>You will want to create a month column in your <code>DataFrame</code> to group by. Then, write a function which calculates the average gap.</p> <h3>Gap Calculation</h3> <p>You are adding up lots of differences as follows:</p> <pre><code> df['Open'][1]-df['Close'][0] +df['Open'][2]-df['Close'][1] +df['Open'][3]-df['C...
python|pandas|dataframe
1
15,634
63,184,571
pytables and pandas string padding question
<p>I've created a dataset using hdf5cpp library with a fixed size string (requirement). However when loading with pytables or pandas the strings are always represented like:</p> <p>b'test\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff</p> <p>The string value of 'test' with the padding after it. Does anyone know a way to suppr...
<p>I can't help with your C Code. It is possible to work with padded strings in Pytables. I can read data written by a C application that creates a struct array of mixed types, including padded strings. (Note: there was an issue related to copying a NumPy struct array with padding. It was fixed in 3.5.0. Read this for...
python|pandas|hdf5|pytables
0
15,635
63,133,592
Calculate Quantiles on Groupby Dataframe and add value back to DF
<p>What I'm looking to do is group my Dataframe on a Categorical column, compute quantiles using second column, and store the result in a 3rd column. For simplicity lets just do the P50. Example below:</p> <p>Original DF:</p> <pre><code>Col1 Col2 A 2 B 4 C 2 A 6 B 12 C ...
<p>You can do <code>transform</code> with <code>quantile</code></p> <pre><code>df['Col3_P50'] = df.groupby(&quot;Col1&quot;)['Col2'].transform('quantile',0.5) print(df) </code></pre> <hr /> <pre><code> Col1 Col2 Col3_P50 0 A 2 4 1 B 4 8 2 C 2 6 3 A 6 4 4 ...
python|pandas|dataframe
1
15,636
63,080,317
Pandas add Mean column header
<p>I'm trying to add column header for a mean column. Refer to below Mean for each column in df :</p> <pre><code> A B C 0 5 3 8 1 5 3 9 2 8 4 9 df.mean() A 6.000000 B 3.333333 C 8.666667 dtype: float64 </code></pre> <p>What I want to achieve is below output:</p> <pre><code> Mean ...
<p>You can <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.rename.html" rel="nofollow noreferrer">rename the series </a>and use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.to_frame.html" rel="nofollow noreferrer"><code>series.to_frame()</code></a><...
python-3.x|pandas
4
15,637
67,700,221
Combine two tables based on certain criteria using python
<p>I have two tables (table1, table2) of the following:</p> <p>table1:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Filename</th> </tr> </thead> <tbody> <tr> <td>12345</td> <td>12345.txt</td> </tr> <tr> <td>12346</td> <td>12346.txt</td> </tr> <tr> <td>12347</td> <td>12347.txt...
<p>You can make a temporary column <code>Filename</code> on <code>df2</code> by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>.assign()</code></a> and use the resulting copy of <code>df2</code> with newly added column to merge with <cod...
python|pandas|path|filenames
0
15,638
61,277,282
pandas: import multiple csv from subfolders if the name contains specific text
<p>I have a folder located at <code>C:\Users\Documents\folder</code> and inside that folder there are 500 randomly named subfolders. Each subfolders has multiple csv files. I want to <strong>import csv files if only their name contain word <code>client</code></strong> from those subfolders and concatenate the imported ...
<p>I think this should do it:</p> <pre><code>import os import pandas as pd source_dir = r'C:\Users\Documents\folder' my_list = [] for root, dirnames, filenames in os.walk(source_dir): for f in filenames: if 'client' in f: my_list.append(pd.read_csv(os.path.join(root, f))) concatted_df = p...
python|pandas|import|python-import
2
15,639
61,298,571
Wrong P_value given by ttest_1samp
<p>Here is a one sample t-test example:</p> <pre><code>from scipy.stats import ttest_1samp import numpy as np ages = [32., 34., 29., 29., 22., 39., 38., 37.,38, 36, 30, 26, 22, 22.] ages_mean = np.mean(ages) ages_std = np.std(ages, ddof=1) print(ages_mean) print(ages_std) ttest, pval = ttest_1samp(ages, 30) print("tt...
<p>If you check the vignette of ttest_1samp, it writes:</p> <p><a href="https://i.stack.imgur.com/eedeJm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eedeJm.png" alt="enter image description here"></a></p> <p>So it's a two-sided p-value, meaning what the sum of probabilities of getting a absolut...
python|numpy|scipy|statistics|hypothesis-test
2
15,640
61,444,409
Convert a Pandas Column to Hours and Minutes
<p>I have one field in a Pandas DataFrame that is in integer format. How do I convert to a DateTime format and append the column to my DataFrame?. Specifically, I need hours and minutes.<br> Example:</p> <ul> <li><strong>DataFrame Name:</strong> df</li> <li><strong>The column as a list:</strong> df.index</li> <li><st...
<p>You have an index that has time values as HHMM represented by an integer. In order to convert this to a datetime dtype, you have to first make strings that can be correctly converted by the <code>to_datetime()</code> method.</p> <pre class="lang-py prettyprint-override"><code>time_strs = df.index.astype(str).str.zf...
python|pandas|datetime
2
15,641
61,520,734
Sorting 2D array by the first n rows
<p>How can I sort an array in NumPy by the two first rows?</p> <p>For example,</p> <pre><code>A=array([[9, 2, 2], [4, 5, 6], [7, 0, 5]]) </code></pre> <p>And I'd like to sort columns by the first two rows, such that I get back:</p> <pre><code>A=array([[2, 2, 9], [5, 6, 4], [0, 5,...
<p>One approach is to transform the 2D array over which we want to take the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="nofollow noreferrer"><code>argsort</code></a> into an easier to handle 1D array. For that one idea could be to multiply the rows to take into accounts for th...
python|arrays|list|numpy|sorting
3
15,642
68,518,393
Embedding: argument indices must be a Tensor, not a list
<p>I am trying to train a RNN, but I am having trouble with my embedding. I am getting the following error message:</p> <pre><code>TypeError: embedding(): argument 'indices' (position 2) must be Tensor, not list </code></pre> <p>The code in the forward method starts like that:</p> <pre><code>def forward(self, word_indi...
<p>You're passing in a <em>list</em> to <code>self.embedding_word</code>: <code>word_indices</code>, not the tensor you just created for that purpose <code>word_ind_tensor</code>.</p>
python-3.x|pytorch|embedding
1
15,643
68,508,314
LSTM output just a variation of input data
<p>I'm building a LSTM and I want to predict <code>s_max</code> with variable <code>q_max</code> but the network just seem to alter the input data and give that as an output. I've tried increasing hidden size and epochs but was not successful. I assume there's a problem in the way I've structured the data or the way th...
<p>After speaking to my project supervisor, there are a couple of things I hadn't thought about. First of all, the forward pass returns <code>h_out</code> instead of the predicted value <code>ula</code>. Secondly, my function <code>def sliding_windows(data, seq_length):</code> is a &quot;many to one&quot; network while...
python|machine-learning|pytorch|lstm
0
15,644
53,272,519
Custom C++ extension : torch/torch.h not found
<p>I am following <a href="https://pytorch.org/tutorials/advanced/cpp_extension.html" rel="nofollow noreferrer">this tutorial</a> to create a C++ extension for Pytorch. My C++ code is giving following error :</p> <pre><code>test.cpp:3:10: fatal error: torch/torch.h: No such file or directory #include &lt;torch/torch....
<p>You most likely need to install the c++ version of torch. </p> <p>If you head over to www.pytorch.org they will guide you to which download is appropriate for you. Just make sure to select the c++ version. </p> <p>Hopefully that works! </p>
python|deep-learning|pytorch
0
15,645
53,098,800
what does it mean when weights of a layer is not normally distributed
<p>I plot all my weights of my neural network on tensorboard, I found that some </p> <p>weights of some layer is normally distributed:</p> <p><a href="https://i.stack.imgur.com/TcmJy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TcmJy.png" alt="enter image description here"></a></p> <p>but, some...
<p>one explanation base on convolutional networks might be this(I don't know if this is true for any other kind of artificial neural models or not), hence the first layer tries to find distinct small features weights are distributed very widely and network tries to find any useful feature it can, then in the next layer...
tensorflow|neural-network|deep-learning
0
15,646
52,961,627
How to prepare an array for an LSTM?
<p>The input array has 4 columns: the first 3 are real numbers between -1 and 1 and the 4th is the desired output that can be either -1 or 0 or +1 (this is a classification problem, -1 and 1 represent useful categories and 0 means the sample doesn't fall to any of them). Obviously the network type is chosen to be LSTM ...
<p>if you're using Keras and have access to a GPU I'd recommend using a <code>CuDNNLSTM</code> instead of a regular LSTM for faster training. Back to your question though.</p> <p>The LSTM requires a 3D input so here's a quick example to get you started. Let's say you have the following two columns of tabular data:</p>...
python|tensorflow|keras|lstm
0
15,647
65,714,757
how to pad a string tensor to a target length in tensorflow
<pre><code>t = 'comcom.android.systemuicom.android.systemuicom.android.systemui' def pad_trunc_shingle(t): shingle_max = 300 actual_len = tf.strings.length(t).numpy() if actual_len &gt; shingle_max: return tf.strings.substr(t, 0, shingle_max) else: return tf.strings.join(('#' * (shingle_...
<p>You can use <code>tf.cond</code> and <code>tf.py_function</code>. This works but there's definitely an easier way than what I did.</p> <pre><code>import tensorflow as tf def joining(word, shin_max, act_len): return tf.strings.join([*tf.repeat('#', shin_max - act_len), word]) def substr(word, shin_max): re...
python|tensorflow|tensorflow2.0|tensorflow-datasets
-1
15,648
65,722,516
Keras for N-tuple Network (sparse input)
<p>I'm trying to train N-tuple Network using keras. N-tuple network is just sparse array of one-hot activated patterns. Imagine chess board with 64 squares, each square containing possible N types of pieces, so there will be always of 64 activated ones, for 64*N possible parameters, and stored as 2d array [64][N]. Or e...
<p>You could use, <a href="https://www.tensorflow.org/api_docs/python/tf/sparse/SparseTensor" rel="nofollow noreferrer">tf.sparse.SparseTensor(...</a>), then set <code>sparse=True</code>, for <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Input#arguments" rel="nofollow noreferrer">tf.keras.Input(...)</a>....
python|tensorflow|machine-learning|keras|sparse-matrix
1
15,649
55,477,626
Resampling gap between Datetime filling with previous values (multi-index)
<p>I am trying to correct every row that there is no date. Then idea is just to fill the gap between the missing dates, and complete the other columns with the previous values.</p> <pre><code> ds SKU Estoque leadtime 0 2018-01-02 504777 45 11 1 2018-01-04 504777 42 11 2 2018-01-05 50477...
<p>In your case you may need to chain with <code>apply</code> </p> <pre><code>#df.set_index('ds', inplace=True) df.groupby('SKU').apply(lambda x : x.resample('D').ffill()).reset_index(level=0,drop=True) </code></pre>
python|pandas
1
15,650
56,543,373
How to compare two rows and when they are different then create another dataframe to copy these two rows
<p>Check column ['esn'] from df1. When any different found between two rows, produce another dataframe, df2. df2 only contains the before change and after change information</p> <pre><code>&gt;&gt;&gt; df1 = pd.DataFrame([[2014,1],[2015,1],[2016,1],[2017,2],[2018,2]],columns=['year','esn']) &gt;&gt;&gt; df1 year e...
<p>Create boolena mask by compare shifted values by <code>ne</code> for not equal and replace first missing value by <code>backfill</code>, similar compare shifted with <code>-1</code> with forward filling missing values - chain by <code>|</code> for <code>bitwise OR</code> and filter by <a href="http://pandas.pydata.o...
python|pandas|dataframe
1
15,651
56,813,691
How to append value_counts() output to the original df?
<p>So I have the following <code>df</code>:</p> <pre><code> Open High Low Close 0 0.001268 0.001277 0.001266 0.001271 1 0.001268 0.001269 0.001265 0.001266 2 0.001265 0.001265 0.001242 0.001254 3 0.001253 0.001271 0.001244 0.001251 4 0.001253 0.001259 0.0...
<p>Use <code>map</code>:</p> <pre><code>df['Open_count'] = df['Open'].map(df['Open'].value_counts()) </code></pre> <p>Output:</p> <pre><code> Open High Low Close Open_count 0 0.001268 0.001277 0.001266 0.001271 2 1 0.001268 0.001269 0.001265 0.001266 2 2 0.001265 0...
python|pandas|dataframe|count
2
15,652
56,456,148
Is it possible to train a neural network with "splited" output
<p><strong>Is it possible to consider the output of one neural network as two or more sets of outputs ?</strong></p> <p>I explain myself a bit more (in a q learning context):</p> <blockquote> <p>Imagine i have two agents in the same environement and each agents have a different amount of performable actions. Bot...
<p>I don't know about this specifically for reinforcement learning, but multi-output neural networks are very common in the literature. </p> <p>If you want a single network to control both agents, it's probably a good idea to share the early stages of the network, before separating the network in two distinct branches...
tensorflow|neural-network|reinforcement-learning|q-learning
1
15,653
67,096,294
Array of 1-dimensional array and array row yields different results
<p>I am having difficulty to understand why neither B or C equals A. How can I extract a specific row from f and calculate the same result as in <code>A</code>?</p> <pre><code>import numpy as np L = np.array([ [2.66667,1.33333], [0.8,1.6] ]) f = np.array([[0.5,0.333333]]) A = L*f.T B = L*f[0,:] C = L*f[...
<pre><code>L = np.array([ [2.66667,1.33333], [0.8,1.6] ]) f = np.array([[0.5,0.333333]]) </code></pre> <p><code>L</code> is (2,2), <code>f</code> is (1,2). <code>f.T</code> is (2,1)</p> <pre><code>A = L*f.T </code></pre> <p>This broadcasts the (2,2) with (2,1), replicating the the <code>f.T</code> columns...
numpy
1
15,654
67,057,945
How to return new array with deleted values python
<p>I try to get new array without the 2's from first array, of course it is possible with many ways, but I'm looking for fewer coding and smarter solution, this array as example..:</p> <pre><code>somearray = np.array( [4, 5, 2, 8, 4, 7, 2, 64, 2, 57, 2, 45, 7, 43, 2, 5, 7, 3, 3, 6523, 3, 4, 3, 0, -65, -343]) #so create...
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.argwhere.html" rel="nofollow noreferrer"><code>argwhere()</code></a> method for finding indices of 2 in your array:</p> <pre><code>indices=np.argwhere(somearray==2) </code></pre> <p>Now Finally make use of <a href="https://numpy.org/doc/stab...
python|arrays|python-3.x|numpy
1
15,655
67,175,240
How to prevent Scikit-Learn Imputer from removing NaN rows?
<p>One of my projects is using the scikit-learn imputer to handle NaN values, however, it seems to remove rows that are entirely made up of NaN as the following snippet shows:</p> <pre><code>tmp = [[math.nan, 3.0],[math.nan, 5.0],[math.nan, math.nan]] imp = SimpleImputer(missing_values=np.nan, strategy='mean') imp_tmp...
<p>As explained in the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html#sklearn.impute.SimpleImputer" rel="nofollow noreferrer">documentation</a>, the columns containing only missing values are discarded unless <code>strategy='constant'</code>:</p> <blockquote> <p>Columns whi...
python|numpy|scikit-learn|imputation
2
15,656
47,423,529
Floating point inconsistencies when converting a NumPy array to a list
<p>I have an interval range generated by python numpy. The values are as expected but when the array is transform into list, the values are not same as in array.</p> <pre><code>numpy.linspace(0.3,0.7,5) array([ 0.3, 0.4, 0.5, 0.6, 0.7]) numpy.linspace(0.3,0.7,5).tolist() [0.3, 0.39999999999999997, 0.5, 0.6, 0.7] ...
<p>It happens to be because of the datatypes and the corresponding <code>__repr__</code> implementations of each type:</p> <pre><code>l = numpy.linspace(0.3,0.7,5).tolist() [type(x) for x in l] [float, float, float, float, float] </code></pre> <p>In the first case, <code>tolist</code> converts each <code>np.float</...
python|arrays|list|numpy|floating-point
4
15,657
59,104,229
TypeError for datetime object, when shifting DataFrame
<p>I am using pandas shift function to calculate returns for a dataset of prices. My index are the corresponding dates. For some reason, I get a TypeError, when shifting the dataset (second row of the code mentioned below):</p> <pre><code>TypeError: unsupported operand type(s) for /: 'float' and 'datetime.datetime' </...
<p>The main problem here was, that excel converted some parts of my .csv from numbers to strings, that then got converted into datetime objects by pandas. I had to manually fix this in my .csv file.</p>
python|pandas|numpy|datetime
0
15,658
57,197,890
Pandas/Numpy: Using multiple conditional statements with Numpy where and transform
<p>In Python 3, I'm trying to create an indicator column which indicates if two conditions hold for each contract in the data. </p> <p>(1) If all the outstanding_balance's in for the contract are == 0, then the contract is <strong>Invalid</strong></p> <p>(2) If the contract_maturity_date is earlier than the minimum d...
<p>I think you need apply here:</p> <pre><code>s=df.groupby('contract_no').apply(lambda x:x.contract_maturity_date.lt(x.date_report_created) &amp;(x.outstanding_balance.sum()==0)).reset_index(drop=True) df['valid_contract_flag']=np.where(s,'Invalid','Valid') </code></pre> <hr> <pre><code>array(['Invalid', 'Invalid',...
r|python-3.x|pandas|numpy|pandas-groupby
2
15,659
50,943,414
update a dataframe at indices returned by query
<p>I would like to have query return a view so that I can modify fields without generating this error.</p> <blockquote> <p>SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead</p> <p>See the caveats in the documen...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="nofollow noreferrer"><code>pd.DataFrame.query</code></a> is designed for querying, not setting values. If you want to use string queries as masks, you can calculate the index and feed into <a href="https://pandas.pydata...
python|pandas|dataframe
1
15,660
66,469,372
Addin through a numpy array using indexes Python
<p>I am trying to write a numpy function where it will add portions of the sequences of <code>indexes</code> value if the last element in the index if not equal to the <code>len(Numbers)</code>. So the length of <code>Numbers</code>is 14 and the last index value within <code>indexes</code> is 11, so since 11 is lower t...
<p>here it is:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np numbers = np.array([1, 5, 6, 7, 4, 3, 6, 7, 11, 3, 4, 6, 2, 20]) indexes = np.array([0, 3, 7, 11]) while numbers.shape[0] &gt; indexes[-1]: diff = (numbers.shape[0] - indexes[-1]) + indexes[-1] indexes = np.append(indexes, ...
python|arrays|function|numpy|iterator
0
15,661
66,431,595
quantization vector with numpy/pytorch
<p>I have created quantized values as: <code>{0.0, 0.5, 1.0}</code> and would like to do quantization for a vector based on the set. For instance, given vector <code>[0.1, 0.1, 0.9, 0.8, 0.6, 0.6]</code> would be transferred into <code>[0.0, 0.0, 1.0, 1.0, 0.5, 0.5]</code>.</p> <p>Please guide me fastest way using pyth...
<p>use <a href="https://docs.python.org/3/tutorial/controlflow.html?highlight=lambda#lambda-expressions" rel="nofollow noreferrer"><code>map()</code></a> and <a href="https://docs.python.org/3/tutorial/controlflow.html?highlight=lambda#lambda-expressions" rel="nofollow noreferrer"><code>lambda()</code></a></p> <p>you c...
python|numpy|pytorch|quantization
2
15,662
66,541,380
Perform operation on columns based on values of another columns in pandas
<p>I have a dataframe</p> <pre><code>df = pd.DataFrame([[&quot;A&quot;,1,98,88,&quot;&quot;,567,453,545,656,323,756], [&quot;B&quot;,1,99,&quot;&quot;,&quot;&quot;,231,232,234,943,474,345], [&quot;C&quot;,1,97,67,23,543,458,456,876,935,876], [&quot;B&quot;,1,&quot;&quot;,79,84,895,237,678,452,545,453], [&quot;A&quot;,1...
<p>Let us try with <strong>boolean masking</strong>:</p> <pre><code># select the columns c = pd.Index(['col1', 'col2', 'col3']) # create boolean mask m = df[c].eq('').to_numpy() # mask the values in `_num` and `_deno` like columns df[c + '_num'] = df[c + '_num'].mask(m, '') df[c + '_deno'] = df[c + '_deno'].mask(m, '...
python|python-3.x|pandas|python-2.7|dataframe
3
15,663
66,642,881
Pandas How to replace all rows in certain columns without affecting the others?
<p>I have a master Dataframe (df_a) with columns a-b-c-d-e. I have a second Dataframe (df_b) with new info that updates the values in columns a-b-c.</p> <p>Minimal reproducible code:</p> <pre><code>df_a = pd.DataFrame(data={ 'a': [1, 0, 0, 0, 0, 0], 'b': [2, 0, 0, 0, 0, 0], 'c': [3, 0, 0, 0, 0, 0], 'd'...
<p>A generic solution would look like :</p> <p>Either find the difference of columns from <code>df_a</code> and <code>df_b</code> then assign them to <code>df_b</code></p> <pre><code>df_b.assign(**df_a.loc[:,df_a.columns.difference(df_b.columns,sort=False)]) </code></pre> <p>Or another way:</p> <pre><code>df_b.combine...
python|pandas
4
15,664
66,529,091
Get most frequent words in list for each row
<p>I have a dataframe <code>df</code> with 50,000+ rows:</p> <pre><code>&gt;&gt;&gt; df message words wordCount uniqueWordCount 0 my name is [my, name, is] 3 3 1 happy birthday to you [happy, birthday, to, you] ...
<p>Use custom lambda function with <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow noreferrer"><code>collections.Counter</code></a>:</p> <pre><code>from collections import Counter f = lambda x: [word for word, word_count in Counter(x).most_common(3)] df[&quot;mostFrequent&...
python|python-3.x|pandas|dataframe
2
15,665
51,371,374
how to sort complex structured data with numpy?
<p>I have a file whose lines consist of 2 integers and one float. I read the file with numpy:</p> <pre class="lang-html prettyprint-override"><code>dt = np.dtype([('pre', np.dtype('i4'), 2),('data', np.float64, 1)]) a = np.fromfile("myfile", dtype=dt) </code></pre> <p><div class="snippet" data-lang="js" data-hide="...
<p>You have a 1d structured array:</p> <pre><code>In [56]: arr = np.array([([65536, 65536], 0.2 ), ([65536, 1], 1.3356 ...: 6434), ...: ([65536, 2], 2.06068931), ([65535, 479], 0.33333333), ...: ([65535, 2295], 0.09090909), ([65535, 249], 0.07692308)], ...: dtype=...
python|numpy
1
15,666
51,520,746
reshape pandas dataframe column with delimiter
<p>I have the following dataframe (tab file with 2 columns-str) :</p> <pre><code>id1 id2 g1 ID:05434 g1 ID:05434 g1 NaN g1 ID:05434|ID:38720|ID:33345 </code></pre> <p>After doing</p> <pre><code>df1 = df[df['id2'].notnull()] df2 = df1.drop_duplicates(['id1','id2']) </code></pre> <p>I got df2, </p> <pre><c...
<p>Use<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>str.split</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a>, also for remove <code...
python|pandas
2
15,667
70,901,855
Get Hour and Minutes and Seconds from numpy Datetime64
<p>In this question (<a href="https://stackoverflow.com/questions/13648774/get-year-month-or-day-from-numpy-datetime64">Get year, month or day from numpy datetime64</a>) an example on how to get year, month and day from a numpy datetime64 can be found.</p> <p>One of the answers uses:</p> <pre><code>dates = np.arange(np...
<p>In your example, the type of the array is <code>np.datetime64[D]</code> so the hours/minutes/seconds are not stored in the items. However, the <code>np.datetime64[s]</code> does this.</p> <p>Here is how to extract the information from a <code>np.datetime64[s]</code>-typed array:</p> <pre><code># dates = array(['2009...
python|numpy
1
15,668
51,959,670
how to set env if python,pandas are installed in local dir
<p>If python,numpy,pandas are installed in local dir,how to set env ,so that ,import numpy as np,import pandas as pd can work.</p>
<p>If you install in a virtualenv, then activating the virtualenv will take care of that for you. Otherwise, add the dir to your PYTHONPATH environment variable. (How this is done depends on your operating system.)</p>
python|pandas
0
15,669
51,674,782
Numpy : 3D to 2D
<p>I have a matrix of shape <code>[2000, 140, 190]</code>. Here, 2000 is the number of 2D slices where each slice is of [140, 190].</p> <p>I want to convert this 3D matrix into <code>[7000, 7600]</code> (Hint : <code>140*50 = 7000</code>; <code>190*40 = 7600</code>; <code>50*40 = 2000</code>). I want to expand the mat...
<p>It sounds like you want a transpose in there too:</p> <pre><code>m_3d = np.random.rand(2000, 140, 190) # break the 2000 dimension in two. Pick one: m_4d = m_3d.reshape((50, 40, 140, 190)) # move the dimensions to collapse to be adjacent # you might need to tweak this - you haven't given enough information to know...
python|python-3.x|python-2.7|numpy|numpy-ndarray
1
15,670
51,666,374
How to remove strings present in a list from a column in pandas
<p>I have a dataframe <code>df</code>, </p> <pre><code>import pandas as pd df = pd.DataFrame( { "ID": [1, 2, 3, 4, 5], "name": [ "Hello Kitty", "Hello Puppy", "It is an Helloexample", "for stackoverflow", "Hello World", ], } )...
<p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="noreferrer"><code>str.replace</code></a> if want remove also substrings:</p> <pre><code>df['name'] = df['name'].str.replace('|'.join(To_remove_lst), '') </code></pre> <p>If possible some regex character...
python|string|pandas
17
15,671
37,418,556
pandas get numpy ndarray using series.values
<p>I want to convert a <code>series</code> to <code>numpy.ndarray</code>, so that using <code>ndarray</code> can lead to great time efficientcy improvement, </p> <pre><code>numpy_martix = df[some_col].values </code></pre> <p>I found that <code>series.values</code> itself took a bit of time to do the conversion, so I ...
<p>(<strong>Edited</strong>)</p> <p>When you call <code>arr = df.values</code>, a reference to <code>df</code> data is returned, so it's very fast (no real job done). On the other hand, <code>arr = df[list_of_cols].values</code> requires some consolidation inside <code>df</code> first.</p> <p>Try running it this way:...
python-3.x|numpy|pandas|series
2
15,672
41,830,605
Pandas plot DataFrame rolling mean gives weird result
<p>If I have a DataFrame built as </p> <pre><code>df = pd.DataFrame({'a': [i for i in range(10)], 'b': [2*i for i in range(10)]}) </code></pre> <p>so that its plot of 'b' against 'a' (obtained via <code>df.plot('a', 'b')</code>) is simply a straight line, and I compute the running mean of it as <...
<p>Use the following code:</p> <pre><code>import pandas as pd df = pd.DataFrame({'a': [i for i in range(10)], 'b': [2*i for i in range(10)]}) rm_df = df.rolling(window=2).mean().plot( kind='line', x='a',y='b', use_index=False) </code></pre> <p><br/>Setting <code>use_index</code> to fa...
python|pandas|plot|dataframe
1
15,673
37,979,785
Counting match between two arrays at same index position and having non zero values
<p>I have two arrays as below:</p> <pre><code>b = array([[1, 0, 1], [0, 0, 1]]) c = array([[ 0.5 , 0. ], [ 0.34, 1. ], [ 0. , 1. ]]) </code></pre> <p>How to count matching values of two arrays based on same index value AND the element value of the array should non zero. Here ...
<p>Your critical problem is checking that the "non-zero" values are equal: you need an <strong>and</strong> here, not <strong>==</strong>:</p> <pre><code> sum += np.sum((b[x,:]!=0) &amp; (c[:,x]!=0)) </code></pre> <p>This yields the desired result of <strong>2</strong>.</p> <pre><code>import numpy as np b = np.a...
python|numpy
1
15,674
37,747,021
Create Numpy array of images
<p>I have some (950) 150x150x3 .jpg image files that I want to read into an Numpy array. </p> <p>Following is my code:</p> <pre><code>X_data = [] files = glob.glob ("*.jpg") for myFile in files: image = cv2.imread (myFile) X_data.append (image) print('X_data shape:', np.array(X_data).shape) </code></pre> <p...
<p>I tested your code. It works fine for me with output</p> <blockquote> <p>('X_data shape:', (4, 617, 1021, 3))</p> </blockquote> <p>however, all images were exactly the same dimension.</p> <p>When I add another image with different extents I have this output:</p> <blockquote> <p>('X_data shape:', (5,))</p> </...
python|image|opencv|numpy|image-processing
23
15,675
64,450,102
pandas value_count() is showing different values every time I restart the notebook
<p>Every time that I restart my <code>jupyter-lab</code> notebook, <code>value_count()</code> is showing different values.</p> <pre><code>bid = customers['BasketID'] bid.value_counts() </code></pre> <p>Here's the results of two executions:</p> <pre><code>576339 542 573585 535 579196 533 580727 529 57827...
<p><code>value_counts</code> by default has <code>sort=True</code>, which most likely uses quicksort to sort. You can try to disable that with <code>sort=False</code>, which returns the series with sorted index:</p> <pre><code>bid.value_counts(sort=False) </code></pre> <p>If you still want the sorted series, you can so...
python|pandas|jupyter-notebook|jupyter|jupyter-lab
2
15,676
64,484,365
Count elements satisfying a condition of two rows
<pre><code>data A B 1 1 5 1 3 6 5 3 3 1 </code></pre> <ol> <li><p>How to apply functional programming to count the number of lines in which A[i]&gt;A[i-1] and B[i]==B[i-1]</p> </li> <li><p>And how to print these lines?</p> </li> </ol> <p>They are different tasks. I know we can solve the second task first and then...
<p>In <code>numpy</code> you need to find differences and then compare values of new array:</p> <pre><code>x = pd.DataFrame(data).values diff = np.diff(x, axis=0) mask = np.logical_and(diff[:,0]&gt;0, diff[:,1]==0) &gt;&gt;&gt; mask array([ True, False, False, False]) </code></pre> <p>You are able to solve both of pro...
python|pandas|numpy|functional-programming|aggregate
0
15,677
64,415,851
How to loop with pandas: 'for each row in file, for each column in row'
<p>My dataset looks like this: <a href="https://i.stack.imgur.com/QBTfL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QBTfL.png" alt="enter image description here" /></a></p> <p>and i need to loop through each day, and then each time of the day, and check whether the state is A, B or C. I tried as ...
<p>use <code>iterrows()</code> instead of <code>itertuples()</code>, also you need a : after each if.</p> <pre><code>for i,row in file.iterrows(): for j in row: if j == 'A': *set parameters to certain values* file.iloc[i,'column_name'] = value #for example if j == 'B': *s...
python|pandas|dataframe|nested-loops
1
15,678
64,185,238
Identifying duplicates, then trying to use a for loop to drop them - ans: instead use dropduplicates()
<p>first I'm a newbie so if there's a simpler way to do this, I'm all ears.</p> <p>I have some relatively simple code to find duplicates, then remove them. I'm not sure what I'm doing wrong. Basically I create a series from <code>.duplicated</code>. Then I'm running a for loop against the data frame to remove the du...
<p>Pandas has <code>drop_duplicates</code> method: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer">documentation</a>. It does exactly what you are aiming for. You can decide which row to keep (first, last or non).</p> <p>As a general t...
python|pandas
1
15,679
47,885,545
Generating a new variable/column in a data frame based on two rows of another variable/column
<p>Context: I am working with Uniform Crime Report data, indexed by city(place). I am trying to merge/concat the years 2006-2016</p> <p>Problem: Not all .csv's have a state column in front of the city name, and there are different numbers of cities in each file. Since there are duplicates in the city name column, merg...
<blockquote> <p>But I could not, for the life of me, figure out how to call the n+1 object in the list, rather than simply adding 1 to value of n.</p> </blockquote> <p>If you want the next iteration object, you can do as such :</p> <pre><code>for index, n in enumerate(firstletter): n # it is your current object...
python|python-3.x|pandas
1
15,680
47,720,307
Inverse of numpy.recarray.tobytes
<p>What's the inverse to <a href="https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.recarray.tobytes.html" rel="nofollow noreferrer"><code>numpy.recarray.tobytes</code></a>?</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; A = np.array([(28483,27759)],dtype=[('x','&lt;u2'),('y','&lt;u2')]) &...
<p>I suspect you want <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.frombuffer.html" rel="nofollow noreferrer"><code>frombuffer</code></a>, which interprets a bytestring (or, more generally, any Python object that supports the <a href="https://docs.python.org/3.6/c-api/buffer.html" rel="nof...
python|numpy
4
15,681
49,197,366
Using FFT for 3D array representation of 2D field
<p>I need to obtain the fourier transform of a complex field. I'm using python.</p> <p>My input is a 2D snapshot of the electric field in the xy-plane.</p> <p>I currently have a 3D array F[x][y][z] where F[x][y][0] contains the real component and F[x][y]<a href="https://i.stack.imgur.com/DXHLJ.png" rel="nofollow nore...
<p>I add here another answer, suitable to the added code.</p> <p>The answer is still <code>np.fft.fft2()</code>. Here's an example. I modified the code slightly. To verify that we need <code>fft2</code> I discarded one of the blobs, and then we know that a single Gaussian blob should transform into a Gaussian blob (wi...
python|numpy|fft
3
15,682
58,963,553
AttributeError: module 'tensorflow.python.keras.backend' has no attribute 'get_graph'
<p>I have been working on keras yolov3 model for object detection. This error keeps showing up. Here is the error:</p> <pre><code>AttributeError: module 'tensorflow.python.keras.backend' has no attribute 'get_graph' </code></pre> <p>I don't know what to do. I have tried replacing "import keras.module.module" to "te...
<p>The project &quot;YOLOv3 model for object detection&quot; has some issues with versions. I had the same issue and I used tensorflow 1.14.0 and keras 2.2.0.</p> <p>Just overwrite the specific versions. Write in the command line.</p> <pre><code>pip install tensorflow==1.14.0 pip install keras==2.2.0 </code></pre>
python|tensorflow|keras|keras-layer|tf.keras
9
15,683
58,936,927
Tensorflow 1.14 on Google Collab - No GPU
<p><strong><em>TL;DR</em></strong></p> <p>Whats the correct way to install CUDA 10 and replace 10.1 as the CUDA driver on Google Colab?</p> <p><strong><em>Longer:</em></strong></p> <p>Recently Google must have updated some drivers on collab, because CUDA 10.1 is installed, and my project requires which required tens...
<p>I've resolved this - short story, use --allow-change-held-packages since Google Colab holds CUDA packages. See the bottom for full instructions:</p> <p>See the edited question above for full solution.</p>
linux|tensorflow|google-colaboratory
1
15,684
70,046,252
How to replace regex pattern hh:mm:ss with hh:mm in python
<p>I'm sorry if this is a simple question but I have a csv file with different time formats as follows: <code>hh:mm</code> and <code>hh:mm:ss</code></p> <p>An extract of the file looks like this:</p> <pre><code>column_name 00:00:00 01:00:00 05:00 02:00:00 03:00:00 06:00 ... 23:00:00 00:00:00 </code></pre> <p>I have the...
<p>You can slice the string with <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.html" rel="nofollow noreferrer">str</a>:</p> <pre><code>df['column_name'] = df['column_name'].str[:-3] </code></pre> <p>Or:</p> <pre><code>df['column_name'] = df['column_name'].str.rsplit(':', 1).str[0] </code></pre...
python|pandas|string|time
1
15,685
70,194,190
Randomly select 50% of records from 3 different groups for A/B test
<p>Apologies if this has been asked already. I am trying to setup a small A/B test and split the records evenly (50%) across 3 categories: <code>Low intent</code>, <code>Medium intent</code>, <code>High intent</code>. I'd like to randomly select 50% of each of the 3 categories to a control group and 50% to a treatment ...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.sample.html" rel="nofollow noreferrer"><code>groupby.sample</code></a> to choose 50% records per group and then assign the labels with <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofoll...
python|pandas|dataframe|numpy
2
15,686
70,164,042
Can I define file path and file name before importing a file (python)?
<p>I'm trying to import an excel file that has multiple sheets to python by using pd.read_excel. Can I define the file path and the excel file names beforehand? This will make it easier to run the script for the different dataset which has different file paths and excel file names. I tried something like this but didn'...
<p>Try this</p> <pre><code>#Define file path file_path =&quot;copied and pasted actual file path here&quot; #Define raw data excel sheet name raw_data=&quot;copied and paste excel file name here&quot; #import excel import pandas as pd PL_raw_data = pd.read_excel (file_path + raw_data, sheet_name='copied and pasted e...
python|excel|pandas|file
0
15,687
70,089,964
I/O Issues in Loading Several Large H5PY Files (Pytorch)
<p>I met a problem!</p> <p>Recently I meet a problem of I/O issue. The target and input data are stored with h5py files. Each target file is <em>2.6GB</em> while each input file is <em>10.2GB</em>. I have 5 input datasets and 5 target datasets in total.</p> <p>I created a custom dataset function for each h5py file and ...
<p>Improving performance requires timing benchmarks. To do that you need to identify potential bottlenecks and associated scenarios. You said &quot;<em>with 2-3 files the I/O speed is normal</em>&quot; and &quot;<em>when 5 files are used, the training speed gradually decreases</em>&quot;. So, is your performance issue...
python|pytorch|h5py|pytorch-dataloader
1
15,688
56,363,530
Summing split dataframe columns in an iterative process
<p>I have a dataframe "fpd" which is split on unique values in column <code>['View']</code> using </p> <pre><code>bookuniques = fpd['View'].unique() fpdict = {elem: pd.DataFrame for elem in bookuniques} for key in fpdict.keys(): fpdict[key] = fpd[:][fpd['View'] == key] </code></pre> <p>The dataframe looks like:...
<p>Here are the assumptions I have to do because this is not clearly stated in the question:</p> <ul> <li>the dataframe has a multi-index on columns Product, PG, Location</li> <li>the new row will have PG=Total and all other non numeric fields set to an empty string</li> <li>fpdict[key] will have <code>View</code> col...
python|pandas|iteration
1
15,689
56,074,399
Convert pandas dataframe to dict to JSON, unflatten nested subkeys, drop None/NaN keys
<p>Can the following be done in Pandas in one go, in more Pythonic code than below? </p> <p>I have a row from a pandas-dataframe:</p> <ul> <li>some values may be NaNs or empty strings or similar</li> <li>I'd like to map this information to a dict (which is then converted to JSON and passed on to another application)<...
<p>To transform your DataFrame to a dictionary without NaN, there is a straightforward way:</p> <pre><code>df.dropna().to_dict() </code></pre> <p>But you also want to create sub-dictionaries from composed keys, and I found no other way than a loop:</p> <pre><code>df = DataFrame({"col": [3, None, 4, 5, None]}, index=...
python|json|pandas|dictionary|nested
3
15,690
55,694,263
How to fix "TypeError: data type not understood" in numpy when creating transformer no peak mask
<p>I'm trying to implement and train a transformer for NMT via a blog post, everything works except I can't create the no peaking mask as I get this error: "TypeError: data type not understood" </p> <p>Code: </p> <pre class="lang-py prettyprint-override"><code>target_seq = batch.Python.transpose(0,1) target_pad = PY_...
<p>The first input to <code>np.triu</code> should be a tuple of desired sizes instead of a numpy array.</p> <p>Try:</p> <pre><code>np.triu((1, size, size), k=1).astype("uint8") </code></pre>
python|numpy|deep-learning|pytorch
2
15,691
55,981,459
How to calculate standard deviation of count-value pairs
<p>In numpy the function for calculating the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html" rel="nofollow noreferrer">standard deviaiton</a> expects a list of values like [1, 2, 1, 1] and calculates the standard deviation from those. In my case I have a nested list of values and counts li...
<p>You are simply looking for numpy.repeat.</p> <pre><code>numpy.std(numpy.repeat(value_counts[0], value_counts[1])) </code></pre>
python|numpy|scipy|statistics
1
15,692
39,860,431
Fast Python/Numpy Frequency-Severity Distribution Simulation
<p>I'm looking for a away to simulate a classical frequency severity distribution, something like: X = sum(i = 1..N, Y_i), where N is for example poisson distributed and Y lognormal.</p> <p>Simple naive numpy script would be:</p> <pre><code>import numpy as np SIM_NUM = 3 X = [] for _i in range(SIM_NUM): nr_claim...
<p>We can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html" rel="nofollow"><code>np.bincount</code></a> , which is quite efficient for such interval/ID based summing operations specially when working with <code>1D</code> arrays. The implementation would look something like this -</p...
python|performance|numpy|vectorization
3
15,693
39,496,476
how to filter by iloc
<p>I have a dataframe that has 2 columns. the second column is one of only a few values. I want to make a method that returns a dataframe where only the rows where that column had a specific value are included.</p> <p>I had this working with this this code:</p> <pre><code>def filterOnName(df1): d1columns = df1.co...
<p>First argument of <code>.iloc</code> is for rows. To get the second column, you'll need:</p> <pre><code>df.iloc[:, 1] </code></pre> <p>where <code>:</code> means "all rows". </p>
python|pandas|dataframe
5
15,694
39,707,159
Reading binary file in c written in python
<p>I wrote numpy 2 dimensional float array as a binary file using </p> <p><code>narr.tofile(open(filename,"wb"),sep="",format='f')</code> </p> <p>and try to retrieve the same in c using</p> <pre><code>FILE* fin = fopen(filename,"rb") float* data = malloc(rows*2*sizeof(float)); fread(data, sizeof(float), rows*2, fin...
<p>It may depends on system you are using, <code>ndarray.tofile()</code> outputs in little-endian, which means that the <strong>least significant byte is stored first</strong>, try to use <code>numpy.byteswap()</code> and then convert to file. Also try to do it without format specifier and see result. Documentation st...
python|c|arrays|numpy
0
15,695
44,328,955
Dealing with unknown dimensions in Tensorflow
<p>I wrote a function that calculates the gram matrix for image features of shape (1, H, W, C). Method I wrote is below:</p> <pre><code>def calc_gram_matrix(features, normalize=True): #input: features is a tensor of shape (1, Height, Width, Channels) _, H, W, C = features.shape matrix = tf.reshape(features, sha...
<p>I made the following changes and it worked. </p> <pre class="lang-py prettyprint-override"><code>def calc_gram_matrix(features, normalize=True): #input: features is a tensor of shape (1, Height, Width, Channels) features_shape = tf.shape(features) H = features_shape[1] W = features_shape[2] C = features_...
tensorflow|deep-learning
4
15,696
69,512,895
Splitting up string contents of 2 or more columns in python dataframe and appending to new rows in Python
<p>I have a problem where there are multiple rows in a csv file that I have converted to a pandas data frame. However there are some rows where the columns 'name' and 'business' have multiple names and businesses that need to be split up and placed into individual rows while keeping the data from the other columns the ...
<p>Since <code>pandas 1.3.0</code> it's possible to <a href="https://pandas.pydata.org/pandas-docs/dev/reference/api/pandas.DataFrame.explode.html#pandas.DataFrame.explode" rel="nofollow noreferrer">explode</a> on multiple columns. So a simple solution would be to:</p> <ol> <li>Split <code>name</code> on comma and <cod...
python|excel|pandas|dataframe|csv
0
15,697
69,524,600
Creating a function to open a file while naming it
<p>I am trying to create a function to open several files from a local directory and to name it. I have tried the following (which already works outside of the function):</p> <pre><code>def read_csv_for_tsv_files(table_name): {table_name}_scn_csv = pd.read_csv(fr'C:\Users\xxx\Desktop\{table_name}.csv', sep=';', ...
<p>It looks like you are trying to assign to a dynamically named variable based on the table name. While it is possible to do this using e.g. <a href="https://docs.python.org/3/library/functions.html#globals" rel="nofollow noreferrer"><code>globals</code></a>, it is probably not a good idea.</p> <p>If you want to store...
python|pandas|function|csv
0
15,698
69,636,238
Pandas DataFrame filtering of groups of rows on multiple columns
<p>Here's a simplified version of my dataframe:</p> <pre><code>d = {'col1': ['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3', 'd1', 'd2', 'd3'], 'col2': [1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1, 1], 'col3': [-1, -1, 1, -1, -1, 1, 1, 1, 1, -1, 1, 1]} df = pd.DataFrame(d) df </code></pre> <pre><code> col1 col2 ...
<p>To put my last comment into an answer. Create a new column that is a lag using <code>n</code>, then just filter the standard way and grab the first value of <code>col1</code>.</p> <pre><code>n = 2 df['newCol'] = df['col2'].shift(n) df.loc[(df['col3'] == 1) &amp; (df['newCol'] == 1), ['col1']].values[0] </code></pre...
python|pandas|dataframe|filter
1
15,699
53,874,379
Pytorch - basic structure of cnn
<p>I just started pytorch today, and I am reading this at the moment. <a href="https://pytorch.org/tutorials/beginner/blitz/neural_networks_tutorial.html" rel="nofollow noreferrer">https://pytorch.org/tutorials/beginner/blitz/neural_networks_tutorial.html</a>. The documentation has this code and also this illustration ...
<p>Yes, the network in the image is represented by the code. Here, C1, C3, ... represents the convolutional layer and S2, S4, ... max pool layers. The dimensions shown are those of image after passing through each of these layers. You can check this by using the following procedure:</p> <p>The input dimension of the i...
python|neural-network|conv-neural-network|pytorch
0