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
11,200
40,664,962
How to display years on x axis line plot?
<p>I'm trying to plot some data using <code>pandas</code> and <code>matplotlib</code>.</p> <p>Consider this data:</p> <pre><code>years = [i for i in range(2005, 2016)] values = [49.929266640000002, 45.441518010000003, 49.762879810000001, 52.849612180000001, 57.618790150000002, 47.750615240000002, 47.508212309999998, ...
<p>The easiest way to fix your problem is to explicitly use <code>datetime</code> objects as your index. Pandas provides a utility for this:</p> <pre><code>years = pd.date_range('2008','2015', freq='AS') </code></pre> <p>The <code>freq</code> parameter takes an offset. You can create your own or use one of the <a hre...
python|python-3.x|pandas|matplotlib|jupyter
2
11,201
40,624,209
Efficient way to delete elements in one numpy array from another
<p>What is the best way to delete the elements from one numpy array in another? Essentially I'm after <code>np.delete()</code> where the order of the arrays doesn't matter.</p> <pre><code>import numpy as np a = np.array([2,1,3]) print a b = np.array([4,1,2,5,2,3]) b = np.delete(b, a) # doesn't work as desired print b ...
<p>Here's an approach using <code>sorting</code> -</p> <pre><code>def remove_first_match(a,b): sidx = b.argsort(kind='mergesort') unqb, idx = np.unique(b[sidx],return_index=1) return np.delete(b,sidx[idx[np.in1d(unqb,a)]]) </code></pre> <p>Sample runs -</p> <pre><code>In [177]: a = np.array([2,1,3]) ...
python|arrays|performance|numpy
1
11,202
61,787,754
Divide a dataframe by a number in python
<p>I want to divide a Dataframe by a constant but I haven't figured out how to do it. Do you know how can I do that, is it possible to do it? The dataframe is the next:</p> <p><a href="https://i.stack.imgur.com/zMFR6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zMFR6.png" alt="Dataframe"></a></p...
<pre><code>#create df as with one row and four columns df = pd.DataFrame({'col1': 10, 'col2': 5}, index=[1,2]) #divide the df by constant directly constant = 29 df[df.columns].apply(lambda x: x/constant) </code></pre>
python|pandas|divide
0
11,203
61,830,491
while using jupyter notebook i got CERTIFICATE_VERIFY_FAILED
<p>I am running Jupyter notebook, while trying to run below code i got the error. Can anyone please suggest.</p> <pre><code>import tensorflow as tf import tensorflow_datasets as tfds import tensorflow_hub as hub pre_trained_model = "https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1" hub_layer = hub.KerasLayer(...
<p>It seems like the verification server for your SSL certificate is failing. Try adding the path in the jupyter config file <code>c.NotebookApp.client_ca = '' </code></p>
jupyter-notebook|ipython|tensorflow-hub|anaconda3
0
11,204
34,363,877
Pandas conditional groupby count
<p>Given this data frame:</p> <pre><code>import pandas as pd df = pd.DataFrame( {'A' : ['foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar'], 'D' : [2, 4, 4, 2, 5, 4, 3, 2]}) </code></pre> <p>df</p> <pre><code> A D 0 foo 2 1 foo 4 2 foo 4 3 foo 2 4 bar 5...
<blockquote> <p>Does this warning matter in this case?</p> </blockquote> <p>I see that warning for a lot of things, and it's never once made a difference to me. I just ignore it.</p> <blockquote> <p>Also, how does pandas know to match the rows up correctly if it's taking them from another dataframe?</p> </blockqu...
python-3.x|pandas
4
11,205
36,817,297
create categorical variables by condition in python with pandas or statsmodels
<p>I want to create categorical variables from my data with this method:</p> <pre><code>cat.var condition 1 x &gt; 10 2 x == 10 3 x &lt; 10 </code></pre> <p>I try using <a href="http://statsmodels.sourceforge.net/devel/contrasts.htm" rel="nofollow">C() method</a> from <code>patsy</code> , ...
<p>you can do it this way (we will do it just for column: <code>a</code>):</p> <pre><code>In [36]: df Out[36]: a b c 0 10 12 6 1 12 8 8 2 10 5 8 3 14 7 7 4 7 12 11 5 14 11 8 6 7 7 14 7 11 9 11 8 5 14 9 9 9 12 9 10 7 8 8 11 13 9 8 12 13 14 ...
python|pandas|statsmodels|patsy
2
11,206
55,044,255
Problem to merge two excel files with pandas
<p>I have two excel files. </p> <p>The only thing these files have in common is the dbsid.</p> <p>In the first excel(SQL) the dbsid called "ID of Sample Card" and in the other one (EMEA) "Barcode"</p> <pre><code>import pandas as pd excel_file = "eu-tracker.xlsx" sql = pd.read_excel(excel_file, sheet_name=0, date_pa...
<p>Both <code>sql.["ID of Sample Card"]</code> and <code>emea.["Barcode"]</code> are <code>object</code> datatypes. I can't determine from the sample data in the original question whether or not they have leading or trailing spaces, but that could mess up joining the two dataframes, even though the data looks the same....
python|pandas
0
11,207
73,257,386
pandas groupby column that has specific value
<p>hi im working with dataset in pandas. lets say the dataset having ID, TEST_TYPE, TEST_STATUS, TEST_DATE, etc</p> <p>i need to group a kind of column so first i try</p> <pre><code>data_useless[['TEST_TYPE', 'TEST_STATUS']].groupby('TEST_STATUS').count_values() </code></pre> <p>and it worked : showing the result of gr...
<p>You can filter using:</p> <pre><code>data_useless.loc[data_useless['TEST_STATUS'] == 'PASS TEST'] </code></pre> <p>Or:</p> <pre><code>data_useless.query('TEST_STATUS == &quot;PASS TEST&quot;') </code></pre> <p>Then, if needed, compute the groupby + aggregation:</p> <pre><code>(data_useless.loc[data_useless['TEST_STA...
python|pandas
2
11,208
73,376,118
How to remove POS-tag 'VERBS' from dataframe
<p>I have imported an Excel file as Pandas Dataframe. This file consists of &gt;4000 rows (documents) and 12 columns. I extracted the column 'Text' for NLP.</p> <p>The text in the column 'Text' is in Dutch. I'm using a Spacy model for Dutch language 'nl_core_news_lg'</p> <pre><code>import spacy import pandas as pd sp...
<p>Try <code>if not token.is_stop and token.pos_ != 'VERB'</code> it's the same as <code>if not (token.is_stop or token.pos_ == 'VERB')</code></p> <p>Also, do you really need the 'tokens' column ? Otherwise you should compute 'final' from 'lower', applying both tokenization and pos tagging with one .apply() and not cre...
python|pandas|dataframe|nlp|part-of-speech
1
11,209
35,034,120
How to understand the "Densely Connected Layer" section in tensorflow tutorial
<p>In the <a href="https://www.tensorflow.org/versions/0.6.0/tutorials/mnist/pros/index.html#convolution-and-pooling" rel="noreferrer">Densely Connected Layer</a> section of the tensorflow tutorial, it says the image size is <strong>7 x 7</strong>, after it is been processed. I tried the code, and it seem these paramet...
<p>You also need to know the stride of the max pool and convolution.</p> <pre><code>def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') </code></pre> <p>He...
tensorflow
24
11,210
30,989,064
python for loop with updated values
<p>I have a pandas dataframe with over 10k rows. I need to iterate through every row and do math based on the value of the previous row after it's updated. For loop is very slow.</p> <p>Example DF:</p> <pre><code>a b c 1 2 3 2 3 4 3 4 5 </code></pre> <p>for loop example:</p> <pre><code>for i in range(1,len(...
<p>Use iloc</p> <pre><code>for i in range(1,len(DF)): DF.iloc[i]['b'] = DF.iloc[i-1]['b']+DF.iloc['i']['c'] </code></pre>
python|numpy|pandas
1
11,211
67,448,196
Detect presence of inverse pairs in two columns of a DataFrame
<p>I have a dataframe with two columns; <code>source</code>, and <code>target</code>. I would like to detect inverse rows, i.e. for a pair of values <code>(source, target)</code>, if there exists a pair of values <code>(target, source)</code> then assign <code>True</code> to a new column.</p> <p>My attempt:</p> <pre><c...
<p>You can apply a lambda function using similar logic to that in your example. We check if there are any rows in the dataframe with a reversed source/target pair.</p> <p>Incidentally, the column name 'oneway' indicates to me the opposite of the logic described in your question, but to change this we can just remove th...
python|pandas|dataframe|graph|networkx
0
11,212
67,299,967
Dynamically assign dataframes to an object inside a for statement
<p>I have 4 dataframes with data :</p> <p>final_101</p> <p>final_102</p> <p>final_103</p> <p>final_104</p> <p>I want to print them into a single text file by calling them dynamically by their last digits. I tried using the below code but I am not able to make it work as the dynamic step just gives a string value instea...
<p>(updated per comments...)</p> <p>It's possible to retrieve variables by name in python, but not really recommended.</p> <p>If there's just the four, you can hard-code them easily enough:</p> <pre><code>dfs = [final_101, final_102, final_103, final_104] with open(f&quot;myfile_{timestamp}.txt&quot;, mode=&quot;w&quo...
python|pandas
1
11,213
67,484,190
why numpy allows mixed datatypes but docs say that it cannot
<p>I have a general question but no one is able to give me answer of that i did lot of search in official docs of python and other sources such as bootcamp and datacamp.</p> <p>Issue is that i have read every where that numpy does not support hetrogenous data types (<a href="https://numpy.org/devdocs/user/whatisnumpy.h...
<p>I tried it out and actually it is homogeneous! Check this out:</p> <pre><code>&gt;&gt;&gt; np.array([&quot;hello&quot;, 1, 2, 3]) array(['hello', '1', '2', '3'], dtype='&lt;U5') </code></pre> <p>What we see here is the type is <code>U</code> for Unicode (<a href="https://numpy.org/devdocs/reference/generated/numpy...
python|python-3.x|numpy
2
11,214
34,598,371
Count number of "True" values in boolean Tensor
<p>I understand that <code>tf.where</code> will return the locations of <code>True</code> values, so that I could use the result's <code>shape[0]</code> to get the number of <code>True</code>s. </p> <p>However, when I try and use this, the dimension is unknown (which makes sense as it needs to be computed at runtime)....
<p>You can cast the values to floats and compute the sum on them: <code>tf.reduce_sum(tf.cast(myOtherTensor, tf.float32))</code></p> <p>Depending on your actual use case you can also compute sums per row/column if you specify the reduce dimensions of the call.</p>
python|tensorflow
55
11,215
60,067,160
Check if groups of numbers in Numpy array?
<p>I have a Numpy array A:</p> <pre><code>A = np.array([1,2,3,4,5,6,8,10,12,15,20,100,200,300,500]) </code></pre> <p>And another Numpy array B with pairs of numbers:</p> <pre><code>B = np.array([[2000,1000],[5000,10000],[1,1000],[300,700],[500,5],[500,700],[1,5]) </code></pre> <p>I am looking for the most efficient...
<p>I would use <code>isin</code> with <code>argmax</code></p> <pre><code>np.isin(B,A).all(1).argmax() Out[931]: 4 B[np.isin(B,A).all(1).argmax()] Out[932]: array([500, 5]) </code></pre>
python|arrays|python-3.x|numpy
2
11,216
60,128,552
Returning a value that is between two row values (pseudo-time series?)
<p>I am trying and failing here. All I want to do is take a "Time_of_Event" value from this dataframe:</p> <pre><code>events_data = {'Time_of_Event':[8, 22, 24,34,61,62,73,79,86]} my_events_df = pd.DataFrame(events_data) </code></pre> <p>And search it against the "Job_Start_Times" of this dataframe:</p> <pre><code>j...
<p>We can try with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>pd.merge_asof</code></a></p> <pre><code>new_df = (pd.merge_asof(my_events_df.sort_values('Time_of_Event'), my_jobs_df, left_on='Time_of_Event', ...
python|pandas|dataframe
1
11,217
65,303,132
Trouble using date/datetime to create new series using Pandas
<p>I have some financial data that I'm playing around with on AWS just to learn some new things. I have downloaded this data using the <code>yfinance</code> module. I'm not sure if/how I could include a csv file with the data but <a href="https://i.stack.imgur.com/DKEFC.png" rel="nofollow noreferrer">here</a> is a crop...
<p>MrFuppes is correct. It was enough to do <code>df.index = pd.to_datetime(df.index)</code>. I had actually tried resetting the index before calling the column and that had given me the same error but at least this works.</p>
python|pandas|dataframe|datetime|series
0
11,218
65,387,052
Pandas sample different fractions for each group after groupby
<pre><code>import pandas as pd df = pd.DataFrame({'a': [1,2,3,4,5,6,7], 'b': [1,1,1,0,0,0,0], }) grouped = df.groupby('b') </code></pre> <p>now sample from each group, e.g., I want 30% from group <code>b = 1</code>, and 20% from group <code>b = 0</code>. How should I do that? if I want to have 150%...
<p>You can dynamically return a random sample dataframe with different % of samples as defined per group. You can do this with percentages below 100% <strong>(see example 1)</strong> AND above 100% <strong>(see example 2)</strong> by passing <code>replace=True</code>:</p> <ol> <li>Using <code>np.select</code>, create a...
python|pandas|group-by|sample-data
2
11,219
65,200,452
Decaying the learning rate from the 100th epoch
<p>Knowing that</p> <pre><code>learning_rate = 0.0004 optimizer = torch.optim.Adam( model.parameters(), lr=learning_rate, betas=(0.5, 0.999) ) </code></pre> <p>is there a way of decaying the learning rate from the 100th epoch?</p> <p>Is this a good practice:</p> <pre><code>decayRate = 0.96 my_lr_scheduler = tor...
<pre><code>from torch.optim.lr_scheduler import MultiStepLR # reduce the learning rate by 0.1 after epoch 100 scheduler = MultiStepLR(optimizer, milestones=[100,], gamma=0.1) </code></pre> <p>Please refer: <a href="https://pytorch.org/docs/stable/optim.html#torch.optim.lr_scheduler.MultiStepLR" rel="nofollow noreferre...
python|machine-learning|pytorch|epoch|learning-rate
1
11,220
50,049,823
How to conditionally slice a dataframe in pandas
<p>Consider a pandas DataFrame constructed like:</p> <pre><code>df = pandas.DataFrame({'a':['one','two','three']}) </code></pre> <p>then I can locate the specific row of the dataframe containing <code>two</code> like:</p> <pre><code>df[df.a == 'two'] </code></pre> <p>but so far the only way I have found to subset t...
<p>You want to identify the indices for a particular start and stop values and get the matching rows plus all the rows in between. One way is to find the indexes and build a range, but you already said that you don't like that approach. Here is a general solution using boolean logic that should work for you.</p> <p>Fi...
python|pandas|dataframe
3
11,221
50,095,924
Could not convert string to float with pandas series in Python
<pre><code>lat=[] lon=[] with open("Rawcomdata.log") as fin: # Input file for line in fin: if '$GPRMC' in line: # check message from input line data=line.split(',') lat.append(data[1]) # extract data and store in buffer lon.append(data[3]) import pandas as pd import numpy ...
<p>Obviously some of your lines don't have valid <code>float</code> data, specifically some line have text <code>lat</code> which can't be converted to <strong>float</strong>.</p> <p>For removing <code>NaN</code> lines you can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna....
python|string|pandas|dataframe
0
11,222
49,964,588
What is the default learningRate and decay of the adam optimizer
<p>According to <a href="https://js.tensorflow.org/api/0.9.0/#train.adam" rel="nofollow noreferrer">the documentation</a>, the learningRate is optionnal in the adam optimizer.</p> <p>If non set what is the default learningRate ?</p> <p>Is it computed dynamically according to the variables values ?</p>
<p>As you can see in the <a href="https://github.com/tensorflow/tfjs-core/blob/v0.13.0/src/optimizers/optimizer_constructors.ts#L130-L134" rel="nofollow noreferrer">source code</a> which is linked to on the <a href="https://js.tensorflow.org/api/0.13.0/#train.adam" rel="nofollow noreferrer">doc page</a>, the default va...
javascript|tensorflow.js
0
11,223
50,140,131
Multiple logical comparisons in pandas df
<p>If I have the following pandas df</p> <pre><code>A B C D 1 2 3 4 2 2 3 4 </code></pre> <p>and I want to add a new column to be 1, 2 or 3 depending on,</p> <pre><code>(A &gt; B) &amp;&amp; (B &gt; C) = 1 (A &lt; B) &amp;&amp; (B &lt; C) = 2 Else = 3 </code></pre> <p>whats the best way to do this...
<p>You can use <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.select.html" rel="noreferrer"><code>numpy.select</code></a> to structure your multiple conditions. The final parameter represents default value.</p> <pre><code>conditions = [(df.A &gt; df.B) &amp; (df.B &gt; df.C), ...
python|pandas|dataframe
5
11,224
64,130,610
Python coulmns validation using pandas schema
<p>I am trying to validate my DataFrame coulmns using PandasSchema.I am stuck at validating some columns such as columns like :</p> <p>1.ip_address- should contain ip address in following format 1.1.1.1 or it should be null if any other value it should raise an error. 2.initial_date- format yyyy-mm-dd h:m:s or mm-dd-yy...
<p>I've just looked at the documentation for PandasShema and most if not all you are looking for it out of the box functionality. Take a look at:</p> <ul> <li><a href="https://tmiguelt.github.io/PandasSchema/#pandas_schema.validation.InListValidation" rel="nofollow noreferrer">InListValidation</a></li> <li><a href="htt...
python|pandas|dataframe|validation|customvalidator
2
11,225
63,768,987
How to make rows and columns into variables in Python numpy?
<p>I need to calculate a mean of values whose indices <code>(row + column) % 5</code>. I understand how to call out specific indices, but I am having trouble defining rows and columns into variables i and j, so that I can create a condition that needs to be met.</p> <pre><code>data = np.random.normal(1, 0.5, size=(8, 9...
<p>Your question is not clear about the <code>(row + column) % 5</code> requirement. But assuming you want the values where <code>(row + column) % 5 == 0</code> you can build an indexer and make use of <a href="https://numpy.org/doc/stable/reference/arrays.indexing.html#advanced-indexing" rel="nofollow noreferrer">adva...
python|numpy
1
11,226
63,956,421
how can on define an operation over the most recent X days in a pandas frame?
<p>Say I have a pandas DataFrame with sales data for a clothes store chain:</p> <pre><code>model day shop amount sold price polo 01-01-2006 B7 3 42.45 polo 01-01-2006 C8 4 41.45 polo 02-01-2006 C8 4 41.43 polo 03-01-2006 B8...
<p>Try this:</p> <pre><code># First, make sure that the `day` column is of type Timestamp, not string: df['day'] = pd.to_datetime(df['day']) # Add a revenue column df['revenue'] = df['amount_sold'] * df['price'] # Sum revenue by model and day # There is some index manipulation to prepare for the next command tmp = df...
pandas
1
11,227
46,742,471
calculate day-to-day change in time series
<p>I have a time series <code>df1</code>. <code>df2</code> indicates <code>start</code> and <code>stop</code> dates and <code>difference</code> in <code>value</code> based on <code>df1</code> between the two dates. In addition to the final difference between the dates (as shown in <code>df2</code>), I want to find the ...
<p>You could do something like this. It will work as long as the Date column is in ascending order. It creates a grouping variable by checking for dates in <code>df2$Start</code>, and then creates a cumulative sum of differences for each group, <code>unlist</code>ing them into a single vector.</p> <pre><code>df1$Cha...
python|r|pandas|merge
2
11,228
46,901,513
Reshape MultiIndex dataframe to tabular format
<p>Given a sample MultiIndex:</p> <pre><code>idx = pd.MultiIndex.from_product([[0, 1, 2], ['a', 'b', 'c', 'd']]) df = pd.DataFrame({'value' : np.arange(12)}, index=idx) df value 0 a 0 b 1 c 2 d 3 1 a 4 b 5 c 6 d 7 2 a 8 b 9 c 10 d 1...
<p>Using <code>unstack</code> and <code>stack</code></p> <pre><code>In [5359]: dff = df['value'].unstack() In [5360]: dff Out[5360]: a b c d 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 In [5361]: dff.stack().to_frame('name') Out[5361]: name 0 a 0 b 1 c 2 d 3 1 a 4 b 5...
python|pandas|dataframe|multi-index
4
11,229
46,715,102
What does this error InvalidArgumentError (see above for traceback): Expected dimension in the range [-1, 1), but got 1 mean?
<p>I'm getting an error when trying to run the following code:</p> <pre><code>correct = tf.equal(tf.argmax(activation,1), tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(correct,'float')) print ('Accuracy: ', sess.run(accuracy, feed_dict = {x: test_x, yL test_y}) </code></pre> <p>The actual error is:</p> <pre><cod...
<p>The problem is not in accuracy. Error clearly shows that problem is in argmax. please check your dimension of 'activation' and 'y' if anyone of them is of 1-D then remove the second operand of argmax and it will probably resolve your issue.</p>
python|tensorflow
2
11,230
38,572,815
Pandas - Modify string values in each cell
<p>I have a pandas dataframe and I need to modify all values in a given string column. Each column contains string values of the same length. <strong>The user provides the index they want to be replaced for each value</strong></p> <ul> <li>for example: <code>[1:3]</code> and the replacement value <code>&quot;AAA&quot...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.slice_replace.html" rel="noreferrer"><code>str.slice_replace</code></a>:</p> <pre><code>df['B'] = df['B'].str.slice_replace(1, 3, 'AAA') </code></pre> <p>Sample Input:</p> <pre><code> A B 0 w abcdefg 1 x bbbbbbb 2...
python|pandas|string
14
11,231
38,928,832
Different results in numpy vs matlab
<p>I'm trying to implement a gradient descent algorithm that was previously written in matlab in python with numpy, but I'm getting a set of similar but different results.</p> <p>Here's the matlab code</p> <pre><code>function [theta] = gradientDescentMulti(X, y, theta, alpha, num_iters) m = length(y); num_features =...
<p>This line in your Python:</p> <pre><code> temp_theta = theta </code></pre> <p>doesn't do what you think it does. It doesn't make a copy of <code>theta</code> and "assign" it to the "variable" <code>temp_theta</code> -- it just says "<code>temp_theta</code> is now a new name for the object currently named by <c...
python|matlab|numpy
8
11,232
63,004,821
If statement across multiple columns in Pandas
<p>This is the data I have:</p> <pre><code>| total | big | med | small| big_perc | med_perc | sml_perc | |:-----:|:-----:|:-----:|:----:|:--------:|:--------:|:--------:| | 5 | 4 | 0 | 1 | 0.8 | 0.0 | 0.2 | | 6 | 0 | 3 | 3 | 0.0 | 0.5 | 0.5 | | 5 | ...
<p>For the <code>condition</code> column, <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer">np.where</a> suffices, since it is just a single condition; however for the <code>size</code> column, since it has multiple conditions, <a href="https://numpy.org/doc/stable/re...
python|pandas|dataframe
1
11,233
67,918,354
Pandas DataFrame.value_counts() does not allow dropna=False
<p>Pandas <code>Series.value_counts()</code> has a <code>dropna</code> parameter but <code>DataFrame.value_counts()</code> not. That is my problem. But I am sure there is a reason and an alternative solution for it.</p> <p>The usecase is that I want to count pattern (value combinations of specific columns) in my DataFr...
<p>I think it is not supported yet, possible alternative solution:</p> <pre><code>pb = df.groupby(['foo', 'bar', 'sun'], dropna=False).size() print(pb) foo bar sun 1 1 NaN 1 2 True 1 3 NaN 1 2 2 False 3 3 5 NaN 1 5 5 True 1 dtype: int64 </code></pre>
python-3.x|pandas
3
11,234
67,697,921
Subtract a dataframe with some matching and non matching columns and indexes
<p>How can I subtract two dataframes that have some matching and some non-matching columns and indexes?</p> <pre><code>df_diff = df_add - df_subtract df_diff = df_add.subtract(df_subtract) </code></pre> <p>where:</p> <p>df_add:</p> <pre><code> 1 2 3 4 A 1.1 1.2 1.3 1.4 B 2.1 2.2 2.3 2.4 D 3.1 3.2 3.3 3.4...
<p>Use <code>pd.DataFrame.sub</code> with <code>fill_value</code>, then <code>fillna</code> for missing values in df_add dataframe:</p> <pre><code>df_add.sub(df_sub, fill_value=0).fillna(0) </code></pre> <p>Output:</p> <pre><code> 1 2 3 4 A 1.1 1.2 1.3 1.4 B 2.1 -2.8 2.3 -5.6 C 0.0 -6.0 0.0 -9.0 D ...
python|python-3.x|pandas|dataframe
4
11,235
67,773,880
Exporting tensorboard computation graph as Panda dataframe
<p>There is a need to export a CNN computational graph from Tensorbaord as Panda dataframe. I have looked at <a href="https://www.tensorflow.org/tensorboard/dataframe_api" rel="nofollow noreferrer">https://www.tensorflow.org/tensorboard/dataframe_api</a> and only training information is logged (because of defining a ca...
<p>The last time I tried doing this using the source you mentioned, it didn't go well. I found out that I couldn't use the ExperimentFromDev(not so sure now) which was used in the tutorial. I instead manually read the TB log files using the method of <a href="https://stackoverflow.com/questions/41074688/how-do-you-read...
tensorflow|keras|tensorboard
0
11,236
67,882,186
Fine tuning resnet unfrozen layers in keras
<p>i am working with resnet to train my data. I have frozen most of the layers and only working training with the last 4 layers. I want to change these last four layer dimension so that it matches my input dimension and channels. As i am new to this i dont know how to do it. I tried googling it but cannot find the sol...
<p>If you want to change last layers architecture, you should get output of the desired intermediate layer and connect it to yours.</p> <p>I assume that you want to change the architecture after the 46th layer.</p> <p>First define pre-trained model:</p> <pre><code>base_model = tf.keras.applications.ResNet50( includ...
python|tensorflow|keras|resnet
0
11,237
31,943,391
Using bool array mask, replace False values with NaN
<p>I have two arrays,</p> <pre><code>a = array([ [ 0.93825418, 0.60731973, 0.44218921, 0.90888805, 0.97695114], [ 0.27422807, 0.75870153, 0.12154102, 0.89137678, 0.04257262], [ 0.32855867, 0.17215507, 0.00302302, 0.95395069, 0.02596567], [ 0.18385244, 0.09108341, 0.27925367, 0.0177183 , 0.4...
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#boolean-array-indexing" rel="noreferrer">boolean indexing</a>:</p> <pre><code>a[~b] = np.nan </code></pre> <p>This replaces all of values in <code>a</code> that correspond to <code>False</code> values in the mask <code>b</code> wit...
python|arrays|numpy|nan
12
11,238
32,086,260
IPython - get rid of numpy newlines on matrix printout
<p>I was was looking at a matrix I had created with numpy, and noticed that when I print it out, by just entering the array name into the interpreter, numpy seems to add a new line, or hits some kind of barrier around the middle of the screen (after 3 elements in this case), and wastes alot of space there on the right....
<p>I would suggest printing using pandas. Even though it's not in Ipython, maybe it'll help.</p> <pre><code>b = np.random.random((5,15)) </code></pre> <p><a href="https://i.stack.imgur.com/4dHFu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4dHFu.png" alt="enter image description here" /></a></p> <...
python|arrays|numpy|matrix
0
11,239
41,598,505
Tensorflow - Dynamic Slicing of Images
<p>I previously asked this question, but after some investigation of the problem it appears I may have just gone down the wrong path for what I am trying to achieve. </p> <p><a href="https://stackoverflow.com/questions/41576944/dynamic-image-cropping-in-tensorflow">Dynamic image cropping in Tensorflow</a> </p> <p>...
<p>Instead of using tf.slice (which doesn't let you operate on a batch), I recommend using <code>tf.image.extract_glimpse</code>. Here is a toy sample program that operates in a batch:</p> <pre><code>import tensorflow as tf import numpy as np NUM_IMAGES = 2 NUM_CHANNELS = 1 CROP_SIZE = [3, 4] IMG_HEIGHT=10 IMG_WIDTH=...
image|python-3.x|tensorflow|slice|crop
1
11,240
41,481,548
Python Excel rows with same value checking
<p>I’m trying get my Python program to verify an excel spreadsheet that looks like this:</p> <p><a href="https://i.stack.imgur.com/BG6NW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BG6NW.jpg" alt="Example of my spreadsheet"></a></p> <p>The first column is the order number and there may be one o...
<p>You are on the right track. Just import the data and pivot it using pandas and check if number of empty counts are > 0. I used a dummy data since I couldn't take from your image:-</p> <pre><code>import pandas as pd df = pd.DataFrame() df['no'] = [1,1,1,2,1,2,1,3] df['ok'] = ['OK','Empty','OK','Empty','Empty','OK',...
python|excel|pandas
0
11,241
41,241,491
Sliding inner product using Tensorflow convolution
<p>I have two tensors of shape N x D1 and M x D2 where D1 > D2, called X and Y respectively. For my task, X acts as the input and Y acts as the filter.</p> <p>I want to calculate a matrix P of shape N x M x (D1-D2+1) such that:</p> <pre><code>P[0,0,0] = dot(X[0,0:D2], Y[0,:]) P[0,0,1] = dot(X[0,1:D2+1], Y[0,:]) ......
<p>tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, data_format=None, name=None)</p> <p>In your case, I'd set strides to 1, and padding to SAME.</p> <p>tf.nn.conv2d(X, Y, strides=1, padding=SAME)</p>
python|tensorflow
0
11,242
41,351,431
Converting numpy structured array subset to numpy array without copy
<p>Suppose I have the following numpy structured array:</p> <pre><code>In [250]: x Out[250]: array([(22, 2, -1000000000, 2000), (22, 2, 400, 2000), (22, 2, 804846, 2000), (44, 2, 800, 4000), (55, 5, 900, 5000), (55, 5, 1000, 5000), (55, 5, 8900, 5000), (55, 5, 11400, 5000), (33, 3, 14500, 3000), ...
<p>This answer is a bit long and rambling. I started with what I knew from previous work on taking array views, and then tried to relate that to your functions.</p> <p>================</p> <p>In your case, all fields are 4 bytes long, both floats and ints. I can then view it as all ints or all floats:</p> <pre><co...
python|numpy|view|structured-array
2
11,243
41,294,542
tensorflow monitoredsession usage
<p>I have the following code to perform simple arithmetic calculations. I am trying to implement fault tolerance in it by using a Monitored Training session.</p> <pre><code>import tensorflow as tf global_step_tensor = tf.Variable(10, trainable=False, name='global_step') cluster = tf.train.ClusterSpec({"local": ["loc...
<p>First issue is in following lines. It uses a local session for a distributed (device assigned) op. Why do you need that?</p> <pre><code>sess = tf.Session() tf.train.global_step(sess, global_step_tensor) </code></pre> <p>Second issue: Code uses <code>WorkerSessionCreator</code>. One machine should be chief. In this...
python|tensorflow|distributed-computing|fault-tolerance
3
11,244
41,634,490
A better way to do this triple loop using numpy methods
<p>So I'm just trying to write a simple script to convert RBG to YUV and I have ended up with something like this:</p> <pre><code>rgb2yuv_matrix = np.array([[0.299, 0.587, 0.114], [-0.1473, -0.28886, 0.436],[0.615, -0.51499, 0.10001]]) for i in range(n_train): for j in range(32): for k in range(32): ...
<p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.tensordot.html" rel="nofollow noreferrer"><code>np.tensordot</code></a> -</p> <pre><code>np.tensordot(X_train, rgb2yuv_matrix, axes=([-1],[1])) </code></pre> <p>Basically, we are sum-reducing the last axis of <code>X_train</code> against...
performance|numpy|vectorization|array-broadcasting
3
11,245
41,641,205
How to avoid output into scrollable frames in jupyter notebook?
<p>Suddenly, output for statements started to appear inside scrollable frames.</p> <p>I was playing with only one parameter</p> <pre><code>pd.options.display.max_rows = 1000 </code></pre> <p>but after experiments, I commented this line out and restarted the kernel. </p> <p>Nevertheless, one of my outputs appears in...
<p>You can just use mouse to click on the outside of the output Frame to toggle between scrolling, it worked for me. More precisely, you have to click the square to the left of your output (see image). <a href="https://i.stack.imgur.com/uHEb5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uHEb5.png" alt="Whe...
python|pandas|ipython|jupyter-notebook
47
11,246
27,734,719
Smoothing a discrete data set
<p>I am attempting to a smooth this data set and produce a single representative curve with error bars. The method to acquire the data points was discretized with a fairly coarse step. I do not have much programming experience but am trying to learn. I read that a Gaussian filter might be a good option. Any help would ...
<p>Typically, you'd use a library for this, rather than implementing it yourself.</p> <p>I'm going to use <code>scipy.ndimage</code> for this instead of <code>scipy.signal</code>. If you've had a signal processing class, you'd probably find the <code>scipy.signal</code> approach more intuitive, but if you haven't it ...
python|numpy|scipy|curve-fitting|smoothing
5
11,247
27,564,671
True X/Y plot for a pandas series
<p>I have a pandas series with date/values where the dates are unevenly spaced, eg:</p> <pre><code>DATE 2014-12-04 0.000000 2014-12-05 250556.619700 2014-12-10 357143.631767 2014-12-20 435740.234867 ... </code></pre> <p>I'm trying to get a true X/Y plot where the spacing of the dates is reflected on ...
<p>It looks like your dates aren't <code>Timestamp</code> objects, and are instead strings. If you convert them to <code>Timestamp</code> objects then it will plot properly, <em>i.e.</em> it'll plot unevenly for uneven date spacing.</p> <p>To parse a column when using <a href="http://pandas.pydata.org/pandas-docs/stab...
python|matplotlib|pandas
2
11,248
61,206,552
Removing extra info after merging two dataframes
<p>The following code adds <strong>x</strong> after <em>Name</em> and <em>Price</em> as well as two additional columns <strong>Name_y</strong> and <strong>Price_y</strong>. How can I remove these items?</p> <pre><code>import pandas as pd df = pd.DataFrame ({ 'IP':['1.1.1.1','2.2.2.2','3.3.3.3','4.4.4.4','5.5.5....
<p>Idea is filter only columns for merge, here <code>IP</code> and <code>ID</code> for <code>df</code>:</p> <pre><code>new=(df1.merge(df[['IP','ID']],indicator=True,how='left', on=['IP', 'ID']) .loc[lambda x : x['_merge']=='left_only'] .drop('_merge',1)) </code></pre> <p>Or if removed <code>on</code> ...
python-3.x|pandas
1
11,249
61,400,273
Save/load a Keras model with (constant) parameters
<p>My case similar to, but a little different from, <a href="https://stackoverflow.com/questions/52413371/save-load-a-keras-model-with-constants">"Save/load a keras model with constants"</a></p> <p>I'm creating an object detection model (based on <a href="https://pjreddie.com/darknet/yolo/" rel="nofollow noreferrer">Y...
<p>You should use the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer#add_weight" rel="nofollow noreferrer"><code>add_weight</code></a> method from the inherited <code>Layer</code> class, using the <code>trainable=False</code> flag to avoid updating your constants:</p> <pre class="lang-py pret...
python|tensorflow|keras|deep-learning
0
11,250
61,409,463
Combine two dataframes in pandas
<p>I have 2 dataframes : </p> <p>df: </p> <pre><code>portfolio symbol id var1 var2 var3 </code></pre> <p>df1:</p> <pre><code>symbol sector market count </code></pre> <p>I want to add the columns sector and market from df1 to df. df1 has uniques values for symbol and hence a smaller dataframe than df whic...
<p>Have you tried doing an inner join,</p> <pre><code>df.merge(df1, on='symbol', how='inner') </code></pre>
python|pandas
1
11,251
68,832,602
Pandas read_sql_query with parameters for a string with no quotes
<p>I have want to insert a string of identifiers into a piece of sql code using</p> <pre><code>df = pd.read_sql_query(query, self.connection,params=sql_parameter) </code></pre> <p>my parameter dictionary looks like this</p> <pre><code>sql_parameter = {'itemids':itemids_str} </code></pre> <p>where itemids_str is a strin...
<p>I don't think there is a provision in params to send a list of numeric values for one condition. I always add such condition directly to the query</p> <pre><code>item_ids = [str(item_id) for item_id in item_ids] where_str = ','.join(item_ids) query = f&quot;&quot;&quot;SELECT xxx, yyy, zzz FROM ...
pandas|postgresql|parameters
2
11,252
68,649,542
Convert a for loop into a map() function approach in Python
<p>I am wondering how to convert a for loop into a map() function approach. Any efficient way to iterate over a list is more than welcome!</p> <pre><code>import feedparser import pandas as pd alist = [ &quot;http://finance.yahoo.com/rss/topstories&quot;, &quot;http://www.marketwatch.com/rss/topstories&quot; ] ...
<p>Simply create a function and pass the list element and call it from map.</p> <pre><code>import feedparser import pandas as pd alist = [ &quot;http://finance.yahoo.com/rss/topstories&quot;, &quot;http://www.marketwatch.com/rss/topstories&quot; ] def func(x): f = feedparser.parse(x) data = pd.DataFr...
python|pandas
2
11,253
36,355,296
How do I estimate the right parameters for a cumulative gaussian fit?
<p>I'm trying to fit a cumulative Gaussian distribution to my data, however the fits are clearly wrong. Why am I getting wrong means and standard deviations? Below you find my code and output.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm testrefratios=np.array([ 0.2, ...
<p>At the moment, nothing you're doing is telling the system that you're trying to fit a <em>cumulative</em> Gaussian. <code>norm.fit(Pn_final)</code> is doing its best under the assumption that <code>Pn_final</code> represents a <em>Gaussian</em>. </p> <p>One way would be to use <code>scipy.optimize.curve_fit</code...
python|numpy|curve-fitting|gaussian
4
11,254
4,912,046
Ordering an array for maximal pairwise matches
<p>I have an array:</p> <pre><code>array([[ 4, 10], [ 4, 2], [ 0, 7], [ 5, 11], [ 6, 8], [ 3, 6], [ 9, 7], [ 2, 11], [ 9, 5], [ 8, 1]]) </code></pre> <p>I want a method by which to order the value pairs so that as many as possible pairwise 2-elemen...
<p>You've described a graph where the vertices are numbers, and the edges are your pairs.</p> <p>Your conditions specify that each number appears once or twice in the list. This means that connected components in your graph are lines (or cycles). You can find them using this algorithm:</p> <ul> <li>[Line exists] If p...
python|arrays|numpy
5
11,255
53,101,655
Pandas - "time data does not match format " error when the string does match the format?
<p>I'm getting a value error saying my data does not match the format when it does. Not sure if this is a bug or I'm missing something here. I'm referring to <a href="http://strftime.org/" rel="nofollow noreferrer">this documentation</a> for the string format. The weird part is if I write the 'data' Dataframe to a csv ...
<p>There seems to be an issue with your date strings. I replicated your issue with your sample data and if I remove the hyphens and replace them manually (for the first three dates) then the code works</p> <pre><code>pd.to_datetime(df1['Date'] ,errors ='coerce') </code></pre> <p>output:</p> <pre><code>0 2018-07-0...
python|pandas|date|datetime
2
11,256
20,889,501
resampled time using scipy.signal.resample
<p>I have a signal that is not sampled equidistant; for further processing it needs to be. I thought that scipy.signal.resample would do it, but I do not understand its behavior.</p> <p>The signal is in y, corresponding time in x. The resampled is expected in yy, with all corresponding time in xx. Does anyone know wha...
<p>Even when you give the <code>x</code> coordinates (which corresponds to the <code>t</code> argument), <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.resample.html" rel="noreferrer"><code>resample</code></a> assumes that the sampling is uniform.</p> <p>Consider using one of the univariate ...
python|numpy|scipy|resampling
14
11,257
63,456,004
UTC to PDT/CDT/EDT pandas based on multiple columns
<p>&quot;Schedule&quot; and &quot;City&quot; are two columns of pandas dataframe df1. How will we convert the values in the column &quot;Schedule&quot; to PDT/CDT/EDT timezones based on local time of the city using PANDAS? Please note that there might be the change in date as well while converting the time from UTC to ...
<p>The pytz package has support for multiple timezones.<br /> The following code can convert your times to the given timezone:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np from dateutil.parser import parse import pytz city_to_timezone = { &quot;New York&quot;: &quot;US...
python|pandas|datetime
1
11,258
24,874,426
Plotting Circular contour lines in matplotlib
<p>I am trying to circular contour lines around an array of random values of radius. The result should be a bunch of concentric circles with different radius. However I am not too sure how to plot the theta so that for each radius, all values of theta is plotted to form a line.</p> <pre><code>import random import nump...
<p>A quick-and-dirty way to do it would be to use <code>np.linspace</code> to effectively draw a polygon (as I think you were attempting to do):</p> <pre><code>import numpy as np from matplotlib import pyplot as plt # some random radii r = np.random.rand(10) # 1000 angles linearly spaced between 0 and 2pi t = np.lin...
python|numpy|matplotlib|plot|scipy
1
11,259
30,249,859
How to compute variance with missing value in a DataFrame - Python Pandas?
<p>To be concrete, say we have a dataframe</p> <p>df1:</p> <pre><code>name date valueA valueB color A 12/1/14 3 10 red A 12/2/14 1 30 red B 12/1/14 2 30 green B 12/3/14 3 20 green C 12/3/14 4 40 white </code></pre> <p>The ra...
<pre><code>&gt;&gt;&gt; df.set_index(['date', 'name']).unstack().fillna(0).apply(var) name value A 1.5000 B 1.6875 C 3.0000 dtype: float64 </code></pre> <p>To arrange the DataFrame indexed on date with a MultiColumn for name and color:</p> <pre><code>df.set_index(['date', '...
python|join|pandas|merge|dataframe
1
11,260
29,978,390
How do I export multiple pivot tables from python using pandas to a single csv document?
<p>Say I have a function pivots() which aggregates pivot tables</p> <pre><code>def pivots(): d = data() #another function which cleans up my raw data price_floor = PF(d) no_floor = NF(d) return price_floor,no_floor </code></pre> <p>I know how to export a single pivot table</p> <pre><code>q,r = pivots...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow"><code>to_csv(path, mode='a')</code></a> to append files.</p> <pre><code># default 'w' write mode q.to_csv('C:\\export.csv') # explicitly specify 'a' append mode r.to_csv('C:\\export.csv', mode='a...
python|excel|pandas
1
11,261
53,373,322
TensorFlow Object Distance Detection
<p>I want to calculate the distance of detected Object using TensorFlow lite. And to calculate distance, I am using </p> <ul> <li><p>Focal Length: 4.42mm</p></li> <li><p>Real Height of object: 1620mm</p></li> <li><p>Camera frame Height: 696px</p></li> <li><p>Image Height: 228px</p></li> <li><p>Sensor height: 3.42mm</p...
<p>You may use detected object height/width and compare it to real object height/width. You would need some baseline of what the mapping is expected to be using a formula or photos you have taken. </p>
android|tensorflow-lite
0
11,262
53,745,871
Image analysis in C# with ML.Net
<p>I have thousands of jpegs in a folder structure. These images are a snapshot of my driveway in 2560 x 1440 and are taken and stored every 60 seconds.</p> <p>I'd like to create a program that can detect, from analyzing an image, whether I or my wife, was home at that particular time or not. I have a red car, she has...
<p>you might find something usefull here <a href="https://stackoverflow.com/questions/50929258/image-recognition-classification-using-microsoft-ml-net-0-2-machine-learning">Image recognition/classification using Microsoft ML.net 0.2 (Machine learning)</a> </p> <p>However I would encourage you to consider python as wea...
c#|tensorflow|machine-learning|ml.net
0
11,263
53,437,076
Plotting more than 2 Features for Decision Tree Classifier using matplotlib python
<h2>The Dataset</h2> <p>I've been playing around the <a href="https://github.com/jbrownlee/Datasets/blob/master/pima-indians-diabetes.data.csv" rel="nofollow noreferrer">Pima Indians Dataset</a> on Classifying using Decision Tree Classifier. However I've got my results and as obvious stage I've been looking for Visual...
<p>Here's how you can do it:</p> <pre><code>from itertools import product from matplotlib import pyplot as plt import numpy as np import scipy.stats as sts features = [np.linspace(0, 5), np.linspace(9, 14), np.linspace(6, 11), np.linspace(3, 8)] labels = ['height', 'we...
python|numpy|matplotlib
1
11,264
53,729,779
Pandas - Filtering out dates by day of week
<p>I have a Dataframe that contains dates along with day of the week. I am trying to filter out dates that fall on Monday or Tuesday.</p> <p>Given below is the view of my Dataframe and what I have tried doing thus far:</p> <pre><code>date, day_of_week 1/1/2018, Monday 1/2/2018, Tuesday 1/3/2018, Wednesday </code></pr...
<p>Try: </p> <pre><code>filtered_df = df.loc[df.day_of_the_week.isin(['Monday', 'Tuesday'])] </code></pre> <p>Output:</p> <pre><code> date day_of_the_week 0 1/1/2018 Monday 1 1/2/2018 Tuesday </code></pre>
pandas
1
11,265
53,630,041
batch size for LSTM
<p>I've been trying to set up an LSTM model but I'm a bit confused about batch_size. I'm using the Keras module in Tensorflow.</p> <p>I have <strong>50,000 samples</strong>, each has <strong>200 time steps</strong> and each time step has <strong>three features</strong>. So I've shaped my training data as <code>(50000,...
<p>If you provide your data as <code>numpy</code> arrays to <code>model.fit()</code> then yes, Keras will take care of feeding the model with the batch size you specified. If your dataset size is not divisible by the batch size, Keras will have the final batch be smaller and equal to <code>dataset_size mod batch_size</...
python|tensorflow|keras|lstm
2
11,266
17,172,472
values assigned to a numpy array do not always equal to the assigned values
<p>The following procedure results in values which do not always match the assigned ones:</p> <pre><code>from scipy.interpolate import splprep, splev, splrep import numpy as np pos2indx = lambda vec: vec.round().astype(np.int64) t = np.linspace(1,3,150) x = 150+100*np.sin(t) + 5*np.random.randn(len(t)) y = 150+100*n...
<p>To summarize your problem, adding <code>v</code> to an array of zeros and then substracting <code>v</code> doesn't always yield an array of zeros:</p> <pre><code>vector_field = np.zeros((x.max()+10,y.max()+10,z.max()+10,3), dtype=np.float64) vector_field[i,j,k,:] += v print np.sum(np.abs(vector_field[i,j,k,:]-v)) ...
python|numpy|scipy
2
11,267
72,082,210
removing columns with pandas from csv - not found in axis
<p>I'm trying to remove 1 column from .csv but I'm receiving an error.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df.drop(&quot;First Invoice #&quot;, axis = 1, inplace= True) </code></pre> <pre><code>KeyError: &quot;['First Invoice #'] not found in axis&quot; </code></pre> <p>Here you find...
<p>Mustansir is right, you can try changing your code with</p> <pre><code>import pandas as pd df.drop(&quot;First Invoice #&quot;, axis = 1, inplace = True) </code></pre> <p>If you refer to the pandas documentation for <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop.html" rel="nofollow noref...
python|pandas
1
11,268
71,810,481
Machine Learning Epochs and loss
<p>Input data = 11000 points with 10000 training and 1000 testing.</p> <p>I am using Keras Sequential LSTM, I am training it with batch size 128 and epochs 1000.</p> <p>I have noticed that over the first 100 the improvement of loss is very low and then over the next 100 the loss improves better than the first 100, Then...
<p>So you could imagine the loss with a sled ride down a hill. You start at the top and want to reach the bottom of the hill (the minima of your function). The closer you get to the bottom the lesser the loss. At first, the hill isn't that steep so you get to the bottom of the hill quite slow. As you go further down th...
python|tensorflow|machine-learning|keras
0
11,269
72,127,376
Reshape tensorflow tensors from feature columns into training samples
<p>Currently my dataset looks like:</p> <pre><code>feat_1 = tf.random.uniform( shape=[8000,1], minval=0, maxval=1, dtype=tf.dtypes.float32, seed=1123, name=None ) feat_2 = tf.random.uniform( shape=[8000,24], minval=0, maxval=1, dtype=tf.dtypes.float32, seed=1123, name=No...
<p>IIUC, you can try using <code>tf.data.Dataset.from_tensor_slices</code>:</p> <pre><code>import tensorflow as tf feat_1 = tf.random.uniform( shape=[8000,1], minval=0, maxval=1, dtype=tf.dtypes.float32, seed=1123, name=None ) feat_2 = tf.random.uniform( shape=[8000,24], minval=0, ...
python|tensorflow
1
11,270
22,311,139
Bar Chart: How to choose color if value is positive vs value is negative
<p>I have a pandas dataframe with positive and negative values and want to plot it as a bar chart.</p> <p>I want to plot the positive colors 'green' and the negative values 'red' (very original...lol).</p> <p>I'm not sure how to pass if &gt; 0 'green' else &lt; 0 'red'?</p> <pre><code>data = pd.DataFrame([[-15], [10], ...
<p>I would create a dummy column for whether the observation is larger than 0.</p> <pre><code>In [39]: data['positive'] = data['values'] &gt; 0 In [40]: data Out[40]: values positive a -15.0 False b 10.0 True c 8.0 True d -4.5 False [4 rows x 2 columns] In [41]: data['values'].plot(kin...
python|matplotlib|pandas
37
11,271
17,739,709
variable number of numpy array for loop arguments required to match variable column numbers
<p>I am populating a numpy array with a contents from a csv file. The number of columns in the CSV file may change. I am trying to concatenate the first two string columns (date + time) into a date object, and I have found an example for this on stackoverflow. However, this example would require me to make changes t...
<p>Try this:</p> <pre><code>date_objects = np.array([datetime.datetime.strptime(row[0] + row[1], "%Y-%m-%d%H:%M") for row in arr]) </code></pre>
python|numpy
1
11,272
18,161,926
Pandas data frame from dictionary
<p>I have a python dictionary of user-item ratings that looks something like this:</p> <pre><code>sample={'user1': {'item1': 2.5, 'item2': 3.5, 'item3': 3.0, 'item4': 3.5, 'item5': 2.5, 'item6': 3.0}, 'user2': {'item1': 2.5, 'item2': 3.0, 'item3': 3.5, 'item4': 4.0}, 'user3': {'item2':4.5,'item5':1.0,'item6':4.0}} <...
<p>Try following code:</p> <pre><code>import pandas sample={'user1': {'item1': 2.5, 'item2': 3.5, 'item3': 3.0, 'item4': 3.5, 'item5': 2.5, 'item6': 3.0}, 'user2': {'item1': 2.5, 'item2': 3.0, 'item3': 3.5, 'item4': 4.0}, 'user3': {'item2':4.5,'item5':1.0,'item6':4.0}} df = pandas.DataFrame([ [co...
python|pandas
19
11,273
8,624,732
Generating batches of n-dimensional Perlin noise using Python and NumPy
<p>I managed to grasp the way Perlin noise works and implement a pixel-at-a-time version using <a href="http://www.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf" rel="nofollow">this</a> awesome PDF as a reference, but, quite obviously it's incredibly slow.</p> <p>First thought would be to generate it as batches - in...
<p>If guess correctly, then Asmagedon wants to per-calculate his noise textures and then later paint them onto some other target of a different size. </p> <p>One way to do this is with <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.resample.html" rel="nofollow">scipy.signal.resample</a> whi...
python|numpy|perlin-noise
1
11,274
55,286,252
Pandas dataframe - add 'position index' based on condition
<p>Given</p> <pre><code>df = pd.DataFrame({"LOCATION":["USA","USA","USA","USA","USA","USA","USA","JAPAN","JAPAN"],"CAR":["BMW","BMW","BMW","BMW","BMW","TOYOTA","FORD","BMW","FORD"],"SALE_DATE":[2017,2017,2017,2018,2018,2018,2019,2019,2019]}) </code></pre> <p>Will result in: </p> <pre><code> CAR LOCATION SALE_D...
<p>Use <code>cumcount</code></p> <pre><code>df['POSITION'] = df.groupby('SALE_DATE').cumcount() </code></pre>
python|pandas|dataframe
2
11,275
55,540,028
Row merging over strings in a dataframe?
<p>I have a phone directory that stores Department, Title, Email and Extension on seperate rows, the things being in common are First and Last Name. I have combined First and Last Name as a Key, and would like to merge the rows to where you would end up with a single row with the Name, Title, Department, Email and Exte...
<p>First we use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer"><code>DataFrame.replace</code></a> to replace the whitespaces with <code>NaN</code>. Then use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame....
python|pandas|dataframe|data-science
1
11,276
55,267,490
Plotting pd.Series object does not show year correctly
<p>I am graphing the results of the measurements of a humidity sensor over time. I'm using Python 3.7.1 and Pandas 0.24.2.</p> <p>I have a list called dateTimeList with date and time strings:</p> <pre><code>dateTimeList = ['15.3.2019 11:44:27', '15.3.2019 12:44:33', '15.3.2019 13:44:39'] </code></pre> <p>I wrote thi...
<p>Add this immediately after creating the plot</p> <pre><code>import matplotlib.dates as mdates # this should be on the top of the script xfmt = mdates.DateFormatter('%Y-%m-%d') ax = plt.gca() ax.xaxis.set_major_formatter(xfmt) </code></pre> <p>My guess is that since March has less data points, Matplotlib prefers t...
python|pandas|plot|datetimeindex
0
11,277
55,300,042
Removing rows from csv file before a particular row based on values in that row using Pandas
<p>I have csv file and that looks like following. I want to remove all rows before one row values [Station Mac, First time seen,Last time seen, Power, packets, BSSID,Probed ESSIDs] for further processing.I am using panadad libarary in python to read this csv file. I am able to remove particular rows by index, but my fi...
<p>We can read the file and then <code>split</code> it into the list <code>s</code> with 2 strings, one with everything before the empty line (using <code>\n\n</code> as the separator) and one with everything after. When this is done we can read these strings as CSV into separate DataFrames:</p> <pre><code>with open('...
python|linux|pandas|csv
1
11,278
56,588,735
How to create a pandas DataFrame from the selected few parts of the string
<p>I have lines of string that look like below:</p> <pre><code>data = [15:07:29] (+?.?????????) host_name data: { cpu_id = 0 }, { var1 = 3, var2 = 4, var3 = 30, var4 = 87.7187 } [15:07:30] (+0:0:1) host_name data: { cpu_id = 0 }, { var1 = 4, var2 = 4, var3 = 29, var4 = 0.073525 } </code></pre> <p>I want a pandas Dat...
<p>I had a very similar problem lately. It looks complicated at first, but if you have the same number of variables in each row, it is actually very easy to construct the regex.</p> <pre><code>import re import pandas as pd data = """ [15:07:29] (+?.?????????) host_name data: { cpu_id = 0 }, { var1 = 3, var2 = 4, var3...
python|pandas|dataframe
1
11,279
56,631,161
Can I convert a text file to python dictionary?
<pre><code>d = dict((line.strip().split(' = ') for line in file(filename))) </code></pre> <p>I used this code, but printed an error.</p>
<p>I think there is a mistake in your code.</p> <p>Simply replace <code>file</code> with <code>open</code> like this:</p> <pre><code>d = dict((line.strip().split(' = ') for line in open(filename))) </code></pre>
python-3.x|tensorflow|dataset
0
11,280
56,739,501
Pandas- pivoting column into (conditional) aggregated string
<p>Lets say I have the following data set, turned into a dataframe:</p> <pre><code>data = [ ['Job 1', datetime.date(2019, 6, 9), 'Jim', 'Tom'], ['Job 1', datetime.date(2019, 6, 9), 'Bill', 'Tom'], ['Job 1', datetime.date(2019, 6, 9), 'Tom', 'Tom'], ['Job 1', datetime.date(2019, 6, 10), 'Bill', None], ...
<p>The tricky part here is removing the Manager from the Employee column.</p> <hr> <pre><code>u = df.melt(['Job', 'Date']) f = u[~u.duplicated(['Job', 'Date', 'value'], keep='last')].astype(str) f.pivot_table( index=['Job', 'Date'], columns='variable', values='value', aggfunc=','.join ).rename_axis(None,...
python|pandas|pivot-table|aggregation
4
11,281
25,858,881
Pandas reading HDFStore in Bottle - DeprecationWarning?
<p>I am attempting to read a few Pandas created HDF5 files in a simple web application using Bottle. In doing so, I'm receiving a DeprecationWarning when reading an HDFStore that was created outside of the Bottle app server.</p> <p>Environment:</p> <ul> <li>OSX: 10.9.4 </li> <li>Python: 2.7.8 (homebrew) </li> <li>pan...
<p>you don't normally run with DeprecationWarning enabled. In any event this is an innocuous warning from PyTables that the API changed (in 3.0.0) and eventually be changed. </p> <p>Pandas 0.15.0 (1 month or so for release) will use the new API and remove the warning.</p>
python|pandas|bottle|pytables
1
11,282
25,506,823
How to assign child objects to parent objects using pandas python
<p>I have a data frame in pandas that looks like the following:</p> <p>df = </p> <pre><code> Image_Number Parent_Object Child_Object 1 1 1 1 1 2 1 1 3 ...
<p>What you want to do is calculate something (counts) for <em>different values (groups)</em> of <code>Image_Number</code> and <code>Parent_Object</code>. This can be done with the <code>groupby</code> method (see here for the docs: <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">http:...
python|for-loop|pandas|dataframe
2
11,283
25,917,287
Pandas groupby - Expanding mean by column value
<p>I'm new to Pandas and somewhat lost on what to do here. I have a dataframe imported from a csv, which (heavily simplified) look like this:</p> <pre><code>date = ['2013-08-10','2013-08-10','2013-08-10','2013-08-10','2013-08-10', '2013-08-10','2013-08-10','2013-08-10','2013-08-10','2013-08-10'] event = ['213'...
<p>I think you're actually looking for an expanding mean, not a rolling mean. An expanding mean considers every previous value. I'll start where you left off:</p> <pre><code>In [63]: res = df.groupby(['event','side']).sum() In [64]: res Out[64]: value event side 213 A 0.193 B 0.312 ...
python|pandas
3
11,284
25,889,869
Sorting an Array Alongside a 2d Array
<p>So I'm using NumPy's linear algebra routines to do some basic computational quantum mechanics. Say I have a matrix, hamiltonian, and I want its eigenvalues and eigenvectors</p> <pre><code>import numpy as np from numpy import linalg as la hamiltonian = np.zeros((N, N)) # N is some constant I have defined # fill up ...
<p>You can use <code>argsort</code> as follows:</p> <pre><code>&gt;&gt;&gt; x = np.random.random((1,10)) &gt;&gt;&gt; x array([ 0.69719108, 0.75828237, 0.79944838, 0.68245968, 0.36232211, 0.46565445, 0.76552493, 0.94967472, 0.43531813, 0.22913607]) &gt;&gt;&gt; y = np.random.random((10)) &gt;&gt;&gt; ...
python|arrays|sorting|numpy
2
11,285
25,449,204
Mathematical Operation with non-unique index
<p>Not sure if the following applies only to <code>groupby().apply()</code>, but that's where I catch the following error when trying to divide a dataframe by a series when both have the same (but non-unique) index: </p> <pre><code>ValueError: cannot reindex from a duplicate axis </code></pre> <p>This is how I get th...
<p>If you just want this code to work, just replace the return with this, which uses the numpy divide function, which will broadcast on shape and not try to match indicies:</p> <pre><code>np.divide(diff, pd.DataFrame(time_intvall)) </code></pre> <p>One other thing, this line</p> <pre><code>group.iloc[1:][columns] - ...
python|pandas
2
11,286
26,163,727
How to test if all rows are equal in a numpy
<p>In numpy, is there a nice idiomatic way of testing if all rows are equal in a 2d array?</p> <p>I can do something like</p> <pre><code>np.all([np.array_equal(M[0], M[i]) for i in xrange(1,len(M))]) </code></pre> <p>This seems to mix python lists with numpy arrays which is ugly and presumably also slow. </p> <p>Is...
<p>One way is to check that every row of the array <code>arr</code> is equal to its first row <code>arr[0]</code>:</p> <pre><code>(arr == arr[0]).all() </code></pre> <p>Using equality <code>==</code> is fine for integer values, but if <code>arr</code> contains floating point values you could use <a href="https://docs...
python|arrays|numpy
27
11,287
67,093,837
How to load file from custom hosted Minio s3 bucket into pandas using s3 URL format?
<p>I have Minio server hosted locally. I need to read file from minio s3 bucket using pandas using S3 URL like &quot;s3://dataset/wine-quality.csv&quot; in Jupyter notebook.</p> <p>I tried using s3 boto3 library am able to download file.</p> <pre><code>import boto3 s3 = boto3.resource('s3', endpoint_url...
<p>Pandas v1.2 onwards allows you to pass storage options which gets passed down to <code>fsspec</code>, see the docs here: <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html?highlight=s3fs#reading-writing-remote-files" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/user_gu...
python-3.x|pandas|jupyter-notebook|minio
3
11,288
66,783,425
add a sequence of numbers to a column in pandas data frame in Python
<p>I have a data frame and I want to add a column with values 0, 0.005, 0.010, 0.015...up to the length of the df, how do I proceed? thanks</p>
<p>Only Pandas:</p> <pre class="lang-py prettyprint-override"><code>df = df.assign(newcol=pd.Series(range(df.shape[0])) * 0.005) </code></pre> <p>Using Numpy:</p> <pre class="lang-py prettyprint-override"><code>df = df.assign(newcol=np.arange(df.shape[0]) * 0.005) </code></pre>
python|pandas
1
11,289
66,788,096
Drop rows in dataframe whose column has more than a certain number of distinct values
<p>I have an example dataframe as given below, and am trying to drop the rows where the column <code>cluster_num</code> has only 1 distinct value.</p> <pre><code>df = pd.DataFrame([[1,2,3,4,5],[1,3,4,2,5],[1,3,7,9,10],[2,6,2,7,9],[2,2,4,7,0],[3,1,9,2,7],[4,9,5,1,2],[5,8,4,2,1],[5,0,7,1,2],[6,9,2,5,7]]) df.rename(column...
<h3><code>groupby</code>/<code>filter</code></h3> <pre><code>df.groupby('cluster_num').filter(lambda d: len(d) &gt; 1) </code></pre> <hr /> <h3><code>duplicated</code></h3> <pre><code>df[df.duplicated('cluster_num', keep=False)] </code></pre> <hr /> <h3><code>groupby</code>/<code>transform</code></h3> <p>Per <a href="h...
python|pandas|dataframe
1
11,290
67,183,757
Panda operation on large dataset using jupiter
<p>I have a very large csv file (10Go) A small example:</p> <pre><code> timestamp LAT LON 0 2018-10-18T00:00:00 36.97696 -89.10680 1 2018-10-18T00:00:00 46.08972 -122.92928 2 2018-10-18T00:00:00 48.10739 -122.77227 3 2018-10-18T00:00:00 28.72571 -89.52151 4 2018-10-18T00:00:00 61.11447...
<p>If you think it is a resource issue you should slice the data up and process the transformation in small batches. I would try a generator.</p>
python|pandas
1
11,291
66,895,928
Why is pandas not allowing me to create a new column for this dataframe and throwing a setting with copy warning?
<p>I'm trying to create a column in a dataframe using the following code:</p> <pre><code>df['engagement_clicks_event_subscribers'] = df['brands_publishers_lifetime_clicks'] / df['brands_publishers_lifetime_events'] / df['content_subscriber_count'] </code></pre> <p>For some reason, this simply does NOT run. It throws a ...
<p>I figured it out.</p> <p>Purely a Pycharm issue.</p> <p>I'm using the Pycharm debugger and for some reason, the dataframe doesn't update in the &quot;Variables&quot; window of the debugger.</p> <p>When I Data View to view it as a dataframe, I can see the columns – I imagine it would work the same way if I were to do...
python|pandas|dataframe
0
11,292
66,876,874
Declarative way to return all indices of matching elements for each element in numpy?
<p>Say I have an array:</p> <pre><code>arr = [1, 1, 2, 2, 1] </code></pre> <p>I want to get an array <code>indices</code> where each element <code>indices[i]</code> is the list of indices having values equal to the value at <code>arr[i]</code>. i.e., <code>indices</code> should be</p> <pre><code>[[0, 1, 4], [0, 1, 4], ...
<pre class="lang-py prettyprint-override"><code>import numpy as np arr = np.array([1, 1, 2, 2, 1]) f = lambda i: np.where(arr == i) result = np.array(list(map(f, arr))) </code></pre> <p>result is:</p> <pre><code>array([[array([0, 1, 4])], [array([0, 1, 4])], [array([2, 3])], [array([2, 3])], ...
arrays|numpy|indexing
0
11,293
10,951,341
Pandas DataFrame aggregate function using multiple columns
<p>Is there a way to write an aggregation function as is used in <code>DataFrame.agg</code> method, that would have access to more than one column of the data that is being aggregated? Typical use cases would be weighted average, weighted standard deviation funcs.</p> <p>I would like to be able to write something like...
<p>Yes; use the <code>.apply(...)</code> function, which will be called on each sub-<code>DataFrame</code>. For example:</p> <pre><code>grouped = df.groupby(keys) def wavg(group): d = group['data'] w = group['weights'] return (d * w).sum() / w.sum() grouped.apply(wavg) </code></pre>
python|pandas
117
11,294
68,255,328
Calcuations on column combinations in a numpy array
<p>Supposing that I have the following <code>numpy</code> array / <code>pandas</code> df:</p> <pre><code>| 0 | 1 | 2 | 3 | 4 | 5 | 6 | | -- | -- | -- | -- | -- | -- | -- | | 39 | 27 | 36 | 30 | 32 | 29 | 40 | | 36 | 26 | 32 | 37 | 30 | 40 | 28 | | 32 | 40 | 35 | 30 | 28 | 39 | 31 | | 27 | 34 | 28 | 28 | 31 | 35 ...
<blockquote> <p>To rephrase the question, how would you perform a certain function by choosing all possible pairs from the column to create a 2D array..</p> </blockquote> <p>Assuming you have a dataframe <code>df</code> with shape <code>(n, m)</code>, ie:</p> <pre><code>n, m = df.shape </code></pre> <p>Use np.mgrid to ...
python|arrays|numpy|array-broadcasting
1
11,295
68,029,884
How to count values since the first non nan value?
<p>I have this <code>df</code>:</p> <pre><code> CODE TMAX 0 000130 NaN 1 000130 NaN 2 000130 32.0 3 000130 32.2 4 000130 31.1 5 158328 22.5 6 158328 8.8 7 158328 NaN 8 158328 NaN 9 158328 9.2 ... ... ... </code></pre> <p...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.notna.html" rel="nofollow noreferrer"><code>Series.notna</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cummax.html" rel="nofollow noreferrer"><code>Series.cummax</code></a> for filt...
python|pandas
1
11,296
59,189,131
How can I identify upscaled images?
<p>Are there any methods that I may employ to identify 'false' 4K images? i.e. Images that have been upscaled to 4K from 720p/1080p. </p> <p>I have tried searching but I have mainly only found methods to upscale images with different methods like Billinear, Bicubic, Lanczos , SRCNN and EDSR. </p> <p>How may I then id...
<p>You should try.</p> <p>Short message potentially you can do it with a CNN, trained on the two class problem upscaled/not upscaled. I actually would train it to even identify the method, as it seems to be an easier problem. I guess you need more images though. Secondly to train a CNN on such large resolution images ...
tensorflow|machine-learning|keras|deep-learning|computer-vision
1
11,297
59,359,462
Generate new column in pandas dataframe based on conditional statement
<p>I have 2 pandas dataframes. The first one contains information about latitude and longitude of station and has only 3 rows:</p> <pre><code> stat_id stat_lon stat_lat 0 db_695203 9.444328 54.787590 1 db_699007 9.438629 54.789577 2 db_695442 9.445865 54.786215 </code></pre> <p>The seco...
<p>First define a function that given a row iterates over the station list and counts if the station is contained within the polygon. Then apply this function on each row of the polygon list DataFrame.</p> <pre><code>def num_stations(polygon): """Count the number of stations that are within a given polygon.""" num...
python|pandas|polygon|shapely
1
11,298
44,977,239
Exog variable with not appropriated shape on Statsmodels SARIMAX get_prediction
<p>I have a very simple Sarimax model using statsmodels:</p> <pre><code>mdl = sm.tsa.statespace.SARIMAX(ts_monthly, exog=ts_exog, order=(3,1,0)).fit() </code></pre> <p>where <code>ts_monthly</code> and <code>ts_exog</code> are pandas series indexed by date:</p> <pre><code>df date vl_1 vl_2 2016-01-01 ...
<p><a href="https://stackoverflow.com/questions/22053050/difference-between-numpy-array-shape-r-1-and-r">This answer may be helpful</a>.</p> <p>While your prediction series is in a pandas Series (and is therefore a numpy ndarray), the shape (3,) indicates that it only has one index (i.e. you access its values with a s...
python|pandas|statsmodels
1
11,299
45,012,974
What's the difference between the shapes in tf.shape(tensor) and print(tensor)
<p>To say, i have a tensor <code>matrix</code>:</p> <pre><code>matrix=tf.convert_to_tensor([[1,1,1,1],[0,0,0,0]],dtype=tf.float32) </code></pre> <p>and i get the shape of matrix using <code>tf.shape(matrix)</code>, the result is</p> <pre><code>&lt;tf.Tensor 'Shape_2:0' shape=(2,) dtype=int32&gt; </code></pre> <p>ho...
<p>The method <a href="https://www.tensorflow.org/api_docs/python/tf/shape" rel="nofollow noreferrer">tf.shape()</a> returns a new tensor containing the shape of the input tensor. The returned tensor is completely different than the input tensor.</p> <pre><code>&gt;&gt;&gt; import tensorflow as tf &gt;&gt;&gt; matrix ...
tensorflow|shapes
1