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
360,700
62,787,056
ImportError: cannot import name 'context' from 'tensorflow.python.eager' (unknown location)
<p>I created virtual environment and installed both tensorflow and tensorflow-gpu. After that I installed keras. And then I checked in my conda terminal by importing keras and I was able to import keras in it. However, using jupyter notebook if I try to import keras then it gives me below error.</p> <pre><code>import k...
<p>Did you installed the dependencies with conda? Like this:</p> <pre><code> $ conda install -c conda-forge keras $ conda install -c conda-forge tensorflow $ conda install -c anaconda tensorflow-gpu </code></pre> <p>If you installed with <code>pip</code> they will not work inside your virtual env. Look at your cond...
python|tensorflow|keras|python-import|importerror
3
360,701
62,840,990
How to store value in a variable and use that variable to filter data in pandas
<p>I have to take input which i store in a variable and use that value to filter out data like this</p> <pre><code>u = 'Jun' duration = compda.query(&quot;Month==u&quot;).groupby('name').duration.mean().reset_index().values.tolist() </code></pre> <p>this doesnt work, however</p> <pre><code>duration = compda.query(&quo...
<p>This should work, you can use @ to pass variables (<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.query.html" rel="nofollow noreferrer">documentation here</a>):</p> <pre><code>u = 'Jun' duration = compda.query('Month == @u').groupby('name').duration.mean().reset_index().values.t...
pandas|pandas-groupby
2
360,702
62,475,240
How to compute how many elements in three arrays in python are equal to some value in the same positon betweel the arrays?
<p>I have three numpy arrays </p> <pre><code>a = [0, 1, 2, 3, 4] b = [5, 1, 7, 3, 9] c = [10, 1, 3, 3, 1] </code></pre> <p>and i wanna to compute how many elements in a, b, c are equal to 3 in the same position, so for that example would be 3.</p>
<p>An elegant solution is to use <em>Numpy</em> functions, like:</p> <pre><code>np.count_nonzero(np.vstack([a, b, c])==3, axis=0).max() </code></pre> <p>Details:</p> <ul> <li><code>np.vstack([a, b, c])</code> - generate an array with 3 rows, composed of your 3 source arrays.</li> <li><code>np.count_nonzero(...==3, a...
numpy
1
360,703
62,552,416
Keras layer shape incompatibility for a small MLP
<p>I have a simple MLP built in Keras. The shapes of my inputs are:</p> <pre><code>X_train.shape - (6, 5) Y_train.shape - 6 </code></pre> <h1>Create the model</h1> <pre><code>model = Sequential() model.add(Dense(32, input_shape=(X_train.shape[0],), activation='relu')) model.add(Dense(Y_train.shape[0], activation='so...
<p>in the input layer use input_shape=(X_train.shape[1],) while your last layer has to be a dimension equal to the number of classes to predict</p> <p>the way to return the softmax vector is model.predict(X)</p> <p>here a complete example</p> <pre><code>n_sample = 5 n_class = 2 X = np.random.uniform(0,1, (n_sample,6)) ...
tensorflow|machine-learning|keras|mlp
2
360,704
62,826,516
Error in the conversion of Bidirectional LSTM Text Classification Model to TFLite Model
<p>My model is trained on the &quot;imdb reviews dataset&quot; and works fine when predicting the sentiment of movie reviews. However, when I convert my model for Tensorflow Lite, it outputs: None is only supported in the 1st dimension. Tensor 'embedding <em>1</em> input' has invalid shape '[None, None]'. When training...
<p>Current stable versions of Tensorflow don't support dynamic input shapes.</p> <p>However, using the nightly build could solve your problem. I found <a href="https://github.com/tensorflow/tensorflow/issues/29590#issuecomment-629583073" rel="nofollow noreferrer">this issue</a> in Tensorflow github where this method is...
keras|nlp|lstm|tensorflow2.0|tensorflow-lite
1
360,705
62,520,806
Should I import a python module if I don't use it directly
<p>I am working on a project with a few files, and one of my helper modules has a function that takes as argument a <a href="https://pytorch.org/docs/master/generated/torch.nn.MSELoss.html" rel="nofollow noreferrer">criterion that measures MSE from the torch library</a>. This module does postprocessing (displaying/savi...
<p>The <code>python</code> compiler figures out if you already imported <code>pytorch</code> and won't import it a second time. In this case, if you want it to potentially run separately by a script that doesn't <code>import torch</code>, better add it at the beginning since it should be ignored anyways if it's not nec...
python|numpy|pytorch
0
360,706
62,666,607
OLS regression storing problem: zero-size array to reduction operation maximum which has no identity
<p>I have a problem with this for loop in python. I'm trying to iterate the OLS command in a cross-section data where I'have multiple id observed during the same period. I want to do a regression for each id of each year, of each month.</p> <p>When i try to run singurlarly the commands they works but in the loop the ou...
<p>it usually happens when there is missing value in dataset, you better try df.dropna(how='all') and test it</p>
python|pandas|regression
0
360,707
62,588,018
How to set numpy matrix boundries to zeros?
<p>I have numpy 10×10 matrix</p> <pre><code>image=np.ones((10,10)) </code></pre> <p>I want to set its boundaries to zero.</p> <pre><code>h,w=image.shape image[:,0:2] = 0 image[:,w-2:w] = 0 image[0:2,:] = 0 image[h-2:h,:] = 0 </code></pre> <p>Is there more efficient way to do this?</p> <p>Thanks</p>
<p>Make the zeros first then assign the ones to the <em>middle</em> of the zeros.</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.zeros((10,10)) &gt;&gt;&gt; b = np.ones((6,6)) &gt;&gt;&gt; a[2:-2,2:-2] = b </code></pre> <hr /> <p>Or if the ones already exist.</p> <pre><code>&gt;&gt;&gt; a = np.ones(...
python|numpy
1
360,708
62,590,537
pandas: add corresponding value to the second dataframe if column names matches the cell value in the second dataframe
<p>I have two dataframes like the following but with more rows:</p> <pre><code>import pandas as pd text1 = {'first_text': ['she is cool', 'they are nice', 'he is good', 'we are friendly'], 'change_adj': ['she is neat', 'NaN', 'NaN', 'we are nice'], 'change_pro': ['NaN', 'she is nice', 'NaN', 'she is ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html" rel="nofollow noreferrer">pandas.melt</a> in combination with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge.html" rel="nofollow noreferrer">pandas.merge</a></p> <pre><code>melt = df1.m...
python|pandas|dataframe
2
360,709
62,488,108
Reformat Tensor in Tensorflow
<p>I have a tensor of data which is the output of a net in Tensorflow, however, I want to reformat it into a larger batch size composed of elements of the original tensor. That wasn't very clear, so let's say the output of my net is a tensor with shape (10, 1000, 1) - (batch_size, length, features), and I want to refor...
<p>How about <code>tf.reshape()</code>? Should work with both eager and graph-based tensors. It's a bit unclear why the total number of elements in your reformatted tensor is less than of the original, but if this is what you really want I suggest using a combination of <code>tf.reshape()</code> and generating a list o...
python|tensorflow
0
360,710
62,783,357
Group By Median, Percentile and Percent of Total
<p>I have a dataframe that looks like this...</p> <pre><code> ID Acuity TOTAL_ED_LOS 1 2 423 2 5 52 3 5 535 4 1 87 ... </code></pre> <p>I would like to produce a table that looks like this:</p> <pre><code> Acuity Count Median Percentile_25 Percentile_75 % of total 1 ...
<p>Here's a one way to do it using some pandas builtin tools:</p> <pre><code># Set random number seeed and create a dummy datafame with two columns np.random.seed(123) df = pd.DataFrame({'activity':np.random.choice([*'ABCDE'], 40), 'TOTAL_ED_LDS':np.random.randint(50, 500, 40)}) # Reshape dataframe...
python|pandas
2
360,711
62,721,934
POS using a column (in pandas)
<p>I would like to extract only nouns from this dataset:</p> <pre><code> Text1 Text2 see if your area is affected afte... public health england have confir... 'i had my throat scraped'. i have been producing some of our... drive-thru testing introdu...
<p>I prefer spAcy via Google Colab for work like this. I prefer spAcy in general for this kind of task.</p> <p>If you want to try your hand before seeing my answer, look here. <a href="https://spacy.io/usage/linguistic-features" rel="nofollow noreferrer">https://spacy.io/usage/linguistic-features</a></p> <p>If you can,...
python|pandas|nltk
0
360,712
62,880,153
Split pandas df based on column name endings
<pre><code>data = {&quot;name&quot;: [], &quot;value&quot;: [], &quot;x1xyz&quot;: [], &quot;x2xyz&quot;: [], &quot;x3xyz&quot;:[], &quot;x1abc&quot;: [], &quot;x2abc&quot;: [], &quot;x3abc&quot;: []} df = pd.DataFrame (data, columns = ['name', 'value', 'x1xyz', &quot;x2xyz&quot;, &quot;x3xyz&quot;, 'x1abc', &quot;x2a...
<p>you can use <code>filter</code> and return a dictionary of dataframes by using a list of values you want to filter by. we need to set the constant columns as the index.</p> <pre><code>filter_vals = ['abc','xyz'] dfs = { filter_name: df.set_index([&quot;name&quot;, &quot;value&quot;]).filter(like=filter_name) ...
python|python-3.x|pandas|dataframe|split
0
360,713
62,661,353
How to combine multiple different numpy arrays along a single common dimension, while setting unique variables as separate dimensions
<p>I have multiple different <code>numpy</code> arrays, all with different shapes and containing different information. But all contain a <code>'timestamp'</code> axis.</p> <p>For example, I have 2 arrays, a, b as follows:</p> <ul> <li><code>a = np.array([[1,[1,2,3,4,5,6,7,8,9,10]],[2,[11,12,13,14,15,16,17,18,19,20]],[...
<p>Maybe the previous answer using a zip solved it for you but it works only if the 2 lists have the &quot;index element&quot; in the same order. In case they are not (or if there are few indexes missing), the zip will not work properly.</p> <p>Try this.</p> <pre><code>import itertools [[i[0][0],[i[0][1],i[1][1]]] for...
arrays|numpy
0
360,714
62,870,408
Why at first epoch validation accuracy is higher than training accuracy?
<p>I'm working with a video classification of 5 classes and using TimeDistributed CNN + RNN model. The training dataset contains 70 videos containing 20 frames each per class. The validation dataset contains 15 videos containing 20 frames each per class. The test dataset contains 15 videos containing 20 frames each per...
<p>My guess is that because you only have 5 classes, by just guessing on one for all frames will give you an accuracy of 20%. Now you have around 32%, so slightly better.</p> <p>I usually don't look at the initial accuracy as the model is really bad. (actually remove the first N (in this case maybe 20/30) epochs from t...
python|tensorflow|keras|deep-learning|conv-neural-network
0
360,715
62,511,767
Rolling operations of grouped data frame
<p>I am trying to do a rolling sum of data frame. Sample of data frame:</p> <pre><code> cdateint severity cnt_alerts 0 20200511 1 48 1 20200511 2 89 2 20200511 3 5 3 20200511 4 1 4 20200512 1 48 5 20200512 ...
<p>IIUC, use <code>pandas.to_datetime</code> and <code>groupby</code> with <code>rolling</code>:</p> <pre><code>df[&quot;cdateint&quot;] = pd.to_datetime(df[&quot;cdateint&quot;].astype(str)) new_df = df.set_index(&quot;cdateint&quot;).groupby(&quot;severity&quot;).rolling(&quot;3d&quot;)[&quot;cnt_alerts&quot;].sum() ...
python|pandas|rolling-computation
2
360,716
62,717,034
Error when saving with numpy.save and loading with pickle.load
<p>I've saved a simple numpy array by doing:</p> <pre><code>numpy.save(filepath, anarray) </code></pre> <p>I'm now trying to retrieve it using pickle (I don't want to switch to numpy.load because the code has to be flexible), but I get:</p> <pre><code>atuple = pickle.load(open(filepath, 'rb')) _pickle.UnpicklingError:...
<p>Numpy and pickle use different file formats. There's no reason to expect that you should be able to unpickle an array saved using <code>np.save</code>. If you need to be able to load things with pickle, you should save them with pickle.</p>
python|numpy|pickle
1
360,717
62,614,359
X and Y label being cut in matplotlib plots
<p>I have this code:</p> <pre><code>import pandas as pd from pandas import datetime from pandas import DataFrame as df import matplotlib from pandas_datareader import data as web import matplotlib.pyplot as plt import datetime start = datetime.date(2016,1,1) end = datetime.date.today() stock = 'fb' fig = plt.figure(dpi...
<p>It's a long-standing issue with <code>.savefig()</code> that it doesn't check legend and axis locations before setting bounds. As a rule, I solve this with the <code>bbox_inches</code> argument:</p> <pre><code>plt.savefig('Test', bbox_inches='tight') </code></pre> <p>This is similar to calling <code>plt.tight_layout...
python-3.x|pandas|matplotlib
4
360,718
62,582,099
"KeyError: True" when matching Pandas DataFrame
<p>I am planning to set up a simple script to see if words from a wordlist can be found in a Pandas DataFrame <code>common_words</code>. In case of a match, I would like to return the corresponding DataFrame entry, while the DF has the format <code>life balance 14</code>, <code>long term 9</code>, <code>upper managemen...
<p>I think it might be helpful to break the code into chunks. This should work if I understood the code correctly:</p> <pre><code>filter_logic = df[i].str.contains(x) df[filter_logic][i] </code></pre>
python|pandas|dataframe|nlp
1
360,719
62,800,275
Whats the best way to convert complex numpy array to an array of magnitudes?
<p>What I mean is something like:</p> <pre><code>mag(complex_array) = [ sqrt(complex.real * complex.real + complex.imag + complex.imag) for complex in complex_array ] </code></pre> <p>Is there a built-in function for this?</p>
<p>Just use <code>np.abs</code>:</p> <pre><code>&gt;&gt;&gt; a = np.array([1+2j, 3+4j]) &gt;&gt;&gt; np.abs(a) array([2.23606798, 5. ]) </code></pre>
python|numpy|complex-numbers
2
360,720
62,688,337
Pandas exclude rows based on dynamic condition set from configuration file
<p>As title suggest, I have a rule engine in xml format which contains column name and values to exlcule.</p> <pre><code> &lt;ExclusionSet&gt; &lt;Exclude Excl=&quot;Col1:A&quot; Count=&quot;1&quot;/&gt; &lt;Exclude Excl=&quot;Col2:BB,BBB&quot; Count=&quot;1&quot;/&gt; &lt;Exclude Excl=&quot;Col3:A1B&quot; ...
<p>You could use the pandas <code>query</code> method. I am dropping all the non related xml stuff, as it is not going to work (you have a duplicate attribute so the supplied text is not a valid xml)</p> <pre><code>import pandas as pd import re def exclusionEngine(config: str,df: pd.DataFrame): ret_df = df.copy() ...
python-3.x|pandas
1
360,721
62,487,251
How to split a dataframe
<p>I have a df which looks like this:</p> <pre><code>df.head() Close Date 2011-12-31 4.472624 2012-01-01 4.680778 2012-01-02 5.000000 2012-01-03 5.145917 2012-01-04 5.228729 </code></pre> <p>and I wanna split the data into two parts according this attempt:</p> <pre><code># Split data df_train = df['2017':'2020...
<p>You need to convert your index to datetime</p> <pre><code>df.index=pd.to_datetime(df.index) </code></pre>
python|pandas|numpy
3
360,722
62,749,459
Custom Metric In Tensorflow 2. Casting Y_true and Y_pred
<p>I am trying to implement a custom metric (F1 Score) for Tensorflow 2 sequential model. As a naive approach i created a function to accept y_true and y_pred and use SK learn to compute the result. I added this function in the Model Compile Metrices.</p> <pre class="lang-py prettyprint-override"><code>from sklearn.met...
<p>Your error says,&quot;TypeError: Expected sequence or array-like, got...&quot;</p> <p>your solution lies on proper reprocessing the y_true value, as you are getting output in shape of [None,10] ,(None, here represent batch), you should make sure your target sequence/array should be one hot encoded to length 10. you ...
python|tensorflow|machine-learning|deep-learning|tensorflow2.0
-1
360,723
62,819,947
Pandas; Python - VLookup
<p>This is my first time posting a question, so take it easy on me if I don't know stack overflow norm of asking questions.</p> <p>Attached is a snippet of what I am trying to accomplish on my side-project. I want to be able to compare a user input with a database <code>.xlsx</code> file that was imported by pandas.</p...
<p>You can do this by taking advantage of indices and using the <code>df.loc</code> accessor in pandas:</p> <pre class="lang-py prettyprint-override"><code># set index to Component column for convenience data = data.set_index('Component') LK = input('What is the Light Key?: ') #Answer should be Benzene in this case # ...
python|pandas
1
360,724
62,509,142
How to quickly normalise data in pandas dataframe?
<p>I have a pandas dataframe as follows.</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'A':[1,2,3], 'B':[100,300,500], 'C':list('abc') }) print(df) A B C 0 1 100 a 1 2 300 b 2 3 500 c </code></pre> <p>I want to normalise the entire dataf...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.select_dtypes.html" rel="nofollow noreferrer"><code>DataFrame.select_dtypes</code></a> for <code>DataFrame</code> with numeric columns and then normalize with division by minimal and maximal values and then assign back only norma...
pandas
1
360,725
62,630,098
More pythonic way to edit column values - python pandas
<p>I feel like there must be a more pythonic way (ie: easier and more straightforward) to change column values in the dataframe I am working with. Basically, I am trying to edit the values of a column <code>match</code> based on values of the 'ID' column.</p> <p>Take this example:</p> <pre><code>data = [['tom', 10, 111...
<p>How about this:</p> <pre><code>rounds = { 111: 'Round 1', 112: 'Round 2', 113: 'Round 3', 114: 'Round 4', } df['match'] = [rounds[i] for i in df.ID] Name Age ID match 0 tom 10 111 Round 1 1 nick 15 112 Round 2 2 juli 14 113 Round 3 3 mary 17 114 Round 4 </code></pre>
python|pandas|dataframe
2
360,726
62,759,575
How to sort values in multi nested dictionary and select first n values in python?
<h2>My dictionary is like this :</h2> <pre><code>dict = { '2020-10-11' : { 'group1':{ 1 : 2356, 21 : 10001, 34 : 234 }, ...
<p>This is a way of doing it with <code>for</code> loops and <code>dict comprehension</code> with <code>sorted</code>:</p> <pre><code>for i in a: for x in a[i]: a[i][x] = {k: v for k, v in sorted(a[i][x].items(), key=lambda item: item[1],reverse=True)} </code></pre> <p>Output:</p> <pre><code>{'2020-10-11': {'grou...
python|pandas|dictionary
1
360,727
62,695,786
error: (-215:Assertion failed) scn + 1 == m.cols in function 'cv::perspectiveTransform'
<p>Below is a python script that calculates the homography between two images and then map a desired point from one image to another</p> <pre><code>import cv2 import numpy as np if __name__ == '__main__' : # Read source image. im_src = cv2.imread(r'C:/Users/kjbaili/.spyder-py3/webcam_calib/homography/khaledd 35...
<p>You are passing wrong arguments to <code>cv2.getPerspectiveTransform()</code>. The function expects a set of four coordinates in the original image and the new coordinates in the transformed image. You can directly pass the <code>pts_src</code> and <code>pts_dst</code> to the function and you will get the transforma...
python|numpy|opencv|computer-vision|homography
1
360,728
62,849,508
Is it possible to do full text search in pandas dataframe
<p>currently, I'm using pandas <code>DataFrame.filter</code> to filter the records of the dataset. if I give a word, I have got all the records that are matching with that word. now if I give two words that are present in the dataset but they are not in one record then I got an empty set. Is there any way in either pan...
<pre><code> Name Qty. 0 Apple 3 1 Orange 4 2 Cake 5 </code></pre> <p>Considering the above dataframe, if you want to find quantities of Apples and Oranges, you can do it like this:</p> <pre><code>result = df[df['Name'].isin(['Apple','Orange'])] print (result) </code></pre>
python|pandas
0
360,729
62,892,535
get bounding boxes with maximum confidence pandas opencv python
<p>I have a Symbol detection algorithm, which can be output from template matching/ faster rcnn or combining the results from both of them, which gives me the coordinates <code>filename,xmin, ymin, xmax, ymax, class, confidence</code>.</p> <p>The issue is that there are multiple bounding boxes occurring for the same ob...
<p>This is the solution which I came up with.</p> <h3>Creating a unique key for each bounding box</h3> <pre class="lang-py prettyprint-override"><code>df['key']=df['xmin'].astype(str)+'_'+df['ymin'].astype(str)+'_'+df['xmax'].astype(str)+'_'+df['ymax'].astype(str) </code></pre> <h3>Making an outer join of all the rows ...
python|pandas|opencv|computer-vision|object-detection
4
360,730
62,790,050
ImportError: cannot import name parse_date while importing Pandas
<pre><code>Python 3.6.9 (default, Apr 18 2020, 01:56:04) [GCC 8.4.0] on linux Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. &gt; import pandas Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;/ho...
<p>Hi I got the same error today when I developed a pyqt project. I found there are two &quot;pandas&quot; when I uninstalled one then tried to install again. What I have done was uninstalling both two &quot;pandas&quot;, then install the latest version, then it works. Although I solved this on Windows, but hope it is ...
python-3.x|pandas
0
360,731
62,487,670
Pandas - How to sum time in a dataframe / column using pandas / numpy
<p>df with a column of time in HH:MM:SS</p> <pre><code>Input: Time 10:00:00 10:00:00 10:00:00 10:00:00 </code></pre> <p>When i try to sum, output is</p> <pre><code>1 day 16:00:00 </code></pre> <p>where as i need it like this</p> <pre><code>Output: Time 40:00:00 </code></pre>
<p>I created your <em>Series</em> the following way:</p> <pre><code>s = pd.Series([pd.Timedelta('10:00:00')] * 4) </code></pre> <p>so that its full printout is:</p> <pre><code>0 10:00:00 1 10:00:00 2 10:00:00 3 10:00:00 dtype: timedelta64[ns] </code></pre> <p>The problem is that <em>s.sum()</em> is by default f...
python|pandas|datetime|time|pivot
0
360,732
62,621,002
Why isn't this replace in DataFrame doing what I intended?
<p>I'm trying to replace NaN in <code>train_df</code> with values of corresponding indexes in <code>dff</code>. I can't understand what I'm doing wrong.</p> <pre><code>train_df.replace(to_replace = train_df[&quot;Age&quot;].values , value = dff[&quot;Age&quot;].values , inplace = Tru...
<p>You replace everything in <code>train_df</code> not just <code>NaN</code>.</p> <p>The <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer"><code>replace</code> docs</a> say:</p> <blockquote> <p>Replace values given in to_replace with value.</p> ...
python|pandas|dataframe
2
360,733
62,525,757
Plotting Multiple Columns Across Rows in a DataFrame
<p>I have the following process stats that I have captured using Python's psutil (see attached <a href="http://www.sharecsv.com/s/ac97ffed30f5225769e543e99f77f173/process_stats.csv" rel="nofollow noreferrer">csv</a>). I am trying to use Pandas and Matplotlib to slice this dataframe such that I can plot all several proc...
<p>If you want to graph the time and memory usage separated by nucleus, you can use the following code</p> <pre><code>process_data['create_time']=pd.to_datetime(process_data['create_time'], infer_datetime_format=True) process_data.set_index('create_time', inplace=True) for i in process_data['cores'].unique().tolist():...
pandas|matplotlib|indexing|numpy-slicing
0
360,734
62,617,901
How do I search for a keyword in a string, extract that string, and place it in a new column?
<p>I'm using Pandas. Here's my df:</p> <pre><code>df = {'Product Name': ['Nike Zoom Pegasus', 'All New Nike Zoom Pegasus 4', 'Metcon 3', 'Nike Metcon 5']} </code></pre> <p>I'd like to search each string value and extract just the product category and then put that extracted string value in another column (&quot;Categor...
<p>How about this solution,When you have a new category all you have to do add new category to cats array.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'Product Name': ['Nike Zoom Pegasus', 'All New Nike Zoom Pegasus 4', 'Metcon 3', 'Nike Metcon 5']}) cats = [&quot;Pegasus&quot;,&quot;Metco...
python|pandas
1
360,735
62,540,583
Parallelized DataFrame Custom Function Dask
<p>I am trying to use Dask to speed up a Python DataFrame for loop operation via Dask's multi-processing features. I am fully aware the for-looping dataframes is generally not best practice, but in my case, it is required. I have read pretty extensively through the documentation and other similar questions, but I canno...
<p>You could try letting Dask handle the application instead of doing the looping yourself:</p> <pre class="lang-py prettyprint-override"><code>ddf[&quot;Locations&quot;] = ddf[&quot;Content&quot;].apply( lambda string: [e.text for e in nlp(string).ents if e.label_ == &quot;GPE&quot;], meta=(&quot;Content&quot;...
python|pandas|dataframe|dask
1
360,736
62,819,172
Pandas appends duplicate rows even though if statement shouldn't be triggered
<p>I have many csv files that only have one row of data. I need to take data from two of the cells and put them into a master csv file ('new_gal.csv'). Initially this will only contain the headings, but no data.</p> <pre><code>#The file I am pulling from: file_name = &quot;N4261_pacs160.csv&quot; #I have the code writ...
<p>I think I've got something that'll work after tinkering with it this morning...</p> <p>Couple points... You shouldn't incrementally build in pandas...get the data setup done externally then do 1 build. In what I have below, I'm building a big dictionary from the small csv files and then using merge to put that tog...
python-3.x|pandas|csv
0
360,737
62,862,808
Is there a way to increase the size of the dataset with labels using data augmentation?
<p>I am trying to implement logistic regression on Kaggle's digit recognition <a href="https://www.kaggle.com/c/digit-recognizer/data?select=train.csv" rel="nofollow noreferrer">dataset</a>. There are 42000 rows in the train set and I want to increase the count using data augmentation.</p> <p>I tried using keras's <cod...
<p>Here is how I eventually saved the augmented data with labels. I sampled 5 rows for viewing pleasure. And the <code>for</code> loop might not be the best way to write to array when full dataset is considered</p> <pre><code>#importing data train = pd.read_csv(&quot;train.csv&quot;) X_train = train.drop(labels=[&quot;...
python|tensorflow|keras
1
360,738
62,636,828
"ImportError: DLL load failed: The specified module could not be found" when trying to import gensim
<p>While trying to import gensim, I run into the following error</p> <pre><code>Traceback (most recent call last): File &quot;c:\Users\usr\Documents\hello\test.py&quot;, line 3, in &lt;module&gt; import gensim File &quot;C:\Users\usr\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\Local...
<p>I had the same problem and tried various things, but the only thing that worked for me was to install an older version of Gensim.</p> <pre><code>pip install gensim==3.7.0 </code></pre>
numpy|scipy|gensim
0
360,739
62,728,575
ValueError: codes need to be array-like integers when extracting X and Y from dataframes
<p>I'm trying to learn more about dataframes by using a reproducible examples of arrays. What i'm doing is trying to extract from my reproducible example the values X and y from my dataframe with my classes enumerated where first 5 rows are features from class A and last 5 rows are features from class B.</p> <p>My actu...
<p><strong>Orignal Answer:</strong></p> <p>First you should refer to this <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Categorical.from_codes.html" rel="nofollow noreferrer">documentation</a>.</p> <p>According to the documentation <code>class_A</code> can be called <code>0</code> and <code...
python|python-3.x|pandas|numpy|dataframe
0
360,740
62,596,678
Python 3 numpy.load() until End of File
<p>Suppose I'm generating a random number of arrays that I need to serialize</p> <pre><code>def generator(): num = 0 while num &lt; random.randint(0, 10): yield np.array(range(2)) num += 1 with open('out.npy', 'wb') as f: for item in generator(): np.save(f, item) </code></pre> <p>N...
<p>Did you try the following?</p> <pre class="lang-py prettyprint-override"><code>data = np.load('out.npy') </code></pre> <p>reference: <a href="https://numpy.org/doc/stable/reference/generated/numpy.load.html" rel="nofollow noreferrer">https://numpy.org/doc/stable/reference/generated/numpy.load.html</a></p>
python|python-3.x|numpy|serialization|deserialization
0
360,741
62,868,829
How to convert numpy.array(dtype=object) to tensor?
<p><em>I have imported all the required libraries for PyTorch. Here are the numpy arrays obtained from my image. And the size of my images are 150x150 grayscale images</em></p> <pre><code>array([[array([[ 89, 117, 59, ..., 39, 48, 38], [118, 85, 96, ..., 41, 42, 31], [171, 118, 70, ..., 33, 42...
<p>I have found an answer but I'd love to hear a more computationally efficient way. My solution was to do the following:</p> <p><code>my_array = numpy.array(my_array.tolist())</code></p>
python|numpy|opencv|deep-learning|pytorch
0
360,742
62,839,985
Python Dataframe drop rows of multi columns with specific values
<p>My dataframe is given below. i want to drop rows in two columns which have less than 0 value.</p> <pre><code>df = name value1 value2 0 A 10 10 1 B -10 10 #drop 2 A 10 10 3 A 40 -10 #drop 4 C 50 10 ...
<p>i guess you mean that if one of the 'value1' or 'value2' are negative, you want to drop the row. so use: <code>df = df[(df['value1'] &gt;= 0) &amp; (df['value2'] &gt;= 0)])</code></p>
python|pandas|dataframe
1
360,743
62,866,577
Android - TFLite OD - Cannot copy to a TensorFlowLite tensor (normalized_input_image_tensor) with 307200 bytes from a Java Buffer with 4320000 bytes
<p>I'm trying to run my own custom model for object detection. I created my dataset from Google cloud - Vision (<a href="https://console.cloud.google.com/vision/" rel="noreferrer">https://console.cloud.google.com/vision/</a>) (I boxed and labeled the images) and it looks like this:</p> <p><a href="https://i.stack.imgu...
<p>There is a superb visualization tool that is called <a href="https://lutzroeder.github.io/netron/" rel="nofollow noreferrer">Netron</a> . I used your .tflite file and the input of your model is:</p> <p><a href="https://i.stack.imgur.com/XEgct.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XEgct.j...
android|tensorflow|google-cloud-platform|tensorflow-lite
20
360,744
54,675,062
How do I better process my data and set parameters for my Neural Network?
<p>When I run my NN the only way to get any training to occur is if I divide X by 1000. The network also needs to be trained under 70000 times with a 0.03 training rate and if those values are larger the NN gets worse. I think this is a due to bad processing of data and maybe the lack of having biases, but I don't real...
<p>In short: all of the problems you mentioned and more.</p> <ul> <li>Scaling is essential, <a href="https://stackoverflow.com/questions/31152967/normalise-2d-numpy-array-zero-mean-unit-variance">typically to 0 mean and a variance of 1</a>. Otherwise, you will quickly saturate the hidden units, their gradients will be...
python|numpy|machine-learning|neural-network
2
360,745
54,336,250
How to compare two dates from two DF without matching index?
<pre><code>df1 USERID DATE 1 1/1/2018 1 1/2/2018 1 1/3/2018 2 1/2/2018 2 1/3/2018 3 1/3/2018 df2 USERID DATE 1 1/1/2018 2 1/2/2018 3 1/3/2018 </code></pre> <p>I want to compare <code>date</cod...
<p>You can do <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> :</p> <pre><code># create a new column df2['Exists'] = True df3 = pd.merge(df1,df2,on=['USERID','DATE'],how='outer').fillna(False) USERID DATE Exists 0 ...
python|pandas|numpy
2
360,746
54,671,553
drop columns are weekends day. select column that index that are week day only
<p>I am using pandas and I need to select the columns with data that represent only weekday and skip weekends, from this .</p> <pre><code>Employee Thu 02-08 Fri 02-08 Sat 02-09 Sun 02-10 Mon 02-11 Tue 02-12 Daniel,s | 7.65 | 0.00 |0.00 |0.00 |8.45 |8.20 Doucore,d| 5.21 | 8.20 |5.00 |0.00 ...
<p>Filter columns not starting with your strings in tuple by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.startswith.html" rel="nofollow noreferrer"><code>startswith</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="n...
python|pandas
2
360,747
54,377,219
Python Aggregate sum over dataframe with conditions
<p>I have a dataframe that looks like this:</p> <pre><code>stuff datetime value A 1/1/2019 3 A 1/2/2019 4 A 1/3/2019 5 A 1/4/2019 6 ... </code></pre> <p>I want to create a new dataframe that looks like this:</p> <pre><code>stuff avg_3 avg_4 avg_5 A 3.4 4.5 5.5 B 2.3 4.2 6.1 </code></pre> <p>where avg_3 is the avg o...
<p>Create boolean masks before <code>groupby</code>, add new columns by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>assign</code></a> and <code>groupby</code> with <code>mean</code>:</p> <pre><code>m1 = df.datetime &gt; pd.datetime.now()...
python|pandas|dataframe
1
360,748
54,350,623
Tensorflow GAN: "No gradients provided for any variable"
<p>I'm trying to set up a GAN with TF but I'm to stupid. I searched the web but couldn't find an answer.</p> <p>When I run the code provided I get:</p> <pre><code>gen_optimize = tf.train.AdamOptimizer(learning_rate, beta1).minimize(gen_loss, var_list=gen_vars) </code></pre> <blockquote> <p>ValueError: No gradients...
<p>Your problem is in how you filter the variables:</p> <pre><code>dis_vars = [var for var in train_vars if 'dis_' in var.name] gen_vars = [var for var in train_vars if 'gen_' in var.name] </code></pre> <p>You defined the variables for the discriminator in the <code>discriminator</code> scope and of the generator in ...
tensorflow|deep-learning|generative-adversarial-network
0
360,749
54,643,686
ERROR: Config value cuda is not defined in any .rc file INFO: Invocation ID: 1faa4ce7-96be-42d3-80bc-10cac6a8f3a7
<p>I am following this <a href="https://medium.com/@zhanwenchen/speed-up-learning-by-building-tensorflow-gpu-from-source-on-ubuntu-d03bb4e06b23" rel="nofollow noreferrer">https://medium.com/@zhanwenchen/speed-up-learning-by-building-tensorflow-gpu-from-source-on-ubuntu-d03bb4e06b23</a> and this <a href="https://allise...
<p>The version of bazel is too new for the level of TensorFlow you want to build.</p> <p>See this page: <a href="https://www.tensorflow.org/install/source" rel="nofollow noreferrer">https://www.tensorflow.org/install/source</a> for what level of bazel to use for each release of TensorFlow. </p> <pre><code>Short summa...
tensorflow|build|bazel
2
360,750
54,357,005
How to append a dataframe row to another within a for loop using .loc?
<p>Let's say I have the following dataframes:</p> <pre><code>df_t1 = pd.DataFrame([["AAA", 1 ,2],["BBB", 0, 3],["CCC", 1, 2],["DDD", 0, 0],["EEE", 0, 3]], columns=list('ABC')) A B C 0 AAA 1 2 1 BBB 0 3 2 CCC 1 2 3 DDD 0 0 4 EEE 0 3 </code></pre> <p>and</p> <pre><code>df_t2 = pd.DataFrame...
<p>Using <code>pd.concat</code></p> <pre><code>df_t1 = pd.DataFrame([["AAA", 1 ,2],["BBB", 0, 3],["CCC", 1, 2],["DDD", 0, 0],["EEE", 0, 3]], columns=list('ABC')) df_t2 = pd.DataFrame([["XXX", 4, 1],["YYY", 5 ,6],["ZZZ", 0, 3]], columns=list('ABC')) value_check = [2, 3] for i in value_check: condition = (df_t1['...
python|python-3.x|pandas|dataframe
1
360,751
54,582,416
Python: size of the resulting function of the convolution of two Gaussians with np.convolve
<p>I am interested to optimize a function which is the convolution of two functions. The main problem is that my resulting function is completly of scale and i do not understand what np.convolve actually does.</p> <p>I wrote a small script that should convolve two Gaussian, but the resulting Gaussian is much larger in...
<p>You gotta renormalize for the dx between two x ticks.</p> <p>Numpy is substituting an integration for a summation, but since the functions takes only the Y values it doesn't care about the volume element on the integration axis which you need to include manually.<br> I've had to deal with this problem as well and i...
python|numpy|convolution|gaussian
8
360,752
54,355,095
Cumulative SUM based on ID
<p>QUESTION:</p> <p>I have a dataframe that I import from a "csv" file with pandas that looks like this (simplified example):</p> <pre><code>id amount 1 50 1 10 1 5 2 10 2 15 2 25 2 40 </code></pre> <p>So the idea is to sum the amounts and add the result to all r...
<p>Use <code>pandas.join</code></p> <pre><code>df.join(df.groupby('id').amount.sum(), rsuffix='_', on = 'id') </code></pre> <p>Output:</p> <pre><code> id amount amount_ 0 1 50 65 1 1 10 65 2 1 5 65 3 2 10 90 4 2 15 90 5 2 25 90 6 2 ...
python|pandas
2
360,753
54,271,008
Check whether column values are within range
<p>Here's what I have in my dataframe-</p> <pre><code>RecordType Latitude Longitude Name L 28.2N 70W Jon L 34.3N 56W Dan L 54.2N 72W Rachel </code></pre> <p><strong><em>Note</strong>: The <code>dtype</code> of all the columns is...
<p>If you don't want to modify <code>df</code>, I would suggest getting rid of the <code>apply</code> and vectorising this. One option is using <code>eval</code>.</p> <pre><code>u = df.assign(Latitude=df['Latitude'].str[:-1].astype(float)) u['Longitude'] = df['Longitude'].str[:-1].astype(float) df[u.eval("24 &lt; Lat...
python|pandas|dataframe
3
360,754
54,348,561
Getting Boolean column for value in another column panda dataframe
<p>I have a data frame and would like to create a boolean column called elevator if "Elevator" is in the amenities column.</p> <p><a href="https://i.stack.imgur.com/WZldA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WZldA.png" alt="enter image description here"></a></p> <p>This code generates a ...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>contains</code></a> with <code>na=False</code> for convert <code>NaN</code>s or numeric to <code>False</code>:</p> <p>Also thanks @jpp for idea for improve performance - u...
python-3.x|pandas|dataframe|apply
2
360,755
54,587,424
Pivot Table to fill pairs of observation in pandas
<p>The objective is to get a table with values of pair T1-T2. I have data in form of:</p> <pre><code>df T1 T2 Score 0 A B 5 1 A C 8 2 B C 4 </code></pre> <p>I tried: </p> <pre><code>df.pivot_table('Score','T1','T2') B C A 5.0 8.0 B NaN 4.0 </code></pre> <p>I expected: </p> ...
<p>First add all possible index with columns values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a> with another <code>pivot</code> by swap <code>T1</code> and <code>T2</code> and last <a href="http://pandas.pydata.org/p...
python|pandas|pivot-table
2
360,756
54,323,988
Splitting strings in tuples within a pandas dataframe column
<p>I have a pandas dataframe where a column contains tuples: </p> <pre><code>p = pd.DataFrame({"sentence" : [("A.Hi", "B.My", "C.Friend"), \ ("AA.How", "BB.Are", "CC.You")]}) </code></pre> <p>I'd like to split each string in the tuple on a punctuation <code>.</code>, take the secon...
<p>Use nested list and set comprehension and for test convert sets to <code>bool</code>s - empty <code>set</code> return <code>False</code>:</p> <pre><code>s = set(["Hi", "My"]) p["tmp"] = [bool(set(i.split(".")[1] for i in x).intersection(s)) for x in p["sentence"]] print (p) sentence tmp 0 ...
python|pandas|vectorization
1
360,757
54,444,630
Application of nn.Linear layer in pytorch on additional dimentions
<p>How is the fully-connected layer (<code>nn.Linear</code>) in pytorch applied on "additional dimensions"? The <a href="https://pytorch.org/docs/stable/nn.html#linear" rel="nofollow noreferrer">documentation</a> says, that it can be applied to connect a tensor <code>(N,*,in_features)</code> to <code>(N,*,out_features)...
<p>There are <code>in_features * out_features</code> parameters learned in <code>linear.weight</code> and <code>out_features</code> parameters learned in <code>linear.bias</code>. You can think of <code>nn.Linear</code> working as</p> <ol> <li>reshape the tensor to some <code>(N', in_features)</code>, where <code>N'</...
pytorch|tensor
3
360,758
54,600,621
Compute the intersection of lists for each pair of values in a column
<p>If I have a data set that has 2 columns user_id and their interests and I want to find users having common interests, how can I do that? For example, I will take the first user and his interests and compare it with all other user's common interests individually, then I will take the second user and compare his inter...
<p>Use a dictionary to perform lookup. You can then find combinations of "userid" using <code>itertools.combinations</code> and then just perform set intersection for each "userid' list pair.</p> <pre><code>import itertools m = df.set_index('userid')['interest'].map(set).to_dict() m # {1: {'A', 'B'}, 2: {'A', 'B', '...
pandas|dataframe|combinations
1
360,759
54,369,955
running python with sublime: dtype output is not stable
<p>I tried to run the following codes for several times. The output is sometimes 'True' (what I expected) and sometimes 'False'. Is there something wrong with sublime? I tested it with jupyter notebook and the output is always 'True'.</p> <pre><code>import pandas as pd df = pd.DataFrame({'a':[1,2,3]}) print(df.dtype...
<p>The output of you example is not <code>True</code> it is <code>False</code>. If you do <code>df.dtypes.values</code> you will see it is not the string <code>'int64'</code> it is <code>dtype('int64')</code> so <code>isin(['int64'])</code> should always return <code>False</code> I tested in <code>Jupyter</code> and th...
python|pandas|sublimetext3
1
360,760
54,608,780
Pandas series extract with regular experession
<p>Need to extract the following from Pandas column which has the following values</p> <pre><code>8-9 yrs 7-12 yrs 4-6 yrs </code></pre> <p>Would need 9,12,6 updated in the column .</p>
<p>A DataFrame with <code>df</code> with a column <code>a</code></p> <p><a href="https://i.stack.imgur.com/p5tgp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p5tgp.png" alt="enter image description here"></a></p> <p>using <code>re</code> library with <code>findall</code> function with regex</p> ...
pandas
0
360,761
54,541,962
How to add calculated column to Dataframe counting frequency in column in pandas
<p>I have dataframe like this:</p> <pre><code> county 1 N 2 N 3 C 4 N 5 S 6 N 7 N </code></pre> <p>and what I'd like to reach is:</p> <pre><code> county frequency 1 N 5 2 N 5 3 C 1 4 N 5 5 S 1 6 N 5 7 N 5 </code></pre> <p>Is t...
<p>Map the values from value_counts to the column</p> <pre><code>df['frequency'] = df['county'].map(df['county'].value_counts()) county frequency 1 N 5 2 N 5 3 C 1 4 N 5 5 S 1 6 N 5 7 N 5 </code></pre>
python|pandas|dataframe|countif
14
360,762
54,278,698
Keras - UnknownError: Failed to get convolution algorithm
<p>While working with Keras and Jupyter Notebook, I occasionally get an error (see below for entire error log) once I start training a model. While <a href="https://stackoverflow.com/questions/53698035/failed-to-get-convolution-algorithm-this-is-probably-because-cudnn-failed-to-in">Failed to get convolution algorithm....
<p>I had this problem several times, all of them it was due to a dirty log file that the Saver was trying to restore - the only solution was to delete the last model checkpoint file and restart from the previous one (also removing the line referring the last one in the checkpoint.txt file).</p> <p>Probably this happen...
python|tensorflow|keras
1
360,763
54,328,502
TensorFlow serving S3 and Docker
<p>I’m trying to find a way to use Tensorflow serving with the ability to add new models and new versions of models. Can I point tensorflow serving to an S3 bucket?</p> <p>Also I need it to run as a container? Is this possible or do I need to implement another program to pull down the model and add it to a shared volu...
<p>I found that I could use the <a href="https://www.tensorflow.org/deploy/s3" rel="noreferrer">TF S3</a> connection information (even though it isn't outlined in the TF Serving Docker Container). Example docker run command:</p> <pre><code>docker run -p 8501:8501 -e AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID -e AWS_SECRET_A...
tensorflow|tensorflow-serving
6
360,764
54,635,962
Issue in creating Keras Model Input tensors to a Model must come from `keras.layers.Input`?
<p>for some reason I am trying to create my Keras model but it won't work. I get this error ValueError: Input tensors to a Model must come from <code>keras.layers.Input</code>. Received: (missing previous layer metadata). [Error when creating the model last line]</p> <p>I tried separating the inputs but it didn't wor...
<p>The model only accepts <code>Input</code>s. You can't pass embeddings to the inputs of a model.</p> <pre><code> inputs = [Input(sent_maxlen,), dtype='int32', name='word_inputs'), Input(sent_maxlen,), dtype='int32', name='predicate_inputs') Input(sent_maxlen,), dtype='int32', name='postags_i...
python|tensorflow|keras|nlp
3
360,765
54,304,551
python csv file reading: turning the first row into column headers, next(reader) returns unwanted characters
<p>Currently I'm writing some code to read in csv files with pandas and I need the first row of the file to be read into a list in order to use it for some descriptives (see code Part1). I can just use the <strong>pandas.read_csv</strong> Parameter <code>header=0</code>, which reads out column headers automatically, bu...
<p>You can use the <code>nrows</code> argument to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html#pandas.read_csv" rel="nofollow noreferrer"><code>pd.read_csv</code></a> to read in column labels separately:</p> <pre><code># read in column labels as list cols = pd.read_csv('file.csv'...
python|pandas|csv
1
360,766
54,583,660
Python - Datetime column from one Dataframe and find datetime range from another dataframe
<p>I am new to Python and this is my first question.</p> <p>I have df1: DF1:</p> <pre><code>period id cust_id product_id start_time end_time 20181001 1 aa 2 01/10/2018 19:04 01/10/2018 19:31 20181001 1 zz 9 01/10/2018 15:57 01/10/2018 16:00 20181001 1 zz 178 01/10/2018 13:01 01/10/2...
<p>It looks like you are wanting to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> your two DataFrames, but you have given no criteria. It's not clear why you want to exclude certain entries. </p> <p>See <a href="https:/...
python|pandas|datetime
1
360,767
54,579,775
Indexing a multidimensional array from a list of indices in NumPy
<p>Say I have an array of the form</p> <pre><code>array = np.random.rand(50, 50, 2) </code></pre> <p>and I have a list of tuples of indices, which will contain duplicates:</p> <pre><code>indices = [(0, 2), (0, 3), (0, 2), (1, 1), (0, 3), (0, 2)] </code></pre> <p>I'm trying to figure out the best way to create a sca...
<p>I have a solution, inspired by hpaulj above. I can convert the list of tuples of indices to an array, and use the long dimension of the resulting array to index my large array, like so:</p> <pre><code>index_array = np.array(indices) reduced_array = array[index_array[:,0],index_array[:,1],:] </code></pre> <p>and th...
python|arrays|numpy|plot|indexing
0
360,768
54,519,478
Google OR Tools constraints from DataFrame
<p>I would like to build a Google OR Tools model to use <code>linear_solver</code> for a <code>CBC_MIXED_INTEGER_PROGRAMMING</code>. Following <a href="https://developers.google.com/optimization/mip/integer_opt" rel="nofollow noreferrer">Google tutorial</a> I learned hot to build the constraints but I have a question.....
<p>In fact, OR-Tools doesn't require each constraint to have a unique name. But the following gives them unique names anyway. As mentioned above, if you need to store the constraints, you can do so in an array as follows. Here I'm using the more common notation (A is the constraint coefficients, B is the constraint rig...
python|python-3.x|pandas|constraints|or-tools
1
360,769
54,640,734
Faster way to update a column in a pandas data frame based on the value of another column
<p>I have a pandas data frame with columns = [A, B, C, D, ...I, Z]. There are around ~80000 rows in the dataframe, and columns A, B, C, D, ..., I have value 0 for all these rows. Z has a value between [0, 9]. What I am trying to do is update the value of the x'th column for all rows in the data frame, where x is the cu...
<pre><code>import numpy as np import pandas as pd cols = np.array(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'temp']) df = pd.DataFrame(columns=cols[:-1]) df['Z'] = [9,1,2,3,1,5,4] df = df.fillna(0) df.update(pd.get_dummies(cols[df['Z']])) print(df) </code></pre> <p>yields</p> <pre><code> A B C D E F G H ...
python|pandas|numpy|dataframe
1
360,770
54,410,138
Slicing using arrays/indices
<p>I am trying to iteratively access an numpy array using indices and arrays. The following example pretty much sums up my problem:</p> <pre><code>x = np.arange(12) x.shape = (3,2,2) nspace = np.array([[0,0], [0,1], [1,0], [1,1]]) for it in range(len(nspace)): x[:,nspace(it)] = np.array([1,1,1]) </code></pre> <p>...
<p>You don't need to use the <code>for</code> loop. Use <code>reshape</code> and <code>transpose</code>.</p> <pre><code>x.reshape(3, 4).T </code></pre> <p>Gives: </p> <pre><code>array([[ 0, 4, 8], [ 1, 5, 9], [ 2, 6, 10], [ 3, 7, 11]]) </code></pre> <p>If you wanted to iterate the result:...
python|numpy|numpy-slicing
1
360,771
54,561,682
Is there a way to calculate an equation with n raised to the power of x?
<p>I'm trying to solve x in the following equation using python;</p> <pre><code> 20 = 3^x - x - 4 </code></pre> <p>I've tried with sympy solve() but rather than outputting the result of solving x, it outputs another equation.</p> <p>Current code:</p> <pre><code>x = Symbol('x', integer = True) eqn = Eq(3**x - x - 4,...
<p>Sympy is giving the correct answer here, the answers only happen to be very close to -24 and 3. For example, Wolfram Alpha says the answers are -23.99999999999645929383851407736751424572557264463826050688997713695590353717193719618212151198215945 and 3, see <a href="https://www.wolframalpha.com/input/?i=solve+3%5Ex+...
python|numpy|sympy
-1
360,772
54,349,928
Filling dates in dataframe with triple index
<p>I know that a similiar question to this one has been made, but the solution works when you have only one categorical variable. I have two of those, and <code>MultiIndexes</code> have always been difficult for me to work with. The thing is, I've got the following dataframe:</p> <pre><code> Date Product eCo...
<p>Use a single <code>DatetimeIndex</code> then <code>groupby</code> + <code>resample.asfreq()</code>, (can use sum for numeric columns) as the date range is group dependent. </p> <pre><code>import pandas as pd df['Date'] = pd.to_datetime(df.Date) df = df.set_index('Date') df.groupby(['Product', 'eCommerce'], sort=F...
python|pandas|date|multi-index|fillna
2
360,773
54,367,830
Adding dynamic columns in pandas DataFrame
<p>I have a directory containing around 96 CSV files each containing a variable number of columns in range of [19000 to 23088]. I am trying to open each of the 96 files and copy the first row from them and paste them to an already created CSV file. The code that I am using is as follows-</p> <pre><code># Read CSV file...
<p>To update a single row, assign a series rather than a dataframe. Indexing with <code>slice(0, None)</code> or its more common representation <code>0:</code> returns a dataframe with one row, while indexing with <code>0</code> returns a series.</p> <pre><code>df = pd.DataFrame({'A': [1, 2], 'B': [3, 4], 'C': [5, 6]}...
python|pandas
0
360,774
54,372,054
Filter by either index level or column when I don't know whether my field is an index level or column
<p>I have a DataFrame with a number of index levels and a number of columns. I have a field that I know is either the name of an index level or the name of a column, but I don't know which. I wish to filter my DataFrame on this field. If the field were an index level, I would do <code>df[df.index.get_level_values(field...
<p>Since you mentioned it's either column or index label, then try:</p> <pre><code>if field in list(df.columns): #do df[df[field] == 0] else: #do df[df.index.get_level_values(field) == 0] </code></pre>
python|pandas|dataframe
0
360,775
54,485,235
Creating duplicate rows while updating a single column with multiindex
<p>I am new to pandas. I have a dataframe that keeps tracks of units sold and associated prices for a number of products. I want to create rows for all products that will be for months up until month 12, copying the data from 'price' and 'units'.</p> <p><strong>INPUT</strong></p> <pre><code>df = pd.read_csv('input.cs...
<p>IIUC , may be something like below:</p> <pre><code>months = list(range(1,13)) a = 13-df.loc[df.month.isin(months),'month'] df_new=pd.DataFrame(np.repeat(df.values,a,axis=0),columns=df.columns) df_new.month=df_new.groupby(['name','location'])['month'].apply(lambda x : (x.duplicated().cumsum()+df_new.month).dropna()...
pandas
1
360,776
54,663,076
Sorting pandas dataframe per group and keep desired order
<p>I have a dataframe as shown below</p> <pre><code>df = pd.DataFrame({ "Junk":list("aaaaaabbbcccc"), "Region":['West','West','West','West','East','East','East','South','South','South','North','North','North'], "Sales":[1, 3, 4, 2, 4, 2, 5, 7, 9, 7, 5, 9, 5] }) +------+--------+-------+ | Junk | Region | ...
<p>Create <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html" rel="nofollow noreferrer">ordered categorical</a> column first and then sorting:</p> <pre><code>order = ['West', 'East', 'South', 'North'] df['Region'] = pd.CategoricalIndex(df['Region'], ordered=True, categories=order) df = d...
python|pandas|sorting|dataframe
5
360,777
54,512,133
String matching of two Pandas Series
<p>I have two (address) columns in two different dataframes, each column having a different length and i wish to iterate each element from one column of a dataframe w.r.t the other column of the other dataframe. Meaning, I wish to check if every element in first column of first dataframe, matches with any of the elemen...
<pre><code>import pandas as pd sales1 = [{'account': 'Jones LLC', 'Jan': 150, 'Feb': 200, 'Mar': 140}, {'account': 'Alpha Co', 'Jan': 200, 'Feb': 210, 'Mar': 215}, {'account': 'Blue Inc', 'Jan': 50, 'Feb': 90, 'Mar': 95 }] sales2 = [{'account': 'Jones LLC', 'Jan': 150, 'Feb': 200, 'Mar': 140}, {'acc...
python|string|pandas|string-matching
1
360,778
73,811,389
overriding dataframe row value with another dataframe
<p>df1:</p> <pre><code>|name |favorite animal| |---------|---------------| |Mary |cat | |Benny |shark | |Jack |dog | |Becca |sheep | |Christie |dinosaur | </code></pre> <p>df2:</p> <pre><code>|name |favorite animal| |---------|---------------| |Mary ...
<p>Create a zip list of <code>name</code> and <code>favorite animal</code> for df2 and use <code>replace</code>:</p> <pre><code>lst = list(zip(df2['name'], df2['favorite animal'])) df1['favorite animal'] = df1['favorite animal'].replace(lst) </code></pre>
python|pandas|dataframe
0
360,779
73,610,815
Pyspark API missing Pandas module _libs.arrays
<p>Using apache-spark running on an azure databricks notebook.</p> <pre><code>rdd_s = sc.parallelize(input_dict) rdd_s = rdd_s.map(lambda day: function(day)) results = pd.concat(rdd_s.collect()) #this line produces the error </code></pre> <p>Error:</p> <pre><code>org.apache.spark.SparkException: Job aborted due to stag...
<p>Pandas <strong>concat</strong> method is used to concat 2 DataFrames or Series.</p> <pre><code>pandas.concat(objs, axis=0, join='outer', ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, sort=False, copy=True) </code></pre> <p>rdd_s.collect() would return the list as a result, You are t...
python|pandas|apache-spark
0
360,780
73,832,271
KeyError: "Key 'Record_Path' not found. If specifying a record_path, all elements of data should have the path."
<p>I am trying to organize a json response from a URL into a panda dataframe but I am having issues getting at the nested data.</p> <pre><code>import requests import json import numpy as np from pandas import json_normalize series = 'f1' season = 2022 ssnround = '1' laps = 3 url = &quot;http://ergast.com/api/f1/2011/...
<p>Try to construct dataframe without <code>.json_normalize</code>:</p> <pre class="lang-py prettyprint-override"><code>import requests import pandas as pd url = &quot;http://ergast.com/api/f1/2011/5/laps/1.json&quot; r = requests.get(url=url) df = pd.DataFrame( r.json()[&quot;MRData&quot;][&quot;RaceTable&quot...
python|json|pandas
0
360,781
73,593,683
Get columns from generator object
<p>I'm using Scrapetube to get videos from a channel, and it brings a generator object. From the very simple documentation, I know it includes the parameter &quot;videoId&quot;, but how can I know what other parameters I can get from there? Can I transform a generator object into, say, a dataframe?</p>
<p>Generators allow you to efficiently iterate over (potentially infinite) sequences.</p> <p>In your case, you probably want to first convert the generator into a list to expose all items in the sequence.</p> <p>Then you can inspect what the returned elements look like and extract the information you need.</p> <p>You c...
python|pandas|generator
1
360,782
73,581,752
Similar to pivot table in Python
<p>Here is a dataframe <code>data_1</code>.</p> <pre><code>data_1=pd.DataFrame({'id':['1','1','1','1','1','2','2','2','2','2'], 'date':['20220325','20220325','20220325','20220327','20220327','20220705','20220705','20220706','20220706','20220706'], 'base':[&quot;wt&quot;,&quot;bmi&quot;...
<p>This is a variation on a <code>pivot</code>:</p> <pre><code>(data_1.assign(id2=data_1.groupby(['id', 'date', 'base']).cumcount()) .pivot(index=['id', 'id2', 'date'], columns='base', values='value') .convert_dtypes().astype(str).replace('&lt;NA&gt;', '') [data_1['base'].unique()] .dropleve...
python|pandas|dataframe|merge|pivot-table
0
360,783
73,659,720
How to save tensorflow recommenders framework model
<p>good tuto, thank you to that, but I have a problem to save model to reuse it. I have this error</p> <blockquote> <p>File &quot;C:\Users\guera\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\utils\traceback_utils.py&quot;, line 67, in error_handler raise e.with_traceback(filtered_tb) from None Fil...
<p>thank you for your help, the second method you give me work correctly.</p> <pre><code> model = MovieLensModel(user_model, movie_model, task) model.compile(optimizer=tf.keras.optimizers.Adagrad(0.5)) # Train for 3 epochs. model.fit(ratings.batch(4096), epochs=3) model.save_weights('content_model_...
python|python-3.x|tensorflow|keras
1
360,784
73,558,690
Mode aggregation doesn't work in pandas (Must produce aggregated value)
<p>When running this:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame(dict(x=[1, 1, 2, 2, 3, 3], group=[&quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;b&quot;, &quot;b&quot;])) df.groupby([&quot;group&quot;]).agg({ &quot;x&quot;: [pd.Series.mode, &quot;s...
<p>Because the mode is returning multiple values for group &quot;a&quot;. Changing one of the values, this works because each mode is unique:</p> <pre><code>import pandas as pd df = pd.DataFrame(dict(x=[1, 1, 1, 2, 3, 3], group=[&quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;b&quot;, &quot;b&quot;])...
python|python-3.x|pandas|dataframe
1
360,785
73,660,677
Reconcile with np.fromiter and multidimensional arrays in Python
<p>I am working on coming up with a multi-dimensional array in order to come up with the following result in jupyter notebook.</p> <p>I have tried several codes but I seem not to be able to produce the forth column with the number range of 30 - 35. The closest I have gone is using this code:</p> <pre><code>import numpy...
<p>You can create a flat array with all your subsequent numbers like this:</p> <pre><code>import numpy as np a = np.arange(1, 16) print(a) # output: [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15] </code></pre> <p>Then you reshape it:</p> <pre><code>a = np.reshape(a, (5, 3)) print(a) # output [[ 1 2 3] [ 4 5 6] [ ...
python-3.x|numpy
0
360,786
73,666,326
What is the most effective way for iterate over dataframe and do sql query and then save as dataframe each row in pandas
<p>i have a dataframe like this:</p> <pre><code>import pandas as pd import sqlalchemy con = sqlalchemy.create_engine('....') df=pd.DataFrame({'user_id':[1,2,3],'start_date':pd.Series(['2022-05-01 00:00:00','2022-05-10 00:00:00','2022-05-20 00:00:00'],dtype='datetime64[ns]'), 'end_date':pd.Series(['202...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_records.html" rel="nofollow noreferrer">.to_records</a> to transform the rows to a list of tuples. Then iterate the list and unpack the tuple and pass the args to &quot;your_sql_function&quot;</p> <pre><code>import pa...
pandas|loops
0
360,787
73,773,592
Select rows of data frame based on true false boolean list
<p>I want to select rows of a dataframe based on isin calculations I did using two seperate dataframes.</p> <p>Here is the code:</p> <pre><code>file = r'file path for df' df = pd.read_csv(file, encoding='utf-16le', sep='\t') keepcolumns = [&quot;CookieID&quot;, &quot;CryptID&quot;] df = df[keepcolumns] file = r'file...
<p>Problem is condition and filtered DataFrame has different index values:</p> <pre><code>#condition has index from dfmappe mask = (dfmappe[['CryptIDs']].isin(df[['CryptID']])).all(axis=1) #filtered df - both DataFrames has different indices, so raise error dffound = df[mask] </code></pre> <p>Possible solutions - becau...
python|pandas|indexing
1
360,788
73,608,332
How to convert RGBA_888 to bytebuffer to feed it to tf lite model
<p>I am using camera x to imageAnalysis use case to run tf lite model, I am getting output image format RGBA_8888. How to convert it to bytebuffer to feed it to my ml model.</p> <p>This is the code generated by the android studio for the ml model:</p> <pre><code> // Creates inputs for reference. val inputFeature0 = Ten...
<p>Try this, works for me.</p> <pre><code> TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 400, 600, 3}, DataType.FLOAT32); Bitmap input=Bitmap.createScaledBitmap(bitmap,400,600,true); TensorImage image=new TensorImage(DataType.FLOAT32); image.load(input); ...
java|android|tensorflow|machine-learning
1
360,789
73,659,806
Debugging Neural Network's feedforward propagation
<p>I am implementing a Neural Network's forward propagation.</p> <p>This is my <code>train</code> method:</p> <pre><code>def train(self, x, y): for layer in self.layers: prediction = layer.forward_prop(x.T) # column vector </code></pre> <p>and this is the <code>forward_prop</code> method:</p> <pre><code>de...
<p>I simply solved this way:</p> <pre><code>def train(self, x, y): z = x.T for layer in self.layers: z = layer.forward_prop(z) </code></pre>
python|numpy|deep-learning|neural-network
1
360,790
73,547,886
How to Explode row into multiple rows based on value of another column?
<p>I have a dataframe with values similar to this (values changed for security) and there are around 1000 lines of data here:</p> <pre><code>dataframe = pd.DataFrame({'Subnet.1.1': ['514.71.90', '871.84.0','33.45.16'], 'Difference' : ['10','16','4'], 'Location': ['Alaska', 'Hawaii', 'Maine']}) # Result: ...
<p>I'm sure there has to be a more efficient way to solve this, but this is the best I could come up with for now. The idea is to make a new temporary column containing a list of all the IPs of the subnet and then use the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.explode.html" rel="nofollow...
python|pandas|dataframe|function|row
1
360,791
73,555,018
Can someone explain this please?
<p>I have the following data:</p> <pre><code>0 Ground out of 2 1 1 out of 3 2 1 out of 3 Name: Floor, dtype: object </code></pre> <p>I want to modify this data so that I can create two columns named first floor and max floor.</p> <p>Looking at the first item as an example:</p> <pre><code>0 Ground ...
<p>You loop is written in a wrong order.</p> <p>But anyway, don't use a loop, rather use vectorial string extraction and <code>fillna</code>:</p> <pre><code>df['Floor'].str.extract('^(\d+)', expand=False).fillna(0).astype(int) </code></pre> <p>Or for more flexibility (Ground -&gt; 0 ; Basement -&gt; -1…):</p> <pre><cod...
python|pandas
1
360,792
73,576,299
Building a custom loss function in TensorFlow
<p>I want to create a neural network with my own loss function. For this purpose, I created this loss function:</p> <pre><code>class my_loss(tf.keras.losses.Loss): def __init__(self,e1,e2,**kwargs): assert e1 &gt; e2 , &quot;e1 must be greater than e2&quot; self.e1 = e1 self.e2 = e2 ...
<p>You're getting that error when you do <code>tf.experimental.numpy.select</code>, right?</p> <p>It is because, as the error suggests, you can't use a <code>tf.Tensor</code> as a Python <code>bool</code>. So you cannot do something like this <code>d &gt;= self.e1</code>. You have to use proper tf functions to do that ...
python|tensorflow|keras|loss-function
2
360,793
73,644,038
I am kinda new to the pytorch, now struggling with a classification problem
<p>I built a very simple structure</p> <pre><code>class classifier (nn.Module): def __init__(self): super().__init__() self.classify = nn.Sequential( nn.Linear(166,80), nn.Tanh(), nn.Linear(80,40), nn.Tanh(), nn.Linear(40,1), nn.Softmax() ) def forward (self, ...
<p>The problem is in the network architecture: you are using a <code>Softmax</code> layer on a single valued output at the end. As per the definition of the softmax function, for a output vector <code>x</code>, we have, for index <code>i</code>:</p> <pre><code>softmax(x_i) = e^{x_i} / sum_j (e^{x_j}) </code></pre> <p>H...
pytorch|classification
2
360,794
73,745,666
using integer as index for multidimensional numpy array
<p>I have boolean array of shape <code>(n_samples, n_items)</code> which represents a set: <code>my_set[i, j]</code> tells if sample <code>i</code> contains item <code>j</code>.</p> <p>To populate it, the array is initialized as zeros, and receive another array of integers, with shape <code>(n_samples, 3)</code>, telli...
<p>You only have column indices, so you also need to create their corresponding row indices:</p> <pre><code>&gt;&gt;&gt; my_set[np.arange(len(my_set))[:, None], init_values] = 1 &gt;&gt;&gt; my_set array([[False, True, False, True, True], [ True, True, True, False, False]]) </code></pre> <p><code>[:, None]<...
python|numpy|array-broadcasting|numpy-slicing
1
360,795
73,553,725
How to change column names of Pandas Series object?
<p>I'm trying to prefix the names of the columns for each series in my Pandas Series, based on one of the other columns value. Currently my objective is to change a Pandas Dataframe that contains 3 columns into a Dataframe of only 1 column named 'Data' - or whatever. Below is an example of stacking a Dataframe to obtai...
<p>You can <code>melt</code> instead:</p> <pre><code>df = (df_single_level_cols .astype({'girth': str}) .melt('girth', value_name='Data') .assign(**{'girth': lambda d: d['girth']+d.pop('variable')}) .set_index('girth') ) </code></pre> <p>output:</p> <pre><code> Data girth 20weight 0 40weight ...
python|pandas|dataframe
2
360,796
73,822,849
How do I group by getting 2 specific values within a single column in Python using pandas
<p>How do I extract the two different values (dog and cat) and then combine them under a new Dataframe</p> <p>I tried</p> <pre><code>d = pd.DataFrame({'Animal':['cat', 'dog', 'bird', 'dog', 'bird', 'bird'],'Age':[1,3,5,3,4,2]}) df[(df['Animal'] == 'cat')&amp;(df['Animal']=='dog')] </code></pre> <p>But when trying to lo...
<p>The condition you are using to filter your results is <code>&amp;</code> which in your case, both cat and dog do not happen on the same row. You need to use <code>|</code> (i.e., union).</p> <pre><code>df = pd.DataFrame({'Animal':['cat', 'dog', 'bird', 'dog', 'bird', 'bird'],'Age':[1,3,5,3,4,2]}) df[(df['Animal'] ==...
python|pandas|dataframe|group-by
0
360,797
73,565,934
problem reading panda csv file into python
<p>I have a very elementary csv reading program which does not work</p> <p><code>import pandas as pd</code></p> <h1>Reading the tips.csv file</h1> <pre><code> data = pd.read_csv('tips.csv')` </code></pre> <p>The error messages are long and end with tips.csv not found</p>
<p>Is your csv file in the same folder?</p>
pandas|csv
0
360,798
73,640,983
Find matching value in column and create another column pandas dataframe
<p>Suppose I have the following dataframe:</p> <pre><code>ID Country Employee Location 1 AE Jay AAA 2 AE Mary aa 3 AE Peter bbb 3 AE Peter ddd 6 DK Donk ddd 7 CZ Cesar fff 7 CZ Cesar GGg 7 CZ Cesar 8 CZ ...
<p>Not complicated, but requires many steps:</p> <pre><code>s = (lookup_df.drop_duplicates('Country') .set_index('Country')['Location'] ) out = (df # handle location independently of case .assign(Location=df['Location'].str.casefold()) # identify the correct values by merging .merge(lookup_df.assign(**{...
python|pandas|dataframe|merge|lines-of-code
1
360,799
73,715,631
how to extract the list of values from one column in pandas
<p>I wish to extract the list of values from one column in pandas how to extract the list of values from one column and then use those values to create additional columns based on number of values within the list.</p> <p>My dataframe:</p> <pre><code>a = pd.DataFrame({&quot;test&quot;:[&quot;&quot;,&quot;&quot;,&quot;&q...
<p>This should be what you're looking for. I replaced the nan values with blank cells, but you can change that of course.</p> <pre><code>a = pd.DataFrame({&quot;test&quot;:[&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,[1,2,3,4,5,6,6],&quot;&quot;,&quot;&quot;,[11,12,13,14,15,16,17]]}) ab = a.test.apply(pd.Serie...
pandas
2