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
17,400
22,845,856
Performance issues with groupby's last in pandas
<p>I have a DataFrame with two columns and a little over one-hundred thousand elements.</p> <pre><code>In [43]: df.head(10) Out[43]: localtime ref 4 2014-04-02 12:00:00.273537 139058754703810577 5 2014-04-02 12:00:02.223501 139058754703810576 6 2014-04-02 12:00:03.518817 13905...
<p>Must be something odd going on....looks ok in 0.13.1 (and master). Post a link to your file and i'll take a look.</p> <pre><code>In [3]: rng = date_range('20130101',periods=20,freq='s') In [4]: df = DataFrame(dict(timestamp = rng.take(np.random.randint(0,20,size=100000)), value = np.random.randint(0,100,size=10000...
python|pandas
4
17,401
29,441,324
Unable to use Pandas and NLTK to train Naive Bayes (machine learning) in Python
<p>Here is what I am trying to do. I have a csv. file with column 1 with people's names (ie: "Michael Jordan", "Anderson Silva", "Muhammad Ali") and column 2 with people's ethnicity (ie: English, French, Chinese).</p> <p>In my code, I create the pandas data frame using all the data. Then create additional data frames:...
<p>There could be many problems when it comes why you don't get the desired results, most often it's either:</p> <ul> <li>Features are not strong enough</li> <li>Not enough training data</li> <li>Wrong classifier</li> <li>Code bugs in NLTK classifiers</li> </ul> <p>For the first 3 reasons, there's no way to verify/re...
python-2.7|pandas|machine-learning|nltk|naivebayes
0
17,402
29,682,587
MemoryError in IPython (using Windows)
<p>I've been trying to initialize an numpy array of integers in IPython that is 1000 x 1000 x 120, and every time I get a <code>MemoryError</code>. I don't know why this would be the case since it's really not that big of an array. </p> <p>My code is simply:</p> <pre><code>bigLattice = np.zeros((numsimulations,end2+1...
<p>The default type for floating point numbers is float64, so the size of your matrix is 915Mb</p> <pre><code>In [1]: a = np.zeros((1000,1000,120)) In [2]: %whos Variable Type Data/Info ------------------------------- a ndarray 1000x1000x120: 120000000 elems, type `float64`, 960000000 bytes (915 M...
python|memory|numpy
3
17,403
29,637,133
Python Pandas Timestamp Subtraction vs. Numpy
<p>I am having an odd issue when subtracting Timestamps in pandas (version 15.2) on Python 3.4 </p> <p>Incorrect</p> <pre><code>y = pd.Timestamp('2015-04-14 00:00:00') z = pd.Timestamp('2015-04-14 00:01:01') np.timedelta64(z-y) &gt;&gt;&gt;numpy.timedelta64(1000000,'us') </code></pre> <p>Correct</p> <pre><code>w =...
<p>Seems to be an issue with Pandas 0.15.2. Upgrading to 0.16.0 solves the issue.</p>
python|numpy|pandas
1
17,404
62,467,110
Matplotlib interface
<p>I'm new in matplotlib and I have confusion on matplotlib interface. I'm reading pandas and matplotlib documentation and in the pandas one I read "the existing interface dataframe. Boxplot" (in a particular case). What does "existing interface" mean?</p> <p>Here the link: <a href="http://pandas.pydata.org/pandas-doc...
<p>The &quot;existing interface&quot; is the syntax used for plotting which is <code>dataFrame.hist()</code>. The &quot;new interface&quot; is the newer syntax which is <code>dataframe.plot.hist()</code>. They will have differences int heir functionality but both are usable to produce boxplots.</p>
pandas|matplotlib|interface|jupyter-notebook
0
17,405
62,391,498
Combine code and print result to excel .csv file
<p>I have 2 script files in python</p> <p>1, This one keeps only numbers and remove characters that are not.</p> <pre><code>import pandas as pd import re from re import sub data = pd.read_csv("C:/Path_to_csv_file.csv") data.columns=["var1", "var2", "var3"] var1_list = list(data.var1) var2_list = list(data.var2) v...
<p>Hi I suggest that you make your .csv file to a pandas dataframe and then use the method pd.concat(....). Hope this helps!</p>
python|excel|pandas|csv
1
17,406
62,134,014
Bar chart with bars from two different dataframes
<p>I have the following dataframes:</p> <pre><code> import pandas as pd import numpy as np import matplotlib.pyplot as plt df_One = pd.DataFrame({'Category': ['1024Sen', '1024Act', '2089Eng', '2089Sen'], 'Qtd_Instrumentation': [18, 5, 25, 10]}) df_Two = pd.D...
<p>This is one way to do it by choosing the <code>align='edge'</code> option and then using positive width for one bar and negative width for another. This will make them aligned next to each other. Also, you have to call <code>plt.legend()</code> to display the legends</p> <pre><code>fig, ax = plt.subplots() index =...
python|pandas|matplotlib|grouped-bar-chart
1
17,407
62,270,808
Remove rows where a column contains a specific substring
<p>how to eliminate rown that have a word i don't want? I have this DataFrame:</p> <pre><code>index price description 0 15 Kit 10 Esponjas Para Cartuchos Jato De Tinta ... 1 15 Snap Fill Para Cartuchos Hp 60 61 122 901 21 ... 2 16 Clips Para Cartuchos Hp 21 22 60 74 75 92 93 ... </...
<p>Create a boolean mask by checking for strings that contain <code>'Esponjas'</code>, then index into your dataframe with the negated mask.</p> <pre><code>df[~df['description'].str.contains('Esponjas')] </code></pre> <p>If you are unsure what's going on, print out what </p> <pre><code>df['description'] df['descript...
python|pandas|dataframe
4
17,408
62,294,295
Python Pivot: Can I get the count of columns per row(id/index) and store it in a new columns?
<p>hope you can help me this. The df looks like this.</p> <p>region AMER </p> <pre><code> country Brazil Canada Columbia Mexico United States metro Rio de Janeiro Sao Paul...
<p>You may want to try </p> <pre><code>df['new']df.sum(level=0, axis=1) </code></pre>
python|pandas|pivot
0
17,409
62,155,474
Remove Columns And Create Unique Row For Each Removed Column Pandas Dataframe
<p>This is a really tricky issue I've run into which is slamming my memory management, here's the setup:</p> <p>I have a dataframe with the following column setup:</p> <pre><code>Unique1 Unique2 Unique3 d_1 d_2 d_3..... d_2000 A B C 1 4 0 100 </code></pre> <p>I want to remove the d_1.....
<p>Pandas has a solution for this : <a href="https://pandas.pydata.org/docs/reference/api/pandas.melt.html" rel="nofollow noreferrer">melt</a></p> <pre><code>df.melt(id_vars=['Unique1','Unique2','Unique3'], var_name='d_index', value_name='d_value') .sort_values('Unique1', ignore_index=True) Unique...
python|pandas|dataframe
1
17,410
51,257,041
How to perform contain operation between a numpy array and a vector row-wise?
<p>Now I have a numpy array,</p> <pre><code>[[1 2] [3 4] [2 5]] </code></pre> <p>and a vector.</p> <pre><code>[2, 5, 2] </code></pre> <p>I want to perform a contain operation between the array and the vector row wise. In other words, I want to check whether the first row <code>[1, 2]</code>contain <code>2</code...
<p>You can broadcast the vector into a column, equate it to all the elements in the rows of the matrix, and see if <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.any.html" rel="nofollow noreferrer"><code>any</code></a> element is <code>True</code> in each row:</p> <pre><code>import numpy as np a ...
python|numpy
7
17,411
51,333,569
groupby pandas dataframe, take difference between value of latest and earliest date
<p>I have a Cumulative column and I want to <code>groupby</code> index and take the values corresponding to the latest date minus the values corresponding to the earliest date.</p> <p>Very similar to this: <a href="https://stackoverflow.com/questions/41525911/group-by-pandas-dataframe-and-select-latest-in-each-group">...
<p>I'm a python rookie, and here is my solution:</p> <pre><code>import pandas as pd from io import StringIO csv = StringIO("""index id product date 0 220 6647 2014-09-01 1 220 6647 2014-09-03 2 220 6647 2014-10-16 3 826 3380 2014-11-11 4 826 3380 2014-12-09 5 ...
pandas|pandas-groupby|difference
0
17,412
51,359,567
update pandas dataframe column not work on first time
<p>I have a dataframe concated from some other dataframes, then I need to update some values in one column, and found that I have to do the same update twice. To find out what happened, I save the dataframe to disk and reload it, then do the update, now it works on the first time.</p> <p>Is it a bug of pandas or I mad...
<p>I checked the data and found some trades are :</p> <pre><code>11.化学纤维制造业 11.印刷和记录媒介复制业 ... </code></pre> <p>After the first substitution, they becomes:</p> <pre><code>1.化学纤维制造业 1.印刷和记录媒介复制业 ... </code></pre> <p>That's why I have to substitute 2 times. I changed my pattern from <code>'^(?\d?\.?\)?(其中:)?'</code> t...
python|pandas
0
17,413
51,426,533
ASYNC - Pandas read_sql and asyncio?
<p>Could someone please point me in the right direction on how to solve this following problem. I am trying to come up with a solution using pandas.read_sql and asyncio. I want to migrate table records from 1 database to another database.</p> <p>I want to do the following:</p> <pre><code>table 1 . . . table n </code>...
<p>asyncio is about organizing non-blocking code into callbacks and coroutines. Running CPU-intensive code in parallel is a use case for threads:</p> <pre><code>from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor() as executor: frames = list(executor.map(extract, all_tables)) </code></pre> ...
python|pandas|python-asyncio|python-3.7
3
17,414
48,288,043
Pandas ordinary linear regression based on dt year-weeknumber (as of 2018)?
<p>I've been looking for the most current method to create a linear regression model given a Pandas Dataframe.</p> <p>DF looks like:</p> <pre><code>+---------------------+-------------+--------------------+--------------------+ | Date | YearWeekNum | Dependent_Variable | Bonus_Grouping_Int | +---------...
<p>This is the "solution" that I was able to make work:</p> <p>First, I only wanted weeks 1-52, not to include 0 or 53.</p> <pre><code>df['YearWeekNum'] = df['Date'].dt.strftime('%Y-Wk%U') df.loc[df['YearWeekNum'].str.contains('Wk53') == True, 'YearWeekNum'] = '2017-Wk52' df.loc[df['YearWeekNum'].str.contains('Wk00')...
python|pandas|linear-regression
0
17,415
48,309,346
Learn the sum of two numbers in Tensorflow
<p>I'm trying to train a neural network to predict the sum of two numbers. But I don't understand what's wrong with my model. Model consists of 2 inputs, 2 hidden and 1 output layers. Every 1000 iteration I print test execution, but the result is getting smaller and smaller.</p> <pre><code>import numpy as np import te...
<p>Cross-entropy loss is used for <em>classification</em> problems, while your task is clearly a <em>regression</em>. The computed <code>cross_entropy</code> value doesn't make sense, hence the result.</p> <p>Change your loss to: </p> <pre><code>cross_entropy = tf.reduce_mean( tf.nn.l2_loss(y_ - y2) ) </code></pr...
python|tensorflow|machine-learning|neural-network|deep-learning
3
17,416
48,236,922
Convert and Assign Pandas Series to a dataframe to create CSV
<p>I've got order data with SKUs inside and would like to find out, how often a SKU has been bought per month over the last 3 years.</p> <pre><code>for row in df_skus.iterrows(): df_filtered = df_orders.loc[df_orders['item_sku'] == row[1]['sku']] # Remove unwanted rows: df_filtered = df_filtered[['txn_id',...
<p>I do these kind of calculations all the time and this seems to be the fastest. </p> <pre><code>import pandas as pd df_orders = df_orders[df_orders["item_sku"].isin(df_skus["sku"])] monthly_sales = df_orders.groupby(["item_sku", pd.Grouper(key="date",freq="M")]).size() monthly_sales = monthly_sales.unstack(0) month...
python|pandas
2
17,417
48,372,837
Tensorflow Estimator API: How to pass parameter from input function
<p>I'm trying to add class weights as a hyperparameter for my model, but to calculate weight I need to read input data, this happens inside input_fn which then passed to <code>estimator.fit()</code>. An output of <code>input_fn</code> are only features, labels which should have same shape num_examples * num_features. M...
<p>Both features and labels can be dictionary of tensors (not just one tensor). The tensors can be any shape you want though it's common to be num_examples * ...</p> <p>If you don't use any of the predefined estimators, the easiest way would be to add another feature with what you need to compute the weights, compute ...
tensorflow|tensorflow-estimator
1
17,418
48,400,602
Finding areas in 2d array with python
<p>Let's say I have the following 2d array:</p> <pre><code>[ [1,1,1,2,2], [1,1,2,3,2], [2,2,2,3,1], [2,1,0,3,2], [2,0,3,3,0]] </code></pre> <p>As can be seen, there are zones in the 2d array with the same values, if the amount of cells in a zone is 5 or higher, the values become zero, resulting in the following array...
<p>Here's my DFS-like approach to this problem (Complexity O(rows * columns)):</p> <pre><code># given array ayyyarray = [ [1,1,1,2,2], [1,1,2,3,2], [2,2,2,3,1], [2,1,0,3,2], [2,0,3,3,0]] # function that mark "color" on cell and call take_a_tour for all neighbours with the same number def take_a_tour(ayyyarray, visite...
python|arrays|algorithm|numpy|multidimensional-array
0
17,419
48,350,693
What is numpy method int0?
<p>I've seen <code>np.int0</code> used for converting bounding box floating point values to int in OpenCV problems.</p> <p>What exactly is <code>np.int0</code>? </p> <p>I've seen <code>np.uint8</code>, <code>np.int32</code>, etc. I can't seem to find <code>np.int0</code> in any online documentation. What kind of int ...
<p><code>int0</code> is an <a href="https://github.com/numpy/numpy/blob/95b435aa91c7259256b5c8a35c92c942f4eeb7d0/numpy/core/numerictypes.py#L372" rel="noreferrer">alias for <code>intp</code></a>; this, in turn, is</p> <blockquote> <p>Integer used for indexing (same as C ssize_t; normally either <code>int32</code> or...
python|numpy|methods|int
26
17,420
48,807,382
Is it possible to make tensorflow graph summary?
<p>I'm aware of Tensorboard and how awesome it is, but I think that simple console output with current graph summary is better (and faster) for prototyping purpose. And also know that I can generate tensorboard graph after simply running session with last network node as shown <a href="https://stackoverflow.com/questio...
<p>It's certainly possible. If you are using <code>tf.keras</code> wrapper to build you can easily visualize the graph, even before <code>model.compile()</code> method executes. It's <code>keras</code> built-in functionality called <a href="https://keras.io/api/utils/model_plotting_utils/" rel="nofollow noreferrer"><co...
tensorflow|keras|tensorboard
2
17,421
48,464,597
Tensorflow convolution vs. Tensorflow multiplication and sum vs. Numpy multiplication and sum
<p>I am experiencing different results (on 16th least significant bit) while performing a single step of a dot product, implemented differently in TF and numpy. </p> <p>The inputs are float32 5x5 image and 5x5 kernel.</p> <pre><code>i = tf.constant(I2D, dtype=tf.float32, name='i') k = tf.constant(K2D, dtype=tf.fl...
<p>I believe the default <code>dtype</code> for these numpy arrays <code>I2D</code> and <code>K2D</code> is <code>np.float64</code>, so all operations are 64-bit. But you're comparing it to 32-bit operations result in tensorflow.</p> <p>I've changed the <code>dtype=tf.float64</code> and got the same result up to the l...
python|numpy|tensorflow|conv-neural-network|convolution
0
17,422
70,757,028
pandas.Grouper for time intervals behavior
<p>Having a DF of ids and timestamps, like:</p> <pre><code> id timestamp idx 0 1 2021-10-24 17:56:03.641 0 1 1 2021-10-24 17:56:04.086 1 2 1 2021-10-24 17:56:11.217 2 </code></pre> <p>I'm trying to group time ranges in each id by 5 minutes and set the first idx of each group to the entire ra...
<p>I think this is because group[er origin is looking at first timestamp in the entire series, and not per grouped id.</p> <p>This seems to work:</p> <pre><code>def tgs(df): df_list = [g for _,g in df.groupby('id')] res_list = [] for df_s in df_list: g = df_s.groupby([pd.Grouper(key=&quot;timestamp&quot;, fre...
python|pandas|group-by|timestamp
1
17,423
70,798,689
Torchscript trace "must be on the current device" error despite model and input both being on the same device
<p>I am failing to run torch.jit.trace despite my best effort, encountering <code>RuntimeError: Input, output and indices must be on the current device</code></p> <p>I have a (fairly complex) model which I have already put on GPU, along with a set of inputs, also on GPU. I can verify that all input tensors and model pa...
<p>After hard-coding the trace command into my code, I was able to get a more precise stack trace which let me to this piece of code, which I simplified for ease of reading:</p> <pre><code>B, L, C, H, W = inp_seq.shape ref_seq = torch.repeat_interleave( ref_seq.squeeze(dim=1), repeats=L, dim=0, ) </code></p...
pytorch|torchscript
0
17,424
64,595,278
How to split a pandas dataframe on the frequency of values
<p>I am interested in separating this data frame into 20 smaller dataframes based on the frequency of entries in column B. B has numerical entries, some of these are repeated several times, as can be seen below.</p> <pre><code> A (index) B (Column of interest) 0 1 1 ...
<ul> <li><p>Count the occurrence of each value in the dataframe, bin the frequency ranges in groups of 10, and then create a <code>dict</code> of <code>DataFrames</code> for each range.</p> <ol> <li>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="nofollow no...
python|pandas|dataframe
3
17,425
64,573,426
Removing numpy array columns with the same non-missing value, when missing values present
<p>I have a numpy array from which I need to remove columns which have the same value for non-missing cells, and remove columns with all values missing. The array:</p> <pre><code>&gt;&gt;&gt; x = np.array([[ 1., 2., 2., np.NaN, 2., 2., 1.], [ 2., np.NaN, 1., np.NaN, 2., 2., 1.], [np.NaN, 1., 1....
<p>You could chain several masks using bitwise operators. You basically need two masks.</p> <ul> <li>One for the <code>NaNs</code></li> <li>One to check if the first row values are equal to the rest of the column</li> </ul> <p>Then chain both conditions with a bitwise <code>OR</code>, and check if <code>all</code> rows...
python|arrays|numpy|missing-data
0
17,426
49,176,370
Uppercase Last Couple Indexes of String Elements in Pandas Series
<p>I have the following pandas series:</p> <pre><code>test_series = pd.Series(['canton, nc', 'leicester, nc', 'asheville, nc', 'candler, nc', 'marshall, nc', 'waynesville, nc', 'fletcher, nc', 'hendersonville, nc', 'old fort, nc', 'horse shoe, nc', 'black mountain, nc', 'maggie valley, nc', 'burns...
<p>First select all values without last 2 and add to last 2 values converted to uppercase by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.upper.html" rel="nofollow noreferrer"><code>str.upper</code></a>:</p> <pre><code>test_series = test_series.str[:-2] + test_series.str[-2:].str.up...
string|python-3.x|pandas|methods|series
2
17,427
49,172,770
Python - Replacing column by indexing removes imaginary components
<p>I am trying to replace an array of 0's column by column like this </p> <pre><code>import numpy as np a = np.zeros((2,10)) b = np.linspace(1,10,10) a[1,:] = b </code></pre> <p>which gives the correct output</p> <pre><code>a = [[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10....
<p>I have just realised this is due to the zero matrix being a different type of data and is fixed by using</p> <pre><code>a = np.zeros((2,2),dtype = np.complex) </code></pre> <p>for reference if anyone else has the same problem</p>
python|arrays|numpy|indexing
1
17,428
49,148,768
split all list columns of a pandas dataframe
<p>I have a <code>dataframe</code> with many columns</p> <pre><code>df= c1\ 2015-01-01 [50.4750711276, 50.4750711276, 50.4750711276] 2015-01-02 [50.5349107929, 50.5349107929, 50.5349107929] c2 2015-01-01 ...
<p>Use <code>list comprehension</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a>:</p> <pre><code>comp = [pd.DataFrame(df[x].values.tolist(), index=df.index).add_suffix('_code_' + x) for x in df.columns] df = pd.co...
python|pandas|dataframe
3
17,429
49,101,269
Does tf.trace() only evaluate diagonal elements?
<p>I have a TensorFlow tensor <code>t</code> with shape <code>(d,d)</code>, a square matrix. I define the trace tensor <code>tr = tf.trace(t)</code>. Now <code>tr</code> is evaluated, using <code>session.run(tr)</code>: Is TensorFlow smart enough to only evaluate the diagonal elements of <code>t</code>, or are all elem...
<p>TensorFlow will compute the matrix first, then run the trace op to extract/sum the diagonal. Potentially this is something that <a href="https://www.tensorflow.org/performance/xla/" rel="nofollow noreferrer">XLA</a> could optimize away if no other ops consume the full matrix (not sure if it does or not currently), b...
tensorflow
1
17,430
49,050,710
Compare tables to create presence/absence matrix filling empty without decimals
<p>Command line:</p> <p>files can be found at git-hub.</p> <p>File1: </p> <p><a href="https://raw.githubusercontent.com/felipelira/files_to_test/master/file1.txt" rel="nofollow noreferrer">https://raw.githubusercontent.com/felipelira/files_to_test/master/file1.txt</a></p> <p>File2:</p> <p><a href="https://raw.gith...
<p>If want use your original solution add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow noreferrer"><code>fillna</code></a> with cast to <code>int</code>:</p> <pre><code>testdf = g.join(pd.get_dummies(g['accession'].apply(pd.Series).stack()).sum(level=0)).dr...
python|pandas|pandas-groupby
2
17,431
58,977,262
Extract intermmediate variable from a custom Tensorflow/Keras layer during inference (TF 2.0)
<p>A bit of background: </p> <p>I've implemented an NLP classification model using mostly Keras functional model bits of Tensorflow 2.0. The model architecture is a pretty straightforward LSTM network with the addition of an Attention layer between the LSTM and the Dense output layer. The Attention layer comes from...
<p>After a little more research I've managed to cobble together a working solution. I'll summarize here for any future weary internet travelers that come across this post. </p> <p>The first clues came from <a href="https://gist.github.com/cbaziotis/6428df359af27d58078ca5ed9792bd6d" rel="nofollow noreferrer">this git...
python|tensorflow|keras|deep-learning
3
17,432
58,685,447
Python - Plot multiple dataframe columns
<p>I have a dataframe with 4 columns and I want to do a groupby and plot the data. But I am not sure how to go about this. </p> <pre><code> Cont Coun X3 Y1 Africa nigeria A 10 Africa nigeria B 93 Africa nigeria C 124 Africa nigeria D 24 --------------...
<p>I'd recommend <code>seaborn</code> for this kind of plots:</p> <pre><code>import seaborn as sns sns.barplot(df.Cont+'\n'+df.Coun, 'Y1', hue='X3', data=df) </code></pre> <p><img src="https://i.stack.imgur.com/5Wo1p.jpg" alt="enter image description here"></p> <hr> <p>For adjusting figure size you can create a fig...
python|pandas|matplotlib|plot|bar-chart
1
17,433
70,256,031
How do you display the scale in meters, the north arrow and the axes in latitude and longitude on a map with Geopandas?
<p>With reference to this <a href="https://github.com/geopandas/geopandas/issues/1597#issuecomment-684014519" rel="nofollow noreferrer">issue</a>, is it possible to have the scale bar (projected in meters, so 3857 for example) <strong>with</strong> the x,y axes in latitude, longitude projection (4326) and the north arr...
<p>From <a href="https://github.com/ppinard/matplotlib-scalebar" rel="nofollow noreferrer">this</a>, it looks like you have to compute the great circle distance between two locations A and B with coordinates A=[longitudeA,latitudeA] and B=[longitudeA+1,latitudeA], at the latitude you are interested in (in your case ~40...
python|matplotlib|geopandas|matplotlib-basemap|geoplot
2
17,434
70,203,328
Calculating mean of column based on the occurence of a number in another column Pandas dataframe Python
<p>I've got a Pandas dataframe like the one below. What I'm trying to do is calculating the mean of column s2, for every time that '5' occures in s1.</p> <pre><code>s1 s2 5 0.5 1 0.43 5 1 5 1 </code></pre> <p>In this case, 5 occures three times, so we take the average over 0.5+1+1=0.83. Can someone help me to ...
<p>Try this</p> <pre><code>df[df['s1']==5]['s2'].mean() </code></pre>
python|pandas|dataframe|conditional-statements
0
17,435
70,366,891
How strides help in traversing an array in numpy?
<pre><code>arr = np.arange(16).reshape((2, 2, 4)) arr.strides (32, 16, 4) </code></pre> <p>So, I believe from my knowledge that in memory it would be something like the image below. The strides are marked along with the axis (on the arrows).</p> <p><a href="https://i.stack.imgur.com/JYagJ.png" rel="nofollow noreferrer...
<p>Numpy always iterate through the axis from the biggest one to the smallest one (ie. decreasing order) unless explicitly ask for (eg. with the <code>axis</code> parameter). Thus, in your example, it first read the item of the view at the offset 0 in memory, then add the stride of the axis 2 (4 here) and read the next...
numpy|memory|numpy-ndarray|stride
2
17,436
56,040,224
np.save is converting floats to weird characters
<p>I am attempting to append results to an ongoing csv file. Each result comes out as an nd.array:</p> <pre><code>[IN]: Print(savearray) [OUT]: [[ 0.55219001 0.39838119]] </code></pre> <p>Initially I tried </p> <pre><code>np.savetxt('flux_ratios.csv', savearray,delimiter=",") </code></pre> <p>But this overwrites ...
<p>First off, <code>np.save</code> does not write text whereas <code>np.savetxt</code> does. You are trying to combine binary with text, which is why you get the odd characters when you try to read the file.</p> <p>You could just change <code>np.save(f, 'a', savearray)</code> to <code>np.savetxt(f, savearray, delimite...
python-3.x|numpy|append
1
17,437
56,242,375
How to fix "symbolic tensors" use "steps_per_epoch" but not "batch_size" bug in a simple conv2d+liquid state machine net
<p>I am making a simple conv2d + dynamic reservoir (a customized recurrent layer with random / fixed connections that only outputs the last time step node states). The reservoir is written as a lambda layer to implement a simple equation as shown in the code. The model can be constructed by Keras.</p> <p>I hope the mo...
<p>That error means that one of your data tensors that is being used by Fit() is a symbolic tensor. The one hot label function returns a symbolic tensor. Try something like:</p> <p>label_onehot = tf.Session().run(K.one_hot(label, 5))</p> <p>I haven't personally tried this with Keras directly -- if it doesn't work wit...
tensorflow|keras
2
17,438
55,676,838
Extracting Year and Month from a custom text field
<p>I have a data frame with a column that has information on the number of years / months the person has an account with the organization. </p> <p>The field is a custom text format,</p> <blockquote> <p>eg: '0yrs 11mon', '15yrs 4mon' etc.</p> </blockquote> <p>Is there a way to extract just to extract the yrs and mo...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow noreferrer">Series.str.extract</a>:</p> <pre><code>df['Year'] = df['Member Since'].str.extract('(\d+)(?:yrs)') df['Mon'] = df['Member Since'].str.extract('(?:\s)(\d+)(?:mon)') </code></pre> <p>th...
python|pandas|dataframe|series
6
17,439
64,726,544
How to overwrite existing worksheet with new dataframe in a multisheet Excel workbook using Pandas?
<p>I have an <code>xlsx</code> file with multiple sheets: <code>sheet1, sheet2, sheet3</code></p> <pre><code># Clean up header issues: xl = pd.ExcelFile(file) sheets = xl.sheet_names for i in sheets: df = xl.parse(i) df = df[df['Symbol'] != 'Symbol'] df.reset_index(drop=True, inplace=True) </code></pre> <p>...
<p>Pandas has a read_excel function that also gives you the option to specify the sheet name. You could do something like this:</p> <pre><code>import pandas as pd file = r'C:\...\file.xlsx' #wherever your excel file is sheets = ['sheet1', 'sheet2'] # whatever and however many you have df = {} for sheet in sheets: ...
python|pandas
0
17,440
64,963,127
Why is pandas DataFrame.to_csv float_format option using the old-style formatting?
<p>I wanted to write a pandas DataFrame into a CSV. I wanted all floats to have 2 decimal points. So I used the <a href="https://docs.python.org/3/library/string.html#formatstrings" rel="nofollow noreferrer">new formatting style of Python</a>:</p> <pre><code>indf.to_csv(&quot;myfile.csv&quot;, float_format=&quot;{:.2}&...
<p>This is under discussion at the moment. Have a look at <a href="https://github.com/pandas-dev/pandas/issues/9448" rel="nofollow noreferrer">https://github.com/pandas-dev/pandas/issues/9448</a></p>
python|pandas|dataframe|floating-point|formatting
1
17,441
40,126,853
Fastest way to build a Matrix with a custom architecture
<p>What's the fastest way in numpy or pandas to build a matrix that has this form:</p> <pre><code>1 1 1 1 1 1 2 2 2 1 1 2 3 2 1 1 2 2 2 1 1 1 1 1 1 </code></pre> <p>That preserves both odd and even architectures?</p>
<p>Using <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy brodacasting</code></a>!</p> <pre><code>In [289]: a = np.array([1,2,3,2,1]) In [290]: np.minimum(a[:,None],a) Out[290]: array([[1, 1, 1, 1, 1], [1, 2, 2, 2, 1], [1, 2, 3, 2, 1], [1, 2, 2,...
python|pandas|numpy
5
17,442
40,198,364
How can I implement a weighted cross entropy loss in tensorflow using sparse_softmax_cross_entropy_with_logits
<p>I am starting to use tensorflow (coming from Caffe), and I am using the loss <code>sparse_softmax_cross_entropy_with_logits</code>. The function accepts labels like <code>0,1,...C-1</code> instead of onehot encodings. Now, I want to use a weighting depending on the class label; I know that this could be done maybe w...
<pre><code>import tensorflow as tf import numpy as np np.random.seed(123) sess = tf.InteractiveSession() # let's say we have the logits and labels of a batch of size 6 with 5 classes logits = tf.constant(np.random.randint(0, 10, 30).reshape(6, 5), dtype=tf.float32) labels = tf.constant(np.random.randint(0, 5, 6), dt...
python|tensorflow|deep-learning|caffe|cross-entropy
24
17,443
44,102,280
How can I select (project) only one dimension of a tensor in TensorFlow?
<p>I have a 2D tensor in TensorFlow, and I want to select only 1D of it. How do I do that?</p>
<p>just for completeness, if you want to select the "full" dimension and not actually just a slice of it, then this seems easier and also reduces the tensor by one dimension:</p> <pre><code>import tensorflow as tf initial = tf.truncated_normal([2,3], mean=100.0, stddev = 10.0) slice1 = initial[0] slice2 = initial[:, ...
tensorflow
1
17,444
44,253,985
Append to a dataframe in Pandas
<p>I am creating a dataframe, and each time I run experiments I would like to add a new entry.</p> <p>I have N tests; some may run while some may not; which is why I decided to use Pandas, so I can use timestamp as unique record identifier, and each test is saved in its own row.</p> <pre><code>dataset = [{"datetime":...
<p>Let's try:</p> <pre><code>df = pd.concat([df,pd.DataFrame(dataset).set_index('datetime')]) </code></pre>
python|pandas
0
17,445
69,465,630
Return unique row values from a pandas dataframe based on some conditions
<p>i have this problem i have been trying to solve myself but stuck in between, so i brought it here to seek your help and i look forward to it.</p> <p>I have a pandas dataframe as below:</p> <pre><code> x1 y1 x2 y2 confidence class 0 238.288834 118.716125 300.878754 137....
<p>You can try:</p> <pre><code>df.groupby(['x1','y1','x2', &quot;y2&quot;], as_index=False, sort=False)['confidence'].max() </code></pre> <p><strong>Result:</strong></p> <pre><code> x1 y1 x2 y2 confidence 0 238.288834 118.716125 300.878754 137.672791 0.885205 1 248.977844...
python|pandas|dataframe|numpy
1
17,446
41,157,879
python pandas: how to format big numbers in powers of ten in latex
<p>I'm using pandas to generate some large LaTex tables with big/small numbers:</p> <pre><code>df = pd.DataFrame(np.array(outfile),columns=['Halo','$r_{v}$','etc']) df.to_latex("uvFlux_table_{:.1f}.tex".format(z)) </code></pre> <p>where "outfile" is just a table of numbers (3 columns)... How can I get the numbers in ...
<p>Thanks @Quickbeam2k1 for the answer. I've expanded to handle 0 and negative numbers:</p> <pre><code># Define function for string formatting of scientific notation def exp_tex(float_number): """ Returns a string representation of the scientific notation of the given number formatted for use with LaTe...
pandas|latex
1
17,447
41,150,741
In tensorflow, what is the difference between a constant and a non-trainable variable?
<p>According to <a href="https://stackoverflow.com/a/35688187/348412">this answer</a>, </p> <blockquote> <p>the value of a <code>tf.constant()</code> is stored multiple times in memory.</p> </blockquote> <p>This provides a practical answer to whether to use a tensorflow constant or non-trainable variable when you h...
<p>If you do <code>W = tf.constant(embedding, name="W")</code> then the value of the embedding is stored twice -- on the numpy side in <code>embedding</code> and on the TensorFlow side in <code>W</code> op. Note that <code>constant</code> values are stored in <code>Graph</code> object which is not optimized for large p...
tensorflow
1
17,448
54,166,732
Find a subset of rows (N rows) in a Pandas data frame having the same values at a subset of columns
<p>I have a df which contains customer data without a primary key. The same customer might show up multiple times. </p> <p>I have a field (df2['campaign']) that is an int and reflects how many times the customer shows up in the df. There are also many customer attributes. </p> <p>In my example, going from top to bott...
<p>Use <code>df2_sorted = df2.sort(['education', 'default'], ascending=[1, 1])</code>. Then if your data is not noisy, the rows should become neighbors.</p>
python-3.x|pandas
0
17,449
53,855,488
MobileNet depthmultiplier parameters
<p>I have a confusing about the <code>depth-multiplier (alpha)</code> parameters in <code>tf.keras.layers.SeparableConv2D</code> and </p> <p><code>tf.keras.layers.DepthwiseConv2D</code></p> <p>Based on the original paper, M inputs channel will be <code>alpha*M</code> where <code>alpha</code> in ]0,1]. My question is ...
<p>It's about an output shape. <code>depth_multiplier</code> is a number of filters applied to each input channel. This is an integer positive number, so if you have 3 channels and <code>depth_multiplier == 4</code>, after depthwise convolution you'll get 12 channels (4 filters for each of 3 channels)</p> <p>From the ...
tensorflow|keras|conv-neural-network
0
17,450
53,937,461
Introduced a new layer using tensorflow
<p>I would like to introduce a new layer as activation function in tensorflow. However, There are errors that can not be solved. This is code of new layer.</p> <pre><code>def smooth_relu(tensor): e=0.15 alpha=0.005 def smooth(tensor): smoothtensor=tf.cond(tensor&lt;(e+alpha) ,lambda: (tensor-...
<p>That's because there is no attributes to assign for <code>smoothtensor</code> as <code>dtype</code></p> <p>your fault is in this line : </p> <pre><code>def smooth(tensor): `smoothtensor=tf.cond(tensor&lt;(e+alpha) ,lambda: (tensor-alpha)*(tensor-alpha),lambda:e*((tensor-alpha)-self.e*0.5),dtype=tf.float32)` </code...
python|tensorflow|deep-learning|reinforcement-learning
0
17,451
66,256,380
How do I get the power at a particular frequency of a sound file?
<p>I'm working on my end of the degree thesis in which I have to measure the Sound Pressure Level of underwater recordings (wav files) at a particular frequency (2000Hz). So I came up with this code:</p> <p>''' def get_value(filename, f0, NFFT=8192, plot = False):</p> <pre><code>#Load audio data, sampling_frequency = s...
<p>If you are interested in only one frequency you don't have to compute the FFT you can simply use</p> <pre class="lang-py prettyprint-override"><code>totalEnergy = np.sum((data - np.mean(data)) ** 2) freqEnergy = np.abs(np.sum(data * np.exp(2j * np.pi * np.arange(len(data)) * target_freq / sampling_freq))) </code></...
python|numpy|audio|fft|frequency
0
17,452
66,177,532
PyTorch one of the variables needed for gradient computation has been modified by an inplace operation
<p>I'm doing a policy gradient method in PyTorch. I wanted to move the network update into the loop and it stopped working. I'm still a PyTorch newbie so sorry if the explanation is obvious.</p> <p>Here is the original code that works:</p> <pre><code>self.policy.optimizer.zero_grad() G = T.tensor(G, dtype=T.float).to(s...
<p>This line, <code>loss += -g * logprob</code>, is what is wrong in your case.</p> <p>Change it to this:</p> <pre class="lang-py prettyprint-override"><code>loss = loss + (-g * logprob) </code></pre> <p>And Yes, they are different. They perform the same operations but in different ways.</p>
python|pytorch
1
17,453
52,798,618
Creating more extensible data extraction from json files
<p>I am looping through a large number of Json files extracting data into variables before putting the data to a dataframe. Something like this:</p> <pre><code> fullTimeEmployees = financial_data['fullTimeEmployees'] longBusinessSummary = financial_data['longBusinessSummary'] currentRatio = data['quoteSumm...
<pre><code>import urllib.request import json url = 'https://query2.finance.yahoo.com/v10/finance/quoteSummary/1109.HK?formatted=true&amp;crumb=cmEFpzsN8.l&amp;lang=en-CA&amp;region=CA&amp;modules=defaultKeyStatistics%2CsummaryProfile%2CassetProfile%2CincomeStatementHistory%2CincomeStatementHistoryQuarterly%2CbalanceSh...
python|pandas
0
17,454
52,870,876
Pandas pivot table and groupby month and hour
<p>I have data that is in this format: <a href="https://i.stack.imgur.com/W8HTy.png" rel="nofollow noreferrer">Screenshot of dataframe</a></p> <p>I have to create barplots of the counts of id for each area (North,South,Middle) per hour for every month. E.g I have to plot 12 seperate barplots of counts of id hourly for...
<pre><code>df = pandas.DataFrame([ ['2017-01-10 08:40:00', 1, 'North'], ['2017-01-10 08:30:00', 1, 'North'], ['2017-01-10 08:40:00', 1, 'North'], ['2017-01-10 15:40:00', 2, 'North'], ['2017-01-10 07:30:00', 2, 'North'], ['2017-01-10 08:40:00', 3, 'North'], ['2017-01-10 08:40:00', 1, 'Middle'], ['2017-01-10 08:30:00', 1...
pandas|group-by|pivot-table|pandas-groupby|python-datetime
1
17,455
58,576,972
Using pd.concat to union multiple dataframes
<p>I would like to union multiple dataframes I create from a given function. I have tried using pd.concat but get the error message:</p> <blockquote> <p>TypeError: first argument must be an iterable of pandas objects, you passed an object of type "DataFrame"</p> </blockquote> <p>This is the code I have written:</...
<p>Add <code>[]</code> for list of <code>DataFrame</code>s passed to <code>pd.concat</code> function, also is possible add <code>ignore_index=True</code> for avoid duplicated index in output:</p> <pre><code>df = pd.concat([plot_percs(originalsims,'original'), plot_percs(facebooksims,'facebook')], ignor...
python|pandas
0
17,456
69,283,727
Pandas Dataframe time series resample, how to modify bins to fit underlying dataset start and end time
<p>I excercice with some stock market data and have a dataframe starts at 09:30 and ends at 16:00. I want to resample to an 4Hour Interval using</p> <pre><code>agg_dict = {'open': 'first','high': 'max','low': 'min','cls': 'last','vol': 'sum'} data_4hour = fullRth.resample('4H',label='left',origin='end').agg(agg_dict).d...
<p>I did a little work around. If someone has a better solution, I would like to read it. First I made sure that the values in the bins are correct located. Then I did with the DataFrame above:</p> <pre><code># separating date and time from DatetimeIndex into new columns data_4hour['times'] = data_4hour.index.time.asty...
python|python-3.x|pandas|pandas-resample
0
17,457
69,033,199
Multiply 2D tensor with 3D tensor in pytorch
<p>Suppose I have a matrix such as P = [[0,1],[1,0]] and a vector v = [a,b]. If I multiply them I have:</p> <p>Pv = [b,a]</p> <p>The matrix P is simply a permutation matrix, which changes the order of each element.</p> <p>Now suppose that I have the same P, but I have the matrices M1 = [[1,2],[3,4]] and M2=[[5,6],[7,8]...
<p>An alternative solution to <a href="https://stackoverflow.com/users/3200554/mlucy">@mlucy</a>'s <a href="https://stackoverflow.com/a/69033571/6331369">answer</a>, is to use <a href="https://pytorch.org/docs/stable/generated/torch.einsum.html" rel="nofollow noreferrer"><code>torch.einsum</code></a>. This has the bene...
pytorch|matrix-multiplication
1
17,458
44,575,828
Translate lasagne neural network in deeplearning4j
<p>I am working on translating a lasagne neural network into deeplearning4j code. So far I've managed to get the layers in place but I am not sure if the other configurations are okay. I am not an expert in neural networks and cannot easily find the equivalent functions/methods in deeplearning4j. </p> <p>This is the l...
<p>Is your data pipeline the exact same? This includes normalization and the like as well. With deeplearning4j you don't need to specify the number of outputs. We do that for you. Also - you are using the UI server wrong. Our examples demonstrate how to do these things already: <a href="https://github.com/deeplearning4...
numpy|deep-learning|theano|lasagne|deeplearning4j
0
17,459
44,528,751
Locate erroneous datapoints in dataframe python
<p>I am working with large datasets (> 100.000, >100). The raw format is a CSV. I read the files as a <code>DataFrame</code> using the <code>pandas</code> library. </p> <p>All data has to be of numerical type (integers of floats), however often it occurs that there is an missing data point, or an erroneous string in t...
<p>I think you can create <code>Series</code> first by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow noreferrer"><code>unstack</code></a>, then create <code>mask</code> with <code>apply</code> and last filter by <a href="http://pandas.pydata.org/pandas-docs/...
python|csv|pandas|dataframe
2
17,460
60,856,728
How do I combine two tabs of the same excel file into one tab in Python w/ pandas?
<p>The tabs have the same amount of columns with the same headers. I want to combine the two tabs.</p>
<pre><code>import pandas as pd # Read out sheets df1 = pd.read_excel("workbook.xlsx", sheet_name="Sheet1") df2 = pd.read_excel("workbook.xlsx", sheet_name="Sheet2") # Concatenate dataframes df3 = pd.concat([df1, df2]) # Write to a new worksheet in existing excel file with pd.ExcelWriter("workbook.xlsx", engine="open...
python|pandas
0
17,461
60,877,353
Getting low accuracy when compiling multiple models one after another in the same program
<p>I tried executing those models singularly by putting the other sections in the comments, but as soon as I start uncommenting the lines and running the whole code together, it stops giving good results.</p> <p>Note: I am only getting low accuracy results in the models using CNNs. I don't know why. I suspect maybe I ...
<p>You are not clearing the session between runs, so there will be junk floating around in the kernel which is leading to poor results. Between each model you should be <a href="https://www.tensorflow.org/api_docs/python/tf/keras/backend/clear_session" rel="nofollow noreferrer">resetting Keras</a>:</p> <pre class="lan...
python|tensorflow|keras|deep-learning|conv-neural-network
1
17,462
61,166,864
'tensorflow.python.framework.ops.EagerTensor' object has no attribute '_in_graph_mode'
<p>I am trying to visualize CNN filters by optimizing a random 'image' so that it produces a high mean activation on that filter which is somehow similar to the neural style transfer algorithm.</p> <p>For that purpose, I am using TensorFlow==2.2.0-rc. But during the optimization process, an error occurs saying <code>'...
<p>The reason for the bug is that the tf.keras optimizers apply gradients to variable objects (of type tf.Variable), while you are trying to apply gradients to tensors (of type tf.Tensor). Tensor objects are not mutable in TensorFlow, thus the optimizer cannot apply gradients to it.</p> <p>You should initialize the va...
python|tensorflow
7
17,463
71,628,605
Initialization of the hidden states of torch.nn.lstm
<p>As the explanations of num_layers in this link: <a href="https://discuss.pytorch.org/t/what-is-num-layers-in-rnn-module/9843" rel="nofollow noreferrer">https://discuss.pytorch.org/t/what-is-num-layers-in-rnn-module/9843</a></p> <p>if the output of hidden state of the first lstm is the input of the hidden state of th...
<p>The answer in <a href="https://discuss.pytorch.org/t/what-is-num-layers-in-rnn-module/9843" rel="nofollow noreferrer">https://discuss.pytorch.org/t/what-is-num-layers-in-rnn-module/9843</a> in fact has not shown the hidden state for the second lstm layer, and only showed its input (which is the output of the hidden ...
pytorch|lstm
0
17,464
71,446,463
Extract full link from a list in Google colab
<p>I'm trying to extract a column of links from this kind of rows in a column</p> <pre><code>{'type': 'uri', 'value': 'http://www.wikidata.org/entity/Q47099'} </code></pre> <p>To this: <a href="http://www.wikidata.org/entity/Q47099" rel="nofollow noreferrer">http://www.wikidata.org/entity/Q47099</a></p> <p>Basically I ...
<p>If your <code>org</code> column contains a real dict, use:</p> <pre><code>data[data['org'].str['value'].str.contains('www.wikidata.org')] # ^^^^^^^^^^^^^ </code></pre> <p>If you want to extract the link:</p> <pre><code>data['links'] = data['org'].str['value'] </code></pre> <p><strong>Update</strong></p...
pandas|numpy|google-colaboratory|data-extraction|information-extraction
1
17,465
42,288,480
Subtract all values from one value and MULTIPLY. Move to next value and repeat
<p>I have a df with three columns 'a','b' and 'c'</p> <pre><code>[a] [b] [c] 2 2 12 11 5.95 12 10 16.7 12 </code></pre> <p>What I need is an extra column 'd', which represents following calculation:</p> <p>((2-11) * 5.95 + (2-10) * 16.7) /12 = -15.59583333</p> <p>((11-2) * 2 + (11-10) * 16.7) /12 ...
<p>One option is to <code>apply</code> through series <code>a</code> and do the calculation for each element separately:</p> <pre><code>df['d'] = df.a.apply(lambda x: ((x - df.a) * df.b / df.c).sum()) df </code></pre> <p><a href="https://i.stack.imgur.com/ntXwA.png" rel="nofollow noreferrer"><img src="https://i.stack...
python|pandas|dataframe
2
17,466
69,856,636
Is there a way to select a subset of a Numpy 2D array using the Manhattan distance?
<p>Say for example, I have a Numpy 2D array (7 rows, 7 columns) filled with zeros:</p> <p>my_ array = numpy.zeros((7, 7))</p> <p>Then for sake of argument say that I want to select the element in the middle and set its value to 1:</p> <p>my_array[3,3] = 1</p> <p>Now say that I have been given a Manhattan distance of 3,...
<p>I would create an auxiliar matrix of size 2,n,n with meshgrid to almacenate the index, then substract the desired index center, sum absolute value of index substracted and put a threshold comparation. Here some example</p> <pre><code>import numpy as np import matplotlib.pyplot as plt #to draw result n=70 #size of...
python|arrays|numpy|subset|manhattan
2
17,467
69,932,948
Sklearn SVM custom rbf kernel function
<p>I was creating a custom rbf function for the SVC class of sklearn as following:</p> <pre><code>def rbf_kernel(x, y, gamma): dis = np.sqrt(((x.reshape(-1, 1)) - y.reshape(1, -1)) ** 2) return np.exp(-(gamma*dis)**2) def eval_kernel(kernel): model = SVC(kernel=kernel, C=C, gamma=gamma, degree=degree, coe...
<p>Your rbf kernel is written incorrectly. You need to return a matrix that is (n_samples, n_samples). In your code you basically unravelled everything, hence the error. You can refer to the <a href="https://github.com/scikit-learn/scikit-learn/blob/0d378913b/sklearn/metrics/pairwise.py#L1142" rel="nofollow noreferrer"...
python|numpy|machine-learning|scikit-learn|svm
1
17,468
72,192,217
Finding eigenvector of the lowest eigenvalue - matrix multiplication has wrong dimensions
<p>Python newbie here. I'm trying to verify an eigenvalue problem - A<em>Cmin = Emin</em>Cmin but the matrix multiplication doesn't work since extracting the corresponding eigenvector gets stored in a weird way ([[[ ]]] instead of [[ ]] )</p> <p>Would appreciate any help with this or other ways of doing it!</p> <p>Than...
<pre><code>In [26]: w.shape Out[26]: (5,) In [27]: v.shape Out[27]: (5, 5) In [28]: w Out[28]: array([5.85888748, 4.57205335, 2.90645081, 0.53081555, 1.64794665]) In [29]: w[3] Out[29]: 0.530815550482961 </code></pre> <p>Indexing <code>v</code> by column works fine:</p> <pre><code>In [30]: v[:,3] Out[30]: array([-0.089...
python|numpy
0
17,469
72,293,671
Python - Import CSV as DataFrame, filter with groupby and export results as formatted text
<p>I'm struggling behind a python script to import a formatted CSV (&quot;,&quot; as delimiter) as DataFrame, group the result by value in specific column and based on that groups I need to output a formatted CLI config script for a network device.</p> <p>I would be very happy if someone could help me</p> <p>My CSV (us...
<p>When doing <code>for group in grouped</code> in reality you are getting a tuple with groupname,groupcontents.</p> <p>Use the groupname for the <code>edit</code> and expand the users with a comprehension of the <code>user</code> field of the &quot;sub-dataframe&quot;. Not the most efficient, but gets the job done</p>...
python|pandas|dataframe|loops|csv
0
17,470
72,353,030
Replace all column with 0 1 except date column
<p>I have a csv file containing of many columns. I want to change 0 1 2 into 0 1 and null. My code is working perfectly but there is an issue. I think it is also replacing 1 2 &amp; 0 in date column too. I don't want this. Below is my code:</p> <pre><code>df1 = df.replace(to_replace = [0,1,2], value = [np.nan,0, 1]) </...
<p>Use a dictionary:</p> <pre><code>df1 = df.replace({0:float('nan'), 1:0, 2:1}) </code></pre> <p>To limit to given columns:</p> <pre><code>df1 = df.copy() df.update(df[['col1', 'col2']].replace({0:float('nan'), 1:0, 2:1})) </code></pre>
python|pandas|pivot-table
1
17,471
45,525,821
Numpy add a matrix to slices of another matrix
<p>Lets say I have a matrix <code>X (1000x10)</code> and a matrix <code>Y (20x10)</code>. I want to efficiently add <code>Y</code> to every <code>(20x10)</code> block of <code>X</code> repeatedly (therefore 50 blocks). Is there an efficient way to do this with numpy? I don't want to use <code>np.repeat</code> as the or...
<p>You can leverage <a href="https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow noreferrer">argument list unpacking</a>, <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow noreferrer">NumPy broadcasting</a> and <a href="https://docs.scipy.org/...
python|numpy|matrix
2
17,472
62,634,036
What is the best way to access specific tensors in a shuffled queue?
<p>I am processing video data in python using tensorflow and want to run a loss calculation using temporal information using the current frame and the ones before and after it. After I've read in the images they are shuffled using tf.train.shuffle_batch as is necessary for the training. However later I want to access...
<p>No, there is no other way than the one you already implemented. Shuffling uses a limited buffer where items are stored and randomly sampled from. If you shuffle individual frames, you don't even have the guarantee the three frames are in the queue at the same time, let alone the possibility to know where they end up...
python|tensorflow|machine-learning|computer-vision|video-processing
0
17,473
62,802,393
Pandas value_counts(normalize=True) gives 'IntegerArray' object has no attribute 'sum'
<p>Pandas <code>value_counts(normalize=True)</code> fails when an extension datatype is used. For example, when creating an <code>int8</code> Series containing <code>pd.NA</code> would typically use <code>Int8</code> extension datatype but an error occurs: <code>AttributeError: 'IntegerArray' object has no attribute 's...
<p>This is believed to be a regression bug, see <a href="https://github.com/pandas-dev/pandas/issues/33317" rel="nofollow noreferrer">GH33317</a>. Good news is that this is fixed on pandas 1.1.</p> <pre><code>pd.__version__ # '1.1.0.dev0+2004.g8d10bfb6f' pd.Series([1, pd.NA], dtype='Int8').value_counts(normalize=Tru...
python|pandas|dataframe|integer|na
2
17,474
62,542,452
JSON to pandas dataframe for multiple filepaths
<p>I have a folder of 40 customer data files. Each customer has a json file filled with different purchases. An example path is ../customer_data/customer_1/transaction.json</p> <p>I want to load this json file into a data frame with <code>customer_id</code>, <code>date</code>, <code>instore</code> and <code>rewards</co...
<ul> <li>Use <a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path.rglob" rel="nofollow noreferrer"><code>rglob</code></a> to find all files.</li> <li>Fix <code>data</code> by filling the empty lists in the <code>purchase</code> key.</li> <li>Use <a href="https://docs.python.org/3/library/pathlib.html#pa...
python|json|pandas|json-normalize
1
17,475
54,649,063
Find different percentile for every group in data frame
<p>I have the date frame with the following structure:</p> <pre><code>df = pd.DataFrame({'GROUP_ID': np.random.randint(1, 7, size=100), 'VALUES': np.random.randint(0, 50, size=100)}) df['THRESHOLD'] = df['GROUP_ID']*5 df = df[['GROUP_ID','VALUES','THRESHOLD']] df.sort_values(by='GROUP_ID', inplace...
<p>Create dictionary and map treshold with <code>x.name</code> for <code>GROUP_ID</code> passed to function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>transform</code></a> for new column with <a href="http://pandas.pydata.or...
python|pandas|statistics|quantile|percentile
1
17,476
54,331,914
How to split one row into multiple and apply datetime on dataframe column?
<p>I have one dataframe which looks like below:</p> <pre><code> Date_1 Date_2 0 5 Dec 2017 5 Dec 2017 1 14 Dec 2017 14 Dec 2017 2 15 Dec 2017 15 Dec 2017 3 18 Dec 2017 21 Dec 2017 18 Dec 2017 21 D...
<p>After using regex with <code>findall</code> get the you date , your problem become a <a href="https://stackoverflow.com/a/53218939/7964527"><code>unnesting</code></a> problem </p> <pre><code>s=df.apply(lambda x : x.str.findall(r'((?:\d{,2}\s)?(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*(?:-|\.|\s|,)\s?...
python|pandas|datetime
4
17,477
54,691,250
How to read specific rows/columns of a .CSV file and storing them as a numpy matrix?
<p>I have a <code>.CSV</code> file with contents like this:</p> <pre><code>DATE OPEN HIGH LOW CLOSE PRICE YCLOSE VOL TICKS 13950309 1000000 1000000 1000000 1000000 1000000 1000000 2100000 74 13950326 1050000 1050010 1050000 1050001 1050000 1000000 1648 5 13950329 1030200 1060000 1030200 10444...
<p>Just use the csv module to process the file, skipping first line and first column. Code can be as simple as:</p> <pre><code>with open('file.csv') as fd: next(fd) # skip initial line rd = csv.reader(fd, delimiter = ' ', skipinitialspace = True) arr = np.array([[int(i) fo...
python|csv|store|numpy-ndarray|file-read
2
17,478
71,361,667
Method to manage "NAN" (in capital letters) with Pandas?
<p>do you know if there is a way to manage the &quot;NAN&quot; all in capital letters present in a data file with Pandas?</p> <p>I have some data files have this format:</p> <pre><code>&quot;2020-08-14 14:00:00&quot;,10,154.9554,153.6879,154.3988,158.5282,&quot;NAN&quot;,&quot;NAN&quot;,158.43,&quot;NAN&quot;,155.2103 ...
<p><code>isnull</code> and <code>isna</code> do <strong>NOT</strong> return True for strings, no matter the case.</p> <p>Most likely you have a mix of real NaN and of strings:</p> <pre><code>s = pd.Series([float('nan'), 'NAN', 'nan', 'NaN']) df = pd.concat({'s': s, 'isnull': s.isnull(), 'isna': s.isna()}, axis=1) </cod...
python|python-3.x|pandas|nan
2
17,479
71,284,989
The added layer must be an instance of class Layer. Found:
<pre><code> batch_size = 32 model = Sequential() model.add(Conv1D(64, kernel_size=122, padding=&quot;same&quot;,activation=&quot;relu&quot;,input_shape=(122, 1))) model.add(MaxPooling1D(pool_length=(5))) model.add(BatchNormalization()) model.add(Bidirectional(LSTM(64, return_sequences=False))) ...
<p>You cannot mix <code>keras</code> and <code>tensorflow.keras</code>. They're two different frameworks that are not compatible.</p> <p>Either you import <strong>everything</strong> <code>from keras</code> or you import <strong>everything</strong> from <code>tensorflow.keras</code>.</p>
tensorflow|keras
0
17,480
52,217,603
Create constant or tensor without knowing shape upfront in Keras/TF?
<p>I am working on a custom method to categorize text documents. Each document has shape (None, 3) where None represents the number of tokens in the document and it's variable. Each batch is then going to have shape (None, None, 3), where the first value represents the batch_size.</p> <p>In one of my custom layer, I n...
<p>You are looking for <a href="https://www.tensorflow.org/api_docs/python/tf/zeros_like" rel="nofollow noreferrer"><code>tf.zeros_like</code></a>.</p> <pre><code>x = tf.placeholder(tf.float32, shape=(None, None)) z = tf.zeros_like(x) # zeros the same shape and dtype as x </code></pre>
python|tensorflow|keras
1
17,481
52,259,869
Multiindexed columns - Select inner
<p>having a DataFrame like the following:</p> <pre><code>frame = pd.DataFrame(np.arange(12).reshape((4, 3)), ....: index=[['a', 'a', 'b', 'b'], [1, 2, 1, 2]], ....: columns=[['Ohio', 'Ohio', 'Colorado'], ....: ['Green', 'Red', 'Green']]) ...
<p>This is multiple index , You can using <code>IndexSlice</code></p> <pre><code>frame.loc[:,pd.IndexSlice[:,'Green']] Out[506]: Ohio Colorado Green Green a 1 0 2 2 3 5 b 1 6 8 2 9 11 </code></pre>
python|pandas
2
17,482
52,435,825
Want MultiIndex for rows and columns with read_csv
<p>My .csv file looks like:</p> <pre><code>Area When Year Month Tickets City Day 2015 1 14 City Night 2015 1 5 Rural Day 2015 1 18 Rural Night 2015 1 21 Suburbs Day 2015 1 15 Suburbs Night 2015 1 21 City Day 2015 2 ...
<p>Seems like you need to <code>pivot_table</code> with multiple indexes <em>and</em> multiple columns.</p> <p>Start with just reading you csv plainly</p> <pre><code>df = pd.read_csv('Tickets.csv') </code></pre> <p>Then</p> <pre><code>df.pivot_table(index=['Year', 'Month'], columns=['Area', 'When'], values=['Ticket...
python|pandas|multi-index
1
17,483
52,270,444
No module named pandas but pandas is already installed in linux
<p>I have two python distributions(python2.7,python3.6) and in both I have installed <code>pandas</code> and <code>numpy</code> as well but cant use</p> <p>These are the errors caused when i tried to import pandas</p> <p><strong>in python 2.7</strong></p> <blockquote> <p>File "/usr/local/lib/python2.7/dist-package...
<p>Most of these cases, the problem is that you are installing pandas in another environment. The easy solution here is using Anaconda. </p> <p>Anaconda is focused on environments. First, you should choose installation of python2 or python3. Then, you can install this version of Anaconda in Linux: <a href="https://www...
python|pandas|numpy
0
17,484
52,427,357
drop values in group by based on group criteria pandas
<p>I have a dataframe of data produced by the following:</p> <pre><code>df2 = df.groupby(['City','Address','date_time'])['house_price'].mean().pct_change() City Address Date Pct Ch Washington, D.C. 111 S Street Appletown 2018-08-03 0...
<p>You can try (assuming the date is sorted )</p> <pre><code>df.groupby(level=[0,1]).apply(lambda x : x.iloc[1:,:]) </code></pre>
python|pandas|lambda|pandas-groupby
2
17,485
60,516,737
pandas 1.0 replace one string dtype columns with NANs
<p>I've started using StringDtype in pandas 1.0.1 I know it's considered experimental, but I'm running into an issue when using replace on a column of type string that contains NaNs.</p> <p>For example:</p> <pre><code>df = pd.DataFrame({'a': ['a', 'b', 'c', None]}, dtype='string') df.replace({'c': 'e'}) </code></pre...
<p>Try this: </p> <pre><code>import pandas as pd df = pd.DataFrame({'a': ['a', 'b', 'c', None]}, dtype='string') df.replace('c', 'e', inplace=True) print(df) </code></pre> <p>you'll get: </p> <pre><code> a 0 a 1 b 2 e 3 &lt;NA&gt; </code></pre> <p>or if you want to keep the <code>dict</code> as ...
pandas|pandas-1.0
0
17,486
60,612,538
Rename column names of groupby and count result with Pandas
<p>Given the following dataframe:</p> <pre><code>import numpy as np df = pd.DataFrame({'price': np.random.random_integers(0, high=100, size=100)}) ranges = [0,10,20,30,40,50,60,70,80,90,100] df.groupby(pd.cut(df.price, ranges)).count() </code></pre> <p>Out:</p> <pre><code> price price (0, 10] 9 (10, ...
<p>This code works but not concise enough, if you have other options, welcome to share:</p> <pre><code>df.groupby(pd.cut(df.price, ranges)).count()\ .rename(columns={'price' : 'counts'})\ .reset_index()\ .rename(columns={'price': 'bins'}) </code></pre> <p>Out:</p> <pre><code> bins counts 0 (0, 10] 9 1 ...
python|pandas|dataframe|rename
3
17,487
60,614,810
How to homogenize date type in a pandas dataframe column?
<p>I have a Date column in my dataframe having dates with 2 different types (YYYY-DD-MM 00:00:00 and YYYY-DD-MM) :</p> <pre><code> Date 0 2023-01-10 00:00:00 1 2024-27-06 2 2022-07-04 00:00:00 3 NaN 4 2020-30-06 </code></pre> ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>Series.str.replace</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> ...
python|pandas|date
1
17,488
72,520,793
How to add unique date values of a datetime64[ns] Series object
<p>I have a column of type datetime64[ns] (<code>df.timeframe</code>).</p> <p>df has columns <code>['id', 'timeframe', 'type']</code></p> <p><code>df['type']</code> can be 'A' or 'B'</p> <p>I want to get the total number of <strong>unique dates</strong> per <code>df.type == 'A'</code> and per <code>df.id</code></p> <p>...
<p>You could use <code>value_counts</code>:</p> <pre><code>df[df['type']=='A'].assign(timeframe=df['timeframe'].dt.date) .value_counts(['id','type','timeframe'], sort=False) .reset_index().rename(columns={0:'count'}) id type timeframe count 0 1 A 2022-06-06 2 1 1 A 2022-06-08 1 2 1 A ...
python-3.x|pandas|datetime|pandas-groupby|python-datetime
0
17,489
72,645,374
Is there a better way to get the product of values from all column combinations from two dataframes?
<p>I have two dataframes :</p> <pre><code> (A0, B0, C0) (A1, B1, C1) (A2, B2, C2) Item0 6 6 4 Item1 2 3 9 (D0, E0) (D1, E1) Item0 3 3 Item1 7 5 </code></pre> <p>I would like to get the product betwee...
<p>With the dataframes you provided, here is how your code performs on my computer:</p> <pre class="lang-py prettyprint-override"><code>import statistics import time elapsed_time = [] for _ in range(10): start_time = time.time() df = pd.concat( [df1[i[0]] * df2[i[1]] for i in itertools.product(df1.colu...
python|pandas
2
17,490
59,877,503
Unsupervised Encoding in Keras with Custom Loss
<p>I am trying to model time-varying covariance using RNNs in Keras, where I decompose the covariance of a signal Y into a time-varying weighted sum: C_Y^t = SUM_i^npriors (alpha_i^t * beta_i), where beta_i are some basis set which is fixed and alpha_i^t are the terms I am trying to infer.</p> <p>As a cost function, I...
<p>Not sure it is the most sensible thing to do, but I used the <code>add_loss</code> function to get around this.</p> <p>I will update my original question with a complete implementation.</p>
python|tensorflow|machine-learning|keras
0
17,491
59,832,252
Taking the maximum values of each row in a tensor [PyTorch]
<p>Suppose I have a tensor of the form</p> <pre><code>[[-5, 0, -1], [3, 100, 87], [17, -34, 2], [45, 1, 25]] </code></pre> <p>I want to find the maximum value in each row and return a rank 1 tensor as follows:</p> <pre><code>[0, 100, 17, 45] </code></pre> <p>How would I do this in PyTorch?</p>
<p>You can use the <code>torch.max()</code> function. So you can do something like</p> <pre><code>x = torch.Tensor([[-5, 0, -1], [3, 100, 87], [17, -34, 2], [45, 1, 25]]) out, inds = torch.max(x,dim=1) </code></pre> <p>and this will return the maximum values acros...
python|deep-learning|max|pytorch
8
17,492
59,522,655
Sorting unique values according to another column in pandas
<p>I'm trying to sort unique values in pandas dataframe with group by;</p> <pre><code>df = pd.DataFrame({ ... 'gr1': ['A', 'A', 'A','A', 'B', 'B', 'B','B'], 'gr1_sum' : [100,100 ,100,100, 200,200,200,200], 'rank_gr1': [2, 2, 2, 2, 1, 1, 1, 1], ... 'gr2': ['a1', 'a1', 'a2','a2', 'b1', 'b1', 'b...
<p>Pass <code>sort=False</code> under the groupby.</p> <p>From docs:</p> <blockquote> <p>sort : bool, default True Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. Groupby preserves the order of rows within each group.</p> </blo...
python|pandas
3
17,493
61,882,740
How do I replace pandas rows with values of another dataframe for all instances of the value in the first df?
<p>I have two dataframes:</p> <pre><code>df1= A B C a 1 3 b 2 3 c 2 2 a 1 4 </code></pre> <pre><code>df2= A B C a 1 3.5 </code></pre> <p>Now I need to replace all occurrences of <code>a</code> in <code>df1</code> (2 in this case) with <code>a</code> in <code>df2</code>, leaving <code>b</c...
<p>Do you mean:</p> <pre><code>df_final = pd.concat((df1[df1['A'].ne('a')], df2)) </code></pre> <p>Or if you have several values like <code>a</code>:</p> <pre><code>list_special = ['a'] df_final = pd.concat((df1[~df1['A'].isin(list_special)], df2)) </code></pre>
python|pandas
1
17,494
61,699,479
contourplot in matplotlib on unsorted but regulary spaced data
<p>I have a data file with x,y,z data points, like this:</p> <pre><code># X Y Z 1.0 1 0.1 1.0 2 0.2 1.0 3 0.3 2.1 3 0.5 2.1 2 0.2 2.1 1 0.4 ... </code></pre> <p>I was able to read in the data i want, and plot it like this:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt data = np.loadt...
<p><code>meshgrid</code> is not going to produce what you want in the way you are using it. One way to think of it is that <code>meshgrid</code> <em>creates</em> data (from <code>n+m</code> data points to <code>n*m + n*m</code> data points) but you don't need to create data, you just need to <em>sort and shape</em> wh...
python|numpy|matplotlib
1
17,495
57,767,968
Split Date in format(YYYY-MM-DD) into 3 new columns in dataframe as Year , Month & Date
<p>How can i split a string in example below into new columns as Year Month and Date in dataframe.</p> <p>Example: Column A in a data frame</p> <pre><code>Column A 2017-10-15 </code></pre> <p>Expected output result in dataframe</p> <pre><code>Column A Year Month Date 2017-10-15 2017 10 15 </code></pre>
<pre><code>df['year']= df['Date'].dt.year df['month']= df['Date'].dt.month df['day']= df['Date'].dt.day </code></pre> <p>This will work only if 'Column A' is in datetime format. you can do that with <code>df['Column A']= pd.to_datetime(df['Column A'],format='%Y-%m-%d')</code></p>
python|pandas|date
6
17,496
57,767,098
Difflib error when applying onto two columns in pandas dataframe
<p>I have DataFrame that look like this:</p> <pre><code>Cities Cities_Dict "San Francisco" ["San Francisco", "New York", "Boston"] "Los Angeles" ["Los Angeles"] "berlin" ["Munich", "Berlin"] "Dubai" ["Dubai"] </code></pre> <p>I want to create new column that compares city from firest column to...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>DataFrame.apply</code></a> with lambda function and <code>axis=1</code> for processing by rows:</p> <pre><code>import difflib, ast #if necessary convert values to lists #df['Cities_Di...
python|pandas|difflib
1
17,497
57,821,942
Keras: how to do weighted addition of outputs of encoders with weights given by another classifier?
<p><strong>I need to merge multidimensional outputs of 3 (or more) encoders by weighted addition, and the weights are coming from another classifier</strong>. How do I do this?</p> <p>basically I need to do this (in a vectorized form):</p> <p>output = dotProduct([output1, output2, output3], w) = w1*output1 + w2*outpu...
<p>For a generic number of encoders, you could do something along the lines of:</p> <pre><code>def f(x): w = x[-1] outputs = x[:-1] outputs_ = K.concatenate([o[:, None, ...] for o in outputs], axis=1) # Shape=(None, nb_outputs, 16, 16, 512) out = K.sum(w[..., None, None, ...
tensorflow|keras
1
17,498
57,897,734
Conditional Group By Statement
<p>I have the data frame : </p> <pre><code> PRODUCT SPEED HEIGHT LENGTH DATE 30 10 5 8 2019-08 30 13 9 15 2019-08 31 19 8 12 2019-08 30 5 6 3 2019-08 31 11 8 6 2019-0...
<p>You were quite close, after your groupby, filter your data on <code>PRODUCT == 30</code>, groupby on date again and then divide the size product by the original <code>avg_summary</code>:</p> <pre><code>s = df.query('PRODUCT==30').groupby('DATE')['PRODUCT'].size().to_numpy() avg_summary['PRODUCT'] = s / avg_summary[...
python|pandas|pandas-groupby
2
17,499
58,150,519
ResourceExhaustedError: OOM when allocating tensor in Keras
<p>I am training a model with the following summary using tf.keras:</p> <pre><code>Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) ...
<p>I will suggest to write your own training data generator or <code>keras.utils.Sequence</code>. Directly feed the entire training data is not a good idea especially when your dataset is very large. In additionally, <strong><code>use_multiprocessing</code> argument is used for generator or keras.utils.Sequence input ...
tensorflow|keras
0