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
14,900
61,531,951
Understanding np.where() in the context of Logistic Regression
<p>I am currently studying the Deep Learning specialization taught on Coursera by Andrew Ng. In the first assignment, I have to define a prediction function, and wanted to know if my alternative solution is as valid as the actual solution. </p> <p>Please let me know if my understanding of the np.where() function is co...
<p>Your alternative approach seems fine. As a remark, I'll add that you don't even need the <code>np.ones</code> and <code>np.zeros</code>, you can just specify directly the integers <code>0</code> and <code>1</code>. When using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofoll...
python|numpy|machine-learning|logistic-regression
2
14,901
53,314,971
Search for part strings in header python pandas
<p>I think I've read all similar posts and haven't found what I need.</p> <p>I have a bunch of .csv files which are in principle similar but may have a bit different Header names, columns are positioned differently etc. I call them using pd.read_csv: </p> <pre><code>df = pd.read_csv('MyFile.csv', delimiter=';') </co...
<p>Use:</p> <pre><code>m1 = df.columns.str.contains('laenge') m2 = df.columns.str.contains('length') m = m1 &amp; m2 df1 = df.loc[:, m] </code></pre>
python|pandas|dataframe
3
14,902
65,515,721
Some points are not displayed on the graph plotted using NumPy and matplotlib
<p>For the following code whose job is to perform Monte Carlo integration for a function f, I was wondering what would happen if I define f as y = sqrt(1-x^2), which is the equation for a unit quarter circle, and specify an endpoint that is greater than 1, since we know that f is only defined for 0&lt;x&lt;1.</p> <pre>...
<p>You can just print out the arrays (for example by generating only one random point) and see that they go into neither <code>ind_below</code> nor <code>ind_above</code>...</p> <p>That's because all comparisons that involves <code>nan</code> returns <code>False</code>. (See also: <a href="https://stackoverflow.com/que...
python|arrays|numpy|matplotlib
2
14,903
65,844,348
How to give multiple conditions to numpy.where()
<p>I have a numpy array like this:</p> <pre><code>letters = np.array([A, B, C, A, B, C, A, B, C]) </code></pre> <p>I'm trying to return another array containing all the indexes of certain items in the array above. I have tried:</p> <pre><code>letter_indexes = np.where(np.any(letters == 'A', letters == 'C')) </code></pr...
<p>You can use <code>np.in1d</code>:</p> <pre><code>np.where(np.in1d(letters, ['A', 'C']))[0] Out[]: array([0, 2, 3, 5, 6, 8], dtype=int64) </code></pre> <p>If you've got multiple more complex conditions, you can use <code>functools.reduce</code></p> <pre><code>from functools import reduce conditions = [letters == 'A'...
python|arrays|numpy
1
14,904
53,678,519
Grouping columns by data type in pandas series throws TypeError: data type not understood
<p>I am grouping values by type as follows:</p> <pre><code>groups = frame.columns.to_series().groupby(frame.dtypes).groups </code></pre> <p>by I get error:</p> <pre><code>TypeError: data type not understood </code></pre> <p>What would be the right way to go about grouping columns by datatype to prevent such errors?...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> along <code>axis=1</code>:</p> <pre><code>type_dct = {str(k): list(v) for k, v in df.groupby(df.dtypes, axis=1)} </code></pre> <p>For your sample dataframe, ...
python|pandas|dataframe|pandas-groupby
4
14,905
53,570,334
Documentation for PyTorch .to('cpu') or .to('cuda')
<p>I've searched through the <a href="https://pytorch.org/docs/stable/index.html" rel="noreferrer">PyTorch documenation</a>, but can't find anything for <code>.to()</code> which moves a tensor to CPU or CUDA memory.</p> <p>I remember seeing somewhere that calling <code>to()</code> on a <code>nn.Module</code> is an in-...
<p>You already found the documentation! great.</p> <p><code>.to</code> is not an in-place operation for tensors. However, if no movement is required it returns the same tensor.</p> <pre><code>In [10]: a = torch.rand(10) In [11]: b = a.to(torch.device("cuda")) In [12]: b is a Out[12]: False In [18]: c = b.to(torch....
python|pytorch
14
14,906
53,788,758
Pandas: Find first occurrences of elements that appear in a certain column
<p>Let's assume that I have the following data-frame:</p> <pre><code>df_raw = pd.DataFrame({"id": [102, 102, 103, 103, 103], "val1": [9,2,4,7,6], "val2": [np.nan, 3, np.nan, 4, 5], "val3": [4, np.nan, np.nan, 5, 1], "date": [pd.Timestamp(2002, 1, 1), pd.Timestamp(2002, 3, 3), pd.Timestamp(2003, 4, 4), pd.Timestamp(200...
<p>IIUC using <code>drop_duplicates</code> then <code>concat</code></p> <pre><code>df1=df_raw.drop_duplicates('id').fillna(-1) target=pd.concat([df1,df_raw.loc[~df_raw.index.isin(df1.index)]]).sort_index() target date id val1 val2 val3 0 2002-01-01 102 9 -1.0 4.0 1 2002-03-03 102 2 3.0 Na...
python|pandas
2
14,907
55,503,358
How to perform (modified) t-test for multiple variables and multiple models
<p>I have created and analyzed around 16 machine learning models using WEKA. Right now, I have a CSV file which shows the models' metrics (such as percent_correct, F-measure, recall, precision, etc.). I am trying to conduct a (modified) student's t-test on these models. I am able to conduct one (according to THIS link)...
<p>This is a simple solution to my question. It only deals with two models and two variables, but you could <em>easily</em> have lists with the names of the classifiers and the metrics you want to analyze. For my purposes, I just change the values of <code>COI</code>, <code>ROI_1</code>, and <code>ROI_2</code> respecti...
python|pandas|data-visualization|t-test|hypothesis-test
1
14,908
55,508,930
How to fetch the entire rows having even numbers in numpy?
<p>I'm trying want to fetch the rows that are having even numbers from the array below:</p> <pre><code> mat1 = np.array([[23,45,63],[22,78,43],[12,77,47],[53,47,33]]).reshape(4,3) mat1 array([[23, 45, 63], [22, 78, 43], [12, 77, 47], [53, 47, 33]]) </code></pre> <p>And the below code returns o...
<p>You can do that like this:</p> <pre><code>import numpy as np mat1 = np.array([[23,45,63],[22,78,43],[12,77,47],[53,47,33]]) is_even = (mat1 % 2 == 0) # Rows print(mat1[is_even.any(1)]) # [[22 78 43] # [12 77 47]] # Columns print(mat1[:, is_even.any(0)]) # [[23 45] # [22 78] # [12 77] # [53 47]] </code></pre>
arrays|python-3.x|numpy
1
14,909
56,547,197
Why is the tensor description of placeholder returned when using sess.run(placeholder, feed_dict)?
<pre><code>sess = tf.Session() sess.run(cost,feed_dict={z:logits,y:labels}) sess.close() print(cost) </code></pre> <p>In the above snippet, it prints the tensor description <strong>"cost = Tensor("logistic_loss_6:0", dtype=float32)"</strong> rather than the value of cost.</p> <p>However, if I use </p> <pre><code...
<p>One of the fundamental things to understand about Tensorflow is that it creates a computation graph that contains all operations. So in fact, the content of the variable <code>cost</code> is a tensor, which is an operation of the graph, that's why you get what you get, when printing it directly. In order to get the ...
python|tensorflow|deep-learning
1
14,910
67,113,863
Issue of creating a Dataframe
<p>I am trying to create a dataframe by using for loop. It works but the output of the dataframe is not correct. Each cell of the Dataframe contain all data. May I know how can I fix it?</p> <p>Here is the code:</p> <pre><code>from pandas_datareader import data import datetime from math import exp, sqrt import pandas a...
<p>Since you're looping over symbols, you should change <code>data.DataReader(test...</code> to <code>data.DataReader(i...</code> (otherwise it reads data for both of them on every iteration):</p> <pre><code>for i in test: stock_price = data.DataReader(i, start='2021-01-01', ...
python|pandas|dataframe
0
14,911
68,117,581
How to use resample while keeping the missing dates
<p>Hello I have the following database:</p> <pre><code> name_normalized method day 2020-01-06 o2 mega searchNotes 2020-01-06 adiral searchPatients 2020-01-06 adiral searchPatients 2020-01-06 o2 mega searchPatients 2020-01-06 adiral searchPatients </code></pre> <pre><code>.tail() </code></pre> <pre><...
<p>As an option, <code>unstack</code> by day with <code>fill_value=0</code> and <code>stack</code> it back:</p> <pre><code>rep_month = Only2020_PPC.groupby( ['name_normalized','method']).resample('M')['method'].count() # unstack by day with fill_value=0 and stack it back rep_month = rep_month.unstack('day', fill_v...
python|pandas
1
14,912
68,384,452
Odds ratios using Python statsmodels
<p>I'm running logistic regressions using statsmodels logit and, downstream, am calculating odds ratios for each independent variable (i.e., exp(B)).</p> <p>I know that, conventionally, an odds ratio is interpreted per &quot;one unit&quot; increase in the value of the variable. I think my ultimate question is how can ...
<p>Simple answer is 1 unit corresponds to 1 degree change in temperature. Whole number unit changes still apply as they would in respiratory_rate, you just happen to have additional precision with your temperature variable. An OR = 2.75 implies that for a 1 unit increase in temperature (1 degree), the odds of your outc...
python|pandas|statistics|regression|logistic-regression
1
14,913
68,351,989
psycopg2 - insert into variable coumns using extras.batch_execution
<p>I am inserting a pandas dataframe into postgres using psycopg2. Below code:</p> <pre><code>... import psycopg2.extras as extras tuples = [tuple(x) for x in df.to_numpy()] cols = ','.join(list(column_list)) query = &quot;INSERT INTO %s(%s) VALUES (%%s,%%s,%%s,%%s,%%s)&quot; % (table , cols) extras.execute_batch(c...
<p>The problem is the location of the %. Because of operator precedence, % binds tighter than +. So:</p> <pre><code>query = &quot;INSERT INTO %s(%s) VALUES(&quot;+vals_frame+&quot;)&quot; % (table , cols) </code></pre> <p>The <code>%</code> operator here applies to the string &quot;)&quot;. Here are some alternati...
python|pandas
0
14,914
57,033,699
What does loss layer do during inference ? To be clear during the forward propagation
<p>I am having a model that uses a very large number of ops for l2 loss. And this ends up being more than the number of mul and add ops. I want to know if it's possible to remove them ? And if not why </p>
<p>Inference refers to the process of using a trained deep learning algorithm to make a prediction. So during this time network perform classify, recognize and process new inputs.</p> <p>Where as before the training of the network begins, the weights in the convolution and fully-connected layers are given random value...
tensorflow|conv-neural-network
0
14,915
57,116,074
TensorFlow - return distinct sub-tensors of multidimensional tensor
<p>In TensorFlow, the <code>tf.unique</code> function can be used to return the distinct elements of a 1-dimensional <code>Tensor</code>. How can I get the distinct sub-<code>Tensor</code>s along the axis 0 of a higher-dimensional <code>Tensor</code>? For example, given the following <code>Tensor</code>, the desired <c...
<p><strong>Without preserving Order</strong></p> <p>You can use <code>tf.py_function</code> and call <code>np.unique</code> to return unique multidimensional tensors along axis=0. Note that this finds the unique rows but does not preserve the order.</p> <pre><code>def distinct(a): _a = np.unique(a, axis=0) r...
python|tensorflow|tensorflow2.0
4
14,916
46,136,411
Find date difference of a specific date from a date column in Pandas
<pre><code>policy.Exposure.fillna(pd.to_datetime(2016,12,31) - policy.EnrollDate,inplace=True) </code></pre> <p>I want to fill the missing value of my Exposure column with the day difference of 2016,12,31 - EnrollDate column. How should I write this? </p> <p>All similar questions are subtracting one column from anoth...
<p>You can fill those <code>NaT</code> values with <code>pd.Series.fillna</code> and <em>then</em> subtract.</p> <pre><code>dt = pd.to_datetime('2016/12/31', format='%Y/%m/%d') policy['Exposure'] = (policy.CancelDate.fillna(dt) - policy.EnrollDate).dt.days </code></pre>
python|pandas|datetime
3
14,917
46,052,676
pandas dataframe assign doesn't update the dataframe
<p>I made a pandas dataframe of the <a href="https://www.kaggle.com/benhamner/python-data-visualizations" rel="nofollow noreferrer">Iris dataset</a> and I want to put 4 extra column in it. The content of the columns have to be SepalRatio, PetalRatio, SepalMultiplied, PetalMultiplied. I used the assign() function of the...
<p>You need assign output to variable like:</p> <pre><code>iris = iris.assign(SepalRatio = iris['SepalLengthCm'] / iris['SepalWidthCm']).assign(PetalRatio = iris['PetalLengthCm'] / iris['PetalWidthCm']).assign(SepalMultiplied = iris['SepalLengthCm'] * iris['SepalWidthCm']).assign(PetalMultiplied = iris['PetalLengthCm'...
python|pandas|jupyter|data-analysis
8
14,918
46,063,093
Assign into a grid of a NumPy array given row and column indices
<p>I want to access a specific row and column restriction of a 2d numpy array.</p> <pre><code>&gt; x array([[1, 2, 0], [3, 4, 0], [0, 0, 1]]) </code></pre> <p>If I do what seems natural, I just get the diagonal elements of the restricted array.</p> <pre><code>&gt; x[[0,1], [0,1]] array([1, 4]) </code><...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ix_.html" rel="nofollow noreferrer"><code>np.ix_</code></a> to map that grid of elements and then assign -</p> <pre><code>x[np.ix_([0,1], [0,1])] = np.array([[1,0],[0,1]]) </code></pre>
python|arrays|numpy
2
14,919
66,432,369
Applying Filter to Pandas Pivot Table blanks out data
<p>Using the following csv data: <a href="https://i.stack.imgur.com/ZqGcg.png" rel="nofollow noreferrer">Data Image</a></p> <p>I've loaded the data from a csv into a Pandas Pivot Table with the output:</p> <pre><code>[[nan nan nan ... nan nan 0.] [nan 21 nan ... nan 0. nan] [nan nan nan ... 0. nan nan] ... [23. ...
<p>This filter is implemented as a sequence of 1-D convolution filters. If your data is nostly <code>nans</code>, these <code>nans</code> get into the convolutions as multipliers and htnce turn the whole convolution results into <code>nans</code>. consider replacing <code>nans</code> with zeros.</p>
python|pandas|scipy
0
14,920
66,598,511
Pandas Group_by using multiple keys, but only want to specify outer key
<p>I have just started learning about pandas. I am doing a project with video games sales data. The data frame I'm working with looks like this:</p> <pre><code> Rank Name Platform Year Genre Publisher Global_Sales 0 1 Wii Sports Wii 2006.0 Sports Nintendo 41.49...
<p>Is this what you need?</p> <pre><code>df.groupby(['Year', 'Genre']).sum('Global_Sales') </code></pre>
python|pandas|dataframe|group-by|pandas-groupby
0
14,921
51,298,548
How to handle different types of dates in a column in pandas
<p>I'm trying to find different data types in a column of pandas dataFrame and have them in a separate column for some computation. I have tried Regex with mask function to identify other data types like string and integer as shown below</p> <pre><code>df[data_types]=df[i].astype(str).str.contains('^[-+]?[0-9]+$', cas...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select</code></a> for create new column by multiple condition and for datetimes use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferr...
python-3.x|pandas
2
14,922
51,200,821
Keras Layer Concatenation
<p>I'm trying to see how I can create a model in Keras with multiple Embedding Layers and other inputs. Here's how my model is structured(E=Embedding Layer, [....]=Input Layer):</p> <pre><code>E E [V V V] \ | / \ | / Dense | Dense </code></pre> <p>Here is my code so far:</p> <pre><code>model_a = Seque...
<pre class="lang-py prettyprint-override"><code>input1 = Input(input_shape=...) input2 = Input(...) input3 = Input(...) values = Input(...) out1 = Embedding(...)(input1) out2 = Embedding(...)(input2) out3 = Embedding(...)(input3) #make sure values has a shape compatible with the embedding outputs. #usually it shou...
tensorflow|neural-network|keras|embedding|keras-layer
4
14,923
35,860,827
What's the advantage of preparing a matrix to return in python?
<p>It's the code in the book 'Machine Learning in Action'. <a href="https://github.com/pbharrin/machinelearninginaction/blob/master/Ch02/kNN.py" rel="nofollow">source code</a></p> <p>And the what is passed to <code>dataSet</code> is a m * 3 array(<code>datingTestSet2.txt</code> which can be found in the superior direc...
<p>There's no advantage. In the code you show, the first assignment to <code>normDataSet</code> has no lasting effect, because two lines later there's a second assignment to <code>normDataSet</code>. At that point, the reference count of the <code>zeros</code> array object that was previously bound to <code>normDataSet...
python|numpy|matrix
2
14,924
37,545,110
Code completion for C code in TensorFlow
<p>I am developing a custom Op for TensorFlow, using Ubuntu on virtual machine and either rmate to edit the code in local Atom installation on my Mac, or Emacs to edit it right on the virtual machine. </p> <p>Is there a way to enable code completion suggestions for C code in TensorFlow? </p>
<p>There's no special support in TensorFlow for code completion, but there may be a specific solution for your editor. For example, <a href="https://superuser.com/a/528407">this answer on SuperUser</a> covers different approaches to C/C++ code completion in Emacs.</p> <p>One way I've managed to get C++ auto-completion...
c|emacs|tensorflow|atom-editor
1
14,925
41,868,845
Selecting top 3 elements within groupby
<p>Given the following pandas group by table, how could I get the top 3 <code>index</code> for <code>Offline_RentetionAge</code> within each <code>CPUCore</code>, and keep the structure of the table?</p> <p><a href="https://i.stack.imgur.com/6LX0B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6LX0...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.head.html" rel="nofollow noreferrer"><code>GroupBy.head</code></a> if values in <code>index column</code> are sorted:</p> <pre><code>df = df.groupby(level=0).head(3) </code></pre> <p>Sample:</p> <pre><code>df = ...
pandas
0
14,926
37,973,619
Tensorflow converging but bad predictions
<p>I posted a similar question the other day <a href="https://stackoverflow.com/questions/37898795/tensorflow-accuracy-at-99-but-predictions-awful">here</a>, but I have since made edits to bugs that I found, and the problem of bad predictions remains. </p> <p>I have two networks -- one with 3 conv layers and another w...
<p>The concept of deconvolution is to output something of the same size as the input.</p> <p>At the line:</p> <pre><code>conv6 = tf.nn.bias_add(conv6, biases['bdc3']) </code></pre> <p>You have this output of shape <code>[batch_size, 200, 200, 2]</code>, so you <strong>don't need</strong> to add your fully connected lay...
python|machine-learning|neural-network|artificial-intelligence|tensorflow
1
14,927
37,787,897
Numpy: Functional assignment?
<p>Suppose I want to create an array <code>b</code> which is a version of array <code>a</code> with the <code>i</code>'th row set to zero.</p> <p>Currently, I have to do:</p> <pre><code>b = a.copy() b[i, :] = 0 </code></pre> <p>Which is a bit annoying, because you can't do that in lambdas, and everything else in num...
<p>Do you mean a simple function like this:</p> <pre><code>def subtensor(a, ind, val): b=a.copy() b[ind] = val return b In [192]: a=np.arange(12).reshape(3,4) In [194]: subtensor(a,(1,slice(None)),0) Out[194]: array([[ 0, 1, 2, 3], [ 0, 0, 0, 0], [ 8, 9, 10, 11]]) </code></pre> <p>...
numpy
0
14,928
31,600,224
How to use fmt in numpy savetxt to align information in each column
<p>I found someone else's use of fmt and tried to adapt it to my purposes. However, I do not understand it, despite reading about it here: <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html</a>. I would l...
<p>You can do it without str.format: </p> <pre><code>np.savetxt('test_file_name.txt', combined, fmt="%-12s") </code></pre> <p>Output:</p> <pre><code>str123456789 1 str2 2458734750 str3 3 </code></pre> <p><code>-</code> is left aligned and <code>12</code> is the width. You nee...
python|numpy
6
14,929
31,481,803
Compute percentage for each row in pandas dataframe
<pre><code> country_name country_code val_code \ United States of America 231 1 United States of America 231 2 United States of America 231 3 United States of America 231 ...
<p>You can get the percentages of each column using a <code>lambda</code> function as follows:</p> <pre><code>&gt;&gt;&gt; df.iloc[:, 3:].apply(lambda x: x / x.sum()) y191 y192 y193 y194 y195 0 0.527231 0.508411 0.490517 0.500544 0.480236 1 0.013305 0.014088 0.013463 0.013631 0.013...
python|pandas
15
14,930
47,880,332
convert a embedded json string into pandas dataframe
<p>I have following data:</p> <pre><code>json_str = "[{“key1”: “value1”, “key2”= “value2”, “key3”: “{“key_a”: “value_a1”, “key_b”: “value_b1”, “key_c”: “value_c1”}”,“key4”: 4}, {“key1”: “value5”, “key2”= “value6”, “key3”: “{“key_a”: “value_a2”, “key_b”: “value_b2”, “key_c”: “value_c2”}”,“key4”: 8}]" </code></pre> <...
<p>There is a need for cleaning of data, here's one way of doing it </p> <pre><code>from functools import reduce import ast di = {'“':"'", '”':"'", "'{":'{', "}'":"}", "=":':' } new = reduce(lambda x, y: x.replace(y, di[y]), di, json) df = pd.io.json.json_normalize(ast.literal_eval(new)) print(df) key1 ke...
python|json|pandas
0
14,931
49,196,602
StopIteration: Could not import PIL.Image. The use of `array_to_img` requires PIL error
<pre class="lang-python prettyprint-override"><code>import keras Using TensorFlow backend. from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator( rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1./255...
<p>I had the same problem. If you are using Anaconda and the Jupyter notebook this is what worked for me.</p> <p>Close your notebook and stop Jupyter. Exit out of your environment Restart the environment again and run:</p> <p><strong>pip install pillow</strong></p> <p>and then:</p> <p><strong>pip install jupyterla...
image|tensorflow|keras|deep-learning|python-imaging-library
1
14,932
58,944,088
cannot unpack non-iterable NoneType object, trying to plot a bar graph
<p>I'm working on this lab for a class and I keep getting the error from the title. What we're supposed to be doing is making a bar graph from a csv file, and I don't really know why I'm getting these errors but it looks like its due to the line</p> <pre><code>college_names, college_enrollments = read_file(file_name) ...
<p>Add <code>return (college_names, college_enrollments)</code> in the end of your <code>read_file</code> function. Your current function doesn’t have any return so python couldn’t unpack it as it expects a collection.</p>
python|numpy|matplotlib
0
14,933
70,332,850
Numpy sort much slower than Matlab sort
<p>I am turning some codes from Matlab to Python. I am sometimes quite surprised by the performance loss. Here is an example on sorting arrays, which turns me nuts.</p> <p><strong>Matlab :</strong></p> <pre class="lang-matlab prettyprint-override"><code>a=rand(50000,1000);tic;b=sort(a,1);toc </code></pre> <p><em>Elapse...
<p>After spending a few hours and checking with colleagues, the solution is now clear:</p> <p><strong>np.sort <em>is not multi-threaded and there is no way to accelerate it.</em></strong></p> <p>It suffices to look at the sources to check this:</p> <p><a href="https://github.com/numpy/numpy/tree/main/numpy/core/src/npy...
python|numpy|matlab|openmp
0
14,934
56,143,216
My sum function does not sum values of some columns
<p>So I have a dataframe, that has some columns with calculated values or values from input:</p> <pre><code>Data = {'name': ['a', 'b'], 'number1': [5, 3], 'number2': [3, 2] } df = pd.DataFrame(Data, columns = ['name','number1', 'number2']) </code></pre> <p>Then I write my total function like ...
<p>Assign it again after all of the code (with <code>axis=1</code>):</p> <pre><code>... df.loc['Grand Total']=df.sum(axis=1) </code></pre>
python|excel|pandas|dataframe
0
14,935
56,085,659
Deleting row from pandas dataframe and dynamically reducing the size of the array
<p>Have a pandas dataframe, want to delete a row on equalizing with some value. Get a 'the label [some integer] is not in the [index]' error</p> <pre><code>while i &lt; 881: ctr=0 sent=df1.loc[i,"text"] print ("SENTENCE:",i,sent) for j in range(i+1,len(df1)): to_compare=df1.loc[j,"text"] ...
<pre><code>range(i+1,len(df1)) </code></pre> <p>creates an iterator that is not updated when len(df1) changes, thus after dropping lines and reindexing, in</p> <pre><code>to_compare=df1.loc[j,"text"] </code></pre> <p>you are passing an index that does not longer exist. An easy fix should be to let the inner loop fin...
python|pandas
0
14,936
56,293,376
Hybridizing Numpy vectorization and plain Python
<p>I have a 2-dimensional <code>ndarray</code>, the rows of which shall be scanned to check whether any one is equal to any other. </p> <p>My first try actually works, but I feel it is not the optimal way. It takes time once the number of rows in the matrix approaches 1000. </p> <p>My code is the following. <code>X</...
<h2>Approach #1</h2> <p>We could leverage row-views to get the pairwise matches. Then, run the loop and assign those in <code>Y</code>. The idea is to minimize the work once we start running loop. Considering that there could be more than one index matching with other indices, a purely vectorized method would be hard ...
python|python-3.x|numpy|vectorization
3
14,937
56,188,792
Convert json string image to numpy 2D array
<p>I'm having troubles with json. I'm trying to convert an image that I'm receiving with json to a 2D numpy array. I've tried a few things but nothing is working.</p> <p>Here is how I get the image:</p> <pre class="lang-py prettyprint-override"><code>@app.route("/&lt;path:fullurl&gt;", methods=['GET', 'POST']) def ma...
<p>Well, i figured out the solution to my problem. It's simple, the string i receive from the json object that represents my image is encoded in base64, that's true. Since i didn't know anything about json objects or base64 at that time, i didn't realise that there is a header at the beginning of the string. So, my sol...
python|json|numpy
0
14,938
56,361,302
Unable to delete a Tensorflow training job on google cloud
<p>I have created 2 Tensorflow Object Detection jobs on Google Cloud. I cancelled one of them and the other has failed. I have tried looking for ways to delete these jobs but am unable to do so. Is there any way I can delete the jobs? Also, will I be billed for these jobs even though they are cancelled/stopped?</p> <p...
<p>It appears that you cannot currently <em>delete</em> GCP AI Platform jobs. The API only describes <a href="https://cloud.google.com/ai-platform/training/docs/managing-models-jobs#managing_jobs" rel="nofollow noreferrer">four operations</a> for jobs: <code>create</code>, <code>cancel</code>, <code>get</code>, and <c...
python|tensorflow|google-cloud-platform|google-compute-engine|object-detection-api
1
14,939
64,790,114
How do I convert this TimeDelta column to total minutes in pandas Datafram
<p><img src="https://i.stack.imgur.com/Rbwyol.png" alt="See column here for visualisation" /></p> <p>I have tried the following without luck:</p> <pre><code>df['TimedSpentInZone'] = df.TimedSpentInZone.astype(int) df['TimedSpentInZone'] = df['TimedSpentInZone'].dt.total_seconds() df['TimedSpentInZone'] = df['TimedSp...
<p>You can, and should convert to <code>Timedelta</code> type:</p> <pre><code>pd.to_timedelta(df['TimedSpentInZone'])/pd.Timedelta('60s') </code></pre>
python|pandas|dataframe|datetime|timedelta
2
14,940
64,780,848
How to add a calculated column based on conditions in pandas?
<p>I have a <code>dataframe</code> below:</p> <pre><code>import pandas as pd data = pd.DataFrame({ 'ID': ['27459', '27459', '27459', '27459', '27459', '27459', '27459', '48002', '48002', '48002'], 'Invoice_Date': ['2020-06-26', '2020-06-29', '2020-06-30', '2020-07-14', '2020-07-25', ...
<p>The <code>Average_Delay</code> can be calculated using <code>.groupby</code> and <code>.resample</code> like:</p> <pre><code>df.groupby(&quot;ID&quot;).get_group(&quot;27459&quot;).resample(&quot;30D&quot;, on=&quot;Invoice_Date&quot;).mean()[&quot;Delay&quot;] </code></pre> <p>results in</p> <pre><code>Invoice_Date...
python|pandas|dataframe|loops|rows
0
14,941
39,938,170
How to manipulate individual elements in a numpy array iteratively
<p>Let's say I want to iterate over a numpy array and print each item. I'm going to use this later on to manipulate the (i,j) entry in my array depending on some rules.</p> <p>I've read the numpy docs and it seems like you can access individual elements in an array easily enough using similar indexing(or slicing) to l...
<p>Start with:</p> <pre><code>for i in range(row): for j in range(column): print space[i,j] </code></pre> <p>You are generating indices in your loops which index some element then!</p> <p>The relevant <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow">numpy docs on in...
arrays|python-2.7|numpy|iteration
2
14,942
39,715,910
Trying to create a pandas series within a dataframe with values based on whether or not keys are in another dataframe
<p>Boiling it down simply...</p> <p>Dataframe 1 = yellow_fruits The columns are fruit_name, and location</p> <p>Dataframe 2 = red_fruits The columns are fruit_name, and location</p> <p>Dataframe 3 = fruit_montage The columns are fruit_name, pounds_of_fruit_needed, freshness</p> <p>Let's say I want to add a column t...
<p>The classic way would be to use your conditions as indexers:</p> <pre><code>df1 = pd.DataFrame({'fruit_name':['banana', 'lemon']}) df2 = pd.DataFrame({'fruit_name':['strawberry', 'apple']}) df3 = pd.DataFrame({'fruit_name':['lemon', 'rockmelon', 'apple']}) df3["color"] = "unknown" df3["color"][df3['fruit_name'].is...
python|pandas|dataframe|series
1
14,943
39,736,386
Correct way to configure interdependent projects (e.g. tensorflow) in bazel build system so proto imports work as is?
<p>As the title suggests, I'm running into an issue where proto import statements do not seem to be relative to the correct path. For concreteness, consider the directory structure in a dir (let's call it ~/base):</p> <pre><code>`&gt;&gt; tree -L 1 ├── models ├── my-lib | ├── nlp | ├── BUILD | └── nl...
<p>I was having a similar problem after trying to build a project of mine depending on tensorflow on Ubuntu after getting it building on OS X. What ended up working for me was disabling sandboxing with <code>--spawn_strategy=standalone</code></p>
tensorflow|bazel|syntaxnet|tensorflow-serving
2
14,944
44,037,942
Pandas select all columns from m to n and replace values on a condition
<p>I have a pandas dataframe looking like:</p> <pre><code>df=pd.DataFrame([list('abcd'),list('efgh'),list('ijkl'),list('mnop')], columns=['one','two', 'three', 'four']) In [328]: df Out[328]: one two three four 0 a b c d 1 e f g h 2 i j k ...
<p>You can use <code>.iloc</code> to numerically index your dataframe, apply a function to replace the values for each cell, then save that output back to the original dataframe</p> <pre><code>d = {'h':1, 'k':2} df.iloc[:,1:4] = df.iloc[:,1:4].applymap(lambda x: d[x] if x in d else x) df # returns one two three fou...
python|pandas
3
14,945
69,553,637
Color code geopandas plot by column value
<p>I have a geopandas dataframe created with some open street map data. Is there away to use the built in plot method to color code the dataframe based on the value of a specific column?</p> <p>I.e. instead of</p> <pre><code>for color, group in gdf.groupby(['col']): plt.plot(group['X'], group['Y'], c=colors[color])...
<p>Could be done using <code>geoplot</code> library.</p> <pre><code>import geoplot as gplt import geopandas as gpd gplt.choropleth(gpd_df, hue='ex_gpd_df_col', projection=gplt.crs.PlateCarree()) </code></pre>
geopandas
0
14,946
69,336,920
Finding a multi-value submatrix with wildcards
<p>I have a matrix with these values (if it helps, this an rgb image):</p> <pre><code>mat = np.array([ [[0, 0, 0], [123, 0, 255], [0, 0, 0]], [[0, 0, 0], [123, 0, 255], [45, 0, 54]], [[0, 0, 0], [100, 0, 100], [45, 0, 54]], ]) </code></pre> <p>I'm trying to find index locations of a pattern like:</p> <pre><...
<p>How about this:</p> <pre><code>from scipy.signal import correlate2d import numpy as np mat = np.array([ [[0, 0, 0], [123, 0, 255], [0, 0, 0]], [[45, 0, 54], [124, 0, 255], [45, 0, 54]], [[127, 0, 255], [45, 0, 54], [45, 0, 54]], ]) # Find all of the places in the matrix where each condition is satisfie...
python|numpy|image-processing|numpy-ndarray
1
14,947
69,580,708
Pandas create dictionary with merge cells
<p>I have the excels file with merged cells on column A and 2 values on column B and C like on this image <a href="https://i.stack.imgur.com/wnPsf.png" rel="nofollow noreferrer">https://i.stack.imgur.com/wnPsf.png</a> (sorry I'm not allowed to upload images yet) In case the image not working, I'm posting the example to...
<p>First forward filling missing values and then create nested lists, <code>groupby</code> is used for working if multiple categories in column <code>A</code>:</p> <pre><code>df = pd.DataFrame({'A': {0: 'A', 1: np.nan, 2: np.nan}, 'B': {0: 'B1', 1: 'B2', 2: 'B3'}, 'C': {0: 'C1', 1...
python|pandas
0
14,948
41,191,441
checking for truthiness on a numpy array but for 2 values
<p>I have a numpy array such as</p> <pre><code>import numpy as np x = np.array(range(1, 10)) </code></pre> <p>assuming that <code>x</code> is a 'timeseries' I am testing for truthiness on 2 conditions, if <code>x</code> t is larger than 5 and <code>x</code> t-1 is larger than 5 at the same time</p> <p>is there a mor...
<p>I wouldn't call your expression "weird"; using shifted slices like that is pretty common in numpy code. There is some inefficiency, because you are repeating the same comparison <code>len(x) - 1</code> times. For a small array, it might not matter, but if in your actual code <code>x</code> can be much larger, you co...
python|numpy
1
14,949
53,971,047
The "to_csv' method does not prompt the download window
<p>I have been trying to download my dataset. I am using Python 3 on Google Colab. </p> <p>Unfortunately, the code works, but no download window appears that would prompt me to download my dataframe, that I converted using the "to_csv" method of Pandas library.</p> <p>Here is my code</p> <pre><code>download = pd.Dat...
<p>Using the file browser on the left hand side, right click and select download to save any file.</p> <p>Here's a complete example: <a href="https://i.stack.imgur.com/XxWW6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XxWW6.png" alt="enter image description here"></a></p>
python-3.x|pandas|google-colaboratory
0
14,950
38,288,372
Unable to drop a column from pandas dataframe
<p>I have imported a Excel sheet into pandas. It has 7 columns which are numeric and 1 column which is a string (a flag).</p> <p>After converting the flag to a categorical variable, I am trying to drop the string column from the Pandas dataframe. However, I am not able to do it.</p> <p>Here's the code:</p> <pre><cod...
<p>You have to use the <strong><em>inplace</em></strong> and <strong><em>axis</em></strong> parameter:</p> <pre><code>parts_median_temp.drop('Flag_median', axis=1, inplace=True) </code></pre> <p>The default value of 'inplace' is <strong>False</strong>, and axis' default is <strong>0</strong>. axis=0 means dropping by...
python|pandas
56
14,951
38,124,065
UnicodeDecodeError when add new list to excel using python
<p>I try to add new sheet to excel file with</p> <pre><code>def add_xlsx_sheet(df, sheet_name=u'Десктопы кратко', index=True, digits=2, path=None): book = load_workbook(path) writer = pd.ExcelWriter(path, engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) if sheet_name...
<p>Try the following:</p> <pre><code>df.groupby('member_id').apply(lambda x: add_xlsx_sheet(x, u'Десктопы полно', path='u{}.xlsx'.format(x.name))) </code></pre> <p>If this doesn't work you may need to decode <code>x.name</code>. Or switch to Python 3.</p>
python|excel|pandas|openpyxl
0
14,952
66,248,186
How to remove stop words from a csv file
<p>Currently I am working on a project which analyses Twitter data. I am in the pre-processing stage and am struggling to get my application to remove stop words from the dataset.</p> <pre><code>import pandas as pd import json import re import nltk from nltk.corpus import stopwords nltk.download('stopwords') self.file...
<p>You are trying to check if a list (the result from the regex) is in a set... this operation cannot be done. You need to loop through the list (or do some sort of set operation, e.g. <code>set(tw).difference(stop_words)</code>.</p> <p>Just for clarity:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; ...
python|pandas|dataframe
1
14,953
52,454,546
Use pandas.read_csv to read files containing str() in file's name
<p>I am trying to use pandas.read_csv to read files that contain the date in their names. I used the below code to do the job. The problem is that the files name is not consistent as the number of date change the pattern. I was wondering if there is a way to let the code read the file with parts of the name is the date...
<p>An alternative of using glob.glob() (since it seems not working) is <a href="https://docs.python.org/2/library/os.html#os.listdir" rel="nofollow noreferrer">os.listdir()</a> as explained in this <a href="https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory">question</a> in order to have...
python|string|pandas
1
14,954
52,787,553
Convert a (n_samples, n_features) ndarray to a (n_samples, 1) array of vectors to use as training labels for an sklearn SVM
<p>I'm trying to calculate the ROC and AUC for an SVM model I'm building. I'm following the code from <a href="http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html" rel="nofollow noreferrer">this sklearn example</a>. One of the requirements is that the output labels <code>y</code> need to be binar...
<p>I ended up fixing this by using a <code>LabelEncoder</code>. Thanks @G.Anderson. The <code>flat_member_list</code> is just a list of all the unique user ids encountered both in the labels <code>y</code>, and the vectors <code>X</code>. </p> <pre><code># Encode "present" users as OneHotVectors mlb = MultiLabelBinari...
python|pandas|numpy|encoding|scikit-learn
0
14,955
52,789,489
How to map words to numbers for input into Tensorflow Neural Network
<p>I am trying to build a chatbot with a seq2seq neural network implementation with Tensorflow in Python. I've never done seq2seq before, and most of my research has been rather unhelpful. </p> <p>I'm not going to flat out ask for the code for a Sequence to Sequence chatbot. Instead, my question is how to best go abou...
<p>I believe the best way would be to create a dictionary / index of words mapping to numbers. This would help in converting the numbers back to words as well. The same problem is discussed at <a href="https://stackoverflow.com/questions/2489595/mapping-words-to-numbers-with-respect-to-definition">this</a> thread as we...
python|tensorflow|neural-network|recurrent-neural-network|preprocessor
1
14,956
46,414,812
How to set starting point for matplotlib x axis?
<p>I'm running into what appears to be a simple issue with using Seaborn/matplotlib, in that my x axis values do not appear to correlate correctly to the labels on the bars. For reference, I had a <code>pandas.DataFrame</code> object and dropped the first 20 rows to show a more detailed look at the data, leaving me wit...
<p>Since we know that the ticks in a seaborn barplot always start at 0, we can just add the first value of your <code>revol_util</code> values to the current ticks in a <a href="https://matplotlib.org/api/ticker_api.html#matplotlib.ticker.FuncFormatter" rel="nofollow noreferrer"><code>matplotlib.ticker.FuncFormatter</c...
python|pandas|matplotlib|seaborn
0
14,957
58,420,868
Nan does not drop out in Python
<p>I have a dataframe which is shown below: <a href="https://i.stack.imgur.com/wSCib.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wSCib.png" alt="enter image description here"></a></p> <p>I want to drop out all the record that has nan in 'Rego' column. I tried few commands such as </p> <pre><co...
<p>Maybe some nan value is a str, so do this first:</p> <pre><code>temp_df['Rego'].replace('nan',np.nan,inplace=True) </code></pre> <p>Then now you can do:</p> <pre><code>temp_df_fitered=temp_df[temp_df['Rego'].notnull()] </code></pre>
python|python-3.x|pandas
2
14,958
69,075,791
How to find closest point to a linestring in python?
<p>I have 2 dataframe in the first one I have linestrings and in the second one I have a lot of points. I want to find a closest point to a linestring. I tried something but I guess it doesn't work. How can I do that?</p> <p>Here is my code:</p> <pre><code>def find_keybyvalue (value,dict): for s,d in dict.items(): ...
<ul> <li>without sample data it's difficult to understand solution you require</li> <li>an approach that can be used is <a href="https://geopandas.org/gallery/spatial_joins.html" rel="nofollow noreferrer">spatial joins</a></li> <li>in this example a point has to be on a line string . This could be extended by using <a...
python|pandas|dataframe|geometry|geopandas
0
14,959
68,875,242
Groupby and concat strings for dataframe
<p><strong>Question</strong></p> <p>Given that <code>groupedMarket = df.groupby(&quot;Market&quot;)</code></p> <p>How do I create a new column <code>Related_Markets</code> with strings concatenated <code>&quot;Ticker&quot;+&quot;-&quot;+&quot;Time&quot;+&quot;-&quot;+&quot;Signal&quot;</code> for other members of <code...
<p>Here is a solution using python sets and <code>apply</code>:</p> <pre><code>df['key'] = df[['Ticker', 'Granularity', &quot;Signal&quot;]].apply('-'.join, axis=1) markets = df.groupby('Market')['key'].apply(set) df['related-markets'] = df.apply(lambda s: ', '.join(markets[s['Market']].difference([s['key']])), axis=1)...
pandas
1
14,960
68,914,396
How to count repeated elements in a numpy 2d array?
<p>I have many very large padded numpy 2d arrays, simplified to array A, shown below. Array Z is the basic pad array:</p> <pre><code>A = np.array(([1 , 2, 3], [2, 3, 4], [0, 0, 0], [0, 0, 0], [0, 0, 0])) Z = np.array([0, 0, 0]) </code></pre> <p>How to count the number of pads in array A in the simplest / fastest python...
<p>Try:</p> <pre><code>&gt;&gt;&gt; np.equal(A, Z).all(axis=1).sum() 3 </code></pre> <p>Step by step:</p> <pre><code>&gt;&gt;&gt; np.equal(A, Z) array([[False, False, False], [False, False, False], [ True, True, True], [ True, True, True], [ True, True, True]]) &gt;&gt;&gt; np.equal(A...
python|arrays|numpy|count
4
14,961
60,823,345
Std on dataframe column error IndexEngine
<p>I have few CSV files which have loading as</p> <pre><code>dataframe = pandas.concat (pandas.read_csv (name) for name in list) </code></pre> <p>where list is list of data files.</p> <p>Which have following columns:</p> <pre><code>Date Close/Last Volume Open High Low </code></pre> <p>I want to calcul...
<p>Looks like your <code>Open</code> column has an extra space there at the beginning. Try </p> <p><code>std = dataframe.loc[:," Open"].std(axis = 0, skipna = True)</code></p>
python|pandas|compiler-errors
0
14,962
71,646,716
Pandas explode dictionary to row while maintaining multi-index
<p>Having now checked a multitude of Stack Overflow threads on this, I'm struggling to apply the answers to my particular use case so hoping someone can help me on my specific problem.</p> <p>I'm trying to explode data out of a dictionary into two separate columns while maintaining a multi-index.</p> <p>Here is what I...
<p>If you turn the dictionaries into lists of key-value pairs, you can explode them and then transform the result into two new columns with <code>.apply(pd.Series)</code> (and rename them to your liking) like so:</p> <pre class="lang-py prettyprint-override"><code>df = (df .css_problem_files.apply(dict.items) # t...
python|pandas
2
14,963
71,541,397
Is there a way to modify the input dimension of MobileNet from (224,224,3) to (150,150,3)
<p>Is there a way to modify the input dimension of MobileNet. Whenever I change it to my desired input of (150,150,3) it throws an error.</p> <pre><code>import tensorflow_hub as hub from tensorflow.keras import Sequential # from tensorflow.keras import Activations classifier_url =&quot;https://hub.tensorflow.google....
<p>Take a look <a href="https://keras.io/api/applications/mobilenet/" rel="nofollow noreferrer">here</a> for info on using MobilenetV2. You are not restricted to 224 X 224 if you set include top=False. Also I advise you set the parameter pooling-'Max' That way MobileNet outputs a vector that you can directly feed into ...
tensorflow|transfer-learning
0
14,964
71,726,385
Create pandas column based on conditional data in current or other df columns
<p>If I have two dataframes, as below.</p> <p><code>df_1</code>:</p> <pre><code>id id_type 100 atype 101 atype 102 atype 603 another 604 another 605 another </code></pre> <p>and</p> <p><code>df_2</code>:</p> <pre><code>id_1 id_2 id_3 100 600 200 101 601 200 102 602 200 103 603 300 104 604 400 105 605...
<p>You can <code>melt</code> and <code>merge</code>. For the demo I added a columns <code>col</code> to <code>df_2</code>:</p> <pre><code> id_1 id_2 col 0 100 600 0 1 101 601 1 2 102 602 2 3 103 603 3 4 104 604 4 5 105 605 5 </code></pre> <p>command:</p> <pre><code>df_1.mer...
python|pandas|calculated-columns
0
14,965
42,192,323
Convert Pandas Dataframe to Float with commas and negative numbers
<p>I've read several posts about how to convert Pandas columns to float using pd.to_numeric as well as applymap(locale.atof). </p> <p>I'm running into problems where neither works. </p> <p>Note the original Dataframe which is dtype: Object</p> <pre><code>df.append(df_income_master[", Net"]) Out[76]: Date 2016-...
<p>It seems you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="noreferrer"><code>replace</code></a> <code>,</code> to empty <code>strings</code>:</p> <pre><code>print (df) 2016-10-31 2,144.78 2016-07-31 2,036.62 2016-04-30 1,916.60 2016-01-31 1,809....
python|pandas|dataframe
18
14,966
43,359,799
populating a nesting dictionary
<p>having trouble populating a nested dictionary and retaining previously populated keys. see this example:</p> <pre><code>fulldict={} keys=['key1', 'key2', 'key3'] for key in keys: for i in xrange(3): x1 = np.random.randn(10) y1 = np.random.randn(10) fulldict[key] = {i:pd.DataFrame({'x1':...
<p>You are reassigning the <code>fulldict[key]</code> each time, so initialize <code>fulldict[key] = {}</code> and use <code>i</code> as a key:</p> <pre><code>for key in keys: fulldict[key] = {} for i in xrange(3): x1 = np.random.randn(10) y1 = np.random.randn(10) fulldict[key][i] = pd....
python|pandas|dictionary
1
14,967
43,348,801
Releasing memory usage by variable in python
<p>I am currently trying to store some data into .h5 files, I quickly realised that might have to store my data into parts, as it is not possible to process it an have in my ram. I started out using <code>numpy.array</code> to compress the memory usage, but that resulted in days spend on formatting data. </p> <p>So i...
<p>You need to explicitly force garbage collection, see <a href="https://stackoverflow.com/questions/1316767/how-can-i-explicitly-free-memory-in-python">here</a>:</p> <blockquote> <p>According to Python Official Documentation, you can force the Garbage Collector to release unreferenced memory with <code>gc.collect()...
python|macos|list|numpy|memory
0
14,968
72,203,408
Derive a Dataframe from existing one
<p>I need some help here. In this DataFrame I need to perform a series of calculations by grouping column'cnpj'</p> <p>What I have as input:</p> <pre><code> cnpj valor_cota ln_ativo ln_IBX CDI tracking 0 cat1 1114.7521 0.027152 -0.003659 23.893879 0.030811 1 cat1 1135.3557 0....
<p>You can pass multiple functions to <code>apply</code>; then construct a DataFrame with the result:</p> <pre class="lang-py prettyprint-override"><code>grouped = df.groupby('cnpj').apply(lambda g: [v1(g),v2(g),v3(g),v4(g),v5(g),v6(g),v7(g),v8(g),v9(g)]) out = pd.DataFrame(grouped.tolist(), index=grouped.index, ...
python|pandas|dataframe
1
14,969
72,334,873
How can I split Pandas arrays into columns?
<p>I'm trying to split array values to columns.</p> <p>I've created a Google Colab notebook and you can find my code <a href="https://colab.research.google.com/drive/1LYs1N6fRwiB7uE5r_dGS5SCuB2Apk_Gx?usp=sharing" rel="nofollow noreferrer">here</a>.</p> <p>Here is a screenshot of the data (Hashtags):</p> <p><img src="ht...
<p>The reason is the lists are still stored as strings in the <code>hashtags</code> column when you read them with <code>read_csv</code>. You can convert them upon reading of the data (follwing code taken from the Colab notebook):</p> <pre><code>import pandas as pd from ast import literal_eval url = &quot;https://raw....
python|arrays|pandas|numpy|split
1
14,970
72,312,729
How to make numpy array mutable?
<pre><code>packed_bytes = resources[bv.byteOffset : bv.byteOffset + bv.byteLength] arr = np.frombuffer( packed_bytes, dtype=component_type[accessor.componentType].replace(&quot;{}&quot;, &quot;&quot;), ).reshape((-1, accessor_type[accessor.type])) arr.flags.writeable = True # this does not work </code></pre> <...
<p>Using an example from <code>frombuffer</code>:</p> <pre><code>x=np.frombuffer(b'\x01\x02', dtype=np.uint8) x Out[105]: array([1, 2], dtype=uint8) x.flags Out[106]: C_CONTIGUOUS : True F_CONTIGUOUS : True OWNDATA : False WRITEABLE : False ALIGNED : True WRITEBACKIFCOPY : False UPDATEIFCOPY : False x...
python|arrays|numpy
3
14,971
50,556,812
Multiple Input types in a keras Neural Network
<p>As an example, I'd like to train a neural network to predict the location of a picture(longitude, latitude) with the image, temperature, humidity and time of year as inputs into the model.</p> <p>My question is, what is the best way to add this addition information to a cnn? Should I just merge the numeric inputs w...
<p>You can process numeric inputs separately and merge them afterwards before making the final prediction:</p> <pre><code># Your usual CNN whatever it may be img_in = Input(shape=(width, height, channels)) img_features = SomeCNN(...)(img_in) # Your usual MLP model aux_in = Input(shape=(3,)) aux_features = Dense(24, ac...
python|tensorflow|neural-network|keras|conv-neural-network
4
14,972
62,656,411
OptKeras (Keras Optuna Wrapper) - use optkeras inside my own class, AttributeError: type object 'FrozenTrial' has no attribute '_field_types'
<p>I wrote a simple Keras code, in which I use CNN for fashion mnist dataset. Everything works great. I implemented my own class and classification is OK.</p> <p>However, I wanted to use Optuna, as OptKeras (Optuna wrapper for Keras), you can see an example here: <a href="https://medium.com/@Minyus86/optkeras-112bcc34e...
<p>It seems that optkeras (version I got was 0.0.7) being not quite up-to-date with optuna library is the reason for the issue. I was able to make it work with optuna 1.5.0 by doing the following changes:</p> <p>First, you'll need to monkey-patch <code>get_default_trial</code> like this before running your code:</p> <p...
python|tensorflow|keras|optuna
3
14,973
62,657,186
Histogram to show sampling rate
<p>I'm having confusion with plotting some data, but here is what I want to do. I have a dataframe with this sample data:</p> <pre><code>&gt;&gt;df.head(20) user_id | trip_id | lat | lon | sampling_rate ---------+--------------------+------------------+------------------+---------...
<p>IIUC, Use, <a href="https://numpy.org/doc/stable/reference/generated/numpy.arange.html" rel="nofollow noreferrer"><code>np.arange</code></a> to create bins with the interval of <code>5sec</code>:</p> <pre><code>plt.figure(figsize=(6, 4)) plt.hist(df['sampling_rate'], bins=np.arange(1, df['sampling_rate'].max() + 5, ...
python|python-3.x|pandas|matplotlib
0
14,974
54,259,807
Image classifier using cifar 100, train accuracy not increasing
<p>I was trying to train an image classifier model using cifar100 dataset in tensorflow, but accuracy is not increasing over 1.2%. I googled the issue and found several solutions but still my model is not doing well.</p> <p>I implemented a few steps such as:</p> <ol> <li>increasing CNN layer and pooling along with dr...
<p>The first argument you are passing to softmax_cross_entropy_with_logits_v2 is incorrect. You must pass the "previous" values to apply the softmax. That's because softmax_cross_entropy_with_logits_v2 is really cross_entropy (softmax (x)). The justification is that the derivative can be simplified.</p> <p>In model yo...
python|tensorflow|machine-learning|neural-network|deep-learning
0
14,975
54,629,699
How to loop through comparing one column with its corresponding column in Python
<p>I have an excel file which I imported as a dataframe. I want to loop through the columns of the dataframe. For eg, I want to compare 2nd column with first , then 3rd column with second.I have converted rule_id column into index. This is the data:</p> <pre><code>rule_id reqid1 reqid2 reqid3 53139 0 0 ...
<p>Like one of the comments state, your expected output could influence what the best solution is. Keeping that in mind, looping over columns is rarely the best solution. I suggest simply adding new columns that indicate whether the columns being compared are equal or not. For instance:</p> <pre><code>In [1]: import p...
python|pandas|dataframe
1
14,976
73,715,140
How to do computation with a c function on a numpy array of a non square matrix of size `n` times `m` (n≠m)
<p><strong>Edit</strong></p> <p>I created a similar question which I found more understandable and practical there: <a href="https://stackoverflow.com/questions/73716630/how-to-copy-a-2d-array-matrix-from-python-with-a-c-function-and-do-some-compu">How to copy a 2D array (matrix) from python with a C function (and do s...
<p>I assume you want to compute sum along last axis for a (n,m) matrix. Segmentation fault occurs when you access memory which you have no access. The issue lies in the the erroneous outer loop. You need to iterate over both dimensions but you iterate over same dimension twice.</p> <pre><code>double * results = (doubl...
python|arrays|c|numpy|malloc
1
14,977
73,550,365
Unmerge specific group in multiindex groupby dataframe
<p>My dataframe</p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;TEAM&quot;:[1,1,1,1,2,2,2], &quot;ID&quot;:[1,1,2,2,8,4,5], &quot;TYPE&quot;:[&quot;A&quot;,&quot;B&quot;,&quot;A&quot;,&quot;B&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;], &quot;VALUE&quot;:[1,1,1,1,1,1,1]}) df = df.groupby([&quot;TEAM&q...
<p>If you want to treat columns <code>TEAM</code> and <code>ID</code> on same level, then you can create a column by combining these two columns and group on this new column.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({&quot;TEAM&quot;:[1,1,1,1,2,2,2], &quot;ID&quot;:[1,1...
pandas|dataframe|group-by|multi-index
0
14,978
71,393,736
How to access latest torchvision.models (e.g. ViT)?
<p>I have seen in the <a href="https://pytorch.org/vision/master/models.html" rel="nofollow noreferrer">official torchvision docs</a> that recently vision transformers and the ConvNeXt model families have been added to the PyTorch model zoo. However, even after upgrading to latest torchvision version 0.11.3 (via <code>...
<p>Event though @Shai's answer is a nice addition, my original question was how I could access the official ViT and ConvNeXt models in <code>torchvision.models</code>. As it turned out the answer was simply to wait. So for the records: After upgrading to latest <code>torchvision</code> pip package in version 0.12 I got...
python|pytorch
0
14,979
71,411,496
Merging dataframes with multiple key columns
<p>I'd like to merge this dataframe:</p> <pre><code>import pandas as pd import numpy as np df1 = pd.DataFrame([[1,10,100],[2,20,np.nan],[3,30,300]], columns=[&quot;A&quot;,&quot;B&quot;,&quot;C&quot;]) df1 A B C 0 1 10 100 1 2 20 NaN 2 3 30 300 </code></pre> <p>with this one:</p> <pre><code>df2 = pd.D...
<p>IIUC, you need a double merge/join.</p> <p>First, <code>melt</code> df1 to get a single column, while keeping the index. Then <code>merge</code> to get the matches. Finally <code>join</code> to the original DataFrame.</p> <pre><code>s = (df1 .reset_index().melt(id_vars='index') .merge(df2, left_on='value',...
python|pandas|merge
3
14,980
71,233,922
All month ends until the end date
<p>I have a df with two columns:</p> <pre><code>index start_date end_date 0 2000-01-03 2000-01-20 1 2000-01-04 2000-01-31 2 2000-01-05 2000-02-02 3 2000-01-05 2000-02-17 ... 5100 2020-12-29 2021-01-11 5111 2020-12-30 2021-03-15 </code></pre> <p>I would like to add column...
<p>If need parse months between start and end datetimes and add last day of each month use custom lambda function with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.period_range.html" rel="nofollow noreferrer"><code>period_range</code></a>:</p> <pre><code>df['start_date'] = pd.to_datetime(df...
python|pandas|date
1
14,981
71,188,943
Function returning unexpected values when vectorizing over numpy tuple
<p>I wanted to take a quick look at the following distribution function and noticed that something is very wrong with the way I'm trying to do that. When applying the function to <code>x_range</code>, all values end up being <code>0</code>. I am very confused about this and struggle to understand why that would be the ...
<p>The documentation for <a href="https://numpy.org/doc/stable/reference/generated/numpy.vectorize.html" rel="nofollow noreferrer"><code>vectorize</code></a> says:</p> <blockquote> <p>The data type of the output of vectorized is determined by calling the function with the first element of the input. This can be avoided...
python|numpy|matplotlib
4
14,982
52,370,489
Find length of streak in pandas
<p>I have a pandas dataframe where a column depicts an integer time index, and I want to add a column that stores whether a row is part of a streak and how long the streak is. For example, given the <code>time</code> column, I would like to compute a <code>streak</code> column, like so</p> <pre><code>time streak 0 ...
<p>Using <code>diff</code> find the whether it continue or not (equal to 1 ), then <code>cumsum</code> with the condition match , then we using <code>groupby</code> + <code>transform</code> <code>szie</code></p> <pre><code>s=df.time.diff().fillna(1).ne(1).cumsum() s.groupby(s).transform('size') Out[396]: 0 3 1 ...
python|pandas
3
14,983
52,386,913
sort values doesn't sort in this case?
<p>I have this dataframe but when using the <code>sort_values</code> from pandas it doesn't get sorted.</p> <pre><code>x = pd.read_csv(r'C:\Users\user\Desktop\Dataset.csv', sep = ',') x.sort_values('duration',ascending = False,inplace = True) x.loc[:,'dates'] = pd.to_datetime(x['dates']) b=x.sort_values(['dates'],asc...
<p>you can group first and sort the values </p> <pre><code>df.groupby('month').apply(lambda x: x.sort_values(['duration'],ascending=False)) </code></pre> <p>Out:</p> <pre><code>month user duration month 9 1 9 user_02 55.82 0 9 user_01 54.73 2 9 user_03 18.00 </code></pre>
python|pandas
0
14,984
60,342,784
numpy: apply an arbitrary function to array element
<pre><code>import pandas as pd from ipaddr import IPv4Address df = pd.DataFrame([[1,'192.168.1.10', '45.7.12.34', 'abc'],[4, '10.10.1.11', '90.90.67.33', 'def'], [77, '52.1.7.90', '67.5.3.5', 'ghi' ], [90, '19.19.90.7', '77.88.99.44', 'xyz']], columns=['A', 'sip', 'dip', 'location']) addrs = [(int)(IPv4Address(addr))...
<p>With pandas (since it is tagged) can you also try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>series.map</code></a> with <a href="https://docs.python.org/3/library/functions.html#map" rel="nofollow noreferrer"><code>map</code></a> from v...
python|pandas|numpy|ip-address
1
14,985
60,334,671
pandas dataframe - How to find consecutive rows that meet some conditions?
<p>I'm trying to make a program that finds consecutive rows that meet some conditions. For example, if there's a dataframe that looks like this:</p> <pre><code>df = pd.DataFrame([1,1,2,-13,-4,-5,6,17,8,9,-10,-11,-12,-13,14,15], index=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15], columns=['value'])...
<p>I create helper columns for easy verify solution:</p> <pre><code>#column for negative and positive df['sign'] = np.where(df['value'] &lt; 0, 'neg','pos') #consecutive groups df['g'] = df['sign'].ne(df['sign'].shift()).cumsum() #removed groups with length more like 2 df = df[df['g'].map(df['g'].value_counts()).gt(2...
python|pandas
8
14,986
60,439,399
Pandas DF Removal of Duplicate Surnames
<p>i have DataFrame that has Name of People and Some Names Incorrect Caught surname due to selenium scraping so i want to remove them</p> <p>Input:</p> <pre><code> TEXT TYPE 0 Barrack Obama PERSON 1 Obama PERSON 2 Don Beyer PERSON 3 Doug Wilson PERSON 4 Wilson PERSON 5 ...
<p>Here is another approach using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer"><code>duplicated()</code></a> </p> <pre><code>df[~df['TEXT'].str.split().str[-1].duplicated()] </code></pre> <p>Or:</p> <pre><code>df[~df['TEXT'].str.split...
python|pandas|dataframe
3
14,987
60,733,109
Understanding a Keras Error: TypeError: Value passed to parameter 'shape' has DataType float32 not in list of allowed values: int32, int64
<p>So I have this line of code:</p> <pre><code>history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(X_val, y_val)) </code></pre> <p>Which throws this error:</p> <pre><code>File "CNN.py", line 125, in model history = model.fit(X_train, y_train, batch_size=batch_s...
<p>So I solved the problem. It came from another line of code. These were the lines in my code that came before the fitting:</p> <pre><code>model.add(Dense(num_neurons, activation= cnn_params["activation_output"])) model.add(Dense(cnn_params["final_dense"]["number_neurons"], activation= cnn_params["activation_output"]...
python|tensorflow|keras|anaconda|conda
0
14,988
72,656,716
concatenate numpy arrays from different Dataframe Columns
<p>I have a pandas data frame including some columns, let say 'a', 'b' and 'c', containing numpy arrays.</p> <p>I would like to concatenate the np arrays from different columns obtaining a single np array for each row.</p> <p>Is there an efficient way to do this avoiding iteration?</p>
<p>You can concat two NumPy arrays with np.concatenate function.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np df = pd.DataFrame() df['x'] = [np.array([1]), np.array([1, 2]), np.array([1, 2, 3])] df['y'] = [np.array([1]), np.array([1, 2]), np.array([1, 2, 3])] df['concat'] =...
pandas|numpy
1
14,989
72,648,002
Multiply by a different number of columns with iloc in Pandas
<p>I have the following dataframe:</p> <pre><code>df = pd.DataFrame({'date' : ['2020-6','2020-07','2020-8'], 'd3_real':[1.2,1.3,0.8], 'd7_real' : [1.5,1.8,1.2], 'd14_real':[1.9,2.1,1.5],'d30_real' : [2.1, 2.2, 1.8], 'd7_mul':[1.12,1.1,1.15],'d14_mul':[1.08, 1.1, 1.14],'d30_mul':[1.23,1.25,1.12]}) </c...
<pre><code>bbb = [[1, 5, 6, 7], [2, 6, 7], [3, 7]] ddd = ['d30_from_d3', 'd30_from_d7', 'd30_from_d14'] for i in range(0, len(ddd)): df[ddd[i]] = df.iloc[:, bbb[i][0]] for x in range(1, len(bbb[i])): df[ddd[i]] = df[ddd[i]] * df.iloc[:, bbb[i][x]] </code></pre> <p>Output</p> <pre><code> date d3_re...
python|pandas|dataframe
1
14,990
72,781,210
Finding indices of 2D array with two constraints
<p>I have two 2D arrays in NumPy of equal size, and am trying to identify the indices where two conditions are met. Here's what I try and what I get. Any suggestions? I'm using <code>np.where</code> and this does not seem to be the correct choice.</p> <p>Thanks for any help.</p> <pre><code>ind_direct_pos = np.where((bz...
<p>If the two arrays with <strong>the same size</strong>, not the same shape, we can <code>ravel</code> it at first (using <code>and</code> instead <code>&amp;</code> is a cause of this problem as <a href="https://stackoverflow.com/users/1740577/imahdi">I'mahdi comment</a>):</p> <pre><code>bz_2D_surface3 = np.array([[1...
python|arrays|numpy|where-clause
0
14,991
72,788,811
ValueError of Input and Output values during LSTM training
<p>I was trying to implement a basic LSTM network using some random data, and I got the following error during execution of the code</p> <p>'''</p> <pre><code>Traceback (most recent call last): File &quot;C:/Users/dell/Desktop/test run for LSTM thingy.py&quot;, line 39, in &lt;module&gt; history = model.fit(x_tra...
<p>You are currently trying to do categorical classification with 5 classes but <code>y</code> has the shape <code>(28, 133, 1320)</code>. It does not work like that. Also, when you use <code>categorical_crossentropy</code>, you need one-hot-encoded labels. Here is a working example as orientation:</p> <pre><code>impor...
python|tensorflow|keras|lstm|recurrent-neural-network
1
14,992
72,754,232
Is there a PyTorch lightning equivalent for Tensorflow?
<p>I saw PyTorch Lightning advertised as PyTorch but for people who don't want to worry so much about the underlying methodology. This narrative is on the PyTorch lightning website but also <a href="https://medium.com/analytics-vidhya/use-pytorch-lightning-to-decouple-science-science-code-from-engineering-code-1e6f36cf...
<p>Probably the best association would be Keras (formerly separate from but now for some time integrated in TF - you can you Keras as a high level API).</p> <p>Note that you can also use <code>tensorflow_addons</code> (I personally enjoy working with it) package and other libraries&amp;wrappers that come into the aid o...
tensorflow|pytorch|pytorch-lightning
1
14,993
59,613,025
Arranging the dataframe from one row to multiple columns in python
<p>I have a dataframe which contains single column but multiple values in the row . I need to transpose and append the data correctly from each row.</p> <p>The dataframe is as follows:</p> <pre><code>l1 l2 0 a:1 b:2 c:3 1 a:11 b:12 c:13 2 a:21 b:22 c:33 </c...
<p>First convert index <code>l1</code> to column, then replace empty strings to missing values and forward filling them, also for column <code>l2</code> is used <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>Series.str.split</code></a> to...
python|python-3.x|pandas|dataframe|pandas-datareader
1
14,994
59,869,152
Python pandas pivot_table margins keyError
<p>Consider the following dataframe:</p> <pre><code>test = pd.DataFrame({'A': [datetime.datetime.now(), datetime.datetime.now()], 'B': [1, 2]}) </code></pre> <p>If I use <code>pivot_table</code> like below then everything is fine:</p> <pre><code>test.pivot_table(index = 'A', aggfunc = {'B': 'mean'}, margins = True) ...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>test['Ax']=test['A'].dt.year test.pivot_table(index = 'Ax' , aggfunc = 'mean', values='B', margins = True) </code></pre> <p>Outputs:</p> <pre class="lang-py prettyprint-override"><code> B Ax 2020 1.5 All 1.5 </code></pre> <p><strong>Explanation<...
python|pandas|pivot-table
1
14,995
59,602,792
Pandas dataframfe TypeError: is there a problem with indexing using int?
<p>For the next code:</p> <pre><code>1_df = pd.read_csv("1.csv") 2_df = pd.read_csv("2.csv") 3_df = pd.read_csv("3.csv") GT_df = pd.DataFrame(columns = {'text', 'labelsum', 'label_value'}) row_count = 0 for x in range(1_df.shape[0]): if 1_df.iloc[x,3] + 2_df.iloc[x,3] + 3_df.iloc[x,3] == 0: GT_df.loc[row...
<p><code>iloc</code> and <code>loc</code> have subtle differences. If you are going to use positions to index, then use <code>iloc</code> and if you are going to use column names or conditions to index, then use <code>loc</code>.</p>
python|pandas|indexing
0
14,996
59,611,000
Saving meta data/information in Keras model
<p>Is it possible to save meta data/meta information in Keras model? My goal is to save input pre-processing parameters, train/test set used, class label maps etc. which I can use while loading model again.<br> I went through Keras documentation and did not find anything. I found similar <a href="https://github.com/ker...
<p>This is working for me:</p> <pre><code>from tensorflow.python.keras.saving import hdf5_format import h5py # Save model with h5py.File(model_path, mode='w') as f: hdf5_format.save_model_to_hdf5(my_keras_model, f) f.attrs['param1'] = param1 f.attrs['param2'] = param2 # Load model with h5py.File(model_p...
python|tensorflow|keras|tf.keras
7
14,997
59,685,609
Pandas, Numpy: How to Speed up row iteration with inner loop?
<p>I have the following data set, and I am calculating the <code>Net Forecast</code> column based on the rest.</p> <p>The logic implemented is,</p> <ul> <li>If there is an <code>Order</code> &lt; 0 for a Part, we add it with <code>Gross Forecast</code> in the same row, i.e., <code>0</code>.</li> <li>If the <code>Orde...
<p>Often where balances like inventory are involved 'vectorisation' can be achieved using cumulative for the flows.</p> <p>iterative <code>balance[t] = balance[t-1] + in[t] - out[t]</code> becomes vectorised <code>balance = in.cumsum() - out.cumsum()</code></p> <pre><code>import numpy as np in_ = np.array( [10, 5, 3...
python|pandas|numpy|dataframe
1
14,998
59,774,328
How can I load a model in PyTorch without redefining the model?
<p>I am looking for a way to save a pytorch model, and load it without the model definition. By this I mean that I want to save my model including model definition.</p> <p>For example, I would like to have two scripts. The first would define, train, and save the model. The second would load and predict the model witho...
<p>You can attempt to export your model to <a href="https://pytorch.org/docs/stable/jit.html#builtin-functions" rel="noreferrer">TorchScript</a> using <a href="https://pytorch.org/docs/master/jit.html#torch.jit.trace" rel="noreferrer">tracing</a>. This has limitations. Due to the way PyTorch constructs the model's comp...
model|save|load|pytorch
10
14,999
40,350,849
Rank mismatch: Rank of labels (received 2) should equal rank of logits minus 1 (received 2)
<p>I'm building DNN to predict if the object is present in the image or not. My network has two hidden layers and the last layer looks like this:</p> <pre><code> # Output layer W_fc2 = weight_variable([2048, 1]) b_fc2 = bias_variable([1]) y = tf.matmul(h_fc1, W_fc2) + b_fc2 </code></pre> <p>Then I have placeh...
<p>From the documentation* for <code>tf.nn.sparse_softmax_cross_entropy_with_logits</code>: </p> <blockquote> <p>"A common use case is to have logits of shape [batch_size, num_classes] and labels of shape [batch_size]. But higher dimensions are supported."</p> </blockquote> <p>So I suppose your labels tensor sh...
python|image-processing|neural-network|tensorflow|conv-neural-network
9