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
353,100
50,605,037
Error while implementing ARIMA in Python on Quandl Data
<pre><code>df = quandl.get('NSE/TATAMOTORS', start_date='2000-01-01', end_date='2018-05-10') df=df.drop(['Last','Total Trade Quantity','Turnover (Lacs)'], axis=1) df.head(10) </code></pre> <p>OUTPUT - </p> <pre><code> Open High Low Close Date 2003-12-26 435.80 440.50...
<p>ARIMA is expected a array-like object, if we instead of using a 2D array(dataframe) and use a 1D array(Series) and this will work.</p> <p>Try:</p> <pre><code>ARIMA(df['Close'].values, order=(5,1,0)) </code></pre> <p>where df has a datetime in index and you select one column:</p> <pre><code>df.info() &lt;class '...
python|python-3.x|pandas|arima|quandl
1
353,101
50,316,600
Training a model to achieve DLib's facial landmarks like feature points for hands and it's landmarks
<p>[I'm a noob in Machine Learning and OpenCV]<br> These below are the results i.e. 68 facial landmarks that you get on applying the DLib's Facial Landmarks model that can be found <a href="http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2" rel="nofollow noreferrer">here</a>.<br> <a href="https://i.stack....
<ol> <li><p>how am I supposed to train the model on those positions? Would I have to manually mark each joint in every single image or is there an optimised way for this?</p> <p>-> Yes, you should do it all manually. Detecting hand location, defining how many points you need to describe shape.</p></li> <li><p>In DLib'...
tensorflow|machine-learning|computer-vision|dlib
4
353,102
50,608,707
Dividing two numbers in a list across a Pandas Series / Column
<pre><code>0 [1, 39] 1 [1, 39] 2 [1, 39] 3 [2, 39] 4 [4, 39] </code></pre> <p>So what I started with was a fraction in each row, I've got it split up into a list with numerical strings. I'd like to simply divide these and be left with a single float in each row. Where I'm at currently below:</p> <pre><...
<p>By using <code>str</code> </p> <pre><code>df.str[0]/df.str[1] Out[403]: 0 0.025641 1 0.025641 dtype: float64 </code></pre>
python|pandas
2
353,103
50,260,353
Displaying one value for multiple rows in a MultiIndexed dataframe
<p>I'm interested in presenting the following data in pandas:</p> <pre><code>metric1 | metric 2 || % occurence | total ----------------------------------------- A | 1 || 20 | | 2 || 10 | 35 | 3 || 5 | ----------------------------------------- ...
<p>With multiple index you can make it and <code>crosstab</code>+<code>stack</code></p> <pre><code>pd.crosstab(index=df.metric1,columns=df.metric2,values=df.percentage,aggfunc='sum',margins=True).set_index('All',append=True).iloc[:-1].stack() Out[59]: metric1 All metric2 A 35 1 20 2 ...
pandas|multi-index
1
353,104
50,501,160
Python Element-wise AVERAGEIF equivalent to Excel
<p>I have a <code>2darray</code> and for each row, i want to calculate the row's <code>average</code> in col <code>numbers</code> for the same key (in this case, <code>key1</code> &amp; <code>key2</code>. Here is simple representation of my problem, and below is what expect to have:</p> <pre class="lang-py prettyprint...
<p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> by both columns:</p> <pre><code>df['new'] = df.groupby(['key1','key2'])['number'].transform('mean') print (df) key1 key2 number new...
python|pandas|aggregate
1
353,105
50,530,100
Keras lstm multi output model predict two features (time series)
<p>I need to ask how to use keras predict from keras functional api. I need to write multivariate LSTM model with multioutput. I have written such model:</p> <pre><code>inp = Input((train_X.shape[1],train_X.shape[2])) x = LSTM(192,return_sequences=True)(inp) x = Dropout(0.5)(x) x = Flatten()(x) out1 = Dense(1,activati...
<p>You are confusing number of inputs with number of outputs. Let's look at this line:</p> <pre><code>ypred = model.predict(pred_X) # equally out1, out2 = model.predict(pred_X) </code></pre> <p>now ypred will be a list of outputs, namely 2. So predict will return both outputs for the same input because that is precis...
python|tensorflow|keras|lstm
4
353,106
50,459,018
HOG +SVM training with iniria dataset, TypeError: samples is not a numpy array, neither a scalar
<p>I'm working on <em>pedestrian detection</em> with a team. I am trying to figure out an error that keeps showing up that says "TypeError: samples is not a numpy array, neither a scalar" which when appear points to the line of code that is <code>svm.train(X_data, cv2.ml.ROW_SAMPLE, labels12)</code> </p> <p>i tried fo...
<p>you should also do <code>X_data2 = np.array([X_data])</code> and call <code>svm.train(X_data2, cv2.ml.ROW_SAMPLE, labels12)</code></p>
numpy|dataset|svm|glob|image-recognition
0
353,107
50,544,493
Cannot figure out why Tensorflow-GPU does not use my GPU and why it displays N instaed of Y as output
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>(tfenv) hobbes@hobbes-HP-Pavilion-Notebook:~/tfenv$ python Python 3.6.5 (default, Apr 1 2018, 05:46:30) [GCC 7.3.0] on linux T...
<p>Sorry, you probably did it but gotta ask if you really did install <code>tensorflow-gpu</code>. And if you correctly managed cuDNN libraries by appropriate versions.</p>
ubuntu|tensorflow|nvidia|ubuntu-18.04
0
353,108
50,390,206
Pandas: drop_duplicates not working correctly
<p>For the following series, <code>drop_duplicates</code> is not working correctly:</p> <pre><code>8672.0 8672.0 8672.0 8672.0 8670.0 8670.0 8670.0 8670.0 8670.0 8670.0 8672.0 8672.0 8672.0 8672.0 8672.0 8672.0 8672.0 8672.0 8672.0 8672.0 8670.0 8670.0 8670.0 8670.0 8670.0 </code></pre> <p>by using <code>drop_duplica...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer">DataFrame.drop_duplicates()</a> removes all duplictes, not only consecutive ones.</p> <p>Assuming <code>s</code> is a Series:</p> <pre><code>In [93]: s[s.diff().ne(0)] Out[93]: 0 867...
python-3.x|pandas|dataframe
3
353,109
50,483,962
AttributeError: 'Tensor' object has no attribute '_keras_history' when using backend random_uniform
<p>I'm implementing a WGAN-GP in Keras where I calculate the random weighted average of two tensors.</p> <pre><code>def random_weighted_average(self, generated, real): alpha = K.random_uniform(shape=K.shape(real)) diff = keras.layers.Subtract()([generated, real]) return keras.layers.Add()([real, keras.laye...
<p>Custom operations that use backend function need to be wrapped around a <code>Layer</code>. If you don't have any trainable weights, as in your case, the simplest approach is to use a <code>Lambda</code> layer:</p> <pre><code>def random_weighted_average(inputs): generated, real = inputs alpha = K.random_uniform...
python|tensorflow|keras
1
353,110
50,277,490
How to determine correlation from dataframe with Nan?
<p>I use method DataFrame.corr() from Pandas. As result it return matrix of correlation, but it removes columns where were even one Nan value. Is possible to compute correlation in DataFrame with Nan?</p>
<p>Try this. For my case it worked</p> <pre><code> df = df.apply(pd.to_numeric, errors='coerce') </code></pre>
python|pandas|dataframe|nan|correlation
1
353,111
50,667,088
Join two pandas datagrames by a column (Country Codes)
<p>I want to have country codes represented in df dataframe as alpha_3_code, in my field Nationality_Codes of df2 dataframe. For every row in df2 I want to match Reviewer_Nationality with en_short_name in df, and if match, assign country code to Nationality_Codes in df2.</p> <p><code>df2.head()</code></p> <pre><code>...
<p>One way would be to create a Series mapping for your english names and codes, and use <code>.map</code>:</p> <pre><code>#my_map = pd.Series(df.alpha_3_code.values,index=df.en_short_name) my_map = df.set_index('en_short_name')['alpha_3_code'] df2['Nationality_Codes'] = df2['Reviewer_Nationality'].map(my_map) </code...
python|pandas|dataframe
3
353,112
50,245,325
Matplotlib - axvlines across subplots
<p>How to draw vertical lines across multiple subplots? Whatever I try <code>axvlines</code> are shown only in the bottom subplot:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt fig, zx = plt.subplots(5,1, gridspec_kw={'height_ratios':[1,1,1,1,1]}) fig.subplots_adjust(hspace=0.01) pd.DataFrame({'A...
<p>You can use axes, zx like this to draw line:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt fig, zx = plt.subplots(5,1, gridspec_kw={'height_ratios':[1,1,1,1,1]}) fig.subplots_adjust(hspace=0.01) pd.DataFrame({'A':[1,2,3,4,5]}).plot( grid = True, ax=zx[2]) for x_val in [2.25,3.25,4.25]: z...
python|pandas|matplotlib
1
353,113
50,470,437
role of feed dictionary command in the training loop
<p>I am trying to understand training loop. While calculating training and test accuracy we replace <code>x</code> and <code>y_</code> by training and test sets but while printing the result for cross entropy why we feed <code>x</code> and <code>y_</code> by <code>batch_xs</code> and <code>batch_ys</code> respectively?...
<p>You can calculate your training loss at the same time you do a training step (so that you do not have to make a separate call, passing your batch again later) with something like:</p> <pre><code>for j in range(nSteps): # ... _, train_loss = sess.run([train_step, cross_entropy], ...
python|tensorflow
0
353,114
50,590,900
How to make plot bigger?
<p>I am a python user and have a large dataframe and want to make correlation plot.</p> <p>I found a good answer to this question at here. <a href="https://stackoverflow.com/questions/27768677/pandas-scatter-matrix-display-correlation-coefficient">pandas scatter matrix display correlation coefficient</a></p> <p>Howev...
<p><code>scatter_matrix</code> takes a variable <code>figsize</code> that controls the size. <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.plotting.scatter_matrix.html" rel="nofollow noreferrer">Documentation here</a>. So you can change the size as you want:</p> <pre><code>scatter_matrix(df, a...
python|pandas|matplotlib|plot|correlation
4
353,115
50,537,266
Appending to a dataframe cell with pandas?
<p>I'm working on a code that assigns tags to people based on data in certain columns. I'm using a pandas dataframe. I had no problem populating the tag column with one initial value, but I can't figure out how to append to the initial value if a person should have more than one tag. </p> <p>The dataframe is treating ...
<p>There are 2 points worth noting for your problem:</p> <ol> <li>Holding lists in a dataframe is inefficient and not recommended. This is because they are stored via pointers rather than in contiguous memory blocks. This means vectorised computations are not possible.</li> <li>You should only iterate rows in a datafr...
python|pandas|dataframe
2
353,116
50,321,512
Pandas groupby two columns and only keep records satisfying condition based on count
<p>Trying to filter out a number of actions a user has done if the number of actions reaches a threshold. </p> <p>Here is the data set: (Only Few records)</p> <pre><code>user_id,session_id,item_id,rating,length,time 123,36,28,3.5,6243.0,2015-03-07 22:44:40 123,36,29,2.5,4884.0,2015-03-07 22:44:14 123,36,30,3.5,6846.0...
<p>It seems like you want to use <code>groupby</code> with <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.head.html" rel="nofollow noreferrer"><code>head</code></a>:</p> <pre><code>In [8]: df.groupby([df.user_id, df.session_id]).head(3) Out[8]: user_id session_id item...
python|pandas|dataframe|pandas-groupby
2
353,117
50,656,197
Tensorflow: How to get tensor value by indices and assign new value
<p>I am trying to do some operations for the top K value for a tensor in Tensorflow. Basically, what I want is first get the indices of the top K value, do some operations and assign new value. For example:</p> <pre><code>A = tf.constant([[1,2,3,4,5],[6,7,8,9,10]]) values, indices = tf.nn.top_k(A, k=3) </code></pre> ...
<p>Unfortunately, Tensorflow is quite painful once you want to use indices with tensors, so to implement your idea you have to use some ugly workarounds. My option would be:</p> <pre class="lang-python prettyprint-override"><code>import tensorflow as tf #First you better use Variable as constant is not designed to ...
tensorflow|keras
0
353,118
50,465,541
pd.DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])
<p>If anybody can explain me this? How i get these decimal values and whats the meaning of <strong>np.random.randn(6,4)</strong> ?</p> <pre><code>In [8]: df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD')) In [9]: df Out[9]: A B C D 2013-01-01 0.4691...
<p>Basically <code>np.random.randn</code> returns random float values of normal distributions with mean = 0 and variance = 1. Now <code>np.random.randn</code> takes shape you would like to return of those distributions.</p> <p>For example:</p> <p><code>np.random.randn(1,2)</code> returns an array of one row and two c...
python|pandas|dataframe
1
353,119
50,327,199
how can i use a deep network the same as other deep network?
<p>I have an auto-encoder as we know this network is produced from 3 parts, Encoder, Decoder , latent space, I attached an image that shows my structure: <a href="https://i.stack.imgur.com/VqYvJ.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/VqYvJ.jpg</a> it has an auto-encoder in first part and after that I ...
<p>The encoder is defined by it's graph (the operations to do) and the weights (the matrices/biases, etc). One is stored in the graph and the other in the session.</p> <p>A new feature in tensoflow is the hub, which is supposed to facilitate transfer learning applications (like yours). Check out the <a href="https://w...
tensorflow|deep-learning|autoencoder
0
353,120
50,290,451
Pandas resample based on higher resolution data
<p>I have two time-series one on 30 min resolution and one on 15 minute resolution <strong>A</strong> and <strong>B</strong> as shown under. I would like to Upsample <strong>A</strong> to a 15 minute resolution using <strong>B</strong> to scale the values for the given interval. So for the first value it would be: </p>...
<p>Say you upsample, then left-merge to util:</p> <pre><code>A.index = pd.to_datetime(A.index) B.index = pd.to_datetime(B.index) merged = pd.merge(B, A.resample('15s').ffill(), left_index=True, right_index=True, how='left') &gt;&gt;&gt; merged util irrad index 2017-11-01 07:15:00 12.67 NaN 2017-11-01 07:3...
python|python-3.x|pandas
1
353,121
50,238,512
installing and configuring virtualenv on ubuntu
<p>I have installed virtualenv on my system using <a href="http://www.pythonforbeginners.com/basics/how-to-use-python-virtualenv" rel="nofollow noreferrer">http://www.pythonforbeginners.com/basics/how-to-use-python-virtualenv</a></p> <p>according to these <a href="http://blog.niandrei.com/2016/03/01/install-tensorflow...
<p>Just run this single command:</p> <ul> <li>It installs python package manager: <code>pip</code>.</li> <li>It creates a virtual environment named: <code>my_env</code>.</li> <li>It activates the virtual environment.</li> </ul> <blockquote> <p><code>sudo apt-get install python3-pip -y &amp;&amp; sudo apt install python...
python|azure|ubuntu|tensorflow|virtualenv
0
353,122
50,490,145
Add characters from filename to column name
<p>I have a folder of csv files labelled as such:</p> <p><code>aa_bbb_2009_10.csv</code></p> <p><code>aa_bbb_2009_100.csv</code></p> <p><code>xx_bbb_2009_10.csv</code></p> <p><code>xx_bbb_2009_100.csv</code></p> <p>All with the same column names within. My end goal is to bring all of these into Python and join all...
<p>I think need <code>dictionary of DataFrame</code> with <code>key</code>s of filenames and add <code>index_col</code> for <code>index</code> from <code>ID</code> column if want join by <a href="http://pands.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a>:<...
python|pandas|csv|glob
0
353,123
50,481,372
Lengthening a DataFrame based on stacking columns within it in Pandas
<p>I am looking for a function that achieves the following. It is best shown in an example. Consider:</p> <pre><code>pd.DataFrame([ [1, 2, 3 ], [4, 5, np.nan ]], columns=['x', 'y1', 'y2']) </code></pre> <p>which looks like:</p> <pre><code> x y1 y2 0 1 2 3 1 4 5 NaN </code></pre> <p>I would like to coll...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a> to get things done i.e </p> <pre><code>pd.DataFrame(df.set_index('x').stack().reset_index(level=0).values,columns=['x','y']) x y 0 1.0 2.0 1 1.0 3.0 ...
python|python-3.x|pandas|numpy|dataframe
3
353,124
50,502,510
Do we have a way to implement face detection and recognition offline on browser?
<p>I need to find a way to implement face detection and recognition completely offline using a browser. Trained model specific to each user maybe loaded initially. We only need to recognize one face per device. What is the best way to implement this?</p> <p>I tried <code>tracking.js</code> to implement face detection....
<p>Take a look at: <a href="https://itnext.io/face-api-js-javascript-api-for-face-recognition-in-the-browser-with-tensorflow-js-bcc2a6c4cf07" rel="nofollow noreferrer">face-api.js</a> it can both detect and recognize faces in realtime completely in the browser! It's made by Vincent Mühler, the same creator of face-reco...
opencv|tensorflow|face-detection|face-recognition|dlib
6
353,125
50,472,447
Split a column of values delimited by a space into separate columns for each value in python
<p>How can I convert the dataset</p> <pre><code>a | a b c d s | e f g h f | i j k l </code></pre> <p>to </p> <pre><code>a | a | b | c | d s | e | f | g | h f | i | j | k | l </code></pre>
<p>A simpler way is using <code>expand=True</code> argument.</p> <pre><code># sample data df = pd.DataFrame({'c1':['a','b','c'], 'c2':['a b c d','e f g h','i j k l']}) # transform into multiple columns df = pd.concat([df['c1'],df['c2'].str.split(' ', expand=True)], axis=1) print(df) c1 0 1 2 3 0 a a b c ...
python|pandas|split|data-cleaning
4
353,126
50,331,918
How does numpy addition work?
<p>I have the following unexpected behaviour</p> <pre><code>import numpy as np class Test: def __radd__(self, other): print(f'value: {other}') [1,2,3] + Test() # prints: value: [1,2,3] np.array([1,2,3]) + Test() # prints # value: 1 # value: 2 # value: 3 </code></pre> <p>I would expect the second addition...
<p>This is because of NumPy <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html" rel="nofollow noreferrer">'broadcasting'</a>.</p> <p>Your explanation is pretty much correct as you can see <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.add.html" rel="nofollow noref...
python|numpy
4
353,127
50,517,934
Keras.predict always gives "1."as the output
<p>I trained a binary classifier distinguish clear MNIST images from blurry images. All images are 28*28*1 grayscale digits and I have 40000 for training, 10000 for validating and 8000 for testing. My code looks like:</p> <pre><code>from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, ...
<p>Some suggestions:</p> <ul> <li>Pull data directly from one of your generators and test on that. Treat the generator like you would a list in a for loop to get image/label pairs out. This should sort out any differences in the way you are obtaining data and its formatting (e.g. channel order).</li> <li>Check how man...
python|tensorflow|keras
0
353,128
50,387,399
Testing Numpy operations
<p>Whenever I need to test a moderately complex numpy expression, say,</p> <pre><code>c = np.multiply.outer(a, b) d = np.einsum('kjij-&gt;ijk', c) </code></pre> <p>I end up doings hacks such as, e.g., setting <code>a</code> and <code>b</code>thus</p> <pre><code>a = np.arange(9).reshape(3,3) b = a / 10 </code></pre> ...
<pre><code>In [454]: a = np.array(list("abcdefghi")).reshape(3,3) ...: b = np.array(list("ABCDEFGHI")).reshape(3,3) </code></pre> <p><code>np.add</code> can't be used because <code>add</code> has not been defined for the string <code>dtype</code>:</p> <pre><code>In [455]: c = np.add.outer(a,b) .... TypeError: uf...
numpy|numpy-ufunc
2
353,129
45,339,819
Vectorized example of the math.atan2() function in python
<p>let us say I have a numpy matrix <code>A</code> that is of size <code>Nx2</code>. What I am doing, is computing the 4-quadrant inverse tangent of the first column, and the second column, as so:</p> <pre><code>import math for i in xrange(A.shape[0]): phase[i] = math.atan2(A[i,0], A[i,1]) </code></pre> <p>I would ...
<p>It looks to me like it should just be:</p> <pre><code>import numpy as np phase = np.arctan2(A[:, 0], A[:, 1]) </code></pre> <p>Or possibly (if <code>phase</code> is a different length than <code>A</code> for some odd reason):</p> <pre><code>phase[:len(A)] = np.arctan2(A[:, 0], A[:, 1]) </code></pre> <p>In other ...
python|numpy|math|vectorization|trigonometry
6
353,130
45,523,205
Get RGB colors from color palette image and apply to binary image
<p>I have a color palette image like <a href="https://imgur.com/a/BXvb3" rel="nofollow noreferrer">this one</a> and a binarized image in a numpy array, for example a square such as this:</p> <pre><code>img = np.zeros((100,100), dtype=np.bool) img[25:75,25:75] = 1 </code></pre> <p>(The real images are more complicated...
<p>You can use a combination of a <code>reshape</code> and <code>np.unique</code> to extract the unique RGB values from your color palette image:</p> <pre><code># Load the color palette from skimage import io palette = io.imread(os.path.join(os.getcwd(), 'color_palette.png')) # Use `np.unique` following a reshape to ...
python|numpy|image-processing|scikit-image
1
353,131
45,348,325
Append rows to dataframe, add new columns if not exist
<p>I have a df like below which</p> <pre><code>&gt;&gt;df group sub_group max 0 A 1 30.0 1 B 1 300.0 2 B 2 3.0 3 A 2 2.0 </code></pre> <p>I need to have group and sub_group as atrributes (columns) and max as row So I do</p> <pre><code>&gt;&gt;&gt; ne...
<p>I think you can add parameter <code>index_col</code> to <code>read_csv</code> first for <code>Multiindex</code> from first and second column:</p> <pre><code>dfs = [] for date in dates: df = pd.read_csv('name', index_col=[0,1]) dfs.append(df) #another test df was added print (df3) max...
python|pandas
1
353,132
45,523,192
Good way to feed input data of different sizes into neural network? (Tensorflow)
<p>My data looks like this. They are floats and they are in a big numpy array [700000,3]. There are no empty fields.</p> <pre><code>Label | Values1 | Values2 1. | 0.01 | 0.01 1. | ... | ... 1. | 2. | 2. | 3. | ... </code></pre> <p>The idea is to feed in the set of values1 ...
<p>Since you have your data in a numpy array (let's call it <code>data</code>, you can use </p> <pre><code>single_digit = data[(data[:,0] == 1.)][: , 1:] </code></pre> <p>which will compare the zeroth element of each row with the digit (<code>1.</code> in this case) and select only the rows having the label <code>1.<...
python|arrays|numpy|tensorflow|neural-network
1
353,133
45,662,403
Melting pandas data frame with multiple variable names and multiple value names
<p>How can I melt a pandas data frame using multiple variable names and values? I have the following data frame that changes its shape in a for loop. In one of the for loop iterations, it looks like this:</p> <pre><code>ID Cat Class_A Class_B Prob_A Prob_B 1 Veg 1 2 0.9 0.1...
<p>You need <a href="https://github.com/pandas-dev/pandas/blob/master/pandas/core/reshape/reshape.py#L776" rel="nofollow noreferrer"><code>lreshape</code></a> by <code>dict</code> for specify categories:</p> <pre><code>d = {'Class':['Class_A', 'Class_B'], 'Prob':['Prob_A','Prob_B']} df = pd.lreshape(df,d) print (df) ...
python|pandas|melt
13
353,134
45,604,880
Web Scraping | Beautiful Soup | Parsing Tables
<p>There are some great threads on this (some of which have helped me get to this point), but I can't seem to figure out why my program isn't working.</p> <p><strong>Problem</strong>: The program works but it only seems to be returning the first row when it should be looping through all the table rows.</p> <p>I am us...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html" rel="nofollow noreferrer"><code>read_html</code></a> with some data cleaning:</p> <pre><code>df = pd.read_html('http://www.the-numbers.com/movies/year/2006', header=0)[0] df = df.dropna(how='all') df['Release Date'] = ...
python|pandas|web-scraping|beautifulsoup
3
353,135
45,698,267
Pandas DateTime get duration of file
<p>My data files consist of roughly 1 million rows of time-series data. It has been read into Python using <code>df = pd.read_csv(...)</code>. I am looking for a way to get the duration of the file (in seconds), the output I am looking for is just one number to give the duration</p> <p>Below shows the first and last ...
<p>IIUC, let's try, given TimeStamp is a DatetimeIndex: First let's get you index into datetime:</p> <pre><code>df.index = pd.to_datetime(df.index) df.reset_index()['TimeStamp'].diff().sum().total_seconds() </code></pre> <p>OR</p> <pre><code>(df.index[-1] - df.index[0]).total_seconds() </code></pre>
python-3.x|pandas|time-series|python-datetime
1
353,136
45,564,256
How do we merge multiple plots?
<p>We want to annotate plots after we fit the model using <code>RandomForestRegressor</code> and plot the actual and predicted values. The two datasets we are considering are found in the following link</p> <p><a href="https://drive.google.com/open?id=0B4Ak8jGD1OxTT0bXM4TkdTeDQ" rel="nofollow noreferrer">https://drive...
<p>You should specify the the coordinates of the text too, e.g. <code>xytext=(-30,30)</code>.<br> You might then determine the coordinates to annotate from your data. I can't be sure if this is working (as there is no reproducible example in the question) but would suggest to try something like</p> <pre><code>plt.anno...
python|python-3.x|pandas|matplotlib|plotly
2
353,137
45,569,856
Before Fully Connected Layer in Tensorflow size of image become 7*7*64
<p>I am a new in tensorflow network.While I am going through the code that is available in tensorflow documentation I found a line--</p> <pre><code>#Densely Connected Layer W_fc1 = weight_variable([7 * 7 * 64, 1024]) b_fc1 = bias_variable([1024]) </code></pre> <p>I came to know that the 7*7*64 is the size of the imag...
<p>the original image size is 28*28, after twice 2*2 pooling operation (28/2)/2 =7, the output size of image is 7*7, 64 is the number of filters</p>
python-3.x|tensorflow
0
353,138
45,423,784
How to find delta in pandas data-frame rows with specific conditions
<p>I need to compute delta column (as shown below). But tricky part is conditions mentioned below. How can I do this in pandas?</p> <pre> speaker | video | frame | time |delta(expected) --------|-------|-------|------|---------------- one |1 | 0 |10 |0 one |1 | 1 |15 |5 one |2 ...
<p>Let't use <code>groupby</code>, <code>diff</code>, and <code>fillna</code>:</p> <pre><code>df['delta'] = df.groupby(['speaker','video'])['time'].diff().fillna(0) </code></pre> <p>Output:</p> <pre><code> speaker video frame time delta(expected) delta 0 one 1 0 10 0 0.0 ...
python|pandas
3
353,139
45,641,758
pandas groupby create a new dataframe with label from apply operation
<p>I would like to create a new dataframe with labeled column('off') after applying my function. </p> <pre><code>df_onoff = df_sample.groupby('id')['digits'].apply(lambda nums: "%d" % ', '.join(format(n%2**60,'060b') for n in nums).count('01')) </code></pre> <p>Here's the output now:</p> <pre><code>id 4013 466 40...
<p>Simply add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.reset_index.html" rel="nofollow noreferrer"><code>reset_index</code></a> because output is <code>Series</code>:</p> <pre><code>df_onoff = df_sample.groupby('id')['digits'] .apply(lambda nums: "%d" % ', '.join...
python|pandas
1
353,140
45,548,483
Create custom parameter to find outliers in pandas dataframe
<p>I have 2 dataframes that i built using pandas. If you look at the graph below you can see that both of my data frames follow pretty much the same data patern. I want to have pandas tell me when my data falls outside of a certain parameter. For example: say i wanted to know when on the x axis the data falls below 2...
<p>You actually did it already. When you do <code>df4[(df4 &lt; 2) | (df4 &gt; 4)]</code> it does not "erase" data, it just shows only those records which satisfy the criteria, in other words you see only the subset of the dataframe. If you want to see the whole dataframe you can just add a new column:</p> <pre><code>...
python|pandas|dataframe|outliers
0
353,141
45,653,175
Set value of loss function when calculating/applying gradients
<p>I am using TensorFlow as a part of a larger system where I want to apply the gradient updates in batches. Ideally I'd like to do something along the lines of (in pseudo-code):</p> <pre><code>grads_and_vars = tf.gradients(loss, [vars]) list_of_losses = [2, 1, 3, ...] for loss_vals in list_of_losses: tf.apply_grad...
<p>When you call <code>tf.gradients</code>, the argument <code>grad_ys</code> let you specify custom values from upstream backprop graph. If you don't specify them, you end up with node that assumes that upstream backprop is tensor of 1's (Fill node). So you could either call <code>tf.gradients</code> with a placeholde...
tensorflow
0
353,142
45,714,178
Python: Improving Image-processing with numpy
<p>Let there be two big (2000x2000 or higher) .tiff images consisting only of numpy float32 values (no rgb). I call them Image A and B. I want to multiply them in a special way:</p> <ul> <li>Find the max value in B and roll it (using numpy.roll) to the upper-left most corner.</li> <li>Multiply A and B</li> <li>Add the...
<p><strong>Prospective method</strong></p> <p>Consider this :</p> <pre><code>In [154]: B = np.arange(5) In [155]: B Out[155]: array([0, 1, 2, 3, 4]) </code></pre> <p>Use the rolled version of <code>B</code> :</p> <pre><code>In [156]: for i in range(len(B)): ...: print np.roll(B, i) ...: [0 1 2 3...
python-2.7|numpy|image-processing
2
353,143
45,493,846
subsampling a 2d array in tensorflow?
<p>Let's say I have a 2d array of length <code>n</code> like <code>[[1,2,3], [0.7, 1. 2.6], [9, 2, 1.4], ...]</code>. How would I use <code>tf.gather_nd</code> to return all of the first and third elements of the arrays. i.e. return an array of length <code>n</code> like: <code>[[1, 3], [0.7, 2.6], [9, 1.4], ...]</code...
<p>You can use the <code>numpy style sub-sampling method</code> in tensorflow: <code>y = X[:,::2]</code></p> <pre><code>x = np.array([[1,2,3], [0.7, 1., 2.6], [9, 2, 1.4]]) X = tf.constant(x) Y = X[:,::2] sess = tf.InteractiveSession() out = Y.eval() #array([[ 1. , 3. ], # [ 0.7, 2.6], # [ 9. , 1.4]]) <...
python|tensorflow
5
353,144
45,378,789
pandas: DataFrame of dates/values -> DataFrame of "biggest value so far"?
<p>I have a DataFrame of dates and values (and in the below code, I might not have parsed the dates correctly).</p> <pre><code>import pandas as pd d = {'date': pd.Series(['2010-01-01', '2011-01-01', '2012-01-01', '2012-07-01', '2013-01-01']), 'value': pd.Series([0, ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cummax.html" rel="nofollow noreferrer"><code>cummax</code></a> on the 'value' column the get the cumulative max, then compare the cumulative max of the 'value' column to the 'value' column itself, and only keep rows where the 'value' c...
python|pandas
2
353,145
45,355,554
Cannot Replace Pandas Column With Dictionary
<p>I have a Pandas column with string value entries, which I have ensured are strings via </p> <p><code>df[col].astype(str)</code></p> <p>And I have created a dictionary out of an enumeration of these string values that takes the form </p> <p><code>{...'hello': 56, 'yello': 71,...}</code></p> <p>I have tried multip...
<p>I think you are looking for <code>apply</code> i.e</p> <pre><code>df = pd.DataFrame({"a":['hello','yello','bye','seeya']}) inv_map = {'hello': 56, 'yello': 71} col = 'a' df[col]=df[col].apply(lambda s: inv_map.get(s) if s in inv_map else s) </code></pre> <pre> 0 56 1 71 2 bye 3 seeya Name: a, d...
python|pandas
2
353,146
45,310,874
pass argument to groupby and agg in pandas
<p>I want to use agg after groupby and pass in two parameters, param1 and param2. I tried the following but failed. What is the correct way to do that? Thanks.</p> <pre><code>def myfun(x, param1, param2): #some calculations return result B = A.groupby([A.index, 'time']).agg({'salary': myfun, param1, param2}) ...
<p>Use this syntax:</p> <pre><code>param1=1 param2=100 A.groupby([A.index,'time'])['salary'].agg(myfun, param1, param2) </code></pre> <p>or as @ayhan suggests:</p> <pre><code>A.groupby([A.index,'time']).agg({'salary':lambda x: myfunc(x, param1, param2)}) </code></pre>
python|pandas
2
353,147
45,346,222
TensorFlow tensor not reshaping properly
<p>I have created a script that mirrors the one described in TensorFlow's <em>Deep MNIST for Experts</em> tutorial found <a href="https://www.tensorflow.org/get_started/mnist/pros" rel="nofollow noreferrer">here</a>.</p> <p>However my script returns an error quite early on when it tries to reshape the x tensor from th...
<p>I have fixed your code and it should work properly.</p> <pre><code>from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) import tensorflow as tf x = tf.placeholder(dtype = tf.float32, shape = [None,784]) y_ = tf.placeholder(dtype = tf.float32, sh...
python|tensorflow|conv-neural-network
1
353,148
45,701,681
Determining the Epoch Number with tf.train.string_input_producer in tensorflow
<p>I have some doubts on how <code>tf.train.string_input_producer</code> works. So suppose I fed filename_list as an input parameter to the <code>string_input_producer</code>. Then, according to the documentation <a href="https://www.tensorflow.org/programmers_guide/reading_data" rel="nofollow noreferrer">https://www.t...
<p>So what I figured out is that using <code>tf.train.shuffle_batch_join</code> solves my issue as it starts shuffling images from different data sets. In other words, every batch is now containing images from all the datasets/file_names. Here is an example:</p> <pre><code>def read_my_file_format(filename_queue): ...
tensorflow|queue|epoch
0
353,149
45,420,740
Pandas add dataframes side to side with different indexes
<p>I have dataframes like this:</p> <pre><code> Sender USD_Equivalent 725 ABC 5777527.31 330 CFE 4717812.90 12 CDE 3085838.19 Sender USD_Equivalent 707 AAP ...
<pre><code>pd.concat([d.reset_index(drop=True) for d in [df1, df2]], axis=1) Sender USD_Equivalent Sender USD_Equivalent 0 ABC 5777527.31 AAP 1962412.94 1 CFE 4717812.90 EFF 1777705.37 2 CDE 3085838.19 EFG 1744705.37 </code></pre>
pandas
5
353,150
45,694,396
How to cast time columns and find timedelta with condition in python pandas
<p>I have a column Time which is non null object and I cannot convert it to timedelta or datetime. </p> <pre><code> Time msg 12:29:36.306000 Setup 12:29:36.507000 Alerting 12:29:38.207000 Service 12:29:39.194000 Setup 12:30:05.773000 Alerting 12:30:06.205000 Service 12:32:...
<p>I think first need convert to <code>str</code> and then call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="noreferrer"><code>to_timedelta</code></a>.</p> <p>Then get <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html" rel="noreferre...
python|pandas|dataframe|timedelta
5
353,151
45,444,339
Panda data frame, group by and sort string data based on its integer representation
<p>I have a panda data frame from a csv file, that looks roughly like this:</p> <pre><code> col1 col2 1 12937 10 8932 1 9090 11 7171 11 12392 3 6262 2 9123 11 9872 3 4321 </code></pre> <p>I want to group them based on the value in col1, I am currently using <code>d...
<p>The CSV reader should have converted the strings to numbers. You can still fix this by <code>df.col1=df.col1.astype(int)</code>.</p>
python|pandas
1
353,152
45,472,810
Keras + Tensorflow model convert to coreml exits NameError: global name ... is not defined
<p>I've adapted the VAE example from the keras site to train on my data, and everything runs fine. But I'm unable to convert to coreml. The error is: </p> <pre><code>NameError: global name `batch_size' is not defined </code></pre> <p>Since batch_size clearly is defined in the python source, I'm guessing it has to do ...
<p>I ran into a similar message when using parameters to construct the neural net. This should work:</p> <pre><code>from keras import models batch_size = 50 model = models.load_model(filename, custom_objects={'batch_size': batch_size}) </code></pre> <p>See also documentation: <a href="https://keras.io/getting-s...
tensorflow|keras|coreml|coremltools
1
353,153
45,310,368
NumPy not properly installing
<p>I've been trying to work with numpy and libraries that require numpy, but i always get the same error when running my code. There are no errors in the code itself however. The error:</p> <pre><code>ImportError: Importing the multiarray numpy extension module failed. Most likely you are trying to import a failed b...
<p>If you run on windows you need to install some libraries that are already compiled for you. Otherwise you have to get the right version of visual studio in order to compile the library</p> <p>Download the wheel for your python version from this site</p> <p><a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy"...
python|python-3.x|numpy
0
353,154
45,676,617
Reverse block of text every x lines in python
<p>Im sure this is a simple readlines solution. I have spent some time trying to solve it without success.</p> <p>I have a block of text that reads:</p> <pre><code>"This is the text 1" 0.0 2.0 2.0 2.0 0.0 0.0 4.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 "This is the text...
<p>This is working under the assumption that the number of rows between the text is always consistent.</p> <pre><code># Open file, split on newlines into a list with open('file.txt') as f: data = f.read().splitlines() # Break list into multiple lists 7 items long # this covers the text and the 6 sets of numbers th...
python|numpy|readlines
0
353,155
45,465,464
minus specify elements in 2D array numpy
<p>Assume there is a matrix X, a mask and a vector y</p> <pre><code>&gt;&gt;&gt; X array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) &gt;&gt;&gt; mask array([[False, True, True, True], [ True, False, True, True], [ True, True, False, True], ...
<p>Two approaches could be suggested for in-place edits.</p> <p><strong>Approach #1 :</strong> Boolean-index into <code>X</code>. Reshape it to have same number of elements as number of elements in <code>y</code>. Subtract <code>y</code> from it, thus leveraging <code>broadcasting</code>. Finally index into <code>X</c...
arrays|numpy
2
353,156
45,330,643
Explaining Grouping in Pandas in a way similar to the group function in dyplr in R
<p>Simple question that I could not find an answer for:</p> <p>Why when we group a panda df by a varaibel and then we sort the result why dont we see the grouped rosw togather like the case in the group function dplyr in R? </p> <p>For examaple, I have this data frame:</p> <pre><code>Item Type Price A ...
<p>To get your output, you can use <code>df.sort_values</code>:</p> <pre><code>In [783]: df.sort_values(['Item', 'Price'], ascending=[True, False]) Out[783]: Item Type Price 3 A 2 80 4 A 3 50 0 A 1 22 5 B 2 98 1 B 1 58 7 B 5 8 6 C 3 63...
python|r|pandas|pandas-groupby
1
353,157
45,359,448
Error after deleting NA values twice, first by using pandas library second by R
<p>First I deleted NA values using the following Python code:</p> <pre><code>import pandas as pd a = pd.read_csv("true.csv",low_memory=False) #print a b = pd.read_csv("false.csv",low_memory=False) merged = a.append(b, ignore_index=False) merged=merged.dropna(axis=1) merged.to_csv("out.csv", index=False) </code></pr...
<p>Before last line </p> <pre><code>(result &lt;- cfs(Activity ~ ., dataset)) </code></pre> <p>use </p> <pre><code>dataset$Activity = factor(dataset$Activity) </code></pre> <p>It will take some time to execute because we have a very large dataset.</p>
python|r|pandas|na|fselector
1
353,158
62,779,585
Train RoBERTa from scratch where dataset is larger than the capacity of RAM?
<p>I have a corpus that is 16 GB large and my ram IS around 16 GB ish. If I load the entire dataset to train the language model RoBERTa from scratch, I am going to have a memory issue. I intend to train my RoBERTa using the script provided from Huggingface's tutorial in their blog post: <a href="https://colab.research....
<p>I would recommend using HuggingFace's own <a href="https://huggingface.co/docs/datasets/quicktour.html#loading-a-dataset" rel="nofollow noreferrer"><code>datasets</code> library</a>. The documentation says:</p> <blockquote> <p>It provides a very efficient way to load and process data from raw files (CSV/JSON/text) o...
huggingface-transformers|roberta-language-model
1
353,159
62,502,919
ValueError: logits and labels must have the same shape ((None, 10) vs (None, 12))
<p>I'm following a tutorial for <a href="https://towardsdatascience.com/lstm-based-african-language-classification-e4f644c0f29e" rel="nofollow noreferrer">POS Tagger for African Language</a>, which uses LSTM-based classifier. When running the code:</p> <pre><code>import pandas as pd import numpy as np from keras.prepro...
<p>Change the value in <code>nb_labels</code> to 10 and set you activation to 'softmax'. Sigmoid is for binary cases.</p>
python|tensorflow|machine-learning|keras|lstm
1
353,160
62,708,464
DataFrame transformation from multiple rows to a single row
<p>I have pandas dataframe that looks like (blank transaction IDs belong to ID 1 or ID 2):</p> <pre><code>df = pd.DataFrame(data=np.array([['1', 'Item1'], ['', 'Item2',], ['', 'Item3'] , ['2', 'Item1'], ['', 'Item2',]]), columns=['TransactionId', 'ProdictName']) </code></pre> <p><a href="https://i.stack.imgur.com/7hNXG...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer"><code>df.replace</code></a>, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ffill.html" rel="nofollow noreferrer"><code>df.ffill()</code></a> ...
python|pandas|dataframe|pandas-groupby
3
353,161
62,876,315
Expand all columns with lists into own columns
<p>Given the following dataframe:</p> <pre><code> FrameLen FrameCapLen IPHdrLen ... TLSRecordLen TLSAppData PacketTime 0 [117, 66] [117, 66] [20, 20] ... [46.0, nan] [nan, nan] 0.000045 1 [117, 66] [117, 66] [20, 20] ... [46.0, nan] [nan, nan] 0.000024 2 [117, 66] [117, 66] [20, 20] ... [4...
<p>You can use a <code>for</code> loop with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.add_prefix.html" rel="nofollow noreferrer"><code>df.add_prefix</code></a> to append column name:</p> <p>Take below df for example:</p> <pre><code>In [93]: In [55]: df = pd.DataFrame({'FrameLe...
python|pandas|dataframe
1
353,162
62,487,609
Applying more than Two Filter to DataFrame with & operator
<p>I have a df and I want to apply multiple filtering that df.</p> <pre><code>... def applyFilter(self): ## 1st Condition if self.col1_lineEdit.text() != &quot;&quot;: self.filter_col1 = (self.myDataFrame['col1'] == self.col1_lineEdit.text()) else: self.filter_col1 = ...
<p>To solve this problem, I had to add a column that had no effect on the results but had to trick filter. So I add to my table an addition column which named <strong>ALL</strong> and filled with <strong>ALL</strong> parameter. Then i edited my filter as;</p> <pre><code>self.filteredResult = self.myDataFrame[(self.myDa...
python|pandas|dataframe|filtering
0
353,163
62,515,329
How to Group By and Count total in that group Pandas
<p>Hi I have the following DataFrame:</p> <pre><code># Import pandas library import pandas as pd import numpy as np from sklearn.linear_model import LogisticRegression # initialize list of lists data = [['tom', 10,1], ['nick', 15,0], ['tom', 14,1], ['jason', 15,0], ['nick', 18,1], ['jason', 15,0], ['jason', 17,1] ...
<p>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 specified column after <code>groupby</code> with aggregate function:</p> <pre><code>df['totalentries'] = df.groupby('Name')['Target'].tr...
python|pandas
2
353,164
62,752,163
Plot the counted values in each column of a data frame in a separate plot
<p>I'm very new to Python and am trying to plot all the columns in my data frame in separate plots.</p> <p>The data frame has 45 columns which are all called, V1_category V2_category V3_category V4_category V5_category V6_category V7_category etc. till V45_category.</p> <p>Each entry has one of the four values: neutral...
<p>I guess what you need is a barplot. There are many options for visualization these categories, <a href="https://seaborn.pydata.org/generated/seaborn.catplot.html" rel="nofollow noreferrer">see more at the vignette for seaborn</a>.</p> <p>Below I try to make a data.frame that looks like yours:</p> <pre><code>import m...
python|pandas|matplotlib
0
353,165
62,817,216
how to plot an histogram with uneven bins in Python?
<p>for this code, I see this histogram</p> <p>'''</p> <pre><code>t = unique_seq_Dataframe.groupby(by=&quot;frequency&quot;).count() unique_seq_Dataframe.frequency.hist(bins=range(0,50,2)) </code></pre> <p>''' <a href="https://i.stack.imgur.com/Atmpa.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Atm...
<p>By definition of a histogram, you cannot maintain the resolution of the lower binned values while preserving the higher values. Binning groups data points to their nearest bin in order to show you what are relevant features. If you consider your high values to not be outliers then the differences between the low val...
python|pandas|bar-chart|histogram
0
353,166
62,710,262
How to split a list in a column into two column in a dataframe using python?
<p>How to split a list in a column into two column in a dataframe using python? For example:</p> <pre><code> row | column_A ================================== 1 |[('Ahli', 'NNP'), | | ('paleontologi', 'NNP'), | | ('Thomas', 'NNP'), | | ('dan', 'CC'), ...
<p>Adding to @Biranchi's answer, the correct answer would be</p> <pre><code>df['postag'] = df['column_A'].apply(lambda x: [(i[1],) for i in x]) </code></pre> <p>Result would be</p> <pre><code># print(df) column_A postag 0 [(Ahli, NNP), (paleontologi, NNP), ...
python|pandas|dataframe
2
353,167
62,541,668
My data does not share the first dimension
<p>I wanted to build a simple NN-Model using Tensorflow, Keras and Matplotlib. When I tried to run the Code in the shell it gave me this output</p> <pre><code>ValueError: Data cardinality is ambiguous: x sizes: 60000 y sizes: 10000 Please provide data which shares the same first dimension. </code></pre> <p>Here's ...
<pre><code>x_test = tf.keras.utils.normalize(x_train, axis=1) </code></pre> <p>should be</p> <pre><code>x_test = tf.keras.utils.normalize(x_test, axis=1) ^ </code></pre>
python|tensorflow|keras
2
353,168
62,538,712
Pandas Python - Multiply every second row from different columns
<p>My data looks as follows:</p> <pre><code>Column_1 Column_2 Result 17.3604 7.4342 20.5787 13.3504 14.9661 8.85 12.5978 6.2025 11.7481 17.9338 ... ... </code></pre> <p>How can I multiply the first value of <code>Column_1</code> with first v...
<p>You can try:</p> <pre><code>df['Result'] = df.Column_1.ffill()*df.Column_2 </code></pre> <p>Output:</p> <pre><code> Column_1 Column_2 Result 0 17.3604 NaN NaN 1 NaN 7.4342 129.060686 2 20.5787 NaN NaN 3 NaN 13.3504 274.733876 4 14.9661 NaN Na...
python|pandas|multiplication
3
353,169
62,842,887
Input dimension issue of Conv1D network
<p>As I am new in Deep Learning field, I am facing a strange issue regarding the input shape of my Convolutional network (1D). The input is normalized values of 13 features and total 7866 samples are available</p> <blockquote> <p>x_train_shape (7866, 13)</p> </blockquote> <p>The target is 0 or 1 for each features.</p> ...
<blockquote> <p>Reshape your training data as follows: Then run your model</p> </blockquote> <pre><code>x_train.reshape(7866, 13,1) </code></pre>
python|pandas|keras|deep-learning|conv-neural-network
0
353,170
62,621,528
Tweets analysis: Get unique positive, unique negative and unique neutral words : Optimised solution:Natural Language processing:
<p>I have a dataframe <code>train</code>, with a column <code>tweet_content</code>. There is a column <code>sentiment</code> which tells the overall sentiment of tweet. Now there are lot of words which are common in tweets of neutral, positive and negative sentiments. I want to find the words which are unique to each s...
<p>This should work (add the bells and whistles like filtering for <code>numwords</code> as you would require it):</p> <p><strong>Edit</strong> (<em>added explainer comments</em>) :</p> <pre><code>import pandas as pd df = pd.DataFrame([['Positive','Positive','Negative','Neutral'],[['PM', 'you', 'rock', 'man'],['PM'],['...
python|pandas|twitter|nlp|textblob
2
353,171
62,747,428
Tensorflow returns ValueError with tf.data.Dataset object, but works fine with np.array
<p>I'm working on a digit classifier model using this Kaggle dataset: <a href="https://www.kaggle.com/c/digit-recognizer/data?select=test.csv" rel="nofollow noreferrer">https://www.kaggle.com/c/digit-recognizer/data?select=test.csv</a></p> <p>When fitting the model with np.array objects, it works fine, but I can't pass...
<p>It seems that you forgot to add the <code>.batch()</code> method at the end of your <code>tf.data.Dataset</code> objects, since your error refers to the batch dimension. From what I understand, creating a <code>tf.data.Dataset</code> stores the data set as something similar to a python generator rather than storing ...
python-3.x|tensorflow|tensorflow2.0|tensorflow-datasets
2
353,172
62,690,008
How to aggregate stats in one dataframe based on filtering values in another dataframe?
<p>I have 2 dataframes. rdf is the reference dataframe I am trying to use to define the interval (top and bottom) to calculate an average between (all of the depths between this interval), but use ldf to actually run that calculation since it contains the values. rdf defines the top and bottom for each id number an ave...
<h2>Sample data and imports</h2> <pre class="lang-py prettyprint-override"><code>import pandas import numpy import random # dfr rdata = {'ID': [1, 1, 1, 1, 2, 2, 2, 2, 3, 3], 'Top': [2010, 4300, 4550, 7100, 3200, 4120, 4300, 5500, 2300, 3200], 'Bottom': [3000, 4500, 5000, 7700, 4100, 4180, 5300, 5520...
python|python-3.x|pandas|pandas-groupby|average
0
353,173
62,486,818
How to count unique combinations of rows in dataframe group by?
<p>I would like to use pandas groupby to count the occurrences of a combination of animals on each farm (denoted by the farm_id). I am trying to count the number of farms with each type of animal combination.</p> <p>The desired output would be something like this:</p> <pre><code>Out[6]: combo count 0...
<p>Try:</p> <pre><code>import pandas as pd from collections import Counter df_1=df.groupby('farm_id')['animals'].unique().apply(list).apply(lambda x: sorted(x)).reset_index() </code></pre> <p>Count the nummber of occurences</p> <pre><code>dict=Counter([tuple(i) for i in df_1['animals']]) counter_df=pd.DataFrame.from_...
python|pandas|pandas-groupby
1
353,174
62,586,436
Why DQN for cartpole game has a ascending reward while loss is not descending?
<p>I wrote a DQN to play the OpenAI gym cart pole game with TensorFlow and tf_agents. The code looks like the following:</p> <pre class="lang-py prettyprint-override"><code>def compute_avg_return(environment, policy, num_episodes=10): total_return = 0.0 for _ in range(num_episodes): time_step = environm...
<p>It might be related to the <strong>scale</strong> of your Q-Values. I have the same behavior in my DQN loss, my agent easily solves the environment but the loss is growing through training.</p> <p>If you look at this part of the DQN algorithm you might get some insights:</p> <p><a href="https://i.stack.imgur.com/hWk...
python|tensorflow|machine-learning|reinforcement-learning|openai-gym
1
353,175
62,861,902
how to return boolean series based on multiple conditions in pandas?
<p>I would like to return a boolean series based on multiple conditions and then subset that in the initial dataframe.</p> <p>This is returning a dataframe type rather than a boolean series.</p> <pre><code>#remove outliers minInCollection = myDataFrame[ (myDataFrame.Age&gt;myDataFrame.Age.min()) &amp; (myDat...
<p>You are very close--if you want the Boolean series returned, you need to drop the brackets. See the example code below and this simple tutorial <a href="https://appdividend.com/2019/01/25/pandas-boolean-indexing-example-python-tutorial/" rel="nofollow noreferrer">here</a>.</p> <pre><code>### Make up data colA = [20,...
python-3.x|pandas
1
353,176
62,550,224
How to put sum value groupwise in a new column pandas
<pre><code>input:----------- df= pd.DataFrame({ 'description':['apple','apple','apple','apple','banana','banana','banana'], 'warehouse' :['main','sales','sales','main','sales','main','main'], 'qty':[10,12,20,30,10,15,14] }) df= pd.pivot_table(data=df, index=['description','warehouse']...
<p>just create a new column that takes the <code>.sum()</code> and do a <code>.groupby</code> and <code>.transform</code> on the <code>.sum</code>.</p> <pre><code>df= pd.DataFrame({'description':['apple','apple','apple','apple'], 'warehouse' :['main','sales','sales','main'], 'qty':[10,12,20,30]}) df = pd.pivot_...
python|pandas
2
353,177
62,698,550
Find the min and max value of second dataframe between 2 dates given by first dataframe
<p>i have this 2 dummy dataframe</p> <pre><code>np.random.seed(12345) df1=pd.DataFrame({'name' : ['A']*4+['B']*4, 'start_date': pd.to_datetime(['2000-03-15', '2000-06-12','2000-09-01', '2001-01-17','2000-03-19', '2000-06-14','2000-09-14', '2001-01-22']), 'end_date':pd.to_datetime(...
<p>Since performance is your issue I think <a href="https://docs.dask.org/en/latest/dataframe.html" rel="nofollow noreferrer">dask</a> can help a lot</p> <pre><code>import pandas as pd import numpy as np import dask.dataframe as dd </code></pre> <p>Create dask df</p> <pre><code>ddf1 = dd.from_pandas(df1, npartitions=5)...
python|pandas|dataframe
0
353,178
62,551,473
Python np.select match some conditions to multiple choices
<p>I have a pandas dataframe like so:</p> <pre><code>id variable value 1 x 5 1 y 5 2 x 7 2 y 7 </code></pre> <p>Now I want to rename some of the variables to something else and for the rest of the variables, I want to map them to two different variables(rest of the row will be co...
<p>You are trying to change the shape of the data , you can try this approach which joins the list with a delimiter then we can explode the column and join:</p> <pre><code>conditions = [(df['variable']=='x'),(df['variable']=='y')] s=pd.Series(np.select(conditions,['x1','|'.join(['a','b'])])).str.split('|').explode() ...
python|pandas|numpy|dataframe
1
353,179
62,690,513
Python pandas: insert rows for missing dates, time series in groupby dataframe
<p>I have a dataframe <code>df</code>:</p> <pre><code> Serial_no date Index x y 1 2014-01-01 1 2.0 3.0 1 2014-03-01 2 3.0 3.0 1 2014-04-01 3 6.0 2.0 2 2011-03-01 1 5.1 1.3 2 2011-04-01 2 5.8 0.6 2 2...
<p>Use custom function with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.asfreq.html" rel="noreferrer"><code>DataFrame.asfreq</code></a> in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.apply.html" rel="noreferrer"><code>GroupBy.app...
python|pandas|dataframe|time-series|data-science
9
353,180
62,619,216
Why is gradient clipping not supported with a distribution strategy in Tensorflow?
<p>It looks like gradient clipping is not supported using a distribution strategy</p> <p><a href="https://github.com/tensorflow/tensorflow/blob/f9f6b4cec2a1bdc5781e4896d80cee1336a2fbab/tensorflow/python/keras/optimizer_v2/optimizer_v2.py#L383" rel="noreferrer">https://github.com/tensorflow/tensorflow/blob/f9f6b4cec2a1b...
<p>GitHub user tomerk <a href="https://github.com/tensorflow/tensorflow/issues/33929#issuecomment-634181668" rel="nofollow noreferrer">wrote</a>:</p> <blockquote> <p>There's two possible places to clip when you have distribution strategies enabled:</p> <ul> <li>before gradients get aggregated (usually wrong)</li> <li>a...
tensorflow
0
353,181
62,654,671
Using Pandas to use transaction history to determine no of shares
<p>So I'm trying to use the transaction history from Football Index to capture the number of shares in my portfolio.</p> <p>Once I've downloaded the csv into python, created a dataframe within pandas and organised the data I have a dataframe that looks like this:</p> <pre><code> name type...
<p>First, use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>DataFrame.pivot_table</code></a> with <code>aggFunc=sum</code> and <code>fill_value=0</code> to pivot the dataframe with index as <code>name</code> and columns as <code>ty...
python|pandas|dataframe|transactions
1
353,182
62,711,330
Create a categorical variable in dataframe from dictionary
<p>What is the best way to convert a dictionary with the numbers of a category into a column in a Dataframe?</p> <p>The number of categories in the dictionary is variable, however the total sum of each value in the dictionary equals the length of the Data Frame.</p> <p>The only important aspect is to preserve the corre...
<p>Here's one way of doing that. Broke the list comprehension part to two for clarity:</p> <pre><code>dic = {&quot;A&quot;:2 , &quot;B&quot;: 3 , &quot;C&quot; : 1, &quot;D&quot; : 3 } l1 = [[k] * v for k, v in dic.items()] l2 = [i for l in l1 for i in l] df[&quot;Cat&quot;] = pd.Series(l2, dtype=&quot;category&quot;...
python|pandas|dictionary|categorical-data
1
353,183
62,649,364
Unable to get the summary while building custom model using tensorflow
<p>I have a very simple model as shown below:</p> <pre><code>import tensorflow as tf class Model(tf.keras.Model): def __init__(self, input_shape=None, name=&quot;cus_model&quot;, **kwargs): super(Model, self).__init__(name=name, **kwargs) def build(self, input_shape): self.dense1 = tf....
<p>I was able to build the network by modifying the line</p> <pre><code>model.build(input_shape=input_shape) # Note the .build call </code></pre> <p>with</p> <pre><code>_ = model(tf.zeros([1,10])) </code></pre> <p>From <a href="https://www.tensorflow.org/tutorials/customization/custom_layers#implementing_custom_layers"...
python|tensorflow|tensorflow2.0
4
353,184
62,567,406
Pandas: Check if a substring exists in another column then create a new column with a specific value
<p>I have this dataframe:</p> <pre class="lang-py prettyprint-override"><code>Receipt Description Card Member Account Cost 200a apple adam 08203928 $2 20022a pear bob 08203228 $7 202a orange alice 0820321228 $8 </code></pre> <p>I want to check if a value in the <code>description</code> column contains a specific subst...
<p>You can try this:</p> <p><strong>Example 1:</strong></p> <pre><code>df[&quot;**Data**&quot;] = df[&quot;Description&quot;].map(lambda x: &quot;apple containes&quot; if &quot;appl&quot; in x else '') </code></pre> <p><strong>Example 2</strong></p> <p>If you have mapping of every fruit to check then you could create l...
python|pandas
7
353,185
62,835,973
How to groupby and count values in a specific column
<p>I have a dataframe <em>procs</em>, where each month several <strong>id</strong>s took place, and also each <strong>id</strong> took place several times:</p> <p><code>procs.groupby(['month', 'id']).size()</code></p> <pre><code>month id 2015-02 UA-2015-02-06-000018-L1 ...
<p>As far as I understand from below comments you want group of groups :</p> <pre class="lang-py prettyprint-override"><code>procs.groupby(['month','id'])['month'].count().groupby(['month']).count() </code></pre>
python|pandas
1
353,186
62,710,350
Is it possible to force datatype of tensorflow op?
<p>I'm using mixed precision computations in Tensorflow and I would like to force certain ops to be computed on float32. I'd like to do something like:</p> <pre><code>relu = tf.nn.relu(input, dtype='float32') </code></pre> <p>This doesn't work because there's no keyword argument 'dtype' for this operation. It's just to...
<p>You can cast your input before feeding it into <code>tf.nn.relu</code> by using <a href="https://www.tensorflow.org/api_docs/python/tf/cast" rel="nofollow noreferrer"><code>tf.cast</code></a>:</p> <p><code>relu = tf.nn.relu(tf.cast(input, dtype=tf.float32))</code></p>
tensorflow
0
353,187
62,819,742
How to convert all the values in a column, from thousands to billions? Using Pandas
<p>I wish to convert the columns imfGDP, gdpPerCapita and pop to billions.</p> <p>[Data frame] <a href="https://i.stack.imgur.com/6JHHZ.png" rel="nofollow noreferrer">https://i.stack.imgur.com/6JHHZ.png</a></p>
<p>Converting gdpPerCapita and pop to billions is really very easy. Just do this:</p> <pre><code>df['gdpPerCapita in bn)']=df['gdpPerCapita']/1000000 #converting thousands into billions #by simply dividing each value with ...
python|pandas|jupyter-notebook
1
353,188
62,612,485
Discard more than 25% missing data using pandas
<p>I have a csv file with more than 30K lines. Some of these lines contain NA values and I would like to discard the one that have more than 25% missing value. I have tried with the pandas command dropna() but I can only use the command &quot;any&quot; or &quot;all&quot;. Which line of code should I use to discriminate...
<p>Update: one line answer based on <a href="https://stackoverflow.com/questions/43311555/how-to-drop-column-according-to-nan-percentage-for-dataframe">similar question</a>:</p> <pre class="lang-py prettyprint-override"><code>df = df[ df.isna().mean(axis=1) &lt;= 0.25 ] </code></pre> <hr /> <p>Assuming that you have th...
python|pandas
0
353,189
62,629,179
How can I manipulate a DataFrame name within a function?
<p>How can I manipulate a DataFrame name within a function so that I can have a new DataFrame with a new name that is derived from the input DataFrame name in return?</p> <p>let say I have this:</p> <pre><code>def some_func(df): # some operations return(df_copy) </code></pre> <p>and whatever df I put inside this ...
<p>It looks like you're trying to access / dynamically set the global/local namespace of a variable from your program.</p> <p>Unless your data object belongs to a more structured <a href="https://docs.python.org/dev/library/argparse.html#argparse.Namespace" rel="nofollow noreferrer">namespace object</a>, <em><strong>I'...
python|pandas|dataframe
1
353,190
62,545,663
Spliting datasets with tfds
<p>I am trying to split <code>tf_flower</code>dataset using <code>tfds.Split</code></p> <pre><code>import tensorflow_datasets as tfds splits = tfds.Split.TRAIN.subsplit(weighted=[80,10,10]) (raw_train, raw_val, raw_test), metadata = tfds.load('tf_flowers', split=lis...
<p>Trying to run your code in TF 2, I didn't get the error you specified, but a different one,</p> <pre><code>AssertionError: Unrecognized instruction format: NamedSplit('train')(tfds.percent[0:80]) </code></pre> <p>However, I was able to get the following to work.</p> <pre><code>(raw_train, raw_val, raw_test), metadat...
python|tensorflow2.0
2
353,191
62,877,425
Validation loss curve is flat and training loss curve is higher than validation error curve
<p>I'm building a LSTM model for prediction senario. My dataset has around 248000 piece of data and I use 24000 (around 10%) as validation set, others are training set. My model learning curve is the following: <a href="https://i.stack.imgur.com/98F8B.png" rel="nofollow noreferrer">learning curve</a></p> <p>The validat...
<p>It might be that, first, your underlying concept is very simple which leads to extremely low validation error early on. Second, your data augmentation makes it harder to learn, which yields higher training error.</p> <p>Yet, I would still run a couple of experiments in your case. First: divide data as 10/90 instead ...
tensorflow|model
0
353,192
62,756,064
aggregating columns in pandas dataframes
<p>I am working with the covid19 datasets for Germany. Aggregating the number of <code>cases</code>, <code>deaths</code> and <code>recovery</code> by month for Germany gives me the same value. What could be wrong? Inspecting the <code>dataframe</code> shows me that they are not same.</p> <pre><code>covid19_data.set_ind...
<p>If you are aggregating, you should be summing the values right?</p> <pre><code>covid19_data.set_index(&quot;Date&quot;).resample(&quot;M&quot;).agg({&quot;deaths&quot;: &quot;sum&quot;, &quot;cases&quot;: &quot;sum&quot;, ...
python|python-3.x|pandas|dataframe|pandas-groupby
0
353,193
62,517,586
Compare two dataframe columns for matching strings or are substrings then count in pandas
<p>I have two dataframes (A and B). I want to compare strings in A and find a match or is contained in another string in B. Then count the amount of times A was matched or contained in B.</p> <pre><code> Dataframe A 0 &quot;4012, 4065, 4682&quot; 1 &quot;4712, 2339, 5652, 10007&quot; 2 &quot;4618, 8987&quot;...
<p>You can try something like this, using <a href="https://stackoverflow.com/questions/31390476/how-to-check-if-all-items-in-a-sub-list-are-in-a-list-python"><code>all</code></a>, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>apply</code...
python|pandas
2
353,194
62,770,964
Is there a native 'MinMaxScaler' in tensorflow?
<p>I need to normalize my data with something similar to <code>sklearn.MinMaxScaler</code> but I need to use native TensorFlow ONLY and to apply it to TensorFlow <code>Dataset</code> API.</p> <p>How can it be done?</p>
<p>Try this:</p> <pre><code>tf.keras.utils.normalize(x, axis=-1, order=2) </code></pre> <p>The detailed documentation is available here:</p> <p><a href="https://www.tensorflow.org/api_docs/python/tf/keras/utils/normalize" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/utils/normalize</a><...
tensorflow|machine-learning|keras|scikit-learn
2
353,195
62,734,780
Alternative to np.arange or np.linspace with non-uniform intervals
<p>I can get a uniform grid on <code>[0,2*pi)</code> with numpy's function <code>np.arange()</code>, however, I would want a grid with the same number of points but having more density of points on certain interval, i.e having a finer grid on<code> [pi,1.5*pi]</code> for example. How can I achieve this, is there a nump...
<p>I'm surprised that I can't find a similar Q&amp;A on Stack Overflow. There are a few on doing something similar for <a href="https://stackoverflow.com/questions/4265988/generate-random-numbers-with-a-given-numerical-distribution">random numbers from a discrete distribution</a>, but not for continuous distributions a...
python|numpy|scipy
4
353,196
62,561,870
Plot segments along axis using start and end points in python (like a stacked bar graph)
<p>I'm trying to plot segments along an axis using a PANDAS dataframe that contains their start and end numbers, and I was wondering if it's possible to do this in python. Here's an exmaple of what the data looks like:</p> <pre><code>ID start end A 94 97 B 20 22 B 22 35 A 63 92 </code></p...
<p>You can do a <code>plt.bar</code>:</p> <pre><code>colors = df.ID.map({'A':'C0', 'B': 'C1'}) plt.bar([1]*len(df), df.end-df.start, bottom=df.start, color=colors, edgecolor='k') </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/zjV0x.png" rel="nofollow noreferrer"><img src="https://i.stack.im...
python|pandas|matplotlib|plot|graph
0
353,197
62,803,267
Flipping numpy array axes based on values in second array
<p>Currently writing a custom data generator for Keras and I'm looking to randomly flip a numpy input array during training for data augmentation purposes.</p> <ul> <li><code>X</code>: input array of shape <code>(batchsize, y_dim, x_dim)</code></li> <li><code>to_flip</code>: boolean array of shape <code>(batchsize, X_r...
<p>You can do it using python indexing as follows,</p> <pre class="lang-py prettyprint-override"><code>flipped_X = [] for sample, flip in zip(X, to_flip): flipped = [*sample] # Generate a copy of x if flip[0]: # if flip[0] is 1 flipped = flipped[::-1] ...
python|arrays|numpy|keras|flip
0
353,198
62,703,425
Differences between MATLAB and Numpy/Scipy FFT
<p><strong>EDIT</strong>: As it turns out this is still a question of floating point rounding error like others. The asymmetry in fft vs ifft absolute error comes from the difference in the magnitudes of the numbers (1e10 vs 1e8).</p> <hr /> <p>So there are many questions about the differences between Numpy/Scipy and M...
<p>As it turns out this is still a question of floating point rounding error like all the other MATLAB vs numpy fft questions.</p> <p>For my data the output of the fft function has numbers on the order of 1e10. This means that a precision of around 1e-16 on a float of this size is an absolute error less than or equal t...
python|matlab|numpy|scipy|fft
1
353,199
62,655,312
Why did the following code work instead of rename()?
<p>I tried to use <code>rename()</code> but it didn't work. I ended up using the following code. I want to understand these two lines and why it worked instead of <code>rename()</code>.</p> <p>This code worked:</p> <pre class="lang-py prettyprint-override"><code>df = df[['1999q4', 9926.1]] df.columns = ['Quarter','GDP'...
<p>I tried solving the code you shared and its working fine: Say you have a dataframe like this (I added your columns as well):</p> <pre><code>` import pandas as pd df = pd.DataFrame({'a': ['yes', 'no', 'yes'], b': [10, 5, 20], &quot;1999q4&quot;: [1, 2, 3], 9926.1: [2, 3, 4]}) df ` </code></pre> <p>Now if you do this...
python|pandas
1