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
366,600
42,631,417
How to release tensors from memory when not in need anymore?
<p>I have hypothetical graph which has a series of computations as follows:</p> <pre><code>a_0 = tf.placeholder() a_1 = some_op_1(a_0) a_2 = some_op_2(a_1) a_3 = some_op_3(a_2) </code></pre> <p>Observe that when computing <code>a_3</code>; <code>a_0</code> and <code>a_1</code> are not needed and hence they can be dis...
<p>TensorFlow uses reference counting to release the memory used by a tensor as soon as it is no longer used. The values of <code>a_0</code> and <code>a_1</code> will be deleted as soon as there are no more references to them, and in the latest builds of TensorFlow (post-1.0 nightly builds) some operations will even re...
tensorflow
3
366,601
42,852,536
Tensorflow v0.12 image not displying after resized
<p>I manage to display an image using the following code:</p> <pre><code>import os import tensorflow as tf from tensorflow.python.framework import ops from tensorflow.python.framework import dtypes import numpy as np import glob import fnmatch import matplotlib.pyplot as plt from PIL import Image def test1(path): ...
<p>Manage to fix it</p> <pre><code>import os import tensorflow as tf from tensorflow.python.framework import ops from tensorflow.python.framework import dtypes import numpy as np import glob import fnmatch import matplotlib.pyplot as plt from PIL import Image def test1(path): filename_queue = tf.train.string_inp...
python|image|tensorflow
0
366,602
42,711,014
Tensorflow py3.5 install from source: "not a supported wheel"?
<p>Previously I've installed tensorflow from source on Ubuntu 16.04 for Python 2.7, and it worked fine.</p> <p>For Python 3.5 (I made a new anaconda environment), I'd installed one of the binary versions, but I was getting warning messages.. </p> <p><strong>EDIT, using the downloaded binary wheel, the messages I get ...
<p>This error caused by running <code>sudo -H pip install ...</code> to install the compiled PIP package. Anaconda uses a virtual environment, which overrides the path to the <code>pip</code> executable. However, the <code>sudo</code> command <a href="https://unix.stackexchange.com/q/83191/220140">does not preserve the...
python|linux|python-3.x|tensorflow
4
366,603
42,603,427
Error when Submitting Job Training in Google Cloud ML
<p>I'm currently trying to submit a job training on Google Cloud ML with the Facenet (a Tensorflow library for face recognition). I'm currently trying this<a href="https://github.com/davidsandberg/facenet/wiki/Classifier-training-of-inception-resnet-v1" rel="nofollow noreferrer"> (link is here) </a> part of the library...
<p>When you are running on Cloud ML Engine you are running in a remote environment; so the file paths will not be the same as the local environment. If you need to import python modules you need to include them in the Python package you build and then import them using the package name.</p> <p>For docs on how to build...
tensorflow|google-cloud-ml|google-cloud-ml-engine
1
366,604
42,992,852
extract week, month from DD-MON-YYYY hh.mm.ss AM/PM [Oracle Date] in Pandas Python
<p>I am trying to Read a CSV File in Python - Pandas.</p> <pre><code>import pandas as pd </code></pre> <p><code>import datetime as dt</code></p> <p>then i need to extract week month for further processing</p> <pre><code>df = pd.read_csv('C:\Python\dm.csv',low_memory=False) df["SUBMITDATE"]=pd.to_datetime(df["SUBMIT...
<p>You can parse dates with python functions like this (change to your date format accordingly):</p> <pre><code>def parse_datetime(x): ''' Parses datetime with timezone formatted as: `[day/month/year:hour:minute:second zone]` Example: `&gt;&gt;&gt; parse_datetime('13/Nov/2015:11:45:42 +000...
python|csv|pandas
1
366,605
27,178,899
How to find strings in pandas
<p>I need to find all the rows that have strings that begin with:"EC4" my attempt was:</p> <pre><code>dataset[dataset['Postcode'].str.contains("EC4")] </code></pre> <p>However, sometimes the string contains EC4 also in the other characters..</p> <p>More in general, having a string: "abcd abcd", ho do I get only thos...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#method-summary" rel="nofollow"><code>startswith</code></a> instead of <code>contains</code>:</p> <pre><code>dataset[dataset['Postcode'].str.startswith("EC4")] </code></pre> <p>Note that <code>contains</code> accepts any regex pattern, so </p> <pre...
python|string|pandas|rows
1
366,606
27,251,451
Python Memory Leak with Struct and Numpy
<p>Continuation of <a href="https://stackoverflow.com/questions/27236967/python-memory-leak-using-binascii-zlib-struct-and-numpy">Python Memory Leak Using binascii, zlib, struct, and numpy</a> but with example code that correctly illustrates the issue I have.</p> <pre><code>import struct import zlib import binascii im...
<p>This link <a href="http://bugs.python.org/issue14596" rel="nofollow">http://bugs.python.org/issue14596</a> was very helpful. The issue was with the struct module caching format strings. If i explicitly create a Struct object, use it, and then delete it the issue goes away.</p> <pre><code>import struct import zlib...
python|numpy|memory-leaks|struct
3
366,607
27,153,970
slice 2D numpy array based on condition
<p>I have an numpy array</p> <pre><code>import numpy as np a = np.array([ [999, 999, 999, 999, 999, 999, 999, 999, 999, 999], [999, 999, 999, 1, 2, 3, 4, 999, 999, 999], [999, 999, 999, 5, 6, 7, 8, 999, 999, 999], [999, 999, 999, 9, 10, 11, 12, 999, 999, 999], [999, 999, 999, 999, 999, 999, 999, 999, 999, 999]]) </co...
<p>You can do the following:</p> <pre><code>&gt;&gt;&gt; mask = (a!=999) &gt;&gt;&gt; dim1 = np.any(mask, axis=1).sum() &gt;&gt;&gt; a[mask].reshape(dim1, -1) array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]]) </code></pre> <p>This of course assume that you only have a single contiguous box i...
arrays|python-2.7|numpy|slice
1
366,608
26,981,772
numpy/pandas: test float64 arrays are equal up to significant digits
<p>I have two pandas data frames in which I store money amounts, i.e. decimal numbers with at most 15 significant decimal digits. Since float64 has a precision of 15 significant decimal digits, this should be lossless.</p> <p><strong>How do I compare the values of two such dataframes for equivalence up to the 15 signi...
<p>there's actually a numpy function for this:</p> <pre><code>np.allclose </code></pre> <p>definition/usage:</p> <pre><code>np.allclose(a, b, rtol=1e-05, atol=1e-08) </code></pre>
python|numpy|floating-point|floating-accuracy|floating-point-precision
0
366,609
26,949,535
Output and Import list of lists to Pandas DataFrame
<p>I want to be able to append to a <code>.txt</code> file each time I run a function.</p> <p>The output I am trying to write to the function is something like this:</p> <pre><code>somelist = ['a','b','b','c'] somefloat = -0.64524 sometuple = (235,633,4245,524) output = tuple(somelist,somefloat,sometuple) (the output...
<p>One way to do this is to separate your columns with a custom separator such as <code>'|'</code></p> <p>Say:</p> <pre><code>somelist = ['a','b','b','c'] somefloat = -0.64524 sometuple = (235,633,4245,524) output = str(somelist) + "|" + str(somefloat) + "|" + str(sometuple) </code></pre> <p>(if you wanna have many ...
python|pandas|import|output
1
366,610
27,022,699
How can I plot a surface using a function with a single vector or array input using matplotlib?
<p>I want to plot a function R^2 -> R using numpy and matplotlib.</p> <p>In most matplotlib examples, a function with two inputs is used, as here:</p> <pre><code>import numpy as np import matplotlib.pyplot as mplot import matplotlib.cm as cm from mpl_toolkits.mplot3d import Axes3D as m3d def f(x,y,sign=1.0): out...
<p>If the input <code>x</code> is a 3-D array representing a regular mesh, you can do, assuming a shape <code>(2, m, n)</code>:</p> <pre><code>def f(x, sign=1.0): x1 = x[0, :] x2 = x[1, :] # Objective function out = sign*(x1**3 + 3*x1**2 - 2*x1*x2 + 3*x1 + x2**3 + 3*x2**2 + 3*x2) return out </code>...
python|arrays|numpy|matplotlib|scipy
1
366,611
14,867,099
Can i get features of the clusters using hierarchical clustering - numpy
<p>I am trying to do hierarchical clustering on an m*n array.</p> <ol> <li>Input array : 500 * 1000 (1000 features, 500 observations)</li> <li>Calculate distance matrix using a self-defined pdist function</li> <li>Feed this distance matrix to linkage function : clusters = sch.linkage(distanceMatrix,'single')</li>...
<p>Clusters in hierarchical clustering (or pretty much anything except k-means and Gaussian Mixture EM that are restricted to "spherical" - actually: convex - clusters) do <strong>not necessarily have sensible means</strong>.</p> <p>Because they allow for non-spherical clusters. That actually is a feature...</p> <p><...
python|numpy|cluster-analysis|data-mining|hierarchical
3
366,612
14,513,638
pandas: merge rows on timestamp
<p>my data looks like this:</p> <pre><code> date, cola, colb, colc 1,10,, 2,11,, 3,12,, 4,13,, 1,,14, 2,,15, 3,,16, 4,,17, 1,,,17 2,,,18 3,,,19 4,13,,20 </code></pre> <p>I'd like to merge the rows based on the first column and have the output look like this:</p> <pre><code> date, cola, colb, colc 1,10,1...
<p>You can use <code>groupby</code>. Start from a <code>csv</code> with duplicates:</p> <pre><code>&gt;&gt;&gt; !cat tomerge.csv date, cola, colb, colc 1,10,, 2,11,, 1,,14, 2,,15, 1,,24, 2,,40, 1,,,17 2,,,18 </code></pre> <p>Read it in:</p> <pre><code>&gt;&gt;&gt; df = pd.read_csv("tomerge.csv") &gt;&gt;&gt; df ...
python|merge|pandas|rows
1
366,613
14,492,898
Pandas Inter-row calculations
<p>I have a DataFrame with daily OHLCV data.</p> <p>I can calculate the range with:</p> <pre><code>s['Range'] = s['High'] - s['Low'] </code></pre> <p>Simple. Now I would like to calculate a new column which I've called <code>s['OIR']</code> (OIR = Open-In-Range)</p> <p>The <code>['OIR']</code> column checks to see ...
<p>Referencing previous rows in the manner you suggest is best accomplished with the <code>Series.shift()</code> function:</p> <pre><code>In [1]: df = DataFrame(randn(10,3),columns=['O','L','H']) In [2]: df Out[2]: O L H 0 0.605412 0.739866 -0.280222 1 -0.707852 0.785651 0.855183 2 -0.08...
pandas
7
366,614
14,861,023
Resampling Minute data
<p>I have minute based OHLCV data for the opening range/first hour (9:30-10:30 AM EST). I'm looking to resample this data so I can get one 60-minute value and then calculate the range.</p> <p>When I call the dataframe.resample() function on the data I get two rows and the initial row starts at 9:00 AM. I'm looking t...
<p>You can use the <code>base</code> argument of <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.resample.html" rel="noreferrer"><code>resample</code></a>:</p> <pre><code>sample.resample('60Min', how=conversion, base=30) </code></pre> <p>From <a href="http://pandas.pydata.org/pandas-docs/...
python|pandas
37
366,615
25,183,483
efficient way for replacing sub-arrays within numpy array - numpy.put or similar?
<p>I have a long list, called "colours", containing tuples of length 4. I need to substitute some of these tuples by other tuples (or more specifically, all the tuples that I need to replace should be replaced by the tuple (1.,0.,0.,1.), corresponding to the colour 'red' in matplotlib). I know the indices of the tuple...
<p>If you convert <code>colours</code> to a NumPy array, then you could use so-called <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#integer" rel="nofollow">"advanced (integer) indexing"</a> to do the assignment:</p> <pre><code>colours = np.array(colours) colours[indices, :] = (1, 0, 0, 1) </c...
python|arrays|list|numpy|matplotlib
1
366,616
25,050,141
How to filter in NaN (pandas)?
<p>I have a pandas dataframe (df), and I want to do something like:</p> <pre><code>newdf = df[(df.var1 == 'a') &amp; (df.var2 == NaN)] </code></pre> <p>I've tried replacing NaN with <code>np.NaN</code>, or <code>'NaN'</code> or <code>'nan'</code> etc, but nothing evaluates to True. There's no <code>pd.NaN</code>.</p>...
<p><strong>Simplest of all solutions:</strong></p> <pre><code>filtered_df = df[df['var2'].isnull()] </code></pre> <p>This filters and gives you rows which has only <code>NaN</code> values in <code>'var2'</code> column.</p>
python|pandas|nan
136
366,617
25,206,376
Python equivalent of the R operator "%in%"
<p>What is the python equivalent of this in operator? I am trying to filter down a pandas database by having rows only remain if a column in the row has a value found in my list. </p> <p>I tried using any() and am having immense difficulty with this. </p>
<p>Pandas comparison with R docs are <a href="http://pandas.pydata.org/pandas-docs/stable/comparison_with_r.html#match" rel="nofollow noreferrer">here</a>.</p> <pre><code>s &lt;- 0:4 s %in% c(2,4) </code></pre> <p>The <code>isin</code> method is similar to R %in% operator:</p> <pre><code>In [13]: s = pd.Series(np.arang...
python|r|pandas
48
366,618
30,606,880
Pandas value_counts() for loop fails as lambda
<p>I have some dataframe of three variables and I want to create a dictionary of the relative count of each label for each variable. </p> <p>I easily created a forloop that outputs exactly what I want, however my lambda produces wierd results.</p> <p>Here is the data:</p> <pre><code>In [3]: import pandas as pd raw_...
<p>I actually can't understand what is going wrong here other than it's not unpacking the <code>dict</code> call, here is a round-about way to achieve what you want:</p> <pre><code>In [86]: ratio = lambda x: x.value_counts(normalize=True) output_lambda = df.apply(lambda x: [x.value_counts().to_dict()]).apply(lambda x:...
python|pandas|lambda
1
366,619
30,641,450
how to add a percentage to grouped data?
<p>I am learning pandas and struggling with how data is organized in that module. </p> <p>I follow the tutorial and docs to handle a basic task: percentages of occurrence of a state ('color') within bins ('site'). The code below hopefully clarifies what I have and want to do:</p> <pre><code>import pandas as pd import...
<p>This can be calculated by dividing the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html#pandas.core.groupby.GroupBy.size" rel="nofollow"><code>size</code></a> by the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sum.html#pandas.Series...
python|pandas
1
366,620
30,670,991
How can I update arrays in h5py?
<p>I need an array for saving values, but I also want to edit some of the values in the array anytime later. </p> <p>I created an array with some random values and save it to disk. I can read it. Than I want to update it, an array slice with the value '23'. When I read it again it looks like it doesn't change.</p> <p...
<p>Append mode works for me. Create file:</p> <pre><code>fh = h5py.File('dummy.h5', 'w') fh.create_dataset('random', data=np.reshape(np.asarray([0, 1, 2, 3]), (2, 2))) fh.close() </code></pre> <p>Open and edit in append mode ('a', default mode)..</p> <pre><code>fh = h5py.File('dummy.h5', 'a') print fh['random'][:] f...
python|arrays|numpy|h5py
4
366,621
30,751,686
Direct chart plotting Pandas DataFrame columns to Xlsxwriter in a loop
<p>I am looking for an efficient way to print multiple Pandas DataFrame plots directly to Excel using xlsxwriter without the need to save the plot to file each time.</p> <p>I have my DataFrame generated and I am using a dictionary to outline the combinations of different plots I am looking to create. I have seen an e...
<blockquote> <p>I get the following error: IOError: [Errno 22] invalid mode ('rb') or filename: '' </p> </blockquote> <p>From where/what? </p> <p>At a guess I would say it is because you didn't supply a filename. Try adding a default name like <code>'plot%d.png' % row_num</code> for each plot.</p>
python|pandas|matplotlib|io|xlsxwriter
0
366,622
30,666,490
Change plot label when plotting different dataframes in pandas
<p>I aggregated on pivot tables some time series information, so each pivot table have columns labeled 2015, 2014, etc. I want to compare each pivot table, so I'm plotting them on the same axis:</p> <pre><code>print pv_test_A.columns Int64Index([2010, 2011, 2012, 2013, 2014, 2015], dtype='int64') print pv_test_B.colu...
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/version/0.16.1/generated/pandas.DataFrame.rename.html" rel="noreferrer"><code>.rename()</code></a>:</p> <pre><code>pv_test_A.loc[:,[2015]].rename(columns={2015: "New Label A"}).plot(ax=axes) pv_test_B.loc[:,[2015]].rename(columns={2015: "New Label B"}).plo...
python|pandas|matplotlib
7
366,623
30,286,629
numpy.power() and math.pow() don't give the same result
<p>Is numpy.power() less accurate then math.pow()?</p> <p>Example:</p> <p>Given <code>A = numpy.array([6.66655333e+12,6.66658000e+12,6.66660667e+12,3.36664533e+12])</code></p> <p>I define <code>result = numpy.power(A,2.5)</code></p> <p>So <code>&gt;&gt; result = [ 1.14750185e+32 1.14751333e+32 1.14752480e+32 ...
<p>This is just a questions how the numbers are displayed:</p> <pre><code>&gt;&gt;&gt; result[0] 1.1475018493845227e+32 </code></pre> <p>and:</p> <pre><code>&gt;&gt;&gt; math.pow(A[0],2.5) 1.1475018493845227e+32 </code></pre> <p>Both ways lead to same value:</p> <pre><code>&gt;&gt;&gt; result[0] == math.pow(A[0],2...
python|math|numpy|floating-point-precision
7
366,624
30,665,115
Error 'numpy.int32' object does not support item assignment
<p>I get this error </p> <pre><code>Traceback (most recent call last): File "C:\Users\User1\Desktop\cellh5_scripts\ewa_pnas_fate.py", line 90, in &lt;module&gt; ec.combine_classifiers("Event labels combined") File "C:\Users\User1\Desktop\cellh5_scripts\ewa_pnas_fate.py", line 53, in combine_classifiers pnas_class[...
<p><code>pnas_class</code> is a an integer so you can't select item from an integer by <code>[pnas_class==3] = 1</code>.</p> <p>Maybe you are trying to affect 1 to <code>pnas_class</code> if it's equal to 3. In this case try this:</p> <pre class="lang-py prettyprint-override"><code>pnas_class= 1*(pnas_class == 3) + p...
python|numpy
2
366,625
30,522,371
Why does converting my data into an ndarray give me 'python' terminated by signal SIGBUS (Misaligned address error)?
<p><code>img</code> is a PIL Image. Below is the terminal output when I try to import the data into an ndarray. Do you think the error is something I did, or something with numpy?</p> <pre><code>&gt;&gt;&gt; img &lt;PIL.TiffImagePlugin.TiffImageFile image mode=I;16 size=1280x1080 at 0x110CB1560&gt; &gt;&gt;&gt; img....
<p>This code works for me, in Python 3.4, Numpy 1.9:</p> <pre><code>import os from PIL import Image import numpy as np def img_data_in_nd_array(): img_dir = 'img' file_name = 'avatar_physical_attraction.jpg' img = Image.open(os.path.join(img_dir, file_name)) print (img.getdata()) print (np.array(...
python|numpy|runtime-error|python-imaging-library
0
366,626
30,678,737
Python: Cell arrays comparison using minus function
<p>I have 3 cell arrays with each cell array have different sizes of array. How can I perform minus function for each of the possible combinations of cell arrays? <br><br>For example:<br> </p> <pre><code>import numpy as np a=np.array([[np.array([[2,2,1,2]]),np.array([[1,3]])]]) b=np.array([[np.array([[4,2,1]])]]) c=n...
<p>You can use the function <a href="https://toolz.readthedocs.org/en/latest/api.html#toolz.itertoolz.sliding_window" rel="nofollow"><code>sliding_window()</code></a> from the <a href="https://toolz.readthedocs.org" rel="nofollow">toolz library</a> to do the shifting window:</p> <pre><code>&gt;&gt;&gt; import numpy as...
python|arrays|numpy|combinations|cell-array
2
366,627
30,311,172
Convert list or numpy array of single element to float in python
<p>I have a function which can accept either a list or a numpy array.</p> <p>In either case, the list/array has a single element (always). I just need to return a float.</p> <p>So, e.g., I could receive:</p> <pre><code>list_ = [4] </code></pre> <p>or the numpy array:</p> <pre><code>array_ = array([4]) </code></pre...
<p>Just access the first item of the list/array, using the index access and the index 0:</p> <pre><code>&gt;&gt;&gt; list_ = [4] &gt;&gt;&gt; list_[0] 4 &gt;&gt;&gt; array_ = np.array([4]) &gt;&gt;&gt; array_[0] 4 </code></pre> <p>This will be an <code>int</code> since that was what you inserted in the first place. I...
python|arrays|list|numpy|floating-point
46
366,628
26,666,269
PIL weird error after resizing image in skimage
<p>I observed this weird issue with PIL and scikit image. When I do </p> <pre><code>img=io.imread(imgLoc) pilImg=Image.fromarray(img) </code></pre> <p>It runs perfect. When I try to resize the image using skimage's rescale method like this:</p> <pre><code>img=rescale(io.imread(imgLoc),0.5) pilImg=Image.fromarray(img...
<p><code>rescale</code> returns a floating point image. Try to do <code>pilImg=Image.fromarray(skimage.util.img_as_ubyte(img))</code>.</p>
numpy|python-imaging-library|pillow|scikit-image
1
366,629
26,912,016
Check Upper or Lower Triangular Matrix
<p>Is there any way, using numpy or scipy, to check if a matrix is a lower or upper triangular matrix?. I know how make a function for check this; but I'd like know if these modules have their own functions themselves. I'm searching in the documentation but I do not have found anything.</p>
<p>I would do</p> <pre><code>np.allclose(mat, np.tril(mat)) # check if lower triangular np.allclose(mat, np.triu(mat)) # check if upper triangular np.allclose(mat, np.diag(np.diag(mat))) # check if diagonal </code></pre> <ul> <li><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.tril.html" rel="noref...
python|numpy|scipy
20
366,630
26,475,435
python pandas yahoo stock data error
<p>i am try to pullout intraday aapl stock data by yahoo. but there problem i facing with my program..</p> <pre><code>import pandas as pd import datetime import urllib2 import matplotlib.pyplot as plt get = 'http://chartapi.finance.yahoo.com/instrument/1.0/aapl/chartdata;type=quote;range=1d/csv' getdata = urllib2.url...
<p><code>pd.read_csv</code> accepts a path or a filelike object. You're passing the text itself, and it's trying to read that as a filename. You can just pass the URL (although <code>get</code> isn't a great variable name..)</p> <pre><code>In [102]: df = pd.read_csv(get, skiprows=17, header=None) In [103]: df.head(...
python|pandas|urllib2
3
366,631
26,609,475
numpy performance differences between Linux and Windows
<p>I am trying to run <strong><code>sklearn.decomposition.TruncatedSVD()</code></strong> on 2 different computers and understand the performance differences.</p> <p><strong>computer 1</strong> (Windows 7, physical computer)</p> <pre><code>OS Name Microsoft Windows 7 Professional System Type x64-based PC Processor I...
<p><code>{built-in method dot}</code> is the <code>np.dot</code> function, which is a NumPy wrapper around the CBLAS routines for matrix-matrix, matrix-vector and vector-vector multiplication. Your Windows machines uses the heavily tuned <a href="https://software.intel.com/en-us/intel-mkl" rel="noreferrer">Intel MKL</a...
python|performance|numpy|scikit-learn
6
366,632
39,388,820
Pandas groupwise percentage
<p>How can I calculate a group-wise percentage in pandas?</p> <p>similar to <a href="https://stackoverflow.com/questions/23627782/pandas-groupby-size-and-percentages">Pandas: .groupby().size() and percentages</a> or <a href="https://stackoverflow.com/questions/29299078/pandas-very-simple-percent-of-total-size-from-gr...
<p>IIUC you can use:</p> <pre><code>mydf = pd.DataFrame({'Field':[1,1,3,3,3], 'ClassLabel':[4,4,4,4,4], 'A':[7,8,9,5,7]}) print (mydf) A ClassLabel Field 0 7 4 1 1 8 4 1 2 9 4 3 3 5 4 3 4 7 4 3 ...
python|pandas|group-by|percentage
4
366,633
39,122,554
Setting axis values in numpy/matplotlib.plot
<p>I am in the process of learning numpy. I wish to plot a graph of Planck's law for different temperatures and so have two <code>np.array</code>s, <code>T</code> and <code>l</code> for temperature and wavelength respectively. </p> <pre><code>import scipy.constants as sc import numpy as np import matplotlib.pyplot as ...
<p>The problem is that you're not giving your wavelength values to <code>plt.plot()</code>, so Matplotlib puts the index into the array on the horizontal axis as a default. Quick solution:</p> <pre><code>plt.plot(l, B) </code></pre> <p>Without explicitly setting tick labels, that gives you this:</p> <p><a href="http...
python|numpy|matplotlib
3
366,634
39,088,489
tensorflow periodic padding
<p>In tensorflow I cannot find a straightforward possibility to do a convolution (<a href="https://www.tensorflow.org/versions/master/api_docs/python/nn.html#conv2d" rel="noreferrer">tf.nn.conv2d</a>) with periodic boundary conditions.</p> <p>E.g. take the tensor</p> <pre><code>[[1,2,3], [4,5,6], [7,8,9]] </code></...
<p>The following should work for your case :</p> <pre><code>import tensorflow as tf a = tf.constant([[1,2,3],[4,5,6],[7,8,9]]) b = tf.tile(a, [3, 3]) result = b[2:7, 2:7] sess = tf.InteractiveSession() print(result.eval()) # prints the following array([[9, 7, 8, 9, 7], [3, 1, 2, 3, 1], [6, 4, 5, 6, 4],...
python|tensorflow
5
366,635
39,162,534
Numpy: finding nonzero values along arbitrary dimension
<p>It seems I just cannot solve this in Numpy: I have a matrix, with an arbitrary number of dimensions, ordered in an arbitrary way. Inside this matrix, there is always one dimension I am interested in (as I said, the position of this dimension is not always the same). Now, I want to find the first nonzero value along ...
<p>You can abuse <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html" rel="nofollow"><code>np.argmax</code></a> for your purpose. Here, you can specify the <code>axis</code> which you are interested in, where <code>0</code> is along columns, <code>1</code> is along rows, and so on. You just n...
arrays|numpy|matrix|iteration|array-broadcasting
0
366,636
38,966,912
How to deal with this logic in pandas
<p>I have a data frame like following below.</p> <pre><code> coutry flag 0 China red 1 Russia green 2 China yellow 3 Britain yellow 4 Russia green ...................... </code></pre> <p>In df['country'], you can see many different country names. I want to set the first appear co...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="nofollow"><code>factorize</code></a> and add <code>1</code>:</p> <pre><code>df['coutry'] = pd.factorize(df.coutry)[0] + 1 df['flag'] = pd.factorize(df.flag)[0] + 1 print (df) coutry flag 0 1 1 1 ...
python|pandas|dataframe|categorical-data
4
366,637
39,159,548
Find index of multiple queries in a multidimensional numpy array
<p>I am looking for a way to find indices of an array of queries in a multidimensional array. For example:</p> <pre><code>arr = np.array([[17, 5, 19, 9], [18, 13, 3, 7], [ 8, 1, 4, 2], [ 8, 9, 7, 19], [ 6, 11, 8, 5], [11, 16, 13, 18], [ 0, 1, 2, 9], [ 1, 7, 4, 6]]) </code></pre> ...
<p>IIUC you may try this:</p> <pre><code>In[19]:np.where((arr==4)|(arr==5)) Out[19]: (array([0, 2, 4, 7], dtype=int64), array([1, 2, 3, 2], dtype=int64)) </code></pre>
python|arrays|numpy|multidimensional-array
2
366,638
39,168,025
Tensorflow: show or save forget gate values in LSTM
<p>I am using the LSTM model that comes by default in tensorflow. I would like to check or to know how to save or show the values of the forget gate in each step, has anyone done this before or at least something similar to this?</p> <p>Till now I have tried with tf.print but many values appear (even more than the one...
<p>If you are using <code>tf.rnn_cell.BasicLSTMCell</code> , the variable you are looking for will have the following suffix in its name : <code>&lt;parent_variable_scope&gt;/BasicLSTMCell/Linear/Matrix</code> . This is a concatenated matrix for all the four gates. Its first dimension matches the sum of the second dime...
python|neural-network|tensorflow|lstm
2
366,639
39,169,905
Remove empty spaces or NaNs from lists in column of lists in Python/Pandas Dataframe
<p>I have a Pandas dataframe <code>df</code> that looks like this:</p> <pre><code> A B 1 1 [a,b,d,d] 2 6 [,1,4,d,g] 3 a [w,1,NaN,x,y,2] </code></pre> <p>I need to remove the blank in row 2, and the NaN in row 3 to get:</p> <pre><code> A B 1 1 [a,b,d,d] 2 6 [1,4,d,g] 3 a [w,1,x,y,2] </code></pre> <...
<p>You need to work on your comprehension skills :)</p> <pre><code>import numpy as np df = pd.DataFrame([ [1, ['a','b','d','d']], [6, ['',1,4,'d','g']], ['a', ['w',1,np.nan,'x','y',2]] ], columns=['A', 'B']) df.B.apply(lambda l: [x for x in l if x not in ['', np.nan]]) </code></pre> <p>w...
python|pandas|nan
3
366,640
38,985,853
Tensorflow variables - adding to same name
<p>In the following lines, can someone please confirm that Tensorflow adds to the single <code>loss</code> tensor, as opposed to creating multiple tensors (all named <code>loss</code>)?</p> <pre><code>loss = tf.nn.l2_loss(a) loss = tf.add(loss, tf.nn.l2_loss(b)) loss = tf.add(loss, tf.nn.l2_loss(c)) </code></pre> ...
<p>Below is the graph you are creating. Every time you do a <code>tf.&lt;something&gt;</code>, it appends to the default graph. That said, from the graph you can see that it actually has the effect of summing up three <code>loss</code> nodes<a href="https://i.stack.imgur.com/DI1cK.png" rel="nofollow noreferrer"><img sr...
tensorflow
2
366,641
39,167,070
Implementing gradient descent in TensorFlow instead of using the one provided with it
<p>I want to use gradient descent with momentum (keep track of previous gradients) while building a classifier in TensorFlow. </p> <p>So I don't want to use <code>tensorflow.train.GradientDescentOptimizer</code> but I want to use <code>tensorflow.gradients</code> to calculate gradients and keep track of previous gradi...
<p>TensorFlow has an <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#MomentumOptimizer">implementation</a> of gradient descent with momentum.</p> <p>To answer your general question about implementing your own optimization algorithm, TensorFlow gives you the primitives to calculate the gra...
tensorflow|gradient-descent
6
366,642
38,981,847
How do Python distributable modules work with external libs
<p>I apologise in advance, as I am rather new to Python programming, but I was curious as to how this system works. My question is: if I write a Python script and make it distributable, but my program imports other external libraries such as numpy or scipy (which is what I am working on currently) how does it all work ...
<p>The easy way to ensure that dependent modules are installed is through <em>pip -r</em>.</p> <p>Essentially, make a <em>requirements.txt</em> along with your script for users to install the correct modules and versions. </p> <p>Inside the text file should look like this:</p> <pre><code>Flask==0.11.1 </code></pre> ...
python|numpy|makefile|import
0
366,643
39,133,682
numpy convert array of strings to integers or boolean (for masking)
<p>I'm new to Python and I'm challenged with converting an array of strings to numbers. My data was extracted from a larger data set of numbers and strings. It looks like:</p> <pre><code>array([b'Single', b'', b'', b'', b'', b'Single', b'Single', b'', b'Single', ...]) </code></pre> <p>I would like to use this data t...
<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html" rel="nofollow">numpy.vectorize</a></p> <pre><code>import numpy as np def f(x): return not x == b'Single' vfunc = np.vectorize(f) x = np.array([b'Single', b'', b'', b'', b'', b'Single']) result = vfunc(x) </code><...
python|arrays|string|numpy
0
366,644
39,073,123
How to address data imported with pandas?
<p>I am using pandas to import some .dta file and numpy/sklearn to do some statistics on the set. I call the data <code>sample</code> I do the following: </p> <pre><code># import neccessary packages import pandas as pd import numpy as np import sklearn as skl # import data and give a little overview (col = var1-v...
<p>See this contrived example. Usually I don't like messing with <code>locals()</code> and <code>globals()</code> but I don't see a cleaner way:</p> <pre><code>class A: def __init__(self): self.var1 = 1 self.var2 = 2 obj = A() locals().update(obj.__dict__) print(var1) print(var2) &gt;&gt; 1 2...
python|variables|pandas|error-handling
4
366,645
39,299,187
Iterate and assign value - Python - Numpy
<p>I´m a newbie in Python.</p> <p>I´m trying to do something like this. Iterate an array, compare the value with a constant and assign values to another array.</p> <p><img src="https://i.stack.imgur.com/r0Sqk.jpg" alt="What I´m trying to do"></p> <p>Thanks in advance!</p> <p>Regards</p> <p>Eduardo</p>
<pre><code>a1 = numpy.array(range(10)) a2 = numpy.array(range(15,25)) print a2[a1==5] print a2[a1 &gt;= 8] print a2[a1 &lt; 5] </code></pre> <p>etc...</p>
python|arrays|loops|numpy
0
366,646
39,267,947
Efficient use of numpy.random.choice with repeated numbers and alternatives
<p>I need to generate a large array with repeated elements, and my code is:</p> <pre><code>np.repeat(xrange(x,y), data) </code></pre> <p>However, data is a numpy array with type float64 (but it represent integeres, no 2.1 there) and I get the error</p> <pre><code>TypeError: Cannot cast array data from dtype('float64...
<p>Lurking in the question is the <a href="https://en.wikipedia.org/wiki/Hypergeometric_distribution#Multivariate_hypergeometric_distribution" rel="nofollow noreferrer">multivariate hypergeometric distribution</a>. In <a href="https://stackoverflow.com/questions/35734026/numpy-drawing-from-urn/35735195#35735195">Numpy...
python|python-2.7|numpy|casting|repeat
4
366,647
19,703,179
Pandas resampling using numpy percentile?
<p>Have you ever used the percentile numpy function when using the pandas function resample??</p> <p>Considering that "data" is a dataframe with just one column with 10min data, I would like to do something like this:</p> <pre><code>dataDaily=data.resample('D',how=np.percentile(data['Col1'],q=90) </code></pre> <p>I ...
<p>You have to pass function to <code>how</code> parameter, not value. I think in your case you can use anonymous function (lambda function):</p> <pre><code>dataDaily = data.resample('D', how=lambda x: np.percentile(x['Col1'], q=90)) </code></pre> <p>example:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'Col1': np...
python|numpy|pandas
6
366,648
19,387,868
How do I store data from the Bloomberg API into a Pandas dataframe?
<p>I recently started using Python so I could interact with the Bloomberg API, and I'm having some trouble storing the data into a Pandas dataframe (or a panel). I can get the output in the command prompt just fine, so that's not an issue.</p> <p>A very similar question was asked here: <a href="https://stackoverflow.c...
<p>I use tia (<a href="https://github.com/bpsmith/tia/blob/master/examples/datamgr.ipynb" rel="noreferrer">https://github.com/bpsmith/tia/blob/master/examples/datamgr.ipynb</a>)</p> <p>It already downloads data as a panda dataframe from bloomberg. You can download history for multiple tickers in one single call and eve...
python|pandas|finance|bloomberg|blpapi
17
366,649
19,530,708
Pandas Dataframe add header without replacing current header
<p>How can I add a header to a DF without replacing the current one? In other words I just want to shift the current header down and just add it to the dataframe as another record. </p> <p>*secondary question: How do I add tables (example dataframe) to stackoverflow question?</p> <p>I have this (Note header and how i...
<p>Another option is to add it as an additional level of the column index, to make it a MultiIndex:</p> <pre><code>In [11]: df = pd.DataFrame(randn(2, 2), columns=['A', 'B']) In [12]: df Out[12]: A B 0 -0.952928 -0.624646 1 -1.020950 -0.883333 In [13]: df.columns = pd.MultiIndex.from_tuples(zip(['...
python|pandas
13
366,650
19,517,684
Encode rows of boolean numpy array to bytes
<p>I have a numpy array of dimensions Nx8, with dtyp=boolean I want to convert it into a numpy 1-d array where each row is turned into a byte, by bin2dec</p> <pre><code>x = array([[ True, True, False, False, True, True, False, False], [ False, False, False, False, True, True, False, False], [ True,...
<pre><code>&gt;&gt;&gt; np.packbits(np.uint8(x)) array([204, 12, 128], dtype=uint8) </code></pre> <p>How that?</p>
python|numpy
7
366,651
19,529,708
maximum recursion error Python
<p>I am trying to scrape some box scores from ESPN.com and put them in Pandas DataFrame. I have done similar things in the past in the same manner with out any problems. However in this case I am getting this error when I try to save the DataFrame. </p> <p><em>RuntimeError: maximum recursion depth exceeded while cal...
<p>This exception from pickle.dump usually means that you're trying to pickle an object that contains itself (directly or indirectly).</p> <p>But what object contains itself? When you <code>print</code> them all out, they all look fine.</p> <p>It's <code>awayTeam</code> This is a <a href="http://www.crummy.com/softwa...
python|pandas
8
366,652
13,115,095
Numpy subclassing: Create a copy of an array with different shape, same metadata
<p>I have a subclassed numpy array - a "spectroscopic axis" with metadata such as units.</p> <p>I can create a copy of any instance using <code>arr.copy</code> or a view using, e.g., <code>arr2=arr[2:5]</code>.</p> <p>Is there any way to create a new instance of one of these arrays <em>with a different shape</em> but...
<p>A simple solution would be to define a <code>.reshape</code> method in your subclass. This <code>.reshape</code> method should call the <code>__array_finalize__</code> method that would be in charge of copying the metadata from your object.</p> <p>For example, the <code>MaskedArray</code> subclass uses a <code>_upd...
python|arrays|numpy|reshape
2
366,653
13,024,292
genfromtxt() artifact when displaying floats
<p>In numpy, I'm reading an ASCII file (see below) using <code>np.genfromtxt()</code></p> <pre><code>0.085 102175 0.00025 0.094 103325 0.00030 raw = genfromtxt(fn) </code></pre> <p>When checking <code>raw</code> I get the following:</p> <pre><code>&gt;&gt;&gt; raw[0,0] 0.085000000000000006 </code></pre> <p>How do ...
<p>This is normal behaviour, and is due to the fundamental imprecision of floating point arithmetic. In other words, <code>0.085</code> cannot be represented exactly in floating point bits. For this reason, it's generally a good idea to assume a bit of noise in any numerical calculations.</p>
numpy|scipy
1
366,654
12,864,673
Adjacent cells of multiple cell patches in a numpy array
<p>this is a followup question arising from this <a href="https://stackoverflow.com/questions/12612663/counting-of-adjacent-cells-in-a-numpy-array">solution</a>. The solution to count adjacent cells works pretty well unless you have multiple patches in the array.</p> <p>So this time the array for instance looks like t...
<p>You can use <code>label</code> from <code>ndimage</code> to segment each patch of ones.</p> <p>Then you just ask where the returned array equals 1, 2, 3 etc and perform your algoritm on it (or you just use the <code>ndimage.distance_transform_cdt</code> but with inverting your forground/background for each labeled ...
python|multidimensional-array|numpy|scipy
4
366,655
12,864,368
python matrix vs numpy matrix. What am I doing wrong?
<p>I am experimenting with some 3d rendering in Python. I keep reading that Python is soooooooo very slow! I simply MUST harness the C-awesomeness of Numpy for all the matrix stuff I can't do in the shaders! Otherwise nothing will work, yadda, yadda (paraphrasing here..). </p> <p>BUT: I did some testing!</p> <p>Here'...
<p>You're inverting the matrix analytically (which is possible since you know the dimensions and since they're not too big). numpy must invert the matrix using some other (numerical) algorithm which works if the matrix is 4x4 as well as 10000x10000. In other words, the general problem is much harder than the simple 4...
python|numpy
7
366,656
28,990,256
python pandas time series year extraction
<p>I have a DF containing timestamps:</p> <pre><code>0 2005-08-31 16:39:40 1 2005-12-28 16:00:34 2 2005-10-21 17:52:10 3 2014-01-28 12:23:15 4 2014-01-28 12:23:15 5 2011-02-04 18:32:34 6 2011-02-04 18:32:34 7 2011-02-04 18:32:34 </code></pre> <p>I would like to extract the year from ea...
<p>No need to apply a function for each row there is a new <a href="https://pandas.pydata.org/pandas-docs/stable/reference/series.html#accessors" rel="noreferrer">datetime</a> accessor you can call to access the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/series.html#api-series-dt" rel="noreferrer">...
python|parsing|datetime|pandas|dataframe
47
366,657
29,152,518
How do you access ward/centroid/median clustering in scipy?
<p>When using <code>scipy.spatial.distance.pdist</code> to create a condensed distance matrix and passing it to <code>ward</code> and I get this error:</p> <pre><code>Valid methods when the raw observations are omitted are 'single', 'complete', 'weighted', and 'average' error. </code></pre> <p>The documentation thou...
<p>From the docstring:</p> <blockquote> <p>y : ndarray</p> <p>A condensed or redundant distance matrix. A condensed distance matrix is a flat array containing the upper triangular of the distance matrix. This is the form that pdist returns. <strong>Alternatively, a collection of m observation vectors in n dimensions ma...
python|numpy|scipy|hierarchical-clustering
2
366,658
29,147,179
Copy a single axis of a numpy array by index
<p>Im looking for an elegant way to extract the values of an single axis of a numpy array by an index. For example: </p> <pre><code>x = np.arange(16).reshape((4,4)) a = x[0] b = x[:, 0] </code></pre> <p>Is what i usually do, however i am looking for something like:</p> <pre><code>a = get( x, axis=0, index=0) b = ge...
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html" rel="nofollow"><code>np.rollaxis</code></a> to move the axis you're interested in to the front, then just index into it as normal:</p> <pre><code>def get(x, axis=0, index=0): return np.rollaxis(x, axis, 0)[index] x = ...
python|numpy
3
366,659
29,180,159
Installing Numpy on 64bit Windows 8.1 with Python 2.7
<p>I am trying to install Numpy on Python 2.7 and I am using Windows 8.1. When I run Numpy from this <a href="http://sourceforge.net/projects/numpy/files/NumPy/1.8.0/" rel="nofollow">link</a> it says, "Python 2.7 required, which was not found in the registry ". How can resolve this issue, I already installed Python 2.7...
<p>For Windows, you should check out Chris Gohlke's page: <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs</a></p> <p>He has some Numpy builds there for Python 2.7.</p>
python|python-2.7|numpy|windows-8.1
2
366,660
29,224,567
Python: compare an array element-wise with a float
<p>I have an array <code>A=[A0,A1]</code>, where <code>A0 is a 4x3 matrix, A1 is a 3x2 matrix</code>. I want to compare A with a float, say, 1.0, element-wise. The expected return <code>B=(A&gt;1.0)</code> is an array with the same size as A. How to achieve this? </p> <p>I can copy A to C and then reset all elements i...
<p>Suppose we have the same shape of a array of arrays you mention:</p> <pre><code>&gt;&gt;&gt; A=np.array([np.random.random((4,3)), np.random.random((3,2))]) &gt;&gt;&gt; A array([ array([[ 0.20621572, 0.83799579, 0.11064094], [ 0.43473089, 0.68767982, 0.36339786], [ 0.91399729, 0.1408565 , 0.7683...
python|arrays|numpy|logical-operators
2
366,661
29,086,773
PYTHON: Error in recognising numpy module
<p>I am using <em>Python 3.4.0</em>. I am going to assume that the <code>numpy</code> module should work, as this is one of the newer versions of python. However, anything I do with <code>numpy</code> will result in a syntax error. Forexample this code here: </p> <pre><code> import numpy list1=[1,3,2,6,9] l...
<p>It looks like <code>numpy</code> is not installed on your system. Assuming that you have the <code>pip</code> script installed with your python, you can perform following command to install it:</p> <pre><code>pip install numpy </code></pre> <p>or </p> <pre><code>pip3.4 install numpy </code></pre> <p>Or, dependin...
python|numpy
1
366,662
29,240,662
Filter numpy array by comparing elements to elements in prior row without looping
<p>I am very new to Python and NumPy and have spent a couple of days searching for an answer to this question.</p> <p>Consider the following 2D array of stock prices with columns 0 through 3 being the open, high, low and close prices with each row (0-6) being subsequent days.</p> <pre> O H L C 0 |...
<p>Generally speaking, you're wanting to do things like (to use your example of "C0 > H2"):</p> <pre><code>values = data[2:][C[2:] &gt; H[:-2]] </code></pre> <p>However, you can easily see how this becomes repetitive.</p> <p>Therefore, it's easiest to make new sequences of "H2", etc that are the same length as the r...
python|arrays|numpy
3
366,663
33,945,086
Dask DataFrame: Resample over groupby object with multiple rows
<p>I have the following dask dataframe created from Castra:</p> <pre><code>import dask.dataframe as dd df = dd.from_castra('data.castra', columns=['user_id','ts','text']) </code></pre> <p>Yielding:</p> <pre><code> user_id / ts / text ts 2015-08-08 01:10:00 9235 2015-08-0...
<p>If we can assume that each <code>user-id</code> group can fit in memory then I recommend using dask.dataframe to do the outer-groupby but then using pandas to do the operations within each group, something like the following.</p> <pre><code>def per_group(blk): return blk.groupby('ts').text.resample('3H', how='s...
python|pandas|dataframe|dask|castra
7
366,664
33,692,321
Why do we need endianness here?
<p>I am reading a <a href="https://tensorflow.googlesource.com/tensorflow/+/master/tensorflow/g3doc/tutorials/mnist/input_data.py">source-code</a> which downloads the zip-file and reads the data into numpy array. The code suppose to work on macos and linux and here is the snippet that I see:</p> <pre><code>def _read32...
<p>That's because data downloaded is in big endian format as described in source page: <a href="http://yann.lecun.com/exdb/mnist/">http://yann.lecun.com/exdb/mnist/</a></p> <blockquote> <p>All the integers in the files are stored in the MSB first (high endian) format used by most non-Intel processors. Users of Int...
python|numpy|endianness
7
366,665
33,704,124
Using not equal and nan together in python
<p>I have strange problem. I have the following code </p> <pre><code>if Group[NN1,8] != 'nan' : print("Group[NN1,8]",Group[NN1,8]) </code></pre> <p>The value of Group[NN1,8] is nan,therefor i expect that print command not execute. But with my code it executes. Result is </p> <pre><code>`('Group[NN1,8]', nan)`. <...
<p>Looks like you're comparing a float with a string, which are never equal.</p> <pre><code>&gt;&gt;&gt; float('nan') nan &gt;&gt;&gt; 'nan' 'nan' &gt;&gt;&gt; float('nan') == 'nan' False </code></pre> <p>In the special cases of <code>nan</code>, it doesn't even equal "itself":</p> <pre><code>&gt;&gt;&gt; x = floa...
python|numpy|import
8
366,666
33,616,094
Is Tensorflow compatible with a Windows workflow?
<p>I haven't seen anything about Windows compatibility -- is this on the way or currently available somewhere if I put forth some effort? (I have a Mac and an Ubuntu box but the Windows machine is the one with the discrete graphics card that I currently use with theano).</p>
<p><strong>Updated 11/28/2016:</strong> Today we released the first release candidate of TensorFlow 0.12, which includes support for Windows. You can install the Python bindings using the following command in a Python shell:</p> <pre><code>C:\&gt; pip install tensorflow </code></pre> <p>...or, if you want GPU support...
python|windows|tensorflow
63
366,667
33,601,093
Index numpy arrays columns by another numpy array
<p>I am trying to index a 2d matrix in numpy so that I can get all rows but only particular columns given by another numpy array. It's something as following:</p> <pre><code>a = [0,1,1,2,0,2,1] d = [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]] </code></pre> <p>I want to get all rows from d such that colu...
<p>This can be done with <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing">advanced indexing</a>:</p> <pre><code>&gt;&gt;&gt; a = numpy.array([0, 1, 1, 2, 0, 2, 1]) &gt;&gt;&gt; d = numpy.array([[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]) &gt;&gt;&gt; d[numpy.aran...
python-2.7|numpy
5
366,668
33,763,678
how to label axis with all the row names from dataframe
<p>I have the dataframe that contains about 430 rows:</p> <pre><code> name Right_Answers Wrong_Answers Alice Ji 7 6 Eleonora LI 2 5 Mike The 6 5 Helen Wo 5 3 </code></pre> <p>for visualize the number of right (re...
<p>Assuming your data is in a dataframe, you can use Pandas' built-in plotting methods, e.g.:</p> <pre><code>df.plot(kind='bar', color=['red', 'blue']) </code></pre> <p><a href="https://i.stack.imgur.com/WfQxg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WfQxg.png" alt="enter image description h...
python|pandas|matplotlib|plot|axis-labels
1
366,669
33,613,596
Pandas dataframe - transform column values into individual columns
<p>I have something like this:</p> <pre><code> XY UV BC Val 0 y u c 11 1 y u b 22 2 y v c 33 3 y v b 44 4 x u c 111 5 x u b 222 6 x v c 333 7 x v b 444 </code></pre> <p>I'd like to get</p> <pre><code> XY UV B_Val C_Val 0 y u 22 11 1 ...
<p>IIUC you want to <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.pivot.html#pandas.DataFrame.pivot" rel="nofollow"><code>pivot</code></a>:</p> <pre><code>In [110]: df.pivot(index='XY',columns='BC', values='Val') Out[110]: BC b c XY x 10 20 y 33 44 </code></...
python|pandas|dataframe
2
366,670
33,914,447
3D plot of a list of lists of values
<p>I'm trying to make a 3d plot from a list of lists of values. All the sublists have the same number of values.</p> <p>I tried this: <a href="https://stackoverflow.com/questions/24919903/plot-a-3d-surface-from-a-list-of-lists-using-matplotlib">Plot a 3d surface from a &#39;list of lists&#39; using matplotlib</a> , bu...
<p>Due to default cartesian indexing of <code>meshgrid</code> output (see <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html" rel="nofollow">docs</a> for more info) your <code>data</code> has shape of (6, 12), but <code>x</code> and <code>y</code> have shapes of (12, 6). The easiest way to...
python|numpy|matplotlib|plot|3d
2
366,671
33,585,928
How to delete columns from a dataframe with columns with the same label?
<p>I have a dataframe where some column labels occur multiple times (i.e., some columns have the same label). This is causing me problems -- I may post more about this separately, because some of the behavior seems a little strange, but here I just wanted to ask about deleting some of these columns. That is, for each...
<pre><code>In [18]: df.ix[: , ~df.columns.duplicated()] Out[18]: A C E 0 0 1 2 1 4 5 6 </code></pre> <h2>Explanation</h2> <hr> <pre><code>In [19]: ~df.columns.duplicated() Out[19]: array([ True, True, True, False], dtype=bool) </code></pre> <p>as you can see here you need first to check whet...
python|pandas|dataframe
5
366,672
33,804,380
Spark fastest way for creating RDD of numpy arrays
<p>My spark application is using RDD's of numpy arrays.<br> At the moment, I'm reading my data from AWS S3, and its represented as a simple text file where each line is a vector and each element is seperated by space, for example:</p> <pre><code>1 2 3 5.1 3.6 2.1 3 0.24 1.333 </code></pre> <p>I'm using numpy's funct...
<p>It would be a little bit more idiomatic and slightly faster to simply map with <code>numpy.fromstring</code> as follows:</p> <pre><code>import numpy as np. path = ... initial_num_of_partitions = ... data = (sc.textFile(path, initial_num_of_partitions) .map(lambda s: np.fromstring(s, dtype=np.float64, sep=" "))...
python|numpy|apache-spark|pyspark|rdd
4
366,673
33,552,454
Python dataframe trimming: pd.concat() vs. df.drop() vs. df2 = df1[selectCols]
<p>Dataframe <code>df1</code> contains columns <code>Week</code>, <code>Mon</code>:<code>Sun</code>, <code>Total</code>. </p> <p>Here are 3 ways to create a new dataframe 'df2' from columns in df1:</p> <pre><code>df2 = pd.concat( [df1.Sun,df1.Mon, df1.Tues, df1.Weds, df1.Thurs, df1.Fri, df1.Sat], ax...
<p>I figure the main advantage would be processing time. I took your examples, made some sample data, and compared them using the <a href="https://docs.python.org/2/library/timeit.html" rel="nofollow noreferrer">timeit</a> library. It looks like options 2 and 3 are a lot faster. I would use option 2 if there are a lot ...
python|pandas|dataframe|concat
0
366,674
33,797,454
Why the column order is changing while appending pandas dataframes?
<p>I want to append (merge) all the csv files in a folder using Python pandas.</p> <p>For example: Say folder has two csv files <code>test1.csv</code> and <code>test2.csv</code> as follows:</p> <pre><code>A_Id P_Id CN1 CN2 CN3 AAA 111 702 709 740 BBB 222 1727 ...
<p>Try this .....</p> <pre><code>all_data = all_data.append(df)[df.columns.tolist()] </code></pre>
python|csv|pandas
25
366,675
23,744,989
Convert a PIL image to a numpy array
<p>I want to convert a PIL image to a numpy array. Numpy's <code>asarray</code> function simply puts the image in a 0-dimensional array.</p> <pre><code>(Pdb) p img &lt;PIL.Image._ImageCrop image mode=RGB size=1024x0 at 0x106953560&gt; (Pdb) img.getdata() &lt;ImagingCore object at 0x104c97b10&gt; (Pdb) np.asarray(img.g...
<p>Your <code>img</code> has size 1024x0:</p> <blockquote> <p>PIL.Image._ImageCrop image mode=RGB size=<strong>1024x0</strong> at 0x106953560</p> </blockquote> <p>That is an image with 0 height. Therefore, the resultant NumPy array is empty. To fix, crop the image so that it has a positive width and height.</p>
python|numpy|python-imaging-library
5
366,676
23,860,029
How could I import a class from a python script into another python script?
<p>I am trying to write a script contains some classes and save for example as <code>model.py</code>. </p> <pre><code>import numpy as np from scipy import integrate class Cosmology(object): def __init__(self, omega_m=0.3, omega_lam=0.7): # no quintessence, no radiation in this universe! self.omega...
<p>You are trying to call an instance method from a class. In order to use the a() method, you need to create an instance of the Cosmology class:</p> <pre><code>&gt;&gt;&gt;from model import Cosmology &gt;&gt;&gt;cosmo = Cosmology() &gt;&gt;&gt;cosmo.a(1.) 0.5 </code></pre> <p>Or, if you want a() to be a class method...
python|numpy|scipy
2
366,677
23,902,157
How to calculate errors on slopes of linear fits when y-errors are asymmetric
<p>I have a data set with values that can be plotted as x-values against y-values. Data on the y-axis have asymmetric errors, i.e., </p> <p><img src="https://latex.codecogs.com/png.latex?y_i%3D10%5E%7B%2B2%7D_%7B-1.5%7D" alt="y_i=10^{+2}_{-1.5}"></p> <p>I want to fit these data with a linear function. I can do this f...
<p>There's a paper by Barlow+04 <a href="https://arxiv.org/abs/physics/0406120" rel="nofollow noreferrer">https://arxiv.org/abs/physics/0406120</a> on finding the mean of variables with asymmetric error bars. You could perhaps use these techniques.</p> <p>The brute force route that I take is to draw many realisations ...
python|numpy|scipy
0
366,678
23,537,510
using histogram counts in scatter
<p>this my code to and i want to use histogram data to plot scatter where y axis is counts center from the histogram,is there any direct command or way to do this?</p> <pre><code>from pylab import* import scipy.stats from scipy.stats import norm import numpy r= numpy.random.uniform(0.0 ,1.0, 4000) x=norm.rvs(5., 0.5,...
<p>In the line </p> <pre><code>from pylab import * </code></pre> <p>you have imported <code>matplotlib</code>'s <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist" rel="nofollow">hist</a> function. This both calculated the histogram AND plots it. From the comments I gather you essentially want ...
python|numpy|matplotlib|histogram
1
366,679
22,570,630
Plot and save multiple figures of group by function as pdf
<p>I would like to create one pdf file with 12 plots, in two options:</p> <ul> <li>one plot per page,</li> <li>four plots per page.</li> </ul> <p>Using <code>plt.savefig("months.pdf")</code> saves only last plot.</p> <p><strong>MWE:</strong></p> <pre class="lang-py prettyprint-override"><code>import pandas as pd in...
<p>To save a plot in each page use:</p> <pre><code>from matplotlib.backends.backend_pdf import PdfPages # create df2 with PdfPages('foo.pdf') as pdf: for key, group in df2: fig = group.plot().get_figure() pdf.savefig(fig) </code></pre> <p>In order to put 4 plots in a page you need to first build ...
python|pdf|matplotlib|plot|pandas
1
366,680
22,870,314
Pandas: How to combine sub-grouped DataFrames to a single DataFrame
<p>I like to group a DataFrame according to their date and get the mean of each group then merge them into a single DataFrame.</p> <pre><code> df1= pd.DataFrame({'A' : ['2014-01-01', '2014-01-01', '2014-01-02', '2014-01-03','2014-01-03', '2014-01-04', '2014-01-04', '2014-01-05'],'B' : ['one', 'one', 'two', 'three','tw...
<p>If you want to do the calculation as above, you can concatenate result to the original frame as below</p> <pre><code>res = pd.concat([df1[k+dt.timedelta(days=-1):k].mean() for k in df1.index], axis=1) df1 = pd.concat([df1, res.T.set_index(df1.index)], axis=1) </code></pre>
python|pandas|merge
1
366,681
22,455,496
Splitting several days long dataframe into half-hourly dataframes using pandas and save them as csv-files
<p>I need to split quite a few large (several million records) files into half-hourly files using pandas to use with some other third-party software. Here's what I tried:</p> <pre><code>import datetime as dt import string import numpy as np import pandas as pd df = pd.DataFrame(np.random.rand(1728000, 2), index=pd.da...
<p>make your grouper like this:</p> <pre><code>df.groupby(pd.TimeGrouper('30T')) </code></pre> <p>In 0.14 this will be slightly different, e.g. <code>df.groupby(pd.Grouper(freq='30T'))</code></p>
python|pandas
7
366,682
22,467,695
numpy: print array with indentation
<p>I would like to print <code>numpy</code> <code>array</code> with indentation for debugging.</p> <p>Say I have an <code>array</code> <code>a = numpy.array([[1,2,3,4], [5,6,7,8]])</code>, then simple <code>print(a)</code> will give</p> <pre><code>[[ 63 903 942 952] [185 332 511 893]] </code></pre> <p>Now if I put ...
<p>This should do it :</p> <pre><code>print('\t' + str(a).replace('\n', '\n\t')) </code></pre>
python|arrays|numpy
5
366,683
22,700,000
Vectorize an iterative process
<p>I've written the following code in python; it takes an image and basically converts it from polar to cartesian coordinates; the effect is the image is 'unfurled' about a point.</p> <pre><code>def unravel(img, origin): max_radius = min(origin) out = np.zeros((max_radius,720,3), np.uint8) for phi in range(0,...
<p>This is a little high level, but you're going to have to get your hands dirty if you want to be able to stream video with a matrix transformation. This is not something you can reasonably do with your current approach.</p> <p>Possibly the most accessible approach is to use <a href="http://gstreamer.freedesktop.org/...
python|opencv|numpy
1
366,684
22,643,741
python pandas create dataframe and force multiple column types
<p>I was able to create dataframe and force one data type by</p> <pre><code>import pandas as pd test = pd.DataFrame({'a':[1,2,3], 'b':[1.1,2.1,3.1]}, dtype=int) </code></pre> <p>But I want to specify type for each column. How can I do this? I tried the following which doesn't work as the resulting dtypes are objects ...
<p>You can pass in a Series which has a dtype parameter</p> <pre><code>In [15]: pd.DataFrame({'a':[1,2,3], 'b':[1.1,2.1,3.1]}).dtypes Out[15]: a int64 b float64 dtype: object In [16]: pd.DataFrame({'a':Series([1,2,3],dtype='int32'), 'b':Series([1.1,2.1,3.1],dtype='float32')}).dtypes Out[16]: a int32 b ...
python|pandas
7
366,685
22,850,489
curve fitting with integer inputs Python 3.3
<p>I am using scipy's curvefit module to fit a function and wanted to know if there is a way to tell it the the only possible entries are integers not real numbers? Any ideas as to another way of doing this?</p>
<p>In its general form, an integer programming problem is NP-hard ( see <a href="https://en.wikipedia.org/wiki/Integer_programming" rel="nofollow">here</a> ). There are some efficient heuristic or approximate algorithm to solve this problem, but none guarantee an exact optimal solution.</p> <p>In scipy you may impleme...
python-3.x|numpy|scipy|curve-fitting
4
366,686
22,764,755
UnboundLocalError: local variable 'df' referenced before assignment
<p>I guess I have declared df as <code>pandas.DataFrame()</code>.</p> <p>Why do the code raise <code>UnboundLocalError</code>?</p> <pre><code>import pandas as pd import statsmodels.api as sm import numpy as np from math import log def half_life(x): df = pd.DataFrame() df['Close'] = x df['ylag'] = df['Clo...
<p><a href="http://pandas.pydata.org/pandas-docs/dev/dsintro.html#dataframe" rel="nofollow">DataFrame</a></p> <blockquote> <p>DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects. It is ge...
python|pandas
0
366,687
22,543,501
Violinplots in seaborn not showing mean, percentiles nor sticks?
<p>When I try to replicate the example <a href="http://nbviewer.ipython.org/github/mwaskom/seaborn/blob/master/examples/plotting_distributions.ipynb" rel="nofollow noreferrer">here</a>, my violin plots (with my data) don't show the median and median, along with the 25th and 75th percentile, but the original example do...
<p>Try <code>sns.violinplot(df, inner="stick", color="pastel")</code>. The second positional argument is a grouping variable. (Although, <code>inner="stick"</code> shows each observation. If you want the 25, 50, and 75th percentiles, do <code>inner="box"</code>).</p> <p>Also to handle a relatively sparse dataframe wit...
python|matplotlib|pandas|seaborn
4
366,688
22,440,421
Python: is the garbage collector run before a MemoryError is raised?
<p>In a Python code that iterates over a sequence of 30 problems involving memory- and CPU-intense numerical computations, I observe that the memory consumption of the Python process grows by ~800MB with the beginning of each of the 30 iterations and finally raises an <code>MemoryError</code> in the 8th iteration (wher...
<p>Actually, there <em>are</em> reference cycles, and it's the only reason why the manual <code>gc.collect()</code> calls are able to reclaim memory at all.</p> <p>In Python (I'm assuming CPython here), the garbage collector's sole purpose is to break reference cycles. When none are present, objects are destroyed and ...
python|memory|numpy|garbage-collection|out-of-memory
4
366,689
22,713,441
Remove words that appear in other column, Pandas
<p>what is the procedure to remove a word from a string in one column column that occurs in the other column? </p> <p>eg:</p> <pre><code>Sr A B C 1 jack jack and jill and jill 2 run you should run, you should , 3 ...
<p>How does this look?</p> <pre><code>In [24]: df Out[24]: Sr A B 0 1 jack jack and jill 1 2 run you should run, 2 3 fly you shouldnt fly,there [3 rows x 3 columns] In [25]: df.apply(lambda row: row.B.strip(row.A), axis=1) Out[25]: 0 and ji...
python|string|replace|pandas|dataframe
5
366,690
22,725,043
Convert dtype from int64 to int32
<p>Basically, I am using python x32 bit to load from file a list object containing several numpy arrays (previously saved inside a pickle using python x64).</p> <p>I can load them properly and check the contents but I cannot use them. </p> <pre><code>TypeError: Cannot cast array data from dtype('int64') to dtype('int...
<p>As others have said, 32-bit versions of numpy still support 64-bit dtypes. But if you really need to convert to int32, you can use the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.html" rel="noreferrer">astype</a> function:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;...
python|numpy
30
366,691
15,183,237
Number of words per sentence
<p>I am reading a text file in Python 2.7 and what I am trying to do is to fill out the count of words in each sentence of a text file in to 1D array. Here is what I have:</p> <pre><code>f = open(file_txt, 'r') sen_prog = [] for line in f: sents = line.split('.') sen_prog.append(sents) sen_p = [] for a in ...
<p>You are reading in the file line by line. Assuming the file is like so, with a sentence spanning multiple lines, you may get a wrong count.</p> <pre><code>This is line 1. This is line 2. This is line 3. </code></pre> <p>sen_prog will have the value:</p> <pre><code>[ "This is line 1", "This", "is line 2", "This ...
python|numpy
1
366,692
15,134,507
How to convert TimeSeries object in pandas into integer?
<p>I've been working with Pandas to calculate the age of a sportsman on a particular fixture, although it's returned as a TimeSeries type.</p> <p>I'd now like to be able to plot age (in days) against the fixture dates, but can't work out how to turn the TimeSeries object to an integer. What can I try next?</p> <p>This ...
<p>For people who find this post by google, if you have numpy >= 0.7 and pandas 0.11, these solutions will not work. What does work:</p> <pre><code>squad_date['mean_age'].apply(lambda x: x / np.timedelta64(1,'D')) </code></pre> <p>The official Pandas documentation can be confusing here. They suggest to do "x.item()",...
python|pandas|time-series
4
366,693
15,461,771
Python pandas. Group By and removing a timestamp
<p>I have the below pandas data frame. I need to do a Group By by column B and sum col A and remove the time stamp. So..In the below...should have one record with the A's summed up. Som How I do thus in pandas?</p> <pre><code> A B 2013-03-15 17:00:00 1 134 2013-03-15 18:00...
<p>This can be done with a straight-forward groupby operation:</p> <pre><code>import io import pandas as pd content='''\ date time A B 2013-03-15 17:00:00 1 134 2013-03-15 18:00:00 810 134 2013-03-15 19:00:00 1797 134 2013-03-15 20:00:00 813 135 ...
python|pandas
2
366,694
13,464,123
How do I convert a list to a generator?
<p>I have a function which returns a list of tuples, that I would like to iterate through:</p> <pre><code>def get_parameter_product(num_parameters, lower_range, upper_range): param_lists = [ xrange(lower_range, upper_range) for _ in xrange(num_parameters)] return list(itertools.product(*param_lists)) for p...
<p><code>itertools.product</code> is already a generator. You can just return it instead of converting it to a list.</p>
python|numpy|generator
2
366,695
13,348,899
Sorting a list of Image Matrices (Numpy nd arrays) by image size
<p>I have a set of matrices as numpy 2d arrays in a list. They are of different sizes (19x19 to 63x63).. Now, I have to arrange them starting from the one with the smallest size to the largest. I am inputting the matrices as below:</p> <pre><code>pics=[] templates=[] c1=0 for c1 in range(1,31): i1=Image.open("dat...
<p>what you want to do is sort by <code>size</code>...</p> <pre><code>templates.sort(key=numpy.size) </code></pre>
python|sorting|image-processing|numpy|multidimensional-array
2
366,696
13,476,450
Numpy sum between pairs of indices in 2d array
<p>I have a 2-d numpy array (MxN) and two more 1-d arrays (Mx1) that represent starting and ending indices for each row of the 2-d array that I'd like to sum over. I'm looking for the most efficient way to do this in a large array (preferably without having to use a loop, which is what I'm currently doing). An example ...
<p>You could do something like this:</p> <pre><code>from numpy import array, random, zeros random.seed(1234) a = random.rand(4,4) b = array([1,0,2,1]) c = array([3,2,4,4]) lookup = zeros(len(a) + 1, a.dtype) lookup[1:] = a.sum(1).cumsum() d = lookup[c] - lookup[b] print d </code></pre> <p>This might help if your b/c...
python|numpy|sum|multidimensional-array
2
366,697
13,731,405
Calculate subset of matrix multiplication
<p>When I have two non-sparse matrices <code>A</code> and <code>B</code>, is there a way to efficiently calculate <code>C=A.T.dot(B)</code> when I only want a subset of the elements of <code>C</code>? I have the desired indices of <code>C</code> stored in CSC format which is specified <a href="http://docs.scipy.org/doc...
<p>Instead of iterating on the coordinates using Python (GaryBishop's answer), you can have numpy do the looping, which constitutes a substantial speed-up (timings below):</p> <pre><code>def sparse_mult(a, b, coords) : rows, cols = zip(*coords) rows, r_idx = np.unique(rows, return_inverse=True) cols, c_idx...
python|numpy|scipy|sparse-matrix
2
366,698
13,421,159
Different result of same numpy mean calculation on two computers
<p>I have two computers with python 2.7.2 (MSC v.1500 32 bit (Intel)] on win32) and numpy 1.6.1. But </p> <pre><code>numpy.mean(data) </code></pre> <p>returns </p> <pre><code>1.13595094681 on my old computer </code></pre> <p>and</p> <pre><code>1.13595104218 on my new computer </code></pre> <p>where</p> <pre><co...
<p>If you want to avoid any differences between the two, then make them explicitly 32-bit or 64-bit float arrays. NumPy uses several other libraries that may be 32 or 64 bit. Note that rounding can occur in your print statements as well:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = [0.20227873, -0....
numpy|python-2.7
3
366,699
13,576,164
Pandas merge and retain the index
<p>A similar question was asked in <a href="https://stackoverflow.com/questions/11976503/how-to-keep-index-when-using-pandas-merge">How to keep index when using pandas merge</a>, but it will not work with MultiIndexes, i.e,</p> <pre><code>a = DataFrame(np.array([1,2,3,4,1,2,3,3]).reshape((4,2)), columns=['col1','to_me...
<p>Provisional solution:</p> <pre><code>In [255]: a = a.reset_index() In [256]: a Out[256]: id1 id2 col1 to_merge_on 0 1 a 1 2 1 1 b 3 4 2 2 a 1 2 3 2 b 3 4 In [271]: c = pd.merge(a, b, how="left") In [272]: c Out[272]: id1 id...
python|pandas|dataframe|merge
3