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
377,200
53,696,327
could not convert string to float: 'K5'
<p>I'm trying to call on a file that has strings in it so I can count how many of that one type of string there is but when I get an error that a string cannot be converted to a float. The file is very large but a small section would look like {K5, M2 K5, M0, M0, M2}. I want to then count how many of each matching entr...
<p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html" rel="nofollow noreferrer"><code>np.loadtxt</code></a> by default expects numeric data. You can specify <code>dtype='S2'</code> for strings of length 2:</p> <pre><code>from io import StringIO import numpy as np file = StringIO(""" 0 K...
python|arrays|numpy
1
377,201
53,391,122
Pandas dataframe wide vs long - unstack vs pivot vs outer join for MULTIPLE df
<h1>Problem</h1> <p>I have some enormous dataframes pulled from equipment, which track multiple runs on said equipment, each recording multiple sensors (voltage, current, rpm, pressures... etc.) I need to widen this data set for plotting and further analysis, but unfortunately the clocks on the sensors are not synchr...
<h3><a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.pivot_table.html#pandas.pivot_table" rel="nofollow noreferrer"><code>pd.pivot_table</code></a></h3> <p>You can pivot your dataframe. The only difference versus your desired output is you only have a single <code>time</code> series; you ...
python|pandas|dataframe|pivot-table|pandas-groupby
2
377,202
53,502,036
Counting amount of people in building over time
<p>I'm struggling in finding a "simple" way to perform this analysis with Pandas:</p> <p>I have xlsx files that show the transits of people into a building. Here after I show a simplified version of my raw data.</p> <pre><code> Full Name Time Direction 0 Uncle Scrooge 08-10-2018 09:16:52 ...
<p>You can start by setting the <code>Time</code> column as index, and sorting it using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow noreferrer"><code>sort_index</code></a>:</p> <pre><code>df = df.set_index('Time').sort_index() print(df) ...
python|pandas|datetime
0
377,203
53,691,389
Count changing bits in numpy array
<p>I'm doing my first steps with Python3, so I'm not sure how to solve the following task. I'd like to count how often each bit in a numpy array changes over the time, my array looks like this:</p> <p>first column: timestamp; second column: ID; third to last column: byte8,...,byte2, byte1, byte0 (8 bit per byte)</p> ...
<p>The first step is definitely removing the "timestamp" and the "ID" columns, and make sure it is not of type <code>string</code>. I don't think you <strong>can</strong> have a <code>numpy</code> array that looks like your example (except for compound <code>dtype</code>, which makes things complicated). For "ID", you ...
python|numpy|char|byte|bit
0
377,204
53,749,155
Convert a dataframe in pandas based on column names
<p>I have a pandas dataframe that looks something like this:</p> <pre><code>employeeId cumbId firstName lastName emailAddress \ 0 E123456 102939485 Andrew Hoover hoovera@xyz.com 1 E123457 675849302 Curt Austin austinc1@xyz.com 2 E123458 354852739 Celeste Riddick riddick...
<p>I think this is what you are looking for... you can use concat after splitting out the parts of your dataframe:</p> <pre><code># create a new df without the id columns df2 = df.loc[:, ~df.columns.isin(['employeeId','employeeIdTypeCode'])] # rename columns to match the df columns names that they "match" to df2 = df...
python|pandas|dataframe
1
377,205
53,489,451
AttributeError: 'module' object has no attribute 'DataFrame'
<p>I am running Python 2.7.10 on a Macbook. </p> <p>I have installed: Homebrew Python 2.x, 3.x NI-VISA pip pyvisa, pyserial, numpy PyVISA Anaconda Pandas I am attempting to run this script. A portion of it can be read here:</p> <pre><code>import visa import time import panda import sys import os import numpy os.syst...
<p>It's <code>pandas</code>, not <code>panda</code>, so use <code>import pandas</code> instead. It's also common practice to import pandas as <code>pd</code> for convenience:</p> <pre><code>import pandas as pd df = pd.DataFrame() </code></pre>
python|macos|pandas|visa|pyvisa
2
377,206
53,745,080
Can I get pytesseract command to work properly in pycharm which is throwing errors
<p>I am defining a fucntion which is converting an image to grayscale (bit black white) after that I am passing it to:</p> <pre><code>text = pytesseract.image_to_string(Image.open(gray_scale_image)) </code></pre> <p>and then I am print the text what I am receiving but it is throwing errors:</p> <pre><code>Traceback ...
<p>Since I guess <strong>gray_scale_image</strong> is output from OpenCV and is therefore numpy array as error suggests</p> <p><code>AttributeError: 'numpy.ndarray' object has no attribute 'read'</code></p> <p>you need to transform array to PIL object. From my own experience, I suggest you to automaticly transform nu...
python|python-3.x|numpy|tesseract
5
377,207
53,568,749
Is it necessary to use "numpy.float64"?
<p>i recently saw an example about "Linear regression"<br> where he uses while creating an array with numpy in order with dtype = numpy.float64</p> <pre><code>x = numpy.array([1,2,3,4] , dtype = numpy.float64) </code></pre> <p>i tried without flaot64 where it returns different value rather than error<br> why?</p>
<p>What data type to use depends on the use case.</p> <pre><code> x = numpy.array([1,2,3,4] , dtype = numpy.float64) </code></pre> <p>Here the elements of an array are of type float64 (Double precision float).</p> <pre><code> x = numpy.array([1,2,3,4]) </code></pre> <p>Here the elements are of type int64 (Int...
python|numpy|algebraic-data-types
1
377,208
53,745,478
ECONNREFUSED error when loading a TensorFlow frozen model from node.js
<p>I was trying to load a TensorFlow fronzen model from a url that points to not existing resource to test my code robustness. However, even though I have set a <code>catch</code>, I am not able to manage a <code>ECONNREFUSED</code> that is raised internally by the function <code>tf.loadFrozenModel</code>.</p> <p>Is t...
<p>If you don't find any other solution you can catch the error on the top level like this:</p> <pre><code>process.on('uncaughtException', function (err) { console.error(err); }); </code></pre> <p>In there you can get more specific to only catch your specific error.</p>
node.js|tensorflow|tensorflow.js
0
377,209
53,578,787
Why does Numpy's RGB array representation of an image have 4 layers not 3?
<p>Shouldn't there be 3 layers one for the intensity of red, one for the intensite of green and one for the intensity of blue? Then why does the shape of my RGB array say: (73, 115, 4)? </p>
<p>There's also a default transparency column.<br> This is called the <code>alpha</code> value, and defaults to <code>1</code>. You can change it of course in one of multiple ways. For instance: </p> <pre><code>plt.imshow(my_im, alpha=0.3) </code></pre> <p>This can be useful for overlaying images one on top of the o...
python|numpy|opencv|colors|vision
1
377,210
53,367,310
Calculating distance between column values in pandas dataframe
<p>I have attached a sample of my dataset. I have minimal Panda experience, hence, I'm struggling to formulate the problem.</p> <p><a href="https://i.stack.imgur.com/zIoXK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zIoXK.png" alt="enter image description here"></a></p> <p>What I'm trying to do...
<p>Here's how I would do it using <code>Shapely</code>, the engine underlying <code>Geopandas</code>, and I'm going to use randomized data.</p> <pre><code>from shapely.geometry import LineString import pandas as pd import random def gen_random(): return [random.randint(1, 100) for x in range(20)] j = {"x1": gen_r...
python|pandas|dataframe|distance
1
377,211
53,572,865
Image understanding - CNN Triplet loss
<p>i'm new to NN and trying to create a simple NN for image understanding.</p> <p>I tried using the triplet loss method, but keep getting errors that made me think i'm missing some fundamental concept. </p> <p>My code is :</p> <pre><code>def triplet_loss(x): anchor, positive, negative = tf.split(x, 3) pos_dist ...
<p>For anyone also struggling </p> <p>My problem was actually the dimension of each observation. By changing the dimension as suggested in the comments</p> <pre><code>(?, 1024, 1024, 3) </code></pre> <p>The colab notebook updated with the solution</p> <p>P.s - i also changed the size of the pictures to 256 * 256 s...
python|tensorflow|keras|neural-network|deep-learning
0
377,212
53,386,933
How to solve / fit a geometric brownian motion process in Python?
<p>For example, the below code simulates Geometric Brownian Motion (GBM) process, which satisfies <a href="https://en.wikipedia.org/wiki/Geometric_Brownian_motion#Technical_definition:_the_SDE" rel="nofollow noreferrer">the following stochastic differential equation</a>:</p> <p><a href="https://i.stack.imgur.com/gyHIX...
<p>Parameter estimation for SDEs is a research level area, and thus rather non-trivial. Whole books exist on the topic. Feel free to look into those for more details.</p> <p>But here's a trivial approach for this case. Firstly, note that the log of GBM is an affinely transformed Wiener process (i.e. a linear Ito drift...
python|numpy|scipy|stochastic|stochastic-process
9
377,213
53,740,008
Delete last N elements if they are 0 and constant
<p>I have an array such as</p> <pre><code>data = [ [1, 0], [2, 0], [3, 1], [4, 1], [5, 1], [6, 0], [7, 0]] </code></pre> <p>and I want the result to be </p> <pre><code>verified_data = [[1, 0], [2, 0], [3, 1]] </code></pre> <p>So how can I remove the last elements if they are 0, and also if last N el...
<p>I've split removing trailing zeros and removing trailing duplicates into two functions. Using the list[-n] indices to avoid explicit index tracking.</p> <pre><code>In [20]: def remove_trailing_duplicates(dat): ...: key=dat[-1][1] ...: while (len(dat)&gt;1) and (dat[-2][1]==key): ...: da...
python|arrays|algorithm|numpy
2
377,214
53,566,848
Keras Estimator + tf.data API
<p>TF 1.12:</p> <p>Trying to convert Pre-canned estimator to Keras with tf.keras.layers:</p> <pre><code>estimator = tf.estimator.DNNClassifier( model_dir='/tmp/keras', feature_columns=deep_columns, hidden_units = [100, 75, 50, 25], config=run_config) </code></pre> <p>to a Keras model ...
<p>You need to add an input layer:</p> <pre><code>model = tf.keras.models.Sequential() model.add(tf.keras.layers.InputLayer(input_shape=your_tensor_shape, name=your_feature_key)) model.add(tf.keras.layers.Dense(100, activation=tf.nn.relu)) </code></pre>
python|tensorflow|keras
-1
377,215
53,726,052
python pandas sum columns into sum column
<p>I want to create a column in a pandas dataframe that would add the values of the other columns (which are 0 or 1s). the column is called "sum"</p> <p>my HEADPandas looks like:</p> <pre><code> Application AnsSr sum Col1 Col2 Col3 .... Col(n-2) Col(n-1) Col(n) date 28-12-11 0.0 0.0 28/12/11 .... ...
<p>Any data you choose to sum, just add to a list, and use that list to provide to your sum function, with axis=1. This will provide you the desired outcome. Here is a sample related to your data. </p> <p>Sample File Data: </p> <pre><code>Date,a,b,c bad, bad, bad, bad # Used to simulate your data better 2018-11-19,1,...
python|pandas|dataframe|sum
1
377,216
17,429,643
Efficient method for creating a last day of month variable
<p>I have a dataframe with a column of date strings (e.g., "2003-11"). Creating a series of dates with the first day of the month is straightforward:</p> <pre><code>data['firstday'] = pd.to_datetime(data['date']) </code></pre> <p>I have not figured out how to create a series of dates with the last day of the month ef...
<p>You could use <code>apply</code>, e.g.:</p> <pre><code>data['lastday'] = pd.to_datetime(data['date']).apply(lambda x: x + MonthEnd()) </code></pre>
datetime|pandas
0
377,217
17,395,298
How can I quickly convert to a list of lists, insert a string at the start of each element?
<p>I have read a file into the Python script using:</p> <pre><code>data=np.loadtxt('myfile') </code></pre> <p>Which gives a list of numbers of type 'numpy.ndarray', in the form:</p> <pre><code>print(data) = [1, 2, 3] </code></pre> <p>I need to convert this into a list of lists, each with a single-character string '...
<p>Maybe something like this:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; data = [1,2,3] &gt;&gt;&gt; a = np.empty([len(data),2], dtype=object) &gt;&gt;&gt; a array([[None, None], [None, None], [None, None]], dtype=object) &gt;&gt;&gt; a[:,0]='a' &gt;&gt;&gt; a array([[a, None], [a...
python|numpy|list-comprehension
0
377,218
17,293,661
Use ipdb in Eclipse
<p>Debugging Python code in Eclipse is often two heavyweight, so I often prefer pdb.set_trace() for a quick check of my code. However ipdb offers a couple of nice features like tab-completion and syntax-highlighting. Is it possible to use ipdb in Eclipse as well?</p> <pre><code>import numpy as np import ipdb test = n...
<p>Try this. <a href="http://mihai-nita.net/2013/06/03/eclipse-plugin-ansi-in-console/" rel="nofollow">http://mihai-nita.net/2013/06/03/eclipse-plugin-ansi-in-console/</a> worked for me in aptana (which is pretty much eclipse). Gives a neat button in the console for enable/disable too.</p> <p>Not sure about tab comple...
python|eclipse|numpy|ipdb
-1
377,219
17,256,952
How to subtract 1 from each value in a column in Pandas
<p>I think this should be a simple problem, but I can't find a solution. </p> <p>Within a subset of rows in a dataframe, I need to decrement the value of each item in a column by 1. I have tried various approaches, but the values continue to be unchanged. Following another entry on SO, I tried </p> <pre><code>def m...
<p>If this returns the data you want to modify:</p> <pre><code>pledges[pledges.Source == 'M0607'].DayOFDrive </code></pre> <p>Then try modifying it this way:</p> <pre><code>pledges[pledges.Source == 'M0607'].DayOFDrive -= 1 </code></pre>
python|pandas
3
377,220
17,458,370
Transformations with DataFrame exporting series
<p>I have data in the following form stored in a DataFrame. I would like to get daily sums for each of the metrics grouped by their type, so for example total sum for linkedin_profiles on October 3rd 2012.</p> <pre><code>sample_date metric_name sample 2012-10-03 21:30:18.742307+00:00 link...
<p>Suppose you have this DataFrame:</p> <pre><code>import io import pandas as pd text = '''\ sample_date metric_name sample 2012-10-03 21:30:18.742307+00:00 linkedin_profile 257 2012-10-03 21:30:25.132189+00:00 twitter_profile 972 2012-10-03 21:30:26.063389+00:00 youtube_vid...
python|pandas|series|dataframe
4
377,221
17,430,090
Contour plotting orbitals in pyquante2 using matplotlib
<p>I'm currently writing line and contour plotting functions for my <a href="https://github.com/rpmuller/pyquante2" rel="nofollow noreferrer">PyQuante</a> quantum chemistry package using matplotlib. I have some great functions that evaluate basis sets along a (npts,3) array of points, e.g.</p> <pre><code>from somewher...
<p>If you can express <code>f</code> as a function of <code>X</code> and <code>Y</code>, you could avoid the Python <code>for-loop</code>s this way:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np def bf(x, y): return np.sin(np.sqrt(x**2+y**2)) xvals = np.linspace(0,10) yvals = np.linspace(0,2...
numpy|matplotlib
1
377,222
17,139,918
Finding median with pandas transform
<p>I needed to find the median for a pandas dataframe and used a piece of code from this previous SO answer: <a href="https://stackoverflow.com/questions/13063259/how-i-do-find-median-using-pandas-on-a-dataset">How I do find median using pandas on a dataset?</a>.</p> <p>I used the following code from that answer:</p> ...
<p>I'd recommend diving into the source code to see exactly why this works (and I'm mobile so I'll be terse).</p> <p>When you pass the argument <code>'median'</code> to <code>tranform</code> pandas converts this behind the scenes via <code>getattr</code> to the appropriate method then behaves like you passed it a func...
python|pandas
2
377,223
17,136,626
What is the correct (stable, efficient) way to use matrix inversion in numpy?
<p>In Matlab, using the inv() function is often discouraged due to numerical instability (see description section in <a href="http://www.mathworks.com/help/matlab/ref/inv.html" rel="nofollow">http://www.mathworks.com/help/matlab/ref/inv.html</a>). It is suggested to replace an expression like:</p> <pre><code>inv(A)*B ...
<p>As mentioned in the comments, you need to use the left inverse.</p> <p>This is described in <a href="https://stackoverflow.com/questions/2250403/left-inverse-in-numpy-or-scipy">this question</a>.</p> <p>To summarize (imitatio, aemulatio):</p> <ul> <li>Use <a href="http://docs.scipy.org/doc/numpy/reference/generat...
matlab|numpy|scipy|linear-algebra|matrix-inverse
1
377,224
17,408,896
Diagonalising a Pandas series
<p>I'm doing some matrix algebra using the very lovely <code>pandas</code> library in Python. I'm really enjoying using the Series and Dataframe objects because of the ability to name rows and columns.</p> <p>But is there a neat way to diagonalise a Series while maintaining row/column names?</p> <p>Consider this mini...
<p>How about this..</p> <pre><code>In [107]: pd.DataFrame(np.diag(s),index=s.index,columns=s.index) Out[107]: a b c d e a 0.630529 0.000000 0.000000 0.000000 0.000000 b 0.000000 0.360884 0.000000 0.000000 0.000000 c 0.000000 0.000000 0.345719 0.000000 0.000000 ...
python|pandas|matrix-multiplication
6
377,225
19,938,809
Instantiate two 2D numpy arrays from a list of strings
<p>I have a list of lines in the form:</p> <pre><code>"a, b, c, d, e ... z," </code></pre> <p>Where the first x need to be saved as a row in one 2D array and the rest of the line saved as a row in another 2D array.</p> <p>Now if this was in C/C++ or Java it would be easy and I could do it in a few seconds. But I hav...
<p>I agree with this last bit:</p> <blockquote> <p>I suppose it may be easier in python/numpy to create one numpy array with all the values then split it into two separate arrays. If this is easier help with doing that would be appreciated. (How nice am I suggesting possible solutions! :P )</p> </blockquote> <p>You...
python|arrays|string|numpy
3
377,226
19,902,562
getting a default value from pandas dataframe when a key is not present
<p>I have a dataframe multi-index where each key is a tuple of two. Currently, the order of the values in the key matters: <code>df[(k1,k2)]</code> is not the same as <code>df[('k2,k1')]</code>. also, sometimes <code>k1,k2</code> exists in the dataframe while <code>k2,k1</code> does not. </p> <p>I'm trying to average ...
<p><code>ix</code> index access and <code>mean</code> function handle this for you. Fetch the two tuples from <code>df.ix</code> and apply the mean function to it: non existing keys are returned as nan values, and mean ignores nan values by default:</p> <pre><code>In [102]: df Out[102]: (26, 22) (10, 48) (48, 42...
pandas
1
377,227
20,303,323
Distance calculation between rows in Pandas Dataframe using a distance matrix
<p>I have the following Pandas DataFrame:</p> <pre><code>In [31]: import pandas as pd sample = pd.DataFrame({'Sym1': ['a','a','a','d'],'Sym2':['a','c','b','b'],'Sym3':['a','c','b','d'],'Sym4':['b','b','b','a']},index=['Item1','Item2','Item3','Item4']) In [32]: print(sample) Out [32]: Sym1 Sym2 Sym3 Sym4 Item1 ...
<p>This is an old question, but there is a Scipy function that does this:</p> <pre><code>from scipy.spatial.distance import pdist, squareform distances = pdist(sample.values, metric='euclidean') dist_matrix = squareform(distances) </code></pre> <p><code>pdist</code> operates on Numpy matrices, and <code>DataFrame.va...
python|matrix|pandas|time-series|euclidean-distance
31
377,228
19,930,998
Single row DataFrame causing "Exception: Reindexing only valid with uniquely valued Index objects"
<p>I have a function returning a dictionary with two DataFrames. One of them has multiple rows with no issues. The second will typically come back with a single row. When trying to remove columns from it or even re-creating a second DataFrame and limiting the columns such as this...</p> <pre><code> analysis['race'] = ...
<p>Turns-out, the reason for the error, as far as I can tell, was a few duplicate columns in the DataFrame. When I removed those, the error subsided.</p>
python|pandas
2
377,229
20,255,485
How to query an HDF store using Pandas/Python
<p>To manage the amount of RAM I consume in doing an analysis, I have a large dataset stored in hdf5 (.h5) and I need to query this dataset efficiently using Pandas.</p> <p>The data set contains user performance data for a suite of apps. I only want to pull a few fields out of the 40 possible, and then filter the resu...
<p>You are pretty close.</p> <pre><code>In [1]: df = DataFrame({'A' : ['foo','foo','bar','bar','baz'], 'B' : [1,2,1,2,1], 'C' : np.random.randn(5) }) In [2]: df Out[2]: A B C 0 foo 1 -0.909708 1 foo 2 1.321838 2 bar 1 0.368994 3 bar 2 -0.058657...
python|pandas|hdfs
14
377,230
19,914,861
2-D contourplot on specific geometry in python
<p>I want to plot a contourplot of a specific geometry (a polygon). I have the corordinates for the corners and a number of points inside this polygon with 1-D parameters that I want to interpolate to a contourplot. I'm able to plot the distribution of the paramater but the image comes out as a square (as I do not know...
<p>It is cheating, but nevertheless: you can add something like that</p> <pre><code>zzi = rbff(xxi, yyi) zzi[zzi&lt;0.1]=nan </code></pre> <p>and play with the value (0.1 at the moment). </p>
python|numpy|matplotlib
1
377,231
6,791,159
numpy.poly1d , root-finding optimization, shifting polynom on x-axis
<p>it is commonly an easy task to build an n-th order polynomial and find the roots with numpy:</p> <pre><code>import numpy f = numpy.poly1d([1,2,3]) print numpy.roots(f) array([-1.+1.41421356j, -1.-1.41421356j]) </code></pre> <p>However, suppose you want a polynomial of type:</p> <pre><code>f(x) = a*(x-x0)**0 + b(x...
<p>First of all, surely you mean polynomial, not polygon?</p> <p>In terms of providing an answer, are you using the same value of "x0" in all the terms? If so, let y = x - x0, solve for y and get x using x = y + x0.</p> <p>You could even wrap it in a lambda function if you want. Say, you want to represent</p> <pre><...
python|optimization|numpy|scipy|polygons
4
377,232
6,931,985
Python, Scipy: Building triplets using large adjacency matrix
<p>I am using an adjacency matrix to represent a network of friends which can be visually interpreted as </p> <pre><code>Mary 0 1 1 1 Joe 1 0 1 1 Bob 1 1 0 1 Susan 1 1 1 0 Mary Joe Bob Susan </code></pre> <p>U...
<p>I think you can find triangles only in rows or columns. for example:</p> <pre><code>Susan 1 1 1 0 Mary Joe Bob Susan </code></pre> <p>this means Mary, Joe, Bob are all friends of Susan, so, use combinations to choose two person from [Mary, Joe, Bob], and combine it with Susan...
python|numpy|data-mining|scipy|adjacency-matrix
6
377,233
6,363,154
What is the difference between numpy.fft and scipy.fftpack?
<p>Is the later just a synonym of the former, or are they two different implementations of FFT? Which one is better?</p>
<p>SciPy does more:</p> <ul> <li><a href="http://docs.scipy.org/doc/numpy/reference/routines.fft.html">http://docs.scipy.org/doc/numpy/reference/routines.fft.html</a></li> <li><a href="http://docs.scipy.org/doc/scipy/reference/fftpack.html#">http://docs.scipy.org/doc/scipy/reference/fftpack.html#</a></li> </ul> <p>In...
python|numpy|scipy|fft
42
377,234
6,795,657
Numpy: arr[...,0,:] works. But how do I store the data contained in the slice command (..., 0, :)?
<p>In Numpy (and Python in general, I suppose), how does one store a slice-index, such as (...,0,:), in order to pass it around and apply it to various arrays? It would be nice to, say, be able to pass a slice-index to and from functions. </p>
<p>Python creates special objects out of the slice syntax, but only inside the square brackets for indexing. You can either create those objects by hand (in this case, <code>(...,0,:)</code> is <code>(Ellipsis, 0, slice(None, None, None))</code>, or you can create a little helper object:</p> <pre><code>class ExtendedS...
python|indexing|numpy|slice
9
377,235
6,561,211
Pythonic way to test if a row is in an array
<p>This seems like a simple question, but I haven't been able to find a good answer.</p> <p>I'm looking for a pythonic way to test whether a 2d numpy array contains a given row. For example:</p> <pre><code>myarray = numpy.array([[0,1], [2,3], [4,5]]) myrow1 = numpy.array...
<p>The SO question below should help you out, but basically you can use:</p> <pre><code>any((myrow1 == x).all() for x in myarray) </code></pre> <p><a href="https://stackoverflow.com/questions/5488307/numpy-array-in-python-list">Numpy.Array in Python list?</a></p>
arrays|testing|numpy|python
5
377,236
15,967,468
Can I export pandas DataFrame to Excel stripping tzinfo?
<p>I have a timezone aware TimeSeries in pandas 0.10.1. I want to export to Excel, but the timezone prevents the date from being recognized as a date in Excel.</p> <pre><code>In [40]: resultado Out[40]: fecha_hora 2013-04-11 13:00:00+02:00 31475.568 2013-04-11 14:00:00+02:00 37263.072 2013-04-11 15:00:00+02:00 ...
<p>You can simply create a copy without timezone.</p> <pre><code>import pandas as pa time = pa.Timestamp('2013-04-16 10:08', tz='Europe/Berlin') time_wo_tz = pa.datetime(year=time.year, month=time.month, day=time.day, hour=time.hour, minute=time.minute, second=time.second, ...
python|excel|pandas|time-series|tzinfo
2
377,237
15,850,198
adding a new column with values from the existing ones
<p>what's the most pandas-appropriate way of achieving this? I want to create a column with datetime objects from the 'year','month' and 'day' columns, but all I came up with is some code that looks way too cumbersome:</p> <pre><code>myList=[] for row in df_orders.iterrows(): #df_orders is the dataframe myList.ap...
<p>Try this:</p> <pre><code>In [1]: df = pd.DataFrame(dict(yyyy=[2000, 2000, 2000, 2000], mm=[1, 2, 3, 4], day=[1, 1, 1, 1])) </code></pre> <p>Convert to an integer:</p> <pre><code>In [2]: df['date'] = df['yyyy'] * 10000 + df['mm'] * 100 + df['day'] </code></pre> <p>Convert to a stri...
pandas
2
377,238
15,525,493
Efficient matching of two arrays (how to use KDTree)
<p>I have two 2d arrays, <code>obs1</code> and <code>obs2</code>. They represent two independent measurement series, and both have <em>dim0 = 2</em>, and slightly different <em>dim1</em>, say <code>obs1.shape = (2, 250000)</code>, and <code>obs2.shape = (2, 250050)</code>. <code>obs1[0]</code> and <code>obs2[0]</code> ...
<p>Using <code>cKDTree</code> for this case would look like:</p> <pre><code>from scipy.spatial import cKDTree obs2 = array with shape (2, m) obs1 = array with shape (2, n) kdt = cKDTree(obs2.T) dist, indices = kdt.query(obs1.T) </code></pre> <p>where <code>indices</code> will contain the column indices in <code>obs...
python|numpy|pandas|scipy|kdtree
1
377,239
15,985,510
iterating randomly through groups in python data frame
<p>I have a data frame named 'lattice' with an attribute 'level'</p> <pre><code>g_lattice=lattice.groupby('level') </code></pre> <p>How do I traverse the groups in g_lattice randomly based on the level.</p>
<pre><code>In [22]: df = pd.DataFrame({'A': ['foo', 'bar'] * 3, 'B': rand.randn(6), 'C': rand.randint(0, 20, 6)}) In [23]: groups = list(df.groupby('A')) In [24]: random.shuffle(groups) In [25]: for g, grp in groups: print grp ....: A B...
python|pandas
3
377,240
15,690,985
How to flatten a numpy slice?
<p>I am implementing a subclass of numpy's ndarray and I need to modify <code>__getitem__</code> to fetch items from a flattened representation of the array. The problem is that <code>__getitem__</code> can either be called with an integer index or a multidimensional slice. </p> <p>Does any one know how to convert a m...
<p>It may not be possible to convert a multidimensional slice to a flat slice, e.g.:</p> <pre><code>&gt;&gt;&gt; a = np.arange(16).reshape(4, 4) &gt;&gt;&gt; a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) &gt;&gt;&gt; a[::3, 1::2] array([[ 1, 3], [13, 15]...
python|numpy
3
377,241
15,516,801
How to make a matrix of arrays in numpy?
<p>I want to make a 2x2 matrix </p> <pre><code>T = [[A, B], [C, D]] </code></pre> <p>where each element <code>A,B,C,D</code> is an array (of same size, of course). Is this possible?</p> <p>I would like to be able to multiply these matrix, for example multiplying two matrix <code>T1</code> and <code>T2</code> sh...
<p>Doesn't your first question just work as you would expect?</p> <pre><code>In [1]: import numpy as np In [2]: arr = np.arange(8).reshape(2, 2, 2) In [3]: arr Out[3]: array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) In [4]: arr*arr Out[4]: array([[[ 0, 1], [ 4, 9]], [[16, 25]...
python|arrays|matrix|numpy
2
377,242
15,952,322
Python package for signal processing
<p>I am looking for a Python package to perform an efficient Constant Q Transform (ie using an FFT to speed up the process). I found a toolbox named CQ-NSGT/sliCQ Toolbox, but I get the following error: </p> <pre><code>File "build\bdist.win32\egg\nsgt\__init__.py", line 37, in &lt;module&gt; File "build\bdist.win32\...
<p>I use the CQT tools in yaafe: <a href="http://perso.telecom-paristech.fr/~essid/tp-yaafe-extension/features.html" rel="nofollow">http://perso.telecom-paristech.fr/~essid/tp-yaafe-extension/features.html</a> </p>
python|numpy|signal-processing|fft|scikits
1
377,243
15,959,411
Fit points to a plane algorithms, how to iterpret results?
<p><strong>Update</strong>: <em>I have modified the Optimize and Eigen and Solve methods to reflect changes. All now return the "same" vector allowing for machine precision. <strong>I am still stumped on the Eigen method. Specifically How/Why I select slice of the eigenvector does not make sense. It was just trial ...
<h2>Optimize</h2> <p>The normal vector of a plane a*x + b*y +c*z = 0, equals (a,b,c)</p> <p>The optimize method finds a values for a and b such that a*x+b*y~z (~ denotes approximates) It omits to use the value of c in the calculation at all. I don't have numpy installed on this machine but I expect that changing the ...
python|numpy|least-squares|svd
6
377,244
15,691,740
Does assignment with advanced indexing copy array data?
<p>I am slowly trying to understand the difference between <code>view</code>s and <code>copy</code>s in numpy, as well as mutable vs. immutable types.</p> <p>If I access part of an array with <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing">'advanced indexing'</a> it is suppos...
<p>When you do <code>c = a[b]</code>, <code>a.__get_item__</code> is called with <code>b</code> as its only argument, and whatever gets returned is assigned to <code>c</code>.</p> <p>When you do<code>a[b] = c</code>, <code>a.__setitem__</code> is called with <code>b</code> and <code>c</code> as arguments and whatever ...
python|numpy|copy
11
377,245
15,930,454
Python 'AttributeError: 'function' object has no attribute 'min''
<p>Firstly, apologies for how obvious these two questions seem to be; I'm very very new to this and don't have a clue what I'm doing.</p> <p>I'm trying to write something to apply the Scipy function for spline interpolation to an array of values. My code currently looks like this:</p> <pre><code>import numpy as np im...
<p>If this line</p> <pre><code>new_x = np.linspace(x.min(), x.max(), new_length) </code></pre> <p>is generating the error message</p> <pre><code>AttributeError: 'function' object has no attribute 'min' </code></pre> <p>then <code>x</code> is a function, and functions (in general) don't have <code>min</code> attribu...
python|numpy|attributes|attributeerror
11
377,246
12,639,628
What is the best vectorization method here?
<p>I am wondering what would be the best way to vectorize the following formula: </p> <pre><code>c= Sum(u(i)*&lt;u(i),y&gt;/v(i) ) </code></pre> <p><code>&lt;.,.&gt;</code> means dot product of two matrix.</p> <p>let say we have a matrix <code>K= U*Diag(w)*U^-1</code> (<code>w</code> and <code>u</code> are eigenvalu...
<p>You can avoid using <code>np.tile</code> with some broadcasting:</p> <pre><code>U = np.dot(u, y) d = U/w a = u*d[:,None] c = a.sum() </code></pre>
python|numpy|vectorization
2
377,247
12,623,835
Replacing loop with List Comprehension instead of loop getting a function to return a new array within the list comprehension
<p>Basically I am trying to avoid looping through big arrays before I had code that looked like this:</p> <pre><code>for rows in book: bs = [] as = [] trdsa = [] trdsb = [] for ish in book: var = (float(str(ish[0]).replace(':',"")) - float(str(book[0]).replace(':',""...
<p>While list comprehensions are indeed interpreted faster than regular loops, they can't work for everything. I don't think you could replace your main <code>for</code> loop by a list comprehension. However, there might be some room for improvement:</p> <ul> <li><p>You could build a list of your <code>time</code> by ...
python|list|loops|numpy|list-comprehension
1
377,248
12,353,359
Why Pandas cause 'ZeroDivisionError' in one case but not in the other?
<p>I have a Pandas dataframe 'dt = myfunc()' , and copy the screen output from IDLE as below:</p> <pre><code>&gt;&gt;&gt; from __future__ import division &gt;&gt;&gt; dt = __get_stk_data__(['*'], frq='CQQ', from_db=False) # my function &gt;&gt;&gt; dt = dt[dt['ebt']==0][['tax','ebt']] &gt;&gt;&gt; type(dt) &lt;class '...
<p>@bigbug, how are you getting the data out of the SQLite backend? If you look in <code>pandas.io.sql</code>, the <code>read_frame</code> method has a <code>coerce_float</code> parameter that should convert numerical data to float if possible.</p> <p>Your second example works because the DataFrame constructor tries t...
python|pandas
3
377,249
12,178,808
Pandas datetime index from seconds series
<p>I have a pandas dataframe consisting of 23 series with a default sequential index (0,1,2,...) obtained by importing an ndarray.</p> <p>Two of the series in the dataframe contain record time information. One series ('SECONDS') contains the number of seconds since the start of the year 1900. The other series ('NAN...
<p>Suppose <code>sec</code> is an array of integers that represents the number of seconds since 1990:</p> <pre><code>In [26]: import pandas as pd In [27]: pd.Index(datetime(1990, 1, 1) + sec * pd.offsets.Second()) Out[27]: &lt;class 'pandas.tseries.index.DatetimeIndex'&gt; [1990-01-01 00:14:40, ..., 1990-04-26 17:26:...
python|numpy|pandas
4
377,250
12,588,986
TypeError generated when using inplace operations on numpy arrays?
<p>If I run the following code:</p> <pre><code>import numpy as np b = np.zeros(1) c = np.zeros(1) c = c/2**63 print b, c b += c </code></pre> <p>I get this error message:</p> <pre><code>TypeError: ufunc 'add' output (typecode 'O') could not be coerced to provided output parameter (typecode 'd') according to the ca...
<p>When you do <code>c=c/2**63</code>, <code>c</code> gets casted to <code>dtype=object</code> (that's the problem), while <code>b</code> stays with <code>dtype=float</code>. </p> <p>When you add a <code>dtype=object</code> array to a <code>dtype=float</code>, the result is a <code>dtype=object</code> array. Think of ...
python|arrays|numpy|typeerror
21
377,251
72,126,459
Pandas expanding a dataframe length but populate each row incrementally based on column
<p>I'm working with a dataframe that looks like this:</p> <pre><code> frame requests 0 0 214388438.0 1 1 194980303.0 2 2 179475934.0 3 3 165196540.0 4 4 154815540.0 5 5 123650671.0 6 6 119089045.0 </code></pre> <p>The thing is I want to add each of the value found on the requests column...
<p>Assuming <code>df</code> as input, you can use numpy to reshape and create a new DataFrame:</p> <pre><code>import numpy as np a = df['requests'].to_numpy() df2 = (pd .DataFrame(np.tril(np.tile(a, (len(a), 1))), index=df['frame']) .stack() .droplevel(1) .reset_index(name='requests') ) </code></pre> <p><em>NB. Y...
python|pandas
1
377,252
72,004,449
How to plot the position of occurrence in python data frame
<p>For example I have a data frame like the following:</p> <pre><code> A B C 0 1 1 1 1 1 1 0 2 1 1 0 3 1 0 1 4 1 0 1 5 1 0 0 6 0 1 0 7 0 1 1 8 0 1 0 9 0 1 1 </code></pre> <p>How can I plot a graph like the following that indicates the index position of column <code>A</code>, <code>B</c...
<p>Assuming your data in <code>df</code>, you can call <code>plt.imshow</code> on the transposed dataframe:</p> <pre><code>import matplotlib.pyplot as plt plt.imshow(df.T, cmap='Blues') </code></pre> <p><a href="https://i.stack.imgur.com/zvmnm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zvmnm.png...
python|pandas|plot
1
377,253
71,887,359
How do i select a whole row based on the highest value of a column
<p>Im trying to print the whole row with the highest number of casualties in this data. Currently i can only print the highest number of casualties and not the whole row using the below code, does anyone know how to change it to what i need;</p> <pre><code>#this code give me the highest casualty number but i also need ...
<pre><code>print(df.loc[df['Number_of_Casualties'] == df['Number_of_Casualties'].max()]) Accident_Index Number_of_Casualties LSOA_of_Accident_Location 1 1 52 E01003117 </code></pre>
python|pandas
1
377,254
71,810,838
for every row find the last column with value 1 in binary data frame
<p>consider a data frame of binary numbers:</p> <pre><code>import pandas import numpy numpy.random.seed(123) this_df = pandas.DataFrame((numpy.random.random(100) &lt; 1/3).astype(int).reshape(10, 10)) 0 1 2 3 4 5 6 7 8 9 0 0 1 1 0 0 0 0 0 0 0 1 0 0 0 1 0 0 1 1 0 0 2 0 0 0 0 0 1 ...
<p>One option is to reverse the column order, then use <code>idxmax</code>:</p> <pre><code>df['rightmost 1'] = df.loc[:,::-1].idxmax(axis=1) </code></pre> <p>Output:</p> <pre><code> 0 1 2 3 4 5 6 7 8 9 rightmost 1 0 0 1 1 0 0 0 0 0 0 0 2 1 0 0 0 1 0 0 1 1 0 0 7 2 0 0...
python|python-3.x|pandas|dataframe
1
377,255
71,982,845
Print a schedule from an array
<p>I have an array ( 10, 200) with 0 &amp; 1. So we have 10 users and 200-time slots.</p> <pre><code>df = pd.DataFrame({'Startpoint': [ 100 , 50, 40 , 75 , 52 , 43, 90 , 48, 56 ,20 ], 'endpoint': [ 150, 70, 80, 90, 140, 160 ,170 , 120 , 135, 170 ]}) df rng = np.arange(200) out = ((df['Startpoint'].to_numpy()[:, None...
<p>I think this should answer your question.</p> <pre><code># Enumerate through your output and get the user ID and their schedule for userID, user in enumerate(out): for i in range(len(user)): # Enumerate through the length of the schedule by index if user[i] == 1: print(f&quot;User {userID} a...
python|arrays|numpy|printing
1
377,256
71,965,149
How can I divide explicit columns of a Dataframe with a single column and add a new header?
<p>I would like to divide all columns, except the first, with a specific column of a dataframe and add the results as new columns with a new header, but I'm stuck. Here is my approach, but please be gentle, I just started programming a month ago..:</p> <p>I got this example dataframe:</p> <pre><code>np.random.seed(0) d...
<p>Because <code>cols</code> is list remove nested <code>[]</code>:</p> <pre><code>data = pd.DataFrame(np.random.randint(1,10,size=(100, 10)), columns=list('ABCDEFGHIJ')) #you can already drop from columns names, converting to list is not necessary cols = data.columns.drop(['A', 'J']) #alternative solution cols = data...
python|pandas|dataframe
2
377,257
72,102,511
Adding string to pandas properly
<p>Ive been trying to add a list of string values to another dataframe in python using pandas and it adds the whole list to the first value</p> <pre><code> prices Close 0 331.462585\n 332.892242\n 328.274536\n 323.79... NaN 0 ...
<p>It's a little hard to understand from your post what each data frame contains but I can guess you should use join:</p> <pre><code>sma = get_sma() sma = pd.DataFrame(sma) prices = pd.DataFrame(data['Close']) prices = prices.to_string(index = False, header=False) # prices = pd.DataFrame(prices) prices = pd.DataFrame([...
python|pandas|dataframe
0
377,258
71,900,363
Recovering nodes from indices in 2D grid graph using Python
<p>This code generates a 2D grid graph with indices corresponding to nodes: <code>{1: (0, 0),2: (0, 1), 3: (0, 2), 4: (1, 0), 5:(1, 1), 6: (1, 2), 7: (2, 0), 8: (2, 1), 9: (2, 2)}</code>. However, I would like to identify specific nodes corresponding to indices. The desired output is attached.</p> <pre><code>import num...
<p>If you build <code>nodes</code> the other way round (swapping key/value)</p> <pre><code>nodes = {n: i for i, n in enumerate(G.nodes, start=1)} </code></pre> <p>then</p> <pre><code>indices= [(1, 1), (2, 2)] result = [nodes[i] for i in indices] </code></pre> <p>gives you</p> <pre><code>[5, 9] </code></pre> <p>Is that ...
python|numpy|networkx
1
377,259
71,790,774
Python, return unique and exact match of substrings in a pandas dataframe column from a list of desired strings and return as new column
<pre><code>import pandas as pd wordsWeWant = [&quot;ball&quot;, &quot;bat&quot;, &quot;ball-sports&quot;] words = [ &quot;football, ball-sports, ball&quot;, &quot;ball, bat, ball, ball, ball, ballgame, football, ball-sports&quot;, &quot;soccer&quot;, &quot;football, basketball, roundball, ball&quot; ] df = pd.DataFr...
<p>Notice the split is ', '</p> <pre><code>df[&quot;WORDS_list&quot;] = df[&quot;WORDS&quot;].str.split(&quot;, &quot;) df[&quot;WORDS_list&quot;].apply(lambda x: list(set(x).intersection(set(wordsWeWant)))) Out[242]: 0 [ball-sports, ball] 1 [bat, ball-sports, ball] 2 [] 3 ...
python|pandas
2
377,260
71,907,464
"TypeError: unsupported operand type(s) for /: 'str' and 'str'" thrown in pct_change
<p>I have some code that reads stock data with the pandas DataReader. That works perfectly. But I also need to read from CSV files. When I attempt to process it (with the same code I used on the DataReader data), I get &quot;TypeError: unsupported operand type(s) for /: 'str' and 'str'&quot; in <code>pct_change</cod...
<p>Here's a test of <code>read_csv()</code> using your file contents (columns are separated by two spaces, as in the question text):</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd base = pd.read_csv('base_start.txt') print(f&quot;columns\n{base.columns}&quot;) print(base) </code></pre> <p>Resul...
python|pandas
0
377,261
71,958,704
Overlaying probability density functions on one plot
<p>I would like to create a probability density function for the isotopic measurements of N from three NOx sources. The number of measurements varies between sources, so I've created three dataframes. Here is the code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np #import matplot...
<p>One option is to <code>melt</code> the dataframes, <code>concat</code> them, and then use <code>hue</code> with <code>displot</code>:</p> <pre><code>data = pd.concat([df.melt(), df1.melt(), df2.melt()], ignore_index=True) sns.displot(data=data, x='value', hue='variable', kind='kde') </code></pre> <p>Output:</p> <p><...
pandas|probability-density|probability-distribution
1
377,262
71,846,006
How to concatenate a pandas column by a partition?
<p>I have a pandas data frame like this:</p> <p>df = pd.DataFrame({&quot;Id&quot;: [1, 1, 1, 2, 2, 2, 2], &quot;Letter&quot;: ['A', 'B', 'C', 'A', 'D', 'B', 'C']})</p> <p>How can I add a new column efficiently, &quot;Merge&quot; such that it concatenates all the values from the column &quot;letter&quot; by &quot;Id&quo...
<p>You can <code>groupby</code> <code>Id</code> column then <code>transform</code></p> <pre class="lang-py prettyprint-override"><code>df['Merge'] = df.groupby('Id').transform(lambda x: '-'.join(x)) </code></pre> <pre><code>print(df) Id Letter Merge 0 1 A A-B-C 1 1 B A-B-C 2 1 C A-B...
python|python-3.x|pandas
6
377,263
72,114,984
Seaborn - KDE line plot change colormap
<p>I have a seaborn KDE plot but I am struggling to change the colormap. Even if I change the <code>palatte</code> it still remains <code>Set1</code>, even if <code>palatte</code> is changed to <code>Blues</code> or a different palatte color. How might I change the line plots to have the colors in colormap <code>viridi...
<p>IIUC, using <a href="https://seaborn.pydata.org/generated/seaborn.set_palette.html" rel="nofollow noreferrer"><code>set_palette</code></a>:</p> <pre><code>sns.set_palette('viridis') sns.kdeplot(data=pd.DataFrame(array_2d.T, columns=range(1, 6)), multiple='layer') </code></pre> <p>Output:</p> <p><a href="https://i.s...
python|numpy|seaborn|jupyter
1
377,264
72,002,419
how to show .npy files' name in a .npz file, using .keys( )
<p>I used .keys() to see the .npy files in a .npz file:</p> <pre><code>a1 = np.arange(5) a2 = np.arange(6) np.savez('zip1.npz', file1 = a1, file2 = a2) data2 = np.load('zip1.npz') data2.keys() </code></pre> <p>Output:</p> <pre><code>KeysView(&lt;numpy.lib.npyio.NpzFile object at 0x0000016D49CA9F10&gt;) </code></pre> <p...
<pre><code>In [223]: d = np.load('data.npz') In [224]: d Out[224]: &lt;numpy.lib.npyio.NpzFile at 0x7f93fae26040&gt; </code></pre> <p><code>keys()</code> on a <code>dict</code> or dict like object produces 'view' that can be used for iteration, or expanded with <code>list</code>. This behavior is widespread in Py3.</p...
python|numpy
0
377,265
72,085,857
Save GAN generated images
<p>I'm new to learning python. I saw a code on the Internet that saves the generated gan images. But I need these generated images to be saved to a folder in Google Coollaboratory (Colab). How do I do this?</p> <pre><code>def generate_and_save_images(model, epoch, test_input): predictions = model(test_input, training=...
<p>You can use <code>files</code> from <code>google.colab</code> library</p> <pre class="lang-py prettyprint-override"><code> # Import files from google colab from google.colab import files def generate_and_save_images(model, epoch, test_input): predictions = model(test_input, training=False) fig = plt.figure(...
python|tensorflow|matplotlib|generative-adversarial-network
0
377,266
72,020,939
ValueError: `logits` and `labels` must have the same shape, received ((None, 250, 1) vs (None,)). What is wrong?
<p>I'm new to ML and im trying to make a simple MLP work using serialization. I'll be using 2 layer MLP and binary outcome. (yes/no) Could someone explain what i'm doing wrong?</p> <p>Data is of following format. Basically trying to figure if a the address is gibberish or not.</p> <pre><code>(['10@¨260 :?Kings .]~H.wy ...
<p>You need to consider the input dimensions, you see I am using the sequence-to-sequence input with simple vocabulary and I read from your model and code trying to predict that is the word sequence contains of those inputs or similarities</p> <p>For only word contains you can use the input generators for the model but...
tensorflow|machine-learning
0
377,267
72,001,429
Applying For loop with def function to generate other DataFrame?
<p>I have a DataFrame called medal. In medal, there is a column called 'event_gender', which has 4 unique values (men, women, open, and mixed). I tried to write a function to get groupby by these unique values.</p> <p>I want to write for loop for these naming process if possible.</p> <p>Here is what I could do so far a...
<p>Yes you could just do:</p> <pre><code>for item in medal['event_gender'].unique(): globals()[item] = gender(medal, item) </code></pre> <p>But why do this? Maintain your dataframe as it is and work on it with groupings. It is easier that way to do same computations on different groups of the same dataframe rather t...
python|pandas|dataframe|function|loops
0
377,268
71,936,837
Check if a column contains data from another column in python pandas
<p>I have a dataframe in pandas like this</p> <pre><code>name url pau lola www.paulola.com pou gine www.cheeseham.com pete raj www.pataraj.com </code></pre> <p>And I want to check if any of the strings in the column name are in the column url (so ignoring spaces). So something like this</p> <pre><code>name url ...
<p><a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>split</code></a> the name into substrings, and use a list comprehension with <code>any</code> to get True is any string matches:</p> <pre><code>df['result'] = [any(s in url for s in lst) ...
python|python-3.x|pandas|string|contains
1
377,269
71,914,495
How can I eliminate the headers from my graph (using python and pandas to graph a CSV file)?
<p>I am trying to graph data from a CSV file, however, I keep getting headers as if I were graphing to different things. I want to remove this (the orange line on the top left corner). Actually if I could remove the whole thing it would be better.</p> <p>My code is:</p> <pre><code>import pandas as pd import matplotlib....
<p>Try this:</p> <pre><code>headers = ['Espectro del plasma de Ag con energía de 30mJ', &quot;tiempo (microsegundos) vs Voltaje (v)&quot;] df = pd.read_csv('TEK0000.csv', names=headers, usecols=[0,1]) </code></pre> <p>Or:</p> <pre><code>ax = df.set_index('Espectro del plasma de Ag con energía de 30mJ')['tiempo (micros...
python|pandas
0
377,270
72,101,554
How to group by one column if condition is true in another column summing values in third column with pandas
<p>I can't think of how to do this: As the headline explains I want to group a dataframe by the column <code>acquired_month</code> only if another column contains <code>Closed Won</code>(in the example I made a helper column that just marks <code>True</code> if that condition is fulfilled although I'm not sure that ste...
<p>If need aggregate column <code>col</code> replace non matched values to <code>0</code> values in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.where.html" rel="nofollow noreferrer"><code>Series.where</code></a> and then aggregate <code>sum</code>:</p> <pre><code>us_lead_scoring = p...
pandas|pandas-groupby
1
377,271
71,991,903
Animating two circles Python
<p>I have a text file, with the coordinates of two circles on it. I want to produce a live animation of both particles. For some reason the following code crashes</p> <pre><code>import numpy as np from matplotlib import pyplot as plt from matplotlib import animation import pandas as pd df = pd.read_csv('/path/to/text/...
<p>The code crashes because you &quot;mixed&quot; matplotlib's &quot;pyplot&quot; and &quot;object-oriented&quot; approaches in a wrong way. Here is the working code. Note that I created <code>ax</code>, the axes in which artists are going to be added. On this axes I also applied the axis limits.</p> <pre class="lang-p...
python|pandas|matplotlib|animation
1
377,272
72,028,743
New values for intervals of numbers
<p>I have numpy arrays that look like this:</p> <pre><code>[2.20535093 2.44367784] [7.20467093 1.54379728] . . . etc </code></pre> <p>I want to take each array and convert it like this:</p> <pre><code>[1 1] [2 0] </code></pre> <p>0 means that the values are below 2. 1 means that the values are between 1 and 3. 2 means ...
<p>Without using a switch case, you can use:</p> <pre><code>num = np.array([[2.20535093, 2.44367784], [7.20467093, 1.54379728]]) print(num) # [[2.20535093 2.44367784], [7.20467093 1.54379728]] num[num &lt; 2] = 0 num[np.logical_and(num &gt; 1, num &lt; 3)] = 1 num[num &gt; 3] = 2 print(num) # [[1 1], ...
python|numpy
1
377,273
71,860,795
How to groupby and count the distinct values in a column
<p>I'm a bit new to this so please be gentle. I have a dataframe structured like the table below and I'd like to groupby column &quot;P&quot; and make new columns for the distinct/unique values in column &quot;U&quot; and then count the instances of those values.</p> <div class="s-table-container"> <table class="s-tabl...
<p>You can use <code>unstack()</code> after <code>groupby(&quot;P&quot;)</code> and count the values in column <code>U</code> .</p> <pre><code>import pandas as pd import io s = '''P U p1 u1 p1 u1 p1 u3 p2 u1 p2 u2 p2 u3''' df = pd.read_csv(io.StringIO(s), sep = &quot;\s+&quot;) df.groupby(&quot;P&quot;)[&quo...
python|pandas
1
377,274
71,891,127
Is there any way I can use the downloaded pre-trained models for TIMM?
<p>For some reason, I have to use TIMM package offline. But I found that if I use <em><strong>create_model()</strong></em>, for example:</p> <pre><code>self.img_encoder = timm.create_model(&quot;swin_base_patch4_window7_224&quot;, pretrained=True) </code></pre> <p>I would get</p> <pre><code>http.client.RemoteDisconnect...
<p>Yes, you can download all models somewhere local. ( all models can be found in the <a href="https://github.com/rwightman/pytorch-image-models/releases" rel="nofollow noreferrer">project's release section</a>).</p> <p>The on your offline system. put them under:</p> <pre><code>~/.cache/torch/hub/checkpoints </code></p...
pytorch|computer-vision|huggingface
0
377,275
71,894,114
How do I install NumPy under Windows 8.1?
<p>How do I install NumPy under Windows 8.1 ? Similar questions/answers on <code>overflow</code> hasn't helped.</p> <p><a href="https://i.stack.imgur.com/FtLhE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FtLhE.jpg" alt="enter image description here" /></a></p>
<p>Have you tried</p> <pre><code>python -m pip install numpy </code></pre> <p>and as you are using pyCharm you can go to:</p> <ol> <li>ctrl-alt-s</li> <li>click &quot;project:projet name&quot;</li> <li>click project interperter</li> <li>double click pip</li> <li>search numpy from the top bar</li> <li>click on numpy</li...
python|numpy
2
377,276
71,953,954
Seaborn barplot display numeric values from groupby
<p>Data from: <a href="https://www.kaggle.com/datasets/prasertk/homicide-suicide-rate-and-gdp" rel="nofollow noreferrer">https://www.kaggle.com/datasets/prasertk/homicide-suicide-rate-and-gdp</a></p> <p>I have a working barplot.</p> <p>Code:</p> <pre><code>df_mean_country = df.groupby([&quot;country&quot;, &quot;iso3c&...
<p>Each hue value leads to one entry in <code>ax.containers</code>. You can loop through them to add the labels.</p> <p>Some additional remarks:</p> <ul> <li>Matplotlib has both an &quot;old&quot; pyplot interface and a &quot;new&quot; <a href="https://matplotlib.org/matplotblog/posts/pyplot-vs-object-oriented-interfac...
python-3.x|pandas-groupby|seaborn
2
377,277
72,028,701
GAN generator loss is 0 from the start
<p>I need data augmentation for network traffic and I'm following an article in which the structure of the discriminator and generator are both specified. My input data is a collection of pcap files, each having 10 packets with 250 bytes. They are then transformed into a (10, 250) array and all the bytes are cast into ...
<p>There is something wrong with the normalization of the output of the generator. In your code, <code>gen_flows = generator_v.predict(z)</code> is normalized between -1 and 1, but this is not the case for the output of the generator in the gan_v model. Also, the last layer of the generator model is a leakyrelu, which ...
python|tensorflow
1
377,278
72,090,528
Quickest way to merge two very large pandas dataframes using python
<p>I have multiple sets of very large csv files that I need to merge based on a unique ID. This unique ID I set as the index which is based on a concatenation my Origin and Destination columns.</p> <p><strong>Dataframe 1</strong>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>Or...
<p>If I understood the request correctly I would use a combination of pandas and numby to get the results you want in a timely manner</p> <pre><code>import datetime import numpy as np df_1_data = [[70, 478, 0.0027788935694843], [70, 479, 0.0016728754853829], [70, 480, 0.0004271405050531], ...
python|pandas|dataframe|csv|merge
1
377,279
72,135,397
Pytorch Geometric: RuntimeError: expected scalar type Long but found Float
<p>I have gone through all the similar threads and even sought help via github.</p> <pre><code>import torch from scipy.sparse import coo_matrix from torch_geometric.data import Data, Dataset, download_url import numpy as np from sklearn.preprocessing import MinMaxScaler import pandas as pd def graph_data(A, X, labels)...
<blockquote> <p>The reason lays in:</p> </blockquote> <p>The input x's dtype is &quot;torch.int64&quot;, after GCNConv the x changes to &quot;torch.float32&quot;,but it also expects torch.int64&quot;</p> <blockquote> <p>Solve way</p> </blockquote> <p>x=x.type(torch.float)</p>
python|pytorch|regression|pytorch-geometric
0
377,280
72,102,548
How to groupby by geometry column with Python?
<p>I'm wondering whether someone can help me with this, may be naive, issue, please? Thanks in advance for your opinion. Q: How can I use groupby to group by ['id', 'geometry']? Assuming the geopandas data reads for: pts =</p> <pre><code> id prix agent_code geometry 0 922769 3000 15 POINT (...
<p>Use <code>to_wkt</code> from <code>geometry</code> column to convert shape as plain text:</p> <pre><code>out = pts.groupby(['id', pts['geometry'].to_wkt()], as_index=False) \ .agg(prom_revenue=('prix', np.mean)) print(out) # Output id prom_revenue 0 922769 1525.0 1 1539368 1700.0 ...
python|pandas|pandas-groupby|geopandas
3
377,281
71,986,500
ValueError: Input 0 of layer "lstm" is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 1024)
<p>I was following Transfer learning with YAMNet for environmental sound classification tutorial. Here is the link: <a href="https://www.tensorflow.org/tutorials/audio/transfer_learning_audio" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/audio/transfer_learning_audio</a> In the tutorial, they defined ...
<p>The line 2 as pointed out in stacktrace is missing the second piece of the tuple (dimension):</p> <pre><code> 1 model = tf.keras.Sequential() ----&gt; 2 model.add(LSTM(32, input_shape=(1024, ))) 3 model.add(tf.keras.layers.Dense(512, activation='relu')) </code></pre> <p>I assume it should have a number in...
python|tensorflow|keras|lstm|sequence
0
377,282
71,915,308
gausian blur image processing matrix multiplication
<p>I am trying to implement Image Filters such as Gausian Blur in python.</p> <p>I encountered a problem when I tried to optimise my code to allow a 5 by 5 kernel.</p> <p>My aim is to allow any nxn Gausian Kernel to be applied to an image.</p> <p>The current implementation</p> <pre><code>def gaussianOperator(roi, kerne...
<p>Simulating your size 3 kernel case:</p> <pre><code>In [174]: roi = np.arange(10) ...: for i in range(roi.shape[0]-2): ...: x = roi[i:i+3] ...: print(x.shape, x) ...: ...: (3,) [0 1 2] (3,) [1 2 3] (3,) [2 3 4] (3,) [3 4 5] (3,) [4 5 6] (3,) [5 6 7] (3,) [6 7 8] (3,) [7 8 9] </code>...
python|numpy
0
377,283
72,066,198
getting raise KeyError(key) from err KeyError: 'Year' from code given below
<p>i get this error from the code provided below :</p> <blockquote> <p>raise KeyError(key) from err KeyError: 'Year'</p> </blockquote> <p>code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import sys import matplotlib matplotlib.use('Agg') mark_base = {&quot;Math&quot;: [99, 98, 97, 96, 93, 92], ...
<p>The CSV file column separator is not the default comma but comma-space.</p> <p>Therefore you either need to remove the extraneous spaces in the CSV file or:</p> <pre><code>mark_chart = pd.read_csv('C:/Users/naman/OneDrive/Desktop/amaiboy/Visual Studio Code/HTML, CSS and JavaScript/markbase.csv', header=0, sep=&quot;...
python|pandas|matplotlib
0
377,284
71,855,193
Extract utc format for datetime object in a new Python column
<p>Be the following pandas DataFrame:</p> <pre><code>| ID | date | |--------------|---------------------------------------| | 0 | 2022-03-02 18:00:20+01:00 | | 0 | 2022-03-12 17:08:30+01:00 | | 1 | 2022-04-23 12:1...
<p>Convert column to datetimes and then extract <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.date.html" rel="nofollow noreferrer"><code>Series.dt.date</code></a> and times with timezones by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftim...
python|pandas|dataframe|datetime
1
377,285
71,963,393
Pandas - Compare each row with one another across dataframe and list the amount of duplicate values
<p>I would like to add a column to an existing dataframe that compares every row in the dataframe against each other and list the amount of duplicate values. (I don't want to remove any of the rows, even if they are entirely duplicated with another row)</p> <p>The duplicates column should show something like this:</p> ...
<p>IIUC, you can convert your dataframe to an array of <code>set</code>s, then use numpy broadcasting to compare each combination (except the diagonal) and get the max intersection:</p> <pre><code>names = df.agg(set, axis=1) a = df.agg(set, axis=1).to_numpy() b = a&amp;a[:,None] np.fill_diagonal(b, {}) df['Duplicates']...
python|pandas
1
377,286
71,854,171
How can I use large hexadecimal values as training data? In machine learning,
<p>I am thinking of doing machine learning using <code>sklearn</code>. But the training data I have is a large hexadecimal value. How do I process this into training data? The code below is an example of a hexadecimal value</p> <p><code>import sklearn</code> <code>hex_train='0x504F1728378126389BACDDDDDFF128737889128937...
<p>Here is a function to convert hex to decimal !</p> <pre><code>import binascii def convert_hex_to_dec(string): try: return int(string, 16) except ValueError: return int(binascii.hexlify(string.encode('utf-8')), 16) except TypeError: return int(hex(0,), 16) </code></pre>
python|machine-learning|sklearn-pandas
1
377,287
72,075,258
ValueError: cannot reshape array of size 921600 into shape (224,224,3)
<p>I trained a model using Transfer Learning(InceptionV3) and when I tried to predict the results it shows:</p> <pre><code>ValueError: cannot reshape array of size 921600 into shape (224,224,3) </code></pre> <p>The image generator I used to train the model is:</p> <pre><code> root_dir = 'G:/Dataset' img_generator_f...
<p>Did you try converting your image to grey first?</p> <p>detectMultiScal() requires an image in format CV_8U.</p> <p><a href="https://docs.opencv.org/3.4/d1/de5/classcv_1_1CascadeClassifier.html#aaf8181cb63968136476ec4204ffca498" rel="nofollow noreferrer">https://docs.opencv.org/3.4/d1/de5/classcv_1_1CascadeClassifie...
python|tensorflow|opencv|keras|deep-learning
0
377,288
71,808,901
Optimize duplicate integers in list / DataFrame column
<p>How to get &quot;<em>Expected list</em>&quot; from &quot;<em>Original list</em>&quot; in Python 3 or by using Pandas?</p> <p>Original list:</p> <pre><code>array = [1, 1, 5, 8, 8, 20213, 22170, 22170, ...] </code></pre> <p>Expected list:</p> <pre><code>array = [1, 1, 2, 3, 3, 4, 5, 5, ...] </code></pre> <p><em>Duplic...
<p>Seems like you've found a Pandas solution. Here's a pure Python attempt:</p> <pre><code>array = [1, 1, 5, 8, 8, 20213, 22170, 22170] position = {} result = [position.setdefault(item, len(position) + 1) for item in array] </code></pre> <p>Result:</p> <pre><code>[1, 1, 2, 3, 3, 4, 5, 5] </code></pre> <p>Or a bit more...
python|python-3.x|pandas
1
377,289
16,642,078
Plot shows up and disappears fast in R
<p>I am plotting some graphs using R. When I run the program the plot appears and then quickly disappears. How can I make the plot stay?`</p> <p>I am running the following code found in <a href="https://stackoverflow.com/questions/5695388/dynamic-time-warping-in-python">Dynamic Time Warping in Python</a></p> <pre><co...
<p>One solution would be to wait for the user to type "enter" before the program finishes:</p> <pre><code>raw_input("Please type enter...") </code></pre> <p>This is also useful with my Matplotlib plots (instead of using <code>pyplot.show()</code>: this closes all the plots automatically).</p> <p>PS: I just saw that ...
python|r|numpy|plot
1
377,290
16,826,049
gradient descent using python numpy matrix class
<p>I'm trying to implement the univariate gradient descent algorithm in python. I have tried a bunch of different ways and nothing works. What follows is one example of what I've tried. What am I doing wrong? Thanks in advance!!!</p> <pre><code>from numpy import * class LinearRegression: def __init__(self,data_fil...
<p>You have two problems, both are related to floating points: <br><br> 1. Initialize your theta matrix like this:</p> <pre><code>self.theta = matrix([[0.0],[0.0]]) </code></pre> <p><br> 2. Change the update lines, replacing <code>(1/m)</code> with <code>(1.0/m)</code>:</p> <pre><code>tempTheta[0] = self.theta[0] - ...
python|matrix|numpy|regression
2
377,291
16,887,148
Python linspace limits from two arrays
<p>I have two arrays:</p> <pre><code>a=np.array((1,2,3,4,5)) b=np.array((2,3,4,5,6)) </code></pre> <p>What I want is to use the values of a and b for the limits of linspace e.g.</p> <pre><code>c=np.linspace(a,b,11) </code></pre> <p>I get an error when I use this code. The answer should be for the first element of ...
<p>If you want to avoid explicit Python loops, you can do the following:</p> <pre><code>&gt;&gt;&gt; a = np.array([1, 2, 3, 4, 5]).reshape(-1, 1) &gt;&gt;&gt; b = np.array([2, 3, 4, 5, 6]).reshape(-1, 1) &gt;&gt;&gt; c = np.linspace(0, 1, 11) &gt;&gt;&gt; a + (b - a) * c array([[ 1. , 1.1, 1.2, 1.3, 1.4, 1.5, 1....
python|arrays|numpy
12
377,292
22,321,623
python C extension of numpy error in 64-bit centos, but Ok in 32-bit centos
<p>It's supposed to be called like this:</p> <pre><code>Pyentropy(np.array([1,2,2,1,1,1],int), 0) </code></pre> <p>or</p> <pre><code>Pyentropy(np.array([1,2,2,1,1,1],int), 1) </code></pre> <p>It meant to calculate the entropy of [1,2,2,1,1,1] But in Pyentropy, [1,2,2,1,1,1] is converted to a C-array and call entrop...
<p>I think the issue is with the type of <code>x</code>. After the call to <code>PyArray_AsCArray</code>, it is pointing to a data segment of <code>NPY_INT64</code>s with the data from <code>xobj</code>. If on your platform <code>int</code> (the type of <code>x</code>) is the same as <code>npy_int64</code>, your progra...
python|c|numpy
1
377,293
22,120,091
Python equivalent for MATLAB function frontcon
<p>Is there a numpy/scipy equivalent to the MATLAB function <a href="http://www.mathworks.co.uk/help/finance/frontcon.html" rel="nofollow">frontocon</a> (mean-variance efficient frontier)?</p>
<p>The only related tools I could find where;</p> <p><a href="http://www.quantandfinancial.com/" rel="nofollow">http://www.quantandfinancial.com/</a></p> <p>There seems to be some case study code around mean-variance efficient frontier located here;</p> <p><a href="https://code.google.com/p/quantandfinancial/source/...
python|matlab|numpy|scipy|equivalent
0
377,294
22,014,496
Merge 2d arrays(different dimensions) at specified row/column in python
<p>Is there a way to combine two 2d arrays(preferably numpy arrays) of different dimensions starting at specified position, e.g. merge 3x3 into 4x4 array starting at position 1 1:</p> <p>Array A</p> <pre><code>1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 </code></pre> <p>Array B</p> <pre><code>5 5 5 5 5 5 5 5 5 </code></pre> <...
<pre><code>In [32]: a2 = np.loadtxt(StringIO.StringIO("""5 5 5\n 5 5 5\n 5 5 5""")) In [33]: a1 = np.loadtxt(StringIO.StringIO("""1 1 1 1\n 2 2 2 2\n 3 3 3 3\n 4 4 4 4""")) In [34]: a1[1:, 1:] = a2 In [35]: a1 ...
python|arrays|numpy|merge
2
377,295
22,126,229
numpy.polyfit with adapted parameters
<p>Regarding to this: <a href="https://stackoverflow.com/questions/21973740/polynomial-equation-parameters">polynomial equation parameters</a> where I get 3 parameters for a squared function <code>y = a*x² + b*x + c</code> now I want only to get the <strong>first</strong> parameter for a squared function which describ...
<p>This can be done by <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html" rel="nofollow noreferrer">numpy.linalg.lstsq</a>. To explain how to use it, it is maybe easiest to show how you would do a standard 2nd order polyfit 'by hand'. Assuming you have your measurement vectors <code>x...
python|numpy|polynomial-math
7
377,296
22,127,569
Opposite of melt in python pandas
<p>I cannot figure out how to do "reverse melt" using Pandas in python. This is my starting data</p> <pre><code>import pandas as pd from StringIO import StringIO origin = pd.read_table(StringIO('''label type value x a 1 x b 2 x c 3 y a 4 y b 5 y c 6 z a 7 z b 8 z c 9''')) o...
<p>there are a few ways;<br> using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html#pandas.DataFrame.pivot" rel="noreferrer"><code>.pivot</code></a>:</p> <pre><code>&gt;&gt;&gt; origin.pivot(index='label', columns='type')['value'] type a b c label x 1 2 3 y...
python|pandas|pivot|reshape|melt
123
377,297
22,148,757
Python Pandas DataFrame cell changes disappear
<p>I'm new to python and pandas and I'm trying to manipulate a csv data file. I load two dataframes one contains a column with keywords and the other is a "bagOfWords" with "id" and "word" columns. What i whant to do is to add a column to the first dataframe with the ids of the keywords in a "list string" like so "[1,2...
<p>there's definitely something wrong with using <code>i</code> for both <code>for</code> loops. change that and see if that helps.</p>
python|loops|csv|pandas
0
377,298
17,771,943
numpy:doesnt give correct for negative powers
<p>i am trying to convert a matlab code in numpy for calculating bit error rate a piece of code is making problem for me this is the matlab code i wanted to convert</p> <pre><code>SNR=6:22; display(SNR) display(length(SNR)) BER=zeros(1,length(SNR)); display(BER) display(length(BER)) Es=10; for ii=1:length(SNR) v...
<p>SNR is of dtype <code>int32</code> be default. Dividing an <code>int</code> by an <code>int</code> gives you an <code>int</code> (or raises a <code>ZeroDivisionError</code>) in Python2. So</p> <pre><code>SNR[ii]/10 </code></pre> <p>gives you the wrong result:</p> <pre><code>In [15]: SNR Out[15]: array([ 6, 7, 8...
python|matlab|numpy
3
377,299
17,924,411
Vectorized (partial) inverse of an N*M*M tensor with numpy
<p>I'm almost exactly in a similar situation as the asker here over a year ago: <a href="https://stackoverflow.com/questions/9284421/fast-way-to-invert-or-dot-kxnxn-matrix">fast way to invert or dot kxnxn matrix</a></p> <p>So I have a tensor with indices a[n,i,j] of dimensions (N,M,M) and I want to invert the M*M squa...
<p><strong>Update:</strong> In NumPy 1.8 and later, the functions in <code>numpy.linalg</code> are generalized universal functions. Meaning that you can now do something like this:</p> <pre><code>import numpy as np a = np.random.rand(12, 3, 3) np.linalg.inv(a) </code></pre> <p>This will invert each 3x3 array and retu...
python|numpy|matrix|scipy|vectorization
4