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
359,200
26,933,467
I want to count number of observations within each subject in PANDAS dataframe
<p>I am quite new to using PANDAS and python in general.</p> <p>I have a hierarchical data set with several subjects, each of whom have some number of observations. The total df is about half a million rows.</p> <p>I want to calculate the observations number...</p> <pre><code>## toy problem d = {'one' : Series(['a'...
<p>You could use the <a href="http://pandas.pydata.org/pandas-docs/version/0.15.0/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>GroupBy.cumcount</code> method</a>:</p> <pre><code>In [14]: df['j'] = df.groupby('one').cumcount() In [15]: df Out[15]: one two j 0 a 1.1 0 1 a 2.5 1...
python|loops|pandas
2
359,201
27,408,716
AttributeError in Py2exe
<p>I made my <code>py</code> file executable using <code>py2exe</code>. My <code>setup.py</code> is as follows:</p> <pre><code>from distutils.core import setup import py2exe setup(windows=['main.py']) </code></pre> <p>When I tried to run <code>main.exe</code>, I get an error and was referred to <code>main.log</code>...
<p>Was running into the same issue with pandas, but I got it working after updating to the most recent version.</p> <p>It seems this error was recently addressed, and was resolved in Pandas 15.2 <a href="https://github.com/pydata/pandas/issues/8602" rel="nofollow">https://github.com/pydata/pandas/issues/8602</a></p>
python|numpy|pandas|py2exe|attributeerror
0
359,202
27,230,705
Calculating the mean of groups in python/pandas
<p>My grouped data looks like:</p> <pre><code>deviceid time 01691cbb94f16f737e4c83eca8e5f5e5390c2801 January 10 022009f075929be71975ce70db19cd47780b112f April 566 August 210 Jan...
<p>You an specify the level in the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mean.html" rel="nofollow"><code>mean</code></a> method:</p> <pre><code>s.mean(level=0) # or: s.mean(level='deviceid') </code></pre> <p>This is equivalent to grouping by the first level of the index and tak...
python|pandas|data-analysis
3
359,203
27,013,532
Pandas read_csv reading time offset strings
<p>I have a text file with data with columns like '10:15.3' meaning 10 minutes 15.3 seconds after some canonical event. When I read this with read_csv, I'm getting strings:</p> <pre><code>&gt;&gt;&gt; df.time.head() 0 08:32.0 1 08:38.0 2 08:39.0 3 08:43.0 4 09:15.0 Name: time, dtype: object &gt;&gt;&gt...
<p>You can use the <code>datetime.time</code> object. To get this you provide: hours, minutes, seconds, microseconds. These are provided as integers, so you just need to int cast the relevant part of each string to the datetime.date constructor. </p> <p>So in your case:</p> <pre><code>import datetime df = pd.read_cs...
python|pandas
1
359,204
27,210,575
Reshaping Dataframe without ID variable
<p>I have a pandas dataframe that looks like this:</p> <p><b>var | info</b> <br> id | 1 <br> author | A <br> title | B <br> id | 2 <br> author | C <br> title | D <br></p> <p>How can I make it into wide format?</p> <p><b>id | author | title </b><br> 1 | A | B <br> 2 | C | ...
<p>You can use the function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.repeat.html" rel="nofollow"><code>repeat</code></a> on Series to duplicate the <code>id</code> values in groups of three rows, and then use <a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html" rel="n...
python|pandas|reshape
1
359,205
27,099,543
how to add packages like numpy,scipy and others to the sublime 2 python?
<p>I am uinsg sublime 2 on a windows machine and not figure out how can I manage and add different python packages into the sublime 2 python? I have multiple versions of python on my machine and it seems sublime is using my python 2.7 ( i dont remember if I set that). I also have REPL up and running but I can not make ...
<p>To install packages such as pyGame, you need to download the installer and run it. Since you have multiple versions of Python, you will need to select the required version in the installer.</p> <p>A link to pyGame: <a href="http://www.pygame.org/download.shtml" rel="nofollow">http://www.pygame.org/download.shtml</a...
python-2.7|numpy|sublimetext2|sublime-text-plugin|sublimerepl
0
359,206
27,151,546
How to filter by month, day, year with Pandas
<p>I create the DataFrame with:</p> <p><code>df = pandas.read_csv("data.csv", sep=';', parse_dates = 1, dayfirst = True)</code></p> <p>I then get the following results:</p> <pre><code> Qty System_created Total 0 2 2014-10-14 08:13:46.000 21.76 1 ...
<p>So long as your pandas version is <code>0.15</code> or higher then the following would work assuming your <code>dtype</code> is already a datetime:</p> <pre><code>In [167]: df[df.System_created.dt.day == 5] Out[167]: Qty System_created Total index 5 2 2014-11-05 ...
python|pandas
11
359,207
27,065,133
Pandas merge giving error "Buffer has wrong number of dimensions (expected 1, got 2)"
<p>I am trying to do a pandas merge and get the above error from the title when I try to run it. I am using 3 columns to match on whereas just before I do similar merge on only 2 columns and it works fine.</p> <pre><code>df = pd.merge(df, c, how=&quot;left&quot;, left_on=[&quot;section_term_ps_id&quot;, &quot;...
<p>As mentioned in the comments, you have a dupe column:</p> <p><img src="https://i.stack.imgur.com/9kb4c.jpg" alt="enter image description here"></p>
python|pandas|dataframe|data-structures
43
359,208
26,977,076
pandas unique values multiple columns
<pre><code>df = pd.DataFrame({'Col1': ['Bob', 'Joe', 'Bill', 'Mary', 'Joe'], 'Col2': ['Joe', 'Steve', 'Bob', 'Bob', 'Steve'], 'Col3': np.random.random(5)}) </code></pre> <p>What is the best way to return the unique values of 'Col1' and 'Col2'?</p> <p>The desired output is </p> <...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.unique.html" rel="noreferrer"><code>pd.unique</code></a> returns the unique values from an input array, or DataFrame column or index.</p> <p>The input to this function needs to be one-dimensional, so multiple columns will need to be combined. The...
python|pandas|dataframe|unique
270
359,209
27,117,923
How to efficiently sum numpy arrays after multiply them?
<p>Actually I need to compute:</p> <pre><code>S_i = sum(U_j * U_j.transpose) * K_i </code></pre> <p>where </p> <pre><code>U_j is a n * k dim matrix, K_i is a n * n dim matrix, j != i, i = 1, 2, ..., n </code></pre> <p>And I used loops like this:</p> <pre><code>import numpy as np for i in xrange(n): temp = n...
<pre><code>import numpy as np n, k = 30, 40 U = np.random.random((n, n, k)) K = np.random.random((n, n, n)) def using_loops(U, K): S = np.empty((n, n, n)) for i in xrange(n): temp = np.zeros((n, n)) for j in xrange (n): if j != i: temp += np.dot(U[j], U[j].T) ...
arrays|for-loop|numpy|add|multiplication
3
359,210
27,046,786
CountVectorizer() in scikit-learn Python gives Memory error when feeding big Dataset. Same code with Smaller dataset works fine, what am I missing?
<p>I am Working on Two Class Machine Learning Problem. Training Set contains 2-Millions Rows of URL(Strings) and Label 0 and 1. Classifier LogisticRegression() should predict any of two labels when testing datasets are passed. <strong>I am getting 95% accuracy results when i use smaller dataset i.e 78,000 URL and 0 and...
<p>IIRC the max_features is only applied after the whole dictionary is computed. The easiest way out is to use the <code>HashingVectorizer</code> that does not compute a dictionary. You will lose the ability to get the corresponding token for a feature, but you shouldn't run into memory issues any more.</p>
python|numpy|machine-learning|scikit-learn|feature-extraction
4
359,211
26,964,705
Artifact when plotting multiindex pandas dataframe
<p>I have my data organized into a multiindex dataframe. Ex: </p> <pre><code> Sweep Time Primary Secondary x720nm x473nm PMTShutter Sweep0001 0.00000 -87.429810 -4.882812 0.000610 0.000305 0.000000 0.00005 -87.445068 -4.882812 0...
<p><code>data.Time['Sweep001':'Sweep0002']</code> is concatenating <code>data.Time['Sweep001']</code> with <code>data.Time['Sweep002']</code>. Thus the time values are going from 0 to N then 0 to N again. <code>plt.plot</code> is thus drawing a line from <code>t=N</code> back to <code>t=0</code> causing the artifact.<...
python|pandas|plot
1
359,212
27,115,491
Subclassing datetime64
<p>How can I subclass from numpy datetime64 ? For instance using the standard datetime I can easily subclass:</p> <pre><code>import datetime as dt class SubFromDateTime(dt.datetime): def __new__(self): return dt.datetime.__new__(self, 2012, 1, 1) print type(SubFromDateTime()) &gt;&gt;&gt; &lt;class '__...
<p>I ended up subclassing ndarray which creates a datetime64 array. Works like a charm for my purposes. In case anyone is interested here the code:</p> <pre><code>import numpy as np class Date64(np.ndarray): def __new__(cls, data): data = np.asarray(data, dtype='datetime64') if (data.dtype != 'dat...
python|numpy|subclass|datetime64
3
359,213
27,417,033
Fitting a Sine Wave in Python with Data in a List
<p>I have a list of about 100 numbers. I know that the data reasonably fits some sine function. I'd like to create some kind of curve. Ideally, I'd like to extract the amplitude, phase, and frequency. Any suggestions or ideas?</p> <p>for example: inputList = [x1,...,x100]</p> <p>and I'm trying to figure out some ...
<p>I am not going to give you code, but this is probably what I would try. Success is highly dependant on how good your data is. For the last step, to get the final values for amplitude, frequency and phase, you could use some optimization framework. It's just that this usually requires a pretty good initial solution. ...
python|numpy|curve-fitting
1
359,214
14,694,941
subset a date-time df in pandas python
<p>Basic question, but I keep running into issues here.</p> <p>I have a df:</p> <pre><code>df: val date 2012-01-01 4.2 2012-01-02 3.7 2012-01-03 6.2 2012-01-04 1.2 2012-01-05 2.4 2012-01-06 2.3 2012-01-08 4.5 </code></pre> <p>As you can see, 2012-01-07 does not exist. If I were to write: </...
<p>To grab the sub-DataFrame with dates below 20120107 you could use:</p> <pre><code>In [11]: df[:'2012-01-07'] Out[11]: val date 2012-01-01 4.2 2012-01-02 3.7 2012-01-03 6.2 2012-01-04 1.2 2012-01-05 2.4 2012-01-06 2.3 </code></pre> <p>To pick the last row using <a href="https://stackov...
python|pandas
1
359,215
14,792,397
Gaussian blur image histogram of Y channel
<p>I'm new to computer vision and image processing, anyway I'm trying to calculate the histogram of image y_channel which has previously been blurred with cv2.GaussianBlur and converted from BGR to YCr-cb color space. However the end result isn't quite what I was expecting, it doesn't seems to have the typical look of...
<p>It actually was a issue that occurs with to bright illumination as @tcaswell suggested to me. Under different conditions the Y histogram looks a lot like a Gaussian one.</p>
python|opencv|numpy|matplotlib|computer-vision
0
359,216
14,416,660
pandas dataframe row change type
<p>I'm dealing with a balance sheet which I've parsed into pandas using:</p> <pre><code> table = xls_file.parse('Consolidated_Balance_Sheet') table.ix[:, 1] 0 None 1 None 2 $ 3,029 3 1989 5 None 6 $ 34,479 </code></pre> <p>I'm trying to identify...
<p>You are just printing these and not <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a>-ing them to the DataFrame, here's one way to do it:</p> <p>Create a function to do the striping (if unicode) or leave it if already a number:</p> <pre><...
python|parsing|pandas|floating-accuracy
3
359,217
14,878,110
How to find all zeros of a function using numpy (and scipy)?
<p>Suppose I have a function <code>f(x)</code> defined between <code>a</code> and <code>b</code>. This function can have many zeros, but also many asymptotes. I need to retrieve <strong>all</strong> the zeros of this function. What is the best way to do it?</p> <p>Actually, my strategy is the following:</p> <ol> <li>...
<p>Why are you limited to <code>numpy</code>? Scipy has a package that does exactly what you want:</p> <p><a href="http://docs.scipy.org/doc/scipy/reference/optimize.nonlin.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/optimize.nonlin.html</a></p> <p>One lesson I've learned: numerical programming is ...
python|numpy|scipy
3
359,218
14,813,530
Poisson confidence interval with numpy
<p>I'm trying to put Poisson continuous error bars on a histogram I'm making with matplotlib, but I can't seem to find a numpy function that will given me a 95% confidence interval assuming poissonian data. Ideally the solution doesn't depend on scipy, but anything will work. Does such a function exist? I've found a lo...
<p>I ended up writing my own function based on <a href="http://en.wikipedia.org/wiki/Poisson_distribution#Confidence_interval" rel="noreferrer">some properties I found on Wikipedia</a>. </p> <pre><code>def poisson_interval(k, alpha=0.05): """ uses chisquared info to get the poisson interval. Uses scipy.stats ...
python|math|numpy|statistics|scipy
11
359,219
25,311,271
Pandas set format for single dataframe
<p><strong>Question</strong></p> <p>Is there a way to format only a specific dataframe?</p> <p>I've seen examples of formatting specific columns of a single dataframe (Example 1) or set the entire pandas library to a default option (Example 2). However, I haven't seen an option for formatting a specific dataframe wi...
<p>I think your best bet is to pass a formatter to <code>to_string</code></p> <pre><code>In [283]: print df.to_string(float_format='${:,.2f}'.format) 0 1 2 3 0 $0.53 $0.01 $0.75 $0.61 1 $0.54 $0.33 $0.42 $0.47 2 $0.28 $0.67 $0.71 $0.53 </code></pre> <p>Although that won't stay with the dataframe. Y...
python|pandas
5
359,220
25,217,510
How to see top n entries of term-document matrix after tfidf in scikit-learn
<p>I am new to scikit-learn, and I was using <code>TfidfVectorizer</code> to find the tfidf values of terms in a set of documents. I used the following code to obtain the same.</p> <pre><code>vectorizer = TfidfVectorizer(stop_words=u'english',ngram_range=(1,5),lowercase=True) X = vectorizer.fit_transform(lectures) </c...
<p>Since version 0.15, the global term weighting of the features learnt by a <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html#sklearn.feature_extraction.text.TfidfVectorizer" rel="noreferrer"><code>TfidfVectorizer</code></a> can be accessed through the attri...
python|numpy|scikit-learn|tf-idf|top-n
64
359,221
25,076,440
Drawing the same random numbers in numpy
<p>I got the following piece of code:</p> <pre><code>import numpy as np rand_draw1 = np.random.rand(5,4) rand_draw2 = rand_draw1 rand_draw2[0:2,0:4] = np.random.rand(2,4) </code></pre> <p>My intention is to have the variables rand_draw1 and rand_draw2 to be identical except for the first two rows. However they turn o...
<p>Just assigning <code>rand_draw2 = rand_draw1</code> <strong>does not</strong> create a copy, it simply binds the name <code>rand_draw2</code> to the <em>same object</em> already bound to <code>rand_draw1</code>:</p> <pre><code>&gt;&gt;&gt; rand_draw2 = rand_draw1 &gt;&gt;&gt; rand_draw2 is rand_draw1 True </code></...
python|numpy|random|random-seed
4
359,222
25,173,887
Pandas to_sql can't write to schema besides 'public' on PostgreSQL
<p>I'm trying to write the contents of a data frame to a table in a schema besides the 'public' schema. I followed the pattern described in <a href="https://stackoverflow.com/questions/24189150/pandas-writing-dataframe-to-other-postgresql-schema">Pandas writing dataframe to other postgresql schema</a>:</p> <pre><code>...
<p><strong>Update</strong>: starting from pandas 0.15, writing to different schema's is supported. Then you will be able to use the <code>schema</code> keyword argument:</p> <pre><code>df.to_sql('test', engine, schema='a_schema') </code></pre> <hr> <p>As I said in the linked <a href="https://stackoverflow.com/questi...
python|sql|postgresql|pandas|sqlalchemy
11
359,223
25,228,168
what is the most efficient way to synchronize two large data frames in pandas?
<p>I would like to synchronize two very long data frames, performance is key in this use case. The two data frames are indexed in chronological order (this should be exploited to be as fast as possible) using datetimes or Timestamps.</p> <p>One way to synch is provided in this example:</p> <pre><code>import pandas as...
<p>If you need to synchronize then, use <code>align</code>, docs are <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.align.html?highlight=align#pandas.DataFrame.align" rel="noreferrer">here</a>. Otherwise merge is a good option.</p> <pre><code>In [18]: N=100000 In [19]: df1=pd.DataFram...
python|performance|pandas|dataframe
5
359,224
24,999,708
Import CSV file into numpy as data table resulting in incorrect shape
<p>I'm trying to use numpy to read in a CSV file as a data table, but having problems. </p> <p>This is my CSV file, in full:</p> <pre><code>week,count,is_successful,percent,percent_tablet,percent_desktop 1,2005,0,23,32,45 1,3805,1,18,22,55 2,1872,0,35,22,43 2,2990,1,22,21,57 3,2005,0,24,24,48 3,3805,1,27,21,52 </code...
<p>When you have named columns, the array created by <code>genfromtxt</code> is a one-dimensional <a href="http://docs.scipy.org/doc/numpy/user/basics.rec.html" rel="nofollow">structured array</a>. Access columns using the column names as keys, e.g. <code>data['week']</code>.</p> <p>You can get a two-dimensional view...
python|csv|numpy
2
359,225
25,141,838
Compiling Cython .pyx files on a non-english Ubuntu (unicode error)
<p>So, I guess this is a bug in one of the involved packets and I want to report it, but I don't really understand where exactly the error is so I'm trying to define it and describe the solution. </p> <p>I recently upgraded to Ubuntu 14.4 and was very happy to be able to use it in my own language, when I ran into an e...
<p>I've managed to compile <a href="https://gist.github.com/Dschoni/4bebd2e6f283adf2563e" rel="nofollow">your example</a> after I replaced the arguments to <code>setup</code></p> <pre><code>ext_modules=linext, cmdclass = {'build_ext': build_ext} </code></pre> <p>with the version that is encouraged in the <a href="htt...
python|gcc|numpy|encoding|cython
1
359,226
30,734,731
How do I create a pivot table in Pandas where one column is the mean of some values, and the other column is the sum of others?
<p>Basically, how would I create a pivot table that consolidates data, where one of the columns of data it represents is calculated, say, by <code>likelihood percentage</code> (0.0 - 1.0) by taking the mean, and another is calculated by <code>number ordered</code> which sums all of them?</p> <p>Right now I can specify...
<p>You could supply to <code>aggfunc</code> a dictionary with <code>column:funtion</code> (<code>key:value</code>) pairs:</p> <pre><code>df = pd.DataFrame({'a':['a','a','a'],'m':[1,2,3],'s':[1,2,3]}) print df a m s 0 a 1 1 1 a 2 2 2 a 3 3 df.pivot_table(index='a', values=['m','s'], aggfunc={'m':pd.Seri...
python|pandas|dataframe
0
359,227
30,657,115
optimize pandas query on multiple columns / multiindex
<p>I have a very large table (currently 55 million rows, could be more), and I need to select subsets of it and perform very simple operations on those subsets, lots and lots of times. It seemed like pandas might be the best way to do this in python, but I'm running into optimization problems.</p> <p>I've tried to cr...
<p>So there are 2 issues here.</p> <p>This is an artifice that makes the syntax a little nicer</p> <pre><code>In [111]: idx = pd.IndexSlice </code></pre> <p>1) Your <code>.query</code> does not have the correct precedence. The <code>&amp;</code> operator has a higher precedence than comparison operators like <code>&...
python|numpy|pandas|bigdata
2
359,228
30,314,744
Segmenting a series of Timedeltas to a minute by minute graph (pandas)
<p>I have a dataframe with the index as a Timedelta, ranging from 0 to 5 minutes, and a column of floating point numbers.</p> <p>Here's an example subset:</p> <pre><code>32 0.740283 34 0.572126 36 0.524788 38 0.509685 40 0.490219 42 0.545977 44 0.444170 46 1.098387 48 2.209113 51 1.426835 53 1.536439 55 1...
<p>Pandas only provides plotting functions for convenience. To have full control, you need to use Matplotlib directly.</p> <p>As a workaround, you could just use datetime instead of timedelta as index. As long as your timespans are within minutes, Pandas won't plot the day or month.</p> <p>To use your example, this w...
python|pandas|matplotlib|dataframe
1
359,229
30,563,072
Geopandas Spatial Joins - unable to import geopandas.tools
<p>I currently do my GIS work in Python using a combination of Pandas and ArcPy. I recently heard of Geopandas and am interested in learning to use this as an alternative to ArcPy for basic geoprocessing operations (spatial joining points to polygons, intersecting polygons, etc). </p> <p>I've installed Geopandas and i...
<p>Geopandas 0.1.0 which is the latest documented release of geopandas was released <a href="https://github.com/geopandas/geopandas/releases" rel="nofollow">on 13 Jul 2014</a> does not contain the tools package <a href="https://github.com/geopandas/geopandas/tree/master/geopandas/tools" rel="nofollow">according to gith...
python|pandas|geopandas
3
359,230
30,369,632
Python- Compute the sum of numerical characters of every string in a dataframe
<p>so I have a dataframe with a column "dname". It contains many rows of 2LD domain names. i.e. <code>[123ask , example92 , what3ver]</code>.</p> <p>I want to find the number of digits for every string in every row.</p> <p>So, to create a new column in the dataframe with values i.e. <code>[3 , 2 , 1]</code>.</p> <p>...
<p>You almost had it. </p> <pre><code>df = {'dname':["123ask", "example92" , "what3ver"]} df['numeric'] = [sum (x.isdigit() for x in b) for b in df['dname']] print df['numeric'] #&gt;&gt;&gt; [3, 2, 1] </code></pre>
python|pandas|dataframe
1
359,231
30,381,396
how to output results of python parallel computing (ipython-parallel or multiprocessing) to a pandas dataframe?
<p>Simple question: all tutorials I've read show you how to output the result of a parallel computation to a list (or at best a dictionary) using either ipython.parallel or multiprocessing. </p> <p>Could you point me to a simple example of outputing the result of a computation to a shared pandas dataframe using either...
<p>You are asking <code>multiprocessing</code> (or other python parallel modules) to output to a data structure that they don't directly output to. If you use a <code>Pool</code>, from any of the parallel packages, the best you are going to get a list (using <code>map</code>) or an iterator (using <code>imap</code>). ...
python|pandas|parallel-processing|multiprocessing|ipython-parallel
2
359,232
26,595,546
Sorting columns in pandas dataframe
<p>I have a dataframe with column headers "DIV3, DIV4, DIV5 ... DIV30"</p> <p>My problem is that pandas will sort the columns in the following way: </p> <pre><code> DIV10, DIV11, DIV12..., DIV3, DIV4, DIV5 </code></pre> <p>Is there a way to arrange it such that the single digit numbers come first? I.e.:</p> <pre><c...
<p>You can solve this by <a href="https://stackoverflow.com/q/4836710/190597">sorting in "human order"</a>:</p> <pre><code>import re import pandas as pd def natural_keys(text): ''' alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's im...
python|pandas
3
359,233
26,846,034
Querying with custom columns along with normal columns on Pandas DataFrame
<p>This is my example data frame and </p> <blockquote> <blockquote> <blockquote> <p>df </p> </blockquote> </blockquote> </blockquote> <pre><code>index,Customer_MailID,Event_Quantity,Amount_Final,Channel,Week_Name,Venue_Name,Event_Genre1 1,aa@hotmail.com,2,172,Web,MON-TO-THU,Tivoli Cinema: Extreem,CO...
<p>In your example, data every Customer_MailID is used only once. I presume in the real data there are multiples which would make sum(Amount_Final) != Amount_Final. If that presumption is correct, then one solution is to create a column to carry the sum of Amount_Final and then use that in your subset. </p> <p>Somethi...
python-3.x|pandas
0
359,234
26,596,363
trouble installing opencv 2.4.10, python 2.7.5 on win7
<p>i tried to install python-numpy-opencv as described in opencv official tutorial, but i have some issues regarding opencv -.-</p> <p><a href="http://docs.opencv.org/trunk/doc/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html" rel="nofollow">http://docs.opencv.org/trunk/doc/py_tutorials/py_setup/py_s...
<p>You need <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">NumPy</a> 1.9. Get an installer <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy" rel="nofollow">here</a> and an <a href="http://en.wikipedia.org/wiki/OpenCV" rel="nofollow">OpenCV</a> installer <a href="http://www.lfd.uci.edu/~gohlke/pyth...
python|opencv|numpy
0
359,235
26,871,083
How can I vectorize the averaging of 2x2 sub-arrays of numpy array?
<p>I have a very a very large 2D numpy array that contains 2x2 subsets that I need to take the average of. I am looking for a way to vectorize this operation. For example, given x: </p> <pre><code># |- col 0 -| |- col 1 -| |- col 2 -| x = np.array( [[ 0.0, 1.0, 2.0, 3.0, 4.0, 5.0],...
<p>If we form the reshaped matrix <code>y = x.reshape(2,2,3,2)</code>, then the (i,j) 2x2 submatrix is given by <code>y[i,:,j,:]</code>. E.g.:</p> <pre><code>In [340]: x Out[340]: array([[ 0., 1., 2., 3., 4., 5.], [ 6., 7., 8., 9., 10., 11.], [ 12., 13., 14., 15., 16., 17.], ...
python|arrays|numpy|vectorization|aggregation
9
359,236
26,859,791
Select all adjacent elements without copying the numpy array
<p>I have a bunch of points with format <code>point = [time, latitude, longitude]</code>.</p> <p>So, I have got myself a numpy array that looks something like -</p> <pre><code>points = numpy.array([ [t_0, lat_0, lon_0], [t_1, lat_1, lon_1], [t_2, lat_2, lon_2], ... [t_n, lat_n, lon_n], ]) </code><...
<p>If I understand correctly, this is just about shifting the array:</p> <p>If you <code>nan</code>-pad the <code>points</code> array on both sides, you can do</p> <pre><code>next_points = points[1:] prev_points = points[:-1] d_next = distance_function(next_points, points[:-1]) d_prev = distance_function(points[1:],...
python|arrays|numpy
0
359,237
26,683,166
Stacked plot from pandas dataframe
<p>I would like to create a stacked bar plot from the following dataframe:</p> <pre><code> VALUE COUNT RECL_LCC RECL_PI 0 1 15686114 3 1 1 2 27537963 1 1 2 3 23448904 1 2 3 4 1213184 1 3 4 5 14185448 3 2 5...
<p>So your problem was that the dtypes were not numeric so no aggregation function will work as they were strings, so you can convert each offending column like so:</p> <pre><code>df['col'] = df['col'].astype(int) </code></pre> <p>or just call <code>convert_objects</code> on the df:</p> <pre><code>df.convert_objects...
python|pandas|stacked
2
359,238
39,352,108
Does the Inception Model have two softmax outputs?
<p>The Inception v3 model is shown in this image:</p> <p><img src="https://4.bp.blogspot.com/-TMOLlkJBxms/Vt3HQXpE2cI/AAAAAAAAA8E/7X7XRFOY6Xo/s1600/image03.png" alt="Inception v3 Model"></p> <p>The image is from this blog-post:</p> <p><a href="https://research.googleblog.com/2016/03/train-your-own-image-classifier-w...
<p>Section 4 of the <a href="http://arxiv.org/pdf/1512.00567v3.pdf" rel="noreferrer">paper</a> you cite is about <em>auxiliary classifiers</em>. These are classifiers added to the lower levels of the network, that improve training by mitigating the vanishing gradients problem and speedup convergence. For running infere...
tensorflow|deep-learning|softmax
5
359,239
39,187,788
Find rows with non zero values in a subset of columns in pandas dataframe
<p>I have a datframe with 4 columns of strings and others as integers. Now I need to find out those rows of data where at least one of the column is a non-zero value (or > 0).</p> <pre><code>manwra,sahAyaH,T7,0,0,0,0,T manwra, akriti,T5,0,0,1,0,K awma, prabrtih,B6, 0,1,1,0,S </code></pre> <p>My output should be</p> ...
<p>Here is an alternative solution which uses <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.select_dtypes.html" rel="noreferrer">select_dtypes()</a> method:</p> <pre><code>In [41]: df[(df.select_dtypes(include=['number']) != 0).any(1)] Out[41]: 0 1 2 3 4 5 6 7 ...
python|pandas|dataframe
10
359,240
39,333,316
When tf.variable() is realized in tensorflow
<p>I started to learn tensorflow two days ago and when I see the sharing variable in tensorflow's offical website I was confused by the tf.Variable(). After I create one variable as follows: </p> <p><code>demo = tf.Variable(tf.random_normal([5, 5, 32, 32]), name="test")</code></p> <p>I wonder whether demo consists of...
<p>Because it's how Tensorflow works.</p> <p>You first define a computational graph, in which you describe the interactions between variables, placeholders and operations. Note that the initialization of a variable is an operation and as such is placed into the graph description.</p> <p>To compute anything, the graph...
tensorflow
1
359,241
39,302,508
Time formats match but still getting error. ValueError: time data 'Time' does match format specified pd.to_datetime
<p>my data column looks like this:</p> <pre><code>0 Time 1 2014-07-28 00:17:35 2 2014-07-28 00:18:05 3 2014-07-28 01:50:54 4 2014-07-28 01:51:24 5 2014-07-28 01:53:57 6 2014-07-28 01:54:56 </code></pre> <p>my code looks like this:</p> <pre><code>df['Epoch'] = pd.to_datetime(df['Time'], format = "%Y-%m-%d %H:%M...
<p>Your dataframe is wrongly loaded: your header is interpreted as a row and is the first row of your dataframe. <code>pd.to_datetime</code> tries to transform the string 'Time' found row 0.</p> <p>Load correctly your dataframe by getting the row 0 loaded as a header instead.</p> <p>Something like this can move the f...
python|pandas|time|python-datetime
0
359,242
39,201,783
Speed up multilple matrix products with numpy
<p>In python I have 2 three dimensional arrays: </p> <p><code>T</code> with size <code>(n,n,n)</code></p> <p><code>U</code> with size <code>(k,n,n)</code></p> <p><code>T</code> and <code>U</code> can be seen as many 2-D arrays one next to the other. I need to multiply all those matrices, ie I have to perform the fol...
<p>Carefully looking into the iterators and how they are involved in those dot product reductions, we could translate all of those into one <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> implementation like so -</p> <pre><code>H = np.einsum('ij...
python|numpy
3
359,243
39,276,249
merge two dataframe columns into 1 in pandas
<p>I have 2 columns in my data frame and I need to merge it into 1 single column</p> <pre><code>Index A Index B 0 A 0 NAN 1 NAN 1 D 2 B 2 NAN 3 NAN 3 E 4 C 4 NAN </code></pre> <p>there will al...
<p><strong><em>Option 1</em></strong></p> <pre><code>df.stack().dropna().reset_index(drop=True) 0 A 1 D 2 B 3 E 4 C dtype: object </code></pre> <p><strong><em>Option 2</em></strong> If Missing values are always alternating</p> <pre><code>df.A.combine_first(df.B) Index 0 A 1 D 2 B 3 E 4 ...
python|pandas|dataframe
9
359,244
39,254,418
Is it possible to write text and charts into an excel along with dataframes from pandas?
<p>I have been able to write write multiple dataframes into each worksheet in a workbook, but I need to be able to add charts and heatmaps alongside them. Is there a way to do that?</p> <p>I've been using this to write the dataframes into the xlsx:</p> <pre><code>writer = pd.ExcelWriter('pandas_simple.xlsx', engine='...
<p>Here is an <a href="https://xlsxwriter.readthedocs.io/example_pandas_chart.html" rel="nofollow">example of adding a dataframe and a chart</a> to an Excel file using XlsxWriter and Pandas, from the XlsxWriter docs.</p> <p>Here is an <a href="https://xlsxwriter.readthedocs.io/example_pandas_conditional.html" rel="nof...
pandas|charts|heatmap|xlsx|xlsxwriter
1
359,245
39,180,685
Why do tensorflow and keras SimpleRNN layers have a default activation of tanh
<p>I want to use a relu activation for my simple RNN in a tensorflow model I am building. It sits on top of a deep convolutional network. I am trying to classify a sequence of images. I noticed that the default activation in both keras and tensorflow source code is tanh for simple RNNs. Is there a reason for this? ...
<p>RNNs can suffer from both exploding gradient and vanishing gradient problems. When the sequence to learn is long, then this can be a very delicate balance tipping into one or the other quite easily. Both problems are caused by exponentiation - each layer multiplies by weight matrix and derivative of activation, so i...
tensorflow|keras
9
359,246
39,184,442
pandas.DataFrame set all string values to nan
<p>I have a <code>pandas.DataFrame</code> that contain string, float and int types.</p> <p>Is there a way to set all strings that cannot be converted to float to <code>NaN</code> ?</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code> A B C D 0 1 2 5 7 1 0 4 NaN 15 2 ...
<p>You can use <code>pd.to_numeric</code> and set <code>errors='coerce'</code></p> <p><a href="http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.to_numeric.html#pandas-to-numeric" rel="noreferrer">pandas.to_numeric</a></p> <p><code>df['D'] = pd.to_numeric(df.D, errors='coerce')</code></p> <p>Which w...
python|string|pandas|dataframe
10
359,247
39,379,987
How can one replace missing values with median or mode in SFrame?
<p>I'm going through the Graphlab documentation and I am trying to figure out how to duplicate the pandas functionality were na values are replaced by the median, the mean, or the mode, etc... In pandas you simply do this by: df.dropna().median() or df.dropna().mean() etc....</p> <p>But the documentation on the dr...
<p>There is one, but only the mean is available, not the median. Have a look at: <code>graphlab.toolkits.feature_engineering.NumericImputer</code> (<a href="https://turi.com/products/create/docs/generated/graphlab.toolkits.feature_engineering.NumericImputer.html" rel="nofollow">doc</a>)</p> <blockquote> <p>Impute mi...
python|pandas|graphlab
2
359,248
39,189,605
Conditional length of a binary data series in Pandas
<p>Having a DataFrame with the following column:</p> <pre><code>df['A'] = [1,1,1,0,1,1,1,1,0,1] </code></pre> <p>What would be the best vectorized way to control the length of "1"-series by some limiting value? Let's say the limit is 2, then the resulting column 'B' must look like:</p> <pre><code> A B 0 1 1 1 ...
<p>One fully-vectorized solution is to use the <code>shift</code>-<code>groupby</code>-<code>cumsum</code>-<code>cumcount</code> combination<sup>1</sup> to indicate where consecutive runs are shorter than 2 (or whatever limiting value you like). Then, <code>&amp;</code> this new boolean Series with the original column:...
python|pandas|dataframe|vectorization
3
359,249
39,361,341
Broadcast an operation along specific axis in python
<p>In python, suppose I have a square <code>numpy</code> matrix <strong>X</strong>, of size <em>n x n</em> and I have a <code>numpy</code> vector <strong>a</strong> of size <em>n</em>. </p> <p>Very simply, I want to perform a broadcasting subtraction of <strong>X - a</strong>, but I want to be able to specify along wh...
<p>Let's generate arrays with random elems</p> <p>Inputs :</p> <pre><code>In [62]: X Out[62]: array([[ 0.32322974, 0.50491961, 0.40854442, 0.36908488], [ 0.58840196, 0.1696713 , 0.75428203, 0.01445901], [ 0.27728281, 0.33722084, 0.64187916, 0.51361972], [ 0.39151808, 0.6883594 , 0.938...
python|arrays|numpy|matrix|array-broadcasting
15
359,250
39,048,355
'numpy.float64' object is not iterable - meanshift clustering
<p>python newbie here. I am trying to run this code but I get the error message that the object is not iterable. Would appreciate some advice on what I am doing wrong. Thanks.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import pandas as pd temp = pd.read_csv("file.csv", encoding='latin-1') xy...
<pre><code>new_centroid = np.average(in_bandwidth, axis=0) </code></pre> <p>Is assigning a scalar to <code>new_centroid</code> then you are trying to <code>tuple(scalar)</code> which is throwing the error.</p> <pre><code>tuple(2.) </code></pre> <blockquote> <pre><code>------------------------------------------------...
python|pandas|numpy|cluster-analysis|mean-shift
1
359,251
39,010,594
Jupyter Notebook - Matplotlib keep running
<p>I just started to use <code>Jupiter Notebook</code> to learn <code>Python</code>. while I am trying out <code>matplotlib</code> with this basic code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() </code></pre> <p>The kernel just keep ru...
<p>To Visualize the plots created by the matplotlib in <strong>Jupiter Notebook or ipython notebook</strong> you have add one extra line at the beginning.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt %matplotlib inline </code></pre> <p>If your matplotlib <strong>version is above 1.4, and you...
python|numpy|matplotlib|ipython|jupyter-notebook
2
359,252
39,030,738
CUDA histogram2d not working
<p>Due to a seeming lack of a decent 2D histogram for CUDA (that I can find... pointers welcome), I'm trying to implement it myself with pyCUDA.</p> <p>Here's what the histogram should look like (using Numpy):</p> <p><a href="https://i.stack.imgur.com/ThdCb.png" rel="nofollow noreferrer"><img src="https://i.stack.img...
<p>The array being allocated for the output array for the CUDA section used Numpy's default float64 instead of float32, so memory was twice as large as expected. Here's the new histogram output:</p> <p><a href="https://i.stack.imgur.com/whUpm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/whUpm.png...
python|numpy|cuda|pycuda|histogram2d
1
359,253
39,135,099
Can you "force" `scipy.stats.norm.rvs` to output positive values?
<p>This may be a naive question but I couldn't find any posts about it so I thought it may be useful to ask. I found a distribution that may fit my data well but all of my data points are positive in real life (- ones are impossible).</p> <p><strong>Is there a way to force <code>.rvs</code> to output only positive val...
<p>You appear to be looking for <a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.stats.truncnorm.html#scipy.stats.truncnorm" rel="nofollow">truncnorm</a>: a truncated normal continuous random variable.</p> <p>For example, try:</p> <pre><code>&gt;&gt;&gt; from scipy import stats &gt;&gt;&gt; i...
numpy|random|scipy|statistics|distribution
4
359,254
39,410,205
How can l convert tuple to integer to do some calculations?
<p>l have 41 years dataset including 10 columns and l m trying to plot these data with Matplotlib and l m able to plot columns without error. However , l would like to produce different kind of graphes like yearly average pcp ,monthly average pcp and yearly sum of pcp etc. l got data from columns and l have problem wi...
<p>Thats because you are trying to convert a decimal number into an int</p> <p>If you want to use the exact value you can use <code>float(tuple(y[5][0]))</code> Or else if you want to truncate the value you can use <code>int(float(tuple(y[5][0])))</code></p>
python|csv|numpy|matplotlib
1
359,255
39,272,267
Local Maxima with circular window
<p>I am trying to compute a local maxima filter on a matrix, using a circular kernel. The output should be the cells that are local maximas. For each pixel in the input 'data', I need to see if it is a local maximum by a circular window, thus returning a value of 1, otherwise 0.</p> <p>I have this code, built upon ans...
<p>The second parameter of <code>sc.filters.generic_filter()</code> should be a function, you are passing it the value returned by the <code>local_maxima(data, np.shape(kernel))</code> call, i.e. a matrix.</p> <p>I'm a bit confused as to what exactly you have done here, but I think you do not need the <code>generic_fi...
python|numpy|filtering
2
359,256
38,980,714
Pandas setting multi-index on rows, then transposing to columns
<p>If I have a simple dataframe:</p> <pre><code>print(a) one two three 0 A 1 a 1 A 2 b 2 B 1 c 3 B 2 d 4 C 1 e 5 C 2 f </code></pre> <p>I can easily create a multi-index on the rows by issuing:</p> <pre><code>a.set_index(['one', 'two']) three one two...
<p>Yes! It's called transposition.</p> <pre><code>a.set_index(['one', 'two']).T </code></pre> <p><a href="https://i.stack.imgur.com/S1jTq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/S1jTq.png" alt="enter image description here"></a></p> <hr> <p>Let's borrow from @ragesz's post because they used a muc...
python|pandas|dataframe|transpose|multi-index
9
359,257
19,686,434
strange behaviour of numpy masked array
<p>I have troubles understanding the behaviour of numpy masked array.</p> <p>Here is the snippet that puzzles me for two reasons:</p> <pre><code>arr = numpy.ma.array([(1,2),(3,4)],dtype=[("toto","int"),("titi","int")]) arr[0][0] = numpy.ma.masked </code></pre> <ol> <li>when doing this nothing happens, no mask is app...
<p>The purpose of a masked array is to tell for any operation that some elements of the array are invalid to be used, i.e. masked.</p> <p>For example, you have an array:</p> <pre><code>a = np.array([[2, 1000], [3, 1000]]) </code></pre> <p>And you want to ignore any operations with the elements <code>&gt;100</code>. ...
python|arrays|numpy|masking
1
359,258
19,322,863
Pandas: Change datatype in columns and then multiply two columns
<p>I have imported two files as DataFrames and want to multiply 'New Price' but '12 Month Quantity Ordered'. I though that I had successfully changed the columns from strings to a number in order to be able to multiply these two columns. And it seems that I did something wrong.</p> <p>I want to change the data types s...
<p>The convert function does not keep the converted data but returns it. You must save it back over the old data if you want it.</p> <pre><code>Comparisonfile['New Price'] = Comparisonfile['New Price'].convert_objects(convert_numeric =True) Comparisonfile['12 Month Quantity Ordered'] = Comparisonfile['12 Month Quant...
python|pandas
1
359,259
19,741,997
DataFrame.drop not dropping expected rows in Pandas
<p>I have a Pandas DataFrame that includes rows that I want to drop based on values in a column "population":</p> <pre><code>data['population'].value_counts() general population 21 developmental delay 20 sibling 2 general population...
<p><a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.drop.html"><code>dataFrame.drop</code></a> accepts an index (list of labels) as a parameter, not a mask.<br> To use <code>drop</code> you should do:</p> <pre><code>data = data.drop(data.index[data.population == 'sibling']) </code></pre> <...
python|pandas
7
359,260
19,518,012
How to add element from user in numpy matrix from user for nxn matrix?
<pre><code>from numpy import matrix new = matrix([raw_input("enter element in matrix. . ")]) # add element from user </code></pre> <p>take row and col size from user and like in c matrix how to enter nxn matrix using numpy</p> <pre><code>matrix([for i in row: for j in col: raw_input(add &gt;data)]) </code></pre>
<p>In contrast to the other answer, I would use <code>ast.literal_eval</code> instead of the built-in <code>eval</code> as it is <em>much</em> safer. If you want you can have the user input <code>(n,m)</code> the matrix dimension ahead of time. It is also a good idea to check that the number of elements matches what yo...
python|numpy|matrix
1
359,261
12,785,834
Wrap a C program in Python that reads custom file into a 2d array
<p>I have a stand-alone c program that takes a char* file name, opens the file, reads and decodes it into a 2d array. We do not know the length of the array until the file is read. The program mallocs memory.</p> <p>I would like to have a python extension that returns a 2d numpy integer array, given the file name:</...
<p><a href="http://pypi.python.org/pypi/SIP" rel="nofollow"><code>SIP</code></a> (<a href="http://www.riverbankcomputing.com/static/Docs/sip4/introduction.html" rel="nofollow">here</a> too) can be used to create Python bindings for C libraries.</p> <p>But that's probably an overkill; it would probably be easier to rea...
python|c|numpy|swig|cython
1
359,262
13,000,427
Reshape Long Format Multivalue Dataframes with Pandas
<p>I would like to turn:</p> <pre><code>DateTime ColumnName Min Avg Max 2012-10-14 11:29:23.810000 Percent_Used 24 24 24 2012-10-14 11:29:23.810000 Current_Count 254503 25...
<p>There is a <code>melt</code> in <code>pandas.core.reshape</code>:</p> <pre><code>In [52]: melted = reshape.melt(df, id_vars=['DateTime', 'ColumnName']) In [53]: melted.set_index(['DateTime', 'ColumnName', 'variable']).value.unstack([1, 2]) Out[53]: ColumnName Percent_Used Current_Count Max ...
python|pivot|pandas|reshape
7
359,263
12,843,610
Python read text files in numpy array when empty or single line
<p>I am reading from text files with the code below:</p> <pre><code>import numpy as np my_data = np.genfromtxt(resultsDirectory+'/Points.txt', delimiter=' ') PointX = my_data[:,5] PointY = my_data[:,11] </code></pre> <p>My input files are typically like this -</p> <pre><code>ParamA : 0 ParamB : 7 ParamC : 0 ParamD :...
<p>Unfortunately, <code>genfromtxt</code> returns a 1D array if given a file with only one line, and returns a 2D array if given more than one line. You could handle the discrepancy by reshaping:</p> <pre><code>import numpy as np my_data = np.genfromtxt('data', delimiter=' ') if my_data.ndim == 1: my_data = my_dat...
python|numpy
3
359,264
13,072,259
Transforming Pandas dataframe
<p>I'm having a little trouble with this maybe someone could direct me in the right direction here. </p> <p>Suppose I have a data frame that looks as follows (actual dataset has many more entries and idents):</p> <pre><code> open ident 2011-01-01 00:00:00 -1.252090 df1 2011-01-01 01:00:00 -1...
<p>You can use the <code>pivot</code> function:</p> <pre><code>df.pivot(index='date', columns='variable', values='value') </code></pre> <p>For more info see: <a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html">http://pandas.pydata.org/pandas-docs/stable/reshaping.html</a></p>
python|pandas
13
359,265
29,324,735
NumPy random seed produces different random numbers
<p>I run the following code:</p> <pre><code> np.random.RandomState(3) idx1 = np.random.choice(range(20),(5,)) idx2 = np.random.choice(range(20),(5,)) np.random.RandomState(3) idx1S = np.random.choice(range(20),(5,)) idx2S = np.random.choice(range(20),(5,)) </code></pre> <p>The output I get is the follow...
<p>You're confusing <code>RandomState</code> with <code>seed</code>. Your first line constructs an object which you can then use as your random source. For example, we make</p> <pre><code>&gt;&gt;&gt; rnd = np.random.RandomState(3) &gt;&gt;&gt; rnd &lt;mtrand.RandomState object at 0xb17e18cc&gt; </code></pre> <p>an...
python|numpy|random
10
359,266
29,261,742
RBF Kernel on Masked array
<p>I wonder if there is a way to compute the Gaussian kernel of a numpy masked array? </p> <p>I import: </p> <pre><code>from sklearn.metrics.pairwise import rbf_kernel </code></pre> <p>If one uses a masked array and gives it as the input to the <code>rbf_kernel</code> function of scikit learn package the result is n...
<p>Scikit-learn doesn't support masked arrays. Computing the RBF kernel is really simple if you can compute euclidean distances, though.</p>
numpy|scikit-learn|mask|masked-array
4
359,267
29,173,321
Speeding up Loading of Pandas Sparse DataFrame
<p>I have a large pickled Sparse DataFrame that I generated, but since it was too big to hold in memory, I had to incrementally append as it was generated, as follows:</p> <pre><code>with open(data.pickle, 'ab') as output: pickle.dump(df.to_sparse(), output, pickle.HIGHEST_PROTOCOL) </code></pre> <p>Then in order...
<p>don't concat in a loop! This is a <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow">note</a> in the docs, maybe should be a warning</p> <pre><code>df_list = [] with open(data.pickle, 'rb') as pickle_file: try: while True: test = pickle.load(pickle_file) ...
python|pandas|pickle|concat|sparse-matrix
2
359,268
28,935,128
Why are CSV files smaller than HDF5 files when writing with Pandas?
<pre><code>import numpy as np import pandas as pd df = pd.DataFrame(data=np.zeros((1000000,1))) df.to_csv('test.csv') df.to_hdf('test.h5', 'df') ls -sh test* 11M test.csv 16M test.h5 </code></pre> <p>If I use an even larger dataset then the effect is even bigger. Using an <code>HDFStore</code> like below changes no...
<p>Briefly:</p> <ul> <li><p>csv files are 'dumb': it is one character at a time, so if you print the (say, four-byte) float 1.0 to ten digits you really use that many bytes -- but the good news is that csv compresses well, so consider <code>.csv.gz</code>.</p></li> <li><p>hdf5 is a <em>meta-format</em> and the <em>No ...
python|csv|pandas|hdf5|hdf
5
359,269
28,963,342
pandas - how to combine selected rows in a DataFrame
<p>I've been reading a huge (5 GB) gzip file in the form:</p> <pre><code> User1 User2 W 0 11 12 1 1 12 11 2 2 13 14 1 3 14 13 2 </code></pre> <p>which is basically a directed graph representation of connections among users with a certain weight W. Since the file is so big, I tr...
<p>There is probably a more concise way, but this works. The main trick is just to normalize the data such that User1 is always the lower number ID. Then you can use <code>groupby</code> since <code>11,12</code> and <code>12,11</code> are now recognized as representing the same thing.</p> <pre><code>In [330]: df = p...
python|pandas|networkx
2
359,270
29,032,937
Aggregate events with start and end times with Pandas
<p>I have data for a number of events with start and end times like this:</p> <pre><code>df = pd.DataFrame({'start': ['2015-01-05', '2015-01-10', '2015-01-11'], 'end': ['2015-01-07', '2015-01-15', '2015-01-13'], 'value': [3, 4, 5]}) df['end'] = pd.to_datetime(df['end']) df['start'] = pd.to_datetime(df['start']) </code...
<p>If I were using SQL, I would do this by joining an all-dates table to the events table, and then grouping by date. Pandas doesn't make this approach especially easy, since there's no way to left-join on a condition, but we can fake it using dummy columns and reindexing:</p> <pre><code>df = pd.DataFrame({'start': ['...
python|pandas
1
359,271
28,909,986
Memory leak in pandas when dropping dataframe column?
<p>I have some code like the following</p> <pre><code>df = ..... # load a very large dataframe good_columns = set(['a','b',........]) # set of "good" columns we want to keep columns = list(df.columns.values) for col in columns: if col not in good_columns: df = df.drop(col, 1) </code></pre> <p>The odd thing i...
<p>Make use of usecols argument while reading the large data frame to keep the columns you want instead of dropping them later on. Check here : <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.io.parsers.read_csv.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/dev/generated/pandas.io.parsers...
python|memory|numpy|pandas|memory-leaks
1
359,272
28,967,199
Adding days to column in pandas using separate column integers
<p>I've tried datetime.timedelta on the series, as well as pd.DateOffset. Neither works. I do know I could iterate over this dataframe and add them manually, but I was looking for a vectorized approach.</p> <p>Example:</p> <pre><code>d = {pd.Timestamp('2015-01-02'):{'days_delinquent':11}, pd.Timestamp('2015-01-15'):{...
<p>You can convert your <code>days_delinquent</code> column to <code>timedelta64[D]</code> (offset in days) and add it to the index, eg:</p> <pre><code>import pandas as pd d = {pd.Timestamp('2015-01-02'):{'days_delinquent':11}, pd.Timestamp('2015-01-15'):{'days_delinquent':23}} df = pd.DataFrame.from_dict(d,orient='i...
python|pandas
3
359,273
28,903,399
'Index' object has no attribute 'tz_localize'
<p>I'm trying to convert all instances of 'GMT' time in a time/date column ('Created_At') in a csv file so that it is all formatted in 'EST'. Please see below:</p> <pre><code>import pandas as pd from pandas.tseries.resample import TimeGrouper from pandas.tseries.offsets import DateOffset from pandas.tseries.index impo...
<p>Replace</p> <pre><code>cambridge.set_index('Created_At', drop=False, inplace=True) </code></pre> <p>with</p> <pre><code>cambridge.set_index(pd.DatetimeIndex(cambridge['Created_At']), drop=False, inplace=True) </code></pre>
python|pandas
3
359,274
29,320,873
Replace values of a numpy array by values from another numpy array
<p>i have a 1000 * 1000 numpy array with 1 million values which was created as follows : </p> <pre><code>&gt;&gt;import numpy as np &gt;&gt;data = np.loadtxt('space_data.txt') &gt;&gt; print (data) &gt;&gt;[[ 13. 15. 15. ..., 15. 15. 16.] [ 14. 13. 14. ..., 13. 15. 16.] [ 16. 13. 13. ..., 13. 15. ...
<p>In Python dicts are a natural choice for mapping from keys to values. NumPy has no direct equivalent of a dict. But it does have arrays which can do fast integer indexing. For example,</p> <pre><code>In [153]: keyarray = np.array(['S','M','L','XL']) In [158]: data = np.array([[0,2,1], [1,3,2]]) In [159]: keyarra...
python|numpy
8
359,275
33,558,467
Filter DataFrame of dtype object using pandas
<p>I'm required to parse data using the following operations.</p> <pre><code>data=[{'a': 1, 'b': {1: 1, 2: 2}, 'c': ['q', 'w', 'e', 'r', 't', 'y']}, {'a': 2, 'b': {1: 2, 2: 3}, 'c': ['q', 't', 'a', 'v', 'o', 'l']}] df = pd.DataFrame(data) </code></pr...
<p>You can use <code>apply</code> on the column to generate a boolean mask describing the desired columns, and then filter the DataFrame by this mask:</p> <pre><code>&gt;&gt;&gt; df[df.c.apply(lambda val: 'q' in val)] a b c 0 1 {1: 1, 2: 2} [q, w, e, r, t, y] 1 2 {1: 2, 2: 3} [q,...
python|json|pandas
1
359,276
33,947,886
Python (Pandas) calculate percent change
<p>I have the following dataset for numerous stocks, and am using the following formula to calculate the percent change <code>df7['Change']=(df7.Close.pct_change())*100</code></p> <p>However, I would like how I can modify this formula, or write a new one that will make the change as <code>NaN</code> the first time the...
<p>You could use groupby method:</p> <pre><code>df['Change'] = df.groupby('Symbol').Close.pct_change() In [20]: df Out[20]: Open High Low Close Volume \ Date 2015-11-02 711.059998 721.619995 705.849976 721.109985 1871100 2015-11-03 718.859985 724.650024 714.719971 ...
python|pandas
4
359,277
33,817,190
Intersection of Two LineStrings Geopandas
<p>Let's say I have the following to GeoDataFrames of linestrings, one of which represents roads and one of which represents contour lines.</p> <pre><code>&gt;&gt;&gt; import geopandas as gpd &gt;&gt;&gt; import geopandas.tools &gt;&gt;&gt; import shapely &gt;&gt;&gt; from shapely.geometry import * &gt;&gt;&gt; &gt;&...
<p>Notice that operations <code>unary_union</code> and <code>intersection</code> are made over the geometries inside the <code>GeoDataFrame</code>, so you lose the data stored in the rest of the columns. I think in this case you have to do it by hand by accessing each geometry in the data frames. The following code:</p...
python|shapely|geopandas
10
359,278
33,962,255
ValueError: invalid literal for float(): 17/08/2015
<p>I'm getting this error "ValueError: invalid literal for float(): 17/08/2015". This is the last row in the file I'm reading and it follows the same format as the others. The code for the script is below.</p> <p>I'm wondering. Is the error actually occurring throughout the file but it's being flagged as the only erro...
<p>The error occurs because you are trying to plot some stuff with dates as strings on the x-axis while <code>plt.plot()</code> expects numerical values. Hence it fails when it tries to convert <code>'17/08/2015'</code> to a float, which cannot work. </p> <p>You need to convert your x-values to <code>datetime</code> o...
python|numpy|matplotlib
5
359,279
33,648,733
pandas.concat forgets column names
<p>I'm trying to create a new <code>DataFrame</code> from columns of two existing frames but after the <code>concat()</code>, the column names are lost and I can't assign new ones:</p> <pre><code>import pandas import datetime dt = datetime.datetime df1 = pandas.DataFrame({'value': [1.1, 2.1], 'foo': ['a', 'b']}, ind...
<p>This is because:</p> <pre><code>df = pandas.concat([df1['value'], df2['value']]) </code></pre> <p>is concatenating 2 <code>Series</code> objects rather than dfs,</p> <p>if you did this:</p> <pre><code>In [201]: df = pd.concat([df1[['value']], df2[['value']]]) df Out[201]: value 2015-11-01 1.1 201...
pandas|merge|dataframe
5
359,280
33,646,005
Get first value of column in dataframe in pandas with offset indices
<p>I have a dataframe with offset indices and I'd like to access the first value of interested column:</p> <pre><code>df = pd.DataFrame({"a": [0,1,2], "b":[3,4,5]}, index=[5,6,7]) In [20]: df Out[20]: a b 5 0 3 6 1 4 7 2 5 </code></pre> <p>None of the .ix, .loc <a href="http://pandas.pydata.org/pandas-docs/...
<p>Use <code>iloc[0]</code> to access the first elements:</p> <pre><code>In [193]: print(df['a'].iloc[0]) print(df['b'].iloc[0]) 0 3 </code></pre> <p>or <code>head</code>:</p> <pre><code>In [194]: df.head(1) Out[194]: a b 5 0 3 </code></pre>
python|pandas
1
359,281
33,626,443
Comparing floats in a pandas column
<p>I have the following dataframe:</p> <pre><code> actual_credit min_required_credit 0 0.3 0.4 1 0.5 0.2 2 0.4 0.4 3 0.2 0.3 </code></pre> <p>I need to add a column indicating where actual_credit >= min_required_credit. The result would ...
<p>Due to imprecise float comparison you can <code>or</code> your comparison with <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.isclose.html" rel="noreferrer"><code>np.isclose</code></a>, <code>isclose</code> takes a relative and absolute tolerance param so the following should work:</p> <p...
python|pandas|floating-point|floating-point-comparison|inexact-arithmetic
45
359,282
33,653,635
Splitting strings in an array - python
<p>I have a pandas dataframe with an array variable that's currently made up of a two part string as in the example below. The first part is a datetime and the second part is a price. Records in the dataframe have different length price_trend arrays.</p> <pre><code>Id Name Color price_trend 1 ...
<p><code>df['price_trend'].apply(lambda x:[i.split(':') for i in x])</code></p> <pre><code>0 [['1420848000, 1.25'], [ '1440201600, 1.35'], [ '1443830400, 1.52']] 1 [['1403740800, 0.32'], ['1422057600, 0.25']] </code></pre>
python|pandas
0
359,283
33,748,619
convert python dict or csv file to a dataframe
<p>I have a dictionary dump out as csv as below. How I convert it to dataframe X,Y,SN as a header? I am thinking about writing a for loop and use split but it doesnt seem very elegant nor efficient...</p> <pre><code>"49,42",001C0BA79A44 "49,43",001C0BA79A46 "49,40",001C0BA79A40 "49,41",001C0BA79A42 "67,22",001C0BA791E...
<p>Don't use a <code>for</code> loop, adding rows to an existing dataframe isn't very efficient.</p> <pre><code>def split(string): return string.split(',', 1) df = pd.read_csv(file_path, header=None, names=['Cord', 'SN']) df['X'], df['Y'] = zip(*df.Cord.map(split)) df = df[['X', 'Y', 'SN']] </code></pre> <p>See...
python|numpy|dictionary|dataframe
1
359,284
33,573,408
Python-pandas Replace NA with the median or mean of a group in dataframe
<p>Suppose we have a df:</p> <pre><code> A B apple 1.0 apple 2.0 apple NA orange NA orange 7.0 melon 14.0 melon NA melon 15.0 melon 16.0 </code></pre> <p>to replace the NA, we can use <code>df[&quot;B&quot;].fillna(df[&quot;B&quot;].median())</code>, but it will fil...
<p>In pandas you may use <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation" rel="noreferrer"><code>transform</code></a> to obtain null-fill values:</p> <pre><code>&gt;&gt;&gt; med = df.groupby('A')['B'].transform('median') &gt;&gt;&gt; df['B'].fillna(med) 0 1.0 1 2.0 2 1.5 3 ...
python|numpy|pandas|dataframe
10
359,285
33,854,121
How to allocation a bunch of 2-D array into each grid as a time series Pandas.DataFrame?
<p>Here is my question:<br> I have some 2-D array data which represent the concentration of some chemical of each grid by the time, like follows:<br> <a href="http://i12.tietuku.com/4501009ea445c286.png" rel="nofollow noreferrer">http://i12.tietuku.com/4501009ea445c286.png</a>.<br> I want to extract the data of each gr...
<p>It looks you might be better off just create one dataframe, with f1, f2, f3 being different columns:</p> <pre><code>In [9]: K1 = np.random.rand(50,50) K2 = np.random.rand(50,50) K3 = np.random.rand(50,50) K_list = [K1, K2, K3] In [10]: df = pd.DataFrame(np.vstack([item.ravel() for item in K_list]).T, ...
python|numpy|pandas|matplotlib
1
359,286
33,651,788
Cosine similarity yields 'nan' values
<p>I was calculating a Cosine Similarity Matrix for sparse vectors, and the elements expected to be float numbers appeared to be 'nan'.</p> <p>'visits' is a sparse matrix showing how many times each user has visited each website. This matrix used to have a shape 1 500 000 x 1500, but I converted it into sparse matrix,...
<p>Try:</p> <pre><code>def norm(x): return np.sqrt((x.T*x).A) </code></pre> <p>I constructed a smaller sample <code>visits</code> matrix, and calculated <code>cosine_distance_matrix</code> with your code. Mine had the diagonal of 1s, and lots of <code>nan</code> on the off diagonal. I choose one of the <code>na...
python|numpy|sparse-matrix|similarity|cosine-similarity
0
359,287
33,546,828
Python translation of R's read.table 'text' argument
<p>In <code>R</code> if someone on SO posts a data frame as text: </p> <pre><code> x y 1 1 a 2 2 b 3 3 c </code></pre> <p>One would highlight and copy the data frame as is, and paste it into R to recreate it:</p> <pre><code>df &lt;- read.table(text=" x y 1 1 a 2 2 b 3 3 c", header=TRUE) </code></pre> <p>What is t...
<p>As @EdChurn suggested in the comments, the task is very simple and straightforward with <code>pandas</code>:</p> <ol> <li><p>Copy the data from the original source with Ctrl+C (or other method)</p></li> <li><p>In Python:</p> <pre><code>import pandas as pd df = pd.read_clipboard() &gt;&gt;&gt; df x y 1 1 a 2...
python|pandas
0
359,288
33,704,780
Python - most efficient way to generate combinations of large sets subject to criteria?
<p>I am trying to generate all possible combinations of financial instruments within a portfolio subject to a boundary condition. </p> <p>Eg, suppose I have a collection of lists which represent allocations to a portfolio subject to a minimum and maximum percentage of the total portfolio size for each instrument: </...
<p>(Note: code available at: <a href="http://lpaste.net/145213" rel="nofollow">http://lpaste.net/145213</a>)</p> <p>First of all I would represent the percentages as integer values to avoid floating point roundoff errors.</p> <p>Secondly, the most efficient method will use bounding to avoid looking at portfolios whic...
python|numpy|combinations|combinatorics
4
359,289
33,596,216
how to split one column into many columns and count the frequency
<p>Here is the question I have in mind, given a table</p> <pre><code> Id type 0 1 [a,b] 1 2 [c] 2 3 [a,d] </code></pre> <p>I want to convert it into the form of:</p> <pre><code> Id a b c d 0 1 1 1 0 0 1 2 0 0 1 0 2 3 1 0 0 1 </code></pre> <p>I need a very eff...
<p>try this:</p> <pre><code>pd.get_dummies(df.type.apply(lambda x: pd.Series([i for i in x]))) </code></pre> <p>to explain:</p> <pre><code>df.type.apply(lambda x: pd.Series([i for i in x] </code></pre> <p>gets you a column for index position in your lists. You can then use <code>get dummies</code> to get the count ...
pandas|dataframe
1
359,290
33,612,074
Converting MATLAB Slicing into Python using Numpy
<p>I am having trouble converting some MATLAB code into python. I am trying to build a signal by adding in shifted copies of base signal into a much longer one. The code that works in MATLAB is </p> <pre><code>function [time, signal] = generateRandomSignal(pulse,data,samples,Tb) N = length(data); time = linspace(0,N...
<p>Change your definition of <code>signal</code> to <code>signal = zeros(time.size)</code>. Unlike Matlab, NumPy's 1D arrays have shape <code>(N,)</code>, not <code>(N,1)</code>.</p>
python|arrays|matlab|numpy|scipy
3
359,291
23,946,120
gropuby and remove specified groups in pandas DataFrame
<p>I have a pandas DataFrame:</p> <pre><code>df=pd.DataFrame({'A':[1,1,2,2,3,3],'B':['c','t','k','c','c','k']}) </code></pre> <p>I need to group df by A and remove A groups where B ='t'. What is pandas <code>groupby</code> syntax to do this? In my example answer are A groups 2 and 3.</p>
<p>A <code>groupby/filter</code> would work here (filter only return groups that meet a certain condition). So, for example, you could do the following:</p> <pre><code>&gt;&gt;&gt; df.groupby('A').filter(lambda x: (x['B'] != 't').all()) A B 2 2 k 3 2 c 4 3 c 5 3 k </code></pre> <p><code>(x['B'] != 't').a...
python|pandas
5
359,292
23,810,367
Ignore character while importing with pandas
<p>I could not find such an option in the documentation. A measuring device spits out everything in Excel:</p> <pre class="lang-none prettyprint-override"><code> &lt;&gt; A B C 1 2 3 </code></pre> <p>When I delete the "&lt;>" characters manually everything works fine. Is there a way to circumvent that ...
<p>Expanding on <a href="https://stackoverflow.com/users/9872839/peruz">Peruz's</a> answer:-</p> <p>For your case, using regex</p> <p><code>df = pd.read_csv(filename, sep=&quot;(?&lt;!&lt;&gt;)\s+&quot;, engine='python') </code></p> <p>This should read in the columns properly, except that the first column would be name...
python|pandas|csv
3
359,293
23,788,179
Is there a GPU accelerated numpy.max(X, axis=0) implementation in Theano?
<p>Do we have a GPU accelerated of version of <code>numpy.max(X, axis=None)</code> in Theano. I looked into the documentation and found <code>theano.tensor.max(X, axis=None)</code>, but it is 4-5 times slower than the numpy implementation. </p> <p>I can assure you, it is not slow because of some bad choice of matrix s...
<p>The previous answer is partial. The suggestion should not work, as the work around is the one used in the final compiled code. There is optimization that will do this transformation automatically.</p> <p>The title of the question isn't the same as the content. They differ by the axis argument. I'll answer both ques...
numpy|pycuda|theano|deep-learning
5
359,294
23,619,253
pandas combining 2 dataframes with different date indices
<p>Let's say I've pulled csv data from two seperate files containing a date index that pandas automatically pulled which was one of the original columns.</p> <pre><code>import pandas as pd df1 = pd.io.parsers.read_csv(data1, parse_dates = True, infer_datetime_format=True, index_col=0, names=['A']) df2 = pd.io.parsers....
<p>By default, pandas DataFrame method 'join' combines two dataframes using 'inner' merging. You want to use 'outer' merging. Your join line should read:</p> <pre><code>df1 = df1.join(df2, how='outer') </code></pre> <p>See <a href="http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.DataFrame.join.ht...
python|datetime|pandas
4
359,295
23,597,700
matplotlib 3d scatter from 2d numpy array vertices error
<p>I'm stumped as to why this is not working. I am pulling a bunch of floating point data in to a numpy array from a csv file, and I just want to create a 3d scatter plot based from 3 of the columns in the array.</p> <pre><code>#import data from the csv file data = np.genfromtxt('data.csv', delimiter=',', dtype=float...
<p>You can use the <code>scatter3D()</code> method of the <code>Axes3DSubplot</code> object:</p> <pre><code>from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter3D(data[:,1], data[:,2], data[:,7], c='r', marker='0') </code></pre>
python|numpy|matplotlib|plot|mplot3d
2
359,296
23,897,186
Opposite of numpy.delete
<p>I have a numpy array which looks like: <code>[3,65,7,83,2,4]</code> and I want to keep indices <code>[1,3,5]</code>. Which would give me <code>[65, 83, 4]</code>. Is there a way to do this in Numpy? </p> <p>This would essentially be the opposite of the <code>numpy.delete</code> function.</p>
<p>Use fancy indexing:</p> <pre><code>&gt;&gt;&gt; a = np.array([3,65,7,83,2,4]) &gt;&gt;&gt; a[[1, 3, 5]] array([65, 83, 4]) </code></pre>
numpy
8
359,297
23,838,453
Example order in machine learning algorithms (Scikit Learn)
<p>I'm doing some classification with Python and scikit-learn. I have a question which doesn't seem to be covered in the documentation: if I'm doing, for example, classification with SVM, does the order of the input examples matter? If I have binary labels, will the results be less accurate if I put all the examples...
<p>No, the ordering of the patterns in the training set do not matter. While the ordering of samples can affect stochastic gradient descent learning algorithms (like for example the one for the NN) they are in most cases coded in a way that ensures internal randomness. SVM on the other hand is globally convergant and i...
python|numpy|machine-learning|scipy|scikit-learn
3
359,298
23,879,562
Multinomial distribution in PyMC
<p>I am a newbie to pymc. I have read the required stuff on github and was doing fine till I was stuck with this problem. I want to make a collection of multinomial random variables which I can later sample using mcmc. But the best I can do is </p> <pre><code>rv = [ Multinomial("rv", count[i], p_d[i]) for i in xrange(...
<p>Think you want something like this:</p> <pre><code>from pymc import * p_d = [[0.7, 0.3], [0.5, 0.1, 0.4], [0.4, 0.6], [0.8, 0.2]] count =[26, 39, 20, 10] rv = [ Multinomial("rv"+str(i), count[i], p_d[i]) for i in xrange(0, len(count)) ] m = MCMC(rv) m.sample(100) print m.trace('rv0')[:] </code></pre> <p>Also m...
python|numpy|bayesian|pymc|multinomial
1
359,299
22,653,773
Python: Select multiple columns in a dataframe from another dataframe without loop
<p>I have a dataframe (df1) that has 3000 columns. Each columns corresponds to a stock ticker. I export in a DataFrame (df2) using <code>pd.read_csv</code> a csv file of 500 stock tickers (1 column and 500 rows, excluding the index). How can I extract into a new datafame from df1 the 500 columns that match the stock ti...
<p>You can use loc directly to select some columns from your DataFrame (to use @waitingkuo's example):</p> <pre><code>In [11]: df1.loc[:, df2.stock] # equivalent to df1[df2.stock] Out[11]: s1 s3 0 1 3 1 4 6 2 7 9 3 10 12 </code></pre>
python|pandas
4