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
353,500
59,803,041
Resize RGB Tensor pytorch
<p>I want to resize a 3-D RBG tensor in pytorch. I know how to resize a 4-D tensor, but unfortunalty this method does not work for 3-D.</p> <p>The input is:</p> <pre><code>#input shape: [3, 100, 200] ---&gt; desired output shape: [3, 80, 120] </code></pre> <p>if I have a 4-D vector it works fine.</p> <pre><code>#...
<p>Thanks to jodag I found the answer:</p> <pre><code># input shape [3, 200, 120] T = T.unsqueeze(0) T = torch.nn.functional.interpolate(T,size=(100,80), mode='bilinear') T = T.squeeze(0) # output shape [3, 100, 80] </code></pre>
python|pytorch|interpolation|tensor
3
353,501
59,810,842
Python pandas, nested loops, creating different lists from rows according to values in another row
<p>I've got an Excel file with 3 rows. The first row is the original text, in the second one there is the corrected version of the text and the third contains the starting point of each sentence.</p> <p>It looks somewhat like this (sorry, I did not know how else to do this):</p> <pre><code> A B C 1...
<p>So, when you input data looks like this:</p> <pre><code>a = 'She is the besst i like here' b = ['', '', '', 'best', 'I', '', 'her'] c = ['x', '', '' , '', 'x', '', ''] df = pd.DataFrame({'A':a.split(), 'B':b, 'C': c}) print(df) </code></pre> <hr> <pre><code> A B C 0 She x 1 is 2...
python|excel|python-3.x|pandas|loops
0
353,502
59,639,343
How to find rows with same time intervals in pandas fataframe
<p>I am locating beaconing activities in DNS records, and I have the pandas dataframe containing parsed DNS records.</p> <p>The structure looks like this:</p> <pre><code> Received_Time Sender_IP Receiver_IP Content 2019-01-01 23:59:54.999 0.0.0.1 1.1.1.1 ... 2019-01-01 23:59:56.999 0.0.0.1 ...
<p>Based from what I understand, you wanna get the interval of each 'Received Time' which can be done by this:</p> <pre><code>df['Beacon_Interval(s)'] = df['Received_Time'].diff().dt.seconds </code></pre> <p>Since we now know the 'Beacon Intervals' we can then count their number of instances using this code:</p> <pr...
python|pandas|dataframe
3
353,503
59,601,541
Concatenate two dataframes and remove duplicate rows based on column value
<p>I have two dataframes. </p> <p><code>df1</code>:</p> <pre><code> Name Symbol ID 0 Jay N/A 372Y105 1 Ray N/A 4446100 2 Faye N/A 484MAA4 3 Maye N/A 504W308 4 Kay N/A 782L107 5 Trey FFF 782L111 </code></pre> <p><code>df2</code>:</p> <pre><code> Name S...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge.html" rel="nofollow noreferrer"><code>merge</code></a> with left join first and then replace missing values in <code>Symbol</code> column by <code>Symbol_</code> column:</p> <pre><code>print (df1.merge(df2, on=['Name','ID'], how='le...
python|pandas
2
353,504
59,589,483
Why should the (huggingface) Transformers library be installed on a virtual environment?
<p>In the <a href="https://github.com/huggingface/transformers#installation" rel="nofollow noreferrer">huggingface github</a> it is written:</p> <blockquote> <p>You should install Transformers in a virtual environment. If you're unfamiliar with Python virtual environments, check out the user guide.</p> <p>Create a vir...
<p>Summing up the comments in a community answer:</p> <p>It's not needed to install huggingface Transformers in a virtual environment, it can be installed just like any other package though there are advantages of using a virtual environment, and is considered a good practice.</p> <ul> <li><p>You want to work in virt...
python|pytorch|huggingface-transformers
4
353,505
59,667,326
Finding Indices for Repeat Sequences in NumPy Array
<p>This is a follow up to a <a href="https://stackoverflow.com/q/59662725/2955541">previous question</a>. If I have a NumPy array <code>[0, 1, 2, 2, 3, 4, 2, 2, 5, 5, 6, 5, 5, 2, 2]</code>, for each repeat sequence (starting at each index), is there a fast way to to then find all matches of that repeat sequence and re...
<p>Here's a way to do so -</p> <pre><code>def group_consec(a, n): idx = consec_repeat_starts(a, n) b = a[idx] sidx = b.argsort() c = b[sidx] cut_idx = np.flatnonzero(np.r_[True, c[:-1]!=c[1:],True]) idx_s = idx[sidx] indices = [idx_s[i:j] for (i,j) in zip(cut_idx[:-1],cut_idx[1:])] retu...
python|numpy
0
353,506
59,706,714
WARNING:tensorflow:Early stopping conditioned on metric `val_binary_accuracy` which is not available
<p>Tensorflow version: 2.0.0</p> <p>gpu: nvidia 2080ti</p> <p>cuda: 10.1</p> <p>cudnn: 7.6.5</p> <p>I am using keras as tensorflow.keras</p> <p>I am using a Conv-LSTM model</p> <pre><code>inputs = Input(shape=(480,3)) conv1 = Conv1D(16, 8, strides =1 , padding='same', activation='relu')(inputs) conv2 = Conv1D(32,...
<p>To solve the EarlyStopping warning, use:</p> <pre><code>earlystop = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=4) # Stop the training when there is no improvement in valid. loss for 4 consecutive epochs. </code></pre> <p>But your error clearly comes from</p> <pre><code>-&gt; use_multiprocessing=use_mu...
tensorflow|keras|conv-neural-network|lstm
0
353,507
59,555,562
Grabbing random samples from pandas dataframe but only one per value
<p>My dataset is an athlete dataset, and one column is the <code>AthleteName</code>. There are 38 observations but some athletes participated more than once, so there are in total 31 athletes. I would like to extract a "random" sample with 31 observations, where there would be all the observations that appear only one...
<p>It sounds like what you want in your "random sample" is:</p> <ul> <li>all of the records for athletes that only occur once in the data</li> <li>a single record for each athlete that occurs two or more times in the data, chosen at random</li> </ul> <p>To do this, first we build a dataframe and indicate whether a re...
python|pandas
0
353,508
59,565,556
How to import values from excel with pandas into tkinter faster?
<p>guys! How are you? I have this code below and I'm having this trouble with the <code>insertData</code> function. This function is used to enter values from an excel spreadsheet into the tkinter treeview using Pandas. It's almost all right, but it's too slow and I don't know how to fix it. If anyone could help me, I'...
<p>How many times do you want to open a excel file for reading?</p> <pre class="lang-py prettyprint-override"><code>def insertData(): for m in range(rowCount): self.dataValues = pd.read_excel(r'Registros.xlsx',str(self.cmb.get()), skip_blank_lines=True, skiprows=0) for l in self.dataValues: dataVector...
python|excel|pandas|tkinter|openpyxl
0
353,509
59,725,840
How to replace all non-NaN entries of a dataframe with a Series?
<p>I know that you can use <code>pandas.DataFrame.fillna</code> to replace all null values with a Series, but is there an easy way to replace all non-null values with a Series?</p> <p>Alternatively, I have seen <code>df.loc[~df.isnull()]</code> for replacing all null values with a single value, but again - is there a ...
<p>You can do it as below. </p> <p>Since you have not provided a df, I am using my own df (input &amp; output shown). 'f' is the series that has been created.</p> <pre><code>a = df.loc[~df['Age'].isnull()] b = df.loc[~df['Age'].isnull()].index f= pd.Series([i for i in range(1,12)], index=b) df.loc[~df['Age'].isnull()...
python|pandas|dataframe
2
353,510
59,852,411
How to fill in missing dates and values in a Pandas DataFrame?
<p>so the data set I am using is only business days but I want to change the date index such that it reflects every calendar day. When I use reindex and have to use reindex(), I am unsure how to use 'fill value' field of reindex to inherit the value above. </p> <pre><code>import pandas as pd idx = pd.date_range("12/1...
<p>You were close! You just need to pass the index you want to reindex on (<code>idx</code> in this case) as a parameter to the reindex method, and then you can set the <code>method</code> parameter to 'ffill' to propagate the last valid value forward. </p> <pre><code>idx = pd.date_range("12/18/2019","12/24/2019") df...
python|pandas|time-series|dataset
2
353,511
59,536,327
Rename columns with pandas
<p>I am attempting to change column names with the following code:</p> <pre><code>import pandas as pd jeopardy = pd.read_csv('/Users/adamshaw/Desktop/Coding/jeopardy_starting/jeopardy.csv') jeopardy = jeopardy.rename(columns={' Air Date': 'Air_Date', ' Round': 'Round'}, inplace=T...
<p>You are using the <code>inplace=True</code> option when renaming your columns. This returns nothing (<code>None</code> type) which you are assigning to the <code>jeopardy</code> variable.</p> <p>Try removing the <code>inplace=True</code> or don't reassign it to <code>jeopardy</code>. So either</p> <pre><code>jeopa...
python|pandas|dataframe
0
353,512
59,709,094
Read n tables in csv file to separate pandas DataFrames
<p>I have a single .csv file with four tables, each a different financial statement four Southwest Airlines from 2001-1986. I know I could separate each table into separate files, but they are initially downloaded as one.</p> <p>I would like to read each table to its own pandas DataFrame for analysis.Here is a subset ...
<p>What you want to do if far beyond what <code>read_csv</code> can do. If fact you input file struct can be modeled as:</p> <pre class="lang-none prettyprint-override"><code>REPEAT: Dataframe name Header line REPEAT: Data line BLANK LINE OR END OF FILE </code></pre> <p>IMHO, the simplest way i...
python|pandas|file|csv|dataframe
1
353,513
59,566,168
specifying a limit for fillna has not been implemented yet
<p>I want to implement a fillna method over a pandas dataframes with the method='bfill' and a limit</p> <pre><code>labeled_features = final_feat.merge(failures, on=['datetime', 'machineID'], how='left') print(type(labeled_features)) labeled_features = labeled_features.bfill(limit=7) # fill backward up to 24h labeled_f...
<p>Was facing the same issue. Apparently it's due to the fact that 'failure' column is of DataType Categorical. Change the Datatype using:</p> <p><code>labeled_features.failure = labeled_features.failure.astype(str)</code></p> <p>then execute below code:</p> <p><code>labeled_features.failure = labeled_features.fail...
python|pandas|fillna
1
353,514
59,801,341
how to use np.max for empty numpy array without ValueError: zero-size array to reduction operation maximum which has no identity
<p>I get a case that when I tried to use <code>np.max()</code> in an empty numpy array it will report such error messages.</p> <pre><code># values is an empty numpy array here max_val = np.max(values) </code></pre> <blockquote> <p>ValueError: zero-size array to reduction operation maximum which has no identity</p> ...
<pre><code>In [3]: np.max([]) --------------------------------------------------------------------------- ... ValueError: zero-size array to reduction operation maximum which has no identity </code></pre> <p>But check the docs. In newer <c...
python|arrays|python-3.x|numpy
17
353,515
59,700,441
I do not understand when to use a Pandas Series and when to use a Pandas Single Column Dataframe
<p>I’ve done quite a lot of searching around and seen many posts that explain the differences but I have not come across clear use cases. I do understand the differences in general but I would like to know why I should learn how to use Series when it seems that a single column Dataframe might perform everything a Serie...
<p>Here are my short explanations:</p> <ul> <li><p><code>Series</code>: Series are for one-dimensional data, just like <code>list</code>s with a lot of functions.</p></li> <li><p><code>DataFrame</code>: DataFrames are for multi-dimensional data, just like nested <code>list</code>s with a lot of functions.</p></li> </u...
python|pandas
5
353,516
59,689,669
numpy arange function build array size error
<p>When I use numpy arange function to build a numpy array, the size is not right when use shape to check. For example, if I build an array: np.arange(-5,6,1), the shape is (11,). However, when I build array:np.arange(-0.001,0.0011,0.0001), the shape is (22,)</p> <p>The shape find with np.array.shape</p>
<p>It looks like when you print the array, you get this -</p> <pre><code>array([-1.00000000e-03, -9.00000000e-04, -8.00000000e-04, -7.00000000e-04, -6.00000000e-04, -5.00000000e-04, -4.00000000e-04, -3.00000000e-04, -2.00000000e-04, -1.00000000e-04, 4.33680869e-19, 1.00000000e-04, 2.00000000e-0...
python|arrays|numpy|methods|shapes
0
353,517
59,698,345
How to calculate max values between two rows of Particular Column
<blockquote> <p>I am trying to calculate max and min values between High and Low from index 9:00 to 9:30, the problem I am facing is my loop including second row of previous iteration each time.you can see in the output , in the second iteration it calculated the max/min between second and third row of High and Low C...
<pre><code>df['max'] = df.High.rolling(2).max() df['min'] = df.Low.rolling(2).min() </code></pre> <p>This should work. </p> <p>If you want to drop the NaN you can use the following command</p> <pre><code>df.dropna(inplace=True) </code></pre>
python-3.x|pandas
0
353,518
59,646,238
in a dataframe column values are like 6.680713e+07 how can i remove e+ from this value in pandas dataframe
<pre><code> CustomerID SaleQuarter NumOfBills PurchaseValue 0 1 101920 31197887.0 0 2 10 6268.5 13 1 1 1527.5 13 2 2 173.5 13 3 3 958.0 13 4 4 ...
<p>You can try setting the display options:</p> <pre><code>import pandas as pd import numpy as np np.random.seed(42) pd.options.display.float_format = '{:,.20f}'.format df = pd.DataFrame(np.random.rand(10, 3) / 1e6) print(df) </code></pre> <p>Result before:</p> <pre><code> 0 1 ...
pandas|dataframe
2
353,519
59,586,521
Problem merging strings in pandas dataframe - encoding issue?
<p>I've been trying to merge strings in Pandas; most of them work, but some don't match, despite appearing to be exactly the same in the excel files.</p> <pre><code>data looks like: File Name: company 1.pdf; Security Name: Series A Common File Name: company 2.pdf; Security Name: Series B Common ra1['File Name'] = ra1...
<p>Just adding as an answer,</p> <p>to match <em>all</em> white space such as <code>a b c</code> we can leverage a regular expression </p> <h3><code>\s+</code> matches any whitespace character (equal to <code>[\r\n\t\f\v ])</code></h3> <h3><code>+</code> Quantifier — Matches between one and unlimited times, a...
python|string|pandas|encoding|merge
0
353,520
32,560,932
How to customize a scatter matrix to see all titles?
<p>I'm running this code to build a scatter matrix. The problem is that the plot looks like a mess, because it's impossible to see the names of variables (see image below). Is there any way to change the orientation of titles and switch off the ticks with numbers?</p> <pre><code>import pandas as pd import matplotlib.p...
<p>As a minimal <code>scatter_matrix</code> example to switch off axis ticks and rotate the labels,</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import pandas as pd try: from pandas.tools.plotting import scatter_matrix except ImportError: #Fix suggested by @Raimundo Jimenez as tools is depr...
python|pandas|matplotlib
11
353,521
32,207,434
How to group timestamps by labels?
<p>I have dataframe(Series) indexed by DatetimeIndex</p> <pre><code> tag 2015-08-21 16:32:00 stationary 2015-08-21 16:33:00 automotive 2015-08-21 16:34:00 automotive 2015-08-21 17:27:00 stationary 2015-08-21 17:28:00 stationary 2015-08-21 17:29:00 stationary 2015-08-21 17:30:00 stationary 2015-08-21...
<p>You can use <code>groupby</code> and <code>apply</code> scheme.</p> <pre><code>def func(group): return pd.Series({'Start': group.index[0], 'End': group.index[-1], 'Tag': group['tag'].values[0]}) df.groupby((df.shift(1) != df).cumsum()['tag'], as_index=False).apply(func) End S...
python|pandas
3
353,522
32,568,012
'Series' objects are mutable, thus they cannot be hashed error calling to_csv
<p>I have a large Dataframe (5 days with one value per second, several columns) of which I'd like to save 2 columns in a csv file with python pandas df.to_csv module.</p> <p>I tried different ways but always get the error message:</p> <p>'Series' objects are mutable, thus they cannot be hashed</p> <p>which I found a...
<p>Your error comes about because you passed a tuple of Series rather than a tuple of column names/strings:</p> <pre><code>df.to_csv('alldatcorr.csv',sep='\t',cols=(df.CO2abs,df.CO2corr)) </code></pre> <p>So you found that this worked:</p> <pre><code>df.to_csv('corr2.csv',sep='\t',cols=('CO2abs','CO2corr')) </code><...
python|csv|pandas|immutability
5
353,523
32,432,405
Pandas data frame's type
<p>Do I understand correctly that pandas data frame is of the type Series, while data type stored in the data frame might be of the type array, list, dictionary, etc.? Is there any good tutorial with examples that explain this staff?</p>
<p>Speaking in panda-terms, a dataframe is a dictionary of Series objects. So to say, each column is a Series. Each series can contain any kind of object.</p> <p>Aside of the online resources mentioned in the other answer, <a href="http://shop.oreilly.com/product/0636920023784.do" rel="nofollow">this</a> is imo the be...
python|pandas|dataframe
1
353,524
32,322,281
Numpy matrix binarization using only one expression
<p>I am looking for a way to binarize numpy N-d array based on the threshold using only one expression. So I have something like this:</p> <pre><code>np.random.seed(0) np.set_printoptions(precision=3) a = np.random.rand(4, 4) threshold, upper, lower = 0.5, 1, 0 </code></pre> <p>a is now:</p> <pre><code>array([[ 0.02...
<p>We may consider <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="noreferrer"><code>np.where</code></a>:</p> <pre><code>np.where(a&gt;threshold, upper, lower) Out[6]: array([[0, 1, 1, 1], [1, 1, 0, 1], [0, 1, 0, 1], [1, 0, 0, 1]]) </code></pre>
python|numpy
48
353,525
32,475,271
Python & Pandas: Create a 3d histogram from 2 columns of a dataframe
<p>In my data frame, I have <code>df['incre']</code> and <code>df['incre_reverse']</code>, the data is like this (the last 2 column): <a href="https://i.stack.imgur.com/Pk20f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pk20f.png" alt="enter image description here"></a></p> <p>Now, I want plot a ...
<p>It seems you have some values that are very common.</p> <p>To make things look more ballanced consider plotting the histogram using the log of your values with NumPy <code>np.log()</code>.</p>
python|pandas
1
353,526
32,546,883
Singular and Plural words matching with Pandas
<p>This question is an extension to my previous question <a href="https://stackoverflow.com/questions/32311008/multiple-phrases-matching-python-pandas">Multiple Phrases Matching Python Pandas</a>. Although I had figured out the way after an answer to solve my problem, some typical problem in singular and plural words a...
<p>consider using a stemmer :) <a href="http://www.nltk.org/howto/stem.html" rel="nofollow">http://www.nltk.org/howto/stem.html</a></p> <p>taken straight out of their page:</p> <pre><code> from nltk.stem.snowball import SnowballStemmer stemmer = SnowballStemmer("english") stemmer2 = SnowballStemmer("englis...
python|regex|pandas
2
353,527
32,425,334
Splitting a string in a Python DataFrame
<p>I have a DataFrame in Python with a column with names (such as Joseph Haydn, Wolfgang Amadeus Mozart, Antonio Salieri and so forth). </p> <p>I want to get a new column with the last names: Haydn, Mozart, Salieri and so forth. </p> <p>I know how to split a string, but I could not find a way to apply it to a series,...
<p>if you have:</p> <pre><code>import pandas data = pandas.DataFrame({"composers": [ "Joseph Haydn", "Wolfgang Amadeus Mozart", "Antonio Salieri", "Eumir Deodato"]}) </code></pre> <p>assuming you want only the first name (and not the middle name like Amadeus):</p> <pre><code>data.composers.str.spl...
python|string|pandas|dataframe
26
353,528
32,562,832
Python Pandas groupby 15Minutes on a column that is not the index
<p>I have a dataframe with Transactions which have a trading_date, a delivery_date and a volume. the Trading_Date is the index.</p> <pre><code> Trading_Date Delivery_Date Volume 01.01.2015 22:15 01.01.2015 23:00 15 01.01.2015 22:18 01.01.2015 23:00 10 01.01.2015 22:25 02.01.2015 00:30 5 01.01...
<p>I have resolved it like this:</p> <pre><code> dfA['help'] = dfA.index dfA['Timediff'] = dfA['help']- dfA['Delivery_Date'] dfA['Timediff2'] = dfA['Timediff'].apply(lambda x: x / np.timedelta64(1,'m')) # converts Timediff in minutely value dfA['Time15M'] = dfA['Timediff2']/15 dfA['Time15M'] = ...
python|pandas|time-series|dataframe|grouping
0
353,529
32,422,764
convert array of tuples to 2 dimensional array
<p>I have an array of tuples loaded from a csv file using <code>np.genfromtxt()</code> function.</p> <pre><code>import numpy as np import re from matplotlib.dates import strpdate2num def convert_string_to_bigint(x): p = re.compile(r'(\d{4})/(\d{1,2})/(\d{1,2}) (\d{1,2}):(\d{2}):\d{2}') m = p.findall(x) l =...
<p>In <code>convert_string_to_bigint</code>, change </p> <pre><code>return long("".join(l)) </code></pre> <p>to </p> <pre><code>return float("".join(l)) </code></pre> <p>Then <code>genfromtxt</code> will recognize all values as floats, and return a 2D array of float dtype:</p> <pre><code>In [23]: np.genfromtxt ('s...
python|arrays|numpy|tuples
2
353,530
32,242,446
try and except in while-loop python
<p>I am working on a live plot of incoming data. The data comes from a spectrum analyser and sometimes I get faulty data. Faulty in the meaning that there are on some positions letters instead of numbers. </p> <p>I save the incoming data as a list and then I convert it to a <code>numpy.array</code> with</p> <pre><cod...
<p>I would recommend putting in the <code>try/except</code> clause only what you expect to raise an exception. The code would be more clear and you would be sure that the exception is raised by what you expect to raise it. Something like:</p> <pre><code>try: trace = np.array(trace, np.float) except ValueError: ...
python|numpy|matplotlib|plot|try-except
0
353,531
40,635,373
Pivot Table and Counting
<p>I have a data set indicating who has shopped at which stores.</p> <pre><code>ID Store 1 C 1 A 2 A 2 B 3 A 3 B 3 C </code></pre> <p>Can I use a pivot table to determine the frequency of a shopper going to other stores? I'm thinking like a 3X3 matrix where the columns and rows would indicate h...
<p>You can create a conditional table of <code>ID</code> and <code>Store</code> with <code>pd.crosstab()</code> and then calculate the matrix product of its transpose and itself, which should produce what you need:</p> <pre><code>mat = pd.crosstab(df.ID, df.Store) mat.T.dot(mat) #Store A B C #Store ...
python|pandas|pivot-table
3
353,532
40,668,795
Populate rows of empty matrix from another matrix by index array in numpy
<p>I have an array:</p> <pre><code>arr = np.array([[ 5.1, 3.5, 1.4, 0.2], [ 4.6, 3.1, 1.5, 0.2], [ 5. , 3.6, 1.4, 0.2]]) </code></pre> <p>and an index array:</p> <pre><code>index_arr = np.array([True, False, False, True, True]) </code></pre> <p>and an empty matrix of zeros:<...
<p>You can use logical vector indexing for subsetting and assignment:</p> <pre><code>output[index_arr] = arr #array([[ 5.1, 3.5, 1.4, 0.2], # [ 0. , 0. , 0. , 0. ], # [ 0. , 0. , 0. , 0. ], # [ 4.6, 3.1, 1.5, 0.2], # [ 5. , 3.6, 1.4, 0.2]]) </code></pre>
python|arrays|numpy
3
353,533
40,739,639
Add a summary of accuracy of the whole train/test dataset in Tensorflow
<p>I am trying to use Tensorboard to visualize my training procedure. My purpose is, when every epoch completed, I would like to test the network's accuracy using the whole validation dataset, and store this accuracy result into a summary file, so that I can visualize it in Tensorboard.</p> <p>I know Tensorflow has <c...
<p>Define a <code>tf.scalar_summary</code> that accepts a placeholder:</p> <pre><code>accuracy_value_ = tf.placeholder(tf.float32, shape=()) accuracy_summary = tf.scalar_summary('accuracy', accuracy_value_) </code></pre> <p>Then calculate the accuracy for the whole dataset (define a routine that calculates the accura...
tensorflow
9
353,534
40,533,617
finding the earliest occurrence in Python
<p>I'm running into trouble with this: I need to find the first time a user clicks on an email (variable sending) and put a one in that respective row when it occurs. </p> <p>The dataset has several thousand users (hashed) who click a part of an email in a newsletter. I tried to group them by the sending, hash and the...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>apply</code></a> where com...
python|pandas
4
353,535
40,657,094
Add constant value column that changes half way down to pandas dataframe
<p>I have the list:</p> <pre><code>[['abc', 1, 2, 3], ['bfg', 4, 5, 6], ['abc', 7, 8, 9], ['bfg', 10, 11, 12]] </code></pre> <p>And I make it into a pandas DataFrame, which returns (after adding a column with the color <code>lst[4] = 'blue'</code>):</p> <pre><code> 0 1 2 3 4 0 abc 1 2 3 blue 1 ...
<p>Solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_records.html" rel="nofollow noreferrer"><code>DataFrame.from_records</code></a>:</p> <pre><code>lst = [['abc', 1, 2, 3], ['bfg', 4, 5, 6], ['abc', 7, 8, 9], ['bfg', 10, 11, 12]] df = pd.DataFrame.from_records(lst) pri...
python|pandas|dataframe
2
353,536
40,408,366
Pandas sorting within a group results in duplicated index
<p>I have a pandas DataFrame in the following format:</p> <pre><code> C1 C2 A 0 1.764052 0.400157 1 0.978738 2.240893 2 1.867558 -0.977278 3 0.950088 -0.151357 4 -0.103219 0.410599 C 0 0.144044 1.454274 1 0.761038 0.121675 2 0.443863 0.333674 3 1.494079 -0.205158 4 0.313...
<p>You need add parameter <code>group_keys=False</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a>:</p> <pre><code>a = df.groupby(level=0, group_keys=False).apply(lambda x: x.sort_values('C1')) print (a) ...
python|sorting|pandas|group-by
4
353,537
40,404,409
Reshaping Pandas DataFrame
<p>I have the following DataFrame</p> <pre><code> A 0 2012-01-13 10:00:06 1 2012-01-13 11:09:04 2 2012-01-13 12:07:05 3 2012-01-13 13:03:04 4 2012-01-16 10:00:10 5 2012-01-16 11:09:04 6 2012-01-16 12:01:05 7 2012-01-16 13:09:04 8 2012-01-17 10:01:04 9 2012-01-17 11:05:06 10 2012-01-17 12:01:05 11 2...
<p>I think you need create column of days by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.day.html" rel="nofollow noreferrer"><code>dt.day</code></a>, then create groups by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="n...
python|pandas
5
353,538
40,776,967
How to find initial guess for leastsq function in Python?
<p>I have a dataset for which I need to fit the plot. I am using leastsq() for fitting. However, currently I need to give initial guess values manually which is really affecting the fitting. Is there any way to first calculate the initial guess values which I can pass in leastsq()?</p>
<p>No, you can't really calculate an initial guess.<br> You'll just have to make an educated guess, and that really depends on your data and model.</p> <p>If the initial guess affects the fitting, there is likely something else going on; you're probably getting stuck in local minima. Your model may be too complex, or ...
python|numpy|least-squares|data-science
1
353,539
40,344,047
Pandas 0.18 vs 0.12 performance
<p>I have this code:</p> <pre><code>from datetime import date, timedelta from time import time import pandas as pd sizes = [500] base_date = date(2016,10,31) for n in sizes: dates = [base_date - timedelta(days = x) for x in range(1, n, 1)] dates_df = pd.DataFrame({'DATE' : dates, 'key' : 1}) identifiers...
<p>In later versions of pandas, iloc is preferred and more optimized than ix, that will be deprecated soon. Try porting your code with iloc and check the performance. </p>
python|performance|pandas|dataframe
0
353,540
40,535,163
Python: transform data set
<p>I have the following data set</p> <pre><code> id type value 0 1 A 10 1 1 C 120 2 2 B 20 3 2 C 40 4 3 A 10 5 3 B 50 </code></pre> <p>I want in python to transform it to be like <code>(1,A,10,C,120) (2,B...
<p>You can use:</p> <pre><code>L = df.groupby('id').apply(lambda x: tuple([x['id'].iat[0]] + x[['type','value']].values.flatten().tolist())) .tolist() print (L) [(1, 'A', 10, 'C', 120), (2, 'B', 20, 'C', 40), (3, 'A', 10, 'B', 50)] </code></pre>
python|python-2.7|pandas
2
353,541
40,712,715
Pandas select test dataframe columns using training dataframe columns
<p>I have a training dataframe that has been cleaned and has a subset of variables that the original test dataframe had. I'd like to create a new test dataframe that retains only the columns the training dataframe has.</p> <p>For example, </p> <pre><code>train.columns=['A','D','E','G'] test.columns=['A','B','C','D',...
<p>Assuming each <code>DataFrame</code> has columns with the same names, then you can simply select the columns from the test <code>DataFrame</code> using the <code>DataFrame.columns</code> property of the training <code>DataFrame</code> and the <code>[]</code> syntax.</p> <p>Here is a working example:</p> <pre><code...
python|pandas
4
353,542
40,397,556
Pandas CONCAT() with merged columns in Creation
<p>I am trying to create a very large dataframe, made up of one column from many smaller dataframes (renamed to the dataframe name). I am using CONCAT() and looping through dictionary values which represent dataframes, and looping over index values, to create the large dataframe. The CONCAT() join_axes is the common i...
<p>I think you need:</p> <pre><code>df = pd.concat([df1, df2]) </code></pre> <p>Or if have duplicates in columns use <code>groupby</code> where if some values are overlapping then are summed:</p> <pre><code>print (df.groupby(level=0, axis=1).sum()) </code></pre> <p>Sample:</p> <pre><code>df1 = pd.DataFrame({'A':[5...
python|pandas|concat
2
353,543
40,699,659
Python Numbers mysteriously being rounded on comparison
<p>I was having some problem with Numpy arrays and I stumbled across it, and it confused me.</p> <p>I'm trying to compare 2 parts of arrays using <code>array_equal</code></p> <pre><code>np.array_equal(updated_image_values[j][k],np.array(initial_means[i])) </code></pre> <p>This is returning <code>False</code> when th...
<p>I assume that <code>updated_image_values</code> has had some operations done on it. And what classes are the numbers?<br> My guess is that what you're seeing isn't "rounding", it's got something to do with the <code>__str__</code> or <code>__repr__</code> functions of the classes. The fact that you're seeing 0.90980...
python|arrays|numpy
0
353,544
40,393,203
How to add a hierarchically-named column to a Pandas DataFrame
<p>I have an empty DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame() </code></pre> <p>I want to add a hierarchically-named column. I tried this:</p> <pre><code>df['foo', 'bar'] = [1,2,3] </code></pre> <p>But it gives a column whose name is a tuple:</p> <pre><code> (foo, bar) 0 1 1 ...
<p>If you are looking to build the multi-index <code>DF</code> one column at a time, you could append the frames and drop the <code>Nan's</code> introduced leaving you with the desired multi-index <code>DF</code> as shown:</p> <p><em><strong>Demo:</strong></em></p> <pre><code>df = pd.DataFrame() df['foo', 'bar'] = [1,2...
python|pandas|dataframe|hierarchical-data|multi-index
2
353,545
40,580,890
Pandas: changing filtered dataframe columns
<p>I'm trying to pass in a filtered dataframe into a function that is meant to manipulate some columns (again using filtering). I know this came up so many times already on SO, but even after reading the docs and other related questions, I have still problems getting my head around. I think I just need a working exampl...
<p>I think you should use the function .ix</p> <p>For example:</p> <pre><code>df1.ix[df1['a']&lt;=2, 'b'] = 0 </code></pre> <p>Is that you want to achieve?</p>
python|pandas
0
353,546
40,392,885
Store Slice Index as Object
<p>Say I have a list of lists of lists etc... of some depth:</p> <pre><code>ExampleNestedObject = numpy.ones(shape = (3,3,3,3,3)) </code></pre> <p>In general I can get an element by writing:</p> <pre><code>#Let: #a, b, c, d, e -&gt; are integers print ExampleNestedObject[a][b][c][d][e] #numpy also happens to allow...
<p>The trick is to think of an index object as a tuple of slice objects.</p> <p>Example1:</p> <pre><code>Object[1,2,:] == Object[(1,2,slice(None,None,None))] </code></pre> <p>Example2:</p> <pre><code>WantedSliceObject = (1,2,slice(None,None,None), 4,5) Object[1,2,:,4,5] == Object[WantedSliceObject] </code></pre> <...
python|numpy|indexing|nested
6
353,547
40,602,269
How to use numpy to get the cumulative count by unique values in linear time?
<p>Consider the following lists <code>short_list</code> and <code>long_list</code></p> <pre><code>short_list = list('aaabaaacaaadaaac') np.random.seed([3,1415]) long_list = pd.DataFrame( np.random.choice(list(ascii_letters), (10000, 2)) ).sum(1).tolist() </code></pre> <p>How do I calculate th...
<p>Here's a vectorized approach using custom grouped range creating function and <code>np.unique</code> for getting the counts -</p> <pre><code>def grp_range(a): idx = a.cumsum() id_arr = np.ones(idx[-1],dtype=int) id_arr[0] = 0 id_arr[idx[:-1]] = -a[:-1]+1 return id_arr.cumsum() count = np.unique...
python|pandas|numpy
6
353,548
40,650,913
Dataframe from complex data structure
<p>Say I need to have data stored as follows:</p> <pre><code>[[[{}][{}]]] </code></pre> <p>or a list of lists of two lists of dictionaries</p> <p>where:</p> <p><code>{}</code>: dictionaries containing data from individual frames observing an event. (There are two observers/stations, hence two dictionaries.)</p> <p...
<p>I don't think you can really avoid using a loop here, unless you want to invoke jq via sh. See <a href="https://stackoverflow.com/questions/21494030/create-a-pandas-dataframe-from-deeply-nested-json">this answer</a></p> <p>Anyways, using your full sample, I managed to parse it into a multiindexed dataframe, which I...
python|pandas|dataframe
1
353,549
40,594,514
How can I "sparsify" on two values?
<p>consider the the pandas series <code>s</code></p> <pre><code>n = 1000 s = pd.Series([0] * n + [1] * n, dtype=int) s.memory_usage() 8080 </code></pre> <p>I can "sparsify" this by using <code>to_sparse</code></p> <pre><code>s.to_sparse(fill_value=0).memory_usage() 4080 </code></pre> <p>But I only have 2 types o...
<p>Since you tagged this with <code>scipy</code>, I'll show you what a <code>scipy.sparse</code> matrix is like:</p> <pre><code>In [31]: n=100 In [32]: arr=np.array([[0]*n+[1]*n],int) In [33]: M=sparse.csr_matrix(arr) In [34]: M.data Out[34]: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,...
python|pandas|numpy|scipy|sparse-matrix
3
353,550
40,534,273
Why am I not able to drop values within columns on pandas using python3?
<p>I have a DataFrame (df) with various columns. In this assignment I have to find the difference between summer gold medals and winter gold medals, relative to total medals, for each country using stats about the olympics. I must only include countries which have at least one gold medal. I am trying to use dropna() t...
<p>You are required to pass an axis e.g. axis=1 into the drop function. An axis of 0 => row, and 1 => column. 0 seems to be the default.</p> <p><a href="https://i.stack.imgur.com/OSCFH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OSCFH.jpg" alt="enter image description here"></a></p> <p>As you c...
python|pandas
-1
353,551
18,686,637
How can I create a matrix, or convert a 2D array into matrix in Python?
<p>I wish to be able to extract a row or a column from a 2D array in Python such that it preserves the 2D shape and can be used for matrix multiplication. However, I cannot find in the <a href="http://docs.scipy.org/doc/numpy/reference/routines.array-creation.html" rel="nofollow">documentation</a> how can this best be ...
<p>You could use <code>np.matrix</code> directly:</p> <pre><code>&gt;&gt;&gt; a = np.zeros(shape=(6,6)) &gt;&gt;&gt; ma = np.matrix(a) &gt;&gt;&gt; ma matrix([[ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.], ...
python|arrays|numpy|matrix|matrix-multiplication
2
353,552
18,495,947
Python Pandas and NumPy.where behavior with mismatching numbers of rows
<p>I'm using Pandas 0.8.1 in all of the examples below, but I can confirm that the same examples work the same way for me when I use Pandas 0.11. </p> <p>Solutions that rely on changing Pandas versions to a newer version aren't applicable for my current problem (although please feel free to add <em>comments</em> (not ...
<p>this is expected; you are assigning a series to a DataFrame column. it is aligned so shorter (or longer) is irrelevant. the index is matched up and those values are taken. the reason straight numpy array only works if the length is the same is simple; Alignment isn't possible so it must be the same length.</p> <p>t...
python|numpy|pandas|where
4
353,553
61,664,204
Determine name of file with Pandas to csv
<p>So I have a script capable of finding the z-score for different dataframe. </p> <p>I'd like my script to save my files (if I'm applying it to multiple dataframe) under specific name depending on name of the dataframe I'm applying the script to. </p> <p>Here's my dataframe:</p> <pre><code>data = pd.DataFrame({'col...
<p>You want the name of the variable? For various complicated reasons related to the python object model, you cannot* do that (* easiliy, or without catches).</p> <p>Much clearer and more reliable to to just pass a string to your class:</p> <pre><code>import numpy as np import pandas as pd from statistics import mean...
python|pandas|csv
0
353,554
61,624,109
Converting State IDs to Time Zones
<p>I would like to create a column of time zones from a column of state abbreviations from a pandas dataframe. <a href="https://stackoverflow.com/questions/47661041/how-to-get-the-local-timezone-given-time-and-state-info">I used basically the exact same code as was discussed in this previous question from Stack Overflo...
<p>make sure df['Event_State'] is string not None value</p>
python-3.x|pandas
0
353,555
62,032,336
Create columns from pandas groupby
<p>I'm trying to calculate the rating difference by gender for each movie. (IMDB dataset)<br> This is the groupby method i've used:</p> <pre class="lang-py prettyprint-override"><code>df.groupby(['movie title', 'gender'])['rating'].mean() </code></pre> <p>And the head:</p> <p><a href="https://i.stack.imgur.com/HFoO7...
<p>You can <code>unstack</code>:</p> <pre><code>(df.groupby(['movie title', 'gender']) ['rating'].mean() .unstack() .reset_index() # turn `movie_title` into a normal column. ) </code></pre> <p>And you should get <code>F,M</code> as column names. Rename as you wish.</p>
python|pandas|pandas-groupby
2
353,556
61,796,697
google.protobuf.text_format.ParseError: 2:1 : '%%writefile {model_pipline}': Expected identifier or number, got %
<p>the below is the error I faced, the <strong>training code</strong> I used is:</p> <pre><code>!python3 /content/model_main.py \ --pipeline_config_path=/content/ssd_mobilenet_v2_coco.config \ --model_dir=training/ </code></pre> <p><strong>error:</strong></p> <pre><code> Traceback (most recent call last): File "/c...
<p>First, please check <a href="https://github.com/tensorflow/models/issues/1897" rel="nofollow noreferrer">this git issue</a> which offer many answers.</p> <p>I solved it by editing the <code>pipeline.config</code> file with the ubuntu built-in text editor instead of LibreOffice. LibreOffice changed the format from <c...
python|tensorflow|config
0
353,557
61,846,131
Reconstituting consumed sequence mask in Keras LSTM autoencoder
<p>I'm trying to get my head around sequence-to-sequence autoencoding (LSTM) for inputs of varying number of time steps in Keras. I'm particularly interested in using such a network to encode variable-length sequences as a fixed vector (not using return_sequences=True for the LSTM encoder).</p> <p>As an example, just...
<p>Here's what seems to be working for me, although I'd love to hear other solutions; likely more elegant than this...</p> <p>I created a custom layer, Reapply_Masking, adapted from Keras's default masking layer. It takes two input layers: Input[0] is the layer to which you're applying the mask (in my example, the R...
keras|lstm|tensorflow2.0
1
353,558
61,984,970
Combing two columns from two different data frames to remove missing values in Pandas
<p>I am working on the Titanic dataset as my first project. To impute missing values of the variable 'Age', I had run a linear regression model. Now, I have 2 dataframes as follows - </p> <pre><code>train_data.tail() Survived Pclass Sex Age SibSp Parch Fare Embarked 886 0 2 m...
<p>Try fillna,</p> <pre><code>train_data['Age'] = train_data['Age'].fillna(imp_age['Age']) </code></pre>
python|pandas|merge|eda
1
353,559
61,838,206
Find columns with the same values rearranged
<p>I want to find values in two columns that differ only in the rearrangement of values between columns. And where matching values are found (for example: 3-b / b-3 and a-3 / 3-a) in case of finding the second event - put down the unit. It is necessary in order to be able to exclude duplicates from the data frame. It i...
<p>First we use <code>np.sort</code> to sort over the rows, so <code>3, 1</code> becomes <code>1, 3</code>. Then we use <code>groupby.cumcount</code> to give a flag for each same row:</p> <pre><code>dft = pd.DataFrame(np.sort(table, axis=1), columns=table.columns) df['Result'] = dft.groupby(['id_1', 'id_2']).cumcount(...
python|pandas|numpy|comparison
2
353,560
61,856,188
NUMPY: select even lines, last column
<p>I am trying to learn numpy and I can't manage to complete this question: take the even lines, last column of the M matrix:</p> <pre><code> [[ 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 27 28 29 30]] </code></pre> <p>What I did : <code>print(M[0:, -1, 2], '\n')</code...
<p>Your array is 2-dimensional, but you're using three indices as if your array had 3 dimensions, you can use this index to get what you want:</p> <pre><code>print(M[::2, -1]) </code></pre> <p>Output:</p> <pre><code>[ 5 15 25] </code></pre>
python|arrays|python-3.x|numpy|multidimensional-array
2
353,561
61,998,280
how to identify label from result of speech command model in reactjs?
<p>I am using tensorflow-models/speech-commands model to detect speech commands using ReactJs app, I'm able to initialize the recognizer in app and getting results also, but not sure how to identify the label based on the result of the model.</p> <pre><code> componentDidMount () { fetch("http://localhost:3001/ITE...
<p><code>.scores</code> contains the probability that the given speech is a certain word. </p> <blockquote> <p>Which one exactly is the predicted</p> </blockquote> <p>It depends of what is intended. Is the word with the highest priority or the topk considered to be the predicted values ?</p> <p>Whatever the case, ...
reactjs|tensorflow|tensorflow.js
1
353,562
61,799,301
Auto generation of apply functions in python
<p>I would like to create a function which, given a dictionary will be able to generate functions for apply, example:</p> <pre><code>df = pd.DataFrame({"A" : [1,2,3,4], "B" : [4,5,6,7]}) </code></pre> <p>it'a pandas dataframe.</p> <p>I want to create a 2 new columns: "D" and "E". If A &lt;=2 D = 0...
<p>You can use boolean operator or <code>np.where/np.select</code>:</p> <pre><code>df['E'] = df['B'].gt(5).astype(int) # eqivalently # df['E'] = np.where(df['B'] &lt;= 5, 0, 1) df['D'] = np.select( (df['A']&lt;= 2, df['A'] ==3), (0, 0.5), 1) </code></pre>
python|pandas|function|autogeneratecolumn
0
353,563
61,833,651
Effective way to find the maximum points in an array with sufficent distance from each other with Numpy
<p>I have an array of number (like time series) and I want to certain number of high values. The high values (local maxima) should be far enough from each other. My solution:</p> <ol> <li>find maxima in the whole arrray</li> <li>clear surrounding around maxima (override the values with any small value)</li> <li>repeat<...
<p>I suggest you <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks.html" rel="nofollow noreferrer">this solution</a> from scipy:</p> <pre><code>from scipy.signal import find_peaks np.random.seed(103) x = np.random.normal(0, 1, 20) x[2] = 4 x[3] = 4.1 x[13] = 3.9 MIN_DIST = 4 peak...
python|numpy|math
1
353,564
61,816,969
Python Timeseries Pandas: remove np.nan if more than 3 occurrences continuously
<p>I have a timeseries dataframe with column [timestamp,Digital_Data]</p> <p>Could you guide me how to remove all rows that are matches if the digital_Data consecutively np.nan for more than three occurrence. data sample as below.</p> <p>Sorry i am not sure how to add a table here, it turns into image when i copy and...
<p>There MUST be a pythonic way to solve it, or even a solution provided by pandas itself, and I encourage you to search! but just in case you urgently need the solution, here is how I solve it:</p> <h2>1. example</h2> <pre><code>x = [1, 2, np.nan, np.nan, np.nan, np.nan, 2, 1, np.nan, np.nan, 3] y = [1, 2, 3, 4, 5, ...
python|pandas
0
353,565
61,880,483
Dynamic web scraping in Python using BeautifulSoup and Pandas
<p>I created a web scraper that pulls data from a single web page using Python. However, I'm having trouble creating a loop that iterates until all records have been scraped while being careful to not duplicate records.</p> <p>It is clear that the only changing piece of the URL is the "start=" portion.</p> <p>What is...
<p>I wrote the code on the assumption that each page is fixed at 50 lines. <code>for i in range(1,752,50):</code> loops from 1 line to 751 lines in 50-line increments.</p> <pre><code>#Imports import pandas as pd import requests import numpy as np from bs4 import BeautifulSoup from datetime import date pd.set_option(...
python|pandas|beautifulsoup
0
353,566
61,924,299
Prevent Keras EarlyStopping from canceling due to early metric spike
<p>This is an issue I've run into recently when training various models using Keras. Particularly, this occurs often when training on <a href="https://archive.vn/wip/H3N27" rel="nofollow noreferrer">imbalanced datasets</a> -- <em>archived Medium.com article</em></p> <h2>The Problem</h2> <p>There are times when model ...
<h2>The (a) Solution</h2> <p>This seems like a silly flaw in the logic, and it's rather easy to correct. One way to do this is by modifying the keras EarlyStopping class's <code>on_epoch_end</code> function ... </p> <pre class="lang-py prettyprint-override"><code>class PatientEarlyStopping(keras.callbacks.EarlyStoppi...
python|tensorflow|machine-learning|keras|tf.keras
0
353,567
61,742,145
Multiply tensor with matrix while flattening
<p>I have a tensor A (could be any dimension) and a Matrix M. I would like to multiply them by flattening the tensor to have a matrix. </p> <p>On MATLAB, I could simply do this:</p> <pre><code>function B = multiplyflatten(A,M) B = M*A(:,:) </code></pre> <p>For the purposes of testing, one could run the above functio...
<p>If I understand <em><code>A(:,:)</code> is compressing many dimensons into the second dimension of a matrix in MATLAB</em> correctly, the final <code>A(:,:)</code> has the shape of (8,5*4*4) as in example of <code>A=rand(8,5,4,4)</code>. In that case, this should be equivalent of <code>A(:,:)</code>: </p> <pre><cod...
python|numpy|matrix|numpy-ndarray|tensor
2
353,568
61,764,287
Create array X with certain number of copies of each element in array Y in python
<p>I have an array <code>counts = [2, 3, 4]</code> with each element denoted by <code>c</code>. I want to convert it into an array <code>weights</code> that has <code>m</code> copies of each element <code>c</code>, where <code>m</code> is an element in <code>M = [3, 2, 1]</code>. </p> <p>So in the end, I'd like an arr...
<p><a href="https://numpy.org/doc/stable/reference/generated/numpy.repeat.html" rel="nofollow noreferrer"><code>numpy.repeat</code></a> does <em>exactly</em> what you want:</p> <pre><code>&gt;&gt;&gt; np.repeat(counts, M) array([2, 2, 2, 3, 3, 4]) </code></pre>
python|numpy
4
353,569
62,015,284
Improving accuracy on a multi-class image classifiier
<p>I am building a classifier using the Food-101 dataset. The dataset has predefined training and test sets, both labeled. It has a total of 101,000 images. I’m trying to build a classifier model with >=90% accuracy for top-1. I’m currently sitting at 75%. The training set was provided unclean. But now, I would like to...
<ul> <li><p>Try augmentations like RandomHorizontalFlip, RandomResizedCrop, RandomRotate, Normalize etc from torchvision transforms. These always help a lot in classification problems.</p></li> <li><p>Label smoothing and/or Mixup precision training.</p></li> <li>Simply try using a more optimized architecture, like Effi...
python|computer-vision|pytorch|classification|fast-ai
2
353,570
61,774,572
What does .post2 in pytorch versions means?
<p>I was looking at torch versions <a href="https://pypi.org/project/torch/#history" rel="nofollow noreferrer">https://pypi.org/project/torch/#history</a></p> <pre><code>1.5.0 1.4.0 1.3.1 1.3.0.post2 1.3.0 1.2.0 1.1.0.post2 1.1.0 1.0.1.post2 1.0.1 1.0.0 0.4.1.post2 0.4.1 0.4.0 0.3.1 0.3.0.post4 0.1.2.post2 0.1.2.post1...
<p>It seems like related to PEP-0440 and post releases: <a href="https://www.python.org/dev/peps/pep-0440/#post-releases" rel="nofollow noreferrer">https://www.python.org/dev/peps/pep-0440/#post-releases</a></p> <h3>Post-releases</h3> <p>Some projects use post-releases to address minor errors in a final release that ...
pytorch
0
353,571
61,801,990
Tensorflow 2.0 : AttributeError: module 'tensorflow' has no attribute 'matrix_band_part'
<p>While running the code tf.matrix_band_part , i get the following error</p> <pre><code>AttributeError: module 'tensorflow' has no attribute 'matrix_band_part' </code></pre> <p>My tensorflow version : 2.0</p> <p>Any solution for this problem is needed.</p>
<p>I have found the answer. So i would like to share.</p> <p>Compatible version for the function for tensorflow 2.0 is</p> <pre><code>tf.compat.v1.matrix_band_part </code></pre> <p>Ref : <a href="https://www.tensorflow.org/api_docs/python/tf/linalg/band_part" rel="nofollow noreferrer">https://www.tensorflow.org/api_...
tensorflow2.0|attributeerror
1
353,572
61,978,831
L-BFGS-B code, Scipy (sciopt.fmin_l_bfgs_b(func, init_guess, maxiter=10, bounds=list(bounds), disp=1, iprint=101))
<p>I'm using the L-BFGS-B optimizer to find the minima of a function. This will help me calculate sharpness for the function. However, I'm not sure if this following message is considered a normal message (i.e. Is there something wrong with my program or is this message typical?) See below:</p> <pre><code>RUNNING THE ...
<p>First, l-bfgs-b will only give a global minimum for a convex function. <br /> the message CONVERGENCE: REL_REDUCTION_OF_F_&lt;=_FACTR*EPSMCH is the normal convergence message. <br /> The warning you are getting says that there are a lot of function/gradient evaluations in the line search - this can often happen when...
python|numpy|tensorflow|scipy|pytorch
1
353,573
61,992,207
Python pitch shifting with Windows
<p>I am attempting to create a sort of autotune/pitch correction algorithm in Python. I am able to detect pitches per a rectangular window size, and tried shifting the pitch of each window (of size 512) by 2 semitones to test if this method would actually work. Doing this, however, creates a huge amount of feedback in ...
<p>There should be a few things that I noticed about the total code:</p> <p>1- Hamming window is a better choice in sound processing and rectangular windows is the worst by no doubt.</p> <p>2- There should be a normalization <code>array/max(abs(array))</code> in order to receive an acceptable answer</p> <p>3- You shou...
python|arrays|numpy|audio|librosa
0
353,574
61,820,356
Using Multithreading or Multiprocessing to improve computational speed
<p>I am iterating through very large file size <code>[mesh]</code>. Since the iteration is independent, I would like to split my mesh into smaller sizes and run them all at the same time in order to lower computation time. Below is a sample code. For example, if <code>mesh</code> is of <code>length=50000</code>, I woul...
<p>This will give you the general idea. I couldn't test this since I do not have your data. The default constructor for <code>ProcessPoolExecutor</code> will use the number of processors on your computer. But since that determines the level of multiprocessing you can have, it will probably be more efficient to set the ...
python|multithreading|numpy|optimization|multiprocessing
0
353,575
61,741,701
Pandas: Difference of time columns returns -1 days
<p>I have a dataframe which has two-time columns (<code>dtype = timedelta64[ns]</code>)<br /> which looks like:</p> <pre class="lang-none prettyprint-override"><code>START_TIME RESTORE_TIME 17:17:00 18:46:00 20:07:00 00:44:00 20:07:00 00:45:00 14:16:00 15:50:00 14:16:00 17:55:0...
<p>In case of cross midnight you need to add following to your code:</p> <pre><code>from datetime import timedelta if df['Diff'].days &lt; 0: df['Diff'] = timedelta(days=0, seconds=df['Diff'].seconds, microseconds=df['Diff'].microseconds) </code></pre>
python|python-3.x|pandas|dataframe|datetime
1
353,576
62,019,748
Python 3.x: function to determine missing values
<p>I have the following data:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd data = {'var1': ['pero03930', 'pero03930', ' '], 'var2': ['121324', '232434', ' '], 'var3': [343, 937, 989], } df = pd.DataFrame (data, columns = ['var1', 'var2', 'var3']) print(df) </code><...
<p>I believe you should use inbuilt function to find <code>None</code>. And also <code>" " != None</code></p> <pre class="lang-py prettyprint-override"><code>import pandas as pd data = {'var1': ['pero03930', 'pero03930', None], 'var2': ['121324', '232434', ' '], 'var3': [343, 937, 989], } df...
python|python-3.x|pandas
1
353,577
61,768,686
How to convert data array to show easy to understand results
<p>I tried to make a algorithm using Teachable Machine to receive a picture and see if it fall under one of two categories of pictures (e.g dogs or humans), but after I exported the code that was given I couldn't make sense of how I could make the results that were given via array to turn into something that anyone can...
<p>Using argmax and max does what you want:</p> <pre><code>"Prediction is {} with {}% probability".format(["dog", "human"][np.argmax(prediction)], round(np.max(prediction)*100,2)) 'Prediction is human with 99.94% probability' </code></pre>
python|arrays|tensorflow|keras
0
353,578
61,844,231
Convert datetime pandas
<p>Below is a sample of my df</p> <pre><code>date value 0006-03-01 00:00:00 1 0006-03-15 00:00:00 2 0006-05-15 00:00:00 1 0006-07-01 00:00:00 3 0006-11-01 00:00:00 1 2009-05-20 00:00:00 2 2009-05-25 00:00:00 8 2020-06-24 00:00:00 1 2020-06-30 00:00:00 ...
<p>You could check the first element of your datetime strings after a split on '-' and clean up / replace based on its integer value. For the small values like '0006', calling <code>pd.to_datetime</code> with <code>errors='coerce'</code> will do the trick. It will leave 'NaT' for the invalid dates. You can drop those w...
python|pandas|datetime
1
353,579
61,721,701
Pandas DF convert date string to date year and month
<p>HI all I have a column in a dataframe that looks like:</p> <pre><code>print(df['Date']): 29-Nov-16 4-Dec-16 1-Oct-16 30-Nov-19 30-Jun-20 28-Apr-16 24-May-16 </code></pre> <p>And i am trying to get an output that looks like</p> <pre><code>print(df): Date Month Year 29-Nov-16 Nov ...
<p>Use <code>strftime</code> and <code>str.split</code> and assign them to new columns</p> <pre><code>df_final = df.assign(**pd.to_datetime(df['Date']).dt.strftime('%b-%Y') .str.split('-', expand=True) .set_axis(['Month',...
python|pandas
2
353,580
61,771,182
PANDAS to JSON: Changing name of columns
<pre><code>df = pd.concat([a,b,c,d,e], axis=1, sort=False) </code></pre> <p>I want to give column names which I usually do to output to Excel as </p> <pre><code>df.to_excel ("ids.xlsx", index = None, header=['IDs', 'Phases','Versions','Internal Version List','Tests']) </code></pre> <p>But when I do output to JSON, w...
<p>You can set the column names beforehand using:</p> <pre><code>df.columns = ['IDs', 'Phases','Versions','Internal Version List','Tests'] </code></pre> <p>After you can write the DataFrame to json using:</p> <pre><code>df.to_json ('Export_DataFrame.json', orient='table') </code></pre>
python|json|pandas
1
353,581
61,905,089
I want to merge 4 rows to form 1 row with 4 sub-rows in pandas Dataframe
<p><a href="https://i.stack.imgur.com/CMWUn.png" rel="nofollow noreferrer">This is my dataframe</a></p> <p>I have tried this but it didn't work:</p> <pre><code>df1['quarter'].str.contains('/^[-+](20)$/', re.IGNORECASE).groupby(df1['quarter']) </code></pre> <p>Thanks in advance</p>
<p>Hi and welcome to the forum! If I understood your question correctly, you want to form groups per year?</p> <p>Of course, you can simply do a group by per year as you already have the column.</p> <p>Assuming you didn't have the year column, you can simply group by the whole string <strong>except</strong> the last ...
python-3.x|regex|pandas
0
353,582
61,948,166
Strange bug from opencv rectangle
<p>I want to draw a box on image with different colors each boxes. So I write a simple code like this:</p> <pre><code>import cv2 import numpy as np image = cv2.imread(image_path) thickness = 2 for i in range(len(x1)): start_point = (x1[i],y1[i]) end_point = (x2[i],y2[i]) color = list(np.random.randint(0,...
<p>The issue seems to be the <code>rectangle</code> function has problems with the np.int64 type. If you try <code>print(type(color1[0]), type(color2[0]))</code> you will find that they are of different types with one being <code>&lt;class 'numpy.int64'&gt;</code> and the other <code>&lt;class 'int'&gt;</code>. To use ...
python|python-3.x|numpy|opencv
1
353,583
61,963,634
Adding commas after imported numerical values
<p>I need the values from a CSV to have a comma after each individual value as well at the end of each row/array. </p> <p>I have used <code>tolist()</code> before having these changes. The conversion of numerical values to strings is not wanted.</p> <p>The code below is what I currently have.</p> <pre><code>import n...
<p>You can basically set any formatter you desire to print your output with via <code>np.set_print_optiones</code> (this does not change your original array type and only change the printing format, which I think is what you are looking for). I think this is what you are looking for, but if it is not, you can define yo...
python|numpy|csv
0
353,584
61,988,588
df.max() not returning highest value in my data set
<p>Complete Python newbie here. I have a small dataset and I want to return a row where a column in that row is the highest using pandas and <code>df.max()</code>.</p> <p>Here is my data set:</p> <pre><code>Destination, Score,Star Rating,Bags,City --------------------------------------------------- Australia, ...
<p>This should help:</p> <pre><code>import pandas as pd frame = pd.read_csv('Australia.csv') max_score = frame['Score'].max() print(f'Max score is {max_score}') best_destinations = ','.join(frame[frame['Score'] == max_score]['Destination'].to_list()) print(f'Area(s) with max_score : {best_destinations}') </code></pre...
python|pandas|dataframe
0
353,585
61,925,783
Pandas: How to resolve truth value of a Series is ambiguous
<p>I am trying to apply a function to a DataFrame but I keep receiving this error: </p> <pre><code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). </code></pre> <p>The line I am calling is this one:</p> <pre><code> results['M1_Position'] = df.apply(instr_1(r...
<p>Assuming ratio, s_entry, and s_exit are columns of your dataframe:</p> <pre><code> results['M1_Position'] = df.apply(lambda row: instr_1(row.ratio, row.s_entry, row.s_exit), axis=1) </code></pre>
python|pandas
0
353,586
61,700,645
Add wT*x+b after CNN Python
<p>I have a problem.</p> <p>I have to take the output of last conv layer of EfficientNet(shape=(,7,7,1280), I call this x) and then calculate H = wT*x+b. My w is [49,49]. After that I have to apply softmax on H and then do <a href="https://i.stack.imgur.com/yvjF1.png" rel="nofollow noreferrer"><img src="https://i.sta...
<p>I see you use Tensorflow only (I mean without Keras). </p> <p>If you want to multiply <code>H</code> and <code>X</code> elementwise, and <code>H</code> and <code>X</code> are tensors with the same shape, you may use the elementwise multiplication functionality available in Tensorflow. If they are not tensors, you m...
python|tensorflow|keras|conv-neural-network|efficientnet
1
353,587
61,736,987
How to name dataframes in a for-loop?
<p>I am attempting to name multiple dataframes using a variable in a for loop. Here is what I tried:</p> <pre><code>for name in DF['names'].unique(): df_name = name + '_df' df_name = DF.loc[DF['names'] == str(name) </code></pre> <p>If one of the names in the DF['names'] column is 'George', the below command s...
<p><strong>SetUp</strong></p> <pre><code>df=pd.DataFrame({'names' : ['a','a','b','b'], 'values':list('1234')}) print(df) names values 0 a 1 1 a 2 2 b 3 3 b 4 </code></pre> <hr> <p>Using <code>globals</code> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/ap...
python|python-3.x|pandas
3
353,588
61,903,535
evaluating each position in a numpy meshgrid and inserting an array
<p>My goal is to evaluate a function over a 2D plane and return an RGB value for each point on the plane so that my final output is a nested array with an [R G B] for each pixel. Here was my first attempt:</p> <pre><code>@np.vectorize def foo(x,y): return [R,G,B] x = np.linspace(-10,10) y = np.linspace(-10,10) ...
<p>Vectorize is designed for convenience not necessarily for speed. It can be quite tricky to work with so if it is not convenient to adapt a function with vectorize it is often better to rewrite the function yourself to handle the indented full scale objects. That being said there are a few things going on here. First...
python|numpy
1
353,589
61,858,594
Apply logic to multiple rows of pandas' groupby
<p>Consider a data frame <code>df</code></p> <pre><code> date time isopen isclose openlate closeearly 20200201 0920 Y N Y N 20200201 1645 N Y N Y 20200202 0900 Y N N N 20200202 1650 N Y N...
<p>You can use the <a href="https://pandas.pydata.org/pandas-docs/version/0.22.0/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.agg</code></a> method. It allows you to apply a custom function to aggregate each group. In fact it even allows you to pass a diction...
python|pandas|dataframe|pandas-groupby
0
353,590
61,677,064
Convert XML to pandas dataframe
<p>I want to convert XML to a pandas DataFrame. I used the <code>ElementTree</code> library to parse the XML.</p> <pre><code>import pandas as pd import xml.etree.ElementTree as et xtree = et.parse('xmlfile.xml) xroot = xtree.getroot() [elem.tag for elem in xroot.iter()] </code></pre> <p>How do I access the values ...
<p>I've made a package for similar use case. It could work here too.</p> <pre><code>pip install pandas_read_xml </code></pre> <p>you can do something like</p> <pre><code>import pandas_read_xml as pdx df = pdx.read_xml('filename.xml', ['FMPDSORESULT']) </code></pre> <p>To flatten, you could</p> <pre><code>df = pdx.flat...
python|xml|pandas
2
353,591
62,002,696
Unexpected division by zero warning when using np.where
<p>I am new to numpy and trying to replace for loops using <code>np.where</code>. What I am trying to achieve is simple, I have 4 different conditions and based on these conditions, I am assigning values to elements of the array:</p> <pre><code>Period = np.arange(0.0,8.0,0.01) Ta = 0.075 Tb = 0.375 Tl = 6.0 Sds = 1.2...
<p>The problem is that <code>arr1 / arr2</code> is evaluated before the call to <code>np.where()</code>, hence NumPy is wisely warning you of the potential issue.</p> <p>If you are absolutely sure that your warning does not apply to you, you can just ignore it for the culprit line(s), e.g.:</p> <pre><code>with numpy....
python|python-3.x|numpy|numpy-ndarray
3
353,592
61,686,357
prevent pandas.interpolate() from extrapolation
<p>I'm having difficulty in preventing pd.DataFrame.interpolate(method='index') from <strong>extrapolation</strong>. </p> <p>Specifically:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({1: range(1, 5), 2: range(2, 6), 3 : range(3, 7)}, index = [1, 2, 3, 4]) &gt;&gt;&gt; df = df.reindex(range(6)).reindex(range(5), axi...
<p>Ok, turns out I'm running this on Pandas 0.21, hence the <code>limit_area</code> argument is silently failing. Looks like starting from 0.24 this is fixed. Case closed.</p>
pandas|interpolation|extrapolation
0
353,593
61,654,891
The shape of an numpy array
<p>Why the shape of any 1d array has an extra comma? Why <strong>(5,)</strong> instead of <strong>(5)</strong>. <br/> And why an extra comma is omitted for >= 2 arrays? Why it is <strong>(3,2)</strong> instead of <strong>(3,2,)</strong>.<br/></p> <p><strong>1D Example</strong><br/></p> <pre><code>data = array([11, 22...
<p><code>(1)</code> would be more consistent with tuples of length greater than one, but in Python syntax, this is nothing more than an expression in brackets and evaluates to the integer <code>1</code>. <code>(1,)</code> on the other hand is a <code>tuple</code>.</p> <p>(By the way, you can also write <code>(1,2,)</c...
python|numpy
0
353,594
61,933,162
am trying to reduce the score when a condition satisfies
<p>Am trying to reduce a score when the condition satisifies. But failing to do so.</p> <pre><code>data = ['A','B'] Score = 10 words = [ 'C', 'D'] for i in data: if i in words: do nothing else: reduce score by 2 </code></pre> <p>Here, when both A and B are not there in words, I want my s...
<pre><code>data = ['A','B'] score = 10 words = [ 'C', 'D'] data_not_found_list = [False for dt in data if dt not in words] if not any(data_not_found_list): score -= 2 print(score) </code></pre> <p>Output : <code>8</code></p> <p>I have made use of the any() method here . You can read how it works to get an idea...
python|pandas|loops|dataframe
2
353,595
61,820,354
Adding and multiplying values of a dataframe in Python
<p>I have a dataset with multiple columns and rows. The rows are supposed to be summed up based on the unique value in a column. I tried .groupby but I want to retain the whole dataset and not just summed up columns based on one unique column. I further need to multiple these individual columns(values) with another col...
<p>You must first sum <em>verticaly</em> the columns B, C and D for common id, then take the <em>horizontal</em> product:</p> <pre><code>result = df.groupby('id').agg({'A': 'first', 'B':'sum', 'C': 'sum', 'D': 'sum', 'E': 'first'}) result['F'] = result.fillna(1).astype('int64').agg('pro...
python|python-3.x|pandas|dataframe
2
353,596
61,804,564
Iterate over grouped rows Python pandas
<p>Let's say I have a dataframe like this</p> <pre><code>df_test = pd.DataFrame({"ID": [912665, 455378, 938724, 557830 ], "NAME": ["Anna","Anna","Diana","Peter" ], "LAST_NAME": ["Johns","Johns","Scott","Scott" ...
<p>IIUC, you can create a rate dictionary with the name of your columns, then <code>stack</code> and <code>map</code> your values whilst only summing the duplicate values.</p> <pre><code>rates = {'NAME' : 5, 'LAST_NAME' : 30, 'ADDRESS' : 0 ,'PHONE' : 50 } s = df.groupby('ngroup').agg(list).stack().explode().duplicate...
python|pandas|group-by|pandas-groupby
0
353,597
61,970,596
How to tell Python to wait until a Windows command from os.system() finishes?
<p>I want to execute a command in <code>cmd</code> to run Matlab in <code>-nodesktop</code> mode (so without gui). The Matlab program that I will run will create a <code>.txt</code> file that later in the same script <code>pandas</code> is going to parse. But on my Windows 10 (on Linux it works), <code>pandas</code> do...
<p>If you don't want to complicate with the subprocess module and you have an estimate for the time it takes to finish, you could simply add a sleep(seconds) after the call:</p> <pre><code>os.system(COMMAND_START) sleep(2) -&gt; wait 2 seconds </code></pre> <p>You can also use the subprocess module:</p> <pre><code>i...
python|pandas|cmd|operating-system
0
353,598
61,819,140
re-arrange data in pandas series by month, regardless of the year
<p>I have a pandas series with data from 07-2018 till 06-2019, e.g.</p> <pre><code>2018-07 1 2018-08 3 2018-09 4 2018-10 5 2018-11 6 2018-12 7 2019-01 9 2019-02 8 2019-03 7 2019-04 6 2019-05 5 2019-06 4 </code></pre> <p>I would like to re-arrange the data from jan-dec, regardless of the year:</p> <pre><code>2019-01 ...
<p>Create <code>MultiIndex</code> by months and years and sorting by it:</p> <pre><code>d = pd.to_datetime(df.index, format='%Y-%m') df.index = [d.year, d.month, df.index] df = df.sort_index(level=[0,1], ascending=[False, True]).reset_index(level=[0,1], drop=True) print (df) col 2019-01 9 2019-02 8 2019...
python|pandas|datetime
2
353,599
61,963,233
Check if date in one dataframe is between two dates in another dataframe, by group
<p>I have the following problem. I've got a dataframe with start and end dates for each group. There might be <strong>more than one start and end date per group</strong>, like this:</p> <pre><code>group start_date end_date 1 2020-01-03 2020-03-03 1 2020-05-03 2020-06-03 2 2020-02-03 202...
<p>Based on @YOBEN_S and @Quang Hoang's advice this made it:</p> <pre><code>df = df.merge(dic_dates, how='left') df['is_between'] = np.where(df.date.between(pd.to_datetime(df.start_date), pd.to_datetime(df.end_Date)),1, 0) df = (df.sort_values(by=['gro...
python|pandas|date
2