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
361,900
53,029,118
Tensorflow tf.scatter_update does not update float value
<p>It seems like tf.scatter_update does not update the variable if the type of the variable is defined as float. Here's a code you can try:</p> <pre><code>import tensorflow as tf def cond(size, i): return tf.less(i,size) def body(size, i): b=2*7.5+c with tf.variable_scope("a", reuse=tf.AUTO_REUSE): ...
<p>Is your expected output this ?</p> <pre><code>[array([19., 19., 19., 19., 19., 19.], dtype=float32), 6] </code></pre> <p>These two patterns produce that.</p> <h3>Pattern 1</h3> <pre><code>import tensorflow as tf def cond(size, i): return tf.less(i,size) def body(size, i): b=2*7.5+c with tf.variabl...
python|tensorflow
0
361,901
53,322,764
pandas DataFrame isin and following row
<p>For a given DataFrame, sorted by <code>b</code> and index reset:</p> <pre><code>df = pd.DataFrame({'a': list('abcdef'), 'b': [0, 2, 7, 3, 9, 15]} ).sort_values('b').reset_index(drop=True) a b 0 a 0 1 b 2 2 d 3 3 c 7 4 e 9 5 f 15 </code></pre> <p>and a lis...
<p>You can combine the <code>isin</code> condition and the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html" rel="nofollow noreferrer"><code>shift</code></a> (next row) to create the boolean you needed:</p> <pre><code>df[df.a.isin(v).pipe(lambda x: x | x.shift())] # a b #0 ...
python|pandas
3
361,902
53,352,604
What is the right way to import data to tensorflow?
<p>I am new to Tensorflow and trying to make my own little project. I would like to import my CSV file as a dataset and then I would like to split it into training and testing sets and also to be able to make batches from my dataset.<br> My CSV file contains 3 columns of numbers so I managed to find these lines of code...
<p>Use a tool to split your data like <code>sklearn.model_selection.train_test_split</code>:</p> <pre><code>X_train, X_test, y_train, y_test = train_test_split( dataset[:2], dataset[2], test_size=0.33, random_state=42) </code></pre> <p>For instance if your dataset consists of two features columns and one output l...
python|tensorflow
1
361,903
53,303,902
Scrolling an array in python
<p>I'm currently writing a python script with pyserial and pyqtgraph that plots data coming in from an accelerometer via the serial port. I append this data to an int array and use it to update the plot. At the moment, my graph width is 500 (I'm only displaying the most recent 500 elements) and I "roll" or "scroll" by ...
<p>To have a O(1) update procedure, you can do it yourself with a double array buffer :</p> <pre><code>size=4 buffersize=2*size buffer=np.zeros(buffersize+1,int) # one more room for keep trace on beginning of buffer. sensor=iter(range(1,10**5)) # emulation def update(): i=buffer[buffersize] # to avoid global var...
python|numpy|pyqt5|pyserial|pyqtgraph
4
361,904
53,001,426
pandas MERGE giving KeyError
<p>I have 2 Dataframes <code>df_general</code> and <code>df_award</code> which share a column called <code>ProjectNumber</code>. I want to merge them.</p> <p>I tried dropping all the rows using dropna() and it did drop them- </p> <pre><code>df_award['ProjectNumber'].replace(' ', np.nan, inplace=True) df_award.dropna(...
<p>It appears you have almost everything right. The key needs to be in both the left and right side. It appears you aren't passing <code>ProjectNumber</code> on the <code>df_general</code> dataframe. Perhaps the following would work better:</p> <pre><code>df_general[['Agency', 'ProjectNumber']].merge(df_award[['Projec...
python-3.x|pandas|dataframe|data-science
4
361,905
53,090,781
what is the tensorflow equivalent for pytorch probability function: torch.bernoulli?
<p>In Pytorch, you can do following:</p> <pre><code>x = torch.bernoulli(my_data) </code></pre> <p>Any similar functionality in tensorflow? Can the input be 2-D tensor, such as (batch, len)?</p> <h1>I tried tensorflow.contrib.distributions.Bernoulli:</h1> <pre><code>import numpy as np tmp_x1 = np.random.rand(20,5) new_...
<p>It seems <a href="https://www.tensorflow.org/api_docs/python/tf/distributions/Bernoulli" rel="nofollow noreferrer"><code>tf.distributions.Bernoulli</code></a> does what you need. The input can be an N-D tensor, which includes a 2D tensor.</p> <p><strong>EDIT: example use</strong></p> <p>After your comment, I trie...
python|tensorflow|pytorch
0
361,906
53,234,770
Filtering pandas dataframe by day
<p>I have a pandas data frame with forex data by minutes, one year long (371635 rows):</p> <pre><code> O H L C 0 2017-01-02 02:00:00 1.05155 1.05197 1.05155 1.05190 2017-01-02 02:01:00 1.05209 1.05209 1.05177 1...
<h3>Avoid Python <code>datetime</code></h3> <p>First you should avoid combining Python <code>datetime</code> with Pandas operations. There are many Pandas / NumPy friendly methods to create <code>datetime</code> objects for comparison, e.g. <code>pd.Timestamp</code> and <code>pd.to_datetime</code>. Your performance is...
python|pandas|performance|datetime|pandas-groupby
9
361,907
53,133,733
Access to the Frequency attribute of a pd.TimeSeries
<p>How is it possible to access the frequency attribute of a pd.TimeSeries </p> <p>For example, here I would like to get "H":</p> <pre><code>rng = pd.date_range('1/1/2011', periods=72, freq='H') ts = pd.Series(np.random.randn(len(rng)), index=rng) ts.head() 2011-01-01 00:00:00 0.469112 2011-01-01 01:00:00 -0.28...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.freqstr.html" rel="nofollow noreferrer"><code>DatetimeIndex.freqstr</code></a>:</p> <pre><code>print (ts.index.freqstr) H </code></pre>
python|pandas|time-series|series
2
361,908
53,203,949
How to subtract time when there is a date change in pandas?
<p>I have following dataframe in pandas</p> <pre><code> start_date start_time end_time 2018-01-01 23:55:00 00:05:00 2018-01-02 00:05:00 00:10:00 2018-01-03 23:59:00 00:05:00 </code></pre> <p>I want to calculate the time difference. But, for ...
<p>Solution working with timedeltas - if difference are <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.days.html" rel="nofollow noreferrer"><code>days</code></a> equal <code>-1</code> then add one day:</p> <pre><code>df['start_time'] = pd.to_timedelta(df['start_time']) df['end_time'] =...
python|pandas
2
361,909
53,069,645
Pandas/Numpy group value changes and derivative value changes above/below 0
<p>I have a series of values (Pandas DF or Numpy Arr):</p> <pre><code>vals = [0,1,3,4,5,5,4,2,1,0,-1,-2,-3,-2,3,5,8,4,2,0,-1,-3,-8,-20,-10,-5,-2,-1,0,1,2,3,5,6,8,4,3] df = pd.DataFrame({'val': vals}) </code></pre> <p>I want to classify/group the values into 4 categories:</p> <ol> <li>Increasing above 0</li> <li>Decr...
<p><strong><em>Setup</em></strong></p> <pre><code>g1 = ['above_zero', 'below_zero', 'diff_above_zero', 'diff_below_zero'] </code></pre> <hr> <p>You can simply index all of your boolean columns, and use <code>shift</code>:</p> <pre><code>c = df.loc[:, g1] (c != c.shift().fillna(c)).any(1).cumsum() </code></pre> <p>...
python|pandas|numpy
2
361,910
53,316,561
Calculating the pearson coefficients in a keras model met with AttributeError: 'NoneType' object has no attribute '_inbound_nodes'
<p>I'm using pearson correlation coefficients as the input features of the MLP model, and meeting with problem when establishing the model.</p> <p>I've updated and run my code according to <strong>today</strong>'s favorable comment that wrapping the function inside a Lambda layer, whereas the same error still occurs. ...
<p>You must wrap your function inside a <a href="https://keras.io/layers/core/#lambda" rel="nofollow noreferrer"><code>Lambda</code></a> layer to let Keras be able to track it and augment its returned tensor(s) with necessary information. To do this, you need to modify the definition of your function as well, since it ...
python|tensorflow|machine-learning|keras|keras-layer
1
361,911
53,286,858
Difference between np.dot() and np.multiply
<p>I am converting my matlab funtion to python. I want to rewrite this simple functions in python</p> <pre><code>function [ H ] = update_H( X , W , H ) H = H.*((W'*X)./secu_plus(W'*W*H,eps)); end function [ W ] = update_W( X , W , H ) W = W.*((X*H')./secu_plus(W*(H*H'),eps)); end </code></pre> <p>Note:...
<p>In <em>Matlap</em>, .<em>operation</em> means element wise operation, for example if array1 = [ 1,2,3] and array3 [1,2,1], the <code>.*</code> will be [1,4,3] The equivalent of this in <em>Python numpy</em> is <code>np.multiply</code></p> <p><code>np.dot</code> is the dot product between two vectors, dot product m...
python|python-3.x|numpy
0
361,912
53,033,586
Pandas to_csv leads to extra lines
<p>The data frame has 906133 rows, such as:</p> <blockquote> <blockquote> <blockquote> <p>df.shape</p> </blockquote> </blockquote> </blockquote> <p>(906133, 24)</p> <p>And I tried to save it as a csv file:</p> <blockquote> <blockquote> <blockquote> <p>df.to_csv('df.csv',encoding='utf-8...
<p>I got to a similar problem, however I was constructing the csv from scratch (not importing).</p> <p>My blank lines disappeared after I used these parameters:</p> <pre><code>df.to_csv('df.csv', mode='w', encoding='utf-8', index=False, line_terminator='\n') </code></pre> <p>I blame the <strong>line_terminator</strong>...
pandas|dataframe
1
361,913
53,041,331
Tensorflow Object Detection Unusually large bounding boxes and wrong results
<p>I am building an object detector in TensorFlow to detect, motorbike riders with and without helmet, I have 1000 Images each for riders with helmet, withouthelmet and pedestrians(pu together -- 3000 IMAGES), My last checkpoint was 35267 steps, I have tested using a traffic video, but I see unusally large bounding bo...
<p>There is no need to wait till 50000 epocs you should get decent result in 35k or even in 10k. I would suggest </p> <ol> <li>go through you data-set again and check all the bounding boxes (data cleaning)</li> <li>Check your model with inference code for changes like batch normalization etc</li> <li>Add some more dat...
tensorflow|bounding-box|object-detection-api
0
361,914
53,023,436
How do I add the lat and long back into the response from Google's Timezone API?
<p>I am using Google's Timezone API to grab the timezone for specific lat and longs I pass to is. I am able to do this successfully but I want to add the corresponding lat and longs back into the data. How can this be done? Here is the code I am using:</p> <pre><code>#get timezone result = [] google_key = '___________...
<p>If <code>latitude</code> and <code>longitude</code> are python lists, pandas does the right thing when you try to turn them into new columns in your DataFrame:</p> <pre><code>tz_df['lat'] = latitude tz_df['lon'] = longitude </code></pre>
python|pandas
1
361,915
53,335,691
How to merge several rows into one row based on a column with specific value in Pandas
<p>I have a DataFrame like this way:</p> <pre><code>item_id revenue month year 1 10.0 01 2014 1 5.0 02 2013 1 6.0 04 2013 1 7.0 03 2013 2 2.0 01 2013 2 3.0 03 2013 3 5.0 ...
<p>You can slice first, <em>then</em> <code>groupby</code> and <code>reindex</code> to include <code>0</code> values.</p> <pre><code>month_start, month_end = 1, 3 year = 2013 res = df.loc[df['month'].between(month_start, month_end) &amp; df['year'].eq(year)]\ .groupby('item_id')['revenue'].sum()\ .rei...
python|pandas|dataframe|pandas-groupby
3
361,916
52,967,376
Conditionally copy certain row values to other rows
<p>I have a dataframe that has the following structure:</p> <pre><code> code name age char 101 NaN NaN ts 101 NaN NaN tt 101 Carl 19 tt 102 NaN NaN ts 102 NaN NaN tt 102 NaN NaN tt 103 NaN NaN ts 103 Aoi 23 tt 103 NaN NaN tt </code></pre> <p>I would l...
<p>In one line:</p> <pre><code>result = df.copy() result.update(df.groupby(['code']).bfill()[df['char']=='ts']) result code name age char 0 101.0 Carl 19.0 ts 1 101.0 NaN NaN tt 2 101.0 Carl 19.0 tt 3 102.0 NaN NaN ts 4 102.0 NaN NaN tt 5 102.0 NaN NaN tt 6 103.0 Aoi ...
python|pandas
1
361,917
53,311,140
How to calculate mean of specific rows based on value and column in numpy matrix?
<p>I'm loading in a file to a pandas dataframe that looks something like:</p> <pre><code>A 3 2 4 1 B 1 3 5 2 C 2 8 9 1 A 4 1 2 3 </code></pre> <p>I converted the dataframe to a numpy matrix because I'd like to store each mean and variance in separate 26 x 4 numpy matric...
<p>This should do it but you’ll need to specify column headers and keep your data in a dataframe.</p> <pre><code> df[column_name].iloc[row_index].mean(axis=0) </code></pre>
python|numpy
0
361,918
53,036,260
add descriptor row over pandas df header
<p>I currently have a DataFrame, <code>df</code>, in the format:</p> <pre><code>name age color John 13 purple Alisa 15 blue </code></pre> <p>making it such that I can access specific columns of this DataFrame using things like <code>df['name']</code>, <code>df['age']</code>, etc.</p> <p>I'd like to add a d...
<p>If you absolutely need this functionality, then you can put the original column name as the top level of the MultiIndex like this:</p> <pre><code>title = "This is a customer's {}" cols = [(name, title.format(name)) for name in df.columns] df.columns = pd.MultiIndex.from_tuples(cols) </code></pre> <p><a href="https...
python|pandas|dataframe
1
361,919
53,279,970
Unicode error using to_csv DESPITE specifying encoding = 'utf-8'
<p>I'm trying to write a dataframe to a csv file like this:</p> <p><code>df.to_csv(path, index = True, header = True)</code></p> <p>But I keep getting this error: </p> <p><strong>SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape</strong></p> <p>I chec...
<p>Should try with absolute path.</p> <p><code>df.to_csv("/home/anand/file.csv", index = True, header = True, encoding = 'utf-8')</code></p> <p>However worth to look at the <a href="https://docs.python.org/2.0/ref/strings.html" rel="nofollow noreferrer">String literals</a> </p> <blockquote> <p>String literals can ...
python|pandas|csv|dataframe|export-to-csv
0
361,920
52,964,807
Padding in Pytorch
<p>In PyTorch tensor, I would like to obtain the output from the input as follows:</p> <p><img src="https://i.stack.imgur.com/yiuho.png" alt="enter image description here"></p> <p>How can I achieve this padding in Pytroch?</p>
<p>One way of doing this is</p> <pre><code>def my_odd_padding(list_of_2d_tensors, pad_value): # get the sizes of the matrices hs = [t_.shape[0] for t_ in list_of_2d_tensors] ws = [t_.shape[1] for t_ in list_of_2d_tensors] # allocate space for output result = torch.zeros(sum(hs), sum(ws)) result.add_(pad_va...
python|pytorch
1
361,921
53,056,395
Extract data containing a specific character with Pandas
<p>I would like to extract data containing a specific character string in another column. </p> <p>For example, The target extracted is like "another column string + 3 digits" character.<br> It has error. I would like to get TARGET row.</p> <pre><code>df = pd.DataFrame({'col1':['xxxx', 'yyyy', 'zzzz'],'col2':['xxxx123...
<p>Two pattern matches, and filter the dataframe</p> <pre><code>cond1 = df.col2.str.extract('([A-Za-z]+)\d', expand = False).eq(df.col1) cond2 = df.col2.str.extract('[A-Za-z](\d{3})$', expand = False) df[(cond1) &amp; (cond2)] col1 col2 0 xxxx xxxx123@gmail.com </code></pre>
python|string|python-3.x|pandas|dataframe
3
361,922
53,244,339
text delimiter shifting values in dataframe
<p>I have a dataframe like the data_df example below, that I create by reading in data from a csv with the code below. the problem I’m running in to is that some of the values in some of the columns are getting shifted to the right. For example the second record values are shifted one column to the right starting wit...
<p>The <code>\</code> is an escape character. Since I take it the values in your file are not enclosed in quotes, the <code>\</code> is placed before the comma so that you treat <code>PEREZ, BRYAN</code> as one value. </p> <p>Try passing <code>\\</code> to the <code>escapechar</code> option of <code>pd.read_csv</code>...
python-3.x|pandas|csv
2
361,923
53,126,939
error loading faster_rcnn models into Opencv
<p>I followed exactly every step from TensorFlow Object Detection API and trained the faster_rcnn_resnet50 model. Then I referenced link:Wiki to generate the pbtxt file for cv2 read net. </p> <p>When I ran the model using opencv, it gave no error most of the time and this error sometimes:</p> <blockquote> <p>cv2.er...
<p>Got answer from @dkurt at <a href="https://github.com/opencv/opencv/issues/13050" rel="nofollow noreferrer">https://github.com/opencv/opencv/issues/13050</a> </p> <p>Wish that can help if you are experiencing the same problem </p>
opencv|tensorflow
0
361,924
53,212,559
Standard Deviation Pooling with Keras
<p>I am trying to implement a standard deviation pooling layer using keras. The idea is similar to implement a layer with a functionality similar to <code>AveragePooling1D</code>, but calculating standard deviation instead.</p> <p>My first course of action was to try and implement this as a Lambda layer. It should tak...
<p>After fiddling a bit more with the code and reading about how keras interacts with tensorflow (in many different places, including the source code for tensorflow and keras) I figured out what was wrong.</p> <p>First of all, here's a minimal working example of what I wanted to do:</p> <pre><code>import tensorflow...
python|python-2.7|tensorflow|keras
2
361,925
53,246,443
Store JSON responses in a way that allows reading them fast into a single dataframe
<p>I got 800 JSON responses that I would like to store somehow. The responses all not uniform - some have more keys than others.</p> <p>Example of a shorter response:</p> <pre><code>{"resource_state":3,"athlete":{"id":3255732,"resource_state":1},"name":"Morning Ride","distance":38070.1,"moving_time":5670,"elapsed_tim...
<p>A fast solution is to read all files into a dataframe just once and then use pickle to save that dataframe. </p> <p>To save:</p> <pre><code>df.to_pickle('filename.pkl') </code></pre> <p>To read:</p> <pre><code>df.read_pickle('filename.pkl') </code></pre>
python|pandas|dataframe
0
361,926
53,131,413
Why doesnt pandas create an excel file?
<p>Im trying to create an excel file with pandas for a database I have generated.</p> <p>I have tried both:</p> <pre><code>import pandas as pd # write database to excel df = pd.DataFrame(database) # Create a Pandas Excel writer using XlsxWriter as the engine. writer = pd.ExcelWriter('fifa19.xlsx', engine='xlsxwrite...
<p>From the pandas document <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html" rel="nofollow noreferrer">Notes</a> itself:</p> <p>If passing an existing <code>ExcelWriter</code> object, then the sheet will be added to the existing workbook. This can be used to save different...
python|excel|pandas
6
361,927
53,104,756
Numpy custom Cumsum function with upper/lower limits?
<p>I have a numpy/pandas list of values:</p> <pre><code>a = np.random.randint(-100, 100, 10000) b = a/100 </code></pre> <p>I want to apply a custom cumsum function, but I haven't found a way to do it without loops. The custom function sets an upper limit of 1 and lower limit of -1 for the cumsum values, if the "add" ...
<p>Loops aren't necessarily undesirable. If performance is an issue, consider <code>numba</code>. There's a ~330x improvement without materially changing your logic:</p> <pre><code>from numba import njit np.random.seed(0) a = np.random.randint(-100, 100, 10000) b = a/100 @njit def cumsum_with_limits_nb(values): ...
python|algorithm|pandas|performance|numpy
5
361,928
65,764,472
Adding a value to an existing row/column in pandas
<p>I have a simple dataframe and I want to dynamically do arithmetic at a given row/col</p> <p>If the dataframe look like this:</p> <pre><code>Bin Count A 21 B 18 C 22 D 24 </code></pre> <p>I want to add 6 to the &quot;Count&quot; for &quot;Bin D&quot; making it equal to 30. Is there a way to...
<pre><code>df.loc[df.Bins=='D', 'Count'] += 6 </code></pre>
pandas|dataframe|math
1
361,929
65,582,909
Splitting a a string into a list of items in pandas dataframe | Python | Pandas |
<p>I have a panda dataframe where column values like:</p> <pre><code>0 ['note' 'pen'] 1 ['paper' 'pencil'] 2 ['note' 'pen'] </code></pre> <p>I want to make the values in column, that contain a list of all different items that is get after splitting each values.</p> <p>Expected Output:</p> <pre><code>0 [note,...
<p>Are you just trying to make <a href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.tolist.html" rel="nofollow noreferrer">numpy arrays into lists</a>?</p> <pre><code>df_['products'].apply(lambda x: x.to_list()) </code></pre>
python|pandas
0
361,930
65,892,520
Pandas Dictionary: How to return a key by matching an input value to multiple values assinged to a single key
<p>I have a dicticionary where each key has multiple values.I'm trying to obtain the key from a dictionary by matching an input value to the values for a certain key</p> <pre><code>areas={ '1':['a', 'b'], '2':['c', 'd', 'e'], '3':['f' 'g', 'h', 'i','j', 'k' ], '4': ['l', 'm','n']...
<p>You've almost done it. Since you need to look inside each key's values, you must access <code>areas[key]</code> for each <code>key</code> inside the list comprehension. Using <code>areas_dict.values()</code> doesn't work because it returns all the values from that dictionary at once.</p> <p>It must be something like...
pandas|dictionary
1
361,931
65,909,856
Python Pandas - Slice DataFrame based on Another Table's Values to Match to Column Name
<p>I have two dataframes, df_stats and df_ratings.</p> <p>df_stats looks like this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>Fruit</th> <th>Rating_Threshold_Low</th> <th>Rating_Threshold_High</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Apple</td> <td>4</td> <td>7</td> </...
<p>You could do something like this</p> <pre><code>sums = [] for i in range(len(df_stats)): min_v, max_v = df_stats[&quot;Rating_Threshold_Low&quot;].values()[i], df_stats[&quot;Rating_Threshold_High&quot;].values()[i] values = [] for z in range(min_v, max_v+1): x = df_ratings[str(z)][i] values.a...
python|pandas|dataframe
0
361,932
65,527,582
Validation Loss and Validation Accuracy do not change during training
<p>I wrote a face classifier program with <code>Tensorflow</code>. In this project, first I just had 2 faces so I used <code>binary_crossentropy</code> as loss function. When I decided to add more faces I switched from <code>binary_crossentropy</code> to <code>categorical_crossentropy</code>.</p> <p><strong>My code:</s...
<p><em>The answer would've been more precise if more information about the data were given.</em></p> <p>For starters, you've used categorical cross-entropy as your loss function and Sigmoid as activation of the last layer, which is kind of contradictory (<strong>sigmoid means you're classifying among 2 classes and cate...
python|tensorflow|machine-learning|keras|deep-learning
1
361,933
65,667,515
Issue with training an Image Classification Model with Tensorflow Lite Model Maker
<p>So I'm new at ML and I have a task where I need to be able to identify a specific object with my phone's camera and trigger an action at that moment. I got to the point where I'm able to train the model, hook it up with a sample Android app Google provides and run it. All of this works perfectly with a few datasets ...
<p>You would have to train the model with an existing dataset + your new set of images labeled as &quot;speaker&quot; (for the sake of this example). If you train a model with only 1 class, it will learn to predict &quot;how close is this object to a speaker?&quot; for every object it finds instead of &quot;is this a s...
python|tensorflow|machine-learning|tensorflow-lite|image-classification
0
361,934
65,883,905
Transforming A Dataframe Using Numpy is Giving Wrong Values
<p>I have a dataframe which looks like:</p> <pre><code> Values Class 0 0.018342 2 1 -0.461340 2 2 -0.461340 2 3 1.787317 2 4 1.896320 2 5 0.987067 2 6 1.923396 2 7 1.923396 2 8 1.640110 2 9 1.952998 2 10 3.961000 2 11 1.954717 2 12 1.954717 2 13 1.436860 ...
<p>Try this and see if it works for you :</p> <pre><code>array = df.to_numpy() left, right = array[:, 0], array[:, -1] data = pd.DataFrame( np.vstack(np.split(np.reshape(left, (-1, 6), order=&quot;F&quot;), 2, 1)), columns=[&quot;var1&quot;, &quot;var2&quot;, &quot;var3&quot;], ) right = np.vstack(np.split(n...
python-3.x|pandas|dataframe|numpy|reshape
0
361,935
65,623,906
How to vectorize indexing and computation when indexed tensors are different dimensions?
<p>I'm trying to vectorize the following for-loop in Pytorch. I'd be happy with just vectorizing the inner for-loop, but doing the whole batch would also be awesome.</p> <pre><code># B: the batch size # N: the number of training examples # dim: the dimension of each feature vector # K: the number of discrete labels. e...
<p>It turns out it actually <em>is</em> possible to vectorize across ragged arrays. I'll use numpy, but code should be directly translatable to torch. The key technique is to:</p> <ol> <li>Sort by ragged array membership</li> <li>Perform an accumulation</li> <li>Find boundary indices, compute adjacent differences</li> ...
python|pytorch|vectorization
2
361,936
65,757,115
PyTorch out of GPU memory in test loop
<p>For the following training program, training and validation are all ok. Once reach to Test method, I have <code>CUDA out of memory</code>. What should I change so that I have enough memory to test as well.</p> <pre><code>import torch from torchvision import datasets, transforms import torch.nn.functional as f class ...
<p>You should call <code>.item()</code> on your <code>loss</code> when appending it to the list of losses:</p> <pre><code>loss = self.criterion(output, target) test_loss.append(loss.item()) </code></pre> <p>This avoids accumulating tensors in a list which are still attached to the computational graph. I would say the s...
pytorch|pytorch-dataloader
1
361,937
65,544,598
Pandas groupby mean unstacked data and then ploting them as horizontal stacked barchart
<p>I have a dataset like this</p> <pre><code>Category Date Score_1 Score_2 Level A 1/1/2020 130 145 Excellent A 1/5/2020 145 148 Excellent C 1/2/2020 107 109 Need-Improvement B 1/1/2020 125 128 Good C 1/7/2020 ...
<p>You can aggregate the mean and the level frequency separately and then combine them:</p> <pre class="lang-py prettyprint-override"><code>mean_score = df.groupby('Category').agg(Mean=('Score_1', 'mean')) level_freq = ( df.groupby(['Category']) ['Level'].value_counts(normalize=True) .mul(100) ...
python|pandas|matplotlib
2
361,938
65,569,640
Remove entries of matrix where both row and column are all zeros
<p>For spectral clustering I am building a small similarity matrix like this:</p> <pre><code>[0. 0. 0. 0. 0. ] [0. 0. 0. 0. 0. ] [0. 0. 0. 0.06750058 0. ] [0. 0. 0.06750058 0. 0. ]...
<p><strong>EDIT:</strong> I just realized that the below code only works, if all entries of your array are non-negative. Better use <a href="https://numpy.org/doc/stable/reference/generated/numpy.nonzero.html" rel="nofollow noreferrer"><code>np.nonzero</code></a> then (cf. <a href="https://docs.python.org/3/tutorial/co...
python|numpy|scikit-learn
1
361,939
65,766,669
Counting amount of occurrences within a certain frame in timestamps on Pandas
<p>I have a file (txt) containing fake data with the following 3 columns:</p> <pre><code>user_13 visit_19 1330760979 user_14 visit_20 1330732782 user_14 visit_21 1330769600 user_14 visit_22 1330783341 user_14 visit_23 1330796012 user_14 visit_24 1330797842 </code></pre> <p>Using Pandas, how can I...
<p>The code I've posted below achieves what you're after. I've also uploaded the full Jupyter Notebook <a href="https://github.com/jdsalaro/snippets/blob/main/pandas/stackoverflow-65766669-counting-amount-of-occurrences-within-a-certain-frame-in-timestamps-on-pandas.ipynb" rel="nofollow noreferrer">here</a>.</p> <pre><...
python|pandas
1
361,940
65,811,195
Pandas: Replace missing dataframe values / conditional calculation: fillna
<p>I want to calculate a pandas dataframe, but some rows contain missing values. For those missing values, i want to use a diffent algorithm. Lets say:</p> <ul> <li>If column B contains a value, then substract A from B</li> <li>If column B does <strong>not</strong> contain a value, then subtract A from C</li> </ul> <pr...
<p>Finally, I stumbled over <code>.fillna</code>:</p> <pre><code>df['calc'] = df['calc'].fillna( df['c']-df['a'] ) </code></pre> <p>gets the job done! Can anyone explain what is wrong with above two approaches...?</p>
python|pandas|dataframe|nan
5
361,941
65,637,465
create a ones tensor according to another lengths tensor
<p>I have one tensor of the size of <code>[batch_size,1]</code> where each number for sample indicates an integer that is smaller than 5000. I'd like to create a new tensor of the size of <code>[batch_size,5000]</code> where the first numbers for each sample are ones, according to the first tensor, and the rest are zer...
<p>This is quite tricky since you want to fill values based on indices and not on the value itself...</p> <p>Yet you can still manage it, but you have to get creative. We need some way for indices to be reflected on the values themselves. We will keep <code>batch_size=2</code> and a vector size of <em>10</em>:</p> <pre...
python|pytorch|tensor
0
361,942
65,864,251
Pandas: create category column based on multiple columns
<p>Which would be the most efficient way to create a category column based on other columns in the row, as quickly as possible?</p> <p>input:</p> <pre><code> col1 col2 col3 col4 0 0 0 -10 1 1 1 100 0 -1 2 0 0 0 1 3 0 0 -10 1 4 1 100 0 -1 </code>...
<p>The fastest method is probably using numpy <a href="https://numpy.org/doc/stable/reference/generated/numpy.unique.html" rel="nofollow noreferrer"><code>unique</code></a> (if all columns are numeric):</p> <pre><code>_, new_col = np.unique(df.to_numpy(), axis=0, return_inverse=True) df['new_col'] = new_col </code></pr...
python|pandas|indexing
2
361,943
65,861,404
python parse string from multi valued column
<p>I'm reading an excel file into a dataframe where one of its columns has 1 to many values, delimited by a space. I need to search the column for a string of text, and if found return the complete value between its delimiters(not the entire cell value).</p> <p>Input would look something like this –</p> <pre><code>impo...
<p>The problem with using <code>replace()</code> is that it will only apply to what matches, and not to the items you want to skip/remove from the results. Instead, use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.findall.html#pandas.Series.str.findall" rel="nofollow noreferrer"...
python|pandas|parsing
2
361,944
65,771,633
Drop duplicated rows based on multiple columns if other column(s) is NaNs in Pandas
<p>Given a test dataset as follows:</p> <pre><code> id city district quantity price 0 1 bj hd 12.0 23.0 1 2 bj cy 23.0 45.0 2 3 bj hd NaN NaN 3 4 bj cy NaN NaN 4 5 sh hp 12.0 NaN 5 6 sh hp NaN NaN 6 7 sh...
<p>You can use:</p> <pre><code>m1 = df['quantity'].notna() m2 = ~df[['city', 'district']].duplicated() m3 = ~df[['city', 'district']].duplicated(keep=False) df1 = df[(m1 &amp; m2) | (~m1 &amp; m3)] print(df1) id city district quantity price 0 1 bj hd 12.0 23.0 1 2 bj cy 23.0 45.0...
python|python-3.x|pandas|dataframe
1
361,945
65,521,840
Pytorch Loss Function for making embeddings similar
<p>I am working on an embedding model, where there is a BERT model, which takes in text inputs and output a multidimensional vector. The goal of the model is to find similar embeddings (high cosine similarity) for texts which are similar and different embeddings (low cosine similarity) for texts that are dissimilar.</p...
<p>To calculate the cosine similarity between two vectors you would have used <a href="https://pytorch.org/docs/stable/generated/torch.nn.CosineSimilarity.html" rel="nofollow noreferrer"><code>nn.CosineSimilarity</code></a>. However, I don't think this allows you to get the pair-similarity from a set of <code>n</code> ...
pytorch|tensor|embedding|bert-language-model|loss
1
361,946
65,720,690
Super simple Keras Sequence doesn't work when serving simple array data
<p>Below is a simple XOR solver, with and without using a Sequence for training data. Just using regular arrays works, but when using a Sequence to serve the same data, it doesn't work. I don't understand the error message, which is in the comment on the last line.</p> <pre><code>from tensorflow.keras.models import Seq...
<p>Many things happen in <code>model.fit</code>, including Keras creating a dataset, and adding a batch dimension. Since you created a new kind of dataset I'm afraid that's something you'll have to do yourself. It will work if you change the <code>return</code> statement to this:</p> <pre><code>return X[index][None, .....
python|tensorflow|keras|deep-learning
0
361,947
65,585,701
NumPy array row wise and column wise slicing syntax
<p>Why does NumPy allow <code>array[row_index, ]</code> but <code>array[, col_index]</code> is not valid and gives Syntax Error. e.g. if I want to traverse the array row wise <code>NumPy.array[row_index, :]</code> and <code>NumPy.array[row_index, ]</code> both give the same answer where as only <code>NumPy.array[:, col...
<p><code>arr[idx,]</code> is actually short for <code>arr[(idx,)]</code>, passing a tuple to the <code>__getitem__</code> method. In python a comma creates a tuple (in most circumstances). <code>(1)</code> is just <code>1</code>, <code>(1,)</code> is a one element tuple, as is <code>1,</code>.</p> <p><code>arr[,idx]<...
python|arrays|numpy
2
361,948
65,769,014
Iteratively combine text in first column with existing text in other columns
<p>I am in the process of creating a python script that extracts data from a poorly designed output file (which I can't change) from a piece of equipment within our research lab. I would like to include a way to iteratively combine the text in the first column of a dataframe (example below) with each other column in th...
<ul> <li>Use <code>.apply</code> to prepend the <code>'Filename'</code> string to the other columns.</li> <li>Of the current answers, the solution from <a href="https://stackoverflow.com/users/8973620/mykola-zotko">Mykola Zotko</a> is the fastest solution, tested against a 3 column dataframe with 100k rows.</li> <li>If...
python|pandas|merge|concatenation
4
361,949
65,656,255
Tensorflow unable to reshape a image
<p>Hi i am unable to use an url to be decoded and classified using tensorflow and mobile net i get the url in discord.js of an image and fetch it with node fetch and then buffer it and then decode it can anyone tell me what resolution does the error mean so i can resize it I have this code</p> <pre><code>const fetch = ...
<p>Use jimp to resize it to 720p and feed that to tfjs</p>
javascript|node.js|tensorflow|discord.js
1
361,950
65,810,887
decorrelation of variables and PCA
<p>I need to run regression analysis with respect to two different scalar predictors, say <code>A</code> and <code>B</code>, stored in the array <code>values</code>. These two predictors are however highly correlated with one another, so I was told to first decorrelate them through PCA. I am most definitely not an expe...
<p>There are a couple of issues:</p> <ul> <li><code>Bz = StandardScaler().fit_transform(A)</code> should be <code>Bz = StandardScaler().fit_transform(B)</code></li> <li><code>pcaA = model.fit_transform(Az)</code>: you are transforming one predictor only.</li> </ul> <p>If you do the following:</p> <pre><code>from sklear...
python|pandas|numpy|correlation|pca
1
361,951
65,497,801
How do I enable grpc on port 443 in nginx without breaking http on port 80 in kubernetes?
<p>I am using Nginx on Kubernetes 1.19 (trying both docker desktop and GKE) and am trying to expose gRPC services. I have installed Nginx with the following command and confirm I can expose REST services on port 80 and gRPC services with proper configuration on port 443.</p> <pre><code>kubectl apply -f https://raw.gith...
<p>You can try adding multipke ingress on the same host, one with tls and another without tls.</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: networking.k8s.io/v1beta1 kind: Ingress metadata: annotations: allowed-values: CN=client kubernetes.io/ingress.class: &quot;nginx&quot; nginx.ing...
nginx|grpc|kubernetes-ingress|tensorflow-serving|nginx-ingress
2
361,952
65,671,031
how to replace nans by numbers in a multidimensional array in Numba?
<p>In plain python, replacing nans by numbers in-place in a numpy array is trivial. However, the following fails in when doing the same in Numba</p> <pre><code>@jit(nopython=True) def dostuff(): x = np.array([[1,np.nan,3]]); np.nan_to_num(x,copy=False); dostuff() </code></pre> <p>How can I replace nans by zeros...
<blockquote> <p>For one-dimensional one can do x[np.isnan(x)]=0 but for higher dimensions this fails as well.</p> </blockquote> <p>There is the clue :)</p> <pre><code>import numpy as np from numba import jit @jit(nopython=True) def dostuff(x): shape = x.shape x = x.ravel() x[np.isnan(x)] = 0 x = x.resh...
numpy|nan|numba
3
361,953
65,759,770
Intuition behind categorical cross entropy
<p>I'm trying to make categorical cross entropy loss function to better understand intuition behind it. So far my implementation looks like this:</p> <pre class="lang-py prettyprint-override"><code># Observations y_true = np.array([[0, 1, 0], [0, 0, 1]]) y_pred = np.array([[0.05, 0.95, 0.05], [0.1, 0.8, 0.1]]) # Loss ...
<p>Regarding <code>y_pred</code> being 0 or 1, digging into the Keras backend source code for both <a href="https://github.com/keras-team/keras/blob/985521ee7050df39f9c06f53b54e17927bd1e6ea/keras/backend/numpy_backend.py#L325" rel="nofollow noreferrer"><code>binary_crossentropy</code></a> and <a href="https://github.co...
python|numpy|machine-learning|cross-entropy
1
361,954
65,665,195
How can I find the missing index using python pandas?
<p>Example</p> <pre><code>Order_ID Name 1 Man 2 Boss 5 Don 7 Lil 9 Dom 10 Bob </code></pre> <p>Want to get an output as:</p> <pre><code>3 4 6 8 are the missing Order_ID </code></pre>
<p>Try using a <code>list</code> comprehension with <code>range</code>:</p> <pre><code>print([i for i in range(1, 10) if i not in df['Order_ID']]) </code></pre> <p>Output:</p> <pre><code>[3, 4, 6, 8] </code></pre>
python|pandas|dataframe
2
361,955
65,766,310
if condition resulting in The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
<p>I am using if condition in python to perform a calculation but I am getting The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). error</p> <p>Can someone please help me in understanding how to perform actions on a dataframe based on <strong>if condition</strong> on other col...
<p>The message if self-explanatory. Since <code>simulated_hour['Weeknnd']</code> <strong>is not a single value</strong>, the term <code>simulated_hour['Weeknnd'] == 'Weekday'</code> might be true for some values and false for others. So, use <code>(...).any()</code> or <code>(...).all()</code> depending on whether you ...
python|pandas|dataframe|if-statement
2
361,956
65,709,604
Compare pandas dataframe columns to sql table dataframe columns
<p>I am working on creating an application that will load up a CSV into one dataframe and a SQL lookup table in another.</p> <p>The first frame has columns: col1, col2, ..., coln.</p> <p>The second frame is a lookup table containing just col1 and col2.</p> <p>The lookup table looks like</p> <div class="s-table-containe...
<p>Found it thanks to <a href="https://stackoverflow.com/questions/53645882/pandas-merging-101">this post</a></p> <p>The correct syntax to capture the fallout records is:</p> <pre><code>frame = df1.merge(df2, how='left', indicator=True, left_on=cols, right_on=cols).query('_merge == &quot;left_only&quot;').drop('_merge'...
python|sql|pandas
0
361,957
65,868,684
Is it possible to create a variable and expect the if statement to be about a variable within the variable?
<p>Sorry, my question is worded weirdly, I know. I'm working on a code for the trapezoidal rule. My function is <code>CTR(N,a,b,f)</code>. At one point I have to find N such that the value of another function is 4. So my code looks like this</p> <pre><code>for N in range (1,2000): if ((CTR(2*N,0,np.sqrt(np.pi/2),fu...
<h3>Issue</h3> <p>When defining <code>Th1</code>, <code>Th2</code>, and <code>Th3</code>, their expressions are evaluated and their value is known. Changing <code>N</code> won't anything about it, since they've already been evaluated with a value of <code>N</code> (in your second code you were indeed <em>supposed</em> ...
python|numpy|if-statement|variables|math
0
361,958
65,823,805
Create a date column for dataframe
<p>I have a dataframe of numeric sequence as show below:</p> <pre><code> power 0 0.434083 1 0.225000 2 1.202458 3 0.672167 4 0.634708 </code></pre> <p>I want to create a date column and make it the index - transform the sequence data into time-series data.</p> <p>I tried the following piece of code:</p> <pre><cod...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> here with <code>origin</code> and <code>unit</code> parameters:</p> <pre><code>import datetime todays_date = datetime.datetime.now() df.index = pd.to_dateti...
python|pandas|time-series
2
361,959
65,667,196
tensor_scatter_nd_update ValueError: Shapes must be equal rank, but are 0 and 1
<p>I've always been able to use <code>tf.tensor_scatter_nd_update</code> without any problems to write into tensors, but I can't manage to figure our why it's not working with some specific tensors.</p> <p>As a simple example, say I want to set certain values in <code>input=[[0 0 0]]</code> to <code>update=[[1 2 3]]</c...
<p>I figured it out.</p> <p>Part of the problem is indeed that <code>tf.where()</code> returns a 2-D tensor, but this came into play because I was using it to also generate the <code>updates</code> vector:</p> <pre><code>input=input=tf.tensor_scatter_nd_update(input,tf.where(mask),tf.where(something_else)) </code></pre...
python|tensorflow
-1
361,960
65,555,617
Python using pd.cut() and np.select( ) condition list based on 80 interval conditions
<pre><code>import pandas as pd data = pd.DataFrame({'ratio' : [0.25,0.20,0.45,0.10], 'range': ['1-25','26-50','51-75','76-100']}) degree = pd.DataFrame({'degree':[1,2,5,10,15,13,25,24,26,27,35,40,44,50,73, 80]}) </code></pre> <p>I need to add a new column, based on the interval conditions listed as the range....
<p>I would use merge_asof</p> <ol> <li>separate on the dash</li> <li>change value type to integer</li> <li>make sure columns are sorted</li> <li>use merge_asof</li> </ol> <pre><code> import pandas as pd data = pd.DataFrame ({'ratio' : [0.25,0.20,0.45,0.10], 'range': ['1-25','26-50','51-75','76-100']}) degree =...
python|pandas
0
361,961
65,529,872
Defining a Keras Custom Layer that adds a random value to a flatten layer output
<p>How to define a Keras Custom Layer to add a random value to the output of a Flatten layer (of a CNN) of size (None, 100)?</p>
<p>TL;DR:</p> <pre class="lang-py prettyprint-override"><code>class Noise(keras.layers.Layer): def __init__(self, mean=0, stddev=1.0, *args, **kwargs): super(Noise, self).__init__(*args, **kwargs) self.mean = mean self.stddev = stddev def call(self, inputs, training=False ...
python|tensorflow|keras|keras-layer
3
361,962
65,523,362
What is the actual use of num_words parameter in keras Tokenizer? How much overall does it affect the accuracy of my model
<p>In the given line of code <code>tokenizer=Tokenizer(num_words=, oov_token= '&lt;OOV&gt;')</code>, what does the num_words parameter actually do and what to take into consideration before determining the value to assign to it. What will be the effect of assigning a very high value to it and a very low one.</p>
<p>It is basically the size of vocabulary you want to have it in your model based on the data you have. Below simple example will explain you in detail.</p> <p><strong>Without num_words:</strong></p> <pre><code>import tensorflow as tf from tensorflow.keras.preprocessing.text import Tokenizer tokenizer = Tokenizer(oov_...
tensorflow|keras|deep-learning|nlp|nltk
0
361,963
65,548,368
Getting a dictionary key error while run a caffe model with python codes
<p>I've trained a caffe model via nvidia's digits. Now I'm trying to initialize my model with a python program. I've tried some samples but I'm stuck on a dictionary key error, which tells me there is no 'prob' key. I'm new to running a deep model. I modified &quot;dersmon&quot;s prediction.py codes on github: <a href=...
<blockquote> <p>I'm not familiar enough with caffe to help, but you can start by checking the dictionary's values using out.items(). I don't know what the expected data for out is, but since you do, you may be able to get a better understanding of your problem using that knowledge.</p> </blockquote> <p>Thanks to Octave...
python|numpy|deep-learning|caffe
0
361,964
65,552,509
Numpy: Size of a 2D array matrix?
<p>How do my 2 statements bellow differ in internal mechanism, while they are however giving the same output?</p> <pre class="lang-py prettyprint-override"><code>x = np.array([[**1, 2, 3, 6, 7, 8**], [**4, 5, 6, 8, 9, 5**]]) np.size(x) x.size </code></pre> <p>Both are correct outputs as the size of the array is 12.<...
<p>Internally <code>np.size(x)</code> calls <code>x.size</code> when axis is not specified sp in this case the result is the same.</p> <pre><code>if axis is None: try: return a.size except AttributeError: return asarray(a).size </code></pre> <p>However, if you specify the <code>axis</code>, then...
python-3.x|numpy-ndarray
0
361,965
65,856,307
Count moving average in circle 360 degrees
<p>This is my data</p> <pre><code>degree, value 0.0,0.42105263157894735 1.0,0.47368421052631576 2.0,0.47368421052631576 3.0,0.47368421052631576 4.0,0.5 5.0,0.5 6.0,0.5 7.0,0.47368421052631576 8.0,0.47368421052631576 9.0,0.47368421052631576 10.0,0.39473684210526316 .............. 350.0,0.5263157894736842 351.0,0.552631...
<p>You can prepend the last <code>9</code> values to the dataframe before taking the <code>rolling</code> <code>mean</code> so that <code>0</code> get's the mean value of <code>351-0</code>, <code>1</code> gets the mean value of <code>352-1</code> and so on:</p> <pre><code>df1 = df[-9:].append(df) df['smoothed'] = df1[...
python|pandas
3
361,966
65,721,103
How does calculating the Loss work with multiple Outputs in Regression with a NN?
<p>I set up a NN with 10 Output values/nodes. Some of them are coordinates, angles and distances. After lots of training my train and test loss gets very good. (~0.05) But after testing the values visually the results arent that good. (some are, but not all) My questions are:</p> <ol> <li>Do i need a loss function that...
<p>Updating the weights is not depends on the sum of the predictions of outputs, it depends on the sum of the gradient of all 10 loss functions.</p> <p>Even if your training and validation error seems good while training, there may still a high error for your unscaled data. I don't know how you measured the test error...
python|tensorflow|neural-network|regression|loss
0
361,967
65,789,681
Best way to evaluate a series of products in numpy
<p>Say I have a 1D array of [a1, a2, a3, ..., an], and I want the array [a1, a1a2, a1a2a3, ..., a1a2...an]. Is this possible to compute using numpy's routines? At the moment, I am using a loop whereby each element is the previous element multiplied by the new `a'. However, this is understanably quite slow.</p> <p>EDIT:...
<p>You can use <code>np.cumprod</code></p> <pre><code>import numpy as np a = np.random.rand(10) p = np.cumprod(a) print(p) </code></pre>
python|numpy
2
361,968
65,495,093
numpy results are order dependent when they should not be
<p>I have a (toy) dense NN implemented on numpy. Putting three vectors through through the network, I am seeing deltas in the least-significant digits of one of the outputs if I change the order of the inputs. E.g., swapping the 2nd and 3rd inputs:</p> <pre><code>xta = train_x[:,0:3] # 1...
<p>I like Frank Yellin's hypothesis, so will recast it as an answer:</p> <p>While the operations are the same and the matrixes that are inputs to the operation are the same, the operations may process the matrix elements in a different order resulting in different rounding errors on the least significant bits.</p>
python|numpy|gpgpu
0
361,969
65,888,541
Error reading cvs with pandas from google drive url
<p>I'm trying to read a cvs file with pandas from google drive. Pandas gets it right when reading it from my computer, but when i try to read it from the url i got from google drive to share the file, it seems like it's reading something else, or google drive is doing something weird with the file... heres what i did:<...
<p>Short answer - you can't put Google Drive URL to <code>pd.read_csv()</code>. You have to download the CSV file and use the actual path to it.</p> <p>Basically, the Google Drive URL shows you that there is some CSV file. In reality, it's just a website (with HTML content) that shows you some information about the CSV...
python|pandas
2
361,970
65,881,147
Skiping rows for certain files while reading the files in a loop in python
<p>I am trying to read 17 files in a loop where I want to skip 1 row for few files but not for others.</p> <p>Using the code as given below</p> <pre><code>import os import pandas as pd import glob path=os.getcwd() files=os.listdie(os.curdir) files_xls=[f for f in files if f[-3]=='xls'] filenames=glob.glob(path + &quot;...
<p>In general you can do something like this:</p> <pre><code>data=pd.read_excel(f, skiprows==1 if condition else 0) </code></pre> <p>But you can't use the data in the file before you read it. The condition can't be function of data (at least you don't read it before in some another way)</p> <p>Note that in your loop yo...
python|excel|pandas
0
361,971
65,821,504
How to convert the dataframe to a desired format?
<p>I'm looking to convert the dataframe to particular format.</p> <p>The example dataframe is as follows:</p> <pre><code>Col1 a b c </code></pre> <p>I want to convert the above dataframe to following format by splitting into two columns:</p> <pre><code>Col1 Col2 a a a b a c b b b c c c <...
<p>You could try <a href="https://docs.python.org/3/library/itertools.html#itertools.combinations_with_replacement" rel="nofollow noreferrer"><code>itertools.combinations_with_replacement</code></a>:</p> <pre><code>from itertools import combinations_with_replacement as comb df = pd.DataFrame(list(comb(df['Col1'], 2)), ...
python|pandas|dataframe|data-manipulation
3
361,972
65,489,612
Add normalization layer at the begining of a pre-trained model
<p>I have a pretrained UNet model with the following architecture</p> <pre><code>UNet( (encoder1): Sequential( (enc1conv1): Conv2d(3, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (enc1norm1): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (enc1relu1):...
<p>You can wrap your pretrained model with a <code>nn.Module</code> that will use the <code>UNet</code> in its forward definition:</p> <pre><code>class UNetWrapper(nn.Module): def __init__(self, unet): super(UNetWrapper, self).__init__() self.norm = nn.BatchNorm2d(3) self.unet = unet de...
python|machine-learning|deep-learning|pytorch
0
361,973
65,702,394
I keep getting this error : TypeError: lemmatize() missing 1 required positional argument: 'word'
<pre><code>lemmatizer = WordNetLemmatizer intents = json.loads(open('intents.json').read()) words = [] classes = [] documents = [] ignore_letters = ['?', '!', '.', ','] for intent in intents['intents']: for pattern in intent['patterns']: word_list = nltk.word_tokenize(pattern) words.extend(word_l...
<p>Same thing happened to me. You just need to add the parenthesis '()' after 'WordNetLemmatizer' to instantiate it correctly.</p> <p>Should read:</p> <pre><code>lemmatizer = WordNetLemmatizer() </code></pre>
python|python-3.x|tensorflow
0
361,974
65,881,540
find a value in a dataframe and add precedent column value in a new column in pandas
<p>I have below data frame with 5 columns, I need to check specific string(&quot;-&quot;) in all columns and add precedent value in new column(F) if &quot;-&quot; is found. for example, &quot;-&quot; is located in Column B row zero and two; hence, 'a' and 'c'[precedent Column value] are added in Column(F) in related ro...
<p>Replace misisng values to all columns by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.where.html" rel="nofollow noreferrer"><code>DataFrame.where</code></a> exclude previous values by <code>-</code> compared by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/...
python|pandas
2
361,975
65,570,296
What is a more efficient or "pythonic" way to clean column headers?
<p>I'm pulling some data from the pro football reference website. All of the information pulled fine, but the column headers are a bit messy. I wrote some code to clean it up, but it doesn't quite feel &quot;right.&quot; It seems a bit too repetitive as I keep reassigning the same variable over in the same for loop.</p...
<p>column name is tuple. so use as follows:</p> <p>Code:</p> <pre><code>cols = [x[1] for x in df.columns] cols = list(map(lambda x: x.replace('1st', 'First'), cols)) cols = list(map(lambda x: x.replace('%', 'Pct'), cols)) print(cols) </code></pre> <p>Output:</p> <pre><code>['Rk', 'Tm', 'G', 'PF', 'Yds', 'Ply', 'Y/P', '...
python|regex|pandas
1
361,976
65,847,730
Drop columns tha thave a header but all rows are empty Python 3 & Pandas
<p>I just could not figure this one out:</p> <pre><code>df.dropna(axis = 1, how=&quot;all&quot;).dropna(axis= 0 ,how=&quot;all&quot;) </code></pre> <p>All headers have data. How can I exclude the headers form a <code>df.dropna(how=&quot;all&quot;)</code> command. I am afraid this is going to be trivial, but help me out...
<p>Okay, as I understand what you want is as follows:</p> <ul> <li>drop any column where all rows contain NaN</li> <li>drop any row in which one or more NaN appear</li> </ul> <p>So for example, given a dataframe df like:</p> <pre><code> Id Col1 Col2 Col3 Col4 0 1 25.0 A NaN 6 1 2 15.0 B N...
python-3.x|pandas|drop
0
361,977
65,847,198
Error while implenting the Faster R-CNN Object detection algorithm
<p>I am trying to implement the Faster R-CNN object detection algorithm and I have an unusual error. While trying to call the <code>train_one_epoch</code> function in this <a href="https://colab.research.google.com/github/pytorch/vision/blob/temp-tutorial/tutorials/torchvision_finetuning_instance_segmentation.ipynb#scr...
<p>Finally, I was able to solve this problem and it's just by adding adjusting the size of the AnchorGenerator and their corresponding aspect ratios in the Faster R-CNN function</p> <pre><code>ft_anchor_generator = AnchorGenerator( sizes=((32, 64, 128),), aspect_ratios=((0.5, 1.0, 2.0),) ) ft_model = FasterRCNN( ...
python|pytorch|object-detection|torchvision|faster-rcnn
0
361,978
65,697,509
How to remove specific data in image processing
<p>I am having images data and I am using it for training my machine learning using SIFT, but my data have problems which some images contain 0 image descriptor. So my result when I am finishing my training and testing only reach 56% (Of course, it not the result I expected). To resolve this problem, I decide to remove...
<p>For this problem that some of the images I have in the data contain no features. SO I give it the solution to delete any data that has no feature</p> <pre><code>def extract_sift_feature(X, y): images_descriptor = [] filter_images_descriptor = [] NoneType_index_list = [] sift = cv2.SIFT_create() ...
python|machine-learning|image-processing|numpy-ndarray|feature-descriptor
0
361,979
65,641,765
Manual mini-batch generation for PyTorch Geometric
<p>Currently I have pytorch tensors with shape <code>(batch_size, height, width, channel_size)</code> and I want to convert it to a mini-batch described <a href="https://pytorch-geometric.readthedocs.io/en/latest/notes/batching.html" rel="nofollow noreferrer">here</a>. My current idea is to convert each example from te...
<p>I think I'm experiencing a similar question with you. If I understand your question correctly, your want to commit following transformation</p> <pre><code>Input: Tensor = [#batch,#vertex,#feature] Output: torch_geometric.data.BatchData = Large tensor </code></pre> <p>My implementation is:</p> <pre><code>x = DataLoad...
pytorch|mini-batch|pytorch-geometric
0
361,980
65,556,026
python reshape every nth column
<p>I have just started with python and need some help. I have a dataframe which looks like &quot;Input Data&quot;, What I want is stack by every nth column. In other words, I want a dataframe where every nth Column is appended below to first m rows</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr...
<pre class="lang-py prettyprint-override"><code>In [74]: column_list = [df.columns[k:k+5] for k in range(2, len(df.columns), 5)] In [75]: column_list Out[75]: [Index(['Col 1', 'Col 2', 'Col 3', 'Col 4', 'Col 5'], dtype='object'), Index(['Col 6', 'Col 7', 'Col 8', 'Col 9', 'Col 10'], dtype='object')] In [76]: dfs = [...
pandas|dataframe
0
361,981
65,544,954
Pandas: extract values from a column with multiple list of dictionaries and split the values into multiple columns
<p>I have a dataframe <code>df</code>. Most of the columns are json strings while some are list of jsons. The preview of sample rows is shown below:</p> <pre><code> id movie genres 1 John [{'id': 28, 'name': 'Action'}, {'id': 12, 'name': 'Adventure'}, {'id': 878, 'name': 'Science Fiction'}] ...
<p>This code;</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd a = {'id': 28, 'name': 'Action'}, {'id': 12, 'name': 'Adventure'}, {'id': 878, 'name': 'Science Fiction'}, {'id': 10749, 'name': 'Romance'} b = {'id': 12, 'name': 'Adventure'}, {'id': 878, 'name': 'Science Fiction'}, {'id': 5, 'name':...
python|pandas|dictionary
0
361,982
65,798,191
Pandas read_html object is not callable
<p>I'm trying to screen scrape an html table located at <a href="https://www.insidearbitrage.com/insider-sales/?desk=no" rel="nofollow noreferrer">https://www.insidearbitrage.com/insider-sales/?desk=no</a> using the code below. I'm using Python 3.9 and it's the only version of Python installed on my pc after I previou...
<p>After much playing around, I decided to just delete Python altogether and reinstall. At one point I had multiple versions of Python on my pc including Anaconda and I had copied all site-packages from those versions into the standalone 3.9.1. Seems like things got pretty messed up so I uninstalled all python versio...
python|pandas
0
361,983
65,886,653
Why is openCV mask turning the whole image black?
<p>The first image is the original, the second is the hsv, and the third is the mask.</p> <p>The yellowest color in the hsv image is between the boundaries set. Why is the whole image turning black?</p> <p><img src="https://i.stack.imgur.com/LZNsl.png" alt="Original" /></p> <p><img src="https://i.stack.imgur.com/zIIZY....
<p>It's all about your color ranges, you can either change the values manually and randomly or maybe take a look at this color seperator script it can be very helpful <a href="https://github.com/twenty-twenty/opencv_basic_color_separator" rel="nofollow noreferrer">hsv color seperator</a></p>
python|image|numpy|opencv
0
361,984
65,819,105
How to convert 'O' values to date format
<p>I have tried to convert a column with 'O' values like</p> <pre><code>31 October 2020 31 October 2020 31 October 2020 30 November 2020 30 November 2020 </code></pre> <p>in a date format:</p> <pre><code>df['Date']=pd.to_datetime(df['Date'], errors='coerce', format='%m %d %Y') </code></pre> <p>However I've got <code>Na...
<p>Try:</p> <pre><code>import pandas as pd from io import StringIO inputtxt = StringIO(&quot;&quot;&quot;Date 31 October 2020 31 October 2020 31 October 2020 30 November 2020 30 November 2020&quot;&quot;&quot;) df = pd.read_csv(inputtxt) df['Date2'] = pd.to_datetime(df['Date'], format='%d %B %Y').dt.strftime('%m/%d/%...
python|pandas|python-datetime
2
361,985
65,679,065
Generating binary sequences without repetition
<p>I am trying to generate sequences containing only <code>0</code>'s and <code>1</code>'s. I have written the following code, and it works.</p> <pre><code>import numpy as np batch = 1000 dim = 32 while 1: is_same = False seq = np.random.randint(0, 2, [batch, dim]) for i in range(batch): for j in ...
<p>Generate <code>batch</code> number of <code>int</code> in <code>range(0, 2**dim + 1)</code> Convert these numbers to binary, then convert to sequence of <code>0</code>a and <code>1</code>s.</p> <pre><code>from random import sample def generate(batch, dim): my_sample = [f'{n:0&gt;32b}' for n in sample(range(2**d...
python|python-3.x|performance|numpy|random
3
361,986
65,654,970
Sample given points stochastically in a 3D space with minimum nearest-neighbor distance and maximum density
<p>I have <code>n</code> points in a 3D space. I want to stochastically sample a subset of points with all nearest-neighbor distances larger than <code>r</code>. The size of the subset <code>m</code> is unknown, but I want the sampled points to be as dense as possible, i.e. maximize <code>m</code>.</p> <p>There are sim...
<p>There's probably an efficient bicriteria approximation scheme, but why bother when integer programming is so quick on average?</p> <pre><code>import numpy as np n = 300 points = np.random.uniform(0, 10, size=(n, 3)) from ortools.linear_solver import pywraplp solver = pywraplp.Solver.CreateSolver(&quot;SCIP&quot;)...
python|algorithm|numpy|random|nearest-neighbor
2
361,987
65,896,666
Python get unique element in array but maintain its original sequence
<p>I would like to get the unique element from an array with specific sequences.</p> <p>For example,</p> <p>initially, I have array as following:</p> <pre><code>array([3, 3, 6, 6, 5, 5, 5, 5, 2, 8, 8]) </code></pre> <p>I would like to get the unique element from the array above and maintain its original order sequence....
<p>Try this snippet:</p> <pre><code>arr = np.array([3,3,6,6,5,5,5,5,2,8,8]) unique = [] [unique.append(n) for n in arr if n not in unique] print(np.array(unique)) </code></pre>
python|arrays|numpy
2
361,988
21,155,237
Strategy to open a corrupt csv file in pandas
<p>I have got a bunch of csv files that I am loading in Pandas just fine, but one file is acting up I'm opening it this way :</p> <pre><code>df = pd.DataFrame.from_csv(csv_file) </code></pre> <p>error:</p> <blockquote> <p>File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/...
<p>if in Linux open it with head in the operating system to inspect it then fix it with awk or sed.. if in windows, you could also try vim to inspect and fix it. In short it probably is not best to fix the file in Pandas. You most likely have odd line endings (since the error message says 0 lines) so heading the file ...
python|pandas
0
361,989
21,322,564
Numpy list of 1D Arrays to 2D Array
<p>I have a large list files that contain 2D numpy arrays pickled through <code>numpy.save</code>. I am trying to read the first column of each file and create a new 2D array.</p> <p>I currently read each column using <code>numpy.load</code> with a <code>mmap</code>. The 1D arrays are now in a list.</p> <pre><code>...
<p>You can use</p> <pre><code>numpy.stack(arrays, axis=0) </code></pre> <p>if you have an array of arrays. You can specify the axis in case you want to stack columns and not rows.</p>
python|arrays|numpy
62
361,990
20,994,419
filling data gaps with monthly averages (Python)
<p>I have a very long time series over 10 years with half-hourly measurements as Csv file. Every now and then the measurement device break down. I want to interpolate this gaps either with the monthly average or a moving average (which neglect missing values). I guess I need a for-loop to do this but I have no Idea how...
<p>With such big gaps of missing values, I guess you're really better off, to keep them as NANs, and adjust your calculations, that they can deal with missing data. Looks like you're doing financial simulations with it, and in the long run, it will always backfire, if you modify the actual raw data. In case you're usin...
python|for-loop|pandas|average|interpolation
1
361,991
21,352,893
Cannot figure out how to install numpy with Python 3.3.3 and Windows 7 64bit
<p>This is driving me nuts. I'm brand new to python and just want to be able to import numpy but have failed while trying to follow 20 different sets of instructions. I know very little about installing things from command prompts, so please don't assume any knowledge.</p> <p>So far I have installed pip and gotten t...
<p>It may be easier to download prebuilt binary from: <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy" rel="noreferrer">http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy</a></p> <p>If your python installation is 32-bit, then you are looking for <code>numpy-MKL-1.8.0.win32-py3.3.exe</code>. For 64-bit python: ...
python|numpy|miniconda
7
361,992
21,233,224
How to logically combine integer indices in numpy?
<p>Does anyone know how to combine integer indices in numpy? Specifically, I've got the results of a few <code>np.where</code>s and I would like to extract the elements that are common between them.</p> <p>For context, I am trying to populate a large 3d array with the number of elements that are between boundary value...
<p>as @ali_m said, use bitwise and should be much faster, but to answer your question:</p> <ul> <li>call <code>ravel_multi_index()</code> to convert the multi-dim index into 1-dim index.</li> <li>call <code>intersect1d()</code> to get the index that in both condition.</li> <li>call <code>unravel_index()</code> to conv...
python|numpy
4
361,993
21,352,016
Remove string quotes from array in Python
<p>I'm trying to get rid of some characters in my array so I'm just left with the <code>x</code> and <code>y</code> coordinates, separated by a comma as follows:</p> <pre><code>[[316705.77017187304,790526.7469308273] [321731.20991025254,790958.3493565321]] </code></pre> <p>I have used <code>zip()</code> to create a ...
<p>Using <a href="http://docs.python.org/2/library/ast.html" rel="nofollow">31.2. ast — Abstract Syntax Trees¶</a></p> <pre><code>import ast xll = [['321731.20991025254,' '790958.3493565321,'], ['321731.20991025254,' '790958.3493565321,']] &gt;&gt;&gt; [ast.literal_eval(xl[0]) for xl in xll] [(321731.20991025254, 790...
python|arrays|python-2.7|numpy|coordinates
1
361,994
21,176,320
How to fetch timestamp in Pandas DataFrame
<p>I'm trying to plot pandas to the web using Flask. I think i'm on the right track but i'm struggling to grab the date to put on the x axis.</p> <p>for the y axis data, its easy:</p> <pre><code>aapl = pd.io.data.get_data_yahoo('AAPL', start=datetime.datetime(2006, 10, 1), end=datetime.datetime(2012, 1, 1)) all_...
<p>Date is the index of your DataFrame. You can access it simply as follows:</p> <pre><code>df.index </code></pre> <p>Vanilla example</p> <pre><code>In [13]: index = pd.DatetimeIndex(start='2012', end='2013', freq='1D') In [14]: index Out[14]: &lt;class 'pandas.tseries.index.DatetimeIndex'&gt; [2012-01-17 00:00:00...
python|matplotlib|pandas
1
361,995
21,011,777
How can I remove Nan from list Python/NumPy
<p>I have a list that countain values, one of the values I got is 'nan'</p> <pre><code>countries= [nan, 'USA', 'UK', 'France'] </code></pre> <p>I tried to remove it, but I everytime get an error </p> <pre><code>cleanedList = [x for x in countries if (math.isnan(x) == True)] TypeError: a float is required </code></pr...
<p>The question has changed, so too has the answer:</p> <p>Strings can't be tested using <code>math.isnan</code> as this expects a float argument. In your <code>countries</code> list, you have floats and strings.</p> <p>In your case the following should suffice:</p> <pre><code>cleanedList = [x for x in countries if str...
python|numpy
181
361,996
21,287,973
Huge time difference on creating numpy.zeros for tiny difference in size of array
<p>I was trying to determine the time complexity of doing <code>numpy.zeros</code> so I ran the following tests. It seems to be linear with the size of the array you're creating, but at a certain point there is a huge disparity on how much time it takes. Here are the interesting cases where <strong>hardly changing th...
<p><a href="https://i.stack.imgur.com/8G6ZC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8G6ZC.png" alt="The x axis is log(i), the y axis is the time/i"></a></p> <p>I had the same problem on my computer. Don't know to explain it. </p> <p>I plotted the time divided by the length of the array, so ...
python|arrays|numpy
1
361,997
3,089,832
sine wave glissando from one pitch to another in Numpy
<p>I have been working on a program where I need to slowly and smoothly change the pitch of a sine wave from one pitch to another. I am able to get an array of the frequency the pitch should be at any given moment (for instance, [440, 526.5, 634.2 794.8, 880], though much, much longer) but it seems I am unable to actu...
<p>The issue is that as you ramp through the frequencies, each frequency effectively has a different phase for the given time. When you scroll through these phases quickly and continuously, they drive the sine wave at higher frequency (or lower is also possible). </p> <p>Imagine, for example, that you changed the fr...
python|math|audio|numpy|trigonometry
10
361,998
3,059,395
numpy array assignment problem
<p>I have a strange problem in Python 2.6.5 with Numpy. I assign a numpy array, then equate a new variable to it. When I perform any operation to the new array, the original's values also change. Why is that? Please see the example below. Kindly enlighten me, as I'm fairly new to Python, and programming in general....
<p>That's actually not a problem at all; it's the way arrays (and other objects) work in Python. </p> <p>Think about it like this: the array you created in your code example is an object that sits at some location in memory. But you can't use it in your program by telling Python where in memory to go look for it; you ...
python|arrays|numpy
70
361,999
2,695,503
removing pairs of elements from numpy arrays that are NaN (or another value) in Python
<p>I have an array with two columns in numpy. For example:</p> <pre><code>a = array([[1, 5, nan, 6], [10, 6, 6, nan]]) a = transpose(a) </code></pre> <p>I want to efficiently iterate through the two columns, a[:, 0] and a[:, 1] and remove any pairs that meet a certain condition, in this case if they are Na...
<p>If you want to take only the rows that have no NANs, this is the expression you need:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a[~np.isnan(a).any(1)] array([[ 1., 10.], [ 5., 6.]]) </code></pre> <p>If you want the rows that do not have a specific number among its elements, e.g. 5:</p...
python|arrays|numpy|scipy
31