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
376,600
65,443,829
Problem with read text file in Python Pandas?
<p>Hello How to read below txt file ?</p> <p><a href="https://i.stack.imgur.com/ivxXQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ivxXQ.png" alt="enter image description here" /></a></p>
<p>Your file appears to be a csv, not a fwf. Use <code>pd.read_csv</code>.</p>
python|pandas|dataframe|text
0
376,601
65,234,228
Sum of only specific columns in a pandas dataframe
<p>Consider I have a dataframe with few columns</p> <p><a href="https://i.stack.imgur.com/3jxz8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3jxz8.png" alt="before operation" /></a></p> <p>and a list ['salary','gross exp']</p> <p>Now I want to perform sum of the column operation only on the column...
<p>Working with the following example:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd list_ = ['sallary', 'gross exp'] d = {'sallary': [1,2,3], 'gross exp': [2,2,2], 'another column': [10,10,10]} df = pd.DataFrame(d) df </code></pre> <div class="s-table-container"> <table class="s-table"> <the...
python|excel|vba|pandas|dataframe
0
376,602
65,353,418
How do you take a text file and change split it into data usable for a machine learning classifier?
<p>for this practice exercise I'm only supposed to use numpy so I can't just use scikit learn.</p> <p>I've loaded the data set and managed to split it into positive and negative arrays. However I'm not sure what to do now or even what I am doing right to process the data for the classifier.</p> <pre><code>datasettrain ...
<p>Ah, if I'm interpreting your sample data correctly, the first two columns are your feature columns and the last column is your target values. If this is correct, then to get training and test sets, you would need to do something like the following:</p> <pre><code>import numpy as np data = np.loadtxt(&quot;Adaboost...
python|numpy|machine-learning
0
376,603
65,165,637
'Fill forward' dummy variable for observations in same group (Python)
<p>I've created a dummy variable (in Python), <code>seo</code>, which takes the value 1 if the value of another column is greater than 0, as shown in the code below.</p> <pre><code>df['seo'] = (df['amount'] &gt; 0).astype(int) </code></pre> <p>What I want to do is to create a second dummy variable, <code>past_seo</code...
<p>I think this should work:</p> <pre><code>df[&quot;past_seo&quot;] = df.groupby(&quot;6_cusip&quot;).seo.cumsum().gt(0).astype(int) </code></pre> <p>Basically, cumulatively sum seo for each group, flag as true if it's greater than <code>1</code> and cast as an integer.</p> <p>output:</p> <pre><code> date 6_cusi...
python|pandas|dataframe|data-science|dummy-variable
0
376,604
65,338,012
Pandas apply() with condition on last notnull value and its index
<p>I have a problem with a code I'm working on right now, so basically what I have is a dataframe with a column filled with numbers in the form pd.Dataframe([2,2,2,0,0,0,0,2,0,2]) for example. So what I want as an output is this [2,2,2,0,0,0,0,10,0,4] (like a memory effect).</p> <p>So I'm thinking if there is a way of...
<p>You included in your post an example how to compute the expected value: (<code>2 * (7 - 2) = 10</code>). It indicates that a more precise formula, for values <em>!= 0</em>, is rather:</p> <pre><code>x * (index(x) - index(previousNonZero(x))) </code></pre> <p>Note the following difference:</p> <ul> <li><em>lastnotnul...
python|pandas|dataframe|conditional-statements
0
376,605
65,447,577
Remove characters from string (DataFrame)
<p>How do I remove extra characters with <strong>REGEX</strong> in this string code snippet below.</p> <p><strong>From This :</strong> Fulham\n3.20\nDraw\n3.25\nSouthampton\n2.25\n</p> <p><strong>To Desired Outcome:</strong> 3.20\n\n3.25\n\n2.25</p> <p><em>Note</em>: I've tried with this regex -&gt; ([^\d.\n]) but it...
<p>Try this:</p> <pre><code>s = &quot;Fulham\n3.20\nDraw\n3.25\nSouthampton\n2.25\n&quot; &quot;\n\n&quot;.join(i for i in s.split() if re.search(r&quot;\d&quot;, i)) </code></pre> <p>Output:</p> <pre><code>'3.20\n\n3.25\n\n2.25' </code></pre>
python-3.x|pandas|dataframe
1
376,606
65,202,651
Python : Most efficient way to count elements of long list 1 in long list 2 ? (list comprehension is really slow)
<p>I have many tuples (e.g. <code>(0, 1)</code>) in two pretty long lists <code>list_0</code>and <code>list_1</code>of size ~40k elements. I need to count the tuples of <code>list_0</code> also in <code>list_1</code>.</p> <p>The following statement with list comprehension takes ~ 1 min and I need to do this multiple ti...
<p>It looks like you can use</p> <pre><code>pd.Series(list_0).isin(list_1).sum() </code></pre> <p>Output:</p> <pre><code>22300 CPU times: user 14.8 ms, sys: 20 µs, total: 14.8 ms Wall time: 14.1 ms </code></pre> <p>which should give the same answer with:</p> <pre><code>len([element for element in list_0 if element in l...
python|pandas|numpy
3
376,607
65,259,666
Pandas group by id and year(date), but show year for all years, not just those which are present in id?
<p>I have a years of transaction data which I am working with by customer ids. The transaction information is at an invoice level and an id could easily have multiple invoices on the same day or not have invoices for years. I am attempting to create dataframes which contain sums of invoices by customer by each year, bu...
<p>Let's suppose the original values are defined in the dataframe named <code>df</code> then you can try the following:</p> <pre><code>output = (df.groupby(['id', 'invoice_date'])['val'].sum() .unstack(fill_value=0) .stack() .reset_index(name='val')) </code></pre> <p>Othe...
python|pandas|group-by
1
376,608
65,470,212
ValueError: Expected target size (128, 44), got torch.Size([128, 100]), LSTM Pytorch
<p>I want to build a model, that predicts next character based on the previous characters. I have spliced text into sequences of integers with length = 100(using dataset and dataloader).</p> <p>Dimensions of my input and target variables are:</p> <pre><code>inputs dimension: (batch_size,sequence length). In my case (12...
<p>As a general comment, let me just say that you have asked many different questions, which makes it difficult for someone to answer. I suggest asking just one question per StackOverflow post, even if that means making several posts. I will answer just the main question that I think you are asking: &quot;why is my cod...
pytorch|lstm|recurrent-neural-network
1
376,609
65,247,333
How to specify a proxy in transformers pipeline
<p>I am using sentiment-analysis pipeline as described <a href="https://huggingface.co/transformers/quicktour.html" rel="noreferrer">here</a>.</p> <pre><code>from transformers import pipeline classifier = pipeline('sentiment-analysis') </code></pre> <p>It's failing with a connection error message</p> <blockquote> <p>Va...
<p>It should be proxy problem. You can try add this code snippet to go through proxies.</p> <pre><code>import os os.environ['HTTP_PROXY'] = 'http://xxx:xxx@xxx:xxx' os.environ['HTTPS_PROXY'] = 'http://xxx:xxx@xxx:xxx' from transformers import pipeline classifier = pipeline('sentiment-analysis') </code></pre> <p><stron...
python|bert-language-model|huggingface-transformers
1
376,610
65,127,731
I'm using a mask to slice a numpy array, but the output is flattened. How do I retain the number of columns?
<p>Here is what I have so far:</p> <pre><code>arr = np.round(np.random.uniform(0,1,size = (10,10)),decimals = 0) print(arr) arr2 = np.cumsum(arr,axis=0) print(arr2) mask = np.where((arr == 1)&amp;(arr2&lt;=3),1,0) print(mask) population = np.round(np.random.uniform(0,5,size=(10,10)),decimals=0) print(population) masked...
<p>It looks like the maks produces the same amount of non-zero rows per column. So you could probably mask (using the boolean array directly) and <code>reshape</code>:</p> <pre><code>population[(arr == 1)&amp;(arr2&lt;=3)].reshape(3,-1) array([[3., 2., 5., 0., 4., 2., 0., 4., 5., 1.], [4., 3., 5., 3., 4., 1., 1...
numpy|mask
1
376,611
65,194,949
Number of different values / distinct in a column per ID in a sorted dataframe
<p>I have a sorted dataframe with an ID, and a value column, which looks like:</p> <pre><code>ID value A 10 A 10 A 10 B 15 B 15 C 10 C 10 ... </code></pre> <p>How can i create a new dataframe, that it counts the &quot;new&quot; distinct values in terms of the number of different IDS, so that it ...
<p>I think you need processing new DataFrame by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer"><code>DataFrame.drop_duplicates</code></a> with <code>factorize</code> and <code>cumsum</code>:</p> <p>Replace duplicated values to <code>Na...
python|pandas
3
376,612
65,063,107
Plotting Monthly data using groupby in dask dataset
<p>I have a large <code>CSV</code> file that it is opened with Dask.</p> <pre><code>import numpy as np import pandas as pd import hvplot.pandas import hvplot.dask import intake data = '../file.csv' ddf = intake.open_csv(data).to_dask() ddf.head() Datetime latitude longitude Temp_2m(C) 1 1980-01-02 03:00:0...
<p>I used to_datetime() and got correct plot with .plot()... ran into problems installing hvplot.</p> <pre><code>import numpy as np import pandas as pd # FIXME : the following does not work #import hvplot.pandas %matplotlib inline d = dict(datetime = ['1980-01-02 02:00:00', '1980-01-02 03:00:00...
python|pandas|pandas-groupby|dask|hvplot
1
376,613
65,119,742
Cannot subset the first column in a DataFrame
<p>Im learning how to use Pandas and I've downloaded some data from Kaggle about car prices etc.</p> <p>I'm trying to create a new dataframe by subsetting all the cars out that have the model &quot;Golf&quot;.</p> <pre><code>golfs = df[df.model == &quot;Golf&quot;] </code></pre> <p>It does return a new dataframe but wh...
<p>The code looks like it is correct to me. If the golf dataframe is empty, it is possible you dont have any rows where df['model'] == 'Golf'?. Maybe it's ==&quot;golf&quot; instead?</p> <pre><code># It this doesnt work.... # golfs = df[df.model == &quot;Golf&quot;] # Maybe try this (or something like this golfs = df[d...
python|python-3.x|pandas|dataframe
0
376,614
65,349,992
Converting a Segemented Ground Truth to a Contour Image efficiently with Numpy
<p>Suppose I have a segmented image as a Numpy array, where each entry in the image is a number from 1, ... C, C+1 where C is the number of segmentation classes, and class C+1 is some background class. I want to find an efficient way to convert this to a contour image (a binary image where a contour pixel will have val...
<p>This might work but it might have some limitations which I cannot be sure of without testing on the actual data, so I'll be relying on your feedback.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from scipy import ndimage import matplotlib.pyplot as plt # some sample data with few rectangul...
numpy|optimization|image-segmentation
1
376,615
65,309,417
How to read '08E55' as string from Excel Using Pandas
<p>In excel i have value in a Column as '<strong>08E55</strong>'. The value is product ID and should be read as it is. While reading the excel through pandas it is being converted as '<strong>8e+55</strong>' . How can i avoid this?</p> <p>Few records include values like - U8716 U8715 8725 U8716 U8721 08E55</p> <p>I hav...
<p>Pretty simple, just use the converters parameter while reading the excel file.</p> <pre><code>pd.read_excel('New.xlsx', converters={'column_name':str}) </code></pre> <p><strong>Edit 1:</strong></p> <pre><code>pd.read_excel('New.xlsx', converters={'column_name':str}, convert_float=False) </code></pre> <p><strong>Edit...
python|python-3.x|excel|pandas
1
376,616
49,972,166
Why does this numpy array with ten times the values take exponentially larger amounts of time to randomly generate?
<p>I initialize three numpy arrays, because I need to feed some random data into an algorithm.</p> <p>My second array has about a hundred times the values, and takes about a hundred times the time.</p> <p>The third, for some reason, takes almost 1800 times the amount of time as the second does.</p> <pre><code>nparra...
<p>Assuming numpy uses <code>dtype('int64')</code> for these arrays, i.e. 8 bytes per element:</p> <ul> <li>The 1st array is 2457600 elements (~20 Megabytes)</li> <li>The 2nd array is 245760000 elements (~2 Gigabytes)</li> <li>The 3rd array is 2457600000 elements (~20 Gigabytes)</li> </ul> <p>If you have a reasonably...
python|numpy|runtime
2
376,617
50,006,950
Split a dataframe into smaller dataframes based on a column python
<p>I have this dataset : </p> <p><a href="https://i.stack.imgur.com/OAmuC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OAmuC.png" alt="raw data"></a></p> <p>And I want it to look like this:</p> <p><a href="https://i.stack.imgur.com/OYcZU.png" rel="nofollow noreferrer"><img src="https://i.stack....
<p>Try this :</p> <pre><code>df.groupby(['index', 'city_id'], as_index=False).sum() </code></pre> <p>This will group the first 2 columns and sum up the remaining ones.</p>
python|pandas
0
376,618
49,863,401
How to use apply function on multiple columns at once
<p>Is it possible to call the apply function on multiple columns in pandas and if so how does one do this.. for example,</p> <pre><code> df['Duration'] = df['Hours', 'Mins', 'Secs'].apply(lambda x,y,z: timedelta(hours=x, minutes=y, seconds=z)) </code></pre> <p><a href="https://i.stack.imgur.com/FdKpV.png" rel="nofoll...
<p><strong>You should use:</strong> </p> <pre><code>df['Duration'] = pd.to_timedelta(df.Hours*3600 + df.Mins*60 + df.Secs, unit='s') </code></pre> <p>When you use apply on a <code>DataFrame</code> with <code>axis=1</code>, it's a row calculation, so typically this syntax makes sense:</p> <pre><code>df['Duration'] = ...
python|pandas|apply|duration|timedelta
4
376,619
50,090,076
slicing a numpy array with characters
<p>I have a text file made as:</p> <pre><code>0.01 1 0.1 1 10 100 a 0.02 3 0.2 2 20 200 b 0.03 2 0.3 3 30 300 c 0.04 1 0.4 4 40 400 d </code></pre> <p>I read it as a list <code>A</code> and then converted to a numpy array, that is:</p> <pre><code>&gt;&gt;&gt; A array([['0.01', '1', '0.1', '1', '10', '100', 'a'], ...
<p>You have to compare <code>int</code> to <code>int</code></p> <pre><code>A[A[:,4].astype(int)&lt;30] </code></pre> <p>or <code>str</code> to <code>str</code></p> <pre><code>A[A[:,4]&lt;'30'] </code></pre> <p>However, notice that the latter would work in your <em>specific example</em>, but won't work generally be...
python|arrays|string|numpy|sub-array
3
376,620
50,098,336
How to Solve: 'str' object has no attribute 'data_format' in keras
<p>I am trying to make a classifier which can classify cats and dogs using keras. I am just trying to create the tensor data from images using <strong>ImageDataGenerator.flow_from_directory()</strong> which are sorted and kept in the directories whose paths are given in train_path, test_path etc.</p> <p><strong>Here i...
<p>Method <code>flow_from_directory</code> of <code>ImageDataGenerator</code> is not static. Therefore you first have to initialize an instance of class <code>ImageDataGenerator</code> and then call this method.</p> <p>This should work:</p> <pre><code>import numpy as np import keras from keras import backend as K ...
python|python-3.x|tensorflow|deep-learning|keras
2
376,621
49,907,240
Serving a TensorFlow Custom Model
<p>I am new in machine learning, basically i created own dataset of images and do training on them and recognize images on jupyter notebook, after this i tried to deploy this model by following <a href="https://www.tensorflow.org/serving/setup" rel="nofollow noreferrer">this</a> tutorial</p> <p>I execute</p> <pre><co...
<p>Move your custom training folder to tmp folder and that model should have version ex 1 folder inside it</p>
tensorflow|tensorflow-serving|tensorflow-datasets|tensorflow-estimator|tensorflow-slim
1
376,622
50,042,016
Correct way to store samples in numpy arrays
<p>Suppose you have a matrix (two-dimensional numpy array) storing multivariate sample data. Is it correct (wrt speed and ease of use) to store the data using one <strong>row</strong> for each sample or one <strong>column</strong> for each? E.g</p> <pre><code>array([[x1, y1, ...], [x2, y2, ...], ..., [xN, yN, ...]]) <...
<p>The performance depends on both the access pattern and the memory layout of the array. The latter may be set with the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html" rel="nofollow noreferrer"><code>order</code> parameter of <code>np.array()</code></a>, which:</p> <blockquote> <p>Sp...
python|numpy
1
376,623
49,928,463
Python Pandas update a dataframe value from another dataframe
<p>I have two dataframes in python. I want to update rows in first dataframe using matching values from another dataframe. Second dataframe serves as an override. </p> <p>Here is an example with same data and code: </p> <p>DataFrame 1 : </p> <p><a href="https://i.stack.imgur.com/QPJs2.png" rel="noreferrer"><img sr...
<p>Using DataFrame.update, which aligns on indices (<a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.update.html" rel="noreferrer">https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.update.html</a>):</p> <pre><code>&gt;&gt;&gt; df1.set_index('Code', inplace=True) &g...
python|pandas|dataframe
66
376,624
49,956,302
How to merge / concat two pandas dataframes with different length?
<p>I would like to concat/merge two pandas dataframes but I don't get the right result. I have following dataframes:</p> <pre><code>df1 Username | User_trim ------------------------------- 0 Maria M | Maria 1 FakeName | N/A 2 Achim B | Achim 3 FlashMaster11 | N/A 4 Fakename2 | ...
<p>I think need <code>left join</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a>:</p> <pre><code>df = df1.merge(df2,how='left', left_on='Username', right_on=0) print (df) Username User_trim 0 1 ...
python|python-2.7|pandas|dataframe|merge
1
376,625
49,950,092
Sklearn multiclass classification class order
<p>I have three classes [-1,0,1] and I am running multi class logistic regression on them. When I run logreg.predict_proba(x) it returns a an array [.25, .5, .25] does this mean that position 0 is class -1, position 1 is class 0, and position 2 is class 1? In other words, how does the logistic regression map the classe...
<p>You can verify the order of the classes using the classes attribute of your logistic regression classifier. For example, if the classifier is named logreg then</p> <pre><code>logreg.classes_ </code></pre> <p>will reveal the order of the classes.</p> <p><a href="http://scikit-learn.org/stable/modules/generated/sklear...
python|pandas|scikit-learn
5
376,626
50,163,284
how to read an lz4 compressed file in Pandas?
<p>I have a file like <code>stackunderflow.csv.lz4</code> and I want to load it in <code>Pandas</code> for processing.</p> <p>I tried the naive <code>pd.read_csv()</code> without success. Can the great <code>Pandas</code> handle these types of compressed files?</p> <p>Thanks!</p>
<p>Per <a href="https://stackoverflow.com/questions/45966508/reading-large-lz4-compressed-json-data-set-in-python-2-7">this StackOverFlow Answer</a>, you can use a 3rd party library to read in the data in chunks and then load that into your Pandas dataframe</p> <p><code> import lz4.frame chunk_size = 128 *...
python|pandas|lz4
2
376,627
49,927,354
Python numpy - DepricationWarning: Passing 1d arrays as data is deprecated
<p>I am quite new to data science/python, and currently I am working on some deep learning algorithms where I would like to use one variable for both input and output data. I have 4 inputs and 1 output. I use the following structure:</p> <pre><code> samples = np.zeros(nb_samples, dtype=[('input', float, 4), ('output',...
<p>I'm using 0.19.1 and indeed I get an error when I try to scale this array. But here's the transformation that works for me:</p> <pre class="lang-py prettyprint-override"><code>samples = np.zeros(nb_samples, dtype=[('input', float, 4), ('output', float, 1)]) x = samples['input'] # shape=(nb_samples, 4) y = sampl...
python|arrays|numpy|scikit-learn|deep-learning
3
376,628
50,169,882
Multiply rows and append to dataframe by cell value
<p>Consider the following dataframe;</p> <pre><code>df = pd.DataFrame( {'X':('a','b','c','d'), 'Y':('a','b','d','e'), 'Z':('a','b','c','d'), '#':(1,2,1,3) }) df </code></pre> <p><a href="https://i.stack.imgur.com/qA1uM.png" rel="nofollow noreferrer"><img src=...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow noreferrer"><code>numpy.repeat</code></a>:</p> <pre><code>c = df.columns[1:] df = pd.DataFrame(np.repeat(df.values, df['#'], axis=0)[:, 1:], columns=c) print (df) X Y Z 0 a a a 1 b b b 2 b b b 3 c d c...
python|pandas|numpy
2
376,629
50,082,220
Tensorboard: unable to find named scope
<p>I have a scope which I named <code>'Pred/Accuracy'</code> that I cant seem to find in Tensorboard. I will include my entire code a little later but specifically in my definition of my cost function I have: </p> <pre><code>def compute_cost(z, Y, parameters, l2_reg=False): with tf.name_scope('cost'): logits = tf...
<p>Tensorflow scopes are hierarchical: you can have a scope within another scope within another scope, etc. The name <code>"Pred/Accuracy"</code> means exactly that: you have a top level <code>"Pred"</code> scope and <code>"Accuracy"</code> nested scope (this is because slash is has a special meaning in naming).</p> <...
python|python-3.x|tensorflow|deep-learning|tensorboard
1
376,630
49,938,429
Removing consecutive asc/desc sequences from dataframe
<p>am thinking of a pandaistic way (not a loop) to remove all consecutive positives or negative pct changes. So assuming i have a dataframe like this:</p> <p><code>df=pd.DataFrame([1,2,3,5,4,3,2,4,5,6,7,8,9])</code></p> <p>i would want to remove all in between points where there is consecutive ascending/descending se...
<p>With the other words you need to choose items where <code>A[i-1] &gt; A[i] &lt; A[i+1]</code> or <code>A[i-1] &lt; A[i] &gt; A[i+1]</code></p> <pre><code>df = pd.DataFrame([1,2,3,4,5,4,3,2,4,5,6,7,8,9]) numbers_list = df[0].values.tolist() df = pd.DataFrame([item[1] for item in filter(lambda x: ((x[2] &lt; x[1] &gt...
python|pandas|dataframe
1
376,631
50,004,616
Special Moving Average
<p>I want to predict the direction towards which the price will change. The term price is used to refer to the mid-price of a stock, which is defined as the mean between the best bid price and best ask price at time t: </p> <p><a href="https://i.stack.imgur.com/AvuIN.png" rel="nofollow noreferrer"><img src="https://i....
<pre><code>def moving_average(df, col_name='Price', k=3): ma_cols = [] mb_cols = [] temp_df = DataFrame() for i in range(0, k+1): ma_col = 'M_A_{}'.format(i) ma_cols.append(ma_col) mb_col = 'M_B_{}'.format(i) mb_cols.append(mb_col) temp_df[ma_col] = df[col_name]....
python|pandas
0
376,632
50,106,611
Convert list of dictionaries containing another list of dictionaries to dataframe
<p>I tried to look for the solution and I am unable to get 1. I have the following output from an api in python.</p> <pre><code>insights = [ &lt;Insights&gt; { "account_id": "1234", "actions": [ { "action_type": "add_to_cart", "value": "8" }, { "actio...
<p>This is one solution.</p> <pre><code>df = pd.DataFrame(insights) parts = [pd.DataFrame({d['action_type']: d['value'] for d in x}, index=[0]) if x == x else pd.DataFrame({'add_to_cart': [np.nan], 'purchase': [np.nan]}) for x in df['actions']] df = df.drop('actions', 1)\ .join(pd.concat(par...
python|pandas|dictionary|dataframe
4
376,633
50,200,303
how to plot attention vector on tensorboard graph
<p>Attention vector for sequence 2 sequence model is basically a array of shape [batch_size, time_step,1], which indicates the weighs of a particular time step. </p> <p>But if I use <code>tf.summary.histogram</code> to show it on tensorboard, tensorflow will only show the distributions of weights, I can't tell the whi...
<p>Tensorboard does not currently support visualizing tensor summaries. There is a <a href="https://www.tensorflow.org/api_docs/python/tf/summary/tensor_summary" rel="nofollow noreferrer">summary op</a> for it, but Tensorboard will just skip it when reading summaries from disk at the moment. I am also not aware of any ...
tensorflow|tensorboard
0
376,634
49,949,428
apply mask on np.array in pandas
<p>I have a <code>pd.DataFrame</code> containing a mask and <code>np.array</code>. I want to apply the mask on the array (like I would do with <code>np.where</code>)</p> <p>Does anyone have an idea how to succeed ?</p> <pre><code>df = pd.DataFrame({'Mask' : [[True, False, True], [False, False], [True, True]], ...
<p>You could just create a mask by using <code>df.Mask</code>, pass it to the <code>mask()</code> function of the data frame and aggregate.</p> <p>This would be the "<em>one-liner</em>":</p> <pre><code>pd.DataFrame(df.Array.tolist())\ .mask(np.asarray(df.Mask.tolist()))\ .agg(['mean', 'std', 'min', 'max']) </...
python|pandas|numpy
2
376,635
49,900,798
How to limit RAM usage while batch training in tensorflow?
<p>I am training a <em>deep neural network</em> with a <em>large image dataset</em> in mini-batches of size 40. My dataset is in <code>.mat</code> format (which I can easily change to any other format e.g. <code>.npy</code> format if necessitates) and before training, loaded as a 4-D <code>numpy</code> array. My proble...
<p>Loading a big dataset in memory is not a good idea. I suggest you to use something different for loading the datasets, take a look to the dataset API in TensorFlow: <a href="https://www.tensorflow.org/programmers_guide/datasets" rel="nofollow noreferrer">https://www.tensorflow.org/programmers_guide/datasets</a></p> ...
python|tensorflow|training-data
3
376,636
49,972,651
How to combine multiple columns from a pandas df into a list
<p>How can you combine multiple columns from a dataframe into a list? </p> <p>Input:</p> <pre><code>df = pd.DataFrame(np.random.randn(10000, 7), columns=list('ABCDEFG')) </code></pre> <p>If I wanted to create a list from column A I would perform:</p> <pre><code>df1 = df['A'].tolist() </code></pre> <p>But if I want...
<p>Is this what you are looking for</p> <pre><code>lst = df.values.tolist() flat_list = [item for x in lst for item in x] print(flat_list) </code></pre>
python|list|pandas
0
376,637
50,036,888
How to get all possible slices of a 1D numpy array depending on input
<p>I have a numpy array</p> <pre><code>a = np.arange(12) &gt;&gt;&gt; [0,1,2,3,4,5,6,7,8,9,10,11] </code></pre> <p>I am trying to calculate all possible cumsums like this</p> <pre><code>np.cumsum[2:] + np.cumsum[:-2] np.cumsum[3:] + np.cumsum[:-3] ... np.cumsum[11:] + np.cumsum[:-11] </code></pre> <p>How can I achi...
<p>It is not what you asked for. But if you are looking for a simpler solution , you can use the pandas approach. </p> <pre><code>df = pd.DataFrame({'a' :np.arange(11)}) # your data window_lengths = np.arange(2,len(a)) # define window lengths from 2 to n [rolling_win.mean() for rolling_win in [df.rolling(length) f...
python|python-3.x|numpy
1
376,638
50,146,655
when to use square brackets and when to use parentheses?
<p>Do we have any difference between </p> <pre><code>a = np.array([1,2,3]) </code></pre> <p>and</p> <pre><code>a = np.array((1,2,3))? </code></pre> <p>With both inputs, I am getting the following output when I try this:</p> <pre><code>print(a) print(a.ndim) print(a.shape) print(type(a)) </code></pre> <p>output</p...
<p>Square brackets <code>[1,2,3]</code> make a <code>list</code>. Round brackets <code>(1,2,3)</code> make a <code>tuple</code>. The main difference is that a list can be resized and modified, whereas a tuple is immutable.</p> <p>There is no practical difference in anonymous expressions like <code>np.array([1,2,3])<...
arrays|python-3.x|list|numpy|tuples
0
376,639
49,846,461
Extracting data from pandas based on condition
<p>I have a data frame <code>A = [1,2,3,5,9,8,11,13] and B = [2,1,6,19,16,15,14,12]</code>. I want to is check is <em>whether the criss cross elements of the A and B are equal in any case</em></p> <p>For eg: here <code>A[0]==B[1] and B[0]==A[1]</code>, this is a criss cross element.</p> <pre><code>import pandas as p...
<h2>Compare contiguous columns</h2> <p>In order to check wheter or not <code>A[i]==B[i+1] &amp; A[i+1]==B[i]</code> for all the rows in the dataframe, you can compare the colums vectorially but shifted:</p> <pre><code>A = np.array([1,2,3,5,14,16,16,13]) # I mdified input data from the question for the second example ...
python|pandas|loops|indexing
0
376,640
50,178,925
Convert nested dictionary of lists into pandas dataframe efficiently
<p>I have a json object such that</p> <pre><code>{ "hits": { "hits": [ { "_source": { "TYPES": [ { "_ID": 130, "_NM": "ARB-130" }, { "_ID": 131, ...
<p>One way is to restructure your dictionary and flatten using <code>itertools.chain</code>.</p> <p>For performance, you should benchmark with your data.</p> <pre><code>from itertools import chain res = list(chain.from_iterable(i['_source']['TYPES'] for i in d['hits']['hits'])) df = pd.DataFrame(res) print(df) ...
python|pandas|dictionary|dataframe
2
376,641
50,109,667
Python: Running function to append values to an empty list returns no values
<p>This is probably a very basic question but I haven't been able to figure this out.</p> <p>I'm currently using the following to append values to an empty list</p> <pre><code>shoes = {'groups':['running','walking']} df_shoes_group_names = pd.DataFrame(shoes) shoes_group_name=[] for type in df_shoes_group_names['gr...
<p>You should <strong>never</strong> call or search a variable name as if it were a string.</p> <p>Instead, use a dictionary to store a variable number of variables.</p> <p><strong>Bad practice</strong></p> <pre><code># dataframes df_shoes_group_names = pd.DataFrame(...) df_boots_group_names = pd.DataFrame(...) df_s...
python|pandas|loops|for-loop
1
376,642
64,162,672
How to randomly set a fixed number of elements in each row of a tensor in PyTorch
<p>I was wondering if there is any more efficient alternative for the below code, without using the &quot;for&quot; loop in the 4th line?</p> <pre><code>import torch n, d = 37700, 7842 k = 4 sample = torch.cat([torch.randperm(d)[:k] for _ in range(n)]).view(n, k) mask = torch.zeros(n, d, dtype=torch.bool) mask.scatter_...
<p>Here's a way to do this with no loop. Let's start with a random matrix where all elements are drawn iid, in this case uniformly on [0,1]. Then we take the k'th quantile for each row and set all smaller or equal elements to True and the rest to False on each row:</p> <pre><code>rand_mat = torch.rand(n, d) k_th_quant ...
pytorch
4
376,643
64,037,243
Python:how to split column into multiple columns in a dataframe and with dynamic column naming
<p>i have a sample dataset</p> <pre><code>id value [10,10] [&quot;apple&quot;,&quot;orange&quot;] [15,67] [&quot;banana&quot;,&quot;orange&quot;] [12,34,45] [&quot;apple&quot;,&quot;banana&quot;,&quot;orange&quot;] </code></pre> <p>i want to convert this into</p> <pre><code>id1 id2 id3 ...
<p>We can reconstruct your data with <code>tolist</code> and <code>pd.DataFrame</code>. Then <code>concat</code> everything together again:</p> <pre><code>d = [pd.DataFrame(df[col].tolist()).add_prefix(col) for col in df.columns] df = pd.concat(d, axis=1) id0 id1 id2 value0 value1 value2 0 10 10 NaN a...
python|pandas|numpy|dataframe
3
376,644
64,129,235
Plot Multiple Y axis + 'hue' scatterplot in python
<p>Dataframe</p> <pre><code>df Sample Type y1 y2 y3 y4 S1 H 1000 135 220 171 S2 H 2900 1560 890 194 S3 P 678 350 127 255 S4 P 179 510 154 275 </code></pre> <p>I want to plot <code>y1</code>, <code>y2</code>, <code>y3</code>, <code>y4</code> vs <code>Sample</code> scat...
<p>Since, you want just one plot you can use <a href="https://seaborn.pydata.org/generated/seaborn.scatterplot.html" rel="nofollow noreferrer"><code>sns.scatterplot</code></a>:</p> <pre><code>import pandas as pd import seaborn as sns import matplotlib.pyplot as plt #df = pd.read_csv('yourfile.csv') #plotting df1 = df...
python|pandas|plot|hue
4
376,645
64,001,892
Group by and assign it to intermediate groups in python pandas
<p>I have the pandas dataframe in the below format. For every group in col1, I am trying to compute the average of 'price' and assign it to the same group but for year '2015'(in Result dataframe below). That result has to be added to the original dataframe.</p> <p>I have tried this but not sure how to assign the interm...
<p>You can do <code>append</code> after <code>groupby</code> <code>assign</code></p> <pre><code>df = df.append(df.groupby('col1').agg({'col1':'first', 'price':'mean'}).assign(year=2015).reset_index(drop=True),sort=True) </code></pre>
python|pandas
1
376,646
64,039,003
extract certain words from column in a pandas df
<p>I have a pandas df in which one column is the message and having a string and have data like below:-</p> <p>df['message']</p> <pre><code>2020-09-23T22:38:34-04:00 mpp-xyz-010101-10-103.vvv0x.net patchpanel[1329]: RTP:a=end pp=10.10.10.10:9999 user=sip:.F02cf9f54b89a48e79772598007efc8c5.@user.com;tag=2021005845 lport...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.extract.html" rel="nofollow noreferrer">series.str.extract</a></p> <pre><code>df['raddr'] = df['message'].str.extract(r'raddr=([\d\.]*)') # not tested </code></pre> <p>The pattern has only one capturing group with the value after the...
python|python-3.x|pandas|dataframe
2
376,647
64,159,078
Classify and Restore data in python
<p>I have a dataset in which resides in a 13 by 506 matrix, let's call the data set data_1. I am interested in one of the columns data, lets call that data column data_c1. Data_c1 is numeric, so the 50th percentile can be calculated with the numpy library.</p> <p>My goal is to go through data_c1, do a binary classifica...
<p>You can apply a function like this:</p> <pre><code>def classifier(row): global t50 #defined somewhere else if row[&quot;data_c1&quot;] &gt; t50: return 1 else: return 0 new_col = df.apply(classifier, axis=1) </code></pre> <p>Then you can do whatever...
python|numpy|classification
0
376,648
63,766,688
Pandas - Understanding how rolling averages work
<p>So I'm trying to calculate rolling averages, based on some column and some groupby columns. In my case:</p> <p>rolling column = RATINGS,</p> <p>groupby_columns = [&quot;DEMOGRAPHIC&quot;,&quot;ORIGINATOR&quot;,&quot;START_ROUND_60&quot;,&quot;WDAY&quot;,&quot;PLAYBACK_PERIOD&quot;]</p> <p>one group of my data looks ...
<blockquote> <p>np.mean([178,479,72,272,158,37,85.5,159,107,<strong>164.55</strong>]) = 171.205</p> </blockquote> <p>Where does the 164.55 come from? The rest of those values are from the &quot;RATINGS&quot; column and the 164.55 is from the &quot;rolling&quot; column. Maybe I am misunderstanding what the <code>rolling...
python|pandas|rolling-computation
1
376,649
64,081,034
Combining different dataframes columns into new dataframe and bonus filtering question
<p>Im trying to create a new dataframe from two other dataframes and I think the indexing is messing me up. Might be a chaining operations issue from what I have been reading, but the answer I am seeing is to use iloc which I did but am still seeing the error.</p> <p>I have original dataframe sorted by date index</p> <...
<p>Try</p> <pre><code>newer['new_close'] = df_inc_11.close.values </code></pre>
python|pandas
1
376,650
64,061,470
Better way of concatenating multiple for loops in a dataframe
<p>So I have a dataframe with quite a few columns and I am running multiple for loops to create variable to be used in my desired function. Is there a better(concatenated format) way/format to run these loops?</p> <pre><code>for x in df['A']: L = x for y in df['B']: M = y for w in df['C']: N = w for v in...
<p>You can create numpy array by seelcting columns by list and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html" rel="nofollow noreferrer"><code>DataFrame.to_numpy</code></a>:</p> <pre><code>for L,M,N,O in df[['A','B','C','D']].to_numpy(): print (L, M, N, O) </...
python|pandas|dataframe
3
376,651
63,920,408
Identify first row amongst similar set of data from pandas dataframe
<p>I have a dataframe similar to the one shown below:</p> <pre><code> BillNumber Description LineAmount TotalAmount 0 INV001 Line Item 1 of INV001 500 700 1 INV001 Line Item 2 of INV001 200 700 2 INV002 Line Item 1 of INV002 100 800 3 INV002 Line Ite...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.duplicated.html" rel="nofollow noreferrer"><code>Series.duplicated</code></a>:</p> <pre><code>df...
python|pandas
4
376,652
63,765,472
Pivot table to Pivot table, by swapping indexes and columns
<p>supposed my dataset</p> <pre><code>Name Month Value A 1 120 A 3 130 A 5 140 B 1 80 B 2 110 B 4 90 C 1 150 C 4 120 C 5 190 D 1 100 D 2 105 .... </code></pre> <p>As shown i...
<p>After impute the value try</p> <pre><code>df_pivot1 = df_pivot1.T </code></pre>
python|pandas|pivot
2
376,653
64,015,762
How to convert a dataframe to tidy form (unpivot)?
<p>I have the following dataframe <code>df = pd.read_excel('...')</code>:</p> <pre><code>Date Id V1 V2 V3 2020-1-1 1 10 100 NaN 2020-1-1 2 20 120 23 2020-1-1 3 11 101 NaN </code></pre> <p>I need to transform it to</p> <pre><code>Date Name Value 2020-1-1 1_V1 10 2020-1-1 1_V2 100 2020-1-1 2_V1 ...
<p>Let us try <code>melt</code></p> <pre><code>s = df.melt(['Date','Id']).dropna() s['name'] = s.pop('variable') +'_'+ s.pop('Id').astype(str) s Date value name 0 2020-1-1 10.0 V1_1 1 2020-1-1 20.0 V1_2 2 2020-1-1 11.0 V1_3 3 2020-1-1 100.0 V2_1 4 2020-1-1 120.0 V2_2 5 2020-1-1 101.0 V2_3 ...
python|pandas|dataframe
2
376,654
64,117,751
Convert c-order index into f-order index in Python
<p>I am trying to find a solution to the following problem. I have an index in C-order and I need to convert it into F-order.</p> <p><strong>To explain simply my problem, here is an example:</strong></p> <hr /> <p>Let's say we have a matrix <code>x</code> as:</p> <pre><code>x = np.arange(1,5).reshape(2,2) print(x) arr...
<p>We can use a combination of <a href="https://numpy.org/doc/stable/reference/generated/numpy.ravel_multi_index.html" rel="nofollow noreferrer"><code>np.ravel_multi_index</code></a> and <a href="https://numpy.org/doc/stable/reference/generated/numpy.unravel_index.html" rel="nofollow noreferrer"><code>np.unravel_index<...
python|numpy
2
376,655
64,042,328
Is convolution useful on a network with a timestep of 1?
<p>This code comes from <a href="https://www.kaggle.com/dkaraflos/1-geomean-nn-and-6featlgbm-2-259-private-lb" rel="nofollow noreferrer">https://www.kaggle.com/dkaraflos/1-geomean-nn-and-6featlgbm-2-259-private-lb</a>, The goal of this competition is to use seismic signals to predict the timing of laboratory earthquake...
<p><strong>1) Assuming you would input a sequence to the LSTM (the normal use case):</strong></p> <p>It would not be the same since the LSTM returns a sequence (<code>return_sequences=True</code>), thereby not reducing the input dimensionality. The output shape is therefore <code>(Batch, Sequence, Hid)</code>. This is ...
python|tensorflow|keras|neural-network|conv-neural-network
1
376,656
63,993,846
Matching values of a dict with the values of two columns of a dataframe and substituting the value of a third column with the key of the dict
<p>I have a pandas dataframe like this:</p> <pre><code>Index | Line Item | Insertion Order | Creative Type _________________________________________________________________________________________________ 1 | blbl 33 dEs '300x600' Q3 | hello 444 ...
<p>Create a <strong>replacement</strong> dictionary by inverting the key-value pairs of given <code>dict</code> i.e for each value in the list map it to its corresponding key, then using <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.replace.html" rel="nofollow noreferrer"><code>Series.replace</cod...
python|pandas|dataframe|dictionary
1
376,657
63,939,064
Shuffle a square numpy array, but retain correspondence between row and column indices
<p>If I have a square <em>and symmetric</em> matrix, for example,</p> <pre><code>[[0 3 2] [3 8 4] [2 4 5]] </code></pre> <p>I do not want to shuffle rows only or columns only. instead,</p> <p>how can I, <em>for example</em> (not the following in the strict order as written, but instead at random):</p> <ul> <li>shuffl...
<p>What you are asking for can be done with so-called matrix conjugation:</p> <pre><code>perm_mat = np.random.permutation(np.eye(len(a),dtype=np.int)) out = (perm_mat @ a) @ (np.linalg.inv(perm_mat)) </code></pre> <p>Output (random of course):</p> <pre><code>array([[8., 4., 3.], [4., 5., 2.], [3., 2., 0....
arrays|numpy|matrix|shuffle
2
376,658
63,990,338
Masked object disapear when converting image from float32 into uint8
<p>Bellow is the following mask showing the detected object by using histogram back projection</p> <p><a href="https://i.stack.imgur.com/5EfNk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5EfNk.png" alt="float" /></a></p> <p><strong>The image has the type float32 which results from the algorithm's...
<p>You are not scaling up the values of the image pixels before converting to int, this is the reason why you are facing error.</p> <p>Do this:</p> <pre class="lang-py prettyprint-override"><code>imageFloat *= 255 imageFloat.astype(np.uint8) </code></pre>
python|numpy|opencv|image-processing|mask
3
376,659
63,974,864
DataFrames - Average Columns
<p>I have the following dataframe in pandas</p> <pre><code>Column 1 Column 2 Column3 Column 4 2 2 2 4 1 2 2 3 </code></pre> <p>I am looking to create a dataframe which contains averages of columns 1&amp; 2, Columns 3 &amp;4, and so on.</p> <pre><code> Colu...
<p>You an do <code>groupby</code> with <code>axis</code> and pass the list</p> <pre><code>out = df.groupby([1,1,2,2],axis=1).mean() 1 2 0 2.0 3.0 1 1.5 2.5 </code></pre>
python|pandas|numpy|dataframe
2
376,660
64,050,235
Pandas - fillna with mean for specific categories
<p>I'd like to fillna with the mean number for the column but only for representatives of the same category as the missing value</p> <pre><code>data = {'Class': ['Superlight', 'Aero', 'Aero', 'Superlight', 'Superlight', 'Superlight', 'Aero', 'Aero'], 'Weight': [5.6, 8.6, np.nan, 5.9, 5.65, np.nan, 8.1, 8.4]} ...
<p><code>groupby + transform</code> and then fillna:</p> <pre><code>df['Weight'].fillna(df.groupby(&quot;Class&quot;)['Weight'].transform(&quot;mean&quot;)) </code></pre> <hr /> <pre><code>0 5.600000 1 8.600000 2 8.366667 3 5.900000 4 5.650000 5 5.716667 6 8.100000 7 8.400000 Name: Weight, dtype...
python|pandas|fillna
9
376,661
63,833,249
ValueError: Must pass DataFrame with boolean values only - When converting Pandas Columns to Numeric
<p>I'm trying to convert these columns to numeric but I get this error, and haven't found much of anything on it for this specific use case on Google or Stack Overflow:</p> <pre><code>ValueError: Must pass DataFrame with boolean values only </code></pre> <p>df:</p> <pre><code> 5 6 7 8 9 10 11 0 0 0 ...
<p>If you want to convert all the columns to numeric you can use</p> <pre><code>df = df.astype(int) </code></pre> <p>If you want to convert specific columns to numeric you can pass the dictionary in astype.</p> <pre><code>convert_dict = {'A': int, 'C': float } df = df.astype(convert_...
python|pandas
1
376,662
64,089,038
How can I pivot a really large dataframe using dask?
<p>I have a Dask dataframe that I load like this:</p> <pre class="lang-py prettyprint-override"><code>dates_devices = dd.read_csv('data_part*.csv.gz', compression='gzip', blocksize=None) dates_devices['cnt'] = 1 dates_devices.astype({'cnt': 'uint8'}).dtypes # make it smaller </code></pre> <p>I'm trying to use dask to ...
<p>You can can try writing your dask dataframes in chunks to overcome the memory limitation: For example:</p> <pre><code>for i in range(final_table.npartitions): partition = final_table.get_partition(i)` </code></pre> <p>Please see how I do <code>.to_sql</code> -- you can take a similar approach with <code>.to_parq...
python|pandas|dask
1
376,663
63,959,950
How to filter a pandas dataframe and then groupby and aggregate a list of values?
<p>I'm trying to use groupby and get values as a list.</p> <p>End df should be &quot;bid&quot; as index, score as list for second column (ex. [85, 58] if they both have the same &quot;bid&quot;]</p> <p>This is my df:</p> <p><a href="https://i.stack.imgur.com/rJjyG.png" rel="nofollow noreferrer"><img src="https://i.stac...
<ul> <li>Aggregate <code>list</code> onto <code>score_y</code> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.aggregate.html" rel="nofollow noreferrer"><code>pandas.DataFrame.aggregat</code></a></li> <li>Depending on <code>merged</code>, the index may need to be reset.</li> </...
python|pandas|group-by|apply
1
376,664
64,157,389
Filter NaN values in Tensorflow dataset
<p><strong>Is there an easy way to filter all entries containing a <code>nan</code> value from a <code>tensorflow.data.Dataset</code> instance? Like the <code>dropna</code> method in Pandas?</strong></p> <hr /> <p>Short example:</p> <pre><code>import numpy as np import tensorflow as tf X = tf.data.Dataset.from_tensor_...
<p>I had a slightly different approach than the existing answer. Rather than using sum, I'm using <code>tf.reduce_any</code>:</p> <pre><code>filter_nan = lambda x, y: not tf.reduce_any(tf.math.is_nan(x)) and not tf.math.is_nan(y) ds = tf.data.Dataset.zip((X,y)).filter(filter_nan) list(ds.as_numpy_iterator()) </code><...
python|tensorflow|tensorflow2.0|tensorflow-datasets
3
376,665
64,122,003
add color to certian cells in excel via pandas - python
<p>I want to add a highlight specific cells in a <strong>CSV</strong> file using the <strong>highlight_special</strong> function the code runs in the terminal with no exceptions but when I look at the <strong>CSV</strong> it stays the same</p> <p>the code takes a csv file runs it to see if there are any words with spec...
<p>When you call <code>highlight_special()</code>, <code>siders</code> is still empty. You have to call your method <code>special()</code>before.</p> <p><code>highlight_special</code> also misused (see <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html" rel="nofollow noreferrer">here</a>), and ...
python|excel|pandas|csv|cell
0
376,666
64,161,106
How to plot a histogram to get counts for all unique values?
<p>I have a Pandas column with data unique to .0001</p> <p>I would like to plot a histogram that has a bar for each unique .0001 of data.</p> <p>I achieve a lot of granularity by</p> <pre><code>plt.hist(df['data'], bins=500) </code></pre> <p>but I would like to see counts for each unique value.</p> <p>How would I go ab...
<p>As your values are discrete, it is important to set the bin boundaries nicely in-between these values. If the boundaries coincide with the values, strange rounding artifacts can happen. The example below has each value 10 times, but the histogram with the boundaries on top of the values puts the last two values into...
python|pandas|matplotlib
2
376,667
64,139,658
Memory leak with Keras Lambda layer
<p>I need to split the channels of a Tensor to apply different normalizations for each split. To do so, I use the Lambda layer from Keras:</p> <pre><code># split the channels in two (first part for IN, second for BN) x_in = Lambda(lambda x: x[:, :, :, :split_index])(x) x_bn = Lambda(lambda x: x[:, :, :, split_index:])(...
<p><a href="https://stackoverflow.com/users/9794742/thibault-bacqueyrisses">Thibault Bacqueyrisses</a> answer was right, the memory leak disappeared with a custom layer!</p> <p>Here is my implementation:</p> <pre><code>class Crop(keras.layers.Layer): def __init__(self, dim, start, end, **kwargs): &quot;&quo...
python|tensorflow|keras|memory-leaks
4
376,668
63,929,796
Can't append to an existing table. Fails silently
<p>I'm trying to dump a pandas DataFrame into an existing Snowflake table (via a jupyter notebook). When I run the code below no errors are raised, but no data is written to the destination SF table (df has ~800 rows).</p> <pre><code>from sqlalchemy import create_engine from snowflake.sqlalchemy import URL sf_engine =...
<p>Try adding <code>role=&quot;&lt;role&gt;&quot;</code> and <code>schema=&quot;&lt;schema&gt;&quot;</code> in URL.</p> <pre><code>engine = create_engine(URL( account=os.getenv(&quot;SNOWFLAKE_ACCOUNT&quot;), user=os.getenv(&quot;SNOWFLAKE_USER&quot;), password=os.getenv(&quot;SNOWFLAKE_PASSWORD...
python|pandas|sqlalchemy|snowflake-cloud-data-platform
0
376,669
64,022,247
Matplotlib Time-Series Heatmap Visualization Row Modification
<p>Thank you in advance for the assistance!</p> <p>I am trying to create a heat map from time-series data and the data begins mid year, which is causing the top of my heat map to be shifted to the left and not match up with the rest of the plot (Shown Below). How would I go about shifting the just the top line over so ...
<p>Now, what its the problem, the dates on the dataset, if you see the Dataset this start on</p> <pre><code>`1990-4-24,15.533` </code></pre> <p>To solve this is neccesary to add the data between 1990/01/01 -/04/23 and delete the 29Feb.</p> <pre><code>rng = pd.date_range(start='1990-01-01', end='1990-04-23', freq='D') d...
python|pandas|numpy|dataframe|matplotlib
2
376,670
64,071,574
Why isn't SchemaGen supported in tfdv.display_schema()?
<p>Regarding TFX' tensorflow-data-validation, I'm trying to understand when I should use *Gen components vs. using TFDV provided methods.</p> <p>Specifically, what's confusing me is that I have this as my ExampleGen:</p> <pre><code>output = example_gen_pb2.Output( split_config=example_gen_pb2.SplitConfig(split...
<p>I'm also new to TFX. Your post about the <code>ExampleValidator</code> helped me out, hopefully this answers your question.</p> <p><strong>Using components only to visualize schema</strong></p> <pre><code> statistics_gen = StatisticsGen( examples=example_gen.outputs['examples'], exclude_splits=['eval'] ) context...
tensorflow2.0|tfx|tensorflow-data-validation
2
376,671
63,838,762
How to plot parallel coordinae plot ftrom Hyperparameter Tuning with the HParams Dashboard?
<p>I am trying to replicate the parallel coordinate plot form Hyperparameter Tuning tutorial in this Tensorflow <a href="https://www.tensorflow.org/tensorboard/hyperparameter_tuning_with_hparams" rel="nofollow noreferrer">tutorial</a> and I have writen my own csv file where I store my results. My output reading the cs...
<p>so I found the answer using plotly</p> <pre><code>import os import sys import pandas as pd from plotly.offline import init_notebook_mode, iplot import plotly.graph_objects as go init_notebook_mode(connected=True) df = pd.read_csv('path/to/csv') fig = go.Figure(data= go.Parcoords( line = dict(color = d...
tensorboard|tensorflow-serving|hyperparameters
0
376,672
63,988,743
How to draw multiple line plots in a grid?
<p>I have a dictionary whose values are consisted of dataframes. Every <code>df</code> has the same column names: <code>X1</code> and <code>X2</code>:</p> <pre><code>dic = {&quot;a&quot;: df1, &quot;b&quot;: df2, ..., &quot;y&quot;: df25} </code></pre> <p>Now I want to draw line plots of these dataframes so that they w...
<p>The basic idea using <a href="https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.subplots.html" rel="nofollow noreferrer"><code>matplotlib.pyplot.subplots</code></a>:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt fig, axes = plt.subplots(5, 5) for ax, (key, df) in zip(...
python|pandas|dataframe|line-plot
1
376,673
63,917,203
Find least frequent value in whole dataframe
<p>my dataframe is something like this</p> <pre><code>&gt; 93 40 73 41 115 74 59 98 76 109 43 44 105 119 56 62 69 51 50 104 91 78 77 75 119 61 106 105 102 75 43 51 60 114 91 83 </code></pre> <p>It has 8000 rows and 12 columns</p> <p>I wanted to find the least frequent value in this whol...
<p>You could <code>stack</code> and take the <code>value_counts</code>:</p> <pre><code>df.stack().value_counts().index[-1] # 69 </code></pre> <p><code>value_counts</code> orders by frequency, so you can just take the last, though in this example many appear just once. <code>69</code> happens to be the last.</p>
python|pandas|numpy|scipy
4
376,674
63,861,019
Fusion of multiple 3D binary arrays in python
<p>I am looking for an efficient way to fuse multiple (N) binary 3D arrays of the same shape. I.e. the resulting fused array should have for each coordinate a value that is obtained by a majority vote among all values at the corresponding coordinate of the N arrays.</p> <p>E.g. a toy 1D case:</p> <pre><code>[0,0,1] - 1...
<p>You can use <code>scipy.stats.mode</code>, which will take an array of your 3D arrays as input. An example with 2D arrays is:</p> <pre><code>arrs = [[[0,1,0],[0,0,0]], [[1,1,0],[0,0,1]], [[1,0,1],[1,0,0]]] scipy.stats.mode(arrs).mode &gt;&gt;&gt; array([[[1, 1, 0], [0, 0, 0]]]) </code></pre>
python|numpy|matrix|numpy-ndarray
0
376,675
64,072,274
Panda's DataFrame dump to CSV file is not decoding values correctly. It has Bytea data as columns
<p>I have a complex table structure in the Database, which I am reading Panda's DataFrame. While printing DataFrame everything is printing correctly but when I dump in CSV or convert it to a list (each of DataFrame row as list) I see the following data at few columns: &lt;memory at 0x11a2c4640&gt;</p> <p>After debuggin...
<p>Try to save the csv with an special encoding:</p> <p><code>df.to_csv(r&quot;C:\your path\ file.csv, index =True, encoding='utf-8-sig')</code></p>
pandas|postgresql|dataframe|export-to-csv|bytea
0
376,676
64,089,984
Day of the month split on Python pandas dictionary
<p>I have the following list of stocks:</p> <p><a href="https://i.stack.imgur.com/3NLnm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3NLnm.png" alt=" " /></a></p> <p>For each one I would like to separate by day of month as this explanatory drawing:</p> <p><a href="https://i.stack.imgur.com/t2YNO.p...
<p>You can use <code>pandas.groupby</code> and use <code>datetime.date()</code> as the grouping field. Then you can use <code>sum</code> operator on the group object to calculate daily return. This <a href="https://stackoverflow.com/questions/24082784/pandas-dataframe-groupby-datetime-month/24083253">post</a> shows usi...
python|pandas|dictionary
0
376,677
64,070,760
Getting memory error while transforming spars matrix to array with column names. This array is input to training model
<p>My training data consists of 5 million rows of product description having average length of 10 words. I can use either CountVectorizer or Tf-IDF to transform my input feature. However, post transforming the feature to a sparse matrix, while converting it to an array or dense array, I am constantly getting memory err...
<p>Out of memory error happens when python is using more memory than available. Along with your system memory, look at your graphics card memory if you are using tensorflow-gpu. You might want to take a look at google colab, which runs the python program in the cloud.</p>
python|tensorflow|out-of-memory
0
376,678
63,746,101
Multiply each value in a pandas dataframe column with all values of 2nd dataframe column & replace each 1st dataframe value with resulting array
<p>I have a dataframe with 4 rows and 3 columns, and all values in this first dataframe (df1) are floats. I also have a second dataframe (df2) that has a column with 8760 entries. I would like to multiply each value in column 3 of the first dataframe by all 8760 values in the second dataframe. Finally, I want to replac...
<p>The following single line of could will fetch you the desired result:</p> <pre><code>df1['col3'] = df1['col3'].apply(lambda x: df2.values[0]*x) </code></pre> <p>Here, the values of column 'col3' are treated as a single value multiplied by the entire DataFrame df2 for each row of the df1.</p>
python|pandas|dataframe
0
376,679
63,825,146
Fastest way to solve an array or list of functions with fsolve
<p>I have the working function below. I have a function from which I calculate the first and second derivative. I then need to find the value of theta where the first derivative is zero and second one is negative. I have to compute this for a large number of points. The number of points is equal to the length of K1 and...
<p>The best thing is to try and process the equation symbolically as much as possible in terms of symbolic parameters. It is possible to get an analytic solution for e.g. <code>first_derivative</code> but you need to transform it a bit. Here I'll rewrite sin/cos as exp and then use the substitution <code>exp(I*theta/2)...
python|numpy|scipy|sympy
2
376,680
64,022,364
How to do group by 2 column and performe count in pandas
<p>How to performe count like this query in pandas?</p> <pre><code>Select col1, col2, count(col3) as total from table GROUP by col1,col2 </code></pre>
<p>You want the pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer">groupby</a> method:</p> <pre><code>df2 = df.groupby(['col1', 'col2'], as_index = False).count() </code></pre> <p>This will give you a count of all your other columns. If yo...
python|pandas
1
376,681
64,159,067
Pandas MySQL exception don't shows
<p>I have this code for connect to MySQL through a SSH, inside of a python class:</p> <pre><code>def executeQuery(self, query_string): print(&quot;connecting to database &quot; + self.sql_main_database) with SSHTunnelForwarder( ( self.ssh_host, self.ssh_port), ssh...
<p>Indeed the problem was not on the connector, just updating the jupyter version was needed.</p>
mysql|pandas|ssh|jupyter-notebook
-1
376,682
64,051,457
Using df.apply on a function with multiple inputs to generate multiple outputs
<p>I have a dataframe that looks like this</p> <pre><code>initial year0 year1 0 0 12 1 1 13 2 2 14 3 3 15 </code></pre> <p>Note that the number of year columns year0, year1... (year_count) is completely variable but will be constant throughout this code</p> <p>I first wanted to a...
<p>IMHO, it's better with a simple <code>for</code> loop:</p> <pre><code>for i in range(2): df[f'val{i}'] = sum_and_scale(df[f'year{i}'], df[f'mod{i}'], scale=10) </code></pre>
python|pandas
0
376,683
63,984,312
How to make a simple Vandermonde matrix with numpy?
<p>My question is how to make a vandermonde matrix. This is the definition: In linear algebra, a Vandermonde matrix, named after Alexandre-Théophile Vandermonde, is a matrix with the terms of a geometric progression in each row, i.e., an m × n matrix</p> <p>I would like to make a 4*4 version of this.</p> <p>So farI hav...
<p>Given a starting column <code>a</code> of length <code>m</code> you can create a Vandermonde matrix <code>v</code> with <code>n</code> columns <code>a**0</code> to <code>a**(n-1)</code>like so:</p> <pre><code>import numpy as np m = 4 n = 4 a = range(1, m+1) v = np.array([a]*n).T**range(n) print(v) #[[ 1 1 1 1] ...
numpy|matrix|numpy-ndarray
2
376,684
64,141,458
Using the Pandas query function and testing if a string is in a column containing lists
<p>I have a DataFrame where one column contains lists e.g.:</p> <pre><code>columnA -------- [val1, val2] [val1, val3] ... </code></pre> <p>I want to use the <code>df.query()</code> syntax to return only rows where a given value exists in the array. But am getting errors, I'm trying things like:</p> <p><code>df.query('&...
<p>I did not use &quot;query&quot; but I think this can help you. You can change the value so I think having a function is a good idea.</p> <pre><code>import pandas as pd df = pd.DataFrame({'columnA': [[1, 4], [1, 2], [3, 4], [6, 2], [0, 10] ,[2, 8]]}) def check(data, value): temp_df = [] for i in range(len(data...
python|pandas
1
376,685
63,793,319
Split column of strings by list of possible substrings
<p>I have a column with text that contains subheadings, such as '1. DESCRIPTION', '2. FOO', etc. I have all the possible subheadings in a list, but the issue is that not every entry in the column contains every subheading. I want to add columns to the df for every possible subheading and add the corresponding text afte...
<p>I tried a solution with some regex</p> <pre><code>df = pd.DataFrame([ {&quot;Text&quot;: '1. Description: example description here. 3. BAR: more text'}, {&quot;Text&quot;: '1. Description: second example. 2. FOO: a foo'} ]) # regex to capture the columns names reg_key = re.compile(&quot;([A-Za-z]*)\:&quot;)...
python|pandas
1
376,686
64,165,983
What is the fastest way to find the average for a list of tuples in Python, each tuple containing a pair of namedtuples?
<pre class="lang-py prettyprint-override"><code>import numpy as numpy from collections import namedtuple from random import random Smoker = namedtuple(&quot;Smoker&quot;, [&quot;Female&quot;,&quot;Male&quot;]) Nonsmoker = namedtuple(&quot;Nonsmoker&quot;, [&quot;Female&quot;,&quot;Male&quot;]) LST = [(Smoker(rando...
<p><code>np.mean</code> has to convert the list to an array, which takes time. Python <code>sum</code> saves time:</p> <pre><code>In [6]: %%timeit ...: grizzly = Smoker(np.mean([a.Female for a,b in LST]),np.mean([a.Male for ...: a,b in LST])) ...: panda = Nonsmoker(np.mean([b.Female for a,b in LST]),np.mean([...
python|list|numpy|tuples|namedtuple
1
376,687
64,159,676
Correlation matrix for panel data in Python
<p>I want to create a correlation matrix for a data panel. The dataframe contains data on 15 numerical variables on a monthly basis for 11 years.</p> <p>I would like to know, if possible, how to generate a single correlation matrix for the variables of this type of dataframe.</p> <p>The alternative I have in mind would...
<p>IIUC, you're mainly looking for the <code>corr</code> method of a DataFrame. Consider this example:</p> <pre><code>import pandas as pd import numpy as np np.random.seed(0) df = pd.DataFrame(np.random.rand(30, 5)).add_prefix(&quot;feature_&quot;) df[&quot;year&quot;] = np.repeat([&quot;2012&quot;, &quot;2013&quot;, ...
python|pandas|dataframe|panel|correlation
1
376,688
63,877,900
KeyError(key) while merging the data frames
<pre class="lang-py prettyprint-override"><code>Input = df=pd.merge(Bx_Users,BX_ratings,on='user_id') Error = Traceback (most recent call last): File &quot;C:/Users/91943/AppData/Roaming/JetBrains/PyCharmCE2020.2/scratches/MergingwithSummerclothingdataset.py&quot;, line 14, in &lt;module&gt; df=pd.merge(Bx_Users,...
<p>Parameters rightDataFrame or named Series Object to merge with.</p> <p>how{‘left’, ‘right’, ‘outer’, ‘inner’, ‘cross’}, default ‘inner’ Type of merge to be performed.</p> <p>left: use only keys from left frame, similar to a SQL left outer join; preserve key order.</p> <p>right: use only keys from right frame, simila...
pandas|merge
0
376,689
64,099,754
Iterating optimization on a dataframe
<p>I'm trying to build an iterating interpolation of series <code>x</code> and dataframe <code>y</code>. Df <code>y</code> is made by <code>n</code> rows and <code>m</code> columns. I would like to run the interpolation for every row of DataFrame <code>y</code>.</p> <p>So far, I've been able to successfully build the i...
<p>In general you can run any function for each row by using <code>.apply</code>. So something like:</p> <pre><code>y.apply(lambda val: interpolate.splrep(x,val)) </code></pre> <p>This will then return a new series object.</p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply...
python|pandas|dataframe|loops|optimization
0
376,690
64,098,085
Finding non-matching rows between two dataframes
<p>I have a scenario where I want to find non-matching rows between two dataframes. Both dataframes will have around 30 columns and an <code>id</code> column that uniquely identify each record/row. So, I want to check if a row in <code>df1</code> is different from the one in <code>df2</code>. The <code>df1</code> is an...
<p>If your df1 and df2 has the same shape, you may easily compare with this code.</p> <pre><code>df3 = pd.DataFrame(np.where(df1==df2,True,False), columns=df1.columns) </code></pre> <p>And you will see boolean output &quot;False&quot; for not matching cell value.</p>
python|pandas|dataframe
1
376,691
63,811,180
pyodbc import error because of Invalid Datetime format
<p>I´ve already look it up here, but couldn´t find a solution for my problem. I want to get a dataframe from 4 accces databanks and 2 work with this exact code and the other 2 display this error:</p> <pre><code>DataError: ('22007', '[22007] [Microsoft][ODBC-Treiber für Microsoft Access]Ungültiges Datetime-Format. bei S...
<p>So I finally find the answer. I selected the Error showing column and import it as a string. I just wrote:</p> <pre><code>df = pd.read_sql_query(sql='SELECT ID, ..., Cstr(dtime), dates FROM TB_cycles_car', con=conn) </code></pre> <p>The DataError didn´t show up anymore :) Thanks a lot @GordThompson for helping!</p>
python|pandas|ms-access|pyodbc
1
376,692
63,989,761
Select Dataframe rows in a date range
<p>I have a data frame like the following</p> <pre><code> transaction_no sales_order is_delivered dispatch_date remarks .... 0 2122.0 1.0 True 06-01-2020 NaN 1 2122.0 1.0 True 06-01-2020 NaN 2 2122.0 1.0 True ...
<p>Assume that just after reading, e.g. calling <em>pd.read_csv</em>, without any type conversion, your DataFrame contains:</p> <pre><code> transaction_no sales_order is_delivered dispatch_date 0 2122.0 1.0 True 06-01-2020 1 2123.0 1.0 True 07-01-2020 2 ...
python|pandas
1
376,693
47,049,073
Keras Initializers of a particular shape
<p>I make a small keras model and get weights of model using following code:</p> <pre><code>from keras.models import Sequential from keras.layers import Dense, Flatten,Conv2D, MaxPooling2D input_shape = (28, 28, 1) model = Sequential() model.add(Conv2D(1, kernel_size=(2, 2), activation='relu', ...
<p><strong>About <code>get_weights()</code>:</strong></p> <p>The method <code>model.get_weights()</code> will return a list of numpy arrays. So you have to take care to create a list with the same number of arrays, in the same order, with the same shapes. </p> <p>In this model, it seems there will be 4 arrays in the ...
numpy|keras|keras-2
2
376,694
46,973,453
Rolling window on dataframe rows Python 3
<p>Is there a way to create a rolling window (2 periods) over a dataframe rows and compute the sum of the values?</p> <p>My data:</p> <pre><code>ID Name Value1 Value2 Value3 Value4 0 A 2 2 4 4 1 B 1 1 3 3 </code></pre> <p>The output desired:</p> <pre><code>ID Name Value...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html" rel="nofollow noreferrer"><code>rolling</code></a>, but first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> ...
python-3.x|pandas
4
376,695
46,796,618
Add missing rows to data frame equally distribueted
<p>I sampled a pandas dataframe using a custom sampler function. This is basically made up by two columns:</p> <ul> <li>a timestamp</li> <li>a value</li> </ul> <p>I'd like to create a new data frame with all the datetimes equally distributed (i.e. every 10 minutes) to fill missing values in the sampled one (sampled ...
<p>You can try with this, I used <code>comvibe_first</code> to merge two dataframe.</p> <pre><code>start_date = datetime.datetime.today() end_date = datetime.datetime(2017, 10, 19) ​ dd = pd.date_range( start_date, end_date, freq="3min" ​ ) dd = dd.map(lambda item: calendar.timegm(item.time...
python|pandas|resampling
1
376,696
46,760,020
Existance row in Dataframe based on other Dataframes
<p>Let's say, I have a Dataframe DF1 like this:</p> <pre><code> A B 0 123 997 1 123 998 2 124 999 3 125 997 4 125 998 </code></pre> <p>And other 2 Dataframes A and B, containing every possible item present in DF1:</p> <pre><code>A a 0 123 1 124 2 125 ...
<p>You can use <code>pd.crosstab</code> + <code>reindex</code>:</p> <pre><code>df = pd.crosstab(df.A, df.B).reindex(index=A.a, columns=B.b).fillna(0).astype(bool) print(df) b 999 998 997 996 995 a 123 False True True False False 124 True False False False False 125 False ...
python|pandas|dataframe
2
376,697
46,950,927
How to create a Initializer for layers.batch_normalization?
<p>The default <code>beta_initializer</code> for <code>layers.batch_normalization</code> is: <code>tf.zeros_initializer()</code>.</p> <p>Is it possible to create a new initializer with an arbitrary value?</p>
<p>See the list of <a href="https://www.tensorflow.org/versions/r1.0/api_guides/python/state_ops#Sharing_Variables" rel="nofollow noreferrer">built-in initializers</a>. The one that interests you is <a href="https://www.tensorflow.org/versions/r1.0/api_docs/python/tf/constant_initializer" rel="nofollow noreferrer"><cod...
machine-learning|tensorflow|initializer|batch-normalization
1
376,698
46,834,436
Choose one entry from a list if its key contains a string from another column
<p>I have a question regarding my dataframe. Specifically, in one column, for each row, I have a list of speakers and speeches. Now, I want to choose exactly one speech, based on whether the speaker is the one I am looking for, which is noted within another column. So one column provides the last name I am looking for ...
<p>This is perhaps best accomplished by writting a function, and then applying it row-wise:</p> <pre><code>def get_speech(row): matches = list(filter(lambda x: x[0].endswith(row['exel_lname']), row['speech'])) if len(matches) &gt; 0: return matches[0][1] return '' df['speechmanager'] = df.apply(ge...
python|pandas|dataframe
2
376,699
46,980,287
Output node for tensorflow graph created with tf.layers
<p>I have built a tensorflow neural net and now want to run the <code>graph_util.convert_variables_to_constants</code> function on it. However this requires an <code>output_node_names</code> parameter. The last layer in the net has the name <code>logit</code> and is built as follows:</p> <pre><code>logits = tf.layers....
<p>If the graph is complex, a common way is to add an identity node at the end:</p> <pre><code>output = tf.identity(logits, 'output') # you can use the name "output" </code></pre> <p>For example, the following code should work:</p> <pre><code>logits = tf.layers.dense(inputs=dropout, units=5, name='logit') output = t...
tensorflow
1