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 |
|---|---|---|---|---|---|---|
351,200 | 59,144,938 | How to loop over batch_size in keras custom layer | <p>I want to create a custom layer that takes in <code>__init__</code> a internal tensor and a custom dot function so that it computes for a given batch the dot function over all possible pairs made with the batch and the internal tensor.</p>
<p>If I were to use the natural inner product, I could write directly <code>... | <p>So all the troubles came from the use of <code>tf.Tensor.shape</code> instead of <code>tf.shape(tf.Tensor)</code>.</p>
<p>Here is a working solution:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Layer
class CustomLayer(Layer):
... | tensorflow|keras|keras-layer | 1 |
351,201 | 59,072,455 | Size Mismatch when passing a state batch to network | <p>Since I’m a beginner in ML, this question or the design overall may sound silly, sorry about that. I’m open to any suggestions.</p>
<p>I have a simple network with three linear layers one of which is output layer.</p>
<pre><code>self.fc1 = nn.Linear(in_features=2, out_features=12)
self.fc2 = nn.Linear(in_features=... | <p>SOLVED. It turned out that I didn't know how to properly create 2d tensor.
2D Tensor must be like this:</p>
<p>states = torch.tensor([[1, 1], [2,2]], dtype=torch.float)</p> | machine-learning|neural-network|pytorch|reinforcement-learning|q-learning | 0 |
351,202 | 59,096,795 | Error with multiple plot in plotly python | <p>I have this data frame</p>
<pre><code> Id Timestamp Data Group
0 1 2013-08-12 10:29:19.673 40.0 1
1 2 2013-08-13 10:29:20.687 50.0 2
2 3 2013-09-14 10:29:20.687 40.0 3
3 4 2013-10-14 10:29:20.687 30.0 4
4 5 2013-11-15 10:29:20.687 50.0 5
..... | <p>You've tagged the question with plotly and only gotten a matplotlib answer so far, so here's a plotly approach:</p>
<hr>
<p>In your provided data sample, there are <code>no duplicate values for 'Group'</code>, but the <code>timestamp</code> seems to be continous. Your question is good though, but your dataset does... | python|pandas|plotly | 1 |
351,203 | 59,226,151 | Add Column to datettime driven Groupby function | <p>I have a dataframe;</p>
<pre><code>index UoW Category Description Date Channel Trans
ADATE
2018-12-31 1603 Pay Infringement 31/12/2018 AustPost 209
2018-12-31 1604 Pay Infringement 31/12/2018 AustPost 14
2019-12-31 1605 Pay Infringement 31/12/2018 CSC ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.idxmax.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.idxmax</code></a> and
<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.idxmin.html" rel="no... | pandas|datetime|transform|pandas-groupby | 2 |
351,204 | 59,167,112 | Python solve ODE system with solve_ivp | <p>I've been trying to solve a system of ODE's with scipys solve_ivp, which is a mean field approximation of a hierarchically organized tissue model, where I want to quantify the number of cells at level 'k' with 'm' number of mutations at a given time point. Here is the equation itself: </p>
<p><a href="https://i.sta... | <p>I could solve it</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/python
import os, shutil, time, sys, math
from sys import *
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp, odeint
from mpmath import *
mp.dps = 30
N0 = 1
rm = 2
nt = 1
mg2 = 1
inf = 25
th... | python|numpy|scipy|ode | 1 |
351,205 | 59,247,236 | "Unqualified exec" from Numpy when trying to run Django app | <p>manage.py</p>
<pre><code>#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some ot... | <p>The mix of Python 2 and Python 3 libraries in the traceback suggests a probably irreconcileable configuration problem.</p>
<p>If your app needs to work with Python 3, you need to install Python 3 versions of all dependencies, and make very sure no Python 2 library paths leak over.</p>
<p>For Python 2, vice versa (... | python|python-3.x|numpy | 2 |
351,206 | 59,217,045 | Calculating difference in values in a dataframe by grouping by | <p>I have a dataframe in the form off:</p>
<pre><code> station num_bikes Rush hour? num_racks hour
Botanic 3 yes-am 9 9
Botanic 2 no 10 14
Botanic 10 no 2 20
Queens 6 no 10 5
Queens 10 ... | <p>Here is what I have tried, let me know if it doesn't seem right:</p>
<pre><code>import pandas as pd
import numpy as np
df_filtered = pd.DataFrame([
('Botanic' , 3 , 'yes-am' , 9 , 9),
('Botanic' , 2 , 'no' , 10 , 14),
('Botanic' , 10 , 'no' , 2 ... | python|pandas|dataframe|diff | 0 |
351,207 | 59,214,696 | Read CSV files and append to new column of Numpy array | <p>I am reading a list of CSV files and always appending the data to a new column in my array. My current solution is analogous to the following:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
# Random generator and paths for the sake of reproducibility
fake_read_csv = lambda path: np.random.... | <p>For starters, every time you append, an entirely new array is allocated, which is quite wasteful. Instead, you can just combine all your columns once they're loaded:</p>
<pre><code>pred = np.array([fake_read_csv(path) for path in paths], order='F').T
</code></pre>
<p>The transpose makes the rows you read in into c... | python|numpy | 1 |
351,208 | 59,466,985 | keyword rotation is not recognized (Pandas Profiling) | <p>I am trying to use pandas_profiling package for data profiling. For basic usage, i have followed this documentation </p>
<p><a href="https://github.com/pandas-profiling/pandas-profiling" rel="nofollow noreferrer">https://github.com/pandas-profiling/pandas-profiling</a> </p>
<p>and use the following code from it </... | <p>For future reference: update your pandas and matplotlib packages. Versions of pandas-profiling later than 2.4.0 will automatically update these packages.</p> | python|pandas|pandas-profiling | 0 |
351,209 | 14,087,545 | Sampling on a spline to a given max chordal deviation | <p>I'm looking for a fast way to sample points on a spline such that a polygon or linestring through those points does not exceed a given chordal error to the original spline. I have an algorithm I wrote some time ago that produces the results in the picture (see code below if interested; I'm not expecting anyone to po... | <p>I found a great solution in one of my favorite modules - Shapely. There's a <code>simplify()</code> method on Shapely geometric objects that takes a tolerance and produces this for the same 0.1 value:
<img src="https://i.stack.imgur.com/KQQoM.png" alt="enter image description here" /></p>
<p>Looks better to me, and ... | python|numpy|scipy | 2 |
351,210 | 13,913,572 | Difference between scipy.stats.mstats.chisquare and scipy.stats.mstats in Python | <p>I am comparing two distributions, such as:</p>
<p><code>group1 = [ 0, 0, 0, 1, 11, 11, 13, 12]</code></p>
<p><code>group2 = [ 0, 0, 0, 0, 5, 11, 18, 14]</code></p>
<p>My distributions don't have a lot of elements, and I am not sure if chi-square is the best approach, but from what I read I think it is stil... | <p>I guess it is a bug in the <code>scipy.stats.mstats</code> module. <code>mstats</code> is supposed to handle masked arrays (arrays with invalid values) better than <code>stats</code>. However it seems that in this case it does not count correctly the number of degrees of freedom (DOF): The chi-square statistics (the... | python|numpy | 1 |
351,211 | 13,969,039 | np.fft.fft off by a factor of 1000 (fitting an powerspectrum) | <p>I'm trying to make a powerspectrum from an experimental dataset which I am reading in, and then to fit it to an theoretical curve. Now everything is working fine and I'm not getting errors, except for the fact that my curve keeps differing by a factor of 1000 from the data and I have absolutely no idea what the prob... | <p>Take a look at the documentation for the FFT that you are using. Many FFTs introduce a scaling factor that is usually N * result (number of samples). Multiplying by 1/N will scale the results back in line. (You said that the result is 1000 too high....could it be that you are using a 1024 size FFT?)</p> | numpy|fft | 1 |
351,212 | 14,322,932 | Changing Biopython include path for compilation during pip installation | <p>I'm trying to install Biopython (a python package) using PIP on my work machine (OpenSuse x86_64).</p>
<p>It all goes fine until it tries to do some compilation using numpy headers</p>
<pre><code>gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -fmessage-length=0 -O2 -Wall -D_FORTIFY_SOURCE=2 -fstack-protector -f... | <p>Thanks to @Bort, I discovered this is, apparently a <a href="http://biopython.org/DIST/docs/install/Installation.html#htoc34" rel="nofollow">known error</a> (local/user space installation wasn't working anyway).</p>
<p>By editing the Biopython <code>setup.py</code> file in the following places </p>
<h2>Original</h... | python|numpy|include|pip|biopython | 2 |
351,213 | 14,025,549 | Changing data in a dataframe with hierarchical indexing | <p>How can I change every element in a DataFrame with hierarchical indexing? For example, maybe I want to convert strings into floats:</p>
<pre><code>from pandas import DataFrame
f = DataFrame({'a': ['1,000','2,000','3,000'], 'b': ['2,000','3,000','4,000']})
f.columns = [['level1', 'level1'],['item1', 'item2']]
f
Out[... | <p>Pass the <code>axis</code> option to the <code>apply</code> function:</p>
<pre><code>In [265]: f.apply(clean, axis=1)
Out[265]:
level1
item1 item2
0 1000 2000
1 2000 3000
2 3000 4000
</code></pre>
<p>When both axes have hierarchical indices here's a workaround:</p>
<pre><code>In [316]: f.index = [[1... | python|pandas|hierarchical | 4 |
351,214 | 13,793,321 | Joining Table/DataFrames with common Column in Python | <p>I have two DataFrames:</p>
<pre><code>df1 = ['Date_Time',
'Temp_1',
'Latitude',
'N_S',
'Longitude',
'E_W']
df2 = ['Date_Time',
'Year',
'Month',
'Day',
'Hour',
'Minute',
'Seconds']
</code></pre>
<p>As You can see both DataFrames have <code>Date_Time</code> as a common co... | <p>You are looking for a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html?highlight=merge#pandas.DataFrame.merge"><code>merge</code></a>:</p>
<pre><code>df1.merge(df2, on='Date_Time')
</code></pre>
<p><em>The keywords are the same as for <code>join</code>, but <code>join</cod... | python|pandas | 21 |
351,215 | 14,225,676 | Save list of DataFrames to multisheet Excel spreadsheet | <p>How can I export a list of DataFrames into one Excel spreadsheet?<br>
The docs for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html"><code>to_excel</code></a> state:</p>
<blockquote>
<p>Notes<br>
If passing an existing ExcelWriter object, then the sheet will be added... | <p>You should be using pandas own <code>ExcelWriter</code> class:</p>
<pre><code>from pandas import ExcelWriter
# from pandas.io.parsers import ExcelWriter
</code></pre>
<p>Then the <code>save_xls</code> function works as expected:</p>
<pre><code>def save_xls(list_dfs, xls_path):
with ExcelWriter(xls_path) as write... | python|pandas|openpyxl | 175 |
351,216 | 44,941,231 | Can I use Layer Normalization with CNN? | <p>I see the Layer Normalization is the modern normalization method than Batch Normalization, and it is very simple to coding in Tensorflow.
But I think the layer normalization is designed for RNN, and the batch normalization for CNN.
Can I use the layer normalization with CNN that process image classification task?
Wh... | <p>You can use <code>Layer normalisation</code> in CNNs, but i don't think it more 'modern' than <code>Batch Norm</code>. They both normalise differently. <code>Layer norm</code> normalises all the activations of a single layer from a batch by collecting statistics from every unit within the layer, while <code>batch no... | tensorflow|deep-learning|normalization|data-processing|batch-normalization | 10 |
351,217 | 45,044,129 | Python Pandas to_html styling | <p>I am trying to translate a csv into an html table, insert it into an email and send it out. I found a similar question <a href="https://stackoverflow.com/questions/38275467/send-table-as-an-email-body-not-attachment-in-python">Here</a> and seems to work great. </p>
<p>My email is sending out but no matter what I do... | <p>Instead using <code>to_html</code> styling, use <code>style</code>. </p>
<pre><code>import pandas as pd
def style_line(s):
'''Rendering odd and even rows with different color'''
return ['background-color: #D4E6F1' if i%2!=0 else 'background-color: #85C1E9' for i in range(len(s))]
df = pd.read_csv('testy.... | python|html|css|pandas|email | 1 |
351,218 | 45,248,276 | Get the last column of a pd.dataFrame and add it to another pd.dataFrame | <p>I have an Excel file that looks like this:</p>
<pre><code>CompanyName High Priority QualityIssue
Customer1 Yes User
Customer1 Yes User
Customer2 No User
Customer3 No Equipment
Customer1 No Neither
Customer3... | <p>Quick and simple way using <code>groupby</code> and <code>size</code></p>
<pre><code>df.groupby(['CompanyName', 'QualityIssue']).size()
CompanyName QualityIssue
Customer1 Neither 1
User 2
Customer2 User 1
Customer3 Equipment 2
User ... | python|pandas | 1 |
351,219 | 44,964,484 | Pandas average timestamp for DateFrame subset | <p>I am really new of Pandas and I have a problem how to calculate the average value of a set of time.</p>
<p>I have a csv file with columns: Date, Time, Outside temperature</p>
<p>I imported and modify it as: </p>
<pre><code>df = pd.read_csv("./file.csv", parse_dates=[0], dayfirst=True)
df["Date"] = pd.to_datetime(... | <p>I think you can use <code>timedelata</code>s by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow noreferrer"><code>to_timedelta</code></a>, then convert to <code>ns</code>, get <code>mean</code> and convert back:</p>
<pre><code>df = pd.read_csv("./file.csv", par... | python|pandas | 2 |
351,220 | 45,047,917 | To Create changeable function depend on column like Excel left double click in Python Pandas | <p>As you know, Excel have a auto fill function (double click or drag). It offer changeable reference depend on column position. ex) C1 tab =A1+B1, C2 tab =A2+B2 </p>
<p><a href="https://i.stack.imgur.com/2CJQk.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>My question is how do i create a tha... | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html" rel="nofollow noreferrer"><code>rolling</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.window.Rolling.sum.html" rel="nofollow noreferrer"><code>sum</code></a>:</p... | python|pandas | 1 |
351,221 | 44,986,027 | HDFStore updating stored HDF5 python pandas dataframe | <p>I have two dataframes, <code>df1</code> which is stored in a <code>pd.HDFStore</code> object and the other which is to be appended to the dataframe. </p>
<pre><code>store = pd.HDFStore('dataframe_store.h5')
df1 = pd.DataFrame(np.empty((100, 5)))
df2 = pd.DataFrame(np.empty((100, 5)))
store['df1'] = df1
</code></p... | <p>Per <a href="http://pandas-docs.github.io/pandas-docs-travis/io.html#table-format" rel="nofollow noreferrer">the docs</a> (my emphasis):</p>
<blockquote>
<p>HDFStore supports another PyTables format on disk, the table
format. Conceptually a table is shaped very much like a DataFrame, with rows and
columns. <s... | python|pandas|hdf5 | 1 |
351,222 | 44,880,535 | What is the best way to feed the image+vector dataset to Tensorflow | <p>I am trying to do a Deep Learning project by using Tensorflow. </p>
<p>Each of my data sets contains 2 files( PNGimage file + TXTvectors file ), where are put in different folders as follow:</p>
<pre><code>./data/image/ #Folders contains different size of images
./data/vector/ #Folders contains vectors of corres... | <p>I recommend you to take a look at <a href="https://www.tensorflow.org/api_guides/python/python_io#tfrecords_format_details" rel="nofollow noreferrer">TFRecords</a> and <a href="https://www.tensorflow.org/programmers_guide/reading_data" rel="nofollow noreferrer">queues</a>. Basically the idea is the following: you re... | tensorflow | 0 |
351,223 | 45,001,434 | How to name a Pandas Series | <p>I have data as follows in a <code>DataFrame</code> <code>symbolData</code>:</p>
<pre><code> Open High Low Close Volume Ex-Dividend Split Ratio Adj. Open Adj. High Adj. Low Adj. Close Adj. Volume
Date
1980-12-12 28.75 28.8700 28.7500 28.75 2093900.0 0.0 ... | <p>This will do the job:</p>
<pre><code>adjClose = symbolData.ix[:,10].rename("AlgoClose")
adjClose =pd.DataFrame(adjClose)
</code></pre> | python|pandas|dataframe | 14 |
351,224 | 44,873,273 | What do the options in ConfigProto like allow_soft_placement and log_device_placement mean? | <p>We see this quite often in many of the TensorFlow tutorials:</p>
<pre class="lang-py prettyprint-override"><code>sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
log_device_placement=True))
</code></pre>
<p>What does <code>allow_soft_placement</code> and <... | <p>If you look at the <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/protobuf/config.proto" rel="noreferrer">API of ConfigProto</a>, on line 278, you will see this:</p>
<pre class="lang-cpp prettyprint-override"><code> // Whether soft placement is allowed. If allow_soft_placement is tru... | tensorflow | 36 |
351,225 | 44,879,517 | Rolling and cumulative standard deviation in a Python dataframe | <p>Is there a vectorized operation to calculate the cumulative and rolling standard deviation (SD) of a Python DataFrame?</p>
<p>For example, I want to add a column 'c' which calculates the cumulative SD based on column 'a', i.e. in index 0, it shows NaN due to 1 data point, and in index 1, it calculates SD based on 2... | <p>For cumulative SD base on columna 'a', let's use <code>rolling</code> with a windows size the length of the dataframe and <code>min_periods = 2</code>:</p>
<pre><code>df['a'].rolling(len(df),min_periods=2).std()
</code></pre>
<p>Output:</p>
<pre><code> a b c
0 -1.085631 0.997345 Na... | python|pandas|dataframe|standard-deviation | 13 |
351,226 | 44,936,698 | conditional evaluation in TensorFlow graph | <p>This can be done with <code>tf.cond</code>, however it will update both branches of the graph, from the <a href="https://www.tensorflow.org/api_docs/python/tf/cond" rel="nofollow noreferrer">manual</a>:</p>
<blockquote>
<p>Note that the conditional execution applies only to the operations
defined in true_fn and... | <p>The general solution is as follows: move the code that you want to execute conditionally <strong>into the body of the <code>lambda</code></strong> (or—in general—the callable object) for the appropriate branch of the <code>tf.cond()</code>. For example, to ensure that <code>tf.multiply(a, b)</code> only ... | python|tensorflow | 5 |
351,227 | 44,906,028 | Cannot convert input to Timestamp, bday_range(...) - Pandas/Python | <p>Looking to generate a number for the days in business days between current date and the end of the month of a pandas dataframe.
E.g. 26/06/2017 - 4, 23/06/2017 - 5</p>
<p>I'm having trouble as I keep getting a Type Error:</p>
<pre><code>TypeError: Cannot convert input to Timestamp
</code></pre>
<p>From line:</p>... | <p>I think you need length of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.bdate_range.html" rel="nofollow noreferrer"><code>bdate_range</code></a> for each row, so need custom function with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollo... | python|pandas | 1 |
351,228 | 45,228,800 | Creating a DataFrame in Pandas using logical and operator | <p>I have a pandas Datarame with some columns and I first wanted to print only those rows whose values in a particular column is less than a certain value. So I did:</p>
<pre><code>df[df.marks < 4.5]
</code></pre>
<p>It successfully created the dataframe, now I want to add only those columns whose values are in a ... | <p>Use </p>
<pre><code>df[(df.marks < 4.5) & (df.marks > 4)]
</code></pre>
<p>Slightly more generally, array logical operations are combined using parentheses around the individual conditions:</p>
<pre><code>(a < b) & (c > d)
</code></pre>
<p>Similar for OR-combinations, or more than 2 condition... | python|pandas|jupyter-notebook | 5 |
351,229 | 44,952,829 | Padding 1D NumPy array with zeros to form 2D array | <p>I have a numpy array:</p>
<pre><code>arr=np.array([0,1,0,0.5])
</code></pre>
<p>I need to form a new array from it as follows, such that every zero elements is repeated thrice and every non-zero element has 2 preceding zeroes, followed by the non-zero number. In short, every element is repeated thrice, zero as it ... | <p>A quick reshape followed by a call to <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html" rel="nofollow noreferrer"><code>np.pad</code></a> will do it:</p>
<pre><code>np.pad(arr.reshape(-1, 1), ((0, 0), (2, 0)), 'constant')
</code></pre>
<p>Output:</p>
<pre><code>array([[ 0. , 0. , 0. ... | python|arrays|numpy | 3 |
351,230 | 45,210,420 | Simple RNN network - ValueError: setting an array element with a sequence | <p>I am completely loosing my patience with TF and Python, I cant get this to work,
"ValueError: setting an array element with a sequence." on testx when sess.run is invoked.</p>
<p>I have tried a lot of different things.. It's almost as if TF is broken, could anyone assist?</p>
<pre><code>import tensorflow as tf
imp... | <p>This is probably what you want. You'll find a few remarks in comments in the code.</p>
<pre><code>import tensorflow as tf
import numpy as np
nColsIn = 1
nSequenceLen = 4
nBatches = 8
nColsOut = 1
rnn_size = 228
# As you use static_rnn it has to be a list of inputs
modelx = [tf.placeholder(tf.float64,[nBatches, nC... | python|tensorflow|deep-learning|rnn | 1 |
351,231 | 44,961,631 | Change order np.argmax index is taken from | <p>I have three matrixes as such:</p>
<pre><code>one = np.empty((5,5))
one[:] = 10
two = np.empty((5,5))
two[:] = 10
three = np.empty((5,5))
three[:] = 2
</code></pre>
<p>I then stack them:</p>
<pre><code>stacked = np.dstack([one, two, three])
</code></pre>
<p>and finally determine the index with the maximum val... | <p>For efficiency purposes, I would suggest using a <code>flipped</code> view and then getting the indices after subtracting from the last axis length, like so -</p>
<pre><code>stacked.shape[-1] - stacked[...,::-1].argmax(-1) - 1
</code></pre>
<p>Another approach without flipping and a bit longer one, would be with c... | numpy | 1 |
351,232 | 45,266,077 | Error installing Tensorflow-GPU | <p>I am attempting to install tensorflow and tensorflow-gpu as per the following instructions:</p>
<p><a href="https://www.tensorflow.org/install/install_windows#CommonInstallationProblems" rel="nofollow noreferrer">https://www.tensorflow.org/install/install_windows#CommonInstallationProblems</a></p>
<p>I think I'm f... | <p>Well, I fixed it, though to be honest, I'm not quite sure which of the things I tried worked.</p>
<p>I carefully went through the steps again. This still didn't work, though it may have fixed some precursor problems. Then I went into the Path Environment Variable and started adding new paths so that it would be eas... | anaconda|cudnn|tensorflow | 0 |
351,233 | 44,913,053 | Numerical differentiation using Cauchy (CIF) | <p>I am trying to create a module with a mathematical class for Taylor series, to have it easily accessible for other projects. Hence I wish to optimize it as far as I can.</p>
<p>For those who are not too familiar with Taylor series, it will be a necessity to be able to differentiate a function in a point many times.... | <p>I seem to have come up with a solution to the problem. I did this by rearranging Cauchy's integral formula in a different way, by exploiting that the initial contour integral can be an arbitrarily large circle around the point of differentiation. Be aware that it is very important that the function is analytic in th... | python-3.x|numpy|math|differentiation | 1 |
351,234 | 45,165,347 | Can I use Tensorflow and Keras interchangeably? | <p>I am using l2_regularization
Tensorflow has - tf.nn.l2_loss
Can I use this?</p>
<ol>
<li>K.sum(K.square(K.abs(Weights)))</li>
<li>tf.nn.l2_loss</li>
</ol>
<p>Can I use this interchangeably in Keras (Tensorflow backend)?</p> | <p>Yes, you can, but keep in mind that <code>tf.nn.l2_loss</code> computes <code>output = sum(t ** 2) / 2</code> (from documentation), so you've forgotten about multiplying by <code>0.5</code>. Also you don't have to calculate <code>K.abs(weights)</code> because <code>K.square(K.abs(weights)) == K.square(weights)</code... | tensorflow|deep-learning|keras|keras-2 | 4 |
351,235 | 44,836,321 | Change Asterix cat 240 stream data (xml) to radar image (visualize) using python or C++ | <p>I do have a stream of radar data cat 240 coming from SPX Radar Simulator and Asterix is successfully receiving the stream and parsing it. What I need is to visualizing radar data on my monitor as radar image. See the attachment.</p>
<p>I am trying to write a code in python to parse the cat 240 line by line output g... | <p>You can use the SPx scan converter to convert the ASTERIX CAT-240 radar stream into a bitmap or image for display. The scan converter has a full C++ API for receipt, processing, scan conversion and display of radar video.</p> | python|numpy | 0 |
351,236 | 44,933,518 | How to remove RunTimeWarning Errors from code? | <p>I keep getting <code>RuntimeWarning</code> when I run the regression code at the very bottom. I am not sure how to fix them. I believe it may be the <code>attencoef</code> list because there is some <code>nan</code> values in it. Any suggestions? </p>
<p>These are the errors I am getting:</p>
<pre><code>C:\Users\M... | <p>You should filter the warning with:</p>
<pre><code>import warnings
warnings.filterwarnings("ignore", category=RuntimeWarning)
</code></pre>
<p>The <code>category</code> is the type of warning you want to silence.</p> | python|numpy|linear-regression|compiler-warnings|spyder | 22 |
351,237 | 44,996,913 | Dataset_factory importerror: Tensorflow fine-tuning a pre-trained model from an existing checkpoint on custom data | <p>I am working on retraining a a pre-trained (inception v1) model on a small custom dataset based on the instructions of the tensorflow github <a href="https://github.com/tensorflow/models/blob/master/inception/README.md" rel="nofollow noreferrer">page</a></p>
<p>Creating the dataset:</p>
<pre><code>python build_ima... | <p>First of all, make shure that you have the latest version of the code <a href="https://github.com/tensorflow/models/tree/master/slim" rel="nofollow noreferrer">https://github.com/tensorflow/models/tree/master/slim</a> . Check, that datasets folder exists. You also may try to add datasets (not dataset_factory.py) fol... | python|machine-learning|tensorflow|computer-vision | 1 |
351,238 | 44,960,170 | Plotting mean lines for different 'hue' data on a Seaborn FacetGrid plot | <p>I am working with the Titanic passenger dataset (from <a href="https://www.kaggle.com/c/titanic" rel="nofollow noreferrer">Kaggle</a>) as part of a Udacity course. I am using a Seaborn FacetGrid to look at passenger age distribution profiles by Travel class and Gender - with hue as 'Survived' (1/0).</p>
<p>The plot... | <p>The <code>kwargs</code> contain the label and the color of the respective hue. Therefore, using </p>
<pre><code>def vertical_mean_line_survived(x, **kwargs):
ls = {"0":"-","1":"--"}
plt.axvline(x.mean(), linestyle =ls[kwargs.get("label","0")],
color = kwargs.get("color", "g"))
txkw = di... | python|pandas|matplotlib|seaborn|facet-grid | 10 |
351,239 | 45,071,647 | Tensorflow fine tuning tutorial without Bazel | <p>I am using the Google Research tutorial for fine tuning the Inception model. </p>
<p><a href="https://github.com/tensorflow/models/tree/master/inception/README.md#how-to-fine-tune-a-pre-trained-model-on-a-new-task" rel="nofollow noreferrer">The tutorial can be found here</a></p>
<p>The tutorial uses Bazel.</p>
<p... | <p>Yes you can.Just check
<a href="https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/?utm_campaign=chrome_series_machinelearning_063016&utm_source=gdev&utm_medium=yt-desc#4." rel="nofollow noreferrer">this</a>.In the section 5.</p> | tensorflow | 0 |
351,240 | 44,901,834 | Tensorflow in android: Linear regression | <p>I have completed training a simple linear regression model on jupyter notebook using tensorflow, and I am able to save and restore the saved variables like so:</p>
<p><a href="https://i.stack.imgur.com/bC9Kc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bC9Kc.png" alt="Grab Data"></a></p>
<p>N... | <p>I may have misunderstood the question but:</p>
<p>Given that the model is pre-trained, the weight and bias are not going to change, you can simply use the W and b values calculated in the Jupyter notebook and hard code them in a simple expression</p>
<pre><code><soc> = -56.0719*<height> + 98.3029
</cod... | android|python|tensorflow|linear-regression|nightly-build | 2 |
351,241 | 44,951,624 | Numpy stack with unequal shapes | <p>I've noticed that the solution to <a href="https://stackoverflow.com/questions/18595488/combining-2d-arrays-to-3d-arrays">combining 2D arrays to 3D arrays</a> through <code>np.stack</code>, <code>np.dstack</code>, or simply passing a list of arrays only works when the arrays have same <code>.shape[0]</code>.</p>
<p... | <p>I've made a function that works for this problem, assuming that you are willing to pad to make the shape rectangular, and you have arbitrarily higher multidimensional arrays. It could probably be optimised further, but it's not too bad.</p>
<pre><code>import numpy as np
def stack_uneven(arrays, fill_value=0.):
... | python|python-3.x|numpy | 3 |
351,242 | 44,873,604 | dynamically calling R library from python using rpy2 | <p>based on <a href="https://stackoverflow.com/a/44827220/1639834">https://stackoverflow.com/a/44827220/1639834</a>:</p>
<p>I have an R routine that I need to call from my python code in a dynamic way.
For this I intended to use rpy2. </p>
<p>First the R code I would like to make use of from python (first time R use... | <p>Consider using the <code>x.names.index('myname')</code> to reference nested named elements in R objects. See <a href="http://rpy.sourceforge.net/rpy2/doc-2.2/html/vector.html" rel="nofollow noreferrer">rpy2 docs</a>. And as a reminder and demonstrated below you can still reference both R and Python nested objects wi... | python|r|numpy|rpy2 | 0 |
351,243 | 45,124,695 | pybind11 return numpy array of objects | <p>Using pybind11 C++ API and python3, how can we properly create a numpy array of objects (i.e. unicode strings) in the C++ implementation and return it back to python? What is the exact memory layout of the underlying data array passed into pybind11::array()? How exactly do we need to manage memory, i.e. delete/free?... | <p>Turns out that it is necessary to:</p>
<ol>
<li><p>create an array of PyObject pointers, fill the array, i.e.</p>
<pre><code>auto* pbuf = new PyObject*[arraySize]; // or create via pybind11 API...
pbuf[0] = <new object...>
pbuf[1] = <new object...>
etc.
</code></pre></li>
<li><p>create an "object" py::... | c++|numpy|pybind11 | 3 |
351,244 | 45,122,032 | How to read file with mixed data type into a numpy array in Python? | <p>How to read file with mixed data type into a numpy array in Python?</p>
<p>I'm a new python learner. I'm trying to read an existing file with mixed data type into a numpy array.</p>
<p>The content of file data.txt (if comma is not a good symbol, it can be replaced by space):</p>
<pre><code> ,'A','B','C','D'
'A'... | <p>You could use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>pandas.read_csv</code></a>:</p>
<pre><code>>>> import pandas as pd
>>> df = pd.read_csv('data.txt', index_col=0, sep=',')
>>> print(df)
'A' 'B' 'C' ... | python|arrays|numpy|readfile|mixed | 1 |
351,245 | 45,015,915 | python most common pair of indices in 3 x n array | <p>I have a numpy array with shape (3, 600219), which is a list of indices. </p>
<p>i.e.</p>
<pre><code>array([[ 0, 0, 0, ..., 2879, 2879, 2879],
[ 40, 40, 40, ..., 162, 165, 168],
[ 249, 250, 251, ..., 195, 196, 198]])
</code></pre>
<p>The first row are time indices, the second a... | <p>I just used a small sample of your data, but I think you'll get the point:</p>
<pre><code>import numpy as np
array = np.array([[ 0, 0, 0, 2879, 2879, 2879],
[ 40, 40, 40, 162, 165, 168],
[ 249, 250, 251, 195, 196, 198]])
# Zip together only the second and third rows
only_coords = ... | python|arrays|sorting|numpy|weather | 4 |
351,246 | 44,965,192 | Slicing columns in Python | <p>I am new in Python. I want to <strong>slice columns from index 1 to end of a marix</strong> and perform some operations on the those sliced out columns. Following is the code: </p>
<pre><code>import numpy as np
import pandas as pd
train_df = pd.read_csv('train_475_60_W1.csv',header = None)
train = train_df.as_mat... | <p>The thing you should know with slicing for single dimension even in normal lists is that it looks like this:</p>
<pre><code>[start : end]
</code></pre>
<p>with start <code>included</code> and end <code>excluded</code>.</p>
<p>you can also use these:</p>
<pre><code>[:x] # from the start to x
[x:] # from x to the ... | python|numpy|dataframe | 3 |
351,247 | 45,038,489 | numpy append 3D matrices | <p>What happens when I <code>numpy.append</code> two 3-D matrices?</p>
<p>Ex.
<code>a</code> is a matrix of shape (662, 887, 3), <code>b</code> is a matrix of shape <code>(77, 103, 100)</code>.</p>
<p>I used <code>numpy.append</code> to create a matrix <code>c</code>, which is of shape <code>(2554682,)</code>.</p>
... | <p>(<code>662</code> * <code>887</code> * <code>3</code>) + (<code>77</code> * <code>103</code> * <code>100</code>) = <code>2554682</code></p>
<p>It squished all the elements into a 1-Dimensional vector with the amount of elements being the sum of the amount of elements of <code>a</code> and <code>b</code>.</p> | numpy | 2 |
351,248 | 45,100,740 | parsing dates pandas but incorrect format | <p>pandas dataframe here need to parse date column </p>
<pre><code> date total
3 Mar-06 1.8
4 Apr-06 1.7
</code></pre>
<p>have tried <code>earning['date'] = earning.date.apply(lambda x: pd.to_datetime(x, format='%b-%y'))</code></p>
<p>which I thought was the correct format but does not seem to be so, can... | <pre><code>earning.date = earning.date.apply(lambda x: x.replace(' ', ''))
pd.to_datetime(earning.date, format='%b-%y')
</code></pre>
<p>done</p> | python|pandas|datetime | 0 |
351,249 | 45,077,507 | Pandas DataFrame: remove � (unknown-character) from strings in rows | <p>I have read a csv file into python 2.7 (windows machine). Sales Price column seems to be mixture of string and float. And some rows contains a euro symbol €. Python sees € as �. </p>
<pre><code>df = pd.read_csv('sales.csv', thousands=',')
print df
Gender Size Color Category Sales Price
Female 36-38 Bl... | <p>I think @jezrael comment is valid. First you need to read the file with encoding(see <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html</a> under encoding section)</p>
<pre><code... | pandas|encoding|non-ascii-characters | 3 |
351,250 | 45,001,687 | looping through groupby in Python dataframe | <p>I am new to python. I am trying to write the code on the python dataframe to loop through the data. Below is my initial data:</p>
<pre><code>A B C Start Date End Date
1 2 5 01/01/15 1/31/15
1 2 4 02/01/15 2/28/15
1 2 7 02/25/15 3/15/15
1 2 9 03/11/15 3/30/15
1 2 8 03... | <p>I was not exactly clear with the question. based on my understanding, this is what i could come up with. Iam using Cross Join instead of a loop.</p>
<pre><code>import pandas
data = #Actual Data Frame
data['Join'] = "CrossJoinColumn"
df1 = pandas.merge(data,data,how = "left",on = "Join",suffixes = ["","_2"])
df1 = d... | python|pandas | 0 |
351,251 | 44,897,075 | How to read column one by one in python pandas? | <p>I have read file from URL as follows :</p>
<pre><code> url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
names = ['sepal length', 'sepal width', 'petal length', 'petal width', 'class']
data = pd.read_csv(url, names=names)
print(data.shape)
print(data)
</code></... | <p>You can use <code>describe</code>:</p>
<pre><code>data.describe()
</code></pre>
<p>Output:</p>
<pre><code> sepal length sepal width petal length petal width
count 150.000000 150.000000 150.000000 150.000000
mean 5.843333 3.054000 3.758667 1.198667
std 0.828066 0.43... | python|pandas|scikit-learn|anaconda | 4 |
351,252 | 56,949,101 | Add column from other dataframe on a specific column while keeping original indexes | <p>New to Pandas and trying to add a column from <code>df2</code> to <code>df1</code> based on a column that both of the dataframes have in common. I want to preserve the indexes in <code>df1</code>. Notice that <code>df2</code> has lots of duplicate rows, including duplicate ItemIds.</p>
<pre class="lang-py prettypri... | <p>A simple left merge will do the job for you. </p>
<p>Try this : </p>
<pre><code>dataframe_1 = dataframe_1.merge(dataframe_2[['ItemId','column_to_merge']], on = 'ItemId', how = 'left')
</code></pre> | pandas|dataframe|join|merge|concatenation | 1 |
351,253 | 56,898,236 | Selecting array of array based on condition in array? | <p>I have this array :</p>
<pre><code>a = [[255,255,255,0],[255,255,254,0],[1,2,3,4],[1,4,6,8],[1,5,7,0]]
</code></pre>
<p>I have tried using numpy but i don't know how to do it further.</p>
<p>I want it omit all the array of array having 0 in the <code>a[i][3]</code>, that is I want my output as <code>a=[[1,2,3,4]... | <p>You could use a list comprehension : </p>
<pre><code>a = [[255,255,255,0],[255,255,254,0],[1,2,3,4],[1,4,6,8],[1,5,7,0]]
a = [x for x in a if x[3] != 0]
</code></pre>
<hr>
<p>Output : </p>
<pre><code>[[1, 2, 3, 4], [1, 4, 6, 8]]
</code></pre> | python|python-3.x|numpy | 0 |
351,254 | 56,939,275 | How to model LSTM properly in Tensorflow and Keras | <p>I have a dataset in a CSV format that looks like this:</p>
<pre><code> 1,dont like the natives
2,Keep it local always
2,Karibu kenya
</code></pre>
<p>The label <code>1</code> indicates a hate speech while <code>2</code> indicates a positive.</p>
<p>Here is my code:</p>
<pre><code>import numpy as np
import csv
... | <p>Replace</p>
<pre><code>prediction = model.predict(tokenized_text, batch_size=1, verbose=1)
</code></pre>
<p>with</p>
<pre><code>prediction = model.predict(tokenized_text[None], batch_size=1, verbose=1)
</code></pre> | python|tensorflow|keras|nlp | 1 |
351,255 | 57,069,274 | Dask, changing column type from second to last | <p>I have multiple CSV's that:</p>
<ul>
<li>Have the identifier string in the first column (i.e. <code>"companyA"</code>).</li>
<li>Have a variable number of subsequent columns (for different properties depending on the CSV), often ranging in the 1000s of columns (and 100000s data rows).</li>
<li>From the second col t... | <p>You can select first, between and last column and join together by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a>:</p>
<pre><code>df = pd.concat([dr.iloc[:,[0]], dr.iloc[:, 1:-1].astype(int), dr.iloc[:, [-1]]], axis=1)
</code>... | python|pandas|dask | 1 |
351,256 | 56,992,488 | Is it possible to download tensorflow library and use without installation? | <p>I have to use tensorflow on a server where I don't have access to <code>pip install</code> or anything like that.</p>
<p>I know for custom python modules you want to import you can usually just do </p>
<pre class="lang-py prettyprint-override"><code>import sys
sys.path.append('path/to/module')
import module
</code... | <p>I often find myself in similar situations when I have to run Python scripts that use 3rd party modules in servers where I do not have access to a cmd.</p>
<p>One solution is to install the package within the Python script, using the following function (taken from <a href="https://stackoverflow.com/a/15950647/714436... | python|tensorflow | 0 |
351,257 | 56,997,664 | How to reshape the dataframe and transform columns as rows? | <pre><code>df = pd.DataFrame({'ProdcutID': {0: '2125',1: '1204',2: '4390'},
'Color':{0:'R',1:'B',2:'Y'},
'From':{0:'CA',1:'OH',2:'IN'},
'Color1':{0:'P',2:'W'},
'From1':{0:'NJ',2:'DE'},
'Color3':{1:'G',2:'P'},
'From3':{1:'MX',2:'PA'}})
</code></pre>
<p><a href="ht... | <p>Try this using <code>pd.wide_to_long</code>, but first you need to rename a couple of column headers to match the pattern of rest of the columns.</p>
<pre><code>df1 = df.rename(columns={'Color':'Color0','From':'From0'})
pd.wide_to_long(df1,['Color','From'],'ProdcutID','No').sort_index(level=0).dropna()
</code></pre... | python|pandas|dataframe | 2 |
351,258 | 56,882,171 | pd.DatetimeIndex keep returning the wrong month | <p>I am reading data from a csv file, and I have a Date column formatted as <strong>"dd/mm/yyyy"</strong>.</p>
<p>I just want to extract the month from it.</p>
<p>The problem is that in some cases (based on my observation it is when dd > 12), it returns the month correctly. Otherwise, it returns the day instead.</p>
... | <p>One thing you can do is recast the <code>df['Date']</code> column as a datetime. </p>
<p>You can specify that the days are first with the dayfirst parameter.</p>
<pre><code>df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)
</code></pre>
<p>source: <a href="https://pandas.pydata.org/pandas-docs/stable/referen... | python-3.x|pandas|datetimeindex | 3 |
351,259 | 57,035,858 | Higher-order multivariate derivatives | <p><strong>Is there a packaged way to compute higher-order multivariate derivatives (using finite differences, not symbolic calculations) in Python?</strong></p>
<p>For example, if <code>f</code> computes the function cos(x)*y from R^2 to R, i.e., <code>f</code> takes numpy arrays of shape <code>2</code> and returns f... | <p>There's <code>scipy.optimize._approx_derivative</code> which does it. This is however not a public function, so if you end up using it, you're on your own. </p> | python|numpy|scipy|scientific-computing | 0 |
351,260 | 57,181,665 | Parameters computation of LSTM | <p>I am trying to compute the total parameters of LSTM model, and I have some confusion.</p>
<p>I have searched some answers, such as <a href="https://datascience.stackexchange.com/questions/10615/number-of-parameters-in-an-lstm-model">this post</a> and <a href="https://stackoverflow.com/questions/38080035/how-to-calc... | <p>In your case, you defined a LSTM cell via this line <code>c1 = tf.nn.rnn_cell.LSTMCell(h1)</code>. To answer your question, here I will introduce the mathematical definition of LSTM. Like the picture (picture source <a href="https://en.wikipedia.org/wiki/LSTM" rel="nofollow noreferrer">wikipedia-lstm</a>) below,</p>... | tensorflow|deep-learning|lstm | 1 |
351,261 | 56,886,764 | How to use Dask to read data from SQL <connection string>? | <p>There are not enough examples in the documentation on how to read data from sqlAlchemy to a dask dataframe.</p>
<p>Some examples i see are in terms of : </p>
<pre><code> df = dd.read_sql_table(table='my_table_name', uri=my_sqlalchemy_con_url, index_col='id')
</code></pre>
<p>But my query is not to get the entir... | <p>The default partition size for numeric indexes is 256 MB, unless you specify npartitions.
For string indexes, you can use the <code>divisions</code> argument, e.g.</p>
<pre><code>... division = sorted(['red', 'green', 'blue', 'yellow']) ...
</code></pre>
<p>if you have an index with color names.</p>
<p>See also <... | python|pandas|dask | 1 |
351,262 | 57,029,481 | plot column name on x-axis | <p>I have 20 columns corresponding to 20 device names and only one row with values throughout the all columns. I want to plot machine names on x-axis and corresponding row value on y-axis</p>
<pre><code>df
device-1 device-2 device-3 device-4 device-5...
0 1 5 0.5 ... | <p>try this:-</p>
<pre><code>cols =list(df.columns.values)
for i in range(0,len(cols)):
plt.scatter(i, df[cols[i]])
plt.xticks(list(range(0,len(cols))))
plt.axes().set_xticklabels(cols)
</code></pre> | python|pandas | 3 |
351,263 | 57,004,159 | Increase and decrease data-series proportional to mean | <p>I have a precipitation data-series in a Pandas DataFrame with as index the dates between 2009-2018 (3652). I'm trying to find a way to decrease or increase proportional the cumulative precipitation relative to the mean by a given percentage (decrease for values < mean, increase for values > mean).</p>
<p><strong... | <p>Assumption is that you y data i always growing when its going into bigger x. Otherwise you need to sort data first.</p>
<p>First you need to create column with percentage proportion according to df shape. Then calculate new value.</p>
<p>Here You go:</p>
<p>=^..^=</p>
<pre><code>import pandas as pd
import matplo... | python|pandas|numpy|dataframe|data-science | 1 |
351,264 | 57,239,074 | Function to get acceptable values for a variable pandas | <p>I am new to python and hence will appreciate any help on this!</p>
<p>Suppose i have a bunch of columns in a dataset with categorical values. Let's say Gender, marital status, etc.</p>
<p>While doing input validation of the dataset, i need to check if the values of columns are within an acceptable range.</p>
<p>F... | <p>You could do something like the following, where we assume that you're storing your data frames in a dictionary called <code>df_dict</code>, and the collection of accepted values in a data frame called <code>df_accepted</code>:</p>
<pre class="lang-py prettyprint-override"><code># First, use the dataset and variabl... | python|pandas | 1 |
351,265 | 57,242,648 | Screen Size of the camera on the example object detection of tensorflow lite | <p>On the tensorflow lite example object detection, the camera don't take all the screen but just a part.</p>
<p>I tried to find some constant in CameraActivity, CameraConnectionFragment and Size classes but no results.</p>
<p>So I just want a way to put the camera in all the screen or just an explanation.</p>
<p>Th... | <p>I just find the solution, it's in the CameraConnectionFragment class :
protected static Size chooseOptimalSize(final Size[] choices, final int width, final int height) {
final int minSize = Math.max(Math.min(width, height), MINIMUM_PREVIEW_SIZE);
final Size desiredSize = new Size(1280, 720);</p>
<pre><code>... | tensorflow|camera|size|tensorflow-lite | 3 |
351,266 | 56,917,734 | how to download .csv file using API Endpoint in pandas | <p>I want to download a csv file from an API endpoint with pandas. I am using the following code: </p>
<pre><code>df=pd.read_csv('https://data.cityofnewyork.us/resource/nu7n-tubp.csv').
</code></pre>
<p>However, the resulting dataframe has only 1,000 rows, even though the dataset is much larger (around 121k rows). Ho... | <p>Socrata <a href="https://support.socrata.com/hc/en-us/articles/202949268-How-to-query-more-than-1000-rows-of-a-dataset" rel="nofollow noreferrer">typically requires you</a> to page through data, which is set at 1,000 rows. You could modify it by increasing it by using the <a href="https://dev.socrata.com/docs/querie... | python|pandas|socrata|soda | 0 |
351,267 | 56,906,669 | Adding a minus sign before pd.get_dummies return 255 instead of -1 | <p><s>I think this is a bug, so not strictly on-topic on this site, but I'd like the help of the pandas' community here with it.</s> Let's consider this dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'col1': [0,1,1,0,1], 'col2':list('aabbc')})
</code></pre>
<p>If I use <code>pd.get_dummies</code> on... | <p>Probably you want </p>
<pre><code>(-pd.get_dummies(df.col2, dtype=int))
</code></pre>
<hr>
<pre><code> a b c
0 -1 0 0
1 -1 0 0
2 0 -1 0
3 0 -1 0
4 0 0 -1
</code></pre>
<p>since the default <code>dtype</code> for <code>pd.get_dummies</code> is 8-bit unsigned int (<code>dtype : dtype, default np.uint... | python|pandas | 3 |
351,268 | 57,083,724 | How to lookup two different ranges based on row's value Pandas dataframe | <p>I'm trying to do a conditional vlookup but with pandas. Here's the data i'm using</p>
<p><strong>n_age_scores</strong></p>
<pre><code>type n aging_n mini_n percent_n
new <30 days 0 0.5543
new 31-50 days 31 0.6446
new 51-100 days 51 0.3134
</code></pre>... | <p>You can define your custom function to extract the data from the two dataframes and use it with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer">apply</a>.</p>
<p>If I understood correctly what you want, the code below shoud do the job.<br>
I... | python|pandas|numpy | 0 |
351,269 | 57,078,539 | How can I sum every n array values and place the result into a new array? | <p>I have a very long list of array numbers I would like to sum and place into a new array. For example the array:</p>
<pre><code>[1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8]
</code></pre>
<p>would become:</p>
<pre><code>[6,15,16,6,15,x]
</code></pre>
<p>if I was to sum every 3.</p>
<p>I cannot figure out how to go about it.... | <p>Cut the array to the correct length first then do a reshape.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
N = 3
a = np.array([1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8])
# first cut it so that lenght of a % N is zero
rest = a.shape[0]%N
a = a[:-rest]
assert a.shape[0]%N == 0
# do the reshape
... | python|arrays|numpy | 2 |
351,270 | 57,001,171 | Installing Keras/Tensorflow in R | <p>I am trying to install Keras/Tensorflow as per the sequence mentioned <a href="https://www.analyticsvidhya.com/blog/2017/06/getting-started-with-deep-learning-using-keras-in-r/" rel="nofollow noreferrer">here </a></p>
<p>It was fine till I installed "tensorflow" using install.packages("tensorflow") but when I tried... | <p>I checked all of the suggestions. None of them worked. This worked for me on Windows 10</p>
<p>1- Open rstudio and uninstall these package if you already installed using:</p>
<pre><code>uninstall.packages(c("keras", "tensorflow","tfruns"))
</code></pre>
<p>2- uninstall rtools from your ... | r|tensorflow|keras | 0 |
351,271 | 57,221,881 | Vectorizing String comparison in Pandas | <p>I'm currently starting with python pandas to automize excel manipulation and have some speed problems regarding larger excel files. Now I try to optimize step by step.</p>
<p>The second step in my script creates 3 new columns: error1, error2 or correct.
If there is no information (NaN) in DATE2 only error1 should h... | <p>To be honest I'm not sure why you're doing any of this but here you go</p>
<pre><code>df['DATE1'] = pd.to_datetime(df['DATE1'], errors = 'coerce')
df['DATE2'] = pd.to_datetime(df['DATE2'], errors = 'coerce')
# Set error1
error1_bool = pd.isnull(df['DATE1']) | pd.isnull(df['DATE2'])
df.loc[error1_bool, 'error1'] = ... | python|pandas|string-comparison | 0 |
351,272 | 57,284,896 | How to calculate the aggregate variance in pivot table | <p>when I use <code>aggfunc = np.var</code> in pivot table. I found the value of metrics became <code>NaN</code>. But when it comes to <code>aggfunc = np.sum</code> it doesn't. </p>
<p>why the original value was changed with <code>aggfunc = np.var</code> or <code>aggfunc = np.std</code>. I can not found answer in the ... | <p>Pandas uses by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.var.html" rel="nofollow noreferrer">default</a> <code>ddof = 1</code>, see <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.var.html" rel="nofollow noreferrer">here</a> for details on <code>np.var</... | pandas|pivot-table | 2 |
351,273 | 57,118,650 | How to split data into train and test keeping in mind the groupby column in pandas? | <p>I would like to split the data set into test and train dataset in the ratio 20:80. However, while splitting, I do not want to split in a manner that 1 S_Id value has few data points in train and other data points in test.</p>
<p>I have a dataset as:</p>
<pre><code>S_Id Datetime Item
1 ... | <p>I don't believe there is a direct function that does so, so you could write a customized one :</p>
<pre class="lang-py prettyprint-override"><code>def sample_(we_array, train_size):
"""
we_array : used as the weight of each unique element on your S_id column,
it's normalized to represent a probabilit... | python|pandas|train-test-split | 1 |
351,274 | 56,927,462 | 'numpy.float64' object is not iterable - Content-based filtering model | <p>I try to make Content-based filtering model but get an TypeError "'numpy.float64' object is not iterable". I'm newbie in Python and would be very appreciate if you give me some advice, what should i edit. </p>
<p>With other dataset this code works well, but this one is the same, what can be a problem?</p>
<pre cla... | <p>If you pass in a number as <code>ids</code>,
rather than some iterable sequence of numbers,
then you will trigger such a type error.</p>
<p>Arrange for this dataset to contain multiple IDs,
similar to your other datasets.</p> | python|python-3.x|numpy | 1 |
351,275 | 56,969,455 | Groupby sum, count, and pattern | <p>I have a dataframe as shown below</p>
<pre><code> ID Status Date Cost
0 1 F 22-Jun-17 500
1 1 M 28-Jul-17 100
2 2 M 29-Jun-17 200
3 3 M 30-Mar-17 300
4 4 F 10-Aug-17 800
5 2 F 2-Sep-17 600
6 2 F 5-Jan-18 500
7 1 F 23-Jun-18 600
8 3 F 2... | <p>First convert column to datetimes and sorting by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>DataFrame.sort_values</code></a>, then aggregate by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.gro... | pandas|pandas-groupby | 2 |
351,276 | 57,006,508 | Changing the values of every second row (pandas data frame) | <p>I would like to change the values of the rows of the first column to 'green' for every second value and 'red' for the remaining values (see below, where I started doing it with the replace method, but it is not very efficient.</p>
<pre><code> color IntDen Density Condition
0 green 936645 Low Ctrl
1 red... | <p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> with modulo <code>2</code> per index values if default <code>RangeIndex</code>:</p>
<pre><code>df['color'] = np.where(df.index % 2, 'red', 'green')
</code></pre>
<p>General sol... | python|pandas|rows | 3 |
351,277 | 57,078,199 | 2d array minus 1d array | <p>In python numpy:</p>
<pre><code>A = [[1,2,3],[4,5,6],[7,8,9]]
b = [2,3,5]
</code></pre>
<p>want <code>[1,2,3] -2, [4,5,6]-3, [7,8,9] -5</code></p>
<p>e.g. ideal result:</p>
<pre><code>[[-1,0,1],[1,2,3],[2,3,4]]
</code></pre>
<p>any way solve this without loop?</p> | <p>You have not used Numpy at all. It is pretty easy with that. You need to add an extra dimension to b with None or numpy.newaxis and then subtract.</p>
<pre><code>import numpy
A = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
b = numpy.array([2,3,5])
c= A-b[:,None]
print(c)
</code></pre>
<p>Output:</p>
<pre><code>[[-1 ... | python|arrays|numpy | 3 |
351,278 | 56,964,085 | Database connection is busy with results from another command | <p>What I am trying to do was to fetch data from an data API which I did using Python and the data that was received as response from the API, was stored in panda dataframe.</p>
<p>Then those dataframes were converted to csv and the csv was pushed to Azure blob storage.</p>
<p>The same program post pushing the csv to... | <p>It got fixed by using </p>
<p>MARS_Connection=yes</p>
<p>In the connection string for database</p> | python|sql-server|pandas|azure|tsql | 0 |
351,279 | 57,130,799 | Pandas get second minimum value from datetime column | <p>I have a data frame with a DateTime column, I can get minimum value by using </p>
<pre><code>df['Date'].min()
</code></pre>
<p>How can I get the second, third... smallest values</p> | <p>Use <code>nlargest</code> or <code>nsmallest</code></p>
<p>For second largest,</p>
<pre><code>series.nlargest(2).iloc[-1]
</code></pre> | python-3.x|pandas|dataframe | 3 |
351,280 | 57,022,421 | How to find the index of header in csv file? | <p>Lets say I have a csv list like below:</p>
<pre><code> A B C
aa bb cc
dd ee ff
gg hh ii
</code></pre>
<p>And I want to know what column, B belongs to?</p>
<p>In other words what command can I use to give me number 2 for the column that has B as the header? </p> | <p>You can use pandas as get column headers as a list, then use list indexing to get the position, from 0.</p>
<pre><code>import pandas as pd
df = pd.read_csv('path/to/csv.csv')
df.columns.to_list().index('B')
</code></pre> | python|pandas|csv | 0 |
351,281 | 57,008,169 | Keeping the lowest value of duplicates across multiple columns in dataframe | <p>I have the following data frame:</p>
<pre><code>import pandas as pd
data = dict(name=['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c'],
objective=[20.0, 20.0, 25.0, 40.0, 40.5, 41.0, 60.0, 60.0],
price=[0.5, 1.0, 1.5, 1.0, 1.2, 1.4, 0.5, 1.0])
df = pd.DataFrame(data, columns=data.keys())
</code></pre... | <p>What I will do </p>
<pre><code>df.sort_values('price').drop_duplicates(['name','objective'],keep='last').assign(cnt=1)
Out[421]:
name objective price cnt
0 a 20.0 0.5 1
2 a 25.0 1.5 1
3 b 40.0 1.0 1
4 b 40.5 1.2 1
5 b 41.0 1.4 1
6 c... | python|pandas|dataframe|group-by | 2 |
351,282 | 56,973,745 | How to compile multiple excel files in numeric order (file1.xls, file2.xls, etc) into one python file? | <p>I am trying to compile several .xls files together. I found some code that works but it put in the files out of order. The files are names therm_sensor1.xls, therm_sensor2.xls, etc. I need the output to be in numeric order but my current code seems to have them scrambled. I am very new to computer coding so an expla... | <p>The problem here is (probably) due to the difference in the way humans and computers tend to sort things. Take a list like this:</p>
<pre><code>files = ['file10.xls', 'file2.xls', 'file1.xls']
</code></pre>
<p>The computer sorts this list in a way that looks unintuitive to humans (because it goes <code>1</code>, ... | python|excel|pandas|glob | 0 |
351,283 | 57,001,614 | Tensorflow implementation for bank transaction classification | <p>I am building a simple machine learning model that takes bank transactions as input (see features below) and I want to predict the spend category (label). I have already worked through some beginner's tutorials, such as <a href="https://developers.google.com/machine-learning/crash-course/" rel="nofollow noreferrer">... | <p>This seems to be a classification problem, but there are some issues for me with your question, there are some steps that you need to take before dumping all the data into a model.</p>
<p>The thing is that I see no preprocessing of the data, are you using all features? Do they need to be scaled? Do you need to enco... | python|tensorflow|machine-learning | 0 |
351,284 | 57,285,389 | How to Copy Right side Cell value of my search pattern in Excel using python (Preferable pandas) | <p>I want to copy the right side cell value of column in Excel. Which is doesn't contain header.</p>
<p>I am using python 3.6, Pandas module.</p>
<p>My input file is like this</p>
<pre><code>Name Hierarchy Module Values
Name1 top top ... | <p>You can try this using <code>pd.read_fwf</code>:</p>
<pre><code>from io import StringIO
txtfile = StringIO("""Name Hierarchy Module Values
Name1 top top 0
Name11 M1 m11 1
Name11 ... | python|python-3.x|pandas | 1 |
351,285 | 56,941,107 | Trouble writing webscraping results to csv file | <p>I'm trying to write my output to a csv-file. I've tried with both pandas and csv, but I just get an empty csv-file. What am I missing?</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import pandas as pd
import csv
r = requests.get('https://superstats.dk/program?aar=2018%2F2019')
bs=BeautifulSoup(r.cont... | <p>I don't know how you really worked with <code>csv</code> library, but using it's <a href="https://docs.python.org/3.5/library/csv.html#csv.csvwriter.writerow" rel="nofollow noreferrer"><code>csvwriter.writerow(row_values)</code></a> method you can easily write data to your csv file row by row.</p>
<p>And talking ab... | python|pandas|csv|beautifulsoup | 0 |
351,286 | 57,094,924 | Attempting create bar charts form a Pandas Data Frame. Charts to be specific to the month | <p>Dataframe contains essentially three things.</p>
<p>Date, Count, and Company.</p>
<p>I want to create a program that makes bar charts with count on the y axis and company on the x axis; but there should be multiple charts for different months. for.eg there should be a may chart containing all the companies counts ... | <p>You could add a 'Month' column and group by month and metric:</p>
<pre><code>import datetime
# New month column
month_key = lambda x: datetime.date(x.year, x.month, 1)
df['Month'] = df['Date'].apply(month_key)
# Group by month and metric
df = df.groupby(['Month', 'Metric']).sum()
# One plot for each month
months... | python|pandas|pandas-groupby | 0 |
351,287 | 57,132,089 | Rotating 5D cube with NumPy | <p>I got 2x 5D cubes in the shape of <code>[1, 4, 21, 302, 302]</code> that I need to compare with each other. However the first is rotated with respect to the second.
If I work with just these two images I can fix it by applying <code>np.rot90(np.flipud(a))</code> to the left image, with a being that <code>302x302</c... | <p>Rotating the image like you're describing it is simply transposing/swapping the two axes x and y. For a single image in a 2D array, you would simply do</p>
<pre><code>img.T
</code></pre>
<p>And for a 5D tensor like yours where the image is contained in the last two axes, you would do</p>
<pre><code>img.transpose(... | python|arrays|numpy | 0 |
351,288 | 57,192,270 | How to merge several csv files averaging fields? | <p>I have several csv files name file1, file2, file3, etc. They all look like this (exactly identical, only the floats change):</p>
<pre><code>filename, column1, column2, ... columnN
asdfasd.jpg 23.23, 21.24, 1e-06
ersdadfsd.jpg 223.23, 1.23, 1
assd.jpg 23.23, 1e-08, 232.1
...
<... | <pre class="lang-py prettyprint-override"><code>all_csv = []
for one_file in list_of_file:
all_csv.append(pd.read_csv(one_file))
df = pd.concat(all_csv).groupby('filename').mean()
</code></pre>
<p>should do want you want.</p>
<p>As example, with two csv:</p>
<pre class="lang-py prettyprint-override"><code>>&g... | python|python-3.x|pandas|csv | 1 |
351,289 | 56,999,387 | "TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed." when calling map function on dataset | <p>I am trying to load and process images with an unique crop factor learned from each image. I keep getting an error stating I can't use a tensor as a Python boolean.</p>
<p>For each image, I want to threshold one row of pixels from the center of the image and calculate the percent of pixels over some threshold. I wa... | <p><a href="https://www.tensorflow.org/api_docs/python/tf/image/central_crop" rel="nofollow noreferrer"><code>tf.image.central_crop</code></a> requires the <code>central_fraction</code> parameter to be an actual float value, so TensorFlow tensors cannot be used. It is easy to replicate the functionality though, for exa... | python|tensorflow|image-processing|keras | 1 |
351,290 | 57,281,829 | How to reshape a multidimensional array from a particular arrangement to another arrangement? | <p>I have a <code>before_arr</code>(2 x 3 x 4) multidimensional array. I want to turn it into a <code>new_arr</code> (3 x 2 x 4) with a specific arrangement pattern which I wrote below. </p>
<pre><code>import numpy as np
before_arr = np.array([
[
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
],
... | <p>use <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow noreferrer"><code>zip</code></a> to match respective rows.</p>
<p>try this:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
before_arr = np.array([
[
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],... | python|arrays|numpy|tensor | 2 |
351,291 | 57,104,880 | How can I accelerate processing tons of patches in a image? | <p>I wrote a function to process the image, in which I extract many patches and then process them using the same function(func) to generate a new image. However, this is very slow because of two loop, func, the number of patches, size of the patches. I don't know how can I accelerate this code.</p>
<p>The function is ... | <p>If your computer has more than one CPU, you could multi-thread this process by submitting it to a <code>ThreadPoolExecutor</code></p>
<p>Your code should look something like this:</p>
<pre><code>from concurrent.futures import ThreadPoolExecutor
from multiprocessing import cpu_count()
executor = ThreadPoolExecutor... | python|numpy|parallel-processing|computer-vision|image-preprocessing | 0 |
351,292 | 56,903,133 | How can I copy an entire column of data (the number of rows are not fixed) to a new column in the same excel file, in Python? | <p>I have an excel file containing a column of 'Usernames' and I want to copy-paste that data into the adjacent column in the same sheet and call it 'Passwords'. All this must be done in a Python program.</p> | <p>You can try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.ExcelWriter.html" rel="nofollow noreferrer">pandas.ExcelWriter</a>:</p>
<pre><code>import pandas as pd
writer = pd.ExcelWriter('testsheet.xlsx', engine='openpyxl')
wb = writer.book
df = pd.read_excel("testsheet.xlsx")
df['Passw... | python|excel|pandas | 1 |
351,293 | 57,083,154 | Read binary file to array of complex numbers | <p>I have a binary file written as </p>
<pre><code>16b-Real (little endian, 2s compliment)
16b-Imag (little endian, 2s compliment)
.....repeating
</code></pre>
<p>I need to convert it to a 1D array of complex numbers. Can't figure out how to combine the "tuples or lists" into a single value</p>
<pre><code>import num... | <p>You can convert each tuple to a <a href="https://docs.python.org/3/library/functions.html#complex" rel="nofollow noreferrer">complex</a> number while iterating over the list of tuples</p>
<pre><code>array = [(531, -660), (267, -801), (-36, -841) ,(835, -102) ,(750, -396), (567, -628)]
#Iterate over each element an... | python|python-3.x|numpy | 3 |
351,294 | 57,115,409 | What metric to use to define model performance when the change in dependent variable is very small? | <p>I have built a regression model with 5 inputs and 1 output.</p>
<p>I am using r2_score as a metric to evaluate my model performance. </p>
<pre><code>#calculate r2_score
from sklearn.metrics import r2_score
score_test = r2_score(y_pred,y_test)
</code></pre>
<p>Variations in my output variable is very small. My out... | <p>In the comments you ask about algorithm and performance metrics. Here is what I did: I pasted your data into my online open source statistical distributions fitter at <a href="http://zunzun.com/StatisticalDistributions/1/" rel="nofollow noreferrer">http://zunzun.com/StatisticalDistributions/1/</a> and hit the Submit... | pandas|machine-learning|scikit-learn|deep-learning|regression | 0 |
351,295 | 57,212,502 | How do I get the coordinate of a specific number in an array in python? | <p>If I have a matrix say</p>
<pre><code>grid = np.array([
[0,2,1,0],
[0,1,0,-1]])
</code></pre>
<p>how do I call the specific coordinates of a number?
If I wanted to call for 2 and then assign the coordinates of 2 to an variable</p>
<pre><code>start = np.where(grid==2) ## I want to assign my start point to 2
start =... | <p>What were you trying to achieve with <code>start.index</code>? <code>start</code> is a tuple of arrays, and as such does have a <code>index</code> method. But <code>start.index</code> just returns that method; it doesn't evaluate it.</p>
<p>But lets look at what <code>where</code> produces:</p>
<pre><code>In [12... | python|arrays|numpy|matrix|tuples | 1 |
351,296 | 57,293,648 | which methodology should I use if I have nested if else's on a dataframe object | <p>I need to create a new variable in my existing dataframe based on nested if else's. I tried using lambda but it gave me error. Since I am pretty new to Python which methodology should I use for nested if-else statements on a dataframe object?</p>
<p>Lambda function failed.
I used the following for loop but that wa... | <p>I got it finally! :)</p>
<pre><code> data['new'] = data[['year1','year2','mnth2','mnth1']]\
.apply(lambda x: calc_is_late(x['year1'],
x['year2'],
x['mnth2'],
... | python|pandas | 0 |
351,297 | 56,906,675 | Why my code does not return what should it? | <p>I'm new in python, I tried some exercises about <code>numpy</code>, but in this doce result, I find the last 2 numbers isn't correct. I think they should be <code>9**9</code> and <code>10**10</code>, in my limited experience with python, I can´t understand how it come to this result.</p>
<pre class="lang-py prettyp... | <p>If you want to output correct answer, set the dtype as np.int64.
By default numpy guess the datatype implicitly (numpy guessed dtype as np.int32).</p>
<pre><code>import numpy as np
a=np.arange(1,11,dtype=np.int64)
xs,ys=np.meshgrid(a,a)
xs**ys
</code></pre> | python-3.x|numpy | 0 |
351,298 | 45,974,044 | Replace column values using a dictionary | <p>I have this dataframe where gender is expected to be male or female.</p>
<pre><code>from io import StringIO
import pandas as pd
audit_trail = StringIO('''
course_id AcademicYear_to months TotalFee Gender
260 2017 24 100 male
260 2018 12 140 male
274 2016 36 300 mail
274 2017 24 340 female
274 2018 12 200 animal
28... | <p>Add another two dummy entries to your <code>corrections</code> dict:</p>
<pre><code>corrections = {'male' : 'male', # dummy entry for male
'female' : 'female', # dummy entry for female
'mail' : 'male',
'maela' : 'male',
'maae' : 'male'}
</code... | python|pandas|dictionary|dataframe|replace | 4 |
351,299 | 45,731,727 | Matching PyTorch w/ CNTK (VGG on CIFAR) | <p>I am trying to understand how PyTorch works and want to replicate a simple CNN training on CIFAR. The <a href="https://github.com/ilkarman/Blog/blob/master/DL-Examples/CNTK_CIFAR.ipynb" rel="nofollow noreferrer">CNTK</a> script gets to <strong>0.76</strong> accuracy after 168 seconds of training (10 epochs), which i... | <p>I try to answer your first two questions:</p>
<ul>
<li><p>weight initialization: different kinds of layers have their own method, you can find the default weight initialization of all these layers in the following link: <a href="https://github.com/pytorch/pytorch/tree/master/torch/nn/modules" rel="nofollow noreferr... | machine-learning|deep-learning|cntk|pytorch|mxnet | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.