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
373,500
17,046,122
transpose a subset columns in dataframe (not groupby, need to create new columns)
<p>I've a table which has two columns, the first one is the indice of the site, and the second is the number of states per hour during 24 hours. Thus for each site, I've 24(lines)x2(columns) data. How can I transpose the second column (24 lines data per site) into the line which contains 24+1 columns with site indice. ...
<p>Although this feels a little hacky, you could use a <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow"><code>groupby</code></a>:</p> <pre><code>In [11]: df Out[11]: site_index state 0 1 a 1 1 b 2 1 a 3 2 a 4 2 a ...
python|dataframe|pandas|transpose
2
373,501
17,013,100
Python plot log scale set xticks?
<p>I am trying to plot between in Log scale but there are problems ;</p> <pre><code>from pylab import * import matplotlib.pyplot as pyplot Ds = pow(10,5) D = np.linspace(0, pow(10,6), 6) alpha=1.44 beta=0.44 A=alpha*pow((D/Ds), beta) L=1.65 a=exp(-(A*L/4.343)) fig = pyplot.figure() ax = fig.add_subplot(1,1,1) ax.set...
<p>Yes, you can do it like:</p> <pre><code>import numpy as np xticks = [0.001, 0.002, 0.003, 0.004, 0.005, 0.01, 0.02, 0.03, 0.04, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 1., 2., 3., 4., 5., 10.] yticks = np.arange(0,1,0.1) ax.xaxis.set_ticks( xticks ) ax.yaxis.set_ticks( yticks ) </code></pre> <p>To force labels in...
python|numpy|matplotlib
2
373,502
16,925,596
How can I use Scipy to do a memory efficient distance transform operation?
<p>I am working on a project in Python using GDAL to work on GIS rasters. These rasters or images can get rather large so I usually use memory mapping in Numpy to load them. Currently I want to do a distance transform operation on a memory mapped Numpy array. I was trying to use Scipy's <a href="http://docs.scipy.org/d...
<p>What version of Scipy are you using? In the version I'm running (0.12.0), there is no <code>out</code> parameter because there are two output parameters: <code>distances</code> and <code>indices</code>, which can both be used for output. If these are provided and are instances of ndarray or a subclass, scipy will do...
python|memory|numpy|scipy
5
373,503
16,807,836
How to resample a TimeSeries in pandas with a fill_value?
<p>I have a <code>TimeSeries</code> of integers that I would like to downsample using <code>resample()</code>. The problem is that I have some periods with missing data that are converted to <code>NaN</code>. Since pandas does not support <a href="http://pandas.pydata.org/pandas-docs/stable/gotchas.html" rel="nofollow"...
<p>You can define your own function to avoid <code>NaN</code></p> <pre><code>In [36]: def _sum(x): ....: if len(x) == 0: return 0 ....: else: return sum(x) ....: In [37]: s.resample('M', how=_sum) Out[37]: 2013-01-31 3 2013-02-28 0 2013-03-31 3 Freq: M, dtype: int64 </code></p...
python|pandas|time-series|resampling
7
373,504
16,958,513
Showing Pandas data frame as a table
<p>since I have installed the updated version of pandas every time I type in the name of a dataframe, e.g.</p> <pre><code>df[0:5] </code></pre> <p>To see the first few rows, it gives me a summary of the columns, the number of values in them and the data types instead.</p> <p>How do I get to see the tabular view inst...
<p><em>Note: To show the top few rows you can also use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.head.html" rel="noreferrer"><code>head</code></a>.</em></p> <p>However, pandas will show the summary view if there are more columns than <code>display.max_columns</code> or they are lo...
python|pandas
23
373,505
18,965,016
How to unite several results of a dataframe columns describe() into one dataframe?
<p>I am applying describe() to several columns of my dataframe, for example:</p> <pre><code>raw_data.groupby("user_id").size().describe() raw_data.groupby("business_id").size().describe() </code></pre> <p>And several more, because I want to find out how many data points are there per user on average/median/etc..</p> ...
<p>I might simply build a new DataFrame manually. If you have</p> <pre><code>&gt;&gt;&gt; raw_data user_id business_id data 0 10 1 5 1 20 10 6 2 20 100 7 3 30 100 8 </code></pre> <p>Then the results of <code>groupby(smth).size().desc...
pandas
0
373,506
18,921,419
Implementing a 2D, FFT-based Kernel Density Estimator in python, and comparing it to the SciPy implimentation
<p>I need code to do 2D Kernel Density Estimation (KDE), and I've found the SciPy implementation is too slow. So, I've written an FFT based implementation, but several things confuse me. (The FFT implementation also enforces periodic boundary conditions, which is what I want.)</p> <p>The implementation is based on cre...
<p>The differences you're seeing are due to the bandwidth and scaling factors, as you've already noticed.</p> <p>By default, <code>gaussian_kde</code> chooses the bandwidth using <a href="http://books.google.com/books?id=wdc8Xme_FfkC&amp;lpg=PP2&amp;ots=kcKiNgFxf2&amp;dq=scott%27s%20rule%20multivariate%20density%20est...
python|numpy|scipy|fft|kernel-density
4
373,507
18,965,402
python loop over continuously expanding list
<p>I have a list containing values (tuples in my case) - in the beginning there is 1 element. I need to loop over a list and for the last value in the list apply some computations, which will provide me with the next list element. After that I need to concatenate those lists and using the last value of the list compute...
<p>If you just want to loop through the list later, you can build a generator:</p> <pre><code>def f(elem): return elem + 10 def lst(init): yield init while True: next = f(init) yield next init = next </code></pre> <p>This goes on forever, so be sure your loop has some break in it:...
python|list|numpy
3
373,508
18,915,609
find index of similar values
<p>I have a numpy array that looks like this</p> <pre><code>a b 1 1 1 1 1 1 1 2 1 3 1 3 2 24 3 1 3 1 3 1 3 1 4 5 4 5 4 7 4 9 </code></pre> <p>Is it possible to get indices of all values of a where values of b are equal? (I dont want indices where a = b, I want indices for all 'a' wher...
<p>Load them in pandas DataFrame and do a groupby:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'a': a, 'b': b}) &gt;&gt;&gt; df.groupby(['a', 'b']).groups {(1, 1): [0, 1, 2], (1, 2): [3], (1, 3): [4, 5], (2, 24): [6], (3, 1): [7, 8, 9, 10], (4, 5): [11, 12], (4, 7): [13], (4, 9): [14]} </code></pre> <p>Then...
python|numpy
3
373,509
22,414,152
Best way to initialize and fill an numpy array?
<p>I want to initialize and fill a <code>numpy</code> array. What is the best way?</p> <p>This works as I expect:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.empty(3) array([ -1.28822975e-231, -1.73060252e-077, 2.23946712e-314]) </code></pre> <p>But this doesn't: </p> <pre><code>&gt;&gt;&gt; n...
<p>You could also try:</p> <pre><code>In [79]: np.full(3, np.nan) Out[79]: array([ nan, nan, nan]) </code></pre> <p>The pertinent doc:</p> <pre><code>Definition: np.full(shape, fill_value, dtype=None, order='C') Docstring: Return a new array of given shape and type, filled with `fill_value`. </code></pre> <p>Alth...
python|arrays|numpy|multidimensional-array|initialization
41
373,510
22,253,632
creating a boolean indexing in for loop in pandas
<p>I would like to get a subset of a pandas dataframe with boolean indexing. </p> <p>The condition I want to test is like (df[var_0] == value_0) &amp; ... &amp; (df[var_n] == value_n) where the number n of variables involved can change. As a result I am not able to write : </p> <pre><code>df = df[(df[var_0] == value_...
<p>The <code>isin</code> method should work for you here.</p> <pre><code>In [7]: df Out[7]: a b c d e 0 6 3 1 9 6 1 8 9 5 7 2 2 6 4 7 4 3 3 4 8 0 0 5 4 4 4 2 3 4 5 2 5 9 0 9 6 4 8 2 9 1 7 3 0 8 9 7 8 0 5 9 9 6 9 0 7 8 4 8 [10 rows x 5 columns] In [8]: vals = ...
python|pandas|dataframe
3
373,511
22,179,147
resampling pandas series with numeric index
<p>suppose I have a pandas.Series with index with numeric value type e.g. </p> <pre><code>pd.Series( [10,20], [1.1, 2.3] ) </code></pre> <p>How do we resample above series with 0.1 interval? look like the .resample func only work on datetime interval? </p>
<p>That goes by the name of interpolation. You can think for resampling as a special case of interpolation.</p> <pre><code>In [24]: new_idx = s.index + pd.Index(np.arange(1.1, 2.3, .01)) In [25]: s.reindex(new_idx).interpolate().head() Out[25]: 1.10 10.000000 1.11 10.083333 1.12 10.166667 1.13 10.250000 ...
python|pandas
5
373,512
22,143,557
Pandas DataFrame group by value and get column & row indexes
<p>I have a pandas <code>DataFrame</code> like following.</p> <pre><code>df = pandas.DataFrame(np.random.randn(5,5),columns=['1','2','3','4','5']) 1 2 3 4 5 0 0.877455 -1.215212 -0.453038 -1.825135 0.440646 1 1.640132 -0.031353 1.159319 -0.615796 0.763137 2 0.132355 -0.7...
<p>You can use <code>np.where</code> on the boolean result to extract the indices:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame(np.random.randn(5,5),columns=['1','2','3','4','5']) condition = df.values &gt; 2 print np.column_stack(np.where(condition)) </code></pre> <p>For a <code>df</code>...
python|pandas|dataframe
2
373,513
22,121,385
list to array with different columns in one row python
<p>I need to convert a list to array. But the function asarray does not generate the desired result, do you know how to do the conversion? Thanks!</p> <p>list:</p> <pre><code>[[1,2],[4,5,6]] </code></pre> <p>convert to array:</p> <pre><code>[[1,2,""], [4,5,6]] </code></pre>
<p>The desired NumPy array would have to be of dtype <code>object</code>. Such arrays enjoy none of the speed advantages of NumPy arrays with native dtypes. You may want to re-adjust your goal.</p> <p>However, more in the spirit of play than practicality, here is how you <em>could</em> create the desired array:</p> <...
python|arrays|list|numpy
3
373,514
17,763,961
numpy cumulative product: normalizing result after each prod operation along axis
<p>I have an array, for example (2,1000) shape. i need to get a cumulative product along axis=1, thats not a problem, though if my numbers are below 1 - they quickly get to zero, if they are above 1 - they quickly get to Inf. The question is if there any way to normalize every column along axis=0 (i.e. by sum) after ev...
<p>I am not very sure I have understood you algorithm very well, but lets say your array is:</p> <pre><code>[[a c e g] [b d f h]] </code></pre> <p>If I get you right, you will first compute <code>a*c</code> and <code>b*d</code>, and before multiplying by <code>e</code> and <code>f</code>, you would divide both numbe...
python|arrays|numpy|normalization
1
373,515
17,818,695
Read excel file from StringIO buffer to dataframe with pandas.io.parsers.ExcelFile?
<p>I'd like to read a string buffer into a pandas DataFrame. It seems that a good way to do it would be to use pandas' ExcelFile functionality. I've tried to do something like the following:</p> <pre><code>from pandas import ExcelFile as excel_handler excel_data = excel_handler(StringIO(file_stream.read()).getvalue())...
<p>Fixed. Had missed a part earlier in my code where file_stream.read() was being called. Consequently, by the time ExcelFile was being called, an empty string was being passed to it, causing an error. getvalue() needed to be removed. Here's how it should go:</p> <pre><code>from pandas import ExcelFile excel_data = Ex...
python|excel|pandas|openpyxl|stringio
1
373,516
17,889,336
Find 'Time Delayed' using python pandas
<p>I have the following dataframe;</p> <pre><code>Group Deadline Time Deadline Date Task Completed Date Task Completed Time Group 1 20:00:00 17-07-2012 17-07-2012 20:34:00 Group 2 20:15:00 17-07-2012 17-07-2012 20:39:00 Group 3 22:00:00 17...
<p>Combine them as strings ("addition" works), convert them to <code>datetime</code> type, and then subtract, which gives a Series of <code>timedelta</code> type.</p> <pre><code>In [14]: deadline = pd.to_datetime(df['Deadline Date'] + ' ' + df['Deadline Time']) In [15]: completed = pd.to_datetime(df['Task Completed D...
python|pandas
3
373,517
17,688,526
checking if pandas dataframe is indexed?
<p>Is it possible to check if a pandas dataframe is indexed? Check if <code>DataFrame.set_index(...)</code> was ever called on the dataframe? I could check if <code>df.index</code> is a numeric list but that's not a perfect test for this.</p>
<p>One way would be to compare it to the plain Index:</p> <pre><code>pd.Index(np.arange(0, len(df))).equals(df.index) </code></pre> <p>For example:</p> <pre><code>In [11]: df = pd.DataFrame([['a', 'b'], ['c', 'd']], columns=['A', 'B']) In [12]: df Out[12]: A B 0 a b 1 c d In [13]: pd.Index(np.arange(0, len...
python|numpy|pandas|dataframe
4
373,518
18,197,071
Find unique columns and column membership
<p>I went through these threads:</p> <ul> <li><a href="https://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array">Find unique rows in numpy.array</a></li> <li><a href="https://stackoverflow.com/questions/7438438/removing-duplicates-in-each-row-of-a-numpy-array">Removing duplicates in each row of a n...
<p>First lets get the unique indices, to do so we need to start by transposing your array:</p> <pre><code>&gt;&gt;&gt; a=a.T </code></pre> <p>Using a modified version of the above to get unique indices.</p> <pre><code>&gt;&gt;&gt; ua, uind = np.unique(np.ascontiguousarray(a).view(np.dtype((np.void,a.dtype.itemsize *...
python|numpy|unique
3
373,519
4,318,615
Python/Numpy MemoryError
<p>Basically, I am getting a memory error in python when trying to perform an algebraic operation on a numpy matrix. The variable <code>u</code>, is a large matrix of double (in the failing case its a 288x288x156 matrix of doubles. I only get this error in this huge case, but I am able to do this on other large matrice...
<p>Rewrite to</p> <pre><code>p *= alpha u += p </code></pre> <p>and this will use much less memory. Whereas <code>p = p*alpha</code> allocates a whole new matrix for the result of <code>p*alpha</code> and then discards the old <code>p</code>; <code>p*= alpha</code> does the same thing in place.</p> <p>In general, wi...
python|memory|numpy|scipy
52
373,520
4,258,106
How to calculate a Fourier series in Numpy?
<p>I have a periodic function of period T and would like to know how to obtain the list of the Fourier coefficients. I tried using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fft.html" rel="noreferrer">fft</a> module from numpy but it seems more dedicated to Fourier transforms than series. Ma...
<p>In the end, the most simple thing (calculating the coefficient with a riemann sum) was the most portable/efficient/robust way to solve my problem:</p> <pre><code>import numpy as np def cn(n): c = y*np.exp(-1j*2*n*np.pi*time/period) return c.sum()/c.size def f(x, Nh): f = np.array([2*cn(i)*np.exp(1j*2*i*np....
python|numpy|fft
32
373,521
4,116,658
Faster numpy cartesian to spherical coordinate conversion?
<p>I have an array of 3 million data points from a 3-axiz accellerometer (XYZ), and I want to add 3 columns to the array containing the equivalent spherical coordinates (r, theta, phi). The following code works, but seems way too slow. How can I do better?</p> <pre><code>import numpy as np import math as m def cart...
<p>This is similar to <a href="https://stackoverflow.com/questions/4116658/faster-numpy-cartesian-to-spherical-coordinate-conversion/4116803#4116803">Justin Peel</a>'s answer, but using just <code>numpy</code> and taking advantage of its built-in vectorization:</p> <pre><code>import numpy as np def appendSpherical_np...
python|numpy|coordinate
43
373,522
8,688,203
excluding element from numpy array
<p>I want to get the c array as result, but I don't know how:</p> <pre><code>import numpy as np a = xrange(10) b = np.array([3,2,1,9]) </code></pre> <p>c is made of elements of a that are not in b:</p> <pre><code>c = np.array([0,4,5,6,7,8]) </code></pre>
<p>Perhaps a more straightforward solution is the following:</p> <pre><code>import numpy as np a = xrange(10) b = np.array([3,2,1,9]) c = np.setdiff1d(a,b) </code></pre> <p>Which results in:</p> <pre><code>In [7]: c Out[7]: array([0, 4, 5, 6, 7, 8]) </code></pre> <p>You can find all of the set-like operations for ...
python|arrays|numpy|elements
9
373,523
8,407,090
finding element of numpy array that satisfies condition
<p>One can use <code>numpy</code>'s <code>extract</code> function to match an element in an array. The following code matches an element <code>'a.'</code> exactly in an array. Suppose I want to match all elements containing <code>'.'</code>, how would I do that? Note that in this case, there would be two matches. I'd a...
<p>You can use the <a href="http://docs.scipy.org/doc/numpy/reference/routines.char.html#string-information">string operations</a>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; x = np.array([['a.','cd'],['ef','g.']]) &gt;&gt;&gt; x[np.char.find(x, '.') &gt; -1] array(['a.', 'g.'], dtype='|S2') </...
python|search|numpy
9
373,524
8,434,919
Install pyopencv inside virtualenv with --no-site-packages
<p>I am trying to install pyopencv to virtualenv created with --no-site-packages option:</p> <pre><code>pip install pyopencv </code></pre> <p>But I am getting following error on Ubuntu 10.04.3:</p> <pre><code>CMake Error at CMakeLists.txt:186 (find_package): Could not find a configuration file for package OpenCV. S...
<p>Adding this two lines to /etc/bash.bashrc (or just run in command prompt) fix problem.</p> <pre><code>PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig export PKG_CONFIG_PATH </code></pre> <p>Also follow insctuctions here: <a href="https://github.com/ingenuitas/SimpleCV#installation" rel="nofollow">https:/...
python|opencv|numpy|scipy
2
373,525
55,557,531
TensorFlow: calling a graph inside another graph
<p>I need to give the "logits" of one graph (g1) as an input of another graph (g2). Then, I need to get layer outputs of g2 when the input is "logits". After some calculations on layer outputs, I should return a custom loss value to g1. </p> <p>Here is the first graph: </p> <pre><code>g1 = tf.Graph() with g.as_defau...
<p>Consider following example. You have first graph as follows:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf graph1 = tf.Graph() with graph1.as_default(): x1 = tf.placeholder(tf.float32, shape=[None, 2]) y1 = tf.placeholder(tf.int32, shape=[None]) with tf.name_scope('networ...
tensorflow|neural-network|tensor
2
373,526
55,253,291
Filtering rows on DataFrame based on data in a Series
<p>There's a DataFrame <code>df</code> containing following data:</p> <pre><code>+------+----------+-------+ | YEAR | CATEGORY | GRADE | +------+----------+-------+ | 1999 | A | 3.5 | | 1999 | A | 7.2 | | 1999 | B | 0.2 | | 1999 | B | 6.4 | | 2000 | A | 1.4 | | 2000 | A...
<p><code>set_index</code> and using <code>gt</code> with boolean to filter the df </p> <pre><code>yourdf=df[df.set_index(['YEAR','CATEGORY']).GRADE.gt(s).values] yourdf YEAR CATEGORY GRADE 1 1999 A 7.2 3 1999 B 6.4 7 2000 B 8.4 </code></pre>
python|pandas
4
373,527
55,515,810
How to create new pandas series based on comparing existing values to lower & upper boundaries
<p>I am creating a script that updates retail prices based on supplier cost changes.</p> <p>I have successfully created a script that bring in external supplier data, matches to internal data, outputs the changes and passes these into API to update our ERP and to Sheets so we can visualise the changes. My final task ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>pandas.merge_asof</code></a> for this.</p> <p>A requirement of this method however, is that your keys on the left frame must be sorted. Hence the need to use <a href="https://pand...
python|pandas
4
373,528
55,379,950
Create a file throught code in Kubernetes
<p>I need (or at least I think I need) to create a file (could be a temp file but for now it does not work while I was testing it) where I can copy a file stored in google cloud storage.</p> <p>This file is a geojson file and after load the file i will read it using geopandas.</p> <p>The code will be run it inside a ...
<p>A VERY general overview of the pattern: </p> <p>You can start by putting the code on a git repository. On Kubernetes, create a deployment/pod with the ubuntu image and make sure you install python, your python dependencies and pull your code in an initialization script, with the final line invoking python to run yo...
python|kubernetes|google-cloud-platform|geopandas
0
373,529
55,300,225
TensorFlow issue with anaconda env
<p>I made a CNN with TensorFlow to use it in the University Cluster. The CNN works fine on my Mac where I have an Anaconda env with TensorFlow 1.10, here all the packages I use in my working env:</p> <pre><code>name: CNN_env channels: - conda-forge - defaults dependencies: - _ipyw_jlab_nb_ext_conf=0.1.0=py36h2fc...
<p>I solved installing Keras with</p> <pre><code>conda install -c conda-forge keras-applications </code></pre> <p>The command automatically downgraded TensorFlow from 1.13 to 1.10 that was what I needed.</p>
linux|macos|tensorflow|anaconda
0
373,530
55,194,999
numpy array IndexError: 'index out of bound' when a mask is inverted or negated
<p>I have 2 arrays one is mask and the other is the labels:</p> <p>Both arrays have the same shape:</p> <pre><code>(Pdb) L.shape (178, 201, 101) (Pdb) MASK.shape (178, 201, 101) </code></pre> <p>when it reaches to this line:</p> <pre><code>L[~MASK] = 0 IndexError: 'index 255 is out of bounds for axis 0 with size 1...
<p>Try:</p> <pre><code>L[np.logical_not(MASK)] </code></pre> <p>The ~ (tilde) operator you are using is a bitwise complement operator, not a logical negation operator.</p>
python|python-3.x|python-2.7|numpy|numpy-ndarray
1
373,531
55,329,893
Setting column value on a slice of DataFrame not working
<p>I have a dataset with employee payroll information (df2). It has a date, job title, shift start time, hours worked.</p> <p>The goal is to create a dataset (df) which shows how many employees were working at any given hour.</p> <p>The problem I am facing is that setting the value in a column is not having any effec...
<p>There are two issues:</p> <p>First </p> <p><code>worked_in_minutes =round(x['Hours']) * 60 + (x['Hours'] - round(x['Hours']))</code> is not doing what you expect it to do. It equals 300.2 for the first row in <code>df2</code> instead of 312 which is what you might be expecting. There is no point in separating out ...
python|pandas|dataframe
0
373,532
55,574,158
Will creating a new Anaconda environment prevent package version override?
<p>I am unclear whether I should create a new environment or/and a new channel in the following case:</p> <p>I have an anaconda with a ~base environment. I created an environment A, a few months ago and installed the Tensorflow version of it at the time. I want to import a new piece of code I found which uses Keras. I...
<p>Conda environment works like virtualenv module for Python. So, yes - you can install different versions of lib into different environments. For example it may be useful, if you want to keep Tensorflow-CPU and Tensorflow-GPU versions installed at the same time. The same thing with Keras. You may read about it e.g. he...
python|tensorflow|anaconda|conda
1
373,533
55,445,355
How can I convert time in string into a datetime format so that I can get difference between two columns
<p>I have a dataframe with two columns with different times in string format, I want to find the difference between the two columns so I use the following code</p> <pre><code>operational_data_clean['Pick/pack start-time'] = pd.to_datetime(operational_data_clean['Pick/pack start-time']) operational_data_clean['Flight ...
<p>I am assuming you are running your code with jupyter notebook. </p> <p>When you execute your code, your variable <code>operational_data_clean['Pick/pack start-time']</code> becomes <code>pd.to_datetime(operational_data_clean['Pick/pack start-time'])</code>.</p> <p>So when you execute the block one more time, jupyt...
python|pandas|datetime
1
373,534
55,382,427
Merging two dataframe by date
<p>I have two dataframe, using pandas, one (df_1) is the average temperature by day of the year until some point in time (for example the average temperature for all the days of 2014 until 03/01/2014) and the other (df_2) is the average temperature by day for the last 30 years. </p> <p>What I want to do is to complete...
<p>Here is a method to accomplish this:</p> <pre><code>from datetime import datetime import numpy as np import pandas as pd # Create date ranges date1 = pd.date_range(datetime(2014,1,1), datetime(2014,3,1)) # 2014 date2 = pd.date_range(datetime(1983,1,1), datetime(2013,12,31)) # 30 years # Create data frames df1 = p...
python|pandas|date|dataframe
0
373,535
55,333,174
Issue faced in converting dataframe to dict
<p>I have a 2 columns (Column names Orig_Nm and Mapping) dataframe:</p> <p>Orig Name Mapping</p> <p>Name FinalName</p> <p>Id_No Identification</p> <p>Group Zone</p> <p>Now I wish to convert it to a dictionary, so I use</p> <pre><code>name_dict = df.set_index('Orig_Nm').to_dict() pr...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.to_dict.html" rel="nofollow noreferrer"><code>Series.to_dict</code></a> instead <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer"><code>DataFrame.to_dict...
python-3.x|pandas|dataframe|dictionary
1
373,536
55,414,046
Problem in shape of y_pred of CIFAR dataset using CNN, tensorflow
<p>Data is from CIFAR-10 I've made the following code originally this code was meant for only 2 conv layer and one fully connected layer. I added one more conv layer with 128 4X4 filter. I have defined a class for extracting batches of a training set. i used a batch size of 100 but now when I'm trying to find out my y_...
<p>there's a problem in flattening the layer, i guess in reshaping. use tf.layers.flatten instead of making your own flatten layer. that would work. </p>
python|tensorflow|deep-learning|conv-neural-network
0
373,537
55,321,559
Grouped 3 monthly aggregation and shifting periods in pandas python
<p><b>The problem</b></p> <p>I have a dataframe with many regions and their respective units sold, visits performed and average visit times on a monthly basis. Not all the regions have the same starting date. </p> <p>So my table looks something like this:</p> <pre><code>Region Month Visits Average_minutes ...
<p>I'm not 100% sure what you are looking for, but the way I interpret, maybe this will help?</p> <p>First sort Region and Month. </p> <pre><code>df = df.sort_values(['Region', 'Month']) </code></pre> <p>The set a multi index.</p> <pre><code>df = df.set_index(['Region', 'Month']) </code></pre> <p>Then groupby the ...
python|pandas
2
373,538
55,495,085
how to code initializer(random.uniform) in custom layers?
<p>I want to initialize my custom layer with random uniform. In TensorFlow,I can find following code which use <code>initializer='uniform'</code>. But I want to set random uniform output range between <code>(-1.0,1.0)</code>. How to do that:</p> <pre><code>class MyDenseLayer(tf.keras.layers.Layer): def __init__(self...
<p>One way is to generate random uniform in <code>numpy</code> and then use <code>tf.constant_initializer()</code> like this:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf import numpy as np class MyDenseLayer(tf.keras.layers.Layer): def __init__(self, num_outputs): super(MyD...
python|tensorflow|keras|initialization
3
373,539
55,237,830
How to find the two closest numpy arrays out of several numpy arrays?
<p>I have several numpy arrays and I want to compare them and find the closest array for a given array. I could calculate the distance between these arrays using <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/scipy/re...
<p>To find the two closest you'll need to compute the distance matrix, then find the minimum in this matrix to get the coordinates that are the closest from each other (using the matrix you'll get the indexes of the coordinates). </p> <pre class="lang-py prettyprint-override"><code>from scipy.spatial import distance i...
python|numpy
1
373,540
55,347,862
How can I create a dataframe of dummies from a dict of lists of unequal length?
<p>I have a dictionary where each key is a row index and each value is a list of dummy values. For example:</p> <pre><code>my_dict = {'row1': ['a', 'b'], 'row2': ['a'], 'row3': ['b', 'c']} </code></pre> <p>Can I create a dataframe of dummies with the above in an efficient manner?</p> <pre><code>&gt;&gt;&gt; df ...
<p><code>crosstab</code> with constructor </p> <pre><code>s=pd.DataFrame(list(my_dict.values()),index=my_dict.keys()).stack() pd.crosstab(s.index.get_level_values(0),s).astype(bool) Out[131]: col_0 a b c row_0 row1 True True False row2 True False False row3 False Tr...
python|pandas|dummy-variable
4
373,541
55,542,575
Combine Pandas DataFrames while creating MultiIndex Columns
<p>I have two DataFrames, something like this:</p> <pre><code>import pandas as pd dates = pd.Index(['2016-10-03', '2016-10-04', '2016-10-05'], name='Date') close = pd.DataFrame( {'AAPL': [112.52, 113., 113.05], 'CSCO': [ 31.5, 31.35, 31.59 ], 'MSFT': [ 57.42, 57.24, 57...
<p>You can use the <code>keys</code> kwarg of concat:</p> <pre><code>In [11]: res = pd.concat([close, volume], axis=1, keys=["close", "volume"]) In [12]: res Out[12]: close volume AAPL CSCO MSFT AAPL CSCO MSFT Date 2016-10-03 112.52 31.50 57.42 217018...
pandas|multi-index
11
373,542
55,441,244
How extract values of dictionary column in pandas dataframe
<p>I'm working on VCF file format,after getting data in pandas dataframe i'm getting below output.</p> <p>Code</p> <pre><code>df1=df['info_dict'] print df1 </code></pre> <p>output-</p> <pre><code>chr1 2337185 {u'END': 2337193} 2337194 {u'IDS': u'1026660,1026661', u'CUR': u'UNKN...
<p>Use <code>.get</code> for get value from dict with default value <code>None</code> if non match, last remove <code>None</code>s by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dropna.html" rel="nofollow noreferrer"><code>Series.dropna</code></a>:</p> <pre><code>s = df['info_dict'...
python|pandas|dataframe
0
373,543
55,517,006
How to get the unique values and transmute the values from a different column?
<p>I generated a unique value based from a column but what I want to get as a result is the transmuted value from a different column. Here's the code for your reference:</p> <pre><code>x = [[123, "M"], [321, "F"], [456, "M"], [678, "F"], [654, "M"], [123, "M"], [678, "F"], [678, "F"]...
<p>The ID is unique, so the gender also the same if the ID is identical. That means you have duplicates. So you can use:</p> <pre><code>x.drop_duplicates() </code></pre>
python|python-3.x|pandas
2
373,544
55,343,096
filling csv file from another csv file grouby column
<p>I have a csv file with 2 columns and I want to create another csv file and fill it like shown in <a href="https://i.stack.imgur.com/1NQYP.png" rel="nofollow noreferrer">the figure</a>. </p> <p>I tried:</p> <pre><code>xx = pd.read_csv('abc.csv', sep=';', encoding='latin-1') for row in xx: ss = [] for p in r...
<p>Try this:</p> <p><code>df.groupby('id').agg(",".join).reset_index()</code></p>
python|pandas|csv|group-by
0
373,545
55,459,995
Pandas dataframe add values in a loop
<p>I am trying to append dynamically to a dataframe a single value that i am generating in a loop.</p> <pre><code>global results_df results_df=pd.DataFrame() avg =109 std_dev = 12 # Loop through many simulations for i in range(1000): # Choose random inputs rev_sim = np.random.normal(avg, std_dev, 1).ro...
<p>You did not assign it back </p> <pre><code>for i in range(1000): # Choose random inputs rev_sim = np.random.normal(avg, std_dev, 1).round(0)#Rounding to 0 decimals # Build the dataframe based on the inputs df_res = pd.DataFrame(data={'REV_SIM': rev_sim}) results_df=results_df.append(df_res...
pandas
3
373,546
55,156,797
Insert values into database from data frame only into corresponding rows
<p>I have a variable dataframe which has variable values when the script is run on different occasions and the values are directly inserted to database. For example, on first run, it may have:</p> <pre><code>column1 column2 A 2 B 1 C 3 D 5 </code></pre> <p>while on other ...
<p>Set the <code>column1</code> as index and concat on <code>axis=1</code>:</p> <pre><code>pd.concat([df1.set_index('column1'),df2.set_index('column1')],axis=1,sort=False) #for exact_match:-&gt; pd.concat([df1.set_index('column1'),df2.set_index('column1')],axis=1,sort=False).fillna('-') column2 column2 A 2...
python|pandas|sqlite|dataframe
1
373,547
55,566,866
Count the occurence of words in a list of all rows of dataframe
<p>I have a dataframe in which one of column has rows with list of values. I want to count the number of occurence of all the words inside the list among all rows.</p> <p>For ex: dataframe df</p> <pre><code>Column A Column B animal [cat, dog, tiger] place [italy, china, japan] pets ...
<p>You need flatten values to simple list and count values - by <a href="https://docs.python.org/3.6/library/collections.html#collections.Counter" rel="nofollow noreferrer"><code>Counter</code></a> or by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="nofollow no...
python|pandas
2
373,548
55,326,529
Why Tensorflow error: `failed to convert object of type <class 'dict'> to Tensor` happens and How can I solve it?
<p>I am doing a task on traffic analysis and I am stymied with some error in my code. My data rows are like this:</p> <p><code>qurter | DOW (Day of week)| Hour | density | speed | label (predicted speed for another half an hour)</code></p> <p>The values are like this:</p> <pre><code>1, 6, 19, 23, 53.32, 45.23 </code...
<blockquote> <p>First of all what is the concept of error? I couldn't find source for reason of error to deal with it. And how can I modify code for solution?</p> </blockquote> <p>Let me first talk about the solution to the problem. You need to change parameter <code>y</code> in <code>pandas_input_fn</code> as f...
tensorflow|regression|python-3.7|tensorflow-estimator|feature-engineering
1
373,549
55,400,942
How does youtube recommender train video_id embedding?
<p>Youtube combines several videos and use average embedding, yet train the embedding.</p> <p>From 3.2 of <a href="https://storage.googleapis.com/pub-tools-public-publication-data/pdf/45530.pdf" rel="nofollow noreferrer">Deep Neural Networks for YouTube Recommendations</a></p> <blockquote> <p>The network requires f...
<p>Mentioning the clarification in the Answer Section (even though it is present in the Comment's section by eugene), for the benefit of the community.</p> <blockquote> <p>Youtube Recommender may train video_id embedding by just Randomly Initializing Embeddings and start from there.. average the Random Embedding...
tensorflow|youtube|embedding
1
373,550
55,150,828
cuDNN launch failure (tensorflow-gpu/CUDA)
<pre><code>Traceback (most recent call last): File "/home/alex/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1322, in _do_call return fn(*args) File "/home/alex/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 130...
<p>I solved it by adding after imports this:</p> <pre><code>os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true' in the script </code></pre>
python|tensorflow|deep-learning|cudnn
0
373,551
55,574,034
How to delete cudnn from ubuntu?
<p>I need cudnn 7 for my tensorflow version. But I can't delete cudnn.</p> <p><a href="https://i.stack.imgur.com/h84AA.png" rel="nofollow noreferrer">terminal</a></p> <p>Update:</p> <pre><code>daniel@tales:~$ rm -r /usr/local/cuda-6.0/lib64/libcudnn* rm: can't delete '/usr/local/cuda-6.0/lib64/libcudnn*': didn't fin...
<p>If you installed cudnn with dpkg, you can simply <code>dpkg --remove</code> each cudnn package. You can check which cudnn packages you installed with dpkg using <code>dpkg -l | grep cudnn</code>.</p>
tensorflow|deep-learning|cudnn
3
373,552
55,224,307
'the label [1] is not in the [index]' error when using DataFrame loc
<p>I have a DataFrame, from which I want to select a cell. I can select a cell by a row index and column label, but when I filter dataframe, same selection doesn't work.</p> <pre><code>print("Title:",df.loc[1,'title']) # Has no error mobiles = df.loc[df['cat3']=='mobile-phones'] print("Title:",mobiles.loc[1,'title']...
<p>When you assign mobiles as:</p> <pre><code>mobiles = df.loc[df['cat3']=='mobile-phones'] </code></pre> <p>chances are there that <code>df['cat3']=='mobile-phones'</code> met the condition at indexes which is not 1. </p> <p>Use:</p> <pre><code>mobiles = df.loc[df['cat3']=='mobile-phones'].reset_index(drop=True) <...
python|pandas|dataframe
2
373,553
55,410,627
How transform string to readable time format in python?
<p>I have a dataset whit two colums, one for date in this format <code>20190313</code> and I convert to date time with this code:</p> <pre><code>import pandas as pd from functools import reduce pd.set_option("display.max_columns", 500) df['Date_O'] = pd.to_datetime(df.Date_O) </code></pre> <p>This transform the strin...
<p>To convert your string to datetime :</p> <pre><code>from datetime import datetime # input : 130928487 means 13:09:28:487 input = "130928487" date_time = datetime.strptime(input, "%H%M%S%f") print("Date time:", date_time) </code></pre> <p><code>Date time: 1900-01-01 13:09:28.487000</code></p> <pre><code>d = dat...
python|pandas|datetime|datetime-format
1
373,554
55,478,428
Making Categorical or Grouped Bar Graph with secondary Axis Line Graph
<p>I need to compare different sets of daily data between 4 shifts(categorical / groupby), using bar graphs and line graphs. I have looked everywhere and have not found a working solution for this that doesn't include generating new pivots and such.</p> <p>I've used both, matplotlib and seaborn, and while I can do one...
<p>Here are two solutions (stacked and unstacked). Based on your questions we will:</p> <ul> <li>plot <code>Head_Count</code> in the left y axis and <code>UTL_R</code> in the right y axis.</li> <li><code>report_date</code> will be our x axis</li> <li><code>shift</code> will represent the hue of our graph.</li> </ul> ...
python|pandas|matplotlib|plot|seaborn
1
373,555
55,177,622
Pandas data frame and SQL query
<p>I'm trying to translate the SQL query to pandas. However, after trying a lot I have now a knot in my head...</p> <pre><code>SELECT ID, Date1, Date2, Value FROM data t1 WHERE t1.ID = 100 AND Date2 BETWEEN '2010-01-01 00:00:00.0' AND '2010-01-31 23:59:59.0' AND t1.Date1 = ( SELECT max(t2.Date1) FROM dat...
<p>You can load data by using the read_sql_query method.</p> <pre><code>import pandas as pd df = pd.read_sql_query(your_sql_statement, your_db_connection) </code></pre>
python|sql|pandas
0
373,556
55,478,561
How to delete many columns in python with one line of code?
<p>I am trying to delete the following columns on my dataframe: 1,2,101:117,121:124,126.</p> <p>So far the two ways I have found to delete columns is:</p> <pre><code>df.drop(df.columns[2:6],axis=1) df.drop(df.columns[[0,3,5]],axis=1) </code></pre> <p>however if I try</p> <pre><code>df.drop(df.columns[1,2,101:117,1...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html" rel="nofollow noreferrer"><code>np.r_</code></a> to slice:</p> <pre><code>import numpy as np df.drop(columns=df.columns[np.r_[1, 2, 101:117, 121:124, 126]]) </code></pre> <hr> <pre><code>import pandas pd df = pd.DataFrame(np.random....
python|python-3.x|pandas
3
373,557
55,209,211
Why can't I make a column with extracted months from the 'dates' column in my DataFrame?
<p>I have a dataframe with dates, and I want to make a column with only the month of the corresponding date in each row. First, I converted my dates to ts objects like this:</p> <pre><code>df['Date'] = pd.to_datetime(df['Date']) </code></pre> <p>After that, I tried to make my new column for the month like this:</p> ...
<p>You have to use property (or accessor object) <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.html" rel="nofollow noreferrer">dt</a></p> <p><code>df["month"] = df.date.dt.month</code></p>
python|pandas|dataframe|timestamp
1
373,558
55,183,413
Duplicate row creation and replace the cell value
<p>I have a CSV file which contains the below data:</p> <pre><code> NAME | AGE | COLLEGE | BRANCH | Qualification ------------------------------------------------------- sai | 21 | FG | CSE | B.Tech Kiran | 22 | FG | EEE | M.Tech Anil | 21 | FG | CSE | B...
<p>First create mask by conditions, replace value by <code>mask</code>, duplicated rows with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> and assign value by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pan...
python-3.x|pandas
1
373,559
55,301,320
I expected a `numpy.lib.polynomial.poly1d` object, I've found a sequence of integers
<pre><code>In [31]: print(np.poly1d((3,2))) 3 x + 2 In [32]: a = np.array(( np.poly1d((3,2)), np.poly1d((3,2)) )) </code></pre> <p>I expected that array <code>a</code> were a <code>(2,)</code> shaped array of <code>numpy.lib.polyn...
<p>A <code>poly1d</code> object is iterable</p> <pre><code>In [1]: np.poly1d((3,2)) Out[1]: poly1d([3, 2]) In [2]: list(_) Out[2]: [3, 2] </code></pre> <p><code>np.array</code> tries to makes a mul...
python|numpy
1
373,560
55,303,765
compare distinct values of two column with pandas
<p>I used this simple DataFrame to play around a little bit.</p> <pre class="lang-py prettyprint-override"><code> A B 0 123 abc 1 123 abc 2 123 def 3 456 def 4 456 def </code></pre> <p>I want to check if the value of column B is always the same for each distinct value in column A. For instance '123' ...
<pre><code>df.groupby(['A',"B"]).filter(lambda x : len(x)==1) </code></pre> <p>and output will be</p> <pre><code> A B 2 123 def </code></pre>
python|pandas|dataframe
0
373,561
55,338,954
Passing keyword argument to quad integration functions in scipy
<p>I want to pass keyword arguments to integrand function in the dblquad or nquad. Is it possible at all to have a keyword argument here or should I just opt in for having positional arguments only?</p> <p>Basically, I tried to pass dictionary as a normal argument. Below is my attempt at doing that: </p> <pre><code>...
<p>Short answer: kwargs are not supported.</p> <p>Possible workarounds include passing keyword args as positionals, passing a single dict as a positional argument, or attaching relevant keywords as attributes to the function you're integrating.</p>
python|numpy|scipy|keyword-argument
2
373,562
55,524,371
convert unacceptable cells to " " (blank, or skip)
<p>I am doing the below, currently; successfully dropping the entire row, with my <code>if in</code> - but it turns out, i don't need to drop the entire row.. How can I handle cells specifically. </p> <hr> <p>How could I <strong>keep the same logic but apply to</strong> the <strong>CELL... convert the <code>N/A,</co...
<p>I assume that excel_data is a Pandas Dataframe.</p> <p>If so, you can use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer">Pandas function fillna()</a> on your IDS column.</p>
python|excel|pandas
0
373,563
55,151,734
ValueError: setting an array element with a sequence?
<p>Why am i getting this error message? </p> <p>Here are the variables that are included in my code. The columns they include are all dummy variables:</p> <pre><code>country_cols = wine_dummies.loc[:, 'country_Chile':'country_US'] variety_cols = wine_dummies.loc[:, 'variety_Cabernet Sauvignon':'variety_Zinfandel'] p...
<p>This is actually quite cumbersome, so it's only going to be useful if you have lots of columns between <code>'country_Chile':'country_US'</code>. In the below example, I'm deliberately dropping the <code>a</code> column in <code>middle_columns</code> by taking the column indices.</p> <p>This is using <a href="https...
python|pandas|valueerror|dummy-variable
0
373,564
55,567,428
How to Divide an array in to segments and then do sub segments of the segments using python numpy?
<p>I want to do divide an 8*8 array in to 4 segments(each segment of 4*4 array) as shown below in step2. Then again divide each segment in to other small 4 subsegemnts(each subsegment of 2*2 array) and then find the mean of each subsegment and then find the stabbndard deviation of each segment using the 4 means of the ...
<p>It can be done using a function <code>view_as_blocks</code> of <code>skimage.util.shape</code>.</p>
python|arrays|image|numpy
1
373,565
55,166,618
Reasonable way to have different versions of None?
<p>Working in Python3. </p> <p>Say you have a million beetles, and your task is to catalogue the size of their spots. So you will make a table, where each row is a beetle and the number in the row represent the size of spots;</p> <pre><code> [[.3, 1.2, 0.5], [.6, .7], [1.4, .9, .5, .7], [.2, .3, .1, .7, .1]] </...
<p>The simplest way to go would be with strings: 'not counted', 'unknown' and 'N/A'. However if you want to process quickly in numpy, arrays with mixed numbers/objects are not your friend. </p> <p>My suggestion would be to add several arrays of the same shape as your data, consisting of 0 and 1. So the array <code>mis...
python|python-3.x|numpy|nonetype
5
373,566
9,707,559
write in file with python
<p>I am searching for the easiest way to save an array in a file. For this I would want to use numpy.savetxt but the problem is that my array is composed of n columns (the number depends on what i ant to do) and it contains complex elements (x+yj). I know how to save it if there is one column and real elements but I d...
<p>You could <a href="http://docs.python.org/py3k/library/pickle.html" rel="nofollow">pickle</a> them:</p> <pre><code>&gt;&gt;&gt; A = np.array([[1,2],[3,4+2j]]) &gt;&gt;&gt; pickle.dump(A, open("out.pkl", "wb")) &gt;&gt;&gt; pickle.load(open("out.pkl", "rb")) array([[ 1.+0.j, 2.+0.j], [ 3.+0.j, 4.+2.j]]) </c...
python|multidimensional-array|numpy
2
373,567
9,858,860
separating mutidimensional array numpy python
<p>i have a numpy array like the following</p> <pre><code>[[ 1 2 3 4 ] [ 5 6 7 8 ] ......... ] </code></pre> <p>So basically I want to create 4 (can be different) lists where</p> <pre><code> list_1 = [1,5...], list_2 = [2,6....] and so on. </code></pre> <p>What is the pythonic way to do this?</p>
<p>Given this</p> <pre><code>&gt;&gt;&gt; a = array([[1,2,3,4], [5,6,7,8], [9, 10,11,12]]) &gt;&gt;&gt; a array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]]) </code></pre> <p>you can use <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing" rel="nofollow">slic...
python|numpy
2
373,568
9,955,021
Numpy EIG approximately 4x slower than MATLAB EIG on Mac OS X 10.6. What am I doing wrong?
<p>I tried profiling the EIG function on MATLAB and NumPy to compare performance on my Macbook Pro (2 GHz, Quad core i7 running OS X 10.6). NumPy EIG appears to be quite slow compared to MATLAB. </p> <p>Here's the code I profiled on NumPy:</p> <pre><code>s = '''\ x = numpy.random.random((2000,2000)); numpy.linalg.eig...
<p>As far as I know, the MATLAB uses MKL libraries as BLAS, not the Accelerate Framework. My experience tells me, that Accelerate is significantly slower than MKL. To check it, you can try to get the academic version of the Enthought Python Distribution (EPD), where Numpy is compiled against MKL, and compare these tim...
macos|numpy|blas|accelerate-framework
5
373,569
9,929,372
min, max and mean over large NumPy arrays in Python
<p>I have a very large NumPy array: <code>a = np.array</code>. From this array I want to get the min, max and average which can be easily done with <code>np.min(a)</code>, <code>np.max(a)</code> and <code>np.mean(a)</code>.</p> <p>However, I want also to have the min, max and average of a portion (begin part or end pa...
<blockquote> <p>All arrays generated by basic slicing are always views of the original array.</p> </blockquote> <p><a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="noreferrer">http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html</a></p> <p>So, yes, just use slices.</p>
python|numpy|max|average|min
7
373,570
7,671,281
numpy: calculate average in a certain area
<p>is there a way for calculating the average within a certain bbox. The difficulty is that the bbox may also contain float values, so that the bounds of the box values must be weighted. The center of each cell has integer values (the edges are x.5).</p> <p>Sample:</p> <pre><code>[[ 1., 1., 1.], [ 1., 1., 1.], [ ...
<p>Your question is unclear to me but it looks like you want to be formatting an array of weights and pass it to the np.average() function along with the array of data you want to average such as:</p> <pre><code>import numpy as np values = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3...
numpy|scipy|average
1
373,571
56,831,303
remove special characters and string from df columns in python
<p>Currently my column is of object type and I'm trying to convert it to type numeric. But it shows the error because of special characters and string contained in it.</p> <p>error:</p> <pre><code>ValueError: Unable to parse string "7`" at position 3298 </code></pre> <p>code:</p> <pre><code>data['col1']=pd.to_numer...
<p>Using <code>str.replace</code> with regex pattern.</p> <p><strong>Ex:</strong></p> <pre><code>df = pd.DataFrame({"col1": ["7`", "123", "AS123", "*&amp;%3R4"]}) print(pd.to_numeric(df['col1'].str.replace(r"[^\d]", ""))) </code></pre> <p><strong>Output:</strong></p> <pre><code>0 7 1 123 2 123 3 34 N...
python|pandas|numpy|dataframe
2
373,572
56,491,623
Combining duplicate dataframe rows with concatenating values for a specific column
<p>I want to combine rows in a way where I concatenate values for a specific column but get some unexpected result on my own dataset. Here is an example. </p> <pre><code>df = pd.DataFrame({'id':['1', '2', '3', '1', '3', '4', '4', '6', '6'], 'words':['a', 'b', 'c', 'b', 'a', 'a', 'b', 'c', 'a' ]}) df2 =...
<p>In my opinion simpliest is sorting values in <code>join</code> function, so <code>value_counts</code> working correct:</p> <pre><code>df2 = df.groupby('id')['words'].apply(lambda x: ' '.join(sorted(x))).reset_index() print (df2) id words 0 1 a b 1 2 b 2 3 a c 3 4 a b 4 6 a c print (df2.words.val...
python|pandas|pandas-groupby
1
373,573
56,519,735
Rolling Count of Previous Defaults for a customer
<p>I would like to generate the amount of defaults/late payements a customer has had previous to a transaction. For example:</p> <pre><code>Customer Late Count A YES 0 B NO 0 A NO 1 B YES 0 B NO 1 A YES 1 A YES 2 <...
<p>In your case , you may need <code>groupby</code> with <code>cumsum</code> and <code>shift</code> </p> <pre><code>df.Late.eq('YES').groupby(df.Customer).apply(lambda x : x.cumsum().shift().fillna(0)).astype(int) Out[501]: 0 0 1 0 2 1 3 0 4 1 5 1 6 2 Name: Late, dtype: int32 </code></pre>
python|pandas|pandas-groupby
1
373,574
56,661,066
Dividing time intervals with multiple index into hourly buckets in Python
<p>here is the code for the sample data set I have </p> <pre><code>data={'ID':[4,4,4,4,22,22,23,25,29], 'Zone':[32,34,21,34,27,29,32,75,9], 'checkin_datetime':['04-01-2019 13:07','04-01-2019 13:09','04-01-2019 14:06','04-01-2019 14:55','04-01-2019 20:23' ,'04-01-2019 21:38','04-01-2019 21:38','04-01-2019 23:...
<p>Not sure if this is efficient, but should work.</p> <pre><code>import pandas as pd from datetime import timedelta def group_into_hourly_buckets(df): df['duration'] = df['checkout_datetime'] - df['checkin_datetime'] grouped_data = [] for idx, row in df.iterrows(): dur = row['duration'].seconds//...
python|pandas|loops|indexing
0
373,575
56,544,766
Assign values to a tensor based on values from another tensor
<p>Suppose I've got two tensors:</p> <pre><code>import keras as K import tensorflow as tf A=K.zeros((4,4)) T=K.constant([0,1,2,2]) #do something #expected result: 1 starting at the index in tensor T ''' array([[1, 1, 1, 1], &lt;-- 1 starting at index(column) 0 [0, 1, 1, 1], &lt;-- 1 starting a...
<p>You need <code>tf.sequence_mask</code>.</p> <pre><code>import keras.backend as K import tensorflow as tf A= K.zeros((4,4)) T= K.constant([0,1,2,2]) mask = tf.sequence_mask(T,A.shape[-1]) # [[False False False False] # [ True False False False] # [ True True False False] # [ True True False False]] result = t...
python-3.x|tensorflow|keras
2
373,576
56,849,801
How to generate Alpha-numaric Fixed length column in panda dataframe
<p>I am trying to create a alpha-numeric(Incremental value) column with fixed length on the basis of one existing column("Number").</p> <p>I have a below data-frame with me:</p> <pre><code>Number Space Student 1 MG A 2 FE B 3 GD C 4 MK D 5 OK E 6 OO...
<p>Use <code>str.zfill</code> as:</p> <pre><code>df['NUM4'] = 'P'+df['Number'].astype(str).str.zfill(3) print(df) Number Space Student NUM4 0 1 MG A P001 1 2 FE B P002 2 3 GD C P003 3 4 MK D P004 4 5 OK E P005 5 6 OO ...
python|pandas
3
373,577
56,691,482
How to add a quote in front of "https" using Python and Pandas?
<p>I have a Python script that is importing links from one CSV file formatting it and then sending it to a different CSV file. I am running into a problem in the formatting phase.</p> <p>I want to add a <code>"</code> before the <code>https</code> in the link. Below is the Python code I am using.</p> <pre><code>df['L...
<p>Instead of this line...</p> <p><code>df['Link'] = df['Link'].apply(lambda x: "\"href:\\{0}\\""\"\"".format(x))</code></p> <p>Try this...</p> <p><code>df['Link'] = df['Link'].apply(lambda x: '\"href:\\"{0}\\""\"\"'.format(x))</code></p>
python|pandas|python-2.7
2
373,578
56,801,863
Unable to interpret a line of python code that creates a LSTM cell using tensorflow
<p>I am trying to figure out how a fully-functional python code works. One block creates a LSTM cell using tensorflow. I don't know how to interpret the line <strong>specified by the comment</strong> below.</p> <pre><code>def get_lstm_weights(n_hidden, forget_bias, dim, scope="rnn_cell"): # Create LSTM cell ce...
<p>Note that <code>tf.contrib.rnn.LSTMCell</code> is an example of a <a href="https://www.geeksforgeeks.org/callable-in-python/" rel="nofollow noreferrer">callable class</a>.</p> <p>That is a class that can be called like a function. The line you are struggling with does exactly that. It <em>calls</em> <code>cell</cod...
python|tensorflow|lstm
1
373,579
56,457,821
How to change some rows to list in dataframe?
<p>I have some rows in df, it is 7 days data with some(may be 3-5) features, I want to merge the 7-day array into a list according to feature.</p> <p>Now is loop unique columns to apply list func, but is not efficient.</p> <p>If you load df directly, df will automatically add a numeric suffix to duplicate columns, bu...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><code>GroupBy.agg</code></a> by columns names:</p> <pre><code>df1 = df.groupby(level=0, axis=1).agg(lambda x: x.tolist()) print (df1) a b c ...
python|pandas|dataframe
1
373,580
56,615,710
Compare one column against two other columns and assign the result back to the DataFrame
<p>Print below code</p> <pre><code>import pandas as pd df = pd.DataFrame() df['A'] = (10,20,34,13,45,2,34,1,18,19,23,9,40,33,17,6,15) df['B'] = (14,26,23,41,12,24,31,1,9,53,4,22,16,19,16,28,13) print(df) </code></pre> <p></p> <ol> <li><p>I would like to add a column that returns 'TRUE' or 'FALSE' if each number ...
<p>You can check with <code>np.where</code> </p> <pre><code>s=np.where(df.A.shift(-5).isna(),'ignore',df.A&gt;df.A.shift(-5)) s Out[90]: array(['True', 'False', 'True', 'False', 'True', 'False', 'True', 'False', 'False', 'True', 'True', 'False', 'ignore', 'ignore', 'ignore', 'ignore', 'ignore'], dtype='...
python|pandas|dataframe
3
373,581
56,466,227
Speed up finding next index in another list of indices (numpy)
<p>The code below works as desired but it does not seem optimized because of the loop. I have been able to successfully vectorize all of my other methods but I cannot seem to figure out how to remove the loop on this one. </p> <p>Speedwise: It becomes an issue when I have millions of rows.</p> <p>Is there a way to v...
<p>The max of subtraction from each element in <code>leading</code> against all elements in <code>within</code> will be subtraction of <code>leading</code> from max of <code>within</code>. Hence, simply do -</p> <pre><code>within.max() - leading </code></pre> <p>No extra modules required.</p> <p>Timings -</p> <pre>...
python-3.x|numpy|cython|numba
3
373,582
56,528,760
How to remove numbers from all column names / headers in a dataframe
<p>Hi So I have a data frame with column names that end in '2018'</p> <p>I need to remove the years from these column names and am having some trouble. I also need to strip leading and trailing spaces from these column names as well.</p> <p>I've already tried the following:</p> <pre><code>df.columns.str.replace('\d+...
<p>You can try using regex as well..</p> <h2>Example DataFrame:</h2> <pre><code>&gt;&gt;&gt; df = pd.DataFrame.from_dict({'Name04': ['Chris', 'Joe', 'Karn', 'Alina'], 'Age04': [14, 16, 18, 21], 'Weight04': [15, 21, 37, 45]}) &gt;&gt;&gt; df Age04 Name04 Weight04 0 14 Chris ...
python|pandas|iteration|renaming
2
373,583
56,497,169
Masking only non-NaN values (Python)
<p>I have a multidimensions matrix and want to mask all values which are NOT NaN values. I know there is a mask for invalid where one can mask NaN values but I want the opposite - to only want to keep the NaN values. I've tried using where but am not sure if I am writing it correctly.</p> <p>Code, tt &amp; tt2 produ...
<p>I think you want:</p> <pre><code>tt2 = np.ma.masked_where(~np.isnan(tt), tt) </code></pre> <p>Note the use of <code>np.isnan</code> (i.e., note that <code>np.NaN == np.NaN</code> is <code>False</code>!), and the <em>not</em> (<code>~</code>) operator. In other words, this does, "mask where the array <code>tt</code...
python|numpy|matrix
1
373,584
56,510,691
I am getting error when importing torch and torch vision
<p>I installed torch and torchvision using pip3 on MAC. When I imported the same, getting the below error.</p> <p>Environment:</p> <pre><code>OS : macOS High Sierra Python : 3.7 pip : 3 Pytorch 1.1 </code></pre> <p>code:</p> <pre><code>import torch import torchvision </code></pre> <p>Error:</p> <blockquote> <p>...
<p>i think</p> <p>$ brew install libomp</p> <p>can help u, cause i solve the same problem by it. </p> <p>according</p> <p><a href="https://github.com/pytorch/pytorch/issues/20030" rel="nofollow noreferrer">github-issue-"libomp.dylib can't be loaded"</a></p>
python-3.x|conv-neural-network|pytorch
2
373,585
56,866,323
pandas string method to handle decimal places
<p>Here is my little sample dataframe:</p> <pre><code>import pandas as pd import numpy as np size = 10000 arr1 = np.tile([1/5000,1/12000,1/7000], (size,1)) df = pd.DataFrame(arr1, columns = ['col1','col2','col3']) df[['col1','col2','col3']] = df[['col1', 'col2', 'col3']].astype(str) </code></pre> <p>I want to use ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.DataFrame.round.html" rel="nofollow noreferrer">df.round()</a> method.</p> <ul> <li>If you want all column values to be rounded off to 10 decimal points:</li> </ul> <blockquote> <p>df.round(10)</p> </blockquote> <ul> <li>If you ...
python|python-3.x|string|pandas|decimal
2
373,586
56,472,233
Getting error while trying to fit model - The kernel appears to have died. It will restart automatically
<p>I am trying to fit a model using keras but I get the following error - </p> <p>WARNING:tensorflow:From /anaconda3/lib/python3.7/site-packages/tensorflow/python/ops/math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version. Instructions for updating: Use t...
<p>There could be many reasons for the Kernel dying, the most common one I encounter is because I have ran out of memory. </p> <p>If you are training a particularly large model try temporarily reducing it and bringing the batch_size down to 1</p> <p>(I don't think the warning message is related - this is just giving ...
python|tensorflow|jupyter
0
373,587
56,572,787
Is it possible to run regular python code on Google TPU?
<p>So I'm pretty new with Google TPU. From what I've already researched, it is optimized specifically for training machine learning models written on TensorFlow. Currently, I am trying to see how the TPU performs with other types of functions. These functions are not related to machine learning. I have been trying to ...
<p>I am afraid the presence or absence of tensorflow has no effect on how <code>np</code> operations are executed.</p> <p>In your example above when you specify </p> <pre><code>tpuOperation = tf.contrib.tpu.batch_parallel(multiplicationComputation, [], num_shards=8) </code></pre> <p>where <code>multiplicationComputa...
python|tensorflow|google-colaboratory|tpu
1
373,588
56,481,289
How to split dataframe into multiple dataframes based on header rows
<p>I need to split a dataframe into 3 unique dataframes based on a header-row reoccuring in the dataframe.</p> <p>My dataframe looks like:</p> <pre><code> 0 1 2 .... 14 0 Alert Type Response Cost 1 w1 x1 y1 z1 2 w2 x2 ...
<h3><code>np.split</code></h3> <pre><code>dfs = np.split(df, np.flatnonzero(df[0] == 'Alert')[1:]) </code></pre> <h3>Explanation</h3> <ul> <li><p>Find where <code>df[0]</code> is equal to <code>'Alert'</code></p> <pre><code>np.flatnonzero(df[0] == 'Alert') </code></pre></li> <li><p>Ignore the first one because we d...
python|pandas|dataframe|indexing|slice
3
373,589
56,613,536
Keras, Tensorflow, CuDDN fails to initialize
<p>I have a very powerful Windows PC (running Windows 10) which has 112GB memory, 16 cores and 3 X Geforce RTX2070 (Doesn't support SLI etc.). It is running CuDNN 7.5 + Tensorflor 1.13 + Python 3.7</p> <p>My issue is that I am getting the error below - whenever I try to run Keras model for training or to make predicti...
<p>On Tensorflow 2.0 and above, you can solve this issue by this way :</p> <pre><code>os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true' </code></pre> <p>or</p> <pre><code>physical_devices = tf.config.experimental.list_physical_devices('GPU') if len(physical_devices) &gt; 0: tf.config.experimental.set_memory_growth(p...
python|tensorflow|keras|cudnn
5
373,590
56,594,197
How to access multi-level index in pandas data frame?
<p>I would like to call those row with same index.</p> <p>so this is the example data frame, </p> <pre><code>arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']), np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])] df = pd.DataFrame(np.random.randn(8, 4), index=arrays) In [16...
<p>You can use MultiIndex slicing (use <code>slice(None)</code> instead of colon):</p> <pre><code>df = df.loc[(slice(None), 'one'), :] </code></pre> <p>Result:</p> <pre><code> 0 1 2 3 bar one -0.424972 0.567020 0.276232 -1.087401 baz one 0.404705 0.577046 -1.715002 -1.03926...
python|pandas|dataframe|multidimensional-array
5
373,591
56,660,893
How do I get the position of the cell whose values I've just printed?
<p>SO I'm using pandas and need to get the position of each element in the dataframe o.</p> <p>I've tried iloc and index() but I haven't been able to get it to work. I'm a newbie to this.</p> <pre><code>o=data['Opposition'].tail(10).dropna() o.astype('str') for i in o: print("Opposition cell number:",o.index(...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_indexer.html" rel="nofollow noreferrer"><code>Index.get_indexer</code></a>:</p> <pre><code>out = data.index.get_indexer(o.index) </code></pre>
python|pandas|dataframe
0
373,592
56,716,223
How to calculate monthly average with python?
<p>I have a dataframe with days and downloads per user:</p> <pre><code>dates downloadsperuser 2004-01-02 12.51118760757315 2004-01-03 6.990049751243781 2004-01-04 6.8099547511312215 2004-01-05 22.513349514563107 2004-01-06 22.348538011695908 2004-01-07 23.895180722891567 2004-01-08 21.765680473372782 ...
<p>First calculate month and year then groupby to find mean :</p> <pre><code>df['month'] = pd.to_datetime(df['date']).dt.month df['year'] = pd.to_datetime(df['date']).dt.year df.groupby(['year','month'],as_index=False).mean() </code></pre>
python|pandas
3
373,593
56,456,721
Numpy load.txt does not convert value to integer
<p>If I run the following code on a windows laptop with numpy 1.16.2, it works. However, when I run this code on a mac with numpy 1.16.4 or 1.16.2, it doesn't and gives the following error:</p> <blockquote> <p>invalid literal for int() with base 10: '34.623659...'</p> </blockquote> <p>We have tried installing diffe...
<p>You need <code>float</code>:</p> <pre><code>A = np.loadtxt('ex2data1.txt', delimiter=',', dtype =float, max_rows = 5).astype(int) </code></pre>
python|numpy
6
373,594
56,729,635
What that mean this message when I update tensorflow and keras in Anaconda Prompt ? Is wrong or Okay?
<p>(tensorflow) C:\Users\Ruben>conda update tensorflow Collecting package metadata: done Solving environment: done</p> <h1>All requested packages already installed.</h1> <p>C:\Users\Ruben>SET DISTUTILS_USE_SDK=1</p> <p>C:\Users\Ruben>SET MSSdk=1</p> <p>C:\Users\Ruben>SET platform=</p> <p>C:\Users\Ruben>IF /I [AMD6...
<p>ECHO "WARNING: Did not find VS in registry or in VS140COMNTOOLS env var - your compiler may not work"</p> <p>Got this warning message after i installed KERAS using Anaconda Prompt. Just make sure KERAS is the last you install otherwise you won't be able to install others eg. Pyinstaller or Nuitka.</p>
tensorflow|keras|anaconda
2
373,595
56,531,206
How to create an array of multiples of Pi to use the Cosine function
<p>I want to create an array of numbers from -Pi to +Pi with a step size of Pi/4. However, using <code>linspace</code> does not give me the accuracy I want, I am guessing it's a problem with the data type.</p> <pre class="lang-py prettyprint-override"><code>arr = np.linspace(-math.pi,math.pi,math.pi/4) print(math.cos(...
<p>The last parameter into <code>np.linspace</code> is the number of samples, not the size of them. In your case, you want 9 samples.</p> <pre><code>arr = np.linspace(-math.pi,math.pi,9) print(arr) </code></pre> <p>Output: </p> <pre><code>[-3.14159265 -2.35619449 -1.57079633 -0.78539816 0. 0.78539816 1.5...
python|numpy
1
373,596
56,737,166
Padding spaces to strings in a series with variable lenght
<p>I am trying to pad "_" on both side of string in a dataframe series.</p> <p>Here is the dataframe.</p> <pre><code>A cat dog rat </code></pre> <p>So i used this</p> <pre><code>A.str.pad(5, side='both', fillchar="_") </code></pre> <p>Output</p> <pre><code>A _cat_ _dog_ _rat_ </code></pre> <p>but now I got a ser...
<p>Basic pandas operations will give you what you want</p> <pre><code>'_' + df['A'].astype(str) + '_' </code></pre> <p>Output:</p> <pre><code>0 _cat_ 1 _dog_ 2 _rat_ 3 _crocodile_ 4 _moose_ </code></pre>
python|python-3.x|pandas
2
373,597
56,549,483
Can I save a Pandas DataFrame with a Tkinter File Dialog?
<p>I am fairly new to programming, and even newer to Tkinter.</p> <p>I am setting up a GUI that works with an SQL Server to allow front end users to retrieve, update, and delete certain information.</p> <p>Currently I have everything communicating and working correctly, but I have a function that exports a list of th...
<p>10 months ago this was posted, but I hope this answer can help a fellow novice googling around for this answer as well.</p> <p>How I solved this was noticing the asksaveasfile function outputs a value that contains the user specified file path and file name. For example:</p> <p>&lt; closed file u'E:Filepath/Anothe...
python|sql|pandas|tkinter
2
373,598
56,856,761
How to read single column of xlsx file into a dataframe?
<p>I have an .xlsx file with 5 sheets, each sheet has 4 columns and I need to read the first column of the 5th sheet into a column of a dataframe.</p> <p>I've tried this:</p> <p><code>df = read_excel('file_path.xlsx', sheet_names='sheet_5', index_col='column_name'</code></p> <p>However this seems to copy the whole s...
<p>Thanks to <a href="https://stackoverflow.com/users/4238408/quang-hoang">@Quang Hoang's</a> comment, I found the solution. </p> <pre><code>df = pd.read_excel('file_path.xlsx', sheet_name, usecols=['column_name']) </code></pre> <p>The <code>usecols</code> option in <code>read_excel</code> only read in the column I w...
python|excel|pandas|dataframe|xlsx
1
373,599
56,571,000
Calculate cumulative sum from last non-zero entry in python
<p>I have a numeric series like [0,0,0,0,1,1,1,0,0,1,1,0]. I would like to calculate the numeric sum from the last non-zero values. i.e the cumsum will be reset to zero once a zero entry occurs.</p> <pre><code>input: [0,0,0,0,1,1,1,0,0,1,1,0] output:[0,0,0,0,1,2,3,0,0,1,2,0] </code></pre> <p>Is there a built-in pyth...
<p>You can do it with <a href="https://docs.python.org/3/library/itertools.html#itertools.accumulate" rel="nofollow noreferrer"><code>itertools.accumulate</code></a>. In addition to passing an iterable as the first argument, it accepts an optional 2nd argument that should be a 2 argument function where the first argume...
python|pandas|numpy|cumsum
9