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
356,200
65,023,229
How to calculate proportion display pie chart in pandas or others?
<p>According to this <a href="https://stackoverflow.com/questions/65021427/how-to-calculate-total-amount-by-pandas-groupby-number-and-unit-price">question</a>, I would like to get the proportion of item in total amount, and display a pie chart like below(need to display the name and the proportion of the item):</p> <p>...
<p>You can use pandas internal plot function, which most likely uses matplotlib backend:</p> <pre><code>s = df.groupby('name')['new'].sum() ax = s.plot.pie(figsize=(10,10), autopct='%.2f%%') </code></pre> <p>Or chain together:</p> <pre><code>ax = (df.groupby('name')['new'].sum() .plot.pie(figsize=(10,10), auto...
python|pandas|matplotlib
0
356,201
65,044,834
Adding a dataframe column to a specific position
<p>I am extracting a column from my dataframe, so i can process the features in the remaining dataframe columns and storing it inside a variable. What i would like to do is return that column back to it's position, for example:</p> <p>Original dataframe:</p> <pre><code>samples = {'col1': [1, 3, 5, 6, 7, 9, 11, 12], ...
<p>assuming you know where the position was (you stored it somewhere), or happy to specify the position directly, let's say you want it in pos 0, use (after you removed it in your code)</p> <pre><code>df.insert(0,df_col1.columns[0], df_col1) </code></pre>
python|pandas|dataframe
1
356,202
65,050,788
TensorFlow layer that converts a 2D matrix to a vector of certain length
<p>I am trying to build a neural network that takes in data in form of a matrix and outputs a vector but I don't know what layers to use to perform that. My input has shape (10,4) and my desired output has shape (3,). My current model is the following :</p> <pre><code>model = tf.keras.Sequential([ tf.keras.layers.D...
<p>Assuming that your <code>(10,4)</code> is a matrix which doesn't represent a 10 length sequence (where you will need an <code>LSTM</code>) OR an image (where you will need a <code>2D CNN</code>), you can simply <code>flatten()</code> the input matrix and pass it through to the next few dense layers as below.</p> <pr...
python|tensorflow
1
356,203
65,050,452
How to build this list comprehension correctly:
<p>How should I write this list comprehension properly: I am trying to keep from the train set X_tr only images for which numpy arrays have a .std() above 10 but I need to keep track of the index to return the corresponding labels in y_tr:</p> <pre class="lang-py prettyprint-override"><code>(X_tr,y_tr) = (np.array([i[i...
<p>The purpose of list comprehensions is to make code clearer and cleaner. Your code is nearly impossible to understand. I'd separate calculating the indices.</p> <pre><code>indices = np.where(np.std(x, axis=1) &gt; 10) x, y = x[indices], y[indices] </code></pre> <p>I think that's what you're trying to do.</p>
python|numpy
0
356,204
64,732,690
Create parent ids for rows in a dataframe in python based on multiple conditions
<p>I have a big data frame with records of individuals. I'm trying to create a parent ID for people that match on specific columns to know which records in fact refer to the same person.</p> <pre><code>df = pd.DataFrame({'id':[1, 2, 3, 4, 5, 6, 7, 8], 'forename':['matt','mark','matthew','chris','rob'...
<p>I'm using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer">.groupby().transform()</a> to get to this.<br> <br> My trick is to group by email and take the minimum id of the group. They all get assigned the minimum id of ...
python|python-3.x|pandas|dataframe
1
356,205
64,897,190
How do I set up a GPU with CUDA in python for TensorFlow on Windows 10?
<p>I've been trying to use TensorFlow but any time I try and run something I get an error saying that I need to set up a GPU on my machine. I've heard that I need to download some sort of CUDA attachments to run it, not too sure though...</p> <pre><code>2020-11-18 11:23:57.579846: I tensorflow/stream_executor/cuda/cuda...
<p>I don't think you will encounter any problem with your current NVIDIA GTX 1050 Ti</p> <p>You need to get TensorFlow GPU. You can't directly <code>pip install</code> tensorflow GPU. You need the set up the configurations required to run Tensorflow GPU just like how you installed python for the first time on your mach...
python|tensorflow
1
356,206
40,298,394
get data from make_response() and convert to json
<p>I want to get data from make_response() Response object and then transform into row, columns using pandas. I know how to go about pandas but how to get json format response in Flask. </p> <pre><code>resp=make_response(jsonify({"data":data, "request_url":request_url})) </code></pre> <p>and resp is getting 200 OK bu...
<p>Change this</p> <pre><code>resp=make_response(jsonify({"data":data, "request_url":request_url})) </code></pre> <p>to</p> <pre><code>resp=make_response(jsonify(data=data, request_url=request_url)) return resp </code></pre>
json|python-2.7|pandas|flask
0
356,207
40,318,041
Compare elements in a numpy array 3 rows a time
<p>I got a numpy array as below:</p> <pre><code>[[3.4, 87] [5.5, 11] [22, 3] [4, 9.8] [41, 11.22] [32, 7.6]] </code></pre> <p>and I want to:</p> <ol> <li>compare elements in column 2, <strong>3 rows a time</strong></li> <li>delete the row with the biggest value in column 2, 3 rows a time</li> </ol> <p>For exam...
<pre><code>import numpy as np x = np.array([[3.4, 87], [5.5, 11], [22, 3], [4, 9.8], [41, 11.22], [32, 7.6]]) y = x.reshape(-1,3,2) idx = y[..., 1].argmax(axis=1) mask = np.arange(3)[None, :] != idx[:, None] y = y[mask] print(y) # This might be help...
python|arrays|numpy|compare
1
356,208
40,161,969
Tensorflow: Access index of variable containing an array
<p>I need to save some values to specific places in a tensorflow array:</p> <pre><code>import tensorflow as tf import numpy as np AVG = tf.Variable([0, 0, 0, 0, 0], name='data') for i in range(5): data = np.random.randint(1000, size=10000) AVG += np.average(data) </code></pre> <p>I need to make it avera...
<p>You can use <code>tf.scatter_add</code>. Here is a complete working program :</p> <pre><code>import tensorflow as tf import numpy as np AVG = tf.Variable([0, 0, 0, 0, 0], name='data') for i in range(5): data = np.random.randint(1000, size=10000) AVG = tf.scatter_add(AVG, [i], [np.average(data).astype('int')])...
tensorflow
1
356,209
39,884,225
Variation of iterating through a single column
<p>I know there are a zillion ways to iterate through data in a data frame. I am acquiring data from a detector, power, frequency, time. The time and power columns have values in every row. The frequency changes with time <strong>but</strong> for each frequency 'segment' the frequency and duty cycle are only listed in ...
<p>You want <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>fillna</code></a>:</p> <pre><code>data = '''time power frequency duty_cycle 1.4 1.2 500.0 45.0 2.1 49.9 NaN NaN 3.4 245.0 NaN NaN 4.5 323.0 NaN NaN 5.6 320.0 N...
python|python-3.x|numpy|dataframe
1
356,210
39,969,751
How to load pre-trained tensorflow model named inception by Google?
<p>I have downloaded a tensorflow checkpoint model named <code>inception_resnet_v2_2016_08_30.ckpt</code>.</p> <p>Do I need to create a graph (with all the variables) that were used when this checkpoint was created?</p> <p>How do I make use of this model?</p>
<p>First of you have get the network architecture in memory. You can get the network architecture from <a href="https://github.com/tensorflow/models/blob/master/research/slim/nets/inception_resnet_v2.py" rel="nofollow noreferrer">here</a></p> <p>Once you have this program with you, use the following approach to use th...
python|tensorflow
4
356,211
40,275,144
Upgrading numpy version
<p>I have three numpy in my system. They are at /usr/local/lib/python2.7/dist-packages/numpy, ~/anaconda2/lib/python2.7/site-packages/numpy and ~/tensorflow/lib/python2.7/site-packages/numpy. tensorflow is Python virtual environment.</p> <p>I checked the versions. How I checked is inside numpy has version.py file and ...
<p>check the path using</p> <pre><code>import numpy print numpy.__path__ </code></pre> <p>and manually delete it using rm / sudo rm if operation is not permitted. try, running the command below, it will overwrite to the latest numpy path.</p> <pre><code>sudo easy_install numpy </code></pre> <p>Now, try to import te...
python|python-2.7|numpy
1
356,212
40,319,433
Numpy: find the euclidean distance between two 3-D arrays
<p>Given, two 3-D arrays of dimensions (2,2,2):</p> <pre><code>A = [[[ 0, 0], [92, 92]], [[ 0, 92], [ 0, 92]]] B = [[[ 0, 0], [92, 0]], [[ 0, 92], [92, 92]]] </code></pre> <p>How do you find the Euclidean distance for each vector in A and B efficiently?</p> <p>I have tried for-loops but t...
<p>Thinking in a NumPy vectorized way that would be performing element-wise differentiation, squaring and summing along the last axis and finally getting square root. So, the straight-forward implementation would be -</p> <pre><code>np.sqrt(((A - B)**2).sum(-1)) </code></pre> <p>We could perform the squaring and summ...
python|numpy|matrix|vectorization|euclidean-distance
5
356,213
40,202,170
Python/Pandas: Array (back) to DataFrame
<p>I applied following function to normalize the columns in my dataframe.</p> <pre><code>from sklearn.preprocessing import normalize pd.DataFrame(normalize(traffic, norm='l2', axis=1, copy=True, return_norm=False)) </code></pre> <p>However, this function returns an array</p> <pre><code>array([[ 0.19781966, 0.21981...
<p>If <code>normalize</code> function returns an array of the same shape as the <code>traffic</code> DF you can do it this way:</p> <pre><code>pd.DataFrame(normalize(traffic, norm='l2', axis=1, copy=True, return_norm=False), columns=traffic.columns, index=traffic.index) </code></pre>
arrays|pandas|dataframe|normalize
0
356,214
40,257,492
GridSearchCV: "TypeError: 'StratifiedKFold' object is not iterable"
<p>I want to perform GridSearchCV in a RandomForestClassifier, but data is not balanced, so I use StratifiedKFold:</p> <pre><code>from sklearn.model_selection import StratifiedKFold from sklearn.grid_search import GridSearchCV from sklearn.ensemble import RandomForestClassifier param_grid = {'n_estimators':[10, 30, 1...
<h2>I had exactly the same problem. The solution that worked for me is to <strong>replace</strong>:</h2> <pre><code>from sklearn.grid_search import GridSearchCV </code></pre> <h2><strong>with</strong></h2> <pre><code>from sklearn.model_selection import GridSearchCV </code></pre> <hr> <p><strong>Then it should work...
pandas|scikit-learn|grid-search|sklearn-pandas
10
356,215
39,907,720
Pandas: How to do analysis on array-like field?
<p>I'm doing analysis on movies, and each movie have a <code>genre</code> attribute, it might be several specific genre, like <code>drama</code>, <code>comedy</code>, the data looks like this:</p> <pre><code>movie_list = [ {'name': 'Movie 1', 'genre' :'Action, Fantasy, Horror'}, {'name': 'Movie 2', 'ge...
<p>If your data isn't too huge, I would do some pre-processing and get 1 record per genre. That is, I would structure your data frame like this:</p> <pre><code> Name Genre Movie 1 Action Movie 1 Fantasy Movie 1 Horor ... </code></pre> <p>Note the names should be repeated. While this may make your data set much...
python|pandas|statistics
0
356,216
40,203,500
RNN regression using Tensorflow?
<p>I am currently trying to implement a RNN for regression. I need to create a neural network capable of converting audio samples into vector of mfcc feature. I've already know what the feature for each audio samples is, so the task it self is to create a neural network that is capable of converting a list of audio sa...
<pre><code>tf.one_hot(length, ...) </code></pre> <p>here length is a function, not a tensor. Try length(something) instead.</p>
python-2.7|audio|tensorflow|regression|recurrent-neural-network
0
356,217
40,300,622
Slicing a list in Python: is there something like -0?
<p>I've got a 3D array and would like to split it into many subvolumes. This is my code so far:</p> <pre><code># this results in a 3D array arr = trainMasks[0, 0, :, :, :] crop = 3 arrs = [arr[x:-(crop - x), y:-(crop - y), z:-(crop - z)] for x in range(crop + 1) for y in range(crop + 1) for z i...
<p>In cases like this it is better to avoid negative indexes.</p> <p>Remeber that for <code>i&gt;0</code>, <code>a[-i]</code> is equivalent to <code>a[len(a)-i]</code>. But in your case, you also need to work for <code>i==0</code>. </p> <p>This works:</p> <pre><code>d1, d2, d3 = arr.shape arrs = [arr[ x : d1-(crop-...
python|arrays|numpy|list-comprehension
5
356,218
40,090,734
Implementing __eq__ using numpy isclose
<p>I fear this might be closed as being a soft question, but perhaps there is an obvious idiomatic way.</p> <p>I have a class that contains a lot of information stored in floating point numbers. I am thinking about implementing the <code>__eq__</code> method using not exact but numerical equivalence similar to <code>...
<p>One option would be to add a context manager to switch modes:</p> <pre><code>from contextlib import contextmanager class MyObject(object): _use_loose_equality = False @contextmanager @classmethod def loose_equality(cls, enabled=True): old_mode = cls._use_loose_equality cls._use_loose...
python|python-3.x|numpy|floating-point|precision
1
356,219
39,898,151
simplify numpy array representation of image
<p>I have an image, read into <code>np.array</code> by PIL. In my case, it's a<code>(1000, 1500)</code> <code>np.array</code>.</p> <p>I'd like to simplify it for visualisation purposes. By simplification, I following transformation from this matrix</p> <pre><code>1 1 1 1 0 0 1 0 1 0 0 0 </code></pre> <p>to </p> <p...
<p>You could use <a href="http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.fromarray" rel="nofollow"><code>PIL.Image.fromarray</code></a> to take the image into PIL, then <a href="http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.resize" rel="nofollow">resize</a> or convert ...
python|arrays|image|numpy|image-processing
1
356,220
40,041,757
Converting pandas dataframe to csv
<p><a href="https://i.stack.imgur.com/ZlUc1.png" rel="nofollow"><img src="https://i.stack.imgur.com/ZlUc1.png" alt="enter image description here"></a> I have the dataframe above and I wish to convert it into a csv file.<br> I am currently using <code>df.to_csv('my_file.csv')</code> to convert it but I want to leave 3 b...
<p>Consider outputting data frame initially as is to a temp file. Then, during creation of the <em>MainCSV</em>, read in temp file, iteratively writing lines, then destroy temp file. Also, prior to writing dataframe to csv, create the three blank columns. </p> <p>Below assumes you want two tasks: 1) three blank column...
python|csv|pandas
1
356,221
40,085,168
Why won't my Python script run using Docker?
<p>I need to use Tensorflow on my Windows machine. I have installed Docker, and following these two tutorials (<a href="https://runnable.com/docker/python/dockerize-your-python-application" rel="nofollow">https://runnable.com/docker/python/dockerize-your-python-application</a> and <a href="https://civisanalytics.com/bl...
<p>I fixed it! The problem was simply the './' in the CMD line in the Dockerfile. Removing this and building it again solved the problem.</p>
python|windows|docker|tensorflow
3
356,222
40,103,226
kNN - How to locate the nearest neighbors in the training matrix based on the calculated distances
<p>I am trying to implement k-nearest neighbor algorithm using python. I ended up with the following code. However, I am struggling with finding the index of the items that are the nearest neighbors. The following function will return the distance matrix. However I need to get the indices of these neighbors in the <cod...
<p>I will suggest to use the python library <code>sklearn</code> that has a <code>KNeighborsClassifier</code> from which, once fitted, you can retrieve the nearest neighbors you are looking for :</p> <p>Try this out:</p> <pre><code># Import from sklearn.neighbors import KNeighborsClassifier # Instanciate your classi...
python|numpy|machine-learning|knn
1
356,223
40,128,515
pairwise comparisons within a dataset
<p>My data is 18 vectors each with upto 200 numbers but some with 5 or other numbers.. organised as:</p> <pre><code>[2, 3, 35, 63, 64, 298, 523, 624, 625, 626, 823, 824] [2, 752, 753, 808, 843] [2, 752, 753, 843] [2, 752, 753, 808, 843] [3, 36, 37, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91...
<p>You can use <code>itertools</code> to generate your pairwise comparisons. If you just want the items which are shared between two lists you can use a <code>set</code> intersection. Using your example:</p> <pre class="lang-python prettyprint-override"><code>import itertools a = [2, 3, 35, 63, 64, 298, 523, 624, 625...
python|python-2.7|numpy|scipy|cosine-similarity
1
356,224
40,107,591
Indexing and slicing dataframe by date and time in python
<p>I have time a series datasets. I can select data from march to may by this code: </p> <pre><code>df[(df.index.month &gt;=3) &amp; (df.index.month&lt;=5)] </code></pre> <p>But the problem is how to select the data from <code>march-15</code> to <code>may-15</code>? Any help will be highly appreciated.</p> <p>and m...
<p>You can use helper <code>Series</code> <code>s</code> where all years are replaced to same - e.g. <code>2000</code>:</p> <pre><code>print (df) A 2001-02-25 0.01 2002-02-26 0.03 2003-02-27 1.00 2004-02-28 1.52 2005-03-29 0.23 2006-03-01 0.45 2007-03-05 2.15 2008-03-06 1.75 s = pd.Series(df.in...
python|pandas|numpy|dataframe
2
356,225
39,732,288
Pandas: how to plot a line in a scatter and bring it to the back/front?
<p>I have checked to the best of my capabilities but haven't found any <code>kwds</code> that allow you to draw a line (such as <code>y=a-x</code>) on a <code>pandas</code> scatter plot (not necessarily the line of best fit) and bring it to the back (or to the front).</p> <pre><code>#the data frame ax=df.plot(kind='sc...
<p>You need to define an axis, and then pass the pandas plot to that axis. You then plot whatever line to that previously defined axis. Here is a solution.</p> <pre><code>np.random.seed(365) # for repeatable data x = np.random.randn(100) y = np.random.randn(100) line = 0.5*np.linspace(-4, 4, 100) x_line = np.linspace(...
python|pandas|matplotlib
5
356,226
39,690,785
Getting a list as the result of a function in pandas
<p>I have data frame in pandas and I have written a function to use the information in each row to generate a new column. I want the result to be in a list format:</p> <pre><code> A B C 3 4 1 4 2 5 def Computation(row): if row['B'] &gt;= 3: return [s for...
<p>Say you start with</p> <pre><code>In [25]: df = pd.DataFrame({'A': [3, 4], 'B': [4, 2], 'C': [1, 5]}) </code></pre> <p>Then there are at least two ways to do it.</p> <p>You can apply twice on the <code>C</code> column, but switch on the <code>B</code> column:</p> <pre><code>In [26]: np.where(df.B &gt;= 3, df.C.a...
list|function|pandas
1
356,227
39,620,105
Converting between projections using pyproj in Pandas dataframe
<p>This is undoubtedly a bit of a "can't see the wood for the trees" moment. I've been staring at this code for an hour and can't see what I've done wrong. I know it's staring me in the face but I just can't see it!</p> <p>I'm trying to convert between two geographical co-ordinate systems using Python.</p> <p>I have ...
<p>When you do <code>df[['newLong','newLat']] = df.apply(convertCoords,axis=1)</code>, you are indexing the columns of the <code>df.apply</code> output. However, the column order is arbitrary because your series was defined using a dictionary (which is inherently unordered).</p> <p>You can opt to return a Series with ...
python|python-3.x|pandas|gis|proj
4
356,228
39,429,058
Simulate impulsive signal and plotting
<p>I'm trying to plot an impulsive signal (Taken from a scientific paper), the equation of the impulsive signal is: <a href="https://i.stack.imgur.com/Zxhig.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zxhig.png" alt="Impact formula" /></a></p> <p>where:</p> <p>Ar= Amplitude of the impulses and eq...
<h1>1.</h1> <blockquote> <p>F=sampling freq. equals to 10 kHz</p> </blockquote> <p>But you wrote</p> <pre><code>F = 10 ** 3 </code></pre> <p>In Python <code>**</code> mean exponentiation, so this is just 10<sup>3</sup> = 1000. That is, you have used F = 1 kHz in your code.</p> <p>If you want to express 10.0 &tim...
python|numpy|signal-processing
2
356,229
39,559,183
What is the reason to use parameter server in distributed tensorflow learning?
<p><strong>Short version:</strong> can't we store variables in one of the workers and not use parameter servers?</p> <p><strong>Long version:</strong> I want to implement synchronous distributed learning of neural network in tensorflow. I want each worker to have a full copy of the model during training.</p> <p>I've ...
<p>Using parameter server can give you better network utilization, and lets you scale your models to more machines.</p> <p>A concrete example, suppose you have 250M parameters, it takes 1 second to compute gradient on each worker, and there are 10 workers. This means that each worker has to send/receive 1 GB of data t...
tensorflow|distributed
24
356,230
39,562,373
substract from date tuple
<p>I have an index consisting of Date tuples.</p> <pre><code>2005-02-04 00:00:00 31.81 31.81 31.81 31.81 2005-02-07 00:00:00 31.885 31.885 31.885 31.885 2005-02-08 00:00:00 31.5326 31.5326 31.5326 31.5326 </code></pre> <p>I would like to...
<p>Actually I ve found it, you simply need to take the first element off the tuple, and it returns a 'TimeStamp' object: </p> <pre><code>df.index.min()[0] - dt.timedelta(minutes=5) </code></pre> <p>works </p>
python|datetime|pandas|dataframe
0
356,231
39,715,612
classification with LSTM RNN in tensorflow, ValueError: Shape (1, 10, 5) must have rank 2
<p>I am trying to design a simple lstm in tensorflow. I want to classify a sequence of data into classes from 1 to 10.</p> <p>I have <em>10 timestamps</em> and data X. I am only taking one sequence for now, so my batch size = 1. At every epoch, a new sequence is generated. For example X is a numpy array like this-</p>...
<p>Looking at your code, your rnn output should have a dimension of <code>batch_size x 1 x num_hidden</code> while your w has dimension <code>batch_size x num_classes x 1</code> however you want multiplication of those two to be <code>batcH_size x num_classes</code>. </p> <p>Can you try <code>output = tf.reshape(outpu...
python|tensorflow|deep-learning|recurrent-neural-network|lstm
2
356,232
39,471,918
'if' on a function when calculating a new column
<p>I have a pandas dataframe <code>df</code> with 2 columns: <code>date1</code> and <code>date2</code>. I want to calculate a new one with the months distances between the 2.</p> <p>If I do:</p> <pre><code>def meses(d1, d2): return (d1.year - d2.year)*12 + d1.month - d2.month df['mora']=meses(df.date1.dt,df.date2....
<p>The first one works because you are performing a simple calculation on an entire series at once i.e. just subtracting or adding the entire column. The second one doesn't work because you checking to see if an entire series/list of values is less than another. Obviously more efficient ways to do this but I keeping as...
python-3.x|pandas
1
356,233
39,553,292
Representing time sequence input/output in tensorflow
<p>I've been working through the TensorFlow documentation (still learning), and I can't figure out how to represent input/output sequence data. My inputs are a sequences of 20 8-entry vectors, making a 8x20xN matrix, where N is the number of instances. I'd like to eventually pass these through an LSTM for sequence to...
<p>As described in the excellent blog post by <a href="http://www.wildml.com/2016/08/rnns-in-tensorflow-a-practical-guide-and-undocumented-features/" rel="nofollow">WildML</a>, the proper way is to save your example in a TFRecord using the formate <code>tf.SequenceExample()</code>. Using TFRecords for this provides the...
python|tensorflow
1
356,234
39,675,716
How can I advance the index of a pandas.dataframe by one quarter?
<p>I would like to shift the index of a pandas.dataframe by one quarter. The dataframe looks like:</p> <pre><code> ID Nowcast Forecast 1991-01-01 35 4144.70 4137.40 1991-01-01 40 4114.00 4105.00 1991-01-01 60 4135.00 4130.00 .... </code></pre> <p>So far, I calculate the number of occu...
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#dateoffset-objects" rel="nofollow">pd.DateOffset()</a>:</p> <pre><code>In [110]: df Out[110]: ID Nowcast Forecast 1991-01-01 35 4144.7 4137.4 1991-01-01 40 4114.0 4105.0 1991-01-01 60 4135.0 4130.0 In [...
python|pandas
2
356,235
39,461,473
Installing BioPython and Numpy
<p>I am working with Python 2.7.11. I've working problems on Rosalind.com from scratch, but I decided to try using tools that are openly available- in order to start familiarizing myself with finding and using said packages and extensions. Good thing too, because I can't figure out how to get any of the third party ext...
<p>So you need to install your modules into your python path. There is some (windows) documentation to that <a href="https://docs.python.org/2/using/windows.html" rel="nofollow">here</a> and <a href="https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7">here</a> but should be easily add...
python|numpy|installation-package|installation-path
0
356,236
39,527,826
How to optimize code that iterates on a big dataframe in Python
<p>I have a big pandas dataframe. It has thousands of columns and over a million rows. I want to calculate the difference between the max value and the min value row-wise. Keep in mind that there are many NaN values and some rows are all NaN values (but I still want to keep them!).</p> <p>I wrote the following code. I...
<p>It is usually a bad idea to use a <code>python</code> <code>for</code> loop to iterate over a large <code>pandas.DataFrame</code> or a <code>numpy.ndarray</code>. You should rather use the available build in functions on them as they are optimized and in many cases actually not written in python but in a compiled la...
python|pandas|optimization|dataframe
2
356,237
39,539,914
Are user defined functions callable?
<p>I am not a very experience programmer. Please can you tell me why this code gives me the error message:</p> <p>error: quad: first argument is not callable</p> <p>code:</p> <pre><code>from matplotlib import pyplot as plt import numpy as np import scipy.integrate as integrate def parabola(x, a): return a+x**2 ...
<p>There are two problems in your code:</p> <p>1) you call the function <code>parabola()</code>. Instead, pass it as an argument to <code>integrate</code>.</p> <p>2) <code>parabola()</code> is a two argument function. <code>integrate</code> expects a single-argument function.</p> <p>To solve the second problem, you ...
python|numpy
3
356,238
39,535,756
apply vector of functions to vector of arguments
<p>I'd like to take in a list of functions, <code>funclist</code>, and return a new function which takes in a list of arguments, <code>arglist</code>, and applies the <code>i</code>th function in <code>funclist</code> to the <code>i</code>th element of <code>arglist</code>, returning the results in a list:</p> <pre><c...
<p>In <code>numpy</code> terms true vectorization means performing the iterative stuff in compiled code. Usually that requires using <code>numpy</code> functions that work with whole arrays, doing thing like addition and indexing.</p> <p><code>np.vectorize</code> is a way of iterate of several arrays, and using their...
python|numpy|vectorization
3
356,239
39,674,863
Python - Alternative for using numpy array as key in dictionary
<p>I'm pretty new to Python numpy. I was attempted to use numpy array as the key in dictionary in one of my functions and then been told by Python interpreter that numpy array is not hashable. I've just found out that one way to work this issue around is to use <code>repr()</code> function to convert numpy array to a s...
<p>If you want to quickly store a <code>numpy.ndarray</code> as a key in a dictionary, a fast option is to use <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.tobytes.html" rel="noreferrer">ndarray.tobytes</a>() which will return a raw python <code>bytes</code> string which is immutab...
python|arrays|numpy|dictionary
25
356,240
39,737,304
most efficient way to create tensorflow::tensor from std::vector
<p>So my question is to know if there is a way to pass directly the values from a <code>vector</code> (but we could also think about <code>array</code>) to a <code>tensorflow::tensor</code>?</p> <p>The only way I know is to copy each value one by one.</p> <p><strong>Example (2D Vector)</strong>: </p> <pre><code>tens...
<p>how about this? <code>std::copy_n(vec.begin(), vec.size(), input.flat&lt;float&gt;().data())</code></p>
c++|tensorflow
6
356,241
44,253,129
Tensorflow shape not correct
<p>I've been trying to use Tensorflow, but I keep getting errors regarding the shape of my data. I'm getting my code from this YouTube tutorial: <a href="https://www.youtube.com/watch?v=PwAGxqrXSCs&amp;list=PLQVvvaa0QuDfKTOs3Keq_kaG2P55YRn5v&amp;index=47" rel="nofollow noreferrer">https://www.youtube.com/watch?v=PwAGxq...
<p>The reason is that you are generating <code>n_classes</code> predictions from the network (<code>n_classes</code> is 10), while comparing it with 4 values in your <code>y</code> placeholder. It should be enough to use</p> <pre><code>y = tf.placeholder('float', [10]) </code></pre> <p>and then actually feed 10 value...
machine-learning|tensorflow|deep-learning|shapes|reshape
1
356,242
44,339,292
Tflearn KeyError [] not in index
<p>I have this code, i think im doing something wrong with de input of de data in the neural net (the neural net is only provisionally)</p> <p>here is my code:</p> <pre><code>import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn import preprocessing import tflearn ...
<p>Place the following code at the beginning of your code to reset the graph. If you ran the code interactively in IPython environment, the tensorflow graph can get really messy. </p> <pre><code>import tensorflow as tf tf.reset_default_graph() </code></pre> <p>Many people are in the same shoes as you do. Refer to <a...
tensorflow|scikit-learn|tflearn
0
356,243
44,093,698
How does Tensorflow Batch Normalization work?
<p>I'm using tensorflow batch normalization in my deep neural network successfully. I'm doing it the following way:</p> <pre class="lang-py prettyprint-override"><code>if apply_bn: with tf.variable_scope('bn'): beta = tf.Variable(tf.constant(0.0, shape=[out_size]), name='beta', trainable=True) gamm...
<p>The formula used is slightly different from:</p> <pre><code>bn = scale * (x - mean) / (sqrt(var) + 1e-3) + offset </code></pre> <p>It <a href="https://github.com/tensorflow/tensorflow/blob/r1.2/tensorflow/python/ops/nn_impl.py#L780" rel="nofollow noreferrer">should be</a>:</p> <pre><code>bn = scale * (x - mean) /...
tensorflow|batch-normalization
2
356,244
44,116,201
Elegant way to concatenate string in one column to several columns in df
<p>I have a df structured as so:</p> <pre><code> CUID DATE T1 T2 T3 0 1000 5/5/2016 3:58:54 4:02:00 4:15:05 1 1001 5/6/2016 17:23:39 17:24:00 17:44:32 2 1002 5/7/2016 18:20:50 18:22:00 18:37:34 3 1003 5/7/2016 21:30:29 21:35:00 21:45:51 4 1004 5/9/2016 ...
<p>Not a pandas feature but you could reduce the code duplication with a simple loop:</p> <pre><code>for column in ['T1', 'T2', 'T3']: df[column] = pd.to_datetime(df.DATE.str.cat(' ' + df[column])) </code></pre>
python|pandas|time|string-concatenation
2
356,245
44,251,758
Neural network: stddev of weights as function of layer size. Why?
<p>Quick question about neural networks. I understand why weights are initialized with a small random value. I breaks a tie between weights so that they have a non-zero loss gradient. I was under the impression that it didn't matter much what the small random value was as long as the tie is broken. Then I read this:</p...
<p>First of all always remember that the aim of these initialization and training is to make sure the neurons and hence the network learns something meaningful.</p> <p>Now assume you are using a sigmoid activation function</p> <p><a href="https://i.stack.imgur.com/2Ohs3.jpg" rel="nofollow noreferrer"><img src="https:...
tensorflow|neural-network
2
356,246
44,284,506
PyTorch: access weights of a specific module in nn.Sequential()
<p>When I use a pre-defined module in PyTorch, I can typically access its weights fairly easily. However, how do I access them if I wrapped the module in <code>nn.Sequential()</code> first? r.g:</p> <pre><code>class My_Model_1(nn.Module): def __init__(self,D_in,D_out): super(My_Model_1, self).__init__() ...
<p>An easy way to access the weights is to use the <code>state_dict()</code> of your model.</p> <p>This should work in your case:</p> <pre><code>for k, v in model_2.state_dict().iteritems(): print(&quot;Layer {}&quot;.format(k)) print(v) </code></pre> <p>Another option is to get the <code>modules()</code> itera...
python|pytorch
12
356,247
44,222,066
How to put bars close to each other in a seaborn's factorplot when comparing 1 variable against many, in python?
<p>I want to make a plot to compare one variable (Fp1) against other 5 ones. How can I make the bars be joined? How can I get rid of the space between them? Is there a way?</p> <p>The dataframe:</p> <pre><code>raw_data = {'Max_Acc': [90.71, 87.98, 92.62, 78.93, 73.69, 73.66, 72.29, 92.62, 94.17, ...
<p>The factorplot reserved one position in the bar subgroups for each unique item in the column given to the <code>hue</code> argument. You could therefore introduce a new column with only two different values.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np import seaborn.apionly...
python-3.x|pandas|matplotlib|data-visualization|seaborn
3
356,248
44,360,708
Python pandas - DataFrame groupby and re-construct
<p>I have a question for groupby() in pandas</p> <p>If I have a DataFrame <strong>"df"</strong> like</p> <pre><code> user day click 0 U1 Mon 15 1 U2 Mon 7 2 U1 Wed 15 3 U3 Tue 21 4 U2 Tue 15 5 U2 Tue 10 </code></pre> <p>When I use <strong>df.groupby(['user', 'day']).sum()</...
<p>Use pivot function with day as columns and fill with clicks.</p> <pre><code>df.groupby(['user', 'day']).sum().reset_index()\ .pivot(index='user',columns='day',values='click') Out[388]: day Mon Tue Wed user U1 15.0 NaN 15.0 U2 7.0 25.0 NaN U3 NaN 21.0 NaN </code></pre>...
python|pandas
3
356,249
44,046,962
Python: Create a new column of date from an existing column of date by subtracting consecutive rows
<p><strong>Code:</strong></p> <pre><code>import pandas as pd df = pd.read_csv('xyz.csv', usecols=['transaction_date', 'amount']) df=pd.concat(g for _, g in df.groupby("amount") if len(g) &gt; 3) df=df.reset_index(drop=True) print(df) </code></pre> <p><strong>Output:</strong></p> <pre><code> transaction_date am...
<p>there're probably some better methods, but you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html" rel="nofollow noreferrer"><code>pandas.Series.shift</code></a>:</p> <pre><code>&gt;&gt;&gt; df.transaction_date.shift(-1) - df.transaction_date 0 0 days 1 0 day...
python|pandas|datetime
0
356,250
44,281,322
Create array by sampling PDF
<p>I would like to create a 2D array with numpy, where each entry at (x,y) is either 0 or 1, and the probability to get a 1 is defined by a PDF, for example a 2D gaussian.</p> <p>The goal ist to be able to add many such arrays, and retrieve something like a histogram where I can see the 2D gaussian peak.</p> <p>I've ...
<p>I don't think that there is a build-in functionality for that but as you already suggested you can easily achieve what you want by comparing random numbers to a threshold. You should not iterate using something like a <code>for</code> loop though, as those are rather slow. I'd suggest to use <a href="https://docs.sc...
python|numpy
2
356,251
44,270,198
When using TFRecord, how can I run intermediate validation check? (a better way?)
<p>Let's say I defined a network <code>Net</code> and the example code below runs well.</p> <pre><code># ... input processing using TFRecord ... # reading from TFRecord x, y = tf.train.batch([image, label]) # encode batch net = Net(x,y) # connect to network # ... initialize ...
<p>There is a better way (than placeholders). I ran into this issue with the CIFAR10 tutorial in TensorFlow, which I adjusted to check accuracy on the test set simultaneous to the training every 500 batches or so. This is where sharing variables comes in handy.</p> <pre><code>x, y = tf.train.batch([image, label], ...)...
python|tensorflow
2
356,252
44,029,578
style transfer implementation tensorflow
<p><a href="https://github.com/cysmith/neural-style-tf/blob/master/neural_style.py" rel="nofollow noreferrer">Here</a>, I read some tensorflow implementation of style transfer. Specifically, it defines the loss which is then to be optimized. In one loss function, it says: `</p> <pre><code>def sum_style_losses(sess, ne...
<p>The code from the github repo is as follows:</p> <pre><code>init_op = tf.global_variables_initializer() sess.run(init_op) sess.run(net['input'].assign(init_img)) optimizer.minimize(sess) </code></pre> <p>A <code>session</code> schedules operations to be run on devices and holds some variables. It can be used to sc...
python|tensorflow|deep-learning
0
356,253
44,078,660
apply a function that takes an argument to an ndimage labeled array
<p>I have an array that I've labeled using scipy.ndimage and I'd like to multiply each element by a factor specific to its corresponding label. I thought I could use ndimage.labeled_comprehension for this, however I can't seem to figure out how to pass an argument to the function. For example:</p> <pre><code>a = np.ra...
<p>Index into factors and then simply multiply with the image array -</p> <pre><code>a*factors[lbls] </code></pre> <p>Sample run -</p> <pre><code>In [483]: a # image/data array Out[483]: array([[ 0.10682998, 0.29631501, 0.08501469], [ 0.46944505, 0.88346229, 0.75672908], [ 0.11381292, 0.240968...
python|numpy|scipy|ndimage
1
356,254
43,950,791
Efficiently converting a Series of dictionaries to a DataFrame
<p>I have a large (ish) <code>Series</code> of dictionaries that I'd like "flatten". In order to test / reproduce my problem I have created a <code>Series</code> with a similar structure:</p> <pre><code>&gt;&gt;&gt; my_series = pd.Series([{'A': [1], 'B' : []}, {'A' : [1, 2], 'B' : [3, 4]}]) &gt;&gt;&gt; my_series 0 ...
<p>First off, since you have your dictionaries in a pandas-based data structure you might be able to create a <code>DataFrame</code> instead of a series.</p> <p>Secondly <code>DataFrame</code> can accept a list of dictionaries and construct the expected result for you. So, if you don't have the control over the constr...
python|performance|pandas
1
356,255
44,000,169
loading Json file in python
<p>I have tried to load a <code>JSON</code> file in pandas with this code and I have this error in the fist line. I think that same thing is wrong in json structure because I tried also with <code>pd.read_json</code> and it didn't work. What is wrong here?</p> <pre><code>Name_file='data582750.txt' l=[] with open(Name...
<p>Please post code, not images... </p> <p>Anyway: <strong><em>from what I can see</em></strong> you have a <a href="http://jsonlines.org/" rel="nofollow noreferrer">jsonlines file</a> - each line is a the representation of a distinct json object by itself. <code>json.loads()</code> expects a single string (representi...
python|json|pandas
2
356,256
44,204,726
Preserving Left/Right Join Logic in Pandas Conditional Join
<p>Pandas currently doesn't support a conditional join in the SQL sense; however, one can be emulated (with lesser performance) by performing a larger join on common fields and then applying a filter on the post-join processing.</p> <p>However, I'm looking for a way to preserve left (or right) elements through this co...
<p>I'm not sure this is the best approach, but it seems to do the job:</p> <pre><code>In [191]: v_df.merge(v_df.merge(df).query("start &lt;= date &lt;= end"), how='left') Out[191]: date name val end start 0 2018-01-01 A 10 2018-02-05 2017-12-01 1 2017-01-01 B 20 NaT NaT </c...
python|pandas|numpy|join
2
356,257
44,255,362
Tensorflow: simultaneous prediction on GPU and CPU
<p>I’m working with tensorflow and I want to speed up the <strong>prediction</strong> phase of a pre-trained Keras model (I'm not interested in the training phase) by using <strong>simultaneously</strong> the CPU and one GPU. </p> <p>I tried to create 2 different threads that feed two different tensorflow sessions (on...
<p>Here's my code that demonstrates how CPU and GPU execution can be done in parallel:</p> <pre><code>import tensorflow as tf import numpy as np from time import time from threading import Thread n = 1024 * 8 data_cpu = np.random.uniform(size=[n//16, n]).astype(np.float32) data_gpu = np.random.uniform(size=[n , n...
python|performance|tensorflow|keras
5
356,258
44,089,653
How can I create a data frame from a text file
<p>I have a text file. Each line in the file looks like this, but has a different length:</p> <pre><code>negative فينو اهبل ابن اهبل positive فينو اهبل ابن اهبل neutral فينو اهبل ابن اهبل </code></pre> <p>when I use <code>pandas.read_table</code> it reads it into one column, I tried converting the file into Excel or...
<p>first read the the whole file into a DataFrame with a single column:</p> <pre><code>df = pd.read_csv('/path/to/file.txt', sep='~', header=None) </code></pre> <p>yields:</p> <pre><code>In [50]: df Out[50]: 0 0 negative aaa bbb ccc ddd 1 positive qqq vvv </code></pre> <p>now ...
python|pandas|dataframe|nlp|text-mining
3
356,259
44,139,234
How do I create a NumPy array from results of a pyodbc query?
<p>I would like to create an array or list from values pulled from a SQL query. From research I believe the data I pull from SQL is a tuple. </p> <p>How do format the data into a list I can use in python? </p> <p>In my current code I try to use the numpy command np.asarray. I'm not sure if numpy arrays allow date...
<blockquote> <p>From research I believe the data I pull from SQL is a tuple.</p> </blockquote> <p>Not exactly. pyodbc's <code>fetchall()</code> method does not return a list of tuples, it returns a list of <code>pyodbc.Row</code> objects:</p> <pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; rows =...
python|numpy|tuples|pyodbc
2
356,260
69,600,139
Converting 2 column dataframe of codes and inconsistent descriptions into a nested list of all possible descriptions for each unique code
<p>Apologies for the poor wording of this posts title, I'm unsure of how best to simplify the explanation for what I'm trying to do.</p> <p>I have a dataframe output where accounting codes with an inconsistent description column between lines are flagged up. For example:</p> <pre><code> Accounting Codes Account Descr...
<p>Use <code>groupby_apply</code>:</p> <pre><code>duplicates = df.groupby('Accounting Codes')['Account Description'] \ .apply(lambda x: [x.name, *x]).tolist() print(duplicates) # Output: [['D_B', '2', 'two'], ['D_C', '3', 'three'], ['D_D', '4', 'four', 'FOUR']] </code></pre>
python|pandas|dataframe|tkinter
2
356,261
69,652,230
Pandas Dataframe GroupBy, How to get the value that everything is grouped by?
<p>My apologizes for the title, I can't think of a better one. I have a csv files that I am reading to a dataframe. This CSV tracks all the times a machine was turned on and logs that time. I am converting the time to a timestamp, and then using <code> df.groupby()</code> to count all the occurrences within an hour. Th...
<p>When you perform a <code>DataFrame.goupby()</code>, the resulting DataFrame will have the <code>by</code> argument as index (here Timestamp).</p> <p>You can use <code>DataFrame.reset_index()</code> after your groupby to reset the index to the default one. The old index will be turned back into a column.</p>
python|pandas|dataframe|pandas-groupby
1
356,262
69,538,102
remove text in a dataframe
<p>I have the dataframe df below: df:</p> <pre><code>Description sociis natoque (penatibus/magnis) nec dui nunc mattis enim (ut/tellus/elementum) </code></pre> <p>I want to remove (penatibus/magnis) and (ut/tellus/elementum) from the description column</p> <p>so i used</p> <pre><code>df[&quot;Description&quot;] =...
<p>Feasible solution using regex:</p> <pre><code>df['Description'] = [re.sub(&quot;[\(\[].*?[\)\]]&quot;, &quot;&quot;, str(x)) for x in df['Description']] </code></pre> <p>This will remove any contents of <code>(...)</code> or <code>[...]</code>, parenthesis included</p>
python|pandas|dataframe
0
356,263
69,549,324
Get the value at a specific index in PyTorch
<p>I have a ground truth label array for size 5.</p> <pre><code>y=tensor([958, 85, 244, 182, 294]) </code></pre> <p>I have the output for scores array of shape : [5,1000]</p> <pre><code>scores = tensor([[ 1.0406, 1.1808, 4.4227, ..., 4.6864, 8.0145, 5.2128], [ 6.9101, 4.6083, 6.9259, ..., 9.7415...
<p>Yes, you can do it by using your <code>y</code> array as an index:</p> <pre><code>scores[torch.arange(5), y] </code></pre>
deep-learning|pytorch
1
356,264
69,631,885
quantile groupby pandas dataframe
<p>I have below pandas dataframe. I want to create a new column that would give me 75% quantile rate groped by State and County</p> <p>below code gives me only 75% quantile rate as output, i want to create a new column with 75% quantile rate in the existing df</p> <p>df = df.groupby('State')['rate'].quantile(0.75)</p> ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with lambda function:</p> <pre><code>df['q'] = df.groupby('State')['rate'].transform(lambda x: x.quantile(0.75)) </code></pre> <p>I...
pandas|group-by|quantile
2
356,265
69,588,429
How to recalculate DataFrame column values based on condition dict (Pandas Python)
<p>Lets say I have the following DataFrame:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>A</th> <th>B</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>aa</td> <td>4.32</td> </tr> <tr> <td>1</td> <td>aa</td> <td>7.00</td> </tr> <tr> <td>2</td> <td>bb</td> <td>8.00</td> </tr> <tr>...
<p>Use <code>pd.Series.map</code>:</p> <pre><code>print (df[&quot;A&quot;].map(dict1).fillna(1)*df[&quot;B&quot;]) 0 -4.32 1 -7.00 2 16.00 3 74.00 4 30.00 5 4.00 dtype: float64 </code></pre>
python-3.x|pandas|dataframe
0
356,266
69,393,552
NumPy setup install doesn't work for IronPython
<p>I'm currently working on a python integration project for a c# application. Everything I need between IronPython and C# was working, now my next step is to implement numpy and scipy for the script usage.</p> <p>I have already installed them on my computer with ironpkg over the following link: <a href="http://code.en...
<p>I solved it. My current company where I'm doing an internship uses proxy and pip can't connect to the servers without using it in the command.</p> <p>The usage is like following:</p> <pre><code>pip install --proxy=&quot;server:port&quot; packagexyz </code></pre> <p>You have to add your proxy server, port and replace...
numpy|scipy|ironpython
1
356,267
69,503,677
How to extract feature after Label Encoding for object to numeric conversion
<pre><code>%matplotlib inline import matplotlib.pyplot as plt import pandas as pd bank=pd.read_csv('train_bank.csv') df=pd.DataFrame(bank) df.head() ID Gen Mar Dep Edu Sel Income 0 LP001002 Male No 0 Graduate No 5849 1 LP001003 Male Yes 1 Graduate No 4583 2 LP001...
<p>Normally the order of the categories are defined alphabetically, so for example in your <code>Edu</code> column, <code>Grad</code> is 0 and <code>Not Grad</code> would be 1.</p> <p>You can store your classes as you iterate through your columns, for example:</p> <pre><code>from sklearn.preprocessing import LabelEncod...
python|pandas|scikit-learn|classification
0
356,268
69,363,222
run functions with differents parameters with python
<p>I have functions that i want to run with differents parameters</p> <p>Here is the directory structure:</p> <pre><code>App/ ├─ main.py └─ fcts1.py └─ fcts2.py └─ File1.csv └─ File2.csv └─ Files/ └─B.xlsx └─A.txt └─C.xlsx </code></pre> <p><strong>Exp 1:</strong></p> <pre><code>f...
<p>You can replace these 6 functions with one:</p> <pre><code>def fct(file_number, file_letter, function): # Key idea: you can pass functions as arguments df = pd.read_excel(file_number) dfA = pd.read_excel(file_letter) function() </code></pre> <p>This can be called like this:</p> <pre><code>import fcts...
python|python-3.x|pandas|parameter-passing|argparse
0
356,269
69,501,759
HTTP Error 503 when reading xlsx file from url
<p>I'm trying to import the following excel file in pandas: <a href="https://rbnz.govt.nz/-/media/ReserveBank/Files/Statistics/tables/b2/hb2-daily-close.xlsx" rel="nofollow noreferrer">https://rbnz.govt.nz/-/media/ReserveBank/Files/Statistics/tables/b2/hb2-daily-close.xlsx</a></p> <p>I tried the following:</p> <pre><co...
<p>It appears that when you added the headers, you removed the <code>www</code> from the start of the URL. That address (without the <code>www</code>) gives you a <code>HTTP 301 Redirect</code>, which with <code>urllib</code> is not automatically followed.</p> <p>Try adding <code>www</code> to your URL when fetching wi...
python|excel|pandas|web-scraping|python-requests
0
356,270
69,443,821
GPFlow Multiclass classification with vector inputs causes value error on shape mismatch
<p>I am trying to follow the Multiclass classification in GPFlow (using v2.1.3) as described here:</p> <p><a href="https://gpflow.readthedocs.io/en/master/notebooks/advanced/multiclass_classification.html" rel="nofollow noreferrer">https://gpflow.readthedocs.io/en/master/notebooks/advanced/multiclass_classification.htm...
<p>When running your example I get a slightly different bug, but the issue is in how you define lengthscales and variances. You write:</p> <pre class="lang-py prettyprint-override"><code>lengthscales = [0.1]*num_classes variances = [1.0]*num_classes kernel = gpflow.kernels.Matern32(variance=variances, lengthscales=leng...
python|tensorflow|gpflow|gaussian-process
1
356,271
69,319,011
Python using Pandas to_sql: How do I add the data from Excel to MariaDB without writing the data to the ID and timestamp column?
<p>I want to import data from Excel into a database using Pandas.</p> <p>In my database that I created using MariaDB, I have in the first column the ID that automatically increments and in the second column a timestamp. The data I have in Excel I want to insert from the third column in the MariaDB. In addition, the dat...
<p>You can do this by assigning column names when you read the Excel file, and then dropping the columns that you don't need before writing to the database. The column name(s) that you want to write to the database must match those in the database table.</p> <p>Given this table</p> <pre class="lang-none prettyprint-ove...
python|mysql|excel|pandas|mariadb
0
356,272
69,421,970
Python How to do conditional selection after groupby
<p>I have a large dataframe mostly hast unique values, still there are multiple same IDs with different values stored. I want to group the same IDs then apply a logic to those to select one among them then remove the others.</p> <pre><code>df = pd.DataFrame({'ID': [11, 11,11,11,22,22,33] , 'Source': ...
<pre><code>d= {4:1,2:2, 3:3} # dict of drop hierarchy new=(df.assign(rank=df.Source.map(d))#Create a rank column that maps the hierachy of selection .sort_values(by='rank')#Sort new dataframe by rank .drop_duplicates(subset='ID',keep='first')#Drop all the duplicated Source values .drop('rank',1)#Drop the...
python|pandas|dataframe|conditional-statements|pandas-groupby
1
356,273
69,459,960
Pandas how to compare two csv file for delete duplicate?
<p>Assume I have two csv file csv1 and csv2. Now I will to delete all record from csv2 if any record match with csv1. Both csv have unique identifier sku.</p> <p>csv1:</p> <pre><code>sku name Gk125 Jhone GK126 Mike </code></pre> <p>csv2:</p> <pre><code>sku name Gk127 Doe GK128 Hock GK126 Mike #th...
<p>Works fine for me:</p> <pre><code>df1 = pd.DataFrame(data={'sku':['Gk125', 'GK126'], 'name':['Jhone', 'Mike']}) df2 = pd.DataFrame(data={'sku':['Gk127', 'GK128', 'GK126'], 'name':['Doe', 'Hock', 'Mike']}) print(df2[~df2['sku'].isin(df1['sku'])]) </code></pre> <p>Output:</p> <pre><code> sku name 0 Gk127 Doe ...
python|python-3.x|pandas|dataframe
3
356,274
69,459,301
NER using spaCy & Transformers - different result when running inside and outside of a loop
<p>I am using NER (spacy &amp; Transformer) for finding and anonymizing personal information. I noticed that the output I get when giving an input line directly is different than when the input line is read from a file (see screenshot below). Does anyone have suggestions on how to fix this?</p> <p><a href="https://i.st...
<p>You are using the csv module to read your file and then trying to convert each row (aka line) of the file to a string with <code>str(row)</code>.</p> <p>If your file just has one sentence per line, then you do not need the csv module at all. You could just do</p> <pre class="lang-py prettyprint-override"><code>with ...
python|spacy|huggingface-transformers|named-entity-recognition
3
356,275
69,392,272
Exception in device=TPU:0: Cannot replicate if number of devices (1) is different from 8
<p>I was trying to create a gan which which will generate anime faces by a dataset from kaggle.</p> <p>I am using pytorch on colab and for faster training I used tpu and pytorch_xla</p> <p>But when I run the code it generates an error and says Exception in device=TPU:0: Cannot replicate if number of devices (1) is diff...
<p>This error suggests the system received an unexpected number of processes for your job. Try calling:</p> <p><code>history = xmp.spawn(fit, args=(epochs, lr), nprocs=1, start_method='fork')</code></p>
pytorch|generative-adversarial-network|tpu
0
356,276
69,583,960
Training fasttext word embedding on your own corpus
<p>I want to train fasttext on my own corpus. However, I have a small question before continuing. Do I need each sentences as a different item in corpus or can I have many sentences as one item?</p> <p>For example, I have this DataFrame:</p> <pre><code> text | summary ...
<p>FastText requires <em>text</em> as its training data - not anything that's pre-vectorized, as if by <code>TfidfVectorizer</code>. (If that's part of your FastText process, it's misplaced.)</p> <p>The Gensim FastText support requires the training corpus as a <em>Python iterable</em>, where each item is a <em>list of ...
python|tensorflow|gensim|word-embedding|fasttext
1
356,277
69,514,818
PYTHON, Pandas Dataframe: how to select and read only certain rows
<p>For the purpose to be clear here is the code that works perfectly (of course I put only the beginning, the rest is not important here):</p> <pre><code>df = pd.read_csv( 'https://github.com/pcm-dpc/COVID-19/raw/master/dati-andamento-nazionale/' 'dpc-covid19-ita-andamento-nazionale.csv', parse_dates=['data'], index_co...
<p>try this:</p> <pre><code>df = pd.read_json('https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-json/dpc-covid19-ita-regioni.json', convert_dates =['data']) df.index = df['data'] df.index = df.index.normalize() df = df[df[&quot;denominazione_regione&quot;] == 'Veneto'] ts = df[['nuovi_positivi']].dropna(...
python|json|pandas|dataframe
0
356,278
69,560,213
How to Export 2D Table in a csv file using PyCharm
<p>I have a xml file: 'product.xml', here is an example of the sample file:</p> <pre><code>&lt;?xml version=&quot;1.0&quot;?&gt; &lt;Rowset&gt; &lt;ROW&gt; &lt;Product_ID&gt;32&lt;/Product_ID&gt; &lt;Company_ID&gt;2&lt;/Company_ID&gt; &lt;User_ID&gt;90&lt;/User_ID&gt; &lt;Product_Type&gt;1&lt;/Product_Ty...
<p>Try:</p> <pre><code>def parse_row(row): ret = {'User_ID':np.nan, 'Application_ID':np.nan} for attr in row: if attr.tag in ret: ret[attr.tag] = attr.text return ret out = pd.DataFrame([parse_row(r) for r in root]) </code></pre> <p>Output:</p> <pre><code> User_ID Application_ID 0 90 ...
python|pandas|xml|csv
0
356,279
69,418,175
x.reshape([1,28,28,1]) reshaping meaning
<p>I can not understand what this reshaping actually do with an array of 28*28.</p> <p><strong>the code is:</strong></p> <pre><code>x.reshape([1,28,28,1]) </code></pre>
<p>Reshape - as the name suggests - reshapes your array into an array of different shape.</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; x = np.arange(28*28) &gt;&gt;&gt; x.shape (784,) &gt;&gt;&gt; y = x.reshape(28,28) &gt;&gt;&gt; y.shape (28, 28) &gt;&gt;&gt; z = y.r...
python|numpy
0
356,280
69,599,393
Pandas fill dates
<p>I have the following dataframe, the <strong>date</strong> corresponds to quarterly periods and the <strong>amount</strong> (and other additional columns not shown here for simplification) corresponding to the associated <strong>id</strong> grouping. Dates are unique per id.</p> <pre><code>import pandas as pd from nu...
<p>You need to define a new time range every third month starting from 2019-12-31 and reindex your dataframe. Then fill the <code>NaN</code> values with a backward fill <code>bfill</code> method. See code below with comments.</p> <pre><code>import pandas as pd # Create the DataFrame according to your question d = {'id...
python|pandas|dataframe|date|pandas-groupby
4
356,281
69,519,370
How to sum arrays in nested arrays?
<p>I have a nested array</p> <pre><code>array([[1,2,4], [2,5,6]]) </code></pre> <p>I want to sum each array in it to get:</p> <pre><code>array([[7], [13]]) </code></pre> <p>How to do that? When I do <code>np.array([[1,2,4], [2,5,6]])</code> it gives</p> <p><code> array([7, 13])</code></p>
<p>Using <code>sum</code> over axis 1:</p> <pre><code>&gt;&gt;&gt; a = np.array([[1,2,4], [2,5,6]]) &gt;&gt;&gt; a.sum(axis=1, keepdims=True) [[ 7] [13]] </code></pre> <p>Or without numpy:</p> <pre><code>&gt;&gt;&gt; a = [[1,2,4], [2,5,6]] &gt;&gt;&gt; [[sum(l)] for l in a] [[7], [13]] </code></pre>
python|python-3.x|numpy|sum
3
356,282
69,610,067
How to fix ValueError: Input contains NaN, infinity or a value too large for dtype('float64'). Error
<p>So I'm trying to write a piece of code that can predict the &quot;pr10tournaments&quot; from the csv data. I am running into an error that says</p> <pre><code>ValueError: Input contains NaN, infinity or a value too large for dtype('float64') </code></pre> <p>Here is the code</p> <pre><code>from os import sep import ...
<p>The issue is because of the first line of your csv file. It is trying to process the strings as floats. I am assuming those are just identifying each column, so I would just remove it.</p>
python|pandas|scikit-learn
0
356,283
69,390,223
Replace a string if it starts with a certain character
<p>I am trying to use Pandas <code>map</code> to assign values to keys, where the keys would be strings returned if an entry in the DataFrame starts with a certain character.</p> <p>Using an example from the Pandas docs, with the following DataFrame and my code:</p> <pre><code>import numpy as np import pandas as pd s ...
<p>Instead function <code>lambda</code> is possible create dictionary and mapping first letter by indexing <code>str[0]</code>:</p> <pre><code>print (s.str[0].map({'c': 'kitten', 'd': 'puppy', 'r': 'bunny'})) 0 kitten 1 puppy 2 NaN 3 bunny dtype: object </code></pre> <p>If lengths of strings for test s...
python|pandas|string|dictionary
4
356,284
69,428,662
Any way of running EfficientDet from the TF Object Detection API inference on a batch of images instead of 1?
<p>I have managed to download the object detection API from the model garden (Tensorflow 2.0, the Object Detection API ). All the inference code I could find (in the directory &amp; online) works on a batch size of 1.</p> <p>I was thinking about reconfiguring the <em>pipeline.config</em> file somehow. More specifically...
<p><strong>Ok so after a lot of tinkering with the code, this is my answer to my own question:</strong></p> <p>Starting from a simple source of pre-trained models:</p> <p><em>1.</em> The TF HUB repo of models gives you many different Object detection models. I specifically wanted to use the EffifcientDet architecture.<...
tensorflow|tensorflow2.0|object-detection|tensorflow-model-garden
1
356,285
69,505,915
precisely slice a 3d array in python
<p>I want to slice a 3D array</p> <blockquote> <p>[-500:500]</p> </blockquote> <p>to subarrays in sequence 100 subarrays of length 2 then one of length 50 then 100 of length 2 then one of length 50, and I wish every subarray is spaced by length one from the following.</p>
<p>This solution is the only one that worked for me: The purpose of the slicing is to distribute particles inside the box. I used software called <code>gsd</code> to produce a GSD file.</p> <p>*) get the <code>xyz</code> file, with the help of another software (I used jmol program ), then you have the orientations of t...
python|arrays|3d|numpy-slicing
1
356,286
69,665,676
Remove rows from pandas dataframe with condition
<p>I have a dataframe that looks like this:</p> <p>import pandas as pd</p> <pre><code>### create toy data set data = [[1111,'10/1/2021',21,123], [1111,'10/1/2021',-21,123], [1111,'10/1/2021',21,123], [2222,'10/2/2021',15,234], [2222,'10/2/2021',15,234], [3333,'10/3/2021',15,234],...
<p>I can't be sure since you did not post your expected output, but you could try the below. Create a separate df called <code>n</code> that contains the rows with -ve 'number' and join it to the original with <code>indicator=True</code>.</p> <pre><code>n = df.loc[df.number.le(0)].drop('number',axis=1) df = pd.merge(df...
python|pandas
1
356,287
69,513,799
pandas read_csv: The error_bad_lines argument has been deprecated and will be removed in a future version
<p>I am trying to read some data which may sometimes have erroneous and bad rows, so as always I passed <code>error_bad_lines=False</code> but the console keeps throwing the deprecation warning on every run. Why is this feature deprecated and is there any other alternative for skipping bad lines?</p>
<p>Read the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="noreferrer">documentation</a>:</p> <blockquote> <p>Deprecated since version 1.3.0: The on_bad_lines parameter should be used instead to specify behavior upon encountering a bad line instead.</p> </blockquote> <p>S...
python|pandas|csv
25
356,288
69,312,964
replace value to NaN based on other column value python pandas
<p>I got the following test dataframe.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>contact</th> <th>phone1_x</th> <th>phone2_x</th> <th>phone1_y</th> <th>phone2_y</th> <th>Match1</th> <th>Match2</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1234</td> <td>12</td> <td>1234</td> <td></td...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> - first replace <code>True</code> to <code>np.nan</code>, if False no replace:</p> <pre><code>df[['phone1_y','phone2_y']] = np.where(df[['Match1','Match2']], ...
python|pandas|dataframe
2
356,289
69,483,029
matplotlib bar chart with overlapping dates
<p>I am plotting a simple bar chart using <code>pandas</code>/<code>matplotlib</code>. The x-axis is a datetime index. There are so many datapoints that the labels overlap. Is there an easy solution for this problem, no matter if I have daily, weekly, monthly, or yearly data?</p> <pre><code>import matplotlib.pyplot as ...
<p>Use <code>DateFormatter</code> to custom the xaxis but let Matplotlib handle the figure rather than Pandas:</p> <pre><code>import matplotlib.dates as mdates # ... fig, ax = plt.subplots(figsize=(15, 7)) ax.bar(df.index, df['returns']) ax.xaxis.set_major_locator(mdates.YearLocator()) ax.xaxis.set_major_formatter(md...
python|pandas|datetime|matplotlib
0
356,290
69,492,864
Python pandas dataframe returning NaN while defining columns name
<p>I'm new in python and I'm trying to read a csv file, delete some columns that are not usefull and write it into another csv file. I manage to do this, but I want to add columns name to my csv, i'm using dataframe to do this but the values are returning NaN while i'm having real values in my tab.</p> <pre><code>impor...
<p>If you want to rename your columns I would recommend setting them in the existing DataFrame, and not creating a new one.</p> <pre><code>x.columns = ['TimeStamp','OpenTemp','CloseTemp','MeanTemp','EndTimeStamp'] </code></pre>
python|pandas|dataframe|csv
0
356,291
69,555,051
Group columns from column to column
<p>I have a dataframe like the following:</p> <p><a href="https://i.stack.imgur.com/Issfz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Issfz.png" alt="enter image description here" /></a></p> <p>and I want to group the answers like the following</p> <p><a href="https://i.stack.imgur.com/Duvx8.png"...
<p>You can use <code>pandas.MultiIndex.from_array</code> to manually craft your custom index:</p> <pre><code>new_level = ['GROUP1', 'GROUP1', 'GROUP1', 'GROUP2', 'GROUP2', 'GROUP3', 'GROUP3'] df.columns = pd.MultiIndex.from_arrays([new_level, df.columns]) </code></pre> <p>example input:</p> <pre><code> A B C D E ...
python|pandas
1
356,292
69,356,871
Python Pylab linspace import order question?
<p>I am trying to use Pylab to plot the function sin(x)/|x|, but I am facing with this problem.</p> <p>When I run this code, it worked fine.</p> <pre><code>from pylab import * from math import * from numpy import * x=linspace(-10*pi,10*pi,10000) plot(x,sin(x)/abs(x)) show() </code></pre> <p>However, this occurs an err...
<p>As mentioned in the comments, the way the libraries are called might be overwritten, it is always best to cut it simple and short like this so that the program do not get confused:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x=np.linspace(-10*np.pi,10*np.pi,10000) plt.plot(x,np.sin(x)/abs(x)) ...
python|numpy|matplotlib
2
356,293
69,404,671
From multiples CSV to Dataframe columns with calculs
<p>I got 10 csvfiles like this :</p> <p><img src="https://i.imgur.com/McRxuOm.png" alt="Text" /></p> <p>I want to add 10 columns in my dataframe with a vwap calculation. I tried to create the columns and then to concatenate it into the dataframe but it doesn't work at all. I tried a lot of things, the main problem is t...
<p>If need only aggregate values in ouput:</p> <pre><code>def add(df): #Removed read_csv df[&quot;timestamp&quot;] = pd.to_datetime(df[&quot;timestamp&quot;]) df = df.groupby(pd.Grouper(key = &quot;timestamp&quot;, freq = &quot;h&quot;)).agg(&quot;mean&quot;).reset_index() price = df[&quot;price&quot;]...
python|pandas|dataframe|merge|concatenation
1
356,294
69,491,507
Python inverse step slice
<p>Occasionally I am in a scenario where I want to take every nth element from a list A and put it in list B, and all other elements into list C. Creating list B is basic python slicing. Is there an elegant way to create list C?</p> <p>For example:</p> <pre><code>A = [0, 1, 2, 3, 4, 5, 6] B = A[::3] # B = [0, 3, 6] C =...
<h1>Pure Python</h1> <p>As you already stated constructing list B is easy. List C could be constructed with <a href="https://docs.python.org/3/library/itertools.html#itertools.compress" rel="nofollow noreferrer">compress</a> and <a href="https://docs.python.org/3/library/itertools.html#itertools.cycle" rel="nofollow no...
python|numpy
3
356,295
69,320,321
Automatic GPU offloading in python
<p>I have written a piece of scientific code in python, mainly using the numpy library (especially Fast Fourier Transforms), and a bit of Cython. Nothing in CUDA or anything GPU related that I am aware of. There is no graphic interface, everything runs in the terminal (I'm using WSL2 on Windows). The whole code is most...
<p><strong>No</strong>, there is no automatic offloading in Numpy, at least not with the <em>standard Numpy implementation</em>. Note that some specific FFT libraries can use the GPU, but the standard implementation of Numpy uses its own implementation of FFT called <a href="https://github.com/numpy/numpy/tree/main/num...
python|numpy|gpu
1
356,296
40,800,031
get special date columns that columns contain date,hour,seconds
<p>I have a dataframe:</p> <pre><code> df=pandas.DataFrame([{'remarkTime':'2014-03-03 10:18','name':'a'},{'remarkTime':'2015-05-03 09:12','name':'b'}, {'remarkTime':'2014-03-03 18:12','name':'c'}]) </code></pre> <p>I want get the remarkTime which is 2014-03-03. the result like this:</p> <pre>...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with comparing <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow noreferrer"><code>date</code></a...
python|pandas
1
356,297
40,979,760
Compare 2 consecutive rows and assign increasing value if different (using Pandas)
<p>I have a dataframe df_in like so:</p> <pre><code>import pandas as pd dic_in = {'A':['aa','aa','bb','cc','cc','cc','cc','dd','dd','dd','ee'], 'B':['200','200','200','400','400','500','700','700','900','900','200'], 'C':['da','cs','fr','fs','se','at','yu','j5','31','ds','sz']} df_in = pd.DataFrame(dic_i...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html" rel="noreferrer"><code>shift</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html" rel="noreferrer"><code>any</code></a> to compare consecutive rows, using <code>True</co...
python|pandas|dataframe|replace|compare
17
356,298
40,881,876
Python pandas convert datetime to timestamp effectively through dt accessor
<p>I have a DataFrame with some (hundreds of) million of rows. And I want to convert datetime to timestamp effectively. How can I do it?</p> <p>My sample <code>df</code>:</p> <pre><code>df = pd.DataFrame(index=pd.DatetimeIndex(start=dt.datetime(2016,1,1,0,0,1), end=dt.datetime(2016,1,2,0,0,1), freq='H'))\ .rese...
<p>I think you need convert first to <code>numpy array</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.values.html" rel="noreferrer"><code>values</code></a> and cast to <code>int64</code> - output is in <code>ns</code>, so need divide by <code>10 ** 9</code>:</p> <pre><code>df['t...
python|datetime|pandas|timestamp
97
356,299
41,037,000
Merge 2 dataframes according to length of list (using Pandas)
<p>I have one dataframe <code>df1</code> like so:</p> <pre><code>import pandas as pd import numpy as np dic1 = {'A':['a','b','c','d','e'], 'B':[np.nan,np.nan,np.nan,150,np.nan], 'C':['x','y','z','v','w']} df1 = pd.DataFrame(dic1) </code></pre> <p>I then have a second dataframe <code>df2</code>:</p> <...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_records.html" rel="nofollow noreferrer"><code>DataFrame.from_records</code></a> for remove <code>lists</code> from column <code>Z</code>:</p> <pre><code>df2 = df2[df2['Z'].str.len() == 1] df2.Z = pd.DataFrame.from_reco...
python|pandas|dataframe|replace|merge
1