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
376,700
46,880,589
Reading image files into Tensorflow with tf.WholeFileReader()
<p>I'm trying to read a directory of images files into tensorflow and I'm having a little trouble. When I run the script, the shell is just hanging (even waited 10 mins for an output) and the only output I get is the from the <code>print(len(os.listdir())</code> line</p> <p>My attempts stem from this guide:</p> <p><a...
<p><code>tf.train.string_input_producer</code> adds a <code>QueueRunner</code> to the current Graph and you need to manually start it. Otherwise it is just hanging and no output is produced.</p> <pre><code>with tf.Session() as sess: coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord)...
python-3.x|file-io|tensorflow
1
376,701
46,757,220
Can anyone explain this list comprehension?
<pre><code>def unpack_dict(matrix, map_index_to_word): table = sorted(map_index_to_word, key=map_index_to_word.get) data = matrix.data indices = matrix.indices indptr = matrix.indptr num_doc = matrix.shape[0] return [{k:v for k,v in zip([table[word_id] for word_id in indic...
<pre><code>[{k: v for k, v in zip([table[word_id] for word_id in indices[indptr[i]:indptr[i + 1]]],data[indptr[i]:indptr[i + 1]].tolist())} for i in range(num_doc)] </code></pre> <p>is same as :</p> <pre><code>final_list = [] for i in range(num_doc): new_list = [] for word_id in indices[indptr[i]:indptr[i + 1...
python|numpy|machine-learning
3
376,702
46,728,376
Selecting columns by column NAME dtype
<pre><code>import pandas as pd import numpy as np cols = ['string',pd.Timestamp('2017-10-13'), 'anotherstring', pd.Timestamp('2017-10-14')] pd.DataFrame(np.random.rand(5,4), columns=cols) </code></pre> <p>How can I get back just the 2nd and 4th column (which have dtype 'date time.datetime')? The types of the column co...
<p>Use <code>type</code> with <code>map</code>:</p> <pre><code>df = df.loc[:, df.columns.map(type) == pd.Timestamp] print (df) 2017-10-13 00:00:00 2017-10-14 00:00:00 0 0.894932 0.502015 1 0.080334 0.155712 2 0.600152 0.206344 3 0....
python|pandas
2
376,703
46,911,725
Find duplicates for one column with the last row group by one column in Pandas Python
<p>I have 4 columns in my dataframe <code>user</code> <code>abcisse</code> <code>ordonnee</code>,<code>time</code></p> <p>I want to find for each user the duplicate row with the last row of the user, duplicate row meaning two row with same abcisse and ordonnee.</p> <p>I was thinking to use the df.duplicated function ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer"><code>drop_duplicates</code></a>:</p> <pre><code>print (entry.drop_duplicates(['user', 'abcisse', 'ordonnee'], keep='last')) user abcisse ordonnee temps 0 1 0 ...
python|pandas|dataframe
0
376,704
46,885,454
How to create a DataFrame with the word2ve vectors as data, and the terms as row labels?
<p>I tried to follow this documentation: nbviewer.jupyter.org/github/skipgram/modern-nlp-in-python/blob/master/executable/Modern_NLP_in_Python.ipynb Where I have the following code snippet:</p> <pre><code>ordered_vocab = [(term, voc.index, voc.count) for term, voc in food2vec.vocab.iteritems()] ordered_v...
<p>Use the following code:</p> <pre><code>ordered_vocab = [(term, voc.index, voc.count) for term, voc in model.wv.vocab.items()] ordered_vocab = sorted(ordered_vocab, key=lambda k: k[2]) ordered_terms, term_indices, term_counts = zip(*ordered_vocab) word_vectors = pd.DataFrame(model.wv.syn0[term_indices, :], index=ord...
python-3.x|pandas|word2vec|gensim
3
376,705
47,024,584
Pandas: reading from multiple files with different variable ordering
<p>I have many files that I'd like to read into a single pandas data frame. An example file might look like this:</p> <pre><code>variable_1_name variable_2_name ... variable_n_name 0.0 0.5 0.3 ... 0.8 ... 1.0 4.5 6.5 ... 1.0 </code></pre> <p>So, the file has a list of variable names (one per line) at the top ...
<p>Extending <a href="https://stackoverflow.com/users/8802367/pal">Pal</a>'s answer: the best way is to read data out of csv files. So why not converting the files to csv files (or even better, csv file-like objects living in memory) and let <code>pandas</code> do the dirty work?</p> <pre><code>try: import io # p...
python|pandas
2
376,706
46,966,865
Is there any way to load data in parallel when gpu is computing?
<p>I am using keras with tensorflow for deep learning. I work with slightly large dataset (images), so I couldn't load the whole dataset at once, instead, I load on batches of 8000 images, and use model.fit() for training (code snippet below). </p> <pre><code>for epochs in range(50): # number of epochs for i in ra...
<p>Yes, you can do this by using <code>fit_generator</code> instead of <code>fit</code> and passing the arguments <code>use_multiprocessing=True</code> and <code>workers=n</code> (where n is the number of worker threads). For loading your dataset, you will need to make a generator method that yields each batch. It shou...
python|tensorflow|deep-learning|keras|conv-neural-network
2
376,707
46,667,790
Distributed tensorflow of Between-graph replication?
<p>Look at the code I wrote:</p> <pre><code>import tensorflow as tf tf.flags.DEFINE_string('job_name', 'ps', 'worker or ps') tf.flags.DEFINE_integer('task_index', 0, 'task id') FLAGS = tf.flags.FLAGS host = '127.0.0.1:' cluster = {"ps": [host+'2222'], "worker": [host+'2223', host+'2224']} clusterspec = ...
<p>This is the intended behavior. Up to this point in your code, you only have created a graph, which does not need/care jobs to be up and running.</p> <p>You will encounter the problem after creating a Session (or any variation of Session).</p> <p>More information here: <a href="https://www.tensorflow.org/extend/arc...
python|tensorflow|distributed-computing|grpc
0
376,708
46,830,776
tensorflow - is this equivalent to mse?
<p>I am very new to TensorFlow, I notice that <a href="https://www.tensorflow.org/api_docs/python/tf/losses/mean_squared_error" rel="nofollow noreferrer">here</a> there is <code>tf.losses.mean_squared_error</code> which implements the mean squared error loss function.</p> <p>Before using it, I played around with TF an...
<p>It is because you sum before taking the mean, so you get the squared error and not its mean. Change <code>tf.reduce_mean(tf.reduce_sum(tf.square(tf.subtract(y, y_))))</code> to <code>tf.reduce_mean((tf.square(tf.subtract(y, y_)))</code></p> <pre class="lang-python prettyprint-override"><code>import tensorflow as ...
machine-learning|tensorflow|neural-network
2
376,709
47,059,124
In pandas crosstab, how to calculate weighted averages? And how to add row and column totals?
<p>I have a pandas dataframe with two categorical variables (in my example, city and colour), a column with percentages, and one with weights. I want to do a crosstab of city and colour, showing, for each combination of the two, the weighted average of perc.</p> <p>I have managed to do it with the code below, where I ...
<p>Here using a groupby with apply() and using the numpy weighted average method.</p> <pre><code>df.groupby(['colour','city']).apply(lambda x: np.average(x.perc, weights=x.weight)).unstack(level=0) </code></pre> <p>which gives</p> <pre><code>colour red yellow city LA 0.173870 0.8...
python|pandas|crosstab|categorical-data
3
376,710
46,647,050
Merging selected columns from multiple pandas dataframe by comparing the values
<p>I have <strong>df1</strong> as follows:</p> <pre><code>id 1 2 3 4 5 6 7 </code></pre> <p>I have <strong>df2</strong> as:</p> <pre><code>id1 name1 val1 1 abbb1 10 2 abbb2 20 3 abbb3 30 4 abbb4 40 7 abbb7 70 </code></pre> <p>I have <strong>df3</strong> as:</p> <pre><code>id2 name2 val2 1 abbb1 9...
<p>I think here is better use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a>.</p> <p>Also is necessary unique values of <code>id1</code> and <code>id2</code> in <code>df2</code> and <code>df3</code>.</p> <pre><code>df1['val1'] = df...
python|pandas|dataframe
1
376,711
46,638,618
python pandas dataframe find row containing specific value and return boolean
<p>I want compare two dataframes which is df1 and df2. df1 is a data that updates every hour by it self. df2 is a dataframe that alreay exists. I want to append specific row that is updated.</p> <p>for example, Here is df1</p> <p>df1:</p> <p><img src="https://i.stack.imgur.com/vfJ4o.png" alt="fd1"></p> <p>which con...
<p>To fix your code ...</p> <pre><code>l=[] for index, row in df1.iterrows(): id = row['Id'] if sum(df2['Id'].isin([id]))&gt;0: l.append(id) l Out[334]: [0, 1, 2, 3, 4] # those are the row you need to remove df1.loc[~df1.index.isin(l)]# you remove them by using `~` + .isin Out[339]: Id Name 5 ...
python|pandas
2
376,712
47,016,833
How to manually select which x-axis label(Dates) gets plotted in pandas
<p>First of all I am sorry if I am not describing the problem correctly but the example should make my issue clear.</p> <p>I have this dataframe and I need to plot it sorted by date, but I have lots of date (around 60), therefore pandas automatically chooses which date to plot(label) in x-axis and the dates are random...
<p><strong>NOTE: Updated to answer OP question more directly.</strong></p> <p>You are mixing Pandas plotting as well as the <code>matplotlib</code> <a href="http://matplotlib.org/api/pyplot_summary.html#id11" rel="nofollow noreferrer">PyPlot API</a> and <a href="http://matplotlib.org/api/pyplot_summary.html#the-object...
python|pandas|datetime|matplotlib|plot
1
376,713
46,861,171
Filter arrays in Numpy
<p>I have an array: <code>[[True], [False], [True]]</code>. If I would want this array to filter my existing array, e.g <code>[[1,2],[3,4],[5,6]]</code> should get filtered to <code>[[1,2],[5,6]]</code>, what is the correct way to do this?</p> <p>A simple <code>a[b]</code> indexing gives the error: <code>boolean index...
<p>The solution is to get the array <code>[[True], [False], [True]]</code> into shape <code>[True, False, True]</code>, so that it works for indexing the rows of the other array. As Divakar said, <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ravel.html#numpy.ravel" rel="nofollow noreferrer...
python|arrays|numpy
1
376,714
47,047,140
Pandas: slice one multiindex dataframe with multiindex of another when some levels don't match
<p>I have two multiindexed dataframes, one with two levels and one with three. The first two levels match in both dataframes. I would like to find all values from the first dataframe where the first two index levels match in the second dataframe. The second data frame does not have a third level. </p> <p>The closest a...
<p>You can use <code>reset_index()</code> and <code>merge()</code>.</p> <p>With <code>df_2_selection</code> as:</p> <pre><code> 0 1 2 3 foo two -0.530151 0.932007 -1.255259 2.441294 qux one 2.006270 1.087412 -0.840916 -1.225508 </code></pre> <p>Merge with:</p> <pre><code>l...
python|pandas|indexing|slice|multi-index
1
376,715
46,902,237
Tensorflow - saving the checkpoint files as .pb, but with no output node names
<p>I have the following files:</p> <pre><code>model.ckpt-2400.data-00000-of-00001 model.ckpt-2400.index model.ckpt-2400.meta </code></pre> <p>And I would like to save them in the form of a <code>.pb</code> with the following function:</p> <pre><code>def freeze_graph(model_dir, output_node_names): """Extract the ...
<p>Turns out all I needed to do is to supply the name of the output node... that I, in another part of my code, designated as the node to log to check the results.</p> <pre><code>predictions = { # Generate predictions (for PREDICT and EVAL mode) "classes": tf.argmax(input=logits, axis=1), # Add `soft...
tensorflow
0
376,716
46,866,513
How do I get values from a text file and put them into a dataframe in python?
<p>I have a text file and want to get its values and want to put them in a dataframe in python. I know I have to use read_csv but not sure how to do it. </p> <p>The text file looks something like this:</p> <p>duration,protocol_type,service,flag,src_bytes,dst_bytes,land,wrong_fragment,urgent,hot,num_failed_logins,logg...
<p>Try this. Path to file is wherever your file is located, the relative path. </p> <pre><code>import pandas as pd data = pd.read_csv('path_to_file.csv', sep=',') </code></pre>
python|pandas
0
376,717
46,882,307
AttributeError: module 'tensorflow' has no attribute 'feature_column'
<p>So I am new to machine learning and was trying out the TensorFlow Linear Model Tutorial given here: <a href="https://www.tensorflow.org/tutorials/wide" rel="noreferrer">https://www.tensorflow.org/tutorials/wide</a></p> <p>I literally just downloaded their tutorial and tried to run it in my computer but I got the er...
<p>Tensorflow 1.3 should support feature_column well. You might accidentally used an old version. Try the following code to verify your version:</p> <pre><code>import tensorflow as tf print(tf.__version__) print(dir(tf.feature_column)) </code></pre>
python|machine-learning|tensorflow
3
376,718
32,958,399
Transpose DataFrame in Pandas while preserving Index column
<p>The problem is, when I transpose the DataFrame, the header of the transposed DataFrame becomes the Index numerical values and not the values in the "id" column. See below original data for examples:</p> <p><strong>Original data that I wanted to transpose (but keep the 0,1,2,... Index intact and change "id" to "id2"...
<p>If I understand your example, what seems to happen to you is that you <code>transpose</code> takes your actual index (the 0...n sequence as column headers. First, if you then want to preserve the numerical index, you can store that as <code>id2</code>.</p> <pre><code>DF['id2'] = DF.index </code></pre> <p>Now if yo...
pandas|indexing|dataframe|transpose
7
376,719
32,652,718
Pandas: Find rows which don't exist in another DataFrame by multiple columns
<p>same as this <a href="https://stackoverflow.com/questions/32651860/python-pandas-how-to-find-rows-in-one-dataframe-but-not-in-another">python pandas: how to find rows in one dataframe but not in another?</a> but with multiple columns</p> <p>This is the setup:</p> <pre><code>import pandas as pd df = pd.DataFrame(d...
<p>Since <code>0.17.0</code> there is a new <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#other-enhancements"><code>indicator</code></a> param you can pass to <code>merge</code> which will tell you whether the rows are only present in left, right or both:</p> <pre><code>In [5]: merged = df.merge(o...
python|join|pandas
46
376,720
32,967,201
how to concat sets when using groupby in pandas dataframe?
<p>This is my dataframe:</p> <pre><code>&gt; df a b 0 1 set([2, 3]) 1 2 set([2, 3]) 2 3 set([4, 5, 6]) 3 1 set([1, 34, 3, 2]) </code></pre> <p>Now when I <code>groupby</code>, I want to update sets. If it was a <code>list</code> there was no problem. But th...
<p>This might be close to what you want</p> <pre><code>df.groupby('a').apply(lambda x: set.union(*x.b)) </code></pre> <p>In this case it takes the union of the sets.</p> <p>If you need to keep the column names you could use:</p> <pre><code>df.groupby('a').agg({'b':lambda x: set.union(*x)}).reset_index('a') </code><...
python|pandas
10
376,721
33,029,514
How to scale MNIST from 28*28 to 29*29 in Python
<p>I was trying to apply deformation to MNIST dataset. The very first step of doing elastic distortion is to scale each image from 28*28 to 29*29 in order to simplify Gaussian convolution. </p> <p>But almost every publications mentioned this procedure ended up with saying "scale it from 28*28 to 29*29". And nothing mo...
<p>You have multiple choices for image resizing.</p> <pre><code>import numpy as np img28 = np.eye(28) from skimage.transform import resize img29r = resize(img, (29, 29)) from scipy.misc import imresize img29i = imresize(img, (29, 29)) </code></pre> <p>It's a matter of taste and specifics of your application which you...
python|numpy|image-processing
1
376,722
32,718,639
Pandas - filling NaNs in Categorical data
<p>I am trying to fill missing values (NAN) using the below code</p> <pre><code>NAN_SUBSTITUTION_VALUE = 1 g = g.fillna(NAN_SUBSTITUTION_VALUE) </code></pre> <p>but I am getting the following error </p> <pre><code>ValueError: fill value must be in categories. </code></pre> <p>Would anybody please throw some light o...
<p>Your question is missing the important point what <code>g</code> is, especially that it has dtype <code>categorical</code>. I assume it is something like this:</p> <pre><code>g = pd.Series(["A", "B", "C", np.nan], dtype="category") </code></pre> <p>The problem you are experiencing is that <code>fillna</code> req...
python|pandas
67
376,723
32,722,843
Transform an array of shape (n,) to a numpy array of shape (n,1)
<p>I have an array that I read from a <code>.npz</code> file with numpy, that has a shape I can not really explain.</p> <p>When I print the array I get numbers in the following form:</p> <pre><code>[1 2 3 2 1 8 9 8 3 4 ...] </code></pre> <p>without any comma separating them</p> <p>I would like to transform this arr...
<p>The shape <code>(n, )</code> means its a one-dimensional array of <code>n</code> length . If you think the shape <code>(n, 1)</code> represents a one-dimensional array, then it does not, <code>(n,1)</code> represents a two dimensional array of n sub-arrays, with each sub-array having 1 element.</p> <p>If what you r...
python|arrays|numpy
6
376,724
32,764,899
Convert pandas multiindex into simple flat index of column names
<p>I have a pandas data frame like this:</p> <pre><code>columns = pd.MultiIndex.from_tuples([ ('A', 'cat', 'long'), ('A', 'cat', 'long2'), ('A', 'dog', 'short'), ('B', 'dog', 'short') ], names=['exp', 'animal', 'hair_length'] ) df = pd.DataFrame(np.random.randn(4, 4), columns=columns, index=['W...
<p>In case anybody else comes across this - this indeed seems to do the trick:</p> <pre><code>df.columns = [ '_'.join(x) for x in df.columns ] </code></pre> <p>Result:</p> <pre><code> A_cat_long A_cat_long2 A_dog_short B_dog_short W -0.968703 0.086291 -0.255741 1.487564 X 2.113484 -0.118909 ...
python|pandas
5
376,725
32,998,842
efficient way of constructing a matrix of pair-wise distances between many vectors?
<p>First, thanks for reading and taking the time to respond.</p> <p>Second, the question:</p> <p>I have a PxN matrix X where P is in the order of 10^6 and N is in the order of 10^3. So, X is relatively large and is not sparse. Let's say each row of X is an N-dimensional sample. I want to construct a PxP matrix of p...
<p>You can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html#scipy.spatial.distance.pdist" rel="nofollow"><code>pdist</code></a> and <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.squareform.html#scipy.spatial.distance.squareform" rel...
python|numpy|scipy|memory-efficient|scalable
2
376,726
32,726,701
Convert real-valued numpy array to binary array by sign
<p>I am looking for a fast way to compute the following:</p> <pre><code>import numpy as np a = np.array([-1,1,2,-4,5.5,-0.1,0]) </code></pre> <p>Now I want to cast <code>a</code> to an array of binary values such that it has a 1 for every positive entry of <code>a</code> and a 0 otherwise. So the result I want is thi...
<p>You can check where <code>a</code> is greater than 0 and cast the boolean array to an integer array:</p> <pre><code>&gt;&gt;&gt; (a &gt; 0).astype(int) array([0, 1, 1, 0, 1, 0, 0]) </code></pre> <p>This should be significantly faster than the method proposed in the question (especially over larger arrays) because ...
python|arrays|numpy|casting
3
376,727
32,977,911
Combine daily data into monthly data in Excel using Python
<p>I am trying to figure out how I can combine daily dates into specific months and summing the data for the each day that falls within the specific month.</p> <p>Note: I have a huge list with daily dates but I put a small sample here to simply the example.</p> <p>File name: (test.xlsx)</p> <p>For an Example (sheet...
<p>This will work if 'DATE' is a column of strings and not your index.</p> <p>Example dataframe - shortened for clarity:</p> <pre><code>df = pd.DataFrame({'DATE': {0: '20110706', 1:'20110707', 2: '20110801'}, 52: {0: 28.52, 1: 28.97, 2: 28.52}, 55: { 0: 24.52, 1: 24.97, 2:24.52 ...
python|excel|date|pandas
2
376,728
32,868,177
Flattening shallow list with pandas
<p>I am trying to flatten the content of a column of a <code>pandas.DataFrame</code> which contains list of list however I cannot find a proper way to get a correct output.</p> <p>Instead of a <a href="https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">different question</a> asked in Stack...
<p>Just change the join to :</p> <pre><code>join = lambda list_of_lists: (val for sublist in list_of_lists for val in sublist if isinstance(sublist, list)) </code></pre> <p>Here is the output :</p> <pre><code>In[69]: df_grouped['merged'] = df_grouped['recipe'].apply(lambda x: list(join(x))) In[70]: df_grouped['merge...
python|python-3.x|pandas|flatten
1
376,729
32,926,116
What is the most canonical way to install Numpy, Scipy, Pandas?
<p>I need to install Numpy, Scipy, Pandas, and sklearn. I downloaded Numpy and Scipy individually from their websites, but Scipy warns not to install manually, and when I try to install Numpy I get an error 'could not locate executable g77'. Scipy recommends using Anaconda. I have downloaded Anaconda, but cannot see ho...
<p>There is a lot of scientific distribution very well done today.For exemple, <a href="http://www.pyzo.org" rel="nofollow">pyzo</a> is a very nice and modern plug and play system for you. </p>
python|numpy
0
376,730
33,055,718
Splitting data in Pandas/Python
<p>I'm new to Python and Pandas so bear with me.</p> <p>I have a big data that looks like:</p> <pre><code>1 E 1 NaN 2 T 2004-09-21 01:15:53 NaN 3 U 30 NaN 4 N 32 NaN 5 ...
<p>You can use <code>groupby</code> here, using the compare-cumsum-groupby pattern (here let's say that the column with the Es is called "letter"):</p> <pre><code>&gt;&gt;&gt; grouped = df.groupby((df["letter"] == "E").cumsum()) &gt;&gt;&gt; frames = [g for k,g in grouped] &gt;&gt;&gt; for frame in frames: ... pri...
python|pandas|split
1
376,731
32,633,944
pandas extrapolation of polynomial
<p>Interpolating is easy in pandas using <code>df.interpolate()</code> is there a method in pandas that with the same elegance do something like extrapolate. I know my extrapolation is fitted to a second degree polynom.</p>
<p>"With the same elegance" is a somewhat tall order but this can be done. As far as I'm aware you'll need to compute the extrapolated values manually. Note it is very unlikely these values will be very meaningful unless the data you are operating on actually obey a law of the form of the interpolant.</p> <p>For examp...
python|numpy|pandas
2
376,732
32,999,650
Python pandas map dict keys to values
<p>I have a csv for input, whose row values I'd like to join into a new field. This new field is a constructed url, which will then be processed by the requests.post() method.</p> <p>I am constructing my url correctly, but my issue is with the data object that should be passed to requests. How can I have the correct v...
<p>Not sure if I understand the problem correctly. However, you can give argument to <code>to_dict</code> function e.g.</p> <pre><code>data = test_df.to_dict(orient='records') </code></pre> <p>which will give you output as follows: <code>[{'FIRST_NAME': ..., 'LAST_NAME': ...}, {'FIRST_NAME': ..., 'LAST_NAME': ...}]</...
python|dictionary|pandas
0
376,733
32,896,097
Error in Python while doing text preprocessing
<p>I have written a couple of functions to work on text documents and convert them into bag of words. Before that I am cleaning the text by removing the stop words, tokenization etc and storing the cleaned text docs as a list which I intend to pass as an argument to another function which would create bag of words feat...
<p>So there are two main ideas here: <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">Boolean indexing</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/basics.html#function-application" rel="nofollow">function application</a></p> <p>Boolean indexing allows...
python|pandas|nltk
0
376,734
38,515,782
scipy.signal's convolve differs from calculated result
<p>I'd like to discuss a little bit on convolution as applied to CNNs and image filtering... If you have an RGB image (dimensions of say <code>3xIxI</code>) and <code>K</code> filters, each of size <code>3xFxF</code>, then you would end up with a <code>Kx(I - F + 1)x(I - F + 1)</code> output, assuming your stride is <c...
<p>You wrote:</p> <blockquote> <p>... the same as this:</p> </blockquote> <pre><code>I -&gt; 3x5x5 matrix F -&gt; 3x2x2 matrix (I[0] * F[0]) + (I[1] * F[1]) + (I[2] * F[2]) -&gt; 1x4x4 matrix </code></pre> <p>You have forgotten that convolution <em>reverses</em> one of the arguments. So the above is not true. In...
python|numpy|scipy|convolution
4
376,735
38,576,969
Pct_change in python with missing data
<p>I have quarterly time series data that I am calculating derivatives for. The problem is, the raw data has gaps in the time series. Therefore, if I am trying to find the quarter-over-quarter percent change in a variable, there are times when it will not realize it's calculating a percent change for a period much long...
<p>I'm going to put <code>['calendardate', 'ticker']</code> in the index to facilitate pivoting. Then <code>unstack</code> to get ticker values in the columns.</p> <pre><code>df.set_index(['calendardate', 'ticker']).unstack().head(10) </code></pre> <p><a href="https://i.stack.imgur.com/2jMrS.png" rel="nofollow noref...
python|numpy|pandas
1
376,736
38,854,582
how to convert a (possibly negative) Pandas TimeDelta in minutes (float)?
<p>I have a dataframe like this</p> <pre><code>df[['timestamp_utc','minute_ts','delta']].head() Out[47]: timestamp_utc minute_ts delta 0 2015-05-21 14:06:33.414 2015-05-21 12:06:00 -1 days +21:59:26.586000 1 2015-05-21 14:06:33.414 2015-05-21 12:07:00 -1 days +22:00:26.586000 ...
<p>You can use:</p> <pre><code>df['a'] = df['delta'] / np.timedelta64(1, 'm') print (df) timestamp_utc minute_ts delta \ 0 2015-05-21 14:06:33.414 2015-05-21 12:06:00 -1 days +21:59:26.586000 1 2015-05-21 14:06:33.414 2015-05-21 12:07:00 -1 days +22:00:26.586000 2 2015-0...
python|datetime|pandas
8
376,737
38,594,625
How to feature-ize timeseries data in Pandas?
<p>I have data that are structured as below:</p> <pre><code>Group, ID, Time, Feat1, Feat2, Feat3 A, 1, 0, 1.52, 2.94, 3.1 A, 1, 2, 1.67, 2.99, 3.3 A, 1, 4, 1.9, 3.34, 5.6 </code></pre> <p>In this data, there are individuals who have been measured repeatedly.</p> <p>I'd like to restructure the data such that each fea...
<pre><code>df = pd.DataFrame({'Group': {0: 'A', 1: 'A', 2: 'A', 3: 'A', 4: 'A', 5: 'A'}, 'Time': {0: 0, 1: 2, 2: 4, 3: 0, 4: 2, 5: 4}, 'ID': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2}, 'Feat1': {0: 1.52, 1: 1.6699999999999999, 2: 1.8999999999999999, 3: 1.52, 4: 1.66999...
python|pandas
1
376,738
38,720,745
Setting boolean values in pandas dataframe (by date) based on column header membership in other dataframe (by date)
<p>I have two pandas dataframes (X and Y) and am trying to populate a third (Z) with boolean values based on interrelationships between the axes of X and the columns/constituents of Y. I could only manage to do this via nested loops and the code works on my toy example but is too slow for my actual data set.</p> <pre...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> method, where values of DataFrame are converted to columns and columns to values of DataFrames. Last test <code>NaN</code> by <a href="http://pandas.pydata.org/pandas-docs/sta...
python|pandas|boolean|intersection
1
376,739
38,901,925
Unexpected colors in multiple scatterplots in matplotlib
<p>I'm sure I'm messing up something really simple here, but can't seem to figure it out. I'm simply trying to plot groups of data as scatterplots with different colors for each group by cycling through a dataframe and repeatedly calling <code>ax.scatter</code>. A minimal example is:</p> <pre><code>import numpy as np;...
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html#scatter-plot" rel="nofollow noreferrer"><code>scatter()</code></a> method of <code>pandas</code> by specifying the target <code>ax</code>and repeating the plots to plot multiple column groups in a single axes,<code>ax</code>.</p> ...
python|pandas|matplotlib
1
376,740
38,808,643
tf.contrib.layers.embedding_column from tensor flow
<p>I am going through tensorflow tutorial <a href="https://www.tensorflow.org/versions/r0.10/tutorials/wide_and_deep/index.html#tensorflow-wide-deep-learning-tutorial" rel="noreferrer">tensorflow</a>. I would like to find description of the following line:</p> <pre><code>tf.contrib.layers.embedding_column </code></pre...
<p>I've been wondering about this too. It's not really clear to me what they're doing, but this is what I found.</p> <p>In the <a href="http://arxiv.org/pdf/1606.07792v1.pdf" rel="noreferrer">paper on wide and deep learning</a>, they describe the embedding vectors as being randomly initialized and then adjusted during...
python|tensorflow|embedding
6
376,741
38,570,198
Python pandas make new column from data in existing column and from another dataframe
<p>I have a DataFrame called 'mydata', and if I do</p> <pre><code>len(mydata.loc['2015-9-2']) </code></pre> <p>It counts the number of rows in mydata that have that date, and returns a number like</p> <pre><code>1067 </code></pre> <p>I have another DataFrame called 'yourdata' which looks something like</p> <pre><c...
<pre><code>import numpy as np import pandas as pd mydata = pd.DataFrame({'timestamp': ['2015-06-22 16:48:00']*3 + ['2015-06-23 16:48:00']*2 + ['2015-06-24 16:48:00'] + ['2015-06-25 16:48:00']*4 + ...
python|pandas|dataframe
1
376,742
38,614,659
Converting a single pandas index into a three level MultiIndex in python
<p>I have some data in a pandas dataframe which looks like this:</p> <pre><code>gene VIM time:2|treatment:TGFb|dose:0.1 -0.158406 time:2|treatment:TGFb|dose:1 0.039158 time:2|treatment:TGFb|dose:10 -0.052608 time:24|treatment:TGFb|dose:0.1 0.157153 time:24|treatment:T...
<p>You can first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html" rel="nofollow"><code>replace</code></a> unnecessary strings (index has to be converted to <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.to_series.html" rel="no...
python|pandas|indexing|multi-index
1
376,743
38,561,268
parsing data using pandas with fixed sequence of strings
<p>I have data looked like below in file a.dat:</p> <pre><code>01/Jul/2016 00:05:09 8438.2 01/Jul/2016 00:05:19 8422.4 g </code></pre> <p>I wish to parsing them into three columns: <strong>timeline, floating number, string(either None or g)</strong></p> <p>I have tried: </p> <pre><code>df=pd.read_csv('a....
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a>:</p> <pre><code>import pandas as pd import io temp=u'''01/Jul/2016 00:05:09 8438.2 01/Jul/2016 00:05:19 8422.4 g''' #after testing replace io.StringIO(temp) to filenam...
python|csv|datetime|pandas|dataframe
2
376,744
38,556,297
Standard deviation from center of mass along Numpy array axis
<p>I am trying to find a well-performing way to calculate the standard deviation from the center of mass/gravity along an axis of a Numpy array.</p> <p>In formula this is (sorry for the misalignment):</p> <p><img src="https://latex.codecogs.com/gif.latex?%5Cmu_j&space;=&space;%5Cfrac%7B%5Csum_i%7Bi&space;A_%7Bij%7D%7...
<p>You want to take the mean, variance and standard deviation of the vector <code>[1, 2, 3, ..., n]</code> &mdash; where <code>n</code> is the dimension of the input matrix <code>A</code> along the axis of interest &mdash;, with weights given by the matrix <code>A</code> itself.</p> <p>For concreteness, say you want t...
python|python-2.7|numpy|standard-deviation|weighted-average
1
376,745
38,853,916
groupby/unstack on columns name
<p>I have a dataframe with the following structure</p> <pre><code> idx value Formula_name 0 123456789 100 Frequency No4 1 123456789 150 Frequency No25 2 123456789 125 Frequency No27 3 123456789 0.2 Power Level No4 4 123456789 0.5 Power Level No25 5 123456789 ...
<p>You can use:</p> <pre><code>print (df) idx value Formula_name 0 123456789 100.0 Frequency No4 1 123456789 150.0 Frequency No25 2 123456789 125.0 Frequency No27 3 123456789 0.2 Power Level No4 4 123456789 0.5 Power Level No25 5 123456789 -1.0 Power Level No27 6 12345678...
python|pandas
3
376,746
38,582,127
How to filter data from a data frame when the number of columns are dynamic?
<p>I have a data frame like below </p> <pre><code> A_Name B_Detail Value_B Value_C Value_D ...... 0 AA X1 1.2 0.5 -1.3 ...... 1 BB Y1 0.76 -0.7 0.8 ...... 2 CC Z1 0.7 -1.3 2.5 ...... 3 DD L1 0.9 -0.5 0.4 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow"><code>filter</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.abs.html" rel="nofollow"><code>abs</code></a> and <a href="http://pandas.pydata.org/pandas-docs/...
python|numpy|pandas|dataframe
5
376,747
38,762,290
Pandas column name of the max cell value
<p>I have a df which has some codes in the leftmost column and a forward profile in the other columns (df1 below)</p> <p>df1:</p> <pre><code> code tp1 tp2 tp3 tp4 tp5 tp6 \ 0 1111 0.000000 0.000000 0.018714 0.127218 0.070055 0.084065 1 222 0.000000 0.00...
<p>Knowing that <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmax.html">idxmax</a> returns the index of the <em>first</em> maximum, you can use cumsum to find the column after which there are only zeros:</p> <pre><code>df.ix[:, 'tp1':].cumsum(axis=1).idxmax(axis=1) Out[61]: 0 ...
python|pandas|dataframe|max|cumsum
5
376,748
38,632,209
Hi, I am trying to add weekstart column
<p>In my current table I am having date column and from that column I am able to find out weekday.By using to_timedelta I have created week_start column but it is not giving correct date. Here the code is:</p> <pre><code>final_data['weekday'] = final_data['DateOfInvoice'].dt.weekday final_data['Weekstart'] = final_da...
<p>IIUC you can construct a TimedeltaIndex and subtract from the other column:</p> <pre><code>In [152]: df['weekstart'] = df['Date'] - pd.TimedeltaIndex(df['weekday'], unit='D') df Out[152]: Date weekday weekstart 0 2016-07-23 5 2016-07-18 </code></pre> <p>in fact the weekday column is unnecessary:<...
python|pandas
1
376,749
38,753,198
How can I remove rows from a numpy array that have NaN as the first element?
<p>I have a numpy array that looks like this:</p> <pre><code> [[nan 0 0 ..., 0.0 0.053526738 0.068421053] [nan 0 0 ..., 0.0 0.059653990999999996 0.068421053] [nan 0 0 ..., 1.0 0.912542592 0.068421053] ..., [1 0 0 ..., 0.0 0.126523399 0.193548387] [nan 0 0 ..., 0.0 0.034388807 0.068421053] [4 0 0 ..., 0.0 0.0225...
<p>If x is the original array, the following puts the valid rows into y:</p> <pre><code>y = x[~np.isnan(x[:, 0])] </code></pre>
python|numpy
3
376,750
38,586,640
pandas multiindex selecting...how to get the right (restricted to selection) index
<p>I am struggeling to get the right (restricted to the selection) index when using the methode <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.xs.html" rel="nofollow">xs</a> by pandas to select specific data in my dataframe. Let me demonstrate, what I am doing:</p> <pre><code>print(df)...
<p>This is a known <strong>feature</strong> not bug. pandas preserves all of the index information. You can determine which of the levels are expressed and at what location via the <code>labels</code> attribute.</p> <p>If you are looking to create an index that is fresh and just contains the information relevant to ...
python|pandas|select|multi-index
1
376,751
38,817,357
Randomly select item from list of lists gives ValueError
<p>I have a function that sometimes gives me a list of lists where the nested lists sometimes only have one item, such as this one:</p> <pre><code>a = [['1'], ['3'], ['w']] </code></pre> <p>And want to randomly select one item from that main list <code>a</code>. If I try to use <code>np.random.choice</code> on this l...
<p>I think <code>choice</code> is first turning your list into an array.</p> <p>In the second case, this array is a 1d array with dtype object:</p> <pre><code>In [125]: np.array([['1'], ['3'], ['w', 'w']]) Out[125]: array([['1'], ['3'], ['w', 'w']], dtype=object) In [126]: _.shape Out[126]: (3,) </code></pre> <p>In ...
python|python-2.7|numpy|nested-lists
3
376,752
38,876,511
Some operations on DataFrame
<p>I am working on praising a *.csv file. Therefore I try to create a class which helps me to simplify some operations on DataFrame.</p> <p>I've created two methods in order to parse a column 'z' that contains values for the 'Price' column. </p> <pre><code>def subr(self): isone = self.df.z == 1.0 if isone.any...
<p>You are passing the <code>DataFrame</code> <code>self.df</code> returned by <code>self.subr()</code> to <code>apply</code>, but actually <code>apply</code> only takes functions as parameters (<a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#flexible-apply" rel="nofollow noreferrer">see examples here...
python|pandas
0
376,753
38,668,482
Efficient way to find the shortest distance between two arrays?
<p>I am trying to find the shortest distance between two sets of arrays. The x- arrays are identical and just contain integers. Here is an example of what I am trying to do:</p> <pre><code>import numpy as np x1 = x2 = np.linspace(-1000, 1000, 2001) y1 = (lambda x, a, b: a*x + b)(x1, 2, 1) y2 = (lambda x, a, b: a*(x-2)...
<p>Your problem could also be represented as 2d collision detection, so a <a href="https://en.wikipedia.org/wiki/Quadtree" rel="nofollow">quadtree</a> might help. Insertion and querying both run in O(log n) time, so the whole search would run in O(n log n). </p> <p>One more suggestion, since sqrt is monotonic, you can...
python|arrays|numpy|runtime|ipython
1
376,754
38,655,983
Reading text file with numpy.loadtxt
<p>I am getting an error when trying to read a text file. </p> <pre><code>import numpy as np fnam = 'file.txt' test_fnames = np.loadtxt(fnam, dtype=None, delimiter=',') test_fnames </code></pre> <p>I now get this error:</p> <pre><code>ValueError: could not convert string to float: </code></pre> <p>The file conten...
<p>You could use <code>np.genfromtxt()</code> instead of <code>np.loadtxt</code>. Because the first one let handles missing values :</p> <pre><code>import numpy as np fnam = 'file.txt' test_fnames = np.genfromtxt(fnam, dtype=None, delimiter=',') </code></pre> <p>You could also try :</p> <pre><code>import numpy as n...
python|numpy|file-io
0
376,755
38,710,993
Encoding data's label for text classification
<p>I am doing a project in clinical text classification. In my corpus ,data are already labelled by code (For examples: 768.2, V13.02, V13.09, 599.0 ...). I already separated text and labels then using word-embedded for text. I am going to feed them into convolution neural network. However, the labels are needs to enco...
<p>Discrete text label is easily convertible to discrete numeric data by creating an enumeration mapping. For example, assuming the labels "Yes", "No" and "Maybe":</p> <pre><code>No -&gt; 0 Yes -&gt; 1 Maybe -&gt; 2 </code></pre> <p>And now you have numeric data, which can later be converted back (as long as the...
python|encoding|tensorflow|text-classification
1
376,756
38,918,623
Pandas: pivot table
<p>I have df:</p> <pre><code>ID,url,used_at,active_seconds,domain,search_engine,diff_time,period,code, category 08cd0141663315ce71e0121e3cd8d91f,market.yandex.ru/product/12858630?hid=91491&amp;track=fr_same,2016-03-20 23:19:49,6,yandex.ru,None,78.0,515,100.0, Search system 08cd0141663315ce71e0121e3cd8d91f,market.yande...
<p>It looks like need:</p> <pre><code>table = pd.pivot_table(df, values='domain', index=['ID'], columns=['category'], aggfunc=lambda x: x.nunique()) print (table) category Internet shop Search system \ ID ...
python|pandas|dataframe|unique|pivot-table
2
376,757
38,885,935
slice df where column looks like [(A, 3), (-A, 1), (-C, 4)] using criteria like all rows such that A>5 etc
<p>I have a dataframe that has a column that looks something like the following:</p> <pre><code>dct = {} for x in range(0,1000000): test = {'A': np.random.randint(1,5), '-A': np.random.randint(1,5), '-C': np.random.randint(1,5)} dct[str(x)+'_key'] = test df = pd.DataFrame([[d.items()] for d in dct.values()]) ...
<p>If you can split the column of tuples, this should work, just replace the conditionals with your numbers. I used these for the example data:</p> <pre><code>def f(x, var): tup_list = list(x) for t in tup_list: if t[0] == var: return t[1] return np.NaN df.columns = ['col'] for var in ['A...
python|pandas|tuples|slice
1
376,758
38,696,101
Python: How to check the number of occurrences and top (n) values in a dataframe?
<p>I want to count up the number of occurrences of countries in a dataframe, below is the sample and also find the top 2 countries by occurrence.</p> <pre><code> Date Location 0 09/17/1908 Virginia 1 07/12/1912 New Jersey 2 08/06/1913 Canada 3 09/09/1913 ...
<pre><code>countCollection = df['collection'].value_counts() </code></pre> <p><code>.value_counts()</code> will give you a count for the items from the collection named <code>collection</code> in a dataFrame.</p> <p>Also, as you mentioned you're new to Python, to get the final value:</p> <pre><code>countCollection["...
python|python-3.x|pandas
1
376,759
38,709,991
Group by hours and plot in Bokeh
<p>I am trying to get a plot like a stock data in Bokeh like in the link <a href="http://docs.bokeh.org/en/latest/docs/gallery/stocks.html" rel="nofollow noreferrer">http://docs.bokeh.org/en/latest/docs/gallery/stocks.html</a></p> <pre><code>2004-01-05,00:00:00,01:00:00,Mon,20504,792 2004-01-05,01:00:00,02:00:00,Mon,1...
<p>Sounds like this is what you need:</p> <pre><code>data.groupby('startTime')['count'].sum() </code></pre> <p>Output:</p> <pre><code>00:00:00 37766 01:00:00 35625 02:00:00 37219 03:00:00 17534 </code></pre>
python|pandas|plot|graph|bokeh
1
376,760
38,726,855
Pandas count the number of times an event has occurred in last n days by group
<p>I have table of events occurring by id. How would I count the number of times in the last n days that each event type has occurred prior to the current row?</p> <p>For example with a list of events like:</p> <pre><code>df = pd.DataFrame([{'id': 1, 'event_day': '2016-01-01', 'event_type': 'type1'}, {'id': 1, 'event...
<pre><code>res = ((((df['event_day'].values &gt;= df['event_day'].values[:, None] - pd.to_timedelta('30 days')) &amp; (df['event_day'].values &lt; df['event_day'].values[:, None])) &amp; (df['id'].values == df['id'].values[:, None])) .dot(pd.get_dummies(df['event_type']))) res Out: array([[ 0....
python|pandas
3
376,761
38,527,667
Appended object to a set is `NoneType` python 2.7
<p>I have a huge array of labels which I make unique via:</p> <pre><code>unique_train_labels = set(train_property_labels) </code></pre> <p>Which prints out as <code>set([u'A', u'B', u'C'])</code>. I want to create a new set of unique labels with a new label called "no_region", and am using:</p> <pre><code>unique_tra...
<p>As mentioned in Moses' answer, the <code>set.add</code> method mutates the original set, it does not create a new set. In Python it's conventional for methods that perform in-place mutation to return <code>None</code>; the methods of all built-in mutable types do that, and the convention is generally observed by 3rd...
python|python-2.7|numpy|random|set
5
376,762
38,923,943
Numpy array from characters in BDF file
<p>I have a file, font_file.bdf, and need to get the characters contained in it as numpy arrays where each element is one pixel.</p> <p>Here's the snippet of that file which defines the '?' character:</p> <pre><code>STARTCHAR question ENCODING 63 SWIDTH 1000 0 DWIDTH 6 0 BBX 5 7 0 0 BITMAP 70 88 08 10 20 00 20 ENDCHA...
<p>For me to get @drake-mossman's answer to work, I had to modify the first line to read the file in byte format:</p> <pre><code>fp = open(&quot;font_file.bdf&quot;, &quot;rb&quot;) </code></pre> <p>Which unfortunately means that the BdfFontFile script currently doesn't support unicode characters (or any code points pa...
python|numpy|fonts|bitmap|python-imaging-library
0
376,763
63,281,404
TFLite Interpreter fails to load quantized model on Android
<p>I have a TFLite model. The model input is a 256x192 image, it is quantized to 16 bit. It was quantized with this converter:</p> <pre class="lang-py prettyprint-override"><code>converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.target_spec.supported_types = [tf.float16] tflite_model = converter.convert() ...
<p>EDIT: Looks like you should use tf.float16 starting tf 2 <a href="https://www.tensorflow.org/lite/convert/1x_compatibility#unsupported_apis" rel="nofollow noreferrer">https://www.tensorflow.org/lite/convert/1x_compatibility#unsupported_apis</a></p> <p>May be file an issue on <a href="https://github.com/tensorflow/te...
android|android-studio|tensorflow|quantization|tensorflow-lite
0
376,764
63,142,022
Computing the loss (MSE) for every iteration and time Tensorflow
<p>I want to use Tensorboard to plot the mean squared error (y-axis) for every iteration over a given time frame (x-axis), say 5 minutes.</p> <p>However, i can only plot the MSE given every epoch and set a callback at 5 minutes. This does not however solve my problem.</p> <p>I have tried looking at the internet for som...
<p>The answer was actually quite simple.</p> <p>tf.keras.callbacks.TensorBoard has an update_freq argument allowing you to control when to write losses and metrics to tensorboard. The standard is epoch, but you can change it to batch or an integer if you want to write to tensorboard every n batches. See the documentati...
python|tensorflow|machine-learning|neural-network|tensorboard
0
376,765
62,935,077
How to fix the reshape process of train and test in CNN via Python
<p>I have a problem about fixing reshape process of train and test in <strong>CNN</strong> via Python.</p> <p>While train set has <code>(270, 660, 3)</code> , test set has <code>(163, 600, 3)</code>. Because of this, these are not the same shape.</p> <p>How can I fix it?</p> <p>Here is my block shown below.</p> <p><str...
<p>Here is my answer</p> <p>After this code plt.imshow(imgFGenuine) , I fix the issue to write down these code snippets.</p> <pre><code>imgFGenuine = cv2.resize(imgFGenuine, (270, 660)) imgFGenuine = imgFGenuine.reshape(270, 660,3) </code></pre>
python|numpy|keras
0
376,766
63,218,311
Locating minimum date based on column equal to specific value in pandas dataframe?
<p>I have a dataframe that looks something like this:</p> <pre><code> Date Account Symbol Name   Transaction type 0 2020-06-24 Vanguard Brokerage VSGAX VANGUARD SMALL CAP GROWTH INDEX ADMIRAL CL Dividend 1 2020-06-24 Vanguard Brokerage VSGAX VANGUAR...
<p>Something like this?</p> <pre><code>df.loc[df['Transaction type'] == 'Buy'].groupby('symbol')['date'].min() </code></pre> <p>The first part (before .groupby()) selects all rows where 'Transaction type' is 'Buy', then you group that dataframe by 'symbol', select column 'date' and apply the min() function to it. If yo...
python|pandas
1
376,767
63,099,290
Remove characters from string in a column
<p>I have a column which contains number of months in string and int format. Need to convert it into just integers. (eg 12)</p> <pre class="lang-py prettyprint-override"><code>df1=pd.DataFrame({'Term':[&quot;12&quot;,&quot; &quot;,&quot;12 Months&quot;,&quot;12months&quot;,&quot;12mthsb&quot;,&quot;12 *4months&quot;]})...
<p>You probably have int/float/str mix in the column</p> <p>You can try to convert to str and then replace:</p> <pre><code>df1['someColumn'].astype(str).str.replace(r'\D', '') </code></pre>
python|pandas
1
376,768
63,153,619
Model is recognizing background better than objects
<p>I created siamese model with triplet loss function. I tested it a little bit and notice that when object are small, like 2/5 of the image space, model is matching images with similar background instead of object. Some of pictures were taken on the same background what is causing the issue as I think.</p> <p>Is there...
<p>the siamese model actually deepened on encoded data simply its match between tow encoded feature representation so it not know your object of intraset you have extract object than do the matching between them</p> <p>for example if the model you built was for face matching use opencv to extract the faces and th...
python|image|tensorflow|image-processing|deep-learning
1
376,769
62,904,660
Get pandas items at selected intervals
<p>I am trying to find a faster way of selecting dates at varying intervals. Currently, I am looping through the data frame and then finding the required interval spans using <code>iloc</code>. The performance is causing a bottleneck though. The files are huge and there many of them, so any help welcome.</p> <pre><code...
<p>Maybe you can shift <code>DT</code> column by required amount:</p> <pre><code>df = pd.DataFrame(pd.date_range(start='01/01/2018', end='01/01/2020'), columns=['DT']) df['DT2'] = df['DT'].shift(-5) print(df[df['DT2'].notna()]) </code></pre> <p>Prints:</p> <pre><code> DT DT2 0 2018-01-01 2018-01-06...
python|pandas|python-2.7|dataframe
2
376,770
62,902,731
Sort the columns by unique values
<p>I have this data-frame:</p> <pre><code> AAA X_980 X_100 X_990 X_1100 X_2200 X_Y_100 X_Y_2200 X_Y_990 X_Y_1100 X_Y_980 X_10_100 X_10_980 X_10_990 X_10_1100 X_10_2200 X_A X_A_B 100 6 6 6 3 4 1 7 5 1 9 9 2 7 ...
<p><strong>Approach #1</strong></p> <p>With simple columns manipulation -</p> <pre><code>c = df.columns.values.copy() c1 = df1.columns c[np.isin(c,c1)] = c1 df_out = df.loc[:,c] </code></pre> <p>Sample output -</p> <pre><code>In [174]: df_out Out[174]: AAA X_100 X_980 X_990 X_1100 X_2200 X_Y_100 X_Y_980 X_...
python|pandas|numpy
4
376,771
63,204,487
pandas - combining datasets
<p>I have 3 datasets I am trying to combine with pandas.</p> <p>The first type dataset is like this. It has multiple index values for postcode as there are multiple restaurants in the dataframe (I am trying to give those restaurants more demographic context).</p> <pre><code> postcode restaurants 37...
<p>First, you need to ensure that postcode column is the (only) index for each of the dataframes. You need to run this for all.</p> <p>Next, if you do have all the dataframes with index as postcode. Please put them in a list called frames (list of dataframes) and use the following code.</p> <pre><code>dfList = [df1, df...
python|pandas
1
376,772
62,902,870
Python pandas vectorization comparison between 2 dataframes
<p>I have two dataframes of different lengths.</p> <p>df1</p> <pre><code> gene_name chr start stop gene 0 ARNTL chr11 13376772 13376843 gene_name 1 ARNTL chr11 13393709 13393956 gene_name 2 PPP4R1 chr18 9595015 9595151 gene_name 3 PPP4R1 chr18 9595015 9595151 gene_name 4 SL...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#database-style-dataframe-or-named-series-joining-merging" rel="nofollow noreferrer"><code>pd.merge</code></a>:</p> <pre class="lang-py prettyprint-override"><code>df = pd.merge(df1, d3, on=['chr', 'gene_name']) df = df[(df.start_x &gt;...
python|pandas
1
376,773
63,095,574
How do I save/export (as .tf or .tflite), run, or test this Tensorflow Convolutional Neural Network (CNN) which It trained as a python file?
<p>How do I save, run, or test this Tensorflow Convolutional Neural Network (CNN) which It trained as a python file?</p> <p>I want to be able to export/save this model as a <code>.tf</code> and <code>.tflite</code> file as well as input images to test it.</p> <p>Here is the code for my model:</p> <pre><code>import tens...
<p>Currently, Tensorflow 2 is much feasible to work with. So, I am posting about it and replicating your model as closely as possible.</p> <pre><code>import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers fashion_mnist = keras.datasets.fashion_mnist (train_images,...
python|tensorflow|machine-learning|deep-learning|neural-network
1
376,774
63,006,475
How to solve ImportError: Keras requires TensorFlow 2.2 or higher. Install TensorFlow via `pip install tensorflow`?
<p>I get this error when I try to import Keras into my project.</p> <blockquote> <p>How to solve ImportError: Keras requires TensorFlow 2.2 or higher. Install TensorFlow via <code>pip install tensorflow</code></p> </blockquote> <p>I verified the versions I have installed (with pip) for everything and I have:</p> <ul> <...
<p>Tensorflow requires Python 3.5–3.8 , pip and venv &gt;= 19.0</p> <p>in order to fix it:</p> <pre><code>sudo apt install python3-pip pip3 install --upgrade pip python3 -m pip install tensorflow </code></pre> <p>if you already had tensorflow installed substitute the last command this this:</p> <pre><code>pip3 instal...
python|tensorflow|keras
8
376,775
63,098,764
Element-wise multiplication of a series of two lists from separate Pandas Dataframe Series in Python
<p>I have a dataframe where there are two series, and each contains a number of lists. I would like to perform element-wise multiplication of each list in 'List A' with the corresponding list in 'List B'.</p> <pre><code>df = pd.DataFrame({'ref': ['A', 'B', 'C', 'D'], 'List A': [ [0,1,2], [2,3,4], [3...
<p>Your code is almost there. Mostly, you need to pass <code>axis=1</code> to apply:</p> <pre><code>df[&quot;new&quot;] = df.apply(lambda x: list(a*b for a,b in zip(x['List A'], x['List B'])), axis=1) print(df) </code></pre> <p>The output is:</p> <pre><code> ref List A List B new 0 A [0, 1, 2] [0...
python|pandas|list|dataframe|multiplication
3
376,776
63,079,717
How to remove ' ' from a list in python
<p>I have df column with lists. Each looks like <code>[1,2,3,4,'',6,7],[2,3,'',5,6]</code>. I want to remove the <code>''</code> in each row. I used</p> <pre><code>df[column].apply(lambda x: x.remove('')) </code></pre> <p>But it didn't work. Could some one help me? Thanks</p> <pre><code>ValueError: list.remove(x): x no...
<p>Make an explicit filter on it: <code>filter(lambda x: x != &quot;&quot;, your_list)</code> or use a list comprehension: <code>[x for x in your_list if x != &quot;&quot;]</code>. They work the same, just a matter of preference.</p> <p>You don't want to filter out by a boolean method because then you'd accidentally ge...
python|pandas|list
2
376,777
62,987,718
PDF hyperlink extraction and writing to a pandas dataframe
<p>I am using altered code from this post (my code below):</p> <p><a href="https://stackoverflow.com/questions/27744210/extract-hyperlinks-from-pdf-in-python">Extract hyperlinks from PDF in Python</a></p> <p>I am trying to extract hyperlinks (URLs) from a PDF. I found code from the link above which worked. However, I a...
<p>I figured out how to fix my own problem. This seems to happen when I post to a forum. Perhaps a forum posting is a prerequiste to discovery. Regardless...</p> <p>All code leading up to what follows is the same.</p> <p>I created a list (aptly named &quot;mylist&quot;) outside the initial forloop. I then append the cu...
python|pandas|pdf
0
376,778
63,173,294
Fastest way to iterate function over pandas dataframe
<p>I have a function which operates over lines of a csv file, adding values of different cells to dictionaries depending on whether conditions are met:</p> <pre class="lang-py prettyprint-override"><code>df = pd.concat([pd.read_csv(filename) for filename in args.csv], ignore_index = True) ID_Use_Totals = {} ID_Order_D...
<p>Probably fastest not to iterate at all:</p> <pre><code># Build some boolean indices for your various conditions idx_stock_item = df[&quot;Stock Item&quot;].isin(IDs) idx_purchases = df[&quot;Action&quot;].isin(['Order/Resupply', 'Cons. Purchase']) idx_order_dates = df[&quot;Stock Item&quot;].isin(ID_Order_Dates) #...
python|python-3.x|pandas|numpy
1
376,779
63,122,285
Is there any way to offload memory with TensorFlow?
<p>I have this method inside a class that prepares the data and trains on it inside the same method, each time the method gets called my memory usage grows around 200MB, this makes the script unable to train for long periods of time in the best cases it trains for 8-9 times before running out of memory, I tried comment...
<p>The issue here is that the model is recreated every time the function is called. Tensorflow does not release a model from memory until the session is restarted (tf &lt; 2.0) or the script itself is rerun (any tf version).</p> <p>You should create your model outside the function (preferably in the <code>__init__</cod...
python|tensorflow
1
376,780
62,915,504
How to calculate a weighted average in Python for each unique value in two columns?
<p>The picture below shows a few lines of printed lists I have in Python. I would like to get: a list of unique values of boroughs, a corresponding list of unique values of years, and a list of weighted averages of &quot;averages&quot; with &quot;nobs&quot; as weights but for each borough and each year (the variable &q...
<p>Assuming that the 'type' column doesn't affect your calculations, you can get the average using <code>groupby</code>. Here's the data:</p> <pre><code>df = pd.DataFrame({'borough': ['b1', 'b2']*6, 'year': [2008, 2009, 2010, 2011]*3, 'average': np.random.randint(low=100, high=200, size=12), 'nobs'...
python|pandas
1
376,781
63,272,148
ValueError: 4 columns passed, passed data had 3 columns when converting python list to dataframe. How to add blank values if 3 passed?
<p>I have a list called 'data' that generally has lists with 3 fields but can sometimes have 4:</p> <pre><code>[['Bob', 'DeVito', '100 Lbs'], ['Mac', 'Charles', '150 Lbs']] </code></pre> <p>If I try converting data to a dataframe with at least one of the lists having 4 elements, it will run fine:</p> <pre><code>df = pd...
<p>This should solve your problem. First it creates a dictionary from your list elements in a try/ except loop so that if there is no height value isntead of throwing an error it puts np.nan instead. Finally it creates the pandas dataframe from dictionary.</p> <pre><code>import pandas as pd import numpy as np list = [...
python|pandas|dataframe
2
376,782
63,080,193
Passing a list to pandas loc method
<p>I'd like to change the values of certain columns in a pandas dataframe. But I can't seem to do if I pass a list of columns inside <code>loc</code>.</p> <pre><code>df = pd.DataFrame({ &quot;ID&quot; : [1, 2, 3, 4, 5], &quot;QA_needed&quot; : [0, 1, 1, 0, 1], &quot;QC_needed&quot; : [1, 0, 1, 0, 0], &quot;Report_neede...
<p>Try <code>update</code></p> <pre><code>df.update(df.loc[:, [&quot;QA_needed&quot;, &quot;Report_needed&quot;]].replace({1: &quot;True&quot;, 0: &quot;False&quot;})) df Out[96]: ID QA_needed QC_needed Report_needed 0 1 False 1 True 1 2 True 0 True 2 3 True ...
python|pandas|dataframe|pandas-loc
3
376,783
62,964,298
How to select a specific TPU in Google Cloud?
<p>I'm trying to use TPUs on Google cloud and I'm trying to figure out how to specify the right TPU to use. I'm trying to following the quickstart</p> <p><a href="https://cloud.google.com/tpu/docs/quickstart" rel="nofollow noreferrer">https://cloud.google.com/tpu/docs/quickstart</a></p> <p>But it doesn't say how to se...
<p>You can select the TPU type by using the <code>tpu-size</code> parameter, as per <a href="https://cloud.google.com/tpu/docs/creating-deleting-tpus#setup_VM_only" rel="nofollow noreferrer">the documentation</a> (also <a href="https://cloud.google.com/tpu/docs/types-zones#accelerator-type" rel="nofollow noreferrer">he...
tensorflow|google-cloud-platform|google-cloud-functions|google-cloud-storage|tpu
3
376,784
63,011,947
Pandas finding average in a comma separated column
<p>I want to take average based on one column which is comma separated and take mean on other column.</p> <p>My file looks like this:</p> <pre><code>ColumnA ColumnB A, B, C 2.9 A, C 9.087 D 6.78 B, D, C 5.49 </code></pre> <p>My output should look like this:</p> <pre><code>A 7.4435 B 5.645 C 5.83 D 6.13...
<p>In your solution is created <code>index</code> by column <code>ColumnB</code> for avoid lost column values after <code>stack</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.reset_index.html" rel="nofollow noreferrer"><code>Series.reset_index</code></a>, last is added <code...
pandas|csv|average
2
376,785
63,220,901
Python Pandas Market Calendars day count (Trading day vs Calendar Days)
<p>I am conducting some market research and one of the variables I am investigating is the distribution of time for an event to occur as a log distribution and create a cumulative probability density function as a function of time. ( I simply convert my dates as so:</p> <pre><code>A=datetime.strptime(UDate1[0],date_fo...
<p>Info on the Pandas Market Calendars is here: <a href="https://pypi.org/project/pandas-market-calendars/" rel="nofollow noreferrer">https://pypi.org/project/pandas-market-calendars/</a></p> <p>First, create a market data object as described in the link:</p> <pre><code>import pandas_market_calendars as mcal # Create ...
python|pandas|datetime|timedelta
2
376,786
63,051,666
Translating strings from Pandas dataframe in batches using googletrans
<p>I am trying to translate words from a Pandas dataframe column of ca. 200000 rows in length. It looks like this:</p> <pre><code> df =| review | rating | | love it | 5 | | hate it | 1 | | its ok | 3 | | great | 4 | </code></pre> <p>I am attempting to transla...
<p>Perhaps you could try to reshape the column with words as a <code>numpy.array</code> instead, ie.:</p> <pre><code>translated = [] for row in df.review.values.reshape((-1, 50)): translated.append(translator.translate(row, src='en', dest='id')) </code></pre> <p>Note that the length of the <code>df.review</code> se...
python|pandas|loops|optimization
0
376,787
63,154,547
Iterating in Dataframe's Columns using column names as a List and then looping through the list in Python
<p>Im trying to LabelEncode particular columns of a Dataframe. I have stored those column names in a list(cat_features). Now i want to use a For loop to iterate through this list's elements (which are strings) and use those elements to access dataframe's column. but it says</p> <pre><code>TypeError: argument must be a ...
<p>The error means that one or more of your columns contains a list/tuple/set or something similar. For this, you will need to convert the list/tuple to a string before you can apply a label encoder</p> <p>Also, instead of a loop, you can first filter your data frame by the features you need then use apply function -</...
python|pandas|scikit-learn|label-encoding
0
376,788
63,290,433
Merge multiple files keeping file name as column names
<p>I have multiple files in a directory. I want to merge them in a way such that the rows are merged together, and file names are kept as column headers. For example, file1 looks like</p> <pre><code>ENSG1 12 ENSG2 13 ENSG3 14 </code></pre> <p>file2 looks like</p> <pre><code>ENSG1 13 ENSG2 14 ENSG4 ...
<p>Here's a way to do that using <code>concat</code>:</p> <pre><code>dfs = [] for f in [&quot;file1&quot;, &quot;file2&quot;]: # iterate the relevant files here df = pd.read_csv(f, header=None, sep = &quot;\s+&quot;, index_col=0) df.columns = [f] dfs.append(df) res = pd.concat(dfs, axis=1) </code></pre> <p>...
python|pandas
0
376,789
63,026,997
Series to dictionary
<p>I have the following code and output</p> <pre><code> mean = dataframe.groupby('LABEL')['RESP'].mean() minimum = dataframe.groupby('LABEL')['RESP'].min() maximum = dataframe.groupby('LABEL')['RESP'].max() std = dataframe.groupby('LABEL')['RESP'].std() df = [mean, minimum, maximum] </code></pre> <p>...
<p>I'm assuming your starting Dataframe is equivalent to one I've synthesised.</p> <ol> <li>calculate all of the aggregate values in one call to aggregate. rounded values so output fits in this answer</li> <li><code>reset_index()</code> on aggregate then <code>to_dict()</code></li> <li>list comprehension to reformat <c...
python-3.x|pandas|dataframe|dictionary|data-science
1
376,790
63,042,278
Why am I getting a syntax error on this code from the tensorflow website?
<p>I am learning tensorflow using the tensorflow website, and I directly copied the code from their website to test for myself. However, for some reason, I am unable to run the code, due to a syntax error. What is wrong with this if I hadn't tweaked any of this code?</p> <pre><code>classifier = tf.estimator.DNNClassifi...
<p>You have to put a closing parenthesis after <code>n_classes=3</code> on line 45.</p>
python|tensorflow|syntax-error
1
376,791
63,095,680
Adding new column to dataframe depending of other column value
<p>I have a dataframe that has two columns: DNI, Email.</p> <p>And I have another one that has: first name, last name, num</p> <p>This is the data structure:</p> <p>dataframe 1:</p> <pre><code> DNI email . 1 Name1.lastname1@domain.com . 525 Name2.lastname2@domain.com . 665 Name3.lastname3@domain.com </code><...
<p>You can follow these steps :</p> <ol> <li><p>Create a new column &quot;email&quot; in dataframe2 by concatenating first_name, last_name and &quot;domain.com&quot; .</p> <blockquote> <p><code>dataframe2[&quot;email&quot;] = dataframe2[&quot;first_name&quot;]+&quot;.&quot;+dataframe2[&quot;last_name&quot;]+ &quot;@dom...
python|pandas|dataframe
1
376,792
63,074,347
I have installed GDAL library but am having troubles importing and using it. What should I do?
<p>When importing the GDAL package in python, it's raising the following error:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import gdal Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;/home/akki/anaconda3/envs/py36/lib/python3.6/site-pack...
<p>you can try</p> <p><code>from osgeo import gdal</code></p>
python-3.6|geospatial|gdal|geopandas
0
376,793
62,941,625
Problem with output of neural network in a cross-entropy method attempt at solving CartPole-v0
<p>I am trying to implement the cross-entropy policy-based method to the classic CartPole-v0 environment. I am actually reformatting a working implementation of this algorithm on the MountainCarContinuous-v0, but when I try to get the agent learning, I get this error message:</p> <pre><code>----------------------------...
<p>Turns out all I needed was to add an act() method to the Agent class.</p> <pre><code>def act(self, state): state = state.unsqueeze(0) probs = self.forward(state).cpu() m = Categorical(probs) action = m.sample() return action.item() </code></pre>
python|deep-learning|pytorch|reinforcement-learning
0
376,794
62,958,651
OpenCV warpPerspective and findHomography created output on both sides of image frame
<p>I've been trying to figure out how to get a birds-eye view of a scene by using a homography and then warping the image. The image that I am trying to warp is linked below, with the points selected with blue circles around them. I have seen advice from similar posts that I need to make sure the points are ordered cor...
<p>After another couple hours banging my head against this problem, I noticed that the issue is that the plane I am interested in will never reach the points in the image above the vanishing point. Thus, the points which are above the vanishing point have undefined behavior, as it cannot be projected onto the plane, wh...
python|numpy|opencv|computer-vision|homography
0
376,795
63,029,166
Comparing two arrays throws a warning. Any workaround for this?
<p>I have 2 np.array() as below. When I compare the two using &quot;==&quot;, I get an output but with a deprecation warning. There is no warning when comparing 2 arrays with a same matrix.</p> <p>What's the workaround to get still the same result but with no warning?</p> <p>Thank you so much!</p> <pre><code>x = np.arr...
<p>This error is telling you that the comparisson you're performing doesn't really make sense, since both arrays have different shapes, hence it can't perform elementwise comparisson:</p> <pre><code>x==y </code></pre> <blockquote> <p>DeprecationWarning: elementwise comparison failed; this will raise an error in the fut...
python|python-3.x|pandas|numpy|data-science
2
376,796
63,188,215
How to plot a wind rose map with depend of color set to gas concentration
<pre><code>speed=[0.129438,0.0366483,0.439946,0.090253,0.19373,0.592419,0.00903306,0.520847,0.513714,1.16971,5.12548,4.37745,3.2362,2.91004,1.60186,0.115595,0.270153,0.19367,0.0865046,0.558443,0.613072,0.648203,0.0770592,0.81772,0.234523,1.04013,0.352675,0.0673293,0.492684,0.109398,0.402816,0.140199,0.998795,0.367604,0...
<p>Try polar scatter plot:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt speed=[0.129438,0.0366483,0.439946,0.090253,0.19373,0.592419,0.00903306,0.520847,0.513714,1.16971,5.12548,4.37745,3.2362,2.91004,1.60186,0.115595,0.270153,0.19367,0.0865046,0.558443,0.613072,0.648203,0.0770592,0.81772,0.234523...
python|numpy|matplotlib|plot|colors
1
376,797
63,083,564
why a[:,[x]] could create a column vector from an array?
<p>why a[:,[x]] could create a column vector from an array? The [ ] represents what? Could anyone explain to me the principle?</p> <pre><code>a = np.random.randn(5,6) a = a.astype(np.float32) print(a) c = torch.from_numpy(a[:,[1]]) </code></pre> <pre><code>[[-1.6919796 0.3160475 0.7606999 0.16881375 1.325092 ...
<p>The [ ] mean you are giving extra dimension. Try numpy shape method to see the diference.</p> <pre><code>a[:,1].shape </code></pre> <p>output :</p> <pre><code>(10,) </code></pre> <p>with [ ]</p> <pre><code>a[:,[1]].shape </code></pre> <p>output :</p> <pre><code>(10,1) </code></pre>
python|numpy|pytorch|tensor
0
376,798
63,170,358
Get columns from excel file and plot them
<p>I'm new to python, and I have this assignment I have to deliver soon. I have a .xlsx file that I've imported with <code>pandas</code>. It's a file from my workplace which tells us the day (mon - sat), time (from 10 am - 8 pm), sales per hour, visiting customers and customers that actually bought from the store (5 ro...
<p>#You can try Pandas's Group by to resolve your issue</p> <p>First, rename the column for better use remove blank space from the name</p> <pre><code>data.rename(columns = {'Sales per hour':'Sales_per_hour'}, inplace = True) Daywise_Data=data.groupby('Day').Sales_per_hour.sum().reset_index() </code></pre> <p>This wil...
python|excel|pandas|matplotlib|plot
0
376,799
63,036,809
How do I use only numpy to apply filters onto images?
<p>I would like to apply a filter/kernel to an image to alter it (for instance, perform vertical edge detection, diagonal blur, etc). I found this <a href="https://en.wikipedia.org/wiki/Kernel_(image_processing)" rel="nofollow noreferrer">wikipedia page</a> with some interesting examples of kernels.</p> <p>When I look ...
<p>Note: I would highly recommend checking out OpenCV, which has a large variety of built-in image filters.</p> <blockquote> <p>Also: a minor problem I've faced all day is that PIL can't display (x, x, 1) shaped arrays as images. Why is this? How do I get it to fix this? (np.squeeze didn't work)</p> </blockquote> <p>I ...
python|numpy|image-processing|matrix|edge-detection
1