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 |
|---|---|---|---|---|---|---|
3,200 | 52,935,668 | What will be the appropriate separator? | <p>I have a text file which has below structure:</p>
<pre><code>>hsa:9934 K04299 purinergic receptor P2Y, G protein-coupled
MINSTSTQPPDESCSQNLLITQQIIPVLYCMVFIAGILLNGVSGWIFFYVPSSKSFIIYL
KNIVIADFVMSLTFPFKILGDSGLGPWQLNVFVCRVSAVLFYVNMYVSIVFFGLISFDRY
>hsa:9934 K04299 purinergic receptor P2Y, G protein-coupled
MINSTST... | <p>you could use str.split('>') so you end up with an array for each value.
Unless '>' might appear in the hashes </p> | python|pandas | 2 |
3,201 | 53,286,009 | Filling in missing data Python | <p>I have a lot of missing data in between years and months of my dataframe that looks like:</p>
<pre><code> Year Month State Value
1969 12 NJ 5500
1969 12 NY 6418
1970 8 IL 10093
1970 12 WI 6430
... | <p>Sorry to all those who took time to correct this. It was a simple matter of accidentally grouping by a false column.</p>
<p>I had previously created a <code>'Region'</code> column based off a collection of the State variables which was called rather than the States themselves.</p>
<p>So to clarify:</p>
<pre><code... | python|python-3.x|pandas|dataframe|missing-data | 1 |
3,202 | 65,905,177 | Retrieving and printing a value from an Access database | <p>I'm trying to retrieve and print a row from an Access database. I want the user to input an ID and a field then a value to be printed.</p>
<p>This is my code so far...</p>
<pre><code>import pypyodbc
import pandas
conn = pypyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Users\Operator\Docum... | <p>I managed to do it but using SQL!</p>
<pre><code>import pandas as pd
import pypyodbc
import sqlalchemy
conn = pypyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Users\Operator\Documents\T31_DB.accdb;')
df = pd.read_sql('SELECT * FROM [TABLE_SIGNAL_ID]', conn)
dfi = df.set_index("signa... | pandas|python-2.7|ms-access|pypyodbc | 0 |
3,203 | 65,803,087 | How to add "OTHER" class in Neural Network? | <p>I have to classify between Real, Fake and Other images but I only have dataset of Real and Fake Faces, how do I add 'other' class, that is neither Real nor Fake face ?</p>
<p>This is how I loaded my dataset</p>
<pre><code>TRAINING_DIR = "Dataset\Training Data"
train_datagen = ImageDataGenerator()
train_gen... | <blockquote>
<ol>
<li>Real Face 2. Fake Face 3. Other Object</li>
</ol>
</blockquote>
<blockquote>
<p>There is this machine learning competition and they told us to add "other" class. and they didn't provide data, so that's why I was asking</p>
</blockquote>
<p>Does this mean you are not allowed to use any ad... | tensorflow|keras|deep-learning|neural-network|conv-neural-network | 1 |
3,204 | 3,069,820 | Ironpython call numpy problem | <p>Ironpython 2.6,
python 2.6.5,
numpy,
SciPy</p>
<pre>
import sys
sys.path.append(r'D:\Python26\dll')
sys.path.append(r'D:\Python26\Lib')
sys.path.append(r'D:\Python26\Lib\site-packages')
» import numpy
Traceback (most recent call last):
File "", line 1, in
File "D:\Python26\Lib\site-packages\numpy\__init__.py"... | <p>From the comments, it looks like <a href="https://stackoverflow.com/questions/3069820/ironpython-call-numpy-problem#comment3161202_3069820">Giles' answer</a> did the trick:</p>
<blockquote>
<p>From looking at the IronPython source, it looks like you'll need to set LanguageSetup.Options["Frames"] = ScriptingRuntim... | python|ironpython|numpy | 0 |
3,205 | 2,674,437 | Adding a numpy array to a scipy.sparse.dok_matrix | <p>I have a <code>scipy.sparse.dok_matrix</code> (dimensions m x n), wanting to add a flat numpy-array with length m.</p>
<pre><code>for col in xrange(n):
dense_array = ...
dok_matrix[:,col] = dense_array
</code></pre>
<p>However, this code raises an Exception in <code>dok_matrix.__setitem__</code> when it tr... | <p>I'm surprised that your unelegant way doesn't have the same problems as the slice way. This looks like a bug to me upon looking at the Scipy code. When you try to set a certain row and column in a dok_matrix to zero when it is already zero, there is be an error because it tries to delete the value at that row and co... | python|numpy|scipy|sparse-matrix | 2 |
3,206 | 63,421,750 | Pytorch Custom data loading with HTTPS is very slow | <p>I tried implementing a custom data loader that will make a web request and will return a sample. My purpose of the program is to see if this idea would be faster than the original data loader. My web server code is run with</p>
<pre><code>srun -n24 --mem = 12g python web.py
</code></pre>
<p>Which will then create 24... | <h2>PyTorch way of distribution</h2>
<p>First of all, you should get yourself acquainted with <a href="https://pytorch.org/docs/master/generated/torch.nn.parallel.DistributedDataParallel.html#distributeddataparallel" rel="nofollow noreferrer">torch.nn.parallel.DistributedDataParallel</a> to see example how to distribut... | python|https|pytorch|basehttpserver | 0 |
3,207 | 63,609,704 | Tabular String data convert to python data | <p>I have a string like this</p>
<pre><code>"""PID TTY TIME CMD
1 ? 00:00:01 systemd
2 ? 00:00:00 kthreadd
3 ? 00:00:00 rcu_gp
4 ? 00:00:00 rcu_par_gp"""
</code></pre>
<p>now I want the data to be like so that i can access it lik... | <p>Use <code>sep="\s+"</code> for separator by whitespace:</p>
<pre><code>from io import StringIO
temp="""PID TTY TIME CMD
1 ? 00:00:01 systemd
2 ? 00:00:00 kthreadd
3 ? 00:00:00 rcu_gp
4 ? 00:00:00 rcu_par_gp"""
df = ... | python|python-3.x|pandas|list | 2 |
3,208 | 63,406,138 | ValueError: Failed to find data adapter that can handle input: <class 'NoneType'>, <class 'NoneType'> in keras model.predict | <p>I have made a CNN model in Keras and saved it as 'model.h5'. It takes an input shape of 128x128. Now, I am in a new file and am trying to make predictions with this model.Here is what I have done so far:</p>
<pre><code>import keras
from keras.preprocessing.image import load_img, img_to_array
from keras.models impor... | <p>You are trying to resize img array after this line:</p>
<p><code>img = img_to_array(img)</code></p>
<p>You might be trying to use reshape the array instead of using resize. If you want to resize the loaded image, you might want to do it before converting it to an array, i.e. before this line:</p>
<pre><code>img = im... | python|tensorflow|keras | 4 |
3,209 | 21,648,654 | Does Scipy Sparse use the (sparse) BLAS library? | <p>Numpy can use one of a number of BLAS libraries (eg. ATLAS, MKL, OpenBLAS etc.).</p>
<p>Does the scipy.sparse matrix module support the sparse BLAS library?</p> | <p>searching the <code>scipy</code> <code>github</code> for <code>sparse BLAS</code> produces a few files like</p>
<p><a href="https://github.com/scipy/scipy/blob/6a4460f68315f0669604054be91ceeacd606f0b6/scipy/sparse/linalg/dsolve/SuperLU/SRC/zsp_blas3.c" rel="nofollow">https://github.com/scipy/scipy/blob/6a4460f68315... | numpy|scipy|sparse-matrix|blas | 2 |
3,210 | 30,224,143 | How to speed up the code - searching through a dataframe takes hours | <p>I've got a CSV file containing the distance between centroids in a GIS-model in the next format:</p>
<pre><code>InputID,TargetID,Distance
1,2,3050.01327866
1,7,3334.99565217
1,5,3390.99115304
1,3,3613.77046864
1,4,4182.29900892
...
...
3330,3322,955927.582933
</code></pre>
<p>It is sorted on origin (<code>InputID<... | <p>IIUC, all you need is <code>pivot</code>. If you start from a frame like this:</p>
<pre><code>df = pd.DataFrame(columns="InputID,TargetID,Distance".split(","))
df["InputID"] = np.arange(36)//6 + 1
df["TargetID"] = np.arange(36) % 6 + 1
df["Distance"] = np.random.uniform(0, 100, len(df))
df = df[df.InputID != df.Ta... | python|csv|python-3.x|pandas | 7 |
3,211 | 53,734,405 | panda convert column to list and add new column | <p>New to Python. I am trying to convert column C to list and add it as extra column D in df.
I tried list() it work for individual raw. But it doesn't work for whole column C in df.
I need hint/help to move forward.</p>
<p>Input </p>
<pre><code>A B C
----------------
1 21 12457643
2 32 34576543
3 41 2... | <p>In general, storing lists in pandas columns is not a very good idea. But if you insist, convert the numbers to strings and then to lists of characters:</p>
<pre><code>df['D'] = df['C'].astype(str).apply(list)
#0 [1, 2, 4, 5, 7, 6, 4, 3]
#1 [3, 4, 5, 7, 6, 5, 4, 3]
#2 [2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>... | python|pandas|multiple-columns | 0 |
3,212 | 53,591,919 | Python Scikit - Learn: Cross Validation with multi-index | <p>Hi I want to use one of the scikit learn's functions for cross validation. What I want is that the splitting of the folds is determined by one of the indexes. For example lets say I have this data with "month" and "day" being the indexes: </p>
<pre><code>Month Day Feature_1
January 1 10
2 ... | <p>This is called splitting by a group. Check out the <a href="https://scikit-learn.org/stable/modules/cross_validation.html#cross-validation-iterators-for-grouped-data" rel="nofollow noreferrer">user-guide in scikit-learn here to understand more about it</a>:</p>
<blockquote>
<p>...</p>
<p>To measure this, we need to ... | python|pandas|scikit-learn | 2 |
3,213 | 20,277,982 | Fastest pairwise distance metric in python | <p>I have an 1D array of numbers, and want to calculate all pairwise euclidean distances. I have a method (thanks to SO) of doing this with broadcasting, but it's inefficient because it calculates each distance twice. And it doesn't scale well.</p>
<p>Here's an example that gives me what I want with an array of 1000 n... | <p>Neither of the other answers quite answered the question - 1 was in Cython, one was slower. But both provided very useful hints. Following up on them suggests that <code>scipy.spatial.distance.pdist</code> is the way to go.</p>
<p>Here's some code:</p>
<pre><code>import numpy as np
import random
import sklearn.met... | python|arrays|numpy|scipy|scikit-learn | 32 |
3,214 | 16,026,181 | Downloading treasury data with Pandas read_csv | <p>I'm trying to download treasury data from <a href="http://www.federalreserve.gov/releases/h15/data.htm" rel="nofollow">this page</a> using Pandas read_csv.</p>
<pre><code>url = "http://www.federalreserve.gov/datadownload/Output.aspx?rel=H15&series=bcb44e57fb57efbe90002369321bfb3f&lastObs=&from=&to=&... | <p>The header is split because of your <code>index_col=0</code> argument. Try without an index column</p>
<pre><code>In [20]: dataframe = read_csv(csvio, header=5, index_col=None, parse_dates=True)
In [21]: dataframe
Out[21]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 13379 entries, 0 to 13378
Data colu... | python|csv|pandas | 1 |
3,215 | 15,734,756 | Is there a "freq" function in numpy/python? | <p>Suppose you have:</p>
<pre><code>arr = np.array([1,2,1,3,3,4])
</code></pre>
<p>Is there a built in function that returns the most frequent element?</p> | <p>Yes, Python's <a href="http://docs.python.org/2.7/library/collections.html#counter-objects" rel="nofollow noreferrer"><em>collections.Counter</em></a> has direct support for finding the most frequent elements:</p>
<pre><code>>>> from collections import Counter
>>> Counter('abracadbra').most_commo... | python|numpy | 13 |
3,216 | 71,883,306 | How to apply regex substitutions to Pandas Series containing string, lists? | <p>I'd like to find a way to apply a regular expression substitution to every element of a Pandas Series where the series may contain strings, lists, or dicts.</p>
<p>The objective would be to replace instances of text matching a specified pattern in a DataFrame column before that column is saved into Google BigQuery.<... | <p>What you could do is:</p>
<ul>
<li>transform your dataframe to csv</li>
<li>replace the strings you need by exploiting string context</li>
<li>get back your dataframe</li>
</ul>
<p>Here's a quick snippet that does replace strings within dictionaries by taking into account keys as a context:</p>
<pre><code>import io
... | python|regex|pandas | 0 |
3,217 | 71,866,069 | Grouping a grouped dataframe in a nested loop | <p>I have a scenario where I have to group a dataframe by a column and again group the resulting dataframe using a different column. The reason I am iteratively grouping is because its easier for me to sack the results to a different dataframe. So the way I am trying to do is</p>
<pre><code>g=df.groupby(col1):
for a,b... | <p>We can't know with what you've given us, but your code should work fine... it does for me.</p>
<pre><code>df = pd.DataFrame({'EmployeeNo':[11111,11112,11113,11115,11116,11128],
'OutletName':['Outlet1', 'Outlet2', 'Outlet3','Outlet4', 'Outlet5','Outlet6'],
'EmployeeName':['John',... | pandas|pandas-groupby | 2 |
3,218 | 18,922,604 | Convolve an RGB image with a custon neighbout kernel using Python and Numpy | <p>I'm trying to implement an algorithm to verify the 4 neighbout (up, down, left and right) pixels of an RGB image, if all pixel RGB values are equal I mark an pixel in the output image as 1, otherwise it will be 0. The non vectorized implementation is:</p>
<pre><code>def set_border_interior(img):
img_rows = img.sh... | <p>Leaving the border aside, where your function is not well defined anyway, you could do the following:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
rows, cols = 480, 640
rgb_img = np.zeros((rows, cols, 3), dtype=np.uint8)
rgb_img[:rows//2, :cols//2] = 255
center_slice = rgb_img[1:-1, 1:-1]
le... | python|image|numpy|scipy | 4 |
3,219 | 22,178,439 | Variable changes value without changing it at all in the program | <p>The numpy array <code>pos_0</code> changes its value without anything happening to it in the program.</p>
<p>Relevant steps:</p>
<ol>
<li>I assign a value to <code>pos_0</code></li>
<li>I set <code>pos=pos_0</code></li>
<li>I change <code>pos</code> (in a while loop)</li>
<li>I print both <code>pos</code> and <cod... | <p>Once you do <code>pos = pos_0</code>, changing <code>pos</code> changes <code>pos_0</code> because numpy arrays much like lists are mutable.</p>
<p>Here's a simplified example:</p>
<pre><code>>>> a = [1, 2, 3]
>>> b = a
>>> b.append(4)
>>> b
[1, 2, 3, 4]
>>> a
[1, 2, 3,... | python|variables|numpy|while-loop|physics | 1 |
3,220 | 22,240,749 | Make all columns (dates) index of data frame | <p>My data is organized like this: </p>
<p><img src="https://i.stack.imgur.com/CUTRI.png" alt="enter image description here"></p>
<p>Where country code is the index of the data frame and the columns are the years for the data. First, is it possible to plot line graphs (using matplotlib.pylot) over time for each coun... | <ol>
<li><p>Transpose using <code>df.T</code>.</p></li>
<li><p>Plot as usual.</p></li>
</ol>
<p>Sample:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({1990:[344,23,43], 1991:[234,64,23], 1992:[43,2,43]}, index = ['AFG', 'ALB', 'DZA'])
df = df.T
df
AFG ALB DZA
1990 344 23 43
1991 234 64 23
19... | python|pandas|matplotlib|dataframe | 1 |
3,221 | 55,435,006 | fit method in keras (shape of the array) | <p>While compiling my code in the fit transform method it is showing an error about the shape of the array
"
ValueError: Error when checking input: expected dense_1_input to have shape (6,) but got array with shape (11,)"</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset... | <p>The discrepency is in <code>x_train</code> and possibly <code>x_test</code>. If you look at <code>print(x_train.shape)</code> you'll probably get something like <code>(N, 11)</code> where N is the number of samples each containing 11 features. But wait, your model is defined to have 6 <code>input_dim</code> features... | python|numpy|tensorflow|keras|neural-network | 0 |
3,222 | 55,305,171 | What does it mean to order the eigen vectors? | <p>I was working on a task that required me to compute the <a href="https://en.wikipedia.org/wiki/Eigenface" rel="nofollow noreferrer">Eigenfaces</a>. To compute the Eigenfaces, it is required to compute the <a href="https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors" rel="nofollow noreferrer">Eigenvalues and E... | <p>They are ordered by eigenvalue magnitude in ascending order, just as the documentation explains:</p>
<pre><code>print(eigen_val)
array([[-0.65484945, 0.53345853, 1.2783374 ],
[-0.54451155, 0.23566298, 1.32844171],
[-0.11539487, 0.49887717, 1.55005921]])
</code></pre>
<p>The eigenvalues with th... | python|numpy|opencv|image-processing|computer-vision | 0 |
3,223 | 55,233,243 | Effective way to compare 1d and a 2d series in python | <p>I have a data frame with one column as an array of strings and the 2nd column as one string value.</p>
<pre><code>a = pd.Series([["a","b","c", "d"],["a","b","c", "d"],["a","b","c", "d"],["a","b","c", "d"],["a","b","c", "d"]])
b = pd.Series(["a","d","e", "c", "b"])
</code></pre>
<p>i wish to check whether b is con... | <p><code>pandas.Series</code> implements the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.combine.html" rel="nofollow noreferrer">combine</a> method which you could use in the following way to find the elements in <code>b</code> that also appear in the <code>a</code> lists:</p>
<pr... | python|string|pandas|numpy|series | 1 |
3,224 | 7,445,769 | Cython numpy array indexing | <p>I am trying to speed up some python code with cython, and I'm making use of cython's <code>-a</code> option to see where I can improve things. My understanding is that in the generated html file, the highlighted lines are ones where python functions are called - is that correct?</p>
<p>In the following trivial fun... | <p>The answer is that the highlighter fools the reader.
I compiled your code and the instructions generated under the highlight are those needed
to handle the error cases and the return value, they are not related to the array assignment.</p>
<p>Indeed if you change the code to read :</p>
<pre><code>def foo(numpy.nda... | python|arrays|indexing|numpy|cython | 5 |
3,225 | 56,451,588 | How to select Image URL by not including "/"? | <p>I'm trying to figure out how to Series.str.extract() the image Urls (image-image-image.jpg) to a new column, but i'm having issues with the Regex. What am I doing wrong ?</p>
<p><strong>Here's how my data looks</strong></p>
<pre><code><a href="https://website.com/wp-content/uploads/2018/09/image-image.image.jpg... | <p>A little more exhaustive solution: </p>
<pre><code>https?:\/\/[A-z0-9-_.\/%]+\/([A-z0-9-_.%]+?\.(png|jpe?g|png))
</code></pre>
<p>It seems a bit scary but it is a little more verbose and supports encoded URLs too. You can find the name of your image in the first matched group($1).</p> | regex|python-3.x|pandas|regex-negation | 1 |
3,226 | 56,496,513 | How to add values in one array according to repeated values in another array? | <p>Suppose I have an array:</p>
<pre><code>Values = np.array([0.221,0.35,25.9,54.212,0.0022])
Indices = np.array([22,10,11,22,10])
</code></pre>
<p>I would like to add elements of 'Values' together that share the same number in 'Indices'.</p>
<p>In other words, my desired outputs(s):</p>
<pre><code>Total = np.array... | <p>We can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow noreferrer"><code>np.unique</code></a> with its optional arg <code>return_inverse</code> to get IDs based on uniqueness within <code>Indices</code> and then use those with <code>bincount</code> to get binned (ID... | python|arrays|numpy|sorting | 4 |
3,227 | 56,591,069 | Clean up this int64 variable in python | <p>This is the raw distribution of the var FREQUENCY</p>
<pre><code>NaN 22131161
1.0 4182626
7.0 218343
3.0 145863
1 59432
0.0 29906
2.0 28129
4.0 15237
5.0 4553
8.0 3617
3 2754
7 2635
9.0 633
2 584
4 276
0 ... | <p>The first issue "
group 1.0 should be the same as 1. I wrote df['x']=df['x].replace({'1.0:'1'}). it does not change anything. 9.0 vs 9, 3.0 vs.3 have same symptom"
was fixed once I add dtype={'FREQUANCY':'object'} while reading the csv file. Group 1.0 collapsed with group 1... After than replace works just fine. </p... | python|pandas|replace|recode|int64 | 0 |
3,228 | 25,942,217 | Cannot install Pandas on Python 3.4.1 on Windows 8 | <p>I downloaded version 0.14.0 of pandas and try to import it, but it says that I am missing <code>dateutil</code>. I can't figure out what I'm doing wrong. I'm using Python version 3.4.1</p>
<p>Download: <a href="https://pypi.python.org/pypi/pandas/0.14.0/" rel="nofollow">https://pypi.python.org/pypi/pandas/0.14.0/... | <p>I am using Anaconda and still get this error after updating pandas to latest version using <code>conda update pandas</code>.
Help?</p>
<pre><code>C:\Anaconda3>conda info
Current conda install:
platform : win-64
conda version : 3.8.3
conda-build version : 1.8.2
python version : 3.4.... | pandas|python-3.4|python-dateutil | 1 |
3,229 | 66,903,255 | Retrieve values from Scipy gaussian_kde | <p>It's the first time I'm using Scipy because I couldn't find many libraries that could generate KDE data directly without plotting beforehand like what <em>Pandas</em> does (data.plot(kind='kde').
I'm trying to get the data in the KDE as a list or array but it's referring to the scipy object <strong><scipy.stats.k... | <p>One you have estimated the density</p>
<pre><code>kde = stats.gaussian_kde(data)
</code></pre>
<p>you need to evaluate the density in the range of data (or a wider range, you can choose)</p>
<pre><code>evaluated = kde.evaluate(np.linspace(data.min(), data.max(), 100))
</code></pre>
<p>Let's try</p>
<pre><code># gene... | python|numpy|scipy | 3 |
3,230 | 66,798,585 | Find value from string using the characters from list Using Python | <p>I have been working on an Excel sheet using python, where i have to extract only the specific value from the column, using an list with set of charaters.</p>
<p>Need to check every character from the column check with the list, If it matches need to return the matched value into the dataframe which can be used for f... | <p>You can use</p>
<pre class="lang-py prettyprint-override"><code>df['country_list'] = df['text_value'].str.findall(r'(?i)\b(?:{})\b'.format('|'.join(countries)))
</code></pre>
<p>Here, <code>Series.str.findall</code> returns all matches found in each cell in the <code>country_list</code> column, and the pattern, that... | python|regex|pandas | 1 |
3,231 | 68,118,646 | What is the purpose of optimizer's state_dict in PyToch Big Graph's embedding dataset? | <p>The documentation for PyTorch Big Graph (PBG) states that "An additional dataset may exist, optimizer/state_dict, which contains the binary blob (obtained through torch.save()) of the state dict of the model’s optimizer." When inspecting this dataset, it seems to be stored as an array of bytes. Could someo... | <blockquote>
<p>Could someone conceptually explain the point of state_dict</p>
</blockquote>
<p>If you know about Adam or SGD's momentum you probably know that there're some parameters in the optimizer that change in every step. When resume training on top of loading the model weights it'll make convergence faster if y... | python|pytorch|bigdata|data-science|h5py | 1 |
3,232 | 68,403,672 | Turn MultiIndex Series into pivot table design by unique value counts | <pre><code>Sample Data:
Date,code
06/01/2021,405
06/01/2021,405
06/01/2021,400
06/02/2021,200
06/02/2021,300
06/03/2021,500
06/02/2021,500
06/03/2021,300
06/05/2021,500
06/04/2021,500
06/03/2021,400
06/02/2021,400
06/04/2021,400
06/03/2021,400
06/01/2021,400
06/04/2021,200
06/05/2021,200
06/02/2021,200
06/06/2021,300
... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unstack.html" rel="nofollow noreferrer"><code>Series.unstack</code></a>:</p>
<pre><code>df = df.groupby(by="Date",)['code'].value_counts().unstack(fill_value=0)
</code></pre> | pandas|pandas-groupby | 1 |
3,233 | 68,435,630 | Python Numpy polyfit row index as x? | <p>I'm trying to calculate a best fit single order regression, because I would like to get the slop.</p>
<p>How can I use the data row index as x?</p>
<pre><code>import pandas as pd
import numpy as np
import json
data1 = [("Temp"),
(101),
(103),
(104),
(101)
]
df1 = p... | <p>There are some problems with your dataframe. You should definitely preprocess your data first. For example, in this case, the 'Temp' in your <code>df1</code> are all <code>objects</code>, whereas we want them to be numeric (int or floats). Let's fix that first.</p>
<pre><code>data1 = [("Temp"), (101), (103... | python|pandas|numpy | 0 |
3,234 | 68,156,710 | Row wise calculations in Python and add them to the dataframe in pandas | <p>I have a DataFrame:</p>
<pre><code>df_IJR
Out[40]:
Date Close
0 2015-01-02 56.610001
1 2015-01-05 55.744999
2 2015-01-06 54.814999
3 2015-01-07 55.384998
4 2015-01-08 56.355000
</code></pre>
<p>How do I perform row wise calculation in a loop.
For Example.</p>
<pre><code>fo... | <p>DataFrames have vectorized operations that are more performant and easier to read than iterative solutions.</p>
<pre class="lang-py prettyprint-override"><code>df_IJR['Shares'] = df_IJR['Capital'] / df_IJR['Close']
</code></pre>
<p>If I understand your code correctly, this will have the same effect. The value in the... | python-3.x|pandas|dataframe | 0 |
3,235 | 68,237,952 | Problem with Tensorflow GPU-anyone knows how to solve it? | <p>I have a Problem and I don't know what to do, has anyone expirienced this problem or knows what to do? I want to use my GPU, but it is using my CPU. I have a RTX 2060 CUDA 11.4 and the cudNN version for it. Everything is set up and installed.
heres my "error" message:</p>
<pre><code>2021-07-03 18:04:08.192... | <p><a href="https://www.jquery-az.com/3-ways-convert-python-list-string-join-map-str/" rel="nofollow noreferrer">List</a> physical devices ( and print number of physical devices ) using <a href="https://www.tensorflow.org/api_docs/python/tf/config/list_physical_devices" rel="nofollow noreferrer">https://www.tensorflow.... | python|tensorflow | 0 |
3,236 | 68,200,045 | How to compare two dataframes with different indices, and print out the duplicate rows? | <p>I am attempting to compare two dataframes by their respective UniqueID column. The code for the following dataframes can be seen below.</p>
<pre><code># Define first dataframe
list1 = {'UniqueID': [13579, 24680, 54678, 1169780, 1195847, 23572],
'Name': ['Joe', 'Pete', 'Jessica', 'Jackson', 'Griffin', 'Katie'... | <p><strong>Update</strong> according your comment:</p>
<blockquote>
<p>After I find the duplicated, I would then like to iterate through each cell of level, and update df1 from the updated level listed in df2. For example, Joe goes from beginner to intermediate from df1 to df2. I would like to auto update those instanc... | python|pandas|numpy | 1 |
3,237 | 59,078,615 | Python itertools groupby with aggregate | <p>I am trying to group on a column based on the sequence it appears (timestamp) and simultaneously finding aggregate (mean) on the other variables within the small group. I can successfully group it but unable to aggregate</p>
<p>Here is my sample input:</p>
<pre><code>Date T/F X1
12/02/19 T 10
12/02/19 ... | <p>You can use the function <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a>:</p>
<pre><code>df1 = df.assign(Count=np.nan).\
groupby(df['T/F'].ne(df['T/F'].shift()).cumsum(), as_index=False).\
agg({'Date': 'first', 'T/... | python|pandas|itertools | 3 |
3,238 | 45,201,552 | Keras does not show progress bar arrow while training | <p>At first, I was running keras with tensorflow backend, and the progress bar was fine. Then I installed Theano, and tried using it for a while before switching back to tensorflow. After installation of Theano, the progress bar that appears at each epoch only comes up as after the epoch is done, so while it's training... | <p>Try using: </p>
<pre><code> model.fit(.....,.....,....,verbose=1)
</code></pre>
<p>The verbose variable is used for showing training progress. You can look at the Keras documentation:</p>
<blockquote>
<p>verbose: 0 for no logging to stdout, 1 for progress bar logging, 2 for one log line per epoch.</p>
</blockqu... | tensorflow|keras|theano | 9 |
3,239 | 45,239,256 | Data imputation with fancyimpute and pandas | <p>I have a large pandas data fame <code>df</code>. It has quite a few missings. Dropping row/or col-wise is not an option. Imputing medians, means or the most frequent values is not an option either (hence imputation with <code>pandas</code> and/or <code>scikit</code> unfortunately doens't do the trick). </p>
<p>I ca... | <p>Add the following lines after your code:</p>
<pre><code>df_filled.columns = df_numeric.columns
df_filled.index = df_numeric.index
</code></pre> | python|python-3.x|pandas|imputation|fancyimpute | 7 |
3,240 | 56,895,836 | I am having a problem with a foor loop that includes dataframes | <p>I have a dataframe with 8 columnds. If two of those columns satisfy a condition, I have to fill two columns with the product of other two. And after running the algorithm it is not working.</p>
<p>I have tryed to use series, I have tryed to use import warnings
<code>warnings.filterwarnings("ignore")</code> but it i... | <p>You can use vectorized condition function <code>numpy.select()</code> to do this quickly:</p>
<pre><code>import pandas as pd
from numpy.random import randn, randint
n = 10
df_data = pd.DataFrame(dict(trade=randint(0, 2, n),
z=randn(n),
Close1=randn(n),
... | pandas|dataframe|for-loop|operation | 0 |
3,241 | 57,257,230 | Replace value with earliest date time record for dataframe | <p>The dataframe with monthly date is as below, and I would like to get the earliest Startdate to fill the column Startdate(including NA) for every month.</p>
<pre><code>ID Month Startdate
a 2019-05-01 NA
a 2019-06-01 2019-04-01
a 2019-07-01 2019-05-01
b 2019-05-0... | <p>IIUC, you want <code>startdate</code> to be the earliest in the record:</p>
<pre><code># change to datetime if not already is
df['Month'] = pd.to_datetime(df['Month'])
df['Startdate'] = pd.to_datetime(df['Startdate'])
# update min
df['Startdate'] = df.groupby('ID').Startdate.transform('min')
</code></pre>
<p>outp... | python-3.x|pandas | 2 |
3,242 | 57,059,709 | Selection in dataframe with array as column value | <p>I have a dataframe filled with twitter data. The columns are:</p>
<ul>
<li>row_id : Int</li>
<li>content : String</li>
<li>mentions : [String]</li>
<li>value : Int</li>
</ul>
<p>So for every tweet I have it's row id in the dataframe, the content of the tweet, the mentions used in it (for example: '@foo') as an arr... | <p>Let's call your DataFrame df.</p>
<p>For the first task you use:</p>
<pre><code>result = df[(Dataframe(df['mentions'].tolist()) == '@foo').any(1)]
</code></pre>
<p>Here, the <code>Dataframe(df['mentions'])</code> creates a new DataFrame where each column is a mention and each row a tweet.</p>
<p>Then <code>== '@... | python|pandas|data-science | 1 |
3,243 | 57,269,160 | Pythonic way to extract and replace text in Dataframe | <p>I have a dataframe containing user-submitted postcodes, many of which aren't in the desired format I need to look them up with the Google Maps Geocoder API to get associated co-ordinates. </p>
<p>I have thus attempted to format it to return them in the format like 'IG1 2BF', 'E6 2QA', 'RH10 4DG'. </p>
<p>This work... | <p>Not sure about this being "pythonic", but seeing as the second block of UK postcodes is always made up of 3 characters, you can just slice the string using that fact:</p>
<pre><code>def format_postcode(postcode):
postcode = postcode.replace(" ", "").upper()
return "{} {}".format(postcode[:-3], postcode[-3:]... | python-3.x|pandas|postal-code | 2 |
3,244 | 56,944,896 | Finding all variations of a list of substrings in a pandas dataframe column | <p>I have a list of strings of movie names which I want to search in a pandas dataframe column <code>description</code> and make a new column <code>movie_name</code> if it is found in the description entered by a user.</p>
<p>Now, since the descriptions are not standardised, how can I search all the possible variation... | <p>I suggest you take a look at the FuzzyWuzzy library. </p>
<p>Here is an easy to understand article: <a href="https://www.geeksforgeeks.org/fuzzywuzzy-python-library/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/fuzzywuzzy-python-library/</a> </p> | python|string|pandas|list | 0 |
3,245 | 45,767,186 | Pandas pivot table value loop | <p>I have a dataset with dates and data points for that specific date (d1, d2, d3, etc.) for every stock for each country. Some datapoints are missing for some stocks within each country and I want to replace them with average for those stocks in other countries</p>
<pre><code>date stock d1 d2 d3 country
12.94 x... | <p>I'm not exactly sure if this is what you are looking for. But you can iterate over all the NaN columns and then the missing value rows and substitute the missing values using numpy.mean and conditional pandas slicing:</p>
<p>convert list into a pandas dataframe:</p>
<pre><code>df = pd.DataFrame(dt[1:], columns=dt[... | python|pandas | 0 |
3,246 | 46,062,169 | array = np.int(array) TypeError: only length-1 arrays can be converted to Python scalars | <pre><code>array = df.as_matrix()
array = np.int(array)
</code></pre>
<p>I tried:</p>
<pre><code>array = np.int(array)
</code></pre>
<p>for :</p>
<pre><code>array[i][10]/5
</code></pre>
<p>but got :</p>
<blockquote>
<p>array = np.int(array) TypeError: only length-1 arrays can be converted to Python scalars????<... | <p>Try:</p>
<pre><code>>>> a = np.random.normal(20, 5, size=(2,2))
array([[ 24.04255462, 24.24954137],
[ 14.64894245, 16.17946985]])
>>> a = a.astype(int)
>>> a
array([[24, 24],
[14, 16]])
</code></pre>
<p>Check the <a href="https://docs.scipy.org/doc/numpy/reference/generat... | python-2.7|numpy|math | 1 |
3,247 | 35,684,121 | Getting Large Dataset Out of MySQL into Pandas Dataframe keeps Failing , Even With Chunksize | <p>I am trying to pull ~700k rows out of mysql into a Pandas dataframe.</p>
<p>I kept getting the same error over and over again:</p>
<p>Traceback (most recent call last):</p>
<blockquote>
<p>File "C:\Anaconda3\lib\site-packages\mysql\connector\network.py", </p>
<p>line 245, in recv_plain read = self.sock.rec... | <p>It sounds like you have a short time out period and are probably lacking appropriate indexes. I would suggest creating an index on <code>(a, b, c, d)</code>:</p>
<pre><code>create index idx_table_a_b_c_d on table(a, b, c, d);
</code></pre>
<p>This needs to be executed only once in the database (and that can be do... | python|mysql|pandas | 1 |
3,248 | 35,598,490 | How to edit source csv file data using pandas | <p>I have a csv file that contains large amount of data,but the data that contained in csv file is not cleaned.The example of csv data is as follows</p>
<pre><code>country branch no_of_employee total_salary count_DOB count_email
x a 30 2500000 20 ... | <p>You can call the vectorised <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html" rel="nofollow"><code>str.strip</code></a> to trim leading and trailing whitespaces:</p>
<pre><code>df['country'] = df['country'].str.strip(' ')
</code></pre>
<p>So the above should work to clean... | python|pandas | 3 |
3,249 | 28,745,909 | Neither builtin power function nor np.power works | <p>I've got the following simple two things given:</p>
<pre><code>n = 2.01
array = np.array([-0.3700708 , -0.41282227, -0.25959961])
</code></pre>
<p>Now I want each of the array elements to be raised to the power of <code>(n-1.)</code>. So I tried the following:</p>
<pre><code>>>> array**(n-1.)
array([ nan... | <p>The reason is that the results are <em>complex values</em>, e.g. </p>
<pre><code> -0.3700708 ** 1.01 == -0.366229 - 0.011509i
</code></pre>
<p>Edit: When computing the value at <strong>Wolfram Alpha</strong> do (raise negative into power)</p>
<pre><code> (-0.3700708) ** 1.01
</code></pre>
<p>and not (first ra... | python|numpy | 3 |
3,250 | 51,070,345 | Sklearn vectoring a document by sentences for classification | <pre><code>temp = []
for i in chunks:
vectorizer2 = CountVectorizer()
vectorizer2.fit_transform(i).todense()
temp.append(vectorizer2)
print(vectorizer2.vocabulary_)
x = [LinearSVC_classifier.classify(y) for y in temp ]
</code></pre>
<p>I have a document that I am trying to put in the proper format to ... | <p>Just put the initialization outside the loop like this, else it will be re-initilized again and again for each sentence seperately which is incorrect.</p>
<pre><code>temp = []
vectorizer2 = CountVectorizer() #<--- This needs to be initialized only once
for i in chunks:
vectorizer2.fit_transform(i).todense... | python|scikit-learn|nlp|classification|sklearn-pandas | 1 |
3,251 | 50,809,257 | Returning dataset from tf.data.Dataset.map() causes 'TensorSliceDataset' object has no attribute 'get_shape' error | <p>I'm using the Dataset API to create an input pipeline. I'm using the tf.data.Dataset.map() method in a pattern similar to the following:</p>
<pre><code>def mapped_fn(_):
X = tf.random_uniform([3,3])
y = tf.random_uniform([3,1])
dataset = tf.data.Dataset.from_tensor_slices((X,y))
return dataset
wit... | <p><a href="https://stackoverflow.com/a/50811745/3574081">DomJack's answer</a> is absolutely correct about the signature of <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#map" rel="nofollow noreferrer"><code>Dataset.map()</code></a>: it expects the return value of the passed <code>mapped_fn</code> ... | tensorflow|machine-learning|deep-learning|tensorflow-datasets | 3 |
3,252 | 51,012,920 | Keras "return_sequences" option returns 2D array instead of 3D | <p>I'm trying to use a simple character-level Keras model for extract key text from a sentence. </p>
<p>I feed it <code>x_train</code> a padded sequence of dim <code>(n_examples, 500)</code> representing the entire sentence and <code>y_train</code>, a padded sequence of dim <code>(n_examples, 100)</code> representing ... | <p>It isn't complaining about the input to <code>TimeDistributed</code> but the target <code>y_train.shape == (n_examples, 100)</code> which isn't 3D. You have a mismatch between predicting a sequence and a single point. In other words, <code>outputs</code> is 3D but <code>y_train</code> is 2D.</p> | tensorflow|neural-network|keras|nlp | 1 |
3,253 | 50,921,288 | Sort Dict by order in list (python) | <p>I'm trying to convert a <code>dict</code> into an ordered <code>df</code>. The <code>dict</code> represents a <code>scatter plot</code>, which displays the coordinates in various <code>bins</code>. </p>
<p>Lets say <code>x,y lists</code> are as follows:</p>
<pre><code>x = [10,40,33,44,66,77,33,44,55,2]
y = [1,4,5... | <p><em>skipping over the pandas part</em></p>
<p><code>b = collections.OrderedDict(bins) #Resort by order in list</code></p>
<p>collections.OrderedDict does not sort the value given in the constructor. it simply preserves the order in which the dict was created.</p>
<p>if you need to re-order the dict and preserve t... | python|pandas|dictionary|ordereddictionary | 1 |
3,254 | 20,473,005 | OpenCV detect if image file is colour prior to loading | <p>I know you can use imread to get an image into a numpy array.</p>
<pre><code>cv2.imread(path,0)
</code></pre>
<p>Loads a greyscale image and...</p>
<pre><code>cv2.imread(path,1)
</code></pre>
<p>Loads a colour one.</p>
<p>I can call the second one on a greyscale image and it returns a shape (y,x,3) hence it is... | <p>I assume your are using Python since you mentioned numpy.</p>
<p>You can´t check which type an image has before loading it.</p>
<p>The easiest solution to guarantee that you have a grayscale image, would be to use something like this (if you want to always have a grayscale):</p>
<pre><code> if len(im.shape... | python|opencv|numpy | 2 |
3,255 | 20,726,493 | Python Pandas qcut behavior with # of observations not divisible by # of bins | <p>Suppose I had a pandas series of dollar values and wanted to discretize into 9 groups using <code>qcut</code>. The # of observations is not divisible by 9. SQL Server's <code>ntile</code> function has a standard approach for this case: it makes the first <em>n</em> out of 9 groups 1 observation larger than the re... | <p>The <code>qcut</code> behaves like this because it's more accurate. Here is an example:</p>
<p>for the <em>i</em>th level, it starts at quantile (<em>i</em>-1)*10%:</p>
<pre><code>import pandas as pd
import numpy as np
a = np.random.rand(26*10+3)
r = pd.qcut(a, 10)
np.bincount(r.labels)
</code></pre>
<p>the outp... | python|pandas|ranking-functions | 2 |
3,256 | 20,532,621 | Pandas import error when debugging using PVTS | <p>I am dealing with a very silly error, and wondering if any of you have the same problem. When I try to import pandas using <code>import pandas as pd</code> I get an error in copy.py. I debugged into the pamdas imports, and I found that the copy error is thrown when pandas tries to import this: <br> <code>from pandas... | <p>This is a limitation of the way PTVS detects unhandled exceptions - it can't see the except-block that's going to catch this exception because it is in the code that is eval'd from a string. See the <a href="https://pytools.codeplex.com/workitem/2077">bug in the tracker</a> for more details.</p>
<p>As a workaround,... | python|python-2.7|visual-studio-2012|pandas|ptvs | 5 |
3,257 | 20,435,432 | ValueError and odepack.error using integrate.odeint() | <p>I'm trying to write an equation to model and then plot an integral control system (specifically regarding cruise control). However I'm receiving two errors whenever I run it:</p>
<p>ValueError: object too deep for desired array
odepack.error: Result from function call is not a proper array of floats.</p>
<p>I've r... | <p>Posting this as separate, because I got your code to work. Well, to run and produce output :P</p>
<p>Actually one big problem is some stealth broadcasting that I didn't notice, but I changed a lot of other things along the way.</p>
<p>First the stealth broadcasting is that if you integrate a 1d function with one ... | python|arrays|numpy|odeint | 1 |
3,258 | 33,451,800 | Decimal to binary Half-Precision IEEE 754 in Python | <p>I was only able to convert a decimal into a binary single-precision IEEE754, using the <code>struct.pack</code> module, or do the opposite (float16 or float32) using <code>numpy.frombuffer</code></p>
<p>Is it possible to convert a decimal to a binary half precision floating point, using Numpy?</p>
<p>I need to pri... | <blockquote>
<p>if I type "117.0", it should print "0101011101010000"</p>
</blockquote>
<pre><code>>>> import numpy as np
>>> bin(np.float16(117.0).view('H'))[2:].zfill(16)
'0101011101010000'
</code></pre>
<p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.view.html" re... | python|numpy|floating-point|precision|ieee-754 | 12 |
3,259 | 9,155,478 | How to try-except an illegal matrix operation due to singularity in NumPy | <p>In NumPy, I'm trying to use <code>linalg</code> to compute matrix inverses at each step of a Newton-Raphson scheme (the problem size is small intentionally so that we can invert analytically computed Hessian matrices). However, after I get far along towards convergence, the Hessian gets close to singular.</p>
<p>Is... | <p>The syntax would be like this:</p>
<pre><code>import numpy as np
try:
# your code that will (maybe) throw
except np.linalg.LinAlgError as err:
if 'Singular matrix' in str(err):
# your error handling block
else:
raise
</code></pre> | python|numpy|linear-algebra | 51 |
3,260 | 66,349,979 | How to fillna limited by date in a groupby | <p>I am working with the following Dataframe that has some NaN values inside.</p>
<pre><code>df = pd.DataFrame({'day':[pd.datetime(2020,1,1),pd.datetime(2020,1,3),pd.datetime(2020,1,4),pd.datetime(2020,1,5),pd.datetime(2020,1,6),pd.datetime(2020,1,7),pd.datetime(2020,1,8),pd.datetime(2020,1,8),pd.datetime(2020,6,9)],
... | <p>You can <code>group</code> the dataframe on columns <code>Security</code> and <code>ID</code> along with an additional <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Grouper.html" rel="nofollow noreferrer"><code>grouper</code></a> for column <code>day</code> with frequency set to <code>60... | python|pandas|group-by|fillna | 1 |
3,261 | 66,588,116 | Why does the `title_text` argument of `fig.update_layout` appear not to be working for Plotly table in Jupyter? | <p>I'm showing a Pandas DataFrame in a Plotly Figure Factory table, and the arguments in <code>fig.update_layout</code> are all working as expected except for <code>title_text</code> (example <a href="https://plotly.com/python/figure-factory-table/" rel="nofollow noreferrer">here</a>).</p>
<pre><code>import pandas as p... | <p>You may need to adjust the margins of the plot.
A similar issue was tagged on github: <a href="https://www.github.com/plotly/plotly.py/issues/2795" rel="nofollow noreferrer">https://www.github.com/plotly/plotly.py/issues/2795</a>.</p>
<p>The solution: <code>fig.update_layout({'margin': {'t': 50}})</code>. This means... | python|pandas|jupyter-notebook|plotly|jupyter-lab | 1 |
3,262 | 66,481,456 | Creating loop that pulls back every three months until 6 months are pulled - Python | <p>How can I create a loop to print every 3 months ago until it gives me back 6 months? For example, I want the loop to pull back dates like this 202012, 202009, 202006, 202003, 201912, 201909, essentially skipping every 3 until it does it for 6 times.</p> | <p>Assuming that when you say 'gives me back 6 months' you mean generates 6 different months, including the starting month:</p>
<pre><code>import datetime
import dateutil.relativedelta
date = datetime.datetime.strptime("202003", "%Y%m")
delta = dateutil.relativedelta.relativedelta(months=3)
print(... | python|pandas|dataframe|loops | 2 |
3,263 | 66,628,140 | Python pandas to_csv issue | <p>I am running python program which takes csv data as string, need to sort it and return output as string</p>
<p>input= "Bet,Charle,Daniell,Ada,Eri\n17945,10091,10088,3907,10132\n2,12,13,48,11"</p>
<p>desired output = "Ada,Bet,Charle,Daniell,Eri\n3907,17945,10091,10088,10132\n48,2,12,13,11"</p>
<pr... | <p>Here is an implementation that avoids using <code>pandas</code>, and allows for the ability to sort by different columns. Once you break your input string into a list of lists, your specified sorting column (i.e. the list you want to use to sort from your list of lists) is sorted whilst keeping note of the original ... | python|pandas | 2 |
3,264 | 16,189,386 | Random bits array by given probabilities with numpy | <p>I have a deterministic neural network and I want to make it stochastic.</p>
<p>Two questions:</p>
<ol>
<li>I'm not sure if it means that I need to use the result of the sigmoid to determine the probabilities for the output, or if the probabilities are simply the neurons input, and a sigmoid function is now redunda... | <ol>
<li>The sigmoid function is still required, as the backpropagation works on computing the derivative of the sigmoid function, and not whether or not the neuron fired.</li>
<li><p>After computing the activation as before, I now run the result array x through this: </p>
<p><code>return numpy.random.ranf(x.shape) &l... | numpy|neural-network|stochastic-process | 0 |
3,265 | 57,496,285 | Why is the memory in GPU still in use after clearing the object? | <p>Starting with zero usage:</p>
<pre><code>>>> import gc
>>> import GPUtil
>>> import torch
>>> GPUtil.showUtilization()
| ID | GPU | MEM |
------------------
| 0 | 0% | 0% |
| 1 | 0% | 0% |
| 2 | 0% | 0% |
| 3 | 0% | 0% |
</code></pre>
<p>Then I create a big enough te... | <p>It looks like PyTorch's caching allocator reserves some fixed amount of memory even if there are no tensors, and this allocation is triggered by the first CUDA memory access
(<code>torch.cuda.empty_cache()</code> deletes unused tensor from the cache, but the cache itself still uses some memory).</p>
<p>Even with a ... | python|memory-leaks|garbage-collection|gpu|pytorch | 15 |
3,266 | 57,374,871 | How to create a New column variable with the data from all other columns using Pandas | <p>I am working on a Data set, and want to create a new variable column with all the columns which are present in data set:</p>
<p><a href="https://i.stack.imgur.com/2tJwA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2tJwA.jpg" alt="enter image description here"></a></p>
<p>I want to make a new ... | <pre class="lang-py prettyprint-override"><code> import pandas as pd
data = pd.DataFrame(
{'Date':['10/2/2011', '11/2/2011', '12/2/2011','13/2/2011'],
'Event':['Music', 'Poetry', 'Theater', 'Comedy'],
'Cost':[10000, 5000, 15000, 2000]})
data... | pandas | 1 |
3,267 | 57,606,801 | pandas style options to latex | <p>Pandas has two nice functionalities I use a lot - that's the <code>df.style...</code> option and the <code>df.to_latex()</code> call. But I do not know how to combine both.</p>
<p>The .style option makes looking at tables much more pleasant. It lets you grasp information rapidly because of visual enhancements. Thi... | <p>Instead of trying to export this formatting to bulky LaTeX markup, I would go the route explored already over in TeX.SE: add the functionality as LaTeX code that draws similar formatting based on the same data.</p>
<ul>
<li>Red/green value bars:<br>
<a href="https://tex.stackexchange.com/questions/81994/partially-c... | python|pandas|dataframe|latex | 2 |
3,268 | 57,579,641 | my question is that what changes there should be in a code | <h2>problem</h2>
<p>I am training CNN model on my GPU with tensorflow but I am running out of memory</p>
<h2>things I tried</h2>
<p>I have tried changing my batch_size , there was a positive change but eventually it was out of memory</p>
<p>model = Sequential()</p>
<h2>CODE</h2>
<p><code>enter code here</code></p... | <p>Since your network is pretty small, and you are taking only 32 images per batch, it might be the case that your images are of very high resolution, in which case you can try following things</p>
<ul>
<li>Try reducing the size of images, but do take care of retaining original aspect ratio while doing this</li>
<li>T... | tensorflow|out-of-memory|conv-neural-network|tf.keras | 0 |
3,269 | 57,704,331 | Is there a way to create a numpy array full of functions in place of elements? | <p>I'm looking to build a numpy array as follows so that I don't have to hard code countless numpy arrays by hand:</p>
<pre class="lang-py prettyprint-override"><code>
def func_1(x):
return x**2
def func_2(x):
return x**3+1
</code></pre>
<p>So the array becomes:</p>
<pre class="lang-py prettyprint-override"><code... | <p>this reproduces what you want:</p>
<pre><code>def A(x):
a = np.full(shape=(3, 2), fill_value=func_1(x))
b = np.full(shape=(3, 1), fill_value=func_2(x))
return np.concatenate((a, b), axis=1)
</code></pre>
<p>i <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html#numpy.con... | python|numpy | 1 |
3,270 | 24,390,645 | Python Pandas merge samed name columns in a dataframe | <p>So I have a few CSV files I'm trying to work with, but some of them have multiple columns with the same name.</p>
<p>For example I could have a csv like this:</p>
<pre><code>ID Name a a a b b
1 test1 1 NaN NaN "a" NaN
2 test2 NaN 2 NaN "a" NaN
3 test3 2 3 NaN NaN ... | <p>You could use <code>groupby</code> on <code>axis=1</code>, and experiment with something like</p>
<pre><code>>>> def sjoin(x): return ';'.join(x[x.notnull()].astype(str))
>>> df.groupby(level=0, axis=1).apply(lambda x: x.apply(sjoin, axis=1))
ID Name a b
0 1 test1 1.0 a
1 2 t... | python|pandas | 14 |
3,271 | 43,698,263 | Python Pandas hierarchical (tuple) row indexing -- how to select all of an intermediate row? | <p>Consider the following code:</p>
<pre><code>row1 = [(2,2), (4,4)]
row2 = [(5,5)]
row3 = [10, 20, 30, 40]
row_tuple_list = []
for r1 in row1:
for r2 in row2:
for r3 in row3:
row_tuple_list.append((r1, r2, r3))
row_index = pd.MultiIndex.from_tuples(row_tuple_list, names=['row1', 'row2', 'row3... | <pre><code># you need to use slice for w as well. This should work.
df.loc[(slice(w),slice(None),y),('f','g')]
df
Out[208]:
col1 f i
col2 g h g h
row1 row2 row3
(2, 2) (5, 5) 10 100 NaN NaN NaN
20 NaN NaN NaN NaN... | python|pandas|dataframe|indexing|hierarchical | 1 |
3,272 | 43,620,478 | Keras predict not working for multiple GPU's | <p>I recently implemented this make_parallel code (<a href="https://github.com/kuza55/keras-extras/blob/master/utils/multi_gpu.py" rel="nofollow noreferrer">https://github.com/kuza55/keras-extras/blob/master/utils/multi_gpu.py</a>) for testing on multiple GPUs. After implementing the predict_classes() function did not ... | <p>If you are using make_parallel function, you need to make sure number of samples is divisible by batch_size*N, where N is the number of GPUs you are using. For example:</p>
<pre><code>nb_samples = X.shape[0] - X.shape[0]%(batch_size*N)
X = X[:nb_samples]
</code></pre>
<p>You can use different batch_size for traini... | python|tensorflow|gpu|keras | 0 |
3,273 | 43,614,102 | pandas to_json returns a string not a json object | <p>I am using the following python code to return a json object:</p>
<pre><code>df_as_json = df.to_json(orient='split')
return jsonify({'status': 'ok', 'json_data': df_as_json})
</code></pre>
<p>When I read the object back in javascript:</p>
<pre><code>// response is xhr respose from server
const mydata = response.d... | <p>There's no such thing as a "json object" in python that's why<code>.to_json</code> returns a string representation of the json object, json in python is essentially the same as a <code>dict</code>, you can use the <code>to_dict</code> method instead. </p>
<pre><code>df_as_json = df.to_dict(orient='split')
return js... | javascript|python|json|pandas|dataframe | 29 |
3,274 | 43,624,502 | Using Python to calculate the unique conic section using five points | <p>I'm trying to develop a Python code which can tell you the centre, directrix, foci and the equation of any unique conic section using a set of five-point inputs from the user. </p>
<p>I'm currently running the code with Python2 on Sublime Text on a MacBook which I've installed Scipy , Numpy and Sympy. </p>
<h2>Aft... | <p>I think the reason you’re getting zeros is because you’re solving the linear system with <code>zeros(6,1)</code>, in which case the all-zero solution is valid. Try setting the right-hand-side to something non-zero.</p>
<p>The other issue is, with five points and six unknowns, the solution is underdetermined. But yo... | python|numpy|geometry|linear-algebra | 1 |
3,275 | 73,080,579 | Comparing two pandas dataframe cells, and if equal ==, copy other content over - results in error | <p>I am importing excel files with products and product specific data. They look like this:</p>
<p>dfA</p>
<pre><code>EAN Code Product Name Color Price
12345 AAA xxx 9
45678 BBB zzz 10
</code></pre>
<p>and
dfB</p>
<pre><code>EAN Code Product Name New Price
12... | <p>Use a <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a>, after setting up a common EAN Code:</p>
<pre><code>out = dfA.merge(
dfB.assign(**{'EAN Code': dfB['EAN Code'].str.replace('-', '')
.... | python|pandas | 2 |
3,276 | 73,133,044 | How to delete the last line of a groupby | <p>I am trying to handle the following dataframe.</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'ID':[1,1,2,2,2,3,3,3,3],
'sum':[1,1,1,2,3,1,4,4,4],
'flg':[1,np.nan, 1, np.nan, np.nan, 1, 1, np.nan, np.nan],
'year':[2018, 2019, 2018, 2... | <p>IIUC, use <code>head(-1)</code>:</p>
<pre><code>g = df.groupby('ID')
out = g.head(-1).assign(diff=g['sum'].apply(lambda x: x - x.iloc[-1]))
</code></pre>
<p>output:</p>
<pre><code> ID sum flg year diff
0 1 1 1.0 2018 0
2 2 1 1.0 2018 -2
3 2 2 NaN 2019 -1
5 3 1 1.0 2018 ... | python|pandas|group-by | 3 |
3,277 | 10,669,270 | Python numpy memmap matrix multiplication | <p>Im trying to produce a usual matrix multiplication between two huge matrices (10*25,000,000).
My memory runs out when I do so. How could I use numpy's memmap to be able to handle this?
Is this even a good idea? I'm not so worried about the speed of the operation, I just want the result even if it means waiting some ... | <p>you might try to use <code>np.memmap</code>, and compute the 10x10 output matrix one element at a time.</p>
<p>so you just load the first row of the first matrix and the first column of the second, and then <code>np.sum(row1 * col1)</code>.</p> | python|numpy|memory-management|matrix-multiplication|large-data | 2 |
3,278 | 70,699,908 | Using custom StyleGAN2-ada network in GANSpace (.pkl to .pt conversion) | <p>I trained a network using <a href="https://github.com/NVlabs/stylegan2-ada-pytorch" rel="nofollow noreferrer">Nvdia's StyleGAN2-ada pytorch implementation</a>. I now have a .pkl file. I would like to use the <a href="https://github.com/harskish/ganspace" rel="nofollow noreferrer">GANSpace code</a> on my network. How... | <p>Long story short, the conversion script provided was to convert weights from the official Tensorflow implementation of StyleGAN2 into Pytorch. As you mentioned, you already have a model in Pytorch, so it's reasonable for the conversion script to not work.</p>
<p>Instead of StyleGAN2 you used StyleGAN2-Ada which isn'... | tensorflow|pytorch|stylegan | 0 |
3,279 | 70,553,630 | how to count occurrences of specific string in previous x rows | <p>I have a list of activities and the approximate timestamp they occur in. I would like to count the occurences of a string in the previous 'x' rows (walking or running etc.) and add it to the dataframe. Pandas DataFrame does not support rolling (for non-numeric data) and I'm not sure if I can use shift to check like ... | <p>You can use a boolean to see when a particular event is occurring, then perform a rolling sum on the boolean series. As @mozway pointed out, the argument <code>min_periods=1</code> will avoid <code>NaN</code> appearing at the beginning of the resulting DataFrame:</p>
<pre><code>df['walking_count'] = (df['event'] == ... | python|pandas|rolling-computation | 3 |
3,280 | 70,509,011 | Error comparing dask date month with an integer | <p>The dask map_partitions function in the code below has a dask date field where its month is compared to an integer. This comparison fails with the following error:</p>
<blockquote>
<p>ValueError: The truth value of a Series is ambiguous. Use a.empty,
a.bool(), a.item(), a.any() or a.all().</p>
</blockquote>
<p>What ... | <p>By using <code>.map_partition</code>, each dask dataframe partition (which is a pandas dataframe) is passed to the function <code>func2</code>. As a result, <code>obj.date2.dt.month</code> refers to a Series, not a single value, so by running the comparison with the integer, it's not clear to Python whether how to d... | python|pandas|dask | 2 |
3,281 | 42,636,000 | How to read a table and Sql query from Oracle in Pandas? | <p>I am completely new to Python and pandas. I want to load a some tables and Sql Queries from Oracle and Teradata to pandas Dataframes and want to analyse them.
I know, we have to create some connection strings to Oracle and Teradata in Pandas. Can you please suggest me them and also add the sample code to read both ... | <blockquote>
<p>I don't have Oracle server, so I take Teradata as an example</p>
<p>This is not the only way to to that, just one approach</p>
</blockquote>
<ul>
<li>Make sure you have installed Teradata ODBC Driver. Please refer to Teradata official website about the steps, I suppose you use Windows (since it ... | oracle|python-3.x|pandas|teradata | 2 |
3,282 | 42,796,852 | Python Pandas - Initialising and Populating a DataFrame | <p>Sorry, a real numpty question here:</p>
<p>Why does the following code not produce a dataframe with values in?</p>
<pre><code>df = pd.DataFrame()
df['First'] = 68
df['Second'] = 157
</code></pre>
<p>How should I modify the code? I'm looking for the column names to be <code>First</code> and <code>Second</code> and... | <p><code>df = pd.DataFrame()</code> produces an empty dataframe... But it's more empty than other empty dataframes. It has no index and no columns.</p>
<p><code>df['First'] = 68</code> assigns the value of 68 to a column named <code>'First'</code> for every index value. You'll note that the columns <code>['First', ... | python|pandas | 2 |
3,283 | 42,765,510 | Extracting element/string from a dict list value | <p>I'm having some trouble extracting info from a Python object. Basically, using notation like this works to get down to values within a dict I am working with:</p>
<pre><code>clean_content['Al38zGKg6YC4']['image']
</code></pre>
<p>I was expecting to see another nested dict which contained the key/value that I wante... | <p>I came to a working solution as follows: converting the original dictionary into a pandas dataframe, I extracted the column containing the lists of image data. Each of these lists contained URLs for multiple images, so I extracted the one required using dicts:</p>
<pre><code>image_df_temp = {}
image_df_url = {}
fo... | python-2.7|pandas | 0 |
3,284 | 25,022,899 | Reading complex data into numpy array | <p>I need to read complex numbers from a text file into a numpy array. My question is similar to this one <a href="https://stackoverflow.com/questions/23231698/writing-and-reading-complex-numbers-using-numpy-savetxt-and-numpy-loadtxt">Writing and reading complex numbers using numpy.savetxt and numpy.loadtxt</a> however... | <blockquote>
<p>however, the solution here is to alter the format the data is saved in</p>
</blockquote>
<p>Good news, you don't have to!</p>
<p><code>numpy.loadtxt</code> can take any iterable of lines, not just a file object.</p>
<p>So, you can wrap your file object in a simple generator that transforms the line... | python|numpy | 5 |
3,285 | 25,265,961 | How to plot different CSV file data into a single graph, day as reference at x-axis | <p>I have written a code to plot several CSV file into single graph, using day as reference @ x-axis.</p>
<pre><code> CSV 1:
Value
time
2012-02-10 11:03:45 520429.598
2012-07-17 09:12:07 522155.535
... ... | <p>You might try letting matplotlib handle turning the dates into your x-axis coordinates. I had a similar problem a little while ago and was able to plot multiple time series with different date ranges.</p>
<p><strong>Edit:</strong> I think this should do what you want. It plots Value based on the time difference in ... | python|matplotlib|plot|pandas | 0 |
3,286 | 25,247,276 | ggplot area plot: order in which groups are rendered affects visibility | <p>I have this dataframe:</p>
<pre><code> Hour ENTRIES_hourly_rainy ENTRIES_hourly_not_rainy ENTRIES_hourly_total
0 0 3559751 7248389 10808140
1 1 1606880 3361780 4968660
2 2 145719 ... | <p>Your code looks like Python, not R, so this might not be helpful. I think the ggplot defaults are different in Python. (You did tag the question R though.)</p>
<p>In R:</p>
<pre><code>library(ggplot2)
library(reshape2)
gg <- melt(entriesPerHourPerRain, id="Hour")
ggplot(gg, aes(x=Hour,y=value,fill=variable)) +
... | python|pandas|ggplot2 | 0 |
3,287 | 25,033,631 | Multiple processes sharing a single Joblib cache | <p>I'm using Joblib to cache results of a computationally expensive function in my python script. The function's input arguments and return values are numpy arrays. The cache works fine for a single run of my python script. Now I want to spawn multiple runs of my python script in parallel for sweeping some parameter in... | <p>Specify a common, fixed <code>cachedir</code> and decorate the function that you want to cache using</p>
<pre><code>from joblib import Memory
mem = Memory(cachedir=cachedir)
@mem.cache
def f(arguments):
"""do things"""
pass
</code></pre>
<p>or simply</p>
<pre><code>def g(arguments):
pass
cached_g = m... | python|caching|numpy|joblib | 13 |
3,288 | 39,174,694 | label a point in graph using matplotlib for timeseries | <p>I have a pandas dataframe with 3 columns.
I plot col1 on Y axis and a time_stamps series on X axis.
For this series whenever col2 is -1, I want to highlight that point on graph as anomaly. I tried to get the coordinate and highlight using ax.text but I cannot get the correct coordinate since X axis is a time series.... | <p>I figured it out that I can convert it to seconds and then label the points as anomalies. This is what i did.</p>
<pre><code>def changetotimedelta(row):
return pd.to_timedelta(row["time_stamps"])/ np.timedelta64(1,'D')
def main()
df=pd.read_csv(inputFile)
df["time"]=df.apply(changetotimedelta,axis=1)
... | python|pandas|matplotlib|dataframe|time-series | 1 |
3,289 | 39,177,438 | Python numpy reshape issues | <p>I am working with machine learning and numpy and having issues with the <code>np.reshape()</code> function. My data sizes are reading in the variable console as Dataframe(22,5), x(21,4),x_lately(1,4), y(22,). I tried reshaping them with <code>np.reshape(22,5)</code> since that is the dataframe size and it is giving... | <p>You really need to describe your data better.</p>
<p>I can imagine the pieces fitting together:</p>
<pre><code>Dataframe(22,5), x(21,4),x_lately(1,4), y(22,)
</code></pre>
<p>The dataframe has 22 rows, 5 columns. <code>y</code> could be one column (22 items). <code>x</code> could be most of the 4 other columns,... | python|numpy|machine-learning | 0 |
3,290 | 19,804,241 | Python Pandas check if a value occurs more then once in the same day | <p>I have a Pandas dataframe as below. What I am trying to do is check if a station has variable <code>yyy</code> and any other variable on the same day (as in the case of <code>station1</code>). If this is true I need to delete the whole row containing <code>yyy</code>. </p>
<p>Currently I am doing this using <code>i... | <p>I might index using a boolean array. We want to delete rows (if I understand what you're after, anyway!) which have <code>yyy</code> and more than one <code>dateuse</code>/<code>station</code> combination.</p>
<p>We can use <code>transform</code> to broadcast the size of each <code>dateuse</code>/<code>station</co... | python|python-2.7|pandas | 4 |
3,291 | 23,561,856 | FFT vs least squares fitting of fourier components? | <p>So I've got a signal, and I've tried fitting a curve to it using two methods that I thought should have been numerically equivalent, but apparently are not.</p>
<p><strong>Method 1: Explicit fitting of sinusoids by least squares:</strong></p>
<pre><code>def curve(x, a0, a1, b1, a2, b2):
return a0 + a1*np.cos(x/7... | <p>Take a look at the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.rfft.html" rel="nofollow">docstring for <code>np.fft.rfft</code></a>. In particular, this: "If n is smaller than the length of the input, the input is cropped." When you do this:</p>
<pre><code> f = np.fft.rfft(y,3)
</cod... | python|numpy|scipy|fft|curve-fitting | 3 |
3,292 | 22,480,884 | Pandas read_csv. Using '^A' as a delimeter | <p>I have a csv file where the field separators are <code>^A</code> characters. When I try</p>
<pre><code>df = pd.read_csv(p_file, sep='^A')
</code></pre>
<p>The file looks as follows:</p>
<pre><code>0J0NrQDHHx^A989.0^A1
0J0NrQDHHx^A1204.0^A1
0U0NrQDHHx^A1654.0^A1
0N0NrQDHHx^A1679.0^A3
...
</code></pre>
<p>However,... | <p>Use <code>sep='\^A</code>:</p>
<pre><code>pd.read_csv(p_file, sep='\^A')
</code></pre>
<p>Reason is that <code>sep</code> also accepts regular expressions, and <code>^</code> has a special meaning in regular expressions, so the <code>\</code> is used to escape this.</p> | python|pandas | 4 |
3,293 | 62,432,442 | Pandas - list with dict to dataframe | <p>I have the following output:</p>
<pre><code>output = [{'test1': [('No Data', '[Auto] Clock in sync with NTP')]},
{'test2': [('No Data', '[Auto] Clock in sync with NTP'),
('No Data','Lambda - Concurrent Execution Limit')
}]
</code></pre>
<p>Needed Dataframe:</p>
<pre><code>... | <pre><code>output = [{'test1': [('No Data', '[Auto] Clock in sync with NTP')]},
{'test2': [('No Data', '[Auto] Clock in sync with NTP'),
('No Data','Lambda - Concurrent Execution Limit')]
}]
</code></pre>
<p>You can do this, but it is not a great idea to have lists be cells in ... | python|pandas|dataframe | 2 |
3,294 | 62,240,134 | How to plot the frequency of a specific word through time | <p>I have a dataset</p>
<pre><code>Column1 Column2 Column3 ....
2020/05/02 She heard the gurgling water (not relevant)
2020/05/02 The water felt delightful
2020/05/03 Another instant and I shall never again see the sun, this water, that gorge!
2020/05/04 Fire woul... | <p><strong>Setup</strong></p>
<pre><code>df = pd.DataFrame({
"Column1": ["2020/05/02", "2020/05/02", "2020/05/03", "2020/05/04", "2020/05/04", "2020/05/31"],
"Column2": ["She heard the gurgling water water", "The water felt delightful", "Another instant and I shall never again see the sun, this water, that gor... | python|regex|pandas|matplotlib | 1 |
3,295 | 62,343,258 | Custom Keras Layer with Trainable Scalars | <p>I'm (trying to) writing a custom Keras layer which implements the following componentwise:</p>
<p>x -> a <em>x + b</em>ReLU(x)</p>
<p>with a and b trainable weights. Here's what I've tries so far:</p>
<pre class="lang-py prettyprint-override"><code>class Custom_ReLU(tf.keras.layers.Layer):
def __init__(self... | <p>I have no problem using your layer:</p>
<pre><code>class Custom_ReLU(tf.keras.layers.Layer):
def __init__(self):
super(Custom_ReLU, self).__init__()
self.a1 = self.add_weight(shape=[1],
initializer = 'random_uniform',
trainable=Tr... | python|tensorflow|keras|neural-network|layer | 1 |
3,296 | 62,439,852 | Sampling from gaussian distribution | <p>My question is very specific. Given a <code>k</code> dimensional Gaussian distribution with mean and standard deviation, say I wish to sample <code>10</code> points from this distribution. But the <code>10</code> samples should be very different from each other. For example, I do not wish to sample <code>5</code> of... | <p>To my knowledge there is no such library. The problem you are trying to solve is straightforward. Just check if the random number you get is 'far enough' from the mean. The complexity of that check is constant. The probability of a point <strong>not</strong> to be between one sigma from the mean is ~32%. It is not t... | python|pytorch|sampling|normal-distribution | 0 |
3,297 | 51,223,859 | Pandas: how to merge two dataframes for different years? | <p>I have two dataframes <code>df1</code> and <code>df2</code>.</p>
<p><code>df1</code> contains the information of people and how money they received and the ID code.</p>
<pre><code>df1 = pd.DataFrame({'Money' : [359,45,780,77,93,257],
'NAME' : ['A', 'B', 'C', 'D', 'E', 'F'],
'I... | <p>First, create the year columns:</p>
<pre><code>c = df2.set_index(['ID', 'Year']).unstack('Year').C
</code></pre>
<p>That gives you:</p>
<pre><code>Year 2015 2016 2017
ID
0 1.0 2.0 3.0
1 NaN 1.0 1.0
2 NaN NaN 3.0
3 3.0 NaN 1.0
4 1.0 NaN NaN
5 NaN 3.0 2.0
</code>... | python|pandas|dataframe|merge | 2 |
3,298 | 51,470,082 | how to remove trailing zeros showing in my data description in jupyter notebook | <p>How do I remove trailing zeros showing in my data description in Jupyter notebook?</p>
<p><img src="https://i.stack.imgur.com/IEFW4.png" alt="enter image description here"></p> | <p><code>pd.set_option('precision', 1)</code> might help.</p> | python|pandas|jupyter-notebook | 2 |
3,299 | 51,367,545 | How to use numpy.where to change all pixels of an image? | <p>I have an image of shape (300,300,3) consisting of these pixels <code>[255, 194, 7],[224, 255, 8],[230, 230, 230],[11, 102, 255]</code>. I want to change this pixel <code>[230, 230, 230]</code> to <code>[255,255,255]</code>. And rest other pixels to <code>[0,0,0]</code>. So I'm applying numpy <code>where</code> func... | <pre><code>import numpy as np
im = np.array([[[255, 194, 7],[224, 255, 8],[230, 230, 230],[11, 102, 255]]])
</code></pre>
<p>Like this?<br>
Make a mask and use it to change the values.</p>
<pre><code>>>> mask = im == 230
>>> im[mask] = 255
>>> im[np.logical_not(mask)] = 0
>>> im
=... | python|image|numpy|image-processing | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.