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
374,300
26,945,812
Compute the product of neighborhood for each cell in a matrix with numpy/scipy
<p>I'm trying to implement an image processing algorithm which involves computing the product of 4-adjacent neighborhood for each cell. That is, to compute a new matrix Y for X where <code>y[i, j] = x[i-1, j] * x[i, j-1] * x[i+1, j] * x[i, j+1]</code>. Out-of-bound neighbors should be ignored.</p> <p>Now I can only th...
<p>I think this better matches what you're asking for:</p> <pre><code>import numpy as np x = np.array([ [1, 2, 3, 4, 5], [6, 7, 8, 9, 1], [2, 3, 4, 5, 6], [7, 8, 9, 1, 2] ]) y = np.ones_like(x) y[+1:, :] *= x[:-1, :] y[:-1, :] *= x[+1:, :] y[:, +1:] *= x[:, :-1] y[:, :-1] *= x[:, +1:] y #&gt;&gt;&gt...
python|numpy
4
374,301
26,934,349
How to assign scipy.sparse matrix to NumPy array via indexing?
<p>When I try to assign a <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/sparse.html" rel="nofollow"><code>scipy.sparse</code></a> matrix <code>s</code> (any of the available sparse types) to a NumPy array <code>a</code> like this:</p> <pre><code>a[:] = s </code></pre> <p>I get a <code>TypeError</code>:</p...
<p>As mentioned in a comment to my question, the sequence interface won't work for sparse <em>matrices</em>, because they don't lose a dimension when indexed with a single number. To try it anyway, I created a very limited quick-and-dirty sparse <em>array</em> class in pure Python, which, when indexed with a single num...
python|numpy|scipy
1
374,302
14,905,443
Can I avoid using `asmatrix`?
<p>Is there any way for me to create matrices directly and not have to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.asmatrix.html" rel="nofollow"><code>asmatrix</code></a>? From what I can see, all of the typical matrix functions (<code>ones</code>, <code>rand</code>, etc) in Numpy return arra...
<p>According to the documentation:</p> <blockquote> <p>Unlike matrix, asmatrix does not make a copy if the input is already a matrix or an ndarray. Equivalent to matrix(data, copy=False).</p> </blockquote> <p>So, <code>asmatrix</code> does <em>not</em> copy the data if it doesn't need to:</p> <pre><code>&gt;&gt;...
python|numpy
1
374,303
14,447,925
Iterating and Writing Pandas Dataframe NaNs back to MySQL
<p>I'm attempting to write the results of a regression back to MySQL, but am having problems iterating through the fitted values and getting the NaNs to write as null values. Originally, I did the iteration this way:</p> <pre><code>for i in dataframe: cur = cnx.cursor() query = ("UPDATE Regression_Data.Input...
<p>I don't have a complete answer, but perhaps I have some tips that might help. I believe you are thinking of your <code>dataframe</code> as an object similar to a SQL record set. </p> <pre><code>for i in dataframe </code></pre> <p>This will iterate over the column name strings in the dataframe. <code>i</code> wi...
python|mysql|iteration|pandas
3
374,304
14,503,660
tuples are inmutable, create lists before replacing its entries
<p>I was trying to do some simple manipulation of lists and numpy arrays and got stuck in some easy thing: </p> <pre><code>a=np.arange(12) a array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) a=np.reshape(a,(3,4)) a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) b=np.arange(12,24) b array...
<p>Then I realized that data is actually a tuple.</p> <p>So this is what solves the problem:</p> <pre><code>data = [[i, j] for i,j in list1] </code></pre> <p>And then I can replace elements like data[0][0]</p>
python|list|numpy|tuples
1
374,305
25,427,197
numpy: How to add a column to an existing structured array?
<p>I have a starting array such as:</p> <pre><code>[(1, [-112.01268501699997, 40.64249414272372]) (2, [-111.86145708699996, 40.4945008710162])] </code></pre> <p>The first column is an <code>int</code> and the second is a <code>list</code> of <code>floats</code>. I need to add a <code>str</code> column called <code>'U...
<p>You have to create a new dtype that contains the new field.</p> <p>For example, here's <code>a</code>:</p> <pre><code>In [86]: a Out[86]: array([(1, [-112.01268501699997, 40.64249414272372]), (2, [-111.86145708699996, 40.4945008710162])], dtype=[('i', '&lt;i8'), ('loc', '&lt;f8', (2,))]) </code></pr...
python|python-2.7|numpy|structured-array|recarray
16
374,306
25,172,212
Pandas - Python: Locate a forward looking variable based on time (minutes)
<p><em>Sorry for the poor title, I am not sure how to best describe my issue in one line</em></p> <p>I have a dataframe <code>df1</code> with index:</p> <p><code>[2014-01-02 10:00:02.644000, ..., 2014-01-02 15:59:58.630000] Length: 26761, Freq: None, Timezone: None</code></p> <p>My <code>df1</code> column <code>pric...
<p>I got my answer <a href="https://stackoverflow.com/questions/9877391/how-to-get-the-closest-single-row-after-a-specific-datetime-index-using-python-p">here</a>. This methodology helps me to find the closest match based on time. I couldn't ask for something better!</p>
python|pandas
0
374,307
25,296,130
Access column in data frame that shares a name with other columns
<p>I have three different columns each named <code>Weight (LB)</code>. When I print out the column names pandas seems to distinguish between them using <code>Weight (LB)</code> and <code>Weight (LB).1</code> and <code>Weight (LB).2</code>. So I tried accessing each one individually while iterating the rows and appendin...
<p>I'd just rename your columns, in general it will make life a lot easier. It's a little tricky with duplicates, but you can assign directly to the columns with some kind of mapping function like this.</p> <pre><code>def rename_dup(col): ans = [] counter = 1 for c in col: if c.startswith('Weight ...
python|python-2.7|pandas
0
374,308
25,101,344
Split columns using pandas
<pre><code>Games Home Away Team 1 vs. Team 2 Team 1 Team 2 Team 1 @ Team 2 Team 2 Team 1 </code></pre> <p>I have a column called Games and want to split it into two new columns label as Home and Away. For the @ I use...
<p>It's not clear from the information you provided exactly what is going wrong here. But pandas provides tools that are specific to this kind of work and likely to provide informative errors if things go wrong.</p> <p>Take a look at the <a href="http://pandas.pydata.org/pandas-docs/stable/basics.html#vectorized-strin...
pandas
0
374,309
25,126,520
Pandas - remove cells based on value
<p>I have a dataframe with z-scores for several values. It looks like this:</p> <pre><code>ID Cat1 Cat2 Cat3 A 1.05 -1.67 0.94 B -0.88 0.22 -0.56 C 1.33 0.84 1.19 </code></pre> <p>I want to write a script that will tell me which IDs correspond with values in each category ...
<p>You don't have to apply the filtration to columns, you can also do</p> <pre><code>df[df &gt; 1] </code></pre> <p>, and also,</p> <pre><code>df[df &gt; 1] = np.NaN </code></pre>
python|pandas|dataframe
2
374,310
25,129,195
How to access an element in a Numpy array
<p>So I have this list of Numpy arrays:</p> <pre><code>import numpy as np from numpy import array m = [array([0, 64]), array([ 0, 79]), array([0, 165]), array([0, 50])] </code></pre> <p>How do I index the number 50 from the m[3] element in the array?</p>
<p>As already mentioned in the other comments, if your intention is to use a 2D-array, you should create it as:</p> <pre><code>m = array([[0, 64], [0, 79], [0, 165], [0, 50]]) </code></pre> <p>and then access the elements like:</p> <pre><code>print(m[3, 1]) </code></pre>
python|list|numpy
4
374,311
30,697,769
How can I unserialize a numpy array that was cast to a bytestring?
<p>I need to serialize a numpy array to some JSON-compatible form. Since the framework I'm using doesn't give me access to the JSON encoder/decoder object, I'm stuck serializing a numpy array to something that can <em>then</em> be marshalled into JSON. I've opted for either <code>array.tobytes</code> or <code>array.t...
<p>Actually numpy.fromstring() returns a single dimensional array of 1024X1024 intead of a 2 Dimensional array, All you need to do is reshape into 1024X1024, </p> <p>Try this :- </p> <pre><code>import numpy as np a = np.random.rand(1024, 1024) # create array of random values b = array.tobytes() np.fromstring(b).resh...
python|numpy
1
374,312
30,623,721
Plot multiple DataFrame columns in Seaborn FacetGrid
<p>I am using the following code</p> <pre><code>import seaborn as sns g = sns.FacetGrid(dataframe, col='A', hue='A') g.map(plt.plot, 'X', 'Y1') plt.show() </code></pre> <p>to make a seaborn facet plot like this: <img src="https://i.stack.imgur.com/B2eay.png" alt="Example facet plot"></p> <p>Now I would like to add ...
<p>I used the following code to create a synthetic dataset which appears to match yours:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt # Generate synthetic data omega = np.linspace(0, 50) A0s = [1., 18., 40., 100.] dfs...
python|pandas|matplotlib|plot|seaborn
13
374,313
30,735,358
How can I convert a list to a numpy array for filtering elements?
<p>I have a list of <code>float</code> numbers and I would like to convert it to <code>numpy array</code> so I can use <code>numpy.where()</code> to get indices of elements that are bigger than 0.0 (not zero)</p> <p>I tried this, but with no luck: </p> <pre><code>import numpy as np arr = np.asarray(enumerate(grade_l...
<p>You don't need the <code>enumerate()</code>: </p> <pre><code>arr = np.asarray(grade_list) g_indices = np.where(arr &gt; 0)[0] </code></pre>
python|arrays|numpy|where
3
374,314
30,514,378
Divide one column in array by another numpy
<p>I am trying to get</p> <pre><code>[[ 4. 0. 0. ] [ 8. 0. 0. ]] </code></pre> <p>out of this:</p> <pre><code>[[ 2. 0.5 0. ] [ 2. 0.25 0. ]] </code></pre> <p>So I want to divide the first column by the second one:</p> <p><code>div = arr[:,0]/arr[:,1]</code> but don't know what's the best way...
<p>If you want to do it in place, you could do</p> <pre><code>a[:, 0] = a[:, 0] / a[:, 1] a[:, 1] = 0 </code></pre> <p>If not</p> <pre><code>b = np.zeros(6).reshape(2, 3) b[:, 0] = (a[:, 0] / a[:, 1]) </code></pre>
python|numpy
2
374,315
30,305,069
Numpy concatenate 2D arrays with 1D array
<p>I am trying to concatenate 4 arrays, one 1D array of shape (78427,) and 3 2D array of shape (78427, 375/81/103). Basically this are 4 arrays with features for 78427 images, in which the 1D array only has 1 value for each image.</p> <p>I tried concatenating the arrays as follows:</p> <pre><code>&gt;&gt;&gt; print X...
<p>Try concatenating <code>X_Yscores[:, None]</code> (or <code>X_Yscores[:, np.newaxis]</code> as imaluengo suggests). This creates a 2D array out of a 1D array.</p> <p>Example:</p> <pre><code>A = np.array([1, 2, 3]) print A.shape print A[:, None].shape </code></pre> <p>Output:</p> <pre><code>(3,) (3,1) </code></pr...
python|arrays|numpy|concatenation
31
374,316
30,354,637
Grouping and aggregating by counts: how to keep column names?
<p>I have an example dataframe similar to the synthetic one I create below. Each ID is classified as <code>good</code> or <code>bad</code> (these could also be country codes, e.g. <code>US</code>, <code>ES</code>, <code>RU</code>, etc):</p> <pre class="lang-py prettyprint-override"><code>In [55]: nf = pandas.DataFrame...
<p>Well you can just use <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>pandas.DataFrame.reset_index()</code></a> to turn multi-index into columns:</p> <pre><code>In [6]: nf.groupby(['id','how']).agg('count').reset_index().head(10) Out[6]: id h...
python|pandas
2
374,317
30,486,141
Python3 changes function name <...>
<p>I have a pandas df where one column lists a particular func used to get the result in that line of the df.</p> <p>It appears that Python changes the name of a func. if it is part of a list of functions. So Python takes the func name 'strategy0' and changes it to the less useful <code>'&lt;function strategy0 at 0x00...
<p>Another solution if you like map and list</p> <pre><code>strategies = list(map(lambda x: x.__name__, strategies)) </code></pre>
python|pandas
1
374,318
30,328,427
Add months to a datetime column in pandas
<p>I have a dataframe df with 2 columns as below -</p> <pre><code> START_DATE MONTHS 0 2015-03-21 240 1 2015-03-21 240 2 2015-03-21 240 3 2015-03-21 240 4 2015-03-21 ...
<p>This is a vectorized way to do this, so should be quite performant. Note that it doesn't handle month crossings / endings (and doesn't deal well with DST changes. I believe that's why you get the times).</p> <pre><code>In [32]: df['START_DATE'] + df['MONTHS'].values.astype("timedelta64[M]") Out[32]: 0 2035-03-20...
python|python-2.7|python-3.x|pandas|ipython
13
374,319
30,302,520
Parallelize operations for each cell in a numpy array
<p>I am trying to figure out which is the best way to parallelize the execution of a single operation for each cell in a 2D numpy array.</p> <p>In particular, I need to do a bitwise operation for each cell in the array.</p> <p>This is what I do using a single <code>for</code> cycle:</p> <pre><code>for x in range(M):...
<p>I am not familiar with bitwise operations but this here gives me the same result as your code and is vectorized. </p> <pre><code>import numpy as np # make sure it is a numpy.array v = np.array(v) # vectorized computation N = (v &gt;&gt; 7) &amp; 255 </code></pre>
python|numpy|parallel-processing|theano
4
374,320
30,561,617
How to get numpy array from multiple lists of same length and sort along an axis?
<p>I have a very simple question ,How to get numpy array from multiple lists of same length and sort along an axis ?</p> <p>I'm looking for something like: </p> <pre><code>a = [1,1,2,3,4,5,6] b = [10,10,11,09,22,20,20] c = [100,100,111,090,220,200,200] d = np.asarray(a,b,c) print d &gt;&gt;&gt;[[1,10,100],[1,10,100],...
<p>You can zip to get the array:</p> <pre><code>a = [1, 1, 2, 3, 4, 5, 6] b = [10, 10, 11, 9, 22, 20, 20] c = [100, 100, 111, 90, 220, 200, 200] d = np.asarray(zip(a,b,c)) print(d) [[ 1 10 100] [ 1 10 100] [ 2 11 111] [ 3 9 90] [ 4 22 220] [ 5 20 200] [ 6 20 200]] print(d[np.argsort(d[:, 1])]) #...
python|arrays|sorting|numpy
2
374,321
26,601,001
Calculate STD manually using Groupby Pandas DataFrame
<p>I was trying to write a solution for <a href="https://stackoverflow.com/questions/26599347/groupby-pandas-dataframe-and-calculate-mean-and-stdev-of-one-column-and-add-the">this question</a> by providing a different and a manual way to calculate a mean and std. </p> <p>I created the <a href="https://stackoverflow.co...
<p>There are <a href="https://statistics.laerd.com/statistical-guides/measures-of-spread-standard-deviation.php" rel="nofollow noreferrer">two kinds of standard deviations (SD)</a>: the population SD and the sample SD.</p> <p>The population SD</p> <p><img src="https://i.stack.imgur.com/j5p4r.png" alt="enter image des...
python|algorithm|pandas
7
374,322
26,795,616
Randomly select the tuples from the list: type error
<pre><code>import numpy as np x = [1,2,3,4,5,6,7,8,9] y = [11,12,13,14,15,16,17,18,19] </code></pre> <p>I have a list of tuples as follows:</p> <pre><code>xy = [(x,y) for x,y in zip(x,y)] </code></pre> <p>Now I wanted to randomly select 3 position/index of the tuples in the list.</p> <pre><code>random_indices = n...
<p>Convert <code>xy</code> to a NumPy array, lists only support indexing with integers:</p> <pre><code>&gt;&gt;&gt; xy = np.array([(a, b) for a, b in zip(x, y)]) &gt;&gt;&gt; random_indices = np.random.choice(len(xy), 3,replace=False) &gt;&gt;&gt; xy[random_indices] array([[ 7, 17], [ 2, 12], [ 4, 14]]) ...
python|numpy
4
374,323
26,671,112
Error of pytz if frequency of dataframe is below 1 hour for DST change [multiindex pandas]
<p>I face a problem to change the timezone of a dataframe in which frequency is below 1 hour. In my case, I get a quarter-hourly dataframe from a CSV source and I have to delete the DST hour in March and add the DST hour in October. The below function works well if freq is hourly but doesn't work with below freq.</p> ...
<p>A workaround would be to use</p> <pre><code>is_dst = False # or True df = df.tz_localize('Europe/Paris', ambiguous=[is_dst]*len(df)) </code></pre> <p>to explicitly specify if the ambiguous local times should be interpreted as in the Daylight Savings Time zone or not.</p> <hr> <p>By the way, </p> <pre><code>df[...
python|pandas|timezone|pytz|multi-index
1
374,324
26,666,799
Array/List from txt file in Python
<p>I was trying to get value from .txt file into array/list in python. Let's say I have this data in user.txt :</p> <pre><code> ghost:001 ghost:002 ghost:003 </code></pre> <p>So, when I want to output it as :</p> <pre><code> 'ghost:001','ghost:002','ghost:003' </code></pre> <p>I use this function</p> <pre><c...
<p>I would store the users in a dict where the keys increment for each user:</p> <pre><code>d = {} with open("in.txt") as f: user = 1 for line in f: d[user]= line.rstrip() user += 1 print(d) {1: 'ghost:001', 2: 'ghost:002', 3: 'ghost:003'} </code></pre> <p>If you just want a list of user and to ...
python|arrays|pandas
1
374,325
26,787,755
How can I access multiple columns in Pandas 0.15 DataFrame.resample method?
<p>In Pandas 0.12, if you used the resample method on a DataFrame with a custom resampling function, it would make one call per dataframe row to the custom function, giving access to the values in all columns. In Pandas 0.15, the resample method calls my custom function once per dataframe entry, and the only available ...
<p>I don't know why the behavior changed, but think using a <code>TimeGrouper</code> and <code>groupby</code> can get you back to the old results, although will error out unless foo is given a return value.</p> <pre><code>In [496]: df.groupby(pd.TimeGrouper('D')).apply(foo) *** a b 2014-01-01 1 x *** Em...
pandas
0
374,326
26,618,964
Convert list of tuples in tabular format in python
<p>What is an elegant way to convert a list of tuples into tables in the following form?</p> <p>Input:</p> <pre><code>from pandas import DataFrame mytup = [('a','b',1), ('a','c',2), ('b','a',2), ('c','a',3), ('c','c',1)] a b 1 a c 2 b a 2 c a 3 c c 1 mydf...
<p><code>pivot</code> and <code>fillna</code> are what you want:</p> <pre><code>import pandas as pd mytup = [('a','b',1), ('a','c',2), ('b','a',2), ('c','a',3), ('c','c',1)] mydf = pd.DataFrame(mytup, columns=['from', 'to', 'val']) mydf.pivot(index='from', columns='to', values='val').fillna(value='-') to a b c ...
python|pandas
7
374,327
39,007,934
Error installing bazel for tensorflow: command not found
<p>I am trying to use bazel to run retrain Inception's Final Layer for New Categories in Tensorflow.</p> <p>I have limited knowledge of anything other than jupyter notebooks, so terminal work = copying and pasting.</p> <p>I installed bazel via brew. So it's there somewhere.</p> <p>When I run:</p> <pre><code>bazel b...
<p>Try running:</p> <pre><code>$ brew info bazel </code></pre> <p>This should print a path to wherever it installed Bazel. You can either use it from there (<code>/usr/local/Cellar/bazel/0.3.1/bin/bazel build tensorflow/and/so/on</code>) or create a symlink to somewhere on your PATH, e.g.,</p> <pre><code>$ mkdir $H...
cmd|terminal|tensorflow|bazel
1
374,328
39,281,956
Remove columns where all items in column are identical (excluding header) and match a specified string
<p>My question is an extension of <a href="https://stackoverflow.com/questions/21164910/delete-column-in-pandas-based-on-condition">Delete Column in Pandas based on Condition</a>, but I have headers and the information isn't binary. Instead of removing a column containing all zeros, I'd like to be able to pass a variab...
<p>You can check the number of <code>non-red</code> item in the column, if it is not zero then select it using <code>loc</code>:</p> <pre><code>df.loc[:, (df != 'red').sum() != 0] # Name Header2 Header3 # 0 name1 red red # 1 name2 orange red # 2 name3 yellow red # 3 name4 gree...
python|pandas
2
374,329
39,407,254
how to set the primary key when writing a pandas dataframe to a sqlite database table using df.to_sql
<p>I have created a sqlite database using pandas df.to_sql however accessing it seems considerably slower than just reading in the 500mb csv file. </p> <p>I need to: </p> <ol> <li>set the primary key for each table using the df.to_sql method</li> <li>tell the sqlite database what datatype each of the columns in my 3....
<p>Unfortunately there is no way right now to set a primary key in the pandas df.to_sql() method. Additionally, just to make things more of a pain there is no way to set a primary key on a column in sqlite after a table has been created. </p> <p>However, a work around at the moment is to create the table in sqlite wit...
python|sqlite|pandas|primary-key
15
374,330
39,226,024
how to convert header row into new columns in python pandas?
<p>I am having following dataframe:</p> <pre><code>A,B,C 1,2,3 </code></pre> <p>I have to convert above dataframe like following format:</p> <pre><code>cols,vals A,1 B,2 c,3 </code></pre> <p>How to create column names as a new column in pandas?</p>
<p>You can transpose by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.T.html" rel="nofollow"><code>T</code></a>:</p> <pre><code>import pandas as pd df = pd.DataFrame({'A': {0: 1}, 'C': {0: 3}, 'B': {0: 2}}) print (df) A B C 0 1 2 3 print (df.T) 0 A 1 B 2 C 3 df1 = df...
python|python-2.7|pandas|dataframe|transpose
2
374,331
39,299,726
Can't find package on Anaconda Navigator. What to do next?
<p>I am trying to install "pulp" module in Anaconda Navigator's Environment tabs. But when I search in "All" packages I can't find it. It happened with other packages too. </p> <p><a href="https://i.stack.imgur.com/JqYIF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/JqYIF.png" alt="enter image description ...
<ol> <li><p>Click <em>Open Terminal</em> from environment.</p> <p><a href="https://i.stack.imgur.com/EiiFc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EiiFc.png" alt="open" /></a></p> </li> <li><p>Execute <code>conda install (package-name)</code> in terminal mode. (The image below shows the insta...
python|numpy|scipy|anaconda|pulp
30
374,332
39,119,025
I write my program with following the steps of Building Autoencoders in Keras in Keras blog, but it errors as follows:
<pre><code> callbacks=[TensorBoard(log_dir='/Users/lyj/Programs/KiseliuGit/DeepLearning/tmp/autoencoder')]) File "/Library/Python/2.7/site-packages/keras/callbacks.py", line 457, in __init__ raise Exception('TensorBoard callback only works ' Exception: TensorBoard callback only works with the TensorFlow backend. <...
<p>Change your backend keras from theano to tnesorflow from .keras.json file</p>
tensorflow|keras
2
374,333
39,396,694
Running tensorflow as daemon and piping all output to log file
<p>To run tensorflow model as daemon I use : </p> <pre><code>nohup python translate.py --data_dir data &amp; </code></pre> <p>This logs error messages to nohup.out but it does not capture Tensorflow stdout . This thread offers describes related : <a href="https://groups.google.com/a/tensorflow.org/forum/#!topic/discu...
<p>Why not try </p> <pre><code>nohup python translate.py --data_dir data &amp;&gt; outputfile.txt </code></pre> <p>You can then suspend the file your self with kill -19 %1 to suspend the first job or whatever number its present as. Then kill -CONT %1 to restart it. </p> <p>Other options:</p> <ul> <li>"disown" comma...
python|linux|tensorflow
0
374,334
39,276,650
Python Pandas ValueError on simple query
<p>The following line causes a ValueError (Pandas 17.1), and I'm trying to understand why.</p> <pre><code>x = (matchdf['ANPR Matched_x'] == 1) </code></pre> <p>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p> <p>I'm trying to use it for following conditio...
<p>Use <code>loc</code> to set the values.</p> <pre><code>matchdf.loc[matchdf['APNR Matched_x'] == 1, 'FullMatch'] = 1 </code></pre> <p><strong>Example</strong></p> <pre><code>df = pd.DataFrame({'APNR Matched_x': [0, 1, 1, 0], 'Full Match': [False] * 4}) &gt;&gt;&gt; df APNR Matched_x Full Match 0 ...
python|pandas|numpy
2
374,335
39,000,115
How can I set the colors per value when coloring plots by a DataFrame column?
<p>In matplotlib (in particular, pandas), how can I map specific colors to values of a column that I use for differentiating colors?</p> <p>Let's say I have a column ...</p> <pre><code>&gt;&gt; df["country"] DE EN US DE </code></pre> <p>... and now I'd like to plot values from the DataFrame where each country is col...
<p>You can do so by specifying the dictionary mapping of hue levels to corresponding <code>matplotlib</code> colors in the <a href="https://stanford.edu/~mwaskom/software/seaborn/tutorial/color_palettes.html" rel="noreferrer"><code>palette</code></a> argument of a <a href="https://stanford.edu/~mwaskom/software/seaborn...
python|pandas|matplotlib|colors|seaborn
8
374,336
39,071,334
Solving Non-Linear Differential Equation Sympy
<p>This code only works for solving the differential equation v_equation if v(t) isn't squared. When I squared it it returned the error PolynomialDivisionFailed. Is there another way of doing this with Sympy or should I find a different python package for doing these sorts of calculations.</p> <pre><code>from sympy im...
<p>From my experience with symbolic math packages, I would not recommend performing (symbolic) calculations using floating point constants. It is better to define equations using symbolic constants, perform calculations as far as possible, and then substitute with numerical values. </p> <p>With this approach, Sympy ca...
python|numpy|sympy
4
374,337
39,376,891
Why is numpy's sine function so inaccurate at some points?
<p>I just checked <code>numpy</code>'s <code>sine</code> function. Apparently, it produce highly inaccurate results around pi. </p> <pre><code>In [26]: import numpy as np In [27]: np.sin(np.pi) Out[27]: 1.2246467991473532e-16 </code></pre> <p>The expected result is 0. Why is <code>numpy</code> so inaccurate there?<...
<p>The main problem here is that <code>np.pi</code> is not exactly π, it's a finite binary floating point number that is close to the true irrational real number π but still off by ~1e-16. <code>np.sin(np.pi)</code> is actually returning a value closer to the true infinite-precision result for <code>sin(np.pi)</code> (...
python|numpy|floating-point
7
374,338
39,309,327
Why does this piece of code gets slower with time?
<p>I'm trying to preprocess my images adding them to a 4D array. It starts off right but it gets slower with time, I thought this was due to my CPU but I tried running it on a GPU on the cloud and it still gets slower. Is this due to RAM? How can I optimize this to run faster?</p> <pre><code>import tensorflow as tf im...
<p>I don't know much about TensorFlow, but I believe the problem is <code>process_image</code> is using a bunch of globals, particularly <code>tf</code>. Every time it's called you're running TensorFlow on an ever increasing set of images. First there's <a href="https://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2...
python|performance|numpy|tensorflow
1
374,339
39,232,013
Extracting tables using pandas read_html function?
<p>This is an unusual problem. I am trying to extract a table from certain website(link cant be given because of security). The problem is that the site will load the table when accessed through website but when we use <code>inspect element</code> on any values/tables on that table it is not visible. It just show <code...
<p>When data scraping off a secure website, the website can be using Java to load the tables so you never see the HTML-styled code. This could be why BeautifulSoup is not returning anything. </p> <p>Does the "scripts and links inside" look like Java? </p> <p>Maybe have a look at <a href="http://selenium-python.readth...
python|html|pandas|web-scraping
0
374,340
19,550,655
numpy: modifyng a transposed array don't work as expected
<p>I have, from a more complex program, this code:</p> <pre><code>import numpy as np ph=np.arange(6).reshape([2,3]) T=np.transpose(ph) print 'T:\n',T print 'ph:\n',ph # printing arrays before for cycle for i in range(0,len(T)): T[i]=2*T[i] print 'ph:\n', ph # printing arrays after for cycle...
<p>You can find the reason in the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html" rel="nofollow">docstring of <code>np.transpose</code></a>:</p> <pre><code> Returns ------- p : ndarray `a` with its axes permuted. A view is returned whenever possible. </code></pre> <p>Sol...
python|numpy|transpose
3
374,341
19,623,150
Issue installing Numpy on Mac OSX using virtualenv
<p>I am attempting to install Numpy via pip (Python version 2.7.5) and keep running into an error that states:</p> <p>SystemError: Cannot compile 'Python.h'. Perhaps you need to install python-dev|python-devel</p> <p>I am using virtualenv with virtualenv wrapper if that helps. I installed python via homebrew</p>
<p>You need to install the python development package from homebrew:</p> <pre><code>brew install python-dev </code></pre> <h2>edit</h2> <p>Indeed, the homebrew formula does not exist. You could find the missing headers by following these steps: <a href="https://stackoverflow.com/questions/15931331/how-to-install-the...
python|macos|numpy
0
374,342
19,472,566
python read_fwf error: 'dtype is not supported with python-fwf parser'
<p>Using python 2.7.5 and pandas 0.12.0, I'm trying to import fixed-width-font text files into a DataFrame with 'pd.io.parsers.read_fwf()'. The values I'm importing are all numeric, but it's important that leading zeros be preserved, so I'd like to specify the dtype as string rather than int.</p> <p>According to the ...
<p>Instead of specifying dtypes, specify a converter for the column you want to keep as str, building on @TomAugspurger's example:</p> <pre><code>from io import StringIO import pandas as pd data = StringIO(u""" 121301234 121300123 121300012 """) pd.read_fwf(data, colspecs=[(0,3),(4,8)], converters = {1: str}) </code>...
python|parsing|pandas
8
374,343
19,721,838
reprojectImageTo3D() typeError, OpenCV Python
<p>I'm not able to use reprojectImageTo3D() using python in the latest openCV version. I keep getting "TypeError: disparity is not a numpy array". It's an iplImage of course.</p> <pre><code>disparityImg = CreateImage( (320,240), IPL_DEPTH_32F, 1) depthMapImg = CreateImage( (320,240), IPL_DEPTH_32F, 3) depthMapImg = re...
<p>take a sharp look : it's cv2.reprojectImageTo3D (or, cv.Reproject...)</p> <p>seems, you're trying to mix the old (deprecated) cv api with the newer cv2 one. <em>don't</em> !</p> <p>cv is using wrapped IplImages, cv2 is using numpy arrays</p> <p>so, discard the old cv api, as it won't be supported in future vers...
python|arrays|opencv|numpy
1
374,344
19,624,104
Equations in Python
<p>I'm trying to implement an equation from a paper in Python (black square equations) -</p> <p><img src="https://i.stack.imgur.com/ePalE.png" alt="enter image description here"></p> <p>So far I have a simplified model but I'm unable to generate the intended output (below image); I suspect the issue is with <a href="...
<p>To illustrate Jacob's comment, here's what you can get by tweaking the constants:</p> <p><img src="https://i.stack.imgur.com/ZMeXP.png" alt="Graph"></p> <p>Code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt f = 5 Omega = 2*np.pi*f i = np.arange(0, 10, 0.001) y = np.sin(Omega*i) * (i**2)...
python|numpy|plot
2
374,345
19,731,012
Combine first two entries in each column as the header when reading excel file
<p>I've been searching this for a while but still can't figure it out. I appreciate if you can provide me some help.</p> <p>I have an excel file:</p> <pre><code> , John, James, Joan, , Smith, Smith, Smith, Index1, 234, 432, 324, Index2, 2987, 234, 4354, </code></pre> <p...
<p>May be it's easier to do by hand?:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; xl = pd.ExcelFile(myfile, header=None) &gt;&gt;&gt; sh = xl.book.sheet_by_index(0) &gt;&gt;&gt; rows = (sh.row_values(i) for i in xrange(sh.nrows)) &gt;&gt;&gt; hd = zip(*itertools.islice(rows, 2))[1:] # read first two r...
python|excel|pandas
1
374,346
12,886,240
iter over dataframe
<p>I want to iterate over a Dataframe like this:</p> <pre><code>for i in y.itertuples(): print i </code></pre> <p>result:</p> <pre><code>(datetime.date(2012, 9, 10), 63.930000305175781, 64.589996337890625, 63.880001068115234, 64.099998474121094, 507700.0, 64.099998474121094) (datetime.date(2012, 9, 11), 63.490001678...
<pre><code>pd.DataFrame.from_records([i], index=0) </code></pre>
python|pandas
2
374,347
12,841,827
Accessing pandas Multiindex Dataframe using integer indexes
<p>I have the following pandas Dataframe:</p> <pre><code>from pandas import DataFrame, MultiIndex index = MultiIndex.from_tuples(zip([21,22,23],[45,45,46]), names=['A', 'B']) df = DataFrame({'values': [0.67, 0.87, 0.23]}, index=index) Out[10]: values A B 21 45 0.67 22 45 0.87 23 46 0.23 </...
<p>Last two are the correct syntax, but there is a (<a href="https://github.com/pydata/pandas/issues/2051" rel="nofollow">bug</a> preventing to display the result.</p> <pre><code>s = df.ix[(22, 45)] </code></pre> <p>works fine, but you can not display it</p>
python|pandas
2
374,348
28,974,425
Calculating Kendall's tau using scipy and groupby
<p>I have a csv file with precipitation data per year and per weather station. It looks like this:</p> <pre><code>station_id year Sum 210018 1916 65.024 210018 1917 35.941 210018 1918 28.448 210018 1919 68.58 210018 1920 31.115 215400 1916 44....
<p>One way to calculate this is to use <code>apply</code> on the <code>groupby</code> object:</p> <pre><code>&gt;&gt;&gt; import scipy.stats as st &gt;&gt;&gt; df.groupby(['station_id']).apply(lambda x: st.kendalltau(x['year'], x['Sum'])) station_id 210018 (-0.2, 0.62420612399) 215400 (0.4, 0.32718689066...
python|pandas|dataframe|scipy|statistics
9
374,349
29,093,235
How to calculate group by cumulative sum for multiple columns in python
<p>I have a data set like,</p> <pre><code>data=pd.DataFrame({'id':pd.Series([1,1,1,2,2,3,3,3]),'var1':pd.Series([1,2,3,4,5,6,7,8]),'var2':pd.Series([11,12,13,14,15,16,17,18]), 'var3':pd.Series([21,22,23,24,25,26,27,28])}) </code></pre> <p>Here I need to calculate groupwise cumulative sum for all columns(var1,var2,var...
<p>If I have understood you right, you can use <code>DataFrame.groupby</code> to calculate the cumulative sum across columns grouped by your <code>'id'</code>-column. Something like:</p> <pre><code>import pandas as pd data=pd.DataFrame({'id':[1,1,1,2,2,3,3,3],'var1':[1,2,3,4,5,6,7,8],'var2':[11,12,13,14,15,16,17,18], ...
python|pandas
2
374,350
29,068,715
How can I repeat this array of 2d pairs using Numpy?
<p>I have an array that I want to repeat.</p> <p><code>test = numpy.array([(1, 11,), (2, 22), (3, 33)])</code></p> <p>Now</p> <pre><code>numpy.repeat(test, 2, 0) numpy.repeat(test, 2, 1) </code></pre> <p>results in</p> <pre><code>array([[ 1, 11], [ 1, 11], [ 2, 22], [ 2, 22], [ 3, 33], ...
<p><code>np.tile</code> lets you specify repeats for each axis (as a tuple)</p> <pre><code>In [370]: np.tile(test,(2,1)) Out[370]: array([[ 1, 11], [ 2, 22], [ 3, 33], [ 1, 11], [ 2, 22], [ 3, 33]]) </code></pre>
python|arrays|numpy|repeat
6
374,351
29,230,866
how to generate histogram in pandas with x-axis labels from column?
<p>Given the following dataframe:</p> <pre><code>import pandas as pd df = pd.read_json('{"genre":{"0":"Drama","1":"Comedy","2":"Action","3":"Thriller"},"count":{"0":1603,"1":1200,"2":503,"3":492}}') </code></pre> <p>Is there a pandas one-liner/fast way to generate a histogram where bars are based on the "count" colum...
<p>Yes you can select the columns to be used with the <code>x</code> and <code>y</code> keyword arguments. You also select the kind of plot you want, in this case a hist, using <code>kind='bar'</code>.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_json('{"genre":{"0":"Drama","1":"Com...
python|pandas
9
374,352
29,253,027
pandas scatter plot colors with three points and seaborn
<p>There is a strange behavior when using pandas and seaborn to plot a scatter plot that has only three points: the points don't have the same color. The problem disappears when seaborn is not loaded or when there are more than three points, or when plotting with matplotlib's scatter method directly. See the following ...
<p>I've tracked down the bug. The bug is in <code>pandas</code> technically, not <code>seaborn</code> as I originally thought, though it involves code from <code>pandas</code>, <code>seaborn</code>, and <code>matplotlib</code>...</p> <p>In <a href="https://github.com/pydata/pandas/blob/master/pandas/tools/plotting.py#...
python|pandas|seaborn
6
374,353
28,910,231
Failing to convert Pandas dataframe timestamp
<p>I'm pretty new to working with Pandas and am trying to figure out why this timestamp won't convert. As an example, one individual timestamp is the string <code>'2010-10-06 16:38:02'</code>. The code looks like this:</p> <pre><code>newdata = pd.DataFrame.from_records(data, columns = ["col1", "col2", "col3", "timesta...
<p>I've been asked to add a formal answer instead of just editing my question, so here it is. Note it builds off the answer above, but that that one didn't quite work for me.</p> <p><code>newdata.index=pd.DatetimeIndex(newdata.index).tz_localize('UTC').tz_convert('US/‌​Eastern')</code></p>
python|indexing|pandas|timezone|timestamp
4
374,354
29,144,921
Numpy local maximas in one dimension of 2D array
<p>I'd like to find the local maximas of a 2D array but only in one dimension. Ie:</p> <pre><code>1 2 3 2 1 1 4 5 6 2 2 2 3 3 3 2 2 2 2 2 1 2 3 2 2 2 2 3 3 3 </code></pre> <p>would return:</p> <pre><code>0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 </code></pre> <p>Obviously this is trivial to so...
<p>You can solve this by applying finite difference gradient to each row and check sign change. However it is not clear what to do at the boundaries.</p>
python|arrays|numpy
1
374,355
33,611,782
Pandas dataframe from nested dictionary
<p>My dictionary looks like this:</p> <pre><code>{'x': {'b': 10, 'c': 20}, 'y': {'b': '33', 'c': 44}} </code></pre> <p>I want to get a dataframe that looks like this:</p> <pre><code>index col1 col2 val 0 x b 10 1 x c 20 2 y b 33 3 y c 44...
<p>You can use a list comprehension to reorder your dict into a list of tuples where each tuple is a row and then you can sort your dataframe</p> <pre><code>import pandas as pd d = {'x': {'b': 10, 'c': 20}, 'y': {'b': '33', 'c': 44}} df = pd.DataFrame([(k,k1,v1) for k,v in d.items() for k1,v1 in v.items()], columns ...
python|dictionary|pandas|dataframe
5
374,356
33,784,214
How to test tensorflow cifar10 cnn tutorial model
<p>I am relatively new to machine-learning and currently have almost no experiencing in developing it.</p> <p>So my <strong>Question</strong> is: after training and evaluating the cifar10 dataset from the tensorflow <a href="http://www.tensorflow.org/tutorials/deep_cnn/index.html" rel="noreferrer">tutorial</a> I was w...
<p>This isn't 100% the answer to the question, but it's a similar way of solving it, based on a MNIST NN training example suggested in the comments to the question.</p> <p>Based on the TensorFlow begginer MNIST tutorial, and thanks to <a href="http://opensourc.es/blog/tensorflow-mnist" rel="noreferrer">this tutorial</...
python|testing|machine-learning|tensorflow
11
374,357
33,627,662
Python Email in HTML format mimelib
<p>I am trying to send two dataframes created in Pandas Python as a html format in an email sent from the python script.</p> <p>I want to write a text and the table and repeat this for two more dataframes but the script is not able to attach more than one html block. The code is as follows:</p> <pre><code>import nump...
<p>The problem is that you are marking up the parts as <code>multipart/alternative</code> -- this means, "I have the information in multiple renderings; choose the one you prefer" and your email client is apparently set up to choose the HTML version. Both parts are in fact there, but you have tagged them as either/or ...
python|email|pandas|mime
2
374,358
33,920,544
Avoiding numerical instability when computing 1/(1+exp(x)) python
<p>I would like to compute 1/(1+exp(x)) for (possibly large) x. This is a well behaved function between 0 and 1. I could just do</p> <pre><code>import numpy as np 1.0/(1.0+np.exp(x)) </code></pre> <p>but in this naive implementation np.exp(x) will likely just return 0 or infinity for large x, depending on the sign. ...
<p>You can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.expit.html" rel="nofollow"><code>scipy.special.expit(-x)</code></a>. It will avoid the overflow warnings generated by <code>1.0/(1.0 + exp(x))</code>.</p>
python|numpy|floating-point|scipy|expansion
5
374,359
33,771,675
pandas concat/merge and sum one column
<p>I have two <code>pandas.DataFrame</code> objects with <code>MultiIndex</code> indices. Some of the index values are shared with the two dataframes, but not all. I would like to merge these two data frames and take the sum of one of the columns if the row (index value) exists. Otherwise, keep the row and column value...
<p>In this particular case, I think you could just add them and use <code>fill_value=0</code>, relying on the default alignment behaviour:</p> <pre><code>&gt;&gt;&gt; df1.add(df2,fill_value=0) a b c A0 C0 0 7 NaN C1 1 6 NaN A1 C0 2 5 NaN C1 3 4 NaN A2 C0 4 3 5 C1 5 3 4 A3 C0 ...
python|pandas
7
374,360
33,736,845
Flag dates that are between a range
<p>I have the following dataframe:</p> <pre><code> exdiv_date expiry_date 0 2015-09-18 2015-12-18 1 2015-11-20 2015-12-18 2 NaN 2016-01-20 3 2015-12-26 2016-01-15 4 NaN 2015-11-21 </code></pre> <p>I need to flag each row where the exdiv_date is after today and before...
<p>There is problem with brackets - use <code>dt.date.today()</code>.</p> <p>You can use alternatively <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow">np.where</a>:</p> <pre><code>import datetime as dt # exdiv_date expiry_date #0 2015-09-18 2015-12-18 #1 2015-11...
python|pandas
1
374,361
33,742,098
border/edge operations on numpy arrays
<p>Suppose I have a 3D numpy array of nonzero values and <code>"background" = 0</code>. As an example I will take a sphere of random values:</p> <pre><code>array = np.random.randint(1, 5, size = (100,100,100)) z,y,x = np.ogrid[-50:50, -50:50, -50:50] mask = x**2 + y**2 + z**2&lt;= 20**2 array[np.invert(mask)] = 0 </co...
<p>I think it's best to start out with the 2D case first, since it can be visualized much more easily:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt A = np.random.randint(1, 5, size=(100, 100)).astype(np.double) y, x = np.ogrid[-50:50, -50:50] mask = x**2 + y**2 &lt;= 30**2 A[~mask] = 0 </cod...
python|numpy|scipy
11
374,362
33,763,963
pandas data frame headers are shifted over when perfoming csv read
<p>I'm trying to read data from a csv file into a pandas data frame but the headers are shifting over two columns when read into data frame. </p> <p>I think it has to do with there being two blank rows after the header, but I'm not sure. It seems to be reading in the first two columns as row titles/indexes.</p> <p>CS...
<p>Your csv data does look strange - you have 20 column headers, but 22 entries in the first line with data.</p> <p>Assuming this is only a copy-paste error*, you can try the following:</p> <pre><code>df = pd.read_csv(file, skiprows=[1,2], index_col=False) </code></pre> <p><code>skiprows</code> will skip the two empty ...
python|csv|pandas
8
374,363
33,951,194
Density profile integral over line of sight
<p>My question is like this:</p> <p>I know the density as a function of radius for a sphere numerically. Say density rho(1000) and radius(1000) are already calculated numerically. I want to find the integration of the density over a line of sight, as shown below in 2D, although it is a 3D problem: <a href="https://i.s...
<p>I have the implementation below (assume density profile <code>rho = exp(1-log(1+r/rs)/(r/rs))</code>):</p> <p>The first approach is much faster because it does not need to deal with the singularity from <code>r/np.sqrt(r**2-r_p**2)</code>.</p> <pre><code>import numpy as np from scipy import integrate as integrate ...
python|numpy|scipy|integration|integral
1
374,364
23,848,003
Detecting mulicollinear , or columns that have linear combinations while modelling in Python : LinAlgError
<p>I am modelling data for a logit model with 34 dependent variables,and it keep throwing in the singular matrix error , as below -:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#1116&gt;", line 1, in &lt;module&gt; test_scores = smf.Logit(m['event'], train_cols,missing='drop').fit() Fil...
<p>Several points to this:</p> <p>You need tol > 0 to detect near perfect collinearity, which might also cause numerical problems in later calculations. Check the number of columns of <code>A2</code> to see whether a column has really be dropped. </p> <p>Logit needs to do some non-linear calculations with the exog, s...
python-2.7|numpy|statsmodels|logistic-regression|singular
6
374,365
23,706,412
Merge a lot of DataFrames together, without loop and not using concat
<p>I have >1000 DataFrames, each have >20K rows and several columns, need to be merge by a certain common column, the idea can be illustrated by this:</p> <pre><code>data1=pd.DataFrame({'name':['a','c','e'], 'value':[1,3,4]}) data2=pd.DataFrame({'name':['a','d','e'], 'value':[3,3,4]}) data3=pd.DataFrame({'name':['d','...
<p>Does it even make sense to merge it, then? What's wrong with a panel?</p> <pre><code>&gt; data = [data1, data2, data3, data4] &gt; p = pd.Panel(dict(zip(map(str, range(len(data))), data))) &gt; p.to_frame().T major 0 1 2 minor name value name value name value 0 a 1 c 3 ...
python|pandas
1
374,366
23,815,527
Pandas / Numpy: Issues with np.where
<p>I have a strange problem with <code>np.where</code>. I first load a database called <code>df</code> and create a duplicate of <code>df</code>, <code>df1</code>. I then use <code>np.where</code> to make each value in <code>df1</code> be 1 if the number in the cell is greater or equal to its mean (found in the DataFra...
<p>Although this is not what you asked for, but my spidy sense tells me, you want to find some form of indicator, if a stock is currently over or underperforming in regard of "something" using the mean of this "something". Maybe try this:</p> <pre><code>S = pd.DataFrame( np.array([[1.2,3.4],[1.1,3.5],[1.4,3.3],[1...
python|numpy|pandas
1
374,367
22,780,563
Group labels in matplotlib barchart using Pandas MultiIndex
<p>I have a pandas DataFrame with a MultiIndex:</p> <pre><code>group subgroup obs_1 obs_2 GroupA Elem1 4 0 Elem2 34 2 Elem3 0 10 GroupB Elem4 5 21 </code></pre> <p>and so on. As noted in <a href="https://stackoverflow.com/questions/19184484/...
<p>If you have just two levels in the <code>MultiIndex</code>, I believe the following will be easier:</p> <pre><code>plt.figure() ax = plt.gca() DF.plot(kind='bar', ax=ax) plt.grid(True, 'both') minor_XT = ax.get_xaxis().get_majorticklocs() DF['XT_V'] = minor_XT major_XT = DF.groupby(by=DF.index.get_level_values(0))....
python|matplotlib|pandas
5
374,368
22,891,523
Joining 2 data frames with overlapping data
<p>I have 2 data frames created by pivot tables</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np df=pd.DataFrame({'axis1': ['Unix','Window','Apple','Linux'], 'A': [1,np.nan,1,1], 'B': [1,np.nan,np.nan,1], 'C': [np.nan,1,np.nan,1],...
<p>you want to <a href="http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.DataFrame.reindex.html" rel="nofollow">reindex</a> your first Dataframe before you call update</p> <p>one robust way would be to calculate the union of both columns and rows of both df, maybe there is a smarter way, but I can'...
python|join|pandas
0
374,369
22,749,007
plotting pandas data frame with unequal data set
<p>I am trying to plot a pandas Data Frame that contain an unequal amount of data points (rows) and I am not sure if this is causing an issue for my plot.</p> <p>in the below code, the portfolioValue# differs in length</p> <pre><code>portfolioValue1 = 521 portfolioValue1 = 500 portfolioValue1 = 521 portfolioValue1 = ...
<p>They need to be of equal length, for example, we can shorten everything to 425 elements:</p> <pre><code>portfolioValue1 = random.random(521) portfolioValue2 = random.random(500) portfolioValue3 = random.random(521) portfolioValue4 = random.random(521) portfolioValue5 = random.random(425) portDFrame=DataFrame(z...
python|plot|pandas|dataframe
0
374,370
22,787,602
Python pandas: Slicing /indexing confusion
<p>I am solving some model using pandas/Python. However I get some very strange results when selecting data. I suspect I am not understanding something very fundamental.</p> <p>The index of the DataFrame is a pandas quarterly timeseries.</p> <p>The problem is when I write:</p> <pre><code>data.SI_PER </code></pre> <...
<p>This is from 0.13.1, works ok</p> <pre><code>In [16]: df = DataFrame(np.random.randn(10,2),index=period_range('2013',periods=10, freq='Q-JAN'),columns=['A','B']) In [17]: df Out[17]: A B 2013Q4 -0.905673 2.670701 2014Q1 -0.465485 -1.849802 2014Q2 -0.526230 -1.265586 2014Q3 -0.515863 -0.464...
python|pandas
2
374,371
22,752,931
SKLearn Cross Validation Error -- Type Error
<p>I'm attempting to implement cross validation on the results from my KNN classifier. I have used the following code, which returns a type error.</p> <p>For context, I have already imported SciKit Learn, Numpy, and Pandas libraries.</p> <pre><code>from sklearn.cross_validation import cross_val_score, ShuffleSplit n...
<p>This is an error related to pandas. Scikit learn expects numpy arrays, sparse matrices or objects that behave similarly to these.</p> <p>The main issue with pandas DataFrames is due to the fact that indexing with [...] chooses columns and not lines. Line indexing in pandas is done through DataFrame.loc[...]. This i...
python|numpy|pandas|scikit-learn|cross-validation
1
374,372
22,837,305
Want to create a thumbnail(25,25) of an Image of size (181,256) using python
<p>I want to create thumbnail(25,25) of an image whose size is 181 x 256. But when i run the code i get the output image of (17,25) thumbnail image . Why am i not getting a image of 25 x 25 height and width?</p> <pre><code>from PIL import Image from numpy import * size=25,25 im=array(Image.open('D:/1.png')) im.thumbna...
<pre><code>from PIL import Image from numpy import * size=25,25 im=(Image.open('...')) im = im.resize(size, Image.ANTIALIAS) im.save("Thumbnail.png","PNG") imgArr = array(im) print imgArr.shape </code></pre>
python|python-2.7|image-processing|numpy|python-imaging-library
1
374,373
22,798,934
Pandas long to wide reshape, by two variables
<p>I have data in long format and am trying to reshape to wide, but there doesn't seem to be a straightforward way to do this using melt/stack/unstack:</p> <pre><code>Salesman Height product price Knut 6 bat 5 Knut 6 ball 1 Knut 6 wand 3 Stev...
<p>Here's another solution more fleshed out, taken from <a href="https://chrisalbon.com/python/data_wrangling/pandas_long_to_wide/" rel="noreferrer">Chris Albon's site</a>. </p> <h3>Create "long" dataframe</h3> <pre><code>raw_data = {'patient': [1, 1, 1, 2, 2], 'obs': [1, 2, 3, 1, 2], 'treat...
python|pandas|stata|reshape
60
374,374
22,902,040
Convert black and white array into an image in python?
<p>I have an array of 50x50 elements of which each is either True or False - this represents a 50x50 black and white image.</p> <p>I can't convert this into image? I've tried countless different functions and none of them work.</p> <pre><code>import numpy as np from PIL import Image my_array = np.array([[True,False,...
<p>First you should make your array 50x50 instead of a 1d array:</p> <pre><code>my_array = my_array.reshape((50, 50)) </code></pre> <p>Then, to get a standard 8bit image, you should use an unsigned 8-bit integer dtype:</p> <pre><code>my_array = my_array.reshape((50, 50)).astype('uint8') </code></pre> <p>But you don...
python|arrays|image-processing|numpy|python-imaging-library
11
374,375
15,471,936
Writing calculation results back into its array?
<p>Something of a follow-up question to <a href="https://stackoverflow.com/questions/15374291/writing-a-faster-python-physics-simulator">my last one</a> about writing efficient python programs. I have been playing with writing my own physics simulations, and want to get away from using a billion classes and methods.</p...
<p>I think, you just invoke your routine the wrong way (probably passing it the entire particle array instead of the array for only one particle.</p> <p>Anyway, on other possible solution would be to split your array in individual arrays:</p> <pre><code>import numpy as np pos = np.array([[200,0], [210,210], [215,215]...
python|multidimensional-array|numpy|scientific-computing
2
374,376
15,316,985
Numpy: regrid by averaging?
<p>I'm trying to regrid a numpy array onto a new grid. In this specific case, I'm trying to regrid a power spectrum onto a logarithmic grid so that the data are evenly spaced logarithmically for plotting purposes.</p> <p>Doing this with straight interpolation using <code>np.interp</code> results in some of the origin...
<p>You can use <code>bincount()</code> twice to calculate the average value of every bins:</p> <pre><code>logpsw2 = np.interp(logfreq, xfreq, psw) counts = np.bincount(inds) mask = counts != 0 logpsw2[mask] = np.bincount(inds, psw)[mask] / counts[mask] </code></pre> <p>or use <code>unique(inds, return_inverse=True)<...
numpy
1
374,377
14,928,169
looping through an array to find euclidean distance in python
<p>This is what I have thus far:</p> <pre><code>Stats2003 = np.loadtxt('/DataFiles/2003.txt') Stats2004 = np.loadtxt('/DataFiles/2004.txt') Stats2005 = np.loadtxt('/DataFiles/2005.txt') Stats2006 = np.loadtxt('/DataFiles/2006.txt') Stats2007 = np.loadtxt('/DataFiles/2007.txt') Stats2008 = np.loadtxt('/DataFiles/20...
<p>To do the loop you will need to <a href="http://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html" rel="nofollow">keep data out of your variable names</a>. A simple solution would be to use dictionaries instead. The loops are implicit in the dict comprehensions:</p> <pre><code>import itertoo...
python|loops|numpy
2
374,378
15,089,310
repeat arange with numpy
<p>I have an array with integer values.</p> <pre><code>a = [2,1,4,0,2] </code></pre> <p>I want a apply arange function to each value in a so as to have : </p> <pre><code>b = [0,1,0,0,1,2,3,1,2] b "=" [arange(2),arange(1),arange(4),arange(0),arange(2)] </code></pre> <p>In fact I use a np.repeat function to repeat a...
<p>There are definitely more numpythonic ways of doing things. One possibility could be something like this:</p> <pre><code>import numpy as np from numpy.lib.stride_tricks import as_strided def concatenated_ranges(ranges_list) : ranges_list = np.array(ranges_list, copy=False) base_range = np.arange(ranges_lis...
python|numpy|repeat
3
374,379
15,454,285
Numpy: Array of class instances
<p>This might be a dumb question, but say i want to build a program from bottom-up like so:</p> <pre><code>class Atom(object): def __init__(self): ''' Constructor ''' def atom(self, foo, bar): #...with foo and bar being arrays of atom Params of lengths m &amp; n "Do what...
<p>The path to hell is paved with premature optimization... As a beginner in python, focus on your program and what is supposed to do, once it is doing it too slowly you can ask focused questions about how to make it do it faster. I would stick with learning python's intrinsic data structures for managing your objects....
python|numpy|inner-classes
8
374,380
15,111,230
what is a reason to use ndarray instead of python array
<p>I build a class with some iteration over coming data. The data are in an array form without use of numpy objects. On my code I often use <code>.append</code> to create another array. At some point I changed one of the big array 1000x2000 to numpy.array. Now I have an error after error. I started to convert all of th...
<p>NumPy and Python arrays share the property of being efficiently stored in memory.</p> <p>NumPy arrays can be added together, multiplied by a number, you can calculate, say, the sine of all their values in one function call, etc. As HYRY pointed out, they can also have more than one dimension. You cannot do this wit...
python|numpy|multidimensional-array
8
374,381
15,033,511
Compute a confidence interval from sample data
<p>I have sample data which I would like to compute a confidence interval for, assuming a normal distribution.</p> <p>I have found and installed the numpy and scipy packages and have gotten numpy to return a mean and standard deviation (numpy.mean(data) with data being a list). Any advice on getting a sample confidenc...
<pre><code>import numpy as np import scipy.stats def mean_confidence_interval(data, confidence=0.95): a = 1.0 * np.array(data) n = len(a) m, se = np.mean(a), scipy.stats.sem(a) h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1) return m, m-h, m+h </code></pre> <p>You can calculate like this.</p...
python|numpy|scipy|statistics|confidence-interval
237
374,382
13,659,401
numpy change array values when mask is one
<p>i'm new to numpy and i'm running into trouble.</p> <p>I've got two numpy arrays, img and thr:</p> <pre><code>&gt;&gt;&gt;img.shape (2448, 3264, 3) &gt;&gt;&gt;thr.shape (2448, 3264) </code></pre> <p>And i want to do something like this: set <code>img[x,y] = [255,255,255]</code> only when <code>thr[x,y] is not 0</...
<p>Using <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#assigning-values-to-indexed-arrays" rel="nofollow">NumPy assignment to an indexed array</a>:</p> <pre><code>img[thr != 0] = [255,255,255] </code></pre>
python|numpy
4
374,383
13,711,803
Python: np.loadtxt, read multiple files
<p>I have managed to get loadtxt to read in a single file, but now I want it to read in a bunch of files off a .list file I have. I tried throwing it in a for loop, but I can't seem to get it to work. Can anyone help please?</p> <p><code>[row1, row2, row3] = np.loadtxt("data.fits",unpack=True,skiprows=1)</code></p> <...
<pre><code>for i in range(len(array)): [row1, row2, row3] = np.loadtxt(list.list[i],unpack=True,skiprows=1) </code></pre> <p>Additionally:</p> <pre><code>filelist=['file1','file2'] for file in filelist: [row1, row2, row3] = np.loadtxt(file,unpack=True,skiprows=1) #Do Stuff </code></pre> <p>I believe the q...
python|numpy
3
374,384
13,288,202
Average arrays with Null values
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/13281904/avarage-of-a-number-of-arrays-with-numpy-without-considering-zero-values">avarage of a number of arrays with numpy without considering zero values</a> </p> </blockquote> <p>I am working on numpy and I ...
<p>Update: As of NumPy 1.8, you could use <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.nanmean.html" rel="nofollow noreferrer">np.nanmean</a> instead of <code>scipy.stats.nanmean</code>.</p> <hr> <p>If you have <code>scipy</code>, you could use <a href="http://www.scipy.org/doc/api_docs/SciP...
python|arrays|numpy|null|average
7
374,385
13,432,492
How to do a 3D revolution plot in matplotlib?
<p>Suppose you have a 2D curve, given by e.g.:</p> <pre><code>from matplotlib import pylab t = numpy.linspace(-1, 1, 21) z = -t**2 pylab.plot(t, z) </code></pre> <p>which produces </p> <p><img src="https://i.stack.imgur.com/69Ior.png" alt="http://i.imgur.com/feQzk.png"></p> <p>I would like to perform a revolution t...
<p>Your plot on your figure seems to use cartesian grid. There is some examples on the matplotlib website of 3D cylindrical functions like Z = f(R) (here: <a href="http://matplotlib.org/examples/mplot3d/surface3d_radial_demo.html" rel="nofollow noreferrer">http://matplotlib.org/examples/mplot3d/surface3d_radial_demo.ht...
python|numpy|matplotlib
4
374,386
29,686,547
Assigning values to multi-dimensional masked arrays does not clear the mask?
<p>Assigning to a masked array is supposed to clear the mask. This works ok for me in a single-dimensional array, but doesn't work in a multi-dimensional array. I am able to workaround this by either flattening the array to a single dimension or assigning the mask explicitly (shown below), but it doesn't seem like I s...
<p>When you do <code>marray2[2][2] = 2</code>, the first <code>[2]</code> is actually returning a <em>copy</em> of the 3rd row of the array, not a reference to the row within <code>marray2</code>, so you are manipulating the copy and not affecting <code>marray2</code>.</p> <p>Unlike lists and tuples, numpy arrays supp...
python|arrays|numpy
1
374,387
29,382,903
How to apply piecewise linear fit in Python?
<p>I am trying to fit piecewise linear fit as shown in fig.1 for a data set</p> <p><img src="https://i.stack.imgur.com/Thrit.png" alt="enter image description here"></p> <p>This figure was obtained by setting on the lines. I attempted to apply a piecewise linear fit using the code:</p> <pre><code>from scipy import o...
<p>You can use <code>numpy.piecewise()</code> to create the piecewise function and then use <code>curve_fit()</code>, Here is the code</p> <pre><code>from scipy import optimize import matplotlib.pyplot as plt import numpy as np %matplotlib inline x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14, 15], dtype=...
python|numpy|scipy|curve-fitting|piecewise
78
374,388
29,344,966
Numpy: add row and column
<p>How can I add one row and one column to a numpy array. The array has the shape (480,639,3) and I want to have the shape (481,640,3). The new row and column should filled with zeros, like this:</p> <pre><code>[43,42,40], ... [64,63,61], [0,0,0] ... ... ... [0,0,0] [29,29...
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html" rel="nofollow"><code>pad</code></a></p> <pre><code>&gt;&gt;&gt; old = np.random.random_integers(0, 100, size=(480, 640)) &gt;&gt;&gt; np.pad(old, pad_width=((0, 1), (0, 1)), mode='constant') array([[ 66, 22, 51, ..., 18, 15...
python|arrays|numpy
3
374,389
29,737,919
datetime conversion and manipulation in python
<p>My raw data is in CSV. I load it as a pandas dataframe and datetime fields are loaded as objects. </p> <pre><code>datetime1 22773 non-null object datetime2 22771 non-null object </code></pre> <p>Using <code>pd.to_datetime(df['datetime1'])</code> I convert it to - <code>datetime64[ns]</code>.</p> <p>But in doi...
<ol> <li><p>It's just a data type that's based on numpy's datetime64[ns]. It doesn't contain a timezone attribute that altered your data</p></li> <li><p><code>df["existing or new column"] = df["datetime1] - pd.Timedelta(7, 'h')</code></p></li> </ol> <p>Also, you can always convert to date time when you read the csv u...
python|datetime|pandas
0
374,390
29,356,825
python: calculate center of mass
<p>I have a data set with 4 columns: x,y,z, and value, let's say:</p> <pre><code>x y z value 0 0 0 0 0 1 0 0 0 2 0 0 1 0 0 0 1 1 0 1 1 2 0 1 2 0 0 0 2 1 0 0 2 2 0 0 </code></pre> <p>I would like to calculate the center of mass <code>CM = (x_m,y_m,z_m)</code> of all values. In the present...
<p>The simplest way I can think of is this: just find an average of the coordinates of mass components weighted by each component's contribution.</p> <pre><code>import numpy masses = numpy.array([[0, 0, 0, 0], [0, 1, 0, 0], [0, 2, 0, 0], [1, 0, 0, 0], [1, 1, 0, 1], [1, 2, 0, 1], [2, 0, 0, 0], [2, ...
python|numpy|centering
14
374,391
29,437,001
Pandas: get index of removed row
<p>I have a large dataframe. Here is a small one for the example.</p> <pre><code> C1 C2 C3 C4 0 foo one 1 4 1 foo one 1 5 2 foo two 2 3 3 bar one 3 6 4 bar two 2 7 </code></pre> <p>I perform a list of filters that remove several rows. Here is the final df</p> <pre><code> C1 C2 C3 C4 0...
<p>You could use the <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Index.difference.html" rel="nofollow"><code>difference</code></a> method on the two Index objects:</p> <pre><code>&gt;&gt;&gt; df_orig.index.difference(df_final.index) Int64Index([1, 4], dtype='int64') </code></pre> <p>If you're u...
python|indexing|pandas
2
374,392
29,658,567
Create vertical NumPy arrays in Python
<p>I'm using NumPy in Python to work with arrays. This is the way I'm using to create a vertical array:</p> <pre><code>import numpy as np a = np.array([[1],[2],[3]]) </code></pre> <p>Is there a simple and more direct way to create vertical arrays?</p>
<p>You can use <code>reshape</code> or <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html" rel="noreferrer"><code>vstack</code></a> :</p> <pre><code>&gt;&gt;&gt; a=np.arange(1,4) &gt;&gt;&gt; a array([1, 2, 3]) &gt;&gt;&gt; a.reshape(3,1) array([[1], [2], [3]]) &gt;&gt;&gt; np...
python|arrays|numpy
28
374,393
29,739,894
pandas: read_csv how to force bool data to dtype bool instead of object
<p>I'm reading in a large flatfile which has timestamped data with multiple columns. Data has a boolean column which can be True/False or can have no entry(which evaluates to nan).</p> <p>When reading the csv the bool column gets typecast as object which prevents saving the data in hdfstore because of serialization er...
<p>As you had a missing value in your csv the dtype of the columns is shown to be object as you have mixed dtypes, the first 3 row values are boolean, the last will be a float.</p> <p>To convert the <code>NaN</code> value use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" r...
python|pandas
10
374,394
29,678,154
Why is numpy/pandas parsing of a csv file with long lines so slow?
<p>I'm trying to efficiently parse a csv file with around 20,000 entries per line (and a few thousand lines) to a numpy array (or list of arrays, or anything similar really). I found a number of other questions, along with <a href="http://wesmckinney.com/blog/a-new-high-performance-memory-efficient-file-parser-engine-f...
<p>Does your CSV file contain column headers? If not, then explicitly passing <code>header=None</code> to <code>pandas.read_csv</code> can give a slight performance improvement for the Python parsing engine (but not for the C engine):</p> <pre><code>In [1]: np.savetxt('test.csv', np.random.randn(1000, 20000), delimite...
python|parsing|csv|numpy|pandas
17
374,395
29,439,589
How to create a pivot table on extremely large dataframes in Pandas
<p>I need to create a pivot table of 2000 columns by around 30-50 million rows from a dataset of around 60 million rows. I've tried pivoting in chunks of 100,000 rows, and that works, but when I try to recombine the DataFrames by doing a .append() followed by .groupby('someKey').sum(), all my memory is taken up and py...
<p>You could do the appending with HDF5/pytables. This keeps it out of RAM.</p> <p>Use the <a href="http://pandas.pydata.org/pandas-docs/dev/io.html#table-format" rel="noreferrer">table format</a>:</p> <pre><code>store = pd.HDFStore('store.h5') for ...: ... chunk # the chunk of the DataFrame (which you want ...
python|python-3.x|pandas|pivot-table
16
374,396
62,357,239
Add attention layer to Seq2Seq model
<p>I have build a Seq2Seq model of encoder-decoder. I want to add an attention layer to it. I tried adding attention layer <a href="https://www.kaggle.com/residentmario/seq-to-seq-rnn-models-attention-teacher-forcing" rel="nofollow noreferrer">through this</a> but it didn't help.</p> <p>Here is my initial code without...
<p>the dot products need to be computed on tensor outputs... in encoder you correctly define the encoder_output, in decoder you have to add <code>decoder_outputs, state_h, state_c = decoder_lstm(enc_emb, initial_state=encoder_states)</code></p> <p>the dot products now are</p> <pre><code>attention = dot([decoder_outputs...
python-3.x|tensorflow|keras|nlp|machine-translation
5
374,397
62,087,703
Need to add missing value from pandas column
<p>I've two pandas dataframe having one common column in both but they are not having same values. Wish to get the missing values to another dataframe common column.</p> <pre><code>df1 name mobile email abcd 992293 abcd@abcd.com efgh 687678 efgh@efgh.com ijkl 7878678 ijkl@ijkl.com mnop 678687 mnop@...
<p>This is a simple case of joining two data frames on a common key:</p> <pre><code>pd.merge(df1, df2, on='name',how='left') </code></pre>
python|pandas
1
374,398
62,239,111
how do I create a new column out of a dictionary's sub string on a pandas dataframe
<p>I have the following repo for the files: <a href="https://github.com/Glarez/learning.git" rel="nofollow noreferrer">https://github.com/Glarez/learning.git</a></p> <p><a href="https://i.stack.imgur.com/zjO5h.png" rel="nofollow noreferrer">dataframe</a></p> <p>I need to create a column with the bold part of that str...
<p>Since you do not want the exact answer. I will provide you one of the ways to achieve this:</p> <ol> <li>filter the params column into a dictionary variable</li> <li>create a loop to access the keys of the dictionary</li> <li>append it to the pandas df you have (df[key] = np.nan) - Make sure you add some values whi...
python|pandas
0
374,399
62,455,255
How do I turn a Tensorflow Dataset into a Numpy Array?
<p>I'm interested in a Tensorflow Dataset, but I want to manipulate it using <code>numpy</code>. Is it possible to turn this <code>PrefetchDataset</code> into an array?</p> <pre><code>import tensorflow_datasets as tfds import numpy as np dataset = tfds.load('mnist') </code></pre>
<p>Since you didn't specify <code>split</code> or <code>as_supervised</code>, <code>tfds</code> will return a dictionary with <code>train</code> and <code>test</code> set. Since <code>as_supervised</code> defaults to <code>False</code>, the <code>image</code> and <code>label</code> will also be separate in a dictionary...
python|arrays|numpy|tensorflow
1