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
367,600
66,049,159
How to divide a dataframe by another column of the same dataframe
<p>I'm stuck on a problem with dataframes due to the lack of understanding in looping/iterating/matrices/etc.</p> <p>so I have a dataframe or an array (whatever works):</p> <pre><code>initial = [[1,2,3,3], [4,5,6,6],[7,8,9,9]] </code></pre> <p>I need to divide all the values in the array/df excluding the last column by...
<p>If initial is a numpy array this is easy to achieve using slicing:</p> <pre><code>import numpy initial = numpy.array([[1,2,3,3],[4,5,6,6],[7,8,9,9]]) result = initial[:,:-1]/initial[:,[-1]] </code></pre> <p>In slicing &quot;:&quot; means take all, &quot;:n&quot; take all up to the n-th element (excluded) in the resp...
python|pandas
0
367,601
66,260,512
How do I add xlsb files to the catalog in Kedro?
<p>1.I am using this code in catalog.yml file</p> <pre><code>equipment_data: type: pandas.ExcelDataSet filepath: data\01_raw\Equipment Profile.xlsb layer: raw </code></pre> <ol start="2"> <li>getting error after executing kedro run command.</li> </ol> <p>` kedro.io.core.DataSetError: Failed while loading data fr...
<p>So the <code>pandas.ExcelDataset</code> simply calls <code>pandas</code> underneath so hopefully you can have luck following <a href="https://stackoverflow.com/a/60019546/2010808">this example from another thread</a> where the engine (provided by <code>pip install pyxlsb</code> installing another package) is used to...
python|pandas|dataframe|kedro
1
367,602
66,144,272
Add values from Series with n rows, to Dataframe with m>n rows according to column value
<p>I have a dataframe <strong>A</strong>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>index</th> <th>some_n</th> </tr> </thead> <tbody> <tr> <td>adf1</td> <td>xy100</td> </tr> <tr> <td>adf2</td> <td>xy100</td> </tr> <tr> <td>adf8</td> <td>xy100</td> </tr> <tr> <td>fds6</td> <td>xy201</t...
<p>Use map:</p> <pre><code>A['my_value'] = A['some_n'].map(b) </code></pre>
python|pandas|dataframe|merge
1
367,603
65,998,560
Python count number of daily changes in panel data
<p>I have a pandas dataframe of panel data where each row is a time series for an individual, each column is a day in the time series. On a daily basis I would like to count the number of day on day changes so I can determine what percentage of individuals change each day.</p> <pre><code>indiv = ['Tom', 'Mike', 'Dave']...
<p>Set the index to the name then transpose the df.</p> <pre class="lang-py prettyprint-override"><code>df = df.set_index('name').T </code></pre> <pre><code> name 2020-01-29 2020-01-30 2020-01-31 0 Tom yes no yes 1 Mike yes yes yes 2 Dave no no yes...
python|pandas|panel-data
1
367,604
66,023,106
How to create Hybrid loss consisting from dice loss and focal loss [Python]
<p>I'm trying to implement the <strong>Multiclass Hybrid loss</strong> function in Python from following article <a href="https://arxiv.org/pdf/1808.05238.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1808.05238.pdf</a> for my <strong>semantic segmentation</strong> problem using an imbalanced dataset. I managed...
<p>To simplify things a little, I have divided the <strong>Hybrid loss</strong> into four separate functions: Tversky's loss, Dice coefficient, Dice loss, Hybrid loss. You can see the code below.</p> <pre><code>def TverskyLoss(targets, inputs, alpha=0.5, beta=0.5, smooth=1e-16, numLabels=3): tversky = 0 for ind...
python|tensorflow|keras|loss|semantic-segmentation
1
367,605
65,915,176
Yolo from scratch dataset and output
<p>Hi I coded a YOLO model from scratch and just came to realise that my dataset does not fit the models output. This is what I mean: The model outputs a <code>S x S x (B * 5 + C)</code> matrix. The shape of y[0] (the answer for the first image) is <code>(7,5)</code>. How will I make the model use the labels of mine. F...
<p>According to the <a href="https://arxiv.org/pdf/1506.02640.pdf" rel="nofollow noreferrer">paper (section 2)</a>, the <code>S x S x (B * 5 + C)</code> shaped output represents the <code>S x S</code> grid cells that YoloV1 splits the image into. The last layer can be implemented as a fully connected layer with an outp...
python|numpy|keras|artificial-intelligence|yolo
0
367,606
65,981,265
Pandas dataframe, how can I group by single column and apply sum to multiple column and add new sum column?
<p>This should be an easy one, but somehow I couldn't find a solution that works.</p> <p>I have a pandas dataframe which looks like this:</p> <pre><code>Slno Date col2 col3 col4 col5 col6 0 01/02/20 2 1 2 5 d 1 03/02/20 5 1 2 4 g 2 04/02/20 ...
<p>You can set <code>Date</code> as index then take sum of the columns on axis=1, then groupby <code>level=0</code> and transform <code>sum</code></p> <pre><code>df['Total'] = (df.set_index('Date')[[&quot;col2&quot;, &quot;col3&quot;,&quot;col4&quot;, &quot;col5&quot;]].sum(1) .groupby(level=0).transform('su...
python|pandas|dataframe|pandas-groupby
1
367,607
66,106,845
Pandas Approximate Frequency Per Year of a DateTimeIndex
<p>I have a multiple Timeseries in different files and I know that Pandas can infer the frequency of the DateTimeIndex for each:</p> <pre><code>pd.infer_freq(data.index) </code></pre> <p>Is there a programmatic way to get the approximate frequency per year from general files. For instance:</p> <pre><code>'M' -&gt; 12 ...
<p>Here's one alternative. We'll create a date_range using the provided frequency and then groupby to figure out the most common number that fit into a year. The <code>periods</code> argument should be large enough such that given the frequency the date range creates many years of data. Really shouldn't need to change ...
python|pandas|frequency|datetimeindex
1
367,608
66,153,920
How to get inner product of 3D array to 2D array?
<p>I have two Numpy array</p> <pre><code>b=np.array([[1, 2, 3], [4, 5, 6]]) a=np.array([[[1, 2,1], [3, 4,1],[4,5,6],[6,7,8]], [[5, 6,1], [7, 8,1],[4,5,6],[6,7,8]]]) a.shape,b.shape ((2, 4, 3), (2, 3)) </code></pre> <p>I want to calculate dot product of these array. I tried below code:</p> <pre><code>s=np.flip(np.dot(a...
<p><code>a</code>'s shape should be <code>(*, 3, 2)</code> because <code>b</code>'s shape is <code>(2, 3)</code>.</p> <pre><code>a_ · b = │ a11 a12 | * | b11 b12 b13 | │ a21 a22 | | b21 b22 b23 | │ a31 a32 | </code></pre> <p>where <code>a_</code> is an element of <code>a</code>.</p> <p>With the fol...
python|arrays|numpy
2
367,609
66,090,004
get the mean of each value in a pandas dataframe column
<p>I need to get the average of the working years for each name in the HR department.</p> <p>I tried this</p> <pre><code>work = df.loc[Employee['Department'] == 'HR', [{'Year' : 'mean'}], ['FirstName', 'LastName', 'Year','Department']].drop_duplicates() </code></pre> <p>The result would be like this. T...
<p>I would use the group by function of pandas:</p> <pre><code>df_gb = df.groupby(['Department','FirstName','LastName'])['Year'].mean().reset_index() df_gb = df_gb[df_gb['Department']=='HR'] </code></pre> <p>The first line gives you the output you want, the average of years by department and name. Then you filter by th...
python|pandas|dataframe
1
367,610
66,035,776
Creating a pandas dataframe from a csv file with 1-hot encoded set of columns
<p>My input csv file is already 1-hot encoded (its exported from another system):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>vehicle_1(car)</th> <th>vehicle_1(truck)</th> <th>vehicle_1(other)</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>0</td> <td>1</td> <td>0</td> </tr>...
<p>I don't think there's a way to tell pandas that the columns imported are already encoded (whichever it was used already before importing).</p> <p>The advantage is you don't have to encode again.</p> <p>The disadvantage is the imported DF treats your encoded columns as new columns rather than encoded values of the sa...
python|pandas
1
367,611
66,142,800
How to modify pandas column if value doesnt match requirements?
<p>I am having trouble to format evenly my pandas df.</p> <p>It is filled with dates and prices for Stocks, but the prices are not formatted equally.</p> <p>From the start of 2021, the values have a comma separating the decimal (cents), but from 1998 to 2020, the prices are not seppareted with comma or dot.</p> <p>How ...
<p>For one particukar column <code>MAX</code>. Same can be applied to required columns. You can use <code>pandas.str.replace</code></p> <p>In this case a string <code>xxxxxx</code>, it adds comma before last 2 digits like <code>xxxx,xx</code></p> <pre class="lang-py prettyprint-override"><code>df['MAX'].str.replace(r'(...
python|pandas
1
367,612
66,235,118
Is there a way to combine two columns in a dataset, keeping the larger float64 using Pandas?
<p>Ill try to keep it simple, but these are very large datasets I am working with. Theoretically I am trying to combine Columns A and B of my data frame. But, if A has a value in a row then B doesn't, and vice versa. That hole is filled with 'NaN'</p> <p>A {1,2,NaN,4,5} B {NaN,NaN,3,NaN,NaN}</p> <p>I need A to equal {1...
<pre><code>df['A'] = df['A'].fillna(df['B']) </code></pre> <p>What this code does is fill all missing values of column <code>A</code> with the values found in column <code>B</code>.</p> <p>For more options see: <a href="https://datascience.stackexchange.com/questions/17769/how-to-fill-missing-value-based-on-other-colum...
dataframe|merge|nan|pandas
0
367,613
66,212,125
Unpack list of dictionary into separate columns in Pandas
<p>Let's assume I have data which is structured like such:</p> <pre><code>{ &quot;_id&quot; : 245, &quot;connId&quot; : &quot;3r34b32&quot;, &quot;roomList&quot; : [ { &quot;reportId&quot; : 29, &quot;siteId&quot; : 1 }] } </code></pre> <p>How do I go about gettin...
<p>You have a nested record. You can handle them separately with <code>record_path</code> and them concatenate them with <code>pd.concat()</code></p> <pre><code>root = pd.json_normalize(d).drop('roomList',1) nested = pd.json_normalize(d, record_path='roomList') output = pd.concat([root, nested],axis=1) print(output) </...
python|pandas|list|unpack
3
367,614
52,489,606
create new columns from comparing rows
<p>My input data is like this</p> <pre><code>df = pd.DataFrame({'A':[1,2,3,4], 'B':['x','y','x','y'], 'C':['S1','S1','S2','S2']}) A B C 0 1 x S1 1 2 y S1 2 3 x S2 3 4 y S2 </code></pre> <p>I want to groupby 'C'. Then for the 2 rows in group, use value of B to assign value of A into a...
<p>What you need is more like a <code>pivot</code> </p> <pre><code>df.pivot('C','B','A') Out[209]: B x y C S1 1 2 S2 3 4 </code></pre>
pandas
3
367,615
52,840,269
How to combine the groupby(s) in pandas?
<p>I have two dataframes and I'd like to concatenate the groupby results using Python...How can I do that?</p> <pre><code>df1=pd.DataFrame({'Country':["US","CN","GB","US","DE","AU","CM","CU","CM"],'July Volume': [2541,3766,3071,1881,4653,1890,3203,1820,1411], 'July Sales':[40264,40400,16135,41301,13757,4...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.concat.html" rel="nofollow noreferrer"><code>pandas.concat()</code></a> like this:</p> <pre><code>df1 = df1.groupby('Country').agg({'July Sales':['count','sum']}) df2 = df2.groupby('Country').agg({'Aug Sales':['count','sum']})...
python|pandas|concatenation|pandas-groupby
3
367,616
52,757,593
Unstacking a pandas dataframe
<p>Suppose I have a dataframe with two columns called 'column' and 'value' that looks like this:</p> <p><strong>Dataframe 1:</strong></p> <pre><code> column value 0 column1 1 1 column2 1 2 column3 1 3 column4 1 4 ...
<p>Create <code>MultiIndex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> with counter <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcoun...
python-3.x|pandas|dataframe
2
367,617
52,812,566
Why do we use the name 'x' in the tensorflow-serving example?
<p>I'm reading the basic tutorial of tensorflow serving. From mnist_saved_model.py I can't uderstand something:</p> <pre><code>serialized_tf_example = tf.placeholder(tf.string, name='tf_example') feature_configs = {'x': tf.FixedLenFeature(shape=[784], dtype=tf.float32),} tf_example = tf.parse_example(serialized_tf_exa...
<p>It's using a linear equation, where convention has it that y as the output and x as the input.</p> <p><code>y = x * w + b</code></p> <ul> <li>x = input</li> <li>w = weights</li> <li>b = bias</li> <li>y = output</li> </ul>
mnist|tensorflow-serving
0
367,618
52,552,978
How to inject data into a graph when using an input pipeline?
<p>I am using an initializable iterator in my code. The iterator returns batches of size 100 from a csv dataset that has 20.000 entries. During training, however, I came across a problem. Consider this piece of code:</p> <pre><code>def get_dataset_iterator(batch_size): # parametrized with batch_size dataset ...
<p>1) Loss calculation over the whole training set (before updating weights) does make sense and is called batch gradient descent (despite using the whole training set and not a mini batch).</p> <p>However, calculating a loss for your whole dataset before updating weights is slow (especially with large datasets) and t...
python|python-3.x|tensorflow
1
367,619
52,606,075
Getting nan value in Output in Tensorflow
<p>Can you please help me in below code ? Getting nan value in Output in Tensorflow, when trying to get the values of w and b in tensorflow session</p> <pre><code>import numpy as np import tensorflow as tf import numpy.random as rand trainX = np.array([[2.5,5.6,7.8,8.9]],dtype=np.float32) trainY = np.array([[6.7,6....
<p>It is "diverged".</p> <p>Change learning rate lower.</p> <pre><code>#learning_rate = 0.01 learning_rate = 0.001 </code></pre> <p>I confirmed below result.</p> <pre><code>[0.00044938] [6.922184] </code></pre>
tensorflow
2
367,620
52,686,406
List of column_names having dtypes as 'object'
<p>Does anyone know how to make a list of column names which contain the names of columns which has dtypes as 'object' Or in other words the columns containing strings</p> <p>Please guys it ill be great help if u do so</p>
<p>Let's say we have following data:</p> <pre><code>df = pd.DataFrame({"a":[1,2,3],"b":["a","b","c"]}) df a b 0 1 a 1 2 b 2 3 c </code></pre> <p>Then the following line will do:</p> <pre><code>[nm for nm, dt in zip(df.columns, df.dtypes) if dt == "object"] ['b'] </code></pre>
python-3.x|pandas|dataframe
0
367,621
52,780,559
Outer sum, etc. in pytorch
<p>Numpy offers optimized outer operations for any <code>RxR -&gt; R</code> function, like <code>np.multiply.outer</code> or <code>np.subtract.outer</code>, with the behaviour:</p> <pre><code>&gt;&gt;&gt; np.subtract.outer([6, 5, 4], [3, 2, 1]) array([[3, 4, 5], [2, 3, 4], [1, 2, 3]]) </code></pre> <p><...
<p>Per the <a href="https://pytorch.org/docs/stable/notes/broadcasting.html" rel="noreferrer">documenation</a>:</p> <blockquote> <p>Many PyTorch operations support NumPy Broadcasting Semantics.</p> </blockquote> <p>An outer subtraction is a broadcasted subtraction from a 2d array to a 1d array, so essentially you c...
python|optimization|pytorch|torch
6
367,622
52,752,241
how to create a new column in a dataframe using a loop in python
<p>I would like to make a new variable, called snapavg, using a loop.</p> <p><a href="https://i.stack.imgur.com/2RnMq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2RnMq.png" alt="Here is a screenshot of the dataframe"></a></p> <p>For each Name, I would like to make a loop that:</p> <ul> <li><p>...
<p>Test data</p> <pre><code>df = pd.DataFrame( { 'date': [1, 2, 3, 1, 2, 3], 'user': ['a', 'a', 'a', 'b', 'b', 'b'], 'value': [1, 2, 3, 2, 4, 6] } </code></pre> <p>Get result:</p> <pre><code>df.apply(lambda x: np.sum([df[(df.user == x.user) &amp; (df.date == each)].iloc[0].value for each in range(1, x.da...
python|pandas|loops|for-loop
0
367,623
52,515,177
cell_clip and proj_clip parameter in Tensorflow LSTMCell
<p>I'm learning TF to train a language model for my project. I found in <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/LSTMCell" rel="nofollow noreferrer">LSTMCell</a> initializer, there are two parameter, cell_clip and proj_clip, that I don't understand. and I don't found any reference about the tw...
<p>In the official implementation of the rnn_cell, tensorflow defines what proj_clip is :</p> <blockquote> <p>proj_clip: (optional) A float value. If <code>num_proj &gt; 0</code> and <code>proj_clip</code> is provided, then the projected values are clipped elementwise to within <code>[-proj_clip, pr...
python|tensorflow|deep-learning|lstm
0
367,624
52,513,455
Add category specific columns and values to dataframe
<p>I'm looking to create category-specific columns based the corresponding category for some of the columns.</p> <p>I've accomplished this in a round-about way by (1) slicing the 2 categories into two separate dataframes, (2) merging the two dataframes on the date (3) deleting redundant columns (4) creating new column...
<p>Use:</p> <pre><code>df = df.set_index(['wk start','car']).unstack() df.columns = df.columns.map('_'.join) df = df.reset_index() df = df.loc[:, df.fillna(0).ne(0).any()] print (df) wk start rims_tesla model 3 rims_tesla model x color_tesla model 3 \ 0 2018-09-09 19.0 17.0 ...
python|pandas|dataframe
3
367,625
52,816,688
Extract multiple submatrices from a Tensor
<p>I'm sorry that I've to ask this question, as it seems pretty straightforward, but I'm trying to find a way specifically in Tensorflow.</p> <p>I've a Tensor matrix like below:</p> <pre><code> [0 0 1 1] X = [0 0 1 1] [1 1 0 0] [1 1 0 0] </code></pre> <p>I need to extract both patches:</p> <pre><code> [...
<p>You can do this using tf.gather_nd as well. Below is an example showing all the working bits, and what you can do with gather_nd. You should be able to construct indices so that you only need a single gather_nd op to get all the submatrices you want. I just included the variable indices to show that you can use it t...
python|python-3.x|tensorflow
2
367,626
52,537,021
How to extract elements in specific column of the dataset?
<p>i have been trying to build a neural network,to do so i have to divide the data into x and y,(my dataset was converted to numpy). The data in the "x" is the 1st column which i have extracted successfully but when i try to extract the 2nd column i get the both x and y values for "y". Here the code i used to divide t...
<p>You may want to review the numpy indexing <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html" rel="nofollow noreferrer">documentation</a>.</p> <p>To get the second column in the same shape as <code>x</code>, use <code>y=data[:, 1:2]</code>.</p> <p>Note: you are creating 2d arrays with ...
python|numpy|neural-network
2
367,627
52,815,264
TypeError: cannot unpack non-iterable int object
<p>Im trying to make my first CNN using pyTorch and am following online help and code already people wrote. i am trying to reproduce their results. I'm using the Kaggle Dogs Breed Dataset for this and below is the error I get. The trainloader does not return my images and labels and any attempt to get them leads in an ...
<p>It seems like you are using torchvision's image transforms. Some of these transforms are expecting as input a <a href="https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#image-module" rel="nofollow noreferrer"><code>PIL.Image</code></a> object, rather than a tensor or numpy array.<br> You are using <code>io...
python|deep-learning|pytorch
1
367,628
52,897,666
Pandas: from multi-line to single line observations
<p>Suppose I have this dataframe:</p> <pre><code>df = pd.DataFrame({'index':['10a','10a','10a','20b','20b','20b','30c','30c','30c'] ,'var_vals': ['aaa','aaa','abb','bbb','bba','bbb','ccc','ccc','cab'] ,'var2_vals':['aga','aga','add','bgb','bbd','bgb','cdd','cdd','cda']}) display(d...
<p>One method via <code>groupby.apply</code>:</p> <pre><code>df.groupby('index')['var_vals'].apply(lambda x: pd.Series(x.unique())).unstack() 0 1 index 10a aaa abb 20b bbb bba 30c ccc cab </code></pre>
python|pandas
3
367,629
52,855,171
python - is it possible to compare the list between 2 lists using the specific digit?
<p>I am a new student who is learning to programme with python and I have 2 example lists which are </p> <pre><code>selected_ipc = ['H01L'] df = [[ 'F24J3/02 ', 'A123'], [ 'G01N31/10 ', 'A124'], [ 'H01L27/14 ', 'A125'], ['G21H1/10 ', 'A126'], ['H01L21/36 ', 'A127']] </code></pre> <p>I have created a simple code like ...
<p>you can do it with list comprehensions like below</p> <pre><code>selected_ipc = ['H01L'] df = ['F24J3/02 ', 'G01N31/10 ', 'H01L27/14 ', 'G21H1/10 ', 'H01L21/36 '] for item in selected_ipc: match_lst = [item1 for item1 in df if item in item1] print(match_lst) </code></pre> <p><strong>UPDATE</strong></p> <p>I...
python|pandas|list|dictionary|compare
0
367,630
52,540,886
How can I read the data in DataFrame one by one with a loop statement?
<p>say</p> <pre><code>&gt;&gt;&gt; import tushare as ts &gt;&gt;&gt; df=ts.get_stock_basics() print(df) &gt;&gt;&gt; print(df) name industry area pe ... profit gpr npr holders code ... 000629 攀钢钒钛 小金属 四川 ...
<p>A simple demonstration traversing DataFrame index:</p> <pre><code>import pandas as pd import tushare as ts df = ts.get_stock_basics() print(df) for i in df.index: print(i, type(i)) </code></pre>
python|pandas
1
367,631
52,471,675
Check if Tensor is Placeholder?
<p>Placeholders are recognized as Tensors in TensorFlow. </p> <p><code>isinstance(tf.placeholder("float", []), tf.Tensor)</code> returns <code>True</code></p> <p>Is there a way to check if a Tensor is a placeholder specifically? Something like:</p> <pre><code>isinstance(tf.placeholder("float", []), tf.Placeholder) <...
<p>You can check it with <code>op.type</code>:</p> <pre><code>assert tf.placeholder("float", []).op.type == 'Placeholder' </code></pre>
python|tensorflow|tensor
5
367,632
52,822,177
python pandas identify word which has highest value in data frame from list of given words
<p>I have a DataFrame, and a list of values. Of the words in my list, I want to find which one has the highest value in my DataFrame.</p> <p>Here is my DataFrame:</p> <pre><code> words sum 284 call 85 937 im 55 2158 ur 41 762 get 40 779 go 37 1098 like 37 1342 now 36 1998 text ...
<p><strong><em>Setup</em></strong></p> <pre><code>df = pd.DataFrame({ 'words': ['call', 'im', 'ur', 'get', 'go', 'like', 'now', 'text', 'free', 'dont', 'ok', 'time'], 'sum': [85, 55, 41, 40, 37, 37, 36, 36, 35, 34, 31, 31]}, index=[284, 937, 2158, 762, 779, 1098, 1342, 1998, 717, 543, 1369, 2045] ) syy = ...
python|pandas|numpy
1
367,633
52,745,665
Delete 2 last rows of each day in a dataframe
<p>I have a dataframe with a multi index 'date' and 'time'. I would like to delete the 2 last rows of each days.</p> <p>For example:</p> <pre><code>Date Time colA colB 01/01/2018 08:00 15 'abc' 01/01/2018 09:00 16 ...
<p>Assuming the dataframe is multi index with Date and Time as index</p> <pre><code>df.groupby(level = 0, as_index = False).apply(lambda x: x.iloc[:-2]) colA colB Date Time 0 01/01/2018 08:00 15 'abc' 09:00 16 'abd' 1 03/01/2018 11:30 19 'abg'...
python|pandas|dataframe
3
367,634
52,845,439
Pandas cannot write to excel sheet
<p><code>dftcr_hv_tv_tth5.to_excel('C:\Users\alemthottg\Desktop\KiTTEN-TAQ\PlyCluster\tcr_hv_tv_tth5.xlsx',sheet_name='NewSheet',encoding='utf-8')</code></p> <p>The Error message I am getting.</p> <blockquote> <p>File "", line 3 dftcr_hv_tv_tth5.to_excel('C:\Users\alemthottg\Desktop\KiTTEN-TAQ\PlyCluster\tcr_...
<p>I think you need to create an ExcelWriter first.</p> <pre><code># create an ExcelWriter writer = pd.ExcelWriter(r'C:\Users\alemthottg\Desktop\KiTTEN-TAQ\PlyCluster\tcr_hv_tv_tth5.xlsx', engine='xlsxwriter') dftcr_hv_tv_tth5.to_excel(writer, sheet_name='NewSheet', encoding='utf-8', index=False) writer.save() </code>...
pandas
1
367,635
52,691,611
spyder doesn't launch after installing pytorch
<p>I installed pytorch but after that Spyder can no longer be launched. Here are the terminal info:</p> <blockquote> <p>conda install pytorch torchvision -c pytorch Solving environment: done</p> <p>==> WARNING: A newer version of conda exists. &lt;== current version: 4.5.10 latest version: 4.5.11</p> <...
<p>I don't know if you have solved your issue, but in case you have and someone else comes across this question or you haven't and are still waiting:</p> <p>I came across your post as a result of having the same thing happen to me... </p> <p>It would seem that all I had to do was "conda update all" for it to start wo...
python|anaconda|spyder|pytorch
1
367,636
52,455,658
Getting rid of maxpooling layer causes running cuda out memory error pytorch
<p>Video card: gtx1070ti 8Gb, batchsize 64, input image size 128*128. I had such UNET with resnet152 as encoder wich worket pretty fine:</p> <pre><code>class UNetResNet(nn.Module): def __init__(self, encoder_depth, num_classes, num_filters=32, dropout_2d=0.2, pretrained=False, is_deconv=False): super...
<p>The problem is that you do not have enough memory, as already mentioned in the comments.</p> <p>To be more specific, the problem lies in the increased size due to the removal of the max pooling, as you already correctly narrowed it down. The point of max pooling - aside from the increased <a href="https://aboveinte...
python|machine-learning|computer-vision|out-of-memory|pytorch
1
367,637
52,704,556
Pandas reading in file that has uneven column lengths
<p>I'm trying to read in a discharge data file which looks like this:</p> <pre><code>Station number: 420 Location: Kotagaon Shringe Latitude: 27 45 00 River: Kali Gandaki Longitude: 84 20 50 Year: ...
<p>You can use the <code>pd.read_fwf()</code> module for reading fixed-width files and leverage the <code>skiprows</code> keyword:</p> <pre><code>disc = pd.read_fwf('test.csv', skiprows=11) </code></pre> <p>Yields:</p> <pre><code> Day Jan. Feb. Mar. Apr. ... Sep. Oct. Nov. Dec. Year 0 1 118.0 ...
python|pandas
1
367,638
52,885,878
How to downsampling time series data in pandas?
<p>I have a time series in pandas that looks like this (order by id):</p> <pre><code>id time value 1 0 2 1 1 4 1 2 5 1 3 10 1 4 15 1 5 16 1 6 18 1 7 20 2 15 3 2 16 5 2 17 ...
<p>You can convert your <code>time</code> series to an actual <code>timedelta</code>, then use <code>resample</code> for a vectorized solution:</p> <pre><code>t = pd.to_timedelta(df.time, unit='T') s = df.set_index(t).groupby('id').resample('3T').last().reset_index(drop=True) s.assign(time=s.groupby('id').cumcount()) ...
python|pandas|dataframe
6
367,639
52,839,666
Best way to flatten dataframe based on values on column
<p>I have to process a whole dataframe with some hundered thousands rows, but I can simplify it as below:</p> <pre><code>df = pd.DataFrame([ ('a', 1, 1), ('a', 0, 0), ('a', 0, 1), ('b', 0, 0), ('b', 1, 0), ('b', 0, 1), ('c', 1, 1), ('c', 1, 0), ('c', 1, 0) ], columns=['A', 'B', 'C']) print (df) A B C 0 a 1 1...
<p>Here is one way:</p> <pre><code># create a row number by group df['rn'] = df.groupby('A').cumcount() + 1 # pivot the table new_df = df.set_index(['A', 'rn']).unstack() # rename columns new_df.columns = [x + '_' + str(y) for (x, y) in new_df.columns] new_df.reset_index() # A B_1 B_2 B_3 C_1 C_2 C_3 #0 a ...
pandas|dataframe|vectorization
14
367,640
52,484,336
is there a way with tensorflow.js to input a shape with -1 as one of the shape value
<p>In numpy, you can input a shape with a value of -1 which will do:</p> <pre><code>np.arange(9) &gt;&gt;&gt; array([0,1,2,3,4,5,6,7,8]) np.arange(9).reshape((3,-1)) &gt;&gt;&gt; array([[0,1,2], [3,4,5], [6,7,8]]) </code></pre> <p>it will infer the remaining shape to have. (3,3) in this case.</...
<p>You do have the same behavior with tensorflow.js when using <a href="https://js.tensorflow.org/api/0.13.0/#reshape" rel="nofollow noreferrer">reshape</a>. But it does not work when creating the tensor. See the following:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="fa...
javascript|arrays|numpy|matrix|tensorflow.js
1
367,641
52,678,843
Numpy Matrix Modulo Index Extraction
<p>Suppose I have a 2-dimensional matrix A, say</p> <pre><code>A = np.mat([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) </code></pre> <p>how can I change all elements in row 1 with column index modulo 2 to 0? I.e., I would like to obtain </p> <pre><code>np.mat([[1,2,3,4], [0,6,0,8], ...
<p>Column <code>index % 2 = 0</code> means that the index is an even integer. You can change the elements of the first row at even column indexes to 0 as follows:</p> <pre><code>A[1, ::2] = 0 # 2 is the step </code></pre> <p>If you want to do it as your (incorrect) <code>A[1][np.arange(len(A))%2==0] = 0</code>, you...
python|numpy
1
367,642
52,814,859
Parsing JSON in Pandas
<p>I need to extract the following json:</p> <pre><code>{"PhysicalDisks":[{"Status":"SMART Passed","Name":"/dev/sda"}]} {"PhysicalDisks":[{"Status":"SMART Passed","Name":"/dev/sda"},{"Status":"SMART Passed","Name":"/dev/sdb"}]} {"PhysicalDisks":[{"Status":"SMART Passed","Name":"/dev/sda"},{"Status":"SMART Passed","Nam...
<pre><code>df1 = df["PhysicalDisks"].apply(pd.Series) df_final = pd.concat([df, df1], axis = 1).drop('PhysicalDisks', axis = 1) df_final.head() </code></pre> <p><a href="https://i.stack.imgur.com/Q71mc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q71mc.png" alt="enter image description here"></a>...
python|json|pandas|dataframe
0
367,643
52,467,759
Flag Daylight Saving Time (DST) Hours in Pandas Date-Time Column
<p>I created an hourly dates dataframe, and now I would like to create a column that flags whether each row (hour) is in Daylight Saving Time or not. For example, in summer hours, the flag should == 1, and in winter hours, the flag should == 0. </p> <pre><code># Localized dates dataframe dates = pd.DataFrame(data=pd.d...
<p>There's a nice link in the comments that at least let you do this manually. AFAIK, there isn't a vectorized way to do this.</p> <pre><code>import pandas as pd import numpy as np from pytz import timezone # Generate data (as opposed to index) ...
python|python-3.x|pandas|pytz
4
367,644
52,759,230
Find the string matching between two data frames
<p>I have a DataFrame as below.</p> <p>DF1:</p> <pre><code> A Any Match Credit I need a debit card. Logging Awesome </code></pre> <p>I have another DataFrame as below:</p> <p>DF2:</p> <pre><code> B I did not find any match. I want a credit card. I need a debit card. I do not know. I am logging into cred...
<p>Try <code>Fuzzywuzzy</code>:</p> <pre><code>import pandas as pd from fuzzywuzzy import fuzz matched_entities = [] for row in df1.index: name1 = vendor_df.get_value(row,"A") for columns in df2.index: name2=df2.get_value(columns,"B") matched_token=fuzz.partial_ratio(name1,name2) if m...
python|string|pandas|dataframe
0
367,645
52,857,863
getting all the rows for the last minute in pandas
<p>How I can get all the rows added in the last minute in pandas. <a href="https://i.stack.imgur.com/0fIxf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0fIxf.png" alt="enter image description here"></a> IF there is any value of date is within the last minute i should get it else not.</p> <p>I am...
<pre><code>created_time = datetime.datetime.utcnow() - datetime.timedelta(minutes=1) data = data[(data['Date'] &gt; created_time) &amp; (data['Date'] &lt;datetime.datetime.utcnow())] </code></pre>
python|python-3.x|pandas|datetime|dataframe
1
367,646
52,880,256
Creating fake data in Python
<p>I am trying to create a function that creates fake data to use in a separate analysis. Here are the requirements for the function.</p> <p><strong>Problem 1</strong></p> <p>In this problem you will create fake data using numpy. In the cell below the function create_data takes in 2 parameters "n" and "rand_gen.</p>...
<p>Define numpy_array = rand_gen.randn(n)</p>
python|numpy|random
1
367,647
46,241,976
How to replace part of email address with another string in pandas?
<p>I have a dataframe with email addresses. I need to replace every ending of email address with a '.mn'. What I mean by ending is '.org', '.com', etc. </p> <p><strong><code>Ex. John@smith.com becomes John@smith.mn</code></strong></p> <p>Not sure what I am doing wrong. </p> <p>This is what I have so far, but this is...
<p>This should do:</p> <pre><code>email['ADDR'] = email['ADDR'].str.replace('.{3}$', 'mn') </code></pre> <hr> <p>If you need to handle variable length domains (<code>.edu</code>, <code>.com1</code>, and so on), you can use:</p> <pre><code>email ADDR 0 john@smith.com 1 test@abc.edu 2 foo@bar.abc...
python|string|pandas|dataframe|replace
4
367,648
46,611,019
Reshaping a 1D bytes object into a 3D numpy array
<p>I'm using FFmpeg to decode a video, and am piping the RGB24 raw data into python.</p> <p>So the format of the binary data is:</p> <pre><code>RGBRGBRGBRGB... </code></pre> <p>I need to convert this into a <code>(640, 360, 3)</code> numpy array, and was wondering if I could use <code>reshape</code> for this and, es...
<p>If <code>rgb</code> is a bytearray with <code>3 * 360 * 640</code> bytes, all you need is :</p> <pre><code>np.array(rgb).reshape(640, 360, 3) </code></pre> <p>As an example:</p> <pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; bytearray(random.getrandbits(8) for _ in range(3 * 4 ...
python|opencv|numpy|multidimensional-array
2
367,649
46,460,054
dataframe/numpy array conversion in Databricks ' Deep Learning Pipelines: scalability issue?
<p>Databricks' Deep Learning Pipelines is a Spark package with Python API which aims to enable Deep Learning models from Tensorflow/Keras to run on Spark and take <code>DataFrame</code> as inputs.</p> <p>This sounds cool, since this would enable to run image recognition (notably) in a distributed way on a distributed ...
<p>It looks like you're describing <a href="https://github.com/databricks/spark-deep-learning/blob/3f668d9b4a0aa2ef6fe05df5bf5c1d705cd2530d/python/sparkdl/estimators/keras_image_file_estimator.py#L39" rel="nofollow noreferrer"><code>KerasImageFileEstimator</code></a> and in that case your observation is correct and it ...
numpy|apache-spark|pyspark|deep-learning|databricks
0
367,650
46,459,511
Compare row N to row N+1 with numpy array operations
<p>please excuse me if this (or something similar) has already been asked.</p> <p>I've got a numpy structured numpy array with > 1E7 entries. Now one of the columns o the array is the timestamp of a specific event. What I'd like to do is filter the array based on timestamps. I'd like to keep the N'th row if the N+1 ro...
<p>This is a good example of using advanced indexing in numpy:</p> <pre><code>this_row = y['timestamp'][:-1] next_row = y['timestamp'][1:] selection = next_row - this_row &gt; T result = y[:-1][selection] </code></pre> <p>The <code>y[:-1]</code> in the last line is necessary because <code>selection</code> has only le...
python|arrays|numpy
1
367,651
46,189,318
How to use multilayered bidirectional LSTM in Tensorflow?
<p>I want to know how to use multilayered bidirectional LSTM in Tensorflow.</p> <p>I have already implemented the contents of bidirectional LSTM, but I wanna compare this model with the model added multi-layers.</p> <p>How should I add some code in this part?</p> <pre class="lang-python prettyprint-override"><code>x...
<p>You can use two different approaches to apply multilayer bilstm model:</p> <p>1) use out of previous bilstm layer as input to the next bilstm. In the beginning you should create the arrays with forward and backward cells of length <em>num_layers</em>. And </p> <pre><code>for n in range(num_layers): cell_fw...
tensorflow|lstm|recurrent-neural-network|bidirectional|multi-layer
5
367,652
46,455,583
Couldn't build proto file into descriptor pool
<p>I am working on AI project, but I am still not very experienced in python.</p> <p>I am trying to <a href="https://github.com/MtDersvan/tf_playground/blob/master/wide_and_deep_tutorial/wide_and_deep_basic_serving.md" rel="noreferrer">build and test this project</a>.</p> <p>I followed all instructions, but I still g...
<p>I ran into a simular issue, this seems to be caused by upgrading tensorflow and non compatible old dependencies.</p> <p>You can try to create a clean enviroment (depending on your system). For me it was a uncompatible version of tensorboard (that was installed with Anaconda and not pip). A uninstall / or reinstall f...
python|tensorflow
1
367,653
46,545,590
Parsing dates in pandas.read_csv with null-value handling?
<p>Consider the following made-up CSV:</p> <pre><code>from io import StringIO data = &quot;&quot;&quot;value,date 7,null 7,10/18/2008 621,(null)&quot;&quot;&quot; fake_file = StringIO(data) </code></pre> <p>I want to read this file using <code>pandas.read_csv</code>, handling nulls with the <code>na_values</code> par...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="noreferrer"><code>to_datetime</code></a> with <code>format</code> and <code>errors='coerce'</code>:</p> <pre><code>date_parser = lambda c: pd.to_datetime(c, format='%m/%d/%Y', errors='coerce') df = pd.read_csv(fake_file...
python|pandas|null
9
367,654
46,249,013
cumulative sum function in pyspark grouping on multiple columns based on condition
<p>I need to create a event_id basically a counter grouping on multiple columns(v_id,d_id,ip,l_id) and incrementing it when delta > 40 to get the output like this</p> <pre> v_id d_id ip l_id delta event_id last_event_flag 1 20 30 40 1 1 N 1 20 30 40 2 1 N 1 20 30 40 ...
<p>In pyspark you can do it using a <code>window</code> function: </p> <p>First let's create the dataframe. Note that you can also directly load it as a dataframe from a csv:</p> <pre class="lang-python prettyprint-override"><code>df = spark.createDataFrame( sc.parallelize( [[1,20,30,40,1,1], [1,2...
python|pandas|apache-spark|pyspark|spark-dataframe
1
367,655
46,444,938
How to optimize a Tensorflow model for Serving
<p>I trained a model with Keras. Now I want to deploy it via Tensorflow serving. Therefore, I converted it to the SavedModel format in that way:</p> <pre><code>K.set_learning_phase(0) K._LEARNING_PHASE = tf.constant(0) # sess = K.get_session() if not os.path.exists(path): os.mkdir(path) export_...
<p>Some thoughts:</p> <ol> <li><p>Be sure you didn't leave any queues (e.g. FIFOQueue) in your serving model. Those are often used in training to hide I/O latencies, but can hurt serving performance.</p></li> <li><p>Consider enabling batching multiple inference requests together into a single call to the TF model/grap...
optimization|tensorflow|keras|tensorflow-serving
2
367,656
46,199,986
Tensorflow: Don't Update if gradient is Nan
<p>I have a deep model to train on CIFAR-10. Training works fine with CPU. However, when I use GPU support, it causes gradients for some batches to be NaNs (I checked it using <code>tf.check_numerics</code>) and it happens randomly but early enough. I believe the problem is related to my GPU.</p> <p>My question is tha...
<p>I could figure it out, albeit not in the most elegant way. My solution is as follows: 1) check all gradients first 2) if gradients are NaNs-free, apply them 3) otherwise, apply fake update (with zero values), this needs gradient override.</p> <p>This is my code:</p> <p>First define custom gradient:</p> <pre><code...
tensorflow|backpropagation
2
367,657
46,326,238
Change DCGAN loss function, that is defined in Tensorflow
<p>I would like to add another term to the generator loss function in <a href="https://github.com/carpedm20/DCGAN-tensorflow/blob/master/model.py" rel="nofollow noreferrer">DCGAN-tensorflow model.py</a> (code lines 127-133). Like this:</p> <pre><code>self.g_loss = self.g_loss + TV(self.G) </code></pre> <p>The problem...
<p>It appears Tensorflow has most of the necessary operations that are available in numpy, so here is the tf version of my numpy code above:</p> <pre><code> def TV(tensor): List =[] for i in range(np.shape(tensor)[2]-1): a = tf.abs(tensor[:, :, i, 0] - tensor[:, :, i+1, 0]); ...
python|tensorflow|dcgan
0
367,658
46,556,224
tensorflow doesn't recognize the graph I import
<p>I'm trying to reuse the graph from another .py file using tf.train.import_meta_graph ()</p> <p><a href="https://imgur.com/xr4AvXO" rel="nofollow noreferrer">test.py</a> is the code which I train/save my model. code below is test.py</p> <pre><code>import tensorflow as tf W = tf.Variable(tf.random_normal([1])) b= t...
<p>The tensor does not exists, because your <code>X</code> has no name. You should write</p> <pre><code>X = tf.placeholder(dtype=tf.float32, name='X') </code></pre> <p>The following code works:</p> <pre><code>import tensorflow as tf X = tf.Variable(tf.random_normal([1])) Y = tf.placeholder(dtype=tf.float32, name='Y...
python|tensorflow
1
367,659
46,327,494
python Pandas DataFrame copy(deep=False) vs copy(deep=True) vs '='
<p>Could somebody explain to me a difference between</p> <pre><code>df2 = df1 df2 = df1.copy() df3 = df1.copy(deep=False) </code></pre> <p>I have tried all options and did as follows:</p> <pre><code>df1 = pd.DataFrame([1,2,3,4,5]) df2 = df1 df3 = df1.copy() df4 = df1.copy(deep=False) df1 = pd.DataFrame([9,9,9]) </...
<p>If you see the object IDs of the various DataFrames you create, you can clearly see what is happening. </p> <p>When you write <code>df2 = df1</code>, you are creating a variable named <code>df2</code>, and binding it with an object with id <code>4541269200</code>. When you write <code>df1 = pd.DataFrame([9,9,9])</c...
python|pandas|dataframe|deep-copy
44
367,660
46,229,822
Find mean of nth item in list of lists in Python
<p>after a lot of searching I haven't been able to find the answer to what seems like a simple question.</p> <p>I have some code that is doing a Monte Carlo simulation and storing the results in a nested list. Here are the results I generate from a 10-trial simulation:</p> <pre><code>[[1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0...
<p>You can use <code>np.mean</code> with <code>axis=0</code>:</p> <pre><code>lst = [[1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1], [1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1], [0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0], [1, 1, 0, 1, 1, 1, 0, 1, 1, 0,...
python|numpy|mean|nested-lists
3
367,661
46,391,692
Obtaining the center of a WKT polygon
<p>I'm using pandas, and a dataset I obtained has a location column in a WKT format. For example:</p> <p><code>hospital.get_value(1,'WKT')</code></p> <pre><code>POLYGON ((-58.4932 -34.5810,-58.4925 -34.5815,-58.4924 -34.5817)) </code></pre> <p>There's a lot more points and with bigger precision in this example, but ...
<p>You almost have WKT, except that a polygons' linear ring needs to be closed.</p> <p>Shapely has a <code>.centroid</code> property to get the center point:</p> <pre><code>from shapely import wkt g = wkt.loads( 'POLYGON ((-58.4932 -34.5810,-58.4925 -34.5815,-58.4924 -34.5817,-58.4932 -34.5810))') print(g.centroi...
python|pandas|polygon|shapely|wkt
3
367,662
46,413,441
pandas df transformation: a better way than df.unstack().unstack()
<p>Trying to convert pandas DataFrames from wide to long format.</p> <p>I've tried to <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow noreferrer"><code>melt()</code></a>, use <a href="https://pandas-docs.github.io/pandas-docs-travis/generated/pandas.wide_to_long.html" re...
<p>Using <code>T</code></p> <pre><code>wide_df.T Out[1108]: greeting name question 0 h s h 1 e t o 2 l a w 3 l c s 4 o k i 5 ! o t 6 v 7 h e g 8 e r ...
python|pandas|dataframe|transformation
3
367,663
46,577,398
TF error: Shapes of both tensors to match
<p>I try to implement a CNN model based on MNIST tutorial on TF website. Here is my code</p> <pre><code>import tensorflow as tf import numpy as np from tensorflow.contrib import learn from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib def cnn_model_fn(features, labels, mode): """M...
<p>You can check this answer, </p> <p><a href="https://stackoverflow.com/questions/40601975/tensorflow-assign-requires-shapes-of-both-tensors-to-match-lhs-shape-20-rhs">Tensorflow Assign requires shapes of both tensors to match. lhs shape= [20] rhs shape= [48]</a></p> <p>Maybe you can install the previous version and...
tensorflow|conv-neural-network
0
367,664
46,508,602
empty dataframe when appending a list to a dataframe
<p>I'm sure this has either been asked before or there is a really simple answer to this, but I'm having a hard time troubleshooting this and finding my exact problem.</p> <p>I have the following code that is basically scraping a table (its actually taking data from a text document that was created out of html) and I'...
<pre><code>df = df.append(list_of_rows,ignore_index=True) </code></pre> <p>I dont think it appends in place, but instead returns a new df.</p>
python|pandas|beautifulsoup
2
367,665
46,549,904
Count the most frequent value and manipulate it
<p>I have a dataframe as follow:</p> <pre><code> User Bought 0 U296 PC 1 U300 Table 2 U296 PC 3 U296 Chair </code></pre> <p>I would like to create 2 columns, one displays the most bought item for a user and th...
<p>Take me long time to make it came true :) By using <code>value_counts</code></p> <pre><code>df[['Most_Bought','Times_bought']]=df.groupby('User').Bought.transform(lambda x : [pd.Series(x).value_counts()\ .reset_index().loc[0].values]).apply(pd.Series) df Out[231]: User Bought Most_B...
python|pandas|numpy|dataframe
2
367,666
46,270,121
python program error: ValueError: setting an array element with a sequence
<p>I am using python burst_detection package link(<a href="https://github.com/nmarinsek/burst_detection/blob/master/README.rst" rel="nofollow noreferrer">https://github.com/nmarinsek/burst_detection/blob/master/README.rst</a>) to try the result. But the program always has some error: ValueError: setting an array elemen...
<p>It looks like is a bug in the <code>burst_detection</code> package. I don't know what that line is supposed to do, but the line</p> <pre><code>q[t] = np.where(cost[t,:] == min(cost[t,:])) </code></pre> <p>will try to set the left side, <code>q[t]</code>, which is a single array element, to the right hand side. Thi...
python|numpy
2
367,667
46,355,651
Understanding Seq2Seq model
<p>Here is my understanding of a basic Sequence to Sequence LSTMs. Suppose we are tackling a question-answer setting. </p> <p>You have two set of LSTMs (green and blue below). Each set respectively sharing weights (i.e. each of the 4 green cells have the same weights and similarly with the blue cells). The first is a ...
<blockquote> <ol> <li>Are we passing the last hidden state only to the blue LSTMs as the initial hidden state. Or is it last hidden state and cell memory.</li> </ol> </blockquote> <p>Both hidden state <code>h</code> and cell memory <code>c</code> are passed to the decoder.</p> <h3>TensorFlow</h3> <p>In <a href="https:/...
tensorflow|keras|lstm
3
367,668
46,220,986
pandas dataframe melt with string values
<p>I have a dataframe that looks like this </p> <pre><code>brand|1 |2 |3 --------------- a |a1|a2|a3 b |b1|b2|b3 </code></pre> <p>And I want the result dataframe to look like this</p> <pre><code>brand|rank|value ---------------- a |1 |a1 a |2 |a2 a |3 |a3 b |1 |b1 b |2 |b2 b |3 |b...
<pre><code>#Create example dataframe a = {'a':['a1','a2','a3'],'b':['b1','b2','b3']} df = pd.DataFrame.from_dict(a) df = df.T df = df.reset_index() df.columns = ['brand','1','2','3'] </code></pre> <p>To transform as you demonstrate, try: </p> <pre><code>pd.melt(df, id_vars =['brand']) </code></pre> <p><a href="https...
python|pandas|dataframe|melt
1
367,669
46,333,976
indexing a tensor with an object of type torch.LongTensor
<p>I am new to using Pytorch and I receive this error when running my code: </p> <p>TypeError: indexing a tensor with an object of type torch.LongTensor. The only supported types are integers, slices, numpy scalars and torch.LongTensor or torch.ByteTensor as the only argument.</p> <p>Can you please point me and the r...
<p>there are still problems with your question. You have not shared complete code which can reproduce your error.From the errors it is clear that you have a problem in your model's forward function.The error is occurring in the below line.</p> <pre><code>text_batch = torch.stack(batch['text'], 0)[:, indices] </code></...
python|pytorch
0
367,670
46,619,945
Finding mean duration(H:M:S) in python pandas
<p>I am trying to find the mean duration in a pandas dataframe. I have tried the following code and receive the error: </p> <pre><code>TypeError: Could not convert 1:10:4200:38:5800:42:142:30:4100:19:22 to numeric </code></pre> <p>Code:</p> <pre><code>import pandas as pd duration=['1:10:42','38:58','42:14','2:30:4...
<p>Demo:</p> <pre><code>In [78]: s = pd.Series(['1:10:42','38:58','42:14','2:30:41','19:22']) In [79]: s Out[79]: 0 1:10:42 1 38:58 2 42:14 3 2:30:41 4 19:22 dtype: object In [80]: s[s.str.match(r'^\d+\:\d+$')] = '00:' + s In [81]: s Out[81]: 0 1:10:42 1 00:38:58 2 00:42:14 3 2:30...
python|pandas|datetime|mean
4
367,671
46,533,210
Linearly separating a Gaussian Filter and calculating with Numpy
<p>I have a <code>2d</code> <code>numpy</code> <code>array</code> containing <code>greyscale</code> pixel values from <code>0</code> to <code>255</code>. What I want to do is to create a <code>gaussian filter</code> <strong>from scratch</strong>. I have already written a function to generate a <code>normalized</code> g...
<p>For anyone interested, the problem was from the fact that The function <code>gaussianKernel</code> returned the <code>2d</code> <code>kernel</code> <code>normalised</code> for use as a <code>2d</code> <code>kernel</code>. This meant that when I split it up into its <code>row</code> and <code>column</code> components...
python|numpy|convolution|gaussianblur
1
367,672
46,610,007
Dropna isn't dropping, fillna isn't filling and my list comprehension can't comprehend how to get rid of nans (python)
<p>I have a case where I am adding data from one dataframe to another, but I can't rid of the nan values.</p> <p>Example data</p> <pre><code>df1 = pd.DataFrame( { 'Journal' : ['US Drug standards.','Acta veterinariae.','Bulletin of big toe science.','The UK journal of dermatology.'], 'ISSN_1': ...
<p>There are a few things going on here. The first is that the question shows that <code>'nan'</code> is in the dataframe, however the comment suggests that this should actually be <code>nan</code> (string versus null). </p> <p>The second is that you are storing lists, and then strings of those lists in a dataframe wh...
python|pandas|nan
1
367,673
46,181,432
How do I group elements of a numpy array by two?
<p>I am facing the following problem. I have an <code>np.array</code>, of the following structure:</p> <pre><code>[A, B, C, D, E, F] </code></pre> <p>where <code>A..F</code> are numpy arrays, guaranteed to be of the same size. I am hoping to achieve the following shape:</p> <pre><code>[ A | B, C | D, E | F ] </code>...
<p>A manual way to compose a NumPy array out of smaller blocks is to use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.block.html" rel="nofollow noreferrer"><code>np.block</code></a> or <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.bmat.html" rel="nofollow noreferrer"><code>n...
python|numpy|multidimensional-array
2
367,674
46,374,113
'IndexError:' when loading saved Tensorflow graph to continue training
<blockquote> <p><strong>Summary</strong>: I have a Training routine that attempts to reload a saved graph for continued training but instead produces an <code>IndexError: list index out of range</code> when I try to load the optimizer with <code>optimizer = tf.get_collection("optimizer")[0]</code>. I experienced seve...
<p><code>optimizer = tf.get_collection("optimization")[0]</code> was throwing an <code>IndexError: list index out of range</code> when trying to restore the saved graph for the simple reason that it wasn't "named" when the graph was built and so there's nothing in the graphed called "optimizer".</p> <p>The training st...
tensorflow
0
367,675
46,281,594
Rolling cumulative product between dates
<p>I have data (dataframe called returns) that looks like this</p> <pre><code>DATE TICKER RETURN_DATA 2010-01-01 xxx 0.05 2010-01-01 yyy 0.01 2010-01-02 xxx 0.02 2010-01-02 yyy 0.08 ..... 2010-01-29 xxx 0.11 2010-01-29 yyy 0.01 </code></pre> <p>what I t...
<p>As mentioned by @Uvar, pandas dataframe supports an offset in window declaration. You need to create the dataframe and convert the index into datetime format. Then use the rolling function</p> <pre><code>a DATE TICKER RETURN_DATA 0 2010-01-01 xxx 0.05 1 2010-01-01 yyy 0.01 2 2010-01-0...
python|pandas|datetime|rolling-average
0
367,676
58,311,702
Read all columns in as string in pandas
<p>I want to read the entire dataframe as string.</p> <p>The # of columns changes sometimes in the dataframe I pass, so I don't want to hardcode which columns specifically to read in.</p> <p>The problems I'm dealing with are (a) lots of NaNs considered as floats when I want to consider as strings in many columns, (b)...
<p>If we are talking about reading <code>*.csv</code>, then consider using <code>dtype=str</code> as one of the parameters for <code>pd.read_csv</code>. <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer">Check documentation</a></p> <p>If you already have...
python|pandas
3
367,677
58,238,133
Python web scraping and saving to a pandas dataframe
<p>I am trying to web scrape a house listing on remax page and save that information to Pandas dataframe. But for some reason, it keeps giving me KeyError. Here is my code:</p> <pre><code>import pandas as pd import requests from bs4 import BeautifulSoup url = 'https://www.remax.ca/ab/calgary-real-estate/720-37-st-nw-w...
<p>You can try this. I assume that you want only the text within the <code>&lt;span&gt;</code> tags. But feel free to adapt from my worked example.</p> <pre><code>import pandas as pd import requests from bs4 import BeautifulSoup url = 'https://www.remax.ca/ab/calgary-real-estate/720-37-st-nw-wp_id251536557-lst' respon...
python|pandas|dataframe|web-scraping|beautifulsoup
3
367,678
58,292,875
Row-wise Broadcast of arbitrary function in numpy
<p>I have a matrix of vectors where each row is a vector. I want to take the mean of all the vectors, then calculate the cosine distance between each vector and this mean, returning an array of distances.</p> <pre><code>&gt;&gt;&gt; x = arange(1,10).reshape(3,3) array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) &gt;&gt;&...
<p>You need to reshape your mean array to be 2D.</p> <pre><code>&gt;&gt;&gt; from scipy.spatial.distance import cdist &gt;&gt;&gt; cdist(x, m.reshape(1, -1), metric='cosine') array([[2.53681538e-02], [2.22044605e-16], [1.80910731e-03]]) </code></pre>
python|numpy|scipy|array-broadcasting
2
367,679
58,473,885
How to get evaluated gradients from keras model using tensorflow 2?
<p>I'm trying to obtain the gradients from a keras model. The backend function keras.backend.gradients creates a symbolic function which needs to be evaluated on some specific input. The following code does work for this problem but it makes use of the old tensorflow sessions and in particular of feed_dict. </p> <pre ...
<p>In tensorflow-2 you can get gradients very easily using gradient tf.GradientTape().</p> <p>I am citing the official tutorial code here - </p> <pre><code>@tf.function def train_step(images, labels): with tf.GradientTape() as tape: predictions = model(images) loss = loss_object(labels, predictions) gradi...
tensorflow|keras
1
367,680
58,198,722
Return relevant matrix rows if any combinations of elements of one column sums to x
<p>I have a matrix shown below. The next step in the project is to identify spreads. These are being defined as a series of trades composed of at least two different contracts but all of the same product type. The trades making up the spread must happen within 10 minutes and the total volume of buy must equal that of s...
<p>I assume you know how to properly slice the time frames. Then you can create a list which contains all buy/sell values where you count the sell values as a negative ones.</p> <p>At this point you are only missing the list that contains all combinations of rows in that time window. This list can be created with the ...
python|numpy
0
367,681
58,277,118
what type of data receive as parameters the method predict of a LinearRegression instance from sklearn?
<p>I am doing an example of <strong>Linear Regression</strong> with <strong>sciki-learn</strong> but i am confuse about the <strong>predict</strong> method;</p> <p>In <a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html" rel="nofollow noreferrer">Scikit-Learn</a> you wi...
<blockquote> <p>Note: array_like does not give me enough information of what type of data a predict method could receive. Remember that with Pandas we deal with Serie and DataFrame object.</p> </blockquote> <p>For linear regression in scikit-learn you need to use numeric types of your columns (int oder float), the o...
python-3.x|pandas|machine-learning|scikit-learn|data-science
0
367,682
58,531,274
Assinging variable value to a new column in pandas DataFrame
<p>I have created 3 new variables a,b and c using certain conditions. Now I want to assign these variables to a new column in a pandas DataFrame again using some conditions.</p> <p>I want a code something like what I have written below but in a smarter way. The code below is working fine but it's not a smart solution....
<p>You want<code>numpy.select</code>:</p> <pre><code>cond=[(df2['month'] == month) for month in df2['month'].unique()] values=[a, b, c] df2['dest_col'] = np.select(cond,values) </code></pre>
python|python-3.x|pandas|loops
2
367,683
58,442,658
Training Multiclass input output in keras
<p>I am trying to train 16-bit binary input and 16-bit binary output for ANN using Keras. the problem is traing accuracy merely reaches 15%. What could be the best way to train datatypes like</p> <pre><code>Xtrain Ytrain 1,0,1,0,1,1,1,0,0,0,0,0=1,0,1,0,1,0,1,1,1,1 1,1,1,0,0,0,0,1,1,1,1,1=0,0,0,0,...
<p><strong>First One:</strong></p> <p>I'm thinking that your problem is a Sequence to a Sequence problem so i Think you need Recurrent Neural Network with uni Directional RNN to get the pattern how we encoding number and convert it : <br> <a href="https://machinelearningmastery.com/sequence-classification-lstm-recurr...
python|tensorflow|keras|training-data
0
367,684
58,470,096
How to split the column with delimiter
<p>I have a <code>.csv</code> and I need to split the \n with ,</p> <pre><code>name,address 711-2880,Mankato\n96522\n(257) 563-7401 971-2880,CA\n965\n(01) 563-7401\nNebraska </code></pre> <p>This is my code:</p> <pre><code>import pandas as pd df = pd.read_csv('test.csv') df.address = df.address.str.split('\n') </cod...
<p>Your data in the <code>address</code> column is a list, not a string. You first need to access the first element of this list (which is a string), and then do your split.</p> <pre><code># Sample Data: df = pd.DataFrame({ "name": ['711-2880', '971-2880'], "address": [['Mankato\n96522\n(257) 563-7401'], ['C...
python|pandas
0
367,685
58,385,699
Generate missing values on the dataset based on ZIPF distribution
<p>Currently, I want to observe the impact of missing values on my dataset. I replace data point (10, 20, 90 %) to missing values and observe the impact. This function below is to replace a certain per cent data point to missing. </p> <pre><code>def dropout(df, percent): # create df copy mat = df.copy() # ...
<p>Zipf distributions are a family of distributions on 0 to infinity, whereas you want to delete values from only 5 discrete columns, so you will have to make some arbitrary decisions to do this. Here is one way:</p> <ol> <li>Pick a parameter for your Zipf distribution, say a = 2 as in the example given on the <a href...
python|pandas|numpy|scipy|zipf
0
367,686
58,282,008
Problem saving HTML table into excel using Python
<p>This is my first time using Python and I am trying the <strong>scraping</strong> method and putting together codes available on the net and currently I'm stuck on saving the output into an Excel file.</p> <p>Ok, so first I need to read an email from Outlook and get the data inside. But it's on table format, meaning ...
<p>To use pandas to_excel() method you first need a pandas DataFrame</p> <p>assuming nodes1 is a dictionary object:</p> <pre><code>data_frame = pd.DataFrame(data=nodes1) data_frame.to_excel('label_name') </code></pre>
python|excel|pandas
2
367,687
58,196,322
factories and unique numbers in a pandas dataframe
<p>I have a dataframe that looks like:</p> <pre><code>import pandas as pd import random d={'ID':["x1", "x2", "x1"], 'CUSIP':['a', 'b', "#NULL"], 'ISIN':["#NULL", "#NULL", 'I']} df=pd.DataFrame(data=d) df </code></pre> <p>I am trying to replace all the '#NULL' with a unique number suffix. So, the output table will l...
<p>Create <code>Series</code> and add new values of filtered rows with <code>range</code>, last reshape back:</p> <pre><code>s = df.unstack() m = s == '#NULL' s.loc[m] = [f'#NULL_{x + 1}' for x in range(m.sum())] df = s.unstack().T print (df) ID CUSIP ISIN 0 x1 a #NULL_2 1 x2 b #NULL_3 2 ...
python|pandas
2
367,688
58,507,325
Is there a way to access inputs when creating custom loss?
<p>I have a quite complex CNN network, where I have <strong>3 different inputs</strong> and <strong>6 outputs</strong>. I need to create a loss function, where one of the inputs influences the loss computation.</p> <p>I tried going along <a href="https://www.kdnuggets.com/2019/04/advanced-keras-constructing-complex-cu...
<p>I solved this by adding identical layer (which I need) to all outputs, then custom loss takes information from that layer and applies it on default calculations of custom MSE as described in the question.</p> <p>Still the question of how to access network input in loss remains unanswered and I am interested in any ...
python|tensorflow|neural-network
0
367,689
58,558,751
Pandas using apply function to filter year and get mean value of months
<p>in the following dataframe there are three columns year, month, vals. I am trying to filter out values for year, below a certain threshold (i.e 2007) and then obtain the mean vals for grouped months. (i.e month 9 has three values for respective years 2006,2001,2006 (less than year 2007), so the combined total (2.9 +...
<p>First filter by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> and then aggregate <code>mean</code>:</p> <pre><code>df = df2.loc[df2['year'] &lt; 2007, 'vals'].groupby(df2['month']).mean().reset_index() #alt...
python|pandas
2
367,690
58,496,483
Pandas dataframe imports and renders incorrectly and causes UnicodeDecodeError
<p>I am trying to import an csv that contains Chinese characters.</p> <p>this command is to download the csv file</p> <pre><code>!wget -O wm.csv https://raw.githubusercontent.com/hierarchyJK/compare-LIBSVM-with-Linear-and-Gassian-Kernel/master/%E8%A5%BF%E7%93%9C3.0.csv </code></pre> <p>The repository is not mine, so...
<p>The encoding is 'GB18030'. I found this by opening the file in a text editor and checking the suggested encoding. Github actually also shows you the encoding when you go to the github link and click on edit file</p>
python|pandas
1
367,691
58,297,060
How to use num_elements from TensorFlow?
<p>I just want the number of elements in my tensor, regardless of shape.</p> <p>I see in the documentation <a href="https://www.tensorflow.org/api_docs/python/tf/TensorShape#num_elements" rel="nofollow noreferrer"><code>num_elements</code></a> serves my purpose. However, if I try to use it as <code>myTensor.num_elemen...
<p>This method belongs to <code>TensorShape</code> instead of <code>Tensor</code>. You can get the number of elements like this</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf a = tf.random.uniform((1,16,23)) a.shape.num_elements() # 368 </code></pre>
python|tensorflow|tensor
1
367,692
58,277,060
Is it possible to get the date-year attribute of a period index or period range?
<p>I want to obtain the Fiscal Year of a company that has its quarters end on the last Friday of the quarter where the fiscal year start is May and the fiscal year end month is April. I get the calendar year of the quarter end year when I ask for the calendar year attribute of a Periodindex (and I understand why and th...
<p>I don't know if this is pythonic, but I solved the issue by leveraging loc:</p> <pre><code>df.loc[((df.dates.dt.month &gt;= 5) | ((df.dates.dt.month == 4) &amp; (df['fscl_quarter_num'] == 1))), 'fiscl_year'] = df.dates.dt.year + 1 df.loc[((df.dates.dt.month &lt;= 4) &amp; (df['fscl_quarter_num'] != 1)), 'fiscl_year...
python|pandas|dataframe
0
367,693
58,385,708
Combine columns in pandas to create a new column
<p>Hello I am working on pandas dataframe and I want to create a column combining multiple columns and applying condition on them and I am looking for a smart way to do it.</p> <p>Suppose the data frame looks as</p> <pre><code>A B C D 1 0 0 0 0 1 0 0 0 0 1 0 1 0 1 0 1 1 1 0 0 0 ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>DataFrame.apply</code></a> + <code>join</code>. Select column names using <code>x.index</code>( <strong>note that <code>axis = 1</code> is used</strong>) + <a href="https://pandas.pyda...
python-3.x|pandas|dataframe|feature-engineering
5
367,694
58,208,517
Add suffix to column names that don't already have a suffix
<p>I have a data frame with columns like </p> <pre><code>Name Date Date_x Date_y A A_x A_y.. </code></pre> <p>and I need to add _z to the columns (except the Name column) that don't already have _x or _y . So, I want the output to be similar to </p> <pre><code>Name Date_z Date_x Date_y A_z A_x A_y... </c...
<p>How about:</p> <pre><code>df.columns = [x if x=='Name' or '_' in x else x+'_z' for x in df.columns] </code></pre>
python|python-3.x|pandas
4
367,695
58,300,357
How to find the shapes of activations in the different layers of a pretrained InceptionResNetV2 model in Keras - Tensorflow 2.0
<p>I have load the inceptionResNetV2 Keras model </p> <pre><code>base_model = tf.keras.applications.inception_resnet_v2.InceptionResNetV2(include_top=False, weights='imagenet') </code></pre> <p>I want to find the shapes of the activations outputed by different layers -- assuming a standard input size of (299x299). <...
<p>You can put the <code>input_shape</code> in the function by</p> <pre><code>base_model = tf.keras.applications.inception_resnet_v2.InceptionResNetV2(include_top=False, weights='imagenet', input_shape=(299, 299, 3)) </code></pre> <p>But this will raise an error if input images aren't 299*299 so better use it only wh...
python|tensorflow|keras|shapes|activation
1
367,696
58,387,701
How to solve the "ImportError: cannot import name 'control_flow_ops' from 'keras.backend.load_backend'"?
<p>I have added this two lines in the <strong>init</strong>.py in C:\Users\xxy19\Anaconda3\envs\tensorflow-gpu\Lib\site-packages\keras\backend:</p> <pre><code>from .load_backend import control_flow_ops from .load_backend import set_image_dim_ordering </code></pre> <p>But it still exists:</p> <pre><code>ImportError: ...
<p>Try this</p> <pre><code>import tensorflow as tf tf.python.control_flow_ops = tf </code></pre>
python|tensorflow|keras
0
367,697
58,567,234
How to calculate binomial cumulative density function with python
<p>I have the following binomial distribution:</p> <p>Last year, the number of new buildings in Community Board 12 and Community Board 11 in the bronx was 347. Of those 347, 107 took place in Community Board 12. </p> <p>If we randomly select 70 of the 347 new buildings, the probability distribution would be:</p> <p>...
<p>Since the <code>cdf(x)</code> of a probability distribution is the integral from negative infinity to <code>x</code>, the integral of <code>x</code> to positive infinity is <code>1-cdf(x)</code>. So for your problem it would simply be:</p> <pre><code>probabilityGreaterThan20inCommunity12 = 1 - binom.cdf (20, 70, 10...
python|numpy|scipy|binomial-cdf
1
367,698
58,256,867
AttributeError: 'DataFrame' object has no attribute 'NET_NAME'
<p>python 3.7 A task. Add a new column in the received date frame based on two conditions: if the value in the NET_NAME column is equal to one of the list and the value in the ECELL_TYPE column is LTE, then assign the value to the SHARING column from the ENODEB_NAME column.</p> <pre><code>import csv import os import p...
<p>Your traceback contains: <em>DataFrame object has no attribute NET_NAME</em>, meaning actually that this <em>DataFrame</em> has no <strong>column</strong> of this name.</p> <p>This message pertains to <em>ecell_sum_df.NET_NAME</em> (also contained in the traceback), so let's look how you created this DataFrame (sli...
python-3.x|pandas
0
367,699
58,457,083
Can i share the legends of multiple pandas plots in different axes?
<p>I would like to plot muiltiple stacked barplots in different axes, using Pandas and matplotlib</p> <p>The problem with the following minimal example is that it creates a legend for each axis.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt d1 = {'a': 1, 'b': 10} d2 = {'a': 5, 'b': 5} df = pd.Da...
<p>Yes, if all the legends are the same, you can grab one of them and place it on <code>plt</code>:</p> <pre><code># grab the legend handles and lables h, l = axes[0].get_legend_handles_labels() # remove all the subplot legends for ax in axes: ax.get_legend().remove() # add one legend on `plt` plt.legend(h,l, loc=(1...
python|pandas|matplotlib
3