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,600
51,691,522
Set the last element equal to the first element in a multidimensional numpy array
<p>For example I have an array:</p> <pre><code>[[[[1 2][3 4]]][[[1 2][3 4]]]] </code></pre> <p>How would I set 4 equal to 1? I used </p> <pre><code>array[-1][-1][-1][-1] = array[0][0][0][0] </code></pre> <p>but I got an error because of it later on. Is there a more general way of doing this?</p>
<p>You can "cheat" by updating the flattened array:</p> <pre><code>a = np.array([[[1,2],[3,4]],[[1,2],[3,4]]]) a.flat[-1] = a.flat[0] a array([[[1, 2], [3, 4]], [[1, 2], [3, 1]]]) </code></pre>
python|numpy
0
374,601
51,956,961
How do I turn this .txt into a dataframe?
<p>I am trying to do a Whatsapp analysis in Python and I want to convert this into a dataframe with columns for date, hour, person, and message.</p> <pre><code> '[8/23/17, 1:45:10 AM] Guillermina: Guten Morgen', '[8/23/17, 1:47:05 AM] Kester Stieldorf: Good morning :) was in Düsseldorf one hour ago ;)', '[8/23/17, 1...
<p>First, to parse your file:</p> <pre><code>with open('file.txt') as f: pieces = [i.strip() for i in f.read().splitlines()] </code></pre> <p>Then using <code>re.findall</code>:</p> <pre><code>pd.DataFrame( re.findall(r'\[(.*?)\]\s*([^:]+):\s*(.*)', '\n'.join(pieces)), columns=['Time', 'Name', 'Text'] ) ...
python|pandas|parsing|whatsapp
1
374,602
51,702,434
Make a folder for each line in a csv with its corresponding name?
<p>csv has this structure:</p> <pre><code>col1 100 101 102 .. 150 </code></pre> <p>I want it to read each line and create a folder that there, will be created each folder for each line with the corresponding number as its name. Also would be nice to store it in the Desktop.</p> <p>Example:</p> <pre><code>New folder...
<p>Try:</p> <pre><code>import pandas as pd import os path = "Your_Desktop_Path" df = pd.read_csv(path) for i in df["col1"].astype(str): os.mkdir(os.path.join(path, i)) </code></pre> <hr> <p><em>Or if you just have a single column.</em></p> <pre><code>import os path = "Your_Desktop_Path" with open(filename) as...
python|pandas
0
374,603
51,850,841
SyntaxError: invalid syntax with return function
<p>I have been trying to use a piece of code that takes an array as input and draws a circle. I keep getting a syntax error. Can someone tell me whats wrong?</p> <pre><code>def planet_maker(a,b,n,r,array,p): import numpy as np y,x = np.ogrid[-a:n[0]-a, -b:n[1]-b] mask = x*x + y*y &lt;= r*r return...
<p>You can't use = and return in the same assignment.</p>
python-3.x|numpy
1
374,604
51,898,233
Python multiprocessing slowed down even in mono-thread
<p>I want to run the same code in parallel using multiprocess. </p> <p>My process code run in 8 minutes alone. In 10 minutes when using the "force mono-thread" thing. But when I run 24 of them in parallel, each instance takes approximately 1 hour. </p> <p>Before, when each process spanned threads furiously like a ma...
<p>Without a &quot;minimal code example&quot;, it is indeed difficult to answer, so instead of a straight answer, I'll provide some code. I've experimented with:</p> <pre><code>import os os.environ['OMP_NUM_THREADS'] = '1' import numpy as np import time def tns(): return time.time_ns() / 1e9 def nps(vec, its=100): ...
python|multithreading|numpy|multiprocessing
0
374,605
51,985,766
python - applying a mask to an array in a for loop
<p>I have this code:</p> <pre><code>import numpy as np result = {} result['depth'] = [1,1,1,2,2,2] result['generation'] = [1,1,1,2,2,2] result['dimension'] = [1,2,3,1,2,3] result['data'] = [np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0])] for v in np.u...
<p>In order to solve your problem (finding and dropping duplicates) I encourage you to use <code>pandas</code>. It is a Python module that makes your life absurdly simple:</p> <pre><code>import numpy as np result = {} result['depth'] = [1,1,1,2,2,2] result['generation'] = [1,1,1,2,2,2] result['dimension'] = [1,2,3,1,...
python|numpy|dictionary
1
374,606
51,641,981
Data not "sticking" to my DataFrame when I append it to a column
<p>I'm pretty new to programming and data science. Here's a strange problem I came across. I'm doing feature engineering on a DataFrame filled with information about movies. I have actors count vectorized for each movie and I'm predicting metacritic score. </p> <p>Originally, I tried to also replace the Actors column ...
<p>Use <code>df.loc[row_index, col_name] = value</code>. Otherwise you're assigning a value to a slice of the dataframe. More info: <a href="https://www.dataquest.io/blog/settingwithcopywarning/" rel="nofollow noreferrer">https://www.dataquest.io/blog/settingwithcopywarning/</a></p>
python|pandas|dataframe
0
374,607
51,624,870
Parsing a set of dictionary to single line pandas (Python)
<p>Hi I have a pandas df similar to below</p> <pre><code>information record name apple size {'weight':{'gram':300,'oz':10.5},'description':{'height':10,'width':15}} country America partiesrelated [{'nameOfFarmer':'John Smith'},{'farmerID':'A0001'}] </code></pre> ...
<p>IIUC, you can define a recursive function to unnest your sequences/dicts until you have a list of key, value that may both serve as a valid input for <code>pd.DataFrame</code> constructor and be formatted as the way you described.</p> <p>Take a look at this solution:</p> <pre><code>import itertools import collecti...
python|pandas|dataframe
2
374,608
51,851,956
Cannot access individual columns of a groupby object of a dataframe after binning it
<p>This question is similar to <a href="https://stackoverflow.com/questions/51838479/how-to-convert-the-data-structure-obtained-after-performing-a-groupby-operation/51838619?noredirect=1">this one</a>, but with a crucial difference - the solution to the linked question does not solve the issue when the dataframe is gro...
<p><strong>If you do <code>reset_index()</code> on your dataframe <code>df1</code>, you should get the dataframe you want to have.</strong> </p> <p>The problem was that you have one of your desired columns (<code>regiment</code>) as an index, so you needed to reset it and make it an another column.</p> <p><strong>Ed...
python|pandas|indexing|seaborn|pandas-groupby
2
374,609
51,659,701
Counting occurrence using Python
<p>I am trying to count the occurrence of a certain type of value in a CSV file column-wise, So what the program will do is ignore the row if there is 0 and count the rest. </p> <pre><code>Program pseudocode - Count each column if the value is greater than 0 count else ignore continue till the last row of each colum...
<p>Just use:</p> <pre><code>df.ne(0).sum() </code></pre> <p>To sum up the number of non zero values column-wise. </p> <p>If you want to stick it back into your original dataframe, rename the series to <code>total</code> so that the index will be called that, and use <code>append</code>:</p> <pre><code>df.append(df....
python-3.x|pandas|for-loop|count
0
374,610
51,605,561
Pandas: Find top 10 combination of records in one column, based on another column
<p>I have a table of 2 columns. First is order_id, Second is item_name. I want the top 10 choice of combination of Items based on order_id</p> <p>Data looks like</p> <pre><code>order_id Item_Name 1 A 1 B 1 C 1 D 2 A 2 B 2 D 2 E 2 B 2 C 3 D 3 E 3 F 3 G 3 A 3 B 4 F 4 D 4 A 4 B...
<p>IIUC</p> <pre><code>n=10 df.groupby('order_id').i.value_counts().groupby('order_id').head(n).astype(str).reset_index(name='v').groupby('order_id').i.agg('|'.join) </code></pre>
python|pandas
0
374,611
51,887,958
Loading a saved model in Keras with a custom layer and prediction results are different?
<p>My network was achieving 96% accuracy on my dataset (edit: on predicting 9 classes). I saved the entire model for every epoch (weights included) whenever I ran it. I ran it 3 times, each time testing different hyperparameters, each time achieving around 96% accuracy.</p> <p>When I try to load any of these tests now...
<p>I <em>finally</em> found the answer.</p> <p>I have implemented a custom Lambda layer to handle reshaping. This layer has difficulties loading. Specifically, it reshapes one dimension into two dimensions on an arbitrary interval. The interval was defaulting to one specific value every time I loaded the model, even t...
python|tensorflow|machine-learning|keras|keras-layer
1
374,612
51,560,617
Tensorflow-gpu 1.9 is not working on Pycharm
<p>I can't import tensorflow in pycharm, it raises the following error:</p> <pre><code>ImportError: Could not find 'cudart64_90.dll'. TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. Download and install CUDA 9.0 from this URL: https://developer.nvidia.co...
<p>Looking into the <code>tensorflow-1.9</code> <a href="https://github.com/tensorflow/tensorflow/blob/25c197e02393bd44f50079945409009dd4d434f8/tensorflow/tools/docker/Dockerfile.devel-gpu#L16" rel="nofollow noreferrer">release branch</a>, it looks like they used <strong>CUDA 9.0</strong> and <strong>CUDNN 7.1.4</stron...
python|tensorflow|pycharm|cudnn
2
374,613
51,642,012
Remove special characters in a pandas column using regex
<p>I am working with a pandas dataframe where a column has non numeric values in it.Is there a way that i can replace characters only while retaining the numbers in the column.I am very new to applying regex patterns to clean data and highly appreciate if someone could point me towards the right regex pattern .</p> <...
<p>The regex groups the digits on either side of the '.' ignoring all non-digits. The code uses these groups to create the required output. <a href="https://regex101.com/r/bo97D9/1" rel="nofollow noreferrer">Regex101</a></p> <pre><code>import pandas as pd def clean_input(m): print(m.group(0)) if m: va...
python|regex|pandas|dataframe
3
374,614
51,737,156
Merge data frames on multiple common values
<p>I'm trying to <code>merge</code> two data frames based off common values. The problem is there are duplicate values. I'm trying to merge the values based on the first appearance. I want to merge on values in <code>Col B</code> &amp; <code>Col C</code></p> <pre><code>import pandas as pd df = pd.DataFrame({ ...
<p>You can use <code>merge</code> and then <code>duplicated</code> + <code>loc</code> to update your merged column:</p> <pre><code>merge_cols = ['B', 'C'] df2 = pd.merge(df, df1, on=merge_cols) df2.loc[df2[merge_cols].duplicated(), 'A_y'] = '' print(df2) A_x B C A_y 0 10:00:05 ABC 1 10:00:00 ...
python|pandas|merge
1
374,615
51,592,274
i have two columns in a dataframe one has column name and other has no column name how can i name them both on python pandas?
<p>Input</p> <pre><code> Fruit Apple 55 Orange 43 </code></pre> <p>Output</p> <pre><code>Fruit Count Apple 55 Orange 43 </code></pre> <p>I need to rename columns accordingly please help</p>
<p>I think need convert <code>Series</code> to <code>DataFrame</code> by:</p> <pre><code>df = df.reset_index(name='Count') </code></pre>
python|python-3.x|pandas|series
1
374,616
35,834,062
How to plot multiple dependent variables with seaborn?
<p>I want to consider time-series data, the three axes of an accelerometer to be exact. I'm digging through the docs but am not immediately seeing how provide more than one signal and trying to figure out how to organize my data for pandas and seaborn in general. After plotting a single run of the three signals, I ho...
<p>This seems to work:</p> <pre><code>N=100 num_runs = 3 out = [] for k in range(num_runs): data = np.random.rand(N,3) + np.sin(np.arange(N)/5)[:,np.newaxis] data = np.hstack([np.arange(N)[:,np.newaxis],data]) data = np.hstack([np.zeros(N)[:,np.newaxis]+k,data]) out.append(data) data = np.vstack(out)...
python|pandas|accelerometer|seaborn
3
374,617
36,035,232
Compute rowmeans ignoring na in pandas, like na.rm in R
<p>I have the following data:</p> <pre><code>a = pd.Series([1, 2, "NA"]) b = pd.Series(["NA", 2, 3]) df = pd.concat([a, b], axis=1) # 0 1 # 0 1 NA # 1 2 2 # 2 NA 3 </code></pre> <p>Now I'd like to compute the rowmeans like in R with <code>na.rm=T</code>.</p> <pre><code>c.mean(skipna=True, axis=0) # S...
<p>You have mixed <code>dtypes</code> due to presence of str 'NA', you need to convert to numeric types first:</p> <pre><code>In [118]: df.apply(lambda x: pd.to_numeric(x, errors='force')).mean(axis=1) Out[118]: 0 1 1 2 2 3 dtype: float64 </code></pre> <p>If your original data was true <code>NaN</code> then...
pandas
1
374,618
35,861,835
Setting a count variable given binary flags in Python (pandas dataframe)
<p>I have a dataframe with layout according to below, <strong>not</strong> including "flag_common":</p> <pre><code>cat flag_1 flag_2 flag_3 pop state year flag_common value1 1 0 0 1.5 Ohio 2000 1 value3 1 1 0 1.7 Ohio 2001 ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmax.html" rel="nofollow"><code>idxmax</code></a> of <code>columns</code> in subset by columns <code>flag_1</code>, <code>flag_2</code> and <code>flag_3</code>, then find positions by list comprehension with <a href="http:/...
python|pandas|dataframe
1
374,619
35,812,074
Shortest Syntax To Use numpy 1d-array As sklearn X
<p>I often have two <code>numpy</code> 1d arrays, <code>x</code> and <code>y</code>, and would like to perform some quick sklearn fitting + prediction using them.</p> <pre><code> import numpy as np from sklearn import linear_model # This is an example for the 1d aspect - it's obtained from something else. x = np.a...
<p>You can slice your array, creating a <a href="http://docs.scipy.org/doc/numpy-1.6.0/reference/arrays.indexing.html#numpy.newaxis" rel="noreferrer">newaxis</a>:</p> <pre><code>x[:, None] </code></pre> <p>This:</p> <pre><code>&gt;&gt;&gt; x = np.arange(5) &gt;&gt;&gt; x[:, None] array([[0], [1], [2], ...
python|numpy|scikit-learn
10
374,620
36,116,414
How to get pseudo-determinant of a square matrix with python
<p>I have a matrix which fails the singular test in which I am calculating for naive bayes classifier. I am handling the <code>ln(det(sigma))</code> portion of the equation. </p> <pre><code>if np.linalg.cond(covarianceMatrix) &lt; 1/sys.float_info.epsilon: return np.log(np.linalg.det(covarianceMatrix)) else: r...
<ol> <li>First compute the eigenvalues of your matrix</li> </ol> <pre> <code> eig_values = np.linalg.eig(covarianceMatrix) </code> </pre> <ol start="2"> <li>Then compute the product of the non-zero eigenvalues (this equals the pseudo-determinant value of the matrix), </li> </ol> <pre> <code> pseudo_determine...
python|numpy|matrix|naivebayes
3
374,621
35,963,102
Pandas DataFrame - check if string in column A contains full word string in column B
<p>I have a dataframe with two columns <code>foo</code> which contains a string of text and <code>bar</code> which contains a search term string. For each row in my dataframe I want to check if the search term is in the text string <strong>with word boundaries</strong>.</p> <p>For example</p> <pre><code>import panda...
<p>You can apply your function to each row:</p> <pre><code>df.apply(lambda x: re.search(r'\b' + x.bar + r'\b', x.foo) is not None, axis=1) </code></pre> <p>Result:</p> <pre><code>0 True 1 False dtype: bool </code></pre>
python|pandas
1
374,622
36,122,527
Normalize multiindex dataframe in pandas
<p>I am trying to normalize multiindex dataframe: subtract it's mean and divide by its standard deviation. That's how you do it with a normal (not multiindex) dataframe:</p> <pre><code>df4 = (df4-df4.mean(1)) / df.std(1) </code></pre> <p>However, with the multiindex dataframe it does not work: I am getting this absur...
<p>Use the <code>subtract</code> and <code>divide</code> methods so you can specify the appropriate axis of operation:</p> <pre><code>df.subtract(mean, axis=0).divide(std, axis=0) </code></pre> <hr> <p>For example,</p> <pre><code>import numpy as np import pandas as pd np.random.seed(2016) arrays = [['bar', 'bar', ...
python|pandas
3
374,623
36,156,336
Create a binary completeness map
<p>I'm touching the goal of my project, but I'm getting a problem on : How I can create a completeness map ? I have lots of data, a field with maybe 500.000 objects which are represented by dots in my plot with different zoom :</p> <p><img src="https://i.stack.imgur.com/QD31g.png" alt="Without zoom"> <img src="https:/...
<p>This is usually a process of inserting your data into a grid (pixel wise, or node wise). The following example builds a grid (2D array) and calculates the "grid coordinates" for the sample data. Once it has those grid coordinates (which in true are nothing but array indexes) you can just set those elements to True. ...
python|numpy|matplotlib
1
374,624
36,057,715
TensorFlow with a NER-Tagger
<p>I was wondering if there is any possibility to use Named-Entity-Recognition with a self trained model in tensorflow.</p> <p>There is a word2vec implementation, but I could not find the 'classic' POS or NER tagger.</p> <p>Thanks for your help!</p>
<p>You can adapt the Sequence-to-Sequence model for NER tagging. Your training text is the source vocabulary/sequences to the encoder:</p> <pre><code>Yesterday afternoon , Mike Smith drove to New York . </code></pre> <p>your BIO / BILOU NER tags are your target vocabulary/sequences to the decoder for NER tagging:</p>...
nlp|tensorflow
8
374,625
35,860,940
Replacing original values
<p>I have a numpy array <code>y</code> which I'm trying to preserve, however is getting replaced by the following operation:</p> <pre><code>ys = np.unique(y) y2 = y for i,val in enumerate(ys): y2[y2==val]=i </code></pre> <p>Why is the original numpy array getting replaced by this operation? originally the <code>y...
<p>As already stated, <code>y2 = y</code> simply makes another reference to the underlying numpy array. As far as python is concerned, <code>y2</code> and <code>y</code> are indistinguishable. You can even check <code>y2 is y</code> will return <code>True</code> and both arrays have the same <code>id</code> (memory l...
python|arrays|numpy
1
374,626
35,912,603
How to apply scipy function on Pandas data frame
<p>I have the following data frame:</p> <pre><code>import pandas as pd import io from scipy import stats temp=u"""probegenes,sample1,sample2,sample3 1415777_at Pnliprp1,20,0.00,11 1415805_at Clps,17,0.00,55 1415884_at Cela3b,47,0.00,100""" df = pd.read_csv(io.StringIO(temp),index_col='probegenes') df </code></pre> <...
<p>The <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow">documentation for <code>pd.DataFrame</code></a> has:</p> <blockquote> <p><strong>data</strong> : numpy ndarray (structured or homogeneous), dict, or DataFrame Dict can contain Series, arrays, constants, or l...
python|pandas|scipy
2
374,627
36,072,367
numpy.vdot for 2 vectors returns a matrix instead of a scalar?
<pre><code>v1=np.matrix([[-0.40824829], [-0.81649658], [-0.40824829]]) v2=np.matrix([[ 8.94427191e-01], [ -4.47213595e-01], [ 2.77555756e-16]]) np.vdot(v2, v1) </code></pre> <p>gives: </p> <pre><code>matrix([[-0.36514837]]) </code></pre> <p>Why isn't it returning a scalar?</p>
<p>You can use <code>np.einsum()</code> to get a scalar by either using as inputs <code>np.ndarray</code> or <code>np.matrix</code>:</p> <pre><code>np.einsum('ij, ij', v1, v2) </code></pre> <p>if <code>v1</code> and <code>v2</code> have the same <code>shape</code>.</p>
numpy|matrix
1
374,628
35,833,995
problems with numpy/python installation on OS 10.11.3
<p>first of all - I know there are other people who asked similar questions, but none of the solutions in those posts worked for me.</p> <p>My problem is that I installed numpy, but for some reason I cannot use it.</p> <p>I tried several things listed in this post: <a href="https://stackoverflow.com/questions/2461500...
<p>I think I did just something that seems to work.. </p> <p>I also have PyCharm installed on my laptop. I just created a new file and typed in "import numpy as np". I told me that it is not installed. So I went to the project interpreter where I found 3 different Python versions (3.5, 2.6 and 2.7).</p> <p>I selected...
python|macos|numpy
0
374,629
36,074,074
Smooth circular data
<p>I have an array of data <code>Y</code> such that <code>Y</code> is a function of an independent variable <code>X</code> (another array).</p> <p>The values in <code>X</code> vary from 0 to 360, with wraparound.</p> <p>The values in <code>Y</code> vary from -180 to 180, also with wraparound.</p> <p>(That is, these ...
<p>Say you start with</p> <pre><code>import numpy as np x = np.linspace(0, 360, 360) y = 5 * np.sin(x / 90. * 3.14) + np.random.randn(360) plot(x, y, '+'); </code></pre> <p><a href="https://i.stack.imgur.com/UHMtK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UHMtK.png" alt="enter image descrip...
python|numpy|scipy|filtering|smoothing
1
374,630
36,106,179
read csv file with special linebreaks
<p>I have to read a CSV file with somehow funny line breaks into a dataframe. Is this the most efficient way to do this?</p> <pre><code>with open(fileToRead,'r') as file: filedata = file.read().replace("#@#@#", "\n") file.close() df = pandas.read_csv(filepath_or_buffer=StringIO(filedata), sep='~') </code></p...
<p>You can alternatively try the following code, which will make a copy of the data with more "normal" linebreaks.</p> <pre><code>with open('{}.clean'.format(fileToRead), 'w') as out_file: with open(fileToRead, 'r') as in_file: in_file_data = in_file.read().replace('#@#@#', '\n') out_file.write(i...
python|csv|pandas
0
374,631
36,139,980
Prevention of overfitting in convolutional layers of a CNN
<p>I'm using TensorFlow to train a Convolutional Neural Network (CNN) for a sign language application. The CNN has to classify 27 different labels, so unsurprisingly, a major problem has been addressing overfitting. I've taken several steps to accomplish this:</p> <ol> <li>I've collected a large amount of high-quali...
<h2>How can I fight overfitting?</h2> <ul> <li>Get more data (or data augmentation)</li> <li>Dropout (see <a href="https://arxiv.org/abs/1207.0580" rel="noreferrer">paper</a>, <a href="https://www.cs.toronto.edu/~hinton/absps/JMLRdropout.pdf" rel="noreferrer">explanation</a>, <a href="https://datascience.stackexchange...
tensorflow|conv-neural-network
15
374,632
37,377,264
How to find which cells couldn't be converted to float?
<p><code>pandas.DataFrame.astype(float)</code> raises <code>ValueError: could not convert string to float</code> error.</p> <p>What's the best way to find which cell(s) caused this to happen?</p>
<p>I think you can first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>fillna</code></a> with some number, e.g. <code>1</code>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code...
python|python-3.x|pandas
4
374,633
37,304,800
pandas: renaming column labels in multiindex df
<p>I have a df which looks like this:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.random((4,4))) df.columns = pd.MultiIndex.from_product([['1|mm','2|lll'],['A|ljjh','B|ldjdj']]) 1|mm 2|lll A|ljjh B|ldjdj A|ljjh B|ldjdj 0 0.599202 0.093...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_level_values.html" rel="nofollow"><code>get_level_values</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>split</code></a> for parsing, create n...
python|pandas|dataframe|multiple-columns|multi-index
1
374,634
37,465,303
python: pandas - order of data frame column
<p>I have following code to output a dataFrame:</p> <pre><code>output = pd.DataFrame({"id":id_test, "hum":y_pred}) output.to_csv("myOutput.csv", index=False) </code></pre> <p>Then in myOutput.csv, I got <code>hum</code> as the first column, <code>id</code> as the second column. Is there a way to make <code>id</code> ...
<p>Just reorder the columns:</p> <pre><code>output.ix[:,['id','hum']].to_csv("myOutput.csv", index=False) </code></pre> <p>Because you used a dict as the data, the column order is not necessarily the same order as the key creation order in the dict</p>
python|pandas
2
374,635
37,580,691
Tensorflow session returns as 'closed'
<p>I have successfully ported the <a href="https://www.tensorflow.org/versions/r0.8/tutorials/deep_cnn/index.html" rel="nofollow">CIFAR-10 ConvNet tutorial code</a> for my own images and am able to train on my data and generate Tensorboard outputs etc.</p> <p>My next step was to implement an evaluation of new data aga...
<p>From <a href="https://www.tensorflow.org/versions/r0.8/api_docs/python/client.html#Session" rel="nofollow">documentation</a> on Session, a session can be closed with <code>.close</code> command or when using it through a context-manager in <code>with</code> block. I did <code>find tensorflow/models/image/cifar10 | ...
python|python-3.x|tensorflow
2
374,636
37,524,056
How to efficiently convert the entries of a dictionary into a dataframe
<p>I have a dictionary like this:</p> <pre><code>mydict = {'A': 'some thing', 'B': 'couple of words'} </code></pre> <p>All the values are strings that are separated by white spaces. My goal is to convert this into a dataframe which looks like this:</p> <pre><code> key_val splitted_words 0 A ...
<p>Based on @qu-dong's idea and using a generator function for readability a working example:</p> <pre><code>#! /usr/bin/env python from __future__ import print_function import pandas as pd mydict = {'A': 'some thing', 'B': 'couple of words'} def splitting_gen(in_dict): """Generator function to split ...
python|performance|dictionary|pandas
4
374,637
37,230,696
How to select the rows that contain a specific value in at least one of the elements in a row?
<p>I have a <code>DataFrame</code> <code>DF</code>and a list, say <code>List1</code>. <code>List1</code> is created from the <code>DF</code> and it has the elements present in <code>DF</code> but without repetitions. I need to do the following:<br/> 1. Select the rows of <code>DF</code> that contain a specific element ...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html" rel="nofollow"><code>isin</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html" rel="nofollow"><code>any</code></a>:</p> <pre><code>List1=['Apple','Orange',...
python|python-3.x|pandas
3
374,638
37,483,238
ImportError: C extension: DLL load failed: %1 win32
<p>I try to install <code>numpy+mkl</code> and <code>scipy</code> and after that I got an error</p> <pre><code>ImportError: C extension: DLL load failed: %1 Win32. not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace' to build the C extensions firs...
<p>I would recommend you to use <a href="https://winpython.github.io/" rel="nofollow">WinPython</a> if you are running in Windows. It is a free open-source portable distribution of the Python programming language for Windows 7/8/10. The thing is that after you install (actually is just extract), you would have all of t...
python|pandas
0
374,639
37,398,944
Pandas remove duplicates with a criteria
<p>Say I have the following dataframe:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; &gt;&gt;&gt; d=pd.DataFrame() &gt;&gt;&gt; &gt;&gt;&gt; d['Var1']=['A','A','B','B','C','C','D','E','F'] &gt;&gt;&gt; d['Var2']=['A','Z','B','Y','X','C','Q','N','P'] &gt;&gt;&gt; d['Value']=[34, 45, 23, 54, 65, 77,100,...
<p>Here's a one-liner:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; d.loc[~d.Var1[(d.Var1 == d.Var2).argsort()].duplicated('last')] Var1 Var2 Value 0 A A 34 2 B B 23 5 C C 77 6 D Q 100 7 E N 102 8 F P 44 </code></pre> <p>You can then se...
python|pandas
2
374,640
37,473,599
Convert a pandas data frame to a pandas data frame with another style
<p>I have data frame containing the IDs of animals and types they belong to as given below</p> <pre><code>ID Class 1 1 2 1 3 0 4 4 5 3 6 2 7 1 8 0 </code></pre> <p>I want convert it to a new style with the classes on the header row as follows.</p> <pre><code>ID 0 1 2 3 4 1 1 ...
<p>See <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow"><code>get_dummies()</code></a>:</p> <pre><code>&gt;&gt;&gt; print df ID Class 0 1 1 1 2 1 2 3 0 3 4 4 4 5 3 5 6 2 6 7 1 7 8 0 &gt;&gt;&gt; df2 = pd...
python|pandas|dataframe|ipython
1
374,641
37,487,067
Pandas: multiple bar plot from aggregated columns
<p>In python pandas I have create a dataframe with one value for each year and two subclasses - i.e., one metric for a parameter triplet</p> <pre><code>import pandas, requests, numpy import matplotlib.pyplot as plt df Metric Tag_1 Tag_2 year 0 5770832 FOOBAR1 name1 2008 1 7526436 FOOBAR1 x...
<p>This should get you on your way:</p> <pre><code>df = pd.read_csv('path_to_file.csv') # Group by the desired columns new_df = df.groupby(['year', 'Tag_1', 'Tag_2']).sum() # Sort descending new_df.sort('Metric', inplace=True) # Helper function for generation sequence of 'r' 'b' colors def get_color(i): if i%2 ...
python|pandas|matplotlib|dataframe
1
374,642
37,561,952
Reloading a created float32 creates a tiled image
<p>I save numpy array as a raw to file (only has green channel so no RGB):</p> <pre><code>dtype_string = "float32" &gt;&gt;&gt; frames.shape (40000L, 128L, 128L) frames.astype(dtype_string).tofile(os.path.expanduser('~/Downloads/') + "aligned_" + str(ind) + ".raw") </code></pre> <p>This is what <code>plt.imshow(fram...
<p>Look at this answer as an extended comment, thank you. The example you gave us doesn't represent a MWE because we have no information about different values you use in your code.</p> <p>I've stuck together this piece of code that mimics yours</p> <pre><code>import numpy as np import matplotlib.pyplot as plt dt = ...
python-2.7|numpy|matplotlib
0
374,643
37,575,008
Adding sheet2 to existing excelfile from data of sheet1 with pandas python
<p>I am fetching data from web into an excel sheet using pandas &amp; able to save it to sheet 1, now i want to fetch a column data into sheet 2 of same excel.</p> <p>When I am executing the code it still doesn't create a new sheet in the excelfile, just overwrites the existing sheet with new name &amp; desired data.<...
<p>You can use <code>openpyxl</code>, the library <code>pandas</code> uses for <code>xlsx</code>, to achieve this:</p> <pre><code>import pandas as pd from openpyxl import load_workbook book = load_workbook('Abc.xlsx') writer = pd.ExcelWriter('Abc.xlsx', engine='openpyxl') writer.book = book writer.sheets = dict((ws....
python|excel|pandas
0
374,644
37,228,193
Sklearn will not run/compile due to numpy errors
<p>I would not be posting this question if I had not researched this problem thoroughly. I run <code>python server.py</code> (it uses sklearn). Which gives me </p> <pre><code>Traceback (most recent call last): File "server.py", line 34, in &lt;module&gt; from lotusApp.lotus import lotus File "/Users/natumyers/...
<p>I was using depreciated python. I updated everything to python 3, and used <code>pip3</code>.</p>
numpy|flask|scikit-learn
1
374,645
37,265,993
angle between two vectors by using simple numpy or math in Python?
<p>i am trying to find out dihedral between two planes i have all the coordinates and i calculated vectors but the last step is giving problem, my last step is to find the angle between the vectors. here is my code</p> <pre><code>V1= (x2-x1,y2-y1,z2-z1) V2= (x3-x2,y3-y2,z3-z2) V3= (x4-x3,y4-y3,z4-z3) V4= numpy.cross(...
<p>Using cross products of vectors to calculate angles will only work if the vectors have unit length. You should normalize them first, e.g.</p> <pre><code>V4 = V4/np.sqrt(np.dot(V4,V4)) </code></pre> <p>Furthermore, I think you meant to write <code>math.acos(np.dot(V4,V5))</code> for <code>math.acos(V4.V5)</code>.</...
python|numpy
2
374,646
37,366,645
Missing value imputation in Python
<p>I have two huge vectors <strong>item_clusters</strong> and <strong>beta</strong>. The element <strong>item_clusters</strong> [ <em>i</em> ] is the cluster id to which the item <em>i</em> belongs. The element <strong>beta</strong> [ <em>i</em> ] is a score given to the item <em>i</em>. Scores are {-1, 0, 1, 2, 3}. <...
<p>I don't know if this means I'm the popular kid here or not, but I think you can vectorize your operations in the following way:</p> <pre><code>def fast_impute(num_clusters, item_clusters, beta): # get counts cluster_counts = np.zeros(num_clusters) np.add.at(cluster_counts, item_clusters, 1) # get ...
python-3.x|numpy|scipy|missing-data
2
374,647
37,497,107
Record and Recognize music from URL
<p>I am using an open source audio fingerprinting platform in python <a href="https://github.com/lenlight/dejavu" rel="nofollow">DeJavu</a> that can recognize music from disk and from microphone. I have tested the recognition from disk and it is amazing. 100% accuracy.</p> <p>I seek assistance on how to add a class "B...
<p>I still think that you need a discrete "piece" of audio, so you need a beginning and an end.<br> For what it is worth, start with something like this, which records a 10 second burst of audio, which you can then test against your finger-printed records.<br> Note: that this is bashed out for python 2, so you would ha...
python|json|numpy|audio|audio-fingerprinting
1
374,648
37,424,981
Code optimization - number of function calls in Python
<p>I'd like to know how I might be able to transform this problem to reduce the overhead of the <code>np.sum()</code> function calls in my code.</p> <p>I have an <code>input</code> matrix, say of <code>shape=(1000, 36)</code>. Each row represents a node in a graph. I have an operation that I am doing, which is iterati...
<p>If scipy.sparse is not an option, one way you might approach this would be to massage your data so that you can use vectorized functions to do everything in the compiled layer. If you change your neighbors dictionary into a two-dimensional array with appropriate flags for missing values, you can use <code>np.take</c...
python|numpy|optimization|matrix|cython
3
374,649
37,305,167
Installing tensorflow through docker on Ubuntu 14.04
<p>I've tried to install tensorflow on Ubuntu 14.04 through docker. It has been added to the docker images successfully. But when I run the docker image, I get the following error. </p> <pre><code>[I 16:12:44.450 NotebookApp] Writing notebook server cookie secret to /root/.local/share/jupyter/runtime/notebook_cookie_s...
<p>When executing the docker image it should be <p><code>docker run -it gcr.io/tensorflow/tensorflow /bin/bash</code> <p>Then it enters the interactive console</p>
image|docker|ubuntu-14.04|tensorflow|jupyter
1
374,650
37,477,224
How to fit an int list to a desired function
<p>I have an int list <code>x</code>, like <code>[43, 43, 46, ....., 487, 496, 502]</code>(just for example)<br> <code>x</code> is a list of word count, I want change a list of word count to a list penalty score when training a text classification model.</p> <p>I'd like use a <strong>curve</strong> function(maybe like...
<p>How about this way?</p> <p>EDIT: added weights. If you don't need to put your end points exactly on the curve you could use weights:</p> <pre><code>import scipy.optimize as opti import numpy as np xdata = np.array([43, 56, 234, 502], float) ydata = np.linspace(0.8, 0.08, len(xdata)) weights = np.ones_like(xdata, ...
python|numpy|pandas|scipy|curve-fitting
1
374,651
37,341,085
reading into np arrays not working
<p>hope all is well...I'm making a dataset feed into <code>sklearn</code> algorithms for categorization and couldn't find any easy datasets to start out with so making my own. got a problem, though...</p> <pre><code>import numpy as np import random type_1 = [random.randrange(0, 30, 1) for i in range(50)] type_1_label...
<p>You can directly create the NumPy arrays you want as a result:</p> <pre><code>ready1 = np.random.randint(0, 30, size=(50, 2)) ready1[:, 1] = 1 ready2 = np.random.randint(31, 71, size=(50, 2)) ready2[:, 1] = -1 </code></pre>
python|arrays|numpy
1
374,652
37,177,623
Python: Very slow execution loops
<p>I am writing a code for proposing typo correction using HMM and Viterbi algorithm. At some point for each word in the text I have to do the following. (lets assume I have 10,000 words) </p> <pre><code>#FYI Windows 10, 64bit, interl i7 4GRam, Python 2.7.3 import numpy as np import pandas as pd for k in range(10000)...
<p>I don't think that <code>range</code> discussion makes much difference. With Python3, where <code>range</code> is the iterator, expanding it into a list before iteration doesn't change time much.</p> <pre><code>In [107]: timeit for k in range(10000):x=k+1 1000 loops, best of 3: 1.43 ms per loop In [108]: timeit f...
python|numpy|pandas|optimization
4
374,653
41,827,109
FuncAnimation with a matrix
<p>I would like to use FuncAnimation to animate a matrix that will evolve. I tried to use a very simple matrix before using a complex one but I don't manage to use FuncAnimation with the simple one. I tried looking on other posts but I can't adapt them to what I want to do. Here's what I tried to do but it doesn't work...
<p>The reason your code doesn't work: You have not defined <code>mat</code> nor <code>modif</code>. Also, you should plot to the axes (<code>ax.matshow()</code>) instead of creating a new plot (<code>plt.matshow()</code>). The following should do what you want. </p> <pre><code>import numpy as np import matplotlib.pyp...
python|numpy|animation|matrix|matplotlib
2
374,654
42,017,411
Why I have to shuffle input data for linear regression in tensorflow
<p>I am using tensorflow to build linear regression model, the following is my code. But from what I experiment, I have to shuffle the train data, otherwise weight and bias would be estimated as na. Could anyone explain to me why I have to shuffle the data ? Thanks</p> <pre><code>train_X = np.linspace(1, 50, 100) trai...
<p>sometimes data is ordered by some columns and when you split you data to ratio of 75% vs 25% you are blind for some values that exists in the last 25% split. so you learn everything except the values that exists in the test (last 25% rows) se. thats why the best is to shuffle, to make sure you break some ordering in...
tensorflow|linear-regression
1
374,655
41,782,812
How do I find alternative methods in tensorflow latest release to deprecated one like tf.image_summary used in some tensorflow official tutorials?
<p>I am new to tensorflow. While I was reading the <a href="https://www.tensorflow.org/versions/master/tutorials/deep_cnn/" rel="nofollow noreferrer">CNN tutorial</a>, I found a broken link to a deprecated method <a href="https://www.tensorflow.org/versions/master/api_docs/python/train#image_summary" rel="nofollow nore...
<p>The safest way might be a quick search into the Tensorflow Github repo. E.g. <a href="https://github.com/tensorflow/tensorflow/search?utf8=%E2%9C%93&amp;q=image+summary" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/search?utf8=%E2%9C%93&amp;q=image+summary</a>, where you'll see it's been rename...
tensorflow
1
374,656
41,730,613
How to edit several elements in df.columns
<p>For example, the elements of the columns is <code>['a', 'b', 2006.0, 2005.0, ... ,1995.0]</code></p> <p>Now, I hope to change the float to int, so the correct elements of the columns should be <code>['a', 'b', 2006, 2005, ... , 1995]</code></p> <p>Since there are many numbers here, I don't think <code>rename(colum...
<p>You can do this:</p> <pre><code>In [49]: df Out[49]: a b 2006.0 2005.0 0 1 1 1 1 1 2 2 2 2 In [50]: df.columns.tolist() Out[50]: ['a', 'b', 2006.0, 2005.0] In [51]: df.rename(columns=lambda x: int(x) if type(x) == float else x) Out[51]: a b 2006 2005 0 1 1 1 1 1 ...
python|pandas|dataframe
7
374,657
41,786,171
Adding a rolling average to pandas dataframes in a loop takes forever
<p>I have a rather large dictionary of pandas dataframes. The keys are stock symbol, and each dataframe has 14 columns, containing stock market data. For example:</p> <pre><code>eodscreen['AAPL'] Out[35]: date open high low close volume ex-dividend \ date ...
<p>You're trying to assign on a slice of a slice that happens to be a view of another dataframe. It happened because of how you created the dictionary in the first place.</p> <p>Work around:</p> <pre><code>for k in eodscreen: eodscreen[k] = eodscreen[k].assign(MA=df['close'].rolling(window=5).mean()) </code></pr...
python|pandas|dictionary|dataframe|large-data
1
374,658
41,878,035
swap tensor axis in keras
<p>I want to swap tensor axis of image batches from (batch_size, row, col, ch) to (batch_size, ch, row, col). </p> <p>in numpy, this can be done with </p> <pre><code>X_batch = np.moveaxis( X_batch, 3, 1) </code></pre> <p>How would I do that in Keras? </p>
<p>You can use <code>K.permute_dimensions()</code> which is exactly similar to <code>np.transpose()</code>.</p> <p>Example:</p> <pre><code>import numpy as np from keras import backend as K A = np.random.random((1000,32,64,3)) # B = np.moveaxis( A, 3, 1) C = np.transpose( A, (0,3,1,2)) print A.shape print C.shape ...
tensorflow|keras
22
374,659
41,763,997
How to append item to list of different column in Pandas
<p>I have a dataframe that looks like this:</p> <pre><code>dic = {'A':['PINCO','PALLO','CAPPO','ALLOP'], 'B':['KILO','KULO','FIGA','GAGO'], 'C':[['CAL','GOL','TOA','PIA','STO'], ['LOL','DAL','ERS','BUS','TIS'], ['PIS','IPS','ZSP','YAS','TUS'], []]} df1 = pd.DataFrame(d...
<p>Inspired by Ted's solution but without modifying columns <code>A</code> and <code>B</code>:</p> <pre><code>def tolist(value): return [value] df1.C = df1.A.map(tolist) + df1.C + df1.B.map(tolist) </code></pre> <p>Using <code>apply</code>, you would not write an explicit loop:</p> <pre><code>def modify(row): ...
python|list|pandas|dataframe|append
3
374,660
41,740,432
Python - split string into multiples columns
<p>I have a dataframe, which containes a column with a string. it looks like :</p> <pre><code>[a] aaa aa a aaaa bbb bbb b cc cccc ccc cc ccc </code></pre> <p>What I would like is to add 6 columns with spliting values of [a], like this :</p> <pre><code>[a] [a0] [a1] [a2] [a3] [a4] [...
<p>You could use <code>str.split</code> and provide <code>expand=True</code> so that it enlarges into a dataframe for each of those individual splits.</p> <p>Reindex these by providing an added range so that we can create an extra column with <code>NaNs</code>. Provide an optional prefix char later.</p> <p>Then, conc...
python|string|pandas|split
8
374,661
41,893,640
Pandas groupby on one column, aggregate on second column, preserve third column
<p>I have the following dataframe:</p> <pre><code>df = pd.DataFrame({'key1': (1,1,1,2), 'key2': (1,2,3,1), 'data1': ("test","test2","t","test")}) </code></pre> <p>I want to group by key1 and have the min of data1. Further I want to preserve the according value of key2 without grouping on it.</p> <pre><code>df.groupb...
<p>You can make use of <code>groupby.apply</code> and retrieve all instances where <code>x['data1']==x['data1'].min()</code> equals to <code>True</code> while preserving the non-grouped columns as shown:</p> <pre><code>df.groupby('key1', group_keys=False).apply(lambda x: x[x['data1'].eq(x['data1'].min())]) </code></pr...
python|pandas|group-by
2
374,662
41,870,787
How to extract row in vertical condition
<p>Now I have dataframe below</p> <pre><code>A B C 1 a 1 1 b 0 1 c 0 1 d 1 2 e 1 2 f 1 2 g 0 3 h 1 3 i 0 3 j 1 3 k 1 </code></pre> <p>I would like to extract in condition with df.C</p> <p>in each number of df.A, for example number 1</p> <p>df.query("A==1")=</p> <pre><code>A B C 1 a 1 1 b 0 1 c 1 1 d 1 </code></pre...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#filtration" rel="nofollow noreferrer">filtration</a> - check first and last values in <code>C</code> in each <code>group</code> is not <code>0</code>:</p> <pre><code>print (df) A B C 0 1 a 1 1 1 b 0 2 1 c 0 3 1 d 1 4...
python|pandas|dataframe
4
374,663
42,074,308
Pandas - Convert String type to Float
<p>I have the following column in a DF. How could I convert this column into a float(13,5) with 5 decimals.String length is always 18 characters. As a workaround , I have used string split function and joined return values.</p> <pre><code>df=pd.DataFrame(['+00000030454360000','-00000030734250000','-00000004643685000']...
<p>Try this:</p> <pre><code>In [23]: pd.to_numeric(df.qty, errors='coerce') / 10**5 Out[23]: 0 304543.60 1 -307342.50 2 -46436.85 Name: qty, dtype: float64 </code></pre>
python|pandas
1
374,664
42,010,114
Training custom dataset with translate model
<p>Running the model out of the box generates these files in the data dir : </p> <pre><code>ls dev-v2.tgz newstest2013.en giga-fren.release2.fixed.en newstest2013.en.ids40000 giga-fren.release2.fixed.en.gz newstest2013.fr giga-fren.release2.fixed.en.ids40000 newstest2013.fr...
<p>blue-sky</p> <p>Great question, training a model on your own data is way more fun than using the standard data. An example of what you could put in the terminal is: </p> <p><code>python translate.py --from_train_data mydatadir/to_translate.in --to_train_data mydatadir/to_translate.out --from_dev_data mydatadir/tes...
tensorflow|translate
3
374,665
41,678,628
Get number of rows from .csv file
<p>I am writing a Python module where I read a .csv file with 2 columns and a random amount of rows. I then go through these rows until column 1 > x. At this point I need the data from the current row and the previous row to do some calculations.</p> <p>Currently, I am using 'for i in range(rows)' but each csv file wi...
<p>Store the previous line</p> <pre><code>with open("myfile.txt", "r") as file: previous_line = next(file) for line in file: print(previous_line, line) previous_line = line </code></pre> <p>Or you can use it with generators </p> <pre><code>def prev_curr(file_name): with open(file_name, ...
python|csv|numpy
1
374,666
42,005,072
Python: general rule for mapping a 2D array onto a larger 2D array
<p>Say you have a 2D <code>numpy</code> array, which you have sliced in order to extract its core, <em>just as if you were cutting out the inner frame from a larger frame</em>.</p> <p>The larger frame:</p> <pre><code>In[0]: import numpy In[1]: a=numpy.array([[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14],[15,16,17,18,19]])...
<pre><code>y, x = np.ogrid[1:m-1, 1:n-1] np.ravel_multi_index((y, x), (m, n)) </code></pre>
python|arrays|numpy|slice
1
374,667
41,928,927
Installing numpy with pip (python3) in virtual environment on ubuntu 15.10
<p>I am getting this error while installing numpy on python3.4 in ubuntu15.10. I am trying to install numpy in virtual environment.</p> <p>Just to make it clear, I have installed numpy and pandas on other windows and ubuntu(12.04) systems many times and did never face this kind of problem.</p> <p>The traceback is:</p...
<p>If you want to build numpy from source (you probably don't want to though) you'll need several build dependencies, usually a fortran compiler <code>apt install gfortran</code> and some mathy libraries <code>apt-install libblas-dev libatlas-base-dev liblapack-dev</code>.</p> <p>If you're using a sufficiently new ver...
python-3.x|ubuntu|numpy|pip
1
374,668
8,126,190
Cython/Numpy: Float being truncated
<p>consider the following:</p> <pre><code>import numpy as np cimport numpy as np DTYPE = np.float ctypedef np.float_t DTYPE_t def do(np.ndarray[DTYPE_t, ndim=2] hlc, int days=2): cdef float dvu = 0.0 cdef Py_ssize_t N = np.shape(hlc)[1]-1, i, j, k cdef np.ndarray[DTYPE_t] h = hlc[0] cdef np.ndarray[...
<p>I'm dumb. I was printing the thing out using the round function in a different module. There's 3 hours of my life I'll never get back ...</p>
python|numpy|cython
0
374,669
7,931,545
python(numpy) -- another way to produce array (from another array)
<p>i did this code :</p> <pre><code>from scitools.std import * npoints=10 vectorpoint=array(random.uniform(-1,1,[1,2])) experiment=array(random.uniform(-1,1,[npoints,2])) print("vectorpoint=",vectorpoint) print("experiment=",experiment) print(vectorpoint.shape) print(experiment.shape) </code></pre> <p>which works ...
<p>If you want <code>experiment</code> to be an array with <code>npoints</code> lines which are all equal to <code>vectorpoint</code>, you can use</p> <pre><code>experiment = vstack([vectorpoint] * npoints) </code></pre> <p>If you want <code>experiment</code> to have <code>npoints</code> lines independently generated...
python|arrays|numpy
1
374,670
8,298,797
Inserting a row at a specific location in a 2d array in numpy?
<p>I have a 2d array in numpy where I want to insert a new row. Following question <a href="https://stackoverflow.com/questions/3881453/numpy-add-row-to-array">Numpy - add row to array</a> can help. We can use <code>numpy.vstack</code>, but it stacks at the start or at the end. Can anyone please help in this regard.</p...
<p>You are probably looking for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.insert.html#numpy.insert" rel="noreferrer"><code>numpy.insert</code></a></p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.zeros((2, 2)) &gt;&gt;&gt; a array([[ 0., 0.], [ 0., 0.]]) # In the fol...
python|numpy
71
374,671
7,778,343
pcolormesh with missing values?
<p>I have 3 1-D ndarrays: x, y, z</p> <p>and the following code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import scipy.interpolate as spinterp ## define data npoints = 50 xreg = np.linspace(x.min(),x.max(),npoints) yreg = np.linspace(y.min(),y.max(),npoints) X,Y = np.meshgrid(xreg,yreg) Z = ...
<p>Got it. This seems round-about, but this was the solution:</p> <pre><code>import numpy.ma as ma Zm = ma.masked_where(np.isnan(Z),Z) plt.pcolormesh(X,Y,Zm.T) </code></pre> <p>If the Z matrix contains <code>nan</code>'s, it has to be a masked array for <code>pcolormesh</code>, which has to be created with <code>ma....
numpy|matplotlib|scipy
26
374,672
37,844,014
Plot dataframe grouped by one column, and hue by another column
<p>I have the following <a href="https://gist.github.com/silviutofan92/5a6ec2b82931831e164f81613ba76903" rel="nofollow">DataFrame</a> and would like to create separate line graphs (1 for each "Cluster"), where x-axis is "Week", y-axis is "Slot Request" and hue is "Group".</p> <p>To get the data that I want to plot, I ...
<p>Try something like this:</p> <pre><code>summed = full_df.groupby(["Group", "Cluster", "Week"])["Slot Request"].sum().reset_index() #reset_index turns this back into a normal dataframe g = sns.FacetGrid(summed, col="Group") #create a new grid for each "Group" g.map(sns.pointplot, 'Week', 'Slot Request') #map a point...
python|pandas|dataframe|seaborn
3
374,673
38,014,053
Learning OR gate through gradient descent
<p>I am trying to make my program learn OR logic gate using neural network and gradient descent algorithm. I took additional input neuron as -1 so that I can adjust threshold of neuron for activation later. currently threshold is simply 0. Here's my attempt at implementation</p> <pre><code>#!/usr/bin/env python from n...
<p>Well this <strong>is</strong> an OR gate, if you correct your testing data to be</p> <pre><code>activation = dot(array([[0,0,-1],[1,0,-1],[1,1,-1],[0,1,-1]]),wei) </code></pre> <p>(your code has 0,0 twice, and never 0,1) it produces</p> <pre><code>[[ 0.30021868] [ 0.67476151] [ 1.0276208 ] [ 0.65307797]] </cod...
python|numpy|machine-learning
1
374,674
37,982,252
pandas DataFrame - find max between offset columns
<p>Suppose I have a pandas dataframe given by</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5,2)) df 0 1 0 0.264053 -1.225456 1 0.805492 -1.072943 2 0.142433 -0.469905 3 0.758322 0.804881 4 -0.281493 0.602433 </code></pre> <p>I want to ...
<p>You want to apply <code>max</code> to rows after having shifted the first column.</p> <pre><code>pd.concat([df.iloc[:, 0].shift(), df.iloc[:, 1]], axis=1).apply(max, axis=1).dropna() </code></pre>
python|pandas|dataframe
1
374,675
37,804,158
syntaxnet bazel test failed
<p>I ran <code>bazel test syntaxnet/... util/utf8/...</code> and it gave me this output:</p> <pre><code>FAIL: //syntaxnet:parser_trainer_test (see /home/me/.cache/bazel/_bazel_rushat/cc4d67663fbe887a603385d628fdf383/syntaxnet/bazel-out/local-opt/testlogs/syntaxnet/parser_trainer_test/test.log). INFO: Elapsed time: 217...
<p>This is a bug in the syntaxnet test, it's looking for the wrong path. It needs the following patch:</p> <pre><code>diff --git a/syntaxnet/syntaxnet/parser_trainer_test.sh b/syntaxnet/syntaxnet/parser_trainer_test.sh index ba2a6e7..977c89c 100755 --- a/syntaxnet/syntaxnet/parser_trainer_test.sh +++ b/syntaxnet/synt...
tensorflow|bazel|syntaxnet
2
374,676
37,884,106
Tensorflow Dimensions are not compatible in CNN
<p>This is main.py:</p> <pre><code># pylint: disable=missing-docstring from __future__ import absolute_import from __future__ import division from __future__ import print_function import time from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf from pylab import * import cnn # ...
<p>Easy Typo:</p> <p>In your second convolution:</p> <pre><code>conv = tf.nn.conv2d(images, kernel, [1, 1, 1, 1], padding='VALID') </code></pre> <p>Change <code>images</code> to <code>pool1</code>:</p> <pre><code>conv = tf.nn.conv2d(pool1, kernel, [1, 1, 1, 1], padding='VALID') </code></pre>
python|numpy|machine-learning|tensorflow
3
374,677
37,714,462
Numpy einsum broadcasting
<p>Can someone please explain how broadcasting (ellipsis) works in the numpy.einsum() function?</p> <p>Some examples to show how and when it can be used would be greatly appreciated.</p> <p>I've checked the following official documentation page but there are only 2 examples and I can't seem to understand how to inter...
<p>The ellipses are a shorthand roughly standing for "all the remaining axes not explicitly mentioned". For example, suppose you had an array of shape (2,3,4,5,6,6):</p> <pre><code>import numpy as np arr = np.random.random((2,3,4,5,6,6)) </code></pre> <p>and you wish to take a trace along its last two axes:</p> <pre...
python|numpy|numpy-einsum
8
374,678
37,989,475
Optimizing/removing loop
<p>I have the following piece of code that I would like to optimize using numpy, preferably removing the loop. I can't see how to approach it, so any suggesting would be helpful.</p> <p>indices is a (N,2) numpy array of integers, N can be a few millions. What the code does is finding the repeated indices in the first ...
<p>Few improvements could be suggested :</p> <ul> <li><p>Initialize output array, for which we can pre-calculate the estimated number of rows needed for storing combinations corresponding to each group. We know that with <code>N</code> elements, the total number of possible combinations would be <code>N*(N-1)/2</code>...
python|numpy|networkx
2
374,679
37,962,759
How set values in pandas dataframe based on NaN values of another column?
<p>I have dataframe named <code>df</code> with original shape <code>(4361, 15)</code>. Some of <code>agefm</code> column`s values are NaN. Just look: </p> <pre><code>&gt; df[df.agefm.isnull() == True].agefm.shape (2282,) </code></pre> <p>Then I create new column and set all its values to 0: </p> <pre><code>df['neve...
<p>The best is use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="noreferrer"><code>numpy.where</code></a>:</p> <pre><code>df['nevermarr'] = np.where(df.agefm.isnull(), 1, 0) print (df) agefm nevermarr 0 NaN 1 1 5.0 0 2 6.0 0 </code></...
python|python-2.7|pandas|nan
8
374,680
37,999,389
'Invalid type comparison' in the code
<p>I have a <code>pandas dataframe</code> which has many columns. These columns may have 3 values - True, False and NaN. I'm replcaing the <code>NaN</code> with the string <code>missing</code>. The sample values for one of my columns is as follows:</p> <pre><code>ConceptTemp.ix[:,1].values </code></pre> <p>resulting ...
<p>As people have commented, it is a bit weird to combine types in your arrays (i.e. strings with booleans). You're going to get results where the boolean array may not be what you think it is. But if you absolutely have to, there are a couple of ways you could go about doing this. The first is with <code>isin</code>:<...
python|pandas|dataframe
3
374,681
37,849,921
Handling masked numpy array
<p>I have masked numpy array. While doing processing for each of the element, I need to first check whether the particular element is masked or not, if masked then I need to skip those element. </p> <p>I have tried like this : </p> <pre><code>from netCDF4 import Dataset data=Dataset('test.nc') dim_size=len(data.dime...
<p>Instead of a loop you could use</p> <pre><code>correction = model_dry_tropo_corr/2 + solid_earth_tide </code></pre> <p>This will create a new masked array that will have your answers and masks. You could then access unmasked values from new array.</p>
python|numpy
1
374,682
37,992,585
How to remove rows from a dataframe if 75 % of its column values is equal to 0
<p>I have a data frame of 44 column and 60,000 rows. I wanted to remove those rows if it has 0 up to 75 % of columns. This 75% :For example in my case out of 44 columns its 33 columns. And so I tried the following function in R as,</p> <pre><code>filter &lt;- apply(df, 1,function(x) any(x[1:33]!=0) &amp;&amp; any(x[34...
<p>Seems you want to remove lines which have more than 75% of <code>0</code>. Eg keep lines which have at least 25% of non zero-values.</p> <p>In <code>R</code>:</p> <pre><code>df = data.frame(a=c(1,8,0), b=c(0,2,0), c=c(0,0,1), d=c(4,4,0)) df[rowMeans(df!=0)&gt;0.25, ] # or df[rowMeans(df==0)&lt;0.75, ] # a b c d...
python|r|numpy|pandas
10
374,683
37,918,760
How to apply resampling and grouping at the same time with Pandas?
<p>My objective is to add rows in pandas in order to replace missing data with previous data and resample dates at the same time. My Data contains different products IDs and I must do a groupBy each time because I must keep the time serie data of every productId. Example : This is my dataframe :</p> <pre><code> pro...
<p>There are duplicates - one possible solution:</p> <pre><code>df = df.groupby(['productId','converted_timestamp','date'], as_index=False)['popularity'] .mean() print (df) productId converted_timestamp date popularity 0 15620743.0 2016-01-11 2016-01-11 526888.000000 1 15620743.0 ...
python-2.7|pandas|indexing|group-by|resampling
1
374,684
37,876,397
Numpy interfering with namespace
<pre><code>import numpy as np def f(x): x /= 10 data = np.linspace(0, 1, 5) print data f(data) print data </code></pre> <p>Output on my system (debian 8, Python 2.7.9-1, numpy 1:1.8.2-2)</p> <pre><code>[ 0. 0.25 0.5 0.75 1. ] [ 0. 0.025 0.05 0.075 0.1 ] </code></pre> <p>Normally I would expect <code>...
<blockquote> <p>Normally I would expect data to stay untouched when passing it to a function as this has its own separate namespace.</p> </blockquote> <p><code>x</code> in the function and <code>data</code> at the module level are two names for the <em>same</em> object. Since that object is mutable, any changes mad...
python|numpy|matplotlib|namespaces
3
374,685
37,791,719
How do I fill a DataFrame from another DataFrame, adding rows and replacing nulls?
<p>I have two <code>pandas.DataFrame</code>s with overlapping columns and indices, like</p> <pre><code>X = pandas.DataFrame({"A": ["A0", "A1", "A2"], "B": ["B0", None, "B2"]}, index=[0, 1, 2]) Y = pandas.DataFrame({"A": [V, "A3"], "B": ["B1", "B3"], "C": ["C1", "C3"]}, index=[...
<p>The <code>combine_first</code> method is half the deal, thanks to @IanS for pointing it out.</p> <pre><code>&gt;&gt;&gt; X.combine_first(Y)[list(X.columns)] A B 0 A0 B0 1 A1 B1 2 A2 B2 3 A3 B3 </code></pre> <p>Now, if <code>V</code> is nice, we should get the same result when <code>combine_first</cod...
python|pandas
0
374,686
37,696,630
how to find difference in dates in pandas dataframe in Azure ML
<p>Is Azure uses some other Syntax for finding difference in dates and time.<br> or<br> Any package is missing in Azure.<br> how to find difference in dates in pandas data-frame in Azure ML. <br>I have 2 columns in a dataframe and I have to find the difference of two and have to kept in third column ,the problem is thi...
<p>Per my experience, it seems that the issue was caused by your code without the <code>dataframe_service</code> which indicates that the function operations on a data frame, please see <a href="https://github.com/Azure/Azure-MachineLearning-ClientLibrary-Python#dataframe_service" rel="nofollow">https://github.com/Azur...
python|azure|pandas|machine-learning|azure-machine-learning-studio
0
374,687
31,445,661
Cython: Performance in Python of view_as_windows vs manual algorithm?
<p>My environment is OS: Ubuntu and Language: Python + Cython.</p> <p>I am having a bit of a quandary as to what path to pursue. I am using view_as_windows to slice up an image and return to me an array of all the patches created from slicing. I also created an algorithm that does pretty much the same thing to have mo...
<p>I don't think you can do much better than <code>view_as_windows</code>, as it is already very efficient as long as the input array is contiguous. I doubt even cythonizing it would make much difference. I looked into its implementation and was actually a bit impressed:</p> <p>A numpy array is made up of an underlyin...
python|algorithm|performance|numpy|cython
4
374,688
31,536,835
Extract value from single row of pandas DataFrame
<p>I have a dataset in a relational database format (linked by ID's over various .csv files).</p> <p>I know that each data frame contains only one value of an ID, and I'd like to know the simplest way to extract values from that row.</p> <p>What I'm doing now:</p> <pre><code># the group has only one element purchase...
<p>If you want just the value and not a df/series then call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.values.html#pandas.DataFrame.values" rel="noreferrer"><code>values</code></a> and index the first element <code>[0]</code> so just:</p> <pre><code>price = purchase_group['Column_n...
python|pandas
69
374,689
31,516,319
Packages not working, using Anaconda
<p>I have installed Anaconda for Windows. It's on my work PC, so I chose the option "Just for Me" as I don't have admin rights.</p> <p>Anaconda is installed on the following directory:</p> <pre><code>c:\Users\huf069\AppData\Local\Continuum\Anaconda </code></pre> <p>The Windows installer has added this directory (+ t...
<blockquote> <p>I can launch Python, but trying to run <code>x = randn(100,100)</code> gives me a <code>Name Error: name 'randn' is not defined</code>, whereas, as I understood, this command should work when using Anaconda, as the <code>numpy</code> package is included</p> </blockquote> <p>The <em>Anaconda</em> dist...
python|numpy|anaconda
7
374,690
31,276,585
how to turn an array into a callable function
<p>I have a <code>np.piecewise</code> function I would like to turn into a callable.</p> <p>For example, suppose we have:</p> <pre><code>import numpy as np x = np.linspace(0,10,1001) my_func = np.piecewise(x, [x&lt;8, x&gt;=8], [np.sin, np.cos]) </code></pre> <p>I am interested in making a function <code>my_callable...
<p>You could simply wrap the <code>np.piecewise</code> call inside a function definition,</p> <pre><code>In [1]: def my_callable_func(x): ...: return np.piecewise(x, [x&lt;8, x&gt;=8], [np.sin, np.cos]) ...: my_callable_func(0.015) Out[1]: array(0.01499943750632809) </code></pre> <p>The value of your orig...
python|numpy
3
374,691
31,306,980
python average of random sample many times
<p>I am working with pandas and I wish to sample 2 stocks from <strong>each trade date</strong> and store as part of the dataset the average "Stock_Change" and the average "Vol_Change" for the given day in question based on the sample taken (in this case, 2 stocks per day). The actual data is much larger spanning year...
<pre><code>import pandas as pd import numpy as np # replicate your data structure # ============================== np.random.seed(0) dates = pd.date_range('2008-01-01', periods=100, freq='B') symbols = 'A B C D E'.split() multi_index = pd.MultiIndex.from_product([dates, symbols], names=['Date', 'Symbol']) stock_change...
random|pandas|sample
1
374,692
31,232,770
Difference between df.describe and df.describe()
<pre><code>import pandas as pd import numpy as np dates =pd.date_range('20150501',periods=5) df =pd.DataFrame(np.random.randn(5,4),index=dates,columns="i know its example".split()) </code></pre> <p><code>df.describe()</code> is giving different results compared to <code>df.describe</code>. Please explain to me the dif...
<p><code>df.describe</code> is the method itself (you can think of a 'pointer to method' in some other languages). <code>df.describe()</code> calls the method, and returns the result.</p> <pre><code>p = df.describe p() df.describe() </code></pre> <p>In the example above, <code>p()</code> and <code>p.describe()</code>...
python-3.x|pandas
2
374,693
31,589,497
Numpy: efficient way of filtering a very large array with a list of values
<p>Let's say I am manipulating a very large array of <code>int</code>s in numpy ( ). I want to filter it with a sublist of its values <code>sublist</code>. As the array is really large it looks like I need to be smart to do it in teh quickest way.</p> <p>For instance:</p> <pre><code>my_array = N.random.randint(size=1...
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html" rel="nofollow"><code>numpy.in1d</code></a> does exactly this. Your code would look like:</p> <pre><code>cut = N.in1d(my_array, sublist) my_array = my_array[cut] </code></pre>
python|numpy
4
374,694
31,380,654
pandas.date_range accurate freq parameter
<p>I'm trying to generate a <code>pandas.DateTimeIndex</code> with a samplefrequency of 5120 Hz. That gives a period of <code>increment=0.0001953125</code> seconds.</p> <p>If you try to use <code>pandas.date_range()</code>, you need to specify the frequency (parameter <code>freq</code>) as <code>str</code> or as <code...
<p>I think I reach a similar result with the function below (although it uses only nanosecond precision):</p> <pre><code>def date_range_fs(duration, fs, start=0): """ Create a DatetimeIndex based on sampling frequency and duration Args: duration: number of seconds contained in the DatetimeIndex ...
python|python-3.x|pandas
0
374,695
31,583,018
python array sorting and indexing
<p>Suppose you have a 3D array:</p> <pre><code>arr = np.zeros((9,9,9)) a[2:7,2:7,2:7] = np.random.randint(5, size=(5,5,5)) </code></pre> <p>How can you sort all occurring values in this array (not along an axis like with e.g. np.sort) and show all indices of those values?</p> <p>Output should be something like:</p> ...
<pre><code>import numpy as np arr = np.zeros((9,9,9)) arr[2:7,2:7,2:7] = np.random.randint(5, size=(5,5,5)) S = np.sort(arr,axis=None) I = np.argsort(arr, axis=None) print np.array([S] + list( np.unravel_index(I, arr.shape))).T </code></pre> <p>This should give you more or less the result you are looking for; the ess...
python|arrays|sorting|numpy
1
374,696
31,598,677
Why list comprehension is much faster than numpy for multiplying arrays?
<p>Recently I answered to <a href="https://stackoverflow.com/questions/31596979/multiplication-between-2-lists/31597029#31597029">THIS</a> question which wanted the multiplication of 2 lists,some user suggested the following way using numpy, alongside mine which I think is the proper way :</p> <pre><code>(a.T*b).T </c...
<p>Creation of numpy arrays is much slower than creation of lists:</p> <pre><code>In [153]: %timeit a = [[2,3,5],[3,6,2],[1,3,2]] 1000000 loops, best of 3: 308 ns per loop In [154]: %timeit a = np.array([[2,3,5],[3,6,2],[1,3,2]]) 100000 loops, best of 3: 2.27 µs per loop </code></pre> <p>There can also fixed costs i...
python|performance|numpy|list-comprehension|matrix-multiplication
14
374,697
31,442,826
Increasing efficiency of barycentric coordinate calculation in python
<p>Background: I'm attempting to warp one face to another of a different shape.</p> <p>In order to warp one image to another, I'm using a delaunay triangulation of facial landmarks and warping the triangles of one portrait to the corresponding triangles of the second portrait. I'm using a barycentric coordinate system...
<p>Here are my suggestions, expressed in your pseudocode. Note that vectorizing the loop over the triangles should not be much harder either.</p> <pre><code># Iterate through each triangle (and get corresponding warp triangle) for triangle in triangulation: # Extract corners of the unwarped triangle a = first...
python|numpy|linear-algebra|delaunay
3
374,698
31,520,033
How to stop Pandas adding time to column title after transposing a datetime index?
<p>I have a Pandas dataframe as follows:</p> <pre><code>In [10]: libor_table Out[10]: Euribor interest rate - 3 months Euribor interest rate - 6 months \ 2015-07-17 -0.019% 0.049% 2015-07-16 -0.019% 0.049%...
<p>This looks like a bug to me which I can reproduce using a small example:</p> <pre><code>In [120]: # generate some dummy data t="""time,value 2015-07-17,0 2015-07-18,1""" df = pd.read_csv(io.StringIO(t), parse_dates=True, index_col=[0]) df Out[120]: value time 2015-07-17 0 2015-07-18 ...
python|pandas
1
374,699
31,430,881
seaborn.heatmap skips data
<p>When creating a heatmap via seaborn <code>seaborn==0.7.0.dev0</code> my axis starts two hours later. The DataFrame used to create the heatmap starts at:</p> <p><code>2015-05-19 21:10:00</code></p> <p>The first get_xticklabels of the heatmap created via seaborn however is <code>2015-05-19 23:10:00</code>.</p> <p>T...
<p>Okay turns out it is the missing tz= value when creating the index which gives the offset inb the example code.</p> <p>My solution (as changing tz in my DataFrame did not change this behaviour) was to set <code>xticklabel=False</code> in <code>heatmap()</code> and use <code>plt.xticks()</code> directly.</p>
python|pandas|heatmap|seaborn
1