Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
353,900
59,957,958
Adding Decimal Places
<pre><code>d = {'col1': [999, 1000]} df = pd.DataFrame(data=d) </code></pre> <p>How would I loop through this data frame and add a decimal two places from the right for values higher than 200. For example, 999 is greater than 200 so make that 9.99</p>
<p>Use the <code>applymap()</code> with a conditional <code>lambda</code> function that will divide by 100 if the cell value is greater than 200.</p> <pre><code>import pandas as pd d = {'col1': [999, 1000, 100]} df = pd.DataFrame(data=d) df = df.applymap(lambda x: x/100 if x &gt;= 200 else x) print(df) </code></pre> ...
python|pandas
0
353,901
60,269,974
Concatenate two numpy arrays so that index order keeps the same?
<p>Assume I have two numpy arrays as follows:</p> <pre><code>{0: array([ 2, 4, 8, 9, 12], dtype=int64), 1: array([ 1, 3, 5], dtype=int64)} </code></pre> <p>Now I want to replace each array with the ID at the front, i.e. the values in array 0 become 0 and in array 1 become 1, then both arrays should be merged, whereby...
<p>Your description of merging is a bit unclear. But here's something that makes sense</p> <pre><code>In [399]: dd ={0: np.array([ 2, 4, 8, 9, 12]), ...: 1: np.array([ 1, 3, 5])} In [403]: res = np.zeros(13, int) ...
python|arrays|numpy
1
353,902
60,037,035
How do I display pandas column blurry?
<p>I have a pandas dataframe that I would like to display. Some of my columns contain personal data. Is it possible to show a column and make its values appear blurry? Consider this example dataframe:</p> <pre><code># initialize list of lists data = [['tom', 10, 'New York'], ['nick', 15., 'London' ], ['juli', 14, 'Be...
<p>Here's a working way to do that blurring:</p> <pre><code>def blurry(s): return 'color: transparent; text-shadow: 0 0 5px rgba(0,0,0,0.5)' df.style.applymap(blurry, subset=["Age"]) </code></pre> <p>And the result is:</p> <p><a href="https://i.stack.imgur.com/5oFsk.jpg" rel="nofollow noreferrer"><img src="http...
python|pandas|printing|data-visualization|display
2
353,903
60,008,371
Problem with indexing within if-elif statements (indexer incompatible with series)
<p>I'm trying to run the following code, but I am having trouble with the .loc function. What I am trying to do is (1) sort each row by the type of row they are, (2) use the data from 4 columns within that row as 4 different indices for another dataframe, then (3) take the product of those 4 newly indexed items and cre...
<p>No idea why, but removing the line that calculates the probability</p> <p>e.g.,</p> <pre><code>TL4_transpose.loc[str(i), 'LearnProb'] = prob_Size </code></pre> <p>and running only the line right under, that takes the natural log, made the code work...</p> <pre><code># run through list of each child for i in rang...
python|pandas|dataframe|if-statement|indexing
0
353,904
60,173,355
xarray create Dataset from list of lat/lon points (not square!)
<p>I need to create a Dataset from an irregular list of latitudes/longitudes. These have been stacked into a list of 'pixels' that I need to unstack and convert back to a regular grid of latitude/longitudes. Because the data values are not complete for every pixel in the grid I need to fill the missing values as <code>...
<p>I have met and solved questions similar to yours, that is why I landed on this page. My solution is to utilize the connection between pandas dataframes and xarray data arrays. I don't understand the above data you've provided. But I think my logic will probably work for your case.</p> <p>The first step is to prepare...
python|python-3.x|numpy|python-xarray
1
353,905
60,325,794
Python Join the matched line with just before matched
<p>Experts, Just trying to match a string in a log file and add or join the line with just a line before match, saying that.. join the matched line with one line just before it.</p> <p>I'm trying below code getting hints from SO, However it working printing matched line with the Just line before. However i want to joi...
<p>A quick sketch:</p> <pre class="lang-py prettyprint-override"><code>prev_line = "&lt;no previous line&gt;" with open(...) as input_file: for line_no, line in enumerate(input_file, start=1): # Reading one line at a time suffices. if 'failed' in line or 'Timed' in line: print(line_no - 1, prev_line) ...
python|python-3.x|pandas
1
353,906
59,939,204
Using pandas.DataFrame.apply to look up and replace values with values from a different DataFrame
<p>I have two pandas DataFrames with the same DateTime index.</p> <p>The first one is J:</p> <pre><code> A B C 01/01/10 100 400 200 01/02/10 300 200 400 01/03/10 200 100 300 </code></pre> <p>The second one is K:</p> <pre><code> 100 200 300 400 01/01/10 ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html#pandas.DataFrame.melt" rel="nofollow noreferrer"><code>DataFrame.melt</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>Data...
python|pandas
0
353,907
59,920,770
Get the nearest distance with two geodataframe in pandas
<p>Here is my first geodatframe :</p> <pre><code>!pip install geopandas import pandas as pd import geopandas city1 = [{'City':"Buenos Aires","Country":"Argentina","Latitude":-34.58,"Longitude":-58.66}, {'City':"Brasilia","Country":"Brazil","Latitude":-15.78 ,"Longitude":-70.66}, {'City':"Santiago"...
<p>Firstly, I merge two data frames by cross join. And then, I found distance between two points using <a href="https://book.pythontips.com/en/latest/map_filter.html#map" rel="noreferrer"><code>map</code></a> in python. I use <code>map</code>, because most of the time it is much faster than <code>apply</code>, <code>it...
python|pandas|dataframe|geolocation|geopandas
13
353,908
60,186,935
How to build semantic search for a given domain
<p>There is a problem we are trying to solve where we want to do a semantic search on our set of data, i.e we have a domain-specific data (example: sentences talking about automobiles)</p> <p>Our data is just a bunch of sentences and what we want is to give a phrase and get back the sentences which are:</p> <ol> <li>...
<p>I would highly suggest that you watch Trey Grainger's lecture on how to build a semantic search system => <a href="https://www.youtube.com/watch?v=4fMZnunTRF8" rel="noreferrer">https://www.youtube.com/watch?v=4fMZnunTRF8</a>. He talks about the anatomy of a semantic search system and each of the pieces used to fit t...
python|elasticsearch|nlp|sentence-similarity|huggingface-transformers
10
353,909
60,208,043
How to replace the first dimension of a 3D numpy array with values from a 1D array?
<p>I've got a 3D and a 1D numpy array- A sized (3750, 17, 1000) and B sized (3750). I want to replace the values in the 1st dimension of A with the values from array B, so that the resulting array C is still sized (3750, 17, 1000), but the values in the first dimension are different. </p> <pre><code>&gt;&gt;&gt; A.sha...
<p>Do you mean:</p> <pre><code>A[:,0,0] = B </code></pre> <p>Is it correct? </p>
python|arrays|numpy|multidimensional-array
2
353,910
60,081,318
Most efficient way to convert a dictionary with list of numpy arrays into pandas dataframe?
<p>I am trying to do bulk calculations on multiple stock symbols over many time periods using numpy vectorization, but I am not sure if how I am approaching the problem is most efficient. I am using the "tulipy" technical indicator library to perform calculations on the "Close" price of different stocks. </p> <p>Here ...
<p>To make the dictionary, you should use pandas <code>DataFrame.groupby</code> rather than processing into arrays and then iterating through them.</p> <pre><code>dictt = {ticker: ti.rsi(group["Close"], 14) for ticker, group in df.groupby("Ticker")} </code></pre> <p><code>group["Close"]</code> will be a pand...
python|pandas|numpy|dataframe|vectorization
0
353,911
60,196,759
Getting Unique 1D NumPy Array Values without Sorting
<p>I have many large 1D arrays and I'd like to grab the unique values. Typically, one could do:</p> <pre><code>x = np.random.randint(10000, size=100000000) np.unique(x) </code></pre> <p>However, this performs an unnecessary sort of the array. The docs for <code>np.unique</code> do not mention any way to retrieve the ...
<p>If your values are positive integers in a relatively small range (e.g. 0 ... 10000), there is an alternative way to obtain a list of unique values using masks: (see <code>unique2()</code> below)</p> <pre><code>import numpy as np def unique1(x): return np.unique(x) def unique2(x): maxVal = np.max(x)+1 ...
python|arrays|numpy
1
353,912
60,222,391
(AttributeError: 'NoneType' object has no attribute 'get' ) while loading saved keras model with .h5 extension in tensorflow 2.1
<p>I have a keras model making use of feature_column api of tensorflow , I am able to save the model in .h5 extension but gets following error in colab while loading the saved model.</p> <pre><code>--------------------------------------------------------------------------- AttributeError Tr...
<p>This error can be caused by having custom logic in your model, and not providing the custom logic in the <code>custom_objects</code> arguments when calling <code>load_model</code>, <code>model_from_json</code>, etc.</p> <p>In my case, this was a function passed to <code>layers.Lambda()</code>:</p> <pre><code>@tf.fun...
python|keras|tensorflow2.0|tf.keras
1
353,913
65,067,608
tf.cast() causes my program to fail back propagation, how can I solve this problem?
<pre><code>import tensorflow as tf tf.compat.v1.disable_eager_execution() A = tf.constant([[1,7,3]],dtype=tf.float32) B = tf.zeros_like([[1,0,0],[0,1,0]]) C = tf.cast(A,dtype=tf.int32)+B f = tf.gradients(C,A) with tf.compat.v1.Session() as sess: print(sess.run(f)) </code></pre> <p>I am using tensorflow 2.3.0 ver...
<p><a href="https://www.tensorflow.org/guide/autodiff#3_took_gradients_through_an_integer_or_string" rel="nofollow noreferrer">Tensorflow does not differentiate through integers</a>. Cast your int to float instead.</p> <pre><code>import tensorflow as tf tf.compat.v1.disable_eager_execution() A = tf.constant([[1,7,3]]...
tensorflow|tensorflow2.0
0
353,914
65,146,786
How to create Pandas Dataframe from lists?
<p>I have four lists like this:</p> <pre><code>A = ['column_1', 'column_2', 'column_3'] B = ['string_1', 'string_2', 'string_3'] numA = [1,2,3] numB = [4,5,6] </code></pre> <p>Is there is way to make Dataframe which as column names will take both lists <code>A</code> and <code>B</code> and as an ...
<p>Try:</p> <pre><code>pd.DataFrame([numA+numB], columns=A+B) </code></pre>
python|pandas
3
353,915
65,388,266
1D CNN in Keras: if the number of filters and kernel_size are too low, will it stop convolution at the middle of a sequence?
<p>For example, I have a sequence of length 100, and I want to use <code>Conv1D</code> in Keras to do convolution:</p> <p>If I set the number of <code>filters = 10</code> and <code>kernel_size = 4</code>, from my understanding, I will have <strong>10 windows</strong> where <strong>every window has a size of 4</strong>...
<p>each filter (a window with size of 4) will be swept over input (96 different position). look at the image below:</p> <p><a href="https://i.stack.imgur.com/VsP0f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VsP0f.png" alt="enter image description here" /></a></p> <p>you have 10 red-window-like f...
python|tensorflow|keras|conv-neural-network
1
353,916
65,388,654
Translate CircleFitByKasa in MATLAB to Python
<p>Dear all: I have no experience with MATLAB but some experience with Python. I'm trying to translate the MATLAB <code>CircleFitByKasa</code> function to Python.</p> <p>The <code>CircleFitByKasa</code> function has the following code:</p> <pre><code>function Par = CircleFitByKasa(XY) %---------------------------------...
<p>The function numpy.linalg.lstsq() returns more than just the least square solution.</p> <p>I think changing this:</p> <pre><code>Par=(P[0]/2 , P[1]/2 , np.sqrt((np.power(P[0],2)+np.power(P[1],2))/4+P[2])) </code></pre> <p>to this:</p> <pre><code>Par=(P[0][0]/2 , P[0][1]/2 , np.sqrt((np.power(P[0][0],2)+np.power(P[0]...
python|arrays|matlab|numpy
1
353,917
65,210,539
From GeoPandas df column containing list of tuple coordinates to a column containing LineString
<p>I have a GeoPandas df:</p> <pre><code>import geopandas as gpd from shapely.geometry import LineString geo_df = gpd.GeoDataFrame({'name': ['foo', 'bar', 'oof'], 'geometry': [[(5.239672304278279, 43.449400744605434), (5.291017601291771, 43.40657292095388)], [(5.27346289130589, 43.418074031107516), (4.935465352479518,...
<p>That should be simple.</p> <pre><code>import geopandas as gpd from shapely.geometry import LineString geo_df = gpd.GeoDataFrame({'name': ['foo', 'bar', 'oof'], 'geometry': [[(5.239672304278279, 43.449400744605434), (5.291017601291771, 43.40657292095388)], [(5.27346289130589, 43.418074031107516), (4.935465352479518,...
python|dataframe|geopandas|shapely
2
353,918
65,362,118
Plotting interval of data in dataframe
<p>A bit new to python so maybe code could be improved.</p> <p>I have a txt file with x and y values, separated by some NaN in between.</p> <p>Data goes from -x to x and then comes back (x to -x) but with somewhat different values of y, say:</p> <p><code>x=np.array([-0.02,-0.01,0,0.01,0.02,NaN,1,NaN,0.02,0.01,0,-0.01,-...
<p>You can create a group label taking the <code>cumsum</code> of where x is null. Then you can define a dictionary keyed by the label with values being a dictionary containing all of the plotting parameters. Use <code>groupby</code> to plot each group separately, unpacking all the parameters to set the arguments for t...
pandas|matplotlib|plot
0
353,919
65,157,063
Selecting second line every 3 lines from web scraped variable with pandas
<p>i webscraped this</p> <pre><code>['', 'Aldoar, Foz Do Douro E Nevogilde', 'Ontem 16:36', '', 'Mafamude E Vilar Do Paraíso', '3', '', 'Estela', '1', '', 'Oeiras E São Julião Da Barra, Paço De Arcos E Caxias', '30', '', 'Olivais', '29', '', 'Olivais', '29', '', 'Olivais', '29', '', 'Nogueira, Fra...
<p>You want to select one element every <em>three</em> elements starting from the <em>second one</em> i.e. <code>index=1</code>.</p> <p>You can achieve this with the built-in list <code>__getitem__</code>:</p> <pre><code>X[1::3] </code></pre> <p>Where <code>X</code> is your initial list.</p>
python|pandas|web-scraping
1
353,920
65,068,263
Pandas DateTime for Month
<p>I have month column with values formatted as: 2019M01 To find the seasonality I need this formatted into Pandas DateTime format. How to format 2019M01 into datetime so that I can use it for my seasonality plotting? Thanks.</p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> with <code>format</code> parameter:</p> <pre><code>print (df) date 0 2019M01 1 2019M03 2 2019M04 df['date'] = pd.to_datetime(df['date'], format='%YM%m') pri...
python|pandas|datetime
3
353,921
65,467,809
Divide a 3d numpy array into 2 groups python
<p>i have a 3d array in this form (12457,8,6) i wand to divide it into 2 equal numpy arrays like (12457,3,8) In fact that the first one containt the first 3 bands and the second one contains the remaind bands: In other words I want my array1 contains the bands 1,2,3 and my array2 contains the bands 4,5,6</p> <p>I tried...
<p>You can use <code>np.split</code> -</p> <pre><code>X = np.random.random((1200,6,8)) print(X.shape) X1, X2 = np.split(X, 2, axis=1) #Array, num of splits, axis for splitting print(X1.shape, X2.shape) </code></pre> <pre><code>(1200, 6, 8) (1200, 3, 8) (1200, 3, 8) </code></pre>
python|numpy|reshape
2
353,922
65,344,062
Web Scraping file path for CSV output
<p>I am new to web scraping. This is my first attempt. I currently have a working script that creates my output but lands it in the same file as where my script is saved. How do I add a file path to where I want my csv to be saved? I will be running it from linux.</p> <pre><code>import requests import pandas as pd url...
<p>Just prepend the full path before the file name.</p> <pre><code>df.to_csv('\home\folder1\folder2\FATCA_Data.csv', index = None, header = True) </code></pre>
python|pandas
0
353,923
65,201,034
How to use Triple Exponential Smoothing to forecast into future?
<p>I want to use Holt-Winters method to forecast into the future. To predict the current values for <code>IdCount</code> with Exponential Smoothing I used this code:</p> <pre><code>df['TES_mul'] = ExponentialSmoothing(df['IdCount'],trend='add',seasonal='add',seasonal_periods=9).fit().fittedvalues </code></pre> <p>This ...
<p>&quot;Triple Exponential Smoothing&quot; is also known as the Hold-Winters method. Please take a look the documentation of: <code>from statsmodels.tsa.holtwinters import ExponentialSmoothing</code></p> <p><a href="https://en.wikipedia.org/wiki/Exponential_smoothing#Triple_exponential_smoothing_(Holt_Winters)" rel="n...
python|pandas|forecast
1
353,924
65,407,473
How to modify Pandas DataFrame based on reversed Dictionary values?
<p><strong>Context:</strong></p> <p>I have a dictionary and a Dataframe.</p> <pre><code>categories = { &quot;Transport&quot;: [&quot;taxi&quot;, &quot;b u s&quot;, &quot;bike&quot;], &quot;Housing&quot;: [&quot;r-ent&quot;,&quot;jysk&quot;, &quot;ikea&quot;]} data = { &quot;Date&quot;: [&quot;2020-09-29...
<p>First idea is loop by dictionary and test joined values by <code>|</code> for regex <code>or</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>Series.str.contains</code></a> and set values by mask in <a href="http://pandas.py...
python|pandas|numpy
2
353,925
65,402,443
drop all cells after a cell
<p>Hello I have the following DataFrame df:</p> <pre><code>A B C D E F apple 0 red green blue 8 orange 2 red blue white 10 apple 2 red green blue 8 orange 0 red 20 purple 10 </c...
<p>Try:</p> <pre><code>df.loc[df['B']==0,'C': ] = '' </code></pre> <p>Prints:</p> <pre><code> A B C D E F 0 apple 0 1 orange 2 red blue white 10 2 apple 2 red green blue 8 3 orange 0 </code></pre>
python|pandas
4
353,926
65,242,684
Pytorch LSTM- VAE Sentence Generator: RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation
<p>I am trying to make a LSTM VAE as a learning stage for future work with pytorch. I managed to get it to work on some small tester data but now that I want to run it on my actual data I am continuously getting this error:</p> <p><em>RuntimeError: one of the variables needed for gradient computation has been modified ...
<p>First, you can re-initialize your hidden layer after each epoch. This will overcome the error that you are facing without any major changes:</p> <pre><code> for epoch in range(epochs): train_rec_loss = [] train_kl_loss = [] for i in range(batches.shape[0]): x = torch.tensor(batches[i], dtype ...
python|pytorch|lstm|autoencoder
0
353,927
65,410,819
Lambda Apply : Referencing other rows and columns
<p>I'm trying to alter the values of a given column in my dataset based on values around the given cell. Consider the following data:</p> <pre><code>Data = {'Col1': [5593 , 5114 , 6803 , 2175 , 2175] , 'Col2': [2879 , 1176 , 7114 , 8677 , 0]} df = pd.DataFrame(data = Data) df.head() Col1 Col2 0 5593 2879 1 5...
<p>IIUC, you could use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer">np.where</a> with the shifted columns:</p> <pre><code>df['Col3'] = np.where(df['Col1'].shift().eq(df['Col1']), df['Col2'].shift(), df['Col2']) print(df) </code></pre> <p><strong>Output</strong></...
python|pandas|lambda|apply
2
353,928
65,091,965
What is mean by (AttributeError: 'NoneType' object has no attribute '__array_interface__') error?
<p>I am trying to build a ML model to detect landmarks on a cartoon image face. When I split the image dataset in to training and validation sets I got the following error. Here I am using pytorch to build the model. So what is mean by this error?</p> <p>This is how I split the dataset.</p> <pre><code># split the datas...
<p>Basically it says when executing the line <code>image = Image.fromarray(image)</code>, the <code>Image.fromarray</code> function is expecting <code>image</code> to be an array and that <code>image</code> implements a function called <code>__array_interface__</code> that will turn itself into an image. However, durin...
python|python-3.x|pytorch|pytorch-dataloader
1
353,929
65,416,246
Why is this block of code converting some value back to Nan?
<p>I have a data frame 'cars', with a column 'price'. Originally, it had 4 null values. Using:</p> <pre><code>cars = cars.dropna(subset=['price']) </code></pre> <p>I dropped those rows. Then I created a new data frame, numeric_cars, with only numeric data. Price at this point still had no null values. However, when I t...
<p>A min_max_scaler will transform that data by doing <code>x = (x - min) / (max - min)</code>.</p> <p>Are you sure there isn't any column with constant values? i.e. min=max? Maybe it's getting a division by 0 and generating the NaN's.</p>
python|pandas
0
353,930
65,457,765
Inaccurate phase returned by np.angle
<ul> <li>I am generating 2 sine waves, first one has fundamental frequency = 50 Hz, amplitude=10, phase=0, the second one has fundamental frequency = 100 Hz, amplitude = 5 and phase = <code>np.pi/6</code> (which is 30degrees).</li> <li>Then I add them up, and perform FFT on the added signal.</li> <li>I calculate the ma...
<p>After performing the FFT the phase of the complex values correspond to the relative phase with a <em>cosine</em>. Since <code>cos(x)</code> has a 90 degrees phase difference with <code>sin(x)</code> you should expect your 0-degrees-phase <code>sin</code> to be detected with a phase of -90 degrees with respect to the...
python|numpy|signal-processing|fft|phase
2
353,931
65,339,428
Drop duplicates and complete nan with oldest values and optimise runing time
<p>I'm working on a data base with some columns, and I drop duplicates after sorting values by date (format Y-m-d). My df is like the following :</p> <pre><code>id date name firstname 01 2020-04-01 max smith 04 2020-08-04 georges yellow 01 2020-05-31 smith 03 2020-02-24 ...
<p>You can optimize a little your code by removing the for loop. I think it is a good idea to use <code>fillna(method='bfill')</code> as you mentioned it in your comment. You can do something like that :</p> <pre><code>df_ind = df.sort_values(by=[&quot;firstname&quot;, &quot;date&quot;], ascending=[True, False]).fillna...
python|pandas|drop-duplicates
0
353,932
65,419,714
how to calculate percent change rate on a multi-date dataframe elegantly?
<p>I have a dataframe, which index is datetime. it contains a columns - price</p> <pre><code>In [9]: df = pd.DataFrame({'price':[3,5,6,10,11]}, index=pd.to_datetime(['2016-01-01 14:58:00', '2016-01-01 14:58:00', '2016-01-01 14:58:00', '2016-01-02 09:30:00', '2016-01-02 09:31:00'])) ...: In [10]: df Out[10]: ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer"><code>GroupBy.apply</code></a> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.date.html" rel="nofollow noreferrer"><code>Datetim...
python|pandas
3
353,933
65,208,845
How to sort dataframe without changing groupings in Pandas?
<p>I am trying to do a groupby using Pandas and apply a sort. Something like below: <img src="https://i.stack.imgur.com/9WAiU.gif" alt="1" /> I have so far created the individual frames to get the subtotals. Not sure how to proceed after that to get the sorting done properly without resorting to hacks.</p> <p>Sample da...
<p>Example for ascending sort by <code>'windspeed'</code>, continuing from your dataframe <code>g</code>:</p> <pre><code>levels = ['admin0', 'admin1', 'admin2'] g.groupby(levels[:-1], group_keys = False).apply(lambda x: x.sort_values(by = 'windspeed', ascending=True)) </code></pre> <p>Basically you need to perform gro...
python|pandas|pandas-groupby
0
353,934
65,323,623
Merge columns from two dataframes when value in columns are not equal
<p>I have a Pandas <code>df</code> which looks like this:</p> <pre><code>| | yyyy_mm_dd | id | product | status | is_50 | cnt | |---|------------|----|------------|--------|-------|-----| | | 2002-12-15 | 7 | prod_rs | 2 | 0 | 8 | | | 2002-12-15 | 16 | prod_go | 2 | 0 | 1 | | | 2...
<p>You would still use merge and just check whether the count columns are different in a second step</p> <pre><code>In [40]: df = pd.merge(df1.drop([&quot;yyyy_mm_dd&quot;, &quot;&quot;, &quot;status&quot;, &quot;is_50&quot;], axis=1), df2, on=['id', 'product'], suffixes=['_df1', '_df2']) ...
python|pandas
3
353,935
65,372,194
Speed up pandas rolling window
<p>I want to speedup my code that I used <code>pandas.rolling().apply()</code> for custom function. The code below is worked fine but it is super slow. Is there any way to speedup it when applying with million of rows.</p> <pre><code>for i in [12, 9, 6, 3]: df[f'want_col_{i}'] = df.groupby(['account'])['types'].rol...
<p>You could try:</p> <pre><code>df['types_eq_1'] = df['types'].eq(1).astype(int) for i in [12, 9, 6, 3]: df[f'want_col_{i}'] = df.groupby(['account'])['types_eq_1'].rolling(window = i).sum() df = df.drop('types_eq_1', 1) </code></pre>
python|pandas|performance|dataframe|rolling-computation
3
353,936
65,468,389
Need work around for downloading xlsx from website
<p>i am trying to obtain data provided in an xslx spreadsheet for download from a url link via python. my fist approach was to read it into a dataframe and save it down to a file that can be manipulated via another script.</p> <p>i have realized that xlsx is no longer supported by xlrd due to security concerns. my curr...
<p>You can always make the request with requests and then read the xlsx into a pandas dataframe like so:</p> <pre><code>import pandas as pd import requests from io import BytesIO url = (&quot;https://www.ssga.com/us/en/institutional/etfs/library-content/&quot; &quot;products/fund-data/etfs/us/holdings-daily-us...
python|pandas|xlrd
0
353,937
65,302,480
Failed precondition: Python interpreter state is not initialized. The process may be terminated
<p>I am trying train my images. This data's size is 50.000 images.</p> <p>My images properities are:</p> <p><a href="https://i.stack.imgur.com/bkU75.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bkU75.png" alt="enter image description here" /></a></p> <p>If i should change my images properities, ho...
<p>Just add this before your program i.e after importing dependencies</p> <pre><code>gpus = tf.config.experimental.list_physical_devices('GPU') tf.config.experimental.set_memory_growth(gpus[0], True) </code></pre>
python|tensorflow|machine-learning|keras|deep-learning
4
353,938
65,111,967
Connecting condition check and random choice
<p>I have question regarding checking a condition and running a random choice afterwards which depends on this check. To make it simple: I have six possible outcomes (e.g. names) and each of them has a specific probability for the following random choice experiment. If the experiment turns out to be 1, I want to print ...
<p>Problem is</p> <ol> <li>your Name and name is not the same</li> <li>you have not import numpy</li> <li>pip3 install numpy</li> </ol> <p>check out this:</p> <pre><code>from numpy import random Name = &quot;Tom&quot; #(result of another process) p_tom = 0.32 p_daniel = 0.19 #(and so on…) employees = [&quot;Tom&quot;, ...
python|numpy|random
1
353,939
65,442,587
Analyzing Token Data from a Pandas Dataframe
<p>I'm a relative python noob and also new to natural language processing (NLP).</p> <p>I have dataframe containing names and sales. I want to: 1) break out all the tokens and 2) aggregate sales by each token.</p> <p>Here's an example of the dataframe:</p> <pre><code>name sales Mike Smith 5 Mike Jones 3 Mary Jane ...
<p><strong>Assumption</strong>: you have a function <code>tokenize</code> that takes in a string as input and returns a list of tokens</p> <p>I'll use this function as a tokenizer for now:</p> <pre class="lang-py prettyprint-override"><code>def tokenize(word): return word.casefold().split() </code></pre> <p><strong...
python|pandas|dataframe|nlp
2
353,940
65,244,586
Seaborn plots for two columns of two different data frames
<p>There are 2 different data frames with identical column names and I would like to draw plots with Seaborn using the below statement.</p> <p>However, I receive an error:</p> <blockquote> <p>'list' object has no attribute 'get'.</p> </blockquote> <pre><code>sns.JointGrid(data=[df_1, df_2] , x=df_1['ABC'], y=df_f2['ABC...
<p><em>I do not believe you can pass a list of dataframes to the <code>data</code> parameter, so you would have to concat the dataframes first OR just call the columns from the separate dataframes</em></p> <p>Also, when you use the <code>data</code> parameter with <code>seaborn</code>, you should only list the names of...
python|pandas|plot|seaborn
0
353,941
65,225,415
Is it possible to pass an extra argument to lambda function in pandas read_csv
<p>I am using the <code>read_csv()</code> function from <code>pandas</code> and the option for a lambda <code>date_parser</code> function quit often and I am wondering if it is possible to pass an argument to this labda function.</p> <p>This is a minimal example where I set the format_string:</p> <pre><code>import pand...
<p>Welcome to the magic of partial functions.</p> <pre><code>def outer(outer_arg): def inner(inner_arg): return outer_arg * inner_arg return inner fn = outer(5) print(fn(3)) </code></pre> <p>Basically you define your function inside a function and return that inner function as the result. In this c...
python|pandas
1
353,942
65,184,378
Plot multiple lines in subplots
<p>I'd like to plot lines from a 3D data frame, the third dimension being an extra level in the column index. But I can't manage to either wrangle the data in a proper format or call the plot function appropriately. What I'm looking for is a plot where many series are plotted in subplots arranged by the outer column in...
<p>If you're okay with using <code>seaborn</code>, it can be used to produce subplots from a data frame column, onto which plots with other columns can then be mapped. With the same setup you had I'd try something along these lines:</p> <pre><code>import seaborn as sns # Completely stack the data frame df = data \ ...
python|pandas|plot
3
353,943
65,346,930
pd.merge "TypeError: string indices must be integers"
<p>I have 3 files and my code is basically a series of merges that populates data from files <code>&quot;lookup&quot;</code> and <code>&quot;NonPO&quot;</code> into the file <code>&quot;supplier&quot;</code> and create a new df called <code>&quot;final2&quot;</code>. The code runs perfectly fine and produces output I a...
<p>You are trying to access <code>NonPO</code> as your data frame, but in fact this is the variable that contains that filename, which is a string. Here it's clear</p> <pre><code>NonPO_Suppliers = pd.read_excel(NonPO) </code></pre> <p>Just change <code>NonPO</code> to <code>NonPO_Suppliers</code> and you should be fine...
python|pandas
2
353,944
65,109,001
pandas object column with string and numerical duplicates
<p>I have</p> <pre><code>import pandas as pd import numpy as np a = pd.DataFrame({'A':['1', '0', '1.0', '0.0', 1.0, 0.0, 'not_ind', np.nan]}).astype('O') print(a['A'].unique()) </code></pre> <p>The set of values is:</p> <pre><code>array(['1', '0', '1.0', '0.0', 1.0, 0.0, 'not_ind', nan], dtype=object) </code></pre> <p>...
<p>If possible numeric values else strings if not possible convert by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.html" rel="nofollow noreferrer"><code>to_numeric</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html" rel="n...
python|pandas
2
353,945
65,444,999
How to delete decimal values from an array in a pythonic way
<p>I am trying to delete an element from an array. When trying to delete integer values(using numpy.delete) it's working but it doesn't work for decimal values.</p> <pre><code>For integer deletion X = [1. 2. 2.5 5.7 3. 6. ] to_delete_key = [3, 7.3] Y = np.delete(X, to_delete_key, None) Output is [1. 2. 2.5 5.7 6. ...
<pre><code>In [249]: X = np.array([1., 2., 2.5, 5.7, 3., 6. ]) ...: to_delete_key = [3, 7.3] In [252]: np.delete(X, to_delete_key) Traceback (most recent call last): File &quot;&lt;ipython-input-252-f9031065a548&gt;&quot;, line 1, in &lt;module&gt; np.delete(X, to_delete_key) File &quot;&lt;__array_func...
python|numpy|numpy-ndarray
1
353,946
65,198,998
sphinx warning: autosummary: stub file not found for the methods of the class. check your autosummary_generate settings
<p>I have an open source package with lots of classes over different submodules. All classes have methods <code>fit</code> and <code>transform</code>, and inherit <code>fit_transform</code> from sklearn. All classes have docstrings that follow numpydoc with subheadings Parameters, Attributes, Notes, See Also, and Metho...
<p>Ok, after 3 days, I nailed it. The secret is add a short description to the methods in the docstrings after the heading &quot;Methods&quot; instead of leaving them empty as I did.</p> <p>So:</p> <pre><code>class DropFeatures(BaseEstimator, TransformerMixin): Some description. Parameters ...
python|python-sphinx|numpydoc|sphinx-napoleon
8
353,947
65,205,599
Is there a possibility to convert each row of a pandas data-frame into a predefined text file?
<p>My dataframe looks as such:</p> <p><a href="https://i.stack.imgur.com/wLdhS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wLdhS.png" alt="Dataframe" /></a> I'm looking to insert each row into a pre-defined text file so that the values have a specific place in the document. This is what I came up...
<p>You are almost there. You can use string formatting to insert your values in the string like so:</p> <pre><code>data = &quot;some data i want to insert&quot; result = &quot;This is what I want to say: {}&quot;.format(data) # or result = f&quot;This is what I want to say: {data}&quot; </code></pre> <p>References:</p...
python|pandas|row
1
353,948
65,399,247
calculate column mean of a matrix - how to optimize?
<p>input:</p> <pre><code>[ [1,2,3,4,5], [5,4,3,2,1], [3,3,3,3,3] ] </code></pre> <p>output:</p> <pre><code>[3,3,3,3,3] </code></pre> <p>brute force solution:</p> <pre><code>def calculate_col_mean(matrix): mean = [] num_row = len(matrix) num_col = len(matrix[0]) result = [0] * num_col for i in range(num_r...
<pre><code>import numpy as np a = np.array([[1,2,3,4,5],[5,4,3,2,1],[3,3,3,3,3]]) column_mean = a.mean(axis=0) </code></pre>
python|multithreading|algorithm|numpy|python-multithreading
1
353,949
50,165,802
tensorflow in google colab
<p>I am trying to reproduce an example of MNIST deep learning neural network online on Google Colab. Here is the link <a href="https://www.tensorflow.org/programmers_guide/summaries_and_tensorboard" rel="nofollow noreferrer">https://www.tensorflow.org/programmers_guide/summaries_and_tensorboard</a> and the correspondin...
<p>i've seen alot of suggestions using ngrok, honestly tensorboard usage in google collab is simple as:</p> <pre><code>%load_ext tensorboard %tensorboard --logdir /content/Tensorflow/workspace/training_demo/models/my_ssd_resnet50_v1_fpn </code></pre> <p>Where /content/Tensorflow/workspace/training_demo/models/my_ssd_r...
python-3.x|tensorflow|tensorboard
0
353,950
50,068,941
SageMaker Tensorflow - how to write my serving_input_fn()
<p>I'm pretty new to Tensorflow and SageMaker and I'm trying to figure out how to write my <code>serving_input_fn()</code>. I've tried a number of ways to do it, but to no avail. </p> <p>my input function has 3 feature columns: <code>amount_normalized, x_month and y_month</code>:</p> <pre><code>def construct_feature_...
<p>Posting this here in case anyone else has this issue.</p> <p>After a bunch of trial and error I managed to solve my issue by writing my serving input function like this:</p> <pre><code>FEATURES = ['amount_normalized', 'x_month', 'y_month'] def serving_input_fn(hyperparameters): feature_spec = { key : t...
tensorflow|amazon-sagemaker
3
353,951
49,885,060
Cross reference list of ids to index
<p>I have grouped together a list of ids that are associated with a certain value and placed all these lists of ids into a dataframe. It looks like this: (with index = id)</p> <pre><code> phase list_ids id a1 1 [a1,a2,c3] a2 3 [a1,b2,c3] b1 3 [a2,b2] b2 2 [b1,b2,c1] b3 3 [b2,c1...
<p>Assuming that each element in the column <code>list_ids</code> is a list of strings, you could do the following:</p> <p>First get a <code>set</code> of the "good" <code>ids</code> (where phase is 2 or 3):</p> <pre><code>good_ids = set(df[df["phase"].isin([2,3])].index) print(good_ids) #{'a2', 'b1', 'b2', 'b3', 'c3...
python|list|pandas|dataframe
1
353,952
50,102,539
Differences in tensorflow prediction on CPU and GPU for CNN models
<p>I have trained an FCN network on a GPU and have saved the model(.pb file). I am getting correct predictions on the GPU. However i am getting NAN for the same model file when I am running predictions on CPU. Are there any CPU/GPU flags that need to be set? Or are there any overflow issues with CPU?</p>
<p>There are no special overflow condition on the CPU. Both should implement IEEE 754.</p> <p>There are different ways some high level functions can be implemented (tanh, sigmoid) and they are implemented differently on GPU vs CPU to take advantage of the platform.</p> <p>Whenever you get NaN from your model somethin...
tensorflow|convolutional-neural-network
2
353,953
50,088,193
To extract unique value and count from the dataframe in pandas
<p>I need to extract the unique value, their counts in the column of a data frame and separate index key column in a data frame.</p> <p>let us consider following as the example, data frame df1 consists</p> <pre><code>+------+--------+ | city | score | +------+--------+ | a | 12 | | b | 45 | | c | ...
<p>IIUC, you need <code>reset_index</code> at the first so we can include the index value in the <code>agg</code> part </p> <pre><code>df.reset_index().groupby('city').agg({'score':'count','index':'first'}) Out[404]: index score city a 0 3 b 1 1 c 2 1 d ...
python|python-3.x|pandas
1
353,954
50,120,736
How to get a discontinuous list according to the values of other list in pandas?
<p>I am trying to give a list of number to a dataframe. The result I want is as below:</p> <pre> Unit Ida 1 Parcel 1 2 Parcel 2 2 Parcel 3 2 3 4 Parcel 1 5 Parcel 2 5 </pre> <p>The first code i used is as below:</p> <pre> Address['Ida'] = '' Id...
<p>IIUC using <code>cumsum</code> with <code>shift</code> </p> <pre><code>((df.Unit=='')|(df.Unit=='Parcel1')).cumsum() Out[129]: 0 1 1 2 2 2 3 2 4 3 5 4 6 5 7 5 Name: Unit, dtype: int32 </code></pre>
python|pandas|numpy
2
353,955
49,926,696
Getting name of images per batch in Keras ResNet50 model
<p>I'm finetuning a ResNet50 model with a few additional layers using Keras. I need to know which images are trained per batch. </p> <p>The problem I have is that only the imagedata and their labels, but no image names can be passed on in the fit and fit_generator in order to output the image names, which are trained...
<p>You can make your own generator so you could track what is fed into the network, and do whatever you like with the data (i.e. match indices to images). </p> <p>Here is a basic example of a generator function which you can build upon: </p> <pre><code>def gen_data(): x_train = np.random.rand(100, 784) y_trai...
python|tensorflow|keras|resnet
1
353,956
49,854,899
How can i train GaussianNB in pipeline by removing error[AttributeError: 'numpy.ndarray' object has no attribute 'lower']
<p>This is the data i use count vectorizer and tfidftransformer and also use GaussianNB but i get error in this code. Please let me know the correct syntax.</p> <pre><code>train = [('I love this sandwich.','pos'), ('This is an amazing place!', 'pos'), ('I feel very good about these beers.', 'pos'), ('Th...
<p>Do</p> <pre><code>clf = GaussianNB().fit(text_train_tfidf.toarray() , list(zip(*train))[1]) </code></pre> <p>The GaussianNB doesnt support sparse matrices as input for X, but the TfidfTransformer will by default return a sparse matrix. Hence the error.</p> <p><code>toarray()</code> will convert that to dense. But...
python|numpy|scikit-learn
1
353,957
50,066,943
Can Luigi file targets be properly managed using pandas file i/o functions instead of open/close
<p>I have a script that relies heavily on pandas file i/o functions like read_csv(), to_csv(), etc. with the many custom parameters they offer.</p> <p><strong>Can these be used in a luigi pipeline for local file targets?</strong></p> <p>I want to convert it to a luigi pipeline but every example I have seen uses open/...
<p>Yes. <code>LocalTarget</code> can be used with the output of arbitrary code. The file tracking relies on the <code>exists()</code> method. <code>open()</code> is just a convenience method.</p>
pandas|csv|luigi
1
353,958
49,966,402
Using Tensorflow's top_k and scatter_nd
<p>I'm trying to write an operation in tensorflow that propagates only the top k values of each feature map.</p> <p>example:</p> <p>k=1, input size is <code>[batch_size, x, y, channels]</code> let's say it's <code>[1,2,2,3]</code></p> <p>The output should be the same size and if k=1 than each x,y plane will have onl...
<p><a href="https://www.tensorflow.org/api_docs/python/tf/nn/top_k" rel="nofollow noreferrer"><code>tf.nn.top_k()</code></a> only returns the top k values in the <em>last dimension</em>. So you have to add back all the other dimensions. Easiest with <a href="https://www.tensorflow.org/api_docs/python/tf/where" rel="nof...
python|tensorflow
3
353,959
49,865,330
Pandas move headers
<p>I have extract a table from a website, however, the generated column headers have been misplaced.</p> <p>For example,</p> <p>Original table:</p> <pre><code>A A-explaned B B-explaned C C-explaned 1 0.2 10% 2 0.7 20% 3 0.8 15% 1 0.2 10% 2 0.7 20% 3 0.8 15% 1 0.2 10% 2 0.7 20% 3 0.8 15% 1 0...
<p>You can use regex for <code>sep</code> parameter in read_csv:</p> <pre><code>from io import StringIO import pandas as pd txt = StringIO("""A A-explaned B B-explaned C C-explaned 1 0.2 10% 2 0.7 20% 3 0.8 15% 1 0.2 10% 2 0.7 20% 3 0.8 15% 1 0.2 10% 2 0.7 20% 3 0.8 15% 1 0.2 10% 2 0.7 ...
python|pandas|io|header|multiple-columns
0
353,960
49,830,159
How do I evaluate a TensorFlow tuple?
<pre><code>import tensorflow as tf a = tf.zeros([10]) b = tf.zeros([10]) state = tf.tuple([a, b], name='initial_state') with tf.Session() as sess: s = sess.run('initial_state:0') </code></pre> <p>I get the following error with this example:</p> <pre class="lang-none prettyprint-override"><code>ValueError: Fetch...
<p>Tuples in TensorFlow are not tensors, but a list of tensors, and so cannot be fetched as a whole through an operation in the graph. <code>tf.tuple</code> will create a few grouping and dependency control operations (<code>initial_state/group_deps</code>, <code>initial_state/control_dependency</code> and <code>initia...
python|tensorflow
1
353,961
49,869,302
Get the value of an item in a tensor in Tensorflow.js
<p>How do I get the value out of a tensor in Tensorflow.js after specifying the index?</p>
<p>You can use datasync for this.</p> <pre><code>const newTensor = tf.tensor2d([[2,4],[5,6]]); const tensorData = newTensor.dataSync(); console.log("data[0] is " + tensorData[0]); console.log("data[3] is " + tensorData[3]); </code></pre> <p><a href="https://codepen.io/anon/pen/NMKgeO?editors=1011" rel="noreferrer">ht...
indexing|tensor|tensorflow.js
20
353,962
49,990,515
Value error with numpy arrays (shapes)
<p>I keep getting a ValueError when working with numpy arrays and I can't figure out what's causing it, as it seems to be working correctly outside of my for loop. Here is my code:</p> <pre><code>import numpy as np def x(t, x_0, w): return x_0*np.cos(w*t) def x_prime(t, x_0, w): return -x_0*w*np.sin(w*t) w =...
<p>In the <code>print</code> line the first argument of <code>x()</code>/<code>x_prime()</code> is a scalar (<code>1</code>).</p> <p>In the <code>y[i]</code> line you pass <code>t</code> instead, which is a 10000-elements array, resulting in <code>np.array([x_prime(t, x_0, w), -w**2 * x(t, x_0, w)])</code> being a (2,...
python|arrays|python-2.7|numpy|valueerror
1
353,963
49,806,485
filter data by str.contains
<p>I'm trying to filter my large data by columns that may contains the following strings 'io' and 'ir'.</p> <p>df1</p> <pre><code>index aio bir ckk 1 2 3 4 2 3 4 5 </code></pre> <p>I want to create a new df with columns that contain 'io' and 'ir. The new df should look :</p> <pre><cod...
<p>with <code>pd.DataFrame.filter</code></p> <pre><code>df.filter(regex='i(o|r)') aio bir index 1 2 3 2 3 4 </code></pre> <p>If you have a list of things to match</p> <pre><code>things = ['io', 'ir'] df.filter(regex='|'.join(things)) aio bir index 1 2 ...
python|pandas|dataframe
6
353,964
50,183,920
Python value counts and return the other columns in pandas
<p>I just started doing my first ML project with Python, and got stuck with one issue. <a href="https://i.stack.imgur.com/9zCt2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9zCt2.png" alt="enter image description here"></a> My project is to analyze some animal shelter information. Above is the lis...
<p>A <code>groupby</code> operation is not required here.</p> <p>You can create a <code>value_counts</code> series, filter it for items which occur more than 3 times, and then use this to filter your original dataframe.</p> <p>This is a minimal example:</p> <pre><code>df = pd.DataFrame({'col1': range(10), 'col2': ra...
python|pandas|dataframe
3
353,965
50,005,801
Python, Pandas: How to change the bandwidth selection for DataFrame.plt.density()?
<p>I have some data i have placed into a <code>pandas</code> <code>dataframe</code>, and I plotted a bar plot of the unique value counts for a particular <code>column</code>. </p> <p>I would like to control the bandwidth of the Pandas built-in <code>df.plot.density()</code></p> <p>Function, which plots the kde over t...
<p>If you want to control the bandwidth I would recommend using seaborn's kdeplot (see <a href="https://seaborn.pydata.org/generated/seaborn.kdeplot.html" rel="nofollow noreferrer">link</a>) - namely the <strong>bw</strong> parameter</p>
python|pandas|dataframe|kernel-density
1
353,966
49,888,935
How to train a model when the derivative is not known and a batch of outputs is required to calculate cost?
<p>I want to know how to train a model in <code>tensorflow</code> if the cost cannot be evaluated at every input. E.g. if my objective function tests whether some condition is met <em>half</em> of the time (with any deviation from this being penalised).</p> <p>Previously I would write code similar to the following to ...
<p>First of all, what you can do is to define your own cost function over a <em>whole batch</em> instead of single inputs. Sticking with your circle example, you can do:</p> <pre><code>inside_bool = ( tf.square( X_pred ) + tf.square( Y_pred ) ) &lt; tf.square( r ) inside_float = tf.cast( inside_bool, tf.float32 ) prop...
python|tensorflow
2
353,967
49,995,079
Getting ValueError at time of applying tensorflow.convert_to_tensor in Tensorflow and Python
<p>I am trying to put two matrices with different shapes in a tensor in the following way:</p> <pre><code> import tensorflow as tf matrix = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]] mat...
<p>The error is due to mismatch in dimensions of <code>matrix</code>(5x5) and <code>matrix2</code>(5x3).</p> <pre><code>import numpy as np mat2=[[1,2,3],[6,7,8]] mat1=[[1,2,3,4,5],[3,4,5,6,7]] test = [] test.append(mat1) test.append(mat2) res=np.array(test) print res </code></pre> <blockquote> <p>array([[list([1, ...
python|tensorflow
0
353,968
50,170,011
Adapting pytorch softmax function
<p>I am currently looking into the softmax function and I would like to adapt the orignally implemented for ome small tests. </p> <p>I have been to the docs but there wasn't that much of usefull information about the function. This is the <a href="https://pytorch.org/docs/master/_modules/torch/nn/modules/activation.ht...
<h2>Softmax Implementation in PyTorch and Numpy</h2> <p>A Softmax function is defined as follows:</p> <p><a href="https://i.stack.imgur.com/46XPI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/46XPI.png" alt="Softmax function definition" /></a></p> <p>A direct implementation of the above formula is ...
pytorch|softmax
2
353,969
50,189,608
How can I change a field with numbers and letters to just numbers in python
<p>Keep up the good work..so far u had helped me with everything that i needed so i hope u can do it once more.</p> <p>I have a csv file with 7-8 columns and in one specific.</p> <p>"Cabin" is the name of it has values that varies from A-T but with numbers (not in all of them).</p> <p>IE A,A23,A43,B,B34 ,B45 etc...<...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/text.html#splitting-and-replacing-strings" rel="nofollow noreferrer"><code>.get</code></a> to extract the string at a given position.</p> <pre><code># sample data df = pd.DataFrame({'codes': ['A','A23','A43','B','B34' ,'B45','E33']}) ## extract code...
python|python-3.x|pandas
0
353,970
50,101,984
Import TensorFlow data from pyspark
<p>I want to create a predictive model on several hundred GBs of data. The data needs some not-intensive preprocessing that I can do in pyspark but not in tensorflow. In my situation, it would be much more convenient to directly pass the result of the pre-processing to TF, ideally treating the pyspark data frame as a v...
<p>It sounds like you simply want to use <code>tf.data.Dataset.from_generator()</code> you define a python generator which reads samples out of spark. Although I don't know spark very well, I'm certain you can do a reduce to the server that will be running the tensorflow model. Better yet, if you're distributing your t...
python|tensorflow|pyspark
4
353,971
49,879,944
Why is numpy.take slow on the result of numpy.split when simple indexing is not?
<p>Consider the following code</p> <pre><code>import timeit import numpy as np MyArray = np.empty((10000, 10000, 1)) print((MyArray.size, MyArray.shape, MyArray.dtype, np.isfortran(MyArray))) print(timeit.timeit(lambda: MyArray[0], number=10000)) print(timeit.timeit(lambda: MyArray.take(0), number=10000)) MyTwoArray...
<p>This answer is a bit long and convoluted, but I think the key point is, <code>MyArray[0]</code> is a view in both constructs. <code>MyArray.take</code> makes a copy in the 2nd case (<code>split</code>) case. That <code>copy</code> takes much longer.</p> <hr> <p>The 2 actions are not equivalent:</p> <pre><code>I...
python|performance|numpy|multidimensional-array
2
353,972
50,166,875
python 2: Slicing pandas dataframe using datetime index skips one day from the wanted date
<p>I have below df with "start_datetime" as index. "start_datetime" is of type class'pandas._libs.tslib.Timestamp' :</p> <pre><code> col1 col2 start_datetime 2017-12-27 01:50:00 0.000000 0.0 2017-12-27 01:55:00 ...
<p>In my opinion problem is <code>2018-01-01</code> does not exist. You can check it:</p> <pre><code>print (df['2018-01-01']) #return unique days by floor idx = df.index.floor('d').unique() #print (idx) #get datetimes between print (idx[(idx &gt;= '2017-12-30') &amp; (idx &lt;= '2018-01-02')]) </code></pre>
python-2.7|pandas
1
353,973
49,988,148
Pandas - Comparing None values
<p>Consider this snippet:</p> <pre><code>a = pd.DataFrame([[None]]) b = pd.DataFrame([[None]]) </code></pre> <p>Now, I want to validate both of them contains the exact same values:</p> <pre><code>int((a == b).sum()) # should be 1 </code></pre> <p>but it's not 1. Instead, it returns 0. This behavior is giving me tr...
<p>pandas is special casing <code>None</code> so as to be interpreted as <code>NaN</code> (since <code>NaN != NaN</code>, and <code>pd.isnull</code> treats both consistently... this may be one explanation). </p> <p>Not a solution, but a workaround – <code>np.array_equal</code> works, if they're <code>None</code> and n...
python|pandas
1
353,974
49,860,636
CUDA 8.0 installation fails because of Visual Studio
<p>I have NVIDIA GEFORCE GTX 950M. So it's respective CUDA distribution is 8.0. So I ve been trying to install CUDA 8.0 GPU Computing toolkit, the status going unknown and the installer couldn't find the respective VS for CUDA 8.0. </p> <p><a href="https://i.stack.imgur.com/QYCnj.jpg" rel="nofollow noreferrer"><img sr...
<p>Visual Studio is a programming IDE. CUDA comes with some built in add-ons for VS that only install if you already have VS installed. As noted in the message "The following information [...] does not describe CUDA toolkit install status."</p> <p>Unless you have VS and are trying to install the add-ons, your install ...
tensorflow|cuda|nvidia
0
353,975
49,874,456
ShuffleSplit of Sklearn issue
<p>I have a data set named <code>df_noyau_yes</code> and I want to apply a ShuffleSplit to split it into train and test sets to train an autoencoder. </p> <p>The problem is that this functions returns indices of the shuffled data, I tried to extract the data of these indices to feed them to the autoencoder but it dose...
<p>For selection a dataframe values by index of rows and columns, <code>iloc</code> is used.</p> <p>From <a href="https://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-position" rel="nofollow noreferrer">the documentation</a>:</p> <blockquote> <p>The .iloc attribute is the primary access method. T...
python|split|sklearn-pandas|autoencoder
0
353,976
50,171,190
Take the best value in dataframe which have multiple same datas
<p>For example, I have this <code>df</code>:</p> <pre><code> score 0 a b c 0.7 1 a b c 0.7 2 b c d 0.8 3 c d e 0.9 4 c d e 0.9 5 d e f 0.8 </code></pre> <p>I want to take values which have the best score, but there are more than...
<p>You can <code>loc</code> to find the largest by <code>score</code>, then <code>iloc</code> to select the last row:</p> <pre><code>res = df.loc[df['score'] == df['score'].max()]\ .iloc[-1] print(res) score 0.9 Name: (4, c, d, e), dtype: float64 </code></pre>
python|pandas|dataframe
3
353,977
50,012,376
Python does not free memory when variable goes out of scope
<p>When I initialize a Numpy array inside a function, Python does not free the memory after the function returns as shown in the code example below. Is there any way I can free this memory? Using gc.collect() did not work and the same problem also occurs in Python2 and Python3.</p> <pre><code>import numpy as np import...
<p>Python is actually freeing the memory as soon as the function is done. The problem here is that the value you're printing out, <a href="https://docs.python.org/3/library/resource.html#resource-usage" rel="nofollow noreferrer"><code>resource.getrusage(resource.RUSAGE_SELF).ru_maxrss</code></a>, tells you the peak or ...
python|numpy|memory
3
353,978
50,210,878
Count appearance of each player by groups in Pandas
<p>There is a dataframe of players playing in different Teams(groups), so I need to count all intersections of each player with his team players where he only appears.</p> <pre><code>df = pd.DataFrame({ 'Team' : ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C'], 'Player' : ['Joe', 'Mike', '...
<p>Given your input DF of:</p> <pre><code>df = pd.DataFrame({ 'Team' : ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C'], 'Player' : ['Joe', 'Mike', 'Steve', 'Henry', 'Steve', 'Joe', 'Mike', 'Joe', 'Steve', 'Dan', 'Henry'] }) </code></pre> <p>You can merge it against itself on the "Team" column to get ...
python-3.x|pandas
2
353,979
49,866,071
Overwriting existing dataframe in loop
<p>I am trying to transform elements in various data frames (standardize numerical values to be between 0 and 1, one-hot encode categorical variables) but when I try to overwrite the dataframe in a loop it doesn't modify the existing dataframe, only the loop variable. Here is a dummy example:</p> <pre><code>t = pd.Dat...
<p>You can't change elements of a list while iterating over the list that way. Search "changing list elements loop python" for a bunch of good stack overflow questions on why this is the case. My understanding is that "hi" is value-copied, not a reference to the original variable.</p> <p>If you want to modify elements...
python|pandas
0
353,980
50,178,866
save checkpoint with Tensorflow
<p>I have 3 folders for my CNN model which are <code>train_data, val_data, test_data.</code></p> <p>when I am training my model, I found that the accuracy may vary and sometimes the last epoch does not show the best accuracy. for example, last epoch accuracy is 71% but I found the better accuracy in the earlier epoch. ...
<p>The <code>tf.train.Saver()</code> documentation describes the following:</p> <pre><code>saver.save(sess, 'my-model', global_step=0) ==&gt; filename: 'my-model-0' ... saver.save(sess, 'my-model', global_step=1000) ==&gt; filename: 'my-model-1000' </code></pre> <p>Note that if you pass <code>global_step</code> to th...
python|python-3.x|tensorflow|tensorflow-estimator
0
353,981
49,908,014
How can I check if a network is scale free?
<p>Given an undirected NetworkX Graph <code>graph</code>, I want to check if it is scale free.</p> <p>To do this, as I understand, I need to find the degree <code>k</code> of each node, and the frequency of that degree <code>P(k)</code> within the entire network. This should represent a power law curve due to the rela...
<p>Have you tried powerlaw module in python? It's pretty straightforward.</p> <p>First, create a degree distribution variable from your network:</p> <pre><code>degree_sequence = sorted([d for n, d in G.degree()], reverse=True) # used for degree distribution and powerlaw test </code></pre> <p>Then fit the data to powerl...
python|numpy|matplotlib|networkx|complex-networks
4
353,982
63,860,284
Path too long for StringIO, but not for text
<p>I would like to copy data into a pandas dataframe using StringIO as opposed to a text file. Some files will be really big and i'd rather not have big text files and then delete. Using StringIO seems like a much nicer solution.</p> <p>If I do this the dataframe gets created no problem</p> <pre><code>import pandas as ...
<p>You pass the buffer, not its contents.</p> <pre><code>df2=pd.read_csv(io, sep='\t', ...) </code></pre>
python|pandas|stringio
1
353,983
63,919,136
How to get average number of transactions within groupby groups?
<p>I have a transaction dataframe with sales figures for McDonalds and KFC</p> <pre><code> month shop transaction_value 0 January McDonalds 5 1 January KFC 1 2 January KFC 34 3 January KFC 12 4 February M...
<p>You are close, need <code>mean</code> per <code>level=0</code>:</p> <pre><code>df.groupby([df.shop,df.month])['transaction_value'].count().mean(level=0) </code></pre> <p>What working same like:</p> <pre><code>df.groupby([df.shop,df.month])['transaction_value'].count().groupby(level=0).mean() </code></pre>
python|pandas
2
353,984
64,135,708
Merge is not working on two dataframes of multi level index
<p>First DataFrame : housing, This data Frame contains MultiIndex (State, RegionName) and some relevant values in other 3 columns.</p> <pre><code>State RegionName 2008q3 2009q2 Ratio New York New York 499766.666667 465833.333333 1.072844 California Los Angeles ...
<p>I found the issue. There was space at the end of the string in the RegionName column of the second dataframe. used Strip() method to remove the space and it worked like a charm.</p>
python|pandas|dataframe|merge
0
353,985
63,824,889
How can i show in GUI a filtered DataFrame in python with Tkinter?
<p>As the title suggest, I need to make a Button in a GUI (With Tkinter) that shows me a filtered DataFrame</p> <p>Import of the DataFrame</p> <pre><code>df = pd.read_csv (r'C:\Users\shold\Downloads\df.csv') df = df[['A', 'B', 'C', 'D', 'E', 'F', 'G']] </code></pre> <p>Filtered DataFrame</p> <pre><code>FIltered_df= df....
<p>Try this out. To show something in GUI you have to use something like <code>Label</code>.</p> <p>Make these changes on the function.</p> <pre><code>def first_print(): text =&quot;Filter the df&quot; text_output = tk.Label(window, text=text) text_output.grid(row=0, column=1, padx = 50) text = tk.Label...
python|pandas|dataframe|user-interface|tkinter
1
353,986
63,808,932
convert a string in a column become Nan in python
<p>can I choose a specific string of a column to become NaN in python? My data frame shows like this:</p> <pre><code>type size A 1 B 1 C 1 </code></pre> <p>and I want to convert 'B' become Nan, so the table will be like:</p> <pre><code>type type A 1 NaN 1 C 1 </code></pre...
<p>You can use <code>np.where</code></p> <pre><code>df['type'] = np.where(df.type.eq('B'), np.nan, df.type) </code></pre> <p>You can also use <code>df.loc</code></p> <pre><code>df.loc[df.type.eq('B'), 'type'] = np.nan </code></pre> <p><strong>Output:</strong></p> <pre><code> type size 0 A 1 1 NaN 1 2 C...
python|pandas|nan
0
353,987
64,077,001
Processing records with conditions in pandas
<p>Given a pandas dataset with columns a, b and c, I have the following requirement:</p> <pre><code>calculate m = mean of c in the entire dataset For each record in the dataset, if (a&gt;10 and b&lt;5) c = m </code></pre> <p>Is it possible to do this with a single pandas command, or I need to loop each record and ask ...
<p>I think it is very much possible using boolean masks</p> <p>This should work-</p> <pre class="lang-py prettyprint-override"><code>m = df.c.mean() df.c[(df.a &gt; 10) &amp; (df.b &lt; 5)] = m </code></pre>
python|python-3.x|pandas
0
353,988
63,843,683
Pandas create multiple dataframe based on group from another dataframe
<p>I have a pandas dataframe</p> <pre><code>df=pd.DataFrame({'Name':['Jhon','Andy','Jenny','Joan','Paul','Rosa'], 'Position':['Programmer','Designer','Programmer','Designer','Analyst','Analyst']}) </code></pre> <p>I want to create multiple of other dataframe based on the Position, and named each datafr...
<p>You could create a dictionary:</p> <pre><code>{&quot;Job_as_&quot;+ x : df.loc[df.Position==x, &quot;Name&quot;].to_list() for x in df.Position.unique()} </code></pre> <p><strong>Output</strong></p> <pre><code>{ 'Job_as_Programmer': ['Jhon', 'Jenny'], 'Job_as_Designer': ['Andy', 'Joan'], 'Job_as_Analyst': ['Paul'...
python|pandas|dataframe
1
353,989
64,043,731
compare two date columns - check if they fall in range - take value from 3rd column
<p>I am working on a question of whether patients' testresults were received between minus 1 and + 3 days after being admitted to hospital. If so, I want to retrieve to which department they were admitted to first.</p> <p>Complexity comes from patients being tested multiple times during admission as well as patients be...
<p>Use iterrows. a series cannot give a single boolean value which <code>if</code> expects.</p> <pre><code>for index,row in df_final.iterrows(): if (df_final['date_rslt'][index] &lt; (df_final['date_admis'][index] + timedelta(days = + 3))) and (df_final['date_rslt'][index] &gt; (df_final['date_admis'][index] + tim...
python|pandas
1
353,990
63,960,443
How to handle Nan values in function
<p>I am new with Python and have a problem that I don't know how to solve.<br /> I have the following code:</p> <pre><code>#Calculating the closest distances df_final=pd.DataFrame() records = df_ipos.to_dict('records') #converting dataframe to a list of dictionaries def return_closest(df,inp_record): &quot;&quot;...
<p>in case <code>param</code> is NaN you can <code>break</code> the for loop to exit the loop or you can <code>continue</code> to the next param.</p> <pre><code>for param in params: d1,d2 = record.get(param,0),inp_record.get(param,0) # fetching value of these parameters. default is0 if not found ...
python|pandas
0
353,991
64,094,705
How to read a specific file from a tar file using Windows?
<p>I have a tar file with several files compressed in it. I need to read one specific file (it is in csv format) using pandas. I tried to use the following code:</p> <pre><code>import tarfile tar = tarfile.open('my_files.tar', 'r:gz') f = tar.extractfile('some_files/need_to_be_read.csv') import pandas as pd df = pd.re...
<p>When you call <code>pandas.read_csv()</code>, you need to give it a filename or file-like object. <code>tar.extractfile()</code> returns a file-like object. Instead of reading the file into memory, pass the file to Pandas.</p> <p>So remove the <code>.read()</code> part:</p> <pre class="lang-py prettyprint-override">...
python|pandas|tar
1
353,992
63,974,485
Sort alphabetically in pandas dataframe
<p>I have a dataframe</p> <pre><code>Counties Numbers Yabucoa Municipio, Puerto Rico 7766 Marion County, West Virginia 8756 Barbour County, Alabama 33445 Santa Cruz County, Arizona 447 Navajo County, Arizona 1500 Denver County, Colorado 67990 </code></pre> <p>I'm...
<p><em>an</em> approach to this could be the following:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame( [ {&quot;Counties&quot;: &quot;Yabucoa Municipio, Puerto Rico&quot;, &quot;Numbers&quot;: 7766}, {&quot;Counties&quot;: &quot;Marion County, West Virginia&quot;, &quot;Numbe...
python|pandas|dataframe|sorting
1
353,993
64,024,550
Semantic Segmentation with a dominant class
<p>I am training a semantic segmentation model consists of 3 classes(counting with the background). The background is the dominant class, and the problem is that the model predicts every pixel as background. I am currently using cross entropy loss function.</p> <p>What are the solutions for this situation?</p>
<p>This is a typical strong imbalance for image segmentation; down below there are a couple of solutions to tackle this problem.</p> <ol> <li>Use <code>Jaccard(IoU)</code> loss or <code>dice loss</code>; rather than optimizing for accuracy, you will optimise for the intersection over union, for example, and it has been...
tensorflow|machine-learning|deep-learning|neural-network
1
353,994
63,973,563
Setting the same seed for torch, random number and numpy throughout all the modules
<p>I am trying to set the same seed throughout all the project. Below are the parameters I am setting in my main file, in which all other modules will be imported -</p> <pre><code>seed = 42 os.environ['PYTHONHASHSEED'] = str(seed) # Torch RNG torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_a...
<blockquote> <p>1)If I just remove the random_state parameter from the above statement so will it take the seed from my main file?</p> </blockquote> <p>Yes, as the <a href="https://scikit-learn.org/stable/glossary.html#term-random-state" rel="nofollow noreferrer">docs</a> for default (<code>None</code>) value say:</p> ...
python|python-3.x|pytorch|random-seed
1
353,995
64,090,900
Getting a single value from np.where() to populate new column
<p>I'm trying to get the value of an np.where() function to populate an entire column, but am running into some issues. I have two tables, a lookup table that contains two columns, &quot;injuryType&quot;, and &quot;Id&quot; where injuryType is a string and Id is an int. The second table is a new table that I am trying ...
<p>One of possible solutions:</p> <pre><code>new_df = pd.DataFrame({ 'Id': lookup[lookup.InjuryType == 'chronic_Ankle'].Id.item(), 'Description': ['a', 'b', 'foo', 'bar']}) </code></pre> <p>The result is:</p> <pre><code> Id Description 0 4 a 1 4 b 2 4 foo 3 4 bar </...
python|pandas|numpy
0
353,996
63,777,021
Why pandas .last('1W') don't show last 7 days?
<p>Trying to extract a max value from a Pandas Dataframe with a daytime as index, I'm using .last('1W'). My data goes from the first day of month (2020-09-01 00:00:00). It seems to work properly until I reach today (monday 07/09/2020). At first I supposed that .last() takes the last days of week from starting value (su...
<p>If you're looking for an offset of 7 days, why not use the <code>Day</code> offset, rather than the <code>Week</code>?</p> <p><code>&quot;1W&quot;</code> offset isn't the same as <code>&quot;7D&quot;</code> because <code>&quot;1W&quot;</code> starting on a Monday in a two-week dataset where the last row is Tuesday w...
python|pandas
1
353,997
63,806,796
How to return elements from pandas.value_counts()
<p>Say I have the following code:</p> <pre><code>y = pd.DataFrame([3, 1, 2, 3, 4], columns=['TARGET']) y['TARGET'].value_counts() </code></pre> <p>Output:</p> <pre><code>3.0 2 4.0 1 2.0 1 1.0 1 Name: TARGET, dtype: int64 </code></pre> <p>How do I return the elements in the output above individually (ie. the...
<p>using <code>.iloc</code></p> <pre><code>import pandas as pd y = pd.DataFrame([3, 1, 2, 3, 4], columns=['TARGET']) print(y['TARGET'].value_counts().iloc[0]) # output 2 print(y['TARGET'].value_counts().iloc[1]) # output 1 print(y['TARGET'].value_counts().iloc[2]) # output 1 print(y['TARGET'].value_counts().iloc[3])...
python|pandas|series
1
353,998
63,741,027
Regression statistics for subsets of Pandas dataframe
<p>I have a dataframe consisting of multiple years of data with multiple environmental parameters as columns. The dataframe looks like this:</p> <pre><code>import pandas as pd import numpy as np from scipy import stats Parameters= ['Temperature','Rain', 'Pressure', 'Humidity'] nrows = 365 daterange = pd.date_range('1/...
<p>Here is a bit of code that I have used in the past. I used <code>sklearn.LinearModel</code> because I think its a bit easier to use, but you can change to scipy.stats if you like.</p> <p>This code uses <code>apply</code> and does the linear regression in the function <code>linear_model</code>.</p> <pre><code>import...
python|pandas|dataframe|regression
1
353,999
64,000,816
Can't read a csv file into pandas
<p>Hi I have a csv file that looks like this</p> <p><a href="https://i.stack.imgur.com/kBLWZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kBLWZ.png" alt="enter image description here" /></a></p> <p>I'm reading this into pandas with this</p> <pre><code>data1 = pd.read_csv(project+dataitem1+'.csv', ...
<p>The header count is less then the data column count. Also use None for the header parameter.</p> <p>Try this code:</p> <pre><code>ss = ''' Norman Hay plc,875412,Chemicals,2008-09-19 00:00:00.000,Original Instance,2008-03-31 00:00:00.000,2008,1,LTM,Ordinary Shares '''.strip() with open ('data.csv','w') as f: f.write...
pandas|dataframe|csv
0