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
1,000
64,317,235
How do I install researchpy on Jupyter Notebook 6.0.3
<p>I am trying to install <code>researchpy</code> with <code>pip install researchpy</code> or <code>pip3 install researchpy</code> on Jupyter but it gives the following error:</p> <pre><code>ModuleNotFoundError Traceback (most recent call last) ModuleNotFoundError: No module named 'researchpy' </c...
<p>You run the command below from the terminal(like cmd.exe):</p> <pre><code>pip install researchpy </code></pre>
python|pandas|jupyter-notebook
1
1,001
64,278,022
Reversing the first two columns of a DataFrame and appending results
<p>I have a Dataframe that looks similar to the following:</p> <pre><code>value1 value2 value3 A B 1 C D 2 E F 3 </code></pre> <p>I want to create a DataFrame that looks something like this:</p> <pre><code>value1 value2 value3 A B 1 C D 2 E F 3 B ...
<p>I would use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename.html" rel="nofollow noreferrer"><code>rename</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html" rel="nofollow noreferrer"><code>append</code></a> follo...
python|pandas|dataframe
1
1,002
47,917,288
Tensorflow Dataset.from_generator blocks input?
<p>I want to build a project that requests will be put to a python Queue at any arbitrary time, and a set of tensorflow models consume those requests from the queue, and return their results immediately.</p> <p>The models are in different threads, different tf.Graph, but the structure and weight values are the same.</...
<p>Could you modify the loop that generates elements into the queue to:</p> <pre><code>for i in range(100): request_queue.put(np.full((1, 8), i, 'int32')) print('round {}, queue size {}'.format(i, request_queue.qsize())) </code></pre> <p>and share the output?</p> <p>I tried reproducing your issue (using the ...
python|multithreading|tensorflow
0
1,003
47,984,900
Profiling Execution Time of ResNet
<p>I used CIFAR-10 dataset to train and evaluate ResNet on Intel i7 CPU. (ResNet model is in Tensorflow: <a href="https://github.com/tensorflow/models/tree/master/official/resnet" rel="nofollow noreferrer">https://github.com/tensorflow/models/tree/master/official/resnet</a>)</p> <p>Now, I am interested in profiling t...
<p>I'd use <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/profiler/README.md" rel="nofollow noreferrer">tf.profiler</a>. Unless you're executing eagerly, the interesting performance issues (once the graph is built) will be in TensorFlow C++ code rather than Python.</p>
tensorflow|neural-network|profiling|conv-neural-network|resnet
0
1,004
47,743,832
Assign requires shapes of both tensors to match. lhs shape= [1024] rhs shape= [1200]
<p>I am new to TensorFlow and trying to create my own NMT based on the tutorial from <code>https://github.com/tensorflow/nmt/</code>.<br> I am experiencing an error upon restoring the trained model for inference:</p> <blockquote> <p>Assign requires shapes of both tensors to match. lhs shape= [1024] rhs shape= [1200]...
<p>I fixed it now, just a human error, switched variable (<code>batch_size</code> and <code>num_units</code>) arrangement in another method.</p>
tensorflow
0
1,005
58,950,272
How to Multi-Head learning
<p>I have about 5 models that work pretty well trained individually but I want to fuse them together in order to have one big model. I'm looking into it because one big model is more easy to update (in production) than many small model this is an image of what I want to achieve. <a href="https://i.stack.imgur.com/hyQd...
<blockquote> <p>my question are, is it ok to do it like this</p> </blockquote> <p>Sure you can do that. This approach is called <a href="https://ruder.io/multi-task/" rel="nofollow noreferrer">multi-task learning</a>. Depending on your datasets and what you are trying to do, it will maybe even increase the performan...
machine-learning|deep-learning|pytorch
4
1,006
59,002,475
Jupyter notebook magic command - use %who DataFrame to get list of DataFrames?
<p>I can print all interactive variables, with some minimal formatting using <code>%who</code>.</p> <p>If I only want defined DataFrames, <code>%who DataFrame</code> works great. </p> <p><strong>Is there a way to send the output of <code>%who DataFrame</code> to a list?</strong> </p>
<p>I believe <a href="https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-who_ls" rel="nofollow noreferrer"><code>%who_ls</code></a> is what you're looking for: </p> <blockquote> <p>Return a sorted list of all interactive variables. <br><br> If arguments are given, only variables of types matchi...
python|pandas|jupyter-notebook
2
1,007
58,620,311
return missing dates Python
<p>I have a CSV file with 1600 dates and I'm trying to find all missing dates. For example:<br> 03-10-2019<br> 01-10-2019<br> 29-09-2019<br> 28-09-2019<br> should return : 02-10-2019,30-09-2019.</p> <p>Here's what I've wrote:</p> <pre><code>with open('measurements.csv','r') as csvfile: df = pd.read_csv(csvfile, deli...
<p>Idea is use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.asfreq.html" rel="nofollow noreferrer"><code>DataFrame.asfreq</code></a> for add all missing values to <code>DatetimeIndex</code>, so possible filter by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/inde...
python-3.x|pandas|dataframe|datetime
1
1,008
58,884,584
TensorFlow Serving Cluster Architecture
<p>Folks, I am writing an application which will produce recommendations based on ML model call. The application will have different models, some of them should be called in sequence. A data scientist should be able, to upload a model in the system. This means that the application should have logic to store models meta...
<p>I need some clarification on what you're trying to do. Is the feature vector for all the models the same? If not then it will be quite a bit harder to do this. Trained models are encapsulated in the SavedModel format. It sounds like you're trying to train an ensemble, but some of the models are frozen? You coul...
tensorflow|tensorflow-serving|tfx
1
1,009
58,808,380
How to change pandas dataframe strings into integers?
<p>Here I have a csv file that I am attempting to turn into all integer values, but I am not sure how to do it. I have looked at other posts but they don't seem to be working.</p> <p>Here is my csv:</p> <pre><code>X1,X2,X3,X4,X5,X6,X7,X8,X9,PosNeg x,x,x,x,o,o,x,o,o,positive x,x,x,x,o,o,o,x,o,positive x,x,x,x,o,o,o,o,...
<p>For this you can use the replace() function of your pandas Dataframe to first replace all "x" values with 1 and then afterwards "o" with 0 as such:</p> <pre><code>&gt;&gt;&gt; df = pd.read_csv(r"&lt;PATH&gt;") &gt;&gt;&gt; df 1 2 3 0 x x o 1 x x o 2 o o x 3 x o x &gt;&gt;&gt; df = df.replace("x", ...
python|pandas|data-science
1
1,010
70,272,926
How do I split a dataframe column values in pandas to get another column using python?
<p>I have created a dataframe like this from a list.</p> <pre><code> Name 0 Security Name % to Net Assets* DEBENtURES 0.04 1 Britannia Industries Ltd. EQUity &amp; RELAtED 96.83 2 HDFC Bank 6.98 3 IC...
<p>There is no column <code>row</code> and no separator comma, so use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.rsplit.html" rel="nofollow noreferrer"><code>Series.str.rsplit</code></a> for split from right with <code>n=1</code> for first space:</p> <pre><code>print (df.column...
python|pandas|dataframe
2
1,011
70,319,286
Question about Google Colab Transformer Tutorial
<p>I'm trying to follow the Tensorflow Transformer tutorial here:</p> <p><a href="https://github.com/tensorflow/text/blob/master/docs/tutorials/transformer.ipynb" rel="nofollow noreferrer">https://github.com/tensorflow/text/blob/master/docs/tutorials/transformer.ipynb</a></p> <p>In the tutorial, they reproduce the imag...
<p>Looking at the notebook more carefully, I see that the loss function is calculated as:</p> <pre><code>loss_object = tf.keras.losses.SparseCategoricalCrossentropy( from_logits=True, reduction='none') </code></pre> <p>As explained in the link below, setting <em>from_logits</em> to <em>True</em> ensures that the So...
tensorflow|google-colaboratory|transformer-model
0
1,012
70,041,590
What does the ^ symbol mean when passed into the .where() funtion?
<p>Could someone please explain what does the <code>^^^</code> symbol does when passed into the <code>np.where</code> function?</p> <p><img src="https://i.stack.imgur.com/tOEje.jpg" alt="Video explaining np.where usage with Pandas dataframe" /></p> <p>Does it just represents the number of arguments that should be passe...
<blockquote> <p>Does it just represents the number of arguments that should be passed in?</p> </blockquote> <p>Yes.</p> <p>It's being used in this case to point to the first call to <code>np.where</code>.</p> <p>You can see for yourself:</p> <pre><code>$ python3 Python 3.9.7 (default, Oct 22 2021, 13:39:39) &gt;&gt;&...
python|pandas|numpy
1
1,013
56,082,038
How to update da Pandas Panel without duplicates
<p>Currently i'm working on a Livetiming-Software for a motorsport-application. Therefore i have to crawl a Livetiming-Webpage and copy the Data to a big Dataframe. This Dataframe is the source of several diagramms i want to make. To keep my Dataframe up to date, i have to crawl the webpage very often. </p> <p>I can d...
<p>If I understand your problem correctly, your issue is that you have overlapping data for the second lap: information while the lap is still in progress and information after it's over. If you want to put all the information for a given lap in one row, I'd suggest use multi-index columns or changing the column names...
python|pandas|dataframe
0
1,014
56,099,598
Binary-vectorize pandas DataFrame column
<p>In a fictional patients dataset one might encounter the following table:</p> <pre class="lang-py prettyprint-override"><code>pd.DataFrame({ "Patients": ["Luke", "Nigel", "Sarah"], "Disease": ["Cooties", "Dragon Pox", "Greycale &amp; Cooties"] }) </code></pre> <p>Which renders the following dataset:</p> <p...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.get_dummies.html#pandas-series-str-get-dummies" rel="nofollow noreferrer">Series.str.get_dummies</a> with right separator,</p> <pre><code>df.set_index('Patients')['Disease'].str.get_dummies(' &amp; ').reset_index() ...
python|pandas|dataframe
6
1,015
56,027,645
Merging column values in a data frame in Pandas / Python
<p>I'm trying to merge the values of columns (Columns B and C) within the same dataframe. B and C sometimes have the same values. Some values in B are present in C while some values in C are present in B. The final results would show one column that is the combination of the two columns.</p> <h2>Initial data:</h2> <pre...
<p>IIUC</p> <pre><code>df['B']=df[['B','C']].replace("''",np.nan).bfill(1).loc[:,'B'] df=df.drop('C',1).rename(columns={'D':'C'}) df Out[102]: A B C 0 Apple Canada RED 1 Bananas Germany BLUE 2 Carrot US GREEN 3 Dorito NaN INDIGO </code></pre>
python|pandas
2
1,016
55,635,300
How to add column data as rows in an efficient manner?
<p>I have a dataframe, df, that looks something like this</p> <pre><code> col1 col2 A 2 2 B 4 1 C 0 0 D 1 1 E 2 2 </code></pre> <p>and would like to add two columns, so that for each row i, the new column col3 contains the value of df.loc[i-1,col1] and col4 contains the value of...
<p>with a <code>map</code> and <code>pd.concat</code></p> <pre><code>df.join( pd.concat( dict(enumerate(map(df.col1.shift, range(1, 3)), 3)), axis=1 ).add_prefix('col') ) col1 col2 col3 col4 A 2 2 NaN NaN B 4 1 2.0 NaN C 0 0 4.0 2.0 D 1 1 0.0 4.0 E...
python|python-3.x|pandas
2
1,017
55,617,581
Barplot comparing two columns
<p>I would like to draw a barplot graph that would compare the evolution of 2 variables of revenues on a monthly time-axis (12 months of invoices).</p> <p>I wanted to use sns.barplot, but can't use "hue" (cause the 2 variables aren't subcategories?). Is there another way, as simple as with hue? Can I "create" a hue?</...
<p>You can do:</p> <pre><code>render_df = data_pivot[data_pivot.columns[-2:]] fig, ax = plt.subplots(1,1) render_df.plot(kind='bar', ax=ax) ax.legend() plt.show() </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/DzTkA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DzTkA.png" alt...
python|pandas|bar-chart|seaborn
2
1,018
55,977,126
Updating older Keras models with deprecation warnings
<p>I have an older Keras model file that works perfectly. When I try to load it in <code>tensorflow==1.13.1</code> however, I'm given a host of warnings:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf model = tf.keras.models.load_model("best.h5") </code></pre> <blockquote> <p>WARNING:te...
<p>These aren't errors, they relate to the internal Keras implementation in tensorflow, there is not much you can do other than to wait for <code>tf.keras</code> to update their implementation and not use deprecated functions.</p>
python|tensorflow|keras
0
1,019
64,650,192
Using multiple filter on multiple columns of numpy array - more efficient way?
<p>I have the following 2 arrays:</p> <pre><code>arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [7, 5, 6, 3], [2, 4, 8, 9]] ids = np.array([6, 5, 7, 8]) </code></pre> <p>Each row in the array <code>arr</code> describes a 4-digit id, there are no redundant ids - neither in...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.isin.html" rel="nofollow noreferrer"><code>np.isin</code></a> all across <code>arr</code> and <code>all</code>-reduce to get <code>result</code> -</p> <pre><code>In [15]: arr[np.isin(arr, ids).all(1)] Out[15]: array([[5, 6, 7, 8]]) </code></pre>
python-3.x|numpy|filter|generator
1
1,020
64,915,035
Aggregate based on value of a different column
<p>I would like to aggregate the sum of <code>source_bytes</code> if <code>destination_port</code> is <code>80</code> into a separate column called <code>source_bytes_port_80</code></p> <p>My dataframe</p> <pre><code>date | source_ip | destination_ip| source_bytes | destination_port 2020-11-13 13:57...
<pre><code>df.groupby(&quot;desination_port&quot;)[&quot;source_bytes&quot;].sum() </code></pre> <p>Will give you the sum for each destination_port. Then add it back into the file as you would like it.</p>
pandas
0
1,021
39,964,254
Python Updating Global variables
<p>Could anyone tell me what I am doing wrong in my code. How come, I cannot update my global variable? To my understanding, if it is a global variable I can modify it anywhere.</p> <p>If the numpy is creating a new array (when I use np.delete), what would be the best way to delete an element in an numpy array. </p> ...
<p>If you want to use a global variable in a function, you have to say it's global IN THAT FUNCTION:</p> <pre><code>import numpy as np a = np.array(['a','b','c','D']) def hello(): global a a = np.delete(a, 1) print a hello() </code></pre> <p>If you wouldn't use the line <code>global a</code> in your fun...
python|numpy
8
1,022
40,196,995
Create a copy and not a reference of a NumPy array
<p>I'm trying to make a Python program with NumPy, but I ran into a problem:</p> <pre><code>width, height, pngData, metaData = png.Reader(file).asDirect() planeCount = metaData['planes'] print('Bildgroesse: ' + str(width) + 'x' + str(height) + ' Pixel') image_2d = np.vstack(list(map(np.uint8, pngData))) imageOriginal_...
<p>You need to create the copy of the object. You may do it using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.copy.html" rel="noreferrer"><code>numpy.copy()</code></a> since you are having <code>numpy</code> object. Hence, your initialisation should be like:</p> <pre><code>imageEdited_3d = imag...
python|numpy|copy
12
1,023
69,628,951
Word2Vec Tensorflow tutorial weird output
<p>I'm trying out the Word2Vec tutorial at tensorflow (see here: <a href="https://www.tensorflow.org/tutorials/text/word2vec" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/text/word2vec</a>)</p> <p>While all seems to work fine, the output is somewhat unexpected to me, especially the small cluster in th...
<p>There can be various reasons.</p> <p>One reason is that this is due to the so-called <a href="https://arxiv.org/pdf/1412.6568.pdf" rel="nofollow noreferrer">hubness problem</a> of embedding spaces, which is an artifact of the high-dimensional space. Some words end up close to a large part of the space and act as sor...
tensorflow|pca|word2vec|embedding
1
1,024
69,655,075
cx_Oracle.NotSupportedError: Python value of type NAType not supported
<p>I am trying to insert data into an oracle table, while in the process I am getting this error:</p> <pre><code>cx_Oracle.NotSupportedError: Python value of type NAType not supported </code></pre> <p>My script:</p> <pre><code>data = data_df.values.tolist() sql = &quot;insert into %s(%s) values(%s)&quot; %(table_name, ...
<p>Here is a minimal example reproducing your problem</p> <pre><code>d = {'id': [1, pd.NA], 'col': [ pd.NA,'x' ]} df = pd.DataFrame(d) print(df.values.tolist()) cur.executemany(&quot;insert into tab(id, col) values (:1, :2)&quot;, df.values.tolist()) [[1, &lt;NA&gt;], [&lt;NA&gt;, 'x']] ... cx_Oracle.NotSupportedEr...
python|pandas|oracle
2
1,025
69,549,094
No CUDA GPUs are available
<p>i get this error from the method during the model training process. i am using the google colab to run the code. the google colab dont have any GPU. Is their any other way i can make the code run without requiring cuda cpu.</p> <p>How can i fix this error ?</p> <pre><code>def train_model(model, train_loader, val_loa...
<p>Just remove the line where you create your <code>torch.device()</code> and remove all the <code>.to(device)</code> functions where you use it. Then you also don't need to write <code>.cpu().detach()</code> also. You can simply write <code>predict.numpy()</code> as such. When you write <code>device = torch.device(&qu...
python|deep-learning|pytorch
1
1,026
41,088,064
ConcatOp : Dimensions of inputs should match
<p>I'm developing a deep learning model with tensor flow and python:</p> <ul> <li>First, using CNN layers, get features.</li> <li>Second, reshaping the feature map, I want to use LSTM layer.</li> </ul> <p>However, a error with not-matching dimension...</p> <p>ConcatOp : Dimensions of inputs should match: <code>shape...
<p>When you input to the rnn cell, the batch size of input tensor and state tensor should be same. </p> <p>In the error message, it says <code>h3_rnn_input[:,time_step,:]</code> has shape of <code>[71,48]</code> while <code>state</code> has shape of <code>[1200,24]</code> </p> <p>What you need to do is make the first...
python|tensorflow|deep-learning|lstm
5
1,027
41,109,480
Calculating the size of a full outer join in pandas
<h2>tl;dr</h2> <p>My issue here is that I'm stuck at calculating how many rows to anticipate on each part of a full outer merge when using Pandas DataFrames as part of a combinatorics graph.</p> <h2>Questions (repeated below).</h2> <ol> <li>The ideal solution would be to not require the merge and to query <a href="h...
<h1>Question 1.</h1> <p><a href="http://dask.pydata.org/en/latest/" rel="nofollow noreferrer">Dask</a> shows a lot of promise in being able to calculate the merge table "out of memory" by using hdf5 files as a temporary store. </p> <p>By using multi-processing to create the merges, dask also offers a performance incr...
python-3.x|pandas|merge|combinatorics
1
1,028
41,151,435
Pandas idiomatic way to custom fillna
<p>I have time series data in the following format, where a value indicates an accumulated amount since the past recording. What I want to do is "spread" that accumulated amount over the past periods containing NaN so that this input:</p> <pre><code>s = pd.Series([0, 0, np.nan, np.nan, 75, np.nan, np.nan, np.nan, np.n...
<p>This might work, for each chunk of missing values, create a group variable with <code>cumsum</code>(from the end of the series) and then perform a grouped average operation on each chunk:</p> <pre><code>s.groupby(s.notnull()[::-1].cumsum()[::-1]).transform(lambda g: g[-1]/g.size) #2016-01-01 0.0 #2016-01-02 ...
python|pandas
5
1,029
54,240,939
euclidean distance calculation using Python and Dask
<p>I'm attempting to identify elements in the euclidean distance matrix that fall under a certain threshold. I then take the positional arguments for this search and use them to compare elements in a second array (for sake of demonstration this array is the first eigenvector of PCA, but the sort is the most relevant pa...
<p>You can calculate the Euclidean distance in Dask by using <a href="https://dask-distance.readthedocs.io/en/latest/dask_distance.html#dask_distance.euclidean" rel="nofollow noreferrer"><code>dask_distance.euclidean(x,y)</code></a>.</p>
python|numpy|dask|euclidean-distance|dask-delayed
1
1,030
52,540,037
Create Image using Matplotlib imshow meshgrid and custom colors
<p>I am trying to create an image where the x axis is the width, and y axis is the height of the image. And where each point can be given a color based on a RBG mapping. From looking at imshow() from Matplotlib I guess I need to create a meshgrid on the form (NxMx3) where 3 is a tuple or something similar with the rbg ...
<p>It will of course completely depend on what you want to do with the values you supply to the function. So let's assume you just want to put the x values as the red channel and the y values as the blue channel, this could look like</p> <pre><code>def somefunc(x_value, y_value): return np.dstack((x_value/5., np.z...
python-3.x|numpy|matplotlib
1
1,031
58,497,010
How to setup tfserving with inception/mobilenet model for image classification?
<p>I'm unable to find the proper documentation to successfully serve the inception or mobilenet models and write a grpc client to connect to the server and perform image classification.</p> <p>Till now, I've successfully configured the tfserving image on CPU only. Unable to run it on my GPU.</p> <p>But, when I make a...
<p>Like I understood, there are 2 issues in your question.</p> <p>A) Running tfserving on GPU.</p> <p>B) Making a successfully grpc client request.</p> <p>Let's start one-by-one.</p> <hr> <p><strong>Running tfserving on GPU</strong></p> <p>It is simple 2-step process.</p> <ol> <li><p>Pulling latest image from th...
tensorflow|grpc|tensorflow-serving|tensorflow2.0
1
1,032
58,466,415
How to reshape a tensorflow Dataset structure?
<p>I'm coding a Pix2Pix network, with my own load_input/real_image function, and I'm currently creating the dataset with tf.data.Dataset. The problem is that my dataset has the wrong shape:</p> <p>I've tried applying a few tf.data.experimemtal functions, none of them work as I want.</p> <pre class="lang-py prettyprin...
<p>You can do it in two ways.</p> <p><strong>Option 1 (Preferred)</strong></p> <pre><code>raw_data1, raw_data2 = tf.unstack(raw_data, axis=1) train_dataset = tf.data.Dataset.from_tensor_slices((raw_data1, raw_data2)) </code></pre> <p><strong>Option 2</strong></p> <pre><code>def map_fn(data): return tf.unstack(d...
python|tensorflow|tensorflow-datasets
2
1,033
58,600,411
Convert list to dataframe
<p>I am running a loop that appends three fields. Predictfinal is a list, though it is not necessary that it should be a list.</p> <pre><code> predictfinal.append(y_hat_orig[0]) predictfinal.append(mape) predictfinal.append(length) </code></pre> <p>At the end, predictfinal returns a long list. But I real...
<p>Based on <a href="https://stackoverflow.com/a/48347320/6926444">https://stackoverflow.com/a/48347320/6926444</a></p> <p>We can achieve it by using <strong>zip()</strong> and <strong>iter()</strong>. The code below iterates three elements each time.</p> <pre><code>res = pd.DataFrame(list(zip(*([iter(data)] * 3))), ...
python|pandas
2
1,034
69,143,408
Revisit "How to find the position/index of a particular file in a directory?"
<p>I have a question from the following discussion:</p> <p><a href="https://stackoverflow.com/questions/40675412/how-to-find-the-position-index-of-a-particular-file-in-a-directory">How to find the position/index of a particular file in a directory?</a></p> <p>Suppose I have <em>three excel files</em> in a folder: <em>t...
<p>If you wanted to look values in the dictionary as per the screenshot you posted, you could do: <code>dfs[files[1][:-5]]</code>. This gets the file at index 1 and then excludes the file extension as you've done in in the step to build the <code>dfs</code> dictionary.</p> <p>Optionally, you could use the <a href="http...
python|excel|pandas
2
1,035
69,189,717
Filtering for and replacing values in one Pandas DataFrame based on common columns of another DataFrame
<p>I have a question regarding Pandas and the correct indexing and replacing of values.</p> <p>I have 2 DataFrames, df1 and df2, with the same columns (Col1, Col2, Col3 and Col4).</p> <pre><code>df1 = pd.DataFrame([['A','b','x',1], ['A','b','y',2], ['A','c','z',3], ['B','b','x',4]], columns=['Col1', 'Col2', 'Col3', 'Co...
<p>You could do an <code>isin</code> with the indices, and assign the value via boolean masking:</p> <pre class="lang-py prettyprint-override"><code> cols = ['Col1', 'Col2', 'Col3'] temp1 = df1.set_index(cols) temp2 = df2.set_index(cols) # get the booleans here booleans = temp1.index.isin(temp2.index) # this assi...
python|pandas|indexing
4
1,036
68,963,686
Get closest datetime index value from pd DataFrame
<p>I've got following DataFrame:</p> <pre><code> holdings 2021-08-28 04:10:14.130412+00:00 {'$USD': 158, 'Apple': 3} 2021-08-25 18:10:14.130412+00:00 {'$USD': 158, 'Apple': 3} </code></pre> <p>With holdings as column and datetimes as index.</p> <p>I got this by converting following di...
<p>I have to say you have a bit unconventional way to work with pandas ;)</p> <p>Nevertheless, <code>get_loc</code> return the range, so you need to use <code>iloc</code> to slice your row:</p> <pre><code>holdings_df.iloc[holdings_df.index.get_loc(pd.to_datetime(cur_datetime), method='backfill')]['holdings'] </code></p...
python|pandas|dataframe
1
1,037
69,187,899
Find Last Available Date in Pandas Data Frame
<p>Suppose that I have a Pandas DataFrame as below:</p> <pre><code>+------------+-------+ | Date | Price | +------------+-------+ | 01/01/2021 | 10 | | 01/02/2021 | 20 | | 01/03/2021 | 30 | | 01/05/2021 | 40 | | 01/08/2021 | 20 | | 01/09/2021 | 10 | +------------+-------+ </code></pre> <p>The ab...
<p>The other answers are assuming the dates are always in order in your dataframe.</p> <p>Since your dates are sortable, you can just use comparison operators (note that this will work even if you keep them as strings, as the format you are using is lexicographically sortable).</p> <p>To get the last available date, fi...
python|pandas|datetime
1
1,038
44,593,948
Using df.column.str.contains and updating a pandas dataframe column
<p>I have a pandas dataframe with two columns.</p> <pre><code>df= pd.DataFrame({"C": ['this is orange','this is apple','this is pear','this is plum','this is orange'], "D": [0,0,0,0,0]}) </code></pre> <p>I want to be able to read this C column and return in the D column the name of the fruit. So my thought process wa...
<p>Consider this dataframe</p> <pre><code>df= pd.DataFrame({"C": ['this is orange','this is apple which is red','this is pear','this is plum','this is orange'], "D": [0,0,0,0,0]}) C D 0 this is orange 0 1 this is apple which is red 0 2 this is pear 0 3 ...
python|regex|pandas
1
1,039
44,400,860
Pandas Filter by string
<p>I need to filter my groups to show only the groups that contain a string in all the rows of a group.</p> <pre><code>Index A B C 0 A1 B5 T 1 A1 B2 T 2 A1 B2 F 3 A2 B5 T 4 A2 F5 T 5 A3 F4 T 6 A4 F4 F </code></pre> <p>Returns: </p>...
<p><strong>Using <code>transform</code></strong><br> <em>Fastest solution that is also simple</em> </p> <pre><code>df[df.C.eq('T').groupby(df.A.values).transform('all')] A B C Index 3 A2 B5 T 4 A2 F5 T 5 A3 F4 T </code></pre> <hr> <p><strong>Using <code>crosstab</code></s...
python|pandas|numpy
2
1,040
44,661,035
Restore vgg16 network in tensorflow
<p>This one has been giving me a headache for quite some time now, even though it seems to be very basic.</p> <p>I have the vgg16 network downloaded as a .cpkt (from <a href="https://github.com/tensorflow/models/blob/master/slim/README.md#Pretrained" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/...
<p>Saver takes the variables to restore in constructor. In other words, you have to create the variables before you can restore them. Here is the example from Saver's doc:</p> <pre><code>v1 = tf.Variable(..., name='v1') v2 = tf.Variable(..., name='v2') # Pass the variables as a dict: saver = tf.train.Saver({'v1': v1,...
r|tensorflow
0
1,041
44,494,221
How to store `pandas.DataFrame` in a PANDAS-LOADABLE binary format other than `pickle`
<p>I have a problem with saving <code>pandas.DataFrame</code> (1 440 000 000 rows).</p> <p>From what I can see in the API, the only available options to store (and then load) the array are either CSV or pickle.</p> <p>Saving in pickle format ends with a mysterious exception (<code>SystemError: error return without ex...
<p>I would guess that your data frame is too big. Pickle has some limits. You are much better off either saving in a database or using <em>to_hdf</em> (or lots of other IO routines, <em>to_msgpack</em> might works as well).</p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_hdf....
python|python-2.7|python-3.x|pandas|dataframe
1
1,042
61,152,176
Joining time series by common date in Python (dataframe & series/list question)
<p>Noob here. PLEASE FORGIVE ABYSMAL FORMATTING as I am still learning. I am trying to create a time series (a dataframe, I think?) that consists of three columns. One is a date column, the next is an inventory column, and the last is a price column.</p> <p>I have pulled two separate series (date &amp; inventory; date...
<p>If you want to manipulate them as DataFrames in the rest of your code, you can transform <code>ngstor</code> and <code>ngpx</code> into DataFrames as follows:</p> <pre><code>import pandas as pd # I create two lists that look like yours ngstor = [[1,2], ["2020-04-03", "2020-05-07"]] ngpx = [[3,4] , ["2020-04-03", "2...
python|pandas|list|join|series
1
1,043
60,777,165
Filter a multidimensional numpy array by column
<p>I have a multidimensional numpy array and I only want specific values in each column of the array. If the vlaue does not match that of what I am filtering by I want to delete the entire row. Code snippet:</p> <pre><code>array = ([4, 78.01, 65.00, 98.00], [5, 23.08, 87.68, 65.3], [6, 45.98, 56.54, ...
<p>You need to chain all conditions with <code>bitwise operators</code> and the perform boolean indexing:</p> <pre><code>array[(array[:,0] &gt; 0) &amp; (array[:,0] &lt; 100) &amp; (array[:,3] &gt; 90) &amp; (array[:,3] &lt; 100)] array([[ 4. , 78.01, 65. , 98. ], [ 6. , 45.98, 56.54, 98.76]]) </code></pre...
python|arrays|numpy|multidimensional-array
1
1,044
71,540,057
numpy matrix row to csv
<p>in the code below, my intention is to copy the rows of this matrix to a csv file. I know that the csv function writer copies an array perfectly. But when the row comes from a matrix this doesn't seem to work. The csv file then looks like this <a href="https://i.stack.imgur.com/jtTI9.png" rel="nofollow noreferrer">'u...
<p>Some Commands that may be useful in this solution:</p> <pre><code>np.matrix.ravel() np.matrix.flatten() np.matrix.tolist() </code></pre> <p>In your example, replace the <code>np.matrix</code> with <code>V</code>.</p>
arrays|matrix|multidimensional-array|numpy-ndarray|csvwriter
0
1,045
71,670,673
How to divide each value in column by the maximum value of a subset of that column
<p>I am trying to divide each row in a column by the maximum of a sub-list in the column where the sub-list if the column filtered by a category variable</p> <blockquote> <p>Is there a single line vector equation that creates col3? I have been trying to use groupby with transform(lambda x: x...) but can't seem to get t...
<p>Sure:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df['col2'] / df.groupby('col1')['col2'].transform(max) 0 0.50 1 1.00 2 0.75 3 1.00 </code></pre> <p>You could then assign that result to a new column of your choice.</p>
python|pandas|lambda|max
2
1,046
71,482,239
Diagonalizing a pandas DataFrame
<p>Consider the following pandas DataFrame:</p> <pre><code>import numpy as np import pandas as pd df_foo = pd.DataFrame([1,2,3]) </code></pre> <p>I believe I used to be able to diagonalize this DataFrame as follows (see e.g. this thread <a href="https://stackoverflow.com/questions/17408896/diagonalising-a-pandas-serie...
<p>Convert one column Dataframe to <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.squeeze.html" rel="nofollow noreferrer"><code>DataFrame.squeeze</code></a> and then your solution working well:</p> <pre><code>df_foo_diag = pd.DataFrame(np.diag(df_foo.squeeze()...
python|pandas|numpy
3
1,047
71,478,959
Removing dot symbol from string - Pandas Dataframe
<p>I'm trying to replace '.' symbol to '':</p> <pre><code>excel_data_df['serialNumber'] = df2[['Serial number', 'Serial number.1']].agg(''.join, axis=1).replace(to_replace = '.', value = '', regex = True) </code></pre> <p>My string: &quot;TF013168.&quot; Name: serialNumber, dtype: object, number saved as text in the ex...
<p>Escape <code>.</code> by <code>\.</code>, because <code>.</code> is special regex character for replace substrings:</p> <pre><code>excel_data_df['serialNumber'] = df2[['Serial number', 'Serial number.1']].agg(''.join, axis=1).replace(to_replace = '\.', value = '', regex = True) </code></pre>
python-3.x|pandas
2
1,048
42,257,725
Spedup distance and summary computation between two HUGE multi-dimensional arrays in python
<p>I have only a year of experience with using python. I would like to find summary statistics based on two multi-dimensional arrays <code>DF_All</code> and <code>DF_On</code>. Both have <code>X</code>,<code>Y</code> values. A function is created that computes distance as <code>sqrt((X-X0)^2 + (Y-Y0)^2)</code> and gene...
<p>Here's an approach making use of <code>vectorization</code> by getting rid of the looping there -</p> <pre><code>from scipy.spatial.distance import cdist def get_values_vectorized(DF_All, Array_On): a = DF_All[['X','Y']].values b = np.array(Array_On)[:,2:].astype(int) v_mask = (cdist(b,a) &lt; 35).asty...
python|numpy
1
1,049
69,809,867
Custom Loss Function returning - InvalidArgumentError: The second input must be a scalar, but it has shape [64]
<p>I'm trying to use a modified version of <a href="https://stackoverflow.com/questions/69803718/keras-custom-loss-penalize-more-when-actual-and-prediction-are-on-opposite-sides/69807735#69807735">this custom loss</a> and I'm getting the error below</p> <pre><code>InvalidArgumentError: The second input must be a scala...
<p>The problem is that your <code>custom_loss</code> is returning a function rather than a scalar value. If you replace <code>tf.cond</code> with <code>tf.where</code> your code will work.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import tensorflow as tf from tensorflow.keras.models import ...
python|tensorflow|keras|deep-learning|loss-function
2
1,050
69,886,845
How do 1x1 convolutions preserve learned features?
<p>Below, I use channels and feature maps interchangeably.</p> <p>I'm trying to better understand how 1x1 convolution works with multiple input channels and have yet to find a good explanation of this. Before getting into 1x1, I'd like to ensure my understanding of 2D vs 3D convolution. Let's look at a simplistic examp...
<p>A 1x1 convolution is a 2D convolution just with a &quot;kernel size&quot; of 1. Since there is no sense of spatial neighborhoods, like in a 3x3 kernel, how they are able to learn spatial features depends on the architecture.</p> <p>By the way, the difference in a 2D convolution and a 3D convolution is in the movemen...
python|tensorflow|keras|deep-learning|conv-neural-network
0
1,051
69,797,187
Keras input Pandas dataframe
<p>I'm new to Keras and I want to fit my train data in an Excel file. My data has shape(1000, 5, 5), 1000 batches of data which are saved in 1000 spreadsheets, each sheet contain 5 columns and rows:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">A</th> <th style...
<p>Maybe try omitting your <code>map</code> function altogether and simply passing your data directly to <code>tf.data.Dataset.from_tensor_slices</code>:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import tensorflow as tf import numpy as np spread_sheet1 = {'A': [1, 2, 1, 2, 9], 'B': [3, 4,...
python|pandas|dataframe|tensorflow|keras
1
1,052
69,920,013
How to combine two dataframes on a column, with missing rows in one of them?
<p>I am trying to combine dataframe_A:</p> <pre><code>file 1 file 2 file 3 file 4 file 5 </code></pre> <p>with dataframe_B:</p> <pre><code>file 2 | some data | more data file 4 | other data | additional data file 5 | data | data data </code></pre> <p>along the file_name column, to end up with something like th...
<p>Use <code>merge</code> with <code>how='left'</code> parameter:</p> <pre><code>&gt;&gt;&gt; dfA.merge(dfB, on='A', how='left').fillna('~') A B C 0 file 1 ~ ~ 1 file 2 some data more data 2 file 3 ~ ~ 3 file 4 other data ...
python|pandas|dataframe
2
1,053
69,974,884
Problem when modifying a copy of slice from DataFrame. (feat. numpy.where)
<p>Why does warning occur when modifying a copy of <code>Pandas.dataframe</code>? And why doesn't warning occur when modifying using <code>numpy.where</code>? (df = DataFrame Object)</p> <p>Warning Code</p> <pre><code>[186] df = input_df.copy() [187] df['trade_status'][df['trade_status'] == 'DONE'] = 'FILLED' ---------...
<p>The result of <code>df = input_df.copy()</code> is indeed a new DataFrame. In this point you are right.</p> <p>But you don't operate on it directly. Note that <code>df['trade_status'][df['trade_status'] == 'DONE']</code> creates a <strong>view</strong> of <em>df</em>.</p> <p>So when you attempt to save a new value t...
python|dataframe|numpy
1
1,054
72,148,923
how to parse numpy array by line
<p>Use cv2 to process PNG image, I want some areas to be transparent. change point [0, 0, 0, 255] to [0, 0, 0, 0].</p> <p>for example,</p> <pre class="lang-py prettyprint-override"><code># a is ndarray(880, 1330, 4) a = [[[100, 90, 80, 255], [80, 10, 10, 255],], ..., [[0, 0, 0, 255], [0, 0, 0, ...
<p>You need to create a mask.</p> <p>Here is a simple example:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np # Create some data a = (np.random.rand(10, 10, 4)*255).astype(int) a[ :5, :5, :] = 0 a[:, :, 3] = 255 b = a.copy() </code></pre> <p>Now create a mask:</p> <pre class="lang-py prettypr...
python|numpy
1
1,055
72,230,762
How to completely reorganise a table using aggregate data from qualitative information
<p>I have a pandas dataframe which has the following layout:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column</th> <th>data type</th> </tr> </thead> <tbody> <tr> <td>'Water-Binder'</td> <td>float</td> </tr> <tr> <td>'Fly Ash'</td> <td>float</td> </tr> <tr> <td>'Age'</td> <td>int</td> ...
<p>Try to concatenate 'Water-Binder', 'Fly Ash', 'Age' fields and then group:</p> <pre><code>data = [ [0.43, 0.0, 3, 26.446759], [0.43, 0.0, 7, 44.444444], [0.43, 0.0, 28, 100.00000], [0.43, 0.0, 3, 11.316173], [0.43, 0.0, 7, 37.493929] ] df = pd.DataFrame(data, columns= ['Water-Binder', 'Fly Ash',...
python|pandas|dataframe|aggregate
0
1,056
72,473,268
Is there a way to resample dataframe and apply customised function but with different frequence?
<p>I've defined a customised function using an array as argument. I've a DataFrame where the indexes are minutely timestamps. They look like:</p> <pre><code>2022-05-12 00:01:03 2022-05-12 00:03:17 2022-05-12 00:06:10 </code></pre> <p>What I want to do is resampling the data so I have a dataframe where the indexes are:...
<p>You could use Pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rolling.html" rel="nofollow noreferrer">rolling</a> function. Since this function also accepts a time period as the moving window size, you could set the window parameter to the desired <code>10min</code> span.</p> <pre class...
python|pandas
0
1,057
50,532,497
Issue with columns in csv using pandas groupby
<p>I have these below columns in my csv . Usually all these columns have value like below and the code works smoothly .</p> <pre><code>dec list_namme list device Service Gate 12 food cookie 200.56.57.58 Shop 123 </code></pre> <p>Now I encountered issue, I got one csv file that has all th...
<p>Performing a <code>groupby</code> on an empty dataframe is resulting in a dataframe without groupby-key columns.</p> <p>One solution is to test if your dataframe is empty before performing manipulations:</p> <pre><code>if os.path.isfile(client_csv_file): df = pd.read_csv(csv_file) if df.empty: df =...
python|python-3.x|pandas|csv|pandas-groupby
1
1,058
50,270,283
RNN with many-to-one setup - which output to use
<p>I going through a series of machine learning examples that use RNNs for document classification (many-to-one). In most tutorials, the RNN output of the last time step is used, i.e., fed into one or more dense layers to map it to the number of classes (e.g., <a href="https://discuss.pytorch.org/t/example-of-many-to-o...
<p><em>Pooling over time</em> is a specific technique that is used to extract the features from the input sequence. From <a href="https://stackoverflow.com/q/48549670/712995">this question</a>:</p> <blockquote> <p>The reason to do this, instead of "down-sampling" the sentence like in a CNN, is that in NLP the senten...
python|machine-learning|recurrent-neural-network|pytorch|rnn
1
1,059
45,705,002
numpy.array with and without specifying dtype behaves strange
<p>I am completely puzzled by this.</p> <p>From the following</p> <pre><code>import numpy as np a = np.array([4, -9]) a[0] = 0.4 a </code></pre> <p>I <strong>expected output:</strong> <code>array([ 0.4, -9])</code>. But it gives me</p> <p><code>array([ 0, -9])</code>.</p> <p>But when I changed the <code>dtype</co...
<p>The problem is that your array is of <code>dtype=np.int64</code>:</p> <pre><code>In [141]: a = np.array([4, -9]) In [142]: a.dtype Out[142]: dtype('int64') </code></pre> <p>This means that you can only store integers, and any floats are truncated before assignment is done. If you want to store floats and ints tog...
python|arrays|numpy
3
1,060
45,285,663
Is it possible to join all the same terms into the same pandas dataframe column?
<p>I have the following large pandas dataframe, which is composed of several terms:</p> <pre><code>type name exp ------------------- feline tiger True feline cat False rodent rabbit True canine dog False feline puma True feline bobcat False </code></pre> <p>Is it possible to join all the terms in...
<p>Here's one way.</p> <pre><code>In [797]: df.groupby('type', as_index=False).agg({'name': ' '.join, 'exp': 'max'}) Out[797]: type name exp 0 canine dog False 1 feline tiger cat puma bobcat True 2 rodent rabbit True </code></pre>
python|python-3.x|pandas|data-structures
2
1,061
45,288,297
Meaning and dimensions of tf.contrib.learn.DNNClassifier's extracted weights and biases
<p>I relatively new to tensorflow, but even with a lot of research I was unable to find a documentation of certain variable meanings.</p> <p>For my current project, I want to train a DNN with the help of tensorflow, and afterwards I want to extract the weight and bias matrices from it to use it in another application ...
<p>The number of input nodes in your network is 11 and not 4 8(embedding_column)+column_heading(1),column_velocity(1),column_acceleration(1) = 11</p> <p>And based on the variable names the output is a binary logistic node, so the number of output nodes is only one and not 2.</p> <p>Below are the weights/biases you ar...
tensorflow
1
1,062
62,710,706
Drop duplicate rows conditionally - Pecking order
<p>I have a df as below</p> <pre><code>A B_x B_y C 1 USD GBP, USD, EUR V1 1 USD V2 2 GBP GBP, USD, EUR V1 3 JPY GBP, USD, EUR V1 3 JPY ...
<p>You can use list comprehension to create the mask by <code>zip</code>:</p> <pre><code>mask = [x in y or not y for x, y in zip(df[&quot;B_x&quot;], df[&quot;B_y&quot;])] print (df.loc[mask].drop_duplicates(&quot;A&quot;, keep=&quot;first&quot;)) A B_x B_y C 0 1 USD GBP, USD, EUR V1 2 2 GBP GB...
pandas
2
1,063
62,787,638
Handling multiple arrays
<p>I have 6 arrays named , x1,......x6 that i read from 'npz' file. I need to perform some mathematical job on each array and stored that into 10 new arrays. I am doing it step by step in a very simple way. To read the file and store variables,</p> <pre><code>files = np.load(&quot;particle.npz&quot;) x1 = files['x1'] ...
<pre><code>files = np.load(&quot;particle.npz&quot;) x_s = [files[key] for key in files.keys()] </code></pre> <p>Creating a list of arrays rather than individually named ones is the preferred method in Python.</p> <pre><code>pox_s = [x[:,0] for x in x_s] </code></pre> <p>Looks like the arrays are all the same size. So...
python|numpy
0
1,064
62,641,466
Show a Camera Activity which runs tflite on image frames in a flutter app
<p>I have an android app having a <strong>CameraActivity</strong> which runs a <strong>tflite classifier</strong> periodically on image frames from the preview stream. The implementation of the Camera and tflite works great in the Android part and gives a good FPS.</p> <p>I want to show this <strong>CameraActivity</str...
<pre><code>//Flutter side Future&lt;Null&gt; showNativeView() async { if (Platform.isAndroid) {//check if platform is android var methodChannel = MethodChannel(&quot;methodchannelname&quot;);//create a method channel name await methodChannel.invokeMethod('showNativeCameraView');//create method name } }...
android|flutter|android-camera|tensorflow-lite|flutter-platform-channel
0
1,065
54,423,677
Hvplot/bokeh summed Bar chart from Pandas Dataframe
<p>I'm trying to print a "simple" Bar chart, using HVPlot and bokeh in jupyter notebook. Here is some simplified data:</p> <p>My Data originally looks like this: <a href="https://i.stack.imgur.com/NRXjg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NRXjg.png" alt=""></a></p> <p>My goal is to ge...
<p>The <code>aggregator</code> is used by the datashade/rasterize operation to aggregate the data and indeed has no effect on bar plots. If you want to aggregate the data I recommend doing so using pandas methods. However in your case I don't think that's the issue, the main problem in implementing the plot you request...
python|pandas|bokeh|holoviews
1
1,066
54,477,327
How to avoid double quotes at the end of lines with .to_csv()
<p>I have .txt file as next:</p> <pre><code>Red Blue Green, 1354,8676,38 ------------------------------ Yellow Or,ange Black TU CD CL 0.26 0.265 0.25 ------------------------------- </code></pre> <p>I need to read it. For that purpose, I use <code>pd.read_csv()</code> and I avoid the last two lines with <code...
<p>the problem you're facing is that csv is a representation of tabular data.</p> <blockquote> <p>In computing, a comma-separated values file is a delimited text file that uses a comma to separate values. A CSV file stores tabular data in plain text. Each line of the file is a data record. Each record consists...
python-3.x|pandas
1
1,067
54,338,108
Loading large dataframe to Vertica
<p>I have a rather large dataframe (500k+ rows) that I'm trying to load to Vertica. I have the following code working, but it is extremely slow. </p> <pre><code>#convert df to list format lists = output_final.values.tolist() #make insert string insert_qry = " INSERT INTO SCHEMA.TABLE(DATE,ID, SCORE) VALUES (%s,%s,%...
<p>After a lot of trial and error... I found that the following worked for me. </p> <pre><code> # insert statements copy_str = "COPY SCHEMA.TABLE(DATE,ID, SCORE)FROM STDIN DELIMITER ','" # turn the df into a csv-like object stream = io.StringIO() contact_output_final.to_csv(stream, sep=",",index=F...
python|pandas|vertica
4
1,068
54,315,043
Generate (n, 1, 2) arrays with np.tile
<p>I want to create n times (1,2) arrays and each array should have the same elements. First I generate n times 1 D array and then I use a loop to iterate over these elements and repeat each element to fill (n, 1,2) array. my code is the following:</p> <pre><code>import numpy as np def u_vec(): return np.array([n...
<p>I see the problem. The problem is that your <code>return u_vec</code> statement is enclosed in the <code>for</code> loop. So only the first subarray is updated with the random values and the rest of <code>u_vec</code>remains 0 because you return <em>immediately after the first iteration</em> of the for loop. You sho...
python|numpy
1
1,069
73,646,375
Use PyTorch DistributedDataParallel with Hugging Face on Amazon SageMaker
<p>Even for single-instance training, PyTorch DistributedDataParallel (DDP) is generally recommended over PyTorch DataParallel (DP) because DP's strategy is less performant and it uses more memory on the default device. (Per <a href="https://discuss.pytorch.org/t/cuda-out-of-memory-error-when-using-multi-gpu/72333" rel...
<p>Great question, thanks for asking! PyTorch DDP runs data parallel workers in multiple processes, that must be launched and managed by developers. DDP should be seen as a managed allreduce, more than a managed data-parallelism library, since it requires you to launch and manage the workers and even assigning resource...
pytorch|amazon-sagemaker|huggingface-transformers
0
1,070
73,710,779
Generate Boolean Matrix of overlapping intervals
<p>I have a dataframe where two columns represent the start and end points of intervals on a real number line. I want to generate a third column as a list of the indices of rows which said row has any overlap with. I'm having difficulty creating a inequality boolean matrix for this natively in pandas. I assume logic li...
<p>The condition for the two intervals <code>(s1,e1)</code> and <code>(s2,e2)</code> to intersect is <code>max(s1,s2) &lt;= min(e1,e2)</code>. So you can do a cross merge (this is the broadcast), calculate the condition, the pivot:</p> <pre><code>d = (intervals_df.reset_index() .merge(intervals_df.reset_index(),...
python|pandas
2
1,071
73,761,272
Python color detection from a point with opencv
<p>I'm trying to do a sorting machine for color detection with a camera and a raspberry pi. I have succeeded to some extent but not really. I am currently reading the color from the center pixel in BGR format and examining it that way. My question would be how can i read this out of a zone not just a point and make the...
<p>Why not try something like this:</p> <p>The image you captured is now a 2D array, slice it from the center, and read a bunch of points representing a small rectangle in the center. Then, you can average them or get the median, it is up to you.</p> <pre><code># capture a video frame here height, width, _ = frame.sha...
python|numpy|opencv|raspberry-pi3
0
1,072
52,210,375
How can you get the most recent business day in Python?
<p>How can you get the most recent business day in python? </p> <p>E.g., if today is a business day, I'd like to get today as a datetime object, but if today is a Sunday, I'd like to get Friday as a datetime object, presuming Friday is the most recent business day.</p> <p>Thanks,</p> <p>Jack</p>
<p>You can use:</p> <pre><code>import pandas as pd pd.datetime.today() - pd.tseries.offsets.BDay(0) </code></pre> <p><strong>Update</strong></p> <pre><code>today = pd.datetime(2018,9,2) np.where((today - pd.tseries.offsets.BDay(0)) &gt; today, (today - pd.tseries.offsets.BDay(1)), (today - pd.tse...
python|pandas|datetime|python-datetime
8
1,073
52,241,853
numPy gives nan while reading a negative number from a file
<p>I tried to read the contents of a 3x3 matrix stored in a text file having the following values.</p> <pre><code>−30 10 20 10 40 −50 20 −50 −10 </code></pre> <p>I used <code>numpy.genfromtxt</code> as follows but when it gave <code>nan</code> in place of negative data values.</p> <pre><code>data = np.genfr...
<p>You've got U+2212 MINUS SIGN characters in your file, not the U+002D HYPHEN-MINUS people usually think of as the minus sign character. <code>genfromtxt</code> doesn't handle that character. Replace the minus sign characters with hyphen-minuses before trying to parse the data.</p>
python|numpy|genfromtxt
4
1,074
60,759,415
How can I plot the following pandas data set with three columns using matplotlib?
<p>I am able to plot the data set below when it only has the last two columns (the GDP per year and the population value) but I want to learn how to plot it to also include the year.</p> <p><code>suicides_gdp = suicides_russia.groupby(["year", " gdp_for_year ($) "])["suicides_no"].sum()</code><br /> <code>suicides_gdp...
<p>I would plot <code>bar</code>, instead of <code>barh</code>. Also, since the two columns have different scales, it's best to plot them in twin axes:</p> <pre><code>suicides_gdp = suicides_gdp.reset_index() fig, ax = plt.subplots(figsize=(12,6)) ax2 = ax.twinx() ax2.bar(suicides_gdp['year'], suicides_gdp['suicides_...
pandas|dataframe|matplotlib|plot|multiple-columns
2
1,075
60,649,722
keras.get_ssion().graph is not working in tensorflow2.x
<p>I could graphs of keras model by code below in tensorflow1.x</p> <pre><code>from tensorflow.python.keras import backend as K model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation='relu'), keras.layers.Dense(10) ]) ... graph=K.get_session().graph grap...
<p>Tensorflow migration guide would be the place where you can start -</p> <p><a href="https://www.tensorflow.org/guide/migrate" rel="nofollow noreferrer">Migrate your TensorFlow 1 code to TensorFlow 2</a></p>
tensorflow|keras
0
1,076
60,553,804
reading csv files with pandas fills dataframe with NaNs
<p>I have a csv output file from a datalogger that I want to bring into Python.<br> <a href="https://i.stack.imgur.com/Y8u9D.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y8u9D.jpg" alt="temp_table"></a></p> <p>Here is some of the data in csv:</p> <pre><code>"Name:,Data Instr INSTR 3/5/2020 11:51...
<pre><code>Pet_Data= pd.read_csv('D:/data.csv',skiprows=14) Pet_Data=Pet_Data.iloc[:,[2,4,6,8]] </code></pre>
python|pandas
0
1,077
72,682,146
Is this group by size behavior correct?
<p>I have this sample dataset:</p> <pre><code>mydf = pd.DataFrame({'city':['Porto','Loa','Porto','Porto','Loa'],\ 'town':['A','C','A','B','C']}) mydf['city'] = pd.Categorical(mydf['city']) mydf['town'] = pd.Categorical(mydf['town']) mydf city town 0 Porto A 1 Loa C 2 Porto A 3 ...
<p><strong>Yes, the <code>groupby</code> + <code>size</code> behavior is expected.</strong></p> <p>By default, if any of the grouping columns are categorical then it will show all the values for categorical columns regardless whether they appear in a particular group or not.</p> <p>To turn this default behaviors off, y...
python|pandas
4
1,078
72,819,710
Fix TypeError in Keras class - how to cast Keras.Sequential to Layer class so it can be part of a Keras.Model instance
<p>I have the following code, and I am getting a TypeError. My guess is that I am making a <code>Keras.Model</code> part of a, well, <code>Keras.Model</code> when I should have been using <code>Layer</code> instead. Long story short, how can I cast the <code>Keras.Sequential</code> object that <code>mlp</code> returns ...
<p>After much discussion with AloneTogether I figured out a way to rewrite the <code>mlp</code> function so that it plays nice with the subclassed model. Apparently, the <code>Sequential</code> module does not cast well.</p> <p>Here is the rewritten function:</p> <pre><code>def mlp2(size_in, size_out): hidden = 128...
python|tensorflow|keras
0
1,079
72,498,115
How to combine values of multiple rows in panda
<p>I have dataframe file that split text into multiple rows, like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>A</th> <th>B</th> </tr> </thead> <tbody> <tr> <td>aaa</td> <td>bbbb</td> </tr> <tr> <td>ccccc</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>dddd</td> <t...
<p>You can create a mask and group from the rows with all NaNs, then <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.aggregate.html" rel="nofollow noreferrer"><code>GroupBy.agg</code></a> to <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow noref...
python|pandas
1
1,080
72,489,534
multiple annotations on bar seaborn chart
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">STRUD</th> <th style="text-align: center;">Struct_Count</th> <th style="text-align: right;">Perc</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">Row</td> <td style="text-align: center;">1151</td> <td style=...
<p>You can play around with the <code>ax.bar_label</code> in order to set custom labels. No need for annotations and loops.</p> <p>I'm assuming the below example is what you mean by &quot;plot the corresponding percentage values on the bars&quot;, but it can be adjusted flexibly.</p> <p>Note that this doesn't show valu...
python|pandas|matplotlib|seaborn
2
1,081
72,490,742
Key error in merge function between dataframes
<p>I have a question. I have two data set as under,</p> <pre><code>df1 Sl No Address 1 1111 2 2222 3 2345 4 7890 5 0987 6 3456 7 1233 </code></pre> <pre><code>df2 email Add. AA A123 AA 1111 AA 99999 BB a9999 BB 345689 BB 345699 CC 1233 </code></pre> <p...
<p>Do not select the email column when you <code>merge</code> , this will make the merged df become series</p> <pre><code>df1 = df1.merge(df2[['Address','email']], how = &quot;left&quot;, on = &quot;Address&quot;) </code></pre>
python|pandas|dataframe|merge
2
1,082
72,552,722
Why is the output shape (3,2,32,64) when I convolve my (3,3,64,64) input with another (3,3,64,64) input using tf.nn.conv2d?
<p>I'm using TensorFlow's tf.nn.conv2d to convolve a (3,3,64,64) input with a (3,3,64,64) filter using stride 2 and SAME padding. I was expecting the output shape to be (2,2,64,64), but I'm getting (3,2,32,64) instead. I think using stride 2 seems to be the cause but I'm not exactly sure why it's outputting the shape (...
<p>I just realized the expected input format for tf.nn.conv2d is (size, h, w, in_channel) when I was using (h, w, in_channel, size). To get my desired output shape (2,2,64,64), I can use tf.transpose to change the format of my input, convolve, and then transpose my output back to the original format:</p> <pre><code>inp...
python|tensorflow
0
1,083
61,658,842
How to merge only on rows where there is no value in the rows of a certain column in pandas dataframe
<p>I have the following dataframe df1,</p> <pre><code> CompanyName Country Ticker .................... 0 Apple Inc. US AAPL 1 Microsoft US 2 Sony US 3 DBS SG D05 4 Razer HK 0700 5 General Electric US GE </code></pre> <p>Then I ha...
<p>You can do <code>fillna</code>:</p> <pre><code># Ticker by company s = df2.set_index('CompanyName')['Ticker'] df['Ticker'] = df['Ticker'].fillna(df['CompanyName'].map(s) ) </code></pre>
python|pandas|dataframe|join|merge
0
1,084
61,808,025
Match coloring of slices for series of pandas pie charts
<p>I have a pandas dataframe that looks like this : </p> <pre><code>df = pd.DataFrame( {'Judge': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2, 6: 3, 7: 3, 8: 3}, 'Category': {0: 'A', 1: 'B', 2: 'C', 3: 'A', 4: 'B', 5: 'C', 6: 'A', 7: 'B', 8: 'C'}, 'Rating': {0: 'Excellent', 1: 'Very Good', 2: 'Good', 3: 'Very Good', 4: 'Very G...
<p>I think you can unstack and plot:</p> <pre><code>axes = (df.groupby('Judge').Rating.value_counts() .unstack('Judge') .plot.pie(subplots=True, figsize=(6,6), layout=(2,2)) ) # do some thing with the axes for ax in axes.ravel(): pass </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/jXE7...
pandas|matplotlib|pandas-groupby
1
1,085
61,870,811
EfficientDet-Custom Dataset -StringToNumberOp could not correctly convert string
<p>As a beginner, I am trying to train my custom datasets with TensorFlow, but getting the following error when start training:</p> <p><a href="https://i.stack.imgur.com/dmPD8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dmPD8.png" alt="enter image description here"></a></p> <p>here is my comman...
<p>Answered here on github. Its an issue with tfrecord creations. In your tf record creation script, change source_id</p> <pre><code>'image/source_id': dataset_util.bytes_feature(input_image_filename.encode('utf8')), </code></pre> <p>to</p> <pre><code>'image/source_id': dataset_util.bytes_feature('0'.encode('utf8'))...
python|tensorflow|error-handling|efficientnet
1
1,086
61,894,015
Pandas extractall merge
<p>Not sure if I should fix my regex pattern, or process more with pandas.</p> <p>Here's a mock setup:</p> <pre><code>import re import pandas as pd regex = r"(?P&lt;adv&gt;This)|(?P&lt;noun&gt;test)" texts = ["This is a test", "Random stuff with no match"] series = pd.Series(texts) </code></pre> <p>I want to find a...
<p>You can try;</p> <pre><code>series.str.extractall(regex).groupby(level=0).first() adv noun 0 This test </code></pre>
python|regex|pandas
2
1,087
57,985,196
How do you get and set a 1-D array with column indexes of a 2-D matrix?
<p>Suppose you have a matrix:</p> <pre><code>a = np.arange(9).reshape(3,3) array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) </code></pre> <p>and I want get or set over the values 1, 5, and 6, how would I do that. </p> <p>For example I thought doing</p> <pre class="lang-py prettyprint-override"><code># gettin...
<p>Only a small tweak makes this work:</p> <pre><code>import numpy as np a = np.arange(9).reshape(3,3) # getting b = a[range(a.shape[0]), np.array([1,2,0])] # setting a[range(a.shape[0]), np.array([1,2,0])] = np.array([9, 10, 11]) </code></pre> <p>The reason why your code didn't work as expected is because you were...
python|numpy
4
1,088
54,800,887
How to create a mm-yyyy column in pandas?
<p>Is there any way to extract mm-yyyy (or even quarter-yyyy) information from a datetime variable?</p> <p>My datetime column is df['event'] which is a dd-mm-yyyy. I know I can extract mm and year from my variable, but is there a way I can extract the two combined?</p> <p>I can resample my data to monthly frequency, ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.to_period.html" rel="nofollow noreferrer"><code>Series.dt.to_period</code></a> for month or quarter periods:</p> <pre><code>df = pd.DataFrame({'event':['01-01-2015','02-05-2015','01-08-2016','01-11-2015']}) df['event'] = pd...
python|pandas|datetime
4
1,089
54,873,635
How do I plot a column vector as a contour with non uniform grid points that are also column vectors?
<p>I have data (<a href="https://drive.google.com/open?id=1Owokm3Xz31INJoA-BW2qsaPFFttxdaFk" rel="nofollow noreferrer">link</a>) in the form given below:</p> <p><strong>Input data format</strong></p> <pre><code>Header: 'x' 'y' 'a' 'b' x1 , y1 , ... (data) x2 , y2 , ... (data) x3 , y3 , ... (data) : : ...
<p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html" rel="nofollow noreferrer"><code>numpy.meshgrid</code></a> should have no problem with non uniform 1-d domains. However, your 2-D data are irregularly distributed in the data file (see plots at the end of post). This has other issues. ...
python|numpy|matplotlib|contour
1
1,090
73,362,254
Pandas - drop n rows by column value
<p>I need to remove last n rows where Status equals 1</p> <pre><code>v = df[df['Status'] == 1].count() f = df[df['Status'] == 0].count() diff = v - f diff df2 = df[~df['Status'] == 1].tail(diff).all() #ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() df2 </c...
<p>Check whether <code>Status</code> is <code>eq</code>ual to <code>1</code> and get only those places where it is (<code>.loc[lambda s: s]</code> is doing that using boolean indexing). The <code>index</code> of <code>n</code> such rows from <code>tail</code> will be <code>drop</code>ped:</p> <pre class="lang-py pretty...
pandas
2
1,091
67,570,175
Missing trainable parameter when loading model from tensorflow hub
<p>I'm migrating our code from tensorflow 1 to tensorflow 2. One of the layers is embedding layer loaded as follows:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow_hub as hub model_url = &quot;https://tfhub.dev/google/universal-sentence-encoder-multilingual/1&quot; self.use_embed = hub.Module(mod...
<p>The <a href="https://www.tensorflow.org/hub/model_compatibility#compatibility_of_tf2_savedmodel" rel="nofollow noreferrer">Model Compatibility Guide</a> mentions that the parameter has a different name for <code>hub.load()</code> and <code>hub.KerasLayer()</code>:</p> <blockquote> <p>Use either hub.load:<br /> m = h...
tensorflow-hub
2
1,092
60,284,375
How to create a new column in a dataframe, with either 1 or 0 based on percentage of results in previous columns?
<p>I have a data frame with 144 rows and 48 columns. It contains results from various prediction models as either 1 or 0. I want to go through a row, find the percentage of 1's in that row and add a new column with either 1 if the percentage is greater than 80, else 0.</p> <p>I know how to do this in excel with <stron...
<p>You can find the percentage of 1's in each row with:</p> <pre><code>df['percentage'] = df.mean(axis=1) </code></pre> <p>Then to create your new binary column you can use <code>np.where</code>:</p> <pre><code>df['new'] = np.where(df['percentage'] &gt; 0.8, 1, 0) </code></pre> <p>This works the same way as the exc...
python|pandas|machine-learning
1
1,093
60,143,296
How to open excel template and save it to another path with pandas
<p>I have a simple excel template <a href="https://i.stack.imgur.com/KOPCd.png" rel="nofollow noreferrer">like this</a> with some deferent sheet</p> <p>and i already has a few dataframe for each sheet with the the same header name However, i want to write it with this template and save it to another directory. How ca...
<p>Pandas deals with only tables not formatting</p> <p>Use <a href="https://openpyxl.readthedocs.io/en/stable/" rel="nofollow noreferrer">openpyxl library</a> instead</p>
python-3.x|pandas
1
1,094
65,309,311
Merging two tables using left join, drop_duplicates doesn't work?
<p>I'm creating a merge from two tables. First table look like this:</p> <pre><code> a b c 0 32 171 28 1 32 172 28 2 1014 173 28 3 1014 179 28 4 1014 154 26 5 1049 156 26 </code></pre> <p>2nd table looks like thi...
<p>If the indeces are exactly the same you can simply do this.</p> <pre><code>df3 = pd.merge(df[['a','b','c']], df2['d'], right_index=True, left_index=True) </code></pre>
python|pandas|dataframe|merge|left-join
1
1,095
65,118,696
Numpy Array - Advanced slicing using sum of a one hot encoded column
<p>I'm trying to slice an array based on a one-hot encoded column, so for an array like this:</p> <pre><code>import numpy as np arr = np.array([[0.1,1,0,0],[0.2,1,0,0],[0.3,1,0,0]]) </code></pre> <p>I would like to select from the first column, any rows before the cumulative sum of column 2 equals 3:</p> <pre><code>out...
<p><code>np.cumsum</code> works to create the cumulative sum column without looping... oops</p>
arrays|numpy|sum|slice
0
1,096
65,434,747
Python pandas timedelta64 fillna
<p>I have a dataset with hundreds of columns. Some of the columns have timedelta64 type. When i use</p> <pre><code>fillna(0) </code></pre> <p>I got an error <code>Passing integers to fillna for timedelta64[ns] dtype is no longer supported. To obtain the old behavior, pass pd.Timedelta(seconds=n)</code></p> <p>How can ...
<p>You may want to update the columns separately accordingly to their dtypes:</p> <pre class="lang-py prettyprint-override"><code># Update inplace numeric columns df.update(df.select_dtypes('number').fillna(0)) # Update inplace timedelta columns df.update(df.select_dtypes('timedelta64[ns]').fillna(pd.Timedelta(seconds...
python|pandas|fillna
1
1,097
50,220,082
Does the seed function in numpy and random work need to be set in every module?
<p>I am calling</p> <pre><code>np.random.seed(seed) random.seed(seed) </code></pre> <p>in the <code>__main__</code> module <code>foo.py</code>. That module calls out to another module <code>bar.py</code> that also uses results from <code>np.random</code> and <code>random</code>. Does the latter also need to set the s...
<p>No. Using <code>np.random.seed(...)</code> sets a global random state.</p> <p>Usually this is not desirable. You may prefer to use a <code>np.random.RandomState()</code> instance in your code, so that you don't also seed the PRNGs for all other library code within your runtime.</p>
python|numpy|random|random-seed
2
1,098
49,821,843
pandas.DataFrame: Filter rows of df A based on data in df B?
<pre><code>import pandas as pd C = {'name': ['Alice', 'Alice', 'Bob', 'Charlie'], 'phone': ['007', '1764', '1317210', '314159']} CONTACTS = pd.DataFrame(data = C) answer = {'guest_name': ['Alice', 'Bob', 'Charlie'], 'attending': [True, False, True]} guest_list = pd.DataFrame(data = answer) </code></pre> <hr> <p><st...
<p>Here's one way:</p> <pre><code>attending_guests_contact = CONTACTS.merge(guest_list[guest_list.attending], \ left_on="name", right_on="guest_name") print attending_guests_contact # name phone attending # 0 Alice 007 True # 1 Alice 1764 Tr...
python|python-3.x|pandas|dataframe
2
1,099
63,835,941
How to enable the python to apply custom function faster
<p>I have developed a customer function to classify product type in my dataframe.</p> <pre><code>def RST_FINAL_SECOND_FUNCTION(DF_FRAME_NAME): if (DF_FRAME_NAME['Column1'] == 'Yes'): return 'YES' elif (DF_FRAME_NAME['Column1'] == 'No'): return DF_FRAME_NAME['column2'] df['column3'] = df.apply(RS...
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer">numpy.where</a></p> <pre><code>import numpy as np df['column3'] = np.where(df['Column1'].eq('Yes'), 'Yes', df['Column2']) print(df) </code></pre> <p><strong>Output:</strong></p> <pre><code> Column1 Co...
pandas|python-3.x
1