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,600
44,209,368
How to change a single value in a NumPy array?
<p>I want to change a single element of an array. For example, I have:</p> <pre><code>A = np.array([1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]) </code></pre> <p>I want to relace <code>A[2][1] = 10</code> with <code>A[2][1] = 150</code>. How can I do it?</p>
<p>Is this what you are after? Just index the element and assign a new value.</p> <pre><code>A[2,1]=150 A Out[345]: array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 150, 11, 12], [13, 14, 15, 16]]) </code></pre>
python|numpy
69
1,601
44,032,789
ValueError: could not broadcast input array from shape (28) into shape (28,0) on adding array to another
<p>I'm trying to add a numpy array to another numpy array, but I'm getting this error:</p> <pre><code>ValueError: could not broadcast input array from shape (28) into shape (28,0) </code></pre> <p>This is my code:</p> <pre><code>sample = np.fabs(sample - avg) counter = np.arange(1,len(sample)+1) np.append(sample, co...
<p>This indicates that the array with shape (28,0) is in fact empty, which means you might need to address your upstream processing that generated sample and avg, and verify the contents of these objects. I could replicate this with the following:</p> <pre><code>import numpy as np from numpy import random a = random.r...
python|numpy
0
1,602
69,615,069
Why do we need to define MicroMutableOpResolver or AllOpsResolver for a particular model before calling an MicroInterpreter in tensorflow-lite?
<p>I am currently trying to build a tflite model for a microcontroller. While creating the test file I came across a peice of code where in the test file was using a MicroMutableOpResolver to load model architecture. But I had already included the c dump of the model in my code then why is it using the resolver? Is it ...
<p><strong>MicroMutableOpResolver</strong> loads the subset of operations needed for your model to be interpreted by <strong>MicroInterpreter</strong>. Alternatively <strong>AllOpsResolver</strong> which loads all of the operations available can be used, but it is not recommended due to heavy memory usage.</p> <p>See a...
tensorflow2.0|tensorflow-lite
0
1,603
69,521,547
using a list comprehension to perform cumsum on multiple arrays
<p>I am trying to write a code where it checks for the <code>np.cumsum()</code> of both <code>a</code> and <code>b</code> separated into positive and negative values. so for the first row in the outputs <code>[12, 101, 111]</code> it combines all the values that are over 0 being <code>[12, 12+89, 12+89+10]</code>. The ...
<p>Just use two list comprehensions:</p> <pre><code>[arr[arr &gt; 0].cumsum() for arr in [a, b]] + [arr[arr &lt;= 0].cumsum() for arr in [a, b]] </code></pre> <p>Output:</p> <pre><code>[array([ 12., 101., 111.]), array([12.4, 23.4, 39.4]), array([ -5. , -60. , -65.5]), array([-5. , -9.5])] </code></pre> <p>But I don't ...
python|arrays|numpy|for-loop|multidimensional-array
1
1,604
69,429,866
Pandas Group by with dict values
<p>I have a DataFrame with the following data:</p> <pre><code>size col1 col2 1.5 {'val':1.1, 'id': 10} None 2.0 {'val':1.1, 'id': 11} None 3.0 {'val':1.1, 'id': 20} None 3.0 None {'val':1.1, 'id': 6} </...
<p>Try with <code>groupby</code> with <code>first</code></p> <pre><code>out = df.groupby('size').first()#.reset_index() </code></pre> <p>Update</p> <pre><code>out = df.replace({'None':np.nan}).groupby('size').first()#.reset_index() </code></pre>
python|pandas|dataframe|pandas-groupby
1
1,605
69,397,570
Pandas: How do I normalize a JSON file with multiple nested lists of JSON?
<p>I'm requesting a data from a API and then trying to normalize this JSON file, it has this structure</p> <pre><code>[{'la_id': '33', 'store': '1405fdsa6001209', 'sell': '110aa346', 'products': [{'codigo': '176690', 'lacre': '15980fd2293', 'valor': '49.90'}, {'codigo': 'sd4907', 'lacre': '1598a12385', 'valor'...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>lst = [ { &quot;la_id&quot;: &quot;33&quot;, &quot;store&quot;: &quot;1405fdsa6001209&quot;, &quot;sell&quot;: &quot;110aa346&quot;, &quot;products&quot;: [ {&quot;codigo&quot;: &quot;176690&quot;, &quot;lacre&qu...
python|json|pandas|python-requests|data-science
3
1,606
53,914,426
Reading text file using pandas using python
<p>I am very new to Python. I am trying to read my text file using python Data Science library Pandas. But I get an error of Unicode which I don't understand.If you could help me then it would be very beneficial to me. I am uploading my code here:</p> <pre><code>import pandas as pd text = pd.read_csv("/home/system/Doc...
<p>Because the data inside a space character, CVS perceives this as a different column. As a solution to this, separate the data with a different character. Then make the sep value this character. Example;</p> <h2>test.csv</h2> <pre><code>data1;data2;data3 My dear countrymen;12;test data1 I convey my best wishes to a...
python|pandas
0
1,607
38,065,968
How to convert a column of type Series to datetime weekdays format in python?
<p>I have the following data and python code</p> <pre><code>Time Started Date Submitted Status 10/29/2015 17:34 10/29/2015 17:34 Complete 10/29/2015 17:35 10/29/2015 17:35 Complete 10/29/2015 17:36 10/29/2015 17:37 Complete import pandas as pd from datetime import datetime, timedelta from pandas...
<p>Add parameter <code>parse_dates</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a> for convert to <code>datetime</code>:</p> <pre><code>import pandas as pd import io temp=u"""Time Started,Date Submitted,Status 10/29/2015 17:34,10/...
python|python-2.7|datetime|pandas|datetime-format
1
1,608
38,397,521
TensorFlow - What is random_crop doing in Cifar10 example?
<p>In the Cifar10 example in the TensorFlow examples they are distorting the images with a random combination of cropping, flipping, brightening, contrasting, and whitening. This concept makes sense except the cropping seems a little odd to me. The images will need to be the same dimensions for the network and the crop...
<p>In the example, <code>IMAGE_SIZE</code> is set to <code>24</code>. So basically what this code does is select a randomly chosen offset and extracts a <code>24 X 24</code> patch. It probably ensures that the offset is chosen in a way that the patch can be extracted without any wrap around or other weird boundary cond...
machine-learning|computer-vision|neural-network|tensorflow
2
1,609
66,284,161
How to put elements in specific locations in a np array in one line
<p>I'm writing in Python 3.6, with Numpy 1.20.1. The problem is I have an <code>np.ndarray</code> called <code>A</code> with size <code>(10, 3)</code>, and I have another <code>np.ndarray</code> called <code>B</code> with size <code>(4, 3)</code>. For the 4 arrays of size 3, I would like to put them into 4 specific pos...
<p>Numpy version one liner.</p> <pre><code>A = np.zeros((10, 3)) B = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) idx = [7,3,1,4] A[idx] = B[ np.arange(B.shape[0]) ] # Source from B.shape </code></pre> <p>OR</p> <pre><code>a[idx] =...
python|python-3.x|numpy
1
1,610
66,251,088
Pandas - create mean column based on cell value
<p>I have this concatenated dataframe:</p> <pre><code> team home rank_home team away rank_away 0 team1 70 1 team2 60 1 1 team2 60 2 team1 40 2 </code></pre> <hr /> <p>Now I need to create a 'mean' column ((home+away)/2), but I can'y do it row-w...
<p>Divide the datframe into two using the iloc accessor. Merge them back with the rows aligned. and calc mean</p> <pre><code> g=pd.merge(df.iloc[:,:3],df.iloc[:,3:], how='left', on='team')#From your datframe #g=pd.merge(df.iloc[:,:3],df.iloc[:,3:], how='left', left_on='team', right_on='team.1')# because I copied and pa...
pandas
1
1,611
66,238,869
How to split AFTER underscore in Python
<p>I've seen a lot of threads that say how to split based on an underscore, but how can we split a string where the split is done after the underscore.</p> <p>So let's say I have a pandas dataframe with one column:</p> <pre><code> item 100_5151 101_1205 102_8153 ... </code></pre> <p>how can I achieve the following outp...
<p>You can split with the <code>_</code> as a separator and then add again the <code>_</code> to the id string:</p> <pre><code>id, group =item.split(&quot;_&quot;) id=id+&quot;_&quot; </code></pre>
python|pandas|split
3
1,612
52,463,149
How to convert a column of image urls to numpy arrays in a dataframe?
<p>I am working on <code>Plant Seedlings</code> dataset on Kaggle and I have prepared a dataframe which has 2 columns.</p> <p>The first column has the directory of each image that is present in the train set and the second column has the label(name) of that image.</p> <p>I want to convert it into a dataframe in such ...
<pre><code>from PIL import Image import numpy as np dataset = [] # If you to encode category names you can do the following # df['category_code'] = df['category'].cat.codes # and you can iterate over this in for loop for image_name, category in zip(df['file'],df['category']): image = np.asarray(Image.open(image_n...
python|pandas|image-processing|keras
0
1,613
46,368,602
Error in creating custom activation that reduces the channel size with keras
<p>I created a custom activation function with keras, which reduce the channel size by half (max-feature map activation). </p> <p>Here's what part of the code looks like :</p> <pre><code>import tensorflow as tf import keras from keras.utils.generic_utils import get_custom_objects from keras.models import Sequential f...
<p>So - based on <a href="https://keras.io/layers/core/#activation" rel="nofollow noreferrer">this</a> documentation, you may see that <code>keras</code> engine automatically sets the output shape from a layer to be the same as its input shape. </p> <p>Use <a href="https://keras.io/layers/core/#lambda" rel="nofollow n...
tensorflow|keras|keras-layer|keras-2
1
1,614
58,195,591
padding image array with gray background
<p>I am comparing thumbnail images by showing them side by side using <code>Image.fromarray(np.haystack(&lt;list of image array&gt;).show()</code>. The problem is that the image arrays have different sizes. My solution is to pad the array with a background gray color (200, 200, 200) and make all arrays equal size 200x2...
<p>Answer by Mark Setchell is to use slicing: </p> <pre><code>array_padded[0:height, 0:width, :] = image_array[:] </code></pre> <p>Just have make sure that the shape of image_array is not bigger than array_padded.</p> <pre><code>import numpy as np from PIL import Image image_arrays = [] for pic in pic_selection: ...
python|numpy|python-imaging-library
1
1,615
58,557,631
How to calculate equation using the column values and store output values one below the other using python?
<p>I have a dataset whose column values are to be used in an equation. <code>Max angle</code> is user defined and angular increments <code>Ang</code> will be the angular steps. </p> <p>Suppose Max Angle = 30 , Angular Increment = 10, So I want 4 output rows for each input row. Only the angle must change with 0,10,20,...
<p>There's no need for a <code>for loop</code> with <code>iterrows</code> here, which will be quite slow.</p> <p>Here's a vectorized solution using <code>numpy broadcasting</code>. </p> <p>First we get your dataframe in the correct format with <code>reindex</code> and <code>index.repeat</code>:</p> <pre><code>import...
python|pandas|list|numpy
2
1,616
58,327,404
N_gram frequency python NTLK
<p>I want to write a function that returns the frequency of each element in the n-gram of a given text. Help please. I did this code fo counting frequency of 2-gram</p> <p>code:</p> <pre><code> from nltk import FreqDist from nltk.util import ngrams def compute_freq(): textfile = "please write a function" ...
<p>I don't see an expected output section, hence I assume this is what might need.</p> <pre><code>import nltk def compute_freq(sentence, n_value=2): tokens = nltk.word_tokenize(sentence) ngrams = nltk.ngrams(tokens, n_value) ngram_fdist = nltk.FreqDist(ngrams) return ngram_fdist </code></pre> <p>By ...
python|pandas|nltk|tf-idf|countvectorizer
3
1,617
69,196,432
how to filter with certain condition and apply a function at the same time in pandas
<p>I have a Dataframe like this:</p> <pre><code>text, pred score logits No thank you. positive [[0, 0, 1], [1, 0, 2], , [1, 0, 0]]] [0.01, 0.02, 0.97] They didn't respond me negative [[], [0, 1, 0], [], []] [0.81, 0.10, 0...
<p>One possible solution is to create mapping-dictionaries with various rules (e.g. if positive, sum only first index (<code>0</code>) etc.):</p> <pre class="lang-py prettyprint-override"><code>m_sum = {&quot;positive&quot;: 0, &quot;negative&quot;: 1} m_mul = {&quot;positive&quot;: 2, &quot;negative&quot;: 0} df[&quo...
python|pandas|dataframe
1
1,618
69,143,886
python pandas: duplicated rows using sort_values and drop_duplicates
<p>I have this dataframe <a href="https://i.stack.imgur.com/q0sB8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q0sB8.png" alt="enter image description here" /></a></p> <p>in column <code>stage</code> I have 4 values :</p> <p><a href="https://i.stack.imgur.com/wabv6.png" rel="nofollow noreferrer"><...
<p>Is this something you're looking for?</p> <pre><code>df = pd.DataFrame([{'tweet_id':89324938479283648628, 'name':'Phineas', 'stage': np.nan}, {'tweet_id':8932493847987465848628, 'name':'Tilly', 'stage': np.nan}, {'tweet_id':8932493847987465848628, 'name':'Tilly', 'stage': 'Dogg...
python|pandas|dataframe|nan|drop-duplicates
0
1,619
69,287,751
Numpy slicing array memory consumption
<p>I have a big 2D numpy array with billions of rows and a few hundred columns, and I would like to select about 100 columns using <code>x[:, [0, 1, 3, 5, 11, ...]]</code> I thought it will only create a view of the original numpy array but in fact it is creating a copy of data along the process and blows up machine me...
<p>As the comments above stated, basic indexing only creates a view and thus avoids the additional memory.</p> <p>If you still need the slice to be defined using a list of indices for the columns for ease of access to subparts later on, then I guess that you could create a wrapper class that processes the column slicin...
python|numpy|numpy-ndarray
0
1,620
68,888,375
Import transparent images to GAN
<p>I have Images set which has transparency.</p> <p>I'm trying to train GAN(Generative adversarial networks).</p> <p>How can I preserve transparency. I can see from output images all transparent area is BLACK.</p> <p>How can I avoid doing that ?</p> <p>I think this is called &quot;Alpha Channel&quot;.</p> <p>Anyways Ho...
<p>Using <a href="https://pytorch.org/vision/stable/datasets.html#torchvision.datasets.ImageFolder" rel="nofollow noreferrer"><code>dset.ImageFolder</code></a>, without explicitly defining the function that reads the image (the <code>loader</code>) results with your dataset using the default <code>pil_loader</code>:</p...
python|python-3.x|pytorch|generative-adversarial-network|pytorch-dataloader
2
1,621
69,005,346
How to combine arrays or images of size 128x128 in python
<p>I have 'n' grayscale images/arrays of 128x128 and I want to join them to get array of size 128x128xn. I have tried several approaches but I can get nx128x128. For example</p> <pre><code>a1 = np.random.rand(128,128) a2 = np.random.rand(128,128) b1 = np.random.rand(128,128) b2 = np.random.rand(128,128) c1 = np.random....
<p>I think you want <a href="https://numpy.org/doc/stable/reference/generated/numpy.moveaxis.html" rel="nofollow noreferrer">np.moveaxis</a> to move the second axis to the last:</p> <pre><code>interesting = np.moveaxis(X, 1, -1) </code></pre>
image|multidimensional-array|numpy-ndarray
1
1,622
44,731,230
Converting a "string" to "float"?
<p>I am trying to plot a .txt file of lines of the form:</p> <pre><code>filename.txt date magnitude V098550.txt 362.0 3.34717962317 </code></pre> <p>but I am getting the error "could not convert string to float: V113573.txt". Does anyone know if this is a syntax error with numpy, or how I can resolve my issue...
<p>It's hard to find everything that's wrong in the code, so one needs to start at the beginning. First it seems the datafile has whitespaces as delimiter, so you need to remove <code>delimiter=","</code> as there is no comma in the file. </p> <p>Next, you cannot convert the string <code>V098550.txt</code> from the fi...
python|numpy|matplotlib
1
1,623
71,620,171
Return 4 row of np array where the values are the biggest in column 1
<p>I have the following array <code>MyArray</code> :</p> <pre><code>[['AZ' 0.144] ['RZ' 14.021] ['BH' 1003.487] ['NE' 1191.514] ['FG' 550.991] ['MA' nan]] </code></pre> <p>Where Array dim is :</p> <pre><code>MyArray.shape (6,2) </code></pre> <p>How would I return the 4 Row where values are the biggest ?</p> <p>So ...
<p>You just sort by second column and get last 4 rows:</p> <pre><code>import numpy as np a = np.array( [['AZ', 0.144], ['RZ', 14.021], ['BH', 1003.487], ['NE', 1191.514], ['FG', 550.991], ['MA', np.nan]], ) a = a[~np.isnan(a[:, 1].astype(float))] srt = a[a[:, 1].astype(float).argsort()] pr...
python|numpy
2
1,624
71,467,315
How to select rows based on dynamic column value?
<p>First of all, I have following a following dataframe df_A</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>sector</th> <th>SALES</th> <th>EBIT</th> <th>DPS</th> </tr> </thead> <tbody> <tr> <td>IT</td> <td>xxxx</td> <td>yyyy</td> <td>zzz</td> </tr> <tr> <td>ENERGY</td> <td>xxxx</td> <td>yy...
<p>Create N dataframes, one for each sector, then concatenate them into a single one:</p> <pre><code>out = pd.concat([pd.DataFrame(df_B[df_B['sector'] == sector].to_dict('records')) for sector in df_A['sector'].unique().tolist()], axis=1) print(out) # Output NAME sector SALES EBIT DPS NAME se...
python|pandas|loops|pandas-loc
2
1,625
71,491,360
Create single boxplot from multiple dataframes
<p>I have 3 dataframes (All,Young, Old) and all of them have 2 columns named the same (Participant and Number_of_whole_fixations). Each participant has a unique ID. For instance, IDBY06, IDBO08, IDBY56...(BY=basic young , BO=basic old ). The dataframe &quot;All&quot; has all the participants together (IDBY and IDBO), y...
<p>I would suggest that you add a category to uniquely separate young and old. You could achieve this by creating a new column based on <code>type of participant</code>:</p> <pre><code>df['Age'] = everything[&quot;type of participant&quot;].str[2:4] </code></pre> <p>which should result in a new column containing eithe...
python|pandas|dataframe|jupyter-notebook|seaborn
0
1,626
71,578,454
Multiple overflow warnings when using scipy.integrate.quad
<p>I am trying to implement the following function in Python:</p> <p><a href="https://i.stack.imgur.com/Jbiqa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jbiqa.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/txioi.png" rel="nofollow noreferrer"><img src="h...
<p>The integration variable should be the first argument, the addtional args <code>(n, r)</code> will be passed after it, so your integrand function should be defined as</p> <pre class="lang-py prettyprint-override"><code>def integrand(u, n, r): return norm.pdf(u, 0, 1) * ((norm.cdf(u + r, 0, 1) - ...
python|numpy|scipy
3
1,627
71,459,399
Plotly barchart using groupby
<p>I have a two column dataframe. There are 3 different codes possible</p> <pre><code>index----| Year-----| Code-----| 0 | 2020 | a | 1 | 2020 | b | 2 | 2020 | c | 3 | 2021 | b | 4 | 2021 | b | </code></pre> <p>I want to plot a ba...
<p>You can use a <a href="https://pandas.pydata.org/docs/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>pandas.crosstab</code></a> to get the counts and plot with stacked bars:</p> <pre><code>(pd.crosstab(df['Year'], df['Code']) .plot.bar(stacked=True) ) </code></pre> <p>output:</p> <p><a href="...
python|pandas|plotly|bar-chart
1
1,628
71,502,541
Excel dates formats in pandas
<p>I have a dataframe that looks like this....</p> <pre><code>df2['date1'] = &quot;&quot; df2['date2'] = '=IF(INDIRECT(&quot;A&quot;&amp;ROW())=&quot;&quot;,&quot;&quot;,INDIRECT(&quot;A&quot;&amp;ROW())+30)' df2['date3'] = '=IF(INDIRECT(&quot;A&quot;&amp;ROW())=&quot;&quot;,&quot;&quot;,INDIRECT(&quot;A&quot;&amp;ROW(...
<p>The <code>datetime_format</code> and <code>date_format</code> options to ExcelWriter() don't work because the dataframe columns don't have a datetime-like data type.</p> <p>Instead you can use the xlsxwriter worksheet handle to set the column format.</p> <p>Here is an adjusted version of your code to demonstrate:</p...
python|excel|pandas|date
2
1,629
71,490,460
Edit this code to run through all CSV files in a folder?
<p>I want to preface this with the fact that I am brand new to python and pandas. I created the code below to run through the CSV file and parse out rows based on column value, then create and save into 5 CSVs. The challenge I am facing now is that I have 50 files. I am hoping to find a way that I can use what I have...
<p>Use this as a starting point. It will read each CSV in the <code>csvs</code> list, process it, and write the results to several new files:</p> <pre><code>import pandas as pd import os csv_dir = r&quot;C:\Users\Kris\Data&quot; csvs = [entry.path for entry in os.scandir(csv_dir) if entry.name.lower().endswith('.csv'...
python|pandas|dataframe|csv
1
1,630
42,187,878
Python writing to dictionary times out with large amount of data
<p>I have a piece of working code that reads in a pandas column and writes its unique values to a dictionary and map that value to an integer. </p> <p>The problem is that its too computationally inefficient and always gets killed before it completes. I have 165 such columns and 300,000+ rows per column. </p> <p>exam...
<p>You could split into chunks your huge dataframe into smaller ones, for example this method can do it where you can decide what is the chunk size:</p> <pre><code>def splitDataFrameIntoSmaller(df, chunkSize = 10000): listOfDf = list() numberChunks = len(df) // chunkSize + 1 for i in range(numberChunks): ...
python|pandas|dictionary
0
1,631
42,208,067
Convert tensor of unknown shape to a SparseTensor in tensorflow
<p>I have a tensor of partially unknown shape and a mask -- a tensor of same shape filled with <code>1.0</code> or <code>0.0</code> -- and I want to convert it into a SparseTensor, considering only the items corresponding to <code>1.0</code> in the mask. So, I think I have to go with something like:</p> <pre><code>imp...
<p>In my case type casting the shape as <code>shape=tf.cast(tf.shape(dense), tf.int64)</code> in your first approach resolved the mentioned error.</p>
python|tensorflow|neural-network|deep-learning
0
1,632
42,140,159
how to speed up the computation?
<p>i need to calculate a 1 million*1 million computations to fill a sparse matrix.But when i use loops to fill the matrix line by line,i find it will take 6 minutes to do a just 100*100 computations.So the task won't be solved.Is there some ways to speed up the process?</p> <pre><code>import numpy as np from scipy.spa...
<p>The technique to use here is sparse matrix multiplication. But for that technique you first need a binary matrix mapping source nodes to destination nodes (the node labels will be the indices of the nonzero entries).</p> <pre><code>from scipy.sparse import csr_matrix I = data['source_node'] - 1 J = data['destinati...
python|numpy|scipy|sparse-matrix
0
1,633
69,959,778
Multilayer Perceptron for multiclass classification task
<p>Assuming that I have a MLP that uses ReLU as activation function and <code>CrossEntropyLoss</code> as loss function to classify samples with 3 features that are part of one of 10 classes: How would I implement that? The target values are given as numbers from 0 to 9. When using <code>CrossEntropyLoss</code> the targ...
<p>As mentioned in the comment softmax is not required inside the model as <code>nn.CrossEntropyLoss</code> includes it. Also, calculation of the loss is done before argmax. Note also the shapes of input and outputs to the model. Please refer the following updates.</p> <pre><code>import torch class MLP(torch.nn.Module)...
python|machine-learning|pytorch|multiclass-classification
0
1,634
43,443,937
Tensorflow: CreateSession still waiting for response from worker
<p>When I run on k8s, and my tensorflow code is in the docker container, this log is always showing for some worker:</p> <blockquote> <p>Distrubuted TensorFlow:<br> CreateSession still waiting for response from worker: /job:ps/replica:0/task:0</p> </blockquote> <p>I don't know why. The network in the cluster is o...
<p>Have you tried to pull the docker image on k8s nodes first?</p> <p>So that pulling image will not disturb TF execute order.</p>
tensorflow|containers|distribute
0
1,635
43,311,555
How to drop column according to NAN percentage for dataframe?
<p>For certain columns of <code>df</code>, if 80% of the column is <code>NAN</code>.</p> <p>What's the simplest code to drop such columns?</p>
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isnull.html" rel="noreferrer"><code>isnull</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mean.html" rel="noreferrer"><code>mean</code></a> for threshold and then remove column...
python|pandas|dataframe|nan
56
1,636
50,518,158
Create pandas dataframe from numpy array
<p>To create a pandas dataframe from numpy I can use : </p> <pre><code>columns = ['1','2'] data = np.array([[1,2] , [1,5] , [2,3]]) df_1 = pd.DataFrame(data,columns=columns) df_1 </code></pre> <p>If I instead use : </p> <pre><code>columns = ['1','2'] data = np.array([[1,2,2] , [1,5,3]]) df_1 = pd.DataFrame(data,colu...
<p>You need to transpose your <code>numpy</code> array:</p> <pre><code>df_1 = pd.DataFrame(data.T, columns=columns) </code></pre> <p>To see why this is necessary, consider the shape of your array:</p> <pre><code>print(data.shape) (2, 3) </code></pre> <p>The second number in the shape tuple, or the number of column...
python|arrays|pandas|numpy
7
1,637
50,574,395
Sub totals and grand totals in Python
<p>I was trying to make a sub totals and grand totals for a data. But some where i stuck and couldn't make my deserved output. Could you please assist on this.</p> <pre><code>data.groupby(['Column4', 'Column5'])['Column1'].count() </code></pre> <p>Current Output:</p> <pre><code> Column4 Column5 ...
<p>Just using <code>crosstab</code></p> <pre><code>pd.crosstab(df['Column4'], df['Column5'], margins = True, margins_name = 'Grand Total' ) </code></pre>
python|pandas|jupyter-notebook
1
1,638
50,456,673
Storing multiple dataframes of different widths with Parquet?
<p>Does Parquet support storing various data frames of different widths (numbers of columns) in a single file? E.g. in HDF5 it is possible to store multiple such data frames and access them by key. So far it looks from my <a href="https://arrow.apache.org/docs/python/parquet.html" rel="noreferrer">reading</a> that Parq...
<p>No, this is not possible as Parquet files have a single schema. They normally also don't appear as single files but as multiple files in a directory with all files being the same schema. This enables tools to read these files as if they were one, either fully into local RAM, distributed over multiple nodes or evalua...
python|pandas|apache-spark|parquet
7
1,639
45,523,447
In Pandas how to remove all subrows but keep one which has the highest value in a specific column in a multiIndex dataframe?
<p>So I have a dataframe like this:</p> <pre><code>+---+-----+------------+------------+-------+ | | | something1 | something2 | score | +---+-----+------------+------------+-------+ | 1 | 112 | 1.00 | 10.0 | 15 | | | 116 | 0.76 | -2.00 | 14 | | 8 | 112 | 0.76 | 0.05 | ...
<p>You only need to group by level 0:</p> <pre><code>df.sort_values("score", ascending=False).groupby(level=0).first() # something1 something2 score #1.0 1.00 10.00 15 #8.0 0.76 0.05 55 </code></pre> <p>To keep the second level index, you can reset it to be a column and set it back ...
python|pandas|dataframe|multi-index
2
1,640
45,379,953
How to "zip" several N-D arrays in Numpy?
<p>The conditions are following:</p> <p>1) we have a list of N-D arrays and this list is of unknown length <code>M</code></p> <p>2) dimensions each arrays are equal, but unknown</p> <p>3) each array should be splitted along 0-th dimension and resulting elements should be grouped along 1-st dimension of length <code>...
<p>Seems you need to transpose the array with respect to its 1st and 2nd dimension; You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.swapaxes.html" rel="nofollow noreferrer"><code>swapaxes</code></a> for this:</p> <pre><code>np.asarray(xs).swapaxes(1,0) </code></pre> <p><em>Example</em>...
python|arrays|numpy|interleave
1
1,641
45,344,958
How do you turn a string back into an array?
<p>Firstly is there a way to turn a string into an array?<br> I'm looking for a way to turn this:</p> <pre><code>['[[ 18.41978673]\n', ' [ 0.34748864]\n', ' [ -9.55729142]]'] </code></pre> <p>back into </p> <pre><code>[[ 18.41978673] [ 0.34748864] [ -9.55729142]] </code></pre> <p>Secondly, is there a was to st...
<p>Since you're using a Numpy array, an easy solution to save the array is:</p> <pre><code>np.savetxt(file_name, my_array) </code></pre> <p>then:</p> <pre><code>my_array = np.loadtxt(file_name) </code></pre>
python|arrays|python-3.x|numpy
2
1,642
62,726,477
My columns shift to left when trying to read it with read_csv
<p>I have a dataset with 6 columns. However, when I try to read it with read_csv, the values associated with column indexes shift to the left by 2 columns. Here is an example of the dataset I am using;</p> <pre><code> time alpha abeta e2e rg rg2 0.000000 0.402192 3.661472 0.599572 0.606992 0.636918 1.000000 0.411551 3....
<p>There's a leading space in the title row.</p> <p>Make your data like this</p> <pre><code>time alpha abeta e2e rg rg2 0.000000 0.402192 3.661472 0.599572 0.606992 0.636918 1.000000 0.411551 3.697878 0.580192 0.604391 0.624746 2.000000 0.354966 3.408603 0.704422 0.622932 0.653885 3.000000 0.359647 3.473973 0.681276 0....
python|pandas|dataframe
0
1,643
62,726,363
Keras AttributeError: 'NoneType' object has no attribute 'endswith' in load_model
<p>I am working with a course assignment, where I have to save and load models in keras. My code for creating a model, training it and saving it is</p> <pre class="lang-py prettyprint-override"><code>def get_new_model(input_shape): &quot;&quot;&quot; This function should build a Sequential model according to th...
<p>I got it. There was an error in the file pathname. I spend a lot of time to figure it out. So correct function is</p> <pre class="lang-py prettyprint-override"><code>def get_model_last_epoch(model): &quot;&quot;&quot; This function should create a new instance of the CNN you created earlier, load on the ...
python|tensorflow|keras
2
1,644
62,812,023
ValueError: operands could not be broadcast together with shapes (100,) (99,) error in Python
<p>I am using the bvp solver in Python to solve a 4th order boundary value problem. The actual equations are not being shown to avoid any further complexity. The code that I have written for the same has been attached below.</p> <pre><code>import numpy as np from scipy.integrate import solve_bvp import matplotlib.pyplo...
<p>When I use <code>print(x.shape, y[0].shape)</code> then at some moment both change size to <code>99</code> and I thin you should use <code>x.shape</code> to create your <code>array</code></p> <pre><code> array = np.empty(x.shape,) # array is an 1-D array </code></pre> <p>And this works for me. But I don't know if it...
python|arrays|numpy|scipy|numpy-ndarray
1
1,645
54,637,921
How to modify a pandas dataframe using broadcasting series on a subset of columns
<p>Given the following table:</p> <pre><code> import numpy as np import pandas as pd data = pd.DataFrame(data = np.arange(16).reshape((4, 4)), index = ['Chile', 'Argentina', 'Peru', 'Bolivia'], columns = ['one', 'two', 'three', 'four']) one two three four Chi...
<p>If you want to update data, I think this would do:</p> <pre><code>ser_to_broad = pd.Series([1, 2], index=['one', 'three']) data[ser_to_broad.index] += ser_to_broad print(data) </code></pre> <p><strong>Output</strong></p> <pre><code> one two three four Chile 1 1 4 3 Argentina 5 ...
python|pandas|dataframe|broadcasting
1
1,646
54,566,212
What's the difference between these two ways to calculate the number of occurrences of two words in a text column?
<p>I'm new to pandas, and I'm learning it on Kaggle now.</p> <p>Here is an exercise asking about to <strong>find the number of occurrences of two words</strong> in the <code>description</code> column.</p> <p>I found the first statement from StackOverflow, but the second one is the correct answer. What's the reason for ...
<p>The first one is less because it's only getting the values that <strong>are</strong> <code>'tropical'</code> or <code>'fruity'</code>.</p> <p>So:</p> <pre><code>&gt;&gt;&gt; s='a' &gt;&gt;&gt; s=='a' True </code></pre> <p>But the second one is getting the values that <strong>contain</strong> <code>'tropical'</cod...
python|pandas
1
1,647
73,702,007
Sliding minimum value in a pandas column
<p>I am working with a pandas dataframe where I have the following two columns: &quot;personID&quot; and &quot;points&quot;. I would like to create a third variable (&quot;localMin&quot;) which will store the minimum value of the column &quot;points&quot; at each point in the dataframe as compared with all previous val...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.cummin.html" rel="nofollow noreferrer"><code>groupby.cummin</code></a>:</p> <pre><code>df['localMin'] = df.groupby('personID')['points'].cummin() </code></pre> <p>Example:</p> <pre><code>df = pd.DataFrame({'p...
python|pandas
3
1,648
71,107,072
Why would I want to merge multiple pieces of parquet files into a single parquet file?
<p>Let's say I have a CSV file with several hundreds of million records. Then I want to convert that CSV into a Parquet file using Python and Pandas to read the CSV and write the Parquet file. But because the file is too big to read it into memory and write a single Parquet file, I decided to read the CSV in chunks of ...
<p>In general, it's the <strong>small files problem</strong>; for companies working with big data, file count limits can be an issue if one does not consistently control this problem.</p> <p>It's a problem to be solved as there is <strong>no benefit for read performance</strong> if you split up files to small files (ea...
python|pandas|csv|parquet|pyarrow
0
1,649
71,169,494
Split Text Column Rows if length excess certain number
<p>I have a dataframe that looks like below. I want to split the &quot;text&quot; column rows if the length is more than 5000 (Has more than 5000 characters).</p> <pre><code> doc name text len 0 doc_1 Texas I have a dream.... 6221 1 doc_2 Georgia I love eating.... 1330...
<p>Here you have a possible solution using slicing (meaning, each text longer than 5000 characters will be cut at said length a the remaining text will continue in the next row):</p> <pre><code>df = pd.DataFrame({ &quot;doc&quot;: [&quot;doc_1&quot;, &quot;doc_2&quot;], &quot;name&quot;: [&quot;Texas&quot;, &qu...
python|pandas|dataframe
1
1,650
71,328,419
pandas series get value by index's value
<p>I have a question about Pandas series. I have a series as following:</p> <p><a href="https://i.stack.imgur.com/ah3DV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ah3DV.png" alt="enter image description here" /></a></p> <p>The data type is:</p> <p><a href="https://i.stack.imgur.com/sBDA1.png" re...
<p>if i got it right, then i think: <code>hh_data.loc[[2000000040054]]</code> should be your sulotion</p>
python|pandas|dataframe|indexing
1
1,651
52,382,503
Pandas: cumsum by group across time, resampled to entire dataframe
<p>I have a time series data frame. I'm interested in plotting the cumulative sums across time, by groups of [column1, column2]. So far I can only plot the cumulative sum at the points where the group combination existed. What I want is the cumulative sum for each group at every single timestamp in the original data fr...
<pre><code>values = np.where((df.column1==someVal) &amp; (df.column2==someVal), df.column3, 0).cumsum() plt.plot(df.timestamp, values) </code></pre>
python|pandas|dataframe|cumsum
0
1,652
52,438,006
Python: Get a gene from column B with the highest value, from a group of genes related to each gene in column A
<p>I have a programming problem that I cannot think up a solution to at the moment. I have a table set up as below:</p> <pre><code>GeneA GeneB Value Distance 1 101 0.9 1 102 1 1 103 0.8 2 201 1 2 202 1 3 301 0.9 3 302 0.8 3 303 0.8 ...
<p>My answer was inspired by <a href="https://stackoverflow.com/questions/42267373/python-drop-duplicate-based-on-max-value-of-a-column">this SO question</a>.</p> <p>In your case:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({ 'GeneA': [ '1', '1', '1', '2', '2', '3', '3',...
python|pandas
0
1,653
60,659,821
How can I calculate score of a new image using entrained autoencoder model for anomaly detection in tensorflow?
<p>I am beginner in tensorflow and I am trying to create a simple autoencoder for images to detect anomalies.Firstly, I created a simple autoencoder using dogs images , now I want to use this model to reconstruct my tests images and compare the result using some metrics.So how can I do it on tensorflow (because I am be...
<p>This is simply because of shape mismatch.</p> <p>when you calculate mean squared error,it calculates the element wise error of ground truth values and estimated values. so <code>pred.shape</code> and <code>train_batches.shape</code> should be equal.check the input data shapes and make sure they are equal.</p> <p>s...
python|image|tensorflow|autoencoder|anomaly-detection
0
1,654
60,406,664
looking to convert dictionary to data frame and csv
<p>I have a script that grabs time and price data from an api. I am looking to convert this to a dataframe, a csv, and ultimately the epoch to date time.</p> <p>I have looked around a while and haven't found anything that has worked. a few seemingly unsolved appeared similar in structure. </p> <p>The bottom few lines...
<p>df will fail because df was not assigned a value. Assuming the value of d will be your json output above, change your code to the below to import the json into a df:</p> <pre><code>df = pd.DataFrame(d['candles'], columns=['open', 'high','low','close','volume', 'datetime']) print(df.head(2)) df.to_csv(r'file_locat...
python|pandas
0
1,655
60,568,928
Why is my convolution implementation so slow compared to the Tensorflow's one?
<p>I've implemented the VGG19 net in C++ using SIMD Instructions for <strong>inference</strong> only. I want to optimize the latency of one inference request.</p> <p>Since the VGG19 consists mostly of Convolution Layers, I mainly focused on implementing an efficient Convolution Layer. I followed this paper while doing...
<p>I found the reason for the poor performance. The clang Compiler only used 2 SSE Registers instead all avaiable ones. This led to unnecessary writes and reads to the L1 Cache.</p> <p>I unrolled the two inner loops by hand and the compiler now uses all 16 SSE register avaible. The performance increased drastically.</...
tensorflow|keras|conv-neural-network|simd|convolution
1
1,656
60,610,515
Using a Multinomial Bayes Classifier
<p>I'm new to python and scikit, so please bear with me if this is a stupid question. I've followed some tutorials in order to make a multinomial naive bayes classifier using sklearn, and I've trained and tested it to a decent accuracy. However, I've reached the end of the tutorials, and have realized I don't actually ...
<p>Your issue is using predict_log_proba instead of just predict. What you are seeing is the log of the probability that each sample is 0 or 1, which is helpful if you want to see how "sure" your model is of each label. If you only want to see the labels themselves, use predict. More info <a href="https://scikit-learn....
python|pandas|machine-learning|scikit-learn|classification
0
1,657
72,728,802
Pandas change row/column color background of cells
<p>I wrote a script that freeze the first row that contains the columns names, but I want to make the background with &quot;red&quot;. I tried using style, but it did not work.</p> <p><a href="https://i.stack.imgur.com/sb0I2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sb0I2.png" alt="changing col...
<p>As we discuessed, your use case actually involves the following steps.</p> <ol> <li>Read multiple xlsx files having one sheet</li> <li>Create another xlsx file and write everything from the xlsx files to the different sheets in the new xlsx file.</li> </ol> <p>There are 2 ways in which you can do this</p> <ol> <li>U...
python|css|pandas|pycharm
2
1,658
72,510,809
Is there a way to fill in specific missing rows in a column using rows in another column as a filter
<p>I have a dataset of car attributes with missing values in some columns. In the <code>Distance</code> column for example, there are missing values and I want to replace them with the mean. There is a second column however, <code>Car Type</code> it shows whether the car is brand new or used. A brand new car would not...
<p>Compute the mean for each <code>Car Type</code> and broadcast the values (with <code>transform</code>) to all rows then use <code>fillna</code> to replace NaN by the mean value:</p> <pre><code>df['Distance'] = (df['Distance'].fillna(df.groupby('Car type')['Distance'] .transform('mean'...
python|pandas
2
1,659
72,737,901
How can I concatenate Rolling Regression Results | Python
<p>I'm having trouble creating a data frame to store my regression results. For each ticker, it calculates the coefficient(Beta) and its standard error with its respected window.</p> <p>The new problem that I'm having is that the rows are repeating themselves to calculate each value per column resulting in NaN values. ...
<p>Here is an example using the logic outlined in my comment above. You can see one dataframe (<code>yx_df</code>) is initialized for every new <code>y, x</code> values, then new columns are concatenated to it for different ticker values with <code>yx_df = pd.concat([yx_df, res], axis = 1)</code>, and finally a full ro...
python|pandas|dataframe|statistics
1
1,660
72,510,658
ValueError: Input 0 of layer "model_1" is incompatible with the layer: expected shape=(None, 224, 224, 3), found shape=(None, 290, 290, 3)
<p>I am trying to implement the game of Rock, paper and scissors in jupyther notebook using tensorflow with a neural network, the code I am trying to implement is this one: <a href="https://learnopencv.com/playing-rock-paper-scissors-with-ai/" rel="nofollow noreferrer">https://learnopencv.com/playing-rock-paper-scissor...
<p>From the error, it seems like the shape of the input images is <code>(290, 290, 3)</code>. Resizing the images to <code>(224, 224, 3)</code> will solve the issue. Please add the following line before normalizing.</p> <pre><code>#Resizing images images = np.resize(images,(400, 224, 224, 3)) #Normalizing images images...
python|tensorflow|opencv|jupyter-notebook|neural-network
1
1,661
59,898,557
Rename name in Python Pandas MultiIndex
<p>I try to rename a column name in a Pandas MultiIndex but it doesn't work. Here you can see my series object. <em>Btw, why is the dataframe df_injury_record becoming a series object in this function?</em></p> <pre><code>Frequency_BodyPart = df_injury_record.groupby(["Surface","BodyPart"]).size() </code></pre> <p>In...
<p>One possible problem should be pandas version under <code>0.24</code> or you forget assign back like mentioned @anky_91:</p> <pre><code>df_injury_record = pd.DataFrame({'Surface':list('aaaabbbbddd'), 'BodyPart':list('abbbbdaaadd')}) Frequency_BodyPart = df_injury_record.groupby(["S...
python|pandas|series|multi-index
0
1,662
59,894,647
subset dataframe to show on GUI Tkinter
<p>I have dropdown option in tkinter which select the option of dropdown by groupby the col1 by dataframe pandas , Now I am able to see the subset of dataframe by clicking ok button in my terminal , I want to see the subset dataframe after selecting into dropdown in my GUI , Please let me know how to see the subset da...
<p>It is my last code from previous question</p> <p><strong>EDIT:</strong> I added <code>command=</code> to <code>OptionMenu</code> so now it doesn't need <code>Button</code> to accept selection.</p> <pre><code>import tkinter as tk import pandas as pd # --- functions --- def showdata(): global table # dest...
python|pandas|dataframe|tkinter
1
1,663
59,505,194
Global fitting using scipy.curve_fit
<p>I had a quick question regarding global fitting using <code>scipy.optimize.curve_fit</code>. From my understanding, the only difference in setting up the script between local fitting versus global fitting, is the difference in concatenating your functions. Take the script below for example: </p> <pre><code>input_da...
<p>You have successfully performed fits to single datasets. Now, you want to perform a global fit of the same function to multiple datasets, simultaneously. The datasets are in a multidimensional array, where each dataset from the previously performed, successful single fits run along the inner axis. However, <a href="...
python|numpy|scipy|curve-fitting
2
1,664
40,489,653
Why is scipy.stats.ttest_ind throwing a new RuntimeWarning when comparing nans?
<p>I'm working with some pretty huge but sparsely populated pandas DataFrames. I use <code>scipy.stats.ttest_ind</code> to make comparisons of some of these columns which contain many nans. I recently updated to Anaconda 4.2.12 and now when use <code>scipy.stats.ttest_ind</code> I get the run time error seen in the exa...
<p>When I do</p> <pre><code>np.array([np.nan, -1]) &lt; 0 </code></pre> <p><a href="https://i.stack.imgur.com/1TLaA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1TLaA.png" alt="enter image description here"></a></p> <p>However, I can wrap it in a pandas series and let pandas supress the warning...
python-3.x|pandas|scipy|anaconda
2
1,665
40,550,631
How to read h5 file like csv file
<p>I have such an algorithm that works with csv file object</p> <pre><code>#diplay_id, ad_id, clicked(1 or 0) colls = {'display_id':np.int32, 'ad_id':np.int32, 'clicked':bool} trainData = pd.read_csv("trainData.csv") for did, ad, c in trainData.itertuples(): print did + ad + c #example </code></...
<p>The main difference in this case is the fact that HDF5 files might contain multiple DFs/tables, so you always have to specify a key (identifier).</p> <p>Here is a small demo:</p> <pre><code>In [14]: fn = r'C:\Temp\test_str.h5' In [15]: store = pd.HDFStore(fn) In [16]: store Out[16]: &lt;class 'pandas.io.pytables...
python|python-2.7|csv|pandas|hdf
0
1,666
61,857,569
Making a barchart in pandas with filtered data
<p>I have a csv file the that has a column that a bunch of different columns. the columns thhat i am interested in are the 'Items', 'OrderDate' and 'Units'. </p> <p>In my IDE I am trying to generate a bar chart of the amount of 'Pencil's sold on each individual 'OrderDate'. What I am trying to do is to look down throu...
<p>If I understood correctly you want to plot the number of pencils sold per day. For that, you can just filter the dataframe and keep only rows about pencils, and then use a barchart.</p> <p>Here's a reproducible code that assumes that all rows have different dates:</p> <pre><code>import pandas as pd import matplotl...
python|pandas
1
1,667
61,842,115
How to convert 200 column numpy array to dataframe?
<p>I have a numpy with 200 columns. Now, I want to store this with the column names in a datagram. How do I do this?</p> <pre><code>array([[0.47692407, 0.29395011, 0.54361545, ..., 0. , 0.69314718, 0. ], [0. , 0.41974993, 0.40546511, ..., 0. , 0.69314718, 0. ],...
<p>You can generate dynamically columns with a list comprehension iterating on the number of columns.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd dd = np.reshape(np.arange(20), (5,4)) pd.DataFrame(dd, columns=['col{0:03d}'.format(k) for k in range(dd.shape[1])]) </code></...
python|pandas|numpy
0
1,668
61,974,341
How to extract data based on 2 columns in a data frame and make a new column using Python?
<p>I have 2 columns in my data frame. “adult” represents the number of adults in a hotel room and “children” represents the number of children in a room. </p> <p>I want to create a new column based on these two. For example if <code>df['adults'] == 2 and df[‘children’]==0</code> the value of the new column would be "...
<h3>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.select.html" rel="nofollow noreferrer"><strong><code>np.select</code></strong></a></h3> <pre><code>df adult children 0 2 0 1 2 0 2 2 1 condlist = [<b>(df['adults']==2) & (df['children']==0)</b>,<b>(df[...
python|pandas|dataframe
1
1,669
58,010,602
How to type "pd.api.types.CategoricalDtype"
<p>I have error running this code and I don't know what the problem is?</p> <pre><code>sedan_classes = ['Minicompact Cars', 'Subcompact Cars', 'Compact Cars', 'Midsize Cars', 'Large Cars'] vclasses = pd.api.types.CategoricalDtype[categories = sedan_classes, ordered = True] fuel_econ['Vclass'] = fuel_econ['Vclass'].a...
<p>You are trying to call a function with rectangular braces which is used for indexing. The call would be <code>vclasses = pd.api.types.CategoricalDtype(categories = sedan_classes, ordered = True)</code> . Check the doc <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.api.types.Categorica...
python|python-3.x|pandas|data-science
1
1,670
57,780,053
How can I implement KL-divergence regularization for Keras?
<p>This is a follow-up question for this question <a href="https://stackoverflow.com/questions/57530823/keras-backend-mean-function-float-object-has-no-attribute-dtype">Keras backend mean function: &quot; &#39;float&#39; object has no attribute &#39;dtype&#39; &quot;?</a> </p> <p>I am trying to make a new regularizer ...
<p>In order to print means,</p> <pre><code>means = K.means((input), axis=1) ... means_ = sess.run(means, feed_dict={x: , y: }) print(means_) </code></pre>
python|tensorflow|keras|keras-layer|autoencoder
2
1,671
57,932,786
Return duration for each id
<p>I have a large list of events being tracked with a timestamp appended to each:</p> <p>I currently have the following table:</p> <pre><code>ID Time_Stamp Event 1 2/20/2019 18:21 0 1 2/20/2019 19:46 0 1 2/21/2019 18:35 0 1 2/22/2019 11:39 1 1 2/22/2019 16:46 0 1 2/23/2019 7:40 ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with <code>min</code> and <code>max</code> for <code>Series</code> with same size like original, so possible subtract for <code>Total...
python|pandas|time|attribution
1
1,672
58,067,850
df.dropna() not working and still appear in the dataframe
<p>I am trying to clean my dataset and for some reason the Nan's and "#N/A Invalid security" still show up. I tried</p> <pre><code>import pandas as pd import numpy as np df = pd.read_excel (r'C:\Users\rgoldstein27\Desktop\1-M index bond drivers.xlsx') df.dropna(how='any') df['EBITDA_TO_TOT_INT_EXP'] = pd.to_numeric(df...
<p><code>df.dropna()</code> creates a new copy, doesn't modify in place, by default. If you want inplace, you should set <code>inplace=True</code>: </p> <pre><code>DataFrame.dropna(self, axis=0, how='any', thresh=None, subset=None, inplace=False) </code></pre>
python|pandas|dataframe|nan
1
1,673
34,045,245
XlsxWriter python to write a dataframe in a specific cell
<p>One can write data to a specific cell, using:</p> <pre><code>xlsworksheet.write('B5', 'Hello') </code></pre> <p>But if you try to write a whole dataframe, df2, starting in cell 'B5': </p> <pre><code>xlsworksheet.write('B5', df2) TypeError: Unsupported type &lt;class 'pandas.core.frame.DataFrame'&gt; in write() <...
<p>XlsxWriter doesn't write Pandas dataframes directly. However, it is integrated with Pandas so you can do it the other way around.</p> <p>Here is a small example of writing 2 dataframes to the same worksheet using the <code>startrow</code> parameter of Pandas <a href="http://pandas.pydata.org/pandas-docs/stable/gene...
python|pandas|xlsxwriter
9
1,674
34,027,288
Cumulative counts in NumPy without iteration
<p>I have an array like so:</p> <pre><code>a = np.array([0.1, 0.2, 1.0, 1.0, 1.0, 0.9, 0.6, 1.0, 0.0, 1.0]) </code></pre> <p>I'd like to have a running counter of <strong>instances of 1.0</strong> that <strong>resets when it encounters a 0.0</strong>, so the result would be:</p> <pre><code>[0, 0, 1, 2, 3, 3, 3, 4, 0...
<p>I think you could do something like</p> <pre><code>def rcount(a): without_reset = (a == 1).cumsum() reset_at = (a == 0) overcount = np.maximum.accumulate(without_reset * reset_at) result = without_reset - overcount return result </code></pre> <p>which gives me</p> <pre><code>&gt;&gt;&gt; a = n...
python|numpy
12
1,675
34,223,105
Julia matrix multiplication is slower than numpy's
<p>I am trying to do some matrix multiplication in Julia to benchmark it against numpy's.</p> <p>My Julia code is the following:</p> <pre><code>function myFunc() A = randn(10000, 10000) B = randn(10000, 10000) return A*B end myFunc() </code></pre> <p>And the python version is:</p> <pre><code>A = np.random.ra...
<p>I don't think those are doing the same thing. The <code>numpy</code> expression just does an element-by-element multiplication, while the Julia expression does true matrix multiplication. </p> <p>You can see the difference by using smaller inputs. Here's the <code>numpy</code> example:</p> <pre><code>&gt;&gt;&gt; ...
python|numpy|julia|matrix-multiplication|blas
12
1,676
54,797,537
Python: splitting DataFrame based on numerical sequence
<p>I'm searching for a Pythonic implementation of splitting a pandas DataFrame based on multiple pre-defined numerical sequences in one column (in this example, <code>state</code>).</p> <p><strong>Example:</strong></p> <pre><code>sequence_1 = [4, 1, 5, 2] sequence_2 = [3, 0] test_data = pd.DataFrame({'state': [4, 1, ...
<p>An fast way if your data in <code>state</code> is well ordered like in your example would be to catch only the first element of both sequences and then <code>cumsum</code> in a <code>groupby</code> such as:</p> <pre><code>for name_g, df_g in test_data.groupby(((test_data.state == sequence_1[0])| ...
python|pandas|dataframe|sequence
2
1,677
49,657,317
How to separate a datetime into date and seconds
<p>Assume that there is a variable <code>time</code>,which is </p> <pre><code>&lt;class 'netCDF4._netCDF4.Variable'&gt; int32 time(time) units: seconds since 1955-01-01 unlimited dimensions: time current shape = (1464,) filling off </code></pre> <p>and I have changed it into datetime with <code>time = nc.num2date...
<p>If efficiency is what you are after, don't use object arrays. Use numpy's inbuilt <code>datetime64</code> dtype instead.</p> <p>As far as I can tell <code>datetime64</code> is not quite as comfortable to use as <code>datetime</code> but it gets the job done.</p> <p>You'd have to do the conversion manually, as far ...
python|arrays|numpy|datetime|netcdf
0
1,678
73,500,582
Pandas sum dataframe but retain shape
<p>I have a dataframe that looks like:</p> <pre><code> keyboards lights candles games 0 100 21 11 20 1 125 12 10 66 2 140 32 42 66 3 110 12 64 55 4 90 10 20 42 5 432 34 20 75 </code></pre> <p>A...
<p>The <code>.sum</code> function returns a pandas series which will always be printed vertically.</p> <p>A possible workaround is to transform the pd.Series to a pd.DataFrame before doing the transpose. The solution would be:</p> <pre><code>df.sum().to_frame().T </code></pre>
python|pandas|dataframe
0
1,679
73,287,503
Find new value occur and nearest value from another column
<p>I found this is complicated, I have a <code>Dataframe</code> and want the first row when a value change in column <code>A</code> and want the row that contains nearest value in column <code>B</code> to new value from <code>A</code> in the previous group.</p> <p>For example:</p> <pre><code>A | B ---------- 803...
<p>Use:</p> <pre><code>#consecutive groups g = df.A.ne(df.A.shift()).cumsum() #aggregate lists s = df.groupby(['A',g], sort=False)['B'].agg(list) #Series with next lists s1 = s.shift(-1,fill_value=[[]]) #get nearest values of previous group vals = [a[(np.abs(np.array(a) - b[0])).argmin()] if len(b) &gt; 0 el...
python|pandas|group-by
1
1,680
35,186,507
How to print "Nothing here" to excel if df or groupby is blank?
<p>I am calculating some metrics and printing them to excel using </p> <pre><code> writer = pd.ExcelWriter('File.xlxs', engine = 'xlsxwriter') 'metric'.to_excel(writer, sheetname = 'x') </code></pre> <p>Sometimes my metrics will be blank (e.g. the filter has filtered everything out). Is there a way to print to exc...
<p>You can get the underlying xlsxwriter workbook to write custom output to the file. More examples in the xlsxwriter <a href="http://xlsxwriter.readthedocs.org/working_with_pandas.html" rel="nofollow">docs</a></p> <pre><code>if metric.empty: sheet = writer.book.add_worksheet('y') sheet.write_string('A1', 'No...
python|excel|pandas|xlsx
1
1,681
35,106,041
Numpy: Creating a Vector through Array Comparison is NOT working
<p>As shown in the IPython (Python 3) snapshot below I expect to see an array of Boolean values printed in the end. However, I see ONLY 1 Boolean value returned.</p> <ol> <li>Unable to identify why?</li> <li>What does the character 'b' before every value in the first print statement denote? Am I using the wrong dtype=...
<p>Python has the distinction between unicode strings and ASCII bytes. In Python3, the default is that "strings" are unicode. </p> <p>The <strong>b</strong> prefixing the "strings", indicate that the interpreter considers these to be bytes. </p> <p>For the comparison, you need to compare it to bytes as well, i.e., </...
python|arrays|numpy
1
1,682
30,983,197
Requirements for converting Spark dataframe to Pandas/R dataframe
<p>I'm running Spark on Hadoop's YARN. How does this conversion work? Does a collect() take place before the conversion?</p> <p>Also I need to install Python and R on every slave node for the conversion to work? I'm struggling to find documentation on this.</p>
<p><strong><code>toPandas</code> (PySpark) / <code>as.data.frame</code> (SparkR)</strong></p> <p>Data has to be collected before local data frame is created. For example <a href="https://github.com/apache/spark/blob/master/python/pyspark/sql/dataframe.py#L1237" rel="nofollow noreferrer"><code>toPandas</code></a> metho...
pandas|apache-spark|dataframe|hadoop|apache-spark-sql
13
1,683
30,791,550
Limit number of threads in numpy
<p>It seems that my numpy library is using 4 threads, and setting <code>OMP_NUM_THREADS=1</code> does not stop this.</p> <p><code>numpy.show_config()</code> gives me these results:</p> <pre><code>atlas_threads_info: libraries = ['lapack', 'ptf77blas', 'ptcblas', 'atlas'] library_dirs = ['/usr/lib64/atlas'] ...
<p>There are a few common multi CPU libraries that are used for numerical computations, including inside of NumPy. There are a few environment flags that you can set <strong>before running the script</strong> to limit the number of CPUS that they use.</p> <p>Try setting all of the following:</p> <pre><code>export MKL_N...
python|multithreading|numpy
61
1,684
67,575,780
Calculate Second Gradient with PyTorch
<p>In PyTorch, there are two ways of calculating second gradients. The first method is to use <code>torch.autograd.grad</code> function, and the other is to use <code>backward</code> function. I use the following examples to illustrate it:</p> <p>Method 1:</p> <pre><code>x=torch.tensor([3.0], requires_grad=True) y = to...
<p>Use the <code>grad</code> method from <code>torch.autograd</code> to differentiate your function. So the steps would be:</p> <pre><code>&gt;&gt;&gt; import torch &gt;&gt;&gt; from torch.autograd import grad &gt;&gt;&gt; x = torch.tensor([3.0], requires_grad=True) &gt;&gt;&gt; y = torch.pow(x,2) &gt;&gt;&gt; z = gr...
python|pytorch
0
1,685
67,271,336
Remove duplicates from list type pandas column
<p>I have a data frame like this,</p> <pre><code>df col1 col2 [1,2,3] [4,5] [1,2,3] [6,7] [4,5,6] [8,9] [9,8,7,1] [1,2] [9,8,7,1] [3,4] </code></pre> <p>Now I want to remove duplicates from col1, and keep the first row of duplicate values so the data frame would look like,</p> <pre><code>col1 ...
<p>We can try mapping the lists in <code>col1</code> to <code>tuple</code>, then we can use <code>duplicated</code> to create a boolean mask which can be used to filter the rows</p> <pre><code>df[~df['col1'].map(tuple).duplicated()] </code></pre> <hr /> <pre><code> col1 col2 0 [1, 2, 3] [4,5] 2 [4,...
python|pandas|dataframe
3
1,686
67,582,429
Remove string like space + letter+ space from a dataframe column
<p>I have those sentences column in a dataframe:</p> <pre><code>&quot;I love x cat&quot; &quot;You x x&quot; &quot;x x x x&quot; &quot;This example is better&quot; </code></pre> <p>And I would like with python remove &quot; x &quot;</p> <pre><code>&quot;I love cat&quot; &quot;You&quot; &quot;&quot; &quot;This example i...
<p>If you've a dataframe then you can use:</p> <pre><code>df['your col name here'] = df['your col name here'].apply(lambda s: ' '.join(i for i in s.split(' ') if i != 'x')) </code></pre>
python|python-3.x|pandas|dataframe
2
1,687
60,193,848
Python - Pandas - Remove only splits that only numeric but maintain if it have alphabetic
<p>I have a dataframe that have two values:</p> <pre><code>df = pd.DataFrame({'Col1': ['Table_A112', 'Table_A_112']}) </code></pre> <p>What I am trying to do is to remove the numeric digits in case of the split('_') only have numeric digits. The desired output is:</p> <pre><code>Table_A112 Table_A_ </code></pre> <p...
<p>You can do something like:</p> <pre><code>s = df['Col1'].str.split('_',expand=True).stack() s.mask(s.str.isdigit(), '').groupby(level=0).agg('_'.join) </code></pre> <p>Output:</p> <pre><code>0 Table_A112 1 Table_A_ dtype: object </code></pre>
python|regex|string|pandas
5
1,688
59,952,486
How to add True or False values to a dataframe column?
<p>Can somebody suggest me on how to create True or False values in a data-frame? For example I have a data-frame like below:</p> <pre><code>df = pd.DataFrame({"a":[0, 1, 2, 3], "b":[1, 4, 7, 9],"c":["In, Out", "Out", "In, Out", "In, Out"]}) print(df) a b c 0 1 In, Out 1 4 Out 2 7 In, Out 3 9 In, Out </...
<p>If want convert column to boolean by indicators (<code>True</code> if exist value) then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.get_dummies.html" rel="nofollow noreferrer"><code>Series.str.get_dummies</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stabl...
python|pandas|dataframe|data-analysis|data-cleaning
2
1,689
60,172,458
sklearn cross_val_score() returns NaN values
<p>i'm trying to predict next customer purchase to my job. I followed a guide, but when i tried to use cross_val_score() function, it returns NaN values.<a href="https://i.stack.imgur.com/AHGzs.png" rel="noreferrer">Google Colab notebook screenshot</a></p> <p>Variables: </p> <ul> <li>X_train is a dataframe</li> <li>X...
<p>My case is a bit different. I was using <code>cross_validate</code> instead of <code>cross_val_score</code> with a list of performance metrics. Doing a 5 fold CV, I kept getting NaNs for all performance metrics for a <code>RandomForestRegressor</code>:</p> <pre><code>scorers = ['neg_mean_absolute_error', 'neg_root_m...
python|nan|prediction|cross-validation|sklearn-pandas
5
1,690
60,101,727
Shift and multipy in Pandas
<p>I have a pandas dataframe looks like this:</p> <pre><code> Year Ship Age Surviving UEC 2018 12.88 13 0.00 17.2 2019 12.57 12 0.02 17.2 2020 12.24 11 0.06 17.2 2021 11.95 10 0.18 17.2 2022 11.77 9 0.37 17.2 2023 11.70 ...
<p>IIUC, I think you want:</p> <pre><code>df.loc[:,'shipping_utc'] = 0 for i in range(df.shape[0]): df.loc[i:,'shipping_utc'] = df.iloc[i:][['Ship','Surviving','UEC']].prod(axis=1) + df.loc[i:,'shipping_utc'] </code></pre> <p>output</p> <pre><code>df Out[25]: Year Ship Age Surviving UEC shipping_utc...
python|pandas
0
1,691
65,475,520
Pandas Series.replace replaces the entire series even in an iterative loop?
<p>So I have this dataframe and I wanna replace some of its rows with another value based on a condition.</p> <pre><code>df = pd.Dataframe({'col1':[1,1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3]}) for rows in df['col1']: if rows == &quot;1&quot;: df['col1'].replace({rows: &quot;A&quot;}, inplace=True) else: ...
<p>in each cycle of the loop you are changing all the values ​​again, this is inefficient, also its value may be integer and not of type <code>string</code>, try with <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a>:</p> <pre><code>import...
python|pandas|dataframe
1
1,692
65,469,362
Non-overlapping rolling windows in pandas groupby
<p>I want to create non-overlapping rolling or sliding window in pandas groupby</p> <pre><code>import pandas as pd df1 = pd.DataFrame( {'a1':['A','A','B','B','B','B','B','B'],'a2':[1,1,1,2,2,2,2,2], 'b':[1,2,5,5,5,4,6,2]}) </code></pre> <p>For overlapping rolling window, I can do this</p> <pre><code>df1.groupby(['a1','...
<p>Well, one approach (not very elegant), is to do:</p> <pre><code>def non_overlapping_mean(x, window=2): return x.groupby(np.arange(len(x)) // window).apply(lambda x: np.nan if len(x) &lt; 2 else x.mean()) res = df1.groupby(['a1', 'a2'])['b'].apply(non_overlapping_mean).droplevel(-1).reset_index() print(res) </c...
python|pandas
2
1,693
64,122,593
Error when plotting y function with range of x values
<p>Get this error when trying to plot a function with respect for a range of x values</p> <p>TypeError: unsupported operand type(s) for *: 'float' and 'range'</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = range(273, 1273) print(list(x)) y = -0.7765 + (0.014350 * x) - (0.000012209 * (x ** 2)) + (...
<p>When you use the function <code>range</code>, it uses python's <code>range</code> function which cannot be used in arithmetic directly as it is an iterator. So you get an error saying multiplication is not supported for: <code>range</code> and <code>float</code>.</p> <p>When you use NumPy's <code>arange</code>, it h...
python|numpy|matplotlib
1
1,694
63,801,101
Slicing values in a column to make a condition for another column
<p>So I have <code>df1</code> which has this particular column :</p> <pre><code>X_codes ----------------------------------- A4529,B5243,E5170 ----------------------------------- A7413,A7260,E5164 ----------------------------------- F6032 </code></p...
<p>Try this:</p> <pre><code>(df.join(df['X_codes'].str.split(',') .explode().str[0] .str.get_dummies() .max(level=0) .reindex(df2['act'], axis=1, fill_value=0))) </code...
python|pandas|slice
1
1,695
63,843,633
a dataframe with several columns having the same column name, how to only keep the first and drop the rest?
<p>I have a df with these columns:</p> <pre><code>Index(['Instrument', 'Date', 'Return on Invst Cap', 'Date', 'Book Value Per Share, Total Equity', 'Date', 'Earnings Per Share Reported - Actual', 'Date', 'Revenue from Business Activities - Total', 'Date', 'Free Cash Flow - Actual', 'Date', '...
<p>You can set all the columns names:</p> <pre><code>df = df.set_axis(['Instrument', 'Date', 'Return on Invst Cap', 'Date2', 'Book Value Per Share, Total Equity', 'Date3', 'Earnings Per Share Reported - Actual', 'Date4', 'Revenue from Business Activities - Total', 'Date5', 'Free Cash Flow - ...
python|pandas|dataframe|rename|drop
1
1,696
46,797,176
How do I multiply a column in predefined increments?
<p>Say I have a pandas df with integers (value) in one column. I need to make a second column that equals 0 when the value is &lt; 100, 1.00 when the value >= 100, and add 0.25 for every 25 increase in value and vice versa if value decreases. BUT I only want to add 0.25 to the new column up to value 2.00, i.e max four ...
<p>You can use <code>//</code> (integer division):</p> <pre><code>In [11]: (df.value // 25) * 0.25 Out[11]: 0 0.75 1 1.00 2 1.00 3 1.00 4 1.25 5 1.25 6 1.50 7 1.75 8 1.75 9 2.00 10 2.25 11 2.50 12 2.00 13 1.75 14 1.50 15 1.25 16 1.00 17 1.00 18 0.75 Na...
python|pandas|dataframe
3
1,697
46,931,434
How to handle scenario where numpy.where condition is unsatisfied?
<p>I am converting this array:</p> <p><code>x = np.array([[0, 0, 1], [1, 1, 0], [0, 1, 0], [1, 0, 0], [0, 0, 0]])</code></p> <p>to: <code>[2, 0, 1, 0, 0]</code>. </p> <p>Basically, I want to return the index of the first <code>1</code> in each sub-array. However, my problem is that I don't know how to handle the sce...
<p>Use <code>mask</code> of <code>1s</code> and then <code>argmax</code> along each row to get the first matching index alongwith <code>any</code> to check for valid rows (rows with at least one <code>1</code>) -</p> <pre><code>mask = x==1 idx = np.where(mask.any(1), mask.argmax(1),0) </code></pre> <p>Now, <code>argm...
python|arrays|numpy
2
1,698
46,750,647
How to test whether one of two values present in numpy array or matrix column on single pass?
<p>Take a matrix like the following:</p> <pre><code>import numpy as np m = np.matrix([[1,1], [2,0], [3,1], [5,1], [5,0]]) </code></pre> <p>Then take two test values:</p> <pre><code>n1 = 4 n2 = 1 </code></pre> <p>How can I test for both of them (it's guaran...
<p>If you need simplicity and readability , the simplest can be found with set logic : </p> <pre><code>{1,4} &amp; set(m[:,0]) </code></pre> <p>Furthermore, the data is actually read exactly one time.</p>
python|arrays|numpy
3
1,699
38,693,417
creating new numpy array dataset for each loop
<p>I need to create a new dataset variable everytime within a for loop using .append as below wont work. Note the shape of each numpy array type variable is (56, 25000)</p> <pre><code>ps=[1,2,3,4] for subj in ps: datapath = '/home/subj%d' % (subj) mydata.append = np.genfromtext(datapath, mydatafile) </cod...
<p>It's hard to say without more code, but <code>.append</code> is generally a method, and should be called like this:</p> <pre><code>some_container.append(your_object) </code></pre> <p>Note I'm also initializing <code>mydata</code> to be an empty list -- you don't show how you initialize it (if you do at all), so ju...
python|numpy
2