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
20,500
33,248,518
Insert into Vertica if table does not exist or not a duplicate row
<p>I have written a python script to create a table using a <code>create table if not exists</code> statement and then insert rows from dataframe into vertica database. For the first time when I run this python script, I want it to create a table and insert the data - it works fine. </p> <p>But from next time onwards,...
<p>First I'll mention that <code>INSERT VALUES</code> is pretty slow if you are doing a lot of rows. If you are using batch sql and the standard vertica drivers, it should convert it to a <code>COPY</code> but if it doesn't then your inserts might take forever. I don't think this will happen with <code>pyodbc</code> s...
python|pandas|insert|vertica
1
20,501
66,669,331
Compute standard Deviation of pandas dataframe values
<p>I am currently working on a Machine Learning model and I am in the process of feature engineering. I am using a dataset that indicates the number of product sales of 70+ items across 13 stores.</p> <p>I have created features such as the average price of an item based on its SKU-ID (what product it is). I now wish to...
<p>Just an another approach, You can use <code>train.describe()</code> for the complete description of your dataset. It will return count, mean, standard deviation, median, 1st quartile, 3rd quartile and maximum value.</p> <p><strong>EXAMPLE</strong></p> <pre><code>df = pd.DataFrame({&quot;a&quot;:range(0,10),&quot;b&q...
python|pandas|statistics
0
20,502
66,555,842
Perform log2 normalization over columns in dataframe
<p>Is there a way to use the np.log2() function to iterate over columns of a dataframe while keeping column names?</p> <pre><code>df = pd.DataFrame(np.random.randint(0,100,size=(100, 10)), columns=list('ABCDEFGHIJ')) print(df) A B C D E F G H I J 0 62 77 38 89 20 38 20 86 13 72 1 4...
<pre><code>for i in list('ABCDEFGHIJ'): df[i] = np.log2(df[i]+0.001) </code></pre> <p>df:</p> <p><a href="https://i.stack.imgur.com/DMahM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DMahM.png" alt="enter image description here" /></a></p>
python|pandas|dataframe|numpy
1
20,503
66,417,109
TypeError: 'function' object is not subscriptable how to resolve this error while reading csv file
<blockquote> <p>when I am writing this code</p> </blockquote> <pre><code> test_df1=pd.read_csv[CSVFILE] </code></pre> <blockquote> <p>it show the below error</p> </blockquote> <pre><code>Traceback (most recent call last): File &quot;&lt;ipython-input-13-cb3d7014d176&gt;&quot;, line 1, in &lt;module&gt; test_df1=...
<p>Instead of</p> <pre><code>test_df1=pd.read_csv[CSVFILE] </code></pre> <p>because <code>read_csv()</code> is a method so it is called by <code>()</code> not <code>[]</code></p> <p>so use :-</p> <pre><code>df1=pd.read_csv('CSVFILE.csv') </code></pre>
pandas|csv|machine-learning|deep-learning|confusion-matrix
2
20,504
66,596,879
how to create start and end date in dataframe
<pre><code>Product component lead time mobile batteries 2days mobile charger 4 days charger cable 2 days charger adapter 2 days </code></pre> <p>I want to create a start date and the due date for example adapter start date should be started by today and due date =start date+ lead time. for product mobile...
<p>The approach would be to use the <code>pandas</code> and <code>datetime</code> module and increment the number of days from the lead time column. But to use the number of days as a number, one would have to extract it out from the string (by removing the 'days', removing all whitespaces and converting the resultant ...
python|pandas
0
20,505
16,229,982
Read Large Gzip Files in Python
<p>I am trying to read a gzip file (with size around 150 MB) and using this script (which I know is badly written):</p> <pre><code>import gzip f_name = 'file.gz' a = [] with gzip.open(f_name, 'r') as infile: for line in infile: a.append(line.split(' ')) new_array1 = [] for l in a: for i in l: ...
<p>My guess is that the problem is constructing <code>a</code> in your code, as that will undoubtedly contain a massive number of entries if your .gz is that large. This modification should solve that problem:</p> <pre><code>import gzip f_name = 'file.gz' filtered = [] with gzip.open(f_name, 'r') as infile: for ...
python|numpy
6
20,506
57,469,335
Subsample abundance dataframe
<p>I have a dataframe with species as columns and site as rows. In each cell is the number of each species I saw at that site. e.g.</p> <pre><code> Fern1 Fern2 Flower1 Flower2 Site1 15 0 6 1 Site2 0 46 16 40 Site3 25 1 19 3 </code></pre> <p>total = 172 But I want to randomly subsample 100 ...
<p>Try look at <code>cumcount</code> </p> <pre><code>yyy = df.groupby(t.index).cumcount()+1 </code></pre>
python|pandas
0
20,507
57,533,728
How to find Eigenspace of a matrix using python
<p>I have a matrix which is I found its Eigenvalues and EigenVectors, but now I want to solve for eigenspace, which is Find a basis for each of the corresponding eigenspaces! and don't know how to start! by finding the null space from scipy or solve for reef(), I tried but didn't work! please help!</p> <p>this is the ...
<p>The <code>np.linalg.eig</code> functions already returns the eigenvectors, which are exactly the basis vectors for your eigenspaces. More precisely: </p> <pre><code>v1 = eigenVec[:,0] v2 = eigenVec[:,1] </code></pre> <p>span the corresponding eigenspaces for eigenvalues <code>lambda1 = eigenVal[0]</code> and <code...
python|numpy|jupyter-notebook|eigenvalue
1
20,508
57,510,608
Cant build a CNN with keras for vectors - problem with dimensions
<p>Let us say that I build an extreamly simple CNN with Keras to classify vectors.</p> <p>My input (X_train) is a matrix in which each row is a vector and each column is a feature. My input labels (y_train) is matrix where each line is a one hot encoded vector. This is a binary classifier. </p> <p>my CNN is built as ...
<p>X_train is suppose to have the shape: (batch_size, steps, input_dim), <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv1D#input_shape" rel="nofollow noreferrer">see documentation</a>. It seems like you are missing one of the dimensions. I would guess input_dim in your case is 1 and that is why...
tensorflow|keras|conv-neural-network
0
20,509
57,598,863
unsupported operand type(s) in python 3.6
<p>Say I have a panda dataframe and want to print rows with two particular columns (<code>Score</code> and <code>Score1</code>) that have different values. I am running on python 3.6</p> <p>I tried </p> <pre><code>print(Data[round(Data['Score'],4)!=round(Data['Score1'],4)]) </code></pre> <p>and got this error:</p> ...
<p>Here are some other common approaches for comparing floating values. They are not equivalent to what you implemented but should still be good in many scenarios.</p> <p>Using native <code>pandas</code>:</p> <pre><code>selected = data[(data["Score"]-data["Score1"]).abs() &gt;= 1e-4] print(selected) </code></pre> <p...
python|python-3.x|pandas|floating-point|decimal
1
20,510
57,688,874
Form a column out of a Datetime field python
<p>Here is the DataFrame column and its datatype</p> <pre><code>df['Hours'].head() OutPut: 0 00:00:00 1 00:00:00 2 11:38:00 3 08:40:00 Name: Hours, dtype: timedelta64[ns] </code></pre> <p>I want to conditionally form anaother column from it, such that it will look like.</p> <pre><code>Hours Test 00:...
<p>Use:</p> <pre><code>df1['Hours'] = pd.to_timedelta(df1['Hours']) conditions = [df1['Hours'] == pd.Timedelta(0), df1['Hours'] &lt; pd.Timedelta(9, unit='H')] choices = ['N/A', 'Under Worked'] s = df1['Hours'].sub(pd.Timedelta(9, unit='h')).astype(str).str[7:15] df1['OT'] = np.select(conditions, choices, default=s...
python-3.x|pandas|datetime|if-statement
2
20,511
57,456,957
Count the element only if it has a number before comma
<p>I'm trying to count the element only if it has a number(at the end) before comma.</p> <p>Examples:</p> <blockquote> <p>12,12,12 = 3<br/> BOOK,,NO,06,07 = 5 &lt;- This is supposed to be 2<br/> 401-402-403-404-405, 301-302-303-304-305 = 2 &lt;- This should be 10<br/> G2,G3,G4 &lt;- It should be 3</p> </blo...
<p>You may use</p> <pre><code>data['total_books']=data['book_no'].str.findall(r'\d+(?![^,])|(?&lt;=,)\d+').str.len() </code></pre> <p>The regex matches</p> <ul> <li><code>\d+(?![^,])</code> - 1+ digits (<code>\d+</code>) that are followed with either a comma or end of string (<code>(?![^,])</code> = <code>(?=,|$)</c...
python|regex|pandas|numpy
1
20,512
43,878,759
tensorflow installation issues in Windows: can't import tensorflow
<p>I just tried installing the tensorflow package for the first time. It worked fine on my OSX Macintosh, but when I tried to install on a Windows computer, I started up Python and got </p> <pre><code>[py35] [py35nogpu] C:\Users\Brian&gt;ipython Python 3.5.3 |Continuum Analytics, Inc.| (default, Feb 22 2017, 21:28:42...
<p>The solution to my problem was found in <a href="https://stackoverflow.com/questions/43577923/cannot-import-tensorflow-for-gpu-on-windows-10?rq=1">Cannot import Tensorflow for GPU on Windows 10</a>. See also <a href="https://stackoverflow.com/questions/38009682/how-to-tell-if-tensorflow-is-using-gpu-acceleration-fr...
python|python-3.x|tensorflow
0
20,513
43,822,393
Dimensionality reduction in this CNN seems to be going against my understanding of the theory
<p>I have a two layer CNN with the following architecture:</p> <p><a href="https://i.stack.imgur.com/rC32k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rC32k.png" alt="enter image description here"></a></p> <p>Here is this architecture represented in tensorflow:</p> <pre><code>import os import ...
<p>It looks to me like you have miscalculated the sizes that are the outputs of each convolution/pooling layer. Here's how you can figure this out. I distilled your code down to just this:</p> <pre><code>import tensorflow as tf import numpy as np def conv_layer(input, size_in, size_out, name="conv"): with tf.name_s...
python|tensorflow|conv-neural-network|dimensionality-reduction
1
20,514
73,045,820
TextVectorization and Autoencoder for feature extraction of text
<p>I'm trying to solve a problem which is as follows:</p> <p>I need to train the autoencoder to extract useful data from text. I will use the trained autoencoder in another model to extract features.</p> <p>The goal is to teach the autocoder to compress the information and then reconstruct the exact same string. I solv...
<p>if you are using <code>tf.data.Dataset</code> you should combine your inputs and outputs in a single <code>Dataset</code> object.</p> <pre class="lang-py prettyprint-override"><code>dataset = tf.data.Dataset.from_tensor_slices( ( (feature1, feature2), # model inputs (label1, label2) # model outpu...
python|tensorflow|nlp|autoencoder|feature-engineering
0
20,515
73,040,591
Pandas - Compare values of multiple dataframes, and keep the majority value
<p>I have 3 dataframes with several columns (examples provided below).</p> <p>I would like to compare the values of each cell across all 3 dataframes. If more than 2 dataframes have the same entry, I want to keep that entry. If there is no majority opinion, I would like the entry to read &quot;no_majority&quot;</p> <p>...
<p>You can <code>concat</code> all dataframe then <code>groupby</code> and check <code>mode()</code> of <code>value</code> column in each group</p> <pre class="lang-py prettyprint-override"><code>df = pd.concat([df_1, df_2, df_3.rename(columns={'fruit': 'item'})], ignore_index=True) out = (df.groupby('item') .ap...
python|pandas|dataframe
1
20,516
72,966,601
How can I write an IF statement in Python Pandas to populate a blank column in my dataframe?
<p>I have a column of Results (A, B, C, D or E). In that column are missing values and Not Applicables. I want to insert a new column (done) and in that column if there is a grade between A-E in the Result column, I want to insert that grade in the new column, but if its not A-E, I want to impute a grade randomly in th...
<pre><code>import random df['B'] = df['A'].fillna(random.choice(df['A'].dropna().unique().tolist())) </code></pre> <p>if you only wish to replace nan values with a random result, then this will work. Basically, we fill all the nan values with a randomly chosen result from the first column</p> <p>'A' is the results colu...
python|pandas|if-statement
2
20,517
72,897,661
Pandas - Get the first n rows if a column has a specific value
<p>I have a DataFrame that has 5 columns including User and MP.</p> <p>I need to extract a sample of n rows for each User, n being a percentage based on User (if User has 1000 entries and n is 5, select the first 50 rows and and go to the next User. After that I have to add all the samples to a new DataFrame. Also if U...
<p>Check Below example. It is intentionally verbose for understanding. The column that solve problem is <strong>&quot;ROW_PERC&quot;</strong>. You can filter it based on the requirement (50% rows or 25% rows) that are required for each <strong>USR/MP</strong>.</p> <pre><code>import pandas as pd df = pd.DataFrame({'USR...
python-3.x|pandas|dataframe
0
20,518
70,410,885
How to find a slice from n: m of singular value decomposition matrix, whithout cicles
<p>SVD is equal to UΣVT, where U - m * k matrix,Σ - k * k diagonal matrix, VT - transposed k * m matrix. Also UΣVT can be determined as A = u1σ1vT1 + u2σ2vT2 + u3σ3vT3 where u1 - first column of U, σ1 - first element of Σ, vT1 - first column of V. Scipy contains function svd(a), which returns UΣVT. How to find for exam...
<p>The reconstruction can be performed by matrix multiplication</p> <pre class="lang-py prettyprint-override"><code>U, s, VT = la.svd(A) np.allclose((U * s) @ VT, A) np.allclose(U @ np.diag(s) @ VT, A) </code></pre> <p>If you find the second singular value as <code>s[1]</code> and the thrid as <code>s[2]</code>, if you...
python|numpy|matrix|scipy|svd
0
20,519
70,418,858
IndexError & AttributError
<p>can someone help me fixing this error? im new in python and im using keggle.</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt import sklearn </code></pre> <pre><code>dataset = pd.read_csv('../input/datacoba2/Data Penjualan1.csv', sep=&quot;,&quot;) x = dataset.iloc[:, :-1:].value...
<p>Your data should folow csv format.</p> <p>Use this to replace your data.</p> <pre><code>BiayaProduksi,NilaiPenjualan 1500,90500 1800,89500 1900,105000 2050,102000 2050,90500 2100,104500 2200,109500 2400,150000 3050,152000 3200,173000 3200,153000 3500,174500 3500,150000 3750,198000 3750,187000 3900,194500 4000,200500...
python|pandas|dataframe
0
20,520
70,417,388
When converting to a numpy array, how can eliminate the single quotation marks? (python3)
<p><img src="https://i.stack.imgur.com/KB7C4.png" alt="enter image description here" /></p> <p>i want this</p> <pre><code>array([[2600, 11749, 9], [976, 16, 2, ...],...) </code></pre> <p>But I don't know why single quotes are printed. What should I do?</p>
<p>It seems that numpy arrays of different lengths have been entered into the pandas series.</p> <p>It seems that numpy arrays of different lengths have been entered into the pandas series.</p> <p>try this</p> <pre><code>X_train.values </code></pre> <p>or</p> <pre><code>list(map(np.array, x_train)) </code></pre>
python|arrays|list|numpy
0
20,521
70,447,904
transform a binary matrix into the original matrix
<p>I am a beginner of python and I have no idea about how to resolve this problem:</p> <p>I have DNA sequences of 60 nucleotides save in a csv format, where each nucleotide is replaced by 3 binary indicator variables as follows:</p> <pre><code>A -&gt; 1 0 0 C -&gt; 0 1 0 G -&gt; 0 0 1 T -&gt; 0 0 0 </code></pre> <p>So ...
<p>It looks like you have the data in <code>X</code>, and based on the file that you linked to, <code>X</code> has shape (3186, 180). Here's a way you can convert that to an array with shape (3186, 60) containig the characters 'A', 'C', 'G' and 'T'.</p> <p>First, note that you can convert each triple to an integer ind...
python|numpy|matrix|binary-data|dna-sequence
1
20,522
43,023,985
Select rows from a DataFrame based on last characters of values in a column in pandas
<p>I want to select rows from columns with last word as 'oo' in Column A how can I do this.</p> <p>I went through the link :- <a href="https://stackoverflow.com/questions/17071871/select-rows-from-a-dataframe-based-on-values-in-a-column-in-pandas">Select rows from a DataFrame based on values in a column in pandas</a><...
<p>I'd do it this way:</p> <pre><code>df[df.A.str.endswith('oo')] </code></pre>
python|python-3.x|pandas
4
20,523
42,756,393
Efficient Euclidean distance for coordinates in different size lists in python
<p>I've got two large point lists. One holds points that represent the edges of a rectangle (edge_points). Edge_points has xy coordinates. The other list holds points within the rectangle (all_point). All_point has xyz coordinates. In the second list, I want to remove any points that are within xy "m" distance of the p...
<p><em>Vectorise, vectorise</em> also applies here:</p> <pre><code>import numpy as np all_point, edge_points = np.asanyarray(all_point), np.asanyarray(edge_points) squared_dists = ((all_point[:, None, :2] - edge_points[None, :, :])**2).sum(axis=-1) mask = np.all(squared_dists &gt; m**2, axis=-1) all_points = all_poin...
python|loops|numpy
0
20,524
27,260,003
Python: how to translate complex SQL aggregate statements into pandas?
<p>With pandas, what is the best way to create the equivalent of a SQL group by statement, using:</p> <ul> <li>a different aggregate function on each field (e.g. I need the sum of field1, the avg of field2 and the max of field3)</li> <li>slightly more complex calculations like sum(field1) / sum(field2), e.g. for weigh...
<pre><code>&gt;&gt;&gt; df Country Region GDP Population male_population 0 USA TX 10 100 50 1 USA TX 11 120 60 2 USA KY 11 200 120 3 Austria Wienna 5 50 34 &gt;&gt;&gt; &gt;&gt;&gt; df...
python|pandas|dataframe
1
20,525
27,153,919
selecting last of day in a pandas index
<p>I got a dataframe indexed with datetime index. That index contains several times the same dates, meaning same year, month and day, the hour may differ. I'd like to select only the last of each and every existing day in the index.</p> <p>I think I'm on the right path, but I miss something in the logic....</p> <p>so...
<p>If you <code>groupby</code> the index date, you can select the last item for each group, e.g.:</p> <pre><code>dfmatches.groupby(dfmatches.index.date).last() </code></pre>
python|pandas
3
20,526
25,226,872
Python not installing sklearn
<p>I am working with ubuntu 14. I have downloaded the dpkg package for sklearn and unpacked it. i try to run <code>sudo python setup.py install</code>But it seems to be stuck in a loop</p> <pre><code> compiling C++ sources C compiler: c++ -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -fPIC creating b...
<p>I recommend installing sklearn and all dependencies with Anaconda package: <a href="https://www.continuum.io/downloads#_unix" rel="nofollow">https://www.continuum.io/downloads#_unix</a></p> <p>It will be installed together with numpy and other packages, full list is available here: <a href="http://docs.continuum.io...
python|python-2.7|ubuntu|numpy|scikit-learn
0
20,527
30,584,879
Python: How to index the elements of a numpy array?
<p>I'm looking for a function that would do what the function <code>indices</code> does in the following hypothetical code:</p> <pre><code>indices( numpy.array([[1, 2, 3], [2, 3, 4]]) ) </code></pre> <blockquote> <p>{1: [(0,0)], 2: [(0,1),(1,0)], 3: [(0,2),(1,1)], 4: [(1,2)]}</p> </blockquote> <p>Specifically, I w...
<p>Given that your desired output is a dictionary, I don't think there's going to be an efficient way to do this with NumPy operations. Your best bet will probably be something like</p> <pre><code>import collections import itertools d = collections.defaultdict(list) for indices in itertools.product(*map(range, a.shap...
python|arrays|numpy|indexing
1
20,528
26,699,756
Formatting a column to line up with data in a text file
<p>I am trying to set-up a text file so that the data is directly in line with its given header. For instance the file contains 7 headers (t, x(t) ect...) </p> <pre><code>np.savetxt('vel.dat', Velocity_Col, fmt='%.5e', delimiter=(' '), header = (' t x(t) y(t) z(t) ...
<p>The <code>5</code> in <code>'%.5e'</code> sets the number of digits displayed after the decimal point. You also want to control the total width of each field. That is controlled with a number before the decimal point in the format specification. (The number sets the <em>minimum</em> field width. More characters ...
numpy|python-3.3
3
20,529
26,842,744
Error: The truth value of an array with more than one element is ambiguous
<p>There are two arrays: <code>a=np.array([1,2,3,4,5])</code>and <code>b=np.array([1,2,3,4,5,6,7,8,9])</code> A new array is created containing the other two arrays: <code>c=np.array([[a],[b]])</code>.</p> <p>We want to threshold every of the two arrays separetely in the <code>c</code> with a min value(e.g. the value ...
<p>Problem is you have added an extra level of <code>[]</code> in <code>c</code>, so instead of accessing just <code>c[i]</code> you should access <code>c[i][0]</code>:</p> <pre><code>&gt;&gt;&gt; for x in c: ... print x ... [array([1, 2, 3, 4, 5])] [array([1, 2, 3, 4, 5, 6, 7, 8, 9])] </code></pre> <p>Repl...
python|numpy
2
20,530
39,189,794
Conditional editing of strings in a Pandas DataFrame
<p>I am learning Pandas and have a DataFrame of strings which looks a little like this:</p> <pre><code>df = pd.DataFrame([['Apple', 'Med6g7867'], ['Orange', 'Med7g8976'], ['Banana', 'Signal'], ['Peach', 'Med8g8989'], ['Mango', 'Possible result %gggyy']], columns=['A', 'B']) df A B 0 Apple Med6g7867 1 O...
<p>You can apply replace twice like this:</p> <pre><code>In [460]: df Out[460]: A B 0 Apple Med6g7867 1 Orange Med7g8976 2 Banana Signal 3 Peach Med8g8989 4 Mango Possible result %gggyy In [461]: df.replace(r'Med\dg\d{4...
python|regex|pandas
2
20,531
19,827,706
Python numpy argsort
<p>Suppose I have the following lists</p> <pre><code>['foo', '333', 32.3] ['bar', 4.0] ['baz', '555', '2232', -1.9] </code></pre> <p>I want to be able to sort this via the last element (float)</p> <pre><code>['baz', '555', '2232', -1.9] ['bar', 4.0] ['foo', '333', 32.3] </code></pre> <p>In ascending order</p> <p...
<p>I would just use plain <code>lists</code> here, when you create a <code>numpy.array</code> with sub-lists of different lengths (or different data types in your <code>array</code>) you get an <code>array</code> of type <code>object</code>, which lacks many useful <code>numpy</code> features and is rarely a good idea ...
python|list|sorting|numpy
2
20,532
28,890,379
With pandas, how do I calculate a rolling number of events in the last second given timestamp data?
<p>I have dataset where I calculate service times based on request and response times. I would like to add a calculation of requests in the last second to show the obvious relationship that as we get more requests per second the system slows. Here is the data that I have, for example:</p> <pre><code>serviceTimes.head(...
<p>For your problem, it looks like you want to summarize your data set using a split-apply-combine approach. See <a href="http://pandas.pydata.org/pandas-docs/dev/groupby.html" rel="nofollow">here</a> for the documentation that will help you get your code in working but basically, you'll want to do the following:</p> ...
python|pandas
3
20,533
33,801,700
Elementwise multiplication of tensors of unknown dimension
<p>How do I do an elementwise multiplication of tensors with the following shapes? The second array here is always assumed to be 2D.</p> <pre><code>[x, y, ?, ?, ?, ...] * [x, y] </code></pre> <p>I want to broadcast over all the dimensions marked ?, of which I don't know the number a-priori. Possible solutions I have ...
<p>The alternatives mentioned in the question (with <code>b</code> the 2D array):</p> <ul> <li><p>Add a variable number of axes to the second array</p> <pre><code>a * b.reshape(b.shape + (1,)*(a.ndim-b.ndim)) </code></pre></li> <li><p>Reverse the order of the axes of both arrays and then reverse them back again</p> ...
python|arrays|numpy|array-broadcasting
4
20,534
23,503,667
How to detect if all the rows of a non-square matrix are orthogonal in python
<p>I can test the rank of a matrix using np.linalg.matrix_rank(A) . But how can I test if all the rows of A are orthogonal efficiently?</p> <p>I could take all pairs of rows and compute the inner product between them but is there a better way?</p> <p>My matrix has fewer rows than columns and the rows are not unit vec...
<p>It seems that this will do</p> <pre><code>product = np.dot(A,A.T) np.fill_diagonal(product,0) if (product.any() == 0): </code></pre>
python|math|numpy|scipy
6
20,535
22,702,760
how to multiply multiple columns by a column in Pandas
<p>I would like to have:</p> <pre><code>df[['income_1', 'income_2']] * df['mtaz_proportion'] </code></pre> <p>return those columns multiplied by <code>df['mtaz_proportion']</code></p> <p>so that I can set </p> <pre><code>df[['mtaz_income_1', 'mtaz_income_2']] = df[['income_1', 'income_2']] * df['mtaz_proportion'] ...
<p>use <code>multiply</code> method and set <code>axis="index"</code>:</p> <pre><code>df[["A", "B"]].multiply(df["C"], axis="index") </code></pre>
python|pandas
104
20,536
15,469,302
numpy 3d to 2d transformation based on 2d mask array
<p>If I have an ndarray like this:</p> <pre><code>&gt;&gt;&gt; a = np.arange(27).reshape(3,3,3) &gt;&gt;&gt; a array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]], [[ 9, 10, 11], [12, 13, 14], [15, 16, 17]], [[18, 19, 20], [21, 22, 23], [24, 25, 26]]]) </co...
<p>Here is some magic numpy indexing that will do what you want, but unfortunately it's pretty unreadable. </p> <pre><code>def apply_mask(a, indices, axis): magic_index = [np.arange(i) for i in indices.shape] magic_index = np.ix_(*magic_index) magic_index = magic_index[:axis] + (indices,) + magic_index[axi...
python|numpy
3
20,537
62,455,457
Applying function over entire parameter space/2d array, Numpy
<p>I'm in one of those weird places, where I know exactly what I want to do. I could easily code it up using for loops. but I'm trying to learn Numpy and I can't formulate how to solve this in Numpy.</p> <p>I want to have a 2d array or parameter space. All values between 1200 and 1800, and all combinations therein. So...
<p>I don't fully understand the problem you are trying to solve. I hope the following will give you a starting point on how numpy can be used. I recommend going through a numpy introductory tutorial.</p> <p>numpy boolean indexing and vector math can improve speed and reduce the need for loops. Here is my understan...
python|numpy
0
20,538
62,205,053
TypeError: Dimension value must be integer or None or have an __index__ method, got TensorShape([None, 1])
<p>I am trying to convert a bot tutorial I found that uses tflearn to use keras. Right now the output should be data for the models prediction. However, I get the error:</p> <p>TypeError: Dimension value must be integer or None or have an __index__ method, got TensorShape([None, 1])</p> <p>my code:</p> <pre><code>wi...
<p>Also not an exact answer to the question, but somewhere related on the same lines. I got the error: <code>TypeError: Dimension value must be integer or None or have an __index__ method, got 108.0</code> which I eventually found that if your generator returns matrices then its shape values are obviously integers e.g....
python|tensorflow|keras
2
20,539
62,147,223
Convert float dtype dataframe to string dtype dataframe (NaN becomes '0')
<p>Here is my code:</p> <pre><code> dfFact = pd.read_sql_query("select * from MusicFact;", conn) dfFact['artist'].fillna(0) dfFact['artist'].astype('Int64') dfFact['artist'] = dfFact['artist'].astype(str) </code></pre> <p><a href="https://i.stack.imgur.com/Sx5Nl.png" rel="nofollow noreferrer">I am tryi...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>Series.fillna</code></a> if used without <code>inplace=True</code> returns a new series with missing values filled with the replacement value. Similarly <a href="https://pandas.pydata.org/pa...
python|pandas|dataframe|nan
0
20,540
62,228,557
How to stack two matrices horizontally in python
<p>In python I need to stack two matrices horizontally.</p> <p>Initial matrices I have:</p> <pre><code>a = [[3, 5] [8, 6] [9, 2]] b = [[4] [1] [7]] </code></pre> <p>What I am able to do:</p> <pre><code>import numpy as np c = np.hstack((a, b)) c = [[3, 5, 4] [8, 6, 1] [9, 2, 7]] </code...
<p>Starting with two lists:</p> <pre><code>In [83]: a = [[3, 5], ...: [8, 6], ...: [9, 2]] ...: ...: b = [[4], ...: [1], ...: [7]] In [84]: ...
python|arrays|numpy|matrix|stack
1
20,541
62,365,697
Count how many columns of a numpy matrix contain all positive values
<p>I want to check how many columns of a numpy array/matrix have only positive values.</p> <p>I took my matrix and printed <code>A&gt;0</code> and got <code>True</code> and <code>False</code> and then I tried <code>any</code> and <code>all</code> functions but didn't succeed.</p> <pre><code>In [55]: a = np.array([[13...
<p>This function counts the number of column whose elements are all greater than 0:</p> <pre><code>def count(mat): counter = 0 tmp = mat &gt; 0 for col in tmp.T: if all(col): counter += 1 return counter </code></pre> <p>How does this function work?</p> <p>First it assigns to tmp ...
python|numpy
0
20,542
51,156,742
Join dataframes by date in python pandas
<p>I am a beginner in pandas and i am facing some problems to join 2 dataframes by date.</p> <p>here is the first data frame <a href="https://i.stack.imgur.com/Y36HW.png" rel="nofollow noreferrer">it contains consumption of electreciy by building id </a></p> <pre><code> date id_bat conso 0 2014-...
<pre><code>df = pd.read_csv('df_conso.csv') df1 = pd.read_csv('df_dju.csv') # reshape columns id_site and id_bat by spliting it in two parts df.id_bat.astype('str') df['id_site'] = df.id_bat.str.slice(0,4) df.id_bat = df. id_bat.str.slice(4,6) # pivot the df and reset index df = df.pivot_table(index=['id_site','date'...
python|pandas|date|dataframe|join
0
20,543
51,459,489
Python fill missing data
<p>So I have a table that is kind of data like this</p> <pre><code>theta phi x y 0 0 1 2 0 1 2 3 -------------------- 90 360 4 5 </code></pre> <p>theta values runs from 0 to 90 and for each theta phi runs from 0 to 360, but some of the phi s are missing here and there in t...
<p>I think you can do it by setting 'theta' and 'phi' as index with <code>set_index</code>, then <code>reindex</code> with <code>pd.MultiIndex.from_product</code> with all the values of 'theta' and 'phi' you expect, fill nan values with <code>interpolate</code> and finally <code>reset_index</code> such as:</p> <pre><c...
python|pandas|dataframe
1
20,544
51,515,819
Accessing reduced dimensionality of trained autoencoder
<p>Here is a autoencoder trained on mnist using PyTorch : </p> <pre><code>import torch import torchvision import torch.nn as nn from torch.autograd import Variable cuda = torch.cuda.is_available() # True if cuda is available, False otherwise FloatTensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor print('T...
<p>I'm not very familiar with pyTorch, but splitting the autoencoder into an encoder and decoder model seems to work (I changed the size of the hidden layer from 512 to 64, and the dimension of the encoded image from 128 to 4, to make the example run faster):</p> <pre><code>import torch import torchvision import torch...
machine-learning|neural-network|pytorch|autoencoder|dimensionality-reduction
1
20,545
51,358,324
Get vector angle by python
<p>I have a vector list. I want to get angle in each vector.</p> <pre><code>import numpy as np v = np.array([[-3, 4], [-2, -5], [2, 6], [3, -10]]) inv = np.arctan(v[:, 1] / v[:, 0]) degree = np.degrees(inv) print(degree) # get [-53.13010235, 68.19859051, 71.56505118, -73....
<p>You can use modulus to get all the angles in the range 0 - 360.</p> <pre><code>import numpy as np v = [ [-3, 4], [-2, -5], [2, 6], [3, -10], ] v = np.array(v) inv = np.degrees(np.arctan2(*v.T[::-1])) % 360.0 print(inv) </code></pre> <p><strong>output</strong></p> <pre><code>[ 126.86989765 248.1...
python|performance|numpy
6
20,546
51,197,126
Plotting large datasets with pandas
<p>I convert an oscilloscope dataset with millions of values into a pandas DataFrame. Next step is to plot it. But Matplotlib needs on my fairly powerful machine ~50 seconds to plot the DataFrame. </p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import readTrc datX, datY, m = readTrc.readTrc('C...
<p>You can use <a href="https://plotly.com/python/" rel="nofollow noreferrer">Ploty</a> and <a href="https://github.com/serant/lenspy" rel="nofollow noreferrer">Lenspy</a> (was built to solve this exact problem). Here is an example of how you can plot 10m points on scatter plot. This plot runs super fast on my 2016 Mac...
python|pandas|matplotlib
1
20,547
48,158,454
How to train a LSTM model on the fly?
<p>I have a LSTM model that is used to create a Chatbot. The Chatbot now knows how to respond from whatever it knows based on its trained model. </p> <p>So, now we have a situation that our chat bot should <em>learn dynamically as and when a new query is posted which the chat bot has no idea about</em>, it should lea...
<p>This can be achieved by simply loading your saved model (which you probably saved with <code>model.save()</code>) and training your new data with <code>fit()</code> method, something like:</p> <pre class="lang-py prettyprint-override"><code>from keras.models import load_model #load your model model = load_model('ch...
python|tensorflow|deep-learning|keras|lstm
4
20,548
48,353,551
Read multiple images using glob (Python) and save them in csv
<p>Trying to read several images from a local folder and save them to csv using numpy.savetxt. Using following code</p> <pre><code>filelist = glob.glob('Filepath/*.png') x = np.array([np.array(Image.open(fname)) for fname in filelist]) print(x.shape) np.savetxt('csvfile.csv', x,fmt='%s') </code></pre> <p>Want this co...
<br/> <br/> <p>I think you could try with glob.glob, what should help</p> <br/> <pre><code>import numpy as np import glob import cv2 import csv </code></pre> <p>Libraries ⬆️; You know what⬇️</p> <pre><code>image_list = [] for filename in glob.glob(r'C:\your path to\file*.png'): # '*' will count files each by one ...
python|arrays|csv|numpy
1
20,549
48,274,585
Pandas extractall() - return list, not a MultiLevel index?
<p>I have a question, which I have a feeling might have already been asked before, but in a different form. Point me to the original if that's the case please.</p> <p>Anyway, I am playing with Pandas <code>extractall()</code> method, and I don't quite like the fact it returns a DataFrame with MultiLevel index <code>(o...
<p>Let's try:</p> <pre><code>df.groupby(level=0)['X'].apply(list) </code></pre> <p>Output:</p> <pre><code>0 [thank] 1 [thank, thanks, thanking] 2 [thanked] Name: X, dtype: object </code></pre>
python|regex|pandas
13
20,550
48,885,878
How to deploy Tensorflow service in a server
<p>I successfully trained a deep net using tensorflow. The net is able to modify the content of a square 512x512 px image. </p> <p>Now I would like to deploy the net in a server and create a basic service. Something like this: <a href="https://letsenhance.io/" rel="nofollow noreferrer">https://letsenhance.io/</a>. Whe...
<p>It will exceed the limitations of AWS Lambda.</p> <p>But you can try running on <a href="https://ramhiser.com/2016/01/05/installing-tensorflow-on-an-aws-ec2-instance-with-gpu-support/" rel="nofollow noreferrer" title="EC2 instance with TensorFlow support">EC2 instance with GPU support</a> but it will take some time...
web-services|tensorflow|aws-lambda
1
20,551
48,763,116
Pandas read_excel keep A:Z column names
<p>When importing an excel file to pandas using read_excel, I would like to keep the column and row names of excel. I.e., I would like my columns to be named 'A','B',...'Z','AA','AB' etc. and rows from 1 and on.</p> <p>Is there a good way to do this?</p>
<p>You need custom <a href="https://stackoverflow.com/q/19153462/2901002">mappings</a> and apply it to <code>rename</code>:</p> <pre><code>np.random.seed(100) df = pd.DataFrame(np.random.randint(10, size=(5,5))) print (df) 0 1 2 3 4 0 8 8 3 7 7 1 0 4 2 5 2 2 2 2 1 0 8 3 4 0 9 6 2 4 4 1 5 ...
python|excel|pandas
5
20,552
70,944,127
Survey data: long to wide including question numbering
<p>I would like to reshape my survey dataframe from long to wide. The current dataframe looks like this, where a second occurrence of a name refers to a answer on a secon question, and so forth:</p> <pre><code>Name | A | B | C | D | E | Bob X Ted X Chris X Bob X Ted X Ch...
<p>You can do <code>stack</code> then create the <code>pivot</code> key with <code>groupby</code> <code>cumcount</code></p> <pre><code>s = df.set_index('Name').stack().reset_index() out = s.assign(key = s.groupby('Name').cumcount()+1).pivot('Name','key','level_1').add_prefix('Q') Out[17]: key Q1 Q2 Name Bob ...
python|pandas
1
20,553
70,775,128
GPU availability check
<p>I am trying to test that my Jupyter notebook is using the GPU or not but when I check with this code, It shows me '0' GPU's available. But, My system is i7 10th Generation and GEFORCE RTX 2060. I have downloaded cuda and NVIDIA CNN added to the system variables and in anaconda downlaoded tensorflow GPU but I don't k...
<p>try use <a href="https://pythonrepo.com/repo/anderskm-gputil-python-gpu-utilities" rel="nofollow noreferrer">gputil</a>:</p> <pre><code>import GPUtil GPUtil.showUtilization() </code></pre> <p>try also look here - <a href="https://stackoverflow.com/questions/38559755/how-to-get-current-available-gpus-in-tensorflow">H...
python|tensorflow|jupyter-notebook|anaconda|gpu
0
20,554
64,273,491
Change multiple boolean columns' values based on a different columns values, using a list
<p>There is a list of values</p> <pre><code>weather = ['cloudy', 'sunny'] </code></pre> <p>I've got a dataframe with an old column &quot;weather&quot;. We switched to 2 newer columns with boolean values, so all the old columns need to be accounted for.</p> <p>Here is my dataframe now:</p> <pre><code>[In] data = [['clou...
<p>Let's try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.get_dummies.html" rel="nofollow noreferrer"><code>str.get_dummies</code></a> to create dummy indicator variables, then <code>join</code> it with original dataframe:</p> <pre><code>df[['old']].join(df['old'].str.get_dummie...
python|pandas|list|boolean
1
20,555
64,542,909
Add a column to the data frame doing element wise operation
<p>Basically, pandas can copy the column by</p> <pre class="lang-py prettyprint-override"><code>df['B'] = df['A'] + 1 </code></pre> <p>Now, I have a column of strings and I want to add a column whose values are the lengths of each string. For example,</p> <pre><code>A. B &quot;hello&quot; 5 &quot;hi&quot; 2 </c...
<p>Use <code>str.len</code>:</p> <pre><code>df['B'] = df['A'].str.len() </code></pre>
python|pandas
3
20,556
49,044,980
How could I feed a custom image into this model?
<p>I've been following a course online and one of the exercises was to create a simple image detection model (using MNIST data) to detect written numbers. I've been trying to load a custom image I drew in (128x128 jpg) but I can't seem to figure it out. I'm really close, but I think I'm just confused about what paramet...
<p>Simply convert your image to an <code>128x128</code> numpy array with values between 0 and 1. </p> <p>Then:</p> <pre><code>image = Variable(torch.from_numpy(image))[None, :, :] classification = model(image) </code></pre> <p><code>classification</code> is then a pytorch Variable containing probabilities of belongi...
python|neural-network|deep-learning|pytorch|mnist
1
20,557
48,995,856
python pandas custom weightages
<p>As per below details, dataframe has company-wise numbers. Dict has custom weightages. Company 'A' has 7 rows, so I would like to fetch custom weightages from dict with key as 7 and create 'custom_weights' as a new column. Latest date will have highest weightage. </p> <p>Similarly for Company 'B' and 'C', I need to ...
<p>Use <code>groupby()</code> to count the number of <code>['CompanyNames']</code> and assign the list from the dictionary back to the dataframe using <code>transform()</code></p> <pre><code>df['CustomWeights'] = df.groupby('CompanyName')['Date_Published'].transform(lambda x: dict_wt.get(len(x))) CompanyName Date_Pu...
python|pandas|dictionary|dataframe|weighted
1
20,558
58,874,778
Tensorflow predictor: Specifying the serving_input_receiver_fn
<p>I want to build a predictor from a an tf.estimator.Estimator model. Therefore I need to specify a input_receiver_fn that specifies the preprocessing graph from the receiver tensors to the features that will be passed to the model_fn by the predictor.</p> <p>Here is an example for an eval_input_fn for the Estimator:...
<p>The error was in the model_fn. The following lines have to be moved down to the # TRAIN mode part of the function</p> <pre><code> gt,fg = tf.unstack(labels,num=2,axis=1) gt.set_shape([1]+params['input_size']) fg.set_shape([1]+params['input_size']) </code></pre> <p>Estimator.predict will feed only t...
tensorflow|tensorflow-serving|tensorflow-estimator
0
20,559
59,005,137
Pandas: Check if a value exist in a column, create a new column, exist add 1 if not add 0
<p>I have a DataFrame</p> <pre><code>df = columnA=[1,2,3,4,5,6] columnB=['Apple AA','Banana BB',NaN,'Strawberry DD',NaN,'Blueberry EE'] </code></pre> <p>I want to create a new column if columnB contains values</p> <pre><code>df = columnA=[1,2,3,4,5,6] columnB=['Apple AA','Banana BB',NaN,'Strawberry DD',NaN,'B...
<p>You can use <code>.notnull()</code> to test if your values are not NaN</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'columnA':[1,2,3,4,5,6], 'columnB':['Apple AA','Banana BB',np.NaN,'Strawberry DD',np.NaN,'Blueberry EE']}) df['columnC'] = df['columnB'].notnull()*1 </c...
python|pandas|dataframe
3
20,560
58,800,357
concat multiple df made from pd.read_html
<p>my title does not make any sense so i am going to give brief about situation</p> <p>i am scraping data from site which basically table but in this case every row is a table element and also every odd table element is not useful so i am eliminating</p> <p>so what i want is concatenation of every individual datafram...
<p>Try this</p> <pre><code>from bs4 import BeautifulSoup as bs import pandas as pd all_table = ''' html content ''' finalDf = pd.DataFrame() soup = bs(all_table) tables = soup.findAll("table") for i,table in enumerate(tables): if i%2==0: df = pd.read_html(str(table)) f...
python-3.x|pandas|web-scraping
0
20,561
58,678,403
Issue of Aggregating Categorical Column
<p>I encountered an issue in <code>pandas</code> 0.25.2 while aggregating multiple columns that include a categorical column.</p> <pre><code>import pandas as pd df = pd.DataFrame({ "col1": [1, 3, 4, 1], "col2": pd.Categorical(["b", "a", "c", "b"], categories=["a", "b", "c"], ordered=False), "col3": [4, ...
<p>I think it is <a href="https://github.com/pandas-dev/pandas/issues/13416" rel="nofollow noreferrer">bug</a>, but possible solution is use lambda function with <code>iat</code> for first value of group:</p> <pre><code>df_agg = df.groupby("col1").agg( col2=pd.NamedAgg("col2", lambda x: x.iat[0]), col3_max=pd....
python|pandas
4
20,562
58,908,050
My text classifier model doens't improve with multiple classes
<p>I'm trying to train a model for a text classification and the model take a list of maximum 300 integer embedded from articles. The model trains without problem and all but the accuracy won't go up. </p> <p>The target consists of 41 categories encoded into int from 0 to 41 and were then normalized.</p> <p>The table...
<p>After 2 days of tweaking and understanding more examples I found <a href="https://machinelearningmastery.com/multi-class-classification-tutorial-keras-deep-learning-library/" rel="nofollow noreferrer">this</a> website which explains quite well about the multi-class classification.</p> <p>The details of changes I mad...
python|pandas|tensorflow|machine-learning|text-classification
0
20,563
70,047,568
Search Value from anywhere in Dataframe and get location of that value and update it
<p>I tried to search value 'Apple' in DataFrame and update these value to 'Green Apple'</p> <p>My method is search location of that value and update it.</p> <p>My code below</p> <pre><code>x = df[df.isin(['Apple'])].stack() </code></pre> <p>It return Row Index and Col Name as I expect, but I don't know how to get these...
<p>For finding location of the element you can use the same method <code>df[df.isin(['Apple'])].stack()</code> and for replacing the element in whole dataframe you can use <code>df.replace()</code> as given below</p> <pre><code>import pandas as pd df = pd.DataFrame({'A': [0, 1, 2, 3, 4], 'B': [5, 6,...
python|pandas
0
20,564
70,067,762
How to identify unique elements in two dataframes and append with a new row
<p>I am trying to write a function that takes in two dataframes with a different number of rows, finds the elements that are unique to each dataframe in the first column, and then appends a new row that only contains the unique element to the dataframe where it does not exist. For example:</p> <pre><code>&gt;&gt;&gt; d...
<p>We can do</p> <pre><code>out1 = pd.concat([df1,pd.DataFrame({'col1':df2.loc[~df2.col1.isin(df1.col1),'col1']})]) Out[269]: col1 col2 0 1 3.0 1 2 4.0 2 5 6.0 2 6 NaN #out2 = pd.concat([df2,pd.DataFrame({'col1':df1.loc[~df1.col1.isin(df2.col1),'col1']})]) </code></pre>
python|pandas|dataframe
1
20,565
70,238,187
How to make a prediction using a model based on csv dataset?
<p>Following tutorial, I made a neural network which dataset comes from csv file made by me. It is simple dataset, which contains first exam result, second exam result, third exam result and nationality of each student. The goal is to predict third exam result using first and second exam result and nationality. Here is...
<p>You need to do the same operations with the test dataset</p> <pre><code>prediction_data.dropna(inplace=True) prediction_data.Country=pd.Categorical(prediction_data.Country, ['PL', 'ENG'], ordered=True) prediction_data.Country=prediction_data.Country.cat.codes normalizer.adapt(np.array(prediction_data)) #You need no...
python|tensorflow|machine-learning|keras|prediction
3
20,566
56,100,670
Matplotlib pyplot plots look different after calling pandas profiling. How can I fix this?
<p>I ran into a strange issue today. I stumbled over a package called <code>pandas_profiling</code>, which I think is quite nice. However, after calling the profiling, the plots in my jupyter notebook change. The axis ticks aren't correct anymore and the whole look is different. </p> <p>Can you help me out how to get ...
<p>Well, let's first go to the reason why this happens. As we can see in the <a href="https://github.com/pandas-profiling/pandas-profiling/blob/master/pandas_profiling/view/plot.py#L20" rel="nofollow noreferrer">source code</a>, the package sets the style: </p> <pre><code>matplotlib.style.use(resource_filename(__name_...
python|pandas|plot|profiling|pandas-profiling
3
20,567
56,045,328
What is the way to create DataFrame of length of intersections of a list of sets
<p>I have a dictionary filled with sets. It might look something like this:</p> <pre><code>import pandas as pd my_dict = {'gs_1': set(('ENS1', 'ENS2', 'ENS3')), 'gs_2': set(('ENS1', 'ENS4', 'ENS5', 'ENS7', 'ENS8')), 'gs_3': set(('ENS2', 'ENS3', 'ENS6'))} </code></pre> <p>I've also built a panda...
<p>Here's my approach based on <code>scipy.spatial.distance_matrix</code>:</p> <pre><code># create unions of values total = set() for key, val in my_dict.items(): total = total.union(val) total = list(total) # create data frame df = pd.DataFrame({}, index=total) for key, val in my_dict.items(): df[key] = pd...
python|pandas
3
20,568
55,660,330
How to get "Date Created" and "Date Modified" while using os.walk()
<p>My company wants to transition from our old <em>store it in the Engineering Folder</em> mentality to a PDM. I writing a script that will walk through the directories and log roots, directories, and files. </p> <p>I've already been able to walk through the directory and do what I want to be able to do with the roots...
<p>You probably want to call <code>os.stat</code>. Something like</p> <pre><code>stats = [os.stat(os.path.join(root, file)) for file in files] self.ctime_list.append([stat.st_ctime for stat in stats]) self.mtime_list.append([stat.st_mtime for stat in stats]) </code></pre>
python|pandas
1
20,569
64,686,187
Is re-training required on a model pruned using TFMOT?
<p>I am trying to prune a pre-trained model using TFMOT (Tensorflow model Optimization ToolKit). Is it necessary to re-train the pruned model to get a reduced gzip size ? Without re-training, the model gzip size does not reduce</p>
<p>Yes, it is necessary to train the model to apply pruning.</p> <p>Pruning slowly reduces some weights to zero during the training process. This gradual process is necessary to maintain a good accuracy, it can be fine tuned with a specific <a href="https://www.tensorflow.org/model_optimization/api_docs/python/tfmot/sp...
tensorflow|deep-learning
0
20,570
64,797,885
Pandas evalassign method?
<p>I have a series of DataFrame transformations which evaluate certain variable values within a DataFrame and generate new variable values. I could do this as I see it in two ways. I need the most concise and readable method possible as we are going to need to do this operation for about 2000 variables and values.</p> ...
<p>How about <code>np.select</code>:</p> <pre><code>df['C'] = np.select([ df.eval('A &lt; B'),df.eval('A == B'),df.eval('A &gt; B')], [&quot;A less than B&quot;, &quot;A equals B&quot;,&quot;A greater than B&quot;]) </code></pre> <p>which should be a little faster than several <code>loc</code> assig...
pandas|eval
1
20,571
40,054,935
How do you install Tensorflow on Windows?
<p>I am trying to install Tensorflow on Windows.</p> <p>I have Anaconda 4.2.0. I tried running</p> <pre><code>conda create -n tensorflow python=3.5 </code></pre> <p>in my command prompt. This seemed to do something, but I'm not sure what this accomplished. It created a folder within the Anaconda3 program in my username...
<p>The syntax of the command is <code>conda create -n &lt;name_of_new_env&gt; &lt;packages&gt;</code>. As a result, you created a clean environment named <code>tensorflow</code> with only Python 3.5 installed. Since <code>conda search tensorflow</code> returned nothing, you will have to use <code>pip</code> or some oth...
python|tensorflow
2
20,572
69,591,866
tf.keras.model call() method, is it possible to use method call() with labels?
<p>I've been having this question bugging me for some time: Is it possible to use the method <code>call()</code> of <code>tf.keras.model</code> with labels? From what I've seen it is not plausible, but it just strikes me as odd that you are able to train the model using this method but you can't pass it labels like the...
<p>You can pass a list of tensors to the call function, so you could pass the labels. However, this is not in the logic of tensorflow/Keras training. In your example, the basic training routine is train_step. The output tensors are first calculated by the generator and discriminator call function, and then passed to th...
python|tensorflow|keras|generative-adversarial-network
3
20,573
69,416,480
Python Matplotlib: add watermark to subplots
<p>I'm plotting a figure with <code>matplotlib</code>, it is a 2x2 figure. I want to add a watermark to every subplot, how can I do that? I know how to add a watermark to the whole figure, but I didn't manage to do that on the single subplots.</p> <p>Here is my code:</p> <pre><code>import numpy as np import pandas as p...
<p>You can assign <code>.text</code> to each <code>axes</code> like below.</p> <p>Try this:</p> <pre><code># Text Watermark axes[0].text(1.0, 1.0,'Subplot 1 Test watermark', alpha=0.4,rotation=45) axes[1].text(1.0, 1.0,'Subplot 2 Test watermark', alpha=0.4,rotation=45) axes[2].text(1.0, 1.0,'Subplot 3 Test watermark', ...
python|pandas|matplotlib
1
20,574
40,919,132
the android tensorflow demo build error with bazel command
<p>when i run the tensorflow android demo. i have installed the bazel for a long time to build the environment. and then when all tool is done.then run the demo in Android Studio. the gradle console show me this:</p> <p><a href="https://i.stack.imgur.com/1J7Zj.png" rel="nofollow noreferrer">the error image</a></p> <p...
<p>Did you build native libs with these commands?</p> <pre><code>CPU=armeabi-v7a bazel build //tensorflow/examples/android:tensorflow_native_libs --crosstool_top=//external:android/crosstool --cpu=$CPU --host_crosstool_top=@bazel_tools//tools/cpp:toolchain NATIVE_FOLDER=tensorflow/examples/android/libs/$CPU mkdir -p ...
android|tensorflow
1
20,575
41,177,806
Group by multiple columns using multiple keys
<p>This is the structure of my dataframe- </p> <pre><code>Key1 Key2 Value1 Value2 A Alpha 16 12345 B Beta 12 123 A Alpha 15 1456 A Beta 14 12345 </code></pre> <p>I have to club Value 1 and Value 2 basis of unique combination of Key 1 and Key 2. I want my final table as follows:</p> <pre><co...
<p>You must write your own custom aggregation function. <code>agg</code> gets passed every series that is not a grouping column and returns a single value. Here we use <code>set</code> as the aggregator.</p> <pre><code>df.groupby(['Key1', 'Key2']).agg(lambda x: set(x.values)) Key1 Key2 Value1 Value2 0 ...
python|pandas|dataframe
1
20,576
54,166,294
Stack two LSTM layers in Keras dimension mismatch
<p>I want to make an LSTM neural net using Keras which gets as input some length of four features and predicts 10 following values. And I can't manage to set proper input dimensions. <code>X_train</code> is an array of shape (34,5,4) (repeated observations, the sequence of observations, features) <code>y_train</code> i...
<p>If you are stacking two <code>lstm</code> layer, you need to use <code>return_sequence</code> for first layer, which return output for each time step, which will be feed into 2nd <code>lstm</code> layer.</p> <p>Here is <a href="https://stackoverflow.com/questions/54138205/shaping-data-for-lstm-and-feeding-output-of...
python|tensorflow|keras|lstm|recurrent-neural-network
2
20,577
66,302,024
Element wise divide like MATLAB's ./ operator?
<p>I am trying to normalize some Nx3 data. If X is a Nx3 array and D is a Nx1 array, in MATLAB, I can do Y = X./D</p> <p>If I do the following in Python, I get an error</p> <pre><code>X = np.random.randn(100,3) D = np.linalg.norm(X,axis=1) Y = X/D ValueError: operands could not be broadcast together with shapes (1...
<p>From <a href="https://numpy.org/doc/stable/user/basics.broadcasting.html#:%7E:text=The%20term%20broadcasting%20describes%20how,that%20they%20have%20compatible%20shapes.&amp;text=NumPy%20operations%20are%20usually%20done,element%2Dby%2Delement%20basis." rel="nofollow noreferrer">numpy documentation</a> on array broad...
python|numpy
1
20,578
66,293,846
Creating a sequence of dates for each group in Python 3
<p>I have a dataset that consists of multiple stores/retailers:</p> <pre><code>RETAILER VOLUME DISP PRICE store1 12 15 10 store1 10 8 17 store1 12 13 12 ... store2 22 22 30 store2 17 14 22 store2 23 18 18 ... store3 1...
<p>Let us <code>group</code> the dataframe on <code>RETAILER</code> and use <code>cumcount</code> to create sequential counter per <code>RETAILER</code> then <code>map</code> this counter to <code>MonthBegin</code> offset and add a <code>Timestamp('2000-01-01')</code>:</p> <pre><code>c = df.groupby('RETAILER').cumcount...
python|python-3.x|pandas|date|seq
4
20,579
66,282,319
ModuleNotFoundError: No module named 'tensorflow.experimental.numpy'
<p>I ran into an error today that I cannot explain. While trying to implement the tensorflow numpy API, I'm getting the follwing error.</p> <pre><code>Traceback (most recent call last): File &quot;XX.py&quot;, line 2, in &lt;module&gt; import tensorflow.experimental.numpy as tnp ModuleNotFoundError: No module nam...
<p>Works without any issue with Tensorflow 2.4.1</p> <p><code>import tensorflow.experimental.numpy as tnp</code></p>
python-3.x|tensorflow
1
20,580
58,223,192
Prepending total (sum, count) of each column of pandas dataframe to csv file
<p>I am trying to prepend Sum/Count of specific column to the pandas dataframe before writing it to a csv file. I came up with a really delicate solution and wondering if anyone can suggest a better approach. </p> <pre><code>`df.to_csv(out_path, index=False) #reading content of csv file with open(out_path,'r') as my...
<p><strong>Tips:</strong> if you do not supply a path to <code>to_csv</code>, the function will return a string. You can use this string to manually build up your CSV content.</p> <pre><code>summary = df.agg({ 'E': 'count', 'F': 'sum', 'T': 'sum' }) summary = summary.reindex(df.columns).to_frame().T heade...
python|python-3.x|pandas
1
20,581
58,280,514
how to add a new feature base on other columns with same value
<p>How do we add a new column of 'new feature' base on A column and Timeseries.</p> <p>column A : Number 5, 8, 9 have same value</p> <p>Timeseries(hh:mm:ms): 115312, 115313, 115314 have the almost the same value. (maybe we can set within the range of 3 minutes)</p> <p>new feature: so they can put into a group, and ...
<p>Use:</p> <pre><code>#3 minutes threshold N = pd.Timedelta(3 * 60, unit='s') #convert times to timedeltas s = df['TImeseries'].astype(str).str.replace('(\d{2})(\d{2})(\d{2})', r'\1:\2:\3') df['TImeseries'] = pd.to_timedelta(s) #sorting by both columns df = df.sort_values(['A','TImeseries']) #get difference per grou...
pandas
1
20,582
69,287,755
replace entire column if row value is between x in python
<p>I want to replace all column values, if the first row value is between 5 and 10</p> <p>here is my df</p> <pre><code>df = pd.DataFrame(data={'a':[13,5,6,21,9], 'b': [11,5,6,1,2], 'c': [9,28,45,61,31], 'd': [5,16,23,1,23]}) </code></pre> <p>and h...
<p>Since the condition is for columns, make sure it goes to the column positions:</p> <pre><code>df.loc[:, df.loc[0].between(5, 10)] = 'test' df a b c d 0 13 11 test test 1 5 5 test test 2 6 6 test test 3 21 1 test test 4 9 2 test test </code></pre>
python|pandas|replace
1
20,583
69,248,676
Adding boolean column to check whether entry is most recent of their attributes in Postgres SQL table?
<p>Simplified Postgres table looks like this:</p> <pre><code>date attribute 2002-04-14 C 2001-12-07 A 1990-12-19 A 1990-12-20 B 1991-01-29 A 1991-07-01 C 1990-07-25 B 1999-05-13 B 1990-09-25 A </code></pre> <p>We need to add a boolean column checking whether the <code>date</code> is the most recent of e...
<p>You may achieve this in a postgresql query using window functions eg</p> <pre><code>SELECT df.date, df.attribute, df.date = MAX(df.date) OVER (PARTITION BY df.attribute) as desired_col FROM df; </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>date</th> <th>attrib...
sql|pandas|postgresql
1
20,584
69,072,187
How to rearrange/move complete rows with NaN in pandas dataframe?
<p>Consider the following <code>df</code>:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame(np.random.randint(0, 10, (10, 4))) df.iloc[[3, 6, 8], :] = np.nan print(df) 0 1 2 3 0 4.0 1.0 9.0 3.0 1 8.0 1.0 8.0 0.0 2 0.0 6.0 5.0 6.0 3 NaN NaN NaN NaN 4 3.0 9.0 9.0...
<p>Get rows in df1 that are nulls and not nulls</p> <pre><code>not_null = df1[df1.notna().any(1)] nulls = df1[df1.isna().any(1)] </code></pre> <p>Get index labels in df2 for null and not null</p> <pre><code>nulls_positions = df2[df2.all(1)].index not_nulls_positions = df2[~df2.all(1)].index </code></pre> <p>Index df1 w...
python|pandas|dataframe
1
20,585
69,020,802
return _VF.norm(input, p, _dim, keepdim=keepdim) IndexError: Dimension out of range (expected to be in range of [-2, 1], but got 2)
<p>I changed</p> <pre><code>if self.l2_norm: norm = torch.norm(masked_embedding, p=2, dim=1) + 1e-10 masked_embedding = masked_embedding / norm.expand_as(masked_embedding) </code></pre> <p>to</p> <pre><code>if self.l2_norm: masked_embedding = torch.nn.functional.normalize(masked_embedding, p=2.0, dim=2, ep...
<p>To switch to <a href="https://pytorch.org/docs/stable/generated/torch.nn.functional.normalize.html" rel="nofollow noreferrer"><code>F.normalize</code></a>, you need to make sure you're applying it on <code>dim=1</code>:</p> <pre><code>if self.l2_norm: masked_embedding = F.normalize(masked_embedding, p=2.0, dim=1...
python|deep-learning|pytorch|computer-vision|index-error
1
20,586
69,229,182
Creating ONE stacked bar beside ONE normal bar in plotly?
<p>I have this series called <code>'CountryCounts'</code> which is the result of calling <code>.value_counts()</code> on my original dataframe's 'Country' column <code>OGdf['Country']</code>.</p> <pre><code>United States 1234 United Kingdom 332 Canada 111 France ...
<ul> <li>it's simple if you create figure as you describe it. <strong>xaxis</strong> is one of two values</li> <li>rest is then setting parameters to <strong>plotly express bar</strong></li> <li>have hidden legend, you can display if you want but will probably be too long with 60+ countries</li> <li>used your sample ...
pandas|plotly|bar-chart|plotly-python|stacked-chart
1
20,587
69,057,749
calculating average for segments in dataframe
<p>In the the pic below, I have a huge dataframe. For each stroke, the machine renders penetration values then gives zeros. I want to calculate the average for each stroke. for example, the average of [0.762, 0.766] alone, and [0.66, 1.37, 2.11, 2.29] alone and so forth till the end of the Dataframe. Note that the stro...
<pre><code># Generate example data based on your image df = pd.DataFrame({'penetration': [0, 1, 0, 2, 3, 0, 0, 5, 6, 7, 0, 0, 0, 0]}) # Flag rows with nonzero penetration depth df['segment'] = df['penetration'].ne(0) # Flag rows which represent a change from non-segment # to s...
pandas|average|segment
0
20,588
61,022,519
average of one column in multi index dataframe in pandas
<p>I have a multi index dataframe similar to this. </p> <pre><code>arrays = [np.array(['bar', 'bar', 'bar','baz', 'baz', 'baz', 'foo', 'foo', 'foo']), np.array(['one', 'two', 'three', 'one', 'two', 'three','one', 'two','three'])] s = pd.Series(np.random.randn(9), index=arrays) df = pd.DataFrame(np.random.randn(...
<p>Try with <code>transform</code> <code>mean</code> </p> <pre><code>df.groupby(level=0).transform('mean') C1 C2 bar one 0.473968 -0.454709 two 0.473968 -0.454709 three 0.473968 -0.454709 baz one 0.731266 -0.437691 two 0.731266 -0.437691 three 0.731266 -0.437691 fo...
python|pandas|multi-level
0
20,589
71,497,553
how to add rows to a numpy array
<p>I have a numpy array and want to add a row to it and modify one column. This is my array:</p> <pre><code>import numpy as np small_array = np.array ([[[3., 2., 5.], [3., 2., 2.]], [[3., 2., 7.], [3., 2., 5.]]]) </code></pre> <p>Then, firstly...
<p>I believe the operation you are looking for is <code>np.concatenate</code>, which can construct a new array by concatenating two arrays.</p> <p>Simple example, we can add a row of zeroes like this:</p> <pre><code>&gt;&gt;&gt; np.concatenate((small_array, np.zeros((2,1,3))), axis=1) array([[[3., 2., 7.], [3.,...
python|arrays|numpy
1
20,590
71,544,140
Pandas new column based on list of indexes
<p>This is my DataFrame</p> <pre><code>Date, Value 2022-01-01 00:00:00,1.1377 2022-01-01 00:05:00,1.1376 2022-01-01 00:10:00,1.1377 2022-01-01 00:15:00,1.13775 2022-01-01 00:20:00,1.13759 2022-01-01 00:25:00,1.13777 2022-01-01 00:30:00,1.137 2022-01-01 00:35:00,1.137776 2022-01-01 00:40:00,1.13775 2022-01-01 00:45:00,1...
<p>try this:</p> <pre><code>import numpy as np df['extremum'] = np.where(df.index.isin(l),True,False) </code></pre>
python|pandas
1
20,591
42,547,466
pandas dataframe subtraction causing nan
<p>I have a pandas dataframe:</p> <pre><code>&gt;&gt;&gt; X_df.shape Out[35]: (177, 2762) &gt;&gt;&gt; X_df.ix[0:5,1000:1005] Out[40]: 1000 1001 1002 1003 1004 1005 2016-01-04 119.225 nan nan nan nan nan 2016-01-05 119.225 119.189 119.177 119.160 119.203 119.220 2016-0...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sub.html" rel="nofollow noreferrer"><code>sub</code></a> with <code>axis=0</code>:</p> <pre><code>a = (X_df.diff(1,axis=1)) print (a) 1000 1001 1002 1003 1004 1005 2016-01-04 NaN NaN NaN NaN ...
pandas|dataframe|nan|broadcasting
3
20,592
69,673,071
read_excel modifies unexpected data
<p>Is it possible that the pandas function read_excel is modifing data from the excel?</p> <p>It seems it changes for example TRUE to 1 and FALSE to False.</p> <p>I use this code</p> <p>df = pd.read_excel(DEFAULT_PATH_2_XLSX_FILE, , dtype=str)</p>
<p>There is a good explanation to that. Pandas read the raw values of cell not the shown values:</p> <pre><code>df = pd.read_excel('data.xlsx', dtype=str, header=None) print(df) # Output 0 1 0 1 0 # A1, B1 1 1 0 # A2, B2 2 1 0 # A3, B3 </code></pre> <p><a href="https://i.stack.imgur.com/tPbkk.png" rel="no...
pandas
0
20,593
69,762,612
How to remove rows based on next value in a sequence? (pandas)
<p>I have the following dataframe:</p> <pre><code>id date outcome 3 03/05/2019 no 3 29/05/2019 no 3 04/09/2019 no 3 30/10/2019 yes 3 03/05/2020 no 5 03/12/2019 no 5 26/12/2019 no 5 27/01/2020 yes 5 03/06/2020 yes 6 04/05/2019 no 6 27/10/2019 no 6 26/11/2019 yes 6 28/11/2019 ...
<p>Let us do</p> <pre><code>m1 = (df['outcome'] != df['outcome'].shift()).cumsum() out = df.groupby([df['id'],m1]).head(1) id date outcome 0 3 03/05/2019 no 3 3 30/10/2019 yes 4 3 03/05/2020 no 5 5 03/12/2019 no 7 5 27/01/2020 yes 9 6 04/05/2019 no 11...
python|pandas|time-series
2
20,594
43,299,121
How to compare two columns, using python?
<p>I want to compare two continuous home price Sale, and create new column that stores binary variables. </p> <p>This is my process so far:</p> <pre><code>dataset['High'] = dataset['November'].map(lambda x: 1 if x&gt;50000 else 0) </code></pre> <p>This allows me to work on only one column, but I want to compare both...
<p>Similar to @3novak but with casting. One uses <code>pandas</code> for greater efficiency but when you use something like <code>map</code> that needs values expressed as (more expensive) python variables, you may as well just use python lists. Try to use pandas operations that apply to entire series and dataframes in...
python|database|uitableview|pandas|ipython
2
20,595
72,295,295
How do I create a new column of max values of a column(corresponding to specific name) using pandas?
<p>I'm wondering if it is possible to use Pandas to create a new column for the max values of a column (corresponding to different names, so that each name will have a max value).</p> <p>For an example:</p> <pre><code>name value max Alice 1 9 Linda 1 1 Ben 3 5 Alice 4 9 A...
<p>You could use <code>transform</code> or <code>map</code></p> <pre><code>df['max'] = df.groupby('name')['value'].transform('max') </code></pre> <p>or</p> <pre><code>df['max'] = df['name'].map(df.groupby('name')['value'].max()) </code></pre>
python|pandas|csv|max|pandas-loc
2
20,596
72,327,076
datetime column of pandas multiply a number
<p>I have a dataframe with a datetime column in string type, like this:</p> <pre><code>&gt;&gt;&gt; df2 date a b 0 2020/1/1 8.0 5.0 1 2020/1/2 10.0 7.0 2 2020/1/3 6.0 1.0 3 2020/1/4 6.0 3.0 </code></pre> <p>I want use its 'date' column to generate a new index with various length by multiply...
<p>Try this</p> <pre><code>df2 = pd.DataFrame({'date': ['2020/1/1', '2020/1/2', '2020/1/3', '2020/1/4'], 'a': [8.0, 10.0, 6.0, 6.0], 'b': [5.0, 7.0, 1.0, 3.0]}) idx_list = [2,3,1,2] # use repeat df2['date'].repeat(idx_list) 0 2020/1/1 0 2020/1/1 1 2020/1/2 1 202...
python|pandas|datetime
1
20,597
50,347,089
Issue while converting date to datetime format in pandas dataframe
<p>Here is the dataframe. I want the dates here in <code>'%Y-%m-%d %H:%M:%S'</code> format.</p> <pre><code>import pandas as pd df2 = pd.DataFrame([['2017-18','','','','','','','','','','','',''], ['COMPANIES', '01-APR-2017', '01-MAY-2017', '01-JUN-2017', '01-JULY-2017', '01-AUG-2017', '01-SEP-2017...
<p>In my opinion, you should transpose your dataframe and use <code>dateutil.parser</code>, which is more flexible with regards to date input format.</p> <p>Structurally, <code>pandas</code> works best and most intuitively when you have series (or columns) of fixed types.</p> <p><strong>Setup</strong></p> <pre><code...
python|python-2.7|pandas|datetime|dataframe
3
20,598
50,572,497
CNTK/TF LSTM model performance degrades after loading from file
<p>I tried implementing a char-LSTM classification model on a dummy dataset using CNTK and TF and both models achieve 100% accuracy on a perfect dataset (I am not concerned about overfitting for now). </p> <p>However, once the training is done and the models are saved to a file and restored, the models seem to forget ...
<p>The issue is not related to saving/loading LSTM.</p> <p>In Python, when you convert a set to a list, the result is not sorted and different from run to run:</p> <pre><code>In [1]: list(set(['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 's', 'p', 'a', 'm'])) Out[1]: ['s', 'a', 'm', 't', 'h', 'p', 'i', ' '] In ...
python|tensorflow|cntk
1
20,599
45,280,750
Tensorflow, probability of predicted value (ROI)
<p>I've got your same problem, <a href="https://stackoverflow.com/questions/44079685/tensorflow-probability-of-predicted-value/45278544#45278544">Tensorflow, probability of predicted value?</a> but i use the predict 2 and i don't know how to print the percentage(confidence level) of a prediction. My question is, i can ...
<p>I use this script too an i had the same problem. i resolve it with this code :</p> <pre><code>probabilities=y_conv prob = probabilities.eval(feed_dict={x: [imvalue], keep_prob: 1.0}, session=sess) probstr = str(prob) </code></pre> <p>That's give you a percentage like this : 0,000007 or 0,12456, ecc. The number '0,...
python|tensorflow|predict|roi
1