Unnamed: 0 int64 0 378k | id int64 49.9k 73.8M | title stringlengths 15 150 | question stringlengths 37 64.2k | answer stringlengths 37 44.1k | tags stringlengths 5 106 | score int64 -10 5.87k |
|---|---|---|---|---|---|---|
14,300 | 62,924,126 | How to fill the null values with the average of all the preceeding values before null and first succeeding value after null in python? | <p><a href="https://i.stack.imgur.com/lQrDZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lQrDZ.png" alt="enter image description here" /></a>I have a dataframe with 5000 records. I want the null values to be filled with:</p>
<p>Average(All the Preceding values before null, First succeeding value a... | <p>The following seems to work. You define an <code>apply</code> function for the rows which modifies the <code>df</code> in place. Each time a row (with null values) is reached you can take an <code>expanding</code> mean of <code>df</code>(<a href="https://stackoverflow.com/a/43414120/13386979">see here</a>), using ... | python-3.x|pandas|python-2.7|dataframe|python-requests | 1 |
14,301 | 67,755,481 | Pandas series remains the same after appending to it through a function | <p><em><strong>EDIT:<br />
Although the answer to my question was that the behaviour of pandas does not allow for this kind of operation, I have still marked Henry Ecker's answer as the correct answer as that is the best alternative.</strong></em></p>
<p>I am currently having trouble modifying pandas series (and datafr... | <p><code>ser1 = ser1.append(ser2)</code> only changes the <em>local</em> variable in the function <code>append_series</code>.</p>
<p><code>return</code> from the function instead and assign back to the <code>series1</code> variable in <code>main</code>:</p>
<pre><code>import pandas as pd
def main():
series1 = pd... | python|pandas|append|series | 0 |
14,302 | 67,859,613 | How can I extract the image pixels from 2D numpy array? | <p>I have a matrix with a shape of (100000, 20) that consists of 20 images, each (500 *200) in size. I just need to know how can I extract those pixels so that I can have the <code>image shape of (500, 200)</code>?
I tried <code>matrix[:,:,19]</code> but it seems that I just grabbed the values of the last feature, exce... | <p>here my attempt at it using reshape:</p>
<pre><code>
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 6 16:43:48 2021
@author: Pietro
https://stackoverflow.com/questions/67859613/how-can-i-extract-the-image-pixels-from-2d-numpy-array?noredirect=1#comment119943691_67859613
&qu... | python|numpy|multidimensional-array | 0 |
14,303 | 31,813,746 | Maintaining a list and interpolation of a map | <p>I am trying to create a voltage colour map and if I want to do so, I have to maintain 3 different lists that have 3 different values used. These 3 values are called: peak, X3 and Y3 (as seen in the code below). Previously I had a problem updating the list as it inserted new values but that was solved by including a ... | <p>So by printing inside the exception (as seen in the question above), I found that values 103 to 111 are displayed as broken electrodes (which they shouldn't because they have values). The only electrode that has a value of zero (as seen in the question above) is electrode 102 (which is the electrode that was broken)... | list|python-2.7|python-3.x|numpy|interpolation | 0 |
14,304 | 41,668,502 | Using tensorflow models in web applications | <p>So I've recently became very interested in machine learning, and have been using <code>tensorflow</code> (python) in some of my projects at work.</p>
<p>However, I've now found a use for digit classification in one of my web projects which is all written in PHP for server-side code. Ideally, I'd like to be able to ... | <p>Tensorflow provides <a href="https://github.com/tensorflow/serving" rel="noreferrer">serving project</a> for communication, so you need to implement gRPC client for PHP, then use it to talk to Tensorflow serving environment.</p>
<p>That's how I work with Ruby and Tensorflow, it should be working for you as well!</p... | php|python|machine-learning|tensorflow|neural-network | 5 |
14,305 | 41,325,739 | Memory after removing last N elements of numpy.ndarray | <p>I've a huge <code>numpy.ndarray</code> of images <code>array1</code> that takes 60GB when loaded on the RAM. I need to remove the last <code>n</code> elements of that array. An easy solution would be:</p>
<pre><code>array1 = array1[:n-1]
</code></pre>
<p>But when I do it, I don't gain any space in the RAM, why is ... | <p><code>array1[:n-1]</code> is a view, a new array which shares the data buffer with the original <code>array1</code>. Even though you reassign <code>array1</code>, its data buffer is not resized.</p>
<p><code>array1.resize(n-1)</code> - the docs indicate that the data buffer is resized/reallocated, provided it is c... | python|arrays|numpy|memory | 1 |
14,306 | 41,433,765 | pandas dataframe sort by date | <p>I made a dataframe by importing a csv file. And converted the date column to datetime and made it the index. However, when sorting the index it doesn't produce the result I wanted</p>
<pre><code>print(df.head())
df['Date'] = pd.to_datetime(df['Date'])
df.index = df['Date']
del df['Date']
df.sort_index()
print(df.he... | <p>Just expanding MaxU's correct answer: you have used correct method, but, just as with many other pandas methods, you will have to "recreate" dataframe in order for desired changes to take effect. As the MaxU already suggested, this is achieved by typing the variable again (to "store" the output o... | python|sorting|datetime|pandas | 14 |
14,307 | 27,890,735 | Difference between list(numpy_array) and numpy_array.tolist() | <p>What is the difference between applying <code>list()</code> on a <code>numpy</code> array vs. calling <code>tolist()</code>? </p>
<p>I was checking the types of both outputs and they both show that what I'm getting as a result is a <code>list</code>, however, the outputs don't look exactly the same. Is it because t... | <p>Your example <strong>already shows the difference</strong>; consider the following 2D array:</p>
<pre><code>>>> import numpy as np
>>> a = np.arange(4).reshape(2, 2)
>>> a
array([[0, 1],
[2, 3]])
>>> a.tolist()
[[0, 1], [2, 3]] # nested vanilla lists
>>> list(a)
[... | python|arrays|list|numpy | 22 |
14,308 | 61,181,932 | Capitalize random rows in Panda Dataframe | <p>I'm making a reverse denoisng autoencoder and I have a dataset but it's all lowercased, but I want 80% of the rows the source entry to be capitalized and only 60% of the target entries to be capitalized. I wrote this</p>
<pre><code>import pandas as pd
import torch
df = pd.read_csv('Data/fb_moe.csv')
for i in rang... | <p>Try adding some boolean mask and some apply functions, pandas does not behave quickly in for loops</p>
<pre><code>n = len(df)
source = np.random.binomial(1, p=.8, size=n) == 1
target = source.copy()
total_source_true = np.sum(source)
target[source] = np.random.binomial(1, p=.6, size=total_source_true) == 1
df.lo... | python|pandas|dataframe | 0 |
14,309 | 61,435,783 | Choosing layer types for a neural network predicting the outcome of individual video game matches | <p>I am working with this dataset: <a href="https://www.kaggle.com/gabisato/league-of-legends-ranked-games/data" rel="nofollow noreferrer">https://www.kaggle.com/gabisato/league-of-legends-ranked-games/data</a></p>
<p>I am using the 'win' column as my target, having converted the data into 2 categorical one-hot vector... | <p>The input to the neural network <code>trainX</code> is of the shape <code>[batch_size, 88]</code>. Convolution Neural Networks expect input to be three-dimensional. From the documentation <a href="https://keras.io/layers/convolutional/" rel="nofollow noreferrer">here</a>, the dimensions it expects are <code>[batch, ... | python|tensorflow|machine-learning|keras|neural-network | 1 |
14,310 | 61,262,730 | Join pandas data frames based on columns and column of lists | <p>I'm trying to join two data frames based on multiple columns. However, one of the conditions is not straight forward, because one column in one data frame exists in column of lists in the other data frame. As following </p>
<p>df_a :</p>
<p><a href="https://i.stack.imgur.com/vJLMp.png" rel="nofollow noreferrer"><i... | <p>Update per comment by @JonClements if not always the first element try:</p>
<pre><code>(df_b.assign(value=df_b['trail'].str.split(','))
.explode('value')
.merge(df_a, on=['node', 'channel', 'value']))
</code></pre>
<p>Try, if value is always the first element in trail:</p>
<pre><code>import pandas as pd... | python|pandas|join | 1 |
14,311 | 68,582,886 | How do I get rid of this error: max() received an invalid combination of arguments - got (str, int), but expected one of: * (Tensor input) | <p>I have used FCN ResNet50 model for semantic segmentation of document images. I've been trying to resolve this issue but so far have not been able to find success. This is the link for the model on google colab: <a href="https://colab.research.google.com/drive/1slJilG1ZBOsk6AqM6AOUaaCxHFSXVMCM?usp=sharing" rel="nofol... | <p>attaching pretrained segmentation models in torchvision</p>
<pre><code>model(inputs.float())
</code></pre>
<p>returns a <strong>dictionary</strong>, not an array. Consequently what you are passing to max is set of keys from this dictionary (since dictionary, when iterated over, is treated as a collection of keys, wh... | python|machine-learning|computer-vision|pytorch|resnet | 0 |
14,312 | 68,830,229 | How to create a new column that groups another column of values by each n numbers? Pandas | <p>I'm using Pandas and I'm trying to figure out if there's a module or a way to group the Price Column in the table that I've linked below to by every $n dollars.</p>
<p>For example, for products priced between $5-$10, I want a new column that shows that this is $5-$10, and for products between $10-$15 then in the new... | <p>You can use <code>pandas.cut</code> to define bins:</p>
<p>example on dummy data:</p>
<pre><code>import numpy as np
import pandas as pd
# dummy data:
df = pd.DataFrame({'price': ['$%.2f' % (i/100) for i in np.random.randint(0, 5000, size=10)]})
# processing:
# convert prices to float
prices = df['price'].str[1:].... | python|python-3.x|pandas|dataframe | 0 |
14,313 | 68,605,901 | Pandas DateTimeArray How to Get First Element? | <p>Given a simple pandas DateTimeArray: <a href="https://pandas.pydata.org/pandas-docs/version/0.24.2/reference/api/pandas.arrays.DatetimeArray.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/version/0.24.2/reference/api/pandas.arrays.DatetimeArray.html</a></p>
<p>Given a pandas DateTimeArray, dta... | <p>Using <code>pandas==1.31.0</code>, simply slice the array using positional indexing</p>
<pre class="lang-py prettyprint-override"><code>dta[0]
</code></pre>
<p>This gives</p>
<pre class="lang-py prettyprint-override"><code>print(dta[0])
2015-01-01 00:00:00
</code></pre>
<p><strong>EDIT</strong></p>
<p>The input arra... | arrays|python-3.x|pandas | 1 |
14,314 | 68,833,961 | Get value out of numpy array view boundaries | <p>If I have a view into part of numpy array:</p>
<pre><code>import numpy as np
array = np.arange(10)
view = array[4:8]
</code></pre>
<p>Can I access element to the left (in memory) of first view element, using only view identifier?
<a href="https://i.stack.imgur.com/HB0wJ.png" rel="nofollow noreferrer"><img src="htt... | <p><code>view</code> keeps a reference to <code>array</code> in the <a href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.base.html" rel="nofollow noreferrer">base</a> attribute. <code>view.base</code> is <code>array</code>.</p>
<p>Thus, you could access this identifier by calling <code>left_element =... | python|numpy | 1 |
14,315 | 68,698,149 | Why does 3.2 in numpy.arange(3, 3.9, .01) return False? | <p>I'm using <a href="https://numpy.org/doc/stable/reference/generated/numpy.arange.html?highlight=arange#numpy.arange" rel="nofollow noreferrer">NumPy's arange() method</a> and trying to figure why my value, which is seemingly in range, does not return True when applied.</p>
<pre><code>3.0 in np.arange(3, 3.9, .01)
</... | <p>The reason is that you are using np.arange() with a non-integer step, which is <a href="https://stackoverflow.com/questions/62217178/inconsistent-behavior-in-np-arange">known to be inconsistent</a>. Taken from <a href="https://numpy.org/doc/stable/reference/generated/numpy.arange.html" rel="nofollow noreferrer">np.a... | python|numpy | 0 |
14,316 | 65,756,553 | Check if ENTIRE pandas object column is a string | <p>How can I check if a column is a string, or another type (e.g. int or float), even though the dtype is object?</p>
<p>(Ideally I want this operation vectorised, and not <code>applymap</code> checking every row...)</p>
<pre class="lang-py prettyprint-override"><code>import io
# American post code
df1_str = "&quo... | <p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.api.types.infer_dtype.html" rel="nofollow noreferrer"><code>pandas.api.types.infer_dtype</code></a>:</p>
<pre><code>>>> pd.api.types.infer_dtype(df2["postal"])
'string'
>>> pd.api.types.infer_dtype(df1["postal&q... | python|pandas | 3 |
14,317 | 65,792,909 | ValueError: Input 0 of layer dense is incompatible with the layer: expected axis -1 to have value 8 but received input with shape [None, 1] | <p>I'm training a model for the OpenAI lunarLander-v2 environment. I've succesfully done this using a Sequential model, but when trying to use the functional model, I get some errors with tensorshapes being incompatible.
Here is the code for the Agent class, the issue I think has to do with the shape of the done_list a... | <p>From here, [https://stackoverflow.com/questions/64512293/input-dense-is-incompatible-with-the-layer-invalid-shape][1]</p>
<p>Input shape should be (1, )</p> | python|tensorflow|keras|deep-learning|openai | 0 |
14,318 | 2,821,072 | Is there a better way of making numpy.argmin() ignore NaN values | <p>I want to get the index of the min value of a numpy array that contains NaNs and I want them ignored</p>
<pre><code>>>> a = array([ nan, 2.5, 3., nan, 4., 5.])
>>> a
array([ NaN, 2.5, 3. , NaN, 4. , 5. ])
</code></pre>
<p>if I run argmin, it returns the index of the first NaN<... | <p>Sure! Use <code>nanargmin</code>:</p>
<pre><code>import numpy as np
a = np.array([ np.nan, 2.5, 3., np.nan, 4., 5.])
print(np.nanargmin(a))
# 1
</code></pre>
<p>There is also <code>nansum</code>, <code>nanmax</code>, <code>nanargmax</code>, and <code>nanmin</code>,</p>
<p>In <code>scipy.stats</code>, the... | arrays|numpy|python|nan | 54 |
14,319 | 63,333,466 | Is normalization necessary for regression problem in Neural network | <p>I am learning how to build a neural network using PyTorch.
This formula is the target of my code:
y =2<em>X^3 + 7</em>X^2 - 8*X + 120</p>
<p>It is a regression problem.</p>
<p>I used this because it is simple and the output can be calculated so that I can ensure my neural network is able to predict output with the g... | <blockquote>
<p>Is normalization necessary for regression problem in Neural Network?</p>
</blockquote>
<p>No.</p>
<p>But...</p>
<p>I can tell you that MSELoss works with non-normalised values. You can tell because:</p>
<pre class="lang-py prettyprint-override"><code>>>> import torch
>>> torch.nn.MSELo... | python|neural-network|pytorch | 6 |
14,320 | 63,531,554 | How to start a for loop for this given DataFrame in Pandas for multiple same name rows? | <p>I need some help, I am working on a .ipynb file to filter data and get certain things from that Dataframe.</p>
<p>This is DataFrame I'm working with.
<a href="https://i.stack.imgur.com/EJXGa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EJXGa.png" alt="enter image description here" /></a></p>
<p... | <p>Although different from the data presented in the question, we have answered the same financial data using equity data as an example.</p>
<pre><code>import pandas as pd
import pandas_datareader.data as web
import datetime
with open('./alpha_vantage_api_key.txt') as f:
api_key = f.read()
start = datetime.dateti... | python|pandas|dataframe|pandas-groupby | 0 |
14,321 | 63,461,262 | BERT sentence embeddings from transformers | <p>I'm trying to get sentence vectors from hidden states in a BERT model. Looking at the huggingface BertModel instructions <a href="https://huggingface.co/bert-base-multilingual-cased?text=This%20sentence%20etc" rel="noreferrer">here</a>, which say:</p>
<pre><code>from transformers import BertTokenizer, BertModel
tok... | <p>While the existing answer of <a href="https://stackoverflow.com/users/5652313/jind%C5%99ich">Jindrich</a> is generally correct, it does not address the question entirely. The OP asked which layer he should use to calculate the cosine similarity between sentence embeddings and the short answer to this question is <st... | bert-language-model|huggingface-transformers | 14 |
14,322 | 63,703,978 | Creating vector with Poisson increments | <p>If we start with a vector between 0 and 1 with M = 100 increments</p>
<pre><code>z = np.linspace(0,10,M)
</code></pre>
<p>this vector has equal increments from 0 to 1.</p>
<p>I want to create a new vector where the increments z_{n+1}-z_n are distributed according to the Poisson distribution with parameter lambda. I ... | <p>Thanks for updating, I understand the problem now. The answer is, no; you shouldn't expect the vector <code>z</code> to have its increments as a poisson distribution.</p>
<p>To demonstrate why, let's create a bunch of different poisson distributions and add them together.</p>
<pre><code>a = np.random.poisson(1000, 2... | python|numpy|poisson | 1 |
14,323 | 21,824,499 | Numpy only on finite entries | <p>Here's a brief example of a function. It maps a vector to a vector. However, entries that are NaN or inf should be ignored. Currently this looks rather clumsy to me. Do you have any suggestions?</p>
<pre><code>from scipy import stats
import numpy as np
def p(vv):
mask = np.isfinite(vv)
y = np.NaN * vv
... | <p>You can change the NaN values to zero with Numpy's isnan function and then remove the zeros as follows:</p>
<pre><code>import numpy as np
def p(vv):
# assuming vv is your array
# use Nympy's isnan function to replace the NaN values in the array with zero
replace_NaN = np.isnan(vv)
vv[replace_NaN... | python|numpy|nan | 1 |
14,324 | 21,445,264 | What is the fastest way to quadratic form numpy array multiplication? | <p>I have tried those two alternatives</p>
<pre><code>objective = lambda A, x : (np.dot(x.T ,np.dot(A, x)))[0,0]
objective = lambda A, x : (np.matrix(x).T * np.matrix(A) * np.matrix(x))[0,0]
</code></pre>
<p>With primary one I got 5 sec of running time with my algorithm
With secondary I got 14 sec </p>
<p>With MATL... | <p>I have both NumPy and Matlab installed and they both take around 45 ms for a 10000x10000 matrix.</p>
<p>Considering your timings, I suspect that <code>x</code> is not a single column vector.
If you want to do this computation for multiple column vectors all at once, look at my answer to this question:
<a href="http... | python|arrays|matlab|numpy|matrix-multiplication | 7 |
14,325 | 24,631,095 | Insert a pandas DataFrame plot into a matplotlib subplot | <p>I have created a plot with 4 subplots and each subplot will show a different type of analyses on some infrasound data. This the code I have used to create the subplots: </p>
<pre><code>gs = gridspec.GridSpec(2, 2, width_ratios=[1,1], height_ratios=[1,1])
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])
ax3 = plt.... | <p>When plotting using <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.plot.html" rel="nofollow"><code>pandas.Dataframe.plot</code></a> you can choose the <code>Axes</code> object you would like to plot to with the keyword argument <code>ax</code> as shown below:</p>
<pre><code>gs = gridsp... | python|matplotlib|pandas|subplot | 4 |
14,326 | 53,792,575 | fetch data from API n times and then convert it into a single pandas dataframe | <p>I have this small python script in which i'm fetching cryptocurrency exchange rate data every second.Now I want to stop after fetching data lets say 100 times and then convert all those data into a single dataframe. Also is scheduler the right way to do this?If no then what else should I be using?</p>
<pre><code>im... | <p>Maybe something like this:</p>
<pre><code>import requests
import json
import pandas as pd
import time
from matplotlib import pyplot as plt
from pandas import DataFrame
eur_collection = []
usd_collection = []
btc_collection = []
for i in range(100):
print("Request {}".format(i))
data = requests.get("https:... | python|pandas | 2 |
14,327 | 53,573,024 | Numpy: broadcast row values to channels | <p>I Have a dataset, where first 48 observations are time series, and other 12 are static variables:</p>
<pre><code>h1 h2 h3 h4 ... h48 v1 v2 v3 v4 v5 v6 .. vn
h1 h2 h3 h4 ... h48 v1 v2 v3 v4 v5 v6 .. vn
</code></pre>
<p>the shape of one item is <code>(367, 60)</code>.</p>
<p>I want to pass variables <code>v1 v2 v3 ... | <p><strong>Approach #1</strong></p>
<p>We could use broadcasted array-assignment for a vectorized solution -</p>
<pre><code>def array_assign(items):
L = 48 # slice at this column ID
N = items.shape[-1]
out = np.empty(shape= items.shape[:2] + (L,N-L+1), dtype=np.float32)
out[...,1:] = items[...,Non... | python|performance|numpy|vectorization | 1 |
14,328 | 53,603,068 | Writing a function that returns and prints the maximum value, out of all the values in a column | <p>I've got this table:</p>
<p><a href="https://i.stack.imgur.com/byT4z.jpg" rel="nofollow noreferrer">A DataFrame table which is made by using Jupyter Notebook.</a></p>
<p>This is actually only part of the table. </p>
<p>The complete table is actually a .csv file, and by using .head() function, only the first five ... | <p>Great first question, I assume you're doing the python for datascience course on coursera?</p>
<p>As already pointed out, <code>df['Gold'].max()</code> is correct however, if the datatype is wrong, it will not return the expected result. So first thing is to make sure it's a number. You can check this by running <c... | python|pandas|jupyter-notebook | 1 |
14,329 | 53,599,632 | AttributeError: 'DataFrame' object has no attribute 'tolist' | <p>When I run this code in Jupyter Notebook:</p>
<pre><code>columns = ['nkill', 'nkillus', 'nkillter','nwound', 'nwoundus', 'nwoundte', 'propvalue', 'nperps', 'nperpcap', 'iyear', 'imonth', 'iday']
for col in columns:
# needed for any missing values set to '-99'
df[col] = [np.nan if (x < 0) else x for x in... | <p>You have an <a href="https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem">XY Problem</a>. You've described what you are trying to achieve in your comments, but your approach is not appropriate for Pandas.</p>
<h3>Avoid <code>for</code> loops and <code>list</code></h3>
<p>With Pandas, you should l... | python|pandas|list|dataframe|jupyter | 1 |
14,330 | 17,579,932 | statsmodel ARMA function is incompatiable with Pandas? | <p>I have got a data set with records in the interval of 30 seconds, I am trying to do forecast prediction using ARMA function from time series module. Due to data privacy, I have used random data to reproduce the error</p>
<pre><code>import numpy as np
from pandas import *
import statsmodels.api as sm
data = np.rando... | <p>The problem is that this freq doesn't give back an offset from pandas for some reason, and we need an offset to be able to use the dates for anything. It looks like a pandas bug/not implemented to me.</p>
<pre><code>from pandas.tseries.frequencies import get_offset
get_offset('30s')
</code></pre>
<p>Perhaps we cou... | python|pandas|statsmodels | 1 |
14,331 | 71,875,379 | How to set categorical row variables as columns | <p>I have a dataframe which looks like this:</p>
<pre><code> date day normalized_returns
0 2020-01-02 Thursday
1 2020-01-03 Friday 0.4707137200215769
2 2020-01-06 Monday 0.23570968223068864
3 2020-01-07 Tuesday -0.001668590491460948
4 2020-01-08 Wednesday 0.2295862505909... | <p>Does this work:</p>
<pre><code>years = df.date.dt.year.rename('year')
weeks = df.date.dt.isocalendar().week.rename('week')
df.set_index([years, weeks, 'day']).normalized_returns.unstack()
day Friday Monday Thursday Tuesday Wednesday
year week
2020 1... | python-3.x|pandas|numpy | 0 |
14,332 | 22,435,947 | numpy conditional format of elements | <p>I have a 3D numpy array and want to change a particular element based on a conditional test of another element. (The applications is to change the 'alpha' of a RGBA image array to play with the transparency in a 3D pyqtgraph image - should ideally be pretty fast).</p>
<pre><code>a= np.ones((2,4,5),dtype=np.int) #cr... | <p>This seems to do the trick:</p>
<pre><code>mask = a[:,:,0] > 1
a[:,:,4][mask] = 255
</code></pre>
<p>So the indexing just needed to be a little different and then it's just standard practice of applying a mask.</p>
<p><em>edit</em>
@Ophion showed this is much better written as:</p>
<pre><code>a[mask,:,-1] = ... | python|arrays|numpy|pyqtgraph | 3 |
14,333 | 18,178,504 | Finding all the overlapping groups of dictionary keys | <p>Say I have a dictionary of lists in Python. I would like to find <strong>all</strong> the groups of keys that have items in common, and for each such group, the corresponding items.</p>
<p>For example, assuming that the items are simple integers:</p>
<pre><code>dct = dict()
dct['a'] = [0, 5, 7]
dct['b'] = [1,... | <p>I would try to create a second dictionary (<code>groups</code>) that represents the intersection of each list in the original <code>dct</code>. For example, youu could do this using a defaultdict something like:</p>
<pre><code>from collections import defaultdict
groups = defaultdict(list)
dct = { 'a' : [0, 5, 7], '... | python|dictionary|numpy | 3 |
14,334 | 55,417,548 | Pandas: add a new column with one single value at the last row of a dataframe | <p>My request is simple but I am stuck and do not know why... my dataframe looks like this: </p>
<pre><code> price time
0 1 3
1 3 6
2 4 7
</code></pre>
<p>What I need to do is to add a new column <code>mkt</code> with only one value equal to 10 at the last row (in my example i... | <p>You can use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.at.html" rel="nofollow noreferrer">at</a> function:</p>
<pre><code>df.mkt = ''
df.at[-1, 'mkt'] = 10
</code></pre> | python|pandas | 4 |
14,335 | 55,329,107 | Calculating the last value for a timeframe | <p>I have a table where i need to calculate the Max value of the Last value in a rolling time frame of 15minutes. Expected column is the column 'MAX'. I would like to get the maximum of Last value in for 15minutes time interval. I didnt talk about grouper 15minutes. but rolling over 15minutes as you can see in the Max ... | <p>A formula will do this. Put this in P3 and drag down.</p>
<pre><code>=MAX(O3:INDEX(O:O, AGGREGATE(15, 7, ROW($2:3)/(N$2:N3>=(N3-TIME(0, 15, 0))), 1)))
</code></pre>
<p><a href="https://i.stack.imgur.com/DNfeo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DNfeo.png" alt="enter image descript... | python|pandas|dataframe | 0 |
14,336 | 55,182,951 | pandas inclusive unique values from two columns | <p>I can't find any elegant way to select unique rows from column <code>A</code> and column <code>B</code> but not jointly and not in a sequence. This is in order to keep "inclusive" intersection of unique values from these two columns.</p>
<p>My aim is to keep as many unique values as possible across columns <code>A<... | <p>Try Below Code:</p>
<pre><code>df1.drop_duplicates( subset=[ "A" and "B"], keep="first", inplace=False, )
</code></pre>
<p>Output:</p>
<pre><code> A B
0 A1 B1
2 A2 B2
3 A3 B3
</code></pre> | python|pandas|filter|unique|drop-duplicates | -1 |
14,337 | 56,765,635 | How to find out whether it is Day or Night using Timestamp | <p>I want to find out whether it is day or night from the "timestamp" column in my data frame. The time stamp columns have values as follows:
20:0 , 14:30, 6:15, 5:0, 4:0 etc. </p>
<p>I used a for loop but it randomly generated day and night. </p>
<pre><code>for x in data['timestamp']:
if x> '12:00':
print('D... | <p>Convert values to timedeltas with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_timedelta.html" rel="nofollow noreferrer"><code>to_timedelta</code></a> and compare by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.between.html" rel="nofollow noreferrer... | python|pandas|datetime|timestamp | 2 |
14,338 | 56,709,949 | How to generate a Python Pivot Table of counts of strings in the Pandas cells? | <p>I am having trouble creating a pivot table in Python 3.7.3 of counts of strings found within a dataframe (df1) and aligning the counts to columns of the string values in another dataframe (df2). How do I go about filling in my second dataframe with the total counts of the column headers (the strings) based on the v... | <p><code>stack</code> first, you don't need <code>df2</code></p>
<hr>
<pre><code>m = (df1.set_index('Unnamed: 0').stack()
.rename_axis(['names', 'values']).rename('columns').reset_index())
m.pivot_table('values', 'names', 'columns', aggfunc='count', fill_value=0)
</code></pre>
<p></p>
<pre><code>columns s... | python|pandas|pivot-table | 1 |
14,339 | 26,143,629 | pyOpenCL getting different results compared to numpy | <p>I'm trying to get started with pyOpenCL and GPGPU in general.</p>
<p>For the below dot product code I'm getting fairly different results between the GPU and CPU versions. What am I doing wrong?</p>
<p>The difference of ~0.5% seems large for floating point errors to account for the difference. The difference does s... | <p>The order in which values are reduced will likely be very different between these two methods. Across large data sets, the tiny errors in floating point rounding can soon add up. There could also be other details about the underlying implementations that affect the precision of the result.</p>
<p>I've run your exam... | python|numpy|opencl|pyopencl | 2 |
14,340 | 66,786,298 | Inference on pre-trained ONNX model from Unity ml-agents in Tensorflow | <p>I have a pre-trained model from Unity's ml-agents. Now I'm trying to do inference with that model in python using TensorFlow. For this, I use <a href="https://github.com/onnx/onnx-tensorflow" rel="nofollow noreferrer">TensorFlow Backend for ONNX</a> to save the ONNX model as a SavedModel so I can later load this mod... | <p>Oke, so it turns out that the output of the network also gives the version and other parameters.</p>
<pre><code>onnx_model = onnx.load(model_path) # load onnx model
tf_rep = prepare(onnx_model)
print(tf_rep.inputs) # Input nodes to the model
> output: ['visual_observation_0', 'visual_observation_1']
print(tf_re... | python|tensorflow|onnx|ml-agent | 1 |
14,341 | 66,874,999 | KeyError while plotting a graph in matplotlib | <p>I am trying to plot a simple graph for the dataframe below</p>
<pre><code> indeces Zeitstempel Ergebnis
0 382 16.04.2020 16:12:07 PASS
1 383 16.04.2020 16:13:07 PASS
2 392 16.04.2020 16:13:20 FAIL
3 382 16.04.2020 16:13:22 PASS
4 383 16.04.2020 16:14:22 PASS
</code></pre>
<p>I... | <p>Take a look at the answer I posted at: <a href="https://stackoverflow.com/a/66908315/10462884">How to read a dataframe in np.genfromtxt instead of a file in matplotlib</a>. It shows how to load data from a csv file with <code>np.genfromtxt()</code> then generate the desired color coded plot (similar to what you want... | pandas|matplotlib|jupyter-lab | 0 |
14,342 | 67,137,768 | Find date difference between two numpy arrays | <p>I have two numpy arrays that contain dates of type datetime64 and I want to iterate through them and find the date differences?</p>
<pre><code>import numpy
print(dates1)
array(['2019-10-10T21:59:17.074007', '2015-10-13T00:55:55.544607',
'2017-05-24T06:00:15.959202', '2015-08-14T04:54:07.114346',
'2018-05-04T0... | <p>the np.datetime64 module can meet your needs. Below is sample code and result.</p>
<p>I don't know much about the subject but I think it will work.</p>
<p>The code:</p>
<pre><code>for index in range(len(dates1)):
print(np.datetime64(dates1[index])-np.datetime64(dates2[index]))
</code></pre>
<p>Response:</p>
<pre... | numpy | 1 |
14,343 | 66,971,222 | Group by column and add columns to count for occurences of values | <p>I have the following code:</p>
<pre><code>import numpy as np
from random import randrange
groups = [randrange(1,8) for x in range(50)]
df = pd.DataFrame(groups,columns = ["group"])
df["dummy1"] = pd.Series(np.random.randint(20,size = len(df)))
df["dummy2"] = pd.Series(np.random.randint... | <p>You can try <code>value_counts</code> with <code>groupby</code> and then join with your <code>groupby().agg()</code>:</p>
<pre><code>groups = df.groupby("group")
(groups.agg({"dummy1":[np.sum,np.mean]})
.join(groups['dummy1'].value_counts().to_frame('count').unstack())
)
</code></pre> | python|pandas|dataframe | 2 |
14,344 | 67,043,249 | How to use np.where in creating new column using previous rows? | <p>I'm kind of new in python and I've been working on migrating my excel to pandas because it cannot run a hundred of thousands of rows.
I have a table that looks like this in excel:</p>
<p><a href="https://i.stack.imgur.com/seoyP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/seoyP.png" alt="enter ... | <p>Since you are creating <strong>new column</strong> <code>Previous</code> and this column is still not yet defined when you use it in the definition of itself, in the <code>np.where()</code> statement, you will get an error.</p>
<p>Also, your question is actually not taking a <em>"previous"</em> value since... | python|excel|pandas|numpy | 2 |
14,345 | 47,218,920 | How do I remove repeated values on grouping with Pandas and Matplotlib | <p>Fairly new to using Pandas and Matplotlib. I have a data frame like below and I'd like to get a count of the users per application. </p>
<pre><code>application environment user
A 1 Bob
A 2 Carol
A 3 Bob
B ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>size</code></a> and then remo... | pandas|matplotlib | 0 |
14,346 | 47,376,300 | adfuller test received ValueError: too many values to unpack | <p>I have some numbers stored in a variable called "constant"</p>
<p><a href="https://i.stack.imgur.com/No55Z.png" rel="noreferrer"><img src="https://i.stack.imgur.com/No55Z.png" alt="enter image description here"></a></p>
<p>When I try to test the mean-reversion by using</p>
<pre><code>cadf = ts.adfuller(constant)
... | <p><code>adfuller()</code> function accepts only 1d array of time series
so first convert it using:</p>
<pre><code>data1 = data.iloc[:,0].values
</code></pre> | python|pandas|statsmodels | 11 |
14,347 | 47,117,979 | How can you form a new dataframe reflecting the changes of values in an original dataframe? | <p>If you could peek into the future and know exactly what stocks to buy and sell given their entire price history, how would you implement it, given constraints that your only values of <code>Shares</code> is <code>1000</code>, <code>0</code>, and <code>-1000</code>? You also start with <code>1000</code> shares. You c... | <p>I was able to figure it out. </p>
<p>This is sufficient:</p>
<pre><code>for i in range(len(df_prices)):
if i == len(df_prices) - 1:
df_orders.set_value(i, 'Date', df_prices.index[i])
df_orders.set_value(i, 'Order', 'BUY')
df_orders.set_value(i, 'Shares', 0)
df_orders.set_value(i... | python|pandas|typeerror | 0 |
14,348 | 11,350,770 | Filter pandas DataFrame by substring criteria | <p>I have a pandas DataFrame with a column of string values. I need to select rows based on partial string matches.</p>
<p>Something like this idiom:</p>
<pre><code>re.search(pattern, cell_in_question)
</code></pre>
<p>returning a boolean. I am familiar with the syntax of <code>df[df['A'] == "hello world"]</... | <p>Based on github issue <a href="https://github.com/pydata/pandas/issues/620" rel="noreferrer">#620</a>, it looks like you'll soon be able to do the following:</p>
<pre><code>df[df['A'].str.contains("hello")]
</code></pre>
<p>Update: <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#text-string-methods"... | python|string|pandas|dataframe | 1,225 |
14,349 | 68,235,963 | Problem analyzing a doc column in a df with spaCy nlp | <p>After using a amazon review scraper to build this data frame, I called on nlp in order to tokenize and create a new column containing the processed reviews as 'docs'</p>
<p>However, now I am trying to create a pattern in order to analyzing the reviews in the doc column, but I keep getting know matches, which makes m... | <p>You are trying to get the matches from the <code>"df.doc"</code> string with <code>doc = nlp("df.doc")</code>. You need to extract matches from the <code>df['doc']</code> column instead.</p>
<p>An example solution is to remove <code>doc = nlp("df.doc")</code> and use the <code>nlp = spa... | python|pandas|nlp|spacy | 1 |
14,350 | 68,034,953 | add new row at next available position | <p>In my code, if the list <code>katalogLinks</code> is empty, I want to add a new row to the <code>df</code> with the url and a <code>0</code> value for the <code>potential client</code> column.</p>
<p>Else, if the len is more than 0, I want to add a new row with the url and a <code>1</code> value for the potential cl... | <p>I tried the code you suggested for appending data, and it adds a new row if you test it with a simple string:</p>
<pre><code> df.append(pd.DataFrame({"Company URL":["ur"l],
"Potential Client":[0]}))
</code></pre>
<p>I think you should try debugging the "getKa... | python|python-3.x|pandas|dataframe | 1 |
14,351 | 68,175,695 | Is it pythonic to send form data as pandas dataframe to database? | <p>So what I do is:</p>
<ol>
<li>Get form data with fastapi's <code>python-multipart</code></li>
<li>Convert the form data to a dictionary</li>
<li>Convert the dictionary to a pandas dataframe</li>
<li>Send the pandas dataframe to my sqlite database</li>
</ol>
<p>However, is this the way to do it or is there a better, ... | <p>The rule is if it works just leave it but if you are still looking for a better approach then please have a look at this <a href="https://python-adv-web-apps.readthedocs.io/en/latest/flask_db3.html" rel="nofollow noreferrer">article</a>.
<a href="https://python-adv-web-apps.readthedocs.io/en/latest/flask_db3.html" r... | python|python-3.x|pandas|dataframe|fastapi | 0 |
14,352 | 1,057,666 | Using Python to replace MATLAB: how to import data? | <p>I want to use some Python libraries to replace MATLAB. How could I import Excel data in Python (for example using <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow noreferrer">NumPy</a>) to use them?</p>
<p>I don't know if Python is a credible alternative to MATLAB, but I want to try it. Is there a a tutor... | <p>Depending on what kind of computations you are doing with <a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow noreferrer">MATLAB</a> (and on which toolboxes you are using), Python could be a good alternative to MATLAB.</p>
<p>Python + <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow noreferrer">Nu... | python|excel|matlab|numpy | 11 |
14,353 | 59,191,644 | Recursive Dictionary for Pandas Dataframe | <p>I have a Pandas DataFrame like this:</p>
<pre><code>index 0 1 2
0 a a 0.2
1 a a 0.4
0 a b 0.4
1 a b 0.7
</code></pre>
<p>What I want is to create a dictionary to access column <code>2</code> easily via columns <code>0</code> and <code>1</code>, looking like this:</p>
... | <p>Try:</p>
<pre><code>df.groupby([0,1]).agg(list).to_dict('index')
{('a', 'a'): {'index': [0, 1], '2': [0.2, 0.4]},
('a', 'b'): {'index': [0, 1], '2': [0.4, 0.7]}}
</code></pre> | python|pandas | 1 |
14,354 | 59,158,272 | How do I run several Keras neural network models in different files? | <p>So I have three models created in three different files: Model_A.py, Model_B.py, Model_C.py. Model_A is the first one i have created. When I run Model_A, everything works well. However, when I run Models B or C python still runs Model A. I guessed it has to do with the session, but I am not sure and I have not figur... | <p>Would it be possible(at least as a workaround) to kill each process after it finishes the task? Killing the process would ensure the release of memory of TensorFlow.</p>
<p>If the models need a communication channel/have intermediate results sent over, you could use queues or text files in order to solve this.</p> | python|tensorflow|keras|model|neural-network | 0 |
14,355 | 59,406,045 | Convert pandas series into a row | <p>I calculated the means of a DatFrame which resulted in a Series object that looks like this:</p>
<pre><code>means.sort_index()
0000 0.000204
0100 -0.000083
0200 -0.000260
0300 -0.000667
0400 -0.000025
0500 0.000127
0600 0.000227
0700 -0.000197
0800 -0.000497
0900 -0.000321
1000 -0.000520
11... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.to_frame.html" rel="noreferrer"><code>Series.to_frame</code></a> for one column <code>DataFrame</code> and then transpose by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.T.html" rel="noreferrer... | python|pandas|dataframe | 6 |
14,356 | 59,237,114 | (Attribute Error: 'function' object has no attribute 'visualize_boxes_and_labels_on_image_array') | <p>I'm getting <code>Attribute Error: 'function' object has no attribute 'visualize_boxes_and_labels_on_image_array'</code> when I run my code.</p>
<p>I'm using python 3.6.5 and tensorflow 2.0.0 </p>
<p>I imported numpy,utils ,vis but I still getting the same error </p>
<p>How can I resolve this issue?</p>
<pre><co... | <p>Did you set the python path before you run the program, you need to run the below line from the research folder - </p>
<hr>
<p>export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim </p>
<hr>
<p>Check the link for more information -
<a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3d... | python|opencv|tensorflow|object-detection | 0 |
14,357 | 44,906,317 | What are possible values for data_augmentation_options in the TensorFlow Object Detection pipeline configuration? | <p>I have successfully trained an object detection model with TensorFlow with the sample configurations given here: <a href="https://github.com/tensorflow/models/tree/master/object_detection/samples/configs" rel="noreferrer">https://github.com/tensorflow/models/tree/master/object_detection/samples/configs</a></p>
<p>N... | <p>The list of options is provided in <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/protos/preprocessor.proto" rel="noreferrer">preprocessor.proto</a>: </p>
<pre><code>NormalizeImage normalize_image = 1;
RandomHorizontalFlip random_horizontal_flip = 2;
RandomPixelValueScale random... | tensorflow|configuration|object-detection | 92 |
14,358 | 45,062,035 | How do I define a shape using tf.random_crop of variable patch sizes? | <p>I'm trying to get random crops from an image of different size (size changes over time and is stored in a <code>Variable</code>). The size of patches changes and represented as a tensor:</p>
<pre><code>patch_size = tf.Variable(128)
patches = []
for i in xrange(num_patches):
patch = tf.random_crop(images, [batch_s... | <p>The <code>set_shape</code> method does not allow the shape to be defined with tensors. This is reasonable, because it does not make a TensorFlow operation. It actually redefines the static shape of the tensor on the spot.</p>
<p>Since <code>patch_size</code> is dynamic, it should not be used to set a static shape. ... | python|tensorflow | 1 |
14,359 | 44,875,242 | numpy.empty giving nonempty array | <p>When I create an empty numpy array using <code>foo = np.empty(1)</code> the resulting array contains a float64:</p>
<pre><code>>>> foo = np.empty(1)
>>> foo
array([ 0.])
>>> type(foo[0])
<type 'numpy.float64'>
</code></pre>
<p>Why doesn't it just return <code>array([])</code>?</p> | <p>You didn't read <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html#numpy.empty" rel="noreferrer">the documentation</a>, which says:</p>
<blockquote>
<p>Return a new array of given shape and type, without initializing entries.</p>
</blockquote>
<p><code>empty</code> has nothing to do w... | python|numpy | 18 |
14,360 | 57,151,732 | Create a new column with IF-THEN in grouped pandas df | <p>I'm applying a simple function to a grouped pandas df. Below is what I'm trying. Even if I try to modify the function to carry one step, I keep getting the same error. Any direction will be super helpful.</p>
<pre><code>def udf_pd(df_group):
if (df_group['A'] - df_group['B']) > 1:
df_group['D'] = 'Condition-... | <p>Note that in <em>groupby.apply</em> the function is applied to <strong>the whole group</strong>.
On the other hand, each <em>if</em> condition must boil down to a <strong>single</strong> value
(not to any <em>Series</em> of <em>True/False</em> values).</p>
<p>So each comparison of 2 columns in this function must be... | pandas | 2 |
14,361 | 23,142,933 | Why am I getting strange behavior for creating several boolean series? | <p>I have a DataFrame to which I am adding several boolean columns. For each column, I initialize it to False and then set some values to True. If I do this for one and then for another, the first gets reinitialized to all False. For example,</p>
<pre><code>In [170]: df['racedif']=False
In [171]: df['racedif'][~ df.n... | <p>you are chain indexing, see docs here: <a href="http://pandas-docs.github.io/pandas-docs-travis/indexing.html#indexing-view-versus-copy" rel="nofollow">http://pandas-docs.github.io/pandas-docs-travis/indexing.html#indexing-view-versus-copy</a></p>
<p>bottom line is use </p>
<pre><code>df.loc[row_indexer,col_indexe... | python|pandas | 3 |
14,362 | 23,308,362 | Get index of the element nearest to the given value | <p>The given value is 6.6. But the value 6.6 is not in the array (data below).
But the nearest value to the given value is 6.7. How can I get this position?</p>
<pre><code>import numpy as np
data = np.array([[2.0, 3.0, 6.5, 6.5, 12.0],[1,2,3,4,5]],dtype=float)
</code></pre> | <p>You can get like this:</p>
<pre><code>data[(np.fabs(data-6.6)).argmin(axis=0)]
</code></pre>
<p>output:</p>
<pre><code>6.7
</code></pre>
<ol>
<li>find the absolute diff on each element</li>
<li>Find the minimum from the result and get the element from index</li>
</ol>
<p>EDIT: for 2d:</p>
<p>If it is python 2.... | python|numpy|scipy | 2 |
14,363 | 35,507,412 | Convert Panda DataFrame to Panel-like structure | <p>I'm having a lot of trouble with a specific problem of reshaping data into the correct format.</p>
<p>I have data like this:</p>
<pre><code>Date Hour Category Col1 Col2
1/1/10 1:00 1 France 1.1 1.2
1/1/10 2:00 2 France 2.9 1.4
1/1/10 1:00 1 UK 3.8 2.3
2/1/10 1:00 1 Fr... | <p>The following seems working (you'll need to do some column renaming, etc.), but what you would like to achieve seems weird to me -- putting data in as a list/array inside a series make it harder to use later.</p>
<pre><code>print df.groupby(['Hour', 'Category']).apply(lambda subdf : subdf[['Date','Col1','Col2']].va... | python|pandas|dataframe|panel|multi-index | 0 |
14,364 | 28,594,389 | how use struct.pack for list of strings | <p>I want to write a list of strings to a binary file. Suppose I have a list of strings <code>mylist</code>? Assume the items of the list has a <code>'\t'</code> at the end, except the last one has a <code>'\n'</code> at the end (to help me, recover the data back). Example: <code>['test\t', 'test1\t', 'test2\t', 'testl... | <p>There's no need for <code>struct</code>. Simply join the strings and encode them using either a specified or an assumed text encoding in order to turn them into bytes.</p>
<pre><code>''.join(L).encode('utf-8')
</code></pre> | string|python-3.x|numpy | 1 |
14,365 | 28,565,965 | Pandas Timezone Aware Index Drops Timezone When Converting To Series | <p>I am trying to get the time index of a dataframe as a series, but it appears to be dropping the timezone when I call the method to_series. Below is an example. Is this a bug or am I doing something incorrectly?</p>
<pre><code>rows = 50
df = pd.DataFrame(np.random.randn(rows,2), columns=list('AB'), index=pd.date_ran... | <p>No, you are not doing something wrong, and neither it is a bug.<br>
It is a <strong>currently known limitation</strong> of pandas/numpy: timezones aware datetime data are only supported in the index. In a series, the data are stored as numpy <code>datetime64</code> types, which does not support timezones. There is a... | python|pandas | 2 |
14,366 | 50,730,034 | `decode_predictions` expects a batch of predictions (i.e. a 2D array of shape (samples, 1000)). Found array with shape: (1, 5) | <p>A retrained the inception_v3 model for my own test data. (Backstory: im just trying to understand how the whole process works before im trying it on my 130 class "problem")</p>
<p>Now i got the .h5.
I tryed to import it and predict some image. But i only get the following error messages.</p>
<pre class="lang-pyt... | <p>The <code>decode_predictions</code> utility converts the class predictions of a pretrained ImageNet model into the corresponding human-readable ImageNet classes.</p>
<p>Using "decode_predictions" only makes sense if your model outputs the ImageNet classes (1000-dimensional). Your model (<code>my_model</code>) appea... | tensorflow|keras|deep-learning|keras-2 | 8 |
14,367 | 51,082,518 | Python: Finite sum with variable range "TypeError: only integer scalar arrays can be converted to a scalar index" | <p>Aim: plot V vs. MF</p>
<p><img src="https://i.stack.imgur.com/maDdb.png" alt="equation"></p>
<pre><code>import numpy as np
V = np.arange(3,46, step = 6)
A = 3
# 'n' is a sequence of odd numbers (i.e. 1,3,5,7, ...)
n = V/A
mm = (n+1)/2
MF = sum((np.power(-1, m)) * np.exp(m * m * (V/n)) for m in range(1,mm))
</co... | <p><code>mm</code> variable is a numpy array containing the sequence of <code>1, 2, 3 ...</code> so <code>range(1, mm)</code> part doesn't make sense since <code>range</code> expects its arguments to be integers. If you want to iterate on <code>mm</code>, you can just</p>
<p><code>MF = sum((np.power(-1, m)) * np.exp(m... | python|numpy | 0 |
14,368 | 66,727,139 | How do I iterate over different links to create a dataframe in pandas? | <p>I have been coding a script to scrape the premier league website for players. It will go into each player page from the main page then scrape the information specified from the table but I cannot loop it yet. I understand it probably is super verbose and horrible but I am still learning. I have stored a list of 843 ... | <p>You can use this example how to extract the data from the two URLs:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
url = "https://www.premierleague.com/players/13549/player"
soup = BeautifulSoup(requests.get(url + "/overview").content, "html.parser")
data = {}
data[&quo... | python|python-3.x|pandas|dataframe|loops | 2 |
14,369 | 66,480,059 | Convert year number to 'yyyy-mm-dd' format | <p>I have a pandas dataframe with 19 columns and one of them is titled <code>'publish_date'</code>. It contains values in the format <code>'yyyy-mm-dd'</code>, however, there are some exceptions where it just shows as <code>'yyyy'</code>. For example, there is a row where the value is <code>2012</code> and I want that ... | <p>You can find and replace all those cases using this:</p>
<pre><code>df['publish_date'][df['publish_date'].str.len()==4] = df['publish_date']+'-01-01'
</code></pre>
<p>Then you need to cast it to datetime.</p> | python|pandas | 0 |
14,370 | 16,509,624 | OS X 10.7 + Python 3.3 + numpy + matplotlib | <p>I have been trying to get Matplotlib running in 3.3 with no luck.</p>
<p>I downloaded the latest github repos for <a href="https://github.com/matplotlib/matplotlib" rel="nofollow">matplotlib</a>, which depends on <a href="https://github.com/numpy/numpy" rel="nofollow">numpy</a>.</p>
<p>For numpy I did 'python3 set... | <p>I'm just going off of the <a href="http://matplotlib.org/users/installing.html" rel="nofollow">Matplotlib install page</a>:</p>
<p>Which says "Click on the latest release of the “matplotlib” package, choose your python version (2.6, 2.7 or 3.2) and your platform (macosx or win32)." </p>
<p>I know that I've reverte... | macos|numpy|python-3.x|matplotlib | 1 |
14,371 | 57,666,898 | How to slice out certain rows and columns and then take only the remaining data in Dataframe Python? | <p>I have data like this</p>
<pre><code>Unnamed: 0 Unnamed: 1 Unnamed: 2 ... Unnamed: 4 Unnamed: 5 Unnamed: 6
0 NaN NaN NaN ... NaN NaN NaN
1 NaN NaN NaN ... NaN NaN NaN
2 NaN ... | <p>You can fix your dataframe by </p>
<pre><code>df=df.dropna(thresh=1).T.set_index(2).T
</code></pre> | python|pandas | 0 |
14,372 | 24,312,963 | assigning arrays from CSV with pandas module | <p>If I have a file of 100+ columns, how can I make each column into an array, referenced by the column header, without having to do header1 = [1,2,3], header2 = ['a','b','c'] , and so on..?</p>
<p>Here is what I have so far, where headers is a list of the header names:</p>
<pre><code>import pandas as pd
data = []
d... | <pre><code>import pandas as pd
</code></pre>
<p>If the headers are in the csv file, we can simply use:</p>
<pre><code>df = pd.read_csv('outtest.csv')
</code></pre>
<p>If the headers are not present in the csv file:</p>
<pre><code>headers = ['list', 'of', 'headers']
df = pd.read_csv('outtest.csv', header=None, names... | python|python-2.7|csv|pandas | 2 |
14,373 | 43,553,523 | Pandas: Efficient way to check if a value in column A is in a list of values in column B | <p>my initial dataframe looks like this</p>
<pre><code> A | B
-----------------
'a' | ['1', 'a', 'b']
'1' | ['2', '5', '6']
'd' | ['a', 'b', 'd']
'y' | ['x', '1', 'y']
</code></pre>
<p>and I want to check if 'a' is in the corresponding list in B: ['1', 'a', 'b']</p>
<p>I could do that by usi... | <p>If you convert each column to sets, you can use <code><</code> to compare pairwise subsets</p>
<pre><code>a = d.A.apply(lambda x: set([x]))
b = d.B.apply(set)
a < b
0 True
1 False
2 True
3 True
dtype: bool
</code></pre>
<p>Otherwise, you can use a list comprehension with <code>zip</code></p>... | python|list|pandas|contains | 4 |
14,374 | 43,644,299 | pandas filter and apply | <p>Hello I have the following data frame (df):</p>
<pre><code>Group Value
A 1
A 2
A 3
B -1
B 2
B 3
</code></pre>
<p>I would like to convert all of group B to negative values if they arent already (ie multiply by -1).</p>
<pre><code>df[df['group'] == 'B', 'value'].apply(... if value... | <pre><code>In [85]: df.loc[df.Group.eq('B') & df.Value.gt(0), 'Value'] *= -1
In [86]: df
Out[86]:
Group Value
0 A 1
1 A 2
2 A 3
3 B -1
4 B -2
5 B -3
</code></pre> | python|pandas | 4 |
14,375 | 43,729,268 | Convert a python dataframe with multiple rows into one row using python pandas? | <p>Having the following dataframe,</p>
<pre><code>df = pd.DataFrame({'device_id' : ['0','0','1','1','2','2'],
'p_food' : [0.2,0.1,0.3,0.5,0.1,0.7],
'p_phone' : [0.8,0.9,0.7,0.5,0.9,0.3]
})
print(df)
</code></pre>
<p>output:</p>
<pre><code> device_id p_food p_phone
... | <p>If you are still looking for an answer using groupby</p>
<pre><code>df = df.groupby('device_id')['p_food', 'p_phone'].apply(lambda x: pd.DataFrame(x.values)).unstack().reset_index()
df.columns = df.columns.droplevel()
df.columns = ['device_id','p_food_1', 'p_food_2', 'p_phone_1','p_phone_2']
</code></pre>
<p>You g... | python|pandas|dataframe|apply | 6 |
14,376 | 72,964,480 | Cannot import tensorflow_text | <p>I have problem with importing <code>tensorflow_text</code> I tried importing like below two methods but none of them worked</p>
<pre><code>import tensorflow_text as text
import tensorflow_text as tf_text
</code></pre>
<p>My tensorflow version is <code>2.9.1</code> and python version is <code>Python 3.7.13</code>. I ... | <p><strong>Update</strong>, Sometimes you need to reinstall and update <code>tensorflow</code> then install <code>tensorflow_text</code>. <em>(Because you need your <code>tensorflow.__version__</code> and <code>tensorflow_text.__version__</code> to have the same version)</em></p>
<pre><code>!pip install -U tensorflow
!... | python|tensorflow|tensorflow2.0 | 1 |
14,377 | 72,874,174 | Dropping Columns with if statements, then adding exception | <p>I have this code that goes through a csv, finds meaningful columns for me, and then drops columns that are not in the list. It works perfectly, but I want it to drop all columns not in found, except one called "MATNR." What can I add to the drop statement that will allow me to drop all of the undesired col... | <pre><code># Import Data Quality Rules (useful attributes)
rexp = re.compile('\.([A-Z]+)')
found = []
with open('DataRules.csv') as f:
for line in f:
found.extend(rexp.findall(line))
# Get rid of columns that are not mentioned in rules (except MATNR)
df.drop(columns=([col for col in df if col not in found... | python|pandas | 1 |
14,378 | 72,986,245 | Index issues while data cleaning | <p>Original code credit-Ken Jee</p>
<pre><code>Salary = df['Salary Estimate'].apply(lambda x:x.split('(')[0])
minus_Kd = Salary.apply(lambda x:x.replace('K','').replace('$',''))
min_hr=minus_Kd.apply(lambda x:x.lower().replace('per hour;','').replace('employer
provided salary:',''))
df['min_salary'] = min_hr.apply(l... | <p>Using .str accessor with extract, regex and eval:</p>
<p>Given df,</p>
<pre><code>df = pd.DataFrame({'Job':['Job 1', 'Job 2', 'Job 3'],
'Salary':['$78K - $191K', '$77K - $107K', '$100K']})
</code></pre>
<p>Input df:</p>
<pre><code> Job Salary
0 Job 1 $78K - $191K
1 Job 2 $77K - $107... | python|pandas|visual-studio-code|data-science|data-cleaning | 1 |
14,379 | 70,472,124 | Remove unwanted part of strings in a column with Pandas | <p>I have a column that looks like this</p>
<pre><code> Message
0 Wings.cpp:222] Current sidewing pressure: 3410
1 Wings.cpp:222] Current sidewing pressure: 4206
2 Wings.cpp:222] Current sidewing pressure: 3433
3 Wings.cpp:222] Current sidewing pressure: 4229
4 Position.cpp:438] &l... | <p>Use <code>str.replace</code>:</p>
<pre class="lang-py prettyprint-override"><code>df["Message"] = df["Message"].str.replace('^.*?\]\s*', '')
</code></pre>
<p>Here is a <a href="https://regex101.com/r/VKOaej/1" rel="nofollow noreferrer">regex demo</a> showing the logic is working.</p> | python|pandas|dataframe | 1 |
14,380 | 70,464,875 | Python return statement failing to return a list to be written into a pandas DF | <p>For the life of me I cannot figure out why this function is not returning anything. Any insight will be greatly appreciated!</p>
<p>Basically I create a list of string variables that I am preserving in a Pandas DF. I am using the DF to pull the variable to plug into the function via a .apply() method. But my return ... | <p>Figured it out! it was a problem of nested functions. The return value from the <code>add_combinations_to_directory</code> was being returned to the <code>add_person_to_lookup_directory</code> function and not passing through to the dataframe.</p> | python|pandas|return | 0 |
14,381 | 70,430,717 | Can't clearTimer in async interval | <p>I'm trying to modify an implementation of some TensorFlow face detection algorithms using Java.
At the moment, I've added a button that properly stops/starts the video streaming from my camera. Also, when the video is playing, I detect the faces on it every 100ms with an async interval.</p>
<p>The problem appears wh... | <p>As <a href="https://stackoverflow.com/users/1427878/cbroe">CBroe</a> mentioned in <a href="https://stackoverflow.com/questions/70430717/cant-cleartimer-in-async-interval/70441983#comment124513067_70430717">a comment</a>:</p>
<blockquote>
<p>I would either handle both in the click event, or both in the play and pause... | javascript|tensorflow | 0 |
14,382 | 42,971,473 | Pandas create df that is the product of columns in another df | <p>I have the following pandas dataframe: </p>
<pre><code>id | a | b | c | d
------------------
0 | 1 | 3 | 4 | 5
1 | 2 | 3 | 5 | 6
</code></pre>
<p>and I would like to create a new df of which its columns is the difference of successive columns in the first df </p>
<p>new df: </p>
<pre><code>id | b-a | c-b | ... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sub.html" rel="nofollow noreferrer"><code>sub</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html" rel="nofollow noreferrer"><code>shift</code></a>, for remove first colu... | python|pandas|dataframe | 3 |
14,383 | 42,754,036 | what's the behavior of tf.trian.optimizer when loss is a vector | <p>Suppose log_prob is a vector rather than a scalar. What will the following code do?
Thank you!</p>
<p>```</p>
<pre><code>optimizer = tf.train.AdamOptimizer(0.001)
minimize = optimizer.minimize(log_prob)
session.run(minimize, feed_dict={action : act, feat : s_batch})
</code></pre>
<p>```</p> | <p><a href="https://www.tensorflow.org/api_docs/python/tf/gradients" rel="nofollow noreferrer">tf.gradients</a>, and therefore <code>Optimizer</code> <code>minimize</code> calls, sum loss Tensors to get a scalar rather than computing the Jacobian. See this discussion of Jacobians in TensorFlow for background: <a href="... | optimization|tensorflow | 0 |
14,384 | 42,595,115 | datetime operation works in notebook but not after export as .py script | <p>I have created a .py file after testing this piece of code on jupyter ipython notebook, which worked well for me. </p>
<pre><code>import datetime as dt
import pandas as pd
def CheckTrend(tdate, px, trend, df):
todaydate = dt.datetime.strptime(tdate,'%m/%d/%Y')
todaydate = todaydate - dt.timedelta(days=6)
... | <p>That seems slightly strange, perhaps try modifying the 'trend' file so that the line
<code>todaydate = todaydate - dt.timedelta(days=6)</code></p>
<p>becomes</p>
<p><code>todaydate = int(todaydate) - int(dt.timedelta(days=6))</code></p>
<p>I'm not sure you'll need the second int around timedelta, but I think th... | python|pandas|datetime | 0 |
14,385 | 26,988,041 | Pandas DataFrame row wise comparison | <p>I have a pandas <code>DataFrame</code> like following.</p>
<pre><code> id label_x label_y
0 1 F R
1 2 F F
2 3 F F
3 4 F F
4 5 F F
</code></pre>
<p>Now I want to count occurrences of label_x and label_y are equal and not equal. In this case the... | <pre><code>(df.label_x == df.label_y).value_counts()
</code></pre>
<p>Many ways to to that, including the above...</p>
<pre><code>In [43]: (df.label_x == df.label_y).value_counts()
Out[43]:
True 4
False 1
dtype: int64
</code></pre> | python|pandas|dataframe | 2 |
14,386 | 27,231,985 | create new column from conditional statement without mask pandas | <p>I am looking for a better way to do the following:</p>
<pre><code> A
TRDNumber
ALB2008081610 430
ALB200808167 0
ALB200808168 190
</code></pre>
<p>Creating a new column based on the value in another column using a conditional statement</p>
<pre><code> ... | <p>I think you want to do the following:</p>
<pre><code>#%%
df = pd.DataFrame()
df['A'] = pd.Series([430,0,190], index=['ALB2008081610', 'ALB200808167', 'ALB200808168'])
print(df)
#%%
df['B'] = None
print(df)
#%%
df.loc[(df.A==0), 'B'] = 'x'
print(df)
#%%
df.loc[(df.A!=0) & (df.A<=200), 'B'] = 'y'
print(df)
<... | python|pandas | 3 |
14,387 | 26,603,747 | Get the indices of N highest values in an ndarray | <p>Considering an histogram of shape 100x100x100, I would like to find the 2 highest values a and b, and their indices (a1, a2, a3) and (b1, b2, b3), such as:</p>
<pre><code>hist[a1][a2][a3] = a
hist[b1][b2][b3] = b
</code></pre>
<p>We can easily get the highest value with hist.max(), but how can we get the X highest... | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argpartition.html"><code>numpy.argpartition</code></a> on flattened version of array first to get the indices of top <code>k</code> items, and then you can convert those 1D indices as per the array's shape using <a href="http://docs.scipy... | python|numpy|indexing|multidimensional-array | 15 |
14,388 | 26,648,781 | Python - Get "subarrays" of 3d array | <p>I would like to get multiple subarrays of an 3D array. I can split the array in 2D case with a function found in a post of Stack :</p>
<pre><code>def blockshaped(arr, nrows, ncols):
h, w = arr.shape
return (arr.reshape(h//nrows, nrows, -1, ncols)
.swapaxes(1,2)
.reshape(-1, nro... | <p>You for loop solution would work doing something like:</p>
<pre><code>sub = np.array([blockshaped(a, 2, 2) for a in test2])
</code></pre>
<p>But you can slightly modify <code>blockshaped()</code>, reshaping the data before and after the slicing:</p>
<pre><code>def blockshaped(arr, nrows, ncols):
need_reshape ... | python|arrays|numpy | 1 |
14,389 | 39,254,319 | Finding the occurrence and position of a character in python | <p>I have a variable (var) with ids
I am interested in finding out the position of last occurrence of Z</p>
<p>I have tried to convert it to an array with their positions</p>
<pre><code> zf1=np.where(df2['Var']=="Z")
</code></pre>
<p>This will give me the result as </p>
<pre><code> (array([4,5,6,7,8,9,10,1... | <p><strong><em>Get Index values</em></strong></p>
<pre><code>df2.index[df2.Var.eq('Z') & df2.Var.ne(df2.Var.shift(-1))]
</code></pre>
<p><strong><em>Filter <code>df2</code></em></strong></p>
<pre><code>df2[df2.Var.eq('Z') & df2.Var.ne(df2.Var.shift(-1))]
</code></pre> | python|pandas|position|np|find-occurrences | 0 |
14,390 | 39,386,957 | Read a file in python starting with a particular string | <p>I have a file in the following path:</p>
<pre><code>/home/[user]/foo_01-01-2016.txt
</code></pre>
<p>I need to read it using the wild card (*) character:</p>
<pre><code>import pandas as pd
df = pd.read_csv("/home/[user]/foo_*.txt")
</code></pre>
<p>But its giving a file not found error.</p> | <p>You can use <a href="https://docs.python.org/3.5/library/glob.html" rel="nofollow"><code>glob</code></a>, but output is list, so select first item by <code>[0]</code>:</p>
<pre><code>import pandas as pd
import glob
path =r'/home/[user]'
filename = glob.glob(path + "/foo_*.txt")
print (filename[0])
df = pd.read_cs... | python|file|pandas|dataframe|wildcard | 1 |
14,391 | 19,696,017 | Different fill methods for different columns in pandas | <p>I'm reindexing a dataframe in the standard way, i.e.</p>
<pre><code>df.reindex(newIndex,method='ffill')
</code></pre>
<p>But realized I need to handle missing data differently on a column-by-column basis. That is, for some columns I want to ffill, but for others I want to missing values recorded as NAs.</p>
<p>Fo... | <p>You can <code>reindex()</code> first, and then call <code>ffill()</code> for columns:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({"A":[10, 20, 30], "B":[100, 200, 300],
"C":[100, 200, 300]}, index=[2, 6, 8])
df2 = df.reindex([2,4,6,8,10])
for col in ["A", "B"]:
df2[col].ffill(inpl... | python|pandas | 7 |
14,392 | 28,910,089 | Filling empty python dataframe using loops | <p>Lets say I want to create and fill an empty dataframe with values from a loop. </p>
<pre><code>import pandas as pd
import numpy as np
years = [2013, 2014, 2015]
dn=pd.DataFrame()
for year in years:
df1 = pd.DataFrame({'Incidents': [ 'C', 'B','A'],
year: [1, 1, 1 ],
}).set_index... | <pre><code>import pandas as pd
years = [2013, 2014, 2015]
dn = []
for year in years:
df1 = pd.DataFrame({'Incidents': [ 'C', 'B','A'],
year: [1, 1, 1 ],
}).set_index('Incidents')
dn.append(df1)
dn = pd.concat(dn, axis=1)
print(dn)
</code></pre>
<p>yields</p>
<pre><code> ... | python|pandas|iteration | 15 |
14,393 | 33,715,079 | Replacing elements in Numpy 2D array with corresponding elements of another Numpy 2D array depending on a condition | <p>I am new to Numpy and I was wondering if there is a fast way to replace elements in a 2D array (lets call it "A") that are meeting a specific condition with their corresponding elements of another 2D array (lets call it "B"), and at the same time keep the values of the remaining elements in array "A" that didn't mee... | <p>Say the condition is <code>element < 2</code>. Then we can create a mask indicating which cells match the condition:</p>
<pre><code>mask = A < 2
</code></pre>
<p>and use advanced indexing to select the corresponding elements of <code>B</code> and assign their values to the corresponding cells of <code>A</cod... | python|arrays|numpy | 4 |
14,394 | 33,868,862 | How to declare the output type of a GNU Radio block to be PMT? | <p>Short: I want to output PMTs in my block, but GNU Radio won't let me.</p>
<p>Generally I write OOT blocks for different applications on GNU Radio. Here I am trying to write a block for outputting a file as a message type. </p>
<p>The thing is if the output of our block if of type <code>numpy.float32</code>, we dec... | <p>PMT (polymorphic types) are variable sized, portable containers.</p>
<p>They are used for message passing and tags, but not for streaming data.</p>
<p>If you want to output a message, then defined an empty <code>out_sig</code>, i.e.</p>
<pre><code>..., out_sig=[], in_sig=[])
</code></pre>
<p>and use the <code>me... | python|numpy|gnuradio | 0 |
14,395 | 33,874,648 | Multiple data frame to single excel file(two different sheets) in python pandas | <p>I have two dataframes processed from the database. I need to export those data frames into excel(libreoffice calc) in two different sheets.</p>
<pre>
DF1:
symbol datetime value
0 MOV 06:25:02 148767
1 TBI 06:25:02 267198
2 HY 06:25:02 56232
3 KAMN 06:25:02 2247
DF2... | <p>If passing an existing <code>ExcelWriter</code> object, then the sheet will be added to the existing workbook. This can be used to save different <code>DataFrames</code> to one workbook:</p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html" rel="nofollow noreferrer">So... | python|pandas|dataframe | 11 |
14,396 | 33,930,446 | Dimension mismatch: array 'cov' is of shape (1, 1), but 'mean' is a vector of length 2 | <p>I'm trying to execute the following code</p>
<pre><code>p, c = [], []
for z in mes:
print (z)
print (c)
print (p)
p.append(kf.x)
c.append(kf.P)
kf.predict()
kf.update(z) #error on this line
</code></pre>
<p>I get the error :</p>
<blockquote>
<p>ValueError: Dimension mismatch: array '... | <p>When using the filterpy library you're responsible for setting up the initial state of the Kalman filter yourself, and the dimensions of the various matrices need to be compatible. If you look into the <code>KalmanFilter.update()</code> method, you can track the computations it does and come up with the following se... | python-3.x|numpy|scipy|kalman-filter | 1 |
14,397 | 22,750,293 | pandas groupby last n | <p>What is the best way to get the mean of the last n instances using pandas groupby?</p>
<p>For example I have a dataframe like this:</p>
<pre><code>frame = pd.DataFrame({'Student' : ['Bob', 'Bill', 'Bob', 'Bob', 'Bill', 'Joe', 'Joe', 'Bill', 'Bob', 'Joe'],
... | <p>Maybe something like this?</p>
<pre><code>>>> df.groupby("Student")["Score"].apply(lambda x: x.iloc[-3:].mean())
Student
Bill 0.513128
Bob 0.342806
Joe 0.469662
Name: Score, dtype: float64
</code></pre>
<p>You can access the last three (or fewer) elements using <code>.iloc[-3:]</code>,... | python|pandas|group-by | 11 |
14,398 | 22,555,056 | TypeError: can't convert expression to float | <p>I am a python newbie. I am trying to evaluate Planck equation using python. I have written a simple program. But when I give input to it is giving me an error. can anyone hep me where I am going wrong? Here is the program and the error:</p>
<p>Program:</p>
<pre><code>from __future__ import division
from sympy.phys... | <p>It seem like you are mixing namespaces, since your are using <code>from ... import *</code>. You wanted to use <code>sympy.exp()</code> but your code uses <code>math.exp()</code>. It is good practice to keep the namespaces separated, i.e. never use <code>from ... import *</code> - it might seem like more typing at ... | python|python-2.7|numpy|scipy|sympy | 10 |
14,399 | 13,424,330 | Python a way to mask two array with different dtype (unit 8 and unit16) | <p>I have 2 arrays: </p>
<p>mask: with value 0 and 1, dtype=uint8</p>
<pre><code>>>> mask
array([[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[1, 1, 1, ..., 0, 0, 0],
...,
[1, 1, 1, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0]], dtype=uint8)... | <p>Am I missing something? This seems as simple as:</p>
<pre><code>prova_clip*mask
</code></pre>
<p>Here's an example:</p>
<pre><code>>>> a = np.arange(10,dtype=np.uint16)
>>> mask = np.ones(10,dtype=np.uint8)
>>> mask[1:3] = 0
>>> a*mask
array([0, 0, 0, 3, 4, 5, 6, 7, 8, 9], dty... | python|arrays|optimization|numpy | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.