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
370,200
57,633,584
Manipulating output of neural network
<p>I have a neural network that takes an input of (m, 2, 3, 96, 96) and outputs (m, 2, 128). I'm trying to turn that output into (m, 1, 128) by subtracting output[m][0][0] - output[m][0][1] and then into (m, 1) by feeding the 1x128 outputs into a dense layer</p> <p>I've tried Lambda and keras.backend.Subtract layers i...
<pre><code>X = Lambda(lambda x: return x[:,0] - x[:,1])(X) X = Dense(...)(X) </code></pre>
python|tensorflow|keras|neural-network
0
370,201
57,624,333
How do I print all values associated to duplicate keys?
<p>It took me a while to realize that my printed dictionary is not outputing all values. My keys are a sum function and my values are unique strings. e.g.:</p> <pre><code>{(target_test == pred_dict['p0']).sum(): str(alg_dict[0].__name__), (target_test == pred_dict['p1']).sum(): str(alg_dict[1].__name__), (target_test ...
<p>You can use Pandas Index.duplicated() like:</p> <pre class="lang-py prettyprint-override"><code> import pandas as pd idx = pd.Index([100, 50, 45, 100, 12, 50, None]) idx.duplicated(keep = False) </code></pre> <p>Result is:</p> <pre><code> array([ True, True, False, True, False, True, False]) </code></pre>
python|pandas
0
370,202
57,481,676
In a dataframe how can I count a specific value and then select the value with the highest count to create another dataframe?
<p>I am looking for a way to select specific rows of data from a dataframe. Here is an example of the dataframe.</p> <pre><code>Id \ Value 0 002D85EF 5 1 002D85EF 1 2 002D85EF 5 3 00557D1B 1 4 00557D1B 1 5 00557D1B 5 6 0063EAFB 5 7 0063EAFB 5 8 0063EAFB 5 9 006DE4E3 ...
<p>(Since i can not comment, i directly try to give You a hint, probably not the answer.)</p> <p>try:</p> <pre class="lang-py prettyprint-override"><code>df.groupby('Value').max() </code></pre> <p>or </p> <pre class="lang-py prettyprint-override"><code>df.groupby('Value').count().max() </code></pre> <p>btw. the gi...
python|pandas|dataframe
1
370,203
57,543,787
Why does broadcasting give an empty tensor?
<pre><code>x = torch.randn(1, 1, 0) y = torch.randn(4, 1, 1) </code></pre> <pre><code>(x+y) </code></pre> <p>tensor([], size=(4, 1, 0))</p> <pre><code>(x + y).shape </code></pre> <p>torch.Size([4, 1, 0])</p> <p>shouldn’t it have been 4, 1, 1, just y?</p>
<p>It is so by design. </p> <p>Tensor <code>x</code> has one dimension 0.</p> <pre><code>import torch x = torch.randn(1, 1, 0) print(x) # tensor([], size=(1, 1, 0)) </code></pre> <p>These tensors are limited and I think the design is bad, but this is my opinion. For instance such tensors cannot be concatenated.</p> ...
pytorch|broadcasting
0
370,204
57,369,039
How to plot 2 histograms on 1 graph from pandas dataframe
<p>I am trying to plot one histogram that shows the frequency counts of hotwings consumed by gender. It is two histograms in 1 plot. </p> <pre> id Hotwings Beer Gender 1 4 24 F 2 5 0 F 3 5 12 F 4 6 12 F 5 7 12 F 6 7 12 F 7 7 24 M 8 8 24 F 9 8 0 M 10 8 12 M 11 9 ...
<p>This will show your bar in same graph</p> <pre><code>plt.bar(dta[dta['Gender']=='F']['Hotwings']-1, dta[dta['Gender']=='F']['Beer'], 0.50, align='center', alpha=0.5, color='b') plt.bar(dta[dta['Gender']=='M']['Hotwings']+1, dta[dta['Gender']=='M']['Beer'], 0.50, align='center', alpha=0.5, color='r') plt.show() </c...
python|pandas|matplotlib
1
370,205
57,660,161
Network bug - Inception v1 isn't training
<p>I am trying to use the Inception model (GoogLeNet) from this link <a href="https://github.com/tensorflow/models/blob/master/research/slim/nets/inception_v1.py" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/research/slim/nets/inception_v1.py</a> which is implemented by Google using the Te...
<p>I managed to find the solution. I had to put the argument scope of inception before calling it, something like this:</p> <pre class="lang-py prettyprint-override"><code>with slim.arg_scope(inception_v1.inception_v1_arg_scope()): Z = inception_v1.inception_v1(inputs,num_classes = n_y,dropout_keep_prob=1,global_p...
tensorflow|conv-neural-network
0
370,206
57,458,523
Group by weighted mean, allowing for zero value weights
<p>I want to take the weighted mean of a column in a group-by statement, like this</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'group': ['A', 'A', 'A', 'B', 'B', 'B'], 'value': [0.4, 0.3, 0.2, 0.4, 0.3, 0.2], 'weight': [2, 2, 4, 3, 1, 2]}) df_grouped...
<p>If you need it to be done in a one-liner it is possible to check whether the Group By Sum is equivalent to zero using a ternary operator inside the lambda as follows. If the group by sum is zero then use the regular mean.</p> <pre><code>df.groupby('group')[['value', 'weight']].apply(lambda x:sum(x['value'])/len(x['...
python|pandas|group-by|weighted-average
2
370,207
57,372,037
how to fix ImportError: cannot import name 'swapaxes' || can't initialize sys standard streams
<p>I installed tensorflow-gpu and since then my project import's went crazy.</p> <p>eventually, after reinstalling most of my packages it comes down to this error which I can't fix:</p> <pre><code>Fatal Python error: Py_Initialize: can't initialize sys standard streams Traceback (most recent call last): File "C:\Pr...
<p>Resolved by starting a new project in Pycharm and copying all the files and folders to it.</p>
python-3.x|numpy|tensorflow|scipy|python-import
0
370,208
57,570,793
Why my tensor defined in forward function can not be transformed in to cuda variable autonomously?
<p>In PyTorch, in the <code>forward</code> function of a model </p> <pre><code>class my_model(torch.nn.module): ...... def forward(): self.a=torch.zeros(1) #blabla </code></pre> <p>After <code>model.cuda()</code>, why <code>self.a</code> is still a <code>cpu</code> variable?</p>
<p>This is so by design. </p> <p>Only the tensors which are a part of the model will move with <code>model.cuda()</code> or <code>model.to("cuda")</code>.</p> <p>These tensors are registered with <code>register_parameter</code> or <code>register_buffer</code>. This also includes child modules, parameters and buffers ...
python|pytorch|torch
3
370,209
57,583,276
Fitting data from scatterplot
<p>I have a Dataframe with two columns which I scatter plotted and got something like the following picture:</p> <p><img src="https://i.stack.imgur.com/t9ja6.jpg" alt="Scatterplot"></p> <p>I would like to know if there is a way to find a distribution curve who best fits it, since the tutorials I've found focus in the...
<p>You can try fitting different degrees of polynomial using <code>numpy.polyfit</code>. It takes x, y and degree of fitting polynomial as inputs. </p> <p>You can write a loop which iterates from 1 to say 5 for the degrees. Plot the f(x) using the coefficients which are returned by the function.</p> <p>for d in degre...
python|pandas|matplotlib
0
370,210
57,372,937
The relation between toco, tflite_convert and TFLiteConverted
<p>I am a bit confused by how these 3 relate to each other. As far as I understand <code>tflite_convert</code> is just a command-line interface to <code>TFLiteConverter</code> class. Is that right? </p> <p>Also, by reading some docs I get it that <code>toco</code> is deprecated and should not be used, whereas <code>tf...
<p>The TensorFlow Lite converter comes with a Python API and a CLI. The cli can be accessed through tflite_convert, and the Python API is accessed through <code>tf.lite.TFLiteConverter</code></p> <p>As you mentioned, toco is deprecated in favour of TFLiteConverter.</p>
tensorflow|tensorflow-lite
2
370,211
57,525,456
Libtorch: cannot load traced lstm scriptmodel
<p>I save a pytorch ScriptModule and load it using libtorch. However I encountered the following problem <img src="https://wx1.sinaimg.cn/mw690/93098207gy1g61u188w88j20sw0e1acr.jpg" alt="jpg"></p> <p>I use linux subsystem under win10 and I use pytorch 1.2. </p> <p>To reproduce my problem, you could run this piece of ...
<p>I know what's wrong now. The libtorch version is of wrong version on the official website. It's ok now when I use the correct libtorch 1.2. Refer to issue <a href="https://github.com/pytorch/pytorch/issues/24382" rel="nofollow noreferrer">https://github.com/pytorch/pytorch/issues/24382</a> </p>
pytorch|jit|libtorch
0
370,212
57,701,525
How to bound input dimension for differential_evolution_minimize in tensorflow-probability?
<p>Unlike in <a href="https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.optimize.differential_evolution.html" rel="nofollow noreferrer">scipy's implementation</a> of differential evolution (DE), there is no direct way to define bounds for my inputs in <a href="https://www.tensorflow.org/probability/api_...
<p>Based on my experience with tfp-0.6 and tf-1.13.1, Code block III could be rewritten as follows:</p> <pre><code>width = ... #some Python float height = ... #some other Python float bijectors = [ tfb.Chain([tfb.AffineScalar(scale=width), tfb.Sigmoid()]), tfb.Chain([tfb.AffineScalar(scale=height), tfb.Sigmoi...
python|tensorflow|tensorflow-probability
1
370,213
57,485,023
How to rename multiple columns using a wildcard in pandas
<p>I have a list of columns defined like this:</p> <pre><code>col_list=['Name_x','Num_x'] </code></pre> <p>I have a df. Any column that matches the colname is col_list, I wish to remove the_x from the col_name.</p> <p>How can I do this?</p>
<pre class="lang-py prettyprint-override"><code># df.columns # Index(['Name_x', 'Num_x', 'test_x'], dtype='object') col_list=['Name_x','Num_x'] df.columns = np.where( df.columns.isin(col_list), df.columns.str.replace(r'_x$', ''), df.columns) # df.columns # Index(['Name', 'Num', 'test_x'], dtype='object') </code>...
python|pandas
1
370,214
57,550,277
Convert index into columns Pandas
<p>I'm having the following multi-index data frame:</p> <pre><code>import pandas as pd item_id = [3,3,3,3,3,3,3,3,7,7,7,7,7] target = [0,0,0,1,1,2,2,2,0,0,0,1,2] label = ['a','a','a','b','b','c','c','c','a','a','a','b','c'] df = pd.DataFrame({'item_id': item_id, 'target': target, 'label': label}) print(df) group =...
<p>You can use <strong>unstack()</strong> to solve to problem</p> <pre><code>df_test = group['label'].unstack() df_test.head() </code></pre> <p>Result:</p> <pre><code>target 0 1 2 item_id 3 a,a,a b,b c,c,c 7 a,a,a b c </code></pre>
pandas|pandas-groupby
0
370,215
57,550,413
For every row, I want to make first row of every column as a new row
<p>I am working with Python Pandas and I have a following table that consists of many rows:</p> <pre><code>Date X X Date Y Y 0 2014-03-31- 0.390- 2014-04-24- 1.80 1 2014-04-01- 0.385- 2014-04-25- 1.75 </code></pre> <p>What I want to do is for every <code>index(row)</code>, take the value of <...
<p>You can try the following:</p> <pre><code>new_df = pd.DataFrame() for index, row in df.iterrows(): first_date = row['Date X'] second_date = row['Date Y'] x = row['X'] y = row['Y'] to_add = pd.DataFrame(data={'Dates': [first_date, second_date], 'params': [x, y]}) new_df = new_df.append(to_add...
pandas|data-transform
0
370,216
57,367,597
Are there some functions in Python for generating matrices with special conditions?
<p>I'm writing dataset generator on Python and I got following problem: I need a set of <strong>zero-one matrices</strong> with <strong>no empty columns/rows</strong>. Also the ratio between zeros and ones should be <strong>constant</strong>.</p> <p>I've tried to shuffle zero-one list with fixed ratio of zeros and one...
<p>If I understand the task, something like this might work:</p> <pre><code>import numpy as np from collections import defaultdict, deque def gen_mat(n, m, k): """ n: rows, m: cols, k: ones, """ assert k % n == 0 and k % m == 0 mat = np.zeros((n, m), dtype=int) ns = np.repeat(np.arang...
python|numpy|matrix|random|probability
1
370,217
57,665,895
split entries dictionary entries for dataframe python
<p>I have the following dataframe</p> <pre><code> item1 item2 item3 777 {'value1':x, 'value2':a} {'value1':y, 'value2':a} {'value1':z, 'value2':c} 778 {'value1':x, 'value2':b} {'value1':z, 'value2':c} { } 779 {'value1':y, 'value2':a} {'v...
<p>You may achieve <em>exacly</em> your output via a simple dict comprehension and <code>str.get()</code></p> <pre><code>pd.concat([pd.DataFrame({ col : df[col].str.get('value1'), 'value2': df[col].str.get('value2')}) \ for col in df.columns], axis=1) </code></pr...
python|pandas|dataframe
1
370,218
57,678,251
Getting all row combinations from a pandas dataframe based on certain column conditions?
<p>I have a Pandas Dataframe that stores a food item on each row in the following format - </p> <pre><code>Id Calories Protein IsBreakfast IsLunch IsDinner 1 300 6 0 1 0 2 400 12 1 1 0 . . . 100 700 25 ...
<p>You can use the approach described in <a href="https://stackoverflow.com/a/29780529/189418">this answer</a> to generate a new DataFrame containing all the combinations of three rows from your original data:</p> <pre class="lang-py prettyprint-override"><code>from itertools import combinations import pandas as pd #...
python|pandas
1
370,219
57,471,607
How to make a table from a class nesting dictionaries in python?
<p>I'm trying to make a table to do fuzzy string matching with data pulled from HubSpot database. Luckily I found a library which allows me to connect to the server through RESTful API. </p> <p>The results that I get look like: </p> <pre><code> from hubspot.connection import APIKey, PortalConnection from hubspot.con...
<p>Following your edit this seems like it would work directly:</p> <pre><code>pd.DataFrame([contact.properties for contact in get_all_contacts(connection)]) </code></pre> <p>If you have a list of dictionaries with the same keys Pandas is smart enough to use keys as column names and the values to build said columns.</...
python|pandas|python-2.7
0
370,220
57,354,698
Paralleling python 'for' loop with 'if' statement using tensorFlow
<p>Could anyone please help convert this code to TensorFlow? I am attempting to find the data point positions in the set for which the CNN outputs a value bigger than 0.95, so as to aid in pseudo-labeling.</p> <pre><code> positions = [] for t in range(int(dataset.shape[0] // batch_size)): data = dataset.n...
<p>This could be implemented as follows:</p> <pre><code>tf.where(tf.greater(output, 0.95)) </code></pre> <p>This returns a tensor with the indices where <code>output</code> is greater than 0.95.</p>
python|for-loop|tensorflow|if-statement
0
370,221
57,490,642
What is the Pythonic way to pull conditional cell value from pandas dataframe
<p>My data frame, <code>new_df</code>, includes 3 columns: "name", "gender", and "Total". I need to pull the value from the total column per a combination of name and gender.</p> <pre><code> name gender Total 357328 Barbara F 3114462 357329 Patricia F 3846693 357330 Betty F ...
<p>You can combine <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc<...
python|pandas
1
370,222
57,594,002
\copy CSV with double quotes inside field to table
<p>This is how the CSV file looks like:</p> <pre><code>c1,c2,c3,c4,c5,c6 "153";"0";"5";"39264";"hey";"4 spaces; not"can;hen" thanks!" </code></pre> <p>The last field contains double quotes and semicolons inside the string. When I try to copy the file to the table like so: </p> <pre><code>psql -U user -d postgres -c ...
<p>You cannot alter the command, you have to alter the file, because the file is not syntactically correct CSV.</p> <p>You'd have to double the double quotes that are <em>not</em> field delimiters:</p> <pre><code>"153";"0";"5";"39264";"hey";"4 spaces; not""can;hen"" thanks!" </code></pre>
python-3.x|pandas|postgresql|psql
3
370,223
57,494,328
How to merge a list containing data and datetime64[ns] with a pandas dataframe with datetime64[ns] index
<p>I want to read two columns S1_max and S2_max from a <code>dataframe</code> <code>data</code>. Wherever a value is present in the S1_max column I want to check that each <code>S1_max</code> is succeeded by a corresponding <code>S2_max</code> signal. If so I calculate the time delta between the <code>S1_max</code> and...
<p>As far as I could understand you are trying to append another column to an existing DataFrame. </p> <p>here how to do it:</p> <pre><code>df1 = pd.DataFrame({'names':['bla', 'blah', 'blahh'], 'values':[1,2,3]}) df2_to_concat = pd.DataFrame({'put_me_as_a_new_column':['row1', 'row2', 'row3']}) pd.concat([df1.reset_i...
python|pandas|dataframe|datetime64
0
370,224
57,393,178
I want to remove rows where a specific value doesn't increase. Is there a faster/more elegant way?
<p>I have a dataframe with <code>30 columns</code>, <code>1.000.000 rows</code> and about <code>150 MB</code> size. One column is categorical with 7 different elements and another column (<code>Depth</code>) contains mostly increasing numbers. The graph for each of the elements looks more or less like this.</p> <p>I t...
<p>Okay, I found a way thats faster. Here is the code:</p> <pre><code> dropList = [True]*len(df.index) for element in elements: currentMax = 0 minIdx = df.loc[df['Element']==element]['Tiefe'].index.min() # maxIdx = df.loc[df['Element']==element]['Tiefe'].index.max() elementList =...
python-3.x|pandas
0
370,225
57,730,557
How to include a variable name in a string (df column title)
<p>I'm iterating through a range from 2010 to 2018. I want to include the results in my api pull for each year as a separate column in my data frame. I'mnot sure how to name the column titles to do so. </p> <p>I tried using "Population {i}" for the column name. </p> <pre><code>for i in range(2010,2019): # Cens...
<p>To get the index of the for loop, use <code>enumerate()</code>:</p> <pre><code>for loop_index, i in enumerate(range(2010,2019)): ... </code></pre> <p>If you're using Python 3.6+, you can use an f-string.</p> <pre><code>census_pd = census_pd.rename(columns={"B01003_001E": f"Population[{loop_index}]", ...}) </c...
python|pandas
0
370,226
57,496,890
Numpy where matching two specific columns
<p>I have a six column matrix. I want to find the row(s) where BOTH columns match the query.</p> <p>I've been trying to use numpy.where, but I can't specify it to match just two columns.</p> <pre><code>#Example of the array x = np.array([[860259, 860328, 861277, 861393, 865534, 865716], [860259, 860328, 861301, 86139...
<p>If I understand you correctly,</p> <p>you can use a little more advanced slicing, like this:</p> <pre class="lang-py prettyprint-override"><code>np.where(np.all(x[:,2:4] == [861277, 861393], axis=1)) </code></pre> <p>this will give you only where these 2 cols are equal to <code>[861277, 861393]</code></p>
python|arrays|numpy
4
370,227
57,479,509
How to solve Keras conv2d input shape error?
<p>I am having problems with the input shape while trying to create a convolutional neural network.</p> <p>My dataset has 164 images 250x250 pixels (123 imgs for training and the remaining for test)</p> <p>The code:</p> <pre class="lang-py prettyprint-override"><code>def conv_neural_net(x_train, x_test, y_train, y_t...
<p>The required shape involves "channels". (RGB has 3 channels, RGBA has 4 channels, black and white has 1 channel)</p> <p>All you need is to add the channels dimension to your input data. </p> <pre><code>x_train = x_train.reshape((123,250,250,1)) x_test = x_test.reshape((164-123,250,250,1)) </code></pre>
tensorflow|keras|conv-neural-network
0
370,228
57,471,414
How to find the x-axis and y-axis index of a value in 2-dimensional array?
<p>StackOverflow! I have hit a wall regarding finding the indices of a 2-dimensional array. I am trying to find the least value in the array and returns the corresponding (x,y) indices.</p> <p>I have tried using <code>np.argmin(a,axis=0)</code> and <code>np.argmin(a,axis=1)</code> simultaneously to find the x and y in...
<p><code>argmin</code> without axis is the location in a flattened version of <code>a</code>:</p> <pre><code>In [200]: a =np.array([[-3.2, 0, 0.5, 5.8], ...: [ 6, 1, 6.2, 7.1], ...: [ 3.8, 5, 2.7, 3.7]]) In [201]: n...
python|arrays|python-3.x|numpy|indices
0
370,229
57,629,445
Coin Flip with Numpy confusion
<p>I'm in the process of learning python and numpy, etc. I'm working on a coding a coin flip, however I'm confused about the code somewhat. I went back through the lesson, but don't see where it explains why total_sums is equal to 2 in the following code.</p> <pre><code>tests = np.random.choice([0, 1], size=(int(1e6)...
<p>You have three flips in each trial. You're checking to see how often you get exactly one head. 1 head implies, ipso facto, 2 tails. Testing for 2 tails is exactly the same as testing for 1 head.</p> <p><code>test_sums == 2</code> goes through the series of flips, yieliding <code>True</code> (1) or <code>False</c...
python|numpy|coin-flipping
0
370,230
57,362,633
Loop through columns in Pandas dataframe
<p>I have a pandas dataframe and would like to loop through all the columns and do some math function. But, unable to get the desired result.Below is my sample dataframe with 3 columns.</p> <pre><code>mydf=pd.DataFrame({'ID1':[9,3,7,5], 'ID2':[15,10,3,8],'ID3':[20,14,10,2]}) mydf ID1 ID2 ID3 0 9 15 20 1 3...
<p>A way to do this is to use <code>apply</code>, no need to iterate rows</p> <pre><code>In [48]: mydf=pd.DataFrame({'ID1':[9,3,7,5], 'ID2':[15,10,3,8],'ID3':[20,14,10,2]}) In [49]: mydf.apply(lambda x: np.log(x).diff(1), axis='rows') Out[49]: ID1 ID2 ID3 0 NaN NaN NaN 1 -1.09861...
python|pandas
1
370,231
57,342,251
Find the first and last element of a NumPy array larger than a threshold
<p>I need to find the first and the last element of a <code>numpy.ndarray</code> which are above a specified threshold. I found the following solution, which works, but it looks a bit convoluted. Is there a simpler/more Pythonic way?</p> <pre><code>import numpy as np import matplotlib.pyplot as plt np.random.seed(1) t...
<p>You could just access the first/last elements</p> <pre><code>s = np.flatnonzero(test &gt; 0.95) imin, imax = s[0], s[-1] </code></pre>
python|arrays|numpy
4
370,232
57,463,158
tf_serving grpc client connection reset by peer
<p>I build a client to feed some data to my modelserver inside docker-container using grpc and c++.</p> <p>when trying to connect i get message: error 14 connection reset by peer.</p> <p>client code:</p> <pre><code>std::cout &lt;&lt; "calling prediction service on " &lt;&lt; "localhost:8500" &lt;&lt; std::endl; ...
<p>I can not rly post an answer but my problem just resolved after doing an fresh ubuntu install.</p> <p>But i can not say how this relates to my problem.</p>
tensorflow|grpc|serving
0
370,233
57,514,557
two date columns to produce new series with selected dates
<p>I have a DataFrame with two date columns, each row corresponding to a disjoint interval of time. I am trying to produce a series which contains as an index all dates from the minimum date to the maximum date from the original columns and has a value 1 if it is a date within one of the original time intervals.</p> <...
<p>Not really pythonic but I think it solves your issue:</p> <pre class="lang-py prettyprint-override"><code>In [1]: from datetime import date, timedelta import pandas as pd df = pd.DataFrame({"A":[pd.Timestamp("2017-1-1"), pd.Timestamp("2017-2-1")], "B": [pd.Timestamp("2017-1-3"), pd.Timestamp("2017-2-...
python|pandas
1
370,234
57,660,083
Pandas: How to add new index levels by column values
<p>I am trying to ease some data evaluation on the following dataframe:</p> <pre><code> 3 9 measurement_location voltage NaN NaN Gleichrichtung ... Gegenrichtung NaN &gt; 50mm ... 1mm &lt; x &l...
<p>Finally i found a solution:</p> <pre><code> 3 9 measurement_location voltage NaN NaN Gleichrichtung ... Gegenrichtung NaN &gt; 50mm ... 1mm &lt; x &lt; 5mm B-Säule 9,5 V ...
python|pandas|multi-index
1
370,235
57,517,740
Pytorch custom dataset: ValueError: some of the strides of a given numpy array are negative
<p>I wrote a custom pytorch dataset, but ran into an error thhat seems quite unintelligible.</p> <p>My custom dataset, </p> <pre class="lang-py prettyprint-override"><code>class data_from_xlsx(Dataset): def __init__(self, xlsx_fp, path_col, class_cols_list): self.xlsx_file = pd.read_excel(xlsx_fp) ...
<p>Thanks to the advice from @jodag and @UsmanAli, I sovled this by return <code>torch.from_numpy(feature.copy())</code> and <code>torch.tensor(label.astype(np.bool))</code> So the whole thing should be,</p> <pre class="lang-py prettyprint-override"><code>class data_from_xlsx(Dataset): def __init__(self, xlsx_fp, ...
python|pytorch
4
370,236
57,428,794
problem with dropped pandas column in numpy array
<p>Dropping one column from a dataset and trying to predict it via a linear regression model shouldn't be a problem. Here is my code:</p> <pre><code>import numpy as np import pandas as pd data = pd.read_csv('student-mat.csv',sep=';') data = data[['G1','G2','G3','studytime','failures','absences']] predict = 'G3' X =...
<p>Try</p> <pre><code>X = np.array(data.drop(predict, axis=1)) </code></pre>
python|pandas|numpy
0
370,237
57,449,382
Lambda function to subtract x and the prior element
<p>I have a dataframe that contains some timestamps and I need to calculate the difference between each timestamp, for each ID. My dataframe is the following:</p> <pre><code>ID Value Date Date_diff_cumsum visVal Weight TempVal 1 0.000 2017-02-13 20:54:00 0.0 0.000 75.0 NaN 1 29....
<p>I worked with just the 'Diff' column The data I used is just Value &amp; Date</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>Value Date 0.000 2017-02-1320:54:00 29.5...
python|pandas|dataframe
1
370,238
57,676,174
VIsual Studio Code not seeing Numpy
<p>So I've finished building my new PC, basically a fresh windows install with just some drivers and basic programs. After setting everything up I decided to install Anaconda and VSCode. Thats what I did and that is ALL I installed. I set up environment paths to the python.exe. Despite this when I try to import numpy i...
<p>Managed to solve this one myself. I noticed the following error in my VS Code:</p> <pre><code>File *name* cannot be loaded because running scripts is disabled on this system. </code></pre> <p>So I went into powershell and allowed to run signed scripts by typing in 'Set-ExecutionPolicy RemoteSigned' and everything...
python|python-3.x|numpy|visual-studio-code|anaconda
1
370,239
57,332,129
How to assign a certain number in an np.array a color in python?
<p>I have a huge array, I want to find all the 3s in the array and make them a certain color. </p> <pre><code>df = pd.read_csv(r'C:\Users\605760\Desktop\path rec\matrix1.csv',header=None) path = zip(*np.where(df==3)) </code></pre> <p>and then something where if a number == 3 find the coordinates and mark it green on...
<p>Are you trying to covert class map to label color map like having 2d array for marking each pixel with value like 1 and you want change it to (0,255,0) Green color?</p> <p>you can use this code to do so.</p> <pre><code>mapping = np.array([[0,0,0],[0,255,0]]) # red for 0 , green for 1, blue for 2 like so on you can...
python|arrays|numpy|matplotlib|matrix
0
370,240
57,334,800
How to add minutes to datetime64 object in a Pandas Dataframe
<p>I want to add a list of minutes to <code>datetime64</code> columns into a new df column.</p> <p>I tried using <code>datetime.timedelta(minutes=x)</code> in a <code>for</code> loop. But as a result, it is adding a constant value to all of my rows. How do I resolve this?</p> <pre><code>for x in wait_min: data['N...
<p>Let us try </p> <pre><code>data['Date'] + pd.to_timedelta(wait_min, unit='m') </code></pre>
python|pandas|minute|datetime64
4
370,241
24,195,673
Append columns to empty list with numpy for rudimentary OCR?
<p>I'm trying to make a program that goes through an image that simulates a line of text and grabs each letter from it. Thinking of the image of a 2D array of pixels, if there exist black pixels in consecutive columns, those columns will be written to a buffer. Once a column with no black pixels has been reached (i.e. ...
<p>The error happened because <code>self.pixels[n, i]</code> returns a pixel, which have 3 values. Looks like you have actually want all 3 values, but you had mistakenly placed a comma after <code>temp[0,i]</code>. Removing the comma would fix the issue.</p> <p>However, there is a quicker way to extract the column. Yo...
python|numpy|ocr|text-recognition
0
370,242
24,010,830
Pandas: Generate Sequential Timestamp with Jump
<p>I have a df with the following index</p> <pre><code>df.index &gt;&gt;&gt; [2010-01-04 10:00:00, ..., 2010-12-31 16:00:00] </code></pre> <p>The main column is <code>volume</code>. </p> <p>In the timestamp sequence, weekends and some other weekdays are not present. I want to resample my time index to have the aggre...
<p>Just construct the range of datetimes you want and reindex to it.</p> <p>Entire range</p> <pre><code>In [9]: rng = pd.date_range('20130101 09:00','20130110 16:00',freq='30T') In [10]: rng Out[10]: &lt;class 'pandas.tseries.index.DatetimeIndex'&gt; [2013-01-01 09:00:00, ..., 2013-01-10 16:00:00] Length: 447, Freq...
python|pandas|indexing|timestamp
6
370,243
24,066,782
Pandas: decompress date range to individual dates
<p><strong>Dataset:</strong> I have a 1GB dataset of stocks, which have values between date ranges. There is no overlapping in date ranges and the dataset is sorted on (ticker, start_date).</p> <pre><code>&gt;&gt;&gt; df.head() start_date end_date val ticker AAPL ...
<p>A bit more than a few lines, but I think it results in what you asked:</p> <p>Starting with your dataframe:</p> <pre><code>In [70]: df Out[70]: start_date end_date val row ticker AAPL 2014-05-01 2014-05-01 10 0 AAPL 2014-06-05 2014-06-10 20 1 GOOG 2014-06-01 2014-06-15 50 2 MSFT 2...
python|pandas|time-series
10
370,244
24,395,258
Random integers from an exponential distribution between min and max
<p>I would like to generate random integers on an interval min to max. For a uniform distribution in numpy:</p> <pre><code>numpy.random.randint(min,max,n) </code></pre> <p>does exactly what I want.</p> <p>However, I would now like to give the distribution of random numbers an exponential bias. There are a number of ...
<p>The exponential distribution is a continuous distribution. What you probably want is its discrete equivalent, the <a href="http://en.wikipedia.org/wiki/Geometric_distribution" rel="nofollow">geometric distribution</a>. <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.geometric.html" rel="n...
python|numpy|random|exponential-distribution
0
370,245
24,130,822
Change string to integer in python / pandas
<p>I am trying to change a string to a float value in a dataframe. </p> <pre><code>#showing dataframe for illustration` IN: df2[:5] OUT: TRD_EXCTN_DT ASCII_RPTD_VOL_TX 0 08/13/2010 1000000 1 08/16/2010 1MM+ 2 08/16/2010 369000 3 08/16/2010 1MM+ 4 08/16/201...
<p>You want to change your second line to <code>df2['ASCII_RPTD_VOL_TX']=df2.ASCII_RPTD_VOL_TX.astype(float)</code>.</p> <p>The reason you are getting strange result is that your 1st and 3rd row, ASCII_RPTD_VOL_TX column cells are still in <code>str</code>. <code>+</code> is doing string <code>concatenate</code> there...
python|pandas|dataframe
0
370,246
24,163,252
Python, section of a tetrahedralized (scipy.Delaunay) 3D cloud of points
<p>I want to draw a "cross section" of a hull in a 3D space, <strong>the intersection of the hull with a plane</strong>. </p> <p>The space is defined by axis <code>X, Y, Z</code>, and the crossing plane, <strong><em>parallel to XZ</em></strong> is defined by <code>Y = 50</code></p> <p>First, I loaded a cloud of 3D <c...
<p>Below I give python code that, given a set of 3d points and a plane (defined by its normal vector and a point on the plane) computes the 3d Delaunay triangulation (tessellation) and the intersection points of the Delaunay edges with the plane.</p> <p>The following figure visualizes the result on an example of twent...
python|numpy|3d|delaunay
0
370,247
24,015,883
Plotting Histogram using data from 2 numpy matrices
<p>I have 2 numpy matrices <code>A</code> and <code>B</code>:</p> <ul> <li><code>A</code> matrix has as possible values only 1 or 0 (ON or OFF). </li> <li><code>B</code> matrix has integers (min value -1). </li> </ul> <p>I need to plot a histogram between the elements of matrix <code>B(X-axis)</code> and their freque...
<p>If the values in <code>B</code> where all small positive integers, you could simply do:</p> <pre><code>count = np.bincount(B.ravel()) tally = np.bincount(B.ravel(), weights=A.ravel()) freq = tally / count </code></pre> <p>But because you have negative numbers, it is probably best to play it safe and run <code>B</c...
python|numpy|matrix
1
370,248
24,264,424
Pandas: Efficient way to get first row with element that is smaller than a given value
<p>I'm wondering if there's an efficient way to do this in pandas: Given a dataframe, what is the first row that is smaller than a given value? For example, given:</p> <pre><code> addr 0 4196656 1 4197034 2 4197075 3 4197082 4 4197134 </code></pre> <p>What is the first value that is smaller than 4197080? I ...
<p>This requires 0.14.0</p> <p>Note that the frame IS NOT SORTED.</p> <pre><code>In [16]: s = df['addr'] </code></pre> <p>Find biggest value lower than required</p> <pre><code>In [18]: %timeit s[s&lt;5783091] 100 loops, best of 3: 9.01 ms per loop In [19]: %timeit s[s&lt;5783091].nlargest(1) 100 loops, best of 3: ...
python|pandas
8
370,249
24,034,839
ValueError resizing an ndarray
<p>I have a small python script, and I always run into an error:</p> <pre><code>ValueError: cannot resize an array references or is referenced by another array in this way. Use the resize function </code></pre> <p><strong>Code:</strong></p> <pre><code>points = comp.findall('Points') # comp is a parsed ...
<p>You cannot resize NumPy arrays that share data with another array in-place using the <code>resize</code> method by default. Instead, you can create a new resized array using the <code>np.resize</code> function:</p> <pre><code>np.resize(a, new_shape) </code></pre> <p>or you can disable reference checking using:</p>...
python|numpy|resize
21
370,250
43,622,771
TensorFlow MNIST DCGAN: how to set up the loss function?
<p>I would like to build a <a href="https://arxiv.org/abs/1511.06434" rel="nofollow noreferrer">DCGAN</a> for MNIST by myself in TensorFlow. However, I'm struggling to find out how I should set up the loss function for the generator. In a <a href="https://github.com/jacobgil/keras-dcgan" rel="nofollow noreferrer">Keras...
<p>In the generator step training, you can think that the network involves the discriminator too. But to do the backpropagation, you will only consider the generator weights. A good explanation for it is found <a href="http://www.rricard.me/machine/learning/generative/adversarial/networks/2017/04/05/gans-part1.html" re...
tensorflow|neural-network|conv-neural-network|mnist|dcgan
5
370,251
43,705,845
how to extract rows by comparing data value and categories in pandas
<p>I have a dataframe like below</p> <pre><code>1320 A 2010 455 1325 B 2010 52 1336 A 2011 148 1341 B 2011 37 1352 A 2012 57 1357 B 2012 8 </code></pre> <p>I'd like to get result of difference between two groups in the same year, like</p> <pre><code>1 2010 403 2 2011 1...
<p>This will work:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame() df['group'] = ['A','B']*3 df['year'] = [2010,2010,2011,2011,2012,2012] df['value'] = [455,52,148,37,57,8] df.loc[df.group=='B','value']*=-1 dfNew = df.groupby('year').sum() print dfNew </code></pre> <p>If we start with <...
python|pandas
1
370,252
43,746,594
Seperate csv file and filter the data
<p>I have a csv file with data as below</p> <pre><code>id^code^result1^result2 AXY-C-5567^AXY^1.0^1.0 RFD-A-3456^RFD^9^8 SAD-AC-4563^SAD^4^6.7 ASE-A-4567^ASE^7.3^2.7 DER-C-3256^DER^5.5^3 </code></pre> <p>How to extract second,third and fourth column if the id has A and not C or AC, in python? In this case, code: RFD,...
<p><strong>UPDATE:</strong></p> <pre><code>In [157]: pd.read_csv(r'/path/to/file.csv', sep='^', usecols=[0,1]) \ .query("id.str.contains('-A-')", engine='python').iloc[:, 1] Out[157]: 1 RFD 3 ASE Name: code, dtype: object In [208]: pd.read_csv(r'/path/to/file.csv', sep='^') \ .query("id....
python|csv|pandas
0
370,253
43,558,555
How can I switch words in a column around?
<p>I am given a .csv file and asked to use pandas to answer some questions. In one of the question it ask to find the three most popular name. But asked to print there first name followed by there last name. I understand how to do that but how can I have a space between the first and last name for example ' John Smith...
<p>Try this:</p> <p>Source DF:</p> <pre><code>In [38]: df Out[38]: ConductorName val 0 AlanGilbert 695 1 JoshuaGersen 45 2 RobFisher 35 </code></pre> <p>Solution:</p> <pre><code>In [39]: df.ConductorName.str.replace(r'([a-z])([A-Z])', r'\1 \2') Out[39]: 0 Alan Gilbert 1 Joshua Gersen 2 R...
python|python-3.x|pandas
3
370,254
43,564,555
PostGIS: Converting Text WKT/WKB/WKB Hex to Polygon
<p>I am importing Polygon shapes into a PostGIS database, using Python (GeoPandas, SQLAlchemy, GeoAlchemy2). I followed the instructions mentioned <a href="https://stackoverflow.com/questions/38361336/write-geodataframe-into-sql-database/43375829">here</a>.</p> <p>I have a database with a table named <code>maps_region...
<p>I realized that the shapes were being registered in mixed format: all but one were in <code>Polygon</code> format, while one was in <code>MultiPolygon</code> format -- <a href="https://i.stack.imgur.com/ZOzcy.png" rel="nofollow noreferrer">see here</a>. Looks like this sufficiently explains the issue/invalid convers...
python|sqlalchemy|postgis|geopandas|geoalchemy2
1
370,255
43,767,862
seaborn exclude columns in clustering
<p>I have a dataset containing 200 rows and 97 columns, which I have stored as a pandas dataframe.</p> <p>I am plotting this dataframe with seaborn, using clustermap, like this:</p> <pre><code>from matplotlib.colors import ListedColormap sns.set(rc={'axes.facecolor':'white', 'figure.facecolor':'white'}) cmap=ListedC...
<p>use <code>iloc</code> to do your trimming</p> <pre><code>from matplotlib.colors import ListedColormap sns.set(rc={'axes.facecolor':'white', 'figure.facecolor':'white'}) cmap=ListedColormap(["white", "lightgray", "blue", "red", "cornflowerblue", "darkcyan", "pink", "violet"]) g = sns.clustermap( df.iloc[:, 2:],...
pandas|seaborn
2
370,256
43,892,267
New columns with incremental numbers that initial based on a diffrent column value (pandas)
<p>I want to add a column with incremental numbers for rows with the same value in a defined row;</p> <p>e.g. if I would have this df </p> <pre><code>df=pd.DataFrame([['a','b'],['a','c'],['c','b']]) </code></pre> <p>and I want incremental numbers for the first column. It should look like this</p> <pre><code>df=pd.D...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>cumcount</code></a>, for name of new column use <code>length</code> of original <code>columns</code>:</p> <pre><code>print (len(df.columns)) 2 df[len(df.columns)] = df.group...
python|pandas
2
370,257
43,575,649
Trouble finding large jumps between data points in an array
<p>I am trying to write a sigma clipping program that calculates the differences between each point in an array and its neighbor, and if the difference is greater than x times the standard deviation of the array, it sets the neighbor equal to the average of the two points closest to it. For example, if I had an array, ...
<p>in line 6 of your function array[-1] may be a typo as it always uses the last element of the array. Are you missing an i? In which case you might need to shift by one as difference[0] is the diff between array[0] and array[1]</p> <p>PS I think I would use np.where with slice notation on array to find just the index...
python|arrays|numpy
0
370,258
43,771,114
Fast way combine multiple columns of type float into one column of type array(float)
<p>I have a dataset like this:</p> <pre><code>df = pd.DataFrame({ "333-0": [123,123,123], "5985-0.0": [1,2,3], "5985-0.1":[1,2,3], "5985-0.2":[1,2,3] }, index = [0,1,2] ) </code></pre> <p>Here, we have three columns <code>["5985-0.0", "5985-0.1", "5985-0.2"]</code> that represent the first...
<p><strong><em>My Choice</em></strong><br> <em>Assuming I know the columns</em> </p> <pre><code>thing = '5985-0' cols = ['5985-0.0', '5985-0.1', '5985-0.2'] k = len(cols) v = df.values l = [v[:, df.columns.get_loc(c)].tolist() for c in cols] s = pd.Series(list(zip(*l)), name=thing) df.drop(cols, 1).join(s) 333-0 ...
pandas
1
370,259
43,783,496
Pandas data frames and matplotlib.pyplot
<p>I have created a dataframe that looks like the following:</p> <p><a href="https://i.stack.imgur.com/3oD4p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3oD4p.png" alt="Data frame #1"></a></p> <p>I have no problems plotting the data with the following:</p> <pre><code>df_catch.plot(x='YY', y='A...
<p>For convert <code>index</code> to column are 2 solutions:</p> <p>Need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>reset_index</code></a>:</p> <pre><code>name = df_catch.groupby('YY') # Apply the sum function to the groupby object...
pandas|matplotlib
1
370,260
43,778,450
How to get the distance to the closest previous finite number in a row using Numpy
<p>I'm stuck at something that I think could easily be solved in a couple of lines using Numpy, I just don't see it. Let's define an example array containing some missing values:</p> <pre><code>import numpy as np input_data = np.array([[1,3,5,8,6],[3,np.nan,np.nan,5,6],[np.nan,6,7,np.nan,2]]) Out[530]: [[1, 3, 5, 8, ...
<p>Here is a solution to your problem. It might not be optimal, as I it might be possible to do something more fancy with map and/or list comprehensions but at least it solves your immediate issue:</p> <pre><code>import numpy as np input_data = np.array([[1,3,5,8,6],[3,np.nan,np.nan,5,6],[np.nan,6,7,np.nan,2]]) def d...
python|numpy|missing-data
1
370,261
43,585,432
TensorFlow layers: using custom(ized) initialization function?
<p>Why does obtaining a new initialization function with <code>partial</code> give me an error, while a <code>lambda</code> doesn't?</p> <p>All of these functions:</p> <pre><code>f_init = partial(tf.random_normal, mean=0.0, stddev=0.01, partition_info=None) f_init = partial(tf.contrib.layers.xavier_initializer, parti...
<p>The error says that the functions <code>tf.random_normal</code> and <code>tf.contrib.layers.xavier_initializer</code> do not have an parameter with the name <code>partition_info</code> which is indeed the case. There is no such parameter (see <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/p...
python-3.x|lambda|tensorflow|initialization|initializer
2
370,262
43,488,919
Tensorboard Embedding projector Maximum points showing?
<p>anyone know does tensorboard embedding only able to show up 100k points only? Or there is any other way to modify the maximum points show? <a href="https://i.stack.imgur.com/9tc3f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9tc3f.png" alt="enter image description here"></a></p>
<p>As it stands there is no real easy way to do this. The problem is discussed in detail over at GitHub issues <a href="https://github.com/tensorflow/tensorboard/issues/725" rel="nofollow noreferrer">Here</a> and <a href="https://github.com/tensorflow/tensorboard/issues/773" rel="nofollow noreferrer">here</a>. </p>
tensorflow|tensorboard|projector
0
370,263
43,870,647
How to duplicate a row or column in a numpy array?
<p>Having this <code>numpy</code> array:</p> <pre><code>[[0 1 2] [3 4 5] [6 7 8]] </code></pre> <p>How do I duplicate for example row 1 so I get the below?:</p> <pre><code>[[0 1 2] [3 4 5] [3 4 5] [6 7 8]] </code></pre>
<p><strong>Approach #1</strong></p> <p>One approach with <a href="https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.insert.html" rel="noreferrer"><code>np.insert</code></a> -</p> <pre><code>np.insert(a,2,a[1],axis=0) </code></pre> <p>For duplicating columns, use it along <code>axis=1</code> -</p> <p...
python|python-3.x|numpy
10
370,264
43,750,548
Do CNNs (Convolution Neural Networks) require a CSV file?
<p>I am trying to do some image classification using TensorFlow, and I'm using a CNN. I have a CSV file for the images, but I was wondering if I need a CSV file when I load the dataset (images), or will the CNN do the classification by itself without one. I'm pretty new to Machine Learning and TensorFlow, so some detai...
<p>Not really sure why/what you are asking, but I think the answer to your question should be: no, you do not require a CVS (did you mean CSV?) file. If you write a program that loads the data with the labels you should be fine!</p>
csv|machine-learning|tensorflow|dataset|computer-vision
1
370,265
43,875,138
Tensorflow SyntaxError with python 3.5.2
<p>I'm trying to install tensorflow to my Linux systems (Linuxmint) with Python 3.5 using pip installation with CPU support. After the installation is done; to validate my installation I try to run the following script </p> <p>python3</p> <pre><code>&gt;import tensorflow as tf </code></pre> <p>the result is the fol...
<p>After upgrading <code>tensorflow</code> 1.3.0 to 1.4.0 I encountered this error. to solve it, I check different steps : </p> <pre><code>sudo pip3 uninstall tensorflow-gpu sudo pip3 uninstall protobuf sudo pip3 install tensorflow-gpu==1.3.0 sudo pip3 install protobuf==3.3.0 </code></pre> <p>but the error was not re...
python-3.x|tensorflow|pip
1
370,266
43,834,830
Tensorflow equivalent of np.corrcoef on a specific axis
<p>I am trying to correlate two matrices column wise. i.e. correlate the 1st column of the 1st matrix with the 1st column of the 2nd matrix and so on. In numpy I do:</p> <pre><code>np.corrcoef(x, y, axis=0) </code></pre> <p>And it works great. What would be the Tensorflow equivalent of that command?</p> <p>I tried u...
<p>Documentation page for numpy <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.corrcoef.html" rel="noreferrer">corrcoef</a> gives connection between corcoef and covariance matrix. So, natural thing is to rewrite it in terms of matmuls in numpy first:</p> <pre><code>fsize=1 dsize=3 x=np.random.rand...
python|numpy|tensorflow|pearson-correlation
5
370,267
43,684,323
Relative gradient error
<p>Is there an easy way to calculate relative gradient error in tensorflow? All what is available is tf.test.compute_gradient_error but it computes absolute gradient error and not relative error. Of courser there're methods which compute numeric and theoretical jacobians but they are private.</p>
<p>I found the answer myself tf.test.compute_gradient returns two jacobians, so I can use them to find the relative gradient error. I.e. if I use L-infinity norm, I can take tf.test.compute_gradient_error and divide in on the maximum element of both jacobians.</p>
tensorflow
0
370,268
43,803,771
fault in defining numpy array as tensorflow variable
<p>I have a x numpy array:</p> <pre><code>[0, 6, 3513, 7, 155, 794, 25, 223, 8, 32, 20, 202, 5025, 350, 91, 6, 66, 207, 5, 2] </code></pre> <p>I want to define it as a tensorflow variable as the following:</p> <pre><code>tf.Variable(x) </code></pre> <p>And I get the following error:</p> <blockquote> <p>TypeError...
<p>Can you share what are you trying to do, as tensorflow just defines a variable you can only use that variable when you are executing that session. Hope Below code helps you. </p> <pre><code> import tensorflow as tf import numpy as np x =[0, 6, 3513, 7, 155, 794, 25, 223, 8, 32, 20, 202, 5025, 350, 91, 6...
python|numpy|tensorflow
2
370,269
43,758,949
Python matrix diagonal of inf without fill_diagonal
<p>I need to set the diagonal elements of a matrix to Inf.</p> <p>An easy way to do it is to use <code>np.fill_diagonal</code>.</p> <pre><code>np.fill_diagonal(my_matrix, float('inf') </code></pre> <p>However <code>fill_diagonal</code> modifies the input matrix instead of returning a new matrix with the diagonal fil...
<p><strong>Approach #1</strong></p> <p>The magic you are looking for is in <a href="http://www.scipy-lectures.org/advanced/advanced_numpy/#indexing-scheme-strides" rel="nofollow noreferrer"><code>NumPy strides</code></a> that gets us a view of the array without the diagonal elements and as such doesn't occupy anymore ...
python|numpy
2
370,270
43,897,296
Pandas – converting yes : no to True : False failing
<p>My best efforts to convert a column with 'yes' 'no' values to True, False or 1 , 0 are failing. The column is 'subscribed'.</p> <pre><code>df.subscribed.unique() returns array(['no', 'yes'], dtype=object) </code></pre> <p>Tried the following. None of them worked:</p> <pre><code>df.subscribed = df.subscribed.astyp...
<p>As EdChum points out you need to assign back to the df.</p> <pre><code>df = pd.DataFrame({'subscribed':np.random.choice(['yes','no'], 10)}) print(df) </code></pre> <p>Input:</p> <pre><code> subscribed 0 yes 1 yes 2 yes 3 no 4 no 5 yes 6 no 7 no 8 ...
python|pandas
3
370,271
43,883,288
Python - optimize matrix values using constraints, beginner
<p>So I have an DataFrame in pandas with simple bond information. I need to create restrictions such that <em>at least</em> 30% of the bonds have to be long-term, or that <em>no more</em> than 60% of the bonds can be classified as high risk. A simplified table is as follows:</p> <pre><code>Bond | Returns | Length | R...
<p>You can count the number of <code>"Longs"</code> and <code>"Highs"</code> and divide by the total number of values using <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer">boolean indexing</a>:</p> <pre><code>&gt;&gt;&gt; sum(df["Length"] == "Long") / df["...
python|numpy|scipy
0
370,272
43,556,339
Disable GPU on certain applications
<p>I was trying to train some neural network on an Nvidia GPU, but it seems the desktop environment (KDE) is occupying the GPU: </p> <pre><code>$ nvidia-smi Sat Apr 22 09:04:16 2017 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 375.39 Driver Versio...
<p>It seem that you don't have enough GPU memory for training. There are some solution:</p> <ol> <li><p><strong>Reduce batch size</strong>: Only a batch is load into GPU at a time. Small batch size would occupy less GPU memory. (try to reduce batch size to 1 to see if it work ?). Look, you have more that 500 MiB of GP...
python|pytorch
0
370,273
43,793,958
How to make (yes/no or 1-0) decisions with random forest?
<p>This is the data set from Kaggle's Titanic competition (<a href="https://1drv.ms/u/s!Ar0y71vBm1oLeTNZl17c1l1bHrw" rel="nofollow noreferrer">train</a> and <a href="https://1drv.ms/u/s!Ar0y71vBm1oLeAGIr7o1s1BG5q4" rel="nofollow noreferrer">test</a> csv files). Each file has features of passengers such as ID, sex, age,...
<p>Transforming your probability into binary output is the right way to go, but why did you choose > .6 and not > .5?</p> <p>Also, if you are having bad results in that case, it is most likely because you did not do a proper job in data cleaning and feature extraction. For example, the title ("Mr", "Mrs",...) can give...
python|pandas|scikit-learn|random-forest|decision-tree
0
370,274
43,656,784
Compare Rows in oracle table and update matching ones
<p>I have a table such as the following:</p> <pre><code>**ID tDate Product Price Quantity BuySell Status** 1 10-May-17 pppp $12 20 Buy Null 2 12-May-17 tttt $10 20 Sell Null 3 12-May-17 tttt $10 ...
<p>Untested but something like this using only SQL:</p> <pre><code>MERGE INTO your_table dst USING ( SELECT ROW_NUMBER() OVER ( PARTITION BY tDate, Product, Price, Quantity, BuySell ORDER BY ID ) AS idx, COUNT( CASE BuySell WHEN 'Buy' THEN 1 END ) OVER ( PAR...
python|sql|oracle|pandas|plsql
2
370,275
43,721,073
Check if a numpy array is lexicographically sorted
<p>How do I check if a sequence of numpy arrays are lexicographically sorted?</p> <pre><code>&gt;&gt;&gt; x = np.asarray([0, 0, 1, 1]) &gt;&gt;&gt; y = np.asarray([0, 1, 0, 2]) &gt;&gt;&gt; is_lex_sorted([x, y]) True &gt;&gt;&gt; x = np.asarray([100, 0, 1, 1]) &gt;&gt;&gt; y = np.asarray([0, 1, 0, 2]) &gt;&gt;&gt; is...
<p>An implementation of <code>is_lexsorted</code> using pure-NumPy functions would almost certainly need to make several passes over one or more of the arrays (since NumPy functions are designed to operate on entire arrays in one go).</p> <p>This means that writing the function in numba or Cython may be a better optio...
python|numpy
3
370,276
72,847,708
Numpy packaging and methods implementation
<p>I was coding in numpy and had a question that made me think about the structure of the package and how methods are implemented. Here I give basic methods to illustrate my point:</p> <pre><code>import numpy as np a = np.array([1, 2, 3]) b = np.ones(3) </code></pre> <p>It is possible to do either <code>a.dot(b)</code>...
<p>The compiled internals of numpy, whether we are talking about the functions or the <code>ndarray</code> methods, are complicated, and don't readily fit the textbook python class layout.</p> <p>Often when there are functions and methods of the same name, the function ensures that its argument(s) is an array and then ...
python|numpy
0
370,277
72,895,737
How to make a grouped bar chart with multiple data for the same x_label string
<p>I'm doing the post-process of an analysis. Basically, for each analysis (=folder), I go through csv files and gather the maximum displacement of the isolated model, and of the assembled model.</p> <p>I created three lists :</p> <ul> <li>analysis : Gather the analysis name, made of the two-component that varies with ...
<p>Thanks to Robbie's answer (see : <a href="https://stackoverflow.com/questions/51130673/bar-chart-using-dictionaries-in-python-using-matplotlib">Bar chart using Dictionaries in python using matplotlib</a>), I ended up using the following code :</p> <pre><code># Sauvegarde des déplacements max dans des dataframes pour...
python|pandas|csv|matplotlib|plot
0
370,278
73,091,099
How to subset a dataframe based on rows that exist in multiple other dataframes?
<p>I have created multiple control dataframes (<code>pos_control_df</code>, <code>neg_control_df</code>) based on columns of the original <code>df</code> dataframe.</p> <pre><code>import pandas as pd import numpy as np # Isolate the control samples ## Samples are &quot;control&quot; if: ## (i) Positive control: &quot;...
<p>You can use merge to do that. You did not give example for your dataframe but let's assume you have an identifier column named 'id', you will do:</p> <pre><code>sample_df = df.merge(right='pos_neg_ctl_df', how='right', on='id') sample_df = sample_df .merge(right='probe_ctl_df', how='right', on='id') sample_df = samp...
pandas
0
370,279
72,971,635
How to take a 2x2 array and turn it into 2 (2x2) arrays under the same variable name in python?
<p>So I am working with a section of code that needs a set of 2x2 arrays that is essentially 2 copies of the same 2x2 array.</p> <p>The array that I have currently is shaped like:</p> <pre><code>[[3.00000000e+02 3.16227766e-02] [4.00000000e+02 1.00000000e-01]] </code></pre> <p>it is called self.concs.</p> <p>I need a...
<p><code>np.stack</code> takes the arrays as a list or collection, not as individual arguments:</p> <pre><code>&gt;&gt;&gt; np.stack((concs, concs)) # or: np.stack([concs, concs]) array([[[3.00000000e+02, 3.16227766e-02], [4.00000000e+02, 1.00000000e-01]], [[3.00000000e+02, 3.16227766e-02], [...
python|arrays|numpy
2
370,280
73,066,151
Check if any value in a list exists in a group of dataframe columns and create new boolean column
<p>I have a dataframe where each row represents a patient and several columns list medical diagnoses. A simplified version is given below. Some patients have empty diagnosis columns, depending on how many diagnoses they have recorded.</p> <pre><code>data = {'id': [1, 2, 3, 4], 'diag_1': ['stroke', 'stroke', 'cancer', '...
<p>You can use</p> <pre class="lang-py prettyprint-override"><code>df['flag'] = df.filter(like='diag').isin(diagnoses).any(axis=1) </code></pre> <pre><code>print(df) id diag_1 diag_2 diag_3 flag 0 1 stroke dementia hypertension True 1 2 stroke heart disease ...
python|pandas|dataframe|numpy
1
370,281
73,059,896
How to correctly estimate the percentage change of two columns considering different indexes in the series with pandas? Python related
<p>Say I have the following df called <code>df_trading_pair</code>:</p> <pre><code> Start Date Open Price High Price Low Price Close Price End Date 0 2022-07-20 08:00:00 0.19277 0.19324 0.19225 0.19324 2022-07-20 08:04:59.999 1 2022-07-20 08:05:00 0.19321 0.194 ...
<p>You need to use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.shift.html" rel="nofollow noreferrer"><code>shift</code></a>, else pandas will realign your indices:</p> <pre><code>df['Close Price'].shift(-1).sub(df['Open Price']).div(df['Open Price'])[:-1] </code></pre> <p>Output:</p> <pre><code>...
python-3.x|pandas|dataframe|debugging|valueerror
1
370,282
73,169,197
Filter pandas dataframe records based on condition with multiple quantifier regex
<p>I am trying to filter some records from pandas dataframe. The dataframe named 'df' consist of two columns Sl.No. and doc_id(which contains urls) is as follows:</p> <pre><code>df Sl.No. doc_id 1. https://www.durangoherald.com/articles/ship-owners-sought-co2-exemption-when-the-sea-...
<p>pandas dataframe isin function will take list as input and search for the values in specified column.</p> <pre><code> print(df) print(df[df['col2'].isin(needed_url)]) </code></pre> <p>output: df:</p> <pre><code> col1 col2 0 1 https://www.durangoherald.com/articles...
python|python-3.x|pandas|regex|numpy
1
370,283
72,955,994
Python Pandas Reformat stacked columns to long(?) format
<p>I have a csv file that looks like this:</p> <p><a href="https://i.stack.imgur.com/TCNkw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TCNkw.png" alt="Current csv" /></a></p> <p>And I want it to look like this:</p> <p><a href="https://i.stack.imgur.com/mknlU.png" rel="nofollow noreferrer"><img sr...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>df.iloc[:, 0] = df.iloc[:, 0].str.strip() idx1 = pd.MultiIndex.from_product( [(&quot;2017&quot;,), (&quot;Enero&quot;, &quot;Febrero&quot;), (&quot;Valor Export&quot;, &quot;Volumen Export&quot;)], names=(&quot;Year&quot;, &quot;Month&quot;, &quot;Exp...
python|pandas|pivot|melt
1
370,284
73,112,793
How to split a column and add additional rows from the split values in pandas?
<p>I have a dataframe as:</p> <pre><code>{'last_name': {0: 'Acosta-Arriola', 1: 'Afragola', 2: 'Bertolini', 3: 'Coyle', 4: 'Davis', 10: 'Duntz', 11: 'Eastman', 12: 'Fitzgerald', 13: 'Fitzgerald', 14: 'Freeman', 15: 'Freeman', 16: 'Gambardella', 17: 'Kelleher', 18: 'King', 19: 'Looney', 20:...
<pre class="lang-py prettyprint-override"><code># split the middle name df.middle_name_or_initial = df.middle_name_or_initial.str.split(';') # explode the dataframe df_new = df.explode('middle_name_or_initial') </code></pre> <p>here is the documentation of <code>df.explode()</code> <a href="https://pandas.pydata.org/d...
python|pandas
3
370,285
73,052,682
Divide dataframe into list of rows containing all columns
<p>From dataframe sructured like this</p> <pre><code> A B 0 1 2 1 3 4 </code></pre> <p>I need to get list like this:</p> <pre><code>[{&quot;A&quot;: 1, &quot;B&quot;: 2}, {&quot;A&quot;: 3, &quot;B&quot;: 4}] </code></pre>
<p>It looks like you want:</p> <pre><code>df.values.tolist() </code></pre> <p>example:</p> <pre><code>df = pd.DataFrame([['A', 'B', 'C'], ['D', 'E', 'F']]) df.values.tolist() </code></pre> <p>output:</p> <pre><code>[['A', 'B', 'C'], ['D', 'E', 'F']] </code></pre> <h4>other options</h4> <pre><code>d...
python|pandas|dataframe|data-science|rows
3
370,286
73,075,286
From Nested dictionary to a flattened Dataframe
<p>I have a bit of a nightmare here. I tried flatten_dict, MutableMapping, export to json trying to read it and cleaning, etc. Nothing works.</p> <p>So, I have 720 rows like these:</p> <pre><code>&quot;{'utilidad neta': 954700.2, 'gastos operacionales': {'total': 32505631.93, 'gastos administrativos': 24734891.6, 'prov...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html" rel="nofollow noreferrer"><code>json_normalize</code></a> with convert values to dictionaries by <code>literal_eval</code>:</p> <pre><code>import ast df = pd.json_normalize(df['col'].apply(ast.literal_eval)) </code><...
python|json|pandas|dictionary
2
370,287
73,126,920
Compare a column in one dataframe with many columns in another dataframe pandas
<p>I have two dataframes:</p> <p>df1:</p> <pre><code> ID name1 0 '' 'company-1' 1 '' 'company2' 2 '' 'company 3' </code></pre> <p>df2:</p> <pre><code> ID name2 name3 name4 0 '1' 'company1' 'company.1' 'company-1' 1 '2' 'company2' 'company.2' 'company-2' </...
<p>This can be tackled in many ways. You can use a row-wise <code>apply</code>, convert the second frame into a mapping/lookup table (Python <code>dict</code>), or try joining the two frames. Here's an example of the latter:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd # The given input data...
python|pandas|dataframe
0
370,288
73,024,975
Is there a way to send location of pytorch tensor in gpu memory between docker containers and build them in different containers
<p>To quickly sum up the problem, I need to transfer images (size is (1920,1200,3)) between PyTorch docker containers and process them. Containers are located in the same system. Speed is very important and transfer should not take more than 2-3ms one way. Two containers will be shared via IPC so I find no problem tran...
<p>I found a function in <code>torch.multiprocessing.reductions</code> that rebuilds tensors from the output generated by <code>_share_cuda_()</code>. Now my code looks something like this:</p> <p>Container 1 code:</p> <pre><code>import torch import zmq def main(): ctx = zmq.Context() sock = ctx.socket(zmq.REQ...
python-3.x|docker|sockets|pytorch|cuda
1
370,289
72,981,116
python convert dataframes to excel in memory, without any file read/write
<p>I need to convert a dataframe to an excel file purely using memory, i.e. there cannot be any reading / writing of files locally. Because of this, I am unable to do something like <code>df.to_excel('filename.xls')</code>, or use <code>with open('filename.xls', 'rb') as f:</code> This is because the script is to be ru...
<blockquote> <p>the print message that comes out looks nothing like an excel file</p> </blockquote> <p><code>xlsx</code> is a zipped format, so it's a binary file and there's no point printing it.</p> <p>For testing, you can just check a round-trip:</p> <pre><code>import io import pandas as pd df = pd.DataFrame([[1,2]...
python|excel|pandas|dataframe|io
0
370,290
73,005,912
Tensorflow Flower Classifier consistent predictions with varied input
<p>I am following this tensorflow tutorial notebook to classify images of flowers: <a href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/images/classification.ipynb#scrollTo=U-e-XzMeyH2O" rel="nofollow noreferrer">https://colab.research.google.com/github/tensorflow/docs/blob/ma...
<p>The issue here was related to the line</p> <pre><code>sunflower_path = tf.keras.utils.get_file('Red_sunflower', origin=sunflower_url) </code></pre> <p>When downloading a new image, it was NOT overwriting the stored image. So the model was making a prediction against the same input every time.</p> <p>I manually defin...
python|tensorflow|machine-learning|keras|classification
0
370,291
72,917,954
Using Pandas, How to find the percentage of a column reaching the target in another column
<p>Using Pandas, I'm having trouble how to figure out the percentage of one column reaching the goal in another column. Goal column list numbers and there is a column for the actual pledges. example below. the actual DF has 6000 rows.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Goal</th...
<p>You can do it like this:</p> <pre><code>df = pd.DataFrame([[4, 2], [10, 2]], columns=['goal', 'fact']) df['goal_fraction'] = df.fact / df.goal </code></pre> <p>To visually transform it to the percentage:</p> <pre><code>df['percentage'] = (df.goal_fraction * 100).round(0).astype(str) + &quot;%&quot; </code></pre>
python|pandas|dataframe|percentage
0
370,292
73,072,340
Arranging a dataframe into multiple dictionaries based on unique values in a specific column
<p>I'd like to create multiple dictionaries based on unique values in a column, in this case unique strings in the 'Name' column as a key. And other columns of my choice also being a key. So for my given dataset, the Name column will have the same name repeated numerous times, but the number of times that name repeats ...
<p>IIUC, we can generate a list of dictionaries:</p> <pre><code>df.groupby('Name')[['Source', 'Number']].agg(list).reset_index().to_dict('records') </code></pre> <p>Output:</p> <pre><code>[{'Name': 'Billy', 'Source': ['Home', 'Work', nan, 'School'], 'Number': ['B:67', 'r:3', 'D:90', 'A:1']}, {'Name': 'Bob', 'Sourc...
python|pandas|dataframe|dictionary|iteration
0
370,293
72,902,619
How do I take user input "n = str(input("Give str"))" while having the numpy module imported?
<p>my problem is that I can't take input from user (&quot;n = str(input(&quot;Give str&quot;))&quot;) while having the numpy module imported. I'm new to basically everything in Python and can't get past this problem.</p> <p>No matter what I do,</p> <pre><code>&quot;TypeError: 'numpy.ndarray' object is not callable&quot...
<p><code>input</code> is a built-in function in python.<br /> Reference: <a href="https://docs.python.org/3/library/functions.html#input" rel="nofollow noreferrer">https://docs.python.org/3/library/functions.html#input</a></p> <p>You are currently using it as a variable for your <code>numpy</code> array.<br /> This wil...
python|python-3.x|string|numpy|input
0
370,294
73,140,803
Numpy array reshape element-wise
<p>I have a 3-D array size = (3,2,3)</p> <pre><code>[ [[1, 2, 3],[4, 5, 6]], [[7, 8, 9],[10,11,12]], [[13,14,15],[16,17,19]] ] </code></pre> <p>How to reshape to (3,3,2):</p> <pre><code>[ [[1,4], [2,5], [3,6]], [[7,10], [8,11], [9,12],], [[13,16],[14,17],[15,19]] ] </code></pre>
<p>You task is not to reshape the array. You have to swap the last axis (the third dimension of your array) with the second.</p> <pre><code>import numpy as np #input arr = np.array([ [[1, 2, 3],[4, 5, 6]], [[7, 8, 9],[10,11,12]], [[13,14,15],[16,17,19]] ]) #output np.moveaxis(arr, 2, 1) #an alternative is np.swap...
python|arrays|numpy|reshape
1
370,295
72,946,937
pandas string replace multiple character in a cell
<pre><code>df = pd.DataFrame({'a': ['123']}) a 0 123 </code></pre> <p>I want to replace 1 with 4, 2 with 5, and 3 with 6</p> <p>So this is the desired output</p> <pre><code> a 0 456 </code></pre> <p>How can I achieve this using <code>pd.str.replace()</code> ?</p>
<p>Try <code>.replace</code> (not <code>.str.replace</code>) with option <code>regex=True</code>:</p> <pre><code>df['a'] = df['a'].replace({'1':'4', '2':'5', '3':'6'}, regex=True) </code></pre> <p>Output:</p> <pre><code> a 0 456 </code></pre>
python|pandas|str-replace
2
370,296
73,028,930
How fix a problem when I change the expression of `x_new` inside the following function `phix`?
<p>I try to change the expression of <code>x_new</code> inside the following function <code>phix</code> defined as follows.</p> <p>[![enter image description here][1]][1]</p> <p>The code for this function is as follows.</p> <pre><code>def phix(x, N): lam=np.floor(N**(1/3)) x_new=0 for i in range(0, int(lam)): ...
<p>Assuming that <code>N</code> is always a constant, you can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.vectorize.html" rel="nofollow noreferrer"><code>numpy.vectorize</code></a>:</p> <pre><code>def adapW1_eot(x, y, N: int): x_new = np.vectorize(phix)(x, N) ... </code></pre> <p>Then <c...
python|numpy
1
370,297
73,119,881
How to write pandas' merge_asof equivalence in PySpark
<p>I am trying to write a <a href="https://pandas.pydata.org/pandas-docs/version/0.25.0/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer">merge_asof</a> function of pandas in Spark.</p> <p>Here is a sample example:</p> <pre><code>df1 = spark.createDataFrame( [ (datetime(2019,2,3,13,30,0,23...
<p>You can do it by first joining and then using <code>last</code> over window:</p> <pre class="lang-py prettyprint-override"><code>from pyspark.sql import functions as F, Window as W df = df2.join(df1, ['time', 'ticker'], 'left') w = W.partitionBy('ticker').orderBy('time') df = df.withColumn('bid', F.coalesce('bid', ...
python|pandas|apache-spark|pyspark|window-functions
2
370,298
72,909,275
pandas.to_gbq() returning "ArrowTypeError: Expected bytes, got a 'datetime.date' object" error
<p><code>pandas.to_gbq()</code> has recently started returning an error when I attempt to append a dataframe to a BigQuery table, despite the df schema/data types being the exact same as those of the BigQuery table.</p> <p>Code snippet below:</p> <pre><code>df.to_gbq(destination_table = PROCESSED_DATA_TABLE_NAME, ...
<p>This is a problem with the pandas to_gbq() method, and one solution is to use google cloud's bigquery package.</p> <p>While the schema of the bigquery table and the local df are the same, appending to the BigQuery table can be accomplished with the following code:</p> <pre><code>from google.cloud import bigquery imp...
python|pandas|google-bigquery
2
370,299
73,094,814
Add element in the beginning of a list which extracted from a dataframe
<p>I wanted to add an element at the beginning of a list which is extracted from a pandas dataframe. Below is my example.</p> <pre><code>import pandas as pd dat = pd.DataFrame({'X' : [1,2], 'Y' : ['A', 'B']}) [999] + dat['X'].values ### array([1000, 1001]) </code></pre> <p>I wanted to add element 999 at the beginning b...
<p>you can use <code>pd.concat()</code> for data frame column or <code>list.insert()</code> for a simple list, <code>list.insert()</code> takes the index where you want to insert your new value as the first argument and the value as the second argument. <code>pd.concat()</code> takes the value you want to insert then t...
arrays|python-3.x|pandas
0