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
362,400
68,132,248
Get rid of data if there are less than 3 data points in the hour
<p>I am fairly new to this so please bear with me. I have a df where the index is in datetime format. My other columns are concentration and a count column that just consists of 1s.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Timestamp</th> <th style="text-alig...
<p>You should be able to join onto your resampled dataframe (using rounded down timestamps as a key) to give a column specifying whether there were more than 3 measurements in the hour of that record. For example:</p> <pre><code>df = df.set_index('Timestamp') df2 = df.resample('H').sum() df['floor'] = df.index.floor('H...
python|pandas|group-by|pandas-resample
1
362,401
68,119,079
Assign value to observation based on a condition
<p>I have a situation:</p> <p>Let's consider two columns: visitor &amp; id_user</p> <p>Some 'visitor' have missing values on 'id_user, but other values not.</p> <p>The thing is that same unique value of 'visitor' appears with both scenarios: having 'id_user' &amp; having missing.</p> <p>I want to fill the values for th...
<p>Try using dictionary while you zip the dataset.</p> <pre><code>dictionary = dict(zip(full_user['visitor'],missing_user['visitor']) for i,j in dictionary : if i == j: missing_user['id_user'] = full_user['id_user'] </code></pre>
python|pandas|missing-data
1
362,402
68,082,766
Stable conversion of a multi-column (2D) numpy array to an indicator vector
<p>I often need to convert a multi-column (or 2D) numpy array into an indicator vector in a stable (i.e., order preserved) manner.</p> <p>For example, I have the following numpy array:</p> <pre><code>import numpy as np arr = np.array([ [2, 20, 1], [1, 10, 3], [2, 20, 2], [2, 20, 1], [1, 20, 3], [2, 20...
<p>In addition to <code>return_inverse</code>, you can add the <code>return_index</code> option. This will tell you the first occurrence of each sorted item:</p> <pre><code>unq, idx, inv = np.unique(arr, axis=0, return_index=True, return_inverse=True) </code></pre> <p>Now you can use the fact that <code>np.argsort</cod...
python|arrays|pandas|numpy
2
362,403
68,035,443
What does padding='same' exactly mean in tensorflow Conv2D? Is it minimum padding or input_shape == output_shape
<p><strong>TL;DR: How can I modify my code given below to incorporate the <code>padding = 'same'</code> method?</strong></p> <p>I was trying to build my own <code>CNN</code> using <code>numpy</code> and got confused due to the two answers for <code>padding = 'same'</code>.</p> <p><a href="https://stackoverflow.com/ques...
<p>According to this <a href="https://stackoverflow.com/questions/37674306/what-is-the-difference-between-same-and-valid-padding-in-tf-nn-max-pool-of-t">SO answer</a>, the name <code>'SAME'</code> padding just came from the property that when stride equals 1, output spatial shape is the <strong>same</strong> as input s...
numpy|tensorflow|keras|deep-learning|computer-vision
5
362,404
68,055,826
How to test one image in keras and output the prediction with its name
<p>I have managed to train images with labels but i'm not able to predict a single image with the respective image and output it.</p> <p>Here is the code:</p> <pre><code>labels = ['Black_Shank', 'Brown_Spot'] img_size = 224 def get_data(data_dir): data = [] for label in labels: path = os.path.join(data...
<p>First since you have a sofmax activation function you should not set from_logits=True in your loss function. Next issue is was your model trained on RGB or BGR images? The image you want to predict must be in the same format that the images were when you trained your model. I will assume it was trained on RGB images...
python|tensorflow|machine-learning|keras|deep-learning
0
362,405
68,054,533
fold/col2im for convolutions in numpy
<p>Suppose I have an input matrix of shape <strong>(batch_size ,channels ,h ,w)</strong></p> <p>in this case (1 ,2 ,3 ,3)</p> <pre><code>[[[[ 0., 1., 2.], [ 3., 4., 5.], [ 6., 7., 8.]], [[ 9., 10., 11.], [12., 13., 14.], [15., 16., 17.]]]]) </code></pre> <p>to do a convolution with it i unroll it t...
<p>With numpy, I expect this can be done using <code>numpy.lib.stride_tricks.as_strided</code>. However, I'd suggest that you look at pytorch, which interoperates easily with numpy and has quite efficient primitives for this operation. In your case, the code would look like:</p> <pre><code>kernel_size = 2 x = torch.ara...
python|numpy|convolution|numpy-slicing
0
362,406
68,236,996
Pandas: methods to transpose DataFrame and Series?
<p>I wanted to respond and extend this post in order to stick together all the similar information about transpose. It was said to me that I have to make a separated question.</p> <p><a href="https://stackoverflow.com/questions/16301546/swapping-axes-in-pandas">Swapping Axes in Pandas</a></p> <p>If you have a simple DF...
<p>Here's one way:</p> <pre><code>s = df1['one'].to_frame().T </code></pre> <p>OUTPUT:</p> <pre><code> 0 1 2 3 one 1.0 2.0 3.0 4.0 </code></pre>
pandas|dataframe|series|transpose
0
362,407
68,137,746
How to filter on a column that has both float and datetime
<p>I have a column in my dataframe that has both <code>datetime</code> values and <code>float</code> values. How do I filter out the <code>float</code> values? I have tried the following:</p> <pre><code>import datetime a = pd.DataFrame([10.0,datetime.datetime.now(),20.0]) a = a[a.dtype!=float] </code></pre> <p>That d...
<p>I highly suspect that the floats that you see are NaN values. So, I would suggest this:</p> <pre><code>a_float_free = a.dropna() </code></pre> <p>On the other hand, if my doubt is wrong you can then filter out the floats using</p> <pre><code>import datetime a = pd.DataFrame([10.0,datetime.datetime.now(),20.0]) a_f...
pandas|datetime|object|floating-point
1
362,408
68,443,850
Extract country from cities in pandas
<p>I have an array of list of cities. I want to group them by the country name. Is there any library I can install which will do that ?</p> <p>e.g array(['Los Angeles', 'Detroit', 'Seattle', 'Atlanta', 'Santiago', 'Pittsburgh', 'Seoul', 'Santa Clara', 'Austin', 'Chicago'])</p> <p>I want to know the country they belong ...
<p>I agree with what has been said in the comments - there is no clear way to join a city to a country when city names are not unique.</p> <p>For example if we run...</p> <pre><code>import pandas as pd df = pd.read_csv('https://datahub.io/core/world-cities/r/world-cities.csv') df.rename(columns ={&quot;name&quot;:&qu...
python|pandas|dataframe|data-analysis|python-module
0
362,409
68,033,208
Gather_Nd error when fine-tuning EfficientDet on a custom dataset on Google Colab
<p>I'm trying to fine tune EfficientDet on a custom dataset using Google Colab (free) for multi-object detection. I'm new to tf so I tried to reproduce/modify an existing notebook (this one: <a href="https://colab.research.google.com/drive/1iOydvFQVE-syG-ixEyam04X3E40Lx7NA?usp=sharing" rel="nofollow noreferrer">https:/...
<p>All right, I found my error: the number of classes and classes texts did not match the number of bbox for a sample in a tfrecord file. I changed the code like this and it did the trick:</p> <pre><code>def create_tf_example(filepath, df_label): encoded_image_data = open(filepath, &quot;rb&quot;).read() key =...
python|google-colaboratory|tensorflow2.0
0
362,410
68,035,784
Why I am getting an error with plotly line chart
<p>I am new to Plotly and was trying to plot the below pivot table using a Plotly line chart. My code is given below. The error is also attached here.</p> <p>May I know where I went wrong</p> <p><a href="https://i.stack.imgur.com/mYQbm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mYQbm.png" alt="T...
<ul> <li>you have not provided sample data so I simulated</li> <li>your initial error was a straight <strong>pandas</strong> coding error. You need to refer to values in indexes using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_level_values.html" rel="nofollow noreferrer">get_l...
python|pandas|plot|plotly|plotly-dash
2
362,411
68,101,534
Convert image sequences to 4D tensor/ .npy in Python
<p>I have a sequence of 2D images (how it has propagated through each time step) depicting a single simulation. Let's say for example I have 1000 sets of simulations, each containing 10-time frame images. This is not a supervised learning problem as there are no class labels. The model has to learn how to simulation pr...
<p><strong>Sample code to convert Images to 4Dimension array</strong></p> <pre><code>import tarfile my_tar = tarfile.open('images.tar.gz') my_tar.extractall() # specify which folder to extract to my_tar.close() import pathlib data_dir = pathlib.Path('/content/images/') import tensorflow as tf batch_size = 32 img_heig...
python|tensorflow|image-preprocessing
0
362,412
68,241,614
Replace values inside list by generic numbers to group and reference for statistical computing
<p>I usually use <code>&quot;${:,.2f}&quot;. format(prices)</code> to round numbers before commas, but what I'm looking for is different, I want to change values numbers to group them and reference them by mode:</p> <p>Let say I have this list:</p> <blockquote> <p>0 34,123.45</p> <p>1 34,456.78</p> <p>2 ...
<p>You can use:</p> <pre><code>&gt;&gt;&gt; sr 0 34123.45 # &lt;- why 34500.00? 1 34456.78 2 34567.89 # &lt;- why 34500.00? 3 33222.22 4 30123.45 dtype: float64 &gt;&gt;&gt; np.round(sr / 100) * 100 0 34100.0 1 34500.0 2 34600.0 3 33200.0 4 30100.0 dtype: float64 </code></pre>
pandas|numpy
1
362,413
68,333,285
Pandas lambda function raised an indexing error
<p>I have a data frame df and would like to reassign value from columns b to the last columns. The logic is as follows: if &quot;b&quot; column value is greater or equal to the previous row of &quot;a&quot; column value, reassign &quot;b&quot; value as &quot;green&quot;, otherwise &quot;red&quot;. My code raise an inde...
<p>Let's try with <a href="https://numpy.org/doc/1.20/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a> and compare where the columns are <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.ge.html" rel="nofollow noreferrer"><code>Series.ge</code></a...
python|pandas|dataframe|indexing|lambda
1
362,414
68,321,264
Keras Sequential prediction always returning the same result
<p>This is an algorithm that I used to classify the class of a picture - running shoes, pencil and book. However, after running the algorithm on 3000 <em><strong>shuffled</strong></em> images (that's all I have), I notice:</p> <ol> <li><p><strong>val_accuracy for every one of the epochs is the same, equaling 0.3400</st...
<p>since you are trying to classify the data into 3 classes the top layer of your model should be</p> <pre><code>model.add(Dense(3)) model.add(Activation('softmax')) </code></pre> <p>You do not show the code for how you generated X-train and y_train. If y_train is one hot encoded then you code for model.compile should ...
python|tensorflow|machine-learning|keras|image-classification
0
362,415
68,295,234
Check if a pandas Dataframe string column contains all the elements given in an array
<p>I have a dataframe as shown below:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame(data = [['app;',1,2,3],['app; web;',4,5,6],['web;',7,8,9],['',1,4,5]],columns = ['a','b','c','d']) &gt;&gt;&gt; df a b c d 0 app; 1 2 3 1 app; web; 4 5 6 2 web; 7 8 9 ...
<p>This should work too:</p> <pre><code>l = [&quot;app&quot;,&quot;web&quot;] df['a'].str.findall('|'.join(l)).map(lambda x: len(set(x)) == len(l)) </code></pre> <p>also this should work as well:</p> <pre><code>pd.concat([df['a'].str.contains(i) for i in l],axis=1).all(axis = 1) </code></pre>
python|pandas|dataframe
2
362,416
68,373,591
two DataFrame plots
<p>I have a similar plot to the one answered in the link below:</p> <p><a href="https://stackoverflow.com/questions/68356120/two-dataframe-plot-in-a-single-plot-matplotlip/68356625?noredirect=1#comment120837919_68356625">two DataFrame plot in a single plot matplotlip</a></p> <p>I made some modification to <code>plots f...
<p>You have several options to make this graph. df1 and df2 are as defined in <a href="https://stackoverflow.com/questions/68356120/two-dataframe-plot-in-a-single-plot-matplotlip/68356625">your previous question</a></p> <p>The version with <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.scatter.htm...
python|pandas|numpy|matplotlib
1
362,417
59,083,222
What is the best way to handle the background pixel classes (ignore_label), when training deep learning models for semantic segmentation?
<p>I am trying to train a <strong>UNET</strong> model on the <a href="https://www.cityscapes-dataset.com/dataset-overview/#class-definitions" rel="noreferrer">cityscapes</a> dataset which has 20 'useful' semantic classes and a bunch of background classes that can be ignored (ex. sky, ego vehicle, mountains, street ligh...
<p>Definitely the second solution is the better one. This is the best solution, the background class is definitely and additional class but not an unnecessary one, since in this way there is a clear differentiation between the classes you want to detect and the background.</p> <p>In fact, this is a standard procedure r...
tensorflow|machine-learning|deep-learning|pytorch|semantic-segmentation
2
362,418
59,213,751
Datetime Variables issues
<p>I have a variable which is a DateTime variable. From that, I get the weeknumber. Afterwards, I want to change the format of the Datetime variable, but then an error occurs to my weeknumber:</p> <p>1st code</p> <pre><code>df['startedAt'] = pd.to_datetime(df['startedAt'], errors='coerce') df['endedAt'] = pd.to_datet...
<p>It is expected, because after <code>.dt.strftime('%d-%m-%Y %H:%M')</code> values in column <code>startedAt</code> are not datetimes, but strings.</p> <p>If want remove minutes, set them to <code>0</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.floor.html" rel="nofollow...
pandas|datetime|type-conversion
0
362,419
59,231,568
is there a better way to do segmented fillna with method 'ffill' with pandas?
<p>Let me explain this situation. the thing is i'm currently working with data that is categorized sometimes and sometimes don't. So i decided to use fillna's pandas with 'ffil' as method. I just don't feel this is the optimal and/or cleaner solution. if someone could help me with a better aproach i'll be so grateful. ...
<p>We can do </p> <pre><code>df['category']=df.groupby('detail')['category'].ffill() df detail category 0 apple mac computer 1 apple iphone x phone 2 samsumg galaxy s10 phone 3 samsumg galaxy s10 phone 4 hp computer NaN </code></pre>
python|pandas|fillna
1
362,420
59,356,210
tf.unique without repeating indices
<p>My input is a tensor of for example <code>[8,8,8,2,2,3,1,1,8,8]</code>. My output should be a tensor that references to each segment of this tensor which would look like this: <code>[0,0,0,1,1,2,3,3,4,4]</code>. I have to compute that in tensorflow.</p> <p><code>tf.unique([8,8,8,2,2,3,1,1,8,8])</code> computes a te...
<p>The operation that you want to do does not really have much to do with <code>tf.unique</code>. One way to achieve that result is this:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf def identify_blocks(a): neq = tf.not_equal(a[1:], a[:-1]) c = tf.cumsum(tf.dtypes.cast(neq, tf.i...
python|tensorflow|deep-learning|unique|tensor
0
362,421
59,161,992
Machine learning - Train medical image
<p>I am trying to create Deep Neural Network based classifier for chest x-ray to check there is TB or not. I read that transfer Learning technique can be used for this using inception model v3. My question is inception model is created by training with imagenet(physical object) right? How can this be used for medical i...
<p>One intuition is that physical objects and medical images do share some similarities especially in low-level features such as edges, curves and small object regions. </p> <p>Experiments indicate that pretraining a network on ImageNet can benefit most computer vision tasks even if the images from the target domain l...
tensorflow|medical
0
362,422
59,158,113
Concatenate layer in keras
<p>If I am concatenating 2 conv2D layers by using Concatenate function in keras then it will concatenate the weights associated with each layer or output of that layer?</p> <p>to more generalize my doubt,</p> <p><code>layer1 = conv2D()<br> layer2 = conv2D() result = Concatenate([layer1, layer2])</code></p>
<p>It will concatenate the results of the weights after activation functions applied upon those weights.</p> <p>Otherwise, it would render useless any activation function which is applied on <code>layer</code>(from 1 to N for example), where <code>layer</code> has an activation function.</p> <p>Imagine in ResNet(resi...
tensorflow|keras|deep-learning
1
362,423
59,448,190
Understanding pandas.DataFrame.corrwith method for spearman rank correlation calculation column-wise and row-wise
<p>I have two dataframes like so :</p> <pre><code>preds_df = pd.DataFrame.from_records ([[ 0.8224], [ 0.7982]]) tgts_df = pd.DataFrame.from_records ([[0.8889], [1.0000]]) </code></pre> <p>and want to compute spearman rank correlation values both across columns and across rows:</p> <pre><code>col_wise = preds_df.co...
<p><strong>Question 1:</strong> Note that when you want to calculate the Spearman correlation coefficient row-wise, you get two one-element samples from both frames (<code>0.8224, 0.8889</code>) corresponding to the first element in the list of coefficients and (<code>0.7982,1.0000</code>) corresponding to the other. N...
pandas|dataframe|nan
1
362,424
59,364,863
Python seaborn plotting from dataframe that was filtered using `pd.Categorical`
<p>I'm trying to plot some data from a subset of my dataframe, but it is plotting empty ticks for data that should have been filtered out. I know the issue is that I used <code>pd.Categorical()</code>, but I need to. How do I plot only the filtered data (i.e. just <code>a1</code> and <code>a2</code>) and no extra ticks...
<p>This seems to be an effect of the categorical type that maintains all of its possible values even if they are not always present (see <code>print(plotdf['A'].dtype)</code>).</p> <p>for example, running <code>plotdf.groupby('A').size()</code> returns</p> <pre><code>A a1 3 a2 3 a3 0 </code></pre> <p>with cate...
python|pandas|matplotlib|seaborn
0
362,425
59,434,659
Runtime error using Python Library Keops using CUDA in Ubuntu18.04
<p>I am trying to run samples from the Python library: <a href="https://www.kernel-operations.io/geomloss/_auto_examples/index.html" rel="nofollow noreferrer">GeomLoss</a>, which depends on CUDA, Pytorch and <a href="https://www.kernel-operations.io/keops/index.html" rel="nofollow noreferrer">Keops</a> in Ubuntu 18.04....
<p>I did the following steps and it worked for me:</p> <p>First, by checking the dependencies in this <a href="http://www.kernel-operations.io/keops/python/installation.html" rel="nofollow noreferrer">link</a> I noticed that <code>nvcc</code> compiler is not installed. By going to <a href="https://docs.nvidia.com/cuda/...
python|ubuntu|gcc|pytorch
0
362,426
59,189,422
Pandas dataframe apply lambda based on inputs from multiple columns
<p>Let's say I have a dataframe that looks like this:</p> <p><br> <a href="https://i.stack.imgur.com/I2pfg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I2pfg.png" alt="df[&#39;GlobalName&#39;][df[&#39;GlobalName&#39;]==&#39;&#39;] = df[&#39;IsPerson&#39;].apply(lambda x: x if x==True else &#39;&#...
<p>I think <code>apply</code> here is not neccesary, only join columns together with <code>+</code>:</p> <pre><code>df['FullName'] = df.FirstName + ' ' + df.LastName </code></pre> <p>Or use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.cat.html" rel="noreferrer"><code>Series.str...
python|pandas|dataframe|lambda
6
362,427
59,337,592
Keras : Value error : setting an array element with a sequence
<h2>Context :</h2> <p>I am just starting in Deep Learning and I have to implement a model in Python that can detect the inference between two sentences (label is neutral, contradiction or entailment). The data set is formatted as follows: </p> <pre><code>| index | sentence_1 | sentence_2 | label | |-----------...
<p>You're trying to solve a problem of sentence entailment. This means that you need to have two streams of network flows in your graph (i.e. one for each sentence). The main problem is that you have defined an <code>Input</code> layer of size <code>(None,2)</code>. But your input has a sequence length of 80 (probably ...
python|pandas|tensorflow|keras|deep-learning
1
362,428
59,470,195
How to achieve elementwise convolution for two tensors using tensorflow?
<p>In my problem, I want to convolve two tensors in my neural network model.</p> <p>The shape of two tensors is [None, 2, 1], [None, 3, 1] respectively. The axis with dimension None means the batch size of the input tensor. For each sample in batch, I want to convolve the two tensors with shape [2, 1] and [3, 1].</p> ...
<p>According to the description of the kernel size arguments for Conv1D layer or any other layer mentioned in the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv1D" rel="nofollow noreferrer">documentation</a>, you cannot add multiple filters with different Kernel size or strides. </p> <p>Also,...
python|tensorflow|conv-neural-network
0
362,429
59,134,796
Pandas dataframe filter rows on within time range
<p>I have a dataframe object like this:</p> <pre><code> Date ID Delta 2019-10-16 16:43:46 BA9565P 0 days 00:00:00 2019-10-17 05:28:36 BA9565P 0 days 12:44:50 2019-10-16 16:43:13 BA9565X 0 days 00:00:00 2019-10-17 03:26:52 BA9565X 0 days 10:43:39 2019-10-10 19:17:17 BABRGNR 0 ...
<p>Solution select all rows of group if difference is more like <code>3 days</code> per group else last rows for all another groups:</p> <pre><code>print (df) Date ID Delta 0 2019-10-16 16:43:46 BA9565P 0 days 00:00:00 1 2019-10-17 05:28:36 BA9565P 0 days 12:44:50 2 2019-10-16 16:...
python|pandas|dataframe
2
362,430
59,476,012
How to change date format of Multiindex?
<p>I have this Multiindex, </p> <pre><code>Product Date col1 A 2019-10-31 5 2019-11-30 7 B 2019-10-31 2 2019-11-30 4 C 2019-10-31 7 2019-11-30 3 </code></pre> <p>I want to change it into this:</p> <pre><code>Product Date col1...
<p>You can't change a frozen list, instead just re-set the whole index:</p> <pre><code>df.index = df.index.set_levels([df.index.levels[0], df.index.levels[1].strftime('%B %Y')]) </code></pre>
pandas|datetime|multi-index
2
362,431
59,213,290
Structured streaming multiple row to pandas udf
<p>I'm writing a structured streaming job that receives data from eventhubs. After some preparation, I apply a pandas_udf function on each row to create a new column with a prediction from a pickle model. </p> <p>I'm experiencing a serious problem: sometimes the input for the pandas_udf is a group of row and not a si...
<p>In this case you are using a SCALAR <code>pandas_udf</code>, which takes as input a pandas Series and returns a <code>pandas.Series</code> of the same size. I don't know the exact details on the internals but my understanding is that each executor will convert your column (<code>F.struct([col(x) for x in (features)]...
pandas|apache-spark|pyspark|user-defined-functions
0
362,432
59,311,232
Pandas make row blank if header does not exist
<p>I am trying to combine multiple excel files with Python Pandas. Some files have different headers from each other:</p> <p><a href="https://stackoverflow.com/questions/43126726/appending-blank-rows-to-dataframe-if-column-does-not-exist?rq=1">Similar question on stackoverflow here</a></p> <p>This is where it fails:<...
<p>Typing this in the blind and not fully tested.</p> <p>You have a fixed set of columns to extract from source Excel files. Use <code>intersection</code> to get only those that exist, then <code>index</code> to add back the missing columns (if any):</p> <pre><code>frames = [] cols = ['Charges', 'Amount','Taxes','Dat...
excel|python-3.x|pandas
1
362,433
59,096,347
How to train a model on multi gpus with tensorflow2 and keras?
<p>I have an LSTM model that I want to train on multiple gpus. I transformed the code to do this and in <code>nvidia-smi</code> I could see that it is using all the memory of all the gpus and each of the gpus are utilizing around 40% BUT the estimated time for training of each batch was almost the same as 1 gpu.</p> <...
<p>Assuming that your <code>batch_size</code> for a single GPU is <code>N</code> and the time taken per batch is <code>X</code> secs.</p> <p>You can measure the training speed by measuring the time taken for the model to converge, but you have to make sure that you feed in the right <code>batch_size</code> with 2 GPUs...
tensorflow|keras|gpu|tensorflow2.0
2
362,434
59,179,049
Error saving files into google drive via google colab
<p>I am trying to save files onto my Google Drive from a colab notebook and I keep getting the same error. I have already mounted my drive. When I call pwd, I get, which seems right:</p> <pre><code>/content/drive/My Drive/ </code></pre> <p>Here is an example code and read-out:</p> <pre><code>from google.colab import...
<p>You want to save to google drive, you should add the mounted path:</p> <pre><code>from google.colab import drive drive.mount('/content/drive') import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD')) print(df) df.to_csv('/content/drive/My Drive/test.csv...
python|pandas|google-drive-api|google-colaboratory
3
362,435
59,077,195
to_datetime() in pandas returns a Categorical type rather than a datetime object
<p>Here is a sample of the code:</p> <pre><code>data.timestamp = pd.to_datetime(data.timestamp, infer_datetime_format = True, utc = True) data.timestamp.dtype CategoricalDtype(categories=['2016-01-10 06:00:00+00:00', '2016-01-10 07:00:00+00:00', '2016-01-10 08:00:00+00:00', '2016-01-10 09:00:00+00:...
<pre><code>data.timestamp = pd.to_datetime(data.timestamp, infer_datetime_format = True, utc = True).astype('datetime64[ns]') </code></pre> <p>This worked.</p>
python-3.x|pandas|string-to-datetime
4
362,436
59,386,797
How to rename dataframe index efficiently using a python list?
<p>I have a pandas dataframe and a ordered list like as shown below</p> <pre><code>df = pd.DataFrame([[1, 2, 3], [4, 5 ,6]], columns=list('ABC')) df = df.rename(index={0:'x1'}) df = df.rename(index={1:'x2'}) </code></pre> <p><a href="https://i.stack.imgur.com/aX609.png" rel="nofollow noreferrer"><img src="https://i.s...
<p>Just use:</p> <pre><code>df.index = ordered_list </code></pre>
python|python-3.x|pandas|dataframe|rename
2
362,437
59,292,232
Pandas groupby year filtering the dataframe by n largest values
<p>I have a dataframe at hourly level with several columns. I want to extract the entire rows (containing all columns) of the 10 top values of a specific column for every year in my dataframe.</p> <p>so far I ran the following code:</p> <pre><code>df = df.groupby([df.index.year])['totaldemand'].apply(lambda grp: grp....
<p>We usually do <code>head</code> after <code>sort_values</code></p> <pre><code>df = df.sort_values('totaldemand',ascending = False).groupby([df.index.year])['totaldemand'].head(10) </code></pre>
pandas|filtering|pandas-groupby
1
362,438
59,473,736
Python bin sets of pairs of interleaving arrays
<p>I have a set of pairs of numpy arrays. Each array in a pair is the same length, but arrays in different pairs have different lengths. An example of a pair of arrays from this set is:</p> <pre><code>Time: [5,8,12,17,100,121,136,156,200] Score: [3,4,5,-10,-90,-80,-70,-40,10] </code></pre> <p>Another pair is:</p> <p...
<p>You can use <code>scipy.stats.binned_statistic</code>. This is a generalization of a histogram function. A histogram divides the space into bins, and returns the <strong>count</strong> of the number of points in each bin. This function allows the computation of the <strong>sum, mean, median, or other statistic</stro...
python|arrays|numpy
1
362,439
59,144,464
Plotting two cross section intensity at the same time in one figure
<p>I have an array of shape(512,512). Looks like, (row=x, column=y, density=z=the number of the array)</p> <pre><code>[[0.012825 0.020408 0.022976 ... 0.015938 0.02165 0.024357] [0.036332 0.031904 0.025462 ... 0.031095 0.019812 0.024523] [0.015831 0.027392 0.031939 ... 0.016249 0.01697 0.028686] ... [0.024545 0...
<p>I cannot help you with finding the center of the circle, but you can create a nice visualization of the cross section by creating 3 axes in a grid. Usually, I would use <a href="https://matplotlib.org/3.1.0/gallery/userdemo/demo_gridspec03.html#sphx-glr-gallery-userdemo-demo-gridspec03-py" rel="nofollow noreferrer">...
python|pandas|numpy|matplotlib
3
362,440
59,428,303
How to scale legend elements down in a scatterplot matplotlib?
<p>Lets say I have this scatterplot and would like to keep the size of the dots in the plot but in the legend I would like to have the size denoted as 1,2,... instead of 50,100,... <a href="https://i.stack.imgur.com/MfyR1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MfyR1.png" alt="enter image des...
<p>It depends. If the numbers you want to show are just arbitrary, i.e. unrelated to the actual sizes, you can supply a list of numbers as labels.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt N = 50 x = np.random.rand(N) y = np.random.rand(N) a2 = 300*np.random.rand(N) sc = plt.scatter(x, y, s=a...
python|numpy|matplotlib
3
362,441
59,381,284
TF 2.0 MLP accuracy always zero
<p>I've written a minimal example of a simple neural network that fits a given function (a multilayer perceptron for regression).</p> <p>During the training process the loss decresses as expected and the model works fine. However, the accuracy remains constant and equal to 0.0 at all times, and I don't understand why...
<p>As Swier pointed out in the comment accuracy is meant for classification. Nevertheless I thought that some points should yield the exact target value, that's why I was expecting acc>0. Anyway I mapped the problem to a integer-only problem and in that scenario the accuracy is different from zero. Obviously not a usef...
python|tensorflow|mlp
0
362,442
59,199,998
Merging Data Frame with mix Data
<p>I have two data_frames <code>df1</code> and <code>df2</code>. I want to merge them but the <code>Value</code> column is mixed <code>int</code> and <code>float</code> numbers from an excel I have. However, I know I cannot merge <code>int or float</code> columns. So I converted both <code>df1 and df2</code> into <code...
<p>You can create a new column in one of your df before merging:</p> <pre><code>df1['type'] = [type(x) for x in df1['Value']] </code></pre>
python|python-3.x|pandas
1
362,443
59,048,656
pyspark updating multiple columns
<pre><code>+----------+---------------+--------------------+--------------+-------+-----------+-----------+-----------+-----------+-----------+-----------+------------+------------+-------------+-------------+-------------+-------------+-------------+-------------+-------------+-------------+-------------+-------------...
<p>Use <a href="http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.types.DecimalType" rel="nofollow noreferrer"><code>DecimalType()</code></a> to set appropriate precision, as desired.</p> <pre><code>from pyspark.sql.types import DecimalType list_smart_cols = [i for i in df.columns if i[:len('...
python|pandas|pyspark
2
362,444
59,296,151
How to efficiently append running sum in Python?
<p>I'm writing a python script that uses a model to predict a large number of values by groupID, where <strong>efficiency is important</strong> (N on the order of 10^8). I initialize a results matrix and am trying to sequentially update a running sum of values in the results matrix.</p> <p>Trying to be efficient, in m...
<p>Here is my understanding, and please correct me if I'm wrong:</p> <p>We want a resultant matrix that has the shape <code>number of groups x timestep</code> which in this case would be <code>2000 x 100</code>. This matrix needs to be efficiently updated sequentially for a batch size of 10^6.</p> <p>If the summary i...
python-3.x|numpy
0
362,445
59,241,598
Merge 2 columns to 1 column with the same name
<p>I will like to merge 2 columns into 1 column and remove nan. </p> <p>I have this data:</p> <pre><code> Name A A Pikachu 2007 nan Pikachu nan 2008 Raichu 2007 nan Mew nan 2018 </code></pre> <p>Expected Result:</p> <pre><code> Name Year Pi...
<p>You can do this (both columns cannot be same name, they have to be different, i have one as <code>A.1</code>)</p> <pre><code>df['year']= df.A.combine_first(df['A.1']) #this gives new column 'year', then you have to drop your existing 2 columns. df['year']= df.pop('A').combine_first(df.pop('A.1')) #this is remove t...
pandas
0
362,446
59,326,735
AttributeError: 'str' object has no attribute 'merge'
<p>I am trying to merge 2 <code>csv</code> files. and I am taking file name with <code>sys.argv[n]</code> but its using filenames as strings? what I am doing wrong here ? ( using <code>python3</code> )</p> <p><strong>Code :</strong></p> <pre><code>import sys, pandas file1 = sys.argv[2] file2 = sys.argv[3] pd.read_cs...
<p>Consider using a better naming for your arguments, that will makes the debug process much easier.</p> <p>lets change:</p> <pre class="lang-py prettyprint-override"><code>file1 = sys.argv[2] file2 = sys.argv[3] </code></pre> <p>into this:</p> <pre class="lang-py prettyprint-override"><code>file1_name = sys.argv[2...
python|python-3.x|linux|pandas|attributeerror
4
362,447
59,460,230
Instantiate large sparse matrices for assignment operation
<p>If I want to instantiate a large boolean sparse matrix to assign values at certain indices later, what's the best way to initialize it? </p> <p>For example, if I want to initialize a 20000000 X 7000 logical sparse matrix on MATLAB with a 10000 filled elements (without mentioning the location of non-zero elements), ...
<p>If you need general incremental indexed-access, <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.dok_matrix.html#scipy.sparse.dok_matrix" rel="nofollow noreferrer">dok_matrix</a> is probably your best bet.</p> <p>It's common to use this one for construction (where it can shine in some case...
python|matlab|numpy|scipy|sparse-matrix
1
362,448
59,260,664
Replace dataframe row with dict
<p>I have the following row from a dataframe:</p> <pre><code>print(row) = a Nan b NaN c NaN d NaN e NaN </code></pre> <p>I have a dict: <code>dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}</code> that I want to replace this row with.</p> <p>I tried a pandas series replace <code>row = ro...
<p>Use:</p> <pre><code>s = pd.Series(row.index.map(dict1.get), index=row.index) print (s) a 1 b 2 c 3 d 4 e 5 dtype: int64 </code></pre> <p>If want replace only index:</p> <pre><code>row.index = row.index.map(dict1.get) </code></pre>
python|pandas
1
362,449
59,383,434
Getting "no table found" error when web scraping with pandas in python 3.7
<p>I want to extract various statistics from a website. Unfortunatley pandas does not recognize the tables presented. Here is my code:</p> <pre><code>url = 'https://u.gg/lol/champions/aurelionsol/matchups/' html = requests.get(url).content df_list = pd.read_html(html) </code></pre> <p><code>ValueError: No tables foun...
<p>You can use <code>API</code> directly.</p> <pre><code>import requests r = requests.get( 'https://static.u.gg/assets/lol/riot_static/9.24.1/data/en_US/champion.json?v9.24.2').json() print(r.keys()) </code></pre> <p>Or you lovely target:</p> <pre><code>import pandas as pd df = pd.read_json( 'https://sta...
pandas|web-scraping|python-requests|python-3.7|valueerror
1
362,450
59,469,649
Access groupby value within apply
<p>How can I access the <code>groupby</code> value from within the function I pass to <code>apply</code>? Here's an example:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame( [ ("bird", "Falconiformes", 389.0), ("bird", "Psittaciformes", 24.0), ("ma...
<p>You can access each groupby object with the following:</p> <pre><code>class_to_features = {"bird": ["wings", "feathers", "beak"], "mammal": ["udder"]} for group_id, group_df in df.groupby("class", as_index=False): # Print the features by mapping the dictionary print(class_to_features[group_id]) # You c...
python|pandas|pandas-groupby
0
362,451
59,344,490
All values of a column is converted to NaN while sub- setting
<p>I am learning <code>bokeh</code> and following <a href="https://realpython.com/python-data-visualization-bokeh/#getting-your-figure-ready-for-data" rel="nofollow noreferrer">a tutorial</a> from real python.</p> <p>In a tutorial it subsets a standings data set to only two teams and produces the result below. I get t...
<p>You have a typo in your statement, this is the correct one: </p> <pre><code>west_top_2 = (standings[ (standings['teamAbbr'] == 'HOU') | (standings['teamAbbr'] == 'GS') ].loc[:, ['stDate', 'teamAbbr', 'gameWon']].sort_values(['teamAbbr','stDate'])) </code></pre> <p>You have a parenthesis missing and a capital '...
python|pandas|nan
0
362,452
59,445,263
Insert values from other dataframe
<p>I am new in python and pandas, and I´m trying to insert the values from df2 ['lp'] for each ['wellname'], into df1. The problem is that I am not able to insert each value in the correct place.</p> <p>I have tryed using df.groupby , df.mask, df.where, but there is something that I am doing wrong.</p> <pre><code>df1...
<p>Run:</p> <pre><code>pd.merge(df1, df2, on=['wellname'], how='left') </code></pre> <p>Merging mode <em>both</em> (as suggested in one of comments) is wrong.</p>
python|pandas|numpy
0
362,453
59,473,845
Why Pandas "apply" function is introducing NULL values in newly added column?
<p>I'm trying to add a new column to dataframe shown below:</p> <pre><code> PM10 PM2.5 SO2 NO2 O3 4.0 4.0 4.0 7.0 77.0 24.0 24.0 26.0 54.0 36.0 19.0 15.0 21.0 57.0 32.0 35.0 26.0 22.0 54.0 43.0 40.0 37.0 24.0 55.0 44.0 ...
<p>Let us try <code>cut</code>, notice your code dose not include the boundary </p> <pre><code>bin = [0,30,60,90,120,250,1000] label = ['Good','Satisfactory','Moderately Polluted','Poor','VaryPoor','Severe'] s=pd.cut(df.PM10,bins=bin ,labels=label ) s #df['aqi']=s Out[61]: 0 Good 1 ...
python-3.x|pandas|if-statement|apply
3
362,454
59,057,540
Creating new dataframe with .txt file using Pandas
<p>I have a text file with data displayed like this:</p> <pre><code>{"created_at":"Mon Jun 02 00:04:00 +0000 2018","id":870430762953920,"id_str":"87043076220","text":"Hello there","source":"\u003ca href=\"http:\/\/tapbots.com\/software\/tweetbot\/mac\" rel=\"nofollow\"\u003eTweetbot for Mac\u003c\/a\u003e","truncated"...
<p>I had to modify the lost two key/value pairs in your data to work. You may want to check if you're getting the data correctly or if you copy and pasted properly because you should be getting errors with the data as is displayed in your post.</p> <pre class="lang-py prettyprint-override"><code>"truncated":False,"in_...
python|pandas
1
362,455
59,472,583
GCP GPU is not detected in Keras
<p>I'm running the UNet Keras model on a GCP instance with one NVIDIA Tesla P4GPU. But it does not detect the GPU. Instead it runs on the CPU. p.s. I installed drivers &amp; tensorflow-gpu buy it wont work. How to fix this issue?</p> <pre><code>I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver d...
<p>You need to first install the driver. <a href="https://cloud.google.com/compute/docs/gpus/install-grid-drivers" rel="nofollow noreferrer">Follow this instruction</a></p>
tensorflow|keras|deep-learning|google-compute-engine|nvidia
1
362,456
59,451,243
how to add sub headings to the html table using pandas dataframes and how can we access dataframe data to html table?
<p>Below if my dataframe</p> <p><code>html = data.to_html()</code></p> <p>I am getting output table as :</p> <p><a href="https://i.stack.imgur.com/0IHla.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0IHla.png" alt="enter image description here"></a></p> <p>by i want output table as :</p> <p><a...
<p>Have duplicate columns isn't a good idea, adding the suffix can help</p> <p><code>df.columns = pd.MultiIndex.from_tuples((('', 'HOUR'), ('BSNL_WEST', 'SUB'), ('BSNL_WEST', 'DEL %'), ('BSNL_WEST', 'WAIT %'), ('BSNL_NORTH', 'SUB_2'), ('BSNL_NORTH', 'DEL %_2'), ('BSNL_NORTH', 'WAIT %_2')))</code></p> <p>Results in</p...
python|pandas
2
362,457
59,278,894
i am getting TypeError: unsupported operand type(s) for /: 'str' and 'str'
<pre class="lang-py prettyprint-override"><code>ratings = pd.read_csv(path/'u.data', delimiter='\t', header=None, names=[user,item,'rating','timestamp']) ratings.head() </code></pre> <p>whenever i run this code i am getting this error </p> <blockquote> <p>TypeError: unsupported operand type(s) for /: 'str' and 'st...
<p>Check your file path. It should be <code>path+'/u.data'</code> and not <code>path/'u.data'</code>. With the latter you're trying to divide a string with another as is evident from the error you get.</p>
pandas|typeerror|unsupportedoperation
0
362,458
59,142,749
How to round away from zero
<p>I am new to python, and as far as I found out, python doesn't have sort of "mathematical" rounding. Or does it have? I have a temperature array, for example:</p> <pre><code>temp = [-20.5, -21.5, -22.5, -23.5, 10.5, 11.5, 12.5, 13.5] </code></pre> <p>I couldn't fine the way to round values mathematically to:</p> <...
<p><code>numpy</code> has a <code>around</code>, which documents:</p> <pre><code>Notes ----- For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc. Results may also be surprising due to the inexact representation...
python|numpy|math|rounding
4
362,459
59,202,250
pd.read_html importing a long string rather than a table
<p>I used pd.read_html to try and import a table, but I'm getting a long string instead when I run it. Is there a simple way to change the format of the result to get 1 word per row rather than a long string, or should i be using a function other than pd.read_html? Thank you!</p> <p>here is my code:</p> <pre><code>im...
<p>The problem is how the table was created in this site. </p> <p>According to <a href="https://www.w3schools.com/html/html_tables.asp" rel="nofollow noreferrer">https://www.w3schools.com/html/html_tables.asp</a>, an HTML table is defined with the &lt; table > tag. Each table row is defined with the &lt; tr > tag. A ...
python|pandas|dataframe|import
0
362,460
59,258,448
How can I add an id column based on unique combinations of other columns?
<p>I'm using NBA play by play data that has player ID numbers for each defensive player and each offensive player. I'd like to add a column for each lineup combination, so a deflinid and offlinid.</p> <p>Here's the code for an example of the dataset:</p> <pre><code>df = pd.DataFrame(np.array([[1,2,3,4,5,11,12,13,14,1...
<p>Using <code>pd.concat</code> to stack <code>offplayerX</code> columns on top of <code>defplayerX</code> columns. Next, <code>agg</code> every row to tuples and call <code>rank</code> and <code>unstack</code></p> <pre><code>offcols = ['offplayer1', 'offplayer2', 'offplayer3', 'offplayer4', 'offplayer5'] defcols = ['...
python|pandas
1
362,461
59,452,745
Insert empty row/s at the end of the data
<p>I have tried <code>df.loc[df.index.max()+1] = None</code>, </p> <p>It did work, but when i tried to run other lines of the script, it got an error.</p> <p>May I know is there any more code I can use other than this?<code>df.loc[df.index.max()+1] = None</code></p>
<p>Sheer concatatenation:</p> <pre><code>df = pd.concat([df, pd.DataFrame(columns=df.columns, data=[[None] * len(df.columns)] * 10)]) </code></pre>
pandas|add|rows
0
362,462
59,278,038
Make pair from row/column data of Python DataFrame
<p>I want to make pairs from below like dataframe from python What I'd like to do is make pairs with row and column like: (1,a), (4,c), (6,c), (3,d), (2,f), (4,f), (6,f), (6,g)</p> <p>Is there any way to do this. Thanks in advance.</p> <p><img src="https://i.stack.imgur.com/1sqrx.png" alt="Example"></p>
<p><strong>Data</strong>:</p> <pre><code> a b c d e f g 1 1.0 NaN NaN NaN NaN NaN NaN 2 NaN NaN NaN NaN NaN 1.0 NaN 3 NaN NaN NaN 1.0 NaN NaN NaN 4 NaN NaN NaN 1.0 NaN 1.0 NaN </code></pre> <p><strong>Option 1</strong>: You can use <code>np.where</code>:</p> <pre><code>rows, cols = np.w...
python|pandas|dataframe
2
362,463
59,461,100
Python/Pytorch - how to use Image arrays?
<p>I want to put image data in a neural network, but I am having trouble using the Image datatype. I read my data here using Pytorch;</p> <pre><code>import torch import torchvision import numpy as np from settings import Settings class Data_Read: @staticmethod def getTrain(): train_dataset = torchvisi...
<p>First of all, your <code>Imagez</code> class returns list of <code>PIL</code> images, those cannot be used for training as you need number representations.</p> <p>Easy fix would be:</p> <pre><code>import torchvision class Imagez: @staticmethod def Get(arr): imageData = [] for item in arr:...
python|pytorch
1
362,464
59,239,922
Python: DataError: No numeric types to aggregate
<p>ok Im getting this error:DataError: No numeric types to aggregate Im trying to plot a csv file and its not working. Any advice? Thank you This is my code:</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv('spacestocksinfo.csv', skipinitial...
<p>So I noticed a lot of people have had this error. Let me explain the issue. OK so I had to clean the data. One company did not post data for a period of time, that lead to the data being incomplete. I had to delete the parts of the csv that didnt post data. That was causing the error. Once that was dont my code ran....
python|pandas|matplotlib|seaborn
0
362,465
59,152,826
Why "conv1d" is different in C code, python and pytorch
<p>I want to reproduce "Conv1D" results of pytorch in C code.</p> <p>I tried to implement "Conv1D" using three methods (C code, Python, Pytorch), but the results are different. Only seven fraction digits are reasonable. Assuming there are multiple layers of conv1d in the structure, the fraction digits accuracy will gr...
<p>Floating point numbers are not precise (by design). Depending on in which order operations are performed, the results might vary. Even worse, some formulas are straight numerical unstable, whereas another one for the same analytical expression can be stable.</p> <p>Compilers often rearange statements as an optimiza...
python|c|conv-neural-network|pytorch
2
362,466
59,228,416
Merging 2 dataframes when key values are slightly different
<p>I would like to merge 2 dataframes, Problem is that the keys I am using do not contain the exact same values. So for example this is what df1 looks like</p> <pre><code>name val3 Wilder Deontay 1 Fury Tyson 2 Ortiz Luis...
<p>Here is my solution,</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; from fuzzywuzzy import fuzz &gt;&gt;&gt; data = { 'name': ['Wilder Deontay', 'Fury Tyson', 'Ortiz Luis', 'Joshua Olaseni Oluwafemi Anthony'], 'val3': [1, 2, 3, 4] }... ... ... &gt;&gt;&gt; ...
python|pandas
1
362,467
59,311,899
Many to many join behaviour
<p>Not really sure how to title this question, but here's the situation. I have one data frame (dfOrders) that has an order_id and basic information like so:</p> <pre><code>|order_id|full_name|order_date|billing|shipping| ------------------------------------------------ |1234567 |John Doe |1/1/2019 |Address|Address1|...
<p>Usually we do <code>cumcount</code> </p> <pre><code>dfOrders['New']=dfOrders.groupby('order_id').cumcount() dfStandardized['New']=dfStandardized.groupby('order_id').cumcount() out=dfOrders.merge(dfStandardized, on = ['order_id','new'], how = 'inner').drop('New',1) </code></pre>
python|sql|pandas
1
362,468
59,200,290
in pandas , add scatter plot to line plot
<p>I am trying to add a scatter plot to a line plot by using plandas plot function (in jupyter notebook).</p> <p>I have tried the following code :</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt %matplotlib inline # plot the line a = pd.DataFrame({'a': [3,2,6,4]}) ax = a.plot.line() # try to add...
<p>This should do it (just add <code>fig, ax = plt.subplots()</code> in the beginning):</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt %matplotlib inline fig, ax = plt.subplots() # plot the line a = pd.DataFrame({'a': [3,2,6,4]}) a.plot.line(ax=ax) # try to add the scatterplot b = pd.DataFrame({...
python|pandas|matplotlib
4
362,469
13,934,959
Data binning: irregular polygons to regular mesh
<p>I have thousands of polygons stored in a table format (given their 4 corner coordinates) which represent small regions of the earth. In addition, each polygon has a data value. The file looks for example like this:</p> <pre><code>lat1, lat2, lat3, lat4, lon1, lon2, lon3, lon4, data 57.27, 57.72, 57.68, ...
<p>There are plenty of ways to do it, but yes, Shapely can help. It appears that your polygons are quadrilateral, but the approach I'll sketch doesn't count on that. You won't need anything other than <a href="http://toblerity.github.com/shapely/manual.html#shapely.geometry.box" rel="nofollow">box()</a> and <a href="ht...
python|numpy|scipy|gis|postgis
3
362,470
45,232,767
Arrange data in Dataframe based on dates
<p>Given the data of the form: </p> <pre><code>ID Date Highlight 1 201501 B 2 201506 C 1 201507 A 3 201508 D 2 201509 A 3 201510 B 3 201501 B </code></pre> <p>Required Output (in a dataframe) -- against every ID I need a sequence in order of the time of occurrence:</p> <pre><code>ID ...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>sort_values</code></a> ...
python|python-3.x|pandas|numpy|dataframe
2
362,471
45,195,073
Missing elements while comprehensing with np.all and getting removed indexes
<p>I have a data set with the size of (400,40). Some of the columns are completely zero. They are not necessary for the calculations (I need to ignore them), but they are needed to rewrite the file.</p> <p>So I'm using numpy to import it as an array, get the initialization done. But a problem occurs when I try to inve...
<p>There's a mistake in your logic. You don't want to discard the columns where all values are <strong>nonzero</strong>. Given the explanation you want to discard columns that are all zero:</p> <p>For example:</p> <pre><code>arr = np.array([[1, 1, 0, 1, 0, 0, 1, 0, 0, 1], [1, 0, 0, 1, 1, 1, 1, 0, 0, 1...
python|windows|python-3.x|numpy
2
362,472
44,915,464
Visualize embedding in tensorboard
<p>I used tensorflow script <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/word2vec/word2vec_basic.py" rel="nofollow noreferrer">word2vec_basic.py</a> and I saved the model with tf.summary : saver = tf.train.Saver() save_path = saver.save(sess, "./w2v/model.ckpt")</p...
<p>I used this answer: <a href="https://stackoverflow.com/questions/41708106/linking-tensorboard-embedding-metadata-to-checkpoint">linking-tensorboard-embedding-metadata-to-checkpoint</a></p> <p>the problem was I tried o call tensorboard with logdir : "./w2v/model.ckpt" I should called it only with "w2v/"</p>
python|tensorflow|word2vec
0
362,473
45,004,196
Python pandas counting
<p>I have a dataframe of "sentences", from which I wish to search for a keyword. Let's say that my keyword is just the letter 'A'. Sample data:</p> <pre><code>year | sentence | index ----------------------- 2015 | AAX | 0 2015 | BAX | 1 2015 | XXY | -1 2016 | AWY | 0 2017 | BWY | -1 </code></p...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>value_counts</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>GroupBy.size</co...
python|pandas
2
362,474
44,826,458
GridSearch in Keras + TensorFlow resulting in Resource exhausted
<p>I know that this error is recurrent and I understand what can cause it. For example, running this model with 163 images of 150x150 gives me the error (however it's not clear to me why setting batch_size Keras still seems to try to allocate all images at a time in the GPU):</p> <pre><code>model = Sequential() mo...
<p>You should work with generators + <code>yield</code>, they discard from the memory the data they already used. Check out my <a href="https://stackoverflow.com/questions/44569938/memory-issues-using-keras-convolutional-network/44593430#44593430">answer</a> to a similar question.</p>
memory-management|out-of-memory|gpu|keras|tensorflow
2
362,475
45,081,194
Tensorflow DNNRegressor Multiple Outputs
<p>I am trying to use <code>tf.contrib.learn.DNNRegressor</code> to model a multi-input multi-output system. I have followed the <a href="https://www.tensorflow.org/versions/r0.12/tutorials/input_fn/" rel="nofollow noreferrer">Boston DNNRegressor example</a> on the Tensorflow website, however when I try to pass an arra...
<p>This might be more than a little too late, but the current <code>tf.estimator.DNNRegressor</code> has an argument <code>label_dimension</code> that might do what you're looking for.</p> <pre><code>regressor = estimator.DNNRegressor(feature_columns=my_feature_columns, label_dimensi...
python|machine-learning|tensorflow
2
362,476
44,994,120
Applying neural network algorithms on Encrypted data
<p>I have encrypted text dataset and i want to classify it using neural network algorithm. I know that there is a pattern in the encrypted data. example of my input data : </p> <p>diss%^ghghE(t dffd$#KL*vb xod@#:n>did ....</p> <p>My questions is should i treat encrypted data as if its normal text and create vocabular...
<p>By definition, a good encryption algorithm will not allow you to learn <em>anything</em>[*] from the encrypted data.</p> <p>So, unless you suspect that the encryption algorithm is weak, I suggest you abandon this idea.</p> <p>[*] apart from the approximate size of the original text</p>
machine-learning|tensorflow|neural-network|data-processing
2
362,477
45,002,441
Getting a dictionary with no column info
<p>I had a pandas dataframe and wanted to turn it into a dictionary that I could search. The dataframe looks like this:</p> <pre><code> 1 0 ko1 836 ko2 786 ko3 898 </code></pre> <p>There were no column names so the headers were automatically set as 1 and 0 and I made column 0 the index...
<p>Just slice the Series first and then call the method:</p> <pre><code>x[1].to_dict() Out: {'ko1': 836, 'ko2': 786, 'ko3': 898} </code></pre>
python|pandas|dictionary
4
362,478
44,892,900
Get the first n/2 of n words in a column in a pandas data frame
<p>I would like to get the first n/2 of n words in a column in a pandas data frame. Each row can have a different number of words, but every row has an even number of words. This column contains the name of an item, but every name is duplicated. For example, <code>One</code> became <code>One One</code> and <code>One Tw...
<pre><code>df = pd.DataFrame(['One One', 'One Two One Two']) def proc(s): l = s.split() return ' '.join(l[:len(l) // 2]) df[1] = [proc(s) for s in df[0].values.tolist()] 0 1 0 One One One 1 One Two One Two One Two </code></pre>
python|pandas
3
362,479
45,144,946
Experimenting with creating OCR in tensorflow, what to do after training on letters?
<p>Honestly, i'm just stuck and can't think. I have worked hard to create an amazing model that can read letters, but how do I move on to words, sentences, paragraphs and full papers?</p> <p>This is a general question so forgive me for not providing code, but assume I have successfully trained a network at recognizing...
<p>Check out the following links for ideas:</p> <ul> <li><a href="https://github.com/Bartzi/stn-ocr" rel="nofollow noreferrer">STN-OCR: A single Neural Network for Text Detection and Text Recognition</a></li> <li><a href="https://medium.com/syncedreview/stn-ocr-a-single-neural-network-for-text-detection-and-text-recog...
python|opencv|image-processing|tensorflow|ocr
1
362,480
45,100,159
How to use Tensorboard with Tflearn
<p>I am used tflearn yet I want to use the tensorboard and its visualization how can I use it? how to get the session form tflearn?</p> <p>for example for this example (Pannous speech_data) <a href="https://github.com/llSourcell/tensorflow_speech_recognition_demo/blob/master/demo.py" rel="nofollow noreferrer">https://...
<p>TFLearn supports a verbose level to automatically manage summaries. Setting it to <code>3</code> will enable visualization.</p> <p>Set,</p> <pre><code>model = tflearn.DNN(net, tensorboard_verbose=3) </code></pre> <p>You can learn more about it in the <a href="http://tflearn.org/getting_started/#visualization" rel...
tensorflow|tensorboard|tflearn
4
362,481
44,850,956
How to avoid map object error in this autocorrelation script
<p>Hello I'd like to use this autocorrelation script, I found here:</p> <p><a href="https://stackoverflow.com/a/20463466/8238271">https://stackoverflow.com/a/20463466/8238271</a></p> <pre><code>import numpy def acf(series): n = len(series) data = numpy.asarray(series) mean = numpy.mean(data) c0 = nump...
<p>I'm assuming you want a <code>list</code> returned instead.</p> <p>To do that, change this line:</p> <pre><code>acf_coeffs = map(r, x) </code></pre> <p>To this:</p> <pre><code>acf_coeffs = list(map(r, x)) </code></pre> <p><strong>Explanation:</strong> The code you copied was probably written for Python 2. The <...
python|arrays|numpy|object|mapping
3
362,482
45,040,312
Filter pandas dataframe by list
<p>I have a dataframe that has a row called &quot;Hybridization REF&quot;. I would like to filter so that I only get the data for the items that have the same label as one of the items in my list.</p> <p>Basically, I'd like to do the following:</p> <pre><code>dataframe[dataframe[&quot;Hybridization REF&quot;].apply(lam...
<p>Suppose <code>df</code> is your <code>dataframe</code>, <code>lst</code> is our <code>list</code> of labels.</p> <pre><code>df.loc[ df.index.isin(lst), : ] </code></pre> <p>Will display all rows whose index matches any value of the list item. I hope this helps solve your query.</p>
python|pandas|numpy|data-science
18
362,483
45,149,588
Change in date from string to datetime object when converting pandas dataframe to dictionary
<p>I have the foll. dataframe:</p> <pre><code> avi fi_id dates 2017-07-17 0.318844 zab_a_002 2017-07-17 </code></pre> <p>When I convert it into a dictionary, I get this:</p> <pre><code>dict_avi = df.reset_index().to_dict('records') [{'index': Timestamp('2017-07-17 00:00:00'), 'avi': ...
<p>You want to make just the datetime columns strings instead</p> <p>First, make sure those columns are actually of <code>dtype</code> <code>datetime</code></p> <pre><code>df['index'] = pd.to_datetime(df['index']) df['dates'] = pd.to_datetime(df['dates']) </code></pre> <p>Since we went through this trouble, we could...
python|pandas
11
362,484
45,172,122
How to mix pandas and beautifulsoup to extract some element tags from a directory of xml files?
<p>I have a directory with several xml files. Some files have the following element tags at the bottom of the document:</p> <pre><code>&lt;items&gt; &lt;item id="id1" grocery="apple"&gt; &lt;stock id="id1.N1" alt="True" alt_id="10069227" type="fruit" type_id="10067060" /&gt; &lt;/item&gt; &lt;item id...
<pre><code>import pandas as pd from cytoolz.dicttoolz import merge from cytoolz import concat from bs4 import BeautifulSoup from glob import glob lox = glob('./*xml') def p_item(i): s = i.find_all('stock') return merge([j.attrs for j in s] + [i.attrs]) def p_soup(f): soup = BeautifulSoup(open(f), "lxml")...
python|xml|python-3.x|pandas|beautifulsoup
2
362,485
45,103,297
Add a title to a pandas.core.series.Series
<p>So I have this code to read an excel file:</p> <pre><code>import pandas as pd DataFrame = pd.read_excel("File.xlsx", sheetname=0) DataFrame.groupby(["X", "Y"]).size() res = DataFrame.groupby(["X", "Y"]).size() print res </code></pre> <p>This code: </p> <pre><code>res = DataFrame.groupby(["X", "Y"]).size() </cod...
<p>Try either:</p> <pre><code>res.rename('Z').sort_values().to_excel(...) </code></pre> <p>Or:</p> <pre><code>res.rename('Z').to_frame().sort_values(by='Z').to_excel(...) </code></pre>
python|pandas
2
362,486
44,873,802
What is tf.bfloat16 "truncated 16-bit floating point"?
<p>What is the difference between tf.float16 and tf.bfloat16 as listed in <a href="https://www.tensorflow.org/versions/r0.12/api_docs/python/framework/tensor_types" rel="noreferrer">https://www.tensorflow.org/versions/r0.12/api_docs/python/framework/tensor_types</a> ?</p> <p>Also, what do they mean by "quantized integ...
<p><code>bfloat16</code> is a tensorflow-specific format that is different from IEEE's own <code>float16</code>, hence the new name. The <code>b</code> stands for (Google) Brain.</p> <p>Basically, <code>bfloat16</code> is a <code>float32</code> truncated to its first 16 bits. So it has the same 8 bits for exponent, and...
tensorflow
21
362,487
44,976,352
Groupby max value and return corresponding row in pandas dataframe
<p>My dataframe consists of students, dates, and test scores. I want to find the max date for each student and return the corresponding row (ultimately, I am most interested in the student's most recent score). How could I do this in pandas?</p> <p>Let's say my dataframe looks like this (an abbreviated version):</p> ...
<p>You can sort the data frame by Date and then use <code>groupby.tail</code> to get the most recent record:</p> <pre><code>df.iloc[pd.to_datetime(df.Date, format='%m/%d/%y').argsort()].groupby('Student_id').tail(1) #Student_id Date Score #2 Lia1 12/13/16 0.845 #0 Tina1 1/17/17 0.950 #3 John2 ...
python|pandas|dataframe|group-by|max
2
362,488
45,223,590
TensorFlow: AttributeError: 'dict' object has no attribute 'SerializeToString'
<p>In Tensorflow, I have set up a neural network as follows:</p> <pre><code>x = tf.placeholder(tf.float32) x_ = tf.placeholder(tf.float32) th = tf.placeholder(tf.float32) th_ = tf.placeholder(tf.float32) rlu_1 = tf.contrib.layers.fully_connected(inputs=tf.reshape([x,x_,th,th_],[1,4]),num_outputs=10) # 4 state featu...
<p>Try to send list of <code>[train,tf.argmax(Qvals,0)]</code> to the <code>sess.run</code> </p> <pre><code>train_,nextAction = sess.run([train,tf.argmax(Qvals,0)], {x:prev_observation[0],x_:prev_observation[1], th:prev_observation[2],th_:prev_observation[3], ...
python|tensorflow
1
362,489
45,254,174
How do pandas Rolling objects work?
<p><strong>Edit:</strong> I condensed this question given that it was probably too involved to begin with. The meat of the question is in bold below.</p> <p>I'd like to know more about the object that is actually created when using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolli...
<p>I suggest you have a look at the source code in order to get into the nitty gritty of what rolling does. In particular I suggest you have a look at the <code>rolling</code> functions in <a href="https://github.com/pandas-dev/pandas/blob/v0.20.3/pandas/core/generic.py#L6188-L6195" rel="noreferrer">generic.py</a> and ...
python|pandas|numpy|dataframe|cython
46
362,490
44,929,456
Python array dimensions
<p>I'm currently learning numpy and I find 'Array Dimensions' . Can anyone explain to me what are array dimensions ? How to find out the dimensions of an array ? Thank you ,</p>
<p>You can print a tuple of the dimensions of an array like so: </p> <pre><code>print array.shape </code></pre> <p>Let's say it was (2,3). Your array might be: [[1,2,3],[3,2,1]] So basically the first dimension is the number of elements in the outer part, then the second is the number of elements in an inner part, an...
arrays|python-2.7|numpy|dimensions
0
362,491
45,201,195
Reading numpy matrix in batches in Tensorflow
<p>I am trying to run some regression models on GPU. While I get a very low GPU utilization upto 20%. After going through the code, </p> <pre><code> for i in range(epochs): rand_index = np.random.choice(args.train_pr, size=args.batch_size) rand_x = X_train[rand_index] rand_y = Y_train[rand_index] <...
<p>You have a large numpy array that lies on the host memory. You want to be able to process it in parallel on the CPU and send batches to the device.</p> <p>Since TF 1.4, the best way to do it is to use <code>tf.data.Dataset</code>, and particularly <code>tf.data.Dataset.from_tensor_slices</code>. However, as <a href...
python|numpy|tensorflow|gpu
3
362,492
44,949,953
How to add a row to a pandas DataFrame without flattening the MultiIndex
<p>I have trouble with adding a single row to a MultiIndexed DataFrame in an efficient way. By adding the row, the MultiIndex is flattened to a simple Index of Tuples. Strangely this is not a problem for MultiIndexed columns.</p> <p>System info:</p> <pre><code>Python 3.6.1 |Continuum Analytics, Inc.| (default, Mar 22...
<p>I think you need tuple with define both values of <code>MultiIndex</code>:</p> <pre><code>df.loc[('last_row', 'a'), :] = 43 print(df) col_0 dull shiny col_1 a b a b row_0 row_1 bar one 1.0 1.0 1.0 1.0 two 1.0 1.0...
python|pandas|dataframe
3
362,493
45,144,935
split pandas dataframe into two based on day of the week
<p>I have a data frame that looks like the image below:</p> <p><img src="https://i.imgur.com/sW6gjt3.png" alt="Image"></p> <p>the data frame is called <code>df_original</code>.</p> <p>How do I split it so that I end up with a <code>df_weekend</code> which contains all the data that occurs on Saturday and Sundar, and...
<p>Let's use boolean indexing:</p> <pre><code>mask = df_original['day'].isin(['Saturday','Sunday']) df_weekend = df_original[mask] df_weekday = df_original[~mask] </code></pre>
python|database|python-2.7|pandas|anaconda
2
362,494
45,110,646
How is this function programatically building a LSTM
<p>Here is the code:</p> <pre><code>def lstm(o, i, state): #these are all calculated seperately, no overlap until.... #(input * input weights) + (output * weights for previous output) + bias input_gate = tf.sigmoid(tf.matmul(i, w_ii) + tf.matmul(o,w_io) + b_i) #(input * forget weights) + (output * we...
<p><a href="http://colah.github.io/posts/2015-08-Understanding-LSTMs/" rel="nofollow noreferrer">This</a> is an excellent blogpost on LSTMs. This code is directly implementing the LSTM; the code here is equivalent to the equations listed on <a href="https://en.wikipedia.org/wiki/Long_short-term_memory#Traditional_LSTM"...
tensorflow|neural-network|lstm|recurrent-neural-network
0
362,495
44,965,880
3d array access in numpy
<p>I have NxMx3 numpy array and want to get access to subarrays of size 3. For example I want instead of</p> <pre><code>arr = [[[...]]] for i in range(N): for j in range(M): b = do_something(arr[i][j]) </code></pre> <p>write</p> <pre><code>map(lambda x: do_something(x), ???) # x - is array of size 3 </co...
<p>If possible, you should manually vectorize your original function, because making use of vectorized arithmetic would be the most efficient solution.</p> <p>If you don't want to or can't do that, you can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html#numpy.vectorize" rel="nofo...
python|arrays|python-3.x|numpy
0
362,496
44,866,579
TensorBoard doesn't do anything upon execution
<p>Whenever I execute TensorBoard I just get:</p> <pre><code>Starting TensorBoard 54 at http://localhost:6006 (Press CTRL+C to quit) </code></pre> <p>and then nothing happens. Any advice on how to get the graph to show? </p> <p>EDIT: Sorry I meant to clarify that I copy and paste "<a href="http://localhost:6006" rel...
<p>One possible reason might be not giving the correct log directory, and at other times people often forget to write back summaries.</p>
tensorflow|tensorboard
0
362,497
45,125,441
How to mask columns with some nan values, using regular expressions in pandas?
<p>I have a dataframe that has a column of boroughs visited (among many other columns):</p> <pre><code>Index User Boroughs_visited 0 Eminem Manhattan, Bronx 1 BrSpears NaN 2 Elvis Brooklyn 3 Adele Queens, Brooklyn </code></pre> <p><strong>I want to create a third column that shows whi...
<p>Let use <code>.str</code> accessor with <code>contains</code> and <code>fillna</code>:</p> <pre><code>df['Brooklyn'] = (df.Boroughs_visited.str.contains('Brooklyn') * 1).fillna(0) </code></pre> <p>Or another format of the same statement:</p> <pre><code>df['Brooklyn'] = df.Boroughs_visited.str.contains('Brooklyn')...
python|pandas|numpy|dataframe
2
362,498
45,128,523
pandas multiindex - how to select second level when using columns?
<p>I have a dataframe with this index:</p> <pre><code>index = pd.MultiIndex.from_product([['stock1','stock2'...],['price','volume'...]]) </code></pre> <p>It's a useful structure for being able to do <code>df['stock1']</code>, but how do I select all the price data? I can't make any sense of the documentation.</p> <p...
<p>Also using John's data sample:</p> <p>Using <code>xs()</code> is another way to slice a <code>MultiIndex</code>:</p> <pre><code>df 0 stock1 price 1 volume 2 stock2 price 3 volume 4 stock3 price 5 volume 6 df.xs('price', level=1, drop_level=False) 0 stock1...
python-3.x|pandas
111
362,499
44,980,556
A better/faster way to handle human names in Pandas columns?
<p>I am dealing with a large amount of data that includes the standard five columns for human names (prefix, firstname, middlename, lastname, suffix) and I would like to merge them in a separate column as a readable name. The issue I have is with handling blank values - the issue creates spacing problems. Also, I canno...
<p><strong>Option 1</strong><br> <em><code>' '.join</code> and <code>pd.Series.str</code></em><br> In this solution we join the entire row by spaces. This may lead to spaces at the beginning or end of the string or with 2 or more spaces in the middle. We handle this by chaining string accessor methods.</p> <pre><cod...
python|pandas
4