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
9,800
57,037,715
Pandas: Delete rows with different encoding of 0s in python
<p>I have calculated statistical values and written them to a csv file. The nan values are replaced with zeros. There are rows with only zeros and there are rows with both 0 and 0.0 values only. How can I delete these rows? According to the attached image rows number 5 , 6 (only 0.0s), 9 and 11 (both 0s and 0.0s) needs...
<h2><strong>Use <code>all_df[(all_df.T != 0).any()]</code> or <code>all_df[(all_df != 0).any(axis=1)]</code>:</strong></h2> <pre><code>all_df = pd.DataFrame({'a':[0,0,0,1], 'b':[0,0,0,1]}) print all_df </code></pre> <pre><code> a b 0 0 0 1 0 0 2 0 0 3 1 1 </code></pre> <pre><code>all_df = all_df[(all_df.T...
python|python-3.x|pandas|csv
2
9,801
56,976,791
Using pypi pretrained models vs PyTorch
<p>I have two setups - one takes approx. 10 minutes to run the other is still going after an hour: </p> <p>10 m: </p> <pre class="lang-py prettyprint-override"><code>import pretrainedmodels def resnext50_32x4d(pretrained=False): pretrained = 'imagenet' if pretrained else None model = pretrainedmodels.se_res...
<p>Both architectures are different. I assume you are using <a href="https://github.com/Cadene/pretrained-models.pytorch/blob/master/README.md" rel="nofollow noreferrer">pretrained-models.pytorch</a>.</p> <p>Please notice you are using <strong>SE</strong>-ResNeXt in your first example and ResNeXt in second (standard o...
python|pytorch|pre-trained-model|fast-ai
1
9,802
56,940,258
pandas iterate over rows and concat results automatically?
<p>I want to iterate over rows and to concat all the resulting dataframes preserving the original row information. I have a working example:</p> <p>MWE:</p> <pre><code>import pandas as pd df = pd.DataFrame({'a': list(range(3)), 'b': list(range(3))}) pd.concat(df.apply(lambda row: ( pd.DataFrame(pd.np.zeros((row....
<p>I can't find the duplicate. But IIUC, you are trying to do sort of <code>crosstab</code> on the two dataframes:</p> <pre><code>df = pd.DataFrame({'a': list(range(3)), 'b': list(range(3))}) df2 = pd.DataFrame([[1,2],[3,4]], columns=('c','d')) pd.concat((df2.loc[np.tile(df2.index, len(df))].reset_index(drop=True), ...
python|pandas|apply
0
9,803
46,074,452
Filtering Pandas dataframe rows
<p>I have a dataframe that has one column <strong>numbers</strong>. The column's data are strings of numbers separated by commas.</p> <pre><code>numbers ------- 1,3,4,5,17,30 5,6,18,37,41,42 1,2,5,14,19,20 1,5,13,20,29,31 1,9,10,11,14,17 2,9,13,25,30,35 </code></pre> <p>How to get all the strings that contain numbers...
<p>You can create <code>df</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>split</code></a> and compare with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.eq.html" rel="nofollow noreferrer"><code>eq<...
python-3.x|pandas
3
9,804
23,122,079
lambda function in class header
<p>I am trying to create nan value for integer. the design i am thinking about is the following. I need to create and isnan lambda function in the class definition header but it returns an error</p> <pre><code>import numpy as np class Integer(object): type = int nan = -1 isnan = lambda val: val==-1 d...
<p>The issue is that your <code>isnan</code> functions are being treated as instance methods by Python. Even though you're using them "unbound", Python 2 still does a type check to ensure that the first argument to a method is an instance of the class (e.g. <code>self</code>). In Python 3, unbound methods have been dis...
python|python-2.7|numpy
2
9,805
35,690,983
Optimize this loop with numpy
<p>Generating 5 millions points <code>r[i]</code> recursively with:</p> <pre><code>import numpy as np n, a, b, c = 5000000, 0.0000002, 0.5, 0.4 eps = np.random.normal(0, 1, n) sigma = np.ones(n) * np.sqrt(a) r = np.zeros(n) for i in range(1,n): sigma[i] = np.sqrt(a + b * r[i-1] ** 2 + c * sigma[i-1] ** 2) r[i]...
<p>Simply changing it to <code>math.sqrt</code> instead of <code>np.sqrt</code> gives you about 40% speedup here.</p> <p>Since I'm quite a numba fanatic I tried the numba version versus your one (<code>initial</code>) and the math-one (<code>normal</code>)</p> <pre><code>import numpy as np import math import numba as...
python|numpy|cython|numerical-methods
2
9,806
11,731,768
Installing numpy on Red Hat 6?
<p>I'm trying to install numpy on a Red Hat (RHEL6) 64-bit linux machine that has Python 2.7. I downloaded and untar'd numpy 1.6.2 from Sourceforge, and I did the following commands in the numpy-1.6.2 folder:</p> <pre><code>python ./setup.py build sudo python ./setup.py install #without sudo, this gives a permissions ...
<p>RHEL6 ships numpy 1.4.1, see <a href="http://distrowatch.com/table.php?distribution=redhat&amp;pkglist=true&amp;version=rhel-6.7#pkglist" rel="nofollow">distrowatch</a>. If 1.4.1 is new enough for you, you can install it with:</p> <pre><code>$ yum install numpy </code></pre>
python|linux|numpy|installation|rhel6
1
9,807
28,482,943
How to use feature hasher to convert non-numerical discrete data so that it can be passed to SVM?
<p>I am trying to use the CRX dataset from the UCI Machine Learning repository. This particular dataset contains some features which are not continuous variables. Therefore I need to convert them into numerical values before they can be passed to an SVM.</p> <p>I initially looked into using the one-hot decoder, which ...
<p>The issue is that the <code>FeatureHasher</code> object expects each row of input to have a particular structure -- or really, one of three different <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.FeatureHasher.html" rel="noreferrer">possible structures</a>. The first possibilit...
python|numpy|machine-learning|scikit-learn|feature-extraction
6
9,808
33,210,112
Does Python-VIPS support assignment to part of its image ?
<p>I've been using Python 3 and Numpy to handle an image processing task where I'm assembling small tiles into a large, complete image. </p> <p>I'd do this: </p> <pre><code>canvas = np.zeros((max_y + tilesize_y, max_x + tilesize_x, 3), dtype='uint8') </code></pre> <p>Where <code>max_x</code>, <code>max_y</code> are ...
<p>VIPS has no destructive operations: you can only build new images, you can't modify existing images. This restriction is why vips can do things like automatic parallelisation and operation caching. </p> <p>Behind the scenes it has some extra machinery to make this less inefficient than it sounds. You can solve your...
python|numpy|image-processing|vips
1
9,809
33,369,772
numpy: distinguish/convert between different types of nan?
<p>I've been seeing a lot of errors like:</p> <pre><code>FloatingPointError: invalid value encountered in multiply </code></pre> <p>on some data I'm loading from disk (using astropy.io.fits). It appears to be related to <a href="https://github.com/numpy/numpy/issues/3190" rel="nofollow">this issue</a>, i.e., I have ...
<p>This will replace all the nans in <code>arr</code> with the default quiet nan:</p> <pre><code>with np.errstate(invalid='ignore'): arr[np.isnan(arr)] = np.nan </code></pre> <hr> <p>For what it's worth, here's a quick <code>issnan</code> function that is True for signaling nans only:</p> <pre><code>import nump...
arrays|numpy
4
9,810
66,448,110
Slices across Contourf plots at different angles to get 2D line plots
<p>I am trying to generate 2D line plots at different angles or slices of a matplotlib contourf plot.</p> <p>As an example from the matplotlib contourf demo example below</p> <pre><code>import numpy as np import matplotlib.pyplot as plt origin = 'lower' delta = 0.025 x = y = np.arange(-3.0, 3.01, delta) X, Y = np.me...
<p>Here is a rather inefficient approach, but it does the job. It recalculates the function on a new grid of which it only needs the diagonal.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import RectBivariateSpline delta = 0.025 x = y = ...
python|numpy|matplotlib|contourf
1
9,811
66,458,784
ValueError: Error when checking input: expected input_13 to have 3 dimensions, but got array with shape (50000, 32, 32, 3)
<p>I'm having a dimension error when I'm training a variational autoencoder and I can't figure out what I'm doing wrong. I had a <a href="https://stackoverflow.com/questions/66454445/valueerror-error-when-checking-input-expected-dense-85-input-to-have-4-dimensi">dimension error in a neural network</a> that just used <c...
<p>There is at least two problems in your code:</p> <ul> <li>Your input data does not match the input of your network. <code>(32,32,3)</code> vs <code>(32,32)</code>. One possible fix is to load your images in grayscale to match your network input, or to make your network accept images with 3 channels.</li> <li>Your gr...
python|tensorflow|keras|autoencoder
1
9,812
66,404,407
Fastest way to append nonzero numpy array elements to list
<p>I want to add all nonzero elements from a <code>numpy</code> array <code>arr</code> to a list <code>out_list</code>. Previous research suggests that for numpy arrays, using <code>np.nonzero</code> is most efficient. (My own benchmark below actually suggests it can be slightly improved using <code>np.delete</code>).<...
<p>I submit that the method of choice, if you are indeed looking for a <code>list</code> output, is:</p> <pre class="lang-py prettyprint-override"><code>def f(arr, out_list): out_list += arr[arr != 0].tolist() </code></pre> <p>It seems to beat all the other methods mentioned so far in the OP's question or in other ...
python|arrays|list|numpy
3
9,813
66,680,238
How to install numpy on linux subsystem for windows?
<p>I'm trying to install NumPy on the Linux subsystem for Windows, but it when I try to install pip <code>sudo apt install python-pip</code> so that I can use <code>pip install numpy</code>, it gives the error <code>E: Unable to locate package python-pip</code>.</p> <p>Any suggestions?</p> <p>Thanks</p> <p>Edit: When I...
<p>Try this <code>sudo apt install python3-pip</code></p>
windows|numpy|ubuntu
0
9,814
16,375,781
Python simple nested for loops
<p>I am trying a simple nested for loop in python to scan a threshold-ed image to detect the white pixels and store their location. The problem is that although the array it is reading from is only 160*120 (19200) it still takes about 6s to execute, my code is as follows and any help or guidance would be greatly apprec...
<p>First, it shouldn't take 6 seconds. Trying your code on a 160x120 image takes ~0.2 s for me.</p> <p>That said, for good <code>numpy</code> performance, you generally want to avoid loops. Sometimes it's simpler to vectorize along all except the smallest axis and loop along that, but when possible you should try to...
python|for-loop|numpy|pygame|nested-loops
2
9,815
57,401,131
i have from my original dataframe obtained another two , how can i merge in a final one the columns that i need
<p>i have a table with 4 columns , from this data i obtained another 2 tables with some rolling averages from the original table. now i want to combine these 3 into a final table. but the indexes are not in order now and i cant do it. I just started to learn python , i have zero experience and i would really need all ...
<p>Done ! i create a new column direct in the data frame like this </p> <p>df = pd.read_csv('Fd.csv', )</p> <p>df['Htgs/3'] = df.groupby('Home Team', ) ['Htgs'].rolling(window=4, min_periods=3).mean().reset_index(0,drop=True)</p> <p>the Htgs/3 will be the new column with the rolling average of the column Home Team, ...
python|pandas|dataframe|group-by|rolling-computation
0
9,816
57,518,057
How can I convert an image from pixels to one-hot encodings?
<p>I have a PNG image I am loading within Tensorflow using:</p> <pre><code>image = tf.io.decode_png(tf.io.read_file(path), channels=3) </code></pre> <p>The image contains pixels that match a lookup like this:</p> <pre><code>image_colors = [ (0, 0, 0), # black (0.5, 0.5, 0.5), # grey (1, 0.5, 1), ...
<p>Let me assume for convenience that all values in <code>image_colors</code> are in <code>[0, 255]</code>:</p> <pre><code>image_colors = [ (0, 0, 0), # black (127, 127, 127), # grey (255, 127, 255), # pink ] </code></pre> <p>My approach maps pixels into one-hot values as follows:</p> <pre><code># Cre...
python|tensorflow
5
9,817
57,583,783
Scraping works fine until appended to list
<p>I am a beginner trying to scrape bitcoin price history, everything works fine until I try to append it to a list, as nothing ends up being appended to the list.</p> <pre><code>import requests from bs4 import BeautifulSoup import pandas as pd from datetime import datetime url = 'https://coinmarketcap.com/currencie...
<p>As noted above, you need to increment i outside that the check for > 0.</p> <p>Secondly, have you considered using pandas <code>.read_html()</code>. That will do the hard work for you.</p> <p><strong>Code:</strong></p> <pre><code>import pandas as pd url = 'https://coinmarketcap.com/currencies/bitcoin/historical-...
python-3.x|pandas|beautifulsoup|python-requests
0
9,818
43,838,557
Custom boolean filtering in Pandas?
<p>I have a dataframe</p> <pre><code> 0 1 2 3 Marketcap 0 1.707280 0.666952 0.638515 -0.061126 2.291747 1.71B 1 -1.017134 1.353627 0.618433 0.008279 0.148128 1.82B 2 -0.774057 -0.165566 -0.083345 0.741598 -0.139851 1.1M 3 -0.630724 0.250737 1.30855...
<p>This isn't super clean, but it does the trick and doesn't use any python iteration:</p> <p><strong>Code:</strong></p> <pre><code># Create a separate column (which you can omit later) that converts 'Marketcap' strings to numbers df['cap'] = df.loc[df['Marketcap'].str.contains('B'), 'Marketcap'].str.replace('B','')....
pandas|filtering
3
9,819
43,768,498
Tensorflow Basic Example Error: CUBLAS_STATUS_NOT_INITIALIZED
<p>Hello I am trying to install and run tensorflow 1.0.</p> <p>I am using the following guide <a href="https://www.tensorflow.org/get_started/mnist/beginners" rel="nofollow noreferrer">https://www.tensorflow.org/get_started/mnist/beginners</a></p> <p>However when I run the file mnist_softmax.py I get the following er...
<p>@FernandoMM I got my script to run where I was getting the same error. In my case, I was running external displays of my GPU and it was eating up all the GPU ram. I disconnected all displays and restarted python (in my case I was using a Jupyter Server) and it worked. It looks like you have only 'Free memory: 349.06...
python-3.x|tensorflow
0
9,820
43,541,625
Fast indexing and bit flipping of boolean data using Python
<p>Using Python, I'm running a simulation where a community of species goes through a sequential set of time steps ('scenes') in each of which extinction occurs. From an initial set of N species, each extinction needs to select a number of survivors, which then forms the pool to be subsampled at the next extinction. Th...
<p>Here's an alternative that's pretty fast:</p> <pre><code>def using_shuffled_array(nspp=1000, nscene=250): a = np.arange(nspp) np.random.shuffle(a) m = np.zeros(nscene, dtype=int) m[0] = nspp # loop over the scenes, selecting survivors for i in range(0, nscene - 1): m[i + 1] = np.ra...
python|performance|numpy|bit-manipulation
1
9,821
43,814,594
Multiply each slice of image by weights
<p>I'm training a network such that one of tensor <code>t1</code> has following shape:</p> <p><code>shape(t1) = [?, 300, 300, 10]</code></p> <p>and another tensor <code>t2</code> has shape:</p> <p><code>shape(t2) = [?, 10]</code></p> <p>I would like to multiple each element of <code>t2</code> tensor by each slice <...
<p>If you reshape <code>t2</code> to shape <code>[?, 1, 1, 10]</code>, then Tensorflow's broadcasting rules will do the rest:</p> <pre><code>t2_reshaped = tf.reshape(t2, [-1, 1, 1, 10]) output = t1 * t2_reshaped </code></pre> <p>Many Tensorflow operators allow broadcasting; the rules for broadcasting are the same as ...
tensorflow
0
9,822
72,902,456
The Panda's DataFrame.apply() doesn't work as intended
<p>The task that I am trying to accomplish is to define a function that adds 1 to the elements of the 'grade' column of a DataFrame if the corresponding element in the 'sqft_living' column is less than 400 and adds 2 to the elements of the 'grade' column if the corresponding element in the 'sqft_living' column is great...
<blockquote> <p>the last digits of the elements of the 'grade' column are the same as their original value</p> </blockquote> <p>It's just a coincide that <code>add(1)</code> and <code>add(2)</code> results to the multiples of ten which is <code>86440</code> in your example.</p> <p><code>housing['grade']</code> is the w...
python|pandas|dataframe
1
9,823
73,130,005
When is `stage is None` in pytorch lightning?
<p>Some official pytorch lightning <a href="https://pytorch-lightning.readthedocs.io/en/stable/extensions/datamodules.html" rel="nofollow noreferrer">docs</a> have code that refer to <code>stage</code> as <code>Optional[str]</code> with for example the following code</p> <pre><code>import pytorch_lightning as pl from t...
<p>The Trainer will never send <code>stage=None</code> to the setup hook, or any of the other hooks that take this argument. The type is annotated optional and the default value is None for historical reasons. The values will always be one of &quot;fit&quot;, &quot;validate&quot;, &quot;test&quot;, &quot;predict&quot;....
deep-learning|pytorch|pytorch-lightning
1
9,824
73,139,985
Pandas change value based on other column values
<p>I want to change the value of each item in the column 'ageatbirth' to '1' if the 'race' is 2. In pseudocode:</p> <pre><code>If 'race' == 2 and 'ageatbirth' == 2: 'ageatbirth' == 1 </code></pre> <p>Is there an easy way to do this for a very large dataset?</p>
<p>Use</p> <pre class="lang-py prettyprint-override"><code>m = df['race'].eq(2) &amp; df['ageatbirth'].eq(2) df['ageatbirth'] = df['ageatbirth'].mask(m, 1) # or df.loc[m, 'ageatbirth'] = 1 </code></pre>
python|pandas
1
9,825
73,117,582
how to cancel filtering if two string conditions occur
<p>I have code that looks like this</p> <pre class="lang-py prettyprint-override"><code>df = pd.read_csv('data.csv', nrows=100000) def get_time(event_1, event_2): clean = df[(df['event_name'] == event_1) | (df['event_name'] == event_2)] ... final_df = get_time(event_1 = 'open', event_2 = 'close') </code></pre> ...
<p>Use a simple <code>if</code> statement</p> <pre><code>def get_time(event_1, event_2): if event_1 == 'open' and event_2 == 'close': clean = df else: clean = df[(df['event_name'] == event_1) | (df['event_name'] == event_2)] ... </code></pre>
python|pandas|dataframe
1
9,826
73,132,314
How to fix the error of "plt.scatter(x_test_encoded[:, 0], x_test_encoded[:, 1], c=y_test)"
<p>I'm testing the &quot;<code>Variational autoencoder (VAE)</code>&quot; from this link: <a href="https://blog.keras.io/building-autoencoders-in-keras.html" rel="nofollow noreferrer">https://blog.keras.io/building-autoencoders-in-keras.html</a></p> <p>But the following code will cause error:</p> <pre><code>x_test_enco...
<p>Your encoder is has three outputs <code>[z_mean, z_log_sigma, z]</code>, but you are actually only interested in <code>z</code> at position [-1]. So, it should actually be something like this (the tutorial seems to have an error):</p> <pre><code>x_test_encoded = encoder.predict(x_test, batch_size=32) plt.figure(figs...
python|numpy|tensorflow|matplotlib|keras
1
9,827
73,101,278
How to append 1 data frame with another based on condition
<p>I have 2 dfs. I want to append one with another only if the first df is not null. Eg:</p> <p>df1</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Name</th> <th style="text-align: left;">place</th> <th style="text-align: left;">Animal</th> </tr> </thead> <tbody> <...
<p>You can place whatever code you want in the if statement, I just placed a print for &quot;DF1 is empty&quot; as a place holder.</p> <pre><code>df1 = pd.DataFrame() df2 = pd.DataFrame({&quot;Name&quot;:[&quot;ABC&quot;, &quot;XYZ&quot;]}) # Check if df1 is empty, if not, concatenate df1 and df2 and reset the index i...
python|pandas
1
9,828
70,513,641
Azure Databricks OOM error that causes the connection to the Python REPL to be closed
<p>In the following sample code, in <code>one cell</code> of our <a href="https://docs.microsoft.com/en-us/azure/databricks/scenarios/what-is-azure-databricks#:%7E:text=Azure%20Databricks%20is%20a%20data,Microsoft%20Azure%20cloud%20services%20platform.&amp;text=For%20a%20big%20data%20pipeline,Event%20Hub%2C%20or%20IoT%...
<p>This means that the driver crashed because of an OOM (Out of memory) exception and after that, it's not able to establish a new connection with the driver.</p> <p>Please try below options</p> <ul> <li>Try increasing driver-side memory and then retry.</li> <li>You can look at the spark job dag which give you more inf...
python|pandas|apache-spark|azure-sql-database|azure-databricks
2
9,829
42,723,780
How does adding a (500x5000) and (5000x1) matrix result in a (500x5000) matrix?
<p>I am following a tutorial in an iPython notebook. My intention is calculating (X^2 - X_train)^2, storing the result in dists. The following code seems to work. I don't understand how it works however.</p> <p>Why does (2*inner_prod + train_sum) which adds differently-sized matrices yield a 500x5000 matrix?</p> <p>H...
<pre><code>print train_sum.shape # (5000,) print train_sum.size print test_sum.reshape(-1,1).shape # (5000,1) # how... does reshaping work??? print (2*inner_prod+train_sum).shape </code></pre> <p><code>test_sum.reshape(-1,1)</code> returns as new array with a new shape (but shared data). It does not resh...
python|numpy
1
9,830
42,947,298
ValueError: cannot reshape array of size 30470400 into shape (50,1104,104)
<p>I am trying to run threw this Tutorial <a href="http://emmanuelle.github.io/segmentation-of-3-d-tomography-images-with-python-and-scikit-image.html" rel="noreferrer">http://emmanuelle.github.io/segmentation-of-3-d-tomography-images-with-python-and-scikit-image.html</a> </p> <p>where I want to do a Segmentation of ...
<p>It seems that there is a typo, since <code>1104*1104*50=60940800</code> and you are trying to reshape to dimensions <code>50,1104,104</code>. So it seems that you need to change 104 to 1104.</p>
python|numpy|reshape
22
9,831
27,296,380
Create conditional probabilities in pandas from dataframe
<p>I have probabilities in a pandas dataframe df (from first July 2011 up to 31th July 2011 in 15-min. periods). Here is a excerpt:</p> <pre><code> Date_Time prob 0 2011-07-01 00:00:00 0.0112 1 2011-07-01 00:15:00 0.0224 2 2011-07-01 00:30:00 0.0112 3 2011-07-01 00:45:00 0.0896 4 2011-07-01 01:00...
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/version/0.15.1/generated/pandas.DataFrame.shift.html" rel="nofollow"><code>shift()</code></a> to calculate all these probabilities</p> <pre><code>&gt;&gt;&gt; for i in range(1,5): ... probB = df.shift(i)['prob'] ... probA = df['prob'] ... df['pro...
python|pandas
0
9,832
25,158,561
ipython pylab: print histogram from dictionary
<p>I have a dictionary <code>d</code>:</p> <pre><code>d = {'apples': 5, 'oranges': 2, 'bananas': 2, 'lemons': 1, 'coconuts': 1} </code></pre> <p>how can I display it graphically, as a histogram using (<code>pylab/matplotlib/ pandas/what-ever-is-best-suitable-for-simple-histograms</code>)</p> <p>What I am looking for...
<p>Using matplotlib:</p> <pre><code>import matplotlib.pyplot as plt d = {'apples': 5, 'oranges': 2, 'bananas': 2, 'lemons': 1, 'coconuts': 1} plt.bar(range(len(d)), d.values(), align='center') plt.xticks(range(len(d)), d.keys(), rotation=25) </code></pre> <p><img src="https://i.stack.imgur.com/S104h.png" alt="enter ...
python|matplotlib|pandas|ipython
3
9,833
30,711,969
object of type 'float' has no len() when using to_stata
<p>I have three columns in my dataset that I'm trying to save as a STATA dta file. These are the last three lines I run after I clean the data.</p> <pre><code>macro1=macro1.rename(columns={'index':'year', 'Price Index, PCE':'pce','Unemployment Rate':'urate'}) macro1.convert_objects(convert_numeric=True).dtypes macro1[...
<p><code>convert_objects</code> does not convert the dtypes inplace so you needed to assign the operation:</p> <pre><code>macro1 = macro1.convert_objects(convert_numeric=True) </code></pre> <p>see the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.convert_objects.html#pandas.DataFrame...
python|pandas
0
9,834
26,739,564
How can I parallelize functions "leastsq" or/and "curve_fit"
<p>What is the best way to parallelize the fitting procedure for multicore computers using scipy functions? As far as I see from manual, these functions do not have parameters like <code>npocs</code>. Does it mean they are not supposed to be parallelized?</p>
<p>Short answer: there is no built-in parallelization at the moment. There is <a href="https://github.com/scipy/scipy/pull/3192" rel="nofollow">a proposal to use multiprocessing</a> in leastsq, but it's not clear whether this is worth it. (if you feel like giving that code a drive and report the results, that'll be app...
numpy|parallel-processing|scipy|mathematical-optimization|curve-fitting
3
9,835
26,783,651
Efficient Partitioning of Pandas DataFrame rows between sandwiched indicator variables
<p>Suppose I have a pandas df with an indicator row that sandwiches a period. Ex. </p> <pre><code>In [9]: pd.DataFrame({'col1':np.arange(1,11),'indicator':[0,1,0,0,0,1,0,0,1,1]}) Out[9]: col1 indicator 0 1 0 1 2 1 2 3 0 3 4 0 4 5 0 5 6 ...
<p>Just assign another column as a <code>cumsum</code> of <code>indicator</code>, then apply <code>groupby</code>, this should do the trick:</p> <pre><code># reverse the order as you have indicator at end of group, then reverse back df['grouped'] = df['indicator'].loc[::-1].cumsum().loc[::-1] for g in df.groupby('gro...
python|pandas|group-by
3
9,836
39,344,587
Select rows if columns meet condition
<p>I have a <code>DataFrame</code> with 75 columns. </p> <p>How can I select rows based on a condition in a specific array of columns? If I want to do this on all columns I can just use</p> <pre><code>df[(df.values &gt; 1.5).any(1)] </code></pre> <p>But let's say I just want to do this on columns 3:45.</p>
<p>Use <code>ix</code> to slice the columns using ordinal position:</p> <pre><code>In [31]: df = pd.DataFrame(np.random.randn(5,10), columns=list('abcdefghij')) df Out[31]: a b c d e f g \ 0 -0.362353 0.302614 -1.007816 -0.360570 0.317197 1.131796 0.35145...
pandas|indexing|dataframe|conditional-statements|any
2
9,837
39,030,075
sort out dataframe where index meet certain conditions
<p>I have a data frame like this:</p> <pre><code> name pe outstanding totals totalAssets code 300533 abc 30.04 2500.00 10000.00 82066.80 300532 def 31.27 2100.00 8400.00 77945.25 603986 ...
<p>You can use <code>str</code> to extract the first 3 characters from index:</p> <pre><code>df[df.index.str[:3].isin(['300', '000'])] # name pe outstanding totals totalAssets # code #300533 abc 30.04 2500.00 10000.00 82066.80 #300532 def 31.27 2100.00 ...
python|pandas
2
9,838
39,024,852
Ignore string data that does not match a certain format when calculating "min" with Pandas
<p>I have a DataFrame column 'datetime' with the values in this format:</p> <p><code>'2016-08-01 13:43:35'</code></p> <p>I would like to find the min and max values. The problem is that some of the rows are missing time values so they look like this:</p> <p><code>'2016-07-29 '</code></p> <p>How can I exclude the r...
<p>You can convert values that have a specific format to datetime, and the remaining ones will be NaT. If you take the minimum on the resulting series, it will ignore NaTs.</p> <pre><code>df['datetime'] = ['2016-08-01 13:43:35', '2016-06-01 13:43:35', '2013-08-01 13:43:35', '2016-07-29 '] df Out: ...
python|pandas
1
9,839
29,015,556
numpy element transformation with lambda?
<p>In a 3D numpy array, I need to transform each element as follows: if it's less that 0, it must be become 0, if it's greater than 255, it must be become 255, and remain as-is otherwise.</p> <p>How can I achieve that with numpy? I am thinking of something like</p> <pre><code>img.transform_each(transform_func) </code...
<p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.clip.html" rel="nofollow"><code>clip</code></a> to keep the values of an array within a particular range. For example:</p> <pre><code>&gt;&gt;&gt; a = np.array([-1, 23, 312, 47, -5]) &gt;&gt;&gt; a.clip(0, 255) array([ 0, 23, 255, 47,...
python|arrays|numpy|vectorization
4
9,840
33,613,945
How to deal with inputs outside 0-1 range in tensorflow?
<p>In the example provided at <a href="http://www.tensorflow.org/get_started" rel="nofollow">http://www.tensorflow.org/get_started</a> if I multiply the input by 2</p> <pre><code>x_data = np.float32(np.random.rand(2, 100))*2 </code></pre> <p>I get non-sense output, while I expected to get the same solution.</p> <pre...
<p>The issue is that the example uses a very aggressive learning rate:</p> <pre><code>optimizer = tf.train.GradientDescentOptimizer(0.5) </code></pre> <p>This makes learning faster, but stops working if you change the problem a bit. A learning rate of <code>0.01</code> would be more typical:</p> <pre><code>optimizer...
python|tensorflow
10
9,841
23,818,364
Speed up a loop in pandas
<p>I am struggling with an issue on Python Pandas, I have a DataFrame which represents connection on a website:</p> <pre><code>No. IDs date duration_since_last_visit 1 4678 2012-11-30 23:59:59 0 2 4703 2012-11-30 23:59:23 0 3 4678 ...
<p>No loops needed.</p> <pre><code>In [12]: df.groupby('IDs')['duration_since_last_visit'].mean() Out[12]: IDs 4678 37.333333 4703 0.000000 5803 0.000000 Name: duration_since_last_visit, dtype: float64 </code></pre> <p>You'll find that vectorized operations are more efficient in pandas / numpy.</p>
python|pandas|dataframe
3
9,842
23,814,517
Get indices of intersecting rows of Numpy 2d Array
<p>I want to get the indices of the intersecting rows of a main numpy 2d array A, with another one B.</p> <pre><code>A=array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]) B=array([[1, 4], [1, 2], [5, 6], [6, 3]]) result=[0,2] </code></pre> <p>Where this sh...
<p>With minimal changes, you can get your approach to work:</p> <pre><code>In [15]: A Out[15]: array([[ 1, 2], [ 3, 4], [ 5, 6], [ 7, 8], [ 9, 10]]) In [16]: B Out[16]: array([[1, 4], [1, 2], [5, 6], [6, 3]]) In [17]: np.in1d(A.view('i,i').reshape(-1), B.view('i...
python|arrays|numpy
5
9,843
29,496,622
Can I use dtype to find the elements of an numpy array are strings?
<p>I got an numpy array, for example:</p> <pre><code>myArray = np.array(['a','bc']) </code></pre> <p>Is it possible use <code>dtype</code> to find out, whether its elements are strings?</p> <p>The only way I can do is checking <code>myArray.dtype == 'S2'</code>, but my Problem is I don't know in advance how many cha...
<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.issubdtype.html" rel="nofollow"><code>issubdtype</code></a> to do the checking:</p> <pre><code>&gt;&gt;&gt; np.issubdtype(myArray.dtype, str) True </code></pre> <p>The function checks whether a given dtype is ordered below another in ...
python|arrays|numpy|types
4
9,844
29,719,136
Select only the column names that contain a specific string
<p>A simple example should make this obvious. Sample data:</p> <pre><code>df = pd.DataFrame( np.random.randn(2,6), columns=['x','y','xy','yx','xx','yy'] ) </code></pre> <p>Now, I just want to list the values for columns containing 'x'. Here's a couple of ways:</p> <pre><code>df[[ x for x in df.columns if 'x' in x ...
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="noreferrer"><code>DataFrame.filter</code></a> with the <code>like</code> argument:</p> <pre><code>&gt;&gt;&gt; df.filter(like="x") x xy yx xx 0 -1.467867 0.766077 1.210667...
python|pandas
11
9,845
62,454,451
Python - get the mean of value between 2 date
<p>I'd like to get the mean of value between 2 dates grouped by shop.</p> <p>In fact I've a first xlsx with the sells by shop and date</p> <pre><code>shop sell date a 100 2000 a 122 2001 a 300 2002 b 55 2000 b 245 2001 b 1156 2002 </code></pre> <p>And I've another file with the start and end ...
<p><code>merge</code> the two DataFrames on 'shop'. Then you can check the date condition using <code>between</code> to filter down to the rows that count. Finally <code>groupby</code> + <code>sum</code>. (This assumes your second df is unique)</p> <pre><code>m = df2.merge(df1, how='left') (m[m['date'].between(m['sta...
python|pandas|dataframe|where-clause
1
9,846
62,083,007
increment counter in a column based on certain condition pandas
<pre><code>col1 col2 - - - - no 1 - - no 2 no 3 </code></pre> <p>I have 2 columns in a dataframe. Whenever 'no' is encountered in col1, need to increment the counter in col2 as shown above</p>
<p>Campare values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.eq.html" rel="nofollow noreferrer"><code>Series.eq</code></a> for <code>==</code>, then use cumulative sum and replace non <code>no</code> values to <code>-</code> by <a href="http://pandas.pydata.org/pandas-docs/stabl...
python|pandas|dataframe
3
9,847
62,353,697
How to get the aggregation statistics of duplicated rows of pandas dataframe?
<p>How to get the mean of duplicated rows of some columns from another column?</p> <h1>Setup</h1> <pre><code> df = pd.DataFrame({'A': [0,0,1,1,0,1], 'B': [0,0,1,1,0,1], 'C': [0,1,0,1,0,1], 'unused': [0.1,0.2,0.3,0.4,0.5,0.5], 'price': [5,10,5...
<p>Use groupby:</p> <pre><code>df.groupby(['A','B','C'])['price'].transform('mean') </code></pre>
python|pandas
0
9,848
62,163,194
PyTorch: The number of sizes provided (0) must be greater or equal to the number of dimensions in the tensor (1)
<p>I'm trying to convert a CPU model to GPU using Pytorch, but I'm running into issues. I'm running this on Colab and I'm sure that Pytorch detects a GPU. This is a deep Q network (RL). </p> <p>I declare my network as: <code>Q = Q_Network(input_size, hidden_size, output_size).to(device)</code></p> <p>I ran into an is...
<p><code>target[j, b_pact[j]]</code> is a single element of the tensor (a scalar, hence size of <code>torch.Size([])</code>). If you want to assign anything to it, the right hand side can only be a scalar. That is not the case, as one of the terms is a tensor with 1 dimension (a vector), namely your <code>maxq[j]</code...
python|numpy|pytorch|tensor
3
9,849
51,228,876
Count of values in a pandas df
<p>I am trying to <code>count</code> the amount of <code>values</code> in a <code>pandas df</code>. I want to do this <code>row</code> by <code>row</code>. So for the <code>df</code> below I want to <code>count</code> the amount of <code>values</code> in each <code>column</code> exported <code>row</code> by <code>row</...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.applymap.html" rel="nofollow noreferrer"><code>applymap</code></a> with <code>if-else</code>:</p> <pre><code>df = df.applymap(lambda x: len(x) if x != [()] else 0) #alternative #df = df.applymap(lambda x: 0 if x == [()] else len(x))...
python|pandas
0
9,850
51,366,666
Ecommerce item sales forecasting with pandas and statsmodels
<p>I want to forecast item sales (number of sales for each product) with pandas and statsmodel for an ecommerce business. Because item sales is a count dependent variable I'm assuming a Poisson modeling would work best.</p> <p>In an ideal world the model will be used to decide on which products to use in ads (increasi...
<p>Looks like a data problem. Since no sample data is shown, cannot be sure. You can try using GLM with family Poisson or GEE with family Poisson</p> <p>example:</p> <pre><code>smf.glm('sedimentation ~ C(control_grid)', data=df, families=sm.families.Poisson) </code></pre>
python|pandas|statsmodels
1
9,851
48,136,804
tf.Estimator.train throws as_list() is not defined on an unknown TensorShape
<p>I created a custom <code>input_func</code> and converted a keras model into <code>tf.Estimator</code> for training. However, it keeps throwing me error. </p> <ul> <li><p>Here is my model summary. I have attempted to set the <code>Input</code> layer with <code>batch_shape=(16, 320, 320, 3)</code> for testing but the...
<p>I had the same problem. In input_fun, if you look at images in line "return {'input_images': images}, labels", you'll see that your tensor has no shape. You have to call set_shape for each image. Look at <a href="https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py" rel="nofollow norefe...
python|tensorflow|deep-learning|keras
1
9,852
48,253,428
NumPy hstack throws "ValueError: all the input arrays must have same number of dimensions?"
<pre><code>data = [['297348640', 'Y', '12', 'Y'], ['300737722','Y', '1', 'Y'], ['300074407', 'Y', '1', 'N']] </code></pre> <p>I want to convert this into a NumPy array so I did:</p> <pre><code>data = np.array(data) </code></pre> <p>The above is working fine.</p> <p>Now I have two lists, say</p> <pre...
<p>Similar to @cᴏʟᴅsᴘᴇᴇᴅ's solution, but instead of passing <code>dtype=object</code>, you can be more explicit by passing <code>data</code>'s dtype:</p> <pre><code>data = np.array([['297348640', 'Y', '12', 'Y'], ['300737722','Y', '1', 'Y'], ['300074407', 'Y', '1', 'N']]) a = [0,2,6...
python|arrays|numpy
4
9,853
48,393,080
Plot Multicolored Time Series Plot based on Conditional in Python
<p>I have a pandas Financial timeseries DataFrame with two columns and one datetime index.</p> <pre><code> TOTAL.PAPRPNT.M Label 1973-03-01 25504.000 3 1973-04-01 25662.000 3 1973-05-01 25763.000 0 1973-06-01 25996.000 0 1973-07-01 26023.000 1 197...
<p>Here's an example of what I think your trying to do. It's based on the MPL documentation mentioned in the comments and uses randomly generated data. Just map the colormap boundaries to the discrete values given by the number of classes.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotl...
python|pandas|matplotlib|plot|time-series
6
9,854
48,461,808
Convert a dictionary including many dataframes into a dataframe
<p>I have a dictionary from an influxdb Time-series database. This dictionary includes many keys like KEY1,KEY2... All keys correspond to a tabular dataset. As an example:</p> <pre><code>dict = { KEY1: MAX MIN Date1 max1 min1 Date2 max2 min2, KEY2: MAX MI...
<p>Just add a <code>key</code> attribute to each dataframe and <code>concat</code>, like so:</p> <pre><code>import pandas as pd d = {'k1': pd.DataFrame({'max': [1, 2, 3], 'min': [1, 2, 3]}, index=[0, 1, 2]), 'k2': pd.DataFrame({'max': [4, 5, 6], 'min': [4, 5, 6]}, index=[3, 4, 5])} for k in d: d[k].insert(0...
python|pandas|dictionary|dataframe|time-series
0
9,855
48,880,634
How to select rows and replace some columns in pandas
<pre><code>import pandas as pd dic = {'A': [np.nan, 4, np.nan, 4], 'B': [9, 2, 5, 3], 'C': [0, 0, 5, 3]} df = pd.DataFrame(dic) df </code></pre> <p>If I have data like below</p> <pre><code> A B C 0 NaN 9 0 1 4.0 2 0 2 NaN 5 5 3 4.0 3 3 </code></pre> <p>I want to select the raw that column A i...
<p><strong>Option 1</strong><br> You were pretty close actually. Use <code>pd.Series.isnull</code> on <code>A</code> and assign values to <code>B</code> using <code>df.loc</code>: </p> <pre><code>df.loc[df.A.isnull(), 'B'] = np.nan df A B C 0 NaN NaN 0 1 4.0 2.0 0 2 NaN NaN 5 3 4.0 3.0 3 </code><...
python|pandas
5
9,856
48,757,358
Pandas Merge Rows with Duplicate Ids Conditionally, Suitable for to CSV
<p>I have the following df and I want to merge the lines that have the same Ids, unless there are duplicates</p> <pre><code>Ids A B C D E F G H I J 4411 24 2 55 26 1 4411 24 2 54 26 0 4412 22 4 54 26 0 4412 ...
<p>This should be slow , but can achieve what you need </p> <pre><code>df.replace('',np.nan).groupby('Ids').apply(lambda x: pd.DataFrame(x).apply(lambda x: sorted(x, key=pd.isnull),0)).dropna(axis=0,thresh=2).fillna('') Out[539]: Ids A B C D E F G H I J 0 7402 24.0 2.0 ...
python|pandas|csv|dataframe
2
9,857
70,982,709
Tensorflow save and load_model not working but save and load_weights does
<p>I am using tensorflow version 2.8.0:</p> <p>I have seen this issue from multiple sources all over forums, githubs, and even some here for the past 5 years with no definitive answer that has worked for me... For some reason, in certain situations, a loaded model from a previous save yields very different results from...
<p>This is because you have not saved your entire model using <code>.h5</code> extension, but you are using <code>.h5</code> for <code>saving the weights</code>. <br>Please check below code section:</p> <pre><code>model.save(&quot;./101_food_classes_10_percent/big_modelh5&quot;) # add .h5 loaded_model = tf.keras.model...
python|tensorflow|keras|save|load
0
9,858
70,753,740
sns.barplot ValueError: Length of values (9) does not match length of index (363)
<p>I wanted to extract the number of specific values from the columns - (<code>I</code> <code>s</code> <code>a</code> <code>x</code>) etc, so as I extracted I got stack that my chart doesn't want to read that.</p> <h1># Crashes AND Newes Frequency (I s a x)</h1> <pre><code># ...
<p>You'll probably want to store all your terms into a list. That way, the list of occurrences can be created via a loop. The terms can serve as labels for the bars. As they are quite long, newlines can be inserted to display them over multiple lines.</p> <p>Converting lists to numpy arrays, <code>np.argsort()</code> c...
python|pandas|seaborn
0
9,859
51,862,716
Cannot insert subtotals into pandas dataframe
<p>I'm rather new to Python and to Pandas. With the help of Google and StackOverflow, I've been able to get most of what I'm after. However, this one has me stumped. I have a dataframe that looks like this:</p> <pre><code> SalesPerson 1 SalesPerson 2 SalesPerson 3 Revenue Number of Orders R...
<p>Simple Example for you. </p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.rand(5, 5)) df_total = pd.DataFrame(np.sum(df.iloc[:, :].values, axis=0)).transpose() df_with_totals = df.append(df_total) df_with_totals 0 1 2 3 4 0 0.743746 0.66...
python|pandas|dataframe|subtotal
1
9,860
41,935,088
Shuffle groups of rows of a 2D array - NumPy
<p>Suppose I have a (50, 5) array. Is there a way for me to shuffle it on the basis of groupings of rows/sequences of datapoints, i.e. instead of shuffling every row, shuffle chunks of say, 5 rows?</p> <p>Thanks</p>
<p><strong>Approach #1 :</strong> Here's an approach that reshapes into a <code>3D</code> array based on the group size, indexes into the indices of blocks with shuffled indices obtained from <code>np.random.permutation</code> and finally reshapes back to <code>2D</code> -</p> <pre><code>N = 5 # Blocks of N rows M,n =...
numpy|multidimensional-array|shuffle
3
9,861
64,214,933
Checking ending characters in dataframe and replacing them
<p>I would like to add two new columns in my pandas dataframe based on the following conditions</p> <ul> <li>if a sentence ends with '...' then add a new column with value 1, otherwise 0;</li> <li>if a sentence ends with '...' then add a new column without '...' at the end</li> </ul> <p>Something like this:</p> <pre><c...
<p>For the first column, I would use the approach you suggested:</p> <pre class="lang-py prettyprint-override"><code>df['T'] = df['Text'].str.endswith('...') </code></pre> <p>(Technically this will create a boolean column, not an integer column. You can use <code>astype()</code> to convert if you care about this.)</p> ...
python|pandas
2
9,862
64,225,653
Random order of one pandas.DataFrame with respect of other
<p>I have the following structure:</p> <pre><code>data_Cnx = pd.read_csv(path_Connection,sep='\t',header=None) data_Cnx.columns = [&quot;ConnectionID&quot;] data_Srv = pd.read_csv(path_Service,sep='\t',header=None) data_Srv.columns = [&quot;ServiceID&quot;] </code></pre> <p>that can be visualized as the following:</p> ...
<p>I simply found the following works:</p> <pre><code>bigdata = pd.concat([data_Srv,data_Cnx], axis=1) bigdata.sample(n = 20) </code></pre> <p>If someone suggested a better idea, I would be opened to try it :)</p>
python|pandas|random
1
9,863
64,462,987
Why does my PCA change every time I run the code in python?
<p>I imputed my dataframe of any missing values with the median of each feature and scaled using StandardScaler(). I ran regular kneighbors with n=3 and the accuracy stays consistent.</p> <p>Now I am to do the PCA of the resulting dataset with n_components=4 and apply K-neighbors with 3 neighbors. However, every time I...
<p>You need to give <code>random_state</code>a value in <code>train_test_split</code> otherwise everytime you run it without specifying <code>random_state</code>, you will get a different result. What happens is that every time you split your data, you do it in different ways, unless you specify a random state, or lack...
python|pandas|pca|knn
0
9,864
47,834,297
TensorFlow softmax_crossentropy_with logits: are "labels" also trained (if differentiable)?
<p>The softmax cross-entropy with logits loss function is used to reduce the difference between the logits and labels provided to the function. Typically, the labels are fixed for supervised learning and the logits are adapted. But what happens when the labels come from a differentiable source, e.g., another network? D...
<p>You need to use tf.softmax_cross_entropy_with_logits_v2 to get gradients with respect to labels.</p>
tensorflow|fixed|label|gradient|loss-function
0
9,865
48,954,748
Normalize gradient magnitude to unit length in tensorflow
<p>How can we normalize the gradient magnitude to a unit length in tensorflow?</p> <p>I am trying to do something like</p> <p><code>gradients = tf.gradients(self.loss, _params) gradients_norm = tf.norm(gradients , name='norm') final_gradients= [(gradients/gradients_norm , var) for grad, var in gradients]</code></p>...
<p>There are some Gradient Clipping functions that do what you want in one step:</p> <p><a href="https://www.tensorflow.org/api_guides/python/train#Gradient_Clipping" rel="nofollow noreferrer">https://www.tensorflow.org/api_guides/python/train#Gradient_Clipping</a></p> <p>For example:</p> <pre><code>tf.clip_by_norm(...
tensorflow|gradient|normalize
2
9,866
49,057,750
groupby select value only if match
<p>I got my data sorted correctly, but now Im trying to find a way to group by "first not empty string value". Is there a way to do this without changing the rest of the data? First was close, but not quite what I needed</p> <pre><code>grouped = sortedvals.groupby(['name']).first().reset_index() </code></pre> <p>does...
<blockquote> <p>Use <code>replace</code> function to replace blank values with <code>np.nan</code></p> </blockquote> <pre><code>import numpy as np grouped = sortedvals.replace('',np.nan).groupby(['name']).first().reset_index() </code></pre>
python-3.x|pandas|pandas-groupby
1
9,867
48,988,697
consistent colors after multiple calls of pd.DataFrame.plot()
<p>I have a dataframe <code>v</code> with some numerical data in it.</p> <pre><code>v=pd.DataFrame(data=np.random.rand(300,3)) </code></pre> <p>I am want to plot on the same <code>matplotlib</code> figure:</p> <ul> <li>a scatter plot</li> <li>a moving average of the same points</li> </ul> <p>I do that using <code>p...
<p><strong>ORIGINAL</strong></p> <p>I believe you need - </p> <pre><code>%matplotlib inline # only for jupyter notebooks import pandas as pd from matplotlib import pyplot as plt import numpy as np colors = {0: 'red', 1:'green', 2:'blue'} v=pd.DataFrame(data=np.random.rand(300,3)) plt.figure() v.plot(marker='o',legen...
python|pandas|matplotlib|plot|colors
2
9,868
49,015,337
Reading and writing column data in Python with Pandas
<p>This endeavour is a variation on the wonderful <a href="https://github.com/MagerValp/MacModelShelf" rel="nofollow noreferrer">Mac Model Shelf</a>. I have managed thus far to write the code myself that can read single Mac serial numbers at the command line and give back the corresponding model type, based on on the l...
<p>See Update 3 for code that solved the issue</p>
python|excel|python-3.x|pandas
0
9,869
49,308,813
Reprinting column but changes don't stick when working with regex
<p>I am trying to use regex to remove the <code>$</code> signs, <code>,</code> and turn the columns into floats.</p> <pre><code>df[[cols]].replace({'\$': '', ',': ''}, regex=True).astype(float) </code></pre> <p>When I check my work and see if the changes stick, I still get <code>$</code> and <code>,</code>.</p> <p>I...
<p>You can do</p> <pre><code>df[col].apply(lambda x: float(x.replace('$', '')) </code></pre> <p>or </p> <pre><code>df[col].apply(lambda x: x.replace('$', '')).astype(float) </code></pre>
python|regex|pandas
0
9,870
58,708,874
Reduce sum with condition in tensorflow
<p>I am given a 2D Tensor with stochastic rows. After applying <code>tf.math.greater()</code> and <code>tf.cast(tf.int32)</code> I am left with a Tensor with 0's and 1's. I now want to apply reduce sum onto that matrix but with a condition: If there was at least one 1 summed and a 0 follows I want to remove all followi...
<p>IIUC, this is one way to do what you want without scanning or looping. It may be a bit convoluted, and is actually iterating the columns twice (one cumsum and one cumprod), but being vectorized operations I think it is probably faster. Code is TF 2.x but runs the same in TF 1.x (except for the last line obviously).<...
python|tensorflow
2
9,871
70,129,985
Use Trailing X Range of Rows when Defining a New Column
<p>I'm looking to turn a <code>for</code> loop, when creating values for a new column, into a one line statement using <code>numpy.where()</code> instead. I'm trying to implement the Doji logic <a href="https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/IsDoji" rel="nofollow noreferrer">he...
<p>Holy smokes I got it! Thanks to inspo from <a href="https://stackoverflow.com/questions/40700762/pandas-dataframe-sum-of-shiftx-for-x-in-range1-n">this answer</a>.</p> <p>This does what I'm looking for, verified by the final dataset that I save:</p> <pre><code>df['isDoji2'] = np.where(abs(df['close'] - df['open']) &...
python|python-3.x|pandas
0
9,872
70,089,778
vectorized matrix list application in numpy
<p>the problem i am trying to solve is as follows. I am given a matrix of arbitrary dimension representing indices of a list, and then a list. I would like to get back a matrix with the list elements swapped for the indices. I can't figure out how to do that in a vectorized way: i.e if <code>z = [[0,1], [1,0]]</code> a...
<p>When they both are <code>np.array</code>, you can do indexing in a natural way:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np z = np.array([[0, 1], [1, 0]]) a = np.array([20, 10]) output = a[z] print(output) # [[20 10] # [10 20]] </code></pre>
python|numpy
1
9,873
70,182,601
Replace consecutive duplicates in 2D numpy array
<p>I have a two dimensional numpy array <code>x</code>:</p> <pre><code>import numpy as np x = np.array([ [1, 2, 8, 4, 5, 5, 5, 3], [0, 2, 2, 2, 2, 1, 1, 4] ]) </code></pre> <p>My goal is to replace all consecutive duplicate numbers with a specific value (lets take <code>-1</code>), but by leaving one occurrenc...
<p>The main problem is that you require the length of the number of consecutives values. This is not easy to get with numpy, but using <code>itertools.groupby</code> we can solve it using the following code.</p> <pre><code>import numpy as np x = np.array([ [1, 2, 8, 4, 5, 5, 5, 3], [0, 2, 2, 2, 2, 1, 1, 4] ]) ...
python|python-3.x|numpy|duplicates|numpy-ndarray
0
9,874
70,248,895
pandas: removing duplicate values in rows with same index in two columns
<p>I have a dataframe as follows:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({'text':['she is good', 'she is bad'], 'label':['she is good', 'she is good']}) </code></pre> <p>I would like to compare row wise and if two same-indexed rows have the same values, replace the duplicate in the 'lab...
<p>Your syntax is not correct, have a look at the documentation of <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a>. Check for equality between your two columns, and replace the values in your label column:</p> <pre><code>import numpy as ...
python-3.x|pandas|duplicates|rowwise
1
9,875
56,140,870
Setting initial state in dynamic RNN
<p>Based on the link:</p> <p><a href="https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn</a></p> <p>In the example, it is shown that the "initial state" is defined in the <strong>first example and not in the second examp...
<blockquote> <p>Could anyone please explain what is the purpose of initial state?</p> </blockquote> <p>As we know that the state matrix is the weights between the hidden neurons in timestep 1 and timestep 2. They join the hidden neurons of both the time steps. Hence they hold temporal data from the layers in previou...
tensorflow|recurrent-neural-network
1
9,876
56,093,391
Trying to port a tensorflow python to javascript
<p>I'm trying to port this python code to javascript, I'm getting very different results in my js script so I wanted to make sure that my <strong>dense layers</strong> are correct:</p> <h2>Python</h2> <pre><code>let trainValues = // data source let trainLabels = // data source model = tf.keras.models.Sequential([ ...
<p>Your second dense layers seem to have a different number of units (<code>2</code> in python, <code>1</code> in JavaScript).</p> <p>In addition, your loss functions are different (<code>sparse_categorical_crossentropy</code> in python, <code>softmaxCrossEntropy</code> in JavaScript). Instead of providing one of the ...
node.js|tensorflow|tensorflow.js
1
9,877
64,795,510
Comparing specific row in a column with all columns for that specific row in a dataframe
<p>I'm new to python and been trying to figure this out for a week now</p> <p>I have a dataset 2 rows by 2000ish columns, the data came in a dictionary format and I used df.DataFrame to convert it (Don't know if this is helpful or not)</p> <p>Here is an example</p> <pre><code> gene1 gene2 gene3 etc locatio...
<p>This is definitely not the best way to do that, but I would try the following as it is the most straight-forward to me.</p> <pre><code>df = pd.DataFrame({&quot;gene1&quot;:[[1,2],&quot;ATCG&quot;], &quot;gene2&quot;:[[3,4],&quot;GGGG&quot;], &quot;gene3&quot;:[[5,6],&quot;CATA&q...
python|pandas
0
9,878
64,851,635
How can I get a substring of a row in a column returned by loc?
<p>I have a dataframe (df) which has the column 'Date Created'.</p> <p>I need to splice the string inside 'Date Created' so that I'm only left with the numerical day instead of the entire datetime string (For example, I want to cut 'Sun Mar 03 2020 11:52 pm' to &quot;2020/03/&quot;+ 'string in Date Created'[8:10] (9th ...
<p>I made up this dataframe.</p> <pre><code>df = pd.DataFrame({&quot;Date Created&quot;: [&quot;Sun Mar 03 2020 11:52 pm&quot;, &quot;Sun Mar 08 2020 11:52 pm&quot;, &quot;Sun Mar 09 2020 11:52 pm&quot;]}) </code></pre> <p>So with</p> <pre><code>d...
python|pandas|string|dataframe|copy
1
9,879
64,877,604
How to shift a histogram to the right?
<p>I have a 1D array for a histogram with bin boundaries:</p> <pre><code>bins = np.arange(1, 6,2) data = np.array([1,2,3,4,4,4,3,2,3,3,3]) plt.hist(data, bins=bins, histtype='step') </code></pre> <p>But I want to shift thee histogram horizontally to the right by 1 unit on the x-axis, how do I do that? I don't want the ...
<p>You were close, but in your <code>np.arange</code> you don't want to increase the step size. So:</p> <pre><code>plt.hist(data+x0, bins=np.arange(1+x0, 6+x0, 2), histtype='step') </code></pre> <p>Both graphs:</p> <p><a href="https://i.stack.imgur.com/SJ0oI.png" rel="nofollow noreferrer"><img src="https://i.stack.img...
python|numpy|jupyter|histogram
1
9,880
64,990,444
merge 4 columns into two columns
<p>I have a DataFrame with repeating 4 columns that i would like to merge in 2 columns.</p> <pre><code>Product ID Year_X Month_X Year_Y Month_Y 1 2020 1 2014 11 1 2019 2 2018 10 2 2022 5 2010 8 ...
<p>Create unique index first by <code>reset_index</code> then you can use <code>wide_to_long</code>:</p> <pre><code>print (pd.wide_to_long(df.reset_index(), stubnames=[&quot;Year&quot;, &quot;Month&quot;], i=&quot;index&quot;, j=&quot;Key&quot;, sep=&quot;_&quot;, suffix=&quot;\w*&quot;) ...
python|pandas
2
9,881
40,137,529
How to get pixel matrix of recognized objects when classifying a image using Tensorflow?
<p>I want to get pixel matrix of objects within a image when the image is classified by Tensorflow (classify_image.py).</p> <p>In other words, the recognized objects must be segmented first. E.g. there is a computer in the picture, i want to get all pixels which belong to the computer.</p> <p>But till now i cannot fi...
<p>Here are some links to models for image segmentation using TensorFlow :</p> <ul> <li><a href="https://github.com/Russell91/TensorBox" rel="nofollow">TensorBox</a></li> <li><a href="https://github.com/fabianbormann/Tensorflow-DeconvNet-Segmentation" rel="nofollow">DeConvNet</a></li> <li><a href="https://github.com/M...
python|tensorflow|deep-learning|object-recognition
1
9,882
40,228,453
Delete row and column in symmetric array if all the values in a row (or column) do not satisfy a given contion
<p>I've got a sparse, symmetric array and I'm trying to delete a row and column of that array if all the individual entries of a given row (and column) do not satisfy some threshold condition. For example if </p> <pre><code>min_value = 2 a = np.array([[2, 2, 1, 0, 0], [2, 0, 1, 4, 0], [1,...
<p>You could have a vectorized solution to solve it as shown below -</p> <pre><code># Get valid mask mask = a &gt;= min_value # As per requirements, look for ANY match along rows and cols and # use those masks to index into row and col dim of input array with # 1D open meshes from np.ix_ and thus select a 2D slice o...
python|arrays|numpy
1
9,883
44,123,874
'DataFrame' object has no attribute 'sort'
<p>I face some problem here, in my python package I have install <code>numpy</code>, but I still have this error:</p> <blockquote> <p><strong>'DataFrame' object has no attribute 'sort'</strong></p> </blockquote> <p>Anyone can give me some idea..</p> <p>This is my code :</p> <pre><code>final.loc[-1] =['', 'P','Actual'] ...
<p><code>sort()</code> was deprecated for DataFrames in favor of either:</p> <ul> <li><a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="noreferrer"><code>sort_values()</code></a> to <strong>sort by column(s)</strong></li> <li><a href="http://pandas.pydata.org/pa...
python|pandas|numpy|dataframe
270
9,884
69,369,193
Replace string in column with other text
<p>This seems like an elementary question with many online examples, but for some reason it does not work for me.</p> <p>I am trying to replace any cells in column 'A' that have the value = &quot;Facility-based testing-OH&quot; with the value = &quot;Facility based testing-OH&quot;. If you note, the only difference bet...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;A&quot;] = df[&quot;A&quot;].str.replace( &quot;Facility-based testing-OH&quot;, &quot;Facility based testing-OH&quot;, regex=False ) print(df) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override"><code> ...
python|pandas|string|replace
0
9,885
69,542,117
Pandas missing value; with fflill and add comment
<p>following through pandas documentation for <code>df.fillna(method=&quot;ffill&quot;)</code>, <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer">here</a>. How to add a new column with comments?How to add a new column with comments?How to add a new column with...
<p>Could you not create the Cost_Assumption column first based on the Cost column?</p> <pre><code>df_1.loc[df_1['Cost'] == '', 'Cost_Assumption'] = 'Cost per 2021-01-01' df_1.loc[df_1['Cost'].isnull(), 'Cost_Assumption'] = 'Cost per 2021-01-01' df_1['Cost_Assumption'] = df_1['Cost_Assumption'].fillna('Actual') </co...
python|pandas|dataframe
0
9,886
69,632,464
Ranking last row of dataframe by entire column
<p>I'd like to rank the values in the last row of a dataframe by the corresponding column above and return a list of the ranks by the 'min' amount. Example below:</p> <pre><code>df = [[10, 2, 8, 4], [12, 6, 4, 1], [8, 4, 3, 2], [9, 3, 4, 6]] df = pd.DataFrame(df) print(df) 0 1 2 3 0 10 2 8 4 1 12 6 4 1 ...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rank.html" rel="nofollow noreferrer"><code>rank</code></a></p> <pre><code>rs = df.rank(method=&quot;dense&quot;, ascending=False).iloc[-1].tolist() print(rs) </code></pre> <p><strong>Output</strong></p> <pre><code>[3.0, 3.0, 2.0, 1.0] </code>...
python|pandas
2
9,887
69,354,637
How to select data after date which is the index of the max value of columns for each group by pandas?
<pre><code> ts_code low high 2021-08-01 881105.TI 1485.0 1629.0 2021-08-01 885452.TI 2216.0 2391.0 2021-08-01 885525.TI 7427.0 8552.0 2021-08-01 885641.TI 621.0 671.0 2021-08-08 881105.TI 1496.0 1623.0 2021-08-08 885452.TI 2297.0 2406.0 2021-08-08 885525.TI 7300.0 7868.0...
<p>Let us try <code>transform</code> with <code>idxmax</code></p> <pre><code>df1 = df.reset_index() df1 = df[df.index &gt;= df.groupby('ts_code')['high'].transform('idxmax')] out = df1[df1.groupby('ts_code').cumcount()&lt;=1] out ts_code low high 2021-08-01 885525.TI 7427.0 8552.0 2021-08-08 88...
python|pandas
0
9,888
69,433,422
How to add the same vector to all vectors in numpy array without loops?
<p>I am trying to plot a 3D mathematical expression using numpy and matplotlib:</p> <p>The mathematical expression is:</p> <p><code>Z(x,y) = exp[(v - v_t)*(v - v_t)']</code></p> <p>while:</p> <p><code>v= [x, y]</code> and <code>v_t = [x_t, y_t]</code></p> <p>initiating vectors through the following code:</p> <pre><code...
<pre><code>In [63]: CONST = 1 ...: x = np.linspace(-5,5,11) ...: y = np.linspace(-5,5,11) ...: v = np.array([x,y]) ...: v_t = np.array([CONST,CONST]) </code></pre> <p>The resulting arrays and shapes:</p> <pre><code>In [64]: v Out[64]: array([[-5., -4., -3., -2., -1., 0., 1., 2., 3., 4., 5.], ...
python|arrays|numpy
1
9,889
69,307,041
Getting RESNet18 to work with float32 data
<p>I have float32 data that I am trying to get RESNet18 to work with. I am using the RESNet model in torchvision (and using pytorch lightning) and modified it to use one layer (grayscale) data like so:</p> <pre><code>class ResNetMSTAR(pl.LightningModule): def __init__(self): super().__init__() # define model and l...
<p>The problem is that the <code>y</code> your feeding your cross entropy loss, is not a LongTensor, but a FloatTensor. CrossEntropy expects getting fed a LongTensor for the target, and raises the error.</p> <p>This is an ugly fix:</p> <pre><code>x, y = batch y = y.long() </code></pre> <p>But what I recommend you to do...
machine-learning|pytorch|computer-vision|cross-entropy|pytorch-lightning
2
9,890
69,628,672
How to divide a numpy array elementwise by another numpy array of lower dimension
<p>Let's say I have a numpy array <code>[[0,1],[3,4],[5,6]]</code> and want to divide it elementwise by <code>[1,2,0]</code>. The desired result will be <code>[[0,1],[1.5,2],[0,0]]</code>. So if the division is by zero, then the result is zero. I only found a way to do it in pandas dataframe with div command, but coul...
<p>You could wrap your operation with <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a> to assign the invalid values to <code>0</code>:</p> <pre><code>&gt;&gt;&gt; np.where(d[:,None], x/d[:,None], 0) array([[0. , 1. ], [1.5, 2. ], ...
python|numpy
1
9,891
41,138,822
How to create a string type tensor in tensorflow C api?
<p>What exactly should the <code>data</code> below in the parameter list be?</p> <pre><code>TF_Tensor* tensorStr = TF_NewTensor(TF_STRING, nullptr, 0, &amp;data[0], 8, no_op, nullptr); </code></pre> <p>I tried:</p> <pre><code>char * data = "blah"; char* data[] = {"blah"}; char data[1][4] = {{'b','l','a','h'}}; </cod...
<p>Example of valid (but a bit ugly) code which creates a string tensor:</p> <pre><code>std::string input_str = "abracdabra"; // any input string size_t encoded_size = TF_StringEncodedSize(input_str.size()); size_t total_size = 8 + encoded_size; // 8 extra bytes - for start_offset char *input_encoded = (char*)mallo...
c|tensorflow
4
9,892
40,885,983
Pandas: Setting different colors for fliers within one boxplot
<p>I would like to set different colors for outliers in a boxplot based on categories. </p> <pre><code>f = plt.figure() ax = f.add_subplot(111) df = pd.DataFrame({"X":[-100,-10,0,0,0,10,100], "Category":["A","A","A","A","B","B","B",]}) bp = df.boxplot("X", return_type="dict", ax=ax, grid=False) ax.s...
<p>Okay, this is one solution. <code>bp["fliers"].get_data()</code> returns a tuple with the x-y values. Then one just has to plot via</p> <pre><code>ax.plot([1],[bp["fliers"][0].get_data()[1][0]], 'b+') ax.plot([1],[bp["fliers"][0].get_data()[1][1]], 'r+') </code></pre> <p><a href="https://i.stack.imgur.com/Nv3sN.pn...
python|pandas|boxplot
2
9,893
41,066,244
Tensorflow: 'module' object has no attribute 'scalar_summary'
<p>I tried to run the following code to test my TensorBoard, however, when I ran the program, there is an error said:</p> <pre><code>'module' object has no attribute 'scalar_summary' </code></pre> <p>I want to know how can I fix this issue, thanks.</p> <p>The following is the system info:</p> <ul> <li>Operating Sys...
<p>The <code>tf.scalar_summary()</code> function was moved in the master branch, after the 0.12 release. You can now find it as <a href="https://www.tensorflow.org/versions/r0.12/api_docs/python/summary.html#scalar"><code>tf.summary.scalar()</code></a>.</p>
tensorflow
48
9,894
41,191,911
Why does `scipy.interpolate.griddata` fail for readonly arrays?
<p>I have some data which I try to interpolate using <code>scipy.interpolate.griddata</code>. In my use-case I marked some of the numpy arrays read-only, which apparently breaks the interpolation:</p> <pre><code>import numpy as np from scipy import interpolate x0 = 10 * np.random.randn(100, 2) y0 = np.random.randn(10...
<p>The <a href="https://github.com/scipy/scipy/blob/master/scipy/interpolate/interpnd.pyx" rel="nofollow noreferrer">relevant code</a> is written in Cython, and when Cython requests a memoryview of the input array, <a href="https://mail.python.org/pipermail/cython-devel/2013-February/003396.html" rel="nofollow noreferr...
python|numpy|scipy
4
9,895
54,044,050
Iterate over columns of a DataFrame and assign values
<p>I have a one-column DataFrame (data), indexed by ordered dates, and I want to create a second DataFrame with p columns, and assign to each column a shifted version of data. I.e., I want in to see in the first column data.shift(1), in the second column data.shift(2), etc. My implementation is as follows:</p> <pre><c...
<h3>Assign series to series</h3> <p>You are assigning a dataframe to a series. While this gives a result, you shouldn't <em>expect</em> this to work. Instead, assign a series to a series and use <code>pd.Series.shift</code>:</p> <pre><code>data = pd.DataFrame({'A': [1, 2, 3, 4, 5]}) lagged_data = pd.DataFrame(index=...
python|pandas|dataframe
2
9,896
53,932,097
AttributeError: 'psycopg2.extensions.cursor' object has no attribute 'fast_executemany'
<p>AttributeError: 'psycopg2.extensions.cursor' object has no attribute 'fast_executemany'</p> <p>to_sql() is too slow. so trying to resolve the problem. but when I run the following code I am getting :-</p> <blockquote> <p>AttributeError: 'psycopg2.extensions.cursor' object has no attribute 'fast_executemany'</p...
<p>use insert with tuples it around 200 time faster than <code>executemany</code> in <code>psycopg</code></p> <pre><code>args_str = ','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in tup) cur.execute("INSERT INTO table VALUES " + args_str) </code></pre> <p>its equivalent of </p> <pre><code>INSERT INT...
python|pandas|amazon-redshift|pandas-to-sql
4
9,897
53,921,226
How to broadcast a subset of a text string from a pandas dataframe column
<p>I am trying to extract the year and rainfall values from messy text strings stored in a dataframe column and save these to new columns. I did it via list comprehensions, after testing with different slicing methods unsuccessfully. Is list comprehension the best way to extract a subset of a string for broadcasting?</...
<pre><code>df['split'] = df[0].str.split() df['year']=df['split'].map(lambda x:x[0]) df['rainfall']=df['split'].map(lambda x:x[5]) df=df[['year','rainfall']] df year rainfall 0 1883 122.1 1 1883 69.8 2 1883 29.6 </code></pre>
python|pandas
1
9,898
52,656,351
How to replace specific rows (based on conditions) using values with similar features condition in pandas?
<p>i'm having a trouble when i wanna replace specific values that satisfies a condition and replace the values based on another condition. </p> <h3>Example of dataframe (df)</h3> <pre><code> Gender Surname Ticket ` 0 masc Family1 a12` ` 1 **fem NoGroup aa3**` ` 2 boy Family1 12...
<p>With Pandas you should aim for vectorised calculations rather than row-wise loops. Here's one approach. First convert selected values to <code>None</code>:</p> <pre><code>df.loc[df['Gender'].ne('masc') &amp; df['Surname'].eq('NoGroup'), 'Surname'] = None </code></pre> <p>Then create a series mapping from <code>Tic...
python|pandas
1
9,899
46,558,129
search column by dictionary key and replace by dictionary value
<p>I have a dictionary d={nam:name, lin:link}</p> <p>I have a data frame that has below column names:</p> <p>nam1 nam2 nam3 nam_4 nam_5 lin1 lin2</p> <p>how do I replace the column names of dataframe with dictionary values?</p> <p>Thanks</p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html" rel="nofollow noreferrer"><code>Series.replace</code></a>, so first convert <code>index</code> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.to_series.html" rel="nofollow noreferrer"><code>to_...
python|pandas
0