Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
360,500
42,331,848
How to display dataframes?
<p>I am doing the Titanic problem in Kaggle and I have problems displaying the dataframe:</p> <pre><code>import pandas as pd import numpy as np titanic = pd.read_csv("input/train.csv") titanic.head() </code></pre> <p>This should display the <code>train.csv</code> but it doesn't. Do you know why?</p>
<p>Whether you are using the REPL in Sublime Text or just running the program, you can display a dataframe called <em>titanic</em> as:</p> <pre><code># prints first 5 rows in dataframe format print(titanic.head()) # prints all rows in dataframe format print(titanic) </code></pre> <p>If you want to display the data f...
python|pandas|numpy|dataframe|kaggle
1
360,501
42,523,086
Grouping Equal Elements In An Array
<p>I’m writing a program in python, which needs to sort through four columns of data in a text file, and return the four numbers the row with largest number in the third column for each set of identical numbers in the first column. </p> <p>For example:</p> <p>I need: </p> <pre><code>1.0 19.3 15.5 0.1 1.0 ...
<p>An approach could be to use a dict where the value is the row keyed by the first column item. This way you won't have to load the whole text file in memory at once. You can scan line by line and update the dict as you go.</p>
python|algorithm|numpy|grouping|slice
0
360,502
42,568,800
Finding the largest element in a array based on another array and delete it (python 3.x)
<p>I am using python-3.x I have two arrays, and I want to delete two rows that in (x) and (e) based on the largest two numbers in the (e) list:</p> <pre><code> index 0 x=[0 0 0 1 0] e=[ [12] 1 [1 1 1 1 0] [6 ] 2 [0 0 1 0 0] delete this row [20] --&gt; the 1st large...
<p>You can use <code>argpartition</code> in this way, firstly negate the <code>e</code> array, so that the largest values' index will be partitioned at the head of the result, after the partition, remove the first two indices and sort the remaining indices:</p> <pre><code>x[np.sort((-e.ravel()).argpartition(2)[2:]),:]...
python|arrays|python-3.x|numpy
1
360,503
42,497,340
How to convert one-hot encodings into integers?
<p>I have a numpy array data set with shape (100,10). Each row is a one-hot encoding. I want to transfer it into a nd-array with shape (100,) such that I transferred each vector row into a integer that denote the index of the nonzero index. Is there a quick way of doing this using numpy or tensorflow?</p>
<p>You can use <a href="https://web.archive.org/web/20170227233359/https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html" rel="noreferrer">numpy.argmax</a> or <a href="https://web.archive.org/web/20170227233407/https://www.tensorflow.org/api_docs/python/tf/argmax" rel="noreferrer">tf.argmax</a>. Exam...
python|numpy|tensorflow
46
360,504
42,466,639
Convert a dictionary to a pandas dataframe
<p>I'm trying to convert a dictionary that only has 1 record to a pandas dataframe. I've used the following code from other solutions:</p> <pre><code>d = {'id': 'CS2_056', 'cost': 2, 'name': 'Tap'} pd.DataFrame(d.items(), columns=['id', 'cost','name']) </code></pre> <p>But I get the following error:</p> <pre><code...
<p>You dict has only one record use list:</p> <pre><code>import pandas as pd d = {'id': 'CS2_056', 'cost': 2, 'name': 'Tap'} df = pd.DataFrame([d], columns=d.keys()) print df </code></pre> <p>Output:</p> <pre><code> id cost name 0 CS2_056 2 Tap </code></pre>
python|pandas|dictionary|dataframe
53
360,505
42,267,128
Extract multiple patterns from a text file and save it to a panda dataframe [python]
<p>my Text file looks like this</p> <pre><code>Description: Text 1 follows &lt;br/&gt; blah blah blah Cause: Cause Text 1 follows here &lt;br/&gt;Description: Text 2 follows &lt;br/&gt; blah blah blah Cause: Cause Text 2 follows here&lt;br/&gt;Description: Text 3 follows &lt;br/&gt; blah blah blah Description: Text...
<p>Here's what I came up with.</p> <pre><code>r"Description:(.*?)&lt;br/&gt;(?:(?!Cause)(?!Description).)*(?:Cause:(.*?)&lt;br/&gt;)?" </code></pre> <p>If you use this regex, which matches both a <code>Description</code> <em>and</em> an optional <code>Cause</code>, it will ensure the pairings of descriptions and caus...
python|regex|pandas
0
360,506
42,354,675
Where does Bazel store TenserFlow build?
<p>I'm trying to build TensorFlow from sources following this guide: <a href="https://www.tensorflow.org/install/install_sources" rel="nofollow noreferrer">Installing TensorFlow from Sources</a>. The build seems to have worked fine, but then there's the last step:</p> <blockquote> <p>Invoke pip install to install th...
<p>It sounds like you may have skipped a step. Bazel does not create this file. The program that Bazel builds does.</p> <p>The prior step on <a href="https://www.tensorflow.org/install/install_sources" rel="nofollow noreferrer">https://www.tensorflow.org/install/install_sources</a> to the one that you mention is to ru...
macos|tensorflow|bazel
3
360,507
42,234,672
python: efficient way to make large-scale check
<p>I have an array <code>test</code> with many lines, and each line has 3 numbers. I need to get <code>True</code> for each line where all 3 numbers are positive, and <code>False</code> otherwise. Currently I use</p> <pre><code>check = np.all((test[:] &gt; 0), axis=1) </code></pre> <p><code>test</code> looks like thi...
<p>Use <code>numexpr</code>:</p> <pre><code>import numexpr as ne t0, t1, t2 = test[:,0], test[:,1], test[:,2] check = ne.evaluate('(t0 &gt; 0) &amp; (t1 &gt; 0) &amp; (t2 &gt; 0)') </code></pre>
python|numpy
4
360,508
42,539,872
How to keep a dictionary of dictionaries (or something with similar functionality) in pandas?
<p>So I have a large dataframe with many columns. Let us say the two main columns I am interested are messages and names. Each message will be something like a personal status and will be accompanied by the person's name. Let's say I have a word bank of emotion/feeling words which is fairly huge but a condensed version...
<p>If you are looking for a very <em>easy</em> way of accomplishing what you are looking for, I would suggest using the pandas <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow noreferrer">groupby</a> functionality in combination with the <a href="https://docs.python.org/2/library/collect...
python|pandas|dictionary|dataframe
3
360,509
42,413,209
Is it possible to load large data directly into numpy int8 array using h5py?
<p>I have a very large data file (1000 by 1400000 array) that contains integers of 0, 1, 2 and 4. It takes a very long time to load this big data into a numpy array using h5py because my memory(4GB) cannot hold that much and the program uses the swap space. Since there are only 4 numbers in the data, I want to use a 8 ...
<p>From the dataset docs page</p> <pre><code> astype(dtype) Return a context manager allowing you to read data as a particular type. Conversion is handled by HDF5 directly, on the fly: &gt;&gt;&gt; dset = f.create_dataset("bigint", (1000,), dtype='int64') &gt;&gt;&gt; with dset.astype('int16'): out = dset...
python|arrays|numpy|h5py
2
360,510
42,151,460
pandas DataFrame - calculate average for a column for each unique index without hardcoding each index label?
<p>Really liking pandas so far, here is something I can't solve though! </p> <p>I'm showing a simplified dataframe here for some flight data. Carriers are the carriers like Am. Air. and Uni. Air. </p> <pre><code>print (df) Carrier | Num_Passengers AA 40 AA 35 AA 64 UA 40 UA 25 UA ...
<p>You are looking to groupby your index and then get the mean number of passengers.</p> <pre><code>df.groupby(level=0).mean() Num_Passengers Carrier AA 46.333333 UA 40.333333 </code></pre>
python|pandas
2
360,511
42,142,913
Tensorflow not using GPU for one dataset, where it does for a very similar dataset
<p>I'm using TensorFlow to train a model using data originating from two sources. For both sources the training and validation data shape are almost identical and the dtypes throughout are np.float32.</p> <p>The strange thing is, when I use the first data set the GPU on my machine is used, but when using the second da...
<p>The cause of the slowness was the memory layout of the ndarray backing the DataFrame. The s2 data was column-major meaning that each row of features and target was not contiguous.</p> <p>This operation changes the memory layout:</p> <pre><code>s2_train_data = s2_train_data.values.copy(order='C') </code></pre> <p>...
tensorflow|gpu
1
360,512
42,471,523
How can I generate a proper MNIST image?
<p>Hey guys so I've been working on a tensorflow project and I want to take a took at the test images from the MNIST database. Below is the gist of my code for converting the original data(ubyte?) into 2d numpy:</p> <pre><code>from PIL import Image from tensorflow.examples.tutorials.mnist import input_data mnist = inp...
<p>Multiply the data by 255 and convert to np.uint8 <a href="http://pillow.readthedocs.io/en/3.4.x/handbook/concepts.html" rel="nofollow noreferrer">(uint8 for mode 'L')</a> have it work.</p> <pre><code>def gen_image(arr): two_d = (np.reshape(arr, (28, 28)) * 255).astype(np.uint8) img = Image.fromarray(two_d, ...
python|numpy|tensorflow|mnist
2
360,513
42,235,155
Matrix inverse in numpy/python not giving correct matrix?
<p>I have a nxn matrix <code>C</code> and use <code>inv</code> from <code>numpy.linalg</code> to take the inverse to get <code>Cinverse</code>. My <code>C</code>matrix has elements of order <code>10**4</code> but my <code>Cinverse</code> matrix has elements of order <code>10**12</code> and higher (not sure if thats cor...
<p>The outer product of two vectors (be they the same or not) is <em>not</em> invertible. Since it is just a stack of scaled copies of the same vector its rank is one. Rank defective matrices <a href="https://en.wikipedia.org/wiki/Rank_(linear_algebra)#Properties" rel="nofollow noreferrer">cannot be inverted</a>.</p> ...
python|numpy|matrix|linear-algebra|matrix-inverse
1
360,514
42,457,193
How to reshape a big array (Memory Error)
<p>I have a very big 6D array as <code>(225, 97, 225, 32, 32, 32)</code>. I want to reshape it into 4D array like <code>(225*97*225, 32, 32, 32)</code>. I tried to used python 2.7 in ubuntu 14.04 with bellow code but I got the memory error. How could I solve it? Thanks</p> <pre><code>import numpy as np #input_6D shap...
<p>The strided expression works with <code>xstep,ystep,zstep=1,1,1</code>. </p> <p>if input is <code>np.zeros((256,128,256),np.int8)</code> with strides <code>(32768, 256, 1)</code>, the output will have the given shape and strides <code>(32768, 256, 1, 32768, 256, 1)</code>.</p> <p>I calculate that the strides for ...
python|python-2.7|numpy
0
360,515
69,937,584
Pandas.read_html() How to avoid putting rows with <th> elements into the header?
<p>I have a HTML table.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt; header 1 &lt;/th&gt; &lt;th&gt;...
<p>You can simply use <code>numpy</code> <code>vstack</code></p> <pre><code>df = pd.DataFrame(np.vstack([df.columns, df])) </code></pre>
python|pandas
0
360,516
69,876,688
Loading a HuggingFace model into AllenNLP gives different predictions
<p>I have a custom classification model trained using <code>transformers</code> library based on a BERT model. The model classifies text into 7 different categories. It is persisted in a directory using:</p> <pre class="lang-py prettyprint-override"><code>trainer.save_model(model_name) tokenizer.save_pretrained(model_n...
<p>As discussed on GitHub: The problem is that you are constructing a 7-way classifier on top of BERT. Even though the BERT model will be identical, the 7-way classifier on top of it is randomly initialized every time.</p> <p>BERT itself does not come with a classifier. That has to be fine-tuned for your data.</p>
python|pytorch|huggingface-transformers|allennlp
1
360,517
69,962,843
Python numpy : Sum an array selectively given information from a second array
<p>Let's say I have a N-dimensionnal array, for example:</p> <pre><code>A = [ [ 1, 2] , [6, 10] ] </code></pre> <p>and another array B that defines an index associated with each value of A</p> <pre><code>B = [[0, 1], [1, 0]] </code></pre> <p>And I want to obtain a 1D list or array that for each index contains the s...
<p>I think I found the best answer for now actually.</p> <p>I can just use:</p> <pre><code>np.histogram(B, weights = A) </code></pre> <p>This code provides the solution I want.</p>
python|arrays|numpy
0
360,518
69,720,964
filter out a dictionary within NOT isin
<p>I read a dataframe into a dictionary. Earlier, I was filtering out all the rows which are <code>.isin(['I1','I2','I3','I4'])</code>. This worked correctly</p> <pre><code>df = {} df['cgo_eafapo_t'] = pd.read_sql_table('cgo_eafapo_t', engine, schema_z2, columns = cols) df['cgo_eafap...
<p>Use <code>~</code> before condition:</p> <pre><code>df['cgo_eafapo_t'] = df['cgo_eafapo_t'][~df['cgo_eafapo_t']['art_kennz'].isin(['I1','I2','I3','I4'])] </code></pre> <p>Better is select by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>...
python|pandas|dataframe|numpy|dictionary
0
360,519
69,785,637
Bicubic block in Keras model
<p>While working with the code of <a href="https://github.com/deepak112/Keras-SRGAN/blob/master/Network.py" rel="nofollow noreferrer">SRGAN</a>, I wanted to replace <code>UpSampling2D</code> by <code>tf.image.resize_bicubic</code>. I used keras lambda layer for this function, as below</p> <pre><code>def bicubic_lambda(...
<p>here is a one liner solution.</p> <pre><code>model = Lambda(lambda image: tf.image.resize_images(image, (image.shape[1]*2, image.shape[2]*2), method = tf.image.ResizeMethod.BICUBIC))(model) </code></pre>
tensorflow|keras
0
360,520
69,968,835
How can i print a specific value in matrix in python? (Using numpy)
<p>I got this code which prints a zero matrix given the size (m x n). But i wanna extract a specific value in a specific location of that matrix but i've tried everything i know and it's still not working. Here's my code:</p> <pre><code>import numpy as np class Matrix: def __init__(self, m, n): self.row = m self...
<pre><code>import numpy as np class Matrix: def __init__(self, m, n): self.row = m self.column = n def define_matrix(self): return np.zeros((self.row, self.column), dtype=int) def __str__(self): return self.define_matrix() def get(self, a, b): try: if not a in range(self.row+1): print('El valo...
python|numpy|matrix
2
360,521
69,920,078
What does "save_graph" keyword in WandbCallback mean?
<p>I'm using Weights and Biases to track my deep learning models. To monitor everything I use the <code>WandbCallback</code> in <code>.fit</code>. In the <a href="https://docs.wandb.ai/ref/python/integrations/keras/wandbcallback" rel="nofollow noreferrer">WandbCallback documentation</a> there is the keyword <code>save_...
<p>That is used to create log a <a href="https://docs.wandb.ai/ref/python/data-types/graph" rel="nofollow noreferrer">wandb.Graph</a> of the model. This class is typically used for saving and diplaying neural net models. It represents the graph as an array of nodes and edges. The nodes can have labels that can be visua...
tensorflow2.0|tf.keras|wandb
1
360,522
69,688,196
Keras/Tensorflow network inference performance
<p>I am using a Keras network which I am calling <code>predict()</code> many times on a single input. A rough calculation based on the layers gives ~3Mops. Running on my CPU should give ~1000 inferences per second, however in a test run which had 400 predicts it took 12 seconds =&gt; ~30 inferences per second. It only ...
<p>It can be also done by using a different toolkit for the inference e.g. <a href="https://docs.openvino.ai/latest/openvino_docs_install_guides_overview.html" rel="nofollow noreferrer">OpenVINO</a>. OpenVINO is optimized for Intel hardware but it should work with any CPU. It optimizes your model by converting to Inter...
tensorflow|keras
1
360,523
69,964,138
Getting the latest record available from a DataFrame
<p>Currently I have a DataFrame as below:</p> <pre><code>import pandas as pd import numpy as np d = {'name': ['a', 'a','a','b','b','b','c','c','c'], 'Year': ['2000', '2010', '2020', '2000', '2010', '2020', '2000', '2010', '2020'], 'v1': [np.NaN, np.NaN, np.NaN, 41, 51, 61, 71, 81, 91], 'v2': [12, 22, 32...
<p>Simply use <code>groupby</code>+<code>last</code> and <code>as_index=False</code> as parameter for <code>groupby</code>:</p> <pre><code>df.groupby('name', as_index=False).last() </code></pre> <p>Alternatively, if you know that the last year is <code>&quot;2020&quot;</code>:</p> <pre><code>df.query('Year == &quot;202...
python|pandas|dataframe
3
360,524
69,769,999
StandardScaler in Python
<p>I want to standardize 'x_train'.</p> <p>The first 'x_train' in the picture is the original data set, and the next 'x_train' below the previous one is standardized.</p> <p>I just want to standardize the first six columns, so I wrote x_train[:,0:6] during standardization.</p> <p>However, the result of standardization ...
<p>Try -</p> <pre><code>scaler = preprocessing.StandardScaler().fit(x_train.iloc[:, 0:6]) #returning the scaled values to a new variable X_train_first_six = scaler.transform(x_train.iloc[:, 0:6]) X_test_first_six = scaler.transform(x_test.iloc[:, 0:6]) </code></pre> <p>ref. <a href="https://pandas.pydata.org/docs/refe...
python|arrays|pandas|machine-learning|standardized
0
360,525
69,951,249
How can I use minibatches with a non-variational GPR in gpflow?
<p>I have tried to adapt the instructions in <a href="https://gpflow.readthedocs.io/en/master/notebooks/advanced/gps_for_big_data.html?highlight=minibatch#Minibatches-speed-up-computation" rel="nofollow noreferrer">this documentation</a> to use minibatches for a training a GPR model, but nothing I have tried works. I c...
<p>You can construct the <code>data</code> tuple to be two <code>tf.Variable</code> objects (if you want to be able to have different-length minibatches, you can pass a <code>shape=None</code> or <code>shape=(None, dim)</code> argument). Something like</p> <pre class="lang-py prettyprint-override"><code>X = tf.Variable...
tensorflow|gpflow|gaussian-process|mini-batch
0
360,526
69,885,909
Python chat bot is not recognizing when I increase the content of the intents file
<p>The python bot code:</p> <pre><code>import nltk nltk.download('punkt') from nltk.stem.lancaster import LancasterStemmer stemmer=LancasterStemmer() import numpy import tflearn import tensorflow import random import json import pickle with open(&quot;intents.json&quot;) as file: data=json.load(file) print...
<p>I realized that actually, the code works correctly, but it is necessary to pay attention to if the content of the intent file changes, it is necessary to delete the &quot;.pickle&quot; file and run the code again.</p>
python-3.x|tensorflow|nltk|chatbot|tflearn
0
360,527
69,963,949
How can I fill a column with values that are computed between two dates in pandas?
<p>I have this dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Position</th> <th>TrainerID</th> <th>Win%</th> </tr> </thead> <tbody> <tr> <td>2017-09-03</td> <td>4</td> <td>1788</td> <td>0 (0 wins, 1 race)</td> </tr> <tr> <td>2017-09-16</td> <td>5</td> <td>1788</td>...
<p>Create a indicator column to represent the win, then group the indicator column by <code>TrainerID</code> and apply the <code>rolling</code> <code>mean</code> to calculate the winning percentage, finally <code>merge</code> the calculated percentage column with the original dataframe</p> <pre><code># Create indicator...
python|pandas|dataframe
3
360,528
69,858,921
`tf.svd` fails during GradientTape
<p>I'm trying to contract a network with multiple tensors and using singular value decomposition during contraction to simplify the contraction process. Whilst this works perfectly when I'm not taking any gradient, it fails once gradient tape starts to watch the tensors (I'm not sure why this is related). Below I wrote...
<p>I found a temporary solution that does not include all the aspects of the previous <code>svd</code> function but it works. TensorFlow requires object shapes to be set after slicing or manipulation (this might not be for every case but specific to mine). Thus I modified the <code>svd</code> function accordingly;</p> ...
python|tensorflow|gradient|gradient-descent|svd
0
360,529
69,964,939
Split string in columns in Python
<p>I have a list like this:</p> <pre><code>[[{'contributionScore': 0.841473400592804, 'variable': 'series_2'}, {'contributionScore': 0.6113986968994141, 'variable': 'series_3'}, {'contributionScore': 0.5985525250434875, 'variable': 'series_1'}, {'contributionScore': 0.5641148686408997, 'variable': 'series_4'}, ...
<p>I am a bit confused with the statement</p> <blockquote> <p>How can I obtain a dataframe with a column for each series?</p> </blockquote> <p>if you meant a single column, for all the series data with column &quot;variable&quot; then Celius Stingher's answer should be good enough.</p> <p>If you meant as in each series...
python|pandas|list|dataframe|split
1
360,530
70,001,353
Building a quick GRU model for stock prediction
<p>I am beginner in <code>RNNs</code> and would like to build a running model gated recurrent unit <code>GRU</code> for stock prediction.</p> <p>I have a numpy array for the training data with this shape:</p> <pre><code>train_x.shape (1122,20,320) </code></pre> <blockquote> <pre><code>`1122` represents the total amount...
<p>So if you have 1122 data samples and each sample has 20 time steps and each time step has 320 features and you want to teach your model to make a binary decision between buying and selling, try something like this:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf tf.random.set_seed(1) mod...
python|tensorflow|keras|recurrent-neural-network|gated-recurrent-unit
1
360,531
69,927,457
How to perform outer subtraction along an axis in numpy
<p>I used to perform an outer subtraction on two one-dimensional arrays as follows to receive a single two-dimensional arrays that contains all pairs of subtractions:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np a = np.arange(5) b = np.arange(3) result = np.subtract.outer(a, b) assert result....
<p>You can expand/reshape <code>A</code> to (5, 1, 2) and <code>B</code> to (1, 3, 2) and let the broadcasting do the job:</p> <pre><code>A[:, None, :] - B[None, :, :] </code></pre>
python|python-3.x|numpy
3
360,532
69,976,624
RuntimeWarning: overflow encountered in reduce return
<p>I am testing this code using real data or a generated dataset from sklearn. In both cases, the code works without errors if the number of factors in the model is less than 6. With 7 factors, I get an error:</p> <pre><code>RuntimeWarning: overflow encountered in square return np.mean((y_true - y_pred)**2) </code></pr...
<p>I found the problem on my own. The code itself has no errors, but it uses gradient descent for optimization. I set the learning rate =1 and 2000 iterations. This, of course, is too much and retraining was taking place. The gradient continued to grow uncontrollably and I was getting huge values. The best solution is ...
python|numpy
0
360,533
69,666,955
Reducing the dimensions of a tensor in tensorflow
<p>I have a tensor with the following shape:</p> <pre><code>&gt; tf.Tensor: shape=(1, 1440) </code></pre> <p>How do I reduce such a shape so that I can get the following:</p> <pre><code>&gt; tf.Tensor: shape=(1440,) </code></pre>
<p>Use <a href="https://www.tensorflow.org/api_docs/python/tf/squeeze" rel="nofollow noreferrer"><code>tf.squeeze</code></a>:</p> <pre><code>import tensorflow as tf tensor = tf.random.uniform((1, 1440)) print(tensor.shape </code></pre> <pre><code>TensorShape([1, 1440]) </code></pre> <p>And now:</p> <pre><code>squeezed...
python|tensorflow
1
360,534
69,775,335
Most efficient way to find polygon-coordinate intersections in large GeoJSON object
<p>I'm working on a project that requires coordinate mappings - determining whether a coordinate point exists in a series of polygons. The number of mappings is quite large - ~10 million coordinates across 100+ million polygons.</p> <p>Before I continue, I've already looked at the questions <a href="https://stackoverfl...
<p>I would use a spatial join.</p> <p>Given this fake data:</p> <p><a href="https://i.stack.imgur.com/snmxH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/snmxH.png" alt="enter image description here" /></a></p> <p>I'd join it with the &quot;within&quot; predicate:</p> <pre class="lang-py prettyprin...
python|python-3.x|computational-geometry|geopandas|shapely
3
360,535
69,927,473
a left join using pandas is populating the data twice for the same row
<p>I am trying to use pandas for a data analysis, used <code>merge</code> for performing a vlookup, the two data sets are as below,</p> <pre><code>data1 = acc_name tier content group gcode acc_ID abc 3 55 b 111 R-DDD def 4 45 c 222 X-TTT xyz ...
<p>Remove duplicates in <code>df2</code> by column for join, here <code>Accountn</code>, so no duplicates in output:</p> <pre><code>final = pd.merge(data1,data2[['Accountn','status']].drop_duplicates('Accountn'), on=['Accountn'], how='left') </code></pre>
python|python-3.x|pandas
1
360,536
69,916,421
How to turn it an element of a list to a string?
<p>I have lists like this in a column of a data frame:</p> <pre><code>list1 = [[Petitioner Jae Lee,his,he],[]] list2 = [[lee],[federal officials]] list3 = [[],[lawyer]] </code></pre> <p>But I want to turn into</p> <pre><code>list1 = ['Petitioner Jae Lee' , 'his','he'] list2 = ['lee' , 'federal officials']] list3 = ['...
<pre><code>list1 = [['Petitioner Jae Lee','his','he'],[]] list2 = [['lee'],['federal officials']] list3 = [[],['lawyer']] flat_list1 = [item for sublist in list1 for item in sublist] flat_list2 = [item for sublist in list2 for item in sublist] flat_list3 = [item for sublist in list3 for item in sublist] print(flat_li...
pandas|list|dataframe|for-loop
0
360,537
69,858,044
How to compare elements of one dataframe to another?
<p>I have a dataframe, called <code>PORResult</code>, of daily temperatures where rows are years and each column is a day (121 rows x 365 columns). I also have an array, called <code>Percentile_90</code>, of a threshold temperature for each day (length=365). For every day for every year in the <code>PORResult</code> da...
<p>(<em>Edited</em>:) Depending on your data structure, I think</p> <pre class="lang-py prettyprint-override"><code>CountResult = PORResult.gt(Percentile_90,axis=0).astype(int) </code></pre> <p>should do the trick. Generally, the toolset provided in <code>pandas</code> is sufficient that <code>for</code>-looping over a...
python|pandas|dataframe|numpy|weather
0
360,538
69,709,776
Python - issue with dimension of sequency
<p>I want to create in Python the following sequence of zero's and one's:</p> <p><code> {0, 1,1,1,1, 0,0, 1,1,1, 0,0,0, 1,1, 0,0,0,0, 1}</code></p> <p>So there is first 1 zero and 4 one's, then 2 zeros and 3 one's, then 3 zeros and 2 ones and finally 4 zeros and 1 one. The final array is supposed to have dimension 20x1...
<p>You can use <code>flatten</code>:</p> <pre><code>import numpy as np l = np.array([[0] * n + [1] * (5 - n) for n in range(1, 5)]).flatten() print(l) # &gt;&gt;&gt; [0 1 1 1 1 0 0 1 1 1 0 0 0 1 1 0 0 0 0 1] </code></pre>
python|numpy|sequence
1
360,539
70,004,390
ValueError: Exception encountered when calling layer "max_pooling2d_26" (type MaxPooling2D)
<p>I have the following code while building a CNN model with Keras. I have added three convolution layers and three pool layers. While compiling the model a value error arises from the pooling layer. I have added the code and error. please help</p> <pre><code>model = Sequential() model.add(Conv2D(filters = 32, kernel_s...
<p>The input to the third MaxPool layer is of size (1,1,64) on which you cannot run a pool of 2x2. You need to check the input dimensions for each layer. Sample:</p> <pre><code>model = Sequential() model.add(Conv2D(filters = 32, kernel_size = (4,4), input_shape = (28,28,1), activation = 'relu')) model.add(MaxPool2D(poo...
tensorflow|keras|valueerror
1
360,540
69,752,833
ImageDataGenerator that outputs patches instead of full image
<p>I have a big dataset that I want to use to train a CNN with Keras (too big to load it in memory). I always train using <code>ImageDataGenerator.flow_from_dataframe</code>, as I have my images across different directories, as shown below.</p> <pre><code>datagen = ImageDataGenerator( rescale=1./255. ) train_gen=da...
<p>You could try using a preprocessing function in your <code>ImageDataGenerator</code> combined with <code>tf.image.extract_patches</code>:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf import matplotlib.pyplot as plt BATCH_SIZE = 32 def get_patches(): def _get_patches(image): ...
python|tensorflow|keras|deep-learning|conv-neural-network
4
360,541
69,740,711
How to create a NumPy array of booleans with k% True values?
<p>I know that we can create a NumPy array of boolean values with the following line of code:</p> <pre><code>np.random.choice(a=[False, True], size=(N,)) </code></pre> <p>But what if I want to specify that I want this random array to have around 60% (or more generally k%) <strong>True</strong> values?</p>
<p>Using <code>np.random.choice</code> can be really slow for large arrays. I recommend doing</p> <pre class="lang-py prettyprint-override"><code>import numpy as np N = 100_000 booleans = np.random.rand(N) &lt; 0.6 </code></pre> <p><code>np.random.rand</code> will produce uniform random numbers between <code>0.0</code>...
python|numpy|random
3
360,542
69,726,577
Python matrix row shifting(Also column)
<p>Is there any way that I can shift specific row in python? (It would be nice if numpy is used). I want</p> <pre><code>[[1,2], [3,4]] </code></pre> <p>to be</p> <pre><code>[[1,2], [4,3]]. </code></pre> <p>Also for the column would be nice!</p> <pre><code>[[1,2], [3,4]] </code></pre> <p>to be</p> <pre><code>[[1,4], [3,...
<p><code>np.roll</code> is your friend.</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; x = np.array([[1,2],[3,4]]) &gt;&gt;&gt; x array([[1, 2], [3, 4]]) &gt;&gt;&gt; x[1] array([3, 4]) &gt;&gt;&gt; np.roll(x[1],1) array([4, 3]) &gt;&gt;&gt; x[1] = np.roll(x[1],1) &gt;&gt;&gt; x array([[1, 2], ...
python|numpy|matrix|shift
1
360,543
69,944,447
How to change the directory of mlflow logs?
<p>I am using MLflow to log the metrics but I want to change the default saving logs directory. So, instead of writing log files besides my main file, I want to store them to <code>/path/outputs/lg </code>. I don't know how to change it. I use it without in the <code>Model</code>.</p> <pre class="lang-py prettyprint-ov...
<p>The solution is:</p> <pre class="lang-py prettyprint-override"><code>mlflow.set_tracking_uri(uri=f'file://{hydra.utils.to_absolute_path(&quot;../output/mlruns&quot;)}') exp = mlflow.get_experiment_by_name(name='Emegency_landing') if not exp: experiment_id = mlflow.create_experiment(name='Emegency_landing', ...
machine-learning|deep-learning|pytorch|mlflow
0
360,544
69,921,886
How to replace value while grouping with specific one?
<p>I have a dataframe:</p> <pre><code>id type val a1 q 100 a1 v 4 a1 l 17 b1 p 1 b1 j 700 b1 s 3 </code></pre> <p>I want to group by id with keeping column type and summing values in column val. Value in column type must be one with highest va...
<p>You can try this:</p> <pre><code>df.sort_values(by='val', ascending=False).groupby('id').agg({'type': 'first', 'val': 'sum'}) </code></pre> <p>It gives:</p> <pre><code> type val id a1 q 121 b1 j 704 </code></pre>
python|python-3.x|pandas|dataframe|group-by
1
360,545
69,884,260
Python: JSON with list of objects to dataframe
<p>I have a JSON example which I would like to flatten into a pandas DataFrame. I already used to apply some methods which I wrote myself, but I wondered if there is a better/shorter solution to this problem.</p> <p><strong>JSON example:</strong></p> <pre class="lang-json prettyprint-override"><code>{ &quot;documentN...
<p>A more straightforward way is to use <code>json_normalize</code> but you lost the information about 'hope':</p> <pre><code>import pandas as pd import json with open(&quot;data.json&quot;) as file: data = json.load(file) out = pd.json_normalize(data, ['data', 'scores'], meta=['documentNa...
python|json|pandas|dataframe
2
360,546
69,886,991
Getting all diagonals from top right to bottom left in array
<p>I am trying to store all the diagonals in the matrix from the top right to the bottom left and store them in an array.</p> <pre class="lang-py prettyprint-override"><code>matrix = array([[2, 0, 0, 2], [3, 0, 0, 3], [3, 0, 0, 2], [0, 0, 0, 0]]) </code></pre> <p><strong>...
<p>If you do not flip the matrix it works. Using:</p> <pre class="lang-py prettyprint-override"><code>def get_diags_lower_left(matrix): return [matrix.diagonal(i) for i in range(-3, 4)][::-1] </code></pre> <p>Will yield:</p> <pre><code>[array([2]), array([0, 3]), array([0, 0, 2]), array([2, 0, 0, 0]), array([3,...
python|arrays|numpy|matrix
2
360,547
69,893,620
break values in pandas column into bins
<p>I have a following DataFrame:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>columns1</th> <th>parametr_1</th> <th>parametr_2</th> <th>parametr_3</th> </tr> </thead> <tbody> <tr> <td>val_1</td> <td>1</td> <td>2</td> <td>1</td> </tr> <tr> <td>val_2</td> <td>1</td> <td>2</td> <td>5</td> <...
<p>First is specified bins for each <code>parameter</code> column by dictioanry and call <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html" rel="nofollow noreferrer"><code>cut</code></a>, then count values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Seri...
python|pandas
2
360,548
69,689,910
Pandas add column on condition: If value of cell is True set value of largest number in Period to true
<p>I have a pandas dataframe with lets say two columns, for example:</p> <pre class="lang-py prettyprint-override"><code> value boolean 0 1 0 1 5 1 2 0 0 3 3 0 4 9 1 5 12 0 6 4 0 7 7 1 8 8 1...
<p>Compute the rolling max of the 'value' column</p> <pre><code>&gt;&gt;&gt; rolling_max_value = df.rolling(window=4, min_periods=1)['value'].max() &gt;&gt;&gt; rolling_max_value 0 1.0 1 5.0 2 5.0 3 5.0 4 9.0 5 12.0 6 12.0 7 12.0 8 12.0 9 8.0 10 17.0 11 17.0 12 1...
python|pandas
-1
360,549
69,753,155
Pandas regex upcase after colon and space
<pre><code>import pandas as pd import re # Source data df = pd.DataFrame( data={'A': ['abc: aaa 123: 111', 'edf: 111', 'ghi: a11 324: aaa', 'jkm: bn2 jsk: 1f4']}) df['A'] = df['A'].re.sub(&quot;(^|[:])\s*([a-zA-Z])&quot;, lambda p: p.group(0).upper(), s) </code></pre> <p>Result:</p> <p>AttributeError: 'Series' objec...
<p>Try this:</p> <pre><code>df['A'] = df.A.str.replace(r':\s+[a-zA-Z]', lambda p: p.group(0).upper()) # output A 0 abc: Aaa 123: 111 1 edf: 111 2 ghi: A11 324: Aaa 3 jkm: Bn2 jsk: 1f4 </code></pre>
python-3.x|pandas|dataframe
0
360,550
69,669,135
How do I create a Pandas Dataframe from a dictionary containing a nested dictionary?
<p>I am working on a project where I am getting JSON data from a GraphQL API. After receiving the data, I am using json.loads() on the data and then accessing parts of the JSON I need, which is then stored in a dictionary containing another dictionary. The dictionary is:</p> <pre><code>{'placement': 1, 'entrant': {'id'...
<p>You need to create proper dictionaries for pandas to create a dataframe. I'm assuming here you have a list of dicts called dictionaries.</p> <pre class="lang-py prettyprint-override"><code>pd.DataFrame( [ {&quot;placement&quot;: d[&quot;placement&quot;], &quot;id&quot;: d[&quot;entrant&quot;][&quot;id&qu...
python|json|pandas|dataframe|dictionary
1
360,551
69,771,753
How do I strip data from a row in Pandas?
<p>I have a Pandas dataframe and I need to strip out components.schema.Person.properties and just call it id.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">column</th> <th>data_type</th> <th>data_description</th> </tr> </thead> <tbody> <tr> <td style="text-align:...
<p>Like this?</p> <pre class="lang-py prettyprint-override"><code>df['column'] = df['column'].apply(lambda x: x.split('.')[-1]) </code></pre> <p>or more compact <a href="https://stackoverflow.com/questions/69771753/how-do-i-strip-data-from-a-row-in-pandas#comment123329869_69771753">solution by @Chris Adams</a>:</p> <pr...
python|pandas
1
360,552
69,997,820
How can I delete a sequence of rows based on a condition?
<p>I have the following dataframe:</p> <pre><code> id outcome 0 3 no 1 3 no 2 3 no 3 3 yes 4 3 no 5 5 no 6 5 no 7 5 yes 8 5 no 9 5 yes 10 6 no 11 6 no 12 6 yes 13 6 no 14 6 no </code></pre> <p>I want to rem...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.cumsum.html" rel="nofollow noreferrer"><code>cumsum</code></a> to mark all 'no' at the ...
python|pandas|dataframe|numpy|time-series
2
360,553
69,890,117
How to free up memory in Lambda due to numpy.core._exceptions._ArrayMemoryError using pandas compare()
<p>When I run this code in a lambda function in which the memory allocation setting is set to max (10240):</p> <pre><code>df_compare = first_less_dupes[compare_columns].compare(second_less_dupes[compare_columns]) </code></pre> <p>I'm seeing this error:</p> <pre><code>Unable to allocate 185. MiB for an array with shape ...
<p><code>del</code> does not properly delete objects, but simple drops the reference tied to the variable name being deleted. You must make sure that every other reference is properly dropped too.</p> <p>Then you might still need to wait for garbage collection to happen. However with <code>pandas</code> and <code>numpy...
python|pandas|amazon-web-services|aws-lambda
1
360,554
69,746,285
How to convert a dictionary with lists to a different kind of dictionary for a column
<p>I have a dataframe like this:</p> <pre><code>import pandas as pd frame={'location': {(2, 'eng', 'US'): {&quot;['sc']&quot;: 3, &quot;['delhi']&quot;: 2, &quot;['sonepat', 'delhi']&quot;: 1, &quot;['new delhi']&quot;: 1}}} df=pd.DataFrame(frame) df.head() </code></pre> <p>Output</p> <pre><code> ...
<p>You could try this:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame( { &quot;location&quot;: { (2, &quot;eng&quot;, &quot;US&quot;): { &quot;['sc']&quot;: 3, &quot;['delhi']&quot;: 2, &quot;['sonepat',...
python|pandas|dataframe|dictionary
2
360,555
69,999,180
Equivalent of NumPy index arrays with standard Python lists or arrays
<p>I can use an array or a list to index into <code>numpy.array</code>, e.g.:</p> <pre><code>a = np.array([1, 2, 3, 4]) print(a[[1, 3]]) </code></pre> <p>will produce</p> <pre><code>[2 4] </code></pre> <p>Is there an equivalent construct to index into a standard Python list or array?</p> <p>Just to be more specific: in...
<pre><code>from operator import itemgetter print(itemgetter(1,3)(a)) </code></pre> <p>and to turn it into a list:</p> <pre><code>print(list(itemgetter(1,3)(a))) </code></pre>
python|arrays|list|numpy|matrix-indexing
1
360,556
69,998,276
How to fix the NumPy .dtype 'NoneType' error
<p>I am running the following Python code in PyCharm debug mode.</p> <pre><code>import numpy as np, pandas as pd, numpy.polynomial.chebyshev as chebyshev from pathlib import Path home = str(Path.home()) directory = '/Downloads' d = pd.read_csv(home+directory+'/data.csv') np.random.seed(0) nData = 4 data = np.random....
<p>You'd need to downgrade to Python 3.9, or wait until this CPython/cython bug is fixed.</p> <p>This is actually a real bug (as of 2022-04-14), and is showing up...:</p> <ul> <li>in cython: <a href="https://github.com/cython/cython/issues/4609" rel="nofollow noreferrer">#4609</a></li> <li>in CPython: <a href="https://...
python-3.x|numpy
5
360,557
70,019,622
Python problem importing pandas dataframe
<p>I have a csv file with this structure:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Path name</th> <th>Path ID</th> <th>Phenotype data</th> </tr> </thead> <tbody> <tr> <td>path name 1</td> <td>ID 1</td> <td>Table 1</td> </tr> <tr> <td>path name 2</td> <td>ID 2</td> <td>Table 2</td> </...
<p>The <code>pheno_data</code> looks like a textual dump of a dataframe into a single cell. Due to the default formatting it has truncated the output, the <code>[</code> does not have a closing <code>]</code> and the last value shows <code>...</code>.</p> <p>Your example is also missing the second half of the last row ...
python|pandas|string|dataframe|csv
0
360,558
69,845,202
why pandas read duplicates in .csv file then rename them?
<p>I am working with python and I read a file and I want to drop duplicates from the same questions but it keeps reading the duplicates with the name.1</p> <p>for example: there is 2 of question1 it reads them question1 and question1.1</p> <p>so when I use .drop_duplicates() it does not do anything, what is the problem...
<p>I think you should consider just specifying which columns <em>you know are duplicates</em> and specifically drop them in. I don't know Pandas, but I imagine you can specify the columns in a row, maybe something like the following to cut out the fourth column (if that's a duplicate):</p> <pre class="lang-py prettypr...
python|pandas|csv|jupyter-notebook|duplicates
0
360,559
43,172,606
Getting weird values on predicting MNIST dataset
<p>I am using TF.LEARN with mnist data. I trained my neural network with 0.96 accuracy but now I am not really sure how to predict a value.</p> <p>Here is my code..</p> <pre><code>#getting mnist data to a zip in the computer. mnist.SOURCE_URL = 'https://web.archive.org/web/20160117040036/http://yann.lecun.com/exdb/mn...
<p>You are getting a 9, which is quite similar to a 4.</p> <p>What <code>model.predict</code> returns is <strong>score</strong> and while the 5-th value in the results array (the 5th value is 4 since it starts with a zero) gets a relatively high score (0.26-second high) - your model gives the last digit (9) the highes...
python|tensorflow|mnist|tflearn
0
360,560
43,266,224
Slicing Output Files
<p>I'm reading in a large file and I want to write a certain portion of it to a new file. </p> <p>The pattern 'CARTESIAN COORDINATES' appears twice in this file and I want to omit everything before the second occurrence in the new file. So far I have:</p> <pre><code>#!/usr/bin/env python import string,sys import nump...
<p>So I'm assuming the <code>101.out</code> file looks something like: </p> <pre><code>not to be written not to be written CARTESIAN COORDINATES not to be written CARTESIAN COORDINATES written written written </code></pre> <p>And you want all the stuff after the second <code>CARTESIAN COORDINATES</code> if I've und...
python|numpy|scientific-computing
1
360,561
43,060,206
what does `control_flow_ops.with_dependencies` mean for tensoflow?
<p>I am reading the code of tensorflow model: <a href="https://github.com/tensorflow/models/blob/master/slim/train_image_classifier.py" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/slim/train_image_classifier.py</a></p> <p>I am very confused with this code part:</p> <pre><code>train_tens...
<p>The function has two arguments <code>control_flow_ops.with_dependencies(dependencies, output_tensor)</code>. The second argument <code>output_tensor</code>, which in your case is <code>total_loss</code> is evaluated only <em>after</em> all operations in <code>dependencies</code> are evaluated. As the name implies, <...
python|tensorflow|computer-vision|deep-learning|conv-neural-network
5
360,562
43,463,111
multi-numpy array from dataframe
<p>I have 5 Pandas DataFrames, its 5 classes of objects in 80,00 images and the coordinates of the objects. Basically, there is more than one class in each image</p> <p>class 1:</p> <pre><code> image_id x y image_0 4835 106 image_0 2609 309 image_0 2891 412 image_0 1823 431 image_...
<p>Create a dictionary of dataframes to pass to <code>pd.concat</code></p> <pre><code>clss = {'class 1': cls1, 'class 2': cls2} catted = pd.concat(clss) g = catted.groupby(['image_id', pd.Grouper(level=0)])[['x', 'y']] g.apply(lambda x: list(zip(*x.values.T))).unstack() </code></pre> <p><a href="https://i.stack.imgu...
python|arrays|pandas|numpy
1
360,563
43,456,244
pandas - fetch series of column values and put them into a cell
<p>I have a dataframe that is multi-indexed by country and by date like so:</p> <p><a href="https://i.stack.imgur.com/xrRHy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xrRHy.png" alt="enter image description here"></a></p> <p>what I need is to create a table that is grouped by country and that ...
<p>Use <code>unstack</code> with <code>stack</code> to capture missing elements of a cartesian product.</p> <pre><code>f = dict( raws=dict(raws='sum', raws_sequence=lambda x: list(x)), cost=dict(cost='sum') ) d1 = df.unstack(fill_value=0).stack().groupby(level='country_name').agg(f) d1.columns = d1.columns.dr...
pandas
1
360,564
43,273,473
Why does convolutional network use every 64 image for training?
<p>I'm looking a code from <a href="https://github.com/tflearn/tflearn/blob/master/examples/images/convnet_mnist.py#L15" rel="nofollow noreferrer">here</a> for Python 3.5 + TensorFlow + TFLearn:</p> <pre><code># -*- coding: utf-8 -*- """ Convolutional Neural Network for MNIST dataset classification task. References:...
<p>It is not only using every 64th image, it is loading batches of 64 image. That is why you see the iter increase by 64 each time, because it has processed 64 images per training step. Take a look at the documentation for the regression layer <a href="http://tflearn.org/layers/estimator/" rel="nofollow noreferrer">htt...
python|python-3.x|tensorflow|tflearn
0
360,565
43,090,069
Pandas/matplotlib plot with date-axis shows correct day/month but wrong weekday/year
<p>I'm loading CSV data using pandas, where one of the columns takes the form of a date in the format '%a %d.%m.%Y' (e.g. 'Mon 06.02.2017'), and then trying to make some plots where the x-axis is labeled according to the date.</p> <p>Something goes wrong during the plotting, because the date labels are wrong; e.g. wha...
<p>Although I couldn't really figure out why it's not working, it seems it has something to do with plotting with pandas vs. solely with matplotlib and maybe the <code>mdates.DateFormatter</code>...</p> <p>When I comment out the formatting lines, it seems to start working:</p> <pre><code># ax1.xaxis.set_minor_locator...
python|pandas|matplotlib
4
360,566
43,270,955
Can some one explain logging device placement in tensorflow tutorial ?
<p><a href="https://www.tensorflow.org/tutorials/using_gpu" rel="nofollow noreferrer">Link for the tf tutorial</a></p> <pre><code># Creates a graph. with tf.device('/cpu:0'): a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='...
<p>That seems like a bug in the documentation, the MatMul operation will be placed on CPU in this case.</p> <p>Indeed, running the code sample does show this:</p> <pre><code>import tensorflow as tf # Creates a graph. with tf.device('/cpu:0'): a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') ...
tensorflow
2
360,567
43,241,728
TFSlim ValueError Can not squeeze dim[1], expected a dimension of 1, got 3 for 'vgg_16/fc8/squeezed' (op: 'Squeeze') with input shapes: [3,3,3,2]
<p>Trying to fine-tune the Tensorflow Slim VGG16 net on a different set of class labels ( 2 ) excluding the fc8. On execution I am getting this error.</p> <h1>Error</h1> <pre><code>logits, _ = vgg.vgg_16(images, num_classes=NUM_CLASSES, is_training=True) /models/slim/nets/vgg.py", line 178, in vgg_16 net = tf.squeeze...
<p>Can you try just defining the batch directly:</p> <pre><code>with tf.Graph().as_default(): tf.logging.set_verbosity(tf.logging.INFO) images = tf.randon_uniform([BATCH_SIZE, 224, 224, 3]) labels = tf.randon_uniform([BATCH_SIZE], max_value=NUM_CLASES) with slim.arg_scope(vgg.vgg_arg_scope()): ...
python|tensorflow
0
360,568
43,270,827
Shifting values in datetimeindex of pandas dataframe
<p>I have a df with a DateTimeIndex of 30 minute intervals over a long period (> 1 year), so >17520 rows. For reasons related to daylight savings, two of the index values are repeated in the index and two values are missing. So the duplicated values are:</p> <pre><code>In[1]: df[df.index.duplicated('first')] Out[2]: ...
<p>I think you need map <code>duplicated index</code> with <code>rename</code> by <code>dict</code>:</p> <pre><code>print (df) a b c timestamp 2013-10-06 01:00:00 1 NaN NaN 2013-10-06 01:30:00 2 NaN NaN 2013-10-06 01:00:00 3 NaN NaN 2013-10-06 01:30:00 4 NaN NaN 2012-1...
pandas|dataframe|datetimeindex
0
360,569
43,247,065
How to combine summary statistics from 100s of *csv files into one *csv with pandas?
<p>I have several hundreds *csv files, which when imported into a pandas data frame look as follows:</p> <pre><code>import pandas as pd df = pd.read_csv("filename1.csv") df column1 column2 column3 column4 0 10 A 1 ID1 1 15 A 1 ID1 2 19 B...
<p>Repeated appending to a pandas <code>DataFrame</code> is highly inefficient as it copies the DataFrame.<br> Instead you could write the max values found to the resultant file directly.</p> <pre><code>files = glob.glob("*.csv") with open("totalfile.csv", "w") as fout: for f in files: df = pd.read_csv(f)...
python|csv|pandas|numpy|dataframe
1
360,570
43,066,064
Tensorflow tuples with different shapes
<p>I have a problem with returning a tuple of two variable <code>v</code> , <code>wt</code> where <code>v</code> has <code>shape=(20,20)</code> and <code>wt</code> has <code>shape=(1,)</code>. <code>wt</code> is a variable that is a weight value. I want to return the tuple (v,wt) inside a <code>map_fn</code></p> <p>m...
<p>You are returning the results of a <code>tf.while</code> loop here. the <code>tf.while</code> loop returns a tuple of multiple values, in your case we can see that your while loop returned a value of interest and a counter value as a tuple.</p> <pre><code>(&lt;tf.Tensor 'map_2/while/while/Exit_1:0' shape=(20,) dtyp...
python|tensorflow|factorization
1
360,571
43,412,007
Numpy: Subtract 2 numpy arrays row wise
<p>I have 2 numpy arrays a and b as below:</p> <pre><code>a = np.random.randint(0,10,(3,2)) Out[124]: array([[0, 2], [6, 8], [0, 4]]) b = np.random.randint(0,10,(2,2)) Out[125]: array([[5, 9], [2, 4]]) </code></pre> <p>I want to subtract each row in b from each row in a and the desired output i...
<p>Just use <code>np.newaxis</code> (which is just an alias for None) to add a singleton dimension to a, and let broadcasting do the rest:</p> <pre><code>In [45]: a[:, np.newaxis] - b Out[45]: array([[[-5, -7], [-2, -2]], [[ 1, -1], [ 4, 4]], [[-5, -5], [-2, 0]]]) </code></pr...
python|numpy
5
360,572
43,234,346
How to rename unnamed columns in Pandas?
<p>I have a pdf with a table in it, and trying to get that table into Pandas. Extracting pdf tables is notoriously difficult to get right, but I have found tabula works best. It is far and away the best I have seen, though still not perfect. I have this pdf table:</p> <p><a href="https://i.stack.imgur.com/WvLxs.png" r...
<p>This is a pure pandas solution - assuming the dataframe is read exactly as pasted below.</p> <pre><code>df.columns = df.columns.str.replace('Unnamed.*', '') + \ df.iloc[0].fillna('') + \ df.iloc[1].fillna('') df.drop([0,1], inplace=True) 1 Asset Type Name ...
python|pandas|dataframe|tabula
3
360,573
43,384,268
Box plot using pandas
<p>Trying to plot a box plot for a pandas dataframe but the x-axis column names don't appear to be clear.</p> <pre><code>import matplotlib.pyplot as plt pd.set_option('display.mpl_style', 'default') fig, ax1 = plt.subplots() %matplotlib inline df.boxplot(column = ['avg_dist','avg_rating_by_driver','avg_rating_of_drive...
<p>I think you need parameter <code>rot</code>:</p> <pre><code>cols = ['avg_dist','avg_rating_by_driver','avg_rating_of_driver', 'avg_surge','surge_pct','trips_in_first_30_days','weekday_pct'] df.boxplot(column=cols, rot=90) </code></pre> <p>Sample:</p> <pre><code>np.random.seed(100) cols = ['avg_dist','avg...
python|pandas|matplotlib|boxplot
2
360,574
43,115,112
how to delete row for a given date index value
<p>I tried below but was not able to delete the row against the given date...</p> <p>I tried the below syntax (line 2 below) but it still does not delete the row for index value = '2016-01-25"</p> <pre><code>norm_data = normalize_data(data, '^NSEI') norm_data.drop(pd.to_datetime('2016-01-25')) print norm_data.head(50...
<p>This: </p> <pre><code>norm_data.drop(pd.to_datetime('2016-01-25')) </code></pre> <p>Returns a copy of norm_data. It does not alter the norm_data df. To change it, you can use:</p> <pre><code># Setting inplace flag to True norm_data.drop(pd.to_datetime('2016-01-25'), inplace=True) </code></pre> <p>Or the less ...
pandas|delete-row
0
360,575
43,170,242
tensorflow modify variables in py_func (and its grad func)
<p>In tensorflow, we can define our own op and its gradient by: <a href="https://gist.github.com/harpone/3453185b41d8d985356cbe5e57d67342" rel="nofollow noreferrer">https://gist.github.com/harpone/3453185b41d8d985356cbe5e57d67342</a></p> <p>However, can we modify any variable in the computational graph in these python...
<p>You can modify the variables in the computational graph in these python functions. Your example code with <code>tmp = var*10</code> will work and does not convert anything to numpy. </p> <p>In fact you should try to avoid converting to numpy as much as possible since it will slow down the computation.</p> <p><stro...
tensorflow
2
360,576
43,045,017
Installing NumPy using Pip on Windows
<p>I downloaded Python 3.6.1 and it came with Pip preinstalled. I wrote this command to install numpy </p> <pre><code>C:\Python36-32&gt;python -m pip install numpy </code></pre> <p>To which I got this as the output: </p> <blockquote> <p>Collecting numpy Could not fetch URL <a href="https://pypi.python.org/...
<p>I solved this problem using the following command: </p> <pre><code>pip install numpy --index-url=http://pypi.python.org/simple/ --trusted-host pypi.python.org </code></pre> <p><a href="https://stackoverflow.com/a/29751768/7529378">This</a> answer helped me figure it out.</p>
python-3.x|numpy|ssl|pip
1
360,577
43,451,249
How does numpy.dot function work?
<pre><code>import numpy as np a = np.array([[1,2],[3,4]]) b = np.array([5, 6]) a.dot(b) b.dot(a) </code></pre> <p>What happens for <em>a.dot(b)</em> and <em>b.dot(a)</em>? For matrix mutiplication, <em>a.dot(b)</em> should be illegal.</p>
<p>In this setup, <code>b.dot(a)</code> is equivalent to <code>b.T.dot(a)</code>; indeed, <code>b</code> and <code>b.T</code> happen to have the same shape, so even though the notation makes it looks like <code>b</code> is a row vector, it really isn't. We can, however, redefine it to behave explicitly as a row vector,...
numpy
3
360,578
43,048,218
Color conditional data on a plot with matplotlib threw a loop
<p>I have a the following dataframe</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt datas = [['RAC1','CD0287',1.52,9.88], ['RAC1','CD0695',2.08,10.05],['RAC1','CD0845',2.01,10.2], ['RAC3','CD0258',1.91,9.8], ['RAC3','CD471',1.66,9.6], ['RAC8','CD0558',1.32,9.3], ['RAC8','CD0968',2.89,10.01]] labels...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> here in conjunction with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.difference.html" rel="nofollow noreferrer"><code>difference...
python|pandas|matplotlib
4
360,579
43,151,403
Using numpy reshape and the "array must be unchanged" error
<p>I am receiving the error:</p> <pre><code>ValueError: total size of new array must be unchanged </code></pre> <p>And I cannot seem to figure out how my array is being changed to throw this error, and pointing to the last line:</p> <pre><code> 1 data = hourlyElectricityForVisualization.values ----&gt; 2 data =...
<p>You have to delete some data points to make it possible to fit into new matrix of size N-to-24*7. You can do the following:</p> <p><code> data = data[:(np.shape(data)[0] - np.shape(data)[0]%(24*7))] data = np.reshape(data, (len(data)/24/7, 24*7)) </code></p> <p>This code will delete last 121 points to make result ...
python|numpy|reshape
1
360,580
43,202,644
how to update tensorflow to 0.9 instead of 1.0?
<p>I want to run code on a Linux server with tensorflow <strong>0.8</strong>,but my code is written in tf <strong>0.9</strong>.I want to update it to 0.9 <strong>instead of 1.0</strong>,but the official site doesn't support version under 1.0.How can I get my ideal version? If I can't,is it different to fix my code to f...
<p>pip install the whl file of your version, for example </p> <pre><code> pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.9.0rc0-cp27-none-linux_x86_64.whl </code></pre>
tensorflow
1
360,581
43,104,309
Is there an equivalent of the python built in function `all` in pandas?
<p>I'm quyering a pandas dataframe <code>df</code> like this.</p> <pre><code>df = df[ (df.value1 &gt;= threshold1) &amp; (df.value2 &gt;= threshold2) &amp; (df.value3.isin(list3)) ] </code></pre> <p>Python has the built in function <a href="https://docs.python.org/3/library/functions.html#all" rel="no...
<p><a href="https://stackoverflow.com/questions/43104309/is-there-an-equivalent-of-the-python-built-in-function-all-in-pandas#comment73290345_43104309">@juanpa.arrivillaga</a> already gave you a very good explanation about boolean indexing in Pandas.</p> <p>I'd like to give you a bit nicer alternative - <a href="http:...
python|pandas|conditional-statements|subset|built-in
4
360,582
72,376,173
Is there a pandas function to give me the ordering positions of a series?
<p>I want a function that would give me the index of an element in a pandas Series object if the Series was sorted. I made the following implementation:</p> <pre><code>def series_ordering(series): positions = series.reset_index(drop=True, inplace=False).sort_values().index return pd.Series(positions, index=seri...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.argsort.html" rel="nofollow noreferrer"><code>argsort</code></a> to get the sorting order:</p> <p>Example:</p> <pre><code>pd.Series([2,3,1,4,0]).argsort() </code></pre> <p>output:</p> <pre><code>0 4 1 2 2 0 3 1 4 3 dtype: int64 </...
python|pandas|sorting
0
360,583
72,157,236
Why is my loss function tending to inifnity, however it is working appropiately when the x and y co-ordinates are swapped
<p>I have a cookie-cutter Linear Regression PyTorch model. To calculate the expected years of experience, dependent on the individuals' salary. A visualisation of the dataset can be viewed below</p> <p><a href="https://i.stack.imgur.com/CFu5R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CFu5R.png...
<p>The issue arose due to the lost function exploding gradient issue since I was using MSEloss and my dataset was using large numbers. the Mean Squared error was initially high, So my iterations on stochastic gradient descent Iterated the loss to a higher value as expected, but these values were too large so when squar...
python-3.x|pytorch|linear-regression|gradient-descent
0
360,584
72,152,650
Built group of two within a dataframe
<p>I would like to create a group of two within a dataframe based on the ID. So basically connect the text inside the second column using a space. Using <code>groupby()</code> will only join the entire text. I would like to set the group size per ID myself. If the group size does not add up, then none should be added f...
<p>Create a sequential counter with <code>cumcount</code> then divide this by <code>2 (desired group size)</code> to create partitions, then group the dataframe by <code>ID</code> along with the partitions and aggregate <code>col2</code> with <code>join</code></p> <pre><code>i = df.groupby('ID').cumcount() // 2 df.grou...
python|pandas|dataframe|pandas-groupby
1
360,585
72,157,607
Null values are not filling
<p>I have a dataset with null values inside the data. The null value is in the gender column. When I try to replace it with mode of that column using the code,</p> <pre><code>name age income gender department grade performance_score 0 Allen Smith 45.0 NaN NaN Operations G3 723 1 S Kumar NaN 16000.0 F ...
<p>Try this,</p> <pre><code>df[&quot;gender&quot;] = df[&quot;gender&quot;].fillna(df[&quot;gender&quot;].mode()[0]) df.head() </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;"></th> <th style="text-align: center;">name</th> <th style="text-align: center;...
python|pandas|dataframe
0
360,586
72,380,691
np.where resulted in length of values does not match
<p>I have used column to filter and create new column</p> <pre><code>df['brought_profit_to_company'] = np.where([(df['product_id'] == '7.99_7free') &amp; (df['trial'] == True)], 0, 5) df.head() </code></pre> <p>But It has resulted in error:</p> <pre><code>/usr/local/lib/python3.7/dist-packages/pandas/core/common.py in...
<p>Remove the [] from the where function, it should be like this instead:</p> <pre><code>df['brought_profit_to_company'] = np.where((df['product_id'] == '7.99_7free') &amp; (df['trial'] == True), 0, 5) </code></pre>
pandas|numpy
0
360,587
72,196,029
Batch plotting in PyTorch using Matplotlib isn't working
<p>I am trying to plot a batch of image (batch size 128) in pytorch using make_grid function in my local machine. But when I call the function its like the calling block never compile. I have waited for long but the asteric sign of compiling never be gone.<a href="https://i.stack.imgur.com/RJldo.jpg" rel="nofollow nore...
<p>Please try adding <code>plt.show()</code> after <code>ax.imshow()</code> (<a href="https://stackoverflow.com/questions/54422714/when-is-plt-show-required-to-show-a-plot-and-when-is-it-not">this answer will be helpful</a>), or replace <code>break</code> to <code>time.sleep(10)</code></p>
matplotlib|pytorch|tensor|image-classification
0
360,588
72,241,521
Python pandas - series to dataframe
<p>.</p> <p>How do I print out only the country names that exist in the dataframe among series with country names as index?</p>
<p>The following will filter for rows with an index value that is also in the index of <code>df2</code> using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isin.html" rel="nofollow noreferrer"><code>.isin()</code></a>.</p> <pre><code>df1.loc[df1.index.isin(df2.index)] </code></pre...
python|pandas|dataframe|series
1
360,589
72,171,808
Unable to assign nn.Module class to self.encoder in another nn.Module class
<p>In the code shown below, I would like to create an <code>Encoder</code> class and then assign it into <code>self.encoder</code> in <code>ComponentEmbedding</code> class. However, when i try to access <code>ComponentEmbedding().encoder</code>, the value is still <code>None</code>. Anyone help?</p> <p>Note: I need to ...
<p>You are initializing <code>encoder</code> as a class attribute with value <code>None</code> whereas it should be an instance attribute:</p> <pre><code>class Encoder(nn.Module): def __init__(self): super().__init__() def forward(self, x): pass class ComponentEmbedding(nn.Module): def...
python|pytorch
0
360,590
72,273,520
Increment numbers in a Pandas column, based on existing highest value
<p>I'm trying to concat two dataframes. dfA has incremental numbers in column 1, dfB does not. Starting from highest value in dfA, I would like to increment the numbers in the rows from dfB when they are concatenated in dfC. So it should be:</p> <p>dfA:</p> <div class="s-table-container"> <table class="s-table"> <th...
<p>You could modify <code>dfB</code> like this -</p> <pre><code>dfB['Column 1'] = pd.Series(list(range(dfA['Column 1'].max(), dfA['Column 1'].max() + len(dfB.index)))) </code></pre> <p>Then you could simply concatenate <code>dfA</code> and the updated version of <code>dfB</code>.</p>
python|pandas
0
360,591
72,220,449
How to devide each raw of data into 3 matrixes in python?
<p>I have data with 1034 columns, I want to divide each raw of it into 3 matrixes of 49*7. It remains 5 columns delete them. How can I do this in python?</p> <p>First, I removed the last 5 columns from the data.</p> <pre><code>rawData = pd.read_csv('../input/smartgrid/data/data.csv')#import the data #remove t...
<p>Here's a way to do what you're asking:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np #rawData = pd.read_csv('../input/smartgrid/data/data.csv')#import the data rawData = pd.DataFrame([[x * 5 + i for x in range(1034)] for i in range(2)], columns=range(1034)) numRowsPerMat...
python|pandas|dataframe|matrix|conv-neural-network
2
360,592
72,297,056
Python pandas update row value from another row
<p>I have a dataframe like the one given below.</p> <pre><code>C1 SIZE M COLOR C1 PRIZE L COLOR C1 COLOR Nan BLUE C2 SIZE L COLOR C2 PRIZE S COLOR C2 COLOR Nan YELLOW </code></pre> <p>I am looking for ways to transform it to the one given below.</p> <pre><code>C1 SIZE M BLUE C1 PRIZE L BLUE C1 COLOR Nan ...
<p>This should work</p> <pre><code>df = pd.DataFrame({'Col1': ['C1', 'C1', 'C1', 'C2', 'C2', 'C2'], 'Col2': ['SIZE', 'PRIZE', 'COLOR', 'SIZE', 'PRIZE', 'COLOR'], 'Col3': ['M', 'L', 'Nan', 'L', 'S', 'Nan'], 'Col4': ['COLOR', 'COLOR', 'BLUE', 'COLOR', 'COLOR', 'YEL...
python|python-3.x|pandas|dataframe
1
360,593
72,463,796
Train multiple connected neural networks with a single optimizer
<p>How can I jointly optimize the parameters of a model comprising two distinct neural networks with a single optimizer? What I've tried is the following, after having initialized an optimizer:</p> <pre><code>optim_global = optim.Adam(zip(model1.parameters(), model2.parameters())) </code></pre> <p>but I get this error<...
<p>These are generator you can control either with the <a href="https://stackoverflow.com/questions/10967819/python-when-can-i-unpack-a-generator">unpacking operator</a> <code>*</code>:</p> <pre><code>&gt;&gt;&gt; optim.Adam([*model1.parameters(), *model2.parameters()]) </code></pre> <p>Or using <a href="https://docs.p...
pytorch
1
360,594
72,401,330
How to convert a Pandas DataFrame into a valid MLserver Predict V2-encoded payload?
<p>I recently found the KServe and MLserver projects which are open source tools for serving ML models. These are great. What's not so great is that these both use a (new to me) and novel formatting for inference inputs, documented here: <a href="https://kserve.github.io/website/modelserving/inference_api/" rel="nofoll...
<p>The V2 Inference Protocol can be thought of as a lower-level spec. It doesn't try to define how to encode higher-level data types (e.g. a Pandas Dataframe) and leaves this to the inference servers themselves.</p> <p>Based on this, MLServer introduces its own conventions which, if followed, ensure that the payload ge...
python|pandas|seldon
1
360,595
72,333,706
How to pull a key from a dict (pandas series) to its own row?
<p>Here is my example data with two fields where the last one [outbreak] is a pandas series.</p> <p>Start: <a href="https://i.stack.imgur.com/nfUOg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nfUOg.png" alt="Start" /></a></p> <p>Goal (Excel mock-up): <a href="https://i.stack.imgur.com/z7PML.png" ...
<p>You can try with <code>ast</code> convert to <code>dict</code> format , then we do conversion</p> <pre><code>import ast out = df.pop('outbreak').map(ast.literal_eval).apply(pd.Series).stack().reset_index(level=1).join(df) out.columns = ['outbreak_id','outbreak_value','report_id'] Out[157]: level_1 ...
python|pandas|dataframe|dictionary|series
2
360,596
72,319,999
Convert combinations of row+column as Column headers
<p>I have a dataframe as follows:</p> <pre><code>Machine Time Part PowerA PowerB 1 20:30 1 0.1 0.4 1 20:30 2 0.9 0.7 1 20:31 1 0.3 0.1 1 20:31 2 0.2 0.3 2 20:30 1 0.2 0.5 2 ...
<p>Let us do <code>pivot_table</code> then <code>swaplevel</code></p> <pre><code>s = df.pivot_table(index= ['Machine','Time'], columns = df.Part.astype(str).radd('Part'), values=['PowerA','PowerB'], fill_value=-1).swaplevel(1,0, axis=1).sort_index(level=0, axis=...
python|pandas|dataframe
2
360,597
72,240,264
Convert date format from a 'yfinance' download
<p>I have a <em>yfinance</em> download that is working fine, but I want the Date column to be in YYYY/MM/DD format when I write to disk.</p> <p>The Date column is the Index, so I first remove the index. Then I have tried using Pandas' &quot;to_datetime&quot; and also &quot;.str.replace&quot; to get the column data to ...
<p>Change the format of the date after resetting the index:</p> <pre><code>df.reset_index(inplace=True) df['Date'] = df['Date'].dt.strftime('%Y/%m/%d') </code></pre> <p>As noted in <em><a href="https://stackoverflow.com/questions/52027033/convert-datetime-to-another-format-without-changing-dtype/52027599#52027599">Con...
python|pandas|dataframe|yfinance
0
360,598
72,236,704
Highlight element based on boolean pandas df
<p>I have 2 data frames with identical indices/columns:</p> <pre><code>df = pd.DataFrame({'A':[5.5, 3, 0, 3, 1], 'B':[2, 1, 0.2, 4, 5], 'C':[3, 1, 3.5, 6, 0]}) df_bool = pd.DataFrame({'A':[0, 1, 0, 0, 1], 'B':[0, 0, 1, 0, 0], ...
<p>You can also use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer">np.where</a> to convert <code>df_bool</code> into a DataFrame of styles based on the locations of <code>1</code> values (<code>df_bool.eq(1)</code>).</p> <p>By setting <code>axis=None</code> to <a h...
python|pandas|dataframe|pandas-styles
1
360,599
72,355,444
Why does pandas.concat() add (), to column name
<p>I am trying to work out why the column names for pandas.concat() are in brackets.</p> <p>There is a similar question <a href="https://stackoverflow.com/questions/60897820/when-using-pd-concat-the-resulting-dataframe-column-names-appear-in-parenthese">here</a> - but in my context I don't understand how this can be ha...
<p>The categories are stored in a list of arrays. When you make them column names, each name becomes a one-element tuple. Change this line:</p> <pre><code>month_df.columns = ohe.categories_ </code></pre> <p>to:</p> <pre><code>month_df.columns = ohe.categories_[0] </code></pre>
pandas|dataframe
2