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
16,700
39,953,068
Python Pandas: select column with the number of unique values greater than 10
<p>In R, we can use <code>sapply</code> to extract columns with the number of unique values greater than 10 by:</p> <pre><code>X[, sapply(X, function(x) length(unique(x))) &gt;=10] </code></pre> <p>How can we do the same thing in Python Pandas?</p> <p>Also, how can we choose columns with missing proportion less t...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.nunique.html" rel="noreferrer"><code>nunique</code></a> with <code>apply</code>, because it works only with <code>Series</code>:</p> <pre><code>print (df.ix[:, df.apply(lambda x: x.nunique()) &gt;= 10]) </code></pre> <p>and se...
python|pandas
8
16,701
40,257,607
tf.contrib.learn Quickstart: - Changing n_classes to 2 does not work
<p>I'm trying out the <a href="https://www.tensorflow.org/versions/r0.11/tutorials/tflearn/index.html#tf-contrib-learn-quickstart" rel="nofollow">tf.contrib.learn Quickstart</a>, and it works when using the code given in the tutorial. But, if I change the training and test sets to just have 2 classifications (i.e. only...
<p>I encountered the same bug and apparently it's a bug from tensorflow, see link below for further information :</p> <p><a href="https://stackoverflow.com/questions/40193505/shape-error-using-tensorflow-tf-learn-dnnclassifier">Shape error using Tensorflow (tf.learn, DNNClassifier)</a></p> <p>I fixed it with set n_cl...
python|tensorflow
1
16,702
44,332,735
Deadlock in tensorflow's MonitoredTrainingSession and slice input producer
<p>The code below deadlocks:</p> <pre><code>import tensorflow as tf def train(): """Stripped down and modified from cifar10.cifar10_train.train""" global_step = tf.contrib.framework.get_or_create_global_step() # for StopAtStepHook images = tf.constant([[1, 2, 3], [1, 2, 3]]) labels = tf.constant([[1, ...
<ol> <li><p>I'm not sure about your first question but I believe what happens is that when you create the MonitoredTrainingSession it tries to initialise the variables of your graph. But in your case, one of the variable initial value relies on a dequeue operation hidden behind <code>tf.train.slice_input_producer</code...
python|tensorflow|deadlock
1
16,703
43,978,621
How could I define a tf.Variable in my own function in tensorlfow?
<pre><code>import tensorflow as tf import numpy as np def myfunction(): return_variable = tf.Variable(initial_value=0.0, dtype=tf.float32) return return_variable a = np.random.randint(1, 5, size=(3, 2, 2)) a_variable = tf.Variable(a, tf.float32) with tf.Session() as sess: sess.run(tf.initialize_all_varia...
<p>The variable is only created when you call <code>myfunction()</code>, and initialized if it is already created when you run <code>tf.initialize_all_variables()</code>. So you just need to call <code>myfunction()</code> before initializing all your variables. Usually you build your whole graph, using <code>myfunction...
tensorflow
0
16,704
69,429,965
Pandas value_counts for a column based on value of different column
<p>I have a dataframe 'students' that looks like the following:</p> <pre><code> Cumulative.GPA Athlete 0 3.9 Yes 1 3.3 Yes 2 4.0 No 3 3.6 Yes </code></pre> <p>I'm trying to get a value_counts table of GPAs separated into two columns: 1...
<p>We can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>crosstab</code></a> to count the frequencies of Athlete vs non-athlete GPA then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="...
pandas
0
16,705
69,512,025
Numpy Sum Rows of 2D Array uniquely (no sequence duplicates)
<p>I have the following array</p> <pre><code>import numpy as np single_array = [[ 1 80 80 80] [ 2 80 80 89] [ 3 52 50 90] [ 4 39 34 54] [ 5 37 47 32] [ 6 42 42 27] [ 7 42 52 27] [ 8 38 33 28] [ 9 42 37 42]] </code></pre> <p>and want to create another array with all unique sums of 2 rows within this single_arra...
<p>This</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from itertools import combinations single_array = np.array( [[ 1, 80, 80, 80], [ 2, 80, 80, 89], [ 3, 52, 50, 90], [ 4, 39, 34, 54], [ 5, 37, 47, 32], [ 6, 42, 42, 27], [ 7, 42, 52, 27], [ 8, 38, 33, 28], [ 9, 42, 37, 42]] ) np.vst...
arrays|python-3.x|numpy
0
16,706
69,325,501
Pandas DataFrame Map With Custom Value
<p>First DataFrame</p> <pre><code>df1 = pd.DataFrame({'Original Invoice ID' : ['IN-11','IN-12','IN-13','IN-14','IN-15','IN-16'], 'ORDER ID' : ['123','123','123','456','996','864'], 'ASIN' : ['ABC','ABC','ABD','KSF','HKS','AJK']}) </code></pre> <p>Second DataFrame</p> <pre><code>d...
<p>You might have a mistake in the provided output (IN-14 instead of IN-13).</p> <p>Anyway, IIUC, you want to merge on your keys in order of the rows. For this you need to create another key for the order:</p> <pre><code>cols = ['ORDER ID', 'ASIN'] (df2.assign(key=df2.groupby(cols).cumcount()) .merge(df1.assign(key...
python|pandas|dataframe
0
16,707
53,978,966
Initialize parameters as zeros in Python
<p>I tried to implement parameter initialization and got the error message:</p> <pre><code>import numpy as np def initialize_with_zeros(dim): w = np.zeros(dim, 1) b = 0 return w, b dim = 2 initialize_with_zeros(dim) </code></pre> <hr> <p><strong>Here is the Error:</strong></p> <blockquote> <p>TypeEr...
<p><a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.zeros.html" rel="nofollow noreferrer">np.zeros</a> takes only the shape as a tuple or a single integer (in case of 1-d arrays). If you just need a 1 dimensional array, pass a single parameter. If you need a 2d-array, pass as a tuple (dim,1). ...
python|numpy
6
16,708
54,223,970
How to add border color to an html character using css?
<p>I am currently tasked to create checks inside of a pandas DataFrame table of different colors when certain data is showing.</p> <p>I was able to find the following:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-co...
<p>You can create a box by border and make the font-size change as done in the snippet.</p> <p>Another option is you can Search google with keywords <strong>checkbox fafa icon</strong> or <strong>check icon fafa</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="fals...
html|css|pandas|css-selectors
1
16,709
53,987,978
Generating a fibonacci pyramid
<p>How can I generate the following pyramid (where the first and second rows are imposed beforehand)?</p> <pre><code> 1 1 4 1 1 5 6 5 1 1 6 12 16 12 6 1 </code></pre> <p>This is what I've tried so far, but it didn't work:</p> <pre><code>def main(): first_row = [1] # given in th...
<p>This seems like a variation of what would be a fibonacci pyramid, where the second row should be a <code>[1,1]</code> instead. </p> <p>A nice and concise way to add rows to the sequence would be to convolve the preceding row with <code>[1,1,1]</code>. You can use <a href="https://docs.scipy.org/doc/numpy-1.15.0/ref...
python|arrays|list|numpy
2
16,710
65,940,166
Create 2D hanning, hamming, blackman, gaussian window in NumPy
<p>I am interested in creating 2D hanning, hamming, Blackman, etc windows in NumPy. I know that off-the-shelf functions exist in NumPy for 1D versions of it such as <code>np.blackman(51)</code>, <code>np.hamming(51)</code>, <code>np.kaiser(51)</code>, <code>np.hanning(51)</code>, etc.</p> <p>How to create 2D versions o...
<p>That looks reasonable to me. If you want to verify what you are doing is sensible, you can try plotting out what you are creating.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 1.5, 51) y = np.linspace(0, 1.5, 51) window1d = np.abs(np.blackman(51)) window2d = np.sqrt(np.oute...
numpy|signal-processing|fft|dft
3
16,711
52,575,694
Calculate total number of values per day with pandas
<p><strong>I have the following data frame</strong></p> <pre><code> UNIT C/A DATETIME TOTAL COUNTs R248 HOO7 2018-03-03 03:00:00 139.0 2018-03-03 07:00:00 927.0 2018-03-04 11:00:00 1946.0 2018-03-05 07:00:00 1330.0 ...
<p>Use if 3 levels <code>MultiIndex</code> use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.floor.html" rel="nofollow noreferrer"><code>floor</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow noreferrer"><code>date</...
python|python-3.x|pandas|datetime
3
16,712
52,466,061
"Tensorflow GPU" version and MX150 2GB GPU
<p>I am considering to buy a laptop to run "Tensorflow GPU" version. The MX150 2GB is not listed under the list of GPU compatible with CUDA. Does that mean it cannot run the "Tensorflow GPU" version but only the standard Tensorflow version?</p>
<p>Yes it can. I am currently using MX150 on my laptop with ubuntu 18.04 and I have successfully installed tensorflow gpu on it. According to MX150 on the <a href="https://www.geforce.com/hardware/notebook-gpus/geforce-mx150" rel="noreferrer">product site</a> it says that it is CUDA compatible. Remember to <a href="htt...
tensorflow|cuda|gpu|nvidia
6
16,713
46,242,660
Dropout for LSTM recurrent weights in tensorflow
<p>Tensorflow's <code>DropoutWrapper</code> allows to apply dropout to either the cell's inputs, outputs or states. However, I haven't seen an option to do the same thing for the recurrent weights of the cell (4 out of the 8 different matrices used in the original LSTM formulation). I just wanted to check that this is ...
<p>It's because original LSTM model only applies dropout on the input and output layers (only to the non-recurrent layers.) This paper is considered as a "textbook" that describes the LSTM with dropout: <a href="https://arxiv.org/pdf/1409.2329.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1409.2329.pdf</a></p> ...
python|tensorflow|lstm
0
16,714
46,624,010
Tensorflow : get prediction out of graph file (.pb file)
<p>i am using a graph file (pb file), the aim of this Tensorflow model is to provide a prediction on certain image </p> <p>i have developed a code that loaded graph file but i can't stat session . the files available are :-</p> <ul> <li>training_model_saved_model.pb</li> <li>variables <ul> <li>training_model_variab...
<p>You appear to be mixing the TensorFlow Serving SavedModel format with the regular TensorFlow export/restore functionality.</p> <p>This is a particularly confusing part of the TensorFlow codebase as this format wasn’t well documented when it first appeared - and there aren’t a lot of examples showing when to use thi...
python|tensorflow|tensorboard
0
16,715
46,579,139
Distribute month's quantity equally into weeks
<p>Have two data frames:</p> <p>1) df</p> <pre><code> Month Qty ------------------- 0 2017-10-31 100 1 2017-11-30 200 </code></pre> <p>2) week</p> <pre><code> Week ---------- 0 2017-10-01 1 2017-10-08 2 2017-10-15 3 2017-10-22 4 2017-10-29 5 2017-11-05 6 2...
<p>Convert <code>datetimes</code> to <code>month</code> period by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.to_period.html" rel="nofollow noreferrer"><code>to_period</code></a> in both <code>df</code>.</p> <p>Then created <code>Series</code> for map column <code>Week</code> and di...
pandas
0
16,716
58,557,635
Neural Networks parameters are stable
<p>I am experimenting audio classification.</p> <p>My code -</p> <pre><code>x_train = (800, 32, 1) x_test = (200, 32, 1) y_train = (800, 1) y_test = (200, 1) model = Sequential() model.add(Conv1D(filters=64, kernel_size=20, padding='same', input_shape=(32,1), activation=&quot;relu&quot;)) model.add(MaxPooling1D(3)) ...
<p>There are two possible answers. You model is already at a local minimum or it is overshooting a local minimum. What you can do to test it is to set a lower learning rate in your optimizer function:</p> <pre><code>optimizer = Adam(lr=0.001) # change it to 0.001 or even lower </code></pre>
python|tensorflow|keras|conv-neural-network
0
16,717
58,279,173
Pandas, Python: Pass names of dataframes to function in a loop
<p>I have <code>n</code> dataframes, <code>df1, df2, df3,..., df_n</code> of arbitrary sizes and I want to pass them to various functions / methods. Passing them one at a time, <code>foo(df1)</code> to <code>foo(df_n)</code>, appears to be tedius, so I want to do it in a loop.</p> <p>If I create a list <code>dfs = ['d...
<p>On constructing <code>dfs = [df1, df2, ..., df_n]</code>, each element is a dataframe object. You need to access them as regular list using index such as <code>dfs[0]</code>, <code>df[1]</code>. </p> <p>As your requirement, you are better with constructing dictionary</p> <pre><code>dfs = {'df1': df1, 'df2': df2, '...
python|pandas
2
16,718
58,520,460
How to use the rank function in dask dataframe?
<p>How to use the pandas's <code>pd.rank()</code> function on dask dataframe. Or is there any alternative inbuild function in dask to do the same.</p>
<p>Currently this operation is not supported. It is hard to do in parallel, and rarely fully needed. You might instead collect the <code>nlargest</code> and then compute <code>pd.rank</code> on the computed pandas result?</p> <p>Alternatively, if you're trying to compute rank across columns then you could use <code>...
python|pandas|python-3.7|dask|rank
1
16,719
44,803,918
Create a one-hot panda dataframe
<p>I have a set of labels from <code>0</code> to <code>9</code>, like:</p> <pre><code>2 7 5 3 </code></pre> <p>I would like to convert that into a one-hot encoding, like this:</p> <pre><code>0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 </code></pre> <p>So I made this method:</p> ...
<p><strong>Approach #1 :</strong> Here's one approach with <code>NumPy broadcasting</code> -</p> <pre><code>In [143]: a = [2 ,7 ,5 ,3] In [144]: pd.DataFrame((np.asarray(a)[:,None] == np.arange(10)).astype(int)) Out[144]: 0 1 2 3 4 5 6 7 8 9 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0...
python|pandas
4
16,720
44,762,532
OutOfRangeError (see above for traceback): FIFOQueue '_1_batch/fifo_queue' is closed and has insufficient elements (requested 5, current size 0)
<p>i don't know how to solve this problem, this error message is useless for me to locate the problem. Thanks for helping!</p> <blockquote> <p>here is the data in e.csv, D.csv and F.csv</p> </blockquote> <pre><code>e.csv: 1,2,3 4,5,6 7,8,9 D.csv: 11,12,13 14,15,16 17,18,19 F.csv: 21,22,2...
<p>Problem is with filepaths. Please provide complete paths as shown below to fileName Queue. </p> <p>This works for me:</p> <pre><code>fileNameQueue.append('/home/****/Desktop/stackoverflow/data/' +file) </code></pre> <p>Hope this helps.</p>
python|csv|tensorflow
0
16,721
60,829,321
Since the indexes are same for both s and t, why is t returning NaN as the first value?
<p>The 1st value is NaN for the Series t but not for s. Why is it so even though the series have same indices.</p> <pre><code>import numpy as np import pandas as pd s = pd.Series([1,2,3,4,5,6],index= [1,2,3,4,5,6]) t = pd.Series([2,4,6,8,10,12],index= [1,2,3,4,5,6]) df = pd.DataFrame(np.c_[s,t],columns = ["MUL1","MUL2...
<p>If assign <code>Series</code> with different index values are generated missing values, like in first row. For correct assign need same values in <code>Series</code> and in <code>DataFrame</code>.</p> <p>Problem is <code>np.c_</code> return 2d array with no index values:</p> <pre><code>print (np.c_[s,t]) [[ 1 2] ...
python|pandas|numpy|dataframe|series
1
16,722
60,787,266
From 10 years of data, I want to select only calendar days with max or min value
<p>Ok, so I have a dataset of temperatures for each day of the year, over a period of ten years. Index is date converted to datetime. </p> <p>I want to get a dataset with only the min and max value for each calendar day throughout the 10-year period.</p> <p>I can convert the index to a string, remove the year and get...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html" rel="nofollow noreferrer"><code>Series.dt.strftime</code></a> with aggregate by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><co...
pandas|datetime
2
16,723
61,081,303
PyTorch gradient calculation gives unexpected results
<p>The following code is intended to explain how the PyTorch gradient calculation works, and it should, IMO return the weights matrix, but it doesn't:</p> <pre><code># the code calculates T x W + B ---&gt; K1 # compute the mean of K1 --&gt; km # compute the gradient of km relative to T # import torch torch.manual_seed...
<p>It's not strange, it is expected as <a href="https://pytorch.org/docs/stable/notes/autograd.html" rel="nofollow noreferrer">indicated by Autograd Mechanics in PyTorch documentation</a>:</p> <blockquote> <p>Backward computation is never performed in the subgraphs, where all Tensors didn’t require gradients.</p> ...
python|pytorch|gradient|matrix-multiplication|autograd
0
16,724
71,536,910
Use of underscore in interger values or Number values in Tensorflow documentation
<p>if we check below documentation <a href="https://www.tensorflow.org/recommenders/examples/basic_retrieval" rel="nofollow noreferrer">https://www.tensorflow.org/recommenders/examples/basic_retrieval</a> it uses underscore (_) in the integer values like for batch size . What does this underscore signifies is it same a...
<p>The underscores are for improved readability, but do not have any deeper meaning. See <a href="https://www.codingame.com/playgrounds/21/whats-new-in-python-3-6/pep-515-underscores-in-numeric-literals#:%7E:text=PEP%20515%3A%20Underscores%20in%20Numeric%20Literals,-PEP%20515%20adds&amp;text=Single%20underscores%20are%...
python|tensorflow|tensorflow2.0
1
16,725
71,615,001
Add a duplicate row and change the value of the duplicated row based on some other value in Pandas
<p>I want to merge 2 columns of the same dataframe, and add a duplicate row using the same values as it has in the other columns.</p> <p>consider the following dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column A</th> <th>Column B</th> <th>Column C</th> </tr> </thead> <tbody>...
<p>You can create a list of values from <code>Column A</code> and <code>Column B</code> columns then explode it:</p> <pre><code>result = df[['A', 'B']].replace('', np.nan).stack().groupby(level=0).apply(list) df = df.assign(Result=result.fillna('')).explode('Result') print(df) # Output A B C Result 0 ABC ...
python|pandas|dataframe
1
16,726
71,618,611
Multiply a [3, 2, 3] by a [3, 2] tensor in pytorch (dot product along dimension)
<p>Given the following tensors <code>x</code> and <code>y</code> with shapes <code>[3,2,3]</code> and <code>[3,2]</code>. I want to multiply the tensors along the 2nd dimension, this is expected to be a kind of dot product and scaling along the axis and return a <code>[3,2,3]</code> tensor.</p> <pre><code>import torch...
<p>This is just <a href="https://numpy.org/doc/stable/user/basics.broadcasting.html" rel="nofollow noreferrer">broadcasted</a> multiply. So you can insert a unitary dimension on the end of <code>y</code> to make it a <code>[3,2,1]</code> tensor and then multiply by <code>x</code>. There are multiple ways to insert unit...
python-3.x|pytorch|tensor
1
16,727
69,790,814
Tensorflow labels for classification aren't loaded properly in the model
<p>I'm having issues with the categories in in my data, I can't set the Dense softmax layer to &quot;3&quot; instead of &quot;1&quot; for 3 categories.</p> <p>I assume my issue is with vectorize_text, but I am not completely sure. I can also assume that I don't set the label tensors correctly.</p> <pre><code># Start of...
<p>Your issue is with your loss function. Categorical cross entropy in Keras requires the classes to not be in idx form, but as their target logits/activated outputs. So, your training losses should be of the form:</p> <pre><code>from tensorflow.keras.utils import to_categorical n_classes = 3 y = [0,1,2] #IMPORTANT TO ...
python|pandas|tensorflow|keras|tensorflow-datasets
1
16,728
69,863,938
Visualization of results from object detection with TensorFlow not displaying
<p>I am trying to test the <a href="https://github.com/ringringyi/DOTA_models" rel="nofollow noreferrer">SSD: Single Shot MultiBox Detector detection model pre-trained on the DOTA dataset</a> in TensorFlow. I have followed Google's guide and everything works fine with errors.</p> <p>However, after running the code belw...
<p>You're missing <code>plt.show()</code> at the end of your code, so the figure is being created but never displayed.</p>
python|tensorflow|machine-learning|data-visualization|object-detection
1
16,729
69,811,772
Pandas - Creating Two Columns From One Column With Intermixed Values
<p>I have a dataframe with values like such (sourced from somewhere else - I can't change the source data, unfortunately).</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Store/Date</th> <th>Sales</th> </tr> </thead> <tbody> <tr> <td>Store1</td> <td>nan</td> </tr> <tr> <td>10/15/21</td> <td...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.insert.html" rel="nofollow noreferrer"><code>DataFrame.insert</code></a> for new column for first position with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.where.html" rel="nofollow noreferrer...
python|pandas|dataframe
1
16,730
43,064,542
Tensorflow contrib.layers compatibility on Windows
<p>I'm currently trying to learn more about the layers API of tensorflow, for this I'm trying the cloud-ml samples (census: <a href="https://github.com/GoogleCloudPlatform/cloudml-samples/tree/master/census" rel="nofollow noreferrer">https://github.com/GoogleCloudPlatform/cloudml-samples/tree/master/census</a>).</p> <...
<p><strong>TL;DR:</strong> These ops should now work in the current nightly build of TensorFlow. I've sent out a <a href="https://github.com/tensorflow/tensorflow/pull/8808" rel="nofollow noreferrer">pull request</a> to add support in the upcoming 1.1 release.</p> <p>The explanation is a bit tortuous, but I'll attempt...
python|tensorflow
3
16,731
72,398,987
Combine unequal length lists to dataframe pandas with values repeating
<p>How to add a list to a dataframe column such that the values repeat for every row of the dataframe?</p> <pre><code>mylist = ['one error','delay error'] df['error'] = mylist </code></pre> <p>This gives error of unequal length as df has 2000 rows. I can still add it if I make mylist into a series, however that only ap...
<p>You can assign to the result of <code>df.to_numpy()</code>. Note that you'll have to use <code>[mylist]</code> instead of <code>mylist</code>, even though it's already a list ;)</p> <pre><code>&gt;&gt;&gt; mylist = ['one error'] &gt;&gt;&gt; df['error'].to_numpy()[:] = [mylist] &gt;&gt;&gt; df col1 col2 e...
pandas
0
16,732
50,325,261
Convert numpy array to RGB img with custom pallete
<p>I want to convert a numpy.ndarray:</p> <pre><code>out = [[12 12 12 ..., 12 12 12] [12 12 12 ..., 12 12 12] [12 12 12 ..., 12 12 12] ..., [11 11 11 ..., 10 10 10] [11 11 11 ..., 10 10 10] [11 11 11 ..., 10 10 10]] </code></pre> <p>to RGB img. </p> <p>The colors are taken from an arra...
<p>You can just use the full image as index for the look-up table. </p> <p>Something like <code>data = colors_pal[out]</code></p> <pre><code>import numpy as np import matplotlib.pyplot as plt import skimage.data import skimage.color # sample image, grayscale 8 bits img = skimage.color.rgb2gray(skimage.data.astronaut...
python|image|python-2.7|numpy
2
16,733
50,596,307
Weird behavior with pandas Grouper method with datetime objects
<p>I am trying to make groups of x days <em>within</em> groups of another column. For some reason the grouping behavior is <em>changed</em> when I add another level of grouping.</p> <p>See toy example below:</p> <p>Create a random dataframe with 40 consecutive dates, an ID column and random values:</p> <pre><code>im...
<p>When you group with both IDs, you have a spillover from the first group into the second when you perform a weekly groupby (because there are not enough days in the last week to complete a full 7 days in group #1). This is obvious when you look at the first date per group:</p> <p>"2018-01-08" in the first case v/s "...
python|pandas|datetime|group-by|pandas-groupby
2
16,734
62,677,043
How to train a model to classify input to one or more classes
<p>I use this sample code to train a model to classify a random number into a one of 10 classes</p> <pre><code>import numpy as np import tensorflow as tf from tensorflow import keras samples_number = 1000 features_number = 5 output_classes_number = 10 x_train = np.random.random((samples_number, features_number)) y_tra...
<p>Just change your final activation function to <code>sigmoid</code> and you will get the probability per class, and so it allows multi-label classification.</p> <p>Naturally, you will need labels that reflect this new task, which you don't seem to have at the moment.</p> <p>Full example:</p> <pre><code>import numpy a...
python|tensorflow|keras|text-classification
1
16,735
62,669,271
pandas data frame add value to a set in a column of a specified row
<p>I am trying to add a value to a set in a column of a specified row. For instance I have: (username and tags are column names)</p> <pre><code>username tags qwe (happy) </code></pre> <p>And I want to change that to:</p> <pre><code>username tags qwe (happy, friendly) </code></pre> <p>To be specific, I wan...
<p>Get the row of the searched user and add the new tag to the set of tags in that row. Since it is a <code>set</code>, you have to use <code>.add</code>.</p> <p>If your 'username' field is not the index -</p> <pre><code>df[df['username']=='qwe']['tags'].values[0].add(tag) </code></pre> <p>If your 'username' field is t...
python|pandas|dataframe
0
16,736
62,806,935
create a dataframe from multiple list
<p>I have several list:</p> <pre><code>a = [1, 2, 3, 4] b = [5, 6, 7, 8] c = [7, 8, 9, 10] </code></pre> <p>I would like a dataframe with 3 columns named automatically using names of the lists</p> <pre><code>a b c 1 5 7 2 6 8 3 7 9 4 8 10 </code></pre> <p>How to do this? Thank you.</p>
<p>You can create a Pandas DataFrame from a list using the code below:</p> <pre><code>import pandas as pd a = [1, 2, 3, 4] b = [5, 6, 7, 8] c = [7, 8, 9, 10] df = pd.DataFrame(list(zip(a, b, c)), columns =['a', 'b', 'c']) print(df) </code></pre> <p>Hope this helps!</p>
python|pandas
1
16,737
62,754,913
'Attempting to capture an EagerTensor without building a function' Error: While building Federated Averaging Process
<p>I am getting 'Attempting to capture an EagerTensor without building a function' error while trying to build my federated averaging process. I have tried all remedies for compatibility of v1 &amp; v2 given in other other similar stack overflow questions, viz., using tf.compat.v1.enable_eager_execution() , tf.disable_...
<p>This looks like tensors are being created outside and later being captured by <code>model_fn</code>. The comment inside <code>model_fn()</code> is related here:</p> <pre class="lang-py prettyprint-override"><code># We _must_ create a new model here, and _not_ capture it from an external scope. TFF # will call this ...
tensorflow|tensorflow2.0|tf.keras|tensorflow-federated
2
16,738
54,576,229
Merge pandas dataframes and create derived column
<p>Given 2 pandas dataframes </p> <p><strong>Med_DF</strong></p> <pre><code>Key Med 1 A 1 B 1 C 2 A 2 F 3 A 3 C 3 E 4 A 4 B 4 C 4 D </code></pre> <p><strong>Key_DF</strong></p> <pre><code>Key ID 1 A1 2 A2 3 A3 4 A4 5 A5 </code></pre> <p>How can I merge the two without duplicate <...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>join</code></a> with <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:...
python-3.x|pandas|merge
1
16,739
73,716,076
error running geopandas coverd_by doumenttion example
<p>I am running the Geopandas cover_by to check if each geometry of GeoSeries is covered by a single geometry example <a href="https://geopandas.org/en/stable/docs/reference/api/geopandas.GeoSeries.covered_by.html#geopandas.GeoSeries.covered_by" rel="nofollow noreferrer">here</a>. but I got this error :</p> <pre><code...
<p>In case someone faces the same situation, solution is to install <strong><code>pygeos</code></strong>.</p>
python|python-3.x|geopandas|shapely
0
16,740
73,833,141
Pandas create new rows based on column values
<pre><code>df_current = pd.DataFrame({'Date':['2022-09-16', '2022-09-17', '2022-09-18'],'Name': ['Bob Jones', 'Mike Smith', 'Adam Smith'], 'Items Sold':[1, 3, 2], 'Ticket Type':['1 x GA', '2 x VIP, 1 x GA', '1 x GA, 1 x VIP']}) Date Name Items Sold Ticket Type 0 2022-09-16 Bob Jones 1 1 x ...
<pre><code>#create df2, by splitting df['ticket type'] on &quot;,&quot; and then explode to create rows df2=df.assign(tt=df['Ticket Type'].str.split(',')).explode('tt') # split again at 'x' df2[['Items Sold','Ticket Type']]=df2['tt'].str.split('x', expand=True) #drop the temp column df2.drop(columns=&quot;tt&quot;, i...
python|pandas|dataframe
3
16,741
73,636,367
Delete rows from pd.DataFrame based on a defenition given in a second DF
<p>I have two dataframes <code>x</code> and <code>y</code>. DF <code>x</code> contains two grouping variables <code>S</code> and <code>A</code>, and a value variable <code>V</code>. From this DF I want to delete rows for group pairs (S,A) defined in <code>y</code>. DF <code>y</code> contains the variable <code>S</code>...
<pre><code>x ### S A V 0 s1 a 0.490194 1 s1 b 0.875381 2 s1 c 0.384808 3 s1 d 0.063960 4 s1 e 0.003159 5 s2 a 0.188624 6 s2 b 0.400527 7 s2 c 0.137458 8 s2 d 0.162291 9 s2 e 0.337899 10 s3 a 0.101296 11 s3 b 0.464031 12 s3 c 0.407629 13 s3 d 0.222498 14 ...
python|pandas|dataframe
1
16,742
71,258,043
Can I parse a dataframe by row number?
<p>I'm not sure if this is possible but say I have this:</p> <pre><code>In [1]: df = pd.DataFrame(np.random.rand(5,2),index=range(0,10,2),columns=list('AB')) In [2]: df Out[2]: A B 0 1.068932 -0.794307 2 -0.470056 1.192211 4 -0.284561 0.756029 6 1.037563 -0.267820 8 -0.538478 -0.800654 In [5]: ...
<p>Using your answer you could change the iloc to have a : wildcard</p> <pre><code>df2 = df.iloc[1:] </code></pre> <p>This would let you look at everything 2+ in the index</p>
pandas
2
16,743
71,169,230
Lower model evaluation metrics than training metrics for same data used in training
<p>I have trained a LSTM model using some data. When I evaluate the performance of the trained model using the same data as used during training, I get different results. The metrics I am using for evaluation are accuracy, precision, recall, and F1 score. I have used PyTorch.</p> <p>My testing code <code>test_model.py<...
<p>could you share your full source code or you can further check your train, val, and test data while calling <code>def test(encoded_seq, y_label, model_path, model_class, config)</code>fucntion.</p>
python|deep-learning|pytorch|evaluation
0
16,744
52,293,831
Unwrap angle to have continuous phase
<p>Let's say I have an array of phases similar to this:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt phase = np.linspace(0., 100., 1000) % np.pi plt.plot(phase) plt.show() </code></pre> <p>(with many discontinuities like this)</p> <p><img src="https://i.stack.imgur.com/n7s1R.png" width="400"></p...
<p>If you want to keep your original phase with pi-periodicity, you should first double it, unwrap it, then divide it by two:</p> <p><code>plt.plot(np.unwrap(2 * phase) / 2) </code></p>
python|numpy|signal-processing|complex-numbers|phase
13
16,745
52,366,200
adding column based on count and unique count in python
<p>i have a dataframe as shown below. </p> <pre><code>type item new apple new apple new io new io old apple old io old io old se old pj etc el </code></pre> <p>i need to create a new dataframe based on count and unique count </p> <pre><code>type type_count unique_item_count new 4 2 old ...
<p>Use <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 list of tuples - first value specify new column name and second aggregate function, here <a href="http://pandas.pydata.org/pandas-docs...
python|pandas
3
16,746
52,207,633
Convert string (2015-Q1) to date (2015-03-31) in python
<p>I have a pandas dataframe, where one column contains a string for the year and quarter in the following format: <code>2015-Q1</code></p> <p><strong>My Question</strong>: ​How do I convert this into last day of the quarter i.e. <code>2015-03-31</code>.</p>
<p>You can try </p> <pre><code>pd.to_datetime(s).apply(lambda x : pd.Period(x, freq='Q').end_time) Out[252]: 0 2015-03-31 1 2015-03-31 2 2015-03-31 3 2015-03-31 4 2015-03-31 5 2015-03-31 6 2015-03-31 7 2015-03-31 8 2015-03-31 9 2015-03-31 dtype: datetime64[ns] </code></pre>
python|pandas|timestamp
2
16,747
60,468,770
How to downgrade hdf5 installed with tensorflow-gpu
<p>recently i have tried to install tensorflow-gpu following <a href="https://www.youtube.com/watch?v=tPq6NIboLSc" rel="nofollow noreferrer">https://www.youtube.com/watch?v=tPq6NIboLSc</a> this video</p> <p>But when I try to import tensorflow (or keras) my kernal dies giving following error message.</p> <pre><code>C:...
<p>I'm not familiar with C Language as I am using Python. But I resolved this with installing the previous version using Anaconda.</p> <pre><code>conda install -c conda-forge hdf5=1.10.4 </code></pre>
python|tensorflow|anaconda|hdf5
2
16,748
60,589,732
Get cell value and fill rows of new column in python pandas
<p>I have data looking like this:</p> <pre><code>Col1 time: 4 1 2 3 time: 7 4 5 6 time: 11 7 8 ... </code></pre> <p>I want to add a new column an make it to look like this:</p> <pre><code>Col1 Col2 time: 4 4 1 4 2 4 3 4 time: 7 7 4 7 5 7 6 7 time: 11 11 7 ...
<p>My two cents:</p> <pre><code>import pandas as pd import re df = pd.read_csv('dummy_data.csv') print(df) df['Col2'] = '' fill_value = 0 regex_pattern = r'time: (\d+)' for index, row in df.iterrows(): if len(re.findall(regex_pattern, row['Col1'])) == 1: fill_value = int(re.findall(regex_pattern, row['Col...
python|pandas
1
16,749
72,702,165
Translate array into x and y direction - Python
<p>We have the following two-dimensional array with x and y coordinates:</p> <pre><code>x = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]) </code></pre> <p>We flatten it: <code>x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) </code>)</p> <p>and our goal is to apply transla...
<p>Can concatenate two <a href="https://numpy.org/doc/stable/reference/generated/numpy.vstack.html" rel="nofollow noreferrer"><code>vstack</code></a> operations. First, <code>roll</code> in <code>axis=1</code> and then, <code>roll</code> in <code>axis=0</code>.</p> <pre><code>np.vstack([np.roll(np.roll(arr, -i, axis=0)...
python|arrays|numpy
1
16,750
72,632,502
Split 1-column dataframe rows into new colums
<p>I have a dataframe with x rows and would like to split it into x rows into column in a new dataframe.</p> <p>I have found this example (30 rows in the x dataframe), where it works if I split it to something where row x col = 30 (below 10 rows en each columns =&gt; 3 col)</p> <pre><code>k = pd.concat([pd.Series(j, n...
<p>Instead of specifying to number of chunks you can specify the indices where to split:</p> <pre><code>x = pd.DataFrame({'TEST': range(30)}) n = 8 pd.concat([pd.Series(j, name='y' + str(i)) for i,j in enumerate(np.split(x['TEST'].to_numpy(), range(n, len(x['TEST']), n)))], axis=1) </code></pre> <p>Result:</p> <pre><co...
python|pandas|dataframe
0
16,751
59,618,890
Rolling stats pandas with based of fixed period or available data
<p>I would like to take rolling stats over a fixed period say 5 day, eg </p> <pre><code> DATE Price ID AAPL US Equity 2015-01-02 109.33 AAPL US Equity 2015-01-05 106.25 AAPL US Equity 2015-01-06 106.26 AAPL US Equity 2015-01-07 107.75 AAPL US Equity 2015-01-08 111.89 AAPL US E...
<p>IIUC, use <code>min_periods</code> parameter in <code>rolling</code>:</p> <pre><code>df['Average']=df['Price'].rolling(5, min_periods=1).mean() </code></pre> <p>Output:</p> <pre><code>0 109.3300 1 107.7900 2 107.2800 3 107.3975 4 108.2960 5 108.8320 6 109.4320 7 110.2240 8 110.6340 9 ...
python|pandas|rolling-computation
4
16,752
59,662,036
Pandas resample by Date and select 2nd smallest value
<p>I have a data frame that looks similar to</p> <pre><code>2020-01-07 09:00:00,22,228 2020-01-07 10:00:00,22,228 2020-01-07 11:00:00,22,228 2020-01-07 12:00:00,22,228 2020-01-07 13:00:00,22,228 2020-01-07 14:00:00,22,228 2020-01-07 15:00:00,21,228 2020-01-07 16:00:00,22,228 2020-01-08 09:00:00,43,45 2020-01-08 10:00:...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.resample.Resampler.aggregate.html" rel="nofollow noreferrer"><code>Resampler.aggregate</code></a> with custom function for return some value e.g. <code>NaN</code> if not exist second smallest val:</p> <pre><code>def f(x): v= x.ns...
python|pandas|datetime
2
16,753
59,560,097
fastest way to copy values from one cell of a dataframe to another data frame if a third cell matches
<p>I have a master dataframe with anywhere between 750 to 3000 rows of data.</p> <p>I have a daily order dataframe with anywhere from 3000 to 5000 rows of data.</p> <p>If the product code of the daily order dataframe is found in the master dataframe, I get the item cost. Otherwise, it is marked as invalid and deleted...
<p>I dont know if this is the most efficient way of doing it - as someone who started programming with Fortran and then C, I am always for basic datatypes and this solution is not utilising basic datatype. This is definitely a highly Pythonic solution.</p> <pre><code>orderDF=orderDF[orderDF[ParamF].isin(mstrDF[ParamF...
python|pandas
0
16,754
59,703,199
Multiplying matrices across tenor axis with numpy and with GPU
<p>I have a matrix <code>X</code> with shape <code>(F,T,M)</code>. I wish to multiply each <code>(T,M)</code> matrix along the <code>F</code> axis so that the answer will be of shape <code>(M,M,F)</code>. This code does the job for me but this operation repeats many times and it is very slow:</p> <pre><code> for f ...
<p>We can use <code>np.matmul/@ opeartor in Python 3.x</code> after extending dimensions -</p> <pre><code>np.matmul(X.swapaxes(1,2),X).swapaxes(0,2) (X.swapaxes(1,2)@X).swapaxes(0,2) </code></pre> <p>Alternatively, with <code>np.einsum</code> with a direct translation off the shape variables used for the string notat...
performance|numpy|matrix-multiplication
0
16,755
61,848,801
Python - converting a JSON read file into a usable DataFrame
<p>I am new to Python and was trying to use the following code to read in a JSON file and convert it to a dataframe with column headers etc. I just cannot seem to understand what I am doing wrong here as the output is as shown below </p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import matplo...
<p>Use the argument <code>orient="records"</code> see the docs <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_json.html" rel="nofollow noreferrer">here</a></p> <pre><code>df = pd.read_json(other_path, orient="records") </code></pre>
python|json|pandas|dataframe
1
16,756
58,033,135
How to change all columns in csv file to str?
<p>I am working on a script that imports an excel file, iterates through a column called "Title," and returns False if a certain keyword is present in "Title." The script runs, until I get to part where I want to export another csv file that gives me a separate column. My error is as follows: <code>AttributeError: 'int...
<p>Use the following code to import your file:</p> <pre><code>data = pd.read_excel(r'C:/Users/Downloads/61_MONDAY_PROCESS_9.16.19.xlsx', dtype='str')` </code></pre>
python|pandas
2
16,757
57,913,507
Merging dataframes is causing to loose rows
<p>I have a dataframe on which I divide into 3 sub dataframes. Then I am applying aggregate functions. After than, I merge the 3 dataframes.</p> <p>However, when comparing the number of rows prior and post the merge, it shows a significant loss, although I used a command to fill in blanks to preserve the row count. I ...
<p>By looking at the given code and metadata information about the data, <code>groupby</code> would aggregate records with the same id into a single <code>GroupBy</code> object, hence the total number of record counts will decrease if the id's are not unique. The count of <strong>unique</strong> id's should be same as ...
python-3.x|pandas
1
16,758
54,947,988
Putting Data In a DataFrame Gives Different Results in SciKit Learn Algorithm
<p>I just noticed that Sci-Kit Learn's Linear Regression algorithm gives some different results are loaded into a pandas dataframe, as opposed to just using them in their raw state.</p> <p>I don't see why this would be the case.</p> <p>Consider the following Linear Regression Example:</p> <pre><code>from sklearn.dat...
<p>It's because of your transformations:</p> <pre><code>X1 = (X1 - X1.mean()) / X1.std() X2 = (X2 - X2.mean()) / X2.std() </code></pre> <p>Pandas will calculate the mean and std along the columns. To do it for numpy, add the axis argument to <code>mean</code> and <code>std</code>:</p> <pre><code>X2 = (X2 - X2.mean(a...
python|pandas|scikit-learn
2
16,759
54,729,988
pandas: How to compare value of column with next value
<p>I have a dataframe which looks as follows:</p> <pre><code> colA colB 0 A 10 1 B 20 2 C 5 3 D 2 4 F 30 .... </code></pre> <p>I would like to compare column 1 values to detect two successive decrements. That is, I want to report the index values where I have two successive decreme...
<p>Yes you can do this without using loop.</p> <pre><code>df = pd.DataFrame({'colA':['A', 'B', 'C', 'D', 'F'], 'colB':[10, 20, 5, 2, 30]}) &gt;&gt;&gt; df['colC'] = df['colB'].diff(-1) &gt;&gt;&gt; df colA colB colC 0 A 10 -10.0 1 B 20 15.0 2 C 5 3.0 3 D 2 -28.0 4 F 30 NaN </co...
pandas
3
16,760
54,912,497
increment variable for each group
<p>I have the following data:</p> <pre><code>ID Time 1 01-01-01 1 02-01-01 1 02-01-01 2 01-01-01 </code></pre> <p>I would like to start with 0 and increase one by one for each new time by group ID. SO I need to get something like that</p> <pre><code>ID Time Result 1 01-01-01 0 1 ...
<p>You can use <code>groupby</code> with <code>pd.factorize</code>:</p> <pre><code>df['Result'] = df.groupby('ID')['Time'].transform(lambda x: pd.factorize(x)[0]) df </code></pre> <p>Output:</p> <pre><code> ID Time Result 0 1 01-01-01 0 1 1 02-01-01 1 2 1 02-01-01 1 3 2 01-01-01...
python|pandas|dataframe|group-by
4
16,761
54,728,259
numpy list comprehension and +=/-= operator
<p>I was trying to vectorize some list calculation, but find something weird when I attempting to use list as index, especially when I try to write back to the original list, repeated list index seems to be useless:</p> <pre><code>import numpy as np x = np.arange(10) y = np.array([1,2,3,4,5]) z = np.array([1,1,1,1,1]...
<p>There's a buffering issue. <code>ufuncs</code> were given a <code>.at</code> method to resolve this:</p> <pre><code>In [392]: np.add.at(x,z,-1) In [394]: x[y] Out[394]: array([-4, 2, 3, 4, 5]) </code></pre> <p>I think the documentation for <code>ufunc.at</code> explains this well</p> <p><a href="https://docs...
python|numpy|list-comprehension|numpy-ndarray
2
16,762
49,604,146
Appending a Pandas .read_excel dataframe to a new dataframe
<p>I'm trying to read several XLS files into a Panda's dataframe. They appear to read in correctly - but when I trying and display(df), df.info() or df.head() the dataframe is empty.</p> <p>All data is in subfolder named <code>data1</code>. xls sheets are named <code>a.xls</code> and <code>b.xls</code>. </p> <p>The...
<p>You never reassign the variable <code>df</code>, then your dataframe is empty. You should do:</p> <pre><code>df = df.append(data) </code></pre>
python|excel|python-3.x|pandas|dataframe
2
16,763
73,448,266
Row wise frequency of each word in another column
<p>How to calculate: <br></p> <blockquote> <p>frequency of each word, present in another column of same row/index, i.e.</p> </blockquote> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;">case_description_new</th> <th style="text-align: right;">item_new</th> </tr> </the...
<p>Solution with comprehension and <code>str.count</code></p> <pre><code>df['freq'] = [{z: x.count(z) for z in y.split()} for x, y in df.to_numpy()[:, :2]] </code></pre> <hr /> <pre><code> case_description_new item_new freq 0 This row contai...
python-3.x|pandas|eda
1
16,764
67,195,426
Condensing forecast in Pandas using column identifier
<p>I have a Pandas dataframe which contains weekly forecasts for products (product information contained in the first two columns) - see the below example.</p> <pre><code>prod_type prod_version 26-04-2021 03-05-2021 10-05-2021 17-05-2021 24-05-2021 product1 a 0 100 ...
<p>you can use multiple column in <strong>groupby</strong></p> <pre><code>df.groupby(['prod_type','prod_version']).sum() </code></pre>
python|pandas|forecasting
1
16,765
67,405,427
Deep learning with Tensorflow: personalized training loop that learn with one element at a time
<p>I need to use batch with element of different size, so i try to create a personalized training loop, the main idea is to start from the one supplied from keras:</p> <pre><code>for epoch in range(epochs): for step, (x_batch_train, y_batch_train) in enumerate(train_dataset): with tf.GradientTape() as tape:...
<p>grads variable only contains the gradients of variables. to apply them you need to move the optimizer inside the last For loop. but why not writing a normal training loop and then set the batch_size to one?</p> <p>====== Update</p> <p>you can calculate the loss for each sample in the last For loop and then do a redu...
python|tensorflow
0
16,766
67,285,633
Translated TensorFlow Python to C# XOR sample throws exception
<p>I am trying to translate the working python XOR sample to the C# binding using TensorFlow.NET</p> <p>The working Python code, which I tested in VS Code is the following:</p> <pre><code>import numpy as np from keras.models import Sequential from keras.layers.core import Activation, Dense training_data = np.array([[0...
<p><strong>NOTE:</strong> This is only a partial answer, which resolves only the exception. However the C# code in the OP, even corrected based on this partial answer still has some inherent problem: It converges the NN to produce 0, 0, 0, 0 output (instead of the expected XOR rule 0, 1, 1, 0). I am posting this in hop...
python|c#|.net|tensorflow|keras
0
16,767
67,304,944
when i tried running tf_pose im having trouble
<p>im trying to use tf-pose using tensorflow version2.</p> <pre><code>!git clone https://github.com/gsethi2409/tf-pose-estimation.git &gt; /dev/null %cd tf-pose-estimation !pip3 install -r requirements.txt </code></pre> <p>this from where i have cloned. but when i run the below code. it is showing an error.</p> <pre><c...
<p>In tf_pose/estimatory.py under the line that imports tensorflow add the following line</p> <p>tf.compat.v1.disable_eager_execution() <a href="http://%20https://github.com/gsethi2409/tf-pose-estimation/issues/12#issuecomment-842847372" rel="nofollow noreferrer">link</a></p>
tensorflow
2
16,768
60,062,571
Selecting columns by conditions in pandas
<p>This is my dataframe:</p> <p><a href="https://ibb.co/z6RKtYt" rel="nofollow noreferrer">https://ibb.co/z6RKtYt</a></p> <p>I want to pick up the "entire home" in "manhattan" for a price between 150 and 175. How can I select this THREE conditions?</p>
<p>I can't really see the whole variable names in the snapshot, but barring any problems with that this should work:</p> <pre><code>df[(df.neighborhood == 'Manhattan') &amp; (df.room_type == 'Entire home') &amp; (df.price.between(150, 175)] </code></pre>
pandas|csv|dataframe
1
16,769
59,956,418
Python: Modify the json type column in pandas dataframe
<p>I am using python3 and pandas version 0.25. I have a JSON datatype in postgresql table. I am using pandas.io.sql to fetch the data from the table.</p> <pre><code>import pandas.io.sql as psql df = psql.read_sql(sql,con,params=params) </code></pre> <p>So I am getting the dataframe from DB call as above.</p> <p>Whe...
<p>Since each value is a list, we can use <code>.update</code> method of a dictionary to add new value. This might work in your case:</p> <p><strong>Method 1</strong></p> <pre><code>df.loc['col2_data'] = df.apply(lambda row: [x.update({'multiplier':'2'}) for x in row['col2_data']], axis=1) </code></pre> <p><strong>M...
python|python-3.x|pandas
1
16,770
65,061,286
which one is better in installing tensorflow
<p>I followed the instructions on the official website to download the TensorFlow. I chose to create a virtual environment as the instruction shown for macOS. My question is that if I need to activate the virtual environment each time before I use TensorFlow?</p> <p>For example, I want to use tensor flow on Jupiter not...
<p>Well, if you downloaded the packages (like you said TensorFlow and Seaborn) in the <strong>base Conda environment</strong> which is the default environment that anaconda provides on installation, then to use what it has, you need to run whatever program/IDE like Jupyter lab from it. So you would open Anaconda Prompt...
tensorflow|installation
1
16,771
65,119,711
Can't pass an Input layer into tf.keras.Model()
<pre><code>from tensorflow.keras.layers import Input input_tensor = Input(shape = (10,)) tf.keras.Model(inputs = input_tensor) </code></pre> <pre><code> TypeError: ('Keyword argument not understood:', 'Inputs') </code></pre> <p>I am using tensorflow 2.0.0 from anaconda's package. This error occurs when assign value...
<p>Primarily, you have an extra bracket.<br /> Regarding the problem, <code>tf.keras</code> only allows <em><strong>both</strong></em> inputs and outputs for instantiating a model.</p> <p>So, if you'd (and I really don't know why) want to create a model with only this tensor, then you should do</p> <pre><code>tf.keras....
keras|tensorflow2.0|keras-layer
2
16,772
65,440,443
RuntimeError: Given groups=1, weight of size [32, 3, 3, 3], expected input[4, 32, 6, 7] to have 3 channels, but got 32 channels instead
<p>I am trying to implement such CNN.</p> <p><a href="https://i.stack.imgur.com/XHB8r.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XHB8r.png" alt="enter image description here" /></a></p> <p>This is my implementation:</p> <pre><code>class Net(BaseFeaturesExtractor): def __init__(self, observat...
<p><code>in_channels</code> of a <code>conv</code> layer should be equal to <code>out_channels</code> of the previous layer. In your case, <code>in_channels</code> of the 2nd and 3rd <code>conv</code> layers don't have the correct values. They should be like below,</p> <pre><code> self.cnn = nn.Sequential( n...
pytorch|conv-neural-network
2
16,773
65,139,027
What is the efficient way to perform row wise match in pandas?
<p>Assume 2 data frames (df_a and df_b). I want to traverse row-wise and check for an exact match in the value column. If a match is found, I want the index of the matched row to be added in df_a.</p> <p>df_a</p> <pre><code>| Index | Name | Value | |-------|------|-------| | 1 | Bon | 124 | | 2 | Bon | 412 ...
<p>Use if need match <code>Name</code> and <code>Value</code> columns use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>DataFrame.merge</code></a> with left join and convert index to column <code>Index_in_df_b</code>:</p> <pre><code>df2 =...
python|python-3.x|pandas|performance
2
16,774
49,863,192
Pandas changing data types of multiple columns
<p>I'm trying to convert all the values in certain columns into floating point dollar amounts, in the pre-existing columns they have a dollar sign before them, however, they are strings which contain the dollar amount as a whole number. All cells in these columns have values that are not (NaN).</p> <p>I'm importing th...
<p>This should work to deal with most cases. Remove the dollar sign with replace and then <code>pandas.to_numeric()</code> will convert it to a float. Anything that isn't a number is coerced to <code>np.NaN</code>, giving you a column with <code>dtype: float64</code></p> <pre><code>import pandas as pd import numpy as ...
python|pandas|dataframe
0
16,775
49,834,916
How to concatenate list of results from pandas.read_html
<p>I am able to print/get to <strong>CSV</strong> dataframe from one URL using the code down below </p> <pre><code>import bs4 as bs import pandas as pd dfs = pd.read_html('http://www.url1.com',header=0) for df in dfs: print(df.head()) df.to_csv('File.csv') </code></pre> <p>I would like is to concatenate multip...
<p>You can use <code>pandas.concat</code> to concatenate dataframes:</p> <pre><code>import pandas as pd urls = ['http://www.url1.com', 'http://www.url2.com', 'http://www.url3.com'] df = pd.concat([pd.concat(pd.read_html(url, header=0), axis=0) for url in urls], axis=0) df.to_csv('file.csv') </code><...
python|pandas|dataframe
2
16,776
63,917,982
How to up sample dates in python
<p>I would like to up-sampling the dates with a mean between the previous and the next one of the same ID. I cannot apply the rolling to a datetime type. Also the interpolation doesn't work as I am expecting, in fact it duplicates the previous date and I cannot do the mean. So I used a for cycle to do this, but it stop...
<p>The key to solving the problem is to take the average in the rolling function, which is a requirement, and make it a separate data frame. Add a cumulative count in ID units to the original and new data frame, respectively. Combine them vertically and order them by ID and Flg.</p> <pre><code>df['flg'] = df.groupby('I...
python|pandas
0
16,777
63,971,055
How to convert a column of dictionaries to separate columns in pandas?
<p>Given the following dictionary created from <code>df['statistics'].head().to_dict()</code></p> <pre><code>{0: {'executions': {'total': '1', 'passed': '1', 'failed': '0', 'skipped': '0'}, 'defects': {'product_bug': {'total': 0, 'PB001': 0}, 'automation_bug': {'AB001': 0, 'total': 0}, 'system_issue': ...
<ul> <li><code>.apply(pd.Series)</code> is slow, don't use it. <ul> <li>See timing in <a href="https://stackoverflow.com/questions/63311361">Splitting dictionary/list inside a Pandas Column into Separate Columns</a></li> </ul> </li> <li>Create a DataFrame with a <code>'statistics'</code> column from the <code>dict</cod...
python|pandas|dictionary|json-normalize
1
16,778
63,314,307
How to reverse onehot-encoding?
<p>I have some labels which look somehow like this: <code>'ABC1234'</code>. I onehot-encoded them using this code:</p> <pre><code>from numpy import argmax # define input string def my_onehot_encoded(label): # define universe of possible input values characters = '0123456789ABCDEFGHIJKLMNPQRSTUVWXYZ' # defi...
<p>Use the <code>characters</code> and iterate through it to get the values of indexes of predicted output as:</p> <pre><code>characters = '0123456789ABCDEFGHIJKLMNPQRSTUVWXYZ' output = [[ 10, 11, 12, 1, 2, 3, 4]] res = [] for i in output: res_str = '' for j in i: res_str = res_str + str(characters[j]) ...
python|numpy|label|one-hot-encoding
1
16,779
67,676,618
Create new column in Pandas with value that corresponds to a unique pair of records
<p>I have a dataframe that includes two columns of integers. I'm trying to identify the unique pairs of records by creating a new column that is an unique identifier for that record pair. Below is an example of my data.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column 1</th> <th>Colum...
<p>Here's one way:</p> <pre><code>df['Column 3'] = (df.groupby(['Column 1', 'Column 2']).cumcount() == 0).cumsum() </code></pre> <p>Output:</p> <pre><code> Column 1 Column 2 Column 3 0 1 2 1 1 1 2 1 2 1 3 2 3 1 4 3 </cod...
python|pandas
1
16,780
61,273,445
Tensorflow MapDataset iterator fails
<p>I am trying to implement the method suggested by the tensorflow documentation over here (<a href="https://www.tensorflow.org/tutorials/load_data/images" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/load_data/images</a>) to load images from local directory as a tensorflow dataset. Especially I am in...
<p>The error occurs because <code>get_label</code> performs an out-of-bounds list access</p> <pre><code>def get_label(file_path): # convert the path to a list of path components parts = tf.strings.split(file_path) # The second to last is the class-directory return parts[-2] == CLASS_NAMES </code></pre...
python|tensorflow|tensorflow-datasets
-1
16,781
61,392,979
Error in storing downloaded images into a variable
<p>I would like to store all the images I downloaded on my computer to the variable called X_data.</p> <pre><code>import glob import cv2 import numpy as np X_data = [] for img in glob.glob ("C:\\Users\\User\*.png"): image = cv2.imread(img) X_data+=[image] print('X_data shape:', np.array(X_data).shape) Out...
<p>Your files will take only one image file. You have to run it in a loop to take all the images. </p> <pre><code>import glob import cv2 import numpy as np X_data = [] for img in glob.glob ("your path\*.png"): image = cv2.imread(img) X_data.append(image) print('X_data shape:', np.array(X_data).shape) </code><...
python|python-3.x|pandas|dataframe|global-variables
0
16,782
61,312,391
Python3: Interpolation for certain points (not grid)
<p>I have a text file (data.txt) with this format(x y z):</p> <p>Example:</p> <pre><code>1.1 0.0 12 1.2 2.2 15 1.3 5.5 30 2.6 1.0 20 2.1 4.8 31 3.9 0.5 12 ... </code></pre> <p>I get this data with the following code:</p> <pre><code>x,y,z = np.genfromtxt(r'data.txt', unpack=True) </code></pre> <p>I want to do an in...
<p>The solution is quite simple:</p> <pre><code> n1=interpolate.griddata(intial_points, z, (positions_path[:,0], positions_path[:,0] ), method='linear') </code></pre> <p>It returns an array with the "z" values of the points in points.txt. No need for a grid. Thanks!</p>
python|python-3.x|numpy|linear-interpolation
0
16,783
61,310,331
Performing inference with a BERT (TF 1.x) saved model
<p>I'm stuck on <em>one line of code</em> and have been stalled on a project all weekend as a result.</p> <p>I am working on a project that uses BERT for sentence classification. I have successfully trained the model, and I can test the results using the example code from run_classifier.py.</p> <p>I can export the mo...
<p>Thank you for this post. Your <code>serving_input_fn</code> was the piece I was missing! Your <code>predict</code> function needs to be changed to feed the features dict directly, rather than use the predict_input_fn:</p> <pre><code>def predict(sentences): labels = [0, 1] input_examples = [ run_clas...
tensorflow|tensorflow-serving|tensorflow-estimator
1
16,784
68,686,563
Read with pd.read_sqlite a sqlite file in a remote server
<p>Is it possible to read a sqlite3 database that is located in a remote server through ssh in python? Up to now, I have to copy the file from the server to my local computer and then open it, which is not very efficient... I am looking for something like this:</p> <pre><code>query = 'SELECT * FROM table' with sqlite3....
<p>I just modified the code from @dan-web (sorry, I don't know how to referr to him) a little bit and now it is working:</p> <pre><code>ssh = SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=hostname, username=username) stdin, stdout, stderr = ssh.ex...
python|pandas|sqlite|ssh
1
16,785
52,973,989
Using different optimizers to train the same layer in tensorflow
<p>I have a model which consists of convolutional layers followed by fully connected layers. I trained this model on the fer dataset. This is considered a classification problem where the number of output is equal to 8. </p> <p>After training this model, I kept the fully connected layer, and replaced only the last lay...
<p>This is probably caused by both optimizers using the (same) default name <code>'Adam'</code>. To avoid this clash, you can give the second optimizer a different name, e.g.</p> <pre><code>opt_finetune = tf.train.AdamOptimizer(name='Adam_finetune') </code></pre> <p>This should make <code>opt_finetune</code> create i...
tensorflow|optimization
3
16,786
52,955,529
how I can dynamically create an list in Tensorflow
<p>how I can dynamically create a loss list from a list of tasks (self.prediction) without having to create the variables:</p> <p><strong>Current:</strong></p> <pre><code>loss0 = tf.losses.softmax_cross_entropy( logits = self.prediction[0], onehot_labels = self.Y[0] ) # task 0 loss1 = tf.losses.softmax_cross_entropy(...
<p>If I understand what you mean, you're asking for</p> <pre><code>def calculate_loss(prediction, label, idx): return tf.losses.softmax_cross_entropy(logits = prediction[idx], onehot_labels = label[idx]) losses = [] for i in range(3): losses.append(calculate_loss(se...
python|tensorflow
0
16,787
53,048,673
Tensorflow Import Error on Amazon EC2 Instance
<p>I am trying to run a convolutional neural network in my p3.16xlarge Amazon EC2 instance. I installed tensorflow and all the other requisite libraries for my program using pip install, however, when I run this program, I receive the error message: </p> <p>"ImportError: libcublas.so.9.0: cannot open shared object fil...
<p>a lot of customers find that the Deep Learning AMI is the simplest way to run their workloads on EC2. It comes pre-installed with all the popular libraries.</p> <p><a href="https://aws.amazon.com/machine-learning/amis/" rel="nofollow noreferrer">https://aws.amazon.com/machine-learning/amis/</a></p> <p>Alternativel...
python|amazon-web-services|tensorflow|amazon-ec2
0
16,788
65,802,236
Python: Creating new column names in a for loop
<p>I am trying to make custom column header names for the dataframe using a for loop. Currently I am using two for loops to iterate through a dataframe, but don't know how to put new column headers in without hardcoding them. I have</p> <pre><code>df = pandas.DataFrame({ 'A':[5,3,6,9,2,4], 'B':[4,5,4,5,5,4], ...
<pre><code>from itertools import combinations for x,y in combinations(df.columns,2): df['Long '+x+' Short '+y]=df[x]*df[y] </code></pre>
python|pandas|loops|for-loop
2
16,789
65,600,964
How to split time data in Python?
<p>I have a dataframe like below:</p> <pre><code>d={ 'Date' :['2016-10-30','2016-10-30','2016-11-01','2016-10-30'], 'Time':['09:58:11', '10:05:34', '10:07:57', '11:15:32'], 'Transaction':[2,3,1,1] } df=pd.DataFrame(d, columns=['Date','Time','Transaction']) </code></pre> <p><a href="https://i.stack.imgur.co...
<p>Using <code>pd.cut</code> with <code>pd.Timedelta</code>:</p> <pre><code>u = df.assign(Time=pd.to_timedelta(df['Time'])) bins = [6,11,17,20] labels = ['Morning','Afternoon','Evening'] u = u.assign(Time_Group=pd.cut(u['Time'],[pd.Timedelta(hours=i) for i in bins], labels=labels)) </code...
python|pandas|numpy
4
16,790
65,863,927
How to remove duplicates based on partial match
<p>I don't even know how to approach it as it feels too complex for my level.</p> <p>Imagine courier tracking numbers and I am receiving some duplicated updates from upstream system in following format:</p> <p><img src="https://i.stack.imgur.com/Z4Wwe.jpg" alt="image" /></p> <p>see attached image or a small piece of co...
<p>Edit: New solution:</p> <pre><code># extract duplicates duplicates = df['Tracking ID'].str.extract('(.+)-S2').dropna() # remove older entry if necessary df = df[~df['Tracking ID'].isin(duplicates[0].unique())] </code></pre> <p><br><br></p> <p>If the 1234-S2 entry is always lower in the DataFrame than the 1234 entr...
python|pandas|dataframe|duplicates
0
16,791
63,486,872
Changing values (with apply) in one column of pandas dataframe depending on particular values in other column in this dataframe with mask
<p>I have a dataframe:</p> <pre><code>df = pd.DataFrame({'col1': [69, 77, 88], 'col2': ['barf;', 'barf;', 'barfoo']}) print(df, '\n') col1 col2 0 69 barf; 1 77 barf; 2 88 barfoo </code></pre> <p>Also i have selection function:</p> <pre><code>def selection_func(string): ''' ...
<p>Found a solution while was writing the question:</p> <pre><code>df.loc[condition, 'col2'] = df.loc[condition, 'col2'].apply(func) print(df, '\n') col1 col2 0 69 a 1 77 barf; 2 88 barfoo </code></pre>
python|pandas|dataframe|pandas-apply
2
16,792
63,552,834
Adding a new column based on other columns and rows
<p>I have a large dataframe. Let me write a sample dataframe for let you understand my question.</p> <pre><code>A B C car red 15 car blue 20 car grey 14 bike red 6 bike blue 8 phone red 9 phone blue 11 phone grey 10 </code></pre> <p>Let's say column C show the price. I ...
<p>Check <code>transform</code> with <code>mean</code>, then do <code>np.where</code></p> <pre><code>s = df.groupby('A').C.transform('mean') df['D'] = np.where(df.C&gt;s, 'expensive', 'cheap') df Out[158]: A B C D 0 car red 15 cheap 1 car blue 20 expensive 2 car grey 14 ...
python|pandas|numpy|dataframe|keyerror
1
16,793
63,644,278
Mapping pandas DataFrame values in a JSON file
<p>I want to take <code>df</code> below and map its columns <code>fruit</code> and <code>dessert</code> into a JSON file.</p> <pre><code>#df fruit dessert ------------------- apple sauce blueberry muffin cherry pie import json df = df.to_json() #desired output {&quot;apple&quot;: &quot;sauce&quot;,...
<p>Create dictionary by <code>zip</code> and <code>dict</code> and then convert to <code>json</code>:</p> <pre><code>import json j = json.dumps(dict(zip(df['fruit'], df['dessert']))) print (j) {&quot;apple&quot;: &quot;sauce&quot;, &quot;blueberry&quot;: &quot;muffin&quot;, &quot;cherry&quot;: &quot;pie&quot;} </code>...
python|json|pandas|mapping
3
16,794
63,644,124
Number of nodes in output later greater than number of classes in a neural network
<p>While training a neural network, on the fashion mnist dataset, I decided to have a greater number of nodes in my output layer than the number of classes in the dataset. <br>The dataset has 10 classes, while I trained my network to have 15 nodes in the output layer. I also used a softmax. <br> Now surprisingly, this ...
<p>The only reason you are able to use such a configuration is because you have specified your loss function as sparse_categorical_crossentropy.</p> <p>let's understand the effects of greater output nodes in forward propagation.<br /> Consider a neural network with 2 layers.<br /> 1st layer - 6 neurons (Hidden layer)<b...
tensorflow|neural-network|classification
3
16,795
53,530,547
How do I change multiple pandas Dataframes at once using for loop
<p>I have two DataFrames that are nearly identical in structure, and I want to perform data transformation/cleaning on them simultaneously. To do this, I created a list that contains both of these DFs and loop through the list.</p> <p>ex:</p> <pre><code>train = pd.read_csv('train.csv') test = pd.read_csv('test.csv') ...
<p>You are creating a new dataset variable at each loop, and the operation is performed on those. So you are indeed, as you say, creating copies of train and test. What you want is to <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow noreferrer"><code>drop</code><...
python|pandas|dataframe|for-loop
0
16,796
71,917,313
I have indices in one tensor and values in another. How do I create a new tensor with this?
<p>Say my indices are:</p> <pre><code>indices = [6, 9, 2], [2, 2, 7], [0, 8, 4] </code></pre> <p>and my values are:</p> <pre><code>values = [0.35764236, 0.47342054, 0.61403205, 0.01948093, 0.21791322, 0.53855718, 0.93596267, 0.3948243 , 0.22061542, 0.09633507] </code></pre> <p>Then in numpy I...
<p>There are simple ways.</p> <pre><code>indices = [[6, 9, 2], [2, 2, 7], [0, 8, 4]] values = [0.35764236, 0.47342054, 0.61403205, 0.01948093, 0.21791322, 0.53855718, 0.93596267, 0.3948243 , 0.22061542, 0.09633507] print(tf.gather(values,indices)) </code></pre> <p>Output :</p> <pre><code>tf...
python|tensorflow
0
16,797
71,885,790
ASC files not preserving empty columns when added to df Python
<p>I have a load of ASC files to extract data from. The issue I am having is that some of the columns have empty rows where there is no data, when I load these files into a df - it populates the first columns with all the data and just adds nans to the end... like this:</p> <p>a| b| c</p> <p>1 | 2 | nan</p> <p>when I w...
<p>Your data looks well behaved, you could try to make use of the Pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_fwf.html" rel="nofollow noreferrer"><code>fwf</code></a> to read the files with fixed-width formatted lines. If the inference from the <code>fwf</code> is not good enough for you, y...
python|pandas|dataframe|ascii
0
16,798
71,990,491
How to get python packages installed for 32 bit before but works on 64bit as well in Visual Code? E.g. Pytorch
<p>I use (1) Windows 11,</p> <p>(2) Python 3.7.8 for 64bit ; Python 3.8.3 for 32bit <a href="https://i.stack.imgur.com/ZHsVE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZHsVE.png" alt="enter image description here" /></a></p> <p>(3) Visual Studio Code.</p> <p>I noticed that all my python packages...
<p>You have selected <code>Python3.7.8(64)</code> in the jupyter notebook, while you have installed the python modules in the <code>Python3.8.3(32)</code> environment. So it will prompt <code>No module named 'pandas'</code>.</p> <p>And looks like torch has no 32bit version, if you want to use it, you need to select <co...
python|visual-studio-code|pytorch
1
16,799
56,615,339
I'm trying creating a pandas dataframe column based on a given condition(multiple condition)
<p>I used two different codes to solve this: 1. I used if conditions inside the dataframe. 2. I tried to use the functions.</p> <p>I'm getting the <code>syntaxerror: invalid syntax</code>. </p> <p>I'm still a beginner using Pyton.</p> <p>1st Method:</p> <pre><code>&lt;df['hours_week'] = ['less_than_40' if x &lt; 40...
<p>You can also use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.searchsorted.html" rel="nofollow noreferrer">searchsorted</a>:</p> <pre><code>bins = pd.Series([40, 45, 60, 80]) labels = ['less_than_40', 'between_40_and_45', 'between_45_and_60', 'between_60_and_80', 'mo...
python|pandas
0