Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
359,600
37,445,855
Pandas read_table error
<p>I am trying to read a tab delimited text file into a dataframe. </p> <p>This is the how the file looks in Excel: </p> <pre><code>CALENDAR_DATE ORDER_NUMBER INVOICE_NUMBER TRANSACTION_TYPE CUSTOMER_NUMBER CUSTOMER_NAME 5/13/2016 0:00 13867666 6892372 S 2026 ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="noreferrer"><code>read_csv</code></a> with separator 2 and more whitespaces:</p> <pre><code>import pandas as pd import io temp=u"""CALENDAR_DATE ORDER_NUMBER INVOICE_NUMBER TRANSACTION_TYPE CUSTOMER_NUMBE...
python|mysql|pandas
5
359,601
37,296,187
Pandas resample by groups with duplicate datetimes
<p>Lots of similar questions on here, but I couldn't find any that actually had observations with the same datetime. A minimum non-working example would be:</p> <pre><code>df = pd.DataFrame( {"Date": np.tile([pd.Series(["2016-01", "2016-03"])], 2)[0], "Group": [1,1,2,2], "Obs":[1,2,5,6]}) </code></pre> ...
<p>You can use:</p> <pre><code>#convert column Date to datetime df['Date'] = pd.to_datetime(df.Date) print (df) Date Group Obs 0 2016-01-01 1 1 1 2016-03-01 1 2 2 2016-01-01 2 5 3 2016-03-01 2 6 #groupby, resample and interpolate df1 = df.groupby('Group').apply(lambda x : x.s...
python|datetime|pandas
3
359,602
37,196,010
Pandas 0.18 how to pivot data frame when the data contains both numeric and non numeric types
<pre><code>import pandas as pd df1 = pd.DataFrame({'index': range(6), 'Name': ["Swap1", "Swap2", "Swap3", "Swap1", "Swap2", "Swap3"], 'LegName': ["pay", "receive", "total", "pay", "receive", "total"], 'Metric': ["pv", "pv", "pv", "start", "start", "start"], ...
<p>this will work:</p> <pre><code>In [32]: df1.pivot_table(values='result', index='index', ....: columns=['Name', 'LegName', 'Metric'], ....: fill_value=0, ....: aggfunc='sum') Out[32]: Name Swap1 Swap2 Swap3 LegName pay receive to...
python|pandas|pivot-table
0
359,603
37,486,335
How to select min record by user in a Pandas data frame while accounting for multiple matches when you only want one
<p>I have a <code>pandas DataFrame</code> that looks like this:</p> <pre><code> record_date userid id priority 1 2016-05-27 02:00:39.600 1rhNGfQjU6 2718376 3 2 2016-05-27 02:00:39.600 EveMoYR1gs 2718377 3 3 2016-05-27 02:00:39.600 iVYGQgU3bX 2718378 3 4 2...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by column <code>userid</code> and date of <code>datetime</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow"><...
python|pandas
1
359,604
37,502,610
Numpy from string (Difference of uint8 and uint16) [Combining two uint8 values to one uint16 value]
<p>I have an audio file in Java, when I read <code>AudioInputStream</code> and convert it to byte array, I get values between <code>-128</code> and <code>127</code>. I need to convert those values to a range between <code>-32768</code> and <code>32767</code>. So I think I need to combine every two values in my Java arr...
<p>Use <a href="https://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html" rel="nofollow"><code>ByteBuffer</code></a>:</p> <pre><code>byte[] b = { 37, -39, -112, -32, 123, -40, -114, 121 }; short[] s = new short[b.length / 2]; ByteBuffer buf = ByteBuffer.wrap(b); // buf.order(ByteOrder.LITTLE_ENDIAN); for (in...
java|python|numpy|binary|hex
0
359,605
37,240,053
Why SyntaxNet demo.sh is not finding correct imports?
<p>I went through <a href="https://github.com/tensorflow/models/tree/master/syntaxnet" rel="nofollow">https://github.com/tensorflow/models/tree/master/syntaxnet</a> and did everything it says.</p> <p>I ran this to test:</p> <pre><code>bazel test --linkopt=-headerpad_max_install_names \ syntaxnet/... util/utf8/......
<p>Solved. I was missing some of the steps in bazel installation, in particular, 'Getting bash completion'. I thought that was only for jdk7.</p>
python|tensorflow|syntaxnet
3
359,606
37,143,466
Find mean of value row wise in a list
<p>I am trying find mean of the values in two columns. </p> <p>Input:</p> <pre><code>tweetcricscore 34 #afgvssco 51 tweetcricscore 23 #afgvszim 46 tweetcricscore 24 #banvsire 12 tweetcricscore 456 #banvsned 46 tweetcricscore 653 #canvsnk 1 tweetcricscore 789 #cricket 178 tweetcricscore 625 #engvswi ...
<p>You can easily do this in Pandas:</p> <pre><code>import pandas as pd df = pd.read_csv('keyword.csv', header = None) df.columns = ['col1','col2','col3','col4'] df['avgCol'] = (df['col2'] + df['col4'])/2 </code></pre>
python|numpy|mean|mathematical-expressions
3
359,607
37,415,068
how to retrieve all lines with errors in pandas
<p>For example, I can use</p> <pre><code>pd.read_csv('file.csv') </code></pre> <p>to load a csv file.</p> <p>By default, it fails when there are any parsing errors. I understand that one can use <code>error_bad_lines=False</code> to skip the rows with errors.</p> <p>But my question is:</p> <p>How to get all the li...
<p>One easy way would be to prepend a row index number to each row. This can easily be done with Awk or Python before loading the data. You could even do it in-memory using StringIO or your own custom file-like object in Python which would "magically" prepend the row numbers.</p>
python|pandas
1
359,608
37,194,685
Populating dataframes in loop
<p>Is there an elegant way to read one file at a time, do some preprocessing, and then merge into one big dataframe. The way I do it is here. I am sure there may be some other way to get rid of variable <code>i</code> here. </p> <pre><code>i=0 outdf = DataFrame() for myfile in myfiles: tdf = read_csv(myfile) #Rea...
<p>You don't need to concatenate the DataFrames on each iteration, as <code>concat</code> can concatenate multiple DataFrames. Just store each individual DataFrame in a list, and concatenate at the end.</p> <pre><code>outdf = [] for myfile in myfiles: tdf = read_csv(myfile) #Do some annotations tdf['Clas...
python|pandas
3
359,609
37,599,764
python find string pattern in numpy array of strings
<p>I have a numpy array of strings 'A' of length 100 and they are sentences of different sizes. It is string NOT numpy strings</p> <pre><code>&gt;&gt;&gt; type(A[0]) &lt;type 'str'&gt; </code></pre> <p>I want to find the location of strings in A which contain certain pattern like 'zzz' in them.</p> <p>I tried</p> <...
<p>No need to be fancy with this, you can get the list of indicies with a list comprehension and the <code>in</code> operator:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; lst = ["aaa","aazzz","zzz"] &gt;&gt;&gt; n = np.array(lst) &gt;&gt;&gt; [i for i,item in enumerate(n) if "zzz" in item] [1, 2] </cod...
python|string|numpy
15
359,610
37,264,301
pandas to_csv split some rows in 2 lines
<p>i have a problem with pandas.to_csv</p> <p>pandas dataframe work correctly and pd.to_excel work well too. </p> <p>when i try to use .to_csv some rows splitted in two (i see it in wordpad and excel)</p> <p>for example:</p> <pre><code>line 1: provincia;comune;Ragione sociale;indirizzo;civico;destinazione;sup_coper...
<p>You can use the Pandas Replace method to achieve this rather than creating a new function.</p> <p><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer">Pandas Replace Method</a></p> <p>It includes regex so you can include expressions in the replace such as <co...
python|pandas
1
359,611
37,577,965
Most efficient way to aggregate tabular data meeting certain conditions in Python in O(1) time?
<p>Let's say I have a table with a bunch of data in long format (each row has one data point). For instance, let's say we have a table of people's SAT scores, with columns for state, city, school, gender, race, and person. My goal is to find a way to easily pull out and average data points corresponding to certain grou...
<p>You cannot do this in O(1) time. </p> <p>This problem has more than one complexity associated with it. I can think of three: Prepossessing, insertion, and lookup. </p> <p>You could do this in O(nlog(n)) preproccessing + O(log(n)) lookup time, and O(log(n)) insertion as follows:</p> <pre><code> from collections...
python|pandas
0
359,612
37,584,260
Opencv: ValueError
<p>I have detected contours and stored them in cnts and i am accessing them one by one, c_list is the list of contours which are of interest to me. I want to check if the contour i am accessing now is already been accessed before or not by using this code:</p> <pre><code>if not (np.all(cnts[c] in c_list)): while...
<p>Your issue is not really related to OpenCV, it comes from numpy.</p> <p>Consider the following examples:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; [1,3] in [[1,3],[4,5]] True &gt;&gt;&gt; np.array([1,3]) in [[1,3],[4,5]] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;m...
python|numpy|python-2.7|opencv|contour
2
359,613
41,786,349
Python pandas loop value conditional on two columns
<p>In my dataframe 'data' I have two columns 'trend' &amp; 'rtrend' </p> <p><code>trend</code> has values -1, 0 and 1. </p> <pre><code>def newfunc(a): j = -1 for i in a: j = j+1 x = (j-1) if data.iloc[j]['trend'] != 0: return data.iloc[j]['trend'] if data.iloc[j]['trend'] == 0: ...
<p>Don't do a procedural slow <code>for</code> loop. Do the vectorized approach. Just copy non zero data into your new <code>rtrend</code> column, then forward fill the data:</p> <pre><code>df['rtrend'] = df[df.trend!=0]['trend'] df Out[21]: trend b c rtrend a -1.0 1.0 -1.0 -1.0 c 0.0 -1.0 1.0 ...
python|function|loops|pandas
4
359,614
42,030,478
Group 2D numpy array elements which have equal 1st column values
<p>I have a 2D numpy array like this</p> <pre><code>[[ 569 897] [ 570 898] [ 570 900] [ 571 901] [ 571 905] [ 572 906]] </code></pre> <p>I want the <strong>elements which have equal values in the first column to be grouped</strong> together in the following way.</p> <pre><code>[[ 569 897] [[ 570 898] ...
<p>You can use <code>np.unique</code> to get the <em>separating</em> indices and then use <code>np.split</code> to actually split -</p> <pre><code>np.split(a, np.unique(a[:,0], return_index=1)[1][1:],axis=0) </code></pre> <p>Alternatively, with slicing and using <code>np.flatnonzero</code> -</p> <pre><code>np.split(...
python|arrays|numpy
4
359,615
42,098,093
Get indices of top N values in 2D numpy ndarray or numpy matrix
<p>I have an array of N-dimensional vectors.</p> <p><code>data = np.array([[5, 6, 1], [2, 0, 8], [4, 9, 3]])</code></p> <pre><code>In [1]: data Out[1]: array([[5, 6, 1], [2, 0, 8], [4, 9, 3]]) </code></pre> <p>I'm using sklearn's <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics...
<p>I'd ravel, argsort, and then unravel. I'm not claiming this is the best way, only that it's the first way that occurred to me, and I'll probably delete it in shame after someone posts something more obvious. :-)</p> <p>That said (choosing the top 2 values, arbitrarily):</p> <pre><code>In [73]: dists = sklearn.met...
python|arrays|numpy|matrix
7
359,616
41,819,735
What is the difference between SessionBundlePredict and SavedModelPredict in tensorflow serving?
<p>As I read in the source code, <code>SessionBundlePredict</code> uses <code>collection_def</code> in <code>MetaGraphDef</code> and <code>SavedModelPredict</code> uses <code>signature_def</code> in <code>MetaGraphDef</code> but I have no idea what is the difference between <code>collection_def</code> and <code>signatu...
<p>That's essentially correct. Specifically, the signature information for session bundles is stored in a special collection in collection_def.</p> <p>However, SessionBundle and Exporter.export have been unsupported since <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/session_bundle/e...
tensorflow-serving
0
359,617
41,726,080
How to insert elements of a list in diagonal elements of identity matrix?
<p>I have 5x5 identity matrix and a list of float numbers</p> <pre><code> 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 L=[0.01, 0.02, 0.26, 0.03, 0.68] </code></pre> <p>My question is how can I put elements of list into identity matrix?</p> <pre><code> 0.01 0 0 0 0 0 0.02 0 0 0 ...
<p>This method is extensible to writing the diagonal of other arrays, i.e. <code>a</code> need not be an identity matrix:</p> <pre><code>&gt;&gt;&gt; a = np.eye(5) &gt;&gt;&gt; L = [0.01, 0.02, 0.26, 0.03, 0.68] &gt;&gt;&gt; d = np.diag_indices_from(a) &gt;&gt;&gt; a[d] = L &gt;&gt;&gt; print(a) [[ 0.01 0. 0. 0...
python|numpy
5
359,618
42,087,302
Tensorflow flags not recognized
<p>I have a tensorflow code to be run on pyspark. Code</p> <pre><code>tf.flags.DEFINE_integer("evaluate_every", 100, "Evaluate model on dev set after this man y steps (default: 100)") tf.flags.DEFINE_integer("window_size", 3, "n-gram") tf.flags.DEFINE_integer("sequence_length", 204, "max tokens b/w entiti...
<p>Get the latest TensorFlow (>1.4) with Python3 and use <code>FLAGS(sys.argv)</code>, since the <code>FLAGS._parse_flags()</code> is not supported any more.</p> <pre><code>import sys import tensorflow as tf FLAGS = tf.app.flags.FLAGS unparsed = FLAGS(sys.argv) </code></pre>
python|tensorflow|pyspark
0
359,619
42,061,323
How to do group by and take count of unique and count of some value as aggregate on same column in python pandas?
<p>My question is related to my previous <a href="https://stackoverflow.com/questions/42022767/how-to-do-group-by-and-take-count-of-one-column-divide-by-count-of-unique-of-sec">Question</a> but it's different. So I am asking the new question.</p> <p>In above question see the answer of @jezrael.</p> <pre><code>df = pd...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.aggregate.html" rel="nofollow noreferrer"><code>aggregate</code></a> with list of function in <code>dict</code> for column <code>col4</code>.</p> <p>If need count <code>3</code> values the simpliest is <code>...
python|mysql|pandas|numpy
2
359,620
42,000,505
Vectorizing an operation between all pairs of elements in two numpy arrays
<p>Given two arrays where each row represents a circle (x, y, r):</p> <pre><code>data = {} data[1] = np.array([[455.108, 97.0478, 0.0122453333], [403.775, 170.558, 0.0138770952], [255.383, 363.815, 0.0179857619]]) data[2] = np.array([[455.103, 97.0473, 0.012041], ...
<p>The most difficult bit is actually getting to your representation of the info. Oh, and I inserted a few squares. If you really don't want Euclidean distances you have to change back.</p> <pre><code>import numpy as np data = {} data[1] = np.array([[455.108, 97.0478, 0.0122453333], [403.775, 170....
python|arrays|numpy|geometry|combinations
3
359,621
41,729,368
pandas randomly replace k percent
<p>having a simple pandas data frame with 2 columns e.g. <code>id</code> and <code>value</code> where <code>value</code> is either <code>0</code> or <code>1</code> I would like to randomly replace <code>10%</code> of all <code>value==1</code> with <code>0</code>.</p> <p>How can I achieve this behaviour with pandas?</p...
<p><strong><em><code>pandas</code> answer</em></strong> </p> <ul> <li>use <code>query</code> to get filtered <code>df</code> with only <code>value == 1</code></li> <li>use <code>sample(frac=.1)</code> to take 10% of those</li> <li>use the index of the result to assign zero</li> </ul> <hr> <pre><code>df.loc[ df....
python|pandas|numpy
15
359,622
42,098,237
Numpy 2D array: change all values to the right of NaNs
<h2>Situation</h2> <p>I have a 2D Numpy array that contains some <code>nan</code> values. Simplified example:</p> <pre><code>arr = np.array([[3, 5, np.nan, 2, 4], [9, 1, 3, 5, 1], [8, np.nan, 3, np.nan, 7]]) </code></pre> <p>which looks like this in console output:</p> <pre><code>arr...
<p>One approach with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html" rel="nofollow noreferrer"><code>cumsum</code></a> and <a href="https://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow noreferrer"><code>boolean-indexing</code></a> -</p> ...
python|arrays|performance|numpy|vectorization
5
359,623
42,040,519
Deleting DataFrame row in a multilevel index Pandas based on column value
<p>Consider the following Multilevel DataFrame</p> <pre><code>import numpy as np import pandas as pd arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ...: ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] tuples = list(zip(*arrays)) index = pd.MultiIndex.from_tuples(tuples, name...
<p>You could use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow noreferrer"><code>drop</code> method</a>:</p> <pre><code>In [26]: s.drop(('bar','two'), axis=0) Out[26]: 0 1 2 3 bar one -0.450943 -1.615345 -0.862521 ...
python-3.x|pandas|dataframe
2
359,624
41,802,834
Find the most common pairs in a Dataframe of lists
<p>I have a data frame with columns <code>ID, Product</code>. For example, </p> <pre><code>ID Product 1 ['a','b'] 2 ['a','b','e'] 3 ['c','d'] 4 ['a','b','c','d'] </code></pre> <p><code>Product</code> is a field of lists where each list contains the products that a person has. For example, a person with <code...
<p>1) Use <a href="https://docs.python.org/3.5/library/itertools.html#itertools.combinations" rel="nofollow noreferrer"><code>itertools.combinations</code></a> to acquire all such combinations of pairs possible and convert the resulting series to it's list representation that needs to be fed to a dataframe constructor ...
python|pandas|list|dataframe
5
359,625
41,909,915
tf.train.string_input_producer behavior in a loop
<p>The following snippet has been taken from the TensorFlow 0.12 API documentation</p> <pre class="lang-py prettyprint-override"><code>def input_pipeline(filenames, batch_size, num_epochs=None): filename_queue = tf.train.string_input_producer( filenames, num_epochs=num_epochs, shuffle=True) example, label = ...
<p>The <code>input_pipeline</code> function only creates the part of a (usually larger) graph that is responsible for producing batches of data. If you were to call <code>input_pipeline</code> twice - for whatever reason - you would be creating two different queues indeed.</p> <p>In general, the function <code>tf.trai...
tensorflow
3
359,626
41,966,763
How to split a column in pandas using separator and also assign custom unique name in the process?
<p>I want to split a hybrid block and assign letters to each column separately:</p> <pre><code>M1 M2 M3 M4 hybrid_block S1 S2 S3 S4 A T T A A|C C G C T T G C T T|A A T A T C A A C C|G G A C G G T G T G|T ...
<p>you can also use <a href="http://pandas.pydata.org/pandas-docs/version/0.19.2/generated/pandas.Series.str.extract.html" rel="nofollow noreferrer">.str.extract()</a> method:</p> <pre><code>In [107]: d1 = pd.concat([ ...: df.filter(like='M'), ...: df.hybrid_block.str.extract(r'(?P&lt;H_x&gt;[^\|]*)\...
python|pandas|split
3
359,627
42,002,521
How to extract the index from pd.Dataframe
<p>I have some Dataframe</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({ 'name': ['Alice','John','Peter','Richard'], 'age': [23,28,43,29], 'gender': [0,1,1,1], 'salary': [900, 400, 900, 400] }) </code></pre> <p>I can extract any value from this</p> <pre><code>df.ix[df['nam...
<p>Use:</p> <pre><code>print (df[df['name'] == 'Alice'].index) Int64Index([0], dtype='int64') print (df.index[df['name'] == 'Alice']) Int64Index([0], dtype='int64') </code></pre> <p>If need output as <code>list</code>:</p> <pre><code>print (df[df['name'] == 'Alice'].index.tolist()) [0] </code></pre> <p>And if need...
python-3.x|pandas|indexing|extract
3
359,628
41,790,857
What is the difference between saving a summary and saving the model in the logdir?
<p>Using Tensorflow (tf.contrib.slim in particular) we are required to calibrate a few parameters to produce the graphs that we want at tensorboard.</p> <p>Saving a <strong>summary interval</strong> is more clear for us what it does. It saves the value (or an average of them?) of a particular point in the graph at the...
<p>You <strong>save the model</strong> to checkpoints because the Variables in the model, including neural network weights and biases and the global_step counter, keep changing during the training process. The structure of the model doesn't change. The saved checkpoints allow you to load the trained model for serving a...
tensorflow|tf-slim
0
359,629
41,816,537
Raising custom errors in procedural python scripts
<p>I'm putting together a short data analysis script using pandas and writing the results out to an excel sheet with graphs.</p> <p>Currently I'm using <code>sys.exit</code> to make the user aware of problems associated with the input data. </p> <p>Below is an example : </p> <pre><code>if len(titles) != len(plot_ke...
<p>A pythonic way to raise custom errors is to define your own exceptions. This might look something like:</p> <pre><code>class MyCustomException(Exception): pass class ChartTitles(MyCustomException): pass class TooManyWells(MyCustomException): pass if len(titles) != len(plot_key): raise ChartTitle...
python|pandas|exception
0
359,630
42,025,223
How to get the unique values from pandas dataframe based on same id of other column
<p>I have pandas dataframe as follows:</p> <pre><code>user id 1 2 1 2 1 2 1 3 1 3 </code></pre> <p>i want to group by values like this: (1,1,1,2),(1,1,3)</p> <p>I am using this and it is giving unique values of one column only</p> <pre><code>pd.unique(df[['id']].values.ravel()) </code></pre> <p...
<p>One way, seems self-explanatory:</p> <pre><code>df = df.sort_values(['user', 'id']) df['groups'] = (df.id!=df.id.shift()).cumsum() # pattern to number groups df Out[26]: user id groups 0 1 2 1 1 1 2 1 2 1 2 1 3 1 3 2 4 1 3 2 df.id = df.id.drop_du...
python-3.x|pandas
1
359,631
41,910,940
Feed non-placeholder variables in seq2seq
<p>I'm playing with Tensorflow seq2seq model and I'm wondering how I can feed a trained seq2seq decoder with an arbitrary initial decoder memory (during the training, this initial decoder memory is an output of the encoder).</p> <p>I figured that I need to use feed_dict and TF forces me to feed input sequence because ...
<p>Shouldn't you be feeding random numbers, but rather 0's? That's a suggestion in the karpathy lesson on rnns: <a href="https://youtu.be/cO0a0QYmFm8?list=PLlJy-eBtNFt6EuMxFYRiNRS07MCWN5UIA" rel="nofollow noreferrer">Recurrent Neural Networks, Image Captioning</a></p>
tensorflow|recurrent-neural-network
0
359,632
41,956,480
How to pass large chunk of data to celery
<p>I am using celery worker for getting results from my machine learning models. </p> <p>What I am doing is sending big numpy arrays(few megabytes) from client to celery task and back.</p> <p>Currently I am serializing in client numpy arrays as base64. When i store/get the data directly from/to Redis on client or cel...
<p>Celery uses JSON or cPickle to serialize messages. So what might be happening is you are serializing twice - first to base64 (which is inefficient) then to either JSON or cPickle.</p> <p>Have you tried skipping the base64 encoding completely and just letting Celery handle it?</p> <p>You can tell Celery to use cPic...
python|numpy|serialization|redis|celery
3
359,633
42,054,728
reshape (1000,1,17) tensor into (1000,17) tensor in numpy
<p>Im stuck with how to transform a (1000,1,17) tensor into (1000,17) tensor. What Im trying with sofar is <code>reshape</code> and transpose as I have seen in other answers but im not able to figure out how they work.</p> <p>Im trying this (actions is my original 3d tensor)</p> <pre><code>actions.transpose(2,0,1).re...
<p>If you wanted to do it through <code>reshape</code>, it'd be</p> <pre><code>actions.reshape([1000, 17]) </code></pre> <p>You just pass in the new shape. I have no idea why you were trying to use <code>transpose</code> or passing <code>3</code> and <code>-1</code> as arguments. The <a href="https://docs.scipy.org/d...
python|numpy
1
359,634
41,819,859
PIP install pandas not working
<p>I am trying to install pandas with .whl file in a work computer but I get " cannot fetch URL" error. I have up to date version of PIP installed.How can I get this to work.I'm using Python 3.5.Any help will be appreciated.</p>
<p>I just used the following which was quite simple. First open a console then cd to where you've downloaded your file like some-package.whl and use</p> <pre><code>pip install some-package.whl </code></pre> <p><code>python -m pip install some-package.whl</code> also works if pip is not found in PATH</p> <p>Note: if ...
pandas
0
359,635
42,029,044
Dataframe groupby when specific values are encountered on a given row
<p>I have a dataframe and I would like to group(or slice)it. The dataframe is in a form of</p> <pre><code>A B C a b 1 a b 0 a b 1 a b 2 a b 0 a e 3 a e 3 f g 6 f g 7 f g 0 </code></pre> <p>I would like to first group the dataframe on column A and B. Then,each group is further split by a certain ...
<p>To do so the approach is alway the same: create an extra column (or several sometimes) that represents your specific grouping logic, then group against it:</p> <pre><code>df.groupby(['A', 'B', 'cut_point']).groups Out[139]: {('a', 'b', 0.0): Int64Index([0, 1], dtype='int64'), ('a', 'b', 1.0): Int64Index([2, 3, 4]...
python|pandas|dataframe|group-by
1
359,636
41,742,571
Updating dataframe with rows of variable size in Pandas/Python
<p>I have imported an excel sheet into a dataframe in Pandas. The blank values were replaced by 'NA's. What I want to do is, for each of the row values, replace them based on indices of a dictionary or dataframe.</p> <pre><code>df1 = pd.DataFrame( {'c1':['a','a','b','b'], 'c2':['1','2','1','3'], 'c3':['2','NA','3'...
<p>One way would be <code>stack</code> + <code>replace</code> + <code>unstack</code> combo:</p> <pre><code>df1.stack().replace(df2.val).unstack() </code></pre> <p><a href="https://i.stack.imgur.com/Drf2i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Drf2i.png" alt="enter image description here"><...
python|excel|pandas
4
359,637
42,011,955
Create new dense column in Pandas Dataframe by joining together two sparse columns
<p>I have a dataframe with three columns, 'Name of Organization', 'Type' , 'Type of Org'. 'Type' and 'Type of Org' are the same thing. I want to create a new column named 'Org Type' that takes the string in the 'Type' column, and if the 'Type' column is blank, takes the name in the 'Type of Org' column. </p> <pre><cod...
<p>This feature is called <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.combine_first.html" rel="nofollow noreferrer"><code>combine_first</code></a>:</p> <pre><code>df.Type.combine_first(df['Type of Org']) Out[332]: 0 Retail 1 Service 2 Comm 3 Tech 4 Retail Name: ...
python|pandas|while-loop
3
359,638
42,123,497
Struggling with 'quiz' python class logic
<p>I have tried search but couldnt find my situation.</p> <p>I have a function that generates an algebraic equation, a question and an answer. I am attempting to figure out how to pass this to a class. Below is a small part of the code</p> <pre><code>class Question: def __init__(self,question,answer=None,equation...
<p>Here is a way for you to go at it:</p> <pre><code>class Person(object): pass def play(): print "i'm playing!" p = Person() p.play = play p.play() </code></pre>
python|python-3.x|class|numpy|sympy
0
359,639
41,826,019
Counting null as percentage
<p>Is there a fast way to automatically generate the null percentage for each columns, and output as a table?</p> <p>e.g., if a column has 40 row, with 10 null values, it will be 10/40</p> <p>I use the following code but now work (no values shown): <a href="https://i.stack.imgur.com/CETbP.png" rel="nofollow noreferre...
<p>You could use <code>df.count()</code></p> <pre><code>In [56]: df Out[56]: a b 0 1.0 NaN 1 2.0 1.0 2 NaN NaN 3 NaN NaN 4 5.0 NaN In [57]: 1 - df.count()/len(df.index) Out[57]: a 0.4 b 0.8 dtype: float64 </code></pre> <p>Timings, <code>count</code> is decently faster than <code>isnull.sum()<...
pandas
6
359,640
7,932,757
python(numpy) -- create array and how to implement an expression
<p>i have this :</p> <pre><code>npoints=10 vectorpoint=random.uniform(-1,1,[1,2]) experiment=random.uniform(-1,1,[npoints,2]) </code></pre> <p>and now i want to create an array with dimensions [1,npoints]. I can't think how to do this. For example table=[1,npoints]</p> <p>Also, i want to evaluate this:</p> <pre><...
<p>Try:</p> <pre><code>table = (experiment[:,0]**2 + experiment[:,1]**2 &lt;= 1).astype(int) </code></pre> <p>You can leave off the <code>astype(int)</code> call if you're happy with an array of booleans rather than an array of integers. As Joe Kington points out, this can be simplified to:</p> <pre><code>table = 1...
python|numpy
2
359,641
8,312,474
multiply() in numpy python
<p>It seems to me there are two versions of numpy function <code>multiply()</code>:</p> <ol> <li><code>c = multiply( a, b )</code></li> <li><code>multiply(a, b, c )</code></li> </ol> <p>My questions is two fold:</p> <ol> <li>What is the difference between the two versions?</li> <li>I need to use <code>dot()</code> f...
<ol> <li><p>The difference between the two versions of <code>multiply()</code>:</p> <pre><code>c = multilpy(a, b) </code></pre> <p>multiplies the arrays <code>a</code> and <code>b</code> element-wise, creating a <strong>new</strong> array as result. The name <code>c</code> is bound to this new array. If <code>c</co...
python|performance|numpy
6
359,642
8,317,022
Get intersecting rows across two 2D numpy arrays
<p>I want to get the intersecting (common) rows across two 2D numpy arrays. E.g., if the following arrays are passed as inputs:</p> <pre><code>array([[1, 4], [2, 5], [3, 6]]) array([[1, 4], [3, 6], [7, 8]]) </code></pre> <p>the output should be:</p> <pre><code>array([[1, 4], [3, 6...
<p>For short arrays, using sets is probably the clearest and most readable way to do it.</p> <p>Another way is to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.intersect1d.html" rel="noreferrer"><code>numpy.intersect1d</code></a>. You'll have to trick it into treating the rows as a single val...
numpy|python
48
359,643
37,890,389
Most efficient way to fill missing elements of dataframe with a function of column and row indices
<p>I have a dataframe with missing values.</p> <pre><code>import pandas as pd import numpy as np np.random.seed([3,1415]) df = pd.DataFrame(np.random.choice((0, np.nan), (5, 5))) print df 0 1 2 3 4 0 0.0 NaN 0.0 NaN 0.0 1 0.0 NaN 0.0 NaN NaN 2 NaN NaN 0.0 NaN NaN 3 0.0 NaN 0.0 0.0...
<p>Both <code>arraymap</code> in <code>pir1</code> and the double for-loop in <code>pir2</code> call <code>f</code> once for each pair of index and column values. If <code>f</code> can be vectorized -- i.e. defined so as to accept NumPy arrays as input instead of scalars, then for large inputs the calculation can be s...
python|performance|pandas|numpy
2
359,644
37,859,014
Python Pandas : Convert multiple rows into single row, ignoring NaN's
<p>I have a <code>DataFrame</code> similar to the one mentioned below,</p> <pre><code> Age Sex Name .... 12 NaN NaN NaN Male NaN NaN NaN David </code></pre> <p>I want to convert it into a dataframe with one row, ignoring the NaN's and merging them</p> <pre><code> Age Sex Name 12 ...
<p>You can use <code>pd.concat</code> to combine all <code>columns</code> after <code>.dropna()</code> and <code>.reset_index()</code> like so:</p> <pre><code>pd.concat([df[col].dropna().reset_index(drop=True) for col in df], axis=1) </code></pre> <p>to get:</p> <pre><code> Age Sex Name 0 12.0 Male David <...
python|python-2.7|pandas|dataframe
5
359,645
38,049,357
New row based on other's row past value to current value
<p>I'm trying to create a new column called <code>move</code> in <code>df</code> that gives the value of <code>1</code> if the value in <code>x is higher</code> than its previous value and a <code>0</code> if the <code>value is lower</code>, so the first value in <code>move</code> should be a <code>NaN</code>.</p> <pr...
<p>You can compare using <code>shift</code> with a slice of the column using <code>iloc</code> and cast the boolean series to numeric dtype using <code>astype</code>:</p> <pre><code>In [82]: df['move'] = (df['x'].iloc[1:] &gt; df['x'].iloc[1:].shift()).astype(int) df Out[82]: x move 0 1 NaN 1 0 0.0 2 2 1...
python|pandas|dataframe|conditional-statements|shift
2
359,646
37,661,063
Variable initialization in the variable_scope in the Tensorflow
<p>I've been trying to understand how variables are initialized in Tensorflow. Below, I created a simple example which defines a variable in some <code>variable_scope</code> and the process is wrapped in the subfunction.</p> <p>In my understanding, this code creates a variable <code>'x'</code> inside the <code>'test_s...
<p>If you want to reuse a variable, you have to declare it using <code>get_variables</code> and than explicitly ask to the scope to make the variables reusable.</p> <p>If you change the line</p> <pre><code> x = tf.Variable(0.0, name='x', trainable=False) </code></pre> <p>with:</p> <pre><code>x = tf.get_variable('x'...
tensorflow
0
359,647
37,980,543
Writing piece-wise functions in TensorFlow / if then in TensorFlow
<p>How do I write a piece-wise TensorFlow function i.e. a function that has an if-statement inside it?</p> <p>Current code</p> <pre><code>import tensorflow as tf my_fn = lambda x : x ** 2 if x &gt; 0 else x + 5 with tf.Session() as sess: x = tf.Variable(tf.random_normal([100, 1])) output = tf.map_fn(my_fn, x) </...
<p><code>tf.select</code> is no more working as indicated by this thread as well <a href="https://github.com/tensorflow/tensorflow/issues/8647" rel="noreferrer">https://github.com/tensorflow/tensorflow/issues/8647</a></p> <p>Something that worked for me was <code>tf.where</code></p> <pre><code>condition = tf.greater(...
python|tensorflow
7
359,648
37,819,341
Need for m.initial_state.eval() in TensorFlow PTB tutorial
<p>In the PTB language model tutorial at <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/rnn/ptb/ptb_word_lm.py" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/rnn/ptb/ptb_word_lm.py</a>. I don't understand the need for line 248 (and the passing of ...
<p>Okay, I figured it out. The RNN is called multiple times, and each time it is called you want it to start with a clean initial state. If you were to just call it once, you wouldn't need to pass in a clean initial state to <code>sess.run()</code>.</p>
python|tensorflow
2
359,649
37,821,903
Adding new rows to dataframe subsets using Pandas
<p>I have the following dataframe:</p> <pre><code>Customer ProductID Count John 1 25 John 6 50 Mary 2 15 Mary 3 35 </code></pre> <p>I want my output to look like this:</p> <pre><code>Customer ProductID Count John 1 25 John 2 0 John 3 ...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>pivot</code></a> - you get <code>NaN</code> values which are <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>fillna</c...
python|pandas|dataframe
1
359,650
37,752,146
Pandas Multiindex Nested Sort and Percent
<p>Given this data frame and pivot table:</p> <pre><code>import pandas as pd df=pd.DataFrame({'County':['A','A','A','A','A','B','B','B','B','A','A','A','A','A','B','B','B','B'], 'Hospital':['a','b','c','d','e','a','b','c','e','a','b','c','d','e','a','b','c','e'], 'Enrollment':[44,55,42,...
<p>You could:</p> <pre><code>df = pd.concat([df, df.groupby(level='County').apply(lambda x: x['2013'].div(x['2013'].sum())).reset_index(0, drop=True).to_frame('Percent')], axis=1) top_3 = df.groupby(level='County')['Percent'].nlargest(3).reset_index(0, drop=True) df = pd.concat([df.drop('Percent', axis=1), top_3], axi...
python|sorting|pandas|pivot-table|percentage
1
359,651
37,955,036
What data types can you give as keys to feed in TensorFlow?
<p>Consider computing an inner product in tensor flow for the sake of an example. I was trying to experiment on the different ways to refer to things in graphs in TensorFlow when one evaluates it with a session using feed. Consider the following code:</p> <pre><code>import numpy as np import tensorflow as tf M = 4 D ...
<p>TensorFlow primarily expects <code>tf.Tensor</code> objects as the keys in the feed dictionary. It will also accept a string (which may be <code>bytes</code> or <code>unicode</code>) if it is equal to the <code>.name</code> property of some <code>tf.Tensor</code> in the session's graph.</p> <p>In your example, <cod...
tensorflow
1
359,652
37,997,668
Pandas number rows within group in increasing order
<p>Given the following data frame:</p> <pre><code>import pandas as pd import numpy as np df=pd.DataFrame({'A':['A','A','A','B','B','B'], 'B':['a','a','b','a','a','a'], }) df A B 0 A a 1 A a 2 A b 3 B a 4 B a 5 B a </code></pre> <p>I'd like to create co...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="noreferrer"><code>groupby/cumcount</code></a>:</p> <pre><code>In [25]: df['C'] = df.groupby(['A','B']).cumcount()+1; df Out[25]: A B C 0 A a 1 1 A a 2 2 A b 1 3 B a 1 4 B a 2 5 B ...
python|python-3.x|pandas|pandas-groupby|rank
145
359,653
37,641,494
Is there a difference in the way we access elements of a list comprehension and the elements of a numpy array
<p>I am working on a genetic algorithm code. I am fairly new to python. My code snippet is as follows:</p> <pre><code> import numpy as np pop_size = 10 # Population size noi = 2 # Number of Iterations M = 2 # Number of Phases in the Data alpha = [np.random.randint(0, 64...
<p>There some questionable programming in these 2 lines</p> <pre><code> alpha = [np.random.randint(0, 64, size = pop_size)]* M ... alpha_en = [(2*np.pi*alpha/63.00) for alpha in alpha] </code></pre> <p>The first makes an array, and then makes a list with <code>M</code> pointers to the same thing. Note, M ...
python|numpy|matrix|list-comprehension
2
359,654
37,713,484
Write object array to .txt file
<p>When I do</p> <pre><code>k=12 rsf = np.zeros((int(k), 9), dtype='object') for i in range(0, int(k)): rsf[i, 0] = "FREQ" for j in range(1, 9): rsf[i, j] = sampled[8*i+j-1, 0] </code></pre> <p>and then try to write it by</p> <pre><code>np.savetxt('test.txt', rsf, delimiter=',') </code></pre> <p>I...
<p>More of the error message:</p> <pre><code>-&gt; 1162 % (str(X.dtype), format)) 1163 if len(footer) &gt; 0: 1164 footer = footer.replace('\n', '\n' + comments) TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e,%.18e,%.18e,%....
python|numpy
14
359,655
37,846,357
Why Does this DataFrame Modification within Function Change Global Outside Function?
<p>Why does the function below change the global <code>DataFrame</code> named <code>df</code>? Shouldn't it just change a local <code>df</code> within the function, but not the global <code>df</code>?</p> <pre><code>import pandas as pd df = pd.DataFrame() def adding_var_inside_function(df): df['value'] = 0 prin...
<p>from <a href="http://pandas.pydata.org/pandas-docs/stable/overview.html#mutability-and-copying-of-data" rel="noreferrer">docs</a>:</p> <blockquote> <p><strong>Mutability and copying of data</strong></p> <p>All pandas data structures are value-mutable (the values they contain can be altered) but not always ...
python|pandas|global|local
9
359,656
37,940,518
pandas interchangeable dual indexing?
<p>I have a DataFrame and I build a dual index. 'start' values don't exist in 'end' index values and versa.</p> <pre><code>c_weights.rename(columns={0:'start',1:'end',2:'metric',3:'angular',4:'special',5:'cos_pi'}, inplace=True) c_weights.set_index(['start','end'],inplace=True) c_weights.head() </code></pre> <p><img ...
<p>Anyways, for the first case, you can just index using <code>ix</code> and passing a tuple on the row index</p> <pre><code>c_weights.ix[(1,638)] </code></pre> <p>For the second case, I guess it'll depend whether you know off hand or not if you're trying to pass the end first, in which case I'd just construct a tupl...
python|pandas|dataframe
0
359,657
38,034,585
Retaining longest consecutive occurrence that does not equal a specific value
<p>I have a df like so:</p> <pre><code>Value 0 1 3 -999 4 5 6 2 7 8 9 -999 3 2 -999 1 </code></pre> <p>and I want to retain the most consecutive values in the dataframe that are NOT <code>-999</code></p> <p>which for this example would give me this:</p> <pre><code>Value 4 5 6 2 7 8 9 </code></pre> <p>I have multip...
<p>You can do a <code>cumsum()</code> on the condition series which gives a unique groupId for each consecutive sequence from one <code>-999</code> to another. Then find the maximum length of the groupId and filter on that should give the desired output:</p> <pre><code>df['groupId'] = (df['Value'] == -999).cumsum() df...
python|pandas
1
359,658
37,661,751
Mat in C++ to Numpy
<p>I have three C++ matrices called <code>myMatrix</code>, <code>myMatrix2</code> and <code>canvas</code> respectively using OpenCV. I'm pretty new to C++, so it's unclear to me what Range::all() does. I understand the second Range statement, and I'm wondering if <code>Range::all()</code> is equivalent to <code>Range(0...
<p>If I did understand properly, the numpy equivalent can be written as:</p> <pre><code>canvas = np.copy(myMatrix[:, :myMatrix2.shape[1]]) </code></pre> <p>Assuming that both <code>myMatrix</code> and <code>myMatrix2</code> exist. If <code>canvas</code> also exists in python beforehand, you can update it inplace (rat...
python|c++|numpy
3
359,659
37,891,008
Difference between a view and assignment
<p>I can understand the difference between an assignment, shallow and deep copy. But I am still unclear what is the difference between a view(<code>c=a</code>) and an assignment(<code>c=a.view()</code>). Both reflect changes and seem the same. Please give <strong>examples</strong> if possible.</p> <p>I am referring to...
<p>A array object in NumPy is a ndarray struct with a <code>data</code> pointer that point to the raw values in the array.</p> <ul> <li><code>b = a</code>: Just give the array another name.</li> <li><code>c = a.view()</code>: Create a view of array <code>a</code> means create a new ndarray struct that point to the sam...
python|numpy|dictionary|scipy
4
359,660
31,675,214
Using mpi4py (or any python module) without installing
<p>I have some parallel code I have written using <code>numpy</code> and <code>mpi4py</code> modules. Till now I was running it on my laptop but now I want to attack bigger problem sizes by using the computing clusters at my university. The trouble is that they don't have mpi4py installed. Is there anyway to use the m...
<p>Did you try <code>pip install --user mpi4py</code>?</p> <p>However, I think the best solution would be to just talk to the people in charge of the cluster and see if they will install it. It seems pretty useless to have a cluster without mpi4py installed.</p>
python|python-2.7|numpy|mpi4py
1
359,661
31,528,375
"Trailing" One-Hot Encode
<p>I am trying to do something similar to One-Hot-Encoding but instead of the selected class being 1 and the rest zero, I want all the classes up to (and including the selected class) to be 1. Say I have a training batch with labels (5 possible class labels; 0, 1, 2, 3, 4)</p> <pre><code>y = np.array([0,2,1,3,4,1]) <...
<p>You could achieve this by using a lower-triangular matrix instead of an identity matrix in your function definition:</p> <pre><code>def many_hot_encode(arr, num_classes): return np.tril(np.ones(num_classes))[arr] many_hot_encode(y,5) array([[ 1., 0., 0., 0., 0.], [ 1., 1., 1., 0., 0.], [ ...
python|numpy
2
359,662
31,389,481
Numpy: Replace random elements in an array
<p>I already googled a bit and didn't find any good answers.</p> <p>The thing is, I have a 2d numpy array and I'd like to replace some of its values at random positions.</p> <p>I found some answers using numpy.random.choice to create a mask for the array. Unfortunately this does not create a view on the original array ...
<p>Just mask your input array with a random one of the same shape.</p> <pre><code>import numpy as np # input array x = np.array([[ 1., 2., 3.], [ 4., 5., 6.], [ 7., 8., 9.]]) # random boolean mask for which values will be changed mask = np.random.randint(0,2,size=x.shape).astype(np.bool) # random matrix the same sh...
python|numpy|random
18
359,663
31,365,669
Set RGB white to transparent?
<p>I have an image I load into python using <code>matplotlib.pyplot.imread</code> which ends up as an <code>numpy</code> array containing an array of rgb values. Here is a dummy snippet with all but two pixel white:</p> <pre><code>&gt;&gt;&gt; test array([[[255, 255, 255], [255, 255, 255]], [[ 1, 255...
<p>One option would be to construct a <a href="http://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html" rel="noreferrer">masked array</a> and then <code>imshow</code> it:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt x = np.array([[[255, 255, 255], [255, 255, 255]], ...
python|numpy|matplotlib|mask|imshow
6
359,664
31,388,637
python pandas- adding values of a column above the row you're on
<p>I have a dataframe that looks like this (but longer):</p> <pre><code>OnsetTime OffsetTime OnSec OffSec RTsec TrialDur 36163 38165 36.163 38.165 0.000 2.002 39157 41152 39.157 41.152 0.605 1.995 42152 44155 42.152 44.155 0.509 2.003 ...
<p>You can use <code>cumsum</code> to compute the cumulative sum (add 0.001 before that), then <code>shift</code> that column by 1, finally set the first row to be 0.</p> <pre><code>df['NewVar'] = (df.TrialDur + 0.001).cumsum() df.loc[df.index[-1]+1, 'NewVar'] = 0 df['NewVar'] = df.NewVar.shift(1) df.loc[0, 'NewVar'] ...
python|pandas
2
359,665
31,440,488
Replace row with another row in 3D numpy array
<p>I am trying to replace a specific row of NaN's in a 3-D array (filled with NaN's) with rows of known integer values from a specific column in a text file (ex: 24 rows of column 8). Is there a method to perform this replacement that I have missed in my search for help?</p> <p>My most recent trial code (of many) is a...
<p>The error message tells you pretty much everything you need to know: the array slice on the left-hand side of the assignment has a shape of <code>(24,1,1)</code>, whereas the right-hand side has shape <code>(24,)</code>. Since these shapes don't match, numpy raises a <code>ValueError</code>.</p> <p>There are two wa...
python|arrays|numpy
0
359,666
31,299,542
How to add to arrays such that matching elements become their own arrays
<p>I feel like there is quick way to do this with Numpy but I can't seem to find the function for it.</p> <p>I need to take three arrays:</p> <pre><code>a = [1,2,3] b = [1,2,3] c = [1,2,3] Z = np.somefunction(a,b,c) print Z ([1,1,1],[2,2,2],[3,3,3]) </code></pre>
<p>If the input arrays are all 1-d, you can use <code>np.column_stack</code>:</p> <pre><code>In [13]: np.column_stack((a,b,c)) Out[13]: array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) </code></pre>
python|arrays|numpy
1
359,667
31,226,102
Pandas.rolling_correlation, threshold?
<p>I am using Pandas.rolling_corr to calculate correlation of two Pandas series. </p> <pre><code>pd.rolling_corr(x, y, 10) </code></pre> <p>x and y have very little variation. For instance </p> <pre><code>x[0] = 1.3342323 x[1] = 1.3342317 </code></pre> <p>Since correlation is covariance divided by standard deviatio...
<p>I think this can more generally be considered as a question about precision rather than correlation. And generally, you can expect things behind the scenes to be done at double precision which means that it's around 13 or 14 decimal places that things can get wonky (though certainly at 11 or 12 decimal places (or l...
python|pandas
0
359,668
31,269,216
Applying uppercase to a column in pandas dataframe
<p>I'm having trouble applying upper case to a column in my DataFrame.</p> <p>dataframe is <code>df</code>.</p> <p><code>1/2 ID</code> is the column head that need to apply UPPERCASE.</p> <p>The problem is that the values are made up of three letters and three numbers. For example <code>rrr123</code> is one of the v...
<p>If your version of pandas is a recent version then you can just use the vectorised string method <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.upper.html#pandas.Series.str.upper" rel="noreferrer"><code>upper</code></a>:</p> <pre><code>df['1/2 ID'] = df['1/2 ID'].str.upper() </code...
python|pandas
112
359,669
31,575,675
How to convert Numpy Array to Python Dictionary with Sequential Keys?
<p>I have a matrix in the form of a numpy array like this :</p> <pre><code>myarray = np.array[[0,400,405,411,415,417,418,0] [0,404,412,419,423,422,422,0] [0,409,416,421,424,425,425,0] [0,411,414,417,420,423,426,0] [0,409,410,410,413,419,424,0]...
<p>Use <code>flatten</code> and then create the dictionary with the help of <code>enumerate</code> starting from 1:</p> <pre><code>myarray = np.array([[0,400,405,411,415,417,418,0], [0,404,412,419,423,422,422,0], [0,409,416,421,424,425,425,0], [0,411,414,417,420...
python|arrays|numpy|dictionary
18
359,670
31,268,998
How to merge two large numpy arrays if slicing doesn't resolve memory error?
<p>I have two numpy arrays <code>container1</code> and <code>container2</code> where <code>container1.shape = (900,4000)</code> and <code>container2.shape = (5000,4000)</code>. Merging them using <code>vstack</code> results in a <code>MemoryError</code>. After searching through the old questions posted here, I tried to...
<p>Every time you call <code>np.vstack</code> NumPy has to allocate space for a brand new array. So if we say 1 row requires 1 unit of memory</p> <pre><code>np.vstack([container, container2]) </code></pre> <p>requires <em>an additional</em> <code>900+5000</code> units of memory. Moreover, before the assignment occur...
python|numpy|data-analysis
9
359,671
31,483,326
Ordering 3 1d numpy array to obtain a 2d numpy array
<p>I have 3 numpy array containing <code>x, y</code> and <code>f(x,y) values</code>. They are ordered one with respect to the others but completely disordered in itself. Let's say, for sake of simplicity, that `f=x+y they are </p> <pre><code>x | y | f 1 | 2 | 3 5 | 1 | 6 .... </code></pre> <p>And let's suppose that I...
<p>Take a look a the concatenate function.</p> <pre><code>a = np.array([[x1, y1, f1]]) b = np.array([[x2, y2, f2]]) np.concatenate((a, b), axis=0) </code></pre> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/nu...
python|arrays|numpy|datagrid
0
359,672
31,620,667
Why is `pandas.read_csv` not the reciprocal of `pandas.DataFrame.to_csv`?
<p>It seems strange to me that <code>pandas.read_csv</code> is not a direct reciprocal function to <code>df.to_csv</code>. In this illustration, notice how when using all the default settings the original and final DataFrames differ by the "Unnamed" column.</p> <pre><code>In [1]: import pandas as pd In [2]: orig_df ...
<p>Thanks for the tip to post to the <a href="https://github.com/pydata/pandas/issues/10670" rel="noreferrer">github</a> page @EdChum. This led me to the <code>pandas.DataFrame.from_csv</code> function which is indeed the reciprocal of <code>pandas.DataFrame.to_csv</code>. </p> <pre><code>In [6]: final_df = pd.DataF...
python|pandas|dataframe
5
359,673
31,539,815
Plotting two distributions in seaborn.jointplot
<p>I have two <code>pandas</code> dataframes I would like to plot in the same seaborn <a href="http://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.jointplot.html" rel="noreferrer">jointplot</a>. It looks something like this (commands are don in an IPython shell; <code>ipython --pylab</code>):</p> <pre><cod...
<p>Here is one way to do it by modifying the underlying data of <code>sns.JointGrid</code>.</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # simulate some artificial data # ======================================== np.random.seed(0) data1 = np.random.multiva...
python|pandas|matplotlib|seaborn
28
359,674
64,616,193
Skip weights of one epoch in Tensorflow Keras
<p>In my machine learning task I have the problem, that in some rare cases (epochs) the optimiser sees a bad training set and the weights and biases get completely messed up after that epoch, so I would like to discard this epoch.</p> <p>I wrote a small callback function like in this <a href="https://keras.io/guides/wr...
<p>I built a callback doing exactly what you wish to do, In addition it adjust the learning as well. First it adjusts the learning rate by monitoring training accuracy. Once the training accuracy reaches a threshold level, say .95 then the callback adjust the learning rate based on validation loss. Validation data when...
python|tensorflow|keras
1
359,675
64,444,524
Row-wise concat with sample 2 dataframes
<p>I've got 2 dataframes,</p> <pre><code>df1 col1 col2 col3 0 ABC XYZ123 RA100 1 DEF YHG753 RA200 2 ABC XYZ123 RA100 3 DEF YHG753 RA200 4 ABC XYZ123 RA100 5 DEF YHG753 RA200 df2 col5 col6 0 TU1 DUM1 1 TU2 DUM2 2 TU3 DUM3 </code></pre> <p>I'm ...
<p>First idea is create helper column with random assign index value of <code>df2.index</code> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>DataFrame.join</code></a>:</p> <pre><code>#for test np.random.seed(2002) df = (df1.a...
pandas|python-2.7|dataframe
3
359,676
64,589,684
In pandas, how to operate on the row with the first instance of a string?
<p>I have a csv file, and I'm trying to convert a column with cumulative values to individual values. I can form most of the column with</p> <pre><code>df['delta'] = df['expenditure'].diff() </code></pre> <p>So for each person (A,B..) I want the change in expenditure since they last attended. What which gives me</p> <p...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.diff.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.diff</code></a> with replace first missing values by original by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fil...
python|python-3.x|pandas
1
359,677
64,305,438
Warning: The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset
<p>This occurred while I was using <code>tf.data.Dataset</code>:</p> <blockquote> <p>The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline sim...
<p>I tried to run your code on <code>Google colab</code>, it ran successfully without giving any warning, I'm using <code>Tensorflow 2.3</code>.</p> <p>However, you can follow this general method while using <code>cache</code>.</p> <p>If the dataset is small enough to fit in memory, you can significantly speed up train...
python|tensorflow|tensorflow-datasets
1
359,678
64,248,656
How to go through a txt file where rows do not have the same number of values
<p>I recently started to use Python and now I have a problem similar to the following. I have a txt file where rows do not have the same number of values:</p> <pre><code> who you gonna call 555 2368 56 20 9 7 8 0 9 7 -789 -9 -19 -14 0 9 0 0 -1 0 9 0 -4.0 -4.1 -4.2 -4.3 -4.4 -5.0 -5.1 -5.2 -5.3...
<p>Since you know when the blocks start and the blocks are separated by empty lines, you can just loop through the file and append each line to a list. When the empty line is found, append the line list to the main block list.</p> <p>Try this code:</p> <pre><code>ss = ''' who you gonna call 555 2368 56 20 9 7 8 0 9 7 -...
python|numpy|loops|iteration|txt
1
359,679
64,531,669
Vectorized method to fill dataframe column from indices from another Multiindexed dataframe?
<p>Say I have a multiindexed dataframe <code>df1</code>:</p> <pre class="lang-py prettyprint-override"><code> x y i0 i1 aaa a 1 6 b 2 5 c 3 4 bbb x 4 3 y 5 2 z 6 1 </code></pre> <p>with a second dataframe <code>df2</code>:</p> <pre class="lang-py prettyprint-overr...
<p>You can use convert your <em>MultiIndex</em> to dataframe using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.to_frame.html" rel="nofollow noreferrer"><strong><code>pd.MultiIndex.to_frame</code></strong></a>, then gropuby and use <a href="https://pandas.pydata.org/pandas-docs/...
python|pandas|dataframe|multi-index
2
359,680
64,519,911
do I have to add softmax in def forward when I use torch.nn.CrossEntropyLoss
<p><a href="https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html" rel="nofollow noreferrer">https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html</a></p> <p>When I read the contents above, I understood that torch.nn.CrossEntropy already computes exp score of the last layer. So I t...
<p>JHPark,</p> <p>You are correct - with <code>torch.nn.CrossEntropyLoss</code> there is no need to include <code>softmax</code> layer. If one does include <code>softmax</code> it will still lead to proper classification result, since softmax does not change which element has max score. However, if applied twice, it m...
python|pytorch|softmax
1
359,681
64,371,688
Generate labels for each line in plot generated by DataFrameGroupBy objects
<p>So far, with the help of you all from SO, I have managed to create a DataFrame from a CSV file, grouped it from column A-Q (they are distinctive only together), and managed to get a graph with each group comprising one line on the graph with following code:</p> <pre><code>fig, ax = plt.subplots(figsize=(15, 12)) for...
<p>The name of the group is in <code>element</code> and it'll be given as a tuple. This tuple contains the multi-level grouping you made of columns A-Q. Assuming Column C is the third column, you should be able to access the value in Column C using <code>label=element[2]</code>.</p> <p>Or, more generally, you can do:</...
python|pandas|matplotlib|graph
0
359,682
64,281,352
Replace Multiple columns at once with fillna()
<p>I have this dataFrame with two column of Null values</p> <pre><code>import numpy as np import pandas as pd ddd = pd.DataFrame({'a' : [1,2,3],'b' : [np.nan,np.nan,np.nan],'c' : [np.nan,np.nan,np.nan] }) </code></pre> <p>I want to replace column b and c with column a values. I am doing this</p> <pre><code>ddd[['b','c'...
<p>This will iterate on all the column BUT the first one:</p> <pre><code>for column in df.columns[1:]: ddd[column]= ddd['a'] </code></pre>
python|pandas
1
359,683
64,426,328
Pandas group by time of day from Datetime multi-index level
<p>I have a dataframe with a multi-index that contains a level named <code>datetime</code> which is a <code>DatetimeIndex</code>. I want to group my data by the time of day. Is it idiomatic to do so via</p> <pre><code>df.groupby(df.index.get_level_values('datetime').time).something() </code></pre> <p>? I'm asking becau...
<blockquote> <p>Is it idiomatic to do so via</p> </blockquote> <pre><code>df.groupby(df.index.get_level_values('datetime').time).median() </code></pre> <blockquote> <p>?</p> </blockquote> <p>I think yes, if want attribute of <code>MultiIndex</code> level, like here <a href="http://pandas.pydata.org/pandas-docs/stable/r...
python|pandas|pandas-groupby|multi-index
1
359,684
64,185,768
How to aggregate sum, and convert unique row values to column names, in pandas?
<p>I have issue with pandas <code>pd.groupby()</code> function. I have DataFrame</p> <pre><code>data = [{'Shop': 'Venga', 'Item Name': 'Oranges', 'Measure':'Supply Cost', 'Value': '10'}, {'Shop': 'Venga', 'Item Name': 'Oranges', 'Measure':'Product Cost', 'Value': '20'}, {'Shop': 'Venga', 'Item Name': 'A...
<ul> <li>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>.groupby</code></a> and then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html#pandas.DataFrame.unstack" rel="nofollow noreferre...
python|pandas|pandas-groupby
1
359,685
64,548,697
How to slice rows between first and last row in pandas dataframe?
<p>How can I use <code>loc</code> to slice everything between first and last row of following pandas <code>DataFrame</code>?</p> <p><strong>Input:</strong></p> <pre><code> id text 0 A 1 B 2 C 3 D </code></pre> <p><strong>Output:</strong></p> <pre><code>| id | text | |----|------| | 1 | ...
<h3>Selecting rows</h3> <p>Use</p> <pre><code>df.iloc[1:-1] # similar to df.iloc[1:3] id text 1 1 B 2 2 C </code></pre> <p>To slice all rows by position between 0 and -1 (exclusive).</p> <hr /> <h3>Assigning to an existing column</h3> <p>Since <code>iloc</code> expects positional values, if you need to ...
python|pandas
2
359,686
64,553,426
How to label satellite images for Image segmentation?
<p>I want to detect Land mines in satellite Images. Initially I built a model with each image having multiple labels and trained it to classify the images.</p> <p>However I want to use Image Segmentation technique as mentioned here : <a href="https://towardsdatascience.com/dstl-satellite-imagery-contest-on-kaggle-2f3ef...
<p>You can use AWS Ground Truth to create a job that can label the images you require. AWS also has released which might help <a href="https://aws.amazon.com/about-aws/whats-new/2019/12/amazon-sagemaker-ground-truth-adds-auto-segment-feature-for-semantic-segmentation-labeling/" rel="nofollow noreferrer">https://aws.ama...
tensorflow|label|data-annotations|image-segmentation|satellite-image
0
359,687
64,258,113
Renaming the columns in pd.DataFrame based on the adjacent column name
<p>My csv file looks like below image.</p> <p>So I want to rename the column <strong>X</strong> using the adjacent column <strong>slice-0010-EDSR_x2</strong>. So the new column X name should be <strong>slice-0010-EDSR_x2_X</strong> And this column slice-0010-EDSR_x2 name should be <strong>slice-0010-EDSR_x2_Y</strong> ...
<p>If I have sample data like this:</p> <pre><code>df = pd.DataFrame( { 'Contour': range(5), 'X': range(5, 10), 'slice-0010-EDSR_x2': range(10, 15), 'X_': range(5, 10), 'slice-0011-EDSR_x2': range(10, 15), } ) </code></pre> <p>then I can achieve your goal with the...
python|pandas|dataframe|multiple-columns|rename
2
359,688
64,228,441
Row to column transformation in pandas
<p>I have a dataframe as below</p> <pre><code>+----+------+------+-----+-----+ | id | year | sell | buy | own | +----+------+------+-----+-----+ | 1 | 2016 | 9 | 2 | 10 | | 1 | 2017 | 9 | 0 | 10 | | 1 | 2018 | 0 | 2 | 10 | | 2 | 2016 | 7 | 2 | 11 | | 2 | 2017 | 2 | 0 | 0 | | 2 | 201...
<p>You can use <code>df.dot</code> with <code>df.pivot</code> here:</p> <pre><code>u = df[['sell','buy','own']] (df.assign(v=u.ne(0).dot(u.columns.str[0].str.upper()+'_').str[:-1]) .pivot(&quot;id&quot;,&quot;year&quot;,&quot;v&quot;)) </code></pre> <hr /> <pre><code>year 2016 2017 2018 id 1 S_...
python|pandas
7
359,689
64,245,691
Pandas, import multiple csv into one data frame with multiple columns
<p>I have 12 csv files which I wanted to import into a data frame in column wise.</p> <p>For instance, the each 12 csv files are named differently as follows:</p> <pre><code>filenames = ['experiment_timesteps_1.csv', 'experiment_timesteps_2.csv', 'experiment_timesteps_3.csv', 'exp...
<p>If I understood correctly, you can do it as follows:</p> <pre><code>results = DataFrame() for name in filenames: aux = read_csv(name) results[name[11:-4]] = aux[&quot;results&quot;] </code></pre> <p>This will generate a column for each file with the unique identifier you want and the &quot;results&quot; colu...
python|pandas|csv|import
1
359,690
64,190,609
How to save and use a Tensorflow dataset using the Experimental save and load mehods?
<p>I wrote two python files create_save.py and load_use.py as shown below. create_save.py is running good and saving tf dataset.</p> <p>But load_use.py is giving errors shown below. How to fix load_use.py errors please?</p> <p>create_save.py</p> <pre><code>import os import numpy as np import pandas as pd import tensorf...
<p>To load a previously saved dataset, you need to specify <strong>element_spec</strong> argument -- a type signature of the elements of the saved dataset, which can be obtained via tf.data.Dataset.element_spec. This requirement exists so that shape inference of the loaded dataset does not need to perform I/O.</p> <pre...
python|tensorflow|tensorflow-datasets
1
359,691
64,603,563
Numpy get reverse index order
<p>I have a numpy array, and I permute it with known order, how can I get the reverse order such that I can recover the input from the output?</p> <pre><code>In [1]: import numpy as np In [2]: a = np.arange(9) ...
<p>Maybe <a href="https://numpy.org/doc/stable/reference/generated/numpy.argsort.html" rel="nofollow noreferrer"><code>np.argsort(order)</code></a> should do the trick.</p>
numpy|indexing|permutation
2
359,692
64,498,035
Playing a movie in OpenCV
<p>I get the following error while trying to show a movie:</p> <pre><code>cv2.imshow(&quot;Video Output&quot;, frames) TypeError: Expected Ptr&lt;cv::UMat&gt; for argument 'mat' </code></pre> <p>The commented-out lines are my attempts to fix the problem, but I still get the error. What am i doing wrong?</p> <pre><code>...
<p>In your code, <code>vid.read()</code> returns two values. The first contains a boolean value, which, according to the <a href="https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html#capture-video-from-camera" rel="nofollow noreferrer">documentation</a>:</p>...
python-3.x|numpy|opencv
2
359,693
64,477,093
Customising model in AWS sagemaker
<p>I have a python script which I wrote using tensorflow python 3.6 AWS sagemaker jupyter notebook inside AWS sagemaker instance. I have to use sagemaker debugger for my Deep Learning model. I can see many links suggesting that first dockerise the algorithm image and then use it over sagemaker. Can anyone please sugges...
<p>You don't have to dockerize your code yourself, you can use an existing SageMaker TensorFlow image, and with the SageMaker Python SDK you can let SageMaker manipulate docker images for you - no docker knowledge needed ! <a href="https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/using_tf.html" rel="nof...
python-3.x|docker|amazon-sagemaker|keras-2|tensorflow1.15
0
359,694
64,463,816
pandas dataframe split and get last element of list
<p>I have a pandas dataframe and in one column I have a string where words are separated by '_', I would like to extract the last element of this string (which is a number) and make a new column with this. I tried the following</p> <pre><code>df = pd.DataFrame({'strings':['some_string_25','a_different_one_13','and_a_la...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="noreferrer"><code>Series.str.split</code></a> for split and select last value of list by indexing or use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html" rel="no...
python|pandas|list|split|element
7
359,695
64,315,154
2D numpy array - extracting rows using for loops
<p>I have a 2D Numpy array. I want to count how many occurrences of the value 1 occur in the second column of the array. I then want to put each row which has value 1 in the second column into another array. This is what I have so far:</p> <pre><code>import numpy as np a=np.array([[0, 1, 2, 3], [1, 1, 2, 3], [4, 0, 1,...
<p>You mean to do something like this?</p> <pre class="lang-py prettyprint-override"><code>result = [] for row in a: if row[1] == 1: result.append(row) result = np.array(result) result </code></pre> <p>or as a one-liner,</p> <pre class="lang-py prettyprint-override"><code>result = np.array([row for row in a...
python|arrays|numpy|for-loop
0
359,696
64,221,771
Efficiently fill an array from a function
<p>I want to construct a 2D array from a function in such a way that I can utilize <code>jax.jit</code>.</p> <p>The way I would normally do this using <code>numpy</code> is to create an empty array, and then fill that array in-place.</p> <pre><code>xx = jnp.empty((num_a, num_b)) yy = jnp.empty((num_a, num_b)) zz = jnp....
<p>JAX has a <a href="https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap" rel="nofollow noreferrer"><code>vmap</code> transform</a> that is designed specifically for this kind of application.</p> <p>As long as your <code>get_coords</code> function is compatible with JAX (i.e. is a pure function with no si...
python|numpy|jax
1
359,697
64,269,975
Converting values of the index of a multi-index dataframe to columns
<p>I have a multi-index dataframe (with indices <code>Date</code> and <code>Company</code>) <code>df</code> below:</p> <pre><code> Amount Date Company 2019-10-01 BoA 3.924454e+09 Starfirst 1.346442e+04 Republic 7....
<p>Use <code>unstack</code> to unstack the inner most index level.</p> <pre><code>df['Amount'].unstack() </code></pre> <p>Output:</p> <pre><code>Company BoA Republic Starfirst Date 2019-10-01 3.924454e+09 7006446.0 13464.42 2019-11-01 2.176354e+09 3545446....
python|pandas
1
359,698
64,482,576
How to merge two different dataframes content on the condition of two columns in a row matches
<p>I have a dataframe1 that contains 1064 records and dataframe2 that contains 328 records in it. I want to merge dataframe2 into dataframe1. the dataframe the rest of the records that doesnt have corresponding data in the second df should get filled in with the text &quot;NA&quot;. for example</p> <p>DF1</p> <pre><cod...
<p>Try this:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({ 'Name': ['Name1', 'Name2', 'Name3', 'Name3'], 'Area': ['Area1', 'Area2', 'Area2', 'Are...
python|pandas|dataframe|merge
1
359,699
64,510,871
Random number generator from a given distribution function
<p>I am completely new in programming. I have density function which have two range. How can i get random function according to this function. The probability density function for the last return time is:</p> <pre><code> (1/sqrt(2*pi*std**2))*exp(-(x+24-µ2)**2/2*std**2) , 0 &lt; x ≤ µ2 − 12 f(x) = (1/sq...
<p>You can create your own distribution using <code>scipy.stats.rv_continuous</code> as the base class. This class has fast default implementations of CDF, random number generator, SF, ISF, ect given the PDF of the distribution. You can implement your own distribution using something like:</p> <pre class="lang-py prett...
python|numpy|scipy|statistics
1