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
7,800
53,638,825
Introduction to Data Science in Python problem
<p>Can any one tell my what that part (town = thisLine[:thisLine.index('(')-1])exactly do?</p> <pre><code>def get_list_of_university_towns(): '''Returns a DataFrame of towns and the states they are in from the university_towns.txt list. The format of the DataFrame should be: DataFrame( [ ["Michigan", "Ann Arbor"], ["...
<p>It performs this step:</p> <pre><code>2. For "RegionName", when applicable, removing every character from " (" to the end. </code></pre> <p>An index of <code>-1</code> means the end of an array or list.</p>
python|pandas|numpy|data-science
0
7,801
53,436,301
How can I calculate the 3 genres most frequent it in python pandas?
<p>I have a dataframe with one column and I need to return 3 most frequent genres.</p> <blockquote> <p><strong>INPUT</strong></p> </blockquote> <pre><code> genres 0 Drama 1 Animation|Children's|Musical 2 Musical|Romance 3 Drama 4 Animation|Children's|Comedy 5 Action|Adventure|Comedy|Romance 6 Actio...
<p>You need <code>split</code> first , the do <code>stack</code> , then using <code>value_counts</code></p> <pre><code>df.genres.str.split('|',expand=True).stack().value_counts().head(3) Drama 6 Musical 6 Children's 5 dtype: int64 </code></pre>
python|pandas|data-science
1
7,802
71,928,043
Subtract one column from another in pandas - with a condition
<p>I have this code that will subtract, for each person (AAC or AAB), timepoint 1 from time point 2 data.</p> <p>i.e this is the original data:</p> <pre><code> pep_seq AAC-T01 AAC-T02 AAB-T01 AAB-T02 0 0 1 2.0 NaN 4.0 1 4 3 2.0 6.0 NaN 2 4 3...
<p>I hope that I understand you correctly but <code>numpy.where()</code> should do it for you.</p> <p>Have a look here: <a href="https://stackoverflow.com/questions/64031732/subtract-two-date-columns-given-condition-in-another-column">condition based substraction</a></p>
python|pandas
0
7,803
72,107,118
Converting simple returns to monthly log returns
<p>I have a pandas DataFrame with simple daily returns. I need to convert it to monthly log returns and add a column to the current DataFrame. I have to use <code>np.log</code> to compute the monthly return. But I can only compute daily log return. Below is my code.</p> <pre><code>df[‘return_monthly’]= np.log(data([‘Si...
<p>The question is a little confusing, but it seems like you want to group the rows by month. This can be done with pandas.resample if you have a datetime index, pandas.groupby, or pandas.pivot.</p> <p>Here is a simple implementation, let us know if this isn't what you're looking for. Furthermore, your values are less ...
python-3.x|pandas|numpy|return|finance
0
7,804
71,884,092
selection on multiple conditions doesn't work correctly in pandas dataframe
<p>I have a dataframe <code>df</code> which I create by loading a csv file and appending another df to (I know that appending is not done in place, so I assign the result of this operation to <code>df</code>). The dataframe has columns: stimulus (contains strings), syllable (contains numbers 1 or 2), response (contains...
<p>Try this:</p> <pre><code>df.loc[(df['stimulus'].str.contains(&quot;bearded_guy&quot;))&amp;(df['syllable']==1), :] </code></pre>
python|pandas
0
7,805
22,413,561
using numpy to import multiple text files
<p>I've been importing multiple txt files and using them to create plots. The code is the same as before but it isn't seeming to work this time. I've taken it back to basics and I have no idea what's going wrong.</p> <pre><code>import numpy close('all') data = [] pixels = [] for i in range(0,92): data...
<p>The problem is how you are passing the <code>usecols</code> parameter, it must be a sequence (<code>list</code> or <code>tuple</code>, for example), with <code>0</code> being the first column. Perhaps you wanted this:</p> <pre><code>for i in range(0,92): data.append(genfromtxt('filename_'+str(i+1)+'.txt', u...
python|file-io|numpy|genfromtxt
0
7,806
18,021,056
Reading GPS RINEX data with Pandas
<p>I am reading a [RINEX-3.02] (page 60) Observation Data file to do some timed based satellite ID filtering, and will eventually reconstruct it latter. This would give me more control over the selection of satellites I allow to contribute to a position solution over time with RTK post processing.</p> <p>Specifically ...
<p>Here is what I ended up doing</p> <pre><code>df = readObs(indir, filename) df.set_index(['%_GPST', 'satID']) </code></pre> <p>Note that I just set the new MultiIndex at the end after building it. <img src="https://i.stack.imgur.com/yC78L.png" alt="enter image description here"></p> <pre><code>def readObs(dir, fil...
python|python-3.x|gps|pandas
3
7,807
55,543,004
How to resample the dataframe without changing it's core?
<p>How to resample the dataframe without changing it's core?</p> <pre><code>import pandas as pd import sys if sys.version_info[0] &lt; 3: from StringIO import StringIO else: from io import StringIO csvdata = StringIO("""date,LASTA,LASTB,LASTC 1999-03-15,2.5597,8.20145,16.900 1999-03-16,2.6349,8.03439,17.150 ...
<p>Please convert index to Datetime index:</p> <pre><code>full_df.index = pd.to_datetime(full_df.index) </code></pre>
python|pandas|dataframe|indexing|datetimeindex
1
7,808
9,651,218
TypeError: unorderable types: float() < function()
<p>I have a code comprised of two functions one that reads data and the other that counts it. Both functions run properly when run separately, but I get the error when I try to have the counter call the file reader. I would appreciate it if some one could tell me where I am goofing up. Thanks in advance</p> <p>Error</p...
<p>You are trying to call <code>counter()</code> on the <em>function <code>read_file()</code></em>, not on the results of calling <code>read_file(F)</code>. You don't include source for <code>read_file()</code>, but you almost certainly want to do:</p> <pre><code>counter(readfile(F)) </code></pre> <p>instead of the l...
python|function|numpy
2
7,809
56,694,234
Can anyone tell me how to use tensorflow iou function?
<p>I want to use tensorflow mean_iou function and write a sample code as follwing; but it gives me error message </p> <p>Attempting to use uninitialized value mean_iou_5/total_confusion_matrix [[{{node mean_iou_5/total_confusion_matrix/read}}]]</p> <p>Can anyone tell me how to use mean_iou function of tensorflo...
<p>Taken from the StackOverflow answer here: <a href="https://stackoverflow.com/a/49326455/9820369">https://stackoverflow.com/a/49326455/9820369</a></p> <pre><code># y_pred and y_true are np.arrays of shape [1, size, channels] with tf.Session() as sess: ypredT = tf.constant(np.argmax(y_pred, axis=-1)) ytrueT =...
python|tensorflow|deep-learning
2
7,810
56,710,490
plot a normal distribution curve and histogram
<p>Please, I want to know how I can plot a normal distribution plot.</p> <p>Here is my code:</p> <pre><code>import numpy as np import scipy.stats as stats import pylab as pl h=[27.3,27.6,27.5,27.6,27.3,27.6,27.9,27.5,27.4,27.5,27.5,27.4,27.1,27.0,27.3,27.4] fit = stats.norm.pdf(h, np.mean(h), np.std(h)) #this is a...
<p>Simply sort your list <code>h</code>.</p> <p>Using sorted like this:</p> <pre><code>h = sorted([27.3,27.6,27.5,27.6,27.3,27.6,27.9,27.5,27.4,27.5,27.5,27.4,27.1,27.0,27.3,27.4]) </code></pre> <p>Alternatively, you can also use <code>h.sort()</code>.</p> <pre><code>h =[27.3,27.6,27.5,27.6,27.3,27.6,27.9,27.5,27.4...
python|numpy|matplotlib|scipy
1
7,811
56,577,834
How to do a loop scrape from a pandas dataframe
<p>So, I have a data frame with a lot of URL, but there is only the second part of the link... I want to do a loop-scrape of every URL but I don't know how to do. I already know what I want to scrape, but I don't know how do the loop.</p> <p>This is the main: <a href="https://www.brewersfriend.com" rel="nofollow noref...
<pre><code>df['links'] = df['URL'].apply(lambda x : 'https://www.brewersfriend.com' + x ) </code></pre>
python|pandas|dataframe|screen-scraping
0
7,812
56,798,635
Random selection with conditional probabilities
<p>I have list say <code>y = [1, 2, 3, 4, 6, 7, 8, 9, 5, 23, 12, 24, 43, 10]</code> and I want to make a random selection from it with conditional probability. A number greater than 10 in the list has a probability of say 0.8 of being selected while the rest have probability 0.2 of being selected.</p>
<p>Since random.choice provides a uniform distribution, you will have to work in two steps. First select between the groups of values (below 10 and above 10). Then select a value within the group.</p> <p>To get different probabilities between groups, you can create a list with the appropriate number of repetitions o...
python|numpy|random|choice
3
7,813
25,460,028
Use numpy to get the positions of all objects in 3D space relative to one another
<p>I want get the differences between all permutations of pairs of <em>vectors</em> in a numpy array.</p> <p>In my specific use case these vectors are the 3D position vectors of a list of objects.</p> <p>So, if I have an array <code>r = [r1, r2, r3]</code> where <code>r1</code>, <code>r2</code> and <code>r3</code> ar...
<p><strong>Short answer:</strong></p> <p>An (almost) pure Python way to do a "pair-wise outer subtraction" of vectors <code>r</code> would be as follows:</p> <pre class="lang-py prettyprint-override"><code>np.array(map(operator.sub, *zip(*product(r, r)))).reshape((2, 2, -1)) </code></pre> <p>So you basically can use...
python|arrays|numpy|vector|array-broadcasting
3
7,814
26,273,512
Numpy's asarray() doesn't work with csr_matrix
<p>I'm a big trouble. I wrote code in python that is using <code>Numpy</code> and <code>Networkx</code> 6 months ago with this code:</p> <pre><code>import numpy as np import networkx as nx G = nx.Graph() #add node and edges to G ... A = nx.adj_matrix(Gx) A = np.asarray(A) </code></pre> <p>Now I need to run this on a...
<p>Judging from this pull request:</p> <p><a href="https://github.com/networkx/networkx/commit/67bf6c1b4d2844a859b21057a63a72b36a45906b" rel="nofollow">https://github.com/networkx/networkx/commit/67bf6c1b4d2844a859b21057a63a72b36a45906b</a></p> <p>In Nov 2013, <code>networkx</code> changed <code>adjacency_matrix</cod...
python|numpy
1
7,815
67,004,312
Multi-output regression using skorch & sklearn pipeline gives runtime error due to dtype
<p>I want to use skorch to do multi-output regression. I've created a small toy example as can be seen below. In the example, the NN should predict 5 outputs. I also want to use a preprocessing step that is incorporated using sklearn pipelines (in this example PCA is used, but it could be any other preprocessor). When ...
<p>By default <code>OneHotEncoder</code> returns numpy array of <code>dtype=float64</code>. So one could simply cast the input-data <code>X</code> when being fed into <code>forward()</code> of the model:</p> <pre><code>class RegressionModule(torch.nn.Module): def __init__(self, input_dim=80): super().__init...
python|pytorch|torch|dtype|skorch
3
7,816
66,775,321
Training accuracy decrease and loss increase when using pack_padded_sequence - pad_packed_sequence
<p>I'm trying to train a bidirectional lstm with pack_padded_sequence and pad_packed_sequence, but the accuracy keeps decreasing while the loss increasing.</p> <p>This is my data loader:</p> <pre><code>X1 (X[0]): tensor([[1408, 1413, 43, ..., 0, 0, 0], [1452, 1415, 2443, ..., 0, 0, 0], [14...
<p>These lines of your code are wrong.</p> <pre><code># take only the final time step out1 = out1[:, -1, :] out2 = out2[:, -1, :] </code></pre> <p>You say you are taking the final time step but you are forgetting that each sequence has different lengths.</p> <p><code>nn.utils.rnn.pad_packed_sequence</code> will <strong...
python|pytorch|bilstm
1
7,817
67,135,327
What is the difference between tensorflow-gpu and tensorflow?
<p>When I see some tutorials regarding TensorFlow with GPU, it seems that the tutorial is using tensorflow-gpu instead of tensorflow.<br /> The only info I got is the <a href="https://pypi.org/project/tensorflow-gpu/#:%7E:text=TensorFlow%20is%20an%20open%20source%20software%20library%20for%20high%20performance,to%20mob...
<p>The main difference is that you need the GPU enabled version of TensorFlow for your system. However, before you install TensorFlow into this environment, you need to setup your computer to be GPU enabled with CUDA and CuDNN.</p> <p>| Support for TensorFlow libraries | tensorflow | tensorflow-gpu | | for hardware ty...
python|tensorflow
1
7,818
67,044,621
Pandas dataframe column forward fill from first non-zero value
<p>I am looking to forward fill specific dataframe columns from first non-zero value and I further want to do this for each group.</p> <pre><code>df = pd.DataFrame(np.array([[1, 0, 0], [1, 5, 1], [1, 8, 0],[2, 4, 0],[2, 8, 1],[2, 81, 0]]), columns=['ID', 'b', 'c']) </code></pre> <p>The result I want ...
<p>Use <code>.values</code> attribute:</p> <pre><code>df['c']=df.groupby('ID',as_index = False)['c'].apply(lambda x: x.replace(to_replace=0, method='ffill')).values </code></pre> <p>Now if you print <code>df</code> you will get your desired output:</p> <pre><code> ID b c 0 1 0 0 1 1 5 1 2 1 8 1 ...
python|pandas
2
7,819
47,232,779
How to extract and save images from tensorboard event summary?
<p>Given a tensorflow event file, how can I extract images corresponding to a specific tag, and then save them to disk in a common format e.g. <code>.png</code>?</p>
<p>You could extract the images like so. The output format may depend on how the image is encoded in the summary, so the resulting write to disk may need to use another format besides <code>.png</code></p> <pre><code>import os import scipy.misc import tensorflow as tf def save_images_from_event(fn, tag, output_dir='....
python|tensorflow|tensorboard
17
7,820
47,444,011
Python 2.7- convert array of strings to csv
<p>I have set of strings, that I want to save as data frame (one column, each string to separated cell). Each string has the following structure: </p> <pre><code>u'word word word\n word word\nword word word word word word \nword word word word' </code></pre> <p>I tried to use <code>np.savetxt("dataframe.csv", string...
<p>You can use pandas.DataFrame.to_csv(path_or_buf='', sep=','). after coverting to csv, then you can write it in a file as .csv file</p>
string|python-2.7|csv|numpy|set
0
7,821
47,212,464
Implement shortcut with Keras Sequential model
<p> I have implemented shortcut with the Keras functional model this way:</p> <pre class="lang-py prettyprint-override"><code>inputs = ... # shortcut path shortcut = ShortcutLayer()(inputs) # main path outputs = MainLayer()(inputs) # add main and shortcut together outputs = Add()([outputs, shortcut]) </code></pre> ...
<p>I would try the following;</p> <pre><code>def my_model_with_shortcut(): def _create_shortcut(inputs): # here create model as in case you know inputs, e.g.: aux = Dense(10, activation='relu')(inputs) output = Dense(10, activation='relu')(aux) return output return _create...
python|tensorflow|machine-learning|keras|deep-learning
0
7,822
68,299,303
numpy sum of each array in a list of arrays of different size
<p>Given a list of numpy arrays, each of different length, as that obtained by doing <code>lst = np.array_split(arr, indices)</code>, how do I get the sum of every array in the list? (I know how to do it using list-comprehension but I was hoping there was a pure-numpy way to do it).</p> <p>I thought that this would wor...
<p>There's a faster way which avoids <code>np.split</code>, and utilizes <a href="https://numpy.org/doc/stable/reference/generated/numpy.ufunc.reduceat.html" rel="nofollow noreferrer"><code>np.reduceat</code></a>. We create an ascending array of indices where you want to sum elements with <code>np.append([0], np.cumsum...
python|numpy
3
7,823
1,053,928
Very large matrices using Python and NumPy
<p><a href="http://en.wikipedia.org/wiki/NumPy" rel="noreferrer">NumPy</a> is an extremely useful library, and from using it I've found that it's capable of handling matrices which are quite large (10000 x 10000) easily, but begins to struggle with anything much larger (trying to create a matrix of 50000 x 50000 fails)...
<p>PyTables and NumPy are the way to go.</p> <p>PyTables will store the data on disk in HDF format, with optional compression. My datasets often get 10x compression, which is handy when dealing with tens or hundreds of millions of rows. It's also very fast; my 5 year old laptop can crunch through data doing SQL-like G...
python|matrix|numpy
93
7,824
59,123,663
Getting top 100 words with highest document frequency in a pandas series
<p>Suppose I have a pandas series like this:</p> <pre><code>0 "sun moon earth moon" 1 "sun saturn mercury saturn" 2 "sun earth mars" 3 "sun earth saturn sun saturn" </code></pre> <p>I want to get the top 3 words with the highest row ("document") frequency <strong>irrespective</strong> of the frequency within a si...
<p>Because performance is important use <code>Counter</code>:</p> <pre><code>from collections import Counter a = Counter([y for x in s for y in x.split()]).most_common(3) print (a) [('sun', 5), ('saturn', 4), ('earth', 3)] b = Counter([y for x in s for y in set(x.split())]).most_common(3) print (b) [('sun', 4), ('ea...
python|pandas|word-frequency
2
7,825
59,359,097
Optimizing a dataframe subset operation in Python
<p>Summarize the Problem</p> <p>I am trying to optimize some code I have written. In its current form it works as intended, however because of the sheer number of loops required the script it takes a very long time to run.</p> <p>I'm looking for a method of speeding up the below-described code.</p> <p>Detail the pro...
<p>your <code>df</code> is not that big and in your code there are few problems:</p> <ul> <li>If you use <code>np.mean</code> and one value is <code>np.nan</code> it returns <code>np.nan</code></li> <li>You can divide by 2 after calculate the mean.</li> <li>It seems to me a perfect case for <code>groupby</code></li> ...
python|pandas|optimization|bioinformatics
2
7,826
59,223,772
Columns display wierd naming after resetting multi index back to columns
<p>So I have been working with a dataframe and converted it to long to wide setting a multi index.</p> <p><code>df_wide = df.pivot_table(index = ["StationId", "day", "month", "year", "hour", "dayofweek"], columns = "minute", values = ["StationTotalFlow"])</code></p> <p>I then used reset_index to reuse the columns I o...
<p>It's not that they're "wrapped in parentheses" really, it's that you went from a MultiIndex to a single-level list of names, so the first level of the MultiIndex became the first element of each tuple, and the second level became the second element of each tuple.</p>
python-3.x|pandas
0
7,827
59,063,138
run pyspark date column thru datetime/pandas function
<p>I have a pyspark dataframe where one column is a date column.</p> <p>I need to run this column thru a pandas/datetime function to calculate business hours.</p> <p>However, I can't seem to get the conversion right:</p> <pre><code>df3 = df2.withColumn('test_date', add_one(df2.AssignedDate.toPandas())) </code></pre>...
<p>You could use regular pyspark.sql.functions to parse the timestamp and manipulate it directly:</p> <pre class="lang-py prettyprint-override"><code>In [1]: from datetime import datetime ...: from pyspark.sql.functions import col, date_format, to_timestamp, when, dayofweek ...: ...: frame = spark.createData...
pandas|datetime|pyspark
2
7,828
59,142,527
np.solve() but when A (first matrix) unknown
<p><code>np.solve()</code> works great when you have an equation in the form of <code>Ax = b</code> My problem is that I actually have an equation in the form of <code>xC = D</code>, where x is a 2x2 matrix I want to find out, and C and D are 2x2 matrices I'm given.</p> <p>And because matrix multiplication is generall...
<p><code>x @ C = D</code> is the same as <code>D^-1 @ x @ C @ C^-1 = D^-1 @ D @ C^-1</code> which is <code>D^-1 @ x = C^-1</code> which is in the form Ax = b where A is <code>np.linalg.pinv(D)</code> and b is <code>np.linalg.pinv(C)</code></p> <p>which boils down to </p> <pre><code>x = D @ np.linalg.pinv(C) </code></...
python|numpy|linear-algebra|matrix-multiplication
2
7,829
59,060,862
Easy way to do this in numpy?
<p>Suppose I have a BxNxL array, M. In other words, M is composed of B NxL matrices. In addition, I have a LxB column vector, Q. Is there any easy way (without for loops) to broadcast (sum) the ith column of Q to the ith matrix in M? </p>
<p>So your iterative code would be?</p> <pre><code>for i in range(...): res[i,:,:] = M[i,:,:] + Q[:,i] # NxL + L </code></pre> <p>with the whole array</p> <pre><code>res = M + Q.T[:,None,:] # BxNxL + (Bx1xL) </code></pre> <p>(I wrote this without a test example, so there might an error, but the basi...
python|numpy
0
7,830
59,107,448
AttributeError: 'numpy.ndarray' object has no attribute 'strip'
<p>i tried to make a training model with multiple inputs and outputs.</p> <p>This model worked very well with single input and output but i got an error message.</p> <p>AttributeError: 'numpy.ndarray' object has no attribute 'strip'</p> <p>I guess the problem is that the fit_generator can't process the numpy array.<...
<p>From the <a href="https://keras.io/models/sequential/#fit_generator" rel="nofollow noreferrer">docs</a>, you cannot simply pass a numpy array in the <code>fit_generator()</code> function. As the name suggests <code>fit_generator()</code> takes in a python generator as an argument. You can use the Keras <code>ImageDa...
numpy|neural-network|multiple-input
0
7,831
59,347,325
Python recursive quadtree issues
<p>I've been writing a recursive quadtree constructor to use for some n-body simulations, but my current implementation doesn't seem to be working properly, and after a lot of debugging, I'm stumped. The results that it gives are clearly incorrect, although all the debugging checks seem to give the results they should....
<p>Try to change the line:</p> <pre><code>quadtree(p3,n+1,x,y,w/2,h/2) </code></pre> <p>to</p> <pre><code>quadtree(p3,n+1,x+w/2,y,w/2,h/2) </code></pre>
python|numpy|quadtree
1
7,832
59,045,410
How can I create a new series by using specific rows and columns of a pandas data frame?
<p>I am working with a pandas data frame which looks like as follows:</p> <pre><code> title view_count comment_count like_count dislike_count dog_tag cat_tag bird_tag other_tag 0 Great Dane Loves 299094 752.0 15167 58 [dog] [] [] [] 1 Guy Loves Hi...
<p>Because if convert empty list to boolean get <code>False</code> you can use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFr...
python|pandas|dataframe|series
3
7,833
13,871,466
Irregular results from numpy and scipy
<p>I am creating finite element code in Python that relies on numpy and scipy for array, matrix and linear algebra calculations. The initial generated code seems to be working and I am getting the results I need.</p> <p>However, for some other feature I need to call a function that performs the analysis more than one ...
<p>If your results are sensitive to rounding error (e.g. you have some programming error in your code), then in general floating point results are not reproducible. This occurs already due to the way modern compilers optimize code, so it does not require e.g. accessing uninitialized memory.</p> <p>Please see: <a href=...
python|numpy|scipy
2
7,834
44,929,823
Unexpectedly needed to give input value to an irrelevant placeholder in the graph
<p><a href="https://gist.github.com/Wermarter/466e9585579ef65927fa934fe4e0ffd4" rel="nofollow noreferrer">https://gist.github.com/Wermarter/466e9585579ef65927fa934fe4e0ffd4</a> Here I'm trying to implement Variational AutoEncoder in Tensorflow with TFLearn.</p> <p>I build the computations for training, encoding, gener...
<p>This is a code-specific error. My <code>self.recognition_model</code> is actually linked to the placeholder <code>self.train_data</code> through <code>self.curr_batch_size</code> in <code>self._sample_z()</code>. My solution is to re-link <code>self.curr_batch_size</code> to the size of <code>self.input_data</code>....
graph|tensorflow|tflearn
0
7,835
44,940,057
why can we use variable name to get data stored in it?
<p>When using Python, I am confronted with a problem confusing me for a long time. Say, I use numpy to define an array <code>x = np.array([1, 2])</code>. </p> <p>This, I think, means that <code>x</code> is an instance of class <code>array</code>. Moreover, the tutorial also says that <code>[1,2]</code> is actually sto...
<p><code>x</code> and <code>x.data</code> are different types though they are interpreting data from the same location in memory</p> <pre><code>In [1]: import numpy as np In [2]: x = np.array([1,2]) In [3]: type(x) Out[3]: numpy.ndarray In [4]: type(x.data) Out[4]: buffer </code></pre> <p><code>x.data</code> is a ...
python|arrays|numpy
4
7,836
44,962,794
How to Integrate Arc Lengths using python, numpy, and scipy?
<p>On another <a href="https://math.stackexchange.com/questions/433094/how-to-determine-the-arc-length-of-ellipse">thread</a>, I saw someone manage to integrate the length of a arc using mathematica.They wrote: </p> <pre><code>In[1]:= ArcTan[3.05*Tan[5Pi/18]/2.23] Out[1]= 1.02051 In[2]:= x=3.05 Cos[t]; In[3]:= y=2.23...
<p>To my knowledge <code>scipy</code> cannot perform symbolic computations (such as symbolic differentiation). You may want to have a look at <a href="http://www.sympy.org" rel="nofollow noreferrer">http://www.sympy.org</a> for a symbolic computation package. Therefore, in the example below, I compute derivatives analy...
python|numpy|scipy|automatic-ref-counting|ellipse
4
7,837
45,151,742
unable to turn a simple text file into pandas dataframe
<p>this is what my file looks like:</p> <p><code>raw_file</code> --> </p> <pre><code>'Date\tValue\tSeries\tLabel\n07/01/2007\t687392\t31537611\tThis home\n08/01/2007\t750624\t31537611\tThis home\n09/01/2007\t769358\t31537611\tThis home\n10/01/2007\t802014\t31537611\tThis home\n11/01/2007\t815973\t31537611\tThis home\...
<p>Why don't you use the <code>csv</code> module and set the delimiter to <code>\t</code>?</p> <p><a href="https://docs.python.org/3.4/library/csv.html" rel="nofollow noreferrer">https://docs.python.org/3.4/library/csv.html</a></p> <p>with csv.reader(your_file, delimiter='\t') as f: # Do stuff</p>
python|pandas|dataframe|text|error-handling
0
7,838
45,265,254
Using tf.contrib.learn to solve basic logistic classifier
<p>I am learning about tf.contrib.learn in Tensorflow, and am using a self-made exercise. The exercise is to classify three regions as follows, with x1 and x2 as inputs, and the labels are triangles/circles/crosses: <a href="https://i.stack.imgur.com/5Amou.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur....
<p>To fix this concrete issue you can add the following input function which is similar to the existing one, except that it returns None as a second element in the tuple</p> <pre><code>def input_fn_predict(): inputs = {"x1": tf.constant([0.1]), "x2": tf.constant([0.2])} print(inputs) return inputs, None </code><...
python|tensorflow|logistic-regression
1
7,839
44,873,026
Sparse matrix with fast access
<p>While working with large SciPy CSR sparse matrices I noticed that slicing the matrix to get a single row from the matrix was very slow as it seems to make a copy.</p> <p>Is there any way to make a sparse matrix that takes a reference of the existing row instead of copying it, perhaps there is a more fitting impleme...
<p>You can take advantage of the CSR representation to slice the underlying arrays directly and share the data with a new CSR matrix:</p> <pre><code>mat = # some CSR matrix i = # the index of whatever row you want start, stop = mat.indptr[i], mat.indptr[i+1] noncopy_row_i = scipy.sparse.csr_matrix((mat.data[start:stop...
python|numpy|scipy
0
7,840
57,280,472
How to plot correlation matrix/heatmap with categorical and numerical variables
<p>I have 4 variables of which 2 variables are nominal (dtype=object) and 2 are numeric(dtypes=int and float). </p> <pre><code>df.head(1) OUT: OS_type|Week_day|clicks|avg_app_speed iOS|Monday|400|3.4 </code></pre> <p>Now, I want to throw the dataframe into a seaborn heatmap visualization.</p> <pre><code>import nump...
<p>The heatmap to be plotted needs values between 0 and 1. For correlations between numerical variables you can use Pearson's R, for categorical variables (the corrected) Cramer's V, and for correlations between categorical and numerical variables you can use the correlation ratio.</p> <p>As for creating numerical repr...
python|pandas|statistics|seaborn
0
7,841
57,048,157
Summing an array along different dim each time with different slice range
<p>Suppose I have an array <code>b</code> of shape <code>(3, 10, 3)</code> and another array <code>v = [8, 9, 4]</code> of shape <code>(3,)</code>, see below. For each of the 3 arrays of shape <code>(10, 3)</code> in <code>b</code>, I need to sum a number of rows as determined by <code>v</code>, i.e. for <code>i = 0, ...
<p>The following function allows for reducing a given axis with varying slices indicated by start and stop arrays. It uses <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.reduceat.html" rel="nofollow noreferrer"><code>np.ufunc.reduceat</code></a> under the hood together with appropriately resh...
python|arrays|numpy|indexing
1
7,842
45,956,139
resetting a Tensorflow graph after OutOfRangeError when using Dataset
<p>I am trying to use <a href="https://www.tensorflow.org/versions/master/api_docs/python/tf/contrib/data/Dataset#from_generator" rel="nofollow noreferrer">the <code>from_generator</code> interface for the Dataset API</a> to inject multiple "rounds" of input into a graph.</p> <p>On my <a href="https://gist.github.com/...
<p>I think the problem stems from using <code>tf.contrib.data.Dataset</code> (which supports reinitialization) with <code>tf.train.batch_join()</code> (which uses TensorFlow queues and queue-runners, and hence does not support reinitialization).</p> <p>I'm not completely clear what your code is doing, but I think you ...
tensorflow
2
7,843
46,121,067
Datetime upsampling
<p>I have a dataframe like such:</p> <pre><code>rows = [['bob', '01/2017', 12], ['bob', '02/2017', 14], ['bob', '03/2017', 16], ['julia', '01/2017', 18], ['julia', '02/2017', 16], ['julia', '03/2017', 24]] df = pd.DataFrame(rows, columns = ['name','date','val']) </code></pre> ...
<p>So someone answered this partially but then deleted it before I could copy it, but I think i figured out what they were going for:</p> <p>So from this dataframe (created in the question)</p> <pre><code> name date val 0 bob 01/2017 12 1 bob 02/2017 14 2 bob 03/2017 16 3 julia 01/2017 18 4 julia...
python|pandas|datetime|resampling
0
7,844
22,946,139
Python class to convert all tables in a database to pandas dataframes
<p>I'm trying to achieve the following. I want to create a python Class that transforms all tables in a database to pandas dataframes. </p> <p>This is how I do it, which is not very generic... </p> <pre><code>class sql2df(): def __init__(self, db, password='123',host='127.0.0.1',user='root'): self.db = db...
<p>I would use SQLAlchemy for this:</p> <pre><code>engine = sqlalchemy.create_engine("mysql+mysqldb://root:123@127.0.0.1/%s" % db) </code></pre> <p>Note the <a href="http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html#database-urls" rel="nofollow">syntax</a> is dialect+driver://username:password@host:port/databas...
python|mysql|pandas
5
7,845
35,518,308
All possible permutations columns Pandas Dataframe within the same column
<p>I had a similar question using Postgres SQL, but I figured that this kind of task is really hard to do in Postgres, and I think python/pandas would make this a lot easier, although I still can't quite come up with the solution.</p> <p>I now have a Pandas Dataframe which looks like this:</p> <pre><code>df={'planid'...
<p>I was trying to chain as many steps together as possible. Break them down to see what each step does :)</p> <pre><code>df2 = pd.DataFrame(index=pd.MultiIndex.from_product([subdf['x'] for p, subdf in df.groupby('planid')], names=df.planid.unique())).reset_index().stack().reset_index() df2.columns = ['permutation_co...
python|pandas|permutation
3
7,846
20,572,749
mapreduce to find multiple max values
<p>Trying to understand how to do this with map_reduce. Currently, I do a find to pull a whole collection into one big pandas dataframe. That df contains something like this:</p> <pre><code>project ep seq shot layers totalframes showA sh18 17120 10 cnt_chr_set 128 showA ...
<p>MapReduce is unnecessary here, most likely, just use aggregation framework:</p> <pre><code>{ "$group" : { "_id" : { "l": "$layers", "s": "$shots" }, "maxframes" : {"$max" : "$totalframes"} } } </code></pre> <p>Not sure if you care about the other fiel...
mongodb|pandas|pymongo
1
7,847
66,378,763
from ._nnls import nnls ImportError: DLL load failed: The specified module could not be found
<p>While running a UNet traning code I found DLL load failed error. Here is the code:</p> <pre><code>''' import torch import scipy import albumentations as A from ._nnls import nnls from albumentations.pytorch import ToTensorV2 from tqdm import tqdm import torch.nn as nn import torch.optim as opti...
<p>The below solution worked for me.</p> <blockquote> <p>conda remove --force numpy, scipy</p> </blockquote> <blockquote> <p>pip install -U numpy, scipy</p> </blockquote> <p>Successfully installed numpy-1.19.5 scipy-1.5.4</p> <p>Reference: <a href="https://github.com/conda/conda/issues/6396#issuecomment-350254762" rel=...
python|pytorch
1
7,848
66,570,293
How to color a dataframe to a conditional heatmap with same color across whole row based on a single column
<p>So I have a dataframe which looks like:</p> <pre><code>Target, Achieved, Goal, Remaining 10, 5, 50, 5 4, 5, 125, 0 3, 3, 100, 0 8, 2, 25, 6 </code></pre> <p>I want to display this dataframe with visible info based on colors, Under this criteria:</p> <ol> <li>If goal is achieved I just wanted row to be green regardle...
<p>Perhaps you are looking for something like this (using @QuangHoang methods):</p> <pre><code>import pandas as pd import numpy as np import matplotlib as mpl df = pd.read_clipboard(sep=',\s+') cmap = mpl.cm.get_cmap('RdYlGn') norm = mpl.colors.Normalize(df['Goal'].min(), 100.) def colorRow(s): return [f'backgro...
python|pandas|dataframe|heatmap
1
7,849
57,562,496
TypeError: 'module' object is not callable. keras
<p><strong>System information</strong><br> - Windows 10<br> - TensorFlow backend (yes / no): yes<br> - TensorFlow version: 1.14.0<br> - Keras version: 2.24<br> - Python version: 3.6<br> - CUDA/cuDNN version: 10<br> - GPU model and memory: gtx 1050 ti </p> <p><strong>Describe the current behavior</strong><br> I ...
<p>This should be fine:</p> <pre><code>import tensorflow as tf import keras import numpy as np model = keras.models.Sequential([keras.layers.Dense(units=1, input_shape=[1])]) model.compile(optimizer="sgd", loss="mean_squared_error") x = np.array([-1, 0, 1, 2, 3, 4]) y = np.array([-3, -1, 1, 3, 5, 7]) model.fit(x, ...
python|tensorflow|keras|anaconda|conda
3
7,850
57,485,856
When using np.linalg.eigvals, I am getting the first eigenvalue with negative value systematically. Why is this?
<p>I am working in a implementation of the Expectation-Maximization algorithm with Missing Data for Mixture of MVNs. You don't have to know anything about this algorithm to help me with my issue.</p> <p>Let say that my dataset has shape <code>D x N</code> with <code>D = 6</code>.</p> <p>I compute the estimation of si...
<p>I think the way covariance matrix is computed is wrong. If X is (N, m) matrix with N as sample size and m as feature size, then</p> <pre class="lang-py prettyprint-override"><code>conv = (X - X_mean).T.dot((X - X_mean)) / (X.shape[0] - 1) </code></pre> <p><code>(X.shape[0] - 1)</code> is becuase this is samples</p...
python|numpy|math|statistics|algebra
0
7,851
57,631,364
Concatenate multiple pandas groupby outputs
<p>I would like to make multiple <code>.groupby()</code> operations on different subsets of a given dataset and bind them all together. For example:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({"ID":[1,1,2,2,2,3],"Subset":[1,1,2,2,2,3],"Value":[5,7,4,1,7,8]}) print(df) ...
<p>The return type in your example is a pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.html#pandas.MultiIndex" rel="nofollow noreferrer">MultiIndex</a> object. To return a dataframe with a single transformation function for a single value, then you can use the following. No...
python|pandas|concatenation|pandas-groupby
1
7,852
23,950,658
Python Pandas operate on row
<p>Hi my dataframe look like:</p> <pre><code>Store,Dept,Date,Sales 1,1,2010-02-05,245 1,1,2010-02-12,449 1,1,2010-02-19,455 1,1,2010-02-26,154 1,1,2010-03-05,29 1,1,2010-03-12,239 1,1,2010-03-19,264 </code></pre> <p>Simply, I need to add another column called '_id' as concatenation of Store, Dept, Date like "1_1_2010...
<p>You can first convert it to strings (the integer columns) before concatenating with <code>+</code>:</p> <pre><code>In [25]: df['id'] = df['Store'].astype(str) +'_' +df['Dept'].astype(str) +'_'+df['Date'] In [26]: df Out[26]: Store Dept Date Sales id 0 1 1 2010-02-05 245 1_1_...
python|pandas|dataframe
3
7,853
43,510,589
How to find Specific values in Pandas Dataframe
<p>I have imported the data in csv format in pandas. Can anybody tell me how i can find the values above 280 in one of the columns that i have and put them into another data frame. I have done the below code so far:</p> <pre><code>import numpy as np import pandas as pd df = pd.read_csv('...csv') </code></pre> <p>And ...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="noreferrer"><code>boolean indexing</code></a>:</p> <pre><code>df1 = df[df[2] &gt; 280] </code></pre> <p>If need select also only column add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFr...
python|pandas|dataframe
5
7,854
43,547,032
Python Pandas groupby multiple counts
<p>I have a dataframe that looks like:</p> <pre><code> id email domain created_at company 0 1 son@mail.com old.com 2017-01-21 18:19:00 company_a 1 2 boy@mail.com new.com 2017-01-22 01:19:00 company_b 2 3 girl@mail.com nadda.com 2017-01-22 01:19:00 no_company </code></pre> <...
<p>Map a new series for <code>has_company</code>/<code>no_company</code> then <code>groupby</code>:</p> <pre><code>c = df.company.map(lambda x: x if x == 'no_company' else 'has_company') y = df.created_at.dt.year.rename('year') m = df.created_at.dt.month.rename('month') df.groupby([y, m, c]).size() year month comp...
python|pandas
4
7,855
43,846,481
Compute mean if two conditions are met
<p><strong>Set-up</strong></p> <p>I am scraping housing ads using Scrapy and subsequently analyse the data with pandas.</p> <p>I use the pandas to compute the means and medians of several housing characteristics. </p> <p>The dataframe <code>df</code> looks like,</p> <pre><code>district | rent | rooms | … ----------...
<p><code>df.groupby(['district', 'rooms'])['rent'].mean().unstack()</code> should work. <code>unstack()</code> turns the MultiIndex returned by the previous expression to a table with <code>district</code> as rows and <code>rooms</code> as the columns.</p>
python|pandas|conditional|mean
1
7,856
72,936,816
Unable to split the column into multiple columns based on the first column value
<p>I've a data frame which contains one column. Below is the example</p> <pre><code>Questionsbysortorder Q1-4,Q2-3,Q3-2,Q4-3,Q5-3 Q1-1,Q2-2,Q3-1,Q4-1 Q1-5,Q2-3,Q3-3 </code></pre> <p>I'm trying to explode the columns with the help of already given row values. Like below is the...
<p>You are very close. You want to</p> <ul> <li>split by <code>','</code>,</li> <li>explode the list,</li> <li>split again by <code>'-'</code> to get the different fields</li> <li>finally pivot the data</li> </ul> <p>In code:</p> <pre><code>df.join(df.Questionsbysortorder.str.split(',') .explode() .str.split('-',...
python|python-3.x|pandas|dataframe|pandas-groupby
2
7,857
73,024,958
Panda python textfile processing into xlsx
<p>I have a .txt file that looks like something like this:</p> <pre><code>&lt;Location /git&gt; AuthType Basic AuthName &quot;Please enter your CVC username and password.&quot; AuthBasicProvider LOCAL_authfile LDAP_CVCLAB LDAP_CVC007 AuthGroupFile /data/conf/git_group #Require valid-user Require...
<p>If the suggestion in my comment is fine, then this is your solution.</p> <p>If it is not, please point out how you would prefer it and I will try to help you do that.</p> <p>Either way, this can get you on the right path for a vectorized solution.</p> <pre><code>def extract(gits): # get repo names in a colum ...
python|pandas|dataframe|numpy|pycharm
2
7,858
73,130,599
Tensorflow Fused conv implementation does not support grouped convolutions
<p>I did a neural network machine learning on colored images (3 channels). It worked but now I want to try to do it in grayscale to see if I can improve accuracy. Here is the code:</p> <pre><code>train_datagen = ImageDataGenerator( rescale=1. / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)...
<p>Your <code>train_generator</code> does not seem to have the <code>colormode='grayscale'</code>. Try:</p> <pre><code>train_generator = train_datagen.flow_from_directory( train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='binary', colormode='grayscale', shuf...
python|tensorflow|keras|deep-learning
2
7,859
73,004,748
TypeError: unsupported operand type(s) for *: 'builtin_function_or_method' and 'int' when multiplying using asterisk (*)
<p>In the <code>HuBMAPDataset</code> class, I set <code>sz</code> using <code>self.sz = reduce*sz</code>. My code raised unsupported operand type error.</p> <pre><code>reduce = 4 class HuBMAPDataset: def __init__(self, idx, fold, train=True, tfms=None): self.data = rasterio.open(os.path.join(DATA,idx+'.tiff...
<p>'reduce' is a function from functools. You multiply a function with an int. That's why you got the error. You can reproduce this error by the following simple code:</p> <pre><code>from functools import reduce c = reduce * 3 </code></pre>
python|algorithm|numpy|machine-learning
0
7,860
70,555,307
find words out of vocabulary
<p>I have some texts in a pandas dataframe <code>df['mytext']</code> I have also got a vocabulary <code>vocab</code> (list of words).</p> <p>I am trying to list and count the words out of vocabulary for each document</p> <p>I have tried the following but it is quite slow for 10k documents.</p> <p>How to quickly and eff...
<p>You can use</p> <pre><code>from collections import Counter vocab=['word1','word2','word3','2021'] df['mytext_list']=df['mytext'].str.split(' ') df['count']=df['mytext_list'].apply(lambda c:sum([Counter(c)[w] for w in vocab])) </code></pre> <p>It should be faster than your solution because it uses pandas vectorizatio...
python|pandas|nlp|vocabulary
1
7,861
70,497,233
How to transform 2D array using values as another array's indices?
<p>I have a 2D array with indices refering to another array:</p> <pre><code>indexarray = np.array([[0,0,1,1], [1,2,3,0]]) </code></pre> <p>The array which these indices refer to is:</p> <pre><code>valuearray = np.array([8,7,6,5]) </code></pre> <p>I would like to get an array with the numbers from...
<p>One way is to flatten the index array and get the values and reshape it back as follows.</p> <pre><code>targetarray = valuearray[indexarray.flatten()].reshape(indexarray.shape) </code></pre>
python|numpy
1
7,862
70,395,851
Showing gps points on altair world map
<p>I'm building (for learning purposes) a python program that extracts gps-data from *jpg files in a directory and display the gps-coordinates from the photo's on a world-map.</p> <p>I managed to extract the latitude and longitude values in a panda's dataframe and display it on a altair-world map.</p> <p>But my problem...
<p>Solved in the comments, adding as an answer to mark this as solved:</p> <blockquote> <p>Try changing x='latitude', y='longitude' to latitude='latitude', longitude='longitude'. This may require you to delete .interactive(), because Altair produces Vega-Lite, which apparently does not support geographic chart interact...
python|pandas|altair
0
7,863
70,626,934
How to compute pandas dataframe of pairwise string-similarities in parallel using dask?
<p>I have a list of strings, and I want to build a dataframe which gives the Jaro-Winkler normalized similarity between each pair of strings. There is a function in the package <a href="https://github.com/life4/textdistance" rel="nofollow noreferrer">textdistance</a> to compute it. Loosely, similar strings have a score...
<p>There's lots of ways, but here's another one, using dask.dataframes...</p> <pre class="lang-py prettyprint-override"><code>In [1]: import dask, dask.distributed, dask.dataframe as dd, pandas as pd, itertools In [2]: client = dask.distributed.Client() In [3]: futures = client.scatter(strings) In [4]: def similarit...
python|pandas|dask
0
7,864
42,945,649
Removing subarray from array
<p>I have a numpy array A and B. </p> <pre><code>A = [ 1, 2, 5, 9.8, 55, 3] B = [ 3, 4] </code></pre> <p>Now, how to remove A[3] &amp; A[4] that is whatever indices array B is having and then put them at the start of array A. So, I want my output to be </p> <pre><code>A = [9.8, 55, 1, 2, 5, 3] </code></pre> <...
<p>One approach with <code>boolean-indexing</code> would be -</p> <pre><code>mask = np.in1d(np.arange(A.size),B) out = np.r_[A[mask], A[~mask]] </code></pre> <p>Sample run -</p> <pre><code>In [26]: A = np.array([ 1, 2, 5, 9.8, 55, 3]) In [27]: B = np.array([ 3, 4]) In [28]: mask = np.in1d(np.arange(A.size),B) In ...
python|numpy
1
7,865
42,739,557
Code runs much faster in C than in NumPy
<p>I wrote physics simulation code in python using numpy and than rewrote it to C++. in C++ it takes only 0.5 seconds while in python around 40s. Can someone please help my find what I did horribly wrong?</p> <pre><code>import numpy as np def myFunc(i): uH = np.copy(u) for j in range(1, xmax-1): u[i][...
<p>fundamentally, C is a compiled language, when Python is a interpreted one, speed against ease of use.</p> <p>Numpy can fill the gap, but you must avoid for loop on items, which need often some skills.</p> <p>For exemple,</p> <pre><code>def block1(): for i in range(xmax): for j in range(1, xmax-1): ...
python|numpy
2
7,866
27,098,762
How to create a data frame from a deeply nested dictionary?
<p>I have a nested dictionary that has 5 levels <code>masterdict = {a : {b: {c: {d : { e: }}}}}</code> and I am trying to create a flat data frame. </p> <p>When I run the following code: </p> <pre><code>masterDF = pd.DataFrame() for a in masterdict: for b in masterdict[a]: for c in masterdict[a][b]: ...
<p>I write this to flatten nested dictionaries. Might help you also. pk becomes a string of previous key, and current key with a ' to join them. a becomes a list of items.</p> <pre><code>a=[] heading=[] def flat_dict(dic,pk=None): for k,v in dic.items(): if isinstance(v, dict): try: ...
python|dictionary|pandas
0
7,867
14,591,855
pandas HDFStore - how to reopen?
<p>I created a file by using:</p> <pre><code>store = pd.HDFStore('/home/.../data.h5') </code></pre> <p>and stored some tables using:</p> <pre><code>store['firstSet'] = df1 store.close() </code></pre> <p>I closed down python and reopened in a fresh environment.</p> <p>How do I reopen this file?</p> <p>When I go:</...
<p>In my hands, following approach works best:</p> <pre><code>df = pd.DataFrame(...) "write" with pd.HDFStore('test.h5', mode='w') as store: store.append('df', df, data_columns= df.columns, format='table') "read" with pd.HDFStore('test.h5', mode='r') as newstore: df_restored = newstore.select('df') </code>...
python|pandas
10
7,868
30,413,714
python pandas time series select day of year
<p>I want to select data from a dataframe for a particular day of the year. Here is what I have so far as a minimal example.</p> <pre><code>import pandas as pd from datetime import datetime from datetime import timedelta import numpy.random as npr rng = pd.date_range('1/1/1990', periods=365*10, freq='D') df1 = pd.D...
<p>You could use <code>.ix</code> to filter <code>dr</code> dates from <code>df1</code></p> <pre><code>In [107]: df1.ix[dr] Out[107]: 0 1991-01-31 -1.239096 1992-01-31 0.153730 1993-01-31 -0.685778 1994-01-31 0.132170 1995-01-31 0.154965 1996-01-31 1.800437 1997-01-31 2.725209 1998-01-31 -0.084...
python|date|pandas|dataframe
3
7,869
26,783,719
Efficiently get indices of histogram bins in Python
<h1>Short Question</h1> <p>I have a large 10000x10000 elements image, which I bin into a few hundred different sectors/bins. I then need to perform some iterative calculation on the values contained within each bin.</p> <p>How do I extract the indices of each bin to efficiently perform my calculation using the bins v...
<p>I found that a particular sparse matrix constructor can achieve the desired result very efficiently. It's a bit obscure but we can abuse it for this purpose. The function below can be used in nearly the same way as <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.binned_statistic.html" rel="...
python|numpy|scipy
11
7,870
26,472,215
Pandas to calculate rolling aggregate rate
<p>I'm trying to calculate a rolling aggregate rate for a time series.</p> <p>The way to think about the data is that it is the results of a bunch of multigame series against a different teams. We don't know who wins the series until the last game. I'm trying to calculate the win rate as it evolves against each of the...
<p>I still don't feel like I understand the rule for how you decide when a series is over. Is 3 over? Why is it NA, I would have thought 1/3rd. Still, here is a way to keep track of the number of completed series and (a) win rate.</p> <p>Define 26472215table.csv:</p> <pre><code>series_id,date,opposing_team,won_series...
python|pandas
1
7,871
39,122,955
Pyspark error for java heap space error
<p>I am new to spark using <strong>Spark 1.6.1</strong> with <strong>two workers</strong> each having <strong>Memory 1GB</strong> and <strong>5 Cores</strong> assigned, running this code on a 33MB file. </p> <p>This Code is used to Index word in spark.</p> <pre><code>from textblob import TextBlob as tb from textblob_...
<p>That's because of the .collect(). You lose everything when you transform your rdd into a classic python variable (or np.array), all data is collected on the same place.</p>
python|numpy|optimization|pyspark
0
7,872
33,709,598
TensorFlow cholesky decomposition
<p>From reading the TensorFlow documentation I see that there is a method for computing the <a href="http://tensorflow.org/api_docs/python/math_ops.md#cholesky" rel="noreferrer">Cholesky decomposition of a square matrix</a>. However, usually when I want to use Cholesky decomposition, I do it for the purposes of solving...
<p>user19..8: The way to do this for now if you want to keep things "mostly" in tensorflow would be to do what you and Berci were discussing in the comments: Run the tensorflow graph until the point where you need to solve the linear system, and then feed the results back in with a feed_dict. In pseudocode:</p> <pr...
scipy|tensorflow
3
7,873
33,872,129
Python - Retrieving last 30 days data from dataframe pandas
<p>I've a dataframe containing six month error logs, collected every day. I want to retrieve the last 30 days records from the last date. Last date isn't today.<br> For example: I've data for the months May, June, July and until <code>August 15</code>, I want to retrieve that data from <code>August 15</code> to <code>J...
<p>Date <code>lastdayfrom</code> is used for selecting last 30 days of <code>DataFrame</code> by function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="noreferrer">loc</a>. </p> <pre><code>lastdayfrom = pd.to_datetime('8/24/2015') print lastdayfrom #2015-08-24 00:00:00 ...
python|pandas|dataframe
11
7,874
33,697,810
Fastest way to group by ID for a really big numpy array
<p>I am trying to find the best way to group 'rows' with similar IDs.</p> <p>My best guess: <code>np.array([test[test[:,0] == ID] for ID in List_IDs])</code></p> <p>result: array of arrays of arrays</p> <pre><code>[ array([['ID_1', 'col1','col2',...,'coln'], ['ID_1', 'col1','col2',...,'coln'],..., ...
<p>I am assuming <code>List_IDs</code> is a list of all unique IDs from the first column. With that assumption, here's a Numpy-based solution -</p> <pre><code># Sort input array test w.r.t. first column that are IDs test_sorted = test[test[:,0].argsort()] # Convert the string IDs to numeric IDs _,numeric_ID = np.uniq...
python|arrays|numpy
2
7,875
22,763,279
Optimize loop for changepoint test
<p>I'm trying to write a simple change point finder in Python. Below, the function loglike(xs) returns the maximized log-likelihood for an iid normal sample xs. The function most_probable_cp(xs) loops through each point in the middle ~75% of xs, and uses a likelihood ratio to find the most likely change point in xs. ...
<p>The first thing, use Numpy's implementation of standard deviation. That will not only be faster, but also more stable.</p> <pre><code>def loglike(xs): n = len(xs) return -0.5 * n * np.log(2 * np.pi * np.std(xs)) - 0.5 * n </code></pre> <p>If you really want to squeeze miliseconds, you could use bottleneck'...
python|numpy|statistics
2
7,876
22,775,371
How to iterate through a numpy array and select neighboring cells
<p>I am converting a USGS elevation raster data set to a Numpy array and then trying to select a position in the array at random. From this position I would like to create a method that identifies the eight surrounding cells to see if the elevations of these cells are within one meter of randomly selected cell. </p> <...
<p>This can be done with an algorithm similar to <a href="http://en.wikipedia.org/wiki/Flood_fill" rel="nofollow">flood fill</a>, using a stack:</p> <pre><code>import numpy as np z = '''33 33 33 37 38 37 43 40 33 33 33 38 38 38 44 40 36 36 36 36 38 39 44 41 35 36 35 35 34 30 40 41 36 36 35 35 34 30 30 41 38 38 35 35 ...
python|arrays|numpy|gis
4
7,877
13,288,889
Installing numpy using port (Python default version issue)
<p>I'm using Mountain Lion now and I've installed python27 and numpy using macports. The problem is that I cannot import numpy from the python. As far as I know, the default python of Mountain Lion is python 2.7.</p> <p>I've tried "import numpy" with both of two python (default - 2.7.2 and port - 2.7.3). It worked wit...
<p>Looks like you missed a step. Did you do port select like this?</p> <pre><code>sudo port select --set python python27 </code></pre> <p>If py27-numpy is installed, then you must be able to import it from the MacPorts version of python 2.7. To make sure which version of python you're running, do a <code>which python...
python|numpy|port|macports
0
7,878
13,293,731
ValueError: object too deep for desired array
<pre><code>""" ___ """ from scipy.optimize import root import numpy as np LENGTH = 3 def process(x): return x[0, 0] + x[0, 1] * 5 def draw(process, length): """ """ X = np.matrix(np.random.normal(0, 10, (length, 2))) y = np.matrix([process(x) for x in X]) y += np.random.normal(3, 1, len(y)) ...
<p>The problem is that fsolve and root do not accept matrixes as return value of the objective function.</p> <p>For example this is a solution of above problem:</p> <pre><code>def maximum_likelyhood(y, X): def objective(b): b = np.matrix(b).T return np.transpose(np.array((X.T * (y - X * b))))[0] ...
python|numpy|scipy
11
7,879
29,751,462
Pandas Yahoo Datareader RemoteDataError when start date or end date is current date
<p>I am running the below program to extract the stock information:</p> <pre><code>import datetime import pandas as pd from pandas import DataFrame from pandas.io.data import DataReader symbols_list = ['AAPL', 'TSLA', 'YHOO','GOOG', 'MSFT','ALTR','WDC','KLAC'] symbols=[] for ticker in symbols_list: r = DataReade...
<p>Putting together the suggestions by @JohnE, the code below seems to do the job:</p> <pre><code>import pandas as pd symbols_list = ['AAPL', 'TSLA', 'YHOO','GOOG', 'MSFT','ALTR','WDC','KLAC'] result = [] for ticker in symbols_list: url = 'http://chartapi.finance.yahoo.com/instrument/1.0/%s/chartdata;type=quote;...
python|pandas|stocks|pandas-datareader
0
7,880
29,438,585
Element-wise average and standard deviation across multiple dataframes
<p>Data: Multiple dataframes of the same format (same columns, an equal number of rows, and no points missing).</p> <p>How do I create a &quot;summary&quot; dataframe that contains an element-wise mean for every element? How about a dataframe that contains an element-wise standard deviation?</p> <pre><code> A ...
<p>You can create a panel of your DataFrames and then compute the mean and SD along the items axis:</p> <pre><code>df1 = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C']) df2 = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C']) df3 = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C']) ...
python|python-3.x|pandas
6
7,881
62,389,358
Extract value from column containing dicts in a few rows
<p>I have a nested json file that I convert to a Pandas Dataframe:</p> <pre><code>tabell = pd.DataFrame.from_records(r.response['trades']) </code></pre> <p>It looks like this:</p> <pre><code>id instrument price initialUnits takeProfitOrder 0 AUD_CAD 0.90 10000 NaN 1 AUD_CAD ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.get.html" rel="nofollow noreferrer"><code>Series.str.get</code></a> for possible processing missing values:</p> <pre><code>tabell['takeProfitOrder'] = tabell['takeProfitOrder'].str.get('id') </code></pre>
python|pandas|dataframe
1
7,882
62,161,367
How to group by key and retrieve keys from the grouped elements?
<p>I'm trying to <code>group</code> and <code>sum</code> dicts from a <code>DataFrame</code> like this:</p> <pre><code>dt = [ {'discount_value': 10, 'is_cumulative': True, 'code': 'x'}, {'discount_value': 10, 'is_cumulative': True, 'code': 'x1'}, {'discount_value': 10, 'is_cumulative': False, 'code': 'x2'}...
<p>Here is what you want:</p> <pre class="lang-py prettyprint-override"><code>import pandas dt = [ {'discount_value': 10, 'is_cumulative': True, 'code': 'x'}, {'discount_value': 10, 'is_cumulative': True, 'code': 'x1'}, {'discount_value': 10, 'is_cumulative': False, 'code': 'x2'} ] df = pandas.DataFrame(...
python|pandas
2
7,883
62,458,837
Groupby transform to list in pandas does not work
<p>Best described with an example</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'a' : ['A','B','C','A','B','C','A','B','C'], 'b': [1,2,3,4,5,6,7,8,9]} ) </code></pre> <p>And i want to create a column that contains in a <code>list</code> the elements of column <code>b</code> by group of column <code>a...
<p>I come up one fix with below. PS : it should something wrong with <code>transform</code> , when the object type is <code>list</code> <code>tuple</code> or <code>set</code>..</p> <pre><code>df.groupby('a')['b'].transform(lambda x : [x.tolist()]*len(x)) Out[226]: 0 [1, 4, 7] 1 [1, 4, 7] 2 [1, 4, 7] 3 [2,...
pandas|pandas-groupby
7
7,884
62,256,536
Most performant data structure in Python to handle live streaming market data
<p>I am about to handle live streaming stock market data, hundreds of "ticks" (<code>dict</code>s) per second, store them in an in-memory data structure and analyze the data.</p> <p>I was reading up on <code>pandas</code> and got pretty excited about it, only to learn that pandas' <code>append</code> function is not r...
<p>The workflow you describe makes me think of a <code>deque</code>, basically a list that allows extending on one end (e.g. right), while popping (fetching/removing) them off the other end (e.g. left). The reference even has a short list of <a href="https://docs.python.org/3/library/collections.html?highlight=deque#de...
python|pandas|performance|data-science|real-time
2
7,885
62,101,315
Validation accuracy increases then suddenly decreases
<p>I am training an LSTM model on the <a href="http://alt.qcri.org/semeval2017/task4/index.php?id=data-and-tools" rel="nofollow noreferrer">SemEval 2017 task 4A dataset</a>. I observe that first validation accuracy increases along with training accuracy but then suddenly decreases by a significant amount. The loss decr...
<p>You have a few choices:</p> <ol> <li>keep training and see what happens</li> <li>if the val_loss become worse, you're overfitting -- check out how to deal with that -- increase the amount of the data, make a simpler network or do whatever seems to work in your particular case.</li> <li>if the val_loss gets better b...
python|tensorflow|keras|deep-learning|glove
2
7,886
62,404,451
pytorch versus autograd.numpy
<p>What are the big differences between pytorch and numpy, in particular, the autograd.numpy package? ( since both of them can compute the gradient automatically for you.) I know that pytorch can move tensors to GPU, but is this the only reason for choosing pytorch over numpy? While pytorch is well known for deep lear...
<p>I'm not sure if this question can be objectively answered, but besides the GPU functionality, it offers</p> <ul> <li>Parallelisation across GPUs</li> <li>Parallelisation across Machines</li> <li>DataLoaders / Manipulators incl. asynchronous pre-fetching</li> <li>Optimizers</li> <li>Predefined/Pretrained Models (can...
numpy|pytorch|autograd
0
7,887
62,093,584
keras load_model cannot recognize new AUC metric tf.keras.metrics.AUC()
<p>I am using new tensorflow version and it has auc metric defined as tf.keras.metrics.AUC(). The model compiles and runs fine but when I load the model it cannot recognize auc metric function. I have added required import function. The codes are given below:</p> <pre><code> import keras import tensorflow as tf...
<pre><code>from keras.metrics import AUC ... model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=[AUC(name='auc')]) </code></pre>
tensorflow|keras|model|metrics|auc
1
7,888
51,369,727
Convert pandas DataFrame into string to be written to a cfg file
<p><strong><em>Target</em></strong></p> <p>I have a Pandas data frame, as shown below, and would like to join the columns, <code>command</code> and <code>value</code> while also converting it back into it's raw string format to be written to a .cfg file.</p> <hr> <p><strong><em>Data Frame</em></strong> - <code>df</c...
<p>After you call</p> <pre><code>df = df['command'].astype(str)+' '+df['value'].astype(str) </code></pre> <p>you're actually left with a <code>Series</code> object, so you can call <code>df.tolist()</code> and then join the elements of the list with a newline. Something like this</p> <pre><code>s = df['command'].ast...
python|python-2.7|pandas|dataframe
2
7,889
51,313,530
getting wrong result while merging pandas dataframe
<p>I have two dataframes like-</p> <pre><code> identity time Date matched_time 0 197_$ 21:21:21 9/11/2015 21:21:30 0 197_$ 21:21:51 9/11/2015 21:22:00 0 197_$ 21:22:21 9/11/2015 21:22:30 0 197_$ 21:22:51 9/11/2015 21:23:00 0 197_$ 21:23:21 9/11/2015 21:23:30 0 ...
<p>In general you should not use <code>merge()</code> unless you have unique keys in at least one side (left or right). Instead, use <code>concat()</code> if you have identical columns in both dataframes. I omitted a column <code>Time</code> of your 2nd dataframe for simplicity.</p> <p><code>df1</code>:</p> <pre><cod...
python|pandas
1
7,890
51,308,340
Cannot override matplotlib format_coord
<p>I'm creating a contour plot with a list of V values as the x-axis and a list of T values as the y-axis (the V and T values are float numbers with 2 digits after the decimal point but all sorted of course). I created a data matrix and populated it with the data correlating with the V-T coordinates. </p> <p>If it hel...
<p>Hi guys so I found out how to solve this in case anyone needs it. There were 2 problems: 1/ I was wrong in my way of generating a list of V,T coordinates 2/ distance.cdist requires everything in the form of a 2d array. So this is the final solution:</p> <pre><code>def fmt(x, y): '''Overrides the original matplo...
python-2.7|numpy|matplotlib|scipy
0
7,891
51,312,815
Taking a specific character in the string for a list of strings in python
<p>I have a list of 22000 strings like abc.wav . I want to take out a specific character from it in python like a character which is before .wav from all the files. How to do that in python ?</p>
<p>finding the spot of a character could be .split(), but if you want to pull up a specific spot in a string, you could use list[stringNum[letterNum]]. And then list[stringNum].split("a") would get two or more separate strings that are on the other side of the letter "a". Using those strings you could get the spots by...
python|pandas|numpy
0
7,892
70,817,269
Longest continuous streaks of multiple users
<p>I want to find the solution for this,</p> <blockquote> <p>Provided a table with user_id and the dates they visited the platform, find the top 100 users with the longest continuous streak of visiting the platform as of yesterday.</p> </blockquote> <p>I found these <a href="https://stackoverflow.com/questions/48897265...
<p>I have gone long hand, there maybe a shorter way out there. Lets try</p> <pre><code>df=df.sort_values(by=['uid','date_val'])# Sort df #Check sequence df=(df.assign(diff=df['date_val'].diff().dt.days, diff1=df['date_val'].diff(-1).dt.days)) #create a grouper s=(((df['diff'].isna())&amp;(df['diff1']==...
python|pandas|dataframe|series
1
7,893
41,693,371
odeint floating point arithmetic
<p>I am interessted in understanding the floating point arithmetics using the <code>scipy.integrate.odeint</code> function.</p> <p>The case I am working with is the following</p> <pre><code># data omega = 136 # rad/s d = 75 # Nm/s k = 390000 # N/m m = 4 # kg n = 1000 # t_0 = 1 # s t_1 = 5.5 # s Y = 0.05 # m # time ...
<p>What you are seeing is the result of a different order for the floating point operations (addition and multiplication). See a classic paper <a href="http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html" rel="nofollow noreferrer">http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html</a> or wikipedi...
python|numpy|floating-point|scipy|odeint
2
7,894
64,580,235
How to use tf.data.Dataset.from_generator() to load only one batch at a time from the dataset?
<p>I want to train a CNN and I am trying to feed the model with one batch at a time, directly from a <code>numpy</code> memmap, not having to load the whole dateset to the memory, using <code>tf.data.Dataset.from_generator()</code>. I am using <code>tf2.2</code> and the GPU for fitting. The dataset is a sequence of 3D ...
<p>An alternative was to subclass <a href="https://www.tensorflow.org/api_docs/python/tf/keras/utils/Sequence" rel="nofollow noreferrer">keras.utils.Sequence</a>. The idea is to generate the whole batch.</p> <p>Quoting the docs:</p> <blockquote> <p>Sequence are a safer way to do multiprocessing. This structure guarante...
python|tensorflow|keras|deep-learning
-2
7,895
48,934,658
mysterious Python Pandas lambda function error
<p>I have a pandas dataframe and I have a column called 'email'. I have verified the dtype is object. It contains normally formatted emails such as xxx@yyy.com</p> <p>When I do this:</p> <pre><code>$ df['emaillower'] = df['email'].apply(lambda x: x.lower()) </code></pre> <p>I get this:</p> <pre><code>Traceback (m...
<p>One of the entries in the column 'email' is a float, not a string, and it doesn't know how to do upper() on a float. This is common when one entry is empty and is converted to NaN - this is read as a float and that's the source of your error. Something like this may fix the problem:</p> <pre><code>df['emaillower'] ...
python|pandas|lambda
3
7,896
58,827,917
AttributeError: module 'keras.backend' has no attribute '_BACKEND'
<p>I am following a book on building chat bots and continue running into this error when attempting to start interactive learning.</p> <p>The full error is this: </p> <blockquote> <p>Traceback (most recent call last): File "train_initialize.py", line 18, in agent = Agent("horoscope_domain.yml", policies ...
<p>Looks like outdated API code; open the files in the error trace, and replace <code>._BACKEND</code> w/ <code>.backend()</code>:</p> <pre class="lang-py prettyprint-override"><code># In "C:\Users\Max\AppData\Local\Programs\Python\Python37\lib\site-packages # \rasa_core\policies\keras_policy.py", line 48: # return k...
python|tensorflow|keras|rasa-nlu|rasa
0
7,897
70,338,783
Double "melt" in a pandas dataframe from Excel file
<p>I am reading an excel file in pandas with two levels for the columns. I am using Python 3.7</p> <p><a href="https://i.stack.imgur.com/aqAUd.png" rel="nofollow noreferrer">Example Excel file</a></p> <pre><code> Unnamed: 0 Unnamed: 1 Unnamed: 2 2021-01-01 2021-01-02 2021-01-03 2021-01-04 2021-01-05 0 Proj...
<p>First of all, we need to read the excel file properly</p> <pre><code>df = pd.read_excel('~/test.xlsx', header=[0, 1], index_col=[0, 1, 2]) </code></pre> <p>Stack using the <code>MultiIndex</code> level that you need keeping the <code>NaN</code>s and then reset the index</p> <pre><code>df = df.stack(level=[1, 0], dro...
python-3.x|excel|pandas|melt
2
7,898
70,359,235
Calculate Weights of a Column in Pandas
<p>this is a basic quesiton and easy to do in excel but have not an idea in python and every example online uses groupby with multiple names in the name column. So, all I need is a row value of weights from a single column. Suppose I have data that looks like this:</p> <pre><code> name value 0 A 4...
<p>You can also groupby 'name' and then apply a function that divides each value by its group sum:</p> <pre><code>df['weights'] = df.groupby('name')['value'].apply(lambda x: x / x.sum()) </code></pre> <p>Output:</p> <pre><code> name value weights 0 A 45 0.069124 1 A 76 0.116743 2 A 320 0.4915...
pandas|calculated-columns|weighted
2
7,899
56,148,015
How can I change the order of the data record with regular expression and put it together in one single dataframe?
<p>What I want to know is how I can use the above data frame with regular expression to put the data rows in the right order. As you can see by for example index 2 and 4, the Quantity and Piece are in the wrong order. Does anyone have any idee how I can fix this?</p> <pre class="lang-py prettyprint-override"><code>d...
<p>This is one approach using <code>str.extract</code></p> <p><strong>Ex:</strong></p> <pre><code>import pandas as pd data = [['Total 8\r\r\nQuantity 2\r\r\nPiece 4'], ['Total 8\r\r\nQuantity 2\r\r\nPiece 4'],['Total 8\r\r\nPiece 2\r\r\nQuantity 4'], ['Total 8\r\r\nQuantity 2\r\r\nPiece 4'], ['Total 8\r\r\nPiece 2\r...
python|regex|pandas|dataframe
2