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
1,500
72,167,624
TF Agent taking the same action for all test states after training in Reinforcement Learning
<p>I am trying to create a Custom PyEnvironment for making an agent learn the optimum hour to send the notification to the users, based on the rewards received by clicking on the notifications sent in previous 7 days.</p> <p>After the training is complete, the agent is only taking the action as the same hour even if di...
<p>I think that 1000 training steps could be on of the reason the agent is stuck with picking one action. RL agents need hundreds of thousands of iterations, and this could be even higher depending on the task and some neural networks hyperparameters, like the learning rate.</p> <p>I suggest you to increase the <code>n...
tensorflow2.0|reinforcement-learning|dqn|tf-agent
0
1,501
50,518,569
How to backprop through a model that predicts the weights for another in Tensorflow
<p>I am currently trying to train a model (hypernetwork) that can predict the weights for another model (main network) such that the main network's cross-entropy loss decreases. However when I use tf.assign to assign the new weights to the network it does not allow backpropagation into the hypernetwork thus rendering t...
<p>In this case your weights aren't variables, they are computed tensors based on the hypernetwork. All you really have is one network during training. If I understand you correctly you are then proposing to discard the hypernetwork and be able to use just the main network to perform predictions.</p> <p>If this is the...
tensorflow|machine-learning|backpropagation|tensorflow-gradient
0
1,502
45,563,438
hybrid of max pooling and average pooling
<p>While tweaking a deep convolutional net using Keras (with the TensorFlow backend) I would like to try out a hybrid between <code>MaxPooling2D</code> and <code>AveragePooling2D</code>, because both strategies seem to improve two different aspects regarding my objective.</p> <p>I'm thinking about something like this:...
<p>I now use a different solution for combining both pooling variations.</p> <ul> <li>give the tensor to both pooling functions</li> <li>concatenate the results</li> <li>use a small conv layer to learn how to combine</li> </ul> <p>This approach, of course, has a higher computational cost but is also more flexible. Th...
tensorflow|keras|deep-learning|max-pooling|spatial-pooling
5
1,503
45,291,810
Finding a key value pair in a dictionary that contains a specific value in python
<p>In python 3 and python 2, is there a way to get the key value pair in a dictionary that contains a specific value? E.g. here is the dictionary:</p> <pre><code>dict_a = {'key_1': [23, 'ab', 'cd'], 'key_2': [12, 'aa', 'hg']} </code></pre> <p>How do I get the key value pair where 'cd' is present in the value? I tried...
<p>You can use a simple dictionary comprehension to check if <code>cd</code> is in the value of each key, value pair:</p> <pre><code>&gt;&gt;&gt; dict_a = {'key_1': [23, 'ab', 'cd'], 'key_2': [12, 'aa', 'hg']} &gt;&gt;&gt; {k: v for k, v in dict_a.items() if 'cd' in v} {'key_1': [23, 'ab', 'cd']} </code></pre> <p>Thi...
python|pandas|dictionary
1
1,504
45,409,148
Python: Looping through Pandas DataFrame to match string in a list
<p>My question is regarding a Pandas DataFrame and a list of e-mail addresses. The simplified dataframe (called 'df') looks like this:</p> <pre><code> Name Address Email 0 Bush Apple Street 1 Volt Orange Street 2 Smith Kiwi Street </code></pre> <p>The simplified list of e-mail addresses looks ...
<p>Generally you should consider using <code>iterrows</code> as last resort only.</p> <p>Consider this:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Name': ['Smith', 'Volt', 'Bush']}) list_of_emails = ['johnsmith@gmail.com', 'judyvolt@hotmail.com', 'bush@yahoo.com'] def foo(name): for email in list_o...
python|python-3.x|pandas
4
1,505
62,530,749
type dependence of 'backward ' in pytorch
<pre class="lang-py prettyprint-override"><code>x = torch.ones(1, requires_grad=True) print(x) y = x + 2. print(y) y.backward() print(x.grad) </code></pre> <p>--&gt;result&gt;&gt;&gt;&gt;&gt;</p> <pre class="lang-py prettyprint-override"><code>tensor([1.], requires_grad=True) tensor([3.], grad_fn=&lt;AddBackward0&gt;) ...
<p>You are looking at the wrong tensor ;)</p> <p>By calling <code>x = x.double()</code> you create a new tensor, so when you call <code>x.grad</code> later on, you call it on the <code>double()</code> version of <code>x</code>, which isn't your original <code>x</code> anymore.</p>
pytorch
0
1,506
62,856,279
How to add values/ labels over each marker in lineplot in Python Seaborn?
<p>I have a dataframe consists of the range of time, stock and the counts of text as the columns . The dataframe looks like this</p> <pre><code> Time Stock Text 0 00:00 - 01:00 BBNI 371 1 00:00 - 01:00 BBRI 675 2 00:00 - 01:00 BBTN 136 3 00:00 - 01:00 BMRI 860 4 01:00 - 02:00 BBNI ...
<p>Loop through the number of data with <code>ax.text</code>. I'm creating this only with the data presented to me, so I'm omitting some of your processing.</p> <pre><code>import pandas as pd import numpy as np import io data = ''' Time Stock Text 0 &quot;00:00 - 01:00&quot; BBNI 371 1 &quot;00:00 - 01:00&quot; BBR...
python|pandas|matplotlib|seaborn|line-plot
2
1,507
54,553,032
Incomplete shape error when try to export inference in tensor flow object detection api
<p>I trained custom object detector with loss 2.x , when i try to export it i am getting the following error</p> <p>I came across this : <a href="https://stackoverflow.com/questions/52002256/parsing-inputs-incomplete-shape-error-while-exporting-the-inference-graph-i">&#39;Parsing Inputs... Incomplete shape&#39; error ...
<p>This happens since you didn't state what is the input resolution with the argument <code>input_shape</code>. It simply means that it cannot compute how many flops an operation will take, since it doesn't know what the input resolution will be. You can still use the exported graph for inference without problem.</p>
python-3.x|tensorflow|object-detection|object-detection-api
1
1,508
54,426,748
Pandas multi index to datetime
<p>How do I convert the following multiindex to datetime object and set that as the new index?</p> <pre><code>df_gauge_mean.index Out[376]: MultiIndex(levels=[[2018, 2019], [1, 12], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]], labels=...
<p>Since you did not post your multiple index , first we need convert it </p> <pre><code>s="MultiIndex(levels=[[2018, 2019], [1, 12], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]],labels=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
python|pandas|multi-index
4
1,509
73,839,762
Error when using `numpy.random.normal()` with Numba
<p>I'm exploring a bit Numba to optimize some signal processing codes. According to Numba's documentation, the function from the <code>numpy.random</code> package is well supported by the just-in-time compiler. However, when I run</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from numba import ...
<p>if you check the <a href="https://numba.pydata.org/numba-doc/dev/reference/numpysupported.html#distributions" rel="nofollow noreferrer">current state of documentation</a>, the size argument is not supported yet.</p> <p>since numba compiles this to machine code, this is equivalent in terms of speed.</p> <pre class="l...
python|numpy|numba
1
1,510
73,756,529
How do I find the value of a row of a column with the value of a variable?
<p>doing it this way and printing the value of &quot;row_x&quot; prints the value of row 1 of a csv file</p> <pre><code>fila = 1 vueltas = 0 fila_x = ejes_df.loc[ejes_df['Variable'].isin([1])] </code></pre> <p>but when I want to indicate the value of the row through the value of a variable &quot;row = 1&quot; it does ...
<p>ok I found the error, I think it was because when changing the value of the row I was only running that line of code, instead of running the line of code where the variable &quot;row&quot; was given the value of 1, that is why the function did not find that value ‍♀️</p>
python|pandas|csv
0
1,511
73,810,774
Pandas: filtering rows based on condition
<p>Existing Dataframe :</p> <pre><code>Id Date Status A 26-01-2022 begin A 26-01-2022 failed A 27-01-2022 begin A 27-01-2022 in-process A 27-01-2022 success B 01-02-2022 in-process B 01-02-2022 ...
<p>Use <code>transform('last')</code>:</p> <pre><code>df[df.groupby(['Id', 'Date']).Status.transform('last') == 'success'] </code></pre>
python|pandas|dataframe
1
1,512
73,807,871
How update column value in dataframe if there are values in another column and keep original value when exist NAN
<p>I have a dataframe like this:</p> <pre><code>Id date sales sales_new 291 2022-03-01 10 15 292 2022-04-01 12 16 293 2022-05-01 9 0 294 2022-06-01 13 20 295 2022-07-01 10 nan 296 2022-08-01 12 nan </code></pre> <p>I would like rep...
<p>You can use <code>update</code> to do that:</p> <pre><code>df['sales'].update(df['sales_new']) df.drop(columns='sales_new') </code></pre> <p><strong>Result</strong></p> <pre><code> Id date sales 0 291 2022-03-01 15 1 292 2022-04-01 16 2 293 2022-05-01 0 3 294 2022-06-01 20 4 295 ...
python|pandas|dataframe
1
1,513
71,310,298
getting vertices and face as numpy array from a stl file using trimesh
<p>I have an STL file, I now need to read the vertices and face value of that STL file using trimesh.</p> <pre><code> myobj = trimesh.load_mesh(&quot;file.stl&quot;, enable_post_processing=True, solid=True) myobj.faces #gives me ndarray of faces </code></pre> <p>how to read vertices from myobj ?</p>
<pre><code>myobj.vertices </code></pre> <p><a href="https://trimsh.org/trimesh.base.html?#trimesh.base.Trimesh.vertices" rel="nofollow noreferrer">Here's the document</a></p>
python|trimesh|numpy-stl
0
1,514
52,242,527
Tensorflow Eager Execution on Colab
<p>I'm trying to enable eager execution with Tensorflow on a Colab notebook but I get an error message:</p> <pre><code>import tensorflow as tf import tensorflow.contrib.eager as tfe tf.enable_eager_execution() </code></pre> <blockquote> <p><em>ValueError: tf.enable_eager_execution must be called at program startup...
<p>This was a bug on our side, fix is now live, and the original code snippet should be working again. See <a href="https://github.com/googlecolab/colabtools/issues/262" rel="noreferrer">Tensorflow eager mode dose not work when GPU is enabled in google colab · Issue #262 · googlecolab/colabtools</a>.</p> <p>(NB: I'm o...
python|tensorflow|google-colaboratory|eager
7
1,515
60,614,574
TensorFlow sees a black screen as an object for 99%
<p>I have the problem that TensorFlow detects a black screen as an object? I have trained it so it only can see two classes, but I want to see N/A label if its neither the classes.</p> <p><a href="https://i.stack.imgur.com/Bg9om.png" rel="nofollow noreferrer">Result</a></p> <p>Hope you guys have any idea how to fix t...
<p>I don't know what code you're using, but I assume your classes are truth or lying from faces. Two suggestions:</p> <ul> <li><p>It may be that you have divided your image data by 255 twice at some point. </p></li> <li><p>Make sure you include a third class which is "not a face". I assume you're passing your convolut...
tensorflow|artificial-intelligence
0
1,516
60,653,617
No module named 'uff'
<p><strong>Goal :</strong> To convert tensorflow .pb model to tensorrt </p> <p><strong>System specs :</strong> Ubundu 18.04 Cuda 10.0 TensorRT 5.1</p> <p>Even Installed <code>sudo apt-get install uff-converter-tf</code></p> <p>Error obtained when trying to import <code>uff</code> in Python:</p> <blockquote> <p>...
<p>Installing <code>uff-converter-tf</code> is not enough, you will need to install Python UFF wheel to be able to use it. <a href="https://docs.nvidia.com/deeplearning/sdk/tensorrt-install-guide/index.html" rel="noreferrer">Here</a> you will find complete installation guide.</p> <p>If using Python 2.7:</p> <pre><cod...
python|tensorflow|tensorrt|uff
5
1,517
72,763,382
How to find most similar string values in a dataframe?
<p>I am finding the similarity between the sentence using embedding sentence and looping through all the document's embedded sentences to find the right match relative to the search string. I also want to display the document name in the output along with the similarity match result but am not sure how I can extract th...
<p>Here is an example of how you can do it using Python standard library <a href="https://docs.python.org/3/library/difflib.html" rel="nofollow noreferrer">difflib</a> module, which provides helpers for computing deltas.</p> <p>Given the following toy dataframe and search sentence:</p> <pre class="lang-py prettyprint-o...
pandas|search|nlp
0
1,518
72,721,266
AnnData: Adding unaligned observations annotations
<p>I have an AnnData (<code>adata</code>) and a pandas Dataframe (<code>df</code>). I would like left-join <code>adata.obs</code> and <code>df</code> on their index. How do I go about doing this? I tried using <code>pd.merge</code> and <code>adata.obs.join(df)</code> with no success. Both result in all the columns cont...
<p>You are on the right track with merge - the following works as expected:</p> <pre class="lang-py prettyprint-override"><code>adata.obs = adata.obs.merge(how='left',right=df, left_index=True, right_index=True) </code></pre> <p>Note: Mismatch of dtypes (e.g. <code>str</code> in <code>adata.obs.index</code> and <code>i...
python|pandas
0
1,519
72,721,237
EarlyStopping using epoch level metrics in Pytorch Lightning
<p>I have written a classifier in pytorch lightning, and I'd like to plot training/validation loss and accuracy against the epoch number, rather than the step number, which seems to be the default behaviour. I can do this using the following code (using tensorboard as the logger:</p> <pre><code>def validation_epoch_end...
<p>If you want to log several values you should use <code>log_dict</code> instead of <code>log</code>. Like this:</p> <pre class="lang-py prettyprint-override"><code>metrics = { 'val_loss': loss, 'val_accuracy': acc } self.log_dict(metrics, on_step=False, on_epoch=True) </code></pre>
tensorboard|pytorch-lightning
0
1,520
59,724,691
Finding the longest sequence of dates in a dataframe
<p>I'd like to know how to find the longest unbroken sequence of dates (formatted as <code>2016-11-27</code>) in a <code>publish_date</code> column (dates are not the index, though I suppose they could be).</p> <p>There are a number of stack overflow questions which are similar, but AFAICT all proposed answers return ...
<p>Here is an example of how you can do this:</p> <pre><code>import pandas as pd import datetime # initialize data data = {'a': [1,2,3,4,5,6,7], 'date': ['2017-01-01', '2017-01-03', '2017-01-05', '2017-01-06', '2017-01-07', '2017-01-09', '2017-01-31']} df = pd.DataFrame(data) df['date'] = pd.to_datetime(df['d...
pandas|dataframe
3
1,521
59,640,574
how to vectorize the scatter-matmul operation
<p>I have many matrices <code>w1</code>, <code>w2</code>, <code>w3...wn</code> with shapes (<code>k*n1</code>, <code>k*n2</code>, <code>k*n3...k*nn</code>) and <code>x1</code>, <code>x2</code>, <code>x3...xn</code> with shapes (<code>n1*m</code>, <code>n2*m</code>, <code>n3*m...nn*m</code>).<br> I want to get <code>w1@...
<p>You can vectorize your operation by creating a large block-diagonal matrix <code>W</code> of shape <code>n*k</code>x<code>(n1+..+nn)</code> where the <code>w_i</code> matrices are the blocks on the diagonal. Then you can vertically stack all <code>x</code> matrices into an <code>X</code> matrix of shape <code>(n1+.....
python|tensorflow|deep-learning|pytorch|vectorization
2
1,522
57,935,290
Selecting rows in a DataFrame based on Time of the day?
<p>I have a DataFrame with <code>Datetime</code> as my <code>index_col</code>. This data is for 14 days. I want to create two different DataFrames based on the time of day: data between 6 am and 18 pm of all days as one df and data between 18 pm and 6 am of all days in another df. How to extract?</p> <p>Below is my D...
<p>try using </p> <p>for df1</p> <pre><code>df1=df.between_time('06:00', '18:00') </code></pre> <p>for df2</p> <pre><code>df2=df.between_time('18:00', '06:00') </code></pre> <p>more about it <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.between_time.html" rel="nofollow norefe...
python|pandas
4
1,523
54,773,169
How to plot specific value counts?
<pre><code>Col 1 Col 2 Col 3 0 No 2901 Yes 639 1 No 1858 Yes 415 2 No 1366 Yes 252 3 No 1236 Yes 277 </code></pre> <p>Say I have the following list. Essentially I'd like to create...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer">df.pivot</a> to make <code>Col 2</code> values column names, and then simply use plot:</p> <pre><code>df.pivot(index="Col 1", columns="Col 2", values="Col 3").plot() </code></pre> <p>Pivot...
pandas|matplotlib
0
1,524
54,839,391
Select the first row of each group after 'groupby()' and 'value_counts() function
<p>I have a data set named <code>new_data_set</code> which looks like this:</p> <p><a href="https://i.stack.imgur.com/n2o22.png" rel="nofollow noreferrer">Image</a></p> <p>I want to find genre which came the maximum number of times for each year.</p> <p>So I did this: </p> <pre><code>new_data_set.groupby('release_y...
<p>Add <code>index[0]</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.reset_index.html" rel="nofollow noreferrer"><code>reset_index</code></a>:</p> <pre><code>new_data_set = pd.DataFrame({ 'release_year':[2004,2005,2004,2005,2005,2004], 'genre':list('aaabb...
pandas|jupyter-notebook|data-science|data-analysis
4
1,525
54,779,775
Issues including Eigen for simple C++ TensorFlow Lite test program
<p>I compiled the library for the C++ API for TensorFlow Lite (r1.97) using the script <code>${TENSORFLOW_ROOT}/tensorflow/lite/tools/make/build_rpi_lib.sh</code> following the steps suggested at this official <a href="https://www.tensorflow.org/lite/rpi" rel="nofollow noreferrer">page</a> (Native Compiling, downloadin...
<p>Turns out I was including the wrong folder. Instead of <code>${TENSORFLOW_ROOT}/tensorflow/contrib/makefile/downloads/eigen</code> or <code>${TENSORFLOW_ROOT}/third_party/eigen3</code>, the right one is <code>${TFLITE_ROOT}/tensorflow/lite/tools/make/downloads/eigen</code>.</p> <p>I am still puzzled by the number o...
c++|include-path|eigen3|tensorflow-lite
0
1,526
49,476,516
Why is dummy '0' row created after pd.read_csv()?
<p>Why there is an additional row named '0' after read_csv?</p> <p>In the following code, I saved df1 to csv file and read it back. However, there is an additional row named '0'. How can I avoid it? </p> <pre><code>d1 = {'a' : 1, 'b' : 2, 'c' : 3} df1=pd.Series(d1) print('\ndf1:'); print(df1) &gt; df1: &gt; a 1 &...
<p>That is not a dummy row - that is the name of your indexing Column.</p> <p>You can check it by running:</p> <pre><code>&gt; df.index.name 0 </code></pre> <p>You can change it by setting it too:</p> <pre><code>&gt; df.index.name = "my_index" 1 my_index a 1 b 2 c 3 </code></pr...
python|pandas
1
1,527
49,512,706
Pandas: Average values in DataFrame column if string in adjacent column contains substring from another DataFrame
<p>I've been stuck on this for a while! I've got these two pandas dataframes:</p> <pre><code>import pandas as pd color_scores = pd.DataFrame({'score': [12.4, 9.8, 7.4, 2.6, 14.8], 'colors': ['blue, red, green', 'blue, purple, orange', 'blue, pink, yellow', 'purple, pink, orange',...
<p>I think need:</p> <pre><code>from collections import Counter c1, c2 = Counter(), Counter() for row in color_scores.itertuples(): for i in row[1].split(', '): c1[i] += row[2] c2[i] += 1 s = pd.Series(c1).div(pd.Series(c2)) print (s) blue 9.866667 green 13.600000 orange 6.200000 pi...
python|pandas|aggregate
1
1,528
73,503,682
how to save space training
<p>I have written an intent classification program. This is first trained with training data and then tested with test data. The training process takes a few seconds. What is the best way to save such a training, so that it does not have to be trained again with every call? Is it enough to save train_X and train_y? or ...
<p><code>spaCy</code> has methods to write any given model <a href="https://spacy.io/usage/saving-loading" rel="nofollow noreferrer">to and from disk</a>.</p> <p>Go <code>model.to_disk(path)</code> to store the model on your hard drive, then <code>model.from_disk()</code> to retrieve it. Let me know if this answers you...
python|pandas|spacy
1
1,529
73,416,907
model.save: Tried to export a function which references 'untracked' resource even though the tensor should be tracked
<h1>The Problem</h1> <p>I am getting this error from my code (see minimal repro code below):</p> <pre><code>AssertionError: Tried to export a function which references 'untracked' resource Tensor(&quot;1310:0&quot;, shape=(), dtype=resource). TensorFlow objects (e.g. tf.Variable) captured by functions must be 'tracked'...
<p>I managed to boil the minimum example down even more and found out what the problem was. Here is the new minimum repro code:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import tensorflow as tf class DummyModel(tf.keras.Model): feature_extractor = None def __init__(self, name=&quo...
python|tensorflow|keras
1
1,530
60,231,072
Is there a way to convert list of string formatted dictionary to a dataframe in Python?
<p>I am practicing how to use beautifulsoup and currently in a pickle as I can't convert the results to a dataframe. Hope to get your help.</p> <p>In this example, the page I want to scrape can be obtained using the following:</p> <pre><code>from bs4 import BeautifulSoup import requests import pandas as pd page = re...
<p>Looks like the question really is about how to parse a string, not how to do something with pandas.</p> <p>The list you have seem to contain simply valid json strings. You can convert them to python dict's using <code>json.loads()</code> from the standard lib. Of course if some strings are malformed that's another ...
python|pandas|list|dictionary|beautifulsoup
1
1,531
60,031,038
Searching for a word within a dataframe column
<p>I have the following datadrame:</p> <pre><code> import pandas as pd df = pd.DataFrame({'Id_email': [1, 2, 3, 4], 'Word': ['_ SENSOR 12', 'new_SEN041', 'engine', 'sens 12'], 'Date': ['2018-01-05', '2018-01-06', '2017-01-06', '2018-01-05']}) prin...
<p>Use pandas str contains, and include case as False - this allows you to search for sen or SEN</p> <pre><code>df.assign(Type = lambda x: np.where(x.Word.str.contains(r'SEN', case=False), 'Sensor_Type','Other')) Id_email Word Date Type 0 1 _ SENSOR 12 2018-01-05 ...
python|pandas|dataframe
3
1,532
65,459,399
Bounding Box regression using Keras transfer learning gives 0% accuracy. The output layer with Sigmoid activation only outputs 0 or 1
<p>I am trying to create an object localization model to detect license plate in an image of a car. I used VGG16 model and excluded the top layer to add my own dense layers, with the final layer having 4 nodes and sigmoid activation to get (xmin, ymin, xmax, ymax).</p> <p>I used the functions provided by keras to read ...
<p>If you're doing object localization task then you shouldn't using <code>'accuracy'</code> as your metrics, because <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model#compile" rel="nofollow noreferrer">docs of compile()</a> said:</p> <blockquote> <p>When you pass the strings 'accuracy' or 'acc', we co...
tensorflow|machine-learning|keras|deep-learning|object-detection
0
1,533
65,234,067
How to reshape BatchDataset class tensor?
<p>Im unable to reshape tensor loaded from my own custom dataset. As shown below <code>ds_train</code> has batch size of 8 and I want to reshape it such as: <code>len(ds_train),128*128</code>. So that I can feed the batch to my keras autoencoder model. Im new to TF and couldnt find solutions online, thus posting here.<...
<p>Try changing the shape inside the neural net:</p> <pre><code>inputs = keras.Input(shape=(128, 128, 1)) flat = keras.layers.Flatten()(inputs) </code></pre> <p>This would work:</p> <pre><code>import numpy as np import tensorflow as tf x = np.random.rand(10, 128, 128, 1).astype(np.float32) inputs = tf.keras.Input(sha...
python|tensorflow2.0
0
1,534
65,092,243
Python - import csv file and group numbers by column
<p>My problem is simple: I have <a href="https://gofile.io/d/O6e9wS" rel="nofollow noreferrer">this</a> csv file. I use Python 3. This file represent the number of new covid cases divided by country every day. But what I want to do is to obtain the global number of cases day by day regardless of the origin country. Wha...
<p>You could make a dictionary with dates as the key and cases as the value.</p> <pre><code>from datetime import datetime cases_by_day = {} with open(&quot;cases.csv&quot;) as f: f.readline() for line in f: elements = line.split(&quot;,&quot;) date = datetime.strptime(elements[0], &quot;%d/%m/%...
python-3.x|pandas|graph|dataset|data-mining
1
1,535
50,040,989
Pandas group by on list of dictionaries
<p>I have a data like below, I am trying to group the data into dayname and hour.</p> <pre><code> [ { "avg": 52, "hour": 9, "dayname": "Friday" }, { "avg": 1, "hour": 10, "dayname": "Friday" }, { ...
<p>You can feed a list of dictionaries directly into <code>pandas</code> and then manipulate:</p> <pre><code>df = pd.DataFrame(lst) res = df.pivot_table(index='hour', columns='dayname', values='avg', aggfunc=np.sum)\ .reset_index() res.columns.name = '' print(res) hour Friday Saturday 0 9 52 ...
python|python-3.x|pandas|pandas-groupby
1
1,536
50,128,438
How to specify column type in pandas dataframe
<p>After executing this line</p> <pre><code>data['numbers'] = data.apply(lambda row : [1] * len(row.text), axis=1) </code></pre> <p>The column 'numbers' is not a list as I expect it to be, but instead it's of type object which can't be indexed and I get IndexError.</p> <p>What I want as result is a column with 'numb...
<p><code>dtype</code> of <code>string</code>s, <code>dict</code>s, <code>list</code>s, <code>set</code>s, <code>tuple</code>s is always <code>object</code>, for testing <code>type</code> use:</p> <pre><code>data = pd.DataFrame({'text':['aaas','as']}, index=[10,12]) data['numbers'] = data.apply(lambda row : [1] * len(...
python|list|pandas|dataframe|apply
2
1,537
63,920,846
Create a 2-D Array From a Group of 1-D Arrays of Different Lengths in Python
<p>I have 2 1-D arrays that I have combined into a single 1-D array and would like to combine them into a 2-D array with 3 columns consisting of the two arrays and the newly created combined array. Ultimately, the objective is to plot all three 1-D arrays on a single chart using Plotly. The values are datetime but I wi...
<p>Pure numpy approach:</p> <pre><code>import numpy as np a = np.array([1,3,4,5,7,9]) b = np.array([2,4,6,8]) c = np.array([1,2,3,4,5,6,7,8,9]) abc = np.zeros((10, 3)) # change to a loop, if you like abc[a, 0] = a abc[b, 1] = b abc[c, 2] = c print(abc[1:]) </code></pre> <p>prints:</p> <pre><code>[[1. 0. 1.] [0....
arrays|python-3.x|numpy
2
1,538
64,129,567
Python/Pandas - Checking the list of values in pandas column for a condition
<p>I have a python program which process multiple files. Each file have customer id column based on value in city column. Some file has 8 digit customer id and some have 9 digit customer id. I need to do this -</p> <pre><code>if column city value is in ['Chicago', 'Newyork', 'Milwaukee', 'Dallas']: input_file['cust...
<p>Check with <code>np.where</code></p> <pre><code>l = ['Chicago', 'Newyork', 'Milwaukee', 'Dallas'] s1 = df['customer_id'].str[0:2] + '-' + df['customer_id'].str[2:8] s2 = 'K' + '-' + df['customer_id'].str[0:3] + '-' + df['customer_id'].str[3:8] df['cusotmerid'] = np.where(df['city'].isin(l), s1, s2) </code></pre>
python|pandas
1
1,539
46,919,525
Custom Dummy Coding in Pandas
<p>I have a dataframe with event data. I have two columns: Primary and Secondary. The Primary and Secondary columns both contain lists of tags (e.g., ['Fun event', 'Dance party']).</p> <pre><code> primary secondary combined ['booze', 'party'] ['singing', 'dance'] ['booze',...
<p>Here's one approach that works by transforming the <code>primary</code> and <code>secondary</code> columns' values into columns on the dataframe:</p> <pre><code>df = pd.DataFrame({ 'primary': [['booze', 'party'], ['concert']], 'secondary': [['singing', 'dance'], ['booze', 'vocals']], }) # creat...
python|pandas|dummy-variable
1
1,540
62,916,521
Keras LSTM to Pytorch
<p>I am using the following code to apply sequential LSTM to time-series data with one value. It works fine with a Keras version. I am wondering how could I do the same using PyTorch?</p> <pre><code>import tensorflow from tensorflow.keras import optimizers from tensorflow.keras import losses from tensorflow.keras.model...
<p>You can check the pytorch documentation for that: <a href="https://pytorch.org/docs/master/generated/torch.nn.LSTM.html" rel="nofollow noreferrer">https://pytorch.org/docs/master/generated/torch.nn.LSTM.html</a></p> <p>the simplest code is the following:</p> <pre><code> import torch, torch.nn as nn, torch.optim.Ad...
pytorch
0
1,541
62,899,927
ValueError: Dataframe must have columns "ds" and "y" with the dates and values respectively
<p>I have created my data source with ds and y format and am still receiving error as above...please see below code</p> <pre><code> import pandas as pd import numpy as np import pystan from fbprophet import Prophet import matplotlib.pyplot as plt plt.style.use(&quot;fivethirtyeight&quot;) df...
<p>I had the same issue; turns out I had <code>ds</code> and <code>y</code> capitalized. Once I made them lowercase in the <code>.csv</code> file, it all worked as it should.</p>
python|pandas
0
1,542
63,047,597
Substituting values in place of variables in pandas dataframe
<p>I have a dataframe as follows:</p> <pre><code> df: Name Age Type Result Ra 35 adult $name is an $type of $age years Ro 12 child $name behaves like $type as he is $age years old &lt;+100 rows&gt; </code></pre> <p>Each statement in Result column is different. All I...
<p><a href="https://docs.python.org/3/library/stdtypes.html?highlight=format_map#str.format_map" rel="nofollow noreferrer">format_map</a> takes a dictionary to replace the placeholders with the actual value.</p> <p>The placeholders to use in our case is the column names.</p> <p><a href="https://pandas.pydata.org/docs/r...
python|pandas|dataframe
1
1,543
63,103,706
MTCNN does not use GPU on first detection but does on following detections
<p>I have tensorflow 2.0 -gpu installed. I am doing face detection using MTCNN. On the first call to detect the face it takes 3.86 seconds. On the next call it takes only .049 seconds. I suspect it is not using the GPU on the first call but it does on the second call. I know MTCNN does import tensorflow but I do not u...
<p>It does use GPU on the first call. The main overhead in the allocation of model's parameters and creation of the computation graph in memory. You can use a small &quot;dummy&quot; image first (it doesn't have to be full-size) to allow the ops to be formed and variables to be placed on the GPU, then continue using th...
python|tensorflow2.0
2
1,544
67,950,502
Selecting values from tensor based on an index tensor
<p>I have two matrices. Matrix A is contains some values and matrix B contains indices. The shape of matrix A and B is (batch, values) and (batch, indices), respectively.</p> <p>My goal is to select values from matrix A based on indices of matrix B along the batch dimension.</p> <p>For example:</p> <pre><code># Matrix ...
<p>You can achieve this with the <a href="https://www.tensorflow.org/api_docs/python/tf/gather" rel="nofollow noreferrer"><code>tf.gather</code></a> function.</p> <pre><code>mat_a = tf.constant([[0., 1., 2., 3., 4.], [5., 6., 7., 8., 9.]]) mat_b = tf.constant([[0, 1], [1, 2]]) out = tf.gather(mat_...
tensorflow|tensorflow2.0
1
1,545
67,862,535
Add calculated column to df2 for every row entry in df2 pandas dataframe
<p>I have 2 dataframes</p> <pre><code>df1 = pd.DataFrame({'X':[1,2,3,4,5],'Y':[1,2,3,4,5],'Point':[1,2,3,4,5]}) </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">X</th> <th style="text-align: center;">Y</th> <th style="text-align: center;">Point</th> </tr> ...
<p>One possibility is to use the <code>cdist</code> function from <code>scipy</code>.</p> <pre><code>from scipy.spatial.distance import cdist output = pd.DataFrame(data=cdist(df1[[&quot;X&quot;, &quot;Y&quot;]], df2, 'euclidean'), index=pd.MultiIndex.from_frame(df2[[&quot;X&quot;,&quot;Y&quot;]])...
python|pandas
0
1,546
61,222,503
How to remove duplicate from rows and convert its value to column in pandas
<p>I have lot of data in the following format.</p> <pre><code>Person_ID Person_value 1 usr:value1 1 val:value2 2 usr:value1 2 val:value2 3 usr:value1 3 val:value2 4 usr:value1 ...
<p>IIUC use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> for helper column with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot.html" rel="nofollow noreferrer"><co...
python|python-3.x|pandas|amortized-analysis
3
1,547
61,495,877
How to replace or swap all values (largest with smallest) in python?
<p>I want to swap all the values of my data frame.Largest value must be replaced with smallest value (i.e. 7 with 1, 6 with 2, 5 with 3, 4 with 4, 3 with 5, and so on..</p> <pre><code>import numpy as np import pandas as pd import io data = ''' Values 6 1 3 7 5 2 4 1 4 7 2 5 ''' df = pd.read_csv(io.StringIO(data)) </...
<p>Here's a vectorized one -</p> <pre><code>In [51]: m,n = np.unique(df['Values'], return_inverse=True) In [52]: df['New_Values'] = m[n.max()-n] In [53]: df Out[53]: Values New_Values 0 6 2 1 1 7 2 3 5 3 7 1 4 5 3 5 2 ...
python|pandas|numpy
3
1,548
61,535,852
Lazy evaluations of numpy.einsum to avoid storing intermediate large dimensional arrays in memory
<p>Imagine that I have integers, <code>n,q</code> and vectors/arrays with these dimensions:</p> <pre><code>import numpy as np n = 100 q = 102 A = np.random.normal(size=(n,n)) B = np.random.normal(size=(q, )) C = np.einsum("i, jk -&gt; ijk", B, A) D = np.einsum('ijk, ikj -&gt; k', C, C) </code></pre> <p>which is work...
<p>This is a really fascinating question - as @s-m-e mentioned, numpy does not offer a lazy <code>einsum</code> computations, but it does offer a lower level function called <a href="https://numpy.org/doc/stable/reference/generated/numpy.einsum_path.html#numpy.einsum_path" rel="nofollow noreferrer">np.einsum_path</a>, ...
numpy|multidimensional-array|lazy-evaluation|numpy-einsum
1
1,549
65,694,416
Can a tf-agents environment be defined with an unobservable exogenous state?
<p>I apologize in advance for the question in the title not being very clear. I'm trying to train a reinforcement learning policy using tf-agents in which there exists some unobservable stochastic variable that affects the state.</p> <p>For example, consider the standard CartPole problem, but we add wind where the velo...
<p>Yes, that is no problem at all. Your environment object (a subclass of <code>PyEnvironment</code> or <code>TFEnvironment</code>) can do whatever you want within it. The <code>observation_spec</code> requirement is only related to the TimeStep that you output in the <code>step</code> and <code>reset</code> methods (m...
tensorflow|reinforcement-learning|tensorflow-agents
2
1,550
65,696,049
How to set date index manually and fill zeros for missing rows in python panda dataframe
<p>I have a dataset given below and I have a parameter that takes current date:</p> <pre><code>product_name serial_number date sum &quot;A&quot; &quot;12&quot; &quot;2020-01-01&quot; 150 &quot;A&quot; &quot;12&quot; &quot;2020-01-02&quot; 35...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot.html" rel="nofollow noreferrer"><code>pivot</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFrame.reindex</code></a> by <a href="ht...
python|pandas|dataframe|time-series
1
1,551
63,558,043
get min and max values of several values in a df
<p>I have this df :</p> <pre><code>df=pd.DataFrame({'stop_i':['stop_0','stop_0','stop_0','stop_1','stop_1','stop_0','stop_0'],'time':[0,10,15,50,60,195,205]}) </code></pre> <p>Each line corresponds to the <code>time</code> (in seconds) where the bus was at the <code>stop_i</code>.</p> <p>First, i want to count how much...
<p>No looping</p> <ol> <li>generate a new column that is the set of times that bus is at a stop (assumes index is sequential)</li> <li>from this get first and last times. then construct a list of first / last times. Plus calcs for &gt; 180s. This logic seems odd. stop_1 only has one visit so count of 1 for &gt; 180...
python|python-3.x|pandas|list|dictionary
2
1,552
53,649,050
Creating separate columns based on string value in python
<p>I am quite new but I am working with a dataframe that looks like the below:</p> <pre><code>ID Tag 123 Asset Class &gt; Equity 123 Inquiry Type &gt; Demonstration 123 Inquiry Topic &gt; Holdings 456 Asset Class &gt; Fixed Income 456 Inquiry Type &gt; BF 456 Inquiry Topi...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>split</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot.html" rel="nofollow noreferrer"><code>pivot</code></a> and selecting splitted lists by ind...
pandas|dataframe
1
1,553
55,550,605
What is it that's being passed to transform function of Series?
<p>I'm using <code>transform</code> function of <code>Series</code>, but something got me confused.</p> <p>I have searched the documentation of Pandas and googled,but couldn't find the answer.</p> <p>When I use <code>np.sum</code>, the result is:</p> <pre><code>s = Series(range(7)) s.transform(lambda x:x + np.sum(x)...
<p>I read the source code. I find that the <code>transform</code> function depend on <code>aggregate</code> function.And It will try a regular apply first:</p> <pre><code>def aggregate(self, func, axis=0, *args, **kwargs): # Validate the axis parameter self._get_axis_number(axis) result, how = self._aggreg...
pandas|transform|series
0
1,554
55,501,746
Type Error when multiplying slope by a list of X
<p><strong>Below is the problem I am running into:</strong></p> <p><em>Linear Regression - Given 16 pairs of prices (as dependent variable) and corresponding demands (as independent variable), use the linear regression tool to estimate the best fitting linear line.</em></p> <pre><code>Price Demand 127 3420 134 3400 1...
<p>You did not convert the Python lists to numpy arrays here:</p> <pre><code>x = [3420, 3400, 3250, 3410, 3190, 3250, 2860, 2830, 3160, 2820, 2780, 2900, 2810, 2580, 2520, 2430] np.asarray(x,dtype= np.float64) </code></pre> <p><code>np.asarray</code> returns a numpy array, but does not modify the original. You can do...
python|python-2.7|numpy|linear-regression
1
1,555
66,885,879
Ranking and extracting the data from a column of a dataframe?
<p>I have a file with ranked information:</p> <p>df1</p> <pre><code>Type Rank frameshift 1 stop_gained 2 stop_lost 3 splice_region_variant 4 splice_acceptor_variant 5 splice_donor_variant 6 missense_variant 7 coding_sequence_variant 8 intron_variant ...
<p>You can change list comprehension for first split by <code>|</code> (or <code>,</code>) and then by <code>&amp;</code>:</p> <pre><code>d = df1.set_index('Type')['Rank'].to_dict() max1 = df1['Rank'].max()+1 def f(x): d1 = {z: d.get(z, max1) for y in x for y in x.split('|') for z in y.split('&amp;')} #htt...
python|pandas
2
1,556
66,860,702
Dataframe doesn't show all columns
<p>I am working in Python with the compas-scores dataset of 47 columns and 11757 rows (<a href="https://github.com/propublica/compas-analysis" rel="nofollow noreferrer">https://github.com/propublica/compas-analysis</a>).</p> <p>I've noticed that when I am calling the dataset, it doesn't shows me all the columns. Instea...
<p>assuming your import statement is <code>import pandas as pd</code></p> <p>I'd suggest trying one of the below:</p> <pre><code>pd.options.display.max_columns = None </code></pre> <p>or</p> <pre><code>pd.set_option('display.max_columns', None) </code></pre> <p>same can be used for <code>max_rows</code>:</p> <pre><cod...
python|pandas|dataframe
2
1,557
68,105,972
pandas pivot based on unique values and criteria
<p>I have this dataframe:</p> <pre><code>df_in = pd.DataFrame({'id': ['123', '123', '123', '123', '123', '456'], 'ven_group': ['a', 'a', 'a', 'b', 'f', 'f'], 'date': ['1/1/21', '2/1/21', '3/1/21', '1/1/21', '1/1/21', '1/1/21'] }) </code></pre> <p><a href="https://i.stack.imgur.com/4rmyc.png" rel="nofollow noreferrer...
<p>One Way:</p> <pre><code>unique_id = df.id.unique() ven_group_li = ['a', 'b', 'c'] df = df[df.ven_group.isin(ven_group_li)] df1 = df.groupby(['id', 'ven_group']).agg( [min, max]).reset_index(-1).groupby(level=0).agg(list) df1.columns = ['name', 'max', 'min'] df2 = pd.concat( [df1[c].apply(pd.Series).add_prefi...
python|pandas|group-by|pivot-table|apply
1
1,558
59,441,896
Using NLTK to tokeniz sentences to words using pandas
<p>I'm trying to tokenize sentences from a csv file into words but my loop is not jumping to the next sentence its just doing first column. any idea where is the mistake ? this is how my CSV file look like <a href="https://i.stack.imgur.com/juWSL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/juWSL....
<p>You just need to change the code to grab the sentences:</p> <pre><code>import re import string import pandas as pd text=pd.read_csv("out157.txt", sep="|") from nltk.tokenize import word_tokenize tokenized_docs=[word_tokenize(doc) for doc in text['SENTENCES']] x=re.compile('[%s]' % re.escape(string.punctuation)) tok...
python|pandas|dataframe|nltk
3
1,559
59,457,670
Best case to use tensorflow
<p>I followed all the steps mentioned in the article:</p> <p><a href="https://stackabuse.com/tensorflow-2-0-solving-classification-and-regression-problems/" rel="nofollow noreferrer">https://stackabuse.com/tensorflow-2-0-solving-classification-and-regression-problems/</a></p> <p>Then I compared the results with Linea...
<p>Answering your first question, Neural Networks are notoriously known for <a href="https://en.wikipedia.org/wiki/Overfitting" rel="nofollow noreferrer">overfitting</a> on smaller datasets, and here you are comparing the performance of a simple linear regression model with a neural network with two hidden layers on th...
tensorflow|scikit-learn|regression|linear-regression
2
1,560
57,087,585
How do I get this output?
<p>I have got a very large <code>Pandas Data Frame</code>. A part of which looks like this: </p> <pre><code> Rule_Name Rule_Seq_No Condition Expression Type Rule P 1 ID 19909 Action Rule P 1 Type A Condition Rule P 1 System B...
<p>Use:</p> <pre><code>df1 = (df.assign(Condition = '(' + df['Condition'] + '=' + df['Expression'] + ')') .groupby(['Rule_Name','Rule_Seq_No','Type']) .agg({'Condition': 'and'.join, 'Expression':'first'}) .unstack() .drop([('Condition','Action'), ('Expression','Condition')], axis=1)...
python-3.x|pandas|dataframe
5
1,561
57,037,742
How to data clean in groups
<p>I have an extremely long dataframe with a lot of data which I have to clean so that I can proceed with data visualization. There are several things I have in mind that needs to be done and I can do each of them to a certain extent but I don't know how to, or if it's even possible, to do them together. </p> <p>This ...
<p>I used this dataframe to test the code (the one in your question):</p> <pre><code>df = pd.DataFrame([['2013-01', 'Total', 'Total', 'Air', 984350], ['2013-01', 'Total', 'Total', 'Sea', 129074], ['2013-01', 'Total', 'Total', 'Land', 178294], ['2013-02', 'Tot...
python|pandas|data-cleaning
1
1,562
45,953,287
Check values of the keys in dictionary and construct matrix for keys only using Python
<p>I have a dictionary as mentioned below.</p> <pre><code>mydictionary = {colours: [red, pink, blue, green, yellow], animals: [cat, rat, dog, goat], vehicles: [car, jeep, van, bus, lorry]} </code></pre> <p>I also have a matrix for each value of the keys as given in the examples below (if that value is in the essay I...
<pre><code>m = {v: k for k, l in mydictionary.items() for v in l} df.groupby(df.columns.map(m.get), 1).sum().clip(0, 1) animals colours vehicles Essay1 0 1 1 Essay2 1 1 0 </code></pre>
python|pandas
3
1,563
46,144,429
Tensorflow Extract Indices Not Equal to Zero
<p>I want to return a dense tensor of the non-zero indices for each row. For example, given the tensors:</p> <pre><code>[0,1,1] [1,0,0] [0,0,1] [0,1,0] </code></pre> <p>Should return</p> <pre><code>[1,2] [0] [2] [1] </code></pre> <p>I can get the indices using tf.where(), but I do not know how to combine the result...
<p>Notice that in your example, the output is not a matrix but a jagged array. Jagged arrays have limited support in TensorFlow (through TensorArray), so it's more convenient to deal with rectangular arrays. You could pad each row with -1's to make the output rectangular</p> <p>Suppose your output was already rectangu...
python|tensorflow
1
1,564
66,437,545
Converting column type 'datetime64[ns]' to datetime in Python3
<p>I would like to perform a comparison between the two dates (One from a pandas dataframe) in python3, another one is calculated. I would like to filter pandas dataframe if the values in the 'Publication_date' is equal to or less than the today's date and is greater than the date 10 years ago.</p> <p>The pandas df loo...
<p>You can use only pandas for working with datetimes - <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.floor.html" rel="nofollow noreferrer"><code>Timestamp.floor</code></a> is for remove times from datetimes (set times to <code>00:00:00</code>):</p> <pre><code>df['Publication_date'...
python|pandas|dataframe|datetime
1
1,565
66,688,647
Fill tensor with another tensor where mask is true
<p>I need to insert elements of tensor <em>new</em> into a tensor <em>old</em> with a certain probability, let's say that it is 0.8 for simplicity. Substantially this is what masked_fill would do, but it only works with monodimensional tensor. Actually I am doing</p> <pre><code> prob = torch.rand(trgs.shape, dtype=t...
<p>I am not sure what some of your objects are, but this should get you to do what you need in short order:</p> <p><code>old</code> is the your existing data.</p> <p><code>mask</code> is the mask you generated with probability p</p> <p><code>new</code> is the new tensor that has elements you want to insert.</p> <pre><c...
python|pytorch|tensor
2
1,566
57,337,931
Tensorflow : DLL load failed: A dynamic link library (DLL) initialization routine failed
<p>I am setting up a Captcha solver with tensorflow object-detection and i get this error</p> <pre> DLL load failed: A dynamic link library (DLL) initialization routine failed. </pre> <p>It is on a Windows Server I got Python 3.7.3 And Tensorflow 1.14.0 and i am not using the tensorflow-gpu ! but i already get this e...
<p><strong>TensorFlow release binaries version 1.6 and higher are prebuilt with AVX instruction sets.</strong> .<br /> Therefore on any CPU that does not have these instruction sets, either CPU or GPU version of TF will fail to load.</p> <p>Apparently, your CPU model does not support AVX instruction sets. You can still...
python|tensorflow|machine-learning
3
1,567
72,868,893
Apply function to dataframe column based on combinations of values from other columns
<p>I have a dataframe that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Region</th> <th>Country</th> <th>Product</th> <th>Year</th> <th>Price</th> </tr> </thead> <tbody> <tr> <td>Africa</td> <td>South Africa</td> <td>ABC</td> <td>2016</td> <td>500</td> </tr> <tr> <td>Afr...
<p>I managed to figure it out, if anyone is interested, the solution is below:</p> <pre><code># Identify outliers using Tukey's method. def outliers_tukey(df, variable, iterable1, iterable2): outliers_prob = [] outliers_poss = [] for (i,j) in itertools.product(df[iterable1].unique(), df[iterable2].unique())...
python|pandas|function|numpy|scipy
0
1,568
72,868,981
How to fetch elements between x and y from tf.data.TFRecordDataset in Tensorflow
<p>The <code>test_dataset</code> is defined as:</p> <pre><code>test_dataset = tf.data.TFRecordDataset([test_tfrecords]) test_dataset = test_dataset.map(map_f) test_dataset = test_dataset.repeat(1) test_dataset = test_dataset.batch(1) </code></pre> <p>For fetching the first 100 elements:</p> <pre><code>for test in test_...
<p>Try <code>tf.data.Dataset.skip</code>:</p> <pre><code>for test in test_dataset.skip(50).take(100): pass </code></pre>
python|tensorflow|tensorflow-datasets
1
1,569
70,666,759
How to update one dataframe based on the value of other dataframe?
<p>Hi I have 2 dataframes in which I have to update the values based on the other dataframe-</p> <p>Example: df1:</p> <pre><code>Region Sub_Region Status Reason LATAM CRM Success LATAM Genesys Failed ASPAC CRM Success ASPAC Genesys Success </code></pre> <p>df2:</p> <pre><...
<p>You can <code>merge</code> and <code>mask</code>:</p> <pre><code>(df1.merge(df2, on=['Region', 'Sub_Region']) .assign(Max_Load_Date=lambda d: d['Max_Load_Date'].mask(d['Status']=='Failed', '')) ) </code></pre> <p>Merging will ensure the correct data is mapped to the correct row in case both dataframes are not so...
python|python-3.x|pandas|dataframe
0
1,570
70,419,906
How to group by date and apply a formula to each group?
<p>I have the following <code>df</code>:</p> <pre><code> DateTime Var1 0 2021-08-01 10:00:00 115.0 1 2021-08-01 11:00:00 99.0 2 2021-08-01 12:00:00 155.0 3 2021-08-01 13:00:00 73.0 4 2021-08-01 14:00:00 44.0 5 2021-08-02 10:00:00 112.0 6 2021-08-02 11:00:00 100.0 7 2021-08-02 12:00:00 150....
<p>Output is expected, because:</p> <pre><code>return group[&quot;Var1&quot;]/len(group) </code></pre> <p>return Series like original DataFrame.</p> <p>Need aggregation, e.g. <code>sum</code>:</p> <pre><code>return group[&quot;Var1&quot;].sum()/len(group) </code></pre> <p>what is same like:</p> <pre><code>return group[...
python|pandas
2
1,571
70,602,796
Pytorch GPU memory keeps increasing with every batch
<p>I'm training a CNN model on images. Initially, I was training on image patches of size <code>(256, 256)</code> and everything was fine. Then I changed my dataloader to load full HD images <code>(1080, 1920)</code> and I was cropping the images after some processing. In this case, the GPU memory keeps increasing with...
<p>As suggested <a href="https://discuss.pytorch.org/t/gpu-memory-consumption-increases-while-training/2770/3?u=nagabhushansn95" rel="nofollow noreferrer">here</a>, deleting the input, output and loss data helped.</p> <p>Additionally, I had the data as a dictionary. Just deleting the dictionary isn't sufficient. I had ...
python|memory-leaks|pytorch
0
1,572
70,408,145
Select a column without "losing" a dimension
<p>Suppose I execute the following code</p> <pre><code>W = tf.random.uniform(shape = (100,1), minval = 0, maxval = 1) Z = tf.random.uniform(shape = (100,1), minval = 0, maxval = 1) X = tf.concat([W,Z],1) </code></pre> <p>The shape of <code>X[:,1]</code> would be <code>[100,]</code>. That is, <code>X[:,1].shape</code> w...
<p>Maybe just use <code>tf.newaxis</code> for your use case:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf W = tf.random.uniform(shape = (100,1), minval = 0, maxval = 1) Z = tf.random.uniform(shape = (100,1), minval = 0, maxval = 1) X = tf.concat([W,Z],1) print(X[:, 1, tf.newaxis].shape)...
python|tensorflow
1
1,573
35,951,712
Numpy Install on Mac OSX
<p>I have been trying to install numpy on my Mac OSX for the last 2 days. I have installed Homebrew as well, and ran the command-</p> <pre><code>pip install numpy </code></pre> <p>which gives me the following output-</p> <pre><code>Requirement already satisfied (use --upgrade to upgrade): numpy in /Library/Framework...
<p>If you run <code>import numpy</code> from the command line, you will get an error:</p> <pre><code>$ import numpy as np -bash: import: command not found </code></pre> <p>You need to start Python, and then type the import statement within the Python interpreter:</p> <pre><code>$ python Python 3.5.1 |Continuum Analy...
macos|python-2.7|numpy
2
1,574
37,384,627
How to show Cartesian system in polar plot in python?
<p>Here I tried to add the polar plot on top of the Cartesian grid,but what I got instead was 2 separate figures(one polar another Cartesian),I want this polar figure to be embedded in the Cartesian plot. Also I have used some of the code previously available as I am new to matplotlib.</p> <pre><code>from pylab impor...
<p>I am not used to <code>matplotlib</code> but I reduced your code to his minimum to better understand it and make it look less redudant. look at what I get: </p> <pre><code>import pylab import matplotlib.pyplot as plt import numpy as np ######################################### x = [0,10,-3,-10] y = [0,10,1,-10] col...
python|numpy|matplotlib
2
1,575
37,257,737
merging dataframes only by certain columns
<p>I try to merge dataframes by index and only take certain columns to the result.</p> <pre><code>result = pd.concat([self.retailer_categories_probes_df['euclidean_distance'], self.retailers_categories_df['euclidean_distance']]) </code></pre> <p>But with the result I get the 'euclidean_distance' from first table ? An...
<p>I think you may need <code>axis=1</code>:</p> <pre><code>result = pd.concat([self.retailer_categories_probes_df['euclidean_distance'], self.retailers_categories_df['euclidean_distance']], axis=1) </code></pre> <p>See <code>pd.concat()</code> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.con...
python|pandas|dataframe
1
1,576
37,424,988
Using apply to write to a global Pandas dataframe
<p>I am trying to create a new dataframe that has values added to it if a condition from another dataframe is met. Where if a column is not empty it would apply a function that would write the proceeding 90 rows to the new dataframe. However, I am having a host of errors when I am writing the current code, as I am havi...
<p>Question is slightly unclear but here is what I think you need:</p> <pre><code>In[1] import pandas as pd df = pd.DataFrame({"Example": ["A","A","A","A","A","B","B","B","B","B"], "Value": [10,20,30,15,10,10,20,30,15,10], "Characters1": [np.nan, np.nan, 1, np.nan,np.nan,np.nan,np.nan,np.nan,1, np.nan]}) In[2]...
python|numpy|pandas
1
1,577
42,096,798
Using gensim Scipy2Corpus without materializing sparse matrix in memory
<p>I have three NumPy arrays saved to disk in <code>.npy</code> format, together totaling about 40 GB (representing text count data from a very large document set). The three arrays represent the <code>data</code>, <code>indices</code>, and <code>indptr</code> attributes of a <a href="https://docs.scipy.org/doc/scipy-0...
<p>I made a sparse matrix:</p> <pre><code>In [207]: A=sparse.random(100,100,.1,'csr') In [208]: A Out[208]: &lt;100x100 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 1000 stored elements in Compressed Sparse Row format&gt; </code></pre> <p>Made copies of its attributes, and saved them</p> <pre><cod...
python|numpy|scipy|sparse-matrix|gensim
0
1,578
8,136,273
Wrapping C++ and CUDA in Python
<p>I want to create an interface for a numerical library consisting of both OOP C++ (boost) and CUDA C code, in Python. There is already an existing MATLAB interface, but it contains a lot of mex.h dependencies. </p> <p>How can this be done as painless as possible? </p>
<p>Here are a couple of links to look at. Could people who've used any of these please comment ?</p> <pre><code># day status packagename version homepage summary 2011-02-03 4 "scikits.cuda" 0.03 http://github.com/lebedov/scikits.cuda/ Python interface to GPU-powered libraries 2010-10-27 0 "KappaCUDA" ...
numpy|cython|ctags|mex
2
1,579
37,978,624
How to export array in csv or txt in Python
<p>I'm trying to export array to txt or csv file. I've been trying with numpy but i always get some error like <code>TypeError: Mismatch between array dtype ('&lt;U14') and format specifier ('%.18e')</code></p> <p>Here is my code without numpy that works great but I need help with part how to export it.</p> <pre><co...
<p>Looks like you are doing something like:</p> <pre><code>In [1339]: peoples=[] In [1340]: for _ in range(3): ......: peoples.append([234, datetime.datetime.now().strftime("%d/%m/%y %H:%M")]) ......: In [1341]: peoples Out[1341]: [[234, '22/06/16 14:57'], [234, '22/06/16 14:57'], [234, '22/06/16 14:5...
python|arrays|csv|numpy
1
1,580
31,466,769
Add column of empty lists to DataFrame
<p>Similar to this question <a href="https://stackoverflow.com/questions/16327055/how-to-add-an-empty-column-to-a-dataframe">How to add an empty column to a dataframe?</a>, I am interested in knowing the best way to add a column of empty lists to a DataFrame.</p> <p>What I am trying to do is basically initialize a col...
<p>One more way is to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html" rel="noreferrer"><code>np.empty</code></a>:</p> <pre><code>df['empty_list'] = np.empty((len(df), 0)).tolist() </code></pre> <hr> <p>You could also knock off <code>.index</code> in your "Method 1" when trying to f...
python|pandas
68
1,581
64,358,754
regex code, how to slove some data entry error
<p>I have two dataframe</p> <pre><code>df1 name ADAM, HAFIZ M ABAD, FARLEY J CORDDED, NANCY C BOMBSHAD, WANG D df2 JOSEPH W. HOLUBKA WANG E. JONATHAN CUCU F. LIU, WANG C. DANA, LANDY F. JON </code></pre> <p>I am hoping to extract the first name of each dataframe. For df1, I need the &quot;first name&quot; portion ...
<p>You can use</p> <pre><code>(^(?=[^,]*,?$)[\w'-]+|(?&lt;=, )[\w'-]+) </code></pre> <p>See the <a href="https://regex101.com/r/WbfbU8/2/" rel="nofollow noreferrer">regex demo</a>. This pattern allows matching a name at the initial position in the string if there is a trailing comma in the string.</p> <p>Use it in Pand...
python|regex|pandas
1
1,582
64,518,556
Can you use a context manager to write a pandas DataFrame to sqlite
<p>When writing a pandas DataFrame to sql, would it be possible to use the with statement in the following way?</p> <pre><code>import sqlite3 import pandas as pd with sqlite3.connect('database.db') as conn: df = pd.read_sql(&quot;SELECT * FROM table&quot;, conn) # add change to db df.to_sql('table', ...
<p>From the <a href="https://docs.python.org/3/library/sqlite3.html#using-the-connection-as-a-context-manager" rel="nofollow noreferrer">documentation</a></p> <blockquote> <p>Connection objects can be used as context managers that automatically commit or rollback transactions. In the event of an exception, the transact...
python|sql|pandas
2
1,583
47,916,288
Python DataFrame: replace or combine selected values into main DataFrame
<p>I have two pandas DataFrame as below. It contains strings and np.nan values. df =</p> <pre><code> A B C D E F 0 aaa abx fwe dcs NaN gsx 1 bbb daf dxs fsx NaN ewe 2 ccc NaN NaN NaN NaN dfw 3 ddd NaN NaN asc NaN NaN 4 eee NaN NaN cse NaN NaN 5 fff NaN NaN wer xer ...
<pre><code>df.update(dfr.fillna('NaN')) df.replace('NaN',np.nan) Out[501]: A B C D E F 0 aaa abx fwe dcs NaN gsx 1 bbb daf dxs fsx NaN ewe 2 sfa NaN NaN NaN NaN wes 3 ddd NaN NaN asc NaN NaN 4 web NaN NaN cse NaN NaN 5 NaN NaN wwc wer wew NaN </code></pre>
python|pandas|dataframe|replace|combiners
3
1,584
47,670,098
slicing error in numpy array
<p>I am trying to run the following code </p> <pre><code>fs = 1000 data = np.loadtxt("trainingdataset.txt", delimiter=",") data1 = data[:,2] data2 = data1.astype(int) X,Y = data2['521'] </code></pre> <p>but it gets me the following error</p> <pre><code>Traceback (most recent call last): File "C:\Users\hadeer.elzia...
<p>You say you want all the data in the 3rd column.</p> <p>I assume you also want some kind of x-axis, since you are attempting to do <code>X, Y = ...</code>. How about using the first column for that? Then your code would be:</p> <pre><code>import numpy as np data = np.loadtxt("trainingdataset.txt", delimiter=',', ...
python-3.x|numpy|matplotlib|signal-processing
0
1,585
47,893,677
Why are numpy functions so slow on pandas series / dataframes?
<p>Consider a small MWE, taken from <a href="https://stackoverflow.com/q/47881048/4909087">another question</a>:</p> <pre><code>DateTime Data 2017-11-21 18:54:31 1 2017-11-22 02:26:48 2 2017-11-22 10:19:44 3 2017-11-22 15:11:28 6 2017-11-22 23:21:58 7 2017-11-28 14:28:28 28 2017-1...
<p>Yes, it seems like <code>np.clip</code> is a lot slower on <code>pandas.Series</code> than on <code>numpy.ndarray</code>s. That's correct but it's actually (at least asymptotically) not that bad. 8000 elements is still in the regime where constant factors are major contributors in the runtime. I think this is a very...
python|performance|pandas|numpy
50
1,586
48,965,791
One value for each df Column group
<pre><code> A B 0 2002-01-16 10 1 2002-01-16 7 2 2002-01-16 2 3 2002-01-16 8 4 2002-01-16 5 5 2002-01-17 54 6 2002-01-17 6 7 2002-01-17 2 </code></pre> <p>I want to add a <em>C column</em> which contains the <strong>first <em>Column B value</em> for each <em>Column A date group</em><...
<p>You can groupby column A, then use <code>.transform('first')</code> on column B to generate a series that has the first value of the group for all items in the group, eg:</p> <pre><code>df.loc[:, 'C'] = df.groupby('A').B.transform('first') </code></pre> <p>This'll make your example frame be:</p> <pre><code> ...
python|pandas
3
1,587
48,935,200
Pandas DF referencing the same slice twice in the same computation
<p>I have a huge data set to process and I am trying to optimize the most costly line, processing wise.</p> <p>I use a df with 3 columns, A, B and C. I have 2 values, a and b, which are used to update the value of C in a subset of the df.</p> <p>Before I continue, let me define a textual substitution to increase read...
<p>If I understand correctly, you may not need to "filter twice" after the <code>+=</code>. see my example below:</p> <pre><code>np.random.seed(5) df = pd.DataFrame(np.random.randint(0,100,size=(4, 4)), columns=list('ABCD')) A B C D 0 99 78 61 16 1 73 8 62 27 2 30 80 7 76 3 15 53 80 ...
python|pandas
1
1,588
49,341,568
Pandas Series argument function memoization
<p>I want to memoize a function with mutable parameters (Pandas Series objects). Is there any way to accomplish this?</p> <p>Here's a simple Fibonacci example, the parameter is a Pandas Series where the first element represents the sequence's index.</p> <p>Example:</p> <pre><code>from functools import lru_cache @lr...
<p>Several options:</p> <ul> <li>Convert the mutable objects to something immutable such as a string or tuple.</li> <li>Create a hash of the mutable objects and use that as the memo dict key. Risk of hash clashes.</li> <li>Create an immutable subclass which implements the __hash__() function.</li> </ul>
python|pandas|memoization|mutable
1
1,589
58,633,886
Highlighting Values in Pandas
<p>Good Evening all, I have made a pandas DataFrame from an excel spreadsheet. I am trying to highlight the names in this list that have logged in at 9:01:00 etc. Anyone who has logged in past the hour or half hour by 1 minute, but excluding those that have logged in early eg 07:59:00 or 07:29:00. EG. Those with * arou...
<p>You can have a look at the Pandas styling options. It has an applymap function which helps you to color code specific columns based on conditions of your choice. </p> <p>The documention (<a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html" rel="nofollow noreferrer">https://pandas.pydata.org/...
python|python-3.x|pandas
0
1,590
70,178,582
Why loss function always return zero after first epoch?
<p>Why the loss function is always printing zero after the first epoch?</p> <p>I suspect it's because of <code>loss = loss_fn(outputs, torch.max(labels, 1)[1])</code>.</p> <p>But if I use <code>loss = loss_fn(outputs, labels)</code>, I will get the error</p> <pre><code>RuntimeError: 0D or 1D target tensor expected, mul...
<p>Usually loss calculation is <code>loss = loss_fn(outputs, labels)</code> and here <code>outputs</code> is as following:</p> <pre><code>_ , outputs = torch.max(model(input), 1) or outputs = torch.max(predictions, 1)[0] </code></pre> <p>Common practice is modifying <code>outputs</code> instead of <code>labels</code>:<...
python|pytorch|conv-neural-network
1
1,591
56,249,665
Pandas Merge returns empty dataframe
<p>I'm loading two dataframes from two different csv's, and, try to join them, but for some reason <code>pd.merge</code> is not joining the data and is returning empty dataframe. I have tried changing the data types, but still nothing. Appreciate any help.</p> <p>Sample <code>mon_apps</code> dataframe:</p> <pre><code...
<p>The month and year is exchanged in the files you are merging try swapping the keys while merging or rename them before the merge:</p> <pre><code>mon_apps.merge(complete_file, left_on=["year", "month"],right_on=['month','year']) </code></pre>
python-3.x|pandas
3
1,592
56,150,863
Pandas: load a table into a dataframe with read_sql - `con` parameter and table name
<p>In trying to import an sql database into a python pandas dataframe, and I am getting a syntax error. I am newbie here, so probably the issue is very simple.</p> <p>After downloading sqlite sample chinook.db from <a href="http://www.sqlitetutorial.net/sqlite-sample-database/" rel="nofollow noreferrer">http://www.sql...
<p>Found it!</p> <p>An example of db connection with SQLAlchemy can be found here: <a href="https://www.codementor.io/sagaragarwal94/building-a-basic-restful-api-in-python-58k02xsiq" rel="nofollow noreferrer">https://www.codementor.io/sagaragarwal94/building-a-basic-restful-api-in-python-58k02xsiq</a></p> <pre><code>...
python|pandas|sqlite
0
1,593
56,381,631
"index 1 is out of bounds for axis 0 with size 1" in python
<p>I seem to be having an indexing problem? I do not know how to interpret this error... :/ I think it has to do with how I initialized u.</p> <p>I have this 3x3 G matrix that I created using the variable u (a vector, x - y). I just made a zero matrix for now bc I'm not quite sure how to code it yet, there are lots of...
<p><code>np.matlib</code> makes a <code>np.matrix</code>, a subclass of <code>np.ndarray</code>. It's supposed to give a MATLAB feel, and (nearly) always produces a 2d array. Its use in new code is being discouraged.</p> <pre><code>In [42]: U = np.matrix(np.arange(9).reshape(3,3)) ...
python|numpy|indexing
0
1,594
55,820,138
Pandas reset_index() is not working after grouping by and aggregating by multiple methods
<p>I have a pandas DataFrame with 2 grouping columns and 3 numeric columns. I am grouping the data like this:</p> <pre><code>df = df.groupby(['date_week', 'uniqeid']).agg({ 'completes':['sum', 'median', 'var', 'min', 'max'] ,'dcount_visitors': ['sum', 'median', 'var', 'min', 'max'] ,'dcount_visitor_group...
<p>(realize it's a bit against the norm to "accept" your own question, but wanted to save folks time in responding to a question that was resolved) </p> <p>@Efran: I did, and it was a 2 level multi-index. @Bugbeeb: Good call on identifying the level. The 5 on the labels was throwing me off. </p> <p>I was able to hun...
python|pandas|feature-engineering
2
1,595
65,007,457
I have a numpy file that is an array of percentages, how do I turn this to a yes/no database where only values higher than 0.3 are a yes?
<p>I have an array of 19000 numbers from 0 to 1 that represent percentages and I would like to have a database of yes and no where yes is every number above 0.3 and no every number below 0.3.</p> <p>Something that should look like this where original is my initial file</p> <p>original = [0.2499320, 0.456484, 0.324824 ....
<p><a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer">numpy.where</a> will do the job.</p> <pre><code>import numpy as np arr = np.random.rand(10) print(arr) print(np.where(arr&gt;=0.3, 'Yes', 'No')) # [0.23556319 0.1173074 0.2673033 0.05552573 0.79930567 0.3344331...
python|arrays|python-3.x|numpy
1
1,596
64,934,798
How to do time series backward resampling e.g. 5 business days starting on the last data date?
<p>I would like to compute weekly returns but starting from the end date backwards. This is my initial attempt to implement it using pandas:</p> <pre><code>import pandas as pd import numpy as np from pandas.tseries.offsets import BDay index = pd.date_range(start='2020-09-13', end='2020-10-13', freq=BDay()) index_len =...
<p>So what you're looking for are <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#anchored-offsets" rel="nofollow noreferrer">anchored offsets</a>, i.e. resampling the DataFrame on a weekly basis, starting on <em>the same weekday</em> that your last index is on. In your case, <code>2020...
python|pandas|pandas-resample
1
1,597
64,980,681
How to list the index and columns names together for a given dataframe?
<p>How to list the column names along with their index from a data frame in python ?</p> <p>the below code gives only the index numbers of the column names. But i need to learn on how to list the index numbers along with the column names for a large dataset with multiple columns names.</p> <pre><code>enter code here: ...
<p>You can create a <code>map</code> like this:</p> <pre><code>In [3359]: col_map = {df.columns.get_loc(c):c for c in df.columns} In [3360]: col_map Out[3360]: {0: 'id', 1: 'count', 2: 'colors'} </code></pre>
python|python-3.x|pandas|dataframe|indexing
2
1,598
39,819,323
How to do logical operation between DataFrame and Series?
<p>Suppose I have a bool <code>DataFrame df</code> and a bool <code>Series x</code> with the same index, and I want to do logical operation between <code>df</code> and <code>x</code> per column. Is there any short and fast way like <code>DataFrame.sub</code> compare to using <code>DataFrame.apply</code>?</p> <pre><cod...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mul.html" rel="noreferrer"><code>mul</code></a>, but need cast to <code>int</code> and then to <code>bool</code>, because <code>UserWarning</code>:</p> <pre><code>print (df.astype(int).mul(x.values, axis=0).astype(bool)) x ...
python|pandas|dataframe|boolean|logical-operators
7
1,599
39,622,059
Slice numpy array to make it desired shaped
<p>Surprisingly, couldn't find the answer across the internet. I have an n-dimensional numpy array. E.g.: 2-D np array:</p> <pre><code>array([['34.5500000', '36.9000000', '37.3200000', '37.6700000'], ['41.7900000', '44.8000000', '48.2600000', '46.1800000'], ['36.1200000', '37.1500000', '39.3100000', '38....
<p>This is not a 2d array. It is a 1d array, whose elements are objects, in this case some 4 element lists and one 5 element one. And this lists contain strings.</p> <pre><code>In [577]: np.array([['34.5500000', '36.9000000', '37.3200000', '37.6700000'], ...: ['41.7900000', '44.8000000', '48.2600000', '4...
python|arrays|numpy
1