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
368,100
45,441,940
Processing Word Data For Input into Scikit-Learn's SVC Algorithm
<p>Let's say people email me with problems they are experiencing with a program. I would like to teach the machine to classify these emails into "issue type" classes based on the words used in each email.</p> <p>I have created two CSV files which respectively contain:</p> <ul> <li>the word contents of each email</li>...
<p>Yes you need to encode the categorical features and the use them then for the SVC.</p> <p>You can use <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.DictVectorizer.html" rel="nofollow noreferrer">DictVectorizer</a> for the <code>data_df</code> features and then <a href="http://...
python|csv|scikit-learn|classification|sklearn-pandas
0
368,101
45,427,828
Difference between tf.nn.batch_normalization and tf.nn.batch_norm_with_global_normalization
<p>I am trying to implement batch normalization using tensorflow and found this <a href="https://stackoverflow.com/questions/33949786/how-could-i-use-batch-normalization-in-tensorflow">nice post</a>. Both functions seem to take similar parameters yet it seems like people use the latter more. </p> <p>Can they be used i...
<p>I guess tf.nn.batch_normalization is better , <br> tf.nn.batch_norm_with_global_normalization method is old version and will deprecate later</p> <p>i think you'll find a better answer <a href="https://stackoverflow.com/questions/48001759/what-is-right-batch-normalization-function-in-tensorflow/48006315#48006315">he...
tensorflow|deep-learning|batch-normalization
0
368,102
45,363,980
Iterating over string to create array of Lat Long coordinates
<p>Elements of a list represent pairs of x and y decimal degree coordinates with a space between respective x and y coordinates formatted as strings: </p> <p><code>'34.894127 29.761515', '32.323574 30.166336', '32.677296 31.961439', '35.298668 31.559237', '34.894127 29.761515</code></p> <p>Thus far I can pick out the...
<p>Where <code>mystring = mystring = "'34.894127 29.761515', '32.323574 30.166336', '32.677296 31.961439', '35.298668 31.559237', '34.894127 29.761515"</code> you could get a list of pairs like so:</p> <pre><code>x = [pair.lstrip().strip("'").split(' ') for pair in mystring.split(',')] # gives: [['34.894127', '29.7615...
python|numpy|gis
3
368,103
45,619,471
Pandas groupby stored in a new dataframe
<p>I have the following code:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'Counterparty':['Bank','Bank','GSE','PSE'], 'Sub Cat':['Tier1','Small','Small', 'Small'], 'Location':['US','US','UK','UK'], 'Amount':[50, 55, 65, 55], 'Amount1':[1,2,3,4]}) df2=df1.grou...
<p>For columns from index add <code>as_index=False</code> parameter or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>reset_index</code></a>:</p> <pre><code>df2=df1.groupby(['Counterparty','Location'])[['Amount']].sum().reset_index() pr...
python|pandas
7
368,104
45,425,934
XGBoost: Feature Names Mismatch
<p>I'm struggling big-time to get my XGBoost model to predict an article's engagement time from its text. First, I get a dataframe representing the features I extracted from the article like this:</p> <pre><code>article_features = pd.concat([tfidf_df, numeric_df_normalized], axis=1) </code></pre> <p>I then train my ...
<p>The problem occurs due to <code>DMatrix..num_col()</code> only returning the amount of non-zero columns in a sparse matrix. Hence, if both train &amp; test data have the same amount of non-zero columns, everything works fine. Otherwise, you end up with different feature names lists. There're currently three solution...
python|pandas|xgboost
4
368,105
45,670,244
unhashable type: 'Dimension' in Keras LSTM
<p>I'm having some trouble with Keras' LSTM. I've reshaped some data into (num_rows, num_timesteps, num_dimensions) but I'm getting an error when I try to fit saying</p> <pre><code> TypeErrorTraceback (most recent call last) &lt;ipython-input-61-a1844d288e79&gt; in &lt;module&gt;() 10 print("Actual input: ...
<p>In case if anyone else has the same problem: Try casting to int, it worked for me. I got this error trying to concat layers after reshaping one of them in the following way:</p> <pre><code>shapes = previous_layer.shape reshape_layer = Reshape( (shapes[1], shapes[3], 1) )(previous_layer) #as the shapes were: (?, sha...
python|tensorflow|keras|lstm
1
368,106
45,427,419
How to delete a batch of rows of a numpy array simultaneously?
<p>I am working on a python project but stuck in a place which disturbs me for hours . I really need your help!!!</p> <p>Here is the question:</p> <p>I got a numpy array X which is very large in size (1300000 × 110) , and I want to delete a batch of rows from the array simultaneously. The indexes of rows for deleting...
<p>There is a NumPy function for this, <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html" rel="nofollow noreferrer"><code>np.delete</code></a>:</p> <pre><code>np.delete(arr, indices_to_be_deleted, axis=0) </code></pre> <p>For example,</p> <pre><code>In [91]: arr = np.arange(20).reshape(...
python|arrays|numpy
1
368,107
45,543,509
Hello, I was working today on tensorflow with R language. library(tensorflow)
<p>I was working today on <strong>tensorflow</strong> with <strong>R language</strong>. </p> <p>But I typed those lines of the code after installing the package of tensorflow: </p> <pre><code>library(tensorflow) sess = tf$Session() hello &lt;- tf$constant("Hello, TensorFlow!") </code></pre> <p>But I got this error m...
<p>After loading the <code>tensorflow</code>, we need to use <code>install_tensorflow</code></p> <pre><code>devtools::install_github("rstudio/tensorflow") library(tensorflow) install_tensorflow() #Using r-tensorflow conda environment for TensorFlow installation ##Determining latest release of TensorFlow...done #Instal...
r|tensorflow
3
368,108
45,447,809
Why does recognition rate drop after multiple online training epochs?
<p>I am using tensorflow to do image recognition on the MNIST dataset. In each training epoch, I picked 10,000 random images and conducted online training with batch size of 1. The recognition rate increased for the first few epochs, however, after several epochs the recognition rate started to drop greatly. (In the fi...
<p><strong>DROPPING ACCURACY</strong></p> <p>You're over-fitting. This is when the model learns false features that are specific to artifacts of the images in the training data, at the expense of important features. One of the main experimental results of any application is to determine the optimal number of trainin...
python|machine-learning|tensorflow|mnist
2
368,109
45,439,833
Seaborn: I just want a log scale
<p>I'm using seaborn to plot some biology data. </p> <p>I just want a distribution one gene against another (expression in ~300 patients), and that's all worked fine and dandy with <code>graph = sns.jointplot(x='Gene1',y='Gene2',data=data,kind='reg')</code></p> <p>I like that the graph gives me a nice linear fit and ...
<pre><code>mybins=np.logspace(0, np.log(100), 100) g = sns.JointGrid(data1, data2, data, xlim=[.5, 1000000], ylim=[.1, 10000000]) g.plot_marginals(sns.distplot, color='blue', bins=mybins) g = g.plot(sns.regplot, sns.distplot) g = g.annotate(stats.pearsonr) ax = g.ax_joint ax.set_xscale('log') ax.set...
python|pandas|data-visualization|seaborn
31
368,110
45,669,786
When I try to install tensorflow I met an error
<p>OS: Ubuntu 16.04. python version is 2.7.12. pip version is 9.0.1. When I type </p> <blockquote> <p>pip install <a href="https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.5.0-cp27-none-linux_x86_64.whl" rel="nofollow noreferrer">https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.5.0-cp...
<p>Thanks a lot for anyone who helps me. I slove this question by using </p> <blockquote> <p>sudo pip install tensorflow</p> </blockquote> <p>instead of using the network address. Luckily, it works.</p>
python|tensorflow|ubuntu-16.04
0
368,111
45,357,377
Python Pandas Column and Fuzzy Match + Replace
<h1>Intro</h1> <p>Hello, I'm working on a project that requires me to replace dictionary keys within a pandas column of text with values - but with potential misspellings. Specifically I am matching names within a pandas column of text and replacing them with &quot;First Name&quot;. For example, I would be replacing &q...
<p><strong>Edit:</strong></p> <p>Changed my solution to use <code>difflib</code>. The core idea is to tokenize your input text and match each token against a list of names. If <code>best_match</code> finds a match then it reports the position (and the best matching string), so then you can replace the token with "Firs...
python|pandas|dictionary|fuzzy-comparison|fuzzywuzzy
1
368,112
45,514,445
Last cell in a column dataframe from excel using pandas
<p>I just had a quick question. How would one go about getting the last cell value of an excel spreadsheet when working with it as a dataframe using pandas, for every single different column. I'm having quite some difficulty with this, I know the index can be found with len(), but I can't quite wrap my finger around it...
<p>If you want the last cell of a dataframe meaning the most bottom right cell, then you can use <code>.iloc</code>:</p> <pre><code>df = pd.DataFrame(np.arange(1,101).reshape((10,-1))) df </code></pre> <p>Output:</p> <pre><code> 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 10 1 ...
python|excel|pandas
4
368,113
45,508,683
Keras binary_crossentropy cost function systematic error with large networks
<p>The title may be too specific and this may also apply to other cost functions as well. Basically I have the dummy setup as below (in my case I have a vastly different architecture, but the problem is always replicated):</p> <pre><code>hidden_units=10000 l2_sparsity = 5e-7 l1_sparsity = 1e-8 mod=Sequential([Dense(h...
<p>There was a regularisation term difference between the two cost functions, which is arguably not that useful in evaluating performance</p>
python|tensorflow|keras|theano
0
368,114
45,445,850
pandas: how to write data in a existing xlsx file in the same sheet without overwriting the old data
<p>I now have a big csv file (18GB) and I want to read it in chunks and then process it.</p> <p>I have two problems here:</p> <ol> <li><p>How can I check whether the last chunk contains NaN since the total length of csv file cannot be divided into integer by chunksize</p></li> <li><p>How can I write the new data into...
<p>If you want to write all chunks into same sheet then try this code:</p> <p>define a variable rowLength, for 1st chunk rowLength should be zero, and increment the value by chunksize</p> <pre><code>rowLength = 0 #for 1st chunk rowLength = rowLength + chunksize </code></pre> <p>then write chun...
python|pandas|csv|readfile
0
368,115
62,694,972
pandas Calculating ratio as values in pivot table
<p>I have a Df which looks like this:</p> <pre><code> tests Machine results 111 A OK 111 A OK 111 A OK 111 A NOK 111 B OK 222 A OK 333 A OK 333 B OK 444 A OK 222 A NOK 222...
<p>Get column for rows that are equal to <code>OK</code>, then run a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html" rel="nofollow noreferrer">crosstab</a> to get your average</p> <pre><code>df = df.assign(passed=df.results.eq(&quot;OK&quot;)) ( pd.crosstab(df.tests, df.Ma...
python|pandas|pivot-table|crosstab
2
368,116
62,568,668
React state is always one step behind while making predictions on uploaded image using Tensorflowjs
<p>I'm developing a React app to classify Pokemon based on Images using Tensorflow.js.</p> <ul> <li><p><em>What I want</em> - Upload an image of a Pokemon, generate predictions for the same Pokemon.</p> </li> <li><p><em>What is actually happening</em> - When I upload an image to make a prediction, the output is always ...
<p>On first sight it looks like the cause could be the missing dependency of &quot;model&quot; in the useEffect that holds the makePredictions function. Since you are using model, and the effect is only triggered when findState.uploadedImage is updated. imageRef is a reference and therefore it doesnt have to be a depen...
reactjs|tensorflow|react-redux|react-hooks|tensorflow.js
1
368,117
62,630,581
model_main.py faster-rcnn CUDA_ERROR_OUT_OF_MEMORY
<p>Description:</p> <p>I am able to train faster-rcnn model with legacy/train.py, but it runs into problem as below when I try to use model_main.py to train with the same config setting. Image resolution: 1920x1080</p> <pre><code>tensorflow/stream_executor/cuda/cuda_driver.cc:890] failed to alloc 8589934592 bytes on ho...
<p>I just found that if I set batch_size to 3, then it works normally. When I set batch_size back to 1, it encounters OOM problem.</p> <p>It is weird and I still don't know why, since it should always save memory with lower batch size.</p> <p>If you encounter the same situation, can try to increase the batch size sligh...
tensorflow|out-of-memory|object-detection|object-detection-api|faster-rcnn
0
368,118
62,793,313
how to get percent from a column
<p>I have a data set with two columns: index (which is the country name) and user_country (which is the count of total users by country).</p> <p>I need to get the percentage of users by country but I'm not sure how to get it. As I have 104 countries I think the best way is to create a for loop but I don't know how to b...
<p>I think you need divide summed values and then multiple by <code>100</code>:</p> <pre><code>df['per'] = df['user_country'].div(df['user_country'].sum()).mul(100) print (df) index user_country per 0 es 329825 62.950790 1 us 129189 24.657166 2 pe 20122 3.840509 3 cl...
python|pandas|loops|dataframe
0
368,119
62,872,365
Write a generic function to calculate a column based specific condition based another column value in pandas
<p>I have a df as shown below.</p> <pre><code>Date t_factor time_in_days 2020-02-01 5 1 2020-02-06 14 6 2020-02-09 23 9 2020-02-03 23 3 2020-03-11 38 40 2020-02-20 ...
<p><code>np.select</code> is the obvious solution here, but since you have pseudocode here why not just run it!</p> <pre><code>if T0 &lt;= time_in_days &lt; T1: t_function = (a1 * time_in_days) + a0 else if T1 &lt; time_in_days &lt;= T2: t_function = 14 else: t_function = (a2 * time_in_days) ** 2 + (a1 * ...
python|pandas
2
368,120
62,890,883
Making line chart of MIS using python and pandas
<p>I have a following dataframe with date as index</p> <pre><code> Apples Oranges Strawberries 07-13-2020 1 5 10 07-14-2020 1 17 4 </code></pre> <p>I have to make the line chart of above dataframe with number of fruits on the Y axi...
<p>Try converting your pandas index to datetime format and try again as below:</p> <pre><code>df.index = pd.to_datetime(df.index, format='%m-%d-%Y', errors='ignore') df.plot(kind=&quot;line&quot;) </code></pre>
python|pandas
2
368,121
62,526,459
Is there a pandas function to convert all the column heads against a particular header row into rows for that particular header
<p>I have a pandas dataframe like this where head wise amounts are available for all categories:</p> <p><a href="https://i.stack.imgur.com/pHqum.png" rel="nofollow noreferrer">Table depicting category wise head wise values where the heads are in the columns</a></p> <p>Now, I want a pandas function to return a dataframe...
<p>You can use <code>pd.melt()</code> to convert your dataframe from a wide to a long format where <code>'CATEGORY'</code> is your identifier variable, and elements under all of the other columns are values and get their own row.</p> <pre><code>new_df = df.melt(id_vars=['CATEGORY'], value_vars = ['ELCH_TOT','FXCH','FPA...
python-3.x|pandas|dataframe|rows
1
368,122
62,626,587
getting data from DFs to put into a main DF
<p>I am trying to get data from a list of dfs into one df.</p> <p>I am using the following code</p> <pre><code>main_df = pd.DataFrame(columns=data.columns[-len_data+1:], index = is_refs) for index, dict in enumerate(dict_lists): df = pd.DataFrame(dict_lists[index]) df = df.reindex(is_refs) main_df = main_d...
<pre><code>df_col = df[df.columns] print(df_col) main_df = main_df.join(df_col) </code></pre>
python|python-3.x|pandas|dataframe
0
368,123
62,546,241
len of nparray inside pandas cell
<p>I have a single Pandas column and each cell inside has a various number of elements of a Numpy array. when trying to obtain the number of elements of the array inside each row, I only get the total number of rows of the column when trying the following:</p> <pre><code>df['elements'] = np.size(df['column']) df['eleme...
<p>You can do</p> <pre><code>df['elements'] = df['column'].str.len() </code></pre>
python-3.x|pandas|numpy
1
368,124
62,640,858
ValueError: Classification metrics can't handle a mix of multilabel-indicator on pretrained CNN
<p>in tensorflow, I intend to tune hyperparams in pre-trained CNN for the image classification tasks. To do so, I used a pre-trained model like <code>vgg16</code> to extract features and used extracted embedded features as inputs for convolutional neural net (CNN). Basically, I place CNN on the top of the pre-trained m...
<p>For multiclass labels to work with sklearn <code>GridSearchCV</code>, the labels should be not be one-hot-encoded. They should be 1d or column vector containing more than two discrete values. Check the <a href="https://scikit-learn.org/stable/modules/multiclass.html" rel="nofollow noreferrer">docs</a> for representa...
python|tensorflow|error-handling|conv-neural-network
2
368,125
62,586,831
Pandas goupby and percentage on same dataframe
<p>I just started learning pandas and numpy recently and a use case where I need to groupby data on the basis of date and calculate the percentage of time the status was up (i.e. count(up)/total_count()) per month.</p> <pre><code> date                         status    2017-08                    ...
<p>We have <code>pd.crosstab</code></p> <pre><code>P_df=pd.crosstab(df.date,df.status,normalize='index')*100 status down up date 2017-08 25.0 75.0 2017-09 50.0 50.0 </code></pre>
python|pandas|numpy|pandas-groupby
2
368,126
62,798,002
grouping by timestamp differences in pandas
<p>I've the following dataframe</p> <pre><code> NUMBER TIMESTAMP 0 67 2020-03-06 12:06:25 1 67 2019-09-20 16:21:45 2 67 2019-09-17 17:54:40 3 67 2019-08-21 19:59:30 4 67 2019-08-13 19:40:26 5 67 2019-06-19 19:45:12 6 67 2019-04-30 20:46:03 7 67 2019-04-29 20:46:03 </c...
<p>Let's try comparing differences with the thresh hold and <code>cumsum</code>:</p> <pre><code>thresh = 30 dt_thresh = pd.to_timedelta(thresh, unit='D') df['NUMBER'] = df['NUMBER'].astype(str) + '_' + \ (df.TIMESTAMP.sort_values() .groupby(df.NUMBER) # added groupby here ...
python|pandas|group-by
1
368,127
62,561,706
How to get an average of row excluding specific value less than or greater than and add new column at last, Python, Pandas
<p>following is my input data frame</p> <pre><code>&gt;&gt;data frame after getting avg a b c d avg 0 1 4 7 8 5 1 3 4 5 6 4.5 2 6 8 2 9 6.25 3 2 9 5 6 5.5 Output required after adding criteria &gt;&gt; a b c d avg avg_criteria 0 1 4 7 8 5 7.5 (&lt;=5) 1 3 4 5 ...
<p>From what I understand, you can try <code>df.mask</code>/<code>df.where</code> after comparing with the mean and then calculate mean:</p> <pre><code>m=df.drop(&quot;avg&quot;,1) m.where(m.ge(df['avg'],axis=0)).mean(1) </code></pre> <hr /> <pre><code>0 7.5 1 5.5 2 8.5 3 7.5 dtype: float64 </code></pre> <h...
python|pandas|average
2
368,128
62,661,616
Python Overlay Different Data into Single Map
<p>i am trying to overlay two sets of latitude and longitude plots so that the first set has points of one color and the second set of points has a different color plotted on the same map. I have tried to share the same axis (ax) but it keeps plotting the points in 2 maps instead of 1 single map with both sets or color...
<p>In your case, you want to plot 3 geodataframes (world, gdf1, and gdf2) on single axes. Then, after you create fig/axes, you must reuse the same axes (say, <code>ax1</code>) for each plot. Here is the summary of important steps:</p> <ol> <li><p>Create figure/axes</p> <p>fig, ax1 = plt.subplots(figsize=(5, 3.5))</p> <...
python|mapping|overlay|geopandas
1
368,129
62,867,934
Fasest way to generate dictionaries from a pandas df without to_dict
<p>I am trying to go from this dataframe:</p> <pre><code> run property low high abs1perc0 in1out0 weight 0 bob a 5 9 1 1 2 1 bob s 5 9 1 1 2 2 bob d 1 10 0 1 2 3 tom a 1 2 1 ...
<p>I recommend save the the output into <code>dict</code> of <code>dict</code> , also do not merge your <code>tuple</code> key to one key , also after we reshape your df, <code>to_dict</code> still work</p> <pre><code>d=df.set_index(['run','property']).stack().unstack(1).to_dict('index') {('bob', 'low'): {'a': 5, 'd': ...
python|pandas
5
368,130
62,638,748
Panda Sequence Grouping than flatern list column
<p>I have this DataFrame</p> <pre><code>data = [[1,'A','a','2020-01-01'], [1,'A','b','2020-01-02'], [1,'A','c','2020-01-03'], [1,'B','a','2020-01-04'], [1,'B','b','2020-01-05'], [2,'A','a','2020-01-06'], [2,'A','b','2020-01-07'], [2,'A','c','2020-01-08'], ...
<p>Convert values to datetimes and then aggregate <code>list</code> by both columns with difference between maximal and minimal values for timedeltas:</p> <pre><code>df_1['date'] = pd.to_datetime(df_1['date']) df = (df_1.groupby(['id','Process']).agg(Process_sub_steps_lst = ('Process_sub_steps',list), ...
python|python-3.x|pandas|pandas-groupby
2
368,131
62,493,458
how to print all values under a column in wikipedia table?
<p>i am scraping COVID-19 data from wikipedia table into pandas dataframe. when i print the cases column in the wikipedia table, i was expecting all the values under column &quot;cases&quot; to be printed but only the last value in the column was printed in dataframe. this is my code below.i want to print all value und...
<p>Your loop overwrites the target values in every iteration, that's why you only get the last row. You need to store these values in a list and THEN convert them to a dataframe.</p> <p>So change your loop to:</p> <pre><code>states = [] cases = [] for items in bsObj.find(&quot;table&quot;,{&quot;class&quot;:&quot;wikit...
pandas|dataframe|beautifulsoup|python-requests|wikipedia
1
368,132
62,640,707
Errors in converting numeric data frame to integer in pandas -- "only integer scalar arrays can be converted to a scalar index"
<p>I have a large dataset and am trying to convert 'object' columns containing only numeric data to 'integer' datatype in python/pandas. With every code I have attempted, I have received the following error:</p> <pre><code>CODE SNIPPET (see below for options I have tried) PATH/frame.py in __setiten__(self, key, value) ...
<p>I found an answer. The problem could be that I am working with an Oracle database connection, I'm not sure. I would still love to hear more comments if anyone has a simpler way to do this in Python, but here's how I did it:</p> <pre><code>#coerce stores all non-convertible values as NA and ignore keeps original valu...
python|pandas|dataframe|typeerror|scalar
0
368,133
62,713,727
Trouble understanding parts of concepts in creating custom callbacks in keras
<pre><code>import keras import numpy as numpy class ActivationLogger(keras.callbacks.Callback): def set_model(self,model): self.model = model //inform the callback of what model we will be calling layer_outputs = [layer.output for layer in model.layers] self.activations_model = keras.models...
<p>Let's say i have an simple model</p> <pre><code>model = Sequential() model.add(Dense(32, input_shape=(784, 1), activation='relu')) model.add(Dense(16, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(4, activation='softmax')) cb = ActivationLogger() cb.set_model(model) </code></pre> <p>Now let me go thro...
tensorflow|machine-learning|keras|deep-learning|neural-network
1
368,134
62,489,900
how to enable GPU visible for ML runtime environment on databricks?
<p>I am trying to run some TensorFlow (2.2) example code on databricks/GPU (p2.xlarge) with environment as:</p> <pre><code>6.6 ML, spark 2.4.5, GPU, Scala 2.11 Keras version : 2.2.5 nvidia-smi NVIDIA-SMI 440.64.00 Driver Version: 440.64.00 CUDA Version: 10.2 </code></pre> <p>I have checked <a href="ht...
<p>Install <code>tensorflow-gpu</code> instead of tensorflow, as that will run primarily on gpu while tensorflow will run primarily on cpu. You won't need to edit the code as it still imports by the alias <code>tensorflow</code></p>
python-3.x|tensorflow|keras|gpu|databricks
0
368,135
62,702,665
Python numpy: floor and ceil decimal values with variable precision (for colorbar of multiple batch plots)
<p>To plot multiple figures in a batch mode, the aim is to define the rounded range for colorbar using <code>np.floor()</code> and <code>np.ceil()</code>. However, if the minimum range is 1.2e-5 then <code>np.floor(1.2e-5)</code> gives 0. instead of 1.e-5, and so on. Precision function cannot be used because there are ...
<p>I don't think you can make it much more efficient. By combining a few statements and trimming some unnecessary <code>astype</code> calls, it can be made a bit shorter:</p> <pre><code>es = 10**np.floor(np.log10(abs(x))) # [1e-5, 1e-3, 1e-1, 1e+2] es[es &gt; 1] = 1 # [1e-5, 1e-3, 1e-1, 1.0] for (xlo, xhi), (elo, ehi) ...
python|numpy|matplotlib|floor|ceil
1
368,136
62,726,333
Create pandas dataframe : map a function over numpy
<p>I am create a pandas dataframe and using numpy to simulate values. I'd like to assign randomly generated ids to two columns in pandas, for which, I wrote a function that returns alphanumeric ids.</p> <p>However, with my current code, it only calls the function once and returns same ids for all rows. I need unique id...
<p>You need to call get_ids once for every cell, and not once for every column:</p> <pre><code>df = pd.DataFrame({ 'LeaseID': [gen_ids(10) for _ in range(1000)], 'PropertyID': [gen_ids(10) for _ in range(1000)], 'xyz': np.random.choice(List1, 1000), ...
python|pandas|numpy|dataframe
2
368,137
62,477,001
How to handle records in dataframe with same ID but some different values in columns in python
<p>I am working on a dataframe using pandas with bank (loan) details for customers. There is a problem because some unique loan id have been recorded 2 times with different values for some of the features respectively. I am attaching a screenshot to be more specific.<a href="https://i.stack.imgur.com/gLrjr.png" rel="no...
<p>Count rows where there are > 1, and then only drop nans where there are > 1 rows.</p> <pre><code>df['flag'] = df.groupby(['Loan ID', 'Credit ID'])['Loan ID'].transform('count') df = df.loc[df['flag'] &gt; 1].dropna(subset=['Credit Score', 'Annual Income']).drop('flag', axis=1) </code></pre>
python|pandas|dataframe|unique
1
368,138
62,505,100
Import CSV from AWS S3 instance to Numpy
<p>I've been trying to directly read a csv file from AWS S3 to numpy. I've used:</p> <pre><code>s3 = boto3.client(service_name = 's3') def s3_read(filename): s3_obj = s3.get_object(Bucket = 'bucket-name', Key = filename) body = s3_obj['Body'] return body.read() </code></pre> <p>as an attempt to pull the da...
<p><code>body.read()</code> returns bytes.</p> <pre><code>import json j = json.loads(s3_obj['Body'].read().decode('utf-8')) </code></pre> <p><code>decode</code> will turn bytes to string, <code>json.loads</code> will parse the string to dictionary.</p>
python|amazon-web-services|numpy|csv|amazon-s3
4
368,139
62,738,047
Create a NxN array for all diagonals
<p>Given an integer n, create nxn nummy array such that all of the elements present in both its diagonals are 1 and all others are 0</p> <p>Input: 4</p> <p>Output</p> <pre><code> *[[1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 1, 0], [1, 0, 0, 1]]* </code></pre> <p>how do i achieve this array?</p>
<p>You can use the <code>fill_diagonal</code> to fill the elements in the principal diagonal and use it with <code>np.fliplr</code> to fill elements across the other diagonal. Refer <a href="https://numpy.org/doc/stable/reference/generated/numpy.fill_diagonal.html" rel="nofollow noreferrer">link</a></p> <pre class="lan...
python|numpy|numpy-ndarray
3
368,140
62,584,912
Keras Tokenizer sequence to text changes word order
<p>I am training a model on DUC2004 and Giga word corpus, for which I am using Tokenizer() from keras as follows:</p> <pre><code>tokenizer = Tokenizer(num_of_words) tokenizer.fit_on_texts(list(x_train)) #convert text sequences into integer sequences train_seq = tokenizer.texts_to_sequences(x_train) val_seq = ...
<p>Your <code>X_train</code> should be a list of raw text where each element of this list corresponds to a docuemnt (text). Try below code:</p> <pre><code>x_train = ['chechen police were searching wednesday for the bodies of four kidnapped foreigners who were beheaded during a botched attempt to free them', 'I ...
python|tensorflow|keras|nlp|tokenize
0
368,141
62,886,372
Find mean from a categorical variable of range (e.g. mean of 30-35) in Python
<p>I'd like to calculate the mean of a category variable of range. Here is the example:</p> <pre><code>dt = {&quot;var1&quot;: [&quot;1-2&quot;, &quot;3-4&quot;,&quot;6-8&quot;,&quot;Missing&quot;], &quot;Wanted result&quot;: [&quot;1.5&quot;, &quot;3.5&quot;,&quot;7&quot;,&quot;Missing&quot;]} pd.DataFrame(dt) ...
<p>You can <code>split</code> the with <code>to_numeric</code></p> <pre><code>s=df.var1.str.split('-',expand=True).apply(pd.to_numeric,errors='coerce').mean(axis=1).fillna(df.var1) 0 1.5 1 3.5 2 7 3 Missing dtype: object df['wanted']=s </code></pre>
python|pandas|dataframe
2
368,142
62,720,065
Rename column that is set as index
<p>I am working with script that pulls stock data from yahoo, in order to use it I need to change the column names so that they are all lower case. This works fine on all other columns except &quot;Date&quot; which is not changing for some reason. I tried renaming the columns before <code>set_index</code> but then the ...
<p>For renaming indexes, you have to do</p> <pre><code> df.rename(columns={'High':'high', 'Low':'low', 'Open':'open', 'Close':'close', 'Volume':'volume', 'Adj Close':'adj close'}, inplace=True) df.inde...
python|pandas|csv|stock
1
368,143
62,701,631
Return value based on condition from multiple columns
<p>I have a dataframe with 4 columns, Basically i am trying to create another column and return values meeting condition using if statement</p> <pre><code>If NR/HL1 is not equal to 0, then outputColumn(NR/HL) = NR/HL1 if NR/HL1 is equals to 0, then outputColumn(NR/HL) = NR/HL2 if NR/HL1 is equals to 0 and NR/HL2 is e...
<p>First of all you should try avoid using <code>apply</code> in favour of vectorization since the performance is way better. Then you can use conditions in order to obtain your desired output:</p> <pre><code>df = pd.DataFrame({&quot;SKU&quot;: [123, 456, 567, 890], &quot;NR/HL1&quot; : [10, 0, 0, 10], &quot;NR/HL2&quo...
python|excel|pandas|numpy
0
368,144
62,476,250
How to run a pre-trained pytorch model on the GPU?
<p>Here I am trying to use the mobilenetv2 mobile to train on a custom dataset. I can get it to work on the CPU, but I would prefer to run it on the GPU. Instead, I am getting errors like these:</p> <p>RuntimeError: Expected object of backend CPU but got backend CUDA for argument #2 'weight'</p> <p>RuntimeError: Expe...
<p>As the RuntimeError said, some weights are still in cpu. One possible flaw I suspect is <code>MobileNet.classifier = nn.Sequential(nn.Linear(1280, 1000), nn.ReLU(), nn.Dropout(0.5), nn.Linear(1000,3), nn.LogSoftmax(dim=1))</code> is done after <code>MobileNet.cuda()</code>, which mean these new created weight probab...
pytorch
1
368,145
62,676,123
Pandas Converting date string (only month and year) to datetime
<p>I am trying to convert a datetime object to datetime. In the original dataframe the data type is a string and the dataset has shape = (28000000, 26). Importantly, the format of the date is MMYYYY only. Here's a data sample:</p> <pre><code> DATE Out[3] 0 081972 1 ...
<p>First if error is raised obviously some datetimes not match, you can test it by <code>errors='coerce'</code> parameter and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isna.html" rel="noreferrer"><code>Series.isna</code></a>, because for not matched values are returned missing val...
python|pandas|string-to-datetime
11
368,146
62,871,041
How to get the angle between two vectors in pygame?
<p>I want my player to look towards some certain coordinates in pygame. I tried to do this by getting the angle between the position of the player and the coordinates and then rotating it the player by that angle. I used a function for this ,the function works properly when I need my player to look towards the coordina...
<p>I recommend to use <a href="https://www.pygame.org/docs/ref/math.html#pygame.math.Vector2" rel="nofollow noreferrer"><code>pygame.math.Vector2</code></a> / <a href="https://www.pygame.org/docs/ref/math.html#pygame.math.Vector2.angle_to" rel="nofollow noreferrer"><code>angle_to()</code></a> to compute the angle betwe...
python|numpy|pygame|angle
1
368,147
62,794,806
Pandas Dataframe column to python list
<p>I have a Pandas data frame with duplicate values and I want to convert into python list in alphabetical order.</p> <pre><code>print(df) items 0 Shoes 1 Shoes 2 Jacket 3 Basket 4 Shoes 5 Umbrella 6 Basket 7 Jacket output=['Bas...
<p>Please try below code</p> <pre><code>output= df.sort_values(by=['items'])['items'].drop_duplicates().tolist() </code></pre>
python|pandas
3
368,148
62,751,576
Pandas merge dataframe with condition
<p>Suppose that I have df1 and df2 that looks like this:</p> <pre><code> df1: start end group index a 1 3 x a 3 6 x a 6 9 z b 1 7 y b 7 15 x b 15 17 y c ...
<p>Assuming, both the dataframes have equal length, you can achieve this easily with np.where</p> <pre><code>np.where((df2.value&gt;=df1.start) &amp; (df2.value&lt;df1.end), df2.group=df1.group, df2.group=0) </code></pre> <p>This evaluates your condition, and if it is False, df2.group is set to 0.</p>
python|pandas|dataframe|merge
0
368,149
62,855,389
Method to dynamically build large dataframe (spark or pandas) for export to csv
<p>I have a csv that I import into databricks using spark.read. This large file contains records/transactions on a daily level. I trim the dataframe down to 5 columns and leave the 500,000 rows as-is. I am trying to build a summary table of this source file that represents these records/transactions at a month level...
<p>IIUC You are doing a lookup on country and stock to restrict the rows then grouping over them to generate the aggregations.</p> <p>Why not filter the df's altogether then grouping</p> <pre><code>df = dataBeforeImpactDate df = df.filter(col('country').isin(country_lookup) &amp; col('stock').isin(stock_lookup)) df =...
python|pandas|apache-spark|pyspark|databricks
1
368,150
62,880,084
Is there a straightforward way to generate two numpy arrays from one based on one logical test?
<p>Is there a straightforward way to generate two numpy arrays from one based on one logical test?</p> <pre><code>import numpy as np x = np.array([1,2,3,4,5,6,7,8]) y = x[x%2==0] z = x[x%2==1] </code></pre> <p>I don't want to perform the second test for z. Obviously z is simply x with elements from y removed. Can I sim...
<p>With the new dtype aware sort functions it is actually pretty fast to argsort and split the condition array:</p> <pre><code>def pp(): order = cond.argsort(kind=&quot;stable&quot;) if cond[order[0]]: return a[:0],a elif not cond[order[-1]...
python|numpy|numpy-slicing
0
368,151
62,684,451
Repeat summary for all columns in Pandas Python
<p>I have a pandas dataframe that includes over 100 categorical columns, and two numeric columns. For example, in the data below I only included four categorical columns, for simplicity:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame({ 'Gender': ['M','M','F'...
<p>First parametrize plots / statistics, for example make function or procedure:</p> <pre><code>def plot_stats(column): #Show the distribution of the column, both count and percent print((df[column].value_counts(sort=False, normalize=False))) print((df[column].value_counts(sort=False, normalize=True))*100) ...
python|pandas|repeat
3
368,152
62,557,092
Output of numpy.where
<p>I noticed a strange thing concerning the output of numpy.where. According to the <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer">documentation</a> the output should be of type ndarray. If I provide all arguments (including also the optional ones) this is true, e....
<p>The answer is in the <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer">documentation you provided</a>:</p> <blockquote> <p>When only condition is provided, this function is a shorthand for <code>np.asarray(condition).nonzero()</code>.</p> </blockquote> <p>Looking a...
python|numpy|where-clause
0
368,153
62,621,797
parse time zone and convert to daylight saving time
<p>I have a pandas dataframe with a <code>Datetime</code> column:</p> <pre><code> Datetime 0 2019-01-01 17:02:00 1 2019-01-01 17:03:00 2 2019-01-01 17:04:00 3 2019-01-01 17:05:00 ... </code></pre> <p>The datetimes are in Eastern Standard Time (EST) WITHOUT Daylight savings adjustment...
<p>Recap: you basically have datetime objects which are UTC-4 (EST), there is no transition to EDT (UTC-5).</p> <p>What you could therefore do is localize from naive datetime to UTC by adding a timedelta of 4 hours and subsequently convert to CT:</p> <pre><code>import pandas as pd # df with naive datetime objects that...
python|pandas|dataframe|datetime|dst
1
368,154
62,597,115
How to properly format a filepath on Windows when using Pandas?
<p>I'm a beginner Pandas users and when trying to read this CSV file with Pandas, it cannot find the file.</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df = pd.read_csv('D:\Python\datasets\tweets') Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File ...
<p>If you're sure the file exists in that directory, it could be as you're using backslash, that <code>\t</code> from <code>\tweets.csv</code> has been interpreted as a tab character.</p> <p>In Windows you need to be mindful when providing paths to Python with backslash.</p> <p>As I pointed in the comment, <code>r, n, ...
python|pandas|dataframe
0
368,155
62,599,732
What is the correct way to add a list as a column to a dataframe?
<p>I want to add a list as a new column to a dataframe. I am doing:</p> <pre><code>df['Intervention'] = interventionList </code></pre> <p>It gives me</p> <pre><code>SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame </code></pre> <p>I read <a href="https://stackoverflow.com/questi...
<p>I believe one option would be to use:</p> <pre><code>df.assign(Intervention = interventionList) </code></pre> <p>or to make a copy of the dataframe:</p> <pre><code>df2 = df.copy() </code></pre>
python|pandas
1
368,156
62,481,829
How to pick/configure AWS GPU Instances to speed up TensorFlow.keras?
<p>I have a LSTM tf.keras model with about 600MB of training data. It takes about 90 seconds for each training epoch. I have the latest version of tensorflow, which is v2.2. It runs on an AWS g3.4xlarge instance. This instance has the Tesla M60 GPU from Nvidia and has 8GB of RAM for the GPU.</p> <p>I want to do hyperp...
<p>The amount of time to run each epoch will obviously be the same until you don't change anything in the network. Just running it on a bigger GPU is not the answer here.</p> <p>First of all if you can change your network to reduce the number of parameters then it will be great. So, reducing your model is obviously th...
performance|tensorflow|keras|nvidia|tensorflow2.x
1
368,157
62,534,704
Indices of two numbers equal to a target value
<p>I was trying to solve this problem and I got stuck at the end. This function takes a list consisting of integers and a target value.The <strong>indices</strong> of any <strong>two</strong> sum of integers which is equal to the target value should be returned. For Eg: - ([1,2,3],4) should return [0,2] because 3+1=4...
<p>You can do it without loop by calculating all combinations of pairwise summation of elements using numpy broadcasting and then searching for target using <code>np.argwhere</code> (if your arrays are too large, using itertools might be slightly more efficient as this one calculates every combination twice, however it...
python|python-3.x|numpy|sum
2
368,158
62,694,555
Filtering array of arrays (best approach)
<p>Input: <code>X = [[0, 2, 4], [1, 4], [2, 0], [3], [4, 0, 1]]</code></p> <p>So I have this array where I have to iterate through to filter it as follow:</p> <p><code>X[0] = [0, 2, 4]</code> so I have to remove every 0, 2 and 4 from all succeeding arrays to get:<code>X = [[0, 2, 4], [1], [], [3], [1]]</code></p> <p><c...
<p>Here is a solution if orders in inner lists doesn't matter:</p> <pre><code>from django.contrib.admin.utils import flatten X = [list(set(X[i])-set(flatten(X[:i]))) for i in range(len(X))] </code></pre> <p>output:</p> <pre><code>[[0, 2, 4], [1], [], [3], []] </code></pre>
python|arrays|list|numpy
0
368,159
62,807,359
Pandas: Loop for specific column values
<p>This is a very short trace. But the original file is too huge<br/></p> <pre><code>highest_layer,transport_layer,src_ip,dst_ip,src_port,dst_port,ip_flag,packet_length,transport_flag,time,timestamp,geo_country,data DNS,UDP,192.168.1.6,172.217.12.131,32631,53,0,89,-1,2020-06-10 19:38:08.863846,1591832288863,Unknown, DN...
<p>I created a table by combining it with the original DF after a subsequent grouping from your code. I made a graph based on that table.</p> <pre><code>df2 = df1[['src_port','packet_length']].groupby('src_port')['packet_length'].transform('cumsum').to_frame() df2.columns = ['cumsum_packets'] df3 = pd.concat([df1,df2],...
python|pandas
0
368,160
62,518,640
TypeError: 'NoneType' object is not iterable adding layers in keras
<p>I was trying to run the following code for creating a network in keras:</p> <pre><code>import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras import backend as K import numpy as np (x...
<p>This error occurs when you are trying to iterate over a <code>None</code> value (i.e. the variable has no value). You can see <a href="https://stackoverflow.com/questions/3887381/typeerror-nonetype-object-is-not-iterable-in-python">here</a> a similar post.</p> <p>With the stacktrace you should be able to identify th...
python|tensorflow|keras|deep-learning
0
368,161
54,667,126
Python pandas format datetime.datetime objects that are added to list
<p>The df this is going through has the countries as column names and the dates in the first row.</p> <p><a href="https://i.stack.imgur.com/MK3Ie.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MK3Ie.png" alt="enter image description here"></a></p> <p>What Im trying to do is check for each country ...
<pre><code>import pandas as pd import datetime df = pd.DataFrame({ "Date": [ datetime.datetime(2017,1,1,0,0,0),datetime.datetime(2018,1,1,0,0,0),datetime.datetime(2019,1,1,0,0,0), ], "Country":["Worked","Uploaded","Worked"], }) dates = df[df["Country"]=="Worked"]["Date"].dt.strftime("%Y%m").tolist()...
python|pandas|datetime
1
368,162
54,403,819
Remove rows that are not duplicated n time
<p>I have a df with 4 observations per company (4 quarter). However, for several companies I have less than 4 observations. When I don't have the 4 quarters for a firm I would like to delete all observations relative to the firm. Any ideas how to do this ? </p> <p>This is how the df looks like:</p> <pre><code>Quarter...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>transform</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>size</code></a...
python|pandas
4
368,163
54,407,144
Is it possible to configure docker-nvidia for use with tensorflow-serving while hosting the docker virtual machine on Windows?
<p>I have noticed while looking at <a href="https://www.tensorflow.org/serving/docker" rel="nofollow noreferrer">tensorflow serving's</a> guide for setting up tf serving with GPU support that it involves using <a href="https://github.com/NVIDIA/nvidia-docker#quick-start" rel="nofollow noreferrer">nvidia's docker</a> wh...
<p>I don't believe NVIDIA has any <a href="https://github.com/NVIDIA/nvidia-docker/wiki/Frequently-Asked-Questions#is-microsoft-windows-supported" rel="nofollow noreferrer">intention</a> on creating <code>nvidia-docker</code> for Windows, or at least not in the foreseeable future, since it would require creating Window...
linux|windows|docker|tensorflow-serving
1
368,164
54,275,436
Applying any optimization causes values to be NaN
<p>I am working on a classifier model for this data set: <a href="https://archive.ics.uci.edu/ml/datasets/ILPD+%28Indian+Liver+Patient+Dataset%29" rel="nofollow noreferrer">https://archive.ics.uci.edu/ml/datasets/ILPD+%28Indian+Liver+Patient+Dataset%29</a> and I have come up with this code in pytorch:</p> <pre><code>i...
<p>The problem is that you're using <code>softmax</code> with <code>NLLLoss</code>, which doesn't work together. The <a href="https://pytorch.org/docs/stable/nn.html#torch.nn.Softmax" rel="nofollow noreferrer">documentation</a> on <code>softmax</code> states:</p> <blockquote> <p>This module doesn’t work directly wit...
pytorch
2
368,165
54,682,203
Create a new ID column based on conditions in other column using pandas
<p>I am trying to make a new column 'ID' which should give a unique ID each time there is no 'NaN' value in 'Data' column. If the non null values come right to each other, the ID remains the same. I have provided how my final Id column should look like below as reference to better understand. Could anyone guide me on t...
<p>Using <code>factorize</code></p> <pre><code>v=pd.factorize(df.Data.isnull().cumsum()[df.Data.notnull()])[0]+1 df.loc[df.Data.notnull(),'Newid']=v df.Newid.fillna(0,inplace=True) df Id Data Newid 0 0 NaN 0.0 1 0 NaN 0.0 2 0 NaN 0.0 3 1 54.0 1.0 4 1 55.0 1.0 5 0 NaN ...
pandas
1
368,166
54,507,769
In pandas, how to check if two strings match multiple columns in any of the rows in existing data frame and delete it
<p>I have a dataframe that looks like this</p> <pre><code> rootID parentID jobID time counter 0 A B D 2019-01-30 14:33:21.339469 0 1 E F G 2019-01-30 14:33:21.812381 0 2 A ...
<p>I would</p> <pre><code>root_id, parent_id, job_id = get_ids() # e.g. ('A', 'B', 'T') cond = df.rootID.eq(root_id) &amp; df.parentID.eq(parent_id) &amp; df.jobID.eq(job_id) df.loc[cond, ['time', 'counter']] = datetime.datetime.now(), df.loc[cond, 'counter']+1 </code></pre> <p>This would update your data frame <co...
python|pandas|dataframe
1
368,167
54,539,396
Distributing a Keras Model Across Multiple GPUs
<p>I'm trying to create a very large Keras model and distribute it across multiple GPUs. To be clear I'm not trying to put multiple copies of the same model on multiple GPUs; I'm trying to put one large model across multiple GPUs. I've been using the multi_gpu_model function in Keras but based off a lot of the out of m...
<p>You may use Estimator API. Convert your model using <code>tf.keras.estimator.model_to_estimator</code> </p> <pre><code>session_config = tf.ConfigProto(allow_soft_placement=True) distribute = tf.contrib.distribute.MirroredStrategy(num_gpus=4) run_config = tf.estimator.RunConfig(train_distribute=distribute) your_netw...
python|tensorflow|keras
1
368,168
54,284,274
TensorFlow How to Initialize Global Step
<p>So I'm trying to run a training session, and when I do I get this error when trying to run my algorithm (when I use <code>tf.train.get_global_step()</code>):</p> <p><code>ValueError: global_step is required for exponential_decay.</code></p> <p>For some reason, <code>tf.train.get_or_create_global_step()</code> does...
<p>Although <a href="https://www.tensorflow.org/api_docs/python/tf/train/get_or_create_global_step" rel="nofollow noreferrer"><code>tf.train.get_or_create_step()</code></a> is perfectly fine, here is another solution:</p> <pre><code>g_step = tf.get_variable('global_step', trainable=False, initializer=0) learning_rate...
python|tensorflow
4
368,169
54,387,659
How to fix ' ImportError: cannot import name 'numpy_type_map' ' in Python?
<p>I've followed the instructions in <a href="https://github.com/roytseng-tw/Detectron.pytorch" rel="nofollow noreferrer">Detectron</a> and I've configured it several times: the code compiles as it should. When it comes to run the code, I get this error:</p> <pre><code> Traceback (most recent call last): File "...
<p>Yeah, these are due to Pytorch version mismatch. Solution depends on what extent you are willing to go, sometimes if you are okay with hacking and just getting it running, then just copy paste the <code>numpy_type_map</code> from older versions:</p> <pre><code>numpy_type_map = { 'float64': torch.DoubleTensor, ...
python|pytorch|object-detection
1
368,170
54,420,479
Defining colour if index contains certain string
<p>I have the following dataframe (for example)</p> <pre><code> Value Sample_A_1 5 Sample_B 1 Sample_A_2 2 Sample_D 3 Sample_F 4 </code></pre> <p>and wish to run <code>df['Value'].plot(kind='bar')</code> If I want to define a colour for the bar whenever the index string contains <code>Sample_A</co...
<p>Idea is create dictionary for specify colors by values contains index, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>extract</code></a> values and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.map.html...
python|pandas|dataframe|matplotlib|bar-chart
3
368,171
54,577,207
Assign values based on multiple conditions
<p>My dataframe looks like this:</p> <pre><code> timestamp price amount amount_f status eth_amount 0 2018-11-30 13:48:00 0.00348016 10 0 cancelled 0.000000 1 2018-11-30 13:48:00 0.00350065 10 0 cancelled 0.000000 2 2018-11-30 13:50:00 0.00348021 10 0 cancelled 0.000000 3 20...
<p>You can use <a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.select.html" rel="noreferrer"><code>np.select</code></a> for this, which allows you to select from a list of values (<code>choicelist</code>) depending on the results of a list of conditions:</p> <pre><code>c1 = df.amount == df.a...
python|pandas|numpy
5
368,172
54,494,875
How to select a subset of mnist training set
<p>I have trouble on how to select a subset of mnist training set which contains M points to train the 1-NN classifier because the number of original training points are too large. </p> <p>That is , I need to figure out a scheme that takes as input a labeled training set as well as a number M, and return a subset.of t...
<p>One option could be to train your network with a a data-generator. It loads only one batch of data step for step. You will not have issues with your data anymore. Furthermore, it is able to use multithreading. So loading and maybe preprocessing of your data is not a bottleneck.</p> <p>Here is a good example: <a hre...
python|tensorflow|scikit-learn|training-data|mnist
0
368,173
54,694,082
TypeError when fitting curve
<p>I'm trying to fit a curve to some data that I have but for some reason I just get the error "'numpy.float64' object cannot be interpreted as an integer" and I don't understand why or how to fix it. Would be grateful for some help, the code is below: </p> <pre><code>import numpy as np import matplotlib.pyplot as plt...
<p>Your problem is that your arguments, <code>mud</code> and <code>F</code> are lists, not arrays, which means that you cannot just multiply them with a number. Hence the error. If you define those parameters as <code>np.ndarray</code>s, it will work:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt f...
python|numpy|curve-fitting|least-squares
1
368,174
54,622,993
Errors running commands in parallel with python multiprocessing
<p>I am trying to parallelize several command line calls in python, using PyCharm IDE. However I am getting some odd errors which I do not understand.</p> <pre><code>from generate_command_list import create_list import multiprocessing import subprocess x = create_command_list().values def execute_commandline_call(ex...
<p><strong>x</strong> may not pickle correctly or rely something not pickle correctly?</p> <p>try:</p> <pre class="lang-py prettyprint-override"><code>x = [str(cmd) for cmd in create_command_list().values] </code></pre>
python|pandas|multiprocessing|python-multiprocessing|multiprocess
0
368,175
54,383,285
Conditionally align two dataframes in order to derive a column passed in as a condition in numpy where
<p>I come from a SQL background and new to python. I have been trying to figure out how to solve this particular problem for awhile now and am unable to come up with anything. </p> <p>Here are my dataframes</p> <pre><code>from pandas import DataFrame import numpy as np Names1 = {'First_name': ['Jon','Bill','Billing'...
<p>If your starting strings differ in length, you can use <code>.str.extract</code></p> <pre><code>df['like_flag'] = df['First_name'].str.extract('^('+'|'.join(df_2.name)+')') df['like_flag'] = df['like_flag'].fillna(df.First_name) # Fill non matches. </code></pre> <hr> <p>I modified <code>df_2</code> to be</p> <p...
python|pandas|numpy|array-broadcasting
3
368,176
54,310,872
pandas.read_csv slow when reading file with variable length string
<p>I have an issue which I think I somewhat solved but I would like to learn more about it or learn about better solutions.</p> <p>The problem: I have tab separated files with ~600k lines (and one comment line), of which one field (out of 8 fields) contains a string of variable length, anything between 1 and ~2000 cha...
<ol> <li>You didn't mention what means <em>slow</em> to you, but if: <ul> <li>your file contains ca. 600k rows,</li> <li>each row contains 1-2000 characters (let's say 1000 in average, so each line has ca. 1000B),</li> </ul></li> </ol> <p>then this file's size is: 600 000 * 1000B ~ 570 MB. It's a lot, especially if y...
python|pandas|csv|dataframe
2
368,177
54,517,485
How to group by column and drop or separate values in pandas?
<p>I have a pandas dataframe with three columns.</p> <p>I want to group the dataframe by column 3 and it works, but my problem is in the display of the values of the other columns. </p> <p>For row one, the values will always be the same, but instead of displaying the same value twice for that row in the output, I wan...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.agg</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.first.html" rel="nofollow no...
pandas|pandas-groupby
0
368,178
54,406,180
ELI5 explain_weights and explain_predictions as pandas DataFrame
<p>How can I save ELI5 <code>explain_weights</code> and <code>explain_prediction</code> as pandas DataFrame?</p> <p>Example toy code below.</p> <pre class="lang-py prettyprint-override"><code># Load the dataset as DataFrame import pandas as pd from sklearn.datasets import load_iris df = pd.DataFrame(load_iris().data,...
<p>Try this. It worked for me.</p> <pre><code>explanation_pred = eli5.explain_prediction_df(estimator=my_model, doc=X_test.iloc[0]) </code></pre>
pandas|keras|scikit-learn
1
368,179
54,609,638
How to get max value of a alphanumeric string in column?
<p>I have a df that looks like this:</p> <p>ID:</p> <pre><code>20190126T153450495Ztest1@test1.com 20190126T155922394Ztest2@test2.com 20190126T164741292Ztest3@test3.com 20190126T160108969Ztest4@test4.com 20190205T000624869Ztest5@test5.com </code></pre> <p>How do I get the the maximum value in the <code>ID</code> colu...
<p>Get first <code>18</code> values, convert to <code>datetime</code>s and get index of maximal value, last select by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.at.html" rel="nofollow noreferrer"><code>at</code></a> or <code>loc</code>:</p> <pre><code>idx = pd.to_datetime(df['ID'].str...
python-3.x|pandas|dataframe
1
368,180
54,442,997
"TypeError: bad operand type for unary ~: 'float'" not down to NA (not available)?
<p>I'm trying to filter a pandas data frame. Following @jezrael's answer <a href="https://stackoverflow.com/a/54439631/575530">here</a> I can use the following to count up the rows I will be removing:</p> <pre class="lang-python prettyprint-override"><code>mask= ((analytic_events['section']==2) &amp; ~(analyti...
<p>I believe you need filter by first condition and then again in filtered values:</p> <pre><code>m1 = analytic_events['section']==2 mask = ~analytic_events.loc[m1, 'identifier'].str[0].str.isdigit() print (mask.sum()) </code></pre>
pandas
1
368,181
54,452,786
How to represent complex matrix from 2 real-valued matrices
<p>I'm trying to represent a matrix of complex numbers using 2 real value matrices (in Pytorch, but using numpy here just for illustrative purposes). </p> <p>Currently I'm doing it this way:</p> <pre><code>import numpy as np # represent real X = np.random.randn(10,10) # represent imaginary I = np.random.randn(10,...
<p>You can implement complex ndarray data structure using numpy arrays. You may want to store real part in one variable of the datasture and complex in anthor variable. Python provides a way to overload some operators including <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>. E.g I've the following class...
python|numpy|linear-algebra|complex-numbers
0
368,182
54,343,898
Extract single column from Pandas DataFrame in two ways, difference?
<p>I have a Pandas DataFrame created like this:</p> <pre><code>df = floor_temperatures.join(power_consumption, how='outer').join(outside_temperatures, how='outer') df = df.resample('5Min').mean() print (df) floor_temperature power_consumption outside_temperature timestamp 2019-01-23 00:00...
<h3>Square brackets are important</h3> <p><code>df['floor_temperature']</code> represents a series. <code>pd.Series</code> objects are one-dimensional. The argument feeding <code>pd.DataFrame.__getitem__</code>, for which <code>[]</code> is syntactic sugar, is a scalar.</p> <p><code>df[['floor_temperature']]</code> rep...
python|pandas
2
368,183
54,346,154
Python numpy - list assignment index out of range
<p>I have a CSV file of the following format</p> <pre><code>86,1 15,2 19,3 52,4 15,5 13,6 18,7 20,8 49,9 266,10 </code></pre> <p>For reproduciability, i have included the full <a href="http://www.mediafire.com/file/vug94ykwk8a30e9/testdata3.csv/file" rel="nofollow noreferrer">CSV file here</a>. From column 1, I wante...
<p>I think this is a better way</p> <pre><code>df = pd.read_csv("testdata.csv", header=None) df 0 1 0 86 1 1 15 2 2 19 3 3 52 4 4 15 5 5 13 6 6 18 7 7 20 8 8 49 9 9 266 10 diffs = np.diff(df[0]) increased_value = np.median(diffs[diffs&gt;0]) increased...
python|python-3.x|pandas|csv|numpy
3
368,184
54,580,708
How can I replace a value from one array with a value in the same index of another array?
<p>I have two 3D numpy arrays which represent two images. The shape of each array is (1080, 1920, 3). The number 3 represents the RGB value of each pixel in the image.</p> <p>My goal is to replace every non-black pixel in the first array to the value of the "parallel" pixel (in the same index) from the other array.</p...
<p>Use a mask with True/False values</p> <pre><code># All pixels should be normalized 0..1 or 0..254 first_img = np.random.rand(1920,1080,3) second_img = np.random.rand(1920,1080,3) eps = 0.01 # Black pixel threshold mask = first_img.sum(axis=2) &gt; eps for i in range(first_img.shape[2]): first_img[:,:,i] = (f...
python|numpy
0
368,185
54,652,174
how to start a for loop from a chosen row of pandas.df?
<p>when processing a pandas.df with for loop.I usually meet up with errors. When the error has been removed, I will have to restart the for loop form the beginning of the dataframe. How can I start the for loop from the error position, getting rid of run it repeatedly. For example:</p> <pre><code>senti = [] for i in d...
<p>If you API requires encoding to GBK, then just encode to that codec using an error handler other than <code>'strict'</code> (the default).</p> <p><code>'ignore'</code> will drop any codepoints that can't be encoded to GBK:</p> <pre><code>dfs['ssentence_encoded'] = dfs['ssentence'].str.encode('gbk', 'ignore') </cod...
python|pandas|for-loop|utf-8|gbk
1
368,186
54,639,776
How do I replace a specific dataframe value while iterating?
<p>I have a df where the 4th column are dog breeds, I'm comparing it to a list of dog breeds (<code>breeds</code>). I'd like to replace the value in the data frame with 'NaN' if that dog breed is not in the list of dog breeds. The logic is working, but I cannot get the replacement right. How is this done? This is what ...
<p>I needed to escape the second loop, this solved it:</p> <pre class="lang-py prettyprint-override"><code>for index, row in df_2.iterrows(): if not any(breed == row[3] for breed in breeds): row[3] = 'NaN' df_2.loc[index, 'breed_probability_1'] = row[3] </code></pre>
python|pandas
0
368,187
54,309,633
Apply np.where against square bracket filtering for numpy filtering
<p>I could perform filtering of numpy arrays via</p> <pre><code>a[np.where(a[:,0]==some_expression)] </code></pre> <p>or </p> <pre><code>a[a[:,0]==some_expression] </code></pre> <p>What are the (dis)advantages of each of these versions - especially with regard to performance?</p>
<p>Boolean indexing is transformed into integer indexing internally. This is <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/arrays.indexing.html#boolean-array-indexing" rel="nofollow noreferrer">indicated in the docs</a>:</p> <blockquote> <p>In general if an index includes a Boolean array, the result wil...
python|arrays|performance|numpy|indexing
3
368,188
54,405,704
Check if all values in dataframe column are the same
<p>I want to do a quick and easy check if all column values for <code>counts</code> are the same in a dataframe:</p> <p>In:</p> <pre><code>import pandas as pd d = {'names': ['Jim', 'Ted', 'Mal', 'Ted'], 'counts': [3, 4, 3, 3]} pd.DataFrame(data=d) </code></pre> <p>Out: </p> <pre><code> names counts 0 Jim ...
<p>An efficient way to do this is by comparing the first value with the rest, and using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html" rel="noreferrer"><code>all</code></a>:</p> <pre><code>def is_unique(s): a = s.to_numpy() # s.values (pandas&lt;0.24) return (a[0] == a).all() is_...
python|python-3.x|pandas|dataframe
69
368,189
54,368,686
LSTM having a systematic offset between predictions and ground truth
<p>Currently i think i'm experiencing a systematic offset in a LSTM model, between the predictions and the ground truth values. What's the best approach to continue further from now on?</p> <p>The model architecture, along with the predictions &amp; ground truth values are shown below. This is a regression problem whe...
<p>It looks like your model is overfitting and is simply always returning the value from the last timestep as a prediction. Your dataset is probably too small to have a model with this amount of parameters converge. You'll need to resort to techniques that combat overfitting: agressive dropout, adding more data, or try...
python|tensorflow|keras|lstm|recurrent-neural-network
11
368,190
54,677,582
Vectorizing a recurrence relation for-loop in python
<p>I have a recurrent relation that looks like the following:</p> <pre><code>f_0 = s_0 f_1 = alpha * s_1 + (1 - alpha) * f_0 f_2 = alpha * s_2 + (1 - alpha) * f_1 ... f_n = alpha * s_n + (1 - alpha) * f_n-1 </code></pre> <p>this is easy enough to code up as a for-loop (example code)</p> <pre><code>import numpy as np...
<p>You could change this into a matrix equation. If you write f and s as numpy arrays (1d) and write a 2d numpy matrix M, such that:</p> <pre><code>F = numpy.dot(M,S) </code></pre> <p>then you only have to create the matrix once (it only depends on alpha), and can keep using it on different S. On first inspection th...
python|numpy|for-loop
0
368,191
54,334,659
How to extract the first element of a 2d array in python?
<p>Let's say I have a 3d array in python that looks like this [[[3, 4, 9], [5, 3, 1], [6, 4, 2]], [[2, 3, 6], [7, 9, 10], [5, 12, 4]], [[7, 5, 1], [3, 1, 2], [6, 5, 2]]]. I want to extract the first element of each entry and put them all into a 1d array like this [3, 5, 6, 2, 7, 5, 7, 3, 6]. I'm working with an hsv ima...
<p>Slicing the array is by far the fastest method available. The array you are importing is 3-dimensional in nature, just as an example let's create a 3d array from random numbers from the domain 0-10: </p> <pre><code>import numpy as np img = np.random.randint(0, 10, (5, 3, 3)) img.shape Out[36]: (5, 3, 3) Out[37]:...
python|image|numpy|hsv
3
368,192
54,571,620
Minimum of ordered categorical data in Panda DataFrames
<p>I have a Pandas DataFrame with one Serie containing ordered Categorical data. Some value of this Serie may be missing (NaN). I want to get the minimum without taking into account NaNs but I obtained strange results ...</p> <p><strong>Code:</strong></p> <pre><code>raw_cat = pd.Categorical(["a", "b", "c", "a"], ...
<p>This issue was a regression of Pandas 0.24.0 and above. It will be correct in Pandas 0.24.2.</p> <p><a href="https://github.com/pandas-dev/pandas/issues/25299" rel="nofollow noreferrer">https://github.com/pandas-dev/pandas/issues/25299</a></p>
python|pandas|categorical-data
0
368,193
54,600,340
How to avoid lines that contain both string and numbers before splitting them?
<p>I use python 3, and I read files that strart with few lines that contain text and number together, and from a certain line it's only columns of numbers, that originally they are also read as str after splitting, that I later convert them to float.</p> <p>the data look like this . I also add the link to the sample o...
<p>You should try this. This code use regexp to find the data as a clean way.</p> <pre><code>import pprint import re if __name__ == '__main__': # pattern to ignore line containing alpha or : ignore_pattern = re.compile(r'[^a-zA-Z:]*[a-zA-Z:]') # number pattern number_pattern = re.compile(r'[-.\d]+') ...
python|pandas|dataframe|readlines
1
368,194
54,445,700
Pricing American Stock Option with TensorFlow Neural Network , Simulate by Monte Carlo
<p>so what I try to do is to simulate with Monte Carlo a American Option (Stock) and use TensorFlow to price it.</p> <p>I use two helper function , <strong>get_continuation_function</strong> to create the TF operators. And the <strong>pricing_function</strong> to create the computational graph for the pricing.</p> <p...
<p>There are a bunch of things discussed in comment with @hallo12. I just want to upload a working version incorporating all the changes. The code is tested and runs without error. But to make sure the final training output is correct, you may want to compare against some benchmark.</p> <p><strong>General comment</str...
python|tensorflow|neural-network|montecarlo|stock
0
368,195
73,548,495
grouper day and cumsum speed
<p>I have the following df:</p> <p><a href="https://i.stack.imgur.com/ubCLq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ubCLq.png" alt="enter image description here" /></a></p> <p>I want to group this df on the first column(ID) and on the second column(key), from there to build a cumsum for each ...
<p>Friendly reminder, it's useful to include a runable example</p> <pre><code>import pandas as pd data = [{&quot;cid&quot;:33613,&quot;key&quot;:14855,&quot;ts&quot;:1550577600000,&quot;value&quot;:50.0}, {&quot;cid&quot;:33613,&quot;key&quot;:14855,&quot;ts&quot;:1550579340000,&quot;value&quot;:50.0}, ...
pandas|datetime|group-by|cumsum
0
368,196
73,638,446
Is it possible to use DataFrame.pct_change and retain all columns?
<p>Is there a way to use the pandas percent change function (DataFrame.pct_change) inplace or in some fashion that retains all the columns of the initial dataframe?</p> <p>For instance,</p> <pre><code>PctChange = CH1['Area_SqM'].pct_change() </code></pre> <p>creates a pandas series of percent change values. But I w...
<pre><code>CH1['pct_change'] = CH1['Area_SqM'].pct_change() </code></pre> <p>Would be how I do it normally. Note your first cell is going to be empty (Null)</p>
python|pandas
0
368,197
73,631,631
Vectorized method find value in dataframe and then use comparison of previous row's value of same column
<p>Sample Data</p> <p>Siutation 1:</p> <pre><code>DateTime Value1 Value2 8/15/2022 10:47 0.00151 0 8/15/2022 10:48 0.0016 1 8/15/2022 10:49 0.00168 1 </code></pre> <p>Situation 2:</p> <pre><code>DateTime Value1 Value2 8/16/2022 13:38 0.00163 1 8/16/2022 13:39 0.0016 0 8/16/2022...
<p>Easy with <a href="https://pandas.pydata.org/pandas-docs/dev/reference/api/pandas.DataFrame.loc.html#pandas.DataFrame.loc" rel="nofollow noreferrer"><code>loc</code></a> and masks:</p> <pre><code>mask1 = df.Value1==0.0016 mask2 = df.Value1.shift(1) &gt; df.Value1 df.loc[mask1 &amp; mask2, 'Value2'] = 1 df.loc[mask1...
python|pandas|dataframe|vectorization
0
368,198
73,723,291
Select date columns in python based on specific date criteria
<p>This is my sample code. My database contains columns for every date of the year, going back multiple years. Each column corresponds to a specific date.</p> <pre><code>import pandas as pd df = pd.DataFrame([[10, 5, 25, 67,25,56], [20, 10, 26, 45, 56, 34], [30, 3, 27, 34, 78, 34...
<p>Yes, you can do:</p> <pre><code># day df.loc[:, df.columns.day == 14] 2022-09-14 2022-08-14 2022-07-14 2021-09-14 2020-09-14 2019-09-14 0 10 5 25 67 25 56 1 20 10 26 45 56 34 2 30 ...
python|pandas|jupyter-lab
3
368,199
73,814,047
pandas : return YES if any of the cell in multiple columns contains a string
<p>I have a data-frame:</p> <pre><code>df = pd.DataFrame({'A': ['Target acc', 'Target acc', 'N'], 'B': ['Target acc', 'Target acc', 'N'], 'C': ['Target acc', 'N', 'N']}) </code></pre> <p>I would like to return 'Yes' if the string 'Target acc' is present at least in of the columns (A,B,C)...
<p>You can use:</p> <pre><code>df['D'] = np.where(df.eq('Target acc').any(axis=1), 'Yes', 'No') </code></pre> <p>If you have more columns and want to limit to A/B/C:</p> <pre><code>df['D'] = np.where(df[['A', 'B', 'C']].eq('Target acc').any(axis=1), 'Yes', 'No') </code></pre> <p>output:</p> <pre><code> A ...
python|pandas
1