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
17,500
57,953,100
Python 3 unable to pickle lambda
<p>I was following a tutorial online about <a href="https://towardsdatascience.com/deep-learning-for-self-driving-cars-7f198ef4cfa2" rel="nofollow noreferrer">Deep Learning for Self-Driving Cars</a> with pytorch. But then I encounter some problem when python trying to pickle lambda.</p> <p>I've tried to define my own ...
<p>Python documentation says that <code>lambda</code> functions cannot be pickled.</p> <p><a href="https://docs.python.org/3/library/pickle.html#id2" rel="nofollow noreferrer">https://docs.python.org/3/library/pickle.html#id2</a>:</p> <blockquote> <p>Note that functions (built-in and user-defined) are pickled by “f...
python|lambda|pytorch
0
17,501
54,698,821
Concat does not recognize shared indices across columns being concatenated
<p>I am attempting to concat 2 csv files, with data df1b(2214,4) and df2b(2262, 4). A large portion of the indices in these 2 files are the same, and therefore I am looking for those rows to overlap, and where indices are unique, the other rows will be filled by NaN. Example below: </p> <p>df1b</p> <pre><code>Index ...
<p>You could use merging:</p> <pre><code>df3 = df1b.merge(df2b, on='Gene', how='outer) </code></pre> <p>You will only need to consider the <code>Gene</code> as a normal column</p> <p>more information here: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow ...
python|pandas|concat
1
17,502
55,131,550
Python 3.7 + Visual Studio 2107 + boost 1.69
<p>I am trying to get boost 1.69 working with visual studio 2107. My goal is to use Numpy in C++</p> <p>When I include <code>#include boost/python/numpy.hpp</code></p> <p>The error I am getting is:</p> <pre><code>Searching C:\boost_1_69_0\stage\lib\boost_python37-vc141-mt-gd-x32-1_69.lib: 1&gt;LINK : fatal error LNK...
<p>I have been looking at this issue for months and finally figure out the root cause and solutions. The root cause that boost numpy is not built is because numpy is unable to be imported when ./b2 checks for numpy. As a clue from this post <a href="https://stackoverflow.com/questions/61609980/using-boost-numpy-with-vi...
numpy|boost|visual-studio-2017
0
17,503
54,732,215
How do I set the minimum threshold for drawing a box?
<p>I have an object detection model that I use with opencv to detect my custom class.</p> <p><strong>I want to output the boxes only when the model is 95% or more confident.</strong></p> <p>Is there a way I can configure that?</p> <p>(Bonus question: Can I set it so that only the object with the highest confidence i...
<p>Okay, answering my own question. It only took me 1 minute to find out on my own.</p> <p>This is the function that visualizes the boxes. Its input parameters are well explained in the source code.</p> <blockquote> <p>object_detection/utils/visualization_utils.visualize_boxes_and_labels_on_image_array(...)</p> </b...
tensorflow|object-detection|object-detection-api
1
17,504
55,055,655
How to use `cv2.perspectiveTransform` to apply homography on a set of points in Python OpenCV?
<p>I want to apply homography to the following points:</p> <pre><code>array([[-7.4894, 1.8873], [-7.4973, 1.8543], [-7.5375, 1.6725], [-7.5681, 1.522 ], [-7.5961, 1.371 ], [-7.6252, 1.2013], [-7.6504, 1.031 ], [-7.667 , 0.8985], [-7.6817, 0.7657], [-7.6954, 0.613 ], [-7.7054, 0...
<p>Make sure the pts shape is <code>(n, 1, 2)</code> or <code>(1,n,2)</code>:</p> <pre><code> pts = np.float32(pts).reshape(-1,1,2) #pts = np.array([pts], np.float32) cv2.perspectiveTransform(pts, M) </code></pre> <hr> <p>For example:</p> <pre><code>pts = np.array([[1,2,],[3,4]], np.float32) M = np.array([[ 3.964...
python|numpy|opencv|homography
8
17,505
49,524,761
Scikit learn GaussianProcessClassifier memory error when using fit() function
<p>I have X_train and y_train as 2 numpy.ndarrays of size (32561, 108) and (32561,) respectively.</p> <p>I am receiving a memory error every time I call fit for my GaussianProcessClassifier.</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from sklearn.gaussian_process impo...
<p>According to the Scikit-Learn <a href="http://scikit-learn.org/stable/modules/generated/sklearn.gaussian_process.GaussianProcessClassifier.html#sklearn.gaussian_process.GaussianProcessClassifier" rel="noreferrer">documentation</a>, the estimator <em>GaussianProcessClassifier</em> (as well as <em>GaussianProcessRegre...
python|pandas|scikit-learn|classification|sklearn-pandas
11
17,506
49,431,332
How to replace directory path in each row of a column with pandas?
<p>I have a python dataframe which has a filename column that looks like this:</p> <pre><code>Filename /var/www/html/projects/Bundesliga/Match1/STAR_SPORTS_2-20170924-200043-210917-00001.jpg /var/www/html/projects/Bundesliga/Match1/STAR_SPORTS_2-20170924-200043-210917-00001.jpg </code></pre> <p>From the Filename colu...
<pre><code>df['Filename'] = df['Filename'].apply(lambda x: x.replace(os.path.dirname(x), dst)) </code></pre>
python|pandas|dataframe
5
17,507
73,521,992
Python-Making a training and testing set from a tensor
<p>I have two tensors one real_image_tensors and one drawing_tensors they are both currently in order, where the first image in real_image_tensors is the reference picture for the drawing in drawing_tensor. I need to keep them in order, but split them into a training set tensor and a testing set tensor. So I would h...
<p>One approach you can try is the following:</p> <ol> <li>Pairwise concatenate the real image tensors and the drawing tensors (so concatenating a real image tensor with its corresponding drawing tensor).</li> <li>Put all the concatenated tensors into a list</li> <li>Stick the list into <code>.train_test_split()</code>...
python|tensorflow|google-codelab
1
17,508
65,269,160
How to operate with two differents dataframes in python?
<p>I want to make a mathematical operation by comparing the values of the two differents dataframes (A and B).</p> <pre><code>A = pd.DataFrame({'a':[1,1,2,2],'s':[10,20,30,40]}) B = pd.DataFrame({'a':[1,2],'I':[5,10]}) </code></pre> <p>I want add a column to A call A['ss'] in which element is equal to <em>s/(1+I)</em> ...
<p>It is probably easiest to merge the two first on <code>a</code>, this will populate the right values of <code>I</code>:</p> <pre><code>A2 = A.merge(B, on='a', how='left') </code></pre> <p>A2 now looks like this:</p> <pre><code> a s I 0 1 10 5 1 1 20 5 2 2 30 10 3 2 40 10 </code></pre> <p>s...
python|pandas
0
17,509
65,423,150
how to filter dataset when reading in tensorflow?
<pre><code>ds_train = tf.data.experimental.make_csv_dataset( file_pattern = &quot;./df_profile_seq_fill_csv/*.csv&quot;, batch_size=batch_size, column_names=use_cols, label_name='label', select_columns= select_cols, num_parallel_reads=30, shuffle_buffer_size=10000) </code></pre> <p>I read the data ...
<p>One way to do it is firstly create dataset from csv with batch 1 (batch is a required arugment). Then filter &quot;batches&quot; which are examples and then re-batch again:</p> <pre class="lang-py prettyprint-override"><code>class_number_to_get_rid_of = 0 TRAIN_DATA_URL = &quot;https://storage.googleapis.com/tf-data...
tensorflow|tensorflow2.0
1
17,510
65,149,044
Downsampling in Pandas DataFrame by dividing observations into ratios
<p>Given a DataFrame having timestamp (ts), I'd like to these by the hour (downsample). Values that were previously indexed by ts should now be divided into ratios based on the number of minutes left in an hour. [note: divide data in ratios for NaN columns while doing resampling]</p> <pre><code> ts ...
<p>The first step is to add &quot;previous ts&quot; column to the source DataFrame:</p> <pre><code>df['tsPrev'] = df.ts.shift() </code></pre> <p>Then set <em>ts</em> column as the index:</p> <pre><code>df.set_index('ts', inplace=True) </code></pre> <p>The third step is to create an auxiliary index, composed of the orig...
python|pandas|dataframe|resampling|pandas-resample
1
17,511
65,283,520
Numba/numPy multiple run speed difference / optimization
<p>I'm seeing some peculiar performance using Numba and also looking to optimize the JIT loop further.</p> <p>Init and generate some practically relevant data:</p> <pre><code>import pandas as pd import numpy as np from datetime import datetime, timedelta from time import time import numba times = np.arange...
<p><code>numba.jit</code> will compile the function when it is first used. This makes the first execution of the function expensive, and subsequent ones much cheaper.</p> <p>Your test presumably runs <code>run_one</code> - which calls <code>entry_exit</code> which numba compiles - and so is slow to compile, but then fa...
python|numpy|jit|numba
1
17,512
50,136,699
TypeError: Failed to convert object of type <class 'generator'> to Tensor
<p>I use <code>tensorflow 1.8</code> to program machine learning framework. There are two files contain data with the format in <code>indices.csv</code> and <code>wordvecs.csv</code> respectively looks like this</p> <pre><code>1 4 2,5 3 5,2 0,4 2 3,0,5 </code></pre> <p>and </p> <pre><code>-0.12345059557113995,0.0337...
<p>You probably miss-placed one ")"</p> <p>Try:</p> <pre><code>tf.stack([tf.reduce_mean(tf.gather(ten_variables, index)) for index in ten_indices]) </code></pre> <p>instead of</p> <pre><code>tf.stack([tf.reduce_mean(tf.gather(ten_variables, index) for index in ten_indices)]) </code></pre> <p>It is usually helpful ...
python|tensorflow
1
17,513
50,091,066
extracting specifiv values from pandas dataframe column
<p>I have a data in pandas data frame column as below:</p> <pre><code>[2, 4] [3, 4] [1, 4] [0, 0] </code></pre> <p>I want the data to be in the form of</p> <pre><code>col_1 col_2 2 4 3 4 1 4 0 0 </code></pre> <p>Can anyone help me how can I get the data in the above form.</p>
<p>You can use <code>.tolist()</code> to do this pretty easily if the lists all have the same number of elements</p> <pre><code>import pandas as pd df = pd.DataFrame({'val1': [[2, 4], [3, 4], [1, 4], [0, 0]]}) df[['col_1', 'col_2']] = pd.DataFrame(df.val1.tolist()) val1 col_1 col_2 0 [2, 4] 2 ...
python|pandas|dataframe|jupyter-notebook
2
17,514
50,198,407
How to concatenate keras layers beyond the last axis
<p>I tried to concatenate keras layers beyond the last axis.</p> <pre><code>concat_layer = keras.layers.concatenate([layer1,layer2],axis=3); </code></pre> <p>The shapes of layer1 and layer2 are both (?,7,7),for now I want it become (?,7,7,2) rather than (?,7,14). If I wrote like axis=3, it returns "IndexError: list a...
<p>Reshape the layer to the required dimension and then use the newly added axis to concatenate</p> <pre><code>from keras.layers import Reshape from keras.layers.merge import concatenate layer1 = Reshape((7, 7, 1))(layer1) layer2 = Reshape((7, 7, 1))(layer2) concat_layer = concatenate([layer1, layer2], axis=3) </code...
tensorflow|keras
3
17,515
63,740,591
Updating missing values in dataframe
<p>I have a <code>df</code> like:</p> <pre><code> col1 col2 col3 col4 0 a 1 jake 1 b 1 li 2 c 2 bob corn 3 d 2 pat 4 e 2 angie 5 f 1 jose pepper 6 g 3 juan </code></pre> <p>What I must do is...
<p>I would do a <code>fillna</code> with <code>groupby().transform</code>:</p> <pre><code>df['col4'] = df['col4'].fillna(df.groupby('col2')['col4'].transform('first')) </code></pre> <p>Output:</p> <pre><code> col1 col2 col3 col4 0 a 1 jake pepper 1 b 1 li pepper 2 c 2 bob corn ...
python|pandas|dataframe|duplicates
4
17,516
63,830,526
How to remove zeros from a 1D tensor - TensorFlow.js?
<p>Given a 1D tensor (just to be clear, not array): <code>[0,2,0,1,-3]</code>, I'd like to get back just the values different than zero. Following the example, I'd like to get back <code>[2,1,-3]</code> as the result. How can I do that in TensorFlow.js?</p>
<ul> <li><p>First we need to find the indexes of the non-zeros values by using <code>tf.whereAsync</code> on the tensor casted to <code>bool</code>. That way all values except 0 values are <code>true</code> and their indexes are thus collected.</p> </li> <li><p>With <code>tf.gather</code> we create a new tensor by coll...
javascript|tensorflow.js
1
17,517
46,878,441
How do I do this tensor transformation and preserve the gradients?
<p>In Tensorflow, I have a float tensor T with shape [batch_size, 3]. For example, <code>T[0] = [4, 4, 3]</code>. </p> <p>I want to turn that into a size 5 one hot in order to yield entries from an embedding dictionary. In the above case, that would look like</p> <p><code>T[0] = [[0, 0, 0, 0, 1], [0, 0, 0, 0, 1], [0,...
<p>I was able to solve this in the following way:</p> <pre><code>expanded = tf.expand_dims(inputs, 2) embedding_input = tf.cast(tf.one_hot(tf.to_int32(inputs), 5), inputs.dtype) embedding_input = tf.stop_gradient(embedding_input - expanded) + expanded </code></pre>
python|tensorflow
1
17,518
63,300,329
Pandas DataFrame removing NaN rows based on condition?
<p>Pandas DataFrame removing NaN rows based on condition.</p> <p>I'm trying to remove the rows whose <code>gender==male</code> and <code>status == NaN</code>.</p> <p>Sample df:</p> <pre><code> name status gender leaves 0 tom NaN male 5 1 tom True male...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.Series.isna.html" rel="noreferrer"><code>isna</code></a> (or <code>isnull</code>) function to get the rows with a value of <code>NaN</code>. With this knowledge, you can filter your dataframe using something like:</p> <pre cla...
python|pandas|numpy|dataframe
5
17,519
67,767,100
regex expression for strings that start the same but end with number to subset pandas dataframe
<p>Might be a bit of a basic question, but, say I have a dataframe that looks like:</p> <pre><code>string_lst = [&quot;bar0001&quot;, &quot;bar0002&quot;, &quot;bar0003&quot;, &quot;bar0003&quot;, &quot;bar0004&quot;, &quot;bar0004&quot;, &quot;bar0005&quot;, &quot;bar0006&quot;] a = pd.DataFrame({'foo': string_lst, ...
<p>If your dataset has the same pattern (bar followed by numbers), you can do something like below. This will handle cases like 'bar004', 'bar00004' etc.</p> <pre><code>a.loc[a.foo.str.extract('(\d+)')[0].astype(float).between(3,6)] </code></pre>
regex|pandas|dataframe|subset
2
17,520
67,623,665
Python: Export huge number as string from Excel File
<p>trying to get a column from excel file, this column has values like= 819195861645728953,213234621044503745. When I get the dataframe device column change all the values as: 8.19195861645729e+17, 2.132346210445037e+17 even if I changed to str or put this:</p> <pre><code>File['device'] = File.apply(lambda x: &quot;'&q...
<p>You need to stop pandas from inferring the dtype when it imports the data, otherwise it's too late. Do this by specifying the <code>dtype</code> upon import.</p> <pre><code>File = pd.read_excel(f'{NewFilePath}{NewFile}', sheet_name='Sheet1', dtype={'device': 'str'}) </code></pre>
python|excel|pandas
0
17,521
67,883,790
Calculate time blocked within a timerange with pandas
<p>I have a list of products produced or processes finished like this one:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Timestamp Start</th> <th>Timestamp Stop</th> </tr> </thead> <tbody> <tr> <td>Product 1</td> <td>2021-01-01 15:15:00</td> <td>2021-01-01 15:37:00</td> </tr...
<p>Input data:</p> <pre><code>&gt;&gt;&gt; df Name Start Stop 0 Product 1 2021-01-01 14:49:00 2021-01-01 15:04:00 # OK (overlap 4') 1 Product 1 2021-01-01 15:15:00 2021-01-01 15:37:00 # OK 2 Product 1 2021-01-01 15:30:00 2021-01-01 15:55:00 # OK 3 Product 1 2021-01-02 15:05:0...
python|pandas|date|datetime
0
17,522
67,636,637
pandas copy numerical values from column based on categorical condition and put in new column
<p>The purpose of this code is to:</p> <ol> <li>Create a dummy data set that contains 2 columns with 25 rows filled with values between 0 and 100.</li> <li>Calculate the peaks and troughs of the data and put in a new column called value.</li> <li>In order to plot the data and visualize the result I need numerical valu...
<p>I haven't looked much into the logic but I think the problem is the indexing here should be only 1 square bracket:</p> <pre><code>df.loc[x, 'peak'] = df.b.iloc[x] </code></pre> <p>same here</p> <pre><code>df.loc[x, 'trough'] = df.b.iloc[x] </code></pre>
python|pandas|scipy
1
17,523
67,900,923
Tensorflow Lite model outputs greater values than Tensorflow model
<p>I've trained a model in Tensorflow so the max output value that can produce is 1.0. Then I converted it to Tensorflow Lite to put on android and now the Tensorflow Lite model produce values much greater than 1.0. What can I do to fix this?</p> <p>I am using Tensorflow 2.5</p> <p>tf model -&gt; tflite model script</p...
<p>I found the solution. In my Tensorflow model I had some operations that could not convert to Tensorflow Lite model. Here is a guide about operation conversion <a href="https://www.tensorflow.org/lite/guide/ops_compatibility" rel="nofollow noreferrer">https://www.tensorflow.org/lite/guide/ops_compatibility</a>. I cha...
android|tensorflow|tensorflow-lite
0
17,524
61,350,752
How to use def-return or for-in statements on dataframes to avoid repetitions in code in python /pandas
<p>could someone please look at below code and advice what I have done wrong.</p> <p>I have 2 panda dataframes - df and x1 Both have the same columns and column names</p> <p>I have to execute below set of codes for df.Date_Appointment, x1.Date_Appointment and similary for df.Date_Scheduled and x1.Date_Scheduled. As ...
<p>It looks like you function should have two arguments -- <code>dataframe</code> and <code>column</code> -- both of which are lists, so I made the names plural. </p> <p>Then you need to loop over each argument. Note that you are also assigning a dataframe in the function the same name as your function, so I changed t...
python|pandas|function|dataframe|repeat
0
17,525
61,589,725
Difference of one element with all other elements after Groupby
<p>I have a data set as shown below:</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>Date Lon_s lat_s HLON_cv HLAT_cv 1853-11-09 31 -10.4 293.85 5.2 1853-11-09 302.3...
<p>Please try the following code and let me know if it works:</p> <pre><code>diff_df = pd.DataFrame() for group, values in df.groupby(df['Date']): lat_diff = []; lon_diff = [] for i in range(len(values['Lon_s'])): for j in range(len(values['HLON_cv']): lon_diff.append(values['Lon_s...
python-3.x|pandas|pandas-groupby
1
17,526
61,385,471
Using apply to add multiple columns in pandas
<p>I'm trying to run a function (row_extract) over a column in my dataframe, that returns three values that I then want to add to three new columns.</p> <p>I've tried running it like this</p> <pre><code>all_data["substance", "extracted name", "name confidence"] = all_data["name"].apply(row_extract) </code></pre> <p>...
<p>Check what the type of your function output is or what the datatypes are. It seems like that's a string.</p> <p>You can use the "split" method on a string to separate them.</p> <p><a href="https://docs.python.org/2/library/string.html" rel="nofollow noreferrer">https://docs.python.org/2/library/string.html</a> <a ...
python|pandas|dataframe
0
17,527
61,530,812
Pandas pivot to one row per subgroup
<p>Given data structured as follows</p> <pre><code>from io import StringIO import pandas as pd data = StringIO(""" person,q,a 1,q1,Yes 1,q2,No 1,q3,Yes 1,q1,No 1,q2,No 1,q3,Yes 2,q1,Yes 2,q2,Yes 2,q3,Yes 3,q1,No 3,q2,Yes 3,q3,Yes 3,q1,Yes 3,q2,No 3,q3,Yes""") df = pd.read_csv(data) </code></pre> <p>I am looking for...
<p>This is similar to pivot by two columns:</p> <pre><code>(df.assign(idx=df.groupby(['person','q']).cumcount()) .pivot_table(index=['person','idx'],columns='q',values='a', aggfunc='first') .reset_index('idx',drop=True) .reset_index() ) </code></pre> <p>Or equivalently with <code>set_index().unstack()</code>...
pandas|pandas-groupby
1
17,528
68,454,260
Pandas rolling window with less than or equal to
<p>I have a dataframe which is classified based on three dimensions:</p> <pre><code>&gt;&gt;&gt; df a b c d 0 a b c 1 1 a e x 2 2 a f e 3 </code></pre> <p>when I do a rolling of metric d by the following command:</p> <pre><code>&gt;&gt;&gt; df.d.rolling(window = 3).mean() 0 NaN 1 NaN 2 2.0 Na...
<p>I was able to roll using the following command:</p> <pre><code>&gt;&gt;&gt; df.d.rolling(min_periods = 1, window = 3).mean() 0 1.0 1 1.5 2 2.0 Name: d, dtype: float64 </code></pre> <p>with the help of <code>min_periods</code> one can specify the rolling window minimum config count.</p>
pandas|dataframe
0
17,529
68,737,929
InternalError: Cannot dlopen all CUDA libraries
<p>I am trying to run the Python code of <a href="https://www.kaggle.com/madz2000/nlp-using-glove-embeddings-99-87-accuracy/notebook" rel="nofollow noreferrer">this</a> Kaggle Jupyter Notebook and encounter following error:</p> <pre><code>--------------------------------------------------------------------------- Inter...
<p>Okay so I tried a few things and after installing tensorflow-gpu it worked. Maybe it can help someone else with this problem as well:</p> <pre><code>pip install tensorflow-gpu </code></pre>
python|tensorflow|machine-learning|keras
0
17,530
68,518,718
Filter Dataframe and leave only two oldest records of the same id
<p>I have this Dataframe:</p> <pre><code>id | object | date | ===|=========|===========| q1 | obj11 | 2021-06-21| q1 | obj16 | 2021-07-21| q1 | obj91 | 2021-05-21| q1 | obj10 | 2021-04-20| q2 | obj17 | 2021-04-21| q2 | obj72 | 2021-04-21| q2 | obj13 | 2021-05-21| q2 | obj14 | 2021-06-20| q3 | obj5...
<p>try via <code>sort_values()</code>+<code>groupby()</code>+<code>head()</code>:</p> <pre><code>df['date']=pd.to_datetime(df['date']) #Ensure that 'date' column is of dtype datetime out=df.sort_values(['id','date']).groupby('id',sort=False).head(2) #OR(Since without sort=False it is giving you opposite result then:) #...
python|pandas|dataframe
1
17,531
68,513,850
How do I convert a pointer returned by a C function invoked using ctypes into a numpy array?
<p>I have a function in C which returns an array of data and its length.</p> <p>Everything compiles and works fine and I can invoke the function.</p> <pre><code>&gt;&gt;&gt; from ctypes import * &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; test = cdll.LoadLibrary(&quot;/home/user/test_ctypes_1/testlib.so&quot;) &gt;&gt...
<p>I finally found the way:</p> <pre><code># CALLING C FUNCTION, RETURNS unsigned int *c_data AND int c_length c_length = c_int() c_data = c_void_p() test.get_uint_array(byref(c_data), byref(c_length)); # CONVERT TO NUMPY data = np.ctypeslib.as_array(cast(c_data, POINTER(c_uint)), shape=(c_length.value,)) </code></pre...
python|c|numpy|pointers|ctypes
1
17,532
53,266,364
Plot smoother bifurcation diagrams in Python
<p>I am using <code>matplotlib.scatter</code> to plot a bifurcation diagram for a system that goes through periodic-doubling route to chaos. Using the data that can be found <a href="https://github.com/Omer80/scatter_bifurcation_diagram" rel="nofollow noreferrer">here</a>, I use the following commands:</p> <pre><code>i...
<p>You would get the most <strong>accurate</strong> representation of the data when plotting each data point exactly one pixel in size.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt p, b = np.loadtxt('data/bifurcation.txt') fig, ax = plt.subplots(figsize=(8,6), dpi=100) # Plot one pixel sizes ma...
python|numpy|matplotlib|plot|scatter
2
17,533
53,245,946
Creating a new column based on Calendar function
<p>I have a <strong>data frame</strong>:</p> <pre><code> Year Month Week_of_month Day_of_week 0 2018 1 2 1 1 2018 1 1 2 2 2018 1 2 2 3 2018 1 1 3 4 20...
<p>Here you go:</p> <pre><code>df['Day'] = df.apply(lambda x: calendar.monthcalendar(x.Year, x.Month)[x.Week_of_month-1][x.Day_of_week-1], axis=1) </code></pre> <p>The output:</p> <p><a href="https://i.stack.imgur.com/thAzH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/thAzH.png" alt="enter imag...
python|pandas|numpy|datetime
1
17,534
53,218,866
Cosine Similarity between Query and Documents
<p>So i'm struggling in an information retrieval concept. It's in regards to the cosine similarity of the documents given a query.</p> <p>I am manipulating about 1000 files to generate a term frequency matrix with [docID x terms].</p> <p>I have this matrix generated but i'm stumped on what to do with the query and ge...
<p>I suggest you to have a look at <a href="https://nlp.stanford.edu/IR-book/pdf/06vect.pdf" rel="nofollow noreferrer">6th Chapter of IR Book</a> (especially at 6.3).</p> <p>You need to treat the query as a document, as well. Construct a vector for your query as you construct it for your documents. Then in order to ge...
python|numpy|multidimensional-array|information-retrieval|cosine-similarity
1
17,535
52,913,379
Concat dataframe having duplicate columns
<p>I have data frame series which looks like this:</p> <pre><code> a b r 1 43 630 587 d b c 1 34 30 87 </code></pre> <p>I want to create a new dataframe which looks like:</p> <pre><code> a b r d c 43 630 587 0 0 0 30 0 34 87 </code></pre> <p>I have used the co...
<p>You will need an outer join for that.</p> <pre><code>import pandas as pd df1 = pd.DataFrame({ 'a': [43], 'b': [630], 'r': [587] }) df2 = pd.DataFrame({ 'd': [34], 'b': [30], 'c': [87] }) df3 = df1.merge(df2, how='outer').fillna(0) print(df3) </code></pre> <p>Yields what you need.</p> <p...
python|pandas
3
17,536
65,667,918
Python Dataframe: How to check specific columns for elements
<p>I want to check whether all elements from a certain column contain the number 0?</p> <p>I have a dataset that I read with <code>df=pd.read_table('ad-data')</code><br> From this I felt a data frame with elements</p> <pre><code>[0] [1.] [2] [3] [4] [5] [6] [7] ....1559 [1.] 3 2 3 0 0 0 0 [2] 2 3 2 ...
<p>You can check for equality with 0 element-wise and use <code>all</code> for rows:</p> <pre><code>df['all_zeros'] = (df.iloc[:, 4:1560] == 0).all(axis=1) </code></pre> <p>Small example to demonstrate it (based on columns 1 to 3 here):</p> <pre><code>N = 5 df = pd.DataFrame(np.random.binomial(1, 0.4, size=(N, N))) df[...
python|pandas|dataframe|numpy|exists
1
17,537
63,708,008
How do you bar plot the nlargest of aggregated groupby data?
<p>I'm sure this has been answered somewhere, but I'm not great with pandas and need someone to break it down for me.</p> <p>I have this function:</p> <pre><code>def process_data(data): data = data[data['Bucket Number'] == 25.0].groupby(['Activity Month', 'Agent Sign']).agg({'Total Ping Current Forecast': [np.sum]}...
<p>Let's try extracting the rows with <code>groupby().cumcount</code> (also possible with <code>nlargest</code>), then plot with <code>sns.barplot()</code>:</p> <pre><code>processed = process_data(data) sns.barplot(data=processed.sort_values('sum',ascending=False) .assign(rank=lambda x: x.groupby...
pandas|sorting|pandas-groupby|bar-chart|seaborn
1
17,538
55,322,991
Why am I getting Nan after adding relu activation in LSTM?
<p>I have simple LSTM network that looks roughly like this:</p> <pre><code>lstm_activation = tf.nn.relu cells_fw = [LSTMCell(num_units=100, activation=lstm_activation), LSTMCell(num_units=10, activation=lstm_activation)] stacked_cells_fw = MultiRNNCell(cells_fw) _, states = tf.nn.dynamic_rnn(cell=stack...
<p>When you use the <code>relu activation function</code> inside the <code>lstm cell</code>, it is guaranteed that all the outputs from the cell, as well as the cell state, will be strictly <code>&gt;= 0</code>. Because of that, your gradients become extremely large and are exploding. For example, run the following cod...
python|tensorflow|lstm|relu
3
17,539
55,443,513
Unable to load model checkpoint to continue training,Unsuccessful TensorSliceReader constructor: Failed to find any matching files
<p>I'am trying to load model to continue training but i kepp getting error </p> <blockquote> <p>NotFoundError: Unsuccessful TensorSliceReader constructor: Failed to find any matching files for ./drive/My Drive/DLSRL/Model/</p> <p>[[Node: save/RestoreV2_81 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/r...
<p>You didn't specify checkpoint to restore. Change to:</p> <pre><code>saver.restore(sess, tf.train.latest_checkpoint('./drive/My Drive/DLSRL/Model/')) </code></pre>
tensorflow|neural-network|deep-learning|recurrent-neural-network
1
17,540
55,483,827
Storing data before passing it to interpolation routine
<p>I'll begin by apologizing, because I'm entirely new to python(Fortran guy here), and have been learning on the fly. As a result, there are probably some pretty glaring holes in my knowledge that may be obvious after reading my current dilemma. </p> <p>I have some data that will need to be written to a file, where i...
<p>I saw this earlier and hoped somebody who knew more than I do replied. Hopefully this can point you in the right direction</p> <p>To use the RectBivariateSpline class you need x and y as 1d arrays with the z values as a 2d array(len(x), len(y))</p> <p>Numpy needs any specific array indices to be integers, not floa...
python|numpy|scipy|interpolation
0
17,541
55,440,308
Merge pandas DataFrame and return common values with the column name
<p>Let us consider two different pandas dataframes <strong>df1</strong> and <strong>df2</strong> described below. This exercise consists of comparing all columns row by row and return the value that is in common in both dataframes, as well as the column name.</p> <p>Let us give an example for a better understanding. ...
<p>We can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html" rel="nofollow noreferrer"><code>pd.melt</code></a> to get the columns to rows, and after that do an <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferre...
python|pandas|dataframe
3
17,542
56,708,884
How to get the n index numbers before/preceding a specific label?
<p>I have a dataset that looks as below; my objective is to create a list that contains the three index numbers before <code>Accepted</code>.</p> <pre><code>i Label value 0 Rejected 12 1 Rejected 10 2 Rejected 22 3 Rejected 32 4 Rejected 25 5 ...
<p>you can use:</p> <pre><code>df[df.Label.ne('Accepted')&amp;df.Label.shift(-3).eq('Accepted')].index </code></pre> <hr> <pre><code>Int64Index([3, 4, 5], dtype='int64', name='i') </code></pre>
python|arrays|pandas|list|indexing
4
17,543
47,495,896
Normalize data on multi-index table using pandas
<p>I have a dataframe</p> <pre><code> O D counts 0 G1 G1 8576 1 G1 G2 4213 2 G1 G3 8762 3 G2 G1 8476 4 G2 G2 2134 ... </code></pre> <p>But each of the groups have different populations in O and D. So for example:</p> <p>G1 in O has, say, 1234 different members, while G1 in D has ...
<p>It seems you need reshape first and then <a href="https://stackoverflow.com/q/12525722/2901002"><code>normalize</code></a>:</p> <pre><code>df = df.set_index(['O','D'])['counts'].unstack(fill_value=0) print (df) D G1 G2 G3 O G1 8576 4213 8762 G2 8476 2134 0 df1 = (df - df.mean(...
python|pandas|dataframe|normalize
1
17,544
68,094,100
DataFrame.ne return false when the data it is comparing is None type
<p>I have been trying to combine two Pandas dataframes and compare the elements column wise and if they are not equal, paint them some color so it is easily distinguishable. The problem is when I try to compare None values. When both the values are None, the Dataframe.ne method return False, but I want it to return Tru...
<p>One trick is replace <code>None/NaN</code>s to same values only for comparing in both <code>DataFrame</code>s:</p> <p><em>Notice: Use values for replace which are not in both DataFrames, for avoid compare NaN in df1 and repalced value in df2 as True (False positive)</em></p> <pre><code>def highlight_diff(data, color...
python|pandas|dataframe
2
17,545
59,194,034
pandas read_csv parse dates
<p>I have written this date parsing function</p> <pre><code>def date_parser(string): try: date = pd.datetime.strptime(string, "%d/%m/%Y") except: date = pd.NaT return date </code></pre> <p>and I call it in pd.read_csv like this</p> <pre><code>df = pd.read_csv(os.path.join(path, file), ...
<p>I suggest change your function by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> with <code>errors='coerce'</code> for return <code>NaT</code> if not matched format <code>%d/%m/%Y</code>:</p> <pre><code>def date_pars...
python|pandas|python-datetime
3
17,546
56,979,908
How to get percentages value of predicted object In Tensorflow Object Detection API
<p>I used this <a href="https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10/blob/master/Object_detection_image.py" rel="nofollow noreferrer">code</a> to display object detector with percentage of predicted value, but the variable <code>num_detections</code> is a...
<p>You only need to evaluate that tensor <code>num_detections</code> in the created <code>session</code> by calling <code>sess.run</code>. The code you linked actually did that for you. </p> <pre><code># Perform the actual detection by running the model with the image as input (boxes, scores, classes, num) = sess.run(...
python|tensorflow
1
17,547
45,990,046
Pandas Iterate through rows from specified row number
<p>I want to read data from a pandas dataframe by iterating through the rows starting from a specific row number. I know there's <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iterrows.html" rel="nofollow noreferrer"><code>df.iterrows()</code></a>, but it doesn't let me specify from wh...
<p>Turn <code>Date</code> into <code>datetime</code>. Set <code>Date</code> as the <code>index</code>:</p> <pre><code>df.Date = pd.to_datetime(df.Date) df = df.set_index('Date') </code></pre> <p>Then:</p> <pre><code>for date, row in df['22/08/2017 00:00:00':].iterrows(): print(date.strftime('%c'), row.squeeze(...
python|pandas|dataframe|iterator
6
17,548
50,760,543
Error: OOM when allocating tensor with shape
<p>i am facing issue with my inception model during the performance testing with Apache JMeter.</p> <blockquote> <p>Error: OOM when allocating tensor with shape[800,1280,3] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc [[Node: Cast = CastDstT=DT_FLOAT, SrcT=DT_UINT8, ...
<p>OOM stands for Out Of Memory. That means that your GPU has run out of space, presumably because you've allocated other tensors which are too large. You can fix this by making your model smaller or reducing your batch size. By the looks of it, you're feeding in a large image (800x1280) you may want to consider dow...
python-3.x|tensorflow|gpu|gunicorn
20
17,549
50,772,396
pandas aggregate count higher than threshold
<p>I have a data frame that I want to groupby. I want to use df.agg to determine the length that exceed above 180.</p> <p>Is there a possible way to write a small function for it?</p> <p>I tried <code>len(nice_numbers[nice_numbers &gt; 180])</code> but it did not work.</p> <pre><code>df = pd.DataFrame(data = {'nice_...
<p>Create boolean mask by compare column by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.gt.html" rel="nofollow noreferrer"><code>gt</code></a> with aggregate <code>sum</code> for count <code>True</code>s values:</p> <pre><code>df1 = (df['nice_numbers'].gt(180) ....
python-3.x|python-2.7|pandas
4
17,550
66,425,396
how to import data from a excel list into a loop for a api python
<p>I am connecting an API and everything is going fine, now I have one problem, I have a data excel list like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Name</th> <th style="text-align: center;">Secondname</th> <th style="text-align: right;">Age</th> </t...
<p>You can do this using <code>pandas</code> but you have to install a module that will read excel files. If you are using only <code>.xls</code> extension, than you the module <code>xlrd</code> will be enough. But if you are using another extension, like <code>.xlsx</code>, you have to install <code>openpyxl</code></p...
python|excel|pandas|csv|data-import
0
17,551
66,664,318
Pandas: converting a None type array retrieved via API call from a list to a string (to enable use of Pivot Table)
<p>I query an internal database, retrieve data, and create a Pandas dataframe <code>df</code> that looks <em>similar</em> to the following:</p> <pre><code>import pandas as pd df = pd.DataFrame({'issue_key':['MED-187', 'MED-188', 'MED-190', 'MED-191'], 'creator': ['Smith, J', 'Williams, S', 'Wilson, ...
<p>If the issue is a rogue <code>None</code> value in the &quot;department&quot; column then you can use a conditional statement inside the list comprehension to deal with it:</p> <pre><code>df['new_department'] = [','.join(map(str, l)) if l is not None else 'NA' for l in df['department']] </code></pre> <p>or more gene...
python|pandas
1
17,552
66,446,346
any way to make validation data from `tfds` data in tensorflow?
<p>I am curious about making validation dataset from <code>tensorflow_datasets</code> in tensorflow because it is not clear to me how to split training data that come from <code>tfds</code>. I understand it is easy to make validation data by using <code>train_test_split</code> from <code>sklearn</code>, but I am not su...
<p>While loading the data you can specify splits, like this:</p> <pre><code>(train_data, validation_data) = tfds.load( 'mnist', split=['train[:80%]', 'train[80%:]'], as_supervised=True, ) </code></pre> <p>Splits can be specified as <code>'train'</code> and <code>'test'</code>. <a href="https://www.tensorflo...
python|tensorflow
1
17,553
66,553,128
Tensorflow bert tokenize unknown words
<p>I am currently doing the following tf tutorial : <a href="https://www.tensorflow.org/tutorials/text/solve_glue_tasks_using_bert_on_tpu" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/text/solve_glue_tasks_using_bert_on_tpu</a></p> <p>Testing the outputs of the tokenize function on different sentences...
<p>The default cache location for the <code>tensorflow/bert_en_uncased_preprocess/3</code> model is <code>/tmp/tfhub_modules/602d30248ff7929470db09f7385fc895e9ceb4c0</code> (<a href="https://www.tensorflow.org/hub/caching" rel="nofollow noreferrer">more on caching</a>). In the <code>assets</code> directory, you'll find...
tensorflow
2
17,554
57,464,201
How do I join 2 DataFrames in Python and preserve the NANs in the result?
<p>I have a dataframe that is missing time indexes of data that I want to upsample to a 15 minute interval and <em>maintain</em> the NAN in the upsampled points. Any idea how to do this? The idea is to build an empty dataframe with the correct timeseries indexes and then fill them with the good values. Here's a toy da...
<p>you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.resample.html" rel="nofollow noreferrer"><code>resample</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.resample.Resampler.asfreq.html?highlight=asfreq" rel="nofollow noref...
python|pandas|dataframe|nan
1
17,555
57,678,677
Multiple Object Tracking (MOT) benchmark data-set format for ground truth tracking
<p>I am trying to evaluate the performance of my object detection+tracking on the standard dataset used in the industry in the <a href="https://motchallenge.net/data/2D_MOT_2015/" rel="nofollow noreferrer">2DMOT Challenge 2015</a>. I have downloaded the dataset but I am unable to understand the data fields in the label...
<p>The last three fields represent the 3D real-world coordinates of the objects. A similar data structure can be found in videos of ETH-Bahnhof, ETH-Sunnyday, PETS09-S2L1 and TUD-Stadtmitte in 2DMOT2015. For ground-truth, score=1. But sometimes it varies b/w 0-1, then it acts as a flag value and zeroes mean that the li...
object-detection|tensorflow-datasets|yolo|video-tracking|faster-rcnn
0
17,556
72,873,406
Pandas to nested json
<p>My Pandas df is like:</p> <pre><code>RollCall Physics Chemisty Maths 1 20 30 25 2 25 30 30 3 15 12 35 4 20 15 30 </code></pre> <p>I wish to convert this to a json like:</p> <pre><code>{&quot;StudentDetails&quot;: { &quot;1&quot;:{&quot;Physics&quot;:20,&quot;Chemisty&quot;:30,&quot;Maths&quot;:...
<p>In your case do</p> <pre><code>df['RollCall'] = df['RollCall'].astype(str) d = {} d['StudentDetails'] = df.set_index('RollCall').to_dict('index') d Out[366]: {'StudentDetails': {'1': {'Physics': 20, 'Chemisty': 30, 'Maths': 25}, '2': {'Physics': 25, 'Chemisty': 30, 'Maths': 30}, '3': {'Physics': 15, 'Chemisty'...
python|pandas
2
17,557
73,135,890
Pandas : Prevent groupby-apply to sort the results according to index
<p>Say I have a dataframe,</p> <pre><code>dict_ = { 'Query' : ['apple', 'banana', 'mango', 'bat', 'cat', 'rat', 'lion', 'potato', 'london', 'new jersey'], 'Category': ['fruits', 'fruits', 'fruits', 'animal', 'animal', 'animal', 'animal', 'veggie', 'place', 'place'], } df = pd.DataFrame(dict_) </code></pre> ...
<p>Set <code>sort=False</code> for the <code>groupby</code> method</p> <p><strong>CODE</strong></p> <pre><code>rep_val = df.groupby('Category', sort=False).size().max() df = df.groupby('Category', sort=False).apply(lambda d: pd.concat(([d] * math.ceil(rep_val / d.shape[0]))).head(rep_val)).reset_index(drop=True) </code...
python|pandas|dataframe|group-by|pandas-apply
1
17,558
73,029,898
Pandas - get rid of repeated pair of column values in a row and move unique row value to new column
<p>I have a dataframe of football matches, like so:</p> <pre><code>team_id adversary_id round_id xG 262 263 1 0.45 263 262 1 0.34 245 254 1 0.67 254 245 1 0.15 ... </code></pre> <p>How do I get rid of repeated fixtures and change dataf...
<p>Try with <code>numpy</code> <code>sort</code> then <code>merge</code></p> <pre><code>df[['team_id','adversary_id']] = np.sort(df[['team_id','adversary_id']].values,axis=1) out = df.iloc[0::2].merge(df.iloc[1::2],on = ['team_id','adversary_id','round_id'], suffixes = ('_team','_adversary')) Out[403]: team_id adv...
python|pandas
3
17,559
73,012,301
Pytorch error mat1 and mat2 shapes cannot be multiplied in Autoencoder to compress images
<p>I receive this error. Whereas the size of my input image is 3x120x120, so I flatten the image by the following code, however, I received this error:</p> <p>mat1 and mat2 shapes cannot be multiplied (720x120 and 43200x512)</p> <p>I have tu use an autoencoder to compress my images of a factor of 360 ( So i started fro...
<p>I think you missed some basic characteristics of <code>nn.Linear</code> function. Its inputs are input and output channel dimension, respectively. And therefore only 1D input is allowable (considering batch, which is 3 in your case, it will be 2D in total ). Therefore you should first flatten your <code>x</code> for...
machine-learning|pytorch|torch|autoencoder
0
17,560
51,549,804
How to plot two maps side by side using pysal or geopandas?
<p>I want to plot two tematic maps side by side to compare then. I am using geopandas to plot the maps and pysal to generate the maps from spatial analysis.</p>
<p>You can create the subplots structure with matplotlib, and then add the plots with geopandas/pysal to the specific subplot:</p> <pre><code>import matplotlib.pyplot as plt fig, axes = plt.subplots(ncols=2) # add geopandas plot to left subplot geodataframe.plot(..., ax=axes[0]) # add pysal plot to right subplot usin...
python|maps|geopandas|pysal
8
17,561
70,959,319
Check every row of a df column for values in a list
<p>The column I'm interested in the dataframe looks like</p> <pre class="lang-py prettyprint-override"><code>names=['nonsoluable water', 'water percentage 98% grade', 'special chemical with grade chlorine', 'name with value'] </code></pre> <p>There are other columns too. Those are just numbers/identifiers.</p> <p>I nee...
<p>Try this:</p> <pre><code>df['flag'] = df['names'].str.contains('|'.join(check_for_these), regex=True, case=False).astype(int) </code></pre>
python|pandas|list|dataframe
2
17,562
51,736,770
averaging numpy array duplicate rows efficiently
<p>I have numpy arrays like this:</p> <pre><code>old=([[5.00000000e+00, 3.39622642e-03], [5.00000000e+00, 5.84905660e-04], [1.00000000e+01, 4.15094340e-04], [1.50000000e+01, 2.26415094e-03], [2.00000000e+01, 4.90566038e-02], [2.50000000e+01, 4.90566038e-01], [3.00000000e+01, 4...
<p>IIUC, you can use <code>pandas</code> for manipulating this data.</p> <pre><code>df = pd.DataFrame(old) </code></pre> <p>gives</p> <pre><code> 0 1 0 5.0 0.003396 1 5.0 0.000585 2 10.0 0.000415 3 15.0 0.002264 4 20.0 0.049057 5 25.0 0.490566 6 30.0 0.490566 7 40.0 ...
python|numpy|duplicates
2
17,563
35,879,757
Custom Time Periods with Groupby
<p>I've got the following Pandas DataFrame:</p> <pre><code>import datetime as dt import pandas as pd import numpy as np offset = 3 * pd.tseries.offsets.BMonthEnd() bond_index_1 = pd.date_range('1/1/14', '1/1/18', freq=offset, name='date') bond_1 = pd.DataFrame(data = np.random.uniform(0, 5, 16), ...
<p><a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#resampling" rel="nofollow">resample</a> seems one of the easy way to solve your problem.</p> <pre><code>print df_merged.reset_index().set_index('date').resample('6M', how='sum', closed='left', loffset='-1M') </code></pre> <p>yield,</p> <pre><cod...
python|pandas|pandas-groupby|date-arithmetic
2
17,564
35,841,600
pandas read_sql not reading all rows
<p>I am running the exact same query both through pandas' read_sql and through an external app (DbVisualizer). </p> <p>DbVisualizer returns 206 rows, while pandas returns 178. </p> <p>I have tried reading the data from pandas by chucks based on the information provided at <a href="https://stackoverflow.com/questions/...
<p>It's not a fix, but what worked for me was to rebuild the indices:</p> <ol> <li><p>drop the indices</p> </li> <li><p>export the whole thing to a csv:</p> </li> <li><p>delete all the rows:</p> <p>DELETE FROM table</p> </li> <li><p>import the csv back in</p> </li> <li><p>rebuild the indices</p> </li> </ol> <p>pandas:<...
pandas|sqlalchemy
-1
17,565
37,557,173
First element of series to cross threshold in numpy, with handling of series that never cross
<p>I have a numpy array of N time series of length T. I want the index at which each first crosses some threshold, and a -1 or something similar if it never crosses. Take <code>ts_array = np.randn(N, T)</code></p> <p><code>np.argmax(ts_array &gt; cutoff, axis=1)</code> gets close, but it returns a 0 for both time ser...
<p>One liner:</p> <pre><code>(ts &gt; c).argmax() if (ts &gt; c).any() else -1 </code></pre> <p>assuming <code>ts = ts_array</code> and <code>c = cutoff</code></p> <p>Otherwise:</p> <p>Use <code>argmax()</code> and <code>any()</code></p> <pre><code>np.random.seed([3,1415]) def xover(ts, cut): x = ts &gt; cut ...
python|numpy
7
17,566
37,336,306
How do I access a numpy array as quickly as a pandas dataframe
<p>I ran a comparison of several ways to access data in a <code>DataFrame</code>. See results below. The quickest access was from using the <code>get_value</code> method on a <code>DataFrame</code>. I was referred to this on this <a href="https://stackoverflow.com/questions/37216485/pandas-at-versus-loc">post</a>.</...
<p><code>iloc</code> is pretty general, accepting slices and lists as well as simple integers. In the case above, where you have simple integer indexing, pandas first determines that it is a valid integer, then it converts the request to an <code>iat</code> index, so clearly it will be much slower. <code>iat</code> e...
python|numpy|pandas
3
17,567
41,834,188
Pandas MultiIndex rearranging columns
<p>The MultiIndex rearranges the columns seemingly randomly when the label values are not aligned, when I use the function <code>get_level_values</code> to get the columns values.</p> <p>For instance, I can create a MultiIndex, whose labels are ordered from 0 to 4. </p> <pre><code>import pandas as pd import numpy as ...
<p>I'm not sure if this is a bug or not, it looks like <code>get_level_values</code> always returns a sorted array ignoring the creation order, the <code>IndexArray</code> itself knows the correct order. You can get the order you want using the following gnarly code to get the <code>label</code> array to mask the level...
python|pandas|multi-index
1
17,568
42,077,247
Calculating thd in python
<p>I'm trying to calculate the total harmonic distortion values of ac voltage supplied. I am sampling voltage data using Arduino at over 8 KHz rate and storing those data into a text file. Then I'm trying to calculate thd using the following code snippet written in python:</p> <pre><code> import numpy as np imp...
<p>Though this is long quiet, for anyone encountering this post like me: There are a couple of problems with the OP method.</p> <p>1) The magnitudes returned by FFT include a magnitude of the 0 frequency bin, so the assumption that max(abs_data) is the magnitude corresponding to the fundamental frequency is not correc...
python|numpy|arduino|fft|sampling
4
17,569
37,668,636
Create new column for data after each iteration of a for loop in python
<p>Using the next code I want to put the results in columns for differents values of m</p> <pre><code>import numpy as np for m in np.arange(0, 4, 1): for n in np.arange(1, 4, 1): coef = 2*m/n print coef </code></pre> <p>The results of this is:</p> <pre><code>0 0 0 2 1 0 4 2 1 6 3 2 </code></pre> <...
<p>Add a comma after the print so we don't add a newline and another print outside the inner loop to separate each line:</p> <pre><code>import numpy as np for m in np.arange(0, 4, 1): for n in np.arange(1, 4, 1): coef = 2*m/n print coef, print </code></pre> <p>Which will give you:</p> <pre><cod...
python|numpy
2
17,570
31,255,562
Stacking frames to a 3D array
<p>I'm working on a Raspberry Pi project in which I need to take about 30 images per second (no movie) and stack each 2D image to a 3D array using numpy array, without saving each 2D capture as a file (because is slow).</p> <p>I found this Python code to take images as fast as possible, but i don't know how to stack a...
<p>Any combination of <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dstack.html" rel="nofollow"><code>numpy.dstack()</code></a>/<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.hstack.html" rel="nofollow"><code>numpy.hstack()</code></a>/<a href="http://docs.scipy.org/doc/numpy/ref...
python|python-2.7|python-3.x|numpy
1
17,571
31,351,073
Pandas select rows where conditions meet across 2 columns
<p>I have a data frame i.</p> <p>I want to select where both columns(QUANTITY and Net) in one row are not equal to 0..</p> <p>i.e.</p> <p>If I want rows where either column is 0 I would use...</p> <pre><code>wanted = i[(i.QUANTITY != 0) &amp; (i.Net != 0)] </code></pre> <p>Instead I am looking where both QUANTITY ...
<p>Simply change the inequalities <code>!=</code> into equalities <code>==</code>:</p> <pre><code>wanted = i.loc[(i.QUANTITY == 0) &amp; (i.Net == 0)] </code></pre>
python|pandas|data-analysis
0
17,572
47,927,861
h5py accuracy for matrix storage
<p>I want to use Python3-h5py to store matrix to the .HDF5 format My problem is that when I compare the initial data to the data extracted from the HDF5 file, I get surprising differences.</p> <pre><code>import numpy import h5py # Create a vector of float64 values between 0 and 1 A = numpy.array(range(16384+1))/(1638...
<p>I am not fully sure that this can be considered as an answer, but I finally get rid of my problem with a small circumvent.</p> <p>To sum it up, it looks like there is a bug with "h5py v2.7.1-2"</p> <p>When using h5py to store arrays, don't use such command :</p> <pre><code>`Group01.create_dataset("Data", data=A, ...
python-3.x|numpy|floating-point|precision|h5py
1
17,573
49,238,722
Using reindex with duplicated axis
<p>Let's say I have a dataframe with dates as index. Each row contains information about a certain event on that date. The problem is that there could be more than one event on said date. This is an example DataFrame, df2:</p> <pre><code> one two 1/2 1.0 1.0 1/2 1.0 1.0 1/4 3.0 3.0 1/5 NaN 4.0 </code></pr...
<p>One way from <code>join</code> </p> <pre><code>df.join(pd.DataFrame(index=["1/2","1/3","1/4","1/5"]),how='outer') Out[193]: one two 1/2 1.0 1.0 1/2 1.0 1.0 1/3 NaN NaN 1/4 3.0 3.0 1/5 NaN 4.0 </code></pre>
python|pandas|dataframe
6
17,574
49,156,504
Prevent pandas from rewriting formatted header to csv for every chunk
<p>I have a dirty csv with an ugly header that I have formatted and stored in a list.</p> <p>I want to read this csv chunk by chunk, perform some regex on the data, and then write to a new csv.</p> <p>I'm using this function to do so</p> <pre><code>def format_data(data_location, formatted_header): df = pd.read_c...
<p>Since you only want to write the header once, use a boolean to see if you're on the first chunk.</p> <p>For example:</p> <pre><code>write_header = True for chunk in df: chunk = chunk.replace('(?!(([^"]*"){2})*[^"]*$),', '', regex=True) chunk.to_csv('formatted_data.csv', mode='a', index=False, header=write_...
python|pandas
7
17,575
58,752,527
How to get specific values from data frame, using pandas to graph
<p>I would like to be able to graph the specific date as x value and size as y value when the size is 24022 and the type is bid. I tried the following:</p> <pre><code>headers = ['ticker', 'size', 'price', 'unix','type','date'] dtypes = {'ticker': 'str', 'size': 'int', 'price': 'float', 'unix': 'float','type': 'str','d...
<p>The answer to your problem is, that <code>&amp;</code> has higher priority than <code>==</code>. So all you need to do is put your conditions in brackets:</p> <pre><code>x1 = now3.loc[(now3["size"] == 24022) &amp; (now3["type"]=='BID'), "date"] y1 = now3.loc[(now3["size"] == 24022) &amp; (now3["type"]=='BID'), "siz...
python|pandas|dataframe
0
17,576
58,697,112
Problems converting mat formular to python
<p>Hope you can help.</p> <p>I am working with the fifa20 dataset, which have around 85 variables describing the players. There are 6 variables I want to work with: attack_finishing, skill_dribbling, power_long_shots, skill_ball_control, mentality_positioning, mentality_penalties. </p> <p>I have the following simple ...
<p>I'm not going to provide the solution to your problem, I'm rather going to help you get through your problem :</p> <p>First of all, if you want to put comments in a python code, use : <code>#</code></p> <pre><code># this is a comment </code></pre> <p>So, your first 2 lines looks right:</p> <pre><code>import pand...
python|pandas|csv
0
17,577
58,789,317
Extract the data and modify an existing excel with openpyxl
<p>I would like to modify an existing excel via openpyxl. The purpose is to take finance data and insert it in the specific columns so that it can perform the calculations.</p> <p>I would like column 1 to show the opening prices</p> <p>I write this code.</p> <p><div class="snippet" data-lang="js" data-hide="false" d...
<p>IIUC, this should work :</p> <pre><code>from openpyxl import load_workbook wb = load_workbook('aa.xlsx') ws = wb['Sheet1'] # choose your sheet. </code></pre> <h3>then we decide your column to replace with your df.</h3> <pre><code>col_to_replace = 'A' for index, row in df.iterrows(): cell = f'{col_to_replace}{...
python|pandas|openpyxl|pandas-datareader
0
17,578
58,842,373
TypeError: 'int' object is not callable in np.random.seed
<p>I am trying to do data augmentation on 2018 Data Science Bowl previous competition on Kaggle. I am trying this code:</p> <pre><code>## Data augmentation # Creating the training Image and Mask generator image_datagen = image.ImageDataGenerator(shear_range=0.5, rotation_range=50, zoom_range=0.2, width_shift_range=0.2...
<p>Make sure you <strong>not</strong> assign <strong>np.random.seed</strong> to some integer somewhere in your script</p> <p>Like this:</p> <pre><code>np.random.seed = 42 </code></pre>
python|numpy|random
15
17,579
70,146,598
how do I initialize a 3D array with two 2D array in python?
<p>I have two array as follows:</p> <pre><code>a=np.vstack([np.loadtxt(path, dtype='float') for path in glob.iglob(r'E:/PostDoc/720/*.txt')]) b=np.vstack([np.loadtxt(path, dtype='float') for path in glob.iglob(r'E:/PostDoc/1080/*.txt')]) </code></pre> <p>the <code>a</code> and <code>b</code> are two arrays with size <c...
<p>If you want to &quot;stack&quot; two 2-D arrays, then the most intuitive method is to use <em>dstack</em>:</p> <pre><code>c = np.dstack((a, b)) </code></pre> <p>This way you don't even need to create any empty array before.</p> <p>But if you want to stack your both source arrays &quot;along another axis&quot; (as I ...
python|arrays|python-3.x|numpy
1
17,580
70,182,295
How to calculate monthly and weekly averages from a dataframe using python?
<p>The below is my dataframe. How to calculate both monthly and weekly averages from this dataframe in python? I need to print month start&amp;end and week start&amp;end then the average of the month and week</p> <pre class="lang-py prettyprint-override"><code>**Input SAMPLE DATASET** kpi_id kpi_name ru...
<p><code>groupby</code> is your friend</p> <pre><code>monthly = df.groupby(pd.Grouper(key='run_date', freq='M')).mean() weekly = df.groupby(pd.Grouper(key='run_date', freq='W')).mean() </code></pre>
python|pandas|dataframe
2
17,581
56,042,764
How to shift the column values based on the difference with previous row in python pandas?
<p>I have dataframe which looks like below:</p> <pre><code> Name width height breadth 0 1 13 90 2 1 2 101 45 1 2 3 78 6 1 3 5 11 34 1 4 6 23 8 ...
<p>Create helper Series for groups by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.diff.html" rel="nofollow noreferrer"><code>Series.diff</code></a>, compare by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.ne.html" rel="nofollow noreferrer"><code>S...
python|pandas|dataframe
1
17,582
56,403,115
find empty cells with support for mixed datatypes of lists and sets and ints and str
<p>Consider the following dataframe.</p> <pre><code>import pandas as pd my_df = pd.DataFrame(columns =['A','B','C']) my_df.at[0,'A'] = 1234 my_df.at[0,'C'] = ['5','6','7'] my_df.at[1,'A'] = set([8,9,10]) my_df.at[1,'B'] = 'my_hat' </code></pre> <p>Then I want to find all the cells that are nan.</p> <pre><code>for ro...
<p><strong>Edit:</strong><br> If you really need to check each cell for <code>NaN</code>, you may do it on <code>my_df.isna()</code> such as </p> <pre><code>for row_index, row_data in my_df.isna().iterrows(): for cell in row_data: if cell: print("found one") </code></pre> <hr> <p>Try this to see t...
pandas|list|nan
2
17,583
56,364,142
How to search list elements in a data frame?
<p>I have a list <code>dates</code> with dates as string objects with all dates from 2003-01-01 to 2017-06-30:</p> <pre><code>['2003-01-01', '2003-01-02', '2003-01-03', '2003-01-04', '2003-01-05', '2003-01-06', '2003-01-07', '2003-01-08', '2003-01-09', '2003-01-10', '2003-01-11', '2003-01-12', '2003-01-13', '2003-01-1...
<p>First we convert your <code>time</code> column to datetime, so we can acces solely the dates with <code>Series.dt.dates</code>. When we extracted the date from your datetime we convert it to <code>string</code> so we can compare it to your list.</p> <p>Finally we use the <a href="https://pandas.pydata.org/pandas-do...
python|pandas|if-statement
0
17,584
55,916,389
i want to convert 1-May-19 and 5/1/2019 to 1/5/2019 in my dataframe
<p>i have 2 columns with date formats: 5/1/2019 and 1-May-19. i want them in 1/5/2019 format.</p> <p>the code mentioned here does not seem to change the format of 1 column, i need to convert both the columns into format 1/5/2019</p> <pre><code>df['billing_start_date'] = (pd.to_datetime(df['billing_start_date'], forma...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html" rel="nofollow noreferrer"><code>Series.dt.strftime</code></a> ...
python|pandas|datetime
0
17,585
55,620,493
Sum up average pixel values of all images: TypeError: 'numpy.float64' object is not iterable
<p>I have to set a threshold based on a pixel value to remove some images in a folder and I need to know the standard deviation of pixel values. Therefore, I need to sum up all mean-pixel-values.</p> <p>The followings are what I have tried</p> <p>The following codes demonstrate how the output of np.mean() look like</...
<p>This function can be substituted for standard deviation.</p> <pre><code>def function(image): (R, G, B)= function_for_rgb(image) std_dev = statistics.stdev([R, G, B]) #standard deviation return round(std_dev,2) </code></pre>
python|numpy|scikit-image
0
17,586
64,940,797
Pandas DataFrame: How to Create Multi Column Index
<p>I have a pandas DataFrame that looks similar to this:</p> <pre><code> player frameID x y 0 Tom 0 1 3 1 Tom 1 2 3 2 Tom 2 1 3 3 John 0 4 2 4 John ...
<p>Let's create a multilevel index then use <code>stack</code> + <code>unstack</code> to reshape the dataframe:</p> <pre><code>df.set_index(['frameID', 'player']).stack().unstack([1, 2]) </code></pre> <hr /> <pre><code>player Tom John Greg x y x y x y frameID 0 ...
python|pandas|dataframe
3
17,587
64,905,649
Meaning of "2 * np.random.rand(100,1)"
<p>I'm a begginer on programming.<br /> I tried running an simple linear regression example in a book. Y=4*X+6<br /> I have set <code>np.random.seed(0)</code>.<br /> When creating X, the code in the book used <code>2 * np.random.rand(100,1)</code>.<br /> I created X1, X2, X3 in the following way. Below is the code.</p>...
<ol> <li><p>It doubles the value. How do you think that it doesn't?</p> </li> <li><p>They're different because you called for a random array in two different locations. Why would you expect <code>random</code> to return the same values on two successive calls? The sequence would hardly be random, then.</p> </li> </o...
python|numpy|random
1
17,588
40,287,438
Returning the index value in Pandas
<p>I know this should be obvious, but with previous similar questions I could not get a satisfying answer. Let's say I have a data frame with the index being peoples names and a few columns containing their data (height, male/female, DOB, etc.). Now I want the tallest person in my dataframe and return the correspondin...
<p><code>df['Height']</code> would return a Serie.</p> <p>Then you should use <code>df['Height'].argmax()</code> or <code>df['Height'].idxmax()</code> to get the corresponding index.</p> <p>With the links to the documentation :</p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.idxma...
python-3.x|pandas
1
17,589
39,494,246
How to plot data after groupby
<p>I have a data frame similar to this</p> <pre><code>import pandas as pd df = pd.DataFrame([['1','3','1','2','3','1','2','2','1','1'], ['ONE','TWO','ONE','ONE','ONE','TWO','ONE','TWO','ONE','THREE']]).T df.columns = [['age','data']] print(df) #printing dataframe. </code></pre> <p>I performed the groupby function o...
<p>Try:</p> <pre><code>group_data = group_data.reset_index() </code></pre> <p>in order to get rid of the multiple index that the <code>groupby()</code> has created for you.</p> <p>Your <code>print(group_data)</code> will give you this:</p> <pre><code>In [24]: group_data = df.groupby(['age','data'])['COUNTER'].sum()...
python|pandas|matplotlib
6
17,590
44,013,981
Difference between array[i][:] and array[i,:]
<p>I'm new to python, so I'm used to use <code>array[i][j]</code> instead of <code>array[i,j]</code>. Today a script I created following a tutorial was not working until I found out that I was using</p> <pre><code>numpy.dot(P[0][:], Q[:][0]) </code></pre> <p>instead of</p> <pre><code>numpy.dot(P[0,:], Q[:,0]) </code...
<p>You should almost always use <code>[i, j]</code> instead of <code>[i][j]</code> when dealing with numpy arrays. In many cases there's no real difference but in your case there is.</p> <p>Suppose you have an array like this:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; arr = np.arange(16).reshape(4, ...
python|arrays|numpy|indexing
6
17,591
69,398,250
How to sort a list of tuples by the first element in each tuple, and pick the tuple with the largest last element in each group
<p>Here I have a list of n k-tuples (Here I set n = 4, k = 5)</p> <pre><code>A = [(1, 3, 5, 6, 6), (0, 1, 2, 4, 5), (1, 9, 8, 3, 5), (0, 2, 3, 5, 7)] </code></pre> <p>I hope to sort these tuples by their first element, so it will be 2 groups. And in each group, I want to select only 1 tuple whose last element is the la...
<p>You can use <code>itertools.groupby</code> for this:</p> <pre class="lang-py prettyprint-override"><code>import itertools def by_first_element(t): return t[0] def by_last_element(t): return t[-1] sorted_A = sorted(A, key=by_first_element) groups = [[*g] for _, g in itertools.groupby(sorted_A, key=by_fi...
python|pandas|list|tuples
1
17,592
69,378,684
PDF table to pandas data frame using camelot
<p>I'm trying to create a simple way to get data from pdf into a pandas data frame. Something like that:</p> <pre class="lang-py prettyprint-override"><code>import camelot import pandas as pd pdf = camelot.read_pdf(&quot;file1.pdf&quot;) print(pdf[0].df) </code></pre> <p>The point is that I'm trying with two differen...
<p>To correctly extract tables from the second file, it is necessary to process background lines, <a href="https://camelot-py.readthedocs.io/en/master/user/advanced.html#process-background-lines" rel="nofollow noreferrer">using the appropriate parameter (process_background)</a> for lattice method, as you can see in the...
python|pandas|python-camelot
1
17,593
41,005,249
What does the error: `Loaded runtime CuDNN library: 5005 but source was compiled with 5103` mean?
<p>I was trying to use TensorFlow with GPU and got the following error:</p> <pre><code>I tensorflow/core/common_runtime/gpu/gpu_device.cc:838] Creating TensorFlow device (/gpu:0) -&gt; (device: 0, name: Tesla K20m, pci bus id: 0000:02:00.0) E tensorflow/stream_executor/cuda/cuda_dnn.cc:347] Loaded runtime CuDNN librar...
<p>This is an approximate description of what is going on.</p> <p>cuDNN has major releases that are numbered e.g. 4.0, 5.0, 5.1, etc.</p> <p>These major releases may incorporate API changes. Therefore a program that uses cuDNN v4 (i.e. 4.0) may need some modifications to work with or use new features in cuDNN v5 (i.e...
python|cuda|tensorflow|cudnn
19
17,594
54,134,632
Why doesn't tf.train.GradientOptimizer work on my digit recognition model, while ShampooOptimizer from tensorflow.contrib works just fine?
<p>I developed a neural network model for digit recognition using tensorflow. I used tf.train.GradientDescent as my optimizer, and I got very low prediction accuracy (around 11%). But if I only change my optimizer to ShampooOptimizer from tensorflow.contrib, it had good accuracy on validation data (around 92%).</p> <p...
<p>You are initializing all weights to the same value (using <code>np.ones</code>). This breaks your model because all hidden units will compute the same thing (and receive the same errors) so they will also learn the same thing, meaning you effectively have one hidden unit only. I don't know what the Shampoo optimizer...
tensorflow|optimization|deep-learning|gradient-descent
0
17,595
54,221,591
pandas: how to summarize unequal size datasets?
<p>Let's say I have datasets of <em>different size</em> eg <code>X_1 = [1,2,3]</code> and <code>X_2 = [4,5,6,7,8]</code>. I would like to create a dataframe with summary variables (mean, std, etc), with one dataset per row, and on statistic per column. How can I do that in pandas?</p>
<p>I will using <code>describe</code></p> <pre><code>df=pd.concat([pd.Series(x) for x in [X_1, X_2]], axis=0, keys=['X_1', 'X_2'])# notice here I am using axis=0 rather than 1 df.groupby(level=0).describe() Out[442]: count mean std min 25% 50% 75% max X_1 3.0 2.0 1.000000 1.0 1.5 2.0 2.5 ...
python|pandas
5
17,596
38,463,210
Correct way of computing a covariance matrix of two matrices with different number of features and same number of observations
<p>What is the proper way of computing the covariance matrix of two matices, X of shape <code>(n x p)</code> and Y of shape <code>(n x q)</code></p> <pre><code>import numpy as np X = np.array([np.random.normal(size=10), np.random.normal(size=10), np.random.normal(size=10)]).T Y = np.array([np.rando...
<p>From the documentation:</p> <pre><code>y : array_like, optional An additional set of variables and observations. y has the same form as that of m. </code></pre> <p>The shape of the matrices is not equal. I suppose the numpy authors forgot to check the dimensions in the first case. I have no other explanat...
python|numpy
1
17,597
65,996,654
Pandas group by unique ID and Distinct date per unique ID
<p>Title may be confusing: I have a dataframe that displays user_id sign in's during the week. My goal is to display the de-duped ID along with the de-duped dates per employee, in order to get a count of # days the user uniquely signed in for the week. So I've been trying to enforce a rule to make sure I'm only getting...
<ul> <li>calculate start of week</li> <li>then it's a simple use of <code>count()</code></li> </ul> <pre><code>df = pd.read_csv(io.StringIO(&quot;&quot;&quot;ID date # days signed in for week 10301 1/4/2021 6 10301 1/4/2021 6 10301 1/5/2021 6 10301 1/6/2021 6 10301 1/7/2021 6 10301 1/8...
python|pandas
1
17,598
52,773,007
Converting list(numpy_array) to list(list) and comparing 2 lists
<pre><code>List1 = ['SSA','NTSS','BB','KI'] List2 = [array(['(IEDSS)'],dtype=object), array(['PSG'], dtype=object), array(['KI'], dtype=object)],array(['IEDSS'], dtype=object)] </code></pre> <p>The questions are given below</p> <ol> <li><p>I want to convert List 2 as list 1 i.e. converting list(numpy array) to list(lis...
<p>You can convert your arrays to lists, extract the first item and replace parentheses with whitespace. This is performed within a set comprehension to extract unique values.</p> <p>Then use <code>set.difference</code>, or its syntactic sugar <code>-</code>, to remove items common with <code>List1</code>.</p> <pre><...
python|list|numpy
0
17,599
52,517,399
Can't filter on dates in pandas
<p>Following some tutorials I am trying to filter my data by dates selected from a dropdown menu. I have set my date column as the index and tested that all the values are of type datetime but I am receiving the following error:</p> <pre><code>TypeError("'&lt;' not supported between instances of 'str' and 'datetime.da...
<p>So it seems I just need to switch the order of the dates in the slice. Using <code>newData = df.loc[lastDayMonth:firstDayMonth]</code> but <code>newData = df.loc[firstDayMonth:lastDayMonth]</code> doesnt work. I think this is due to in my data my data is decending from latest date to oldest.</p>
python|pandas
1