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
11,000
58,896,556
Calulating number of series in python pandas
<p>I wanted to calculate the number of series present in the given data.</p> <p>I need this information for <em>the time-series</em> count.</p> <p><a href="https://i.stack.imgur.com/VHQvw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VHQvw.png" alt="Here is the data"></a></p> <p>Here I would lik...
<p>IIUC, You want <code>GroupBy.ngroups</code>:</p> <pre><code>df.groupby(['Region','Country','Sales']).ngroups #8 Output </code></pre>
python|pandas|numpy|dataframe|time-series
1
11,001
70,052,088
Python while true statement - will not take the input as a variable to use
<p>I am trying to get from either choice the variables start_date and end_date to use later in my program. But the code does not return either. The values for start_date and end_date are still values entered ealrier and still in memory. Any ideas how to fix? Thanks.</p> <pre class="lang-py prettyprint-override"><cod...
<p>Couple of things need to be changed</p> <ol> <li>Indentation - the while loop is outside of the function</li> <li>No need of break after return</li> <li>When a function is returning values, need to capture them in variables.</li> </ol> <p>I have made these changes and hopefully this is what you are expecting</p> <pr...
python|pandas|dataframe|while-loop
1
11,002
56,353,747
How to count the elements belonging to one label class in a custom keras loss function?
<p>I'm looking for a way to count to number of occurrences of each class in the y_true array in a custom loss function and replace each element in the array with its respective number of occurrences.</p> <p>I've already implemented a numpy solution, but I can't seem to translate it into keras (with tf backend).</p> <...
<p>Try <code>tf.bincount</code> and <code>tf.gather</code>.</p> <pre><code>import tensorflow as tf y_true = tf.constant([0, 1, 1, 1, 0, 3],dtype=tf.int32) bins = tf.bincount(y_true) y_true_counts = tf.gather(bins,y_true) with tf.Session()as sess: print(sess.run(bins)) print(sess.run(y_true_counts)) [2 3 0 1...
python|numpy|tensorflow|keras|loss-function
1
11,003
56,003,095
no add_to_collection was found when using tensorflowjs_converter
<p>I am trying to convert a savedModel into TensorFlow.js web format.</p> <p>I installed tensorflowjs via <code>sudo pip3 install tensorflowjs</code></p> <p>When running <code>tensorflowjs_converter--input_path=full_path_to/saved_model/saved_model.pb --outputpath=full_path_to/js</code></p> <p>I get an error saying ...
<p>Problem solved by downgrading tensorflowjs 1.0.1 to 0.6.4</p>
python-3.x|tensorflowjs-converter
2
11,004
55,952,354
List of dates from DatetimeIndex object
<p>I have a <code>DatetimeIndex</code> object comprised of two dates given as follows:</p> <pre><code>import pandas as pd timestamps = pd.DatetimeIndex(['2014-1-1', '2014-1-2'], freq='D') </code></pre> <p>which looks like this:</p> <pre><code>DatetimeIndex(['2014-01-01', '2014-01-02'], dtype='datetime64[ns]', freq='...
<p>to_native_types() converts the values of timestamps to str format and then tolist() creates a list of str (dates). </p> <pre><code>timestamps.to_native_types().tolist() </code></pre> <p>Output</p> <pre><code>['2014-01-01', '2014-01-02'] </code></pre>
python|pandas|list|datetimeindex
5
11,005
64,988,038
TensorFlow Checkpoint restoring Learning rate
<p>I am trying to use <code>TensorFlow checkpoint</code>, everything is working well except for the <code>Learning rate</code>. It is getting re-initialized every time I run and does not restore from the previous.</p> <p>Here is a toy example I am trying to replicate the problem:</p> <pre><code>import numpy as np impor...
<p>I found the fix and thought of leaving this post, may be it may help someone in the future.</p> <p>Had to add <code>self.global_step = tf.Variable(1, trainable=False)</code></p> <p>Here is the full script;</p> <pre><code>import numpy as np import tensorflow as tf from matplotlib import pyplot as plt X = tf.range(1...
python-3.x|tensorflow|tensorflow2.0|checkpoint
0
11,006
64,726,866
How to multiply a 3D numpy array in Python to get a 2D numpy array?
<p>Let's say I have the following array A, where the right-hand-side is its '.shape':</p> <p><code>A.shape = (10000, 10, 10)</code></p> <p>and I would like to get <code>C.shape = (10000,10)</code> such that: for each 10x10 matrix in A (out of 10000 ones), it is reduced to a 1D vector (10,1) of the sum of each row, henc...
<p>The simplest solution is:</p> <pre><code>import numpy as np C = np.sum (A, axis=2) </code></pre> <p><strong>Alternative Solution 1 (Reduce):</strong></p> <p>If you want to use the <code>reduce()</code> function, use this:</p> <pre><code>import numpy as np C = np.add.reduce (A, 2) </code></pre> <p>Here,<code>2</code>...
python|arrays|numpy|multidimensional-array|vectorization
0
11,007
64,817,406
Fetching particular rows of a csv file where date matches as entered by user?
<p><a href="https://i.stack.imgur.com/pFcg0.png" rel="nofollow noreferrer">enter image description here</a>i have a csv file like</p> <pre><code>Slot object Name object Plate object Date_of_reg datetime64[ns] dtype: object </code></pre> <p>I was working on a parki...
<p>The empty database was being created as np.datetime64 is no longer comparable to datetime.datetime so that waa the problem</p>
python|pandas|csv|datetime64|csvreader
2
11,008
64,789,818
Need a list of row-values in pandas
<h3>What I have, and what I need</h3> <p>I have a pandas DataFrame <code>p</code> with cols <code>'a'</code>, <code>'b'</code>, <code>'c'</code> (col names stored in <code>pc</code>).</p> <p>From that I would like to create a DataFrame <code>pn</code> of the same shape, but each cell as a <strong>list of values</strong...
<p>You can explode the <code>n</code>, use that to slice <code>p</code> and groupby:</p> <pre><code>s = n['sel_row'].explode() p.loc[s].groupby(s.index).agg(list) </code></pre> <p>Output:</p> <pre><code> a b c 1001 [11] [12] [13] 1002 [11, 21] [12, 22] [13, 23] </code></pre...
python|pandas|list|dataframe
3
11,009
64,845,490
Python pandas dataframe print ValueError: could not convert string to float: '1,971.25'
<p>I have a python pandas dataframe that should print with the following line:</p> <pre><code>close.loc[stock, str(j)+'_days_ago'] = float(stocks.iloc[[-1 - j]]['Close'].to_string(header=None, index=None)) </code></pre> <p>yet I get the following error:</p> <pre><code>ValueError: could not convert string to float: '1,9...
<p>You have to remove the <code>,</code> form the string (provided your decimal separator is the <code>.</code>.</p> <p>I.e. use</p> <pre><code>float('1,971.25'.replace(',', '')) </code></pre> <p>In your code it should be</p> <pre><code>close.loc[stock, str(j)+'_days_ago'] = float(stocks.iloc[[-1 - j]]['Close'].to_stri...
python|pandas|dataframe
1
11,010
40,201,705
Install tensorflow python API on Android gnuroot
<p>I've installed Debian+python on an android table with GNURoot. Now I'm trying to install tensorflow python API, so that I can "import tensorflow" in my python code. My tablet CPU is arm 32 bits, so I can not install with pip because tensorflow only supports 64 bits.</p> <p>I thus try to compile tensorflow from sour...
<p>Unfortunately building TensorFlow Python requires Bazel (for just C++ inference you can use the instructions at tensorflow/contrib/makefile), and this is quite an involved and buggy process. The best place to start is this post on setting things up on the Jetson board:</p> <p><a href="http://cudamusing.blogspot.com...
android|python|tensorflow
2
11,011
44,345,684
python / pandas from timetable to timedate dataframe
<p>i have a set of data like this:</p> <pre><code> Unnamed: 0 0:30 1:00 1:30 2:00 2:30 3:00 3:30 4:00 4:30 ... \ 0 2016-01-01 26.9 26.4 26.9 26.1 26.4 26.7 26.5 25.5 25.4 ... 1 2016-01-02 26.8 25.9 25.7 26.0 25.2 25.3 25.6 25.0 25.1 ... 2 2016-01-03 25.6 25.4 25.2 2...
<p>You can use pandas stack() for this</p> <pre><code>df.set_index('Unnamed: 0').stack().reset_index() Unnamed: 0 level_1 0 0 2016-01-01 0:30 26.9 1 2016-01-01 1:00 26.4 2 2016-01-01 1:30 26.9 3 2016-01-01 2:00 26.1 4 2016-01-01 2:30 26.4 5 2016-01-01 3:00 26.7 6 2016-01-01 ...
python|pandas
2
11,012
44,045,893
Pandorific dayofyear Comparison with Leap Years
<p>I'm a Pandas newbie and trying to do year over year comparisons for some years that include leap years. They 'dayofyear' function is great..except when there are leap years. Here's my code:</p> <pre><code>df = pd.read_csv('myfile.csv') df['Date'] = pd.to_datetime(df['Date']) df['Day_of_Year'] = df['Date'].dt.dayo...
<p>You could make up an arbitrary index for each day like this:</p> <p><code>df['Day_of_Year'] = df['Date'].dt.month*31 + df['Date'].dt.day</code></p> <p>In this way, entries with the same 'Day_of_Year' value will correspond to the same date, irrespective of leap years.</p>
python|python-3.x|pandas|leap-year
2
11,013
44,107,716
Standardizing numpy array in Keras
<p>After I trained my model in Keras, it is time for prediction, so I am using some data in order to check my model on. However, the trained model is standardized before training (Very different range of values).</p> <p>So in order to predict on some data, I should standardize it too:</p> <pre><code>packet = numpy.ar...
<p>This actually comes from the fact that you have only one example in your dataset. When you call <code>fit</code> on a table with one example - a mean of each column is computed - but in case when you have only one number in each column - this <code>mean</code> is equal to first (and only) row. That's why you are obt...
python|numpy|keras|standardized
1
11,014
44,197,916
How to insert a pandas dataframe into elasticsearch with the column types?
<p>I want index a <strong>pandas</strong> data frame into <strong>elasticsearch</strong> server. One of my columns is <strong>Timestamp</strong> and some of them are numbers and some are string. How can I import this type of dataframe in elasticsearch. I know that I can use <strong>_bulk API</strong> but I don't know H...
<p>By this function you can insert a pandas dataframe into elasticsearch easily. But for time column you have to apply map to time fieldName before insert dataframe.</p> <pre><code>def insertDataframeIntoElastic(dataFrame,index='index', typ = 'test', server = 'http://192.168.11.148:9200', ch...
python|pandas|elasticsearch
4
11,015
44,314,337
python - Convolution of 3d array with 2d kernel for each channel separately
<p>I have a matrix of size <code>[c, n, m]</code> where <code>c</code> is a number of channels; <code>n</code> and <code>m</code> are width and height. In the particular example I have a matrix that has 1000 channels. I want to make a convolution with a kernel of the size <code>a x a</code> for each channel separately....
<p>I think you just need to make you kernel three-dimensional. Something like this ought to work:</p> <pre><code>kernel = kernel[:, :, None] </code></pre> <p>If <code>scipy.ndimage.convolve</code> doesn't work for 3D arrays, you could try <code>scipy.signal.convolve</code>.</p>
python|numpy|scipy|convolution
12
11,016
44,039,146
How to connect boxplot median values
<p>It seems like plotting a line connecting the mean values of box plots would be a simple thing to do, but I couldn't figure out how to do this plot in pandas. </p> <p>I'm using this syntax to do the boxplot so that it automatically generate the box plot for Y vs. X device without having to do external manipulation o...
<p>You can save the axis object that gets returned from <code>df.boxplot()</code>, and plot the means as a line plot using that same axis. I'd suggest using Seaborn's <a href="http://seaborn.pydata.org/generated/seaborn.pointplot.html#seaborn.pointplot" rel="noreferrer"><code>pointplot</code></a> for the lines, as it ...
python|pandas|plot|line|boxplot
6
11,017
44,146,876
How to truncate datestring in pandas to_json datetime
<p>I have the following code:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; df = pd.DataFrame({"a" : [datetime(2017, 1, 3), datetime(2017, 2, 4)], "b" : [2, 4]}) &gt;&gt;&gt; df a b 0 2017-01-03 2 1 2017-02-04 4 &gt;&gt;&gt; df.to_json(orient = "index", date_format = "iso") '{"0"...
<p>You can cast them to string and then export:</p> <pre><code>df.astype(str).to_json(orient = "index", date_format = "iso") Out[45]: '{"0":{"a":"2017-01-03","b":"2"},"1":{"a":"2017-02-04","b":"4"}}' </code></pre>
python|pandas|datetime
0
11,018
69,422,478
Modify column B values based on the range of column A
<p>Following is my test dataframe:</p> <pre><code>df.head(25) freq pow group avg 0 0.000000 10.716615 0 NaN 1 0.022888 -9.757687 0 NaN 2 0.045776 -9.203844 0 NaN 3 0.068665 -8.746512 0 NaN 4 0.091553 -8.725540 0 NaN ... 95 2.174377 ...
<p>You can use -</p> <pre><code>df.loc[(df['freq'] &gt;= 1) &amp; (df['freq'] &lt;= 1.2), 'group'] = 2 </code></pre> <p>in the same way for <strong>mean-</strong></p> <pre><code>df.loc[(df['freq'] &gt;= 1) &amp; (df['freq'] &lt;= 1.2), 'avg'] = df[(df['freq'] &gt;= 1) &amp; (df['freq'] &lt;= 1.2)]['pow'].mean </code></...
python|pandas|dataframe
1
11,019
69,549,126
Tensorflow TypeError: Cannot convert 1e-12 to EagerTensor of dtype int32
<p>I have a multiclass classification machine learning application for which I want to calculate the f1 score using tensorflow. The predicted and actual values are stored in pandas dataframes <code>y_pred</code> and <code>y_act</code> respectively. Both are populated with 1's and 0's. So I do something like this:</p> <...
<p>This is the code sample provided on the tfa api docs:</p> <pre><code>metric = tfa.metrics.F1Score(num_classes=3, threshold=0.5) y_true = np.array([[1, 1, 1], [1, 0, 0], [1, 1, 0]], np.int32) y_pred = np.array([[0.2, 0.6, 0.7], [0.2, 0.6, 0.6], ...
python|pandas|numpy|tensorflow|tensor
1
11,020
41,208,119
Casting a bytearray containing 11-bit integers to an array of 16-bit integers
<p>I have a bytes object or bytearray object representing a packed stream of 11-bit integers. (Edit: Stream is 11-bit big-endian integers without padding.)</p> <p>Is there a reasonably efficient way of copying this to a stream of 16-bit integers? Or any other integer type?</p> <p>I know that ctypes supports bit field...
<p>There may be a more efficient way to do this with a 3rd-party library, but here's one way to do it with standard Python. </p> <p>The <code>unpack</code> generator iterates over its <code>data</code> argument in chunks, <code>data</code> can be any iterable that yields bytes. To unpack 11 bit data we read chunks of ...
python|arrays|numpy|cython|ctypes
2
11,021
41,189,780
python, openCv, chain code -> i would like to find angles between the points
<p>I'm new here and i need your HELP !!!! I'm making a project (hand gesture recognition for my school), so the image which is imread is my hand. I'm would like to find angles between the points ( in chain code )</p> <p>Thank you in advance :)</p> <pre><code>import cv2 import cv2.cv as cv import numpy as np # Create...
<p>To find the angle given <code>dY</code> and <code>dX</code>, use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.arctan2.html" rel="nofollow noreferrer"><code>numpy.arctan2(dY, dX)</code></a>. It handles <code>dX = 0</code> correctly.</p>
python|opencv|numpy
1
11,022
53,961,640
Alter Keras model for validation step
<p>I have a model that differs during the training and inference. More precisely, it is a SSD (Single Shot Detector) that requires additional DetectionOutput layer to be added on the top of its training counterpart. In Caffe, one can use the 'include' parameter in the layer definition to turn layers on/off. </p> <p>Bu...
<p>You should use the headless (without DetectionOutput) model for training, but provide a model with the top layer to the evaluation:</p> <pre><code>def add_detection_output(model): # make validation/inference model here ... evaluation = SSDEvaluation(model=add_detection_output(model), ...
python|tensorflow|keras
1
11,023
54,039,614
Vectorize Function over Groups
<p>I have some values (X) that belong to various groups (G). I would like (N) to divide each value by the maximum value in the group, as shown in this table:</p> <p><a href="https://i.stack.imgur.com/I3Ngx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I3Ngx.jpg" alt="enter image description here">...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.transform.html" rel="nofollow noreferrer"><code>transform</code></a>: </p> <pre><code>df['N'] = df['X']/df.groupby('G')['X'].transform('max') </code></pre>
pandas|grouping
2
11,024
54,173,689
Take Flask Form Data Input and Turn it Into Pandas Dataframe For ML Modeling
<p>I'm building a small flask application to take in form data from an HTML. I'd like to convert this form data (each selection get put into a column) into a Pandas DataFrame. I will then use a pickle file to create a prediction off this DataFrame. Problem i'm having now is not knowing how to convert the data I have in...
<p>Convert <strong>HTML form input</strong> to <strong>Dictionary</strong> and then to <strong>Pandas dataframe</strong></p> <pre><code>@app.route('/predict/&lt;target&gt;',methods=['GET','POST']) def predict(target): d = None if request.method == 'POST': print('POST received') d = request.form....
python|pandas|flask
0
11,025
54,083,220
Why does this semantic segmentation network have no softmax classification layer in Pytorch?
<p>I am trying to use the following CNN architecture for semantic pixel classification. The code I am using is <a href="https://github.com/meetshah1995/pytorch-semseg/blob/master/ptsemseg/models/segnet.py" rel="nofollow noreferrer">here</a></p> <p>However, from my understanding this type of semantic segmentation netwo...
<p>You are using quite a complex code to do the training/inference. But if you dig a little you'll see that the loss functions are implemented <a href="https://github.com/meetshah1995/pytorch-semseg/blob/master/ptsemseg/loss/loss.py" rel="nofollow noreferrer">here</a> and your model is actually trained using <a href="h...
neural-network|deep-learning|conv-neural-network|pytorch
3
11,026
66,145,041
Converting a pandas dataframe column in "Wed May 27 07:13:23 EDT 2020" format to datetime
<p>How do I convert an object column in &quot;Wed May 27 07:13:23 EDT 2020&quot; format to datetime in pandas dataframe?</p>
<p>You can just let Pandas try:</p> <pre><code>pd.to_datetime(['Wed May 27 07:13:23 EDT 2020']) </code></pre> <p>Output:</p> <pre><code>DatetimeIndex(['2020-05-27 07:13:23-04:00'], dtype='datetime64[ns, pytz.FixedOffset(-240)]', freq=None) </code></pre>
python-3.x|pandas
0
11,027
66,228,127
how to replace a match word with other word in python?
<p>I am new to python, I have an issue with replacing. SO I have a list and a string I want to replace the word of string if it matches the word in the list. I have tried it but I am not getting the excepted output. Like below:-</p> <pre><code>str = &quot;'hi'+'bikes'-'cars'&gt;=20+'rangers'&quot; list = [df['hi'],df['...
<p>If you are sure that the column names are always alphabets then simply use</p> <pre class="lang-py prettyprint-override"><code>import re s = &quot;'hi'+'bikes'-'cars'&gt;=20+'rangers'&quot; s2 = re.sub(r&quot;('[A-Za-z]+')&quot;, r'df[\1]', s) </code></pre> <pre><code>&quot;df['hi']+df['bikes']-df['cars']&gt;=20+df...
python|pandas|string|list
1
11,028
66,283,370
Pandas create new dataframe by querying other dataframes without using iterrows
<p>I have two huge dataframes that both have the same id field. I want to make a simple summary dataframe where I show the maximum of specific columns. I understand <code>iterrows()</code> is frowned upon, so are a couple one-liners to do this? I don't understand lambda/apply very well, but maybe this would work here.<...
<p>you can try <code>concat+groupby.max</code></p> <pre><code>out = (pd.concat((df1,df2),sort=False).groupby(['myid','name']).max() .add_prefix(&quot;Max_&quot;).reset_index()) </code></pre> <hr /> <pre><code> myid name Max_x Max_y 0 1 A 15.0 9.0 1 2 B 3.0 6.0 2 3 C 3.0 ...
python|pandas
2
11,029
52,511,980
Convert pandas columns of arrays to reshaped np.array
<p>I have the following pandas dataframe:</p> <pre><code>col1 col2 col3 2 [0.006576649077136777, 0.0030259599523339924, ... [0.00567579212503948, -0.005498750236370691, 0... [-0.015786838188947716, 0.0042899171402874135,... 3 [-0.44547847984244543, -0.4482984342731749, 0.... [-0.02218552412064...
<p>Question is not completely clear, but if i understand right you have this:</p> <pre><code>df = pd.DataFrame({ "col1": [np.random.rand(7190) for i in range(30)], "col2": [np.random.rand(7190) for i in range(30)], "col3": [np.random.rand(7190) for i in range(30)] }) </code></pre> <p>N...
python|pandas|numpy|matrix
0
11,030
46,386,432
Match until first occurrence only
<p>My pandas dataframe column <code>center</code> looks as follows:</p> <pre><code>In [6]: df.center.head() Out[6]: 0 /Users/sachin/uniwork/IMG/center_2017_09_17_20... 1 /Users/sachin/uniwork/IMG/center_2017_09_17_20... 2 /Users/sachin/uniwork/IMG/center_2017_09_17_20... 3 /Users/sachin/uniwork/IMG/center_...
<p>Another method with the help of split though I prefer regex i.e </p> <pre><code>df.center.apply(lambda x : '/IMG'+x.split('IMG')[-1]) </code></pre> <p>Output: </p> <pre> 0 /IMG/center_2017_09_17_20... 1 /IMG/center_2017_09_17_20... 2 /IMG/center_2017_09_17_20... 3 /IMG/center_2017_09_17_20... 4 /IM...
python|regex|pandas
3
11,031
46,551,951
Merge two dataframes with multi-index
<p>I have seen several posts about this but I could not get my head around how merge, join and concat would deal with this. How can I merge two dataframes to find matching indexes?</p> <p>in:</p> <pre><code>import pandas as pd import numpy as np row_x1 = ['a1','b1','c1'] row_x2 = ['a2','b2','c2'] row_x3 = ['a3','b3',...
<p><strong>Option 1</strong><br> Use <code>pd.DataFrame.reindex</code> + <code>pd.DataFrame.join</code><br> <code>reindex</code> has a convenient <code>level</code> parameter that allows you to expand on the index levels not present. </p> <pre><code>df1.join(df2.reindex(df1.index, level=0)) A B C D...
python|pandas|merge|concat|multi-index
19
11,032
58,318,195
How to bypass portion of neural network in TensorFlow for some (but not all) features
<p>In my TensorFlow model I have some data that I feed into a stack of CNNs before it goes into a few fully connected layers. I have implemented that with Keras' <code>Sequential</code> model. However, I now have some data that should not go into the CNN and instead be fed directly into the first fully connected layer ...
<p>Here is an simple example in which the operation is to sum the activations from different subnets:</p> <pre><code>import keras import numpy as np import tensorflow as tf from keras.layers import Input, Dense, Activation tf.reset_default_graph() # this represents your cnn model def nn_model(input_x): feature_...
python|tensorflow|keras
1
11,033
69,150,305
dataframe drop time values outside of range: seeking efficiency boost
<p>Need to exclude rows with <code>Time</code> outside of 9:30-16:00 (inclusive of 9:30 &amp; 16:00).</p> <pre><code> Symbol Time Open High Low Close Volume LOD Sessions 0 AEHR 2021-08-11 04:33:00 6.52 6.52 6.52 6.52 200 NaN NaN 1 AEHR 2021...
<p>Try this two-liner:</p> <pre><code>df['Time'] = pd.to_datetime(df['Time']) df = df.loc[df['Time'].ge(&quot;09:30:00&quot;) &amp; df['Time'].le(&quot;16:00:00&quot;)] </code></pre> <hr /> <pre><code>print(df) </code></pre>
pandas|database|dataframe|filtering
0
11,034
69,281,046
How to change clipping and noise parameters during differentially private training with Tensorflow Federated
<p>I'm using Tensorflow Federated (TFF) to train with differential privacy. Currently I am creating a Tensorflow Privacy NormalizedQuery and then passing it into a TFF DifferentiallyPrivateFactory to create an AggregationProcess:</p> <pre><code>_weights_type = tff.learning.framework.weights_type_from_model(placeholder_...
<p>I can think of two ways to do what you want: the easy way and the right way.</p> <p>The right way is to make a new type of DPQuery that keeps track of the training round in its global state and adjusts the clip and stddev the way you want in its <code>get_noised_result</code> function. Then you can pass this new DPQ...
tensorflow-federated
2
11,035
68,884,833
Precision recall
<p>can some tell me what does closest_zero, closest_zero_p and closest_zero_r mean?</p> <pre><code>from sklearn.metrics import precision_recall_curve precision, recall, thresholds = precision_recall_curve(y_test, y_scores_lr) closest_zero = np.argmin(np.abs(thresholds)) closest_zero_p = precision[closest_zero] closest_...
<p>First we have <code>y_test</code> which is the ground-truth and supposed to be of a binary type - two classes (0 and 1 usually). Also, we have <code>y_scores_lr</code> which is the prediction values that are continuous. <code>precision_recall_curve</code> is a function calculating the values to draw a recall-precis...
python|numpy|machine-learning|data-science|precision-recall
0
11,036
69,121,533
Tensorflow 2.2: custom gradient for a vector valued input/output custom layer
<p>I am using tensorflow 2.2 for my research and would like to implement a custom layer that takes in a vector(tensor) input and outputs a vector(tensor). My input/output relation is complicated and I need to create a function that computes the forward pass and the gradients. I came across the <a href="https://www.tens...
<p>I don't think you have to define your own <code>custom_grad</code> function if you don't need customized gradient computation.</p> <p>I would use <code>tf.GradientTape</code> outside of the layer call. The gradient tape watches the trainable variables and the operations performed on them. The <code>tape.gradient</co...
python|tensorflow|keras
0
11,037
68,998,206
How do I store binary .wav data in a file?
<p>I'm trying to get .wav data stored in a txt-file in C array format to copy into a C program. This is done in a jupyter notebook running locally. The file has 16kHz and int16 PCM format.</p> <pre><code>from scipy.io.wavfile import read import numpy a = read(&quot;sound.wav&quot;) numpy.array(a[1]) fd = open(&quot;wa...
<blockquote> <pre><code>numpy.array(a[1]) fd = open(&quot;wav_array.txt&quot;, 'w') numpy.ndarray.tofile(fd, ', ') </code></pre> </blockquote> <p>Rather than discarding the <code>numpy.array</code> and calling a static method, you meant:</p> <pre><code>with open(&quot;wav_array.txt&quot;, 'w') as fd: numpy.array(a[1])....
numpy|file|wav
0
11,038
44,553,073
Python Panda Percentages Calculations
<p>Trying to Calculate Percentages on Python Pandas</p> <pre><code> 1 2 0 A 0 1 A 1 2 A 2 3 B 0 4 B 0 5 B 1.5 6 B 0 </code></pre> <p>Output of Percentage of A's and B's with a score higher than 0. </p> <pre><code>A = 66% B = 25% </code></pre>
<pre><code>In [3]: df['2'].gt(0).groupby(df['1']).mean() Out[3]: 1 A 0.666667 B 0.250000 Name: 2, dtype: float64 </code></pre>
python|pandas|numpy
3
11,039
61,072,436
Add encoder.categores_ as column name in Pandas dataframe after using OneHotEncoder
<p>I am using the Titanic dataset. I have done oneHotEncoding on 3 categories survived,sex,cabin.</p> <pre><code>encoder = OneHotEncoder(categories='auto', drop='first', sparse=False, handle_unknown='error') encoder.fit(X_train.fillna('Missing')) tmp = encoder...
<p>encoder.categories_ is a matrix maybe, try index first element:</p> <p>Try this:</p> <pre><code>encoder = OneHotEncoder(categories='auto', drop='first', sparse=False, handle_unknown='error') encoder.fit(X_train.fillna('Missing')) tmp = encoder.transform(X_...
pandas|machine-learning|scikit-learn|one-hot-encoding|feature-engineering
0
11,040
60,877,440
PyTorch custom DataLoader dimension issues for CNN
<p>I have written a custom Dataset and DataLoader for a PyTorch CNN project. Here is the relevant code for the dataset</p> <pre><code>class MyDataset(Dataset): def __init__(self): pass def __len__(self): return COUNT def __getitem__(self, idx): x, y = X[idx], Y[idx] x = image_augment(x) # cu...
<p>I got it eventually. Had to <code>x = x.view(x.shape[0], 3, self.img_height, self.img_width).type('torch.FloatTensor')</code>. for example. This would make that swap from <code>[4, 32, 32, 3]</code> to <code>[4, 3, 32, 32]</code>.</p>
python-3.x|tensorflow|deep-learning|pytorch|tensor
0
11,041
61,032,062
PyTorch transferring index to 1-0
<p>How to quickly set the elements in the given index list to 1 and others to 0?</p> <p>For example,I have an ID pool like: <code>torch.arange(10)</code>, for a given input index <code>tensor([1,5,7,9,2])</code> wanna return <code>tensor([0,1,1,0,0,1,0,1,0,1])</code></p>
<p>Easiest is to start with <code>zeros</code> and fill with <code>ones</code> using fancy indexing like this:</p> <pre><code>import torch tensor = torch.zeros(10) tensor[[1, 5, 7, 9, 2]] = 1 </code></pre> <p>If your IDs are predefined (e.g. <code>torch.arange(10)</code>) and you want to get only those elements whic...
pytorch
1
11,042
71,518,310
How to intercept and feed intra-layer output as target data
<p>Sometimes we need to preprocess the data by feeding them through <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/experimental/preprocessing" rel="nofollow noreferrer">preprocessing</a> layers. This becomes problematic when your model is an autoencoder, in which case the input is both the x and th...
<p>You simply have to modify your loss function in order to minimize the difference between predictions and scaled inputs.</p> <p>This can be done using <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer#add_loss" rel="nofollow noreferrer">model.add_loss</a>.</p> <p>Considering a dummy reconstruc...
tensorflow|keras|tensorflow-datasets
1
11,043
71,713,114
OpenCV DNN inference with "training=True" for using sample mean and variance (Pix2Pix)
<p>I have trained a Pix2Pix network using Keras Tensorflow, following this tutorial. The Pix2Pix uses Instance Normalization, such that when doing inference, we would need to have the Instance Normalization layers (batch norm for batch size of 1) to compute the sample mean and variance. In Tensorflow, I would call the ...
<p>This question is actually <strong>focused on OpenCV instead of OpenVINO</strong>. For a deeper explanation, it's best to redirect this to their forum/platform as they are the proper expert for these.</p> <p>Generally, the <code>training</code> argument informs the Neural Network Layers on which path it should take s...
python|tensorflow|opencv|openvino|inference-engine
0
11,044
71,475,164
Build confusion matrix for instance segmantation (mask r-cnn from detectron2)
<p>I've trained a mask r-cnn on corn images (I cannot show examples because they are confidential), but they are basically pictures of corn kernels scattered over a flat surface.</p> <p>There are different kinds of corn kernels I want to be able to segment and classify. I understand the AP metrics are the best way of m...
<p>I was able to do it, I built the confusion matrix function from scratch:</p> <pre><code>import pandas as pd import torch from detectron2.structures import Boxes, pairwise_iou def coco_bbox_to_coordinates(bbox): out = bbox.copy().astype(float) out[:, 2] = bbox[:, 0] + bbox[:, 2] out[:, 3] = bbox[:, 1] + ...
python|pytorch|computer-vision|image-segmentation|detectron
2
11,045
71,443,446
select only record where the cumulated sum of (VolumePred) is less than 450
<p>I have a dataframe :</p> <pre><code> ConversionPred VolumePred OSBrowser PageId (11, 16) 955764 88273.0 125110.0 955761 78408.0 104703.0 1184903 57702.0 118085.0 955767 49224.0 68942.0 ...
<p>IIUC, try:</p> <pre><code>output = subdata[subdata.groupby(level=0).transform(&quot;cumsum&quot;).lt(450)] </code></pre>
python|python-3.x|pandas|dataframe
0
11,046
42,538,533
Calculate and plot 95% range of data on scatter plot in Python
<p>I wish to know, for a given predicted commute journey duration in minutes, the range of actual commute times I might expect. For example, if Google Maps predicts my commute to be 20 minutes, what is the minimum and maximum commute I should expect (perhaps a 95% range)?</p> <p>Let's import my data into pandas:</p> ...
<p>The relationship between actual duration of a commute and the prediction should be linear, so I can use <a href="http://statsmodels.sourceforge.net/devel/examples/notebooks/generated/quantile_regression.html" rel="nofollow noreferrer">quantile regression</a>:</p> <pre><code>%matplotlib inline import matplotlib.pypl...
python|pandas|statistics|scatter-plot|percentile
3
11,047
69,945,634
Groupby with condition, include 0 occurrences
<p>I have a dataset with week's worth of mobile pings. I want to know how many times on average do people go to gym, based on a group they're in, or based on where they're from.</p> <p>The 'problem' is, some people never go to the gym, and I want to include those too, otherwise the average gets very skewed.</p> <p><a h...
<p>You can do</p> <pre><code>out1 = df['Ping_coordinates'].eq(df['Local_gym_coordinates']).groupby(df['ID']).sum() out2 = out1.mean() </code></pre>
python|pandas
1
11,048
69,728,226
ValueError: ('Lengths must match to compare', (229025,), (1,))
<p>I'm working inside Jupyter notebook, and my understanding's that in the last line by calling <code> df_speed_full['cam_id'] == rand_cam_id</code> I label indices as <code>True</code> and <code>False</code>, and then pass them to outer <code>df_speed_full</code> to select only those with <code>True</code>. Yet someho...
<p>The complaint is on your <code>==</code> operation (visible by the fact that the special method <code>__eq__</code> is in the error traceback).</p> <p>When comparing DataFrame or Series objects like <code>A == B</code> the following happens:</p> <ol> <li>if <code>A</code> is a dataframe/series and <code>B</code> is ...
python|pandas
1
11,049
43,443,280
Pandas - check if a string column in one dataframe contains a pair of strings from another dataframe
<p>This question is based on another question I asked, where I didn't cover the problem entirely: <a href="https://stackoverflow.com/questions/43442591/pandas-check-if-a-string-column-contains-a-pair-of-strings/43442899?noredirect=1#comment73943120_43442899">Pandas - check if a string column contains a pair of strings<...
<p>This is my answer using comprehensions and <code>zip</code><br> Note, this checks substrings in <code>df1</code></p> <pre><code>c = df1.consumption.values.tolist() f = df2.food.values.tolist() a = df2.creature.values.tolist() check = np.array([[fd in cs and cr in cs for fd, cr in zip(f, a)] for cs in c]) check.a...
python|pandas|string-matching|boolean-expression
3
11,050
43,304,989
filter 3D signal using medilt on each component separately gives different results than filtering the signal at once
<p>I am using medfilt to filter a 3 dimensional array (a,b,c)</p> <pre><code> import scipy as sp import numpy as np a = np.random.rand(180000) b = np.random.rand(180000) c = np.random.rand(180000) </code></pre> <p>if I filter the 3 components separatly like this</p> <pre><code>...
<p>For the <code>2D</code> stacked array, we need to use <a href="https://docs.scipy.org/doc/scipy-0.13.0/reference/generated/scipy.signal.medfilt2d.html" rel="nofollow noreferrer"><code>2D</code> version of <code>median filter</code></a>, with the list of kernel sizes along each dimension.</p> <p>Thus, we would have ...
python|numpy|scipy
0
11,051
72,357,344
Pandas How to mapping two dataframes without remove unique value?
<p>I have two dataframes like this.</p> <pre><code>df1 id value1 0 002 10 1 003 10 2 004 20 3 005 20 df2 id value2 0 001 100 1 002 200 2 003 150 </code></pre> <p>I merge dataframe like with this code.</p> <pre><code>df3 = pd.merge(df1, df2, left_on='id', rig...
<p>You can try <code>how=outer</code></p> <pre class="lang-py prettyprint-override"><code>df3 = pd.merge(df1, df2, on='id', how='outer') </code></pre> <pre><code>print(df3) id value1 value2 0 2 10.0 200.0 1 3 10.0 150.0 2 4 20.0 NaN 3 5 20.0 NaN 4 1 NaN 100.0 </code></pre>
python|pandas
0
11,052
72,399,731
Sum of Specific String Elements in a dataframe
<p>So, I have a data frame in pandas which contains a column called &quot;Tracking&quot;. Now the column contains different values like &quot;Received&quot;, &quot;In Progress&quot;, &quot;Delayed due to something&quot; etc. I am wondering is there a possibility that i can get the sum of each of these status from this ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.value_counts.html" rel="nofollow noreferrer">value_counts</a></p> <pre><code>df = pd.DataFrame({'Tracking': ['Received', 'Received', 'In Progress', 'Delayed due to something','In Progress','In Progress']}) print(df.Trac...
python|pandas
0
11,053
62,579,289
How to find out which columns are duplicated?
<p>I have a dataframe where I suspect some of the columns may be duplicates of each other. How can I find out which ones they are? For example:</p> <pre><code>Name val1 val2 val3 val4 dog 4 0 2 4 fish 0 0 8 0 falcon ...
<p>You can check duplicated on transpose:</p> <pre><code>df.T.duplicated(keep=False) </code></pre> <p>Output:</p> <pre><code>Name False val1 True val2 False val3 False val4 True dtype: bool </code></pre> <p>And you can drop duplicated with <code>loc</code>:</p> <pre><code>df.loc[:,~df.T.duplicated()] <...
python|pandas
3
11,054
62,640,829
Faster code to make a DataFrame from existing DataFrame
<p>I have the following pandas DataFrame from which I want to create a new DataFrame.</p> <pre><code> Id UserId BadgeName Date Class TagBased 0 2 23 Autobiographer 2016-01-12T18:44:49.267 3 False 1 3 22 Autobiographer 2016-01-12T18:44:49.267 3 False 2 4 21 Autobi...
<p>Don't loop! Here is your data with a couple extra lines.</p> <pre><code>df = pd.DataFrame({'BadgeName': ['Autobiographer', 'Autobiographer', 'Autobiographer', 'Autobiographer', 'Autobiographer', 'Autobiographer', 'Autobiographer'], 'Class': ['Bronze', 'Bronze', 'Bronze', 'Bronze', 'Bronze', 'Gold', 'Sil...
python-3.x|pandas|loops|dataframe|append
0
11,055
54,374,596
pandas datetime index serial difference
<p>How do I compute the serial differences of a pandas datetime index? The <code>diff</code> function does not work:</p> <pre><code>import pandas as pd pd.date_range('2018-12-31','2019-01-31').diff() AttributeError: 'DatetimeIndex' object has no attribute 'diff' </code></pre>
<p>Use <code>np.diff</code>, to get the difference in nanoseconds.</p> <pre><code>np.diff(dt) </code></pre> <p>From this, if you need an Index of Timedeltas, you can call <code>to_timedelta</code>.</p> <pre><code>pd.to_timedelta(np.diff(dt), unit='ns') # TimedeltaIndex(['1 days', '1 days', ...], dtype='timedelta64[n...
python|pandas|datetime
3
11,056
54,616,292
cumsum() by month but repeat the values if there is no data in that month
<p>I have data: <code>df</code> </p> <pre><code> date col1 col2 0 1/16/2016 apple 20 1 2/1/2016 apple 40 2 2/2/2016 pear 60 3 3/13/2016 apple 10 4 5/4/2016 apple 50 5 6/15/2016 pear 5 </code></pre> <p>With <code>cumsum()</code> I can get cumulative sum of the values. ...
<p>Use:</p> <pre><code>#create month period column for correct ordering df['months'] = df['date'].dt.to_period('m') #aggregate month df1 = df.groupby(['months', 'col1'])['col2'].sum() #MultiIndex with all possible combinations mux = pd.MultiIndex.from_product([pd.period_range(df['months'].min(), ...
python-3.x|pandas|pandas-groupby|cumsum
4
11,057
54,349,664
Show all matched pairs in a single dataframe - Python Record Linkage
<p>I have a pandas MultiIndex object :</p> <pre><code>In [0]: index Out[0]: MultiIndex(levels=[[1, 2, 3, 8], [10, 11]], labels=[[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]]) </code></pre> <p>This MultiIndex object defines the following 8 pairs : (1,10), (1,11), (2,10), (2,11), (3,10), (3,11), (8,10), (...
<p>Using <code>stack</code> with <code>iloc</code> or <code>reindex</code> </p> <pre><code>df.iloc[m.to_frame().stack()].assign(key=m.to_frame().reset_index(drop=True).stack().index.get_level_values(0)) Out[205]: col_1 col_2 key 1 2 3 0 10 20 21 0 1 2 3 1 11 22 23 ...
python|pandas|dataframe|multi-index|record-linkage
4
11,058
54,537,792
Constructing a dataframe with multiple columns based on str conditions using a loop - python
<p>I have a webscraped Twitter DataFrame that includes user location. The location variable looks like this:</p> <pre><code>2 Crockett, Houston County, Texas, 75835, USA 3 NYC, New York, USA 4 Warszawa, mazowieckie, RP 5 ...
<p>Use <code>.str.extract</code> to get a <code>Series</code> of the states, and then use <code>pd.get_dummies</code> on that <code>Series</code>. Will need to define a list of all 50 states:</p> <pre><code>import pandas as pd states = ['Texas', 'New York', 'Kentucky', 'Virginia'] pd.get_dummies(df.col1.str.extract('...
python|pandas|dataframe|conditional-statements
1
11,059
54,605,964
Composition versus subclass for Pandas DataFrame
<p>I am trying to create a method called 'tilt' in a Python class which turns the DataFrame upside down using Pandas. But I am getting this error "The object has no attribute 'iloc'", whenever I use this 'tilt' method on an instance created out of this class.</p> <pre><code>import numpy as np import pandas as pd clas...
<p>In <code>.tilt()</code>, you use <code>self.iloc[::-1]</code>. However, inside the scope of this instance method, <code>self</code> is just a plain, minimalistic Python class, not a DataFrame. It knows nothing about the operations that you did to the local variable <code>self</code> inside of <code>.arrange()</cod...
python|pandas|class
5
11,060
73,778,963
Remove multi-word substring from string if substring in list in data frame column
<p>Asking a follow up question to my question here: <a href="https://stackoverflow.com/questions/73718949/remove-substring-from-string-if-substring-in-list-in-data-frame-column/73719025#73719025">Remove substring from string if substring in list in data frame column</a></p> <p>I have the following data frame <code>df1<...
<p>The question is roughly similar, but still quite different.</p> <p>In this case we use <code>re.sub</code> over the row axis (<code>axis=1</code>):</p> <pre><code>df.apply(lambda row: re.sub(&quot;|&quot;.join(row[&quot;lists&quot;]), &quot;&quot;, row[&quot;string&quot;], flags=re.I), axis=1) </code></pre> <pre><co...
python|pandas
1
11,061
73,640,609
How do I get the latest entries in a DataFrame up to a certain time, for a given list of column values?
<p>Say I have the following DataFrame <code>df</code>:</p> <pre><code>time person attributes ---------------------------- 1 1 a 2 2 b 3 1 c 4 3 d 5 2 e 6 1 f 7 3 g ... ... ......
<p>How about <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.query.html" rel="nofollow noreferrer">pd.DataFrame.query</a></p> <pre><code>def latest_entries(request_time: int or float, ids: list) -&gt; pd.DataFrame: return ( df .query(&quot;time &lt;= @request_time &amp; person...
python|pandas|dataframe|data-science
3
11,062
73,622,461
Turn list of dictionaries that share column value to pandas multiindex dataframe with keys as columns
<p>I have a df with a <code>wallet</code> column (which I want to use as the index and a <code>positions_rewards</code> column, which is the main target of this question.</p> <p>Each row in <code>positions_rewards</code> is a list of dictionaries (each row has a different amount of dictionaries within their list).</p> ...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>df = df.drop(columns=&quot;amount&quot;).explode(&quot;positions_rewards&quot;) df = pd.concat([df, df.pop(&quot;positions_rewards&quot;).apply(pd.Series)], axis=1) print(df) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override"><code> ...
python|pandas|dataframe|dictionary|multi-index
1
11,063
52,234,518
Change dimension of a dateframe
<p><a href="https://i.stack.imgur.com/PgqbZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PgqbZ.png" alt="This is my dataframe"></a></p> <p>I have a dataframe with a MultiIndex and dimensions 18 x 1. I want to get a dataframe with dimensions 6 x 3 with the airline names as row index and the sentim...
<p>This is simple once you know the method :<br> Just <code>df.unstack()</code> will get you there :)</p> <p>To get rid of the MultiIndex as columns, and just keep the sentiment scores, do : </p> <pre><code>df.columns = df.columns.droplevel() </code></pre>
python|pandas|dataframe
0
11,064
60,509,312
python and tensorflow: Which is optimized way to call function which exploits tensorflow operations?
<p>I'm developing a simple function using tensorflow:</p> <pre><code>def xcross(T, S): sum_spectra_sq = tf.reduce_sum(tf.square(S), 1) #shape (batch,) sum_template_sq = tf.reduce_sum(tf.square(T), 0) #shape (Nz) norm = tf.sqrt(tf.reshape(sum_spectra_sq, (-1,1))*tf.reshape(sum_template_sq, (1,-1))) xcor...
<p>Your creating a new graph for each iteration (= calling <code>xcross</code>). You should redefine <code>xcross</code> so that it takes a <code>tf.placeholder</code> as input and define it outside the loop, even outside the <code>with tf.Session as sess:</code>. Then you can call the graph with:</p> <pre><code>xcros...
python-3.x|tensorflow|optimization
1
11,065
60,575,153
error: Illegal instruction (core dumped) - tensorflow==2.1.0
<p>I am importing tensorflow in my ubuntu (Lenovo 110-Ideapad laptop) python using following commands- </p> <pre><code>(tfx-test) chandni@mxnet:~/Chandni/TFX$ python Python 3.6.9 (default, Nov 7 2019, 10:44:02) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt;...
<p>You may need to downgrade to CPU 1.5.</p> <pre><code>#Try running pip uninstall tensorflow #And then pip install tensorflow==1.5 </code></pre> <p>Then import tensorflow and let me know if the error reoccur</p>
tensorflow|tensorflow2.x
2
11,066
60,675,077
How is this error possible and what can be done about it? "ValueError: invalid literal for int() with base 10: '1.0'"
<p>I'm using Python 3 with the pandas library and some other data science libraries. After running into a variety of subtle type errors while just trying to compare values across two columns that should contain like integer values in a single pandas DataFrame (although the Python interpreter arbitrarily interprets the ...
<p>Solved it for myself with the following substitution, in case anyone else runs into this. It may also have helped that I updated pandas from 1.0.1 to 1.0.2, since that update did includes some type conversion bug fixes, but more likely it was this workaround (where pd is of course the alias for the pandas library):<...
python-3.x|pandas|dataframe|type-conversion
0
11,067
60,584,338
GroupBy index and columns then transform selected Columns in Pandas
<p>I have a sample DF:</p> <pre><code>sample_df_train = pd.DataFrame(np.random.randint(1,20,size=(10, 3)), columns=list('ABC')) sample_df_train["date"]= ["2020-02-01","2020-02-01","2020-02-01","2020-02-01","2020-02-01", "2020-02-02","2020-02-02","2020-02-02","2020-02-02","2020-02-02"] sample_df_train["...
<p>Notice you just <code>reset_index</code> when you do <code>groupby</code> , so the original df's <code>index</code> is different from the <code>groupby</code> result </p> <pre><code>sample_df_train= sample_df_train.reset_index() sample_df_train[selected_columns] = sample_df_train.groupby(group_by_cols)[selected_col...
python|pandas|numpy|pandas-groupby
0
11,068
72,529,346
Change dataframe index to include column names
<p>I want to change the way the information in the dataframe is displayed to a dataframe reflected in the excel picture included here.[!1]]<a href="https://i.stack.imgur.com/iCz9T.png" rel="nofollow noreferrer">1</a> I have looked at Multi Index and itertools but can't make any headway and any help will be appreciated....
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></a> with join values of <code>MultiIndex</code> and then create 2 columns DataFrame by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.S...
python|pandas|dataframe
1
11,069
72,597,918
Subset between 4 different times in Python
<p>I have some data where I would like to subset between different times of day for different dates, specifically I want the column <code>df['event']</code> to have a <code>1</code> if the time is between 9am to 11am, a <code>2</code> if it is between 3pm to 4pm, and <code>0</code> otherwise. As such, I tried to use th...
<p>If need working only with times here is solution with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.indexer_between_time.html" rel="nofollow noreferrer"><code>DatetimeIndex.indexer_between_time</code></a>:</p> <pre><code>df = pd.DataFrame({'datetime':pd.date_range('2020-01-0...
python|pandas|timestamp
1
11,070
72,675,744
Finding anomalies for millions of records
<p>i have a database (more then 2M rows) that contains 4 columns:</p> <ol> <li>PC</li> <li>User</li> <li>Date</li> <li>Count</li> </ol> <p>The 'Count' columns is aggregate base on (PC + User + Date) <em>t's how many specific user visit specific computer in specific day</em> So for example:</p> <div class="s-table-conta...
<p>I can propose the statistic method, not ML, it works really fast, but I don't know if it will work for you. You can use the same formula used in <a href="https://en.wikipedia.org/wiki/Box_plot" rel="nofollow noreferrer">boxplots</a> for anomaly detection. You can set the sensitivity of the method by increasing or de...
python|pandas|machine-learning|deep-learning|anomaly-detection
0
11,071
59,737,872
How can I optimize the groupby.apply(function) in Python?
<p>I have a function that uses deque.collections to track daily stock in based on FIFO. An order will be fulfilled if possible and is substracted from stock accordingly. I use a function in groupby.apply(my_function). </p> <p>I have struggles where to place the second loop. Both loops work properly when run on their o...
<p>You do not have access to <code>sl_list</code> inside the second loop, you should just define it in the upper scope: for example just after the first global for loop:</p> <pre><code>for i in x.index: # define it just here sl_list = [] order = x['order_bin'][i] </code></pre>
python|pandas|loops|collections|deque
0
11,072
59,709,218
How to use for loop in column dataframe
<p>I have a big csv file with information about 911 calls. The describtion of the calls are long string:</p> <pre><code>2015-12-10 @ 14:39:21-Station:STA27; OLD YORK RD &amp; VALLEY RD; CHELTENHAM; 2015-12-10 @ 17:12:47; </code></pre> <p>I wan't to filter out the Rows without Station in it. And del the part what's s...
<p>You can use regular expression to extract a group from the string.</p> <pre><code> import re e = re.compile("(Station\s*:*\s*\w*;+)") r = e.search("REINDEER CT &amp; DEAD END; NEW HANOVER; Station 332; 2015-12-10 @ 17:10:52;").group(1) print(r) //prints Station 332; </code></pre>
python|string|pandas|for-loop
0
11,073
59,857,257
Return array from tuple
<p>I am trying to return two arrays from 1 tuple at once.</p> <p>I have a (large) iteration </p> <pre><code>def iteration_newton(...., ....,) </code></pre> <p>with at the end of the iteration</p> <pre><code>return x_save, V </code></pre> <p>Where <code>x_save</code> is a matrix of <code>28x1000</code> and <code>V<...
<p>You can make use of unpacking assignment:</p> <pre><code>Results, V = iteration_newton(...., ....,) </code></pre> <p>which is somehow similar to:</p> <pre><code>iteration = iteration_newton(...., ....,) # calculate it once and store it for later use Results = iteration[0] V = iteration[1] </code></pre>
arrays|numpy|matrix|tuples|iteration
1
11,074
59,786,646
Truncation issue with 19 digit long integer
<p><a href="https://i.stack.imgur.com/9sgE5.png" rel="nofollow noreferrer">DataFrame</a></p> <p>I downloaded a CSV file from a web service. When I import the csv using <code>pandas.read_csv</code>, the 19 digit long IDs are truncated to decimals. I then use <code>pd.options.display.float_format = '{:.6f}'.format</code...
<p>For me default solution working, but maybe need <code>np.int64</code>:</p> <pre><code>df = pd.read_csv(filepath, dtype={'ID':np.int64}) </code></pre> <p>If possible some missing values and pandas version is 0.24+ use <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/integer_na.html" rel="nofollow no...
python|pandas|dataframe|decimal|truncation
0
11,075
59,901,366
Use html to go into url and scrape tables
<p>I need to scrape tables from individual pages of players, but sometimes the search will go to a list of players if there are multiple with the same name. I want the one that played in the NBA. For example, for Sergio Rodriguez, a list shows up (<a href="https://basketball.realgm.com/search?q=Sergio+Rodriguez" rel="n...
<p>Use if condition check if the text of the element matches with <code>Sergio Rodriguez</code> then go to that block and get the latest url and then get the soup ans so on..</p> <pre><code>import requests from bs4 import BeautifulSoup import pandas as pd playernames=['Carlos Delfino', 'Sergio Rodriguez','Nikola Jok...
python|html|pandas|web-scraping|beautifulsoup
1
11,076
61,714,874
does python have a package or function to train neural network with stacked autoencoder like deepnet in R
<p>I have a neural network that I am using in Python with Keras / tensorflow. I'm trying to get used to using Python.</p> <p>In R there <a href="https://www.rdocumentation.org/packages/deepnet/versions/0.2/topics/sae.dnn.train" rel="nofollow noreferrer">is this function</a> that pre-trains a neural network with a stac...
<p>Yes, you can find this implementation in python using the below function. </p> <p>Configuration:</p> <pre><code>n_hidden_layer = 3 n_hidden_unit = 1000 neuron = Neurons.Sigmoid() param_key_prefix = "ip-layer" corruption_rates = [0.1,0.2,0.3] pretrain_epoch = 15 finetune_epoch = 1000 batch_size ...
python|r|tensorflow|keras
1
11,077
61,626,334
How to retain custom layer names and avoid "TensorFlowOpLayer" in json model export
<p>I am training a sequential <code>tf.keras</code> model which I want to convert to <code>tfjs</code> format consisting of a <code>model.json</code> file describing the layers and binary weight files to deploy it on a website for inference.</p> <p>Two layers in my model are custom layers since there are no suitable l...
<p>The <code>__call__</code> method should be <code>call</code> instead. </p>
javascript|python|tensorflow|tensorflow.js
1
11,078
61,738,541
Numpy.fromfunction(): How to use it with strings?
<p>The first line works, but the second doesn't:</p> <pre><code>print(np.fromfunction(lambda x, y: 10 * x + y , (3, 5), dtype=int)) print(np.fromfunction(lambda x, y: str(10 * x + y), (3, 5), dtype=str)) [[ 0 1 2 3 4] [10 11 12 13 14] [20 21 22 23 24]] Traceback (most recent call last): File "&lt;stdin&gt...
<p>Do you understand what the <code>dtype</code> is supposed to be doing in <code>fromfunction</code>? Reread the docs.</p> <p>This action is producing the same error:</p> <pre><code>In [2]: np.arange(3, dtype=str) ------------------------------...
python|numpy
0
11,079
57,928,010
Remove array index based on numpy array
<p>Suppose I have array1 of shape (69316, 5, 5, 28) and array2 of length 10050. I want to remove elements from array2 for indices <code>0:len(array1)</code>. However, I have tried:</p> <pre><code>array3 = np.delete(array1, array2, axis=0) </code></pre> <p>Which throws an error (yes, I am upgrading to Python 3 next we...
<p>Try this out -</p> <pre><code>array3 = array1[10050:, :, :, :] </code></pre> <p>Here, I'm saving only the elements after index 10050, keeping the other dimensions intact.</p>
python|numpy|indexing
1
11,080
58,007,252
Calculate not-null values' percentages of several columns in Pandas
<p>For a data frame as follows, how can I calculate <code>not-null values</code>' percentages of columns <code>A, C, D</code> in Pandas? Thank you.</p> <pre><code> id A B C D 0 1 1.0 one 4.0 NaN 1 2 NaN one 14.0 NaN 2 3 2.0 two 3.0 -12.0 3 4 55.0 three NaN 12.0 4...
<p>For count number of non NaNs values use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.notna.html" rel="nofollow noreferrer"><code>DataFrame.notna</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mean.html" rel="nofollow noreferr...
python|pandas|dataframe
2
11,081
58,072,054
TensorFlow Estimator: how to do prediction when using parameter server?
<p>TensorFlow Estimator is easy to use for distributed training with parameter server strategy. But I cannot do prediction with the parameter server strategy. I cannot find any resource to introduce the part.</p> <p>prediction sample code:</p> <pre><code> run_config = tf.estimator.RunConfig() model = tf.estima...
<p>In <a href="https://github.com/tensorflow/estimator/blob/master/tensorflow_estimator/python/estimator/estimator.py#L623" rel="nofollow noreferrer">Estimator predict</a>, every ps and worker use <code>MonitoredSession</code> to start a node which restores from an existing checkpoint. In order to do a distributed pred...
tensorflow|distributed|tensorflow-estimator|parameter-server
0
11,082
55,002,118
How do I perform operations according to the inner index of a multiIndex DataFrame?
<p>Suppose I have a DataFrame of students' grades and want to track their grades with time. The DataFrame might look like this:</p> <pre><code>data = [ { "Name": "John", "Period": 1, "Grade": 60 }, { "Name": "John", "Period": 2, "Grade": 80 }, { "Name": "John", "Period": 3, "Grade": 90 }, { "Name": "Bill", "Period": 1...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.pct_change.html" rel="nofollow noreferrer"><code>GroupBy.pct_change</code></a> by first level of <code>MultiIndex</code>:</p> <pre><code>df["change"] = df.groupby(level=0)['Grade'].pct_change() print (df) ...
python|pandas
2
11,083
54,744,616
How do I clean duplicate data in cells in pandas?
<p>I have a data frame where the column gender has duplicates within the cells, here is an example:</p> <pre><code>1. Male 2. Female, female 3. Female, female , Female, female </code></pre>
<p>Convert values to lowercase, then split, convert to <code>set</code>s and join back if necessary:</p> <pre><code>df['new'] = df['col'].apply(lambda x: ', '.join(set(x.lower().split(', ')))) print (df) col new 1.0 Male male 2.0 Female...
python|pandas
3
11,084
55,102,113
Tensorflow training: CPU Xeon or 2 GPU gtx750. Who is faster?
<p>I use CPU xeon E5-1650 (3.2 GHz, 6Cores, 12 Threads) for training Tensorflow model. But training is so slow...</p> <p>If I will use desktop computer with typical CPU and 2 GPU GeForce GTX750 (2 Gb), it will be faster?</p>
<p>Using the GPU's will be faster. The only things to keep in mind are that the size of your model is then constrained by the memory of the GPUs and that you have to choose the right sets of version numbers and drivers, such that your GPU is supported.</p>
tensorflow|deep-learning|computer-vision
-2
11,085
49,638,765
Information on new fields TFRecord format for Object Detection API
<p>I was digging through the <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/data_decoders/tf_example_decoder.py" rel="nofollow noreferrer">TfExampleDecoder</a> and saw some fields that don't appear to be documented anywhere. Starting in line 207:</p> <p><code> fields.InputDataField...
<p>fields.InputDataFields.groundtruth_weights is <em>most likely</em> a weight that gets multiplied with the loss. See 3.1 in <a href="https://arxiv.org/pdf/1708.02002.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1708.02002.pdf</a></p>
tensorflow|object-detection
0
11,086
49,572,606
"tensor not found in the checkpoint" when evaluating the re-tuned inception-v3 model using TF-slim
<p>When I evaluated the re-tuned inception-v3 model with my dataset using <a href="https://github.com/tensorflow/models/blob/master/research/slim/eval_image_classifier.py" rel="nofollow noreferrer">eval_image_classifier.py</a> in TF-slim, I got an error:</p> <pre><code>NotFoundError (see above for traceback): Key Ince...
<p>Add <code>tf.reset_default_graph()</code> to python script it will fix issue like this.</p>
python|tensorflow
0
11,087
73,458,428
TypeError: '<' not supported between instances of 'str' and 'bool' although info doesn't have bool in sklearn column transformer
<p>There are similar questions asked before on stackoverflow, however, none of them could fix my problem. I don't understand why info() clearly doesn't output a &quot;bool&quot; but sklearn is outputting an error saying I have boolean values in my dataframe. Can anyone help me debug this thanks!</p> <pre><code>X = df.d...
<p>Thing is, columns like <code>CryoSleep</code> and <code>VIP</code> are actually boolean (I assume this is the original Kaggle ST dataset). They're shown as <code>object</code> because of missing values (resulting in a mixed type).</p> <p>Try explicitly changing the values first, e.g.:</p> <pre><code> df['CryoSleep...
pandas|machine-learning|scikit-learn|sklearn-pandas|supervised-learning
1
11,088
73,475,930
Torch automatic differentiation for matrix defined with components of vector
<p>The title is quite self-explanatory. I have the following</p> <pre><code>import torch x = torch.tensor([3., 4.], requires_grad=True) A = torch.tensor([[x[0], x[1]], [x[1], x[0]]], requires_grad=True) f = torch.norm(A) f.backward() </code></pre> <p>I would like to compute the gradient of f with re...
<p>The problem might be, that when you take a slice of a leaf tensor, it returns a non-leaf tensor like so:</p> <pre><code>&gt;&gt;&gt; x.is_leaf True &gt;&gt;&gt; x[0].is_leaf False </code></pre> <p>So what's happening is that x is not what was added to the graph, but instead x[0].</p> <p>Try this instead:</p> <pre><c...
python|pytorch|autograd|automatic-differentiation
1
11,089
67,212,326
How can we use as input only one row for each node-cell of a dense layer?
<p>I will like to ask: How can we use as input only one row of a dataset for each node-cell of a dense layer?</p> <p><a href="https://i.stack.imgur.com/7H5pd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7H5pd.png" alt="enter image description here" /></a></p>
<p>The extended version about how to manage multiple inputs and outputs in keras-models:</p> <pre><code>import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import numpy as np import time #Examples...in case of input size of one row only... input_vector_1=[1,2,3] input_vector_2=[4,...
python|tensorflow|keras
1
11,090
60,317,569
How to switch n columns to rows of a r rows pandas dataframe (n*r rows in the final dataframe)?
<p>Let's take this dataframe :</p> <pre><code>pd.DataFrame(dict(Col1=["a","c"],Col2=["b","d"],Col3=[1,3],Col4=[2,4])) Col1 Col2 Col3 Col4 0 a b 1 2 1 c d 3 4 </code></pre> <p>I would like to have one row per value in column Col1 and column Col2 (n=2 and r=2 so the expected dataframe ha...
<p>Pandas melt does the job here; the rest just has to do with repositioning and renaming the columns appropriately. <br><br> Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html" rel="nofollow noreferrer">pandas melt</a> to transform the dataframe, using Col3 and 4 as the index vari...
python|pandas|dataframe
2
11,091
60,218,204
Problems with Python & Pandas: Adding calculated column to dataframe that includes data from a function provides error
<p>I am trying to add a calculated column: "NetEarnings" to my DataFram "Wages". The "NetEarnings" column subtracting Tax from AnnualIncome; tax is drawing from a function I created to calculate taxes. It will not let me add this new column due to an error: </p> <blockquote> <p>"TypeError: unsupported operand type...
<p>Additionally to Ente answer,</p> <p>I suggest to use np.where instead of apply. Apply is faster than a for loop, but much slower than apply.</p> <p>A possible solution would be:</p> <pre><code>np.where(df['AnnualIncome'] &lt;= 21450, (.15 *df['AnnualIncome']), np.where(df['AnnualIncome'] &lt;= 519...
python|pandas|function|dataframe
1
11,092
65,166,143
How to print the values of a symbolic tensor in tensorflow 2.0?
<p>I am using tensorflow2.0. The code I am using is this:</p> <pre><code>f_1 = ConvLSTM2D(filters=25, kernel_size=(1,1), input_shape=(None,None,25,1,3), return_sequences=True)(expand_x1) f_1 = f_1[:,:,:,0,:] </code></pre> <p>I want to see the f_1 variable. So I converted it into a NumPy array but get this error: &quot;...
<p><code>Symbolic Tensors</code> doesn't hold values like regular tensors which we define using <code>tf.constant(4)</code> etc which you can see only the type of Tensor but you can't visualize symbolic tensors.</p> <p>Usually, symbolic tensors are created while defining the model using <code>Functional</code> or <code...
tensorflow|deep-learning
0
11,093
65,072,984
Pandas dataframe `apply` using recursive lambda function possible?
<p>I have a data frame that represents a recursive parent child relationship. The data in this case is called &quot;factor families&quot;</p> <p>Each factor family contains a number of factors, which are weighted, adding up to 100% per family.</p> <p>A factor may itself be a factor family</p> <p>There is no limit to th...
<p>I'd do it this way, looping over subsets of the dataframe and using temporary columns to store the chained weights and current parent tested. Note that I replaced your blank strings in df by np.nan values.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({ &quot;code&quot;: [&quot;a&quot;, &q...
python|pandas|dataframe|recursion|apply
0
11,094
63,857,358
_th_addr_out not supported on CPUType for ComplexFloat
<p>I am trying to use a customized loss function for my NN. I've implemented all operations in torch and I have complex numbers among my data.</p> <p>I get the error while training a NN:</p> <pre><code>RuntimeError: _th_addr_out not supported on CPUType for ComplexFloat </code></pre> <p>Do you know any possible soluti...
<p>Well it seems Complex Autograd in PyTorch is currently in a prototype state, and the backward functionality for some of function is not included.</p> <p>For example: torch.sign, which is used in the backward computation of torch.abs, is not defined for complex tensors. same for torch.mv. So I debugged my code line ...
pytorch|customization|complex-numbers|loss-function|autograd
1
11,095
64,125,158
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() whilst trying to use function with pandas df
<p>I have the following code which makes the following error. I think the error comes from the loop section <code>while epsilon &gt; tol:</code>. Ive added a small df with the desired results in the column &quot;IV&quot;.</p> <p>line 1478, in <strong>nonzero</strong> raise ValueError( ValueError: The truth value of a S...
<p>I managed to find a solution which is:</p> <pre><code>list_of_iv = [] # Print out the results for index, row in df.iterrows(): iv = calc_put_iv(df[&quot;Stock Price&quot;].iloc[index], df[&quot;Strike&quot;].iloc[index], df[&quot;Length/365&quot;].iloc[index],0.001,df[&quot;Div Yield&quot;].iloc[index],df[&...
python|pandas|numpy|loops
0
11,096
64,032,679
OpenCV calcOpticalFlowFarneback: How to extract velocity vector values from specific pixels
<p>The standard code for calcOpticalFlowFarneback python.</p> <pre><code>import numpy as np import cv2 cam = cv2.VideoCapture(&quot;video.mp4&quot;) ret, prev = cam.read() prevgray = cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY) coords = np.array([ [230, 218, 205, 189, 176, 156], [145, 156, 162, 166, 166, 165] ]) t...
<p><code>coords</code> is simply 2D NumPy array where the first column contains the row locations and second column contains the column locations. You can use these to index into the array in a vectorized form to obtain the values of interest, then find the average of those escaping the need for a loop all together:</...
python|image|numpy|opencv
2
11,097
62,910,720
How can I ensure that my PDF reading code does not return a NaN row and a duplicate row?
<p>I am working on reading PDF files that are CVs into a DataFrame (pandas). However, after reading the files I find a NaN row and a duplicate row of the last CV (alphabetically). Is there something in the code that does this? I can't seem to figure out why. I have tried changing around the iloc index[0] parts and the ...
<p>Fixed by changing the following part of the code:</p> <pre><code>dataset = pd.DataFrame(columns = ['FileName','Text']) for file in pdf_files: pdfFileObj = open(file,'rb') #'rb' for read binary mode pdfReader = PyPDF2.PdfFileReader(pdfFileObj) startPage = 0 text = '' cleanText = '' while startPage &...
python|pandas|machine-learning|nlp
0
11,098
63,266,306
Nested JSON extract first level keys and add to a column Python 3?
<p>I have the following JSON type:</p> <pre><code>import pandas as pd data = {'Big Bean Pot': [{'name': 'bacon', 'unit': 'lb', 'amount': 0.06}, {'name': 'baked beans', 'unit': 'oz', 'amount': 2.67}, {'name': 'brown sugar', 'unit': 'cup', 'amount': 0.04}, {'name': 'canned lima beans', 'unit': 'oz', 'amount': 1.25}, {'n...
<p>Try <code>pandas concat</code> :</p> <pre><code>pd.concat(pd.DataFrame(value).assign(recipe=key) for key, value in data.items()) </code></pre> <p>To set it as the first column, numpy's <code>np.r_</code> comes in handy :</p> <pre><code>pd.concat(pd.DataFrame(value).assign(recipe=key) for key, value in data.items())....
json|pandas|dataframe
2
11,099
62,997,748
Boolean mask on timeseries with different frequencies
<p>I'm trying to mask some timeseries data with 6hours frequency with a boolean dataframe that is at daily frequency. The result should remain at 6hours frequency. The following function gives me what I want but it's superslow and I'm shure there are much better versions to do this. I'm an absolute beginner...</p> <p>T...
<p>If you merge the original data w/the mask data you can use <code>np.where</code> to apply the mask.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'a': [0,1,10,2,5,4,7,5],'b': [0,10,100,20,50,40,70,50], 'date': [pd.to_datetime('2017-04-01 00:00:00'), ...
python|pandas|dataframe|time-series
1