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
374,400
62,114,529
changing range causes a distribution not normal
<p><a href="https://stackoverflow.com/a/37412692">A post</a> gives some code to plot this figure</p> <pre><code>import scipy.stats as ss import numpy as np import matplotlib.pyplot as plt x = np.arange(-10, 11) xU, xL = x + 0.5, x - 0.5 prob = ss.norm.cdf(xU, scale = 3) - ss.norm.cdf(xL, scale = 3) prob = prob / pro...
<p>Given what you're asking Python to do, there's no error in this plot: it's a histogram of 10,000 samples from the tail (anything that rounds to between 10 and 31) of a normal distribution with mean 0 and standard deviation 3. Since probabilities drop off steeply in the tail of a normal, it happens that none of the 1...
numpy
0
374,401
62,281,249
Python Merge Join with multiple join columns
<p>I have two tables with following structure:</p> <pre><code> Table 1 ID City Country 1 India 2 Delhi 3 America 4 New York 5 Germany Table 2 ID Country City 1 India 2 India Delhi 3 America 4 America New York 5 Germany Select * from table1 Left outer...
<p>Once you've stored your data as <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html" rel="nofollow noreferrer">DataFrames</a>, you can use pandas' <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>mer...
python|pandas|dataframe|merge
0
374,402
62,104,731
Pie chart with non labelled data?
<p>How can I produce a pie chart when the data is not labelled as usual? See the example dataframe below:</p> <pre><code> First_Half Second_Half Div Bundesliga 0.438 0.562 EPL 0.434 0.566 La Liga 0.441 0.559 </code></pre> <p>This just shows the proportion of f...
<p>Given your dataframe, you can also do something like this:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import matplotlib.pyplot as plt df = # your data for i in range(len(df)): df.iloc[i].plot.pie() plt.show() </code></pre>
python|pandas|matplotlib|seaborn
0
374,403
62,116,002
Referencing index from a column and adding count
<p>Following my project below, I would like to python to be able to show which date a trade is made. Currently I have done a backtest that shows if price is above average or below average. Is there a way where I can specify in the result on which date is the trade (buy and sell) is done? For example "Buying now at 5.86...
<p>Managed to find a workaround this, it might be quite idiocracy but somehow i works :D</p> <pre><code>### Purpose of this code is to backtest MACD strategy using 12,26,9. This is a long only strategy ## Below is to import the relevant code and set pandas option import matplotlib.pyplot as plt import numpy as np impo...
python|pandas|dataframe
0
374,404
62,154,915
Error message trying to change string to year
<p>I'm trying to combine three fields to make a date, the year is currently string: code to change string to datetime:</p> <pre><code>f2[:,'frt_eli_year'] = pd.to_datetime(f2['frt_eli_year'].astype(str), format='%Y',errors='coerce',utc=True) </code></pre> <p>error message:</p> <pre><code>TypeError: unhashable type: ...
<p>The mistake is in <code>f2[:,'frt_eli_year']</code>. Check this <a href="https://stackoverflow.com/a/43291257/7891326">this answer</a>. Basically it'll work if you change to <code>f2.loc[:,'frt_eli_year']</code>, or or since you want all rows, just <code>f2['frt_eli_year']</code>.</p> <p>In total:</p> <pre><code>f...
python|pandas
0
374,405
62,044,768
Delete Multiple Columns
<p>How can I delete column on index 2 onwards for a dataframe that contains 10 columns. The dataframe looks like this:</p> <pre><code>column1 column2 column3 column4 ... </code></pre> <p>The task is to delete column3-column10</p>
<p>Invert logic - select first 2 columns by positions by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>DataFrame.iloc</code></a>:</p> <pre><code>df = df.iloc[:, :2] </code></pre> <p>If need <a href="http://pandas.pydata.org/pandas-docs/s...
python|pandas
2
374,406
62,084,464
XLA-able dynamic slicing
<p>Is there any way to dynamically slice a tensor according to a random number generator in an XLA-compiled function? For example:</p> <pre class="lang-py prettyprint-override"><code>@tf.function(experimental_compile=True) def random_slice(input, max_slice_size): offset = tf.squeeze(tf.random.uniform([1], minval=...
<p>The underlying issue here is that XLA needs to know, statically, the shapes of all <code>Tensor</code>s in the program. In this case it complains about <code>tf.range</code> because its output is not knowable given the random inputs. You might instead be able to get away with generating a masked version (zeroing out...
python|tensorflow|tensorflow-xla
0
374,407
62,305,841
regex multiple lines and store results in an array iteratively
<p>I have a bank statement and have used Regex to extract all the items in a table. The list is </p> <pre><code>['15-10-2019 BIL/INFT/001823982708/Block2B5/ MAHAK JUNEJA 5,130.00 5,19,319.08', '15-10-2019 BIL/INFT/001824120963/watermaintoct/ AAANKSHA AGRAWA 3,895.00 5,23,214.08', '15-10-2019 MOBILE BANKING MMT/IMPS...
<p>I am not sure about how you want to store those values but you can use split method such as following,</p> <pre><code>l1=['15-10-2019 BIL/INFT/001823982708/Block2B5/ MAHAK JUNEJA 5,130.00 5,19,319.08', '15-10-2019 BIL/INFT/001824120963/watermaintoct/ AAANKSHA AGRAWA 3,895.00 5,23,214.08', '15-10-2019 MOBILE BANKI...
arrays|python-3.x|regex|pandas|loops
0
374,408
62,465,980
Machine Learning model to identify grammatical errors in a sentence?
<p>Is there any machine learning model for identifying grammatical errors in a sentence? Please note that I've already tried BERT which is a classification based model and it is useful to tell us whether a sentence has any errors or not. But what I want is that a model which could identify exactly which word in sentenc...
<p>Hi I just tried testing this repo <a href="https://github.com/grammarly/gector" rel="nofollow noreferrer">GECToR</a> it was able to spot the grammatical errors in a sentence and identifying SVA errors were also there.</p> <p>And building a sequence tagger model can also help you, as described in this <a href="https:...
python|tensorflow|machine-learning|deep-learning|statistics
0
374,409
62,118,771
"mask cannot be scalar" in keras.max() function
<p>When I used Keras.max(box_scores,keep_dims=False) in an assignment, I got an error, and it was "mask cannot be scalar". But when I used Keras.max(box_scores,axis=-1,keep_dims=False) , I got the result. But I don't understand it.What is the purpose of axis=-1 in this function to correct this error?</p> <pre><code>bo...
<p>For <code>max</code> function <code>axis</code> parameter specifies a list of dimensions (or one dimension or <code>None</code> for all dimensions) over which max is computed. When negative integers are used they are interpreted similarly to Python negative indicies of array (i.e. <code>-1</code> means the last dime...
python|tensorflow|keras|neural-network|conv-neural-network
1
374,410
62,063,085
How to build this simple vector in NumPy
<p>I'm new to Python and I want to create an array which has 0.00 has first element, and then adds 0.01 for its next elements until the last one is less than or equal to a given number (in my case 0.55).</p> <p>In Matlab the code for it would be <code>(0: 0.01: 0.55)</code></p> <p>And the result would be: <code>[0.00...
<p>would go with</p> <pre><code>np.arange(0, 0.555, 0.01) </code></pre> <p>just took a look into the docs of numpy:</p> <blockquote> <p>End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out. <a href="htt...
python|numpy
5
374,411
62,272,424
Removing tensors for optimising a for loop in python
<p>I am working on a large code that I'm trying to optimise. The part of code you see below is a for loop that returns encodings in a tensor. How do I output these numbers in a regular list instead, without going to tensors? </p> <pre><code>def _make_batches(self, lines): tokens = [self._tokenize(line) for lin...
<p>You mean this?</p> <pre><code>a=[torch.tensor([[29733, 20720, 2]])] b=a[0].squeeze(0).tolist() print(b) </code></pre>
python|for-loop|pytorch|tensor
0
374,412
62,409,126
(Python) How can I compare 2 or more columns with Pandas?
<p>I have been using the module pandas for data scraping, and albeit I understood how to (), I'm still unsure about how can I compare 2 or more columns of a CSV. Taking as an example the code below, I wanted to find out, e.g. the 3 publishers who published more Action, Shooter and Platform games, separately. I wrote th...
<p>These are a lot of questions at once:</p> <ol> <li><blockquote> <p><code>a = data['Publisher'].groupby((data['Genre'] == 'Action')).value_counts().head(3) print(a)</code></p> </blockquote></li> </ol> <p>In a groupby you do not specify a concrete Genre like 'Action'. That is what query is for. The point of grou...
python|pandas|csv
1
374,413
62,332,343
TF Lite Retraining on Mobile
<p>Let's assume I made an app that has machine learning in it using a tflite file.</p> <p>Is it possible that I could retrain this model right inside the app?</p> <p>I have tried to use the <a href="https://www.tensorflow.org/lite/tutorials/model_maker_image_classification" rel="nofollow noreferrer">Model Maker</a> w...
<p>Do you mean training on the device when the app is deployed? If yes, TFLite currently doesn't support training in general. But there's some experimental work in this direction with limited support as shown by <a href="https://github.com/tensorflow/examples/blob/master/lite/examples/model_personalization" rel="nofoll...
tensorflow|tensorflow-lite
1
374,414
62,323,443
Getting a predictable Pandas DataFrame from (sparse) JSON
<p>I'm getting JSON from an API. This API omits <code>null</code> values (properties which are <code>null</code> are not sent over the wire), thus the data can be sparse. The properties contain a mix of, string, numeric, boolean, unix-timestamps, ISO8601-timestamps and ISO8601-durations. </p> <p>Here's an example JSON...
<p>Oh, well it was very close. It should use the new (pandas >= 1.0) string type (<code>StringDtype</code>) in the <code>astype</code> call.</p> <pre><code>def extract_df(js: List) -&gt; pd.DataFrame: df = pd.json_normalize(js) create_cols_if_absent(df=df, expected_cols=('name', 'las...
python|python-3.x|pandas|dataframe|missing-data
0
374,415
62,109,293
Sometimes Unable to Import NumPy
<p>When I work in Jupyter Notebooks everything works fine, and I can import numpy and pandas successfully. However, when I try to download the script and then run it in an editor such as PyCharm or Atom, I get an import error: no module named numpy, and the same for pandas. How do I fix this? Is this due to the package...
<p>This may be because Pycharm and Atom are using your default python install rather than your anaconda python environment.</p> <p>You can configure Pycharm to use your conda environment via (<a href="https://www.jetbrains.com/help/pycharm/conda-support-creating-conda-virtual-environment.html" rel="nofollow noreferrer"...
python|pandas|numpy|installation|anaconda
1
374,416
62,433,465
How to plot 3D point clouds from an npy file?
<p>I have a few Numpy binary files created by LIDAR readings containing 3D point clouds. I want to be able to plot a top-down (orthogonal) view for every point cloud by reading them from a file. I looked up various 3D point cloud libraries such as Open3d, pyntcloud, etc but none of them work with NPY files. How can I p...
<p><code>matplotlib.pyplot</code> would be my personal go to option.</p> <p>You did not supply any data or how the data is saved, so I assume that the points of the point cloud are saved in an <code>Nx3</code> dimensional <code>numpy</code> array:</p> <pre><code>data = np.load('file.npy') x = data[:, 0] y = data[:, 1...
python-3.x|numpy|plot|point-clouds
3
374,417
62,380,480
Pandas Type error while graphing pairplot in Seaborn
<p>I have a pandas DataFrame created from a file with the columns ['Time','Q1','Q2','T1','T2']. This works when I try to plot a lineplot: </p> <pre class="lang-py prettyprint-override"><code>sns.lineplot(x=data4['Time'], y=data4['Q1'], label='Q1') </code></pre> <p>However when I do a pairplot:</p> <pre class="lang-...
<p>This is a syntax error solved by formatting the pairplot call as follows: </p> <pre class="lang-py prettyprint-override"><code>sns.pairplot(df[['Q1', 'T1']]) </code></pre> <p>This will create the right object type for the graph.</p>
python|pandas|seaborn
1
374,418
62,284,954
Flip image left right in tensorflow js
<p>I am new to tfjs and stuck on finding mirror of image. Is there any way to flip tensor in tensorflowjs, similar to - <a href="https://www.tensorflow.org/api_docs/python/tf/image/flip_left_right" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/image/flip_left_right</a>? </p>
<p><code>tf.reverse</code> can be used along the first axis</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> flip = tf.tensor( [[[1.0, 2.0, 3.0], [4.0, 5.0,...
javascript|browser|tensorflow.js
2
374,419
62,092,199
Pandas groupby apply strange behavior when NaN's in group column
<p>I'm encountering some unexpected Pandas groupby-apply results, and I can't figure out the exact cause. </p> <p>Below I have to dataframes that are equal except the ordering of 2 values. df1 produces results as I expect them, but df2 produces a completely different result.</p> <pre><code>import numpy as np df1 = p...
<p>Let's begin with looking at some simple grouping calculations to understand how pandas works on it.</p> <p>In the following case, grouping keys are used as index in the resulting <code>Series</code> object. The original index was dropped.</p> <pre><code>In [4]: df1.groupby('group_col')['value_col'] \ ...: .appl...
python|pandas|numpy|dataframe|pandas-groupby
1
374,420
62,051,800
LSTM Neural Network for temperature time series predictions
<p>I'm learning to work with neural networks applied to time-series so I tuned and LSTM example that I found to make predictions of daily temperature data. However, I found that the results are extremely poor as is shown in the image. (I only predict the last 92 days in order to save time for now).</p> <p><a href="htt...
<p>You are missing one argument: return_sequences.</p> <p>When you have more than one LSTM layer, you should set it to TRUE. Because, otherwise, that layer will only output the last hidden state. Add it to each LSTM layer.</p> <pre><code>model.add(LSTM(128, activation='relu', return_sequences=True)) </code></pre> <p...
python|pandas|tensorflow|datetime|keras
0
374,421
62,090,888
Trying to convert a .npy file (float64) to uint8 or uint16
<p>I'm trying to display a 3D Numpy Array using VTK (python 3) but it needs the type to be uint8 or uint16.</p> <p>I don't know how to do this and any help would be greatly appreciated. </p> <p>In case, there's nothing I can do, I just want to display my .npy file using VTK. Any suggestions will be highly appreciated...
<p>You can use the numpy.astype() function to change the data type. Here's an example:</p> <pre><code>&gt;&gt;&gt; arr = np.array([10., 20., 30., 40., 50.]) &gt;&gt;&gt; print(arr) [10. 20. 30. 40. 50.] &gt;&gt;&gt; print(arr.dtype) float64 &gt;&gt;&gt; arr = arr.astype('uint16') &gt;&gt;&gt; print(arr) [10 20 30 40...
python|python-3.x|numpy|vtk
0
374,422
62,390,746
How to speed up the Grad-CAM calculation within a loop in Keras?
<p>I'm coding an hand-crafted solution to compute the Grad-CAM for each image contained in a given dataset. Here is the code:</p> <pre><code>def grad_cam(model, image, _class, layer_name, channel_index): class_output = model.output[:, _class] conv_output_layer = model.get_layer(layer_name).output gradie...
<p>You should split the creation of the <code>grad_function</code> function and use it independently, for example:</p> <pre><code>def grad_cam(model, _class, layer_name, channel_index): class_output = model.output[:, _class] conv_output_layer = model.get_layer(layer_name).output gradients = K.gradients(...
python|tensorflow|keras|neural-network|heatmap
0
374,423
62,458,141
Using Python pandas, how do I create a function to calculate the proportion of rows that represent a lower value than the previous row?
<p>Using Python pandas, how do I create a function to calculate the proportion of rows that represent a lower value than the previous row? So in other words, I need a function to iterate through the values under a particular series column of a Pandas Data Frame and only count those values where the next row's value (u...
<p>You can do this using the <code>series.shift</code> function:</p> <pre><code>proportion = len(df[df['Mileage'] &lt; df['Mileage'].shift(1)])/len(df) print(proportion) </code></pre> <p>output:</p> <pre><code>0.2857142857142857 </code></pre> <p>the part of the code:</p> <pre><code>df[df['Mileage'] &lt; df['Mileag...
python|pandas|dataframe|counter
0
374,424
62,073,781
Convert a dictionary of strings to a dictionary of numpy arrays
<p>I have a dictionary structured similar to below.</p> <pre><code>test_dict = {1: 'I run fast', 2: 'She runs', 3: 'How are you?'} </code></pre> <p>What I'm trying to do is convert all the strings to 4x4 numpy arrays where each word is in it's own row and each letter occupies one cell of the array, populated with bla...
<p>Is this what you mean?</p> <pre><code>{ key: np.array([list(word.ljust(4)) for word in val.split()]) for key, val in test_dict.items() } </code></pre> <p>output:</p> <pre><code>{1: array([['I', ' ', ' ', ' '], ['r', 'u', 'n', ' '], ['f', 'a', 's', 't']], dtype='&lt;U1'), 2: array([[...
python|arrays|numpy|for-loop|numpy-ndarray
1
374,425
62,110,186
concatenate numpy 1D array in columns
<p>I have two numpy arrays:</p> <pre><code>a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) </code></pre> <p>and I want to concatenate them into two columns like, </p> <pre><code>1 4 2 5 3 6 </code></pre> <p>is there any way to do this without transposing or reshaping the arrays?</p>
<p>You can try:</p> <pre><code>a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) c = np.concatenate((a[np.newaxis, :], b[np.newaxis, :]), axis = 0).T </code></pre> <p>And you get :</p> <p><code>c = array([[1, 4], [2, 5], [3, 6]]) </code></p> <p>Best, </p>
arrays|numpy|concatenation
1
374,426
62,134,357
type Error : 'dict' object is not callable
<p>I can't find the problem. It's ALL about the <strong>Williams Accumulation Distribution financial analysis</strong> indicator. It "supposedly" represents the amount of buying and selling in the market.</p> <pre><code>def wadl(prices, periods): results = holder() dict = {} for i in range(0,len(periods)): ...
<p>I think the error is at line <code>results.wadl= dict</code> as here, <code>wadl</code> is a function but you are assigning a dictionary object <code>dict</code> to a callable function <code>wadl</code>.</p>
python-3.x|pandas
0
374,427
62,173,658
Implement an Encoder and Decoder architecture with attention mechanism
<p>I want to implement Encoder-Decoder with attention mechanism from scratch. Can anyone please help me with the code?</p>
<p>This should be a good place to start <a href="https://www.tensorflow.org/tutorials/text/nmt_with_attention" rel="nofollow noreferrer">tutorial</a></p>
python|tensorflow|keras|attention-model|encoder-decoder
0
374,428
62,225,024
Handling object column with mixed data types by fixing floating point categories
<p><a href="https://i.stack.imgur.com/Wb1jI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wb1jI.png" alt="column with mixed dtype"></a></p> <p>I have an object column with mixed data type and there are categories such as 57.0 and 57 that are being treated differently. Is it possible to convert the...
<p>Apply <code>int()</code> to the objects of type <code>float</code>;</p> <pre><code>df['category'] = df['category'].map(lambda x: int(x) if isinstance(x, float) else x) </code></pre> <p><code>isinstance()</code> example:</p> <pre><code>&gt;&gt;&gt; x = 12 &gt;&gt;&gt; isinstance(x, int) True &gt;&gt;&gt; y = 12.0 ...
python|pandas
1
374,429
62,213,054
How to exclude certain rows in a pandas dataframe in Python
<p>I have an Excel sheet which has a list of folder names. I have to read the Excel sheet and create folder names on my drive. However if the process breaks during creation or if there is an exception then when I rerun the process it should exclude the folders which have already have been created.</p> <p>Below is my cu...
<p>This question boils down to safely create a (nested) directory, answered here: <a href="https://stackoverflow.com/questions/273192/how-can-i-safely-create-a-nested-directory">How can I safely create a nested directory?</a></p> <p>This code should do the trick, taken from the linked question:</p> <pre><code>import...
python|pandas
2
374,430
62,136,127
df.loc using index in slicer return nan
<p>I am trying to iterate over a dateFrame and get the max of column between certain rows, the problem is when I am putting the index value over a number I get nan:</p> <pre><code>for index, row in df.iterrows(): if index &gt;= 51: print(df.loc[index:(index - 51), 'close'].max()) </code></pre> <p>...
<p>I think the issue is you have the <code>loc</code> index slice backwards, causing nothing to be returned; on the first iteration, your slice is <code>df.loc[51:0, 'close'].max()</code>. Instead:</p> <pre><code>for index, row in df.iterrows(): if index &gt;= 51: print(df.loc[index-51:index,'close'].max(...
python|pandas
1
374,431
62,467,822
Implement ConvND in Tensorflow
<p>So I need a ND convolutional layer that also supports complex numbers. So I decided to code it myself. </p> <p>I tested this code on numpy alone and it worked. Tested with several channels, 2D and 1D and complex. However, I have problems when I do it on TF.</p> <p>This is my code so far:</p> <pre><code>def call(s...
<p>In the end, I did it in a very inefficient way based in this <a href="https://github.com/tensorflow/tensorflow/issues/14132#issuecomment-483002522" rel="nofollow noreferrer">comment</a>, also commented <a href="https://towardsdatascience.com/how-to-replace-values-by-index-in-a-tensor-with-tensorflow-2-0-510994fe6c5f...
python|tensorflow|conv-neural-network|convolution
0
374,432
62,251,957
How to get a centred rolling mean?
<p>I want to compute the rolling mean of data taken on successive days. If I just use dataframe.rolling(7) the mean is from the previous week. Instead I would like day to be at the centre of the window the mean is computed over not right at the end. Is there an easy/fast way to get such a centred rolling mean of a pa...
<pre class="lang-py prettyprint-override"><code>df.rolling(7, center=True).mean() </code></pre> <p>The rolling mean can be centered by setting the <code>center</code> argument to <code>True</code>.</p> <p><a href="https://i.stack.imgur.com/Fe5ZU.png" rel="noreferrer">Example plot</a></p>
python|pandas
6
374,433
62,316,979
linear regression on time series in python
<p>How to show dates on the chart for linear regression?</p> <p>My data in csv file:</p> <pre><code>"date","bat" "2020-05-13 00:00:00",84 "2020-05-14 00:00:00",83 "2020-05-15 00:00:00",81 "2020-05-16 00:00:00",81 </code></pre> <p>I'm able to generate chart with linear reg. but don't know how to make x axis to show d...
<p>try this:</p> <pre><code>df = pd.read_csv('battery.csv', parse_dates=['date']) x=pd.to_datetime(df['date'], format='%Y-%m-%d') y=df['bat'].values.reshape(-1, 1) lm = linear_model.LinearRegression() model = lm.fit(x.values.reshape(-1, 1),y) predictions = lm.predict(x.values.astype(float).reshape(-1, 1)) f, ax = ...
python|pandas|scikit-learn
4
374,434
62,286,166
Merge DataFrame with many-to-many
<p>I have 2 DataFrames containing examples, I would like to see if a example of DataFrame 1 is present in DataFrame 2.</p> <p>Normally I would aggregate the rows per example and simply merge the DataFrames. Unfortunately the merging has to be done with a "matching table" which has a many-to-many relationship between t...
<p>IIUC:</p> <pre><code>d2.merge(dm) .merge(d1.merge(dm), on='id_high')\ .groupby(['Example_x','Example_y'])['id_high'].agg(list)\ .reset_index() </code></pre> <p>Output:</p> <pre><code> Example_x Example_y id_high 0 Example 2 Example 1 [A, B, E] </code></pre>
python|pandas
3
374,435
62,410,758
Pandas sqlalchemy create_engine connection with SQL server windows authentication
<p>I am trying to upload a Pandas DataFrame to SQL server table. From reading, the sqlalchemy to_sql method seems like a great option. However, I am not able to get the create_engine to make the connection. </p> <p>I am able to connect to the database to retrieve data with Windows authentication. Here is the connectio...
<p>If you are going to use Windows authentication then you simply omit the username/password part of the connection URI. This works fine for me:</p> <pre class="lang-py prettyprint-override"><code>connection_uri = ( "mssql+pyodbc://@192.168.0.179:49242/mydb?driver=ODBC+Driver+17+for+SQL+Server" ) engine = sa.creat...
python|sql-server|pandas|sqlalchemy
4
374,436
62,357,679
How to iterate over multiple datasets in TensorFlow 2
<p>I use <strong>TensorFlow 2.2.0</strong>. In my data pipeline, I use multiple datasets to train a neural net. Something like:</p> <pre><code># these are all tf.data.Dataset objects: paired_data = get_dataset(id=0, repeat=False, shuffle=True) unpaired_images = get_dataset(id=1, repeat=True, shuffle=True) unpaired_mask...
<p>My current solution:</p> <pre><code>def train_one_epoch(self, writer, step, paired_data, unpaired_images, unpaired_masks): # create a new dataset zipping the three original dataset objects dataset = tf.data.Dataset.zip((paired_data, unpaired_images, unpaired_masks)) for (images, labels), unpaired_image...
python|tensorflow|iterator|dataset
-1
374,437
62,269,487
Keras: dimension mismatch between input and output after UpSampling2D
<p>I'm trying to implement RDN from here <a href="https://arxiv.org/pdf/1802.08797.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1802.08797.pdf</a></p> <p>As an input I specify: (64, 64, 3) and I expect on the output (128, 128, 3), but after compiling the model keras says those dimensions do not match and both ...
<p>If we look at the error message again:</p> <pre><code>ValueError: Dimensions must be equal, but are 128 and 64 for '{{node mean_squared_error/SquaredDifference}} = SquaredDifference[T=DT_FLOAT](model_10/sr/BiasAdd, IteratorGetNext:1)' with input shapes: [32,128,128,3], [32,64,64,3]. </code></pre> <p>We'll realize ...
python|tensorflow|keras
0
374,438
62,112,343
Problem in creating a new column using for loop
<p>I have to create a new column 'Action' in a dataframe whose values are : 1 if the next day's Close Price is greater than the present day's -1 if the next day's Close Price is less than the present day's that is, Action[i] = 1 if Close Price[i+1]>Close Price[i] Action[i] = -1 if Close Price[i+1] <p>I have used the f...
<p>You are getting the key error because you don't have a column called <code>action</code>. Any of the following before the loop will resolve the error:</p> <pre><code>df['Action'] = 0 </code></pre> <p>or</p> <pre><code>df['Action'] = np.nan </code></pre> <p>However, you will get warnings because of the way you ar...
pandas|dataframe
0
374,439
62,343,093
Remove empty string from a list of strings
<p>I have a column in my dataframe that contains a list of names with such a structure:</p> <pre><code>df['name']=[ ['anna','karen','',] ['', 'peter','mark','john'] ] </code></pre> <p>I want to get rid of the empty strings i tried it with list comprehension</p> <pre><code>[[name for name in df['name'] if name.str...
<p>You can do this using the filter function</p> <pre><code>df['name'] = [list(filter(None, sublist)) for sublist in df['name']] </code></pre>
python|pandas
3
374,440
62,471,054
Condas environment does not include pandas
<p>I have created a conda environment:</p> <pre><code>conda create -n nnlibs </code></pre> <p>and installed some libraries on it. While trying to run a code I found out there's no pandas installed on this environment.</p> <pre><code>&gt;&gt;&gt;import pandas No module named 'pandas' </code></pre> <p>and running <co...
<p>I managed to fix the issue by installing the library manually:</p> <pre><code>conda install -c anaconda pandas </code></pre> <p>as @cel explained in the comments, this happened because <code>conda create -n nnlibs</code> creates an empty environment. While I managed to solve the problem by installing each pa...
python|pandas|conda
0
374,441
62,339,563
Find the highest peak between width range and window integral
<p>I have frequency and PSD arrays which I want to find the highest peak within a certain Hz range. From the highest peak, constructing a window of 0.015 Hz and integral the area.</p> <p><strong>Find Peak and Integral</strong></p> <pre><code>freq=np.array([0.0, 0.0009765625, 0.001953125, 0.0029296875, 0.00390625, 0.0...
<p>First you should look for a peak in <code>psd</code>, not <code>freq</code>. Next, the <code>psd</code> from your example is a growing sequence thus there is no peak. Please update your question.</p> <p>After adding a dummy value <code>0</code> at the end I got:</p> <pre><code>psd = np.array([26.88687233, 82.36241...
python|numpy|scipy
1
374,442
62,411,635
Cannot load model weights in TensorFlow 2
<p>I cannot load model weights after saving them in TensorFlow 2.2. Weights appear to be saved correctly (I think), however, I fail to load the pre-trained model.</p> <p>My current code is:</p> <pre><code>segmentor = sequential_model_1() discriminator = sequential_model_2() def save_model(ckp_dir): # create dire...
<p>Ok here is your problem - the <code>try-except</code> block you have is obscuring the real issue. Removing it gives the <code>ValueError</code>:</p> <p><code>ValueError: When calling model.load_weights, skip_mismatch can only be set to True when by_name is True.</code></p> <p>There are two ways to mitigate this - yo...
tensorflow|save|load
3
374,443
62,376,476
Combine multiple rows into one row based on Column values in pandas
<p>I am trying to parse csv file which I have done almost but stuck at one point. <strong>I want to combine row with the previous row Where Column 1 of the previous row should not be null</strong> . I have data format like this.</p> <pre><code>C1 C2 C3 C4 C5 1001 1S30 5:00:00 MP...
<p>Update:</p> <pre><code>df.groupby(df['C1'].ffill()).apply(lambda x: x.stack().reset_index())[0].unstack().reset_index() </code></pre> <p>Output:</p> <pre><code> C1 0 1 2 3 4 5 6 7 8 ... 11 \ 0 1001.0 1001 1S30 5:00:00 MP GL 1M94 9:06:00 GL MP ... NaN ...
python|pandas
0
374,444
62,202,915
How to convert Pandas read excel dataframe to a list in Python?
<p>I'm reading a single column from an Excel file using Pandas:</p> <pre><code>df = pandas.read_excel(file_location, usecols=columnA) </code></pre> <p>and I want to convert that dataframe (df) into a list. I'm trying to do the following:</p> <pre><code>listA = df.values() </code></pre> <p>but I'm getting the follow...
<p>remove the parenthesis from your statement. with the parens on there, it is treating values like a function. It is an instance variable:</p> <pre><code>listA = df.values # note no parenthesis after values </code></pre> <p>Here are a couple ideas. You should probably access the column by name</p> <pre><code...
python|excel|pandas
2
374,445
62,339,302
Last day of customer activity (Python DataFrame)
<p>I have a DataFrame like this:</p> <pre><code>Customer_id Date Turnover 1 2020.6.1 123 1 2020.6.2 434 1 2020.6.3 2656 1 2020.6.4 121 1 2020.6.5 2412421 2 2020.6.1 2312 2 2020.6.2 213 2 2020.6.3 5787 3 2020.6.1 237 3 ...
<p>Using <code>pandas.DataFrame.groupby</code> with <code>max</code>:</p> <pre><code>new_df = df.groupby("Customer_id")["Date"].max() print(new_df) </code></pre> <p>Output:</p> <pre><code>Customer_id 1 2020.6.5 2 2020.6.3 3 2020.6.4 Name: Date, dtype: object </code></pre> <p>To be extra careful, use <code>...
python|pandas|dataframe|pandas-groupby
2
374,446
62,230,798
How to measure accuracy for each target when some of the targets are NaNs in a TensorFlow model
<p>I have a dataset about 400 variables and 5 target columns. In many of the rows, only a few of the Y values are present, i.e. I have some unknown (NaNs) in the targets. I'm applying a custom loss function through TF to make sure that loss is only applied to predictions of Y values where there is a Y value to compare ...
<p>When we need to use a loss function (or metric) other than the ones available , we can construct our own custom function and pass to <code>model.compile</code>.</p> <p>So define the custom loss function as below. <code>nan_friendly_loss</code> is somewhat similar but you are defining <code>sum</code> instead of <co...
python|tensorflow|keras
0
374,447
62,360,455
ModuleNotFoundError: No module named 'sklearn.svm._classes'
<p>I have created a model for breast cancer prediction. Now I want to deploy my model on a UI, for that I am using flask. To connect the model, I made .pkl file of the model but when I am trying to read the file through my app.py, it is giving me an error: ModuleNotFoundError: No module named 'sklearn.svm._classes' Wha...
<p><code>'sklearn.svm._classes'</code> is specific to version 0.19.2 of the scikit-learn package.</p> <p>You can install this version using:</p> <pre><code>pip install scikit-learn==0.19.2 </code></pre>
python|flask|scikit-learn|pickle|sklearn-pandas
1
374,448
62,192,337
Rebalancing portfolio creates a Singular Matrix
<p>I am trying to create a minimum variance portfolio based on 1 year of data. I then want to rebalance the portfolio every month recomputing thus the covariance matrix. (my dataset starts in 1992 and finishes in 2017).</p> <p>I did the following code which works when it is not in a loop. But when put in the loop the ...
<p>It would be better to identify what is causing the singularity of the matrix but there are means of living with singular matrices.</p> <p>Try to use pseudoinverse by <code>np.linalg.pinv()</code>. It is guaranteed to always exist. See <a href="https://numpy.org/doc/1.18/reference/generated/numpy.linalg.pinv.html" r...
python|numpy|matrix|portfolio|singular
2
374,449
62,273,005
Compositing images by blurred mask in Numpy
<p>I have two images and a mask, all of same dimensions, as Numpy arrays: </p> <p><a href="https://i.stack.imgur.com/O48QE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O48QE.jpg" alt="enter image description here"></a><br> <a href="https://i.stack.imgur.com/P7J0p.jpg" rel="nofollow noreferrer"><...
<p>You need to renormalize the mask before blending:</p> <pre><code>def blend_merge(lena, rocket, mask): mask = cv2.GaussianBlur(mask, (51, 51), 0) mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR) mask = mask.astype('float32') / 255 foreground = cv2.multiply(lena, mask, dtype=cv2.CV_8U) background = c...
python|numpy|opencv|python-imaging-library|bitwise-or
2
374,450
51,476,568
Using GPU with Keras
<p>i'm actally facing a probleme since last friday and didn't find a solution for the moment.</p> <p>First of all, you need to know that i'm a beginner on linux,i'm trying to do some deep learning in my internship, and i discovered that even if my company have a 1080 Ti, keras wasn't using it, so have the job to corre...
<p>Uninstall tensorflow and install only tensorflow-gpu. You should not install both. If you are using keras, then install keras-gpu. </p> <p>Let's say you are working with conda and you want to tidy up all this. Do </p> <pre><code>conda remove keras conda remove tensorflow* conda install keras-gpu </code></pre> <p>...
python|tensorflow|cuda|keras
2
374,451
51,423,017
Python pandas to compare 2 Microsoft Excel and output the changes
<p>I am trying to use Python pandas to determine the changes need to make on a certain rows.</p> <p>data1</p> <pre><code>name contract id unit qty location siteA 00012345 A001 pcs 1 M.K.141.1 siteA 00012345 A002 pcs 2 M.K.141.1 siteA 00012345 A003 pcs 3 M.K.141.1 siteA 00012345...
<p>I think I'd use merge to join those to datasets together then look for differences.</p> <pre><code>data1.merge(data2, on=['name','id','unit']).query('qty_x != qty_y') </code></pre> <p>Output:</p> <pre><code> name contract id unit qty_x location qty_y 1 siteA 12345 A002 pcs 2 M.K.141.1 ...
python|pandas
0
374,452
51,158,934
unable to get the details on the x-axis using plot method in pandas
<pre><code>import pandas as pd from pandas import Series,DataFrame import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style('whitegrid') %matplotlib inline poll_df=pd.read_csv('http://elections.huffingtonpost.com/pollster/2012-general-election-romney-vs-obama.csv') poll_df.plot(x='End Date...
<p>You need to change the dtype of End Date, End Date in poll_df was a string, converting it to datetime dtype allows pandas plot to correctly format the x-axis with the labels:</p> <pre><code>import pandas as pd from pandas import Series,DataFrame import numpy as np import matplotlib.pyplot as plt import seaborn as s...
python-3.x|pandas|numpy|dataframe|data-science
0
374,453
51,333,050
How to group by three column using conditions in Pandas(Python)?
<p>Hi so I am currently working with a data frame which has the following Columns:</p> <p>User_id(has more than 30 types of repeated user id's):1,22,33,3,1,222,1,3 and so on</p> <p>Column1(has two categories):A,B,A,B and so on</p> <p>Column2(has two categories):BB,CC,BB,CC and so on..</p> <p>Date: 2010-01-09,2010-0...
<p>what you want to do is group by <code>Column2</code>, <code>Column1</code> and <code>id</code> and get the min of the date column:</p> <pre><code>mins = df.groupby(['Column2', 'Column1','id']).Date.min() </code></pre> <p>if you want to get the info for only one particular user id you can filter the df beforehand</...
python|python-3.x|pandas|pandas-groupby
0
374,454
51,130,264
Pandas - Storing the results of df.apply() to only select rows
<p>I have a rather convoluted <code>df.apply()</code> to calculate the business hours between two dates.</p> <p>I have it working with no issues for a single row/example, however I'm now trying to apply it across the entire df.</p> <p>Example code: <code>df.apply(lambda row: calc_bus_hrs(row['Created Date'], row['T1 ...
<p>You can achieve it with by defining a separate lambda function that can handle the row logic:</p> <pre><code>def lambda_func(row): if df['T1 - Date'] is not None: return calc_bus_hrs(row['Created Date'], row['T1 - Date']) else: return nan df[df['T1 - From'].values[0] + " Time"] = df.apply(l...
python|pandas
1
374,455
51,278,422
Interpreting the FLOPs profile result of tensorflow
<p>I want to profile the FLOPs of a very simple neural network model, which is used to classify the MNIST dataset, and the batch size is 128. As I followed the official tutorials, I got the result of the following model, but I cannot understand some parts of the output.</p> <pre><code>w1 = tf.Variable(tf.random_unifor...
<p>I'll give it a try:</p> <p>(1) From this example, looks like the first number is the "self" flops, the second number means the "total" flops under the naming scope. For example: for the 3 nodes respectively named random_uniform (if there is such a node), random_uniform/mul, random_uniform/sub, they respectively tak...
tensorflow|profiler|flops
1
374,456
51,375,616
Dask groupby date performance
<p>Given the following dask dataframe:</p> <pre><code>import numpy as np import pandas as pd import dask.dataframe as dd N = int(1e4) df = pd.DataFrame(np.random.randn(N, 3), columns=list('abc'), index=pd.date_range(datetime.now(), periods=N, freq='1min')) df['dt'] = pd.to_datetime(df.index.date) dd...
<p>When data fit in memory <code>pandas</code> is faster than <code>dask</code>. I'm wondering which version of <code>dask</code> are you using because if you don't declare your metadata for the apply it should return a warning. (Your question is edited and I added metadata).</p> <p>You could try to run these experime...
python|pandas|dask
0
374,457
51,447,460
Location of documentation on special methods recognized by numpy
<p>One of the differences between <code>math.exp</code> and <code>numpy.exp</code> is that, if you have a custom class <code>C</code> that has a <code>C.exp</code> method, <code>numpy.exp</code> will notice and delegate to this method whereas <code>math.exp</code> will not:</p> <pre><code>class C: def exp(self): ...
<p>This isn't a special behavior of the <code>np.exp</code> function; it's just a consequence of how object dtype arrays are evaluated.</p> <p><code>np.exp</code> like many numpy functions tries to convert non-array inputs into arrays before acting.</p> <pre><code>In [227]: class C: ...: def exp(self): ...
python|numpy
4
374,458
51,491,248
do not let matplotlib automatically adjust the order of x axis
<p>Here is my little data:</p> <pre><code>aa3=pd.DataFrame({'OfficeName':['Narre Warren','Cannington','Chadstone','1_Mean', 'Traralgon','Bondi Junction','Hobart','2_Mean'], 'Ratio':[0.1,0.2,0.4,0.1,0.43,0.4,0.15,0.32]}) </code></pre> <p>The order of OfficeName is exactly what...
<p>Try this code:</p> <pre><code>a3=pd.DataFrame({'OfficeName':['Narre Warren', 'Cannington', 'Chadstone', '1_Mean', 'Traralgon', 'Bondi Junction', 'Hobart', '2_Mean'], 'Ratio':[0.1, 0.2, 0.4, 0.1, 0.43, 0.4, 0.15, 0.32]}) fig, ax = plt.subplots() ind = np.arange(a3.loc[:, 'O...
python|pandas|matplotlib|indexing|axis
1
374,459
51,463,341
numpy masking does not work with bounded range on both sides
<p>Suppose we have:</p> <pre><code>&gt;&gt;&gt; x array([-1. , -1.3, 0. , 1.3, 0.2]) </code></pre> <p>We can choose select elements with a range:</p> <pre><code>&gt;&gt;&gt; x[x &lt;= 1] array([-1. , -1.3, 0. , 0.2]) </code></pre> <p>And we can bound it below too:</p> <pre><code>&gt;&gt;&gt; x[-1 &lt;= x] arr...
<p>Although regular Python types do support "chained comparison" like <code>1 &lt; x &lt; 5</code>, NumPy arrays do not. Perhaps that's unfortunate, but you can work around it easily:</p> <pre><code>x[(-1 &lt;= x) &amp; (x &lt;= 1)] </code></pre>
python|numpy
1
374,460
51,364,416
CNN weights getting stuck
<p>This is a slightly theoretical question. Below is a graph the plots the loss as the CNN is being trained. Y axis is MSE and X axis is number of Epochs.<a href="https://i.stack.imgur.com/VlnUn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VlnUn.png" alt="enter image description here"></a></p> <p...
<p>Is this a multiclass classification problem? If so you could try using <a href="https://pytorch.org/docs/stable/nn.html#crossentropyloss" rel="nofollow noreferrer">cross entropy loss</a>. And a softmax layer before output maybe? I'm not sure because I don't know what's the model's input and output.</p>
conv-neural-network|pytorch|gradient|hyperparameters
0
374,461
51,328,272
Running Growing Self-Organizing Map(GSOM) GitHub Implementation failed with AttributeError: 'numpy.ndarray' object has no attribute 'iteritems'
<p>I have got some codes of Growing Self-Organizing Map(GSOM) from <a href="https://github.com/philippludwig/pygsom" rel="nofollow noreferrer">GitHub</a> (All required information for understanding the Mechanism of GSOM has described in the implementation's Documentation).</p> <p>I tried to run it in <strong>PyCharm v...
<p>For solving this error after a complete 4 hours search!! i found that i have to use below code:</p> <pre><code>for fn, t in np.ndenumerate(dataset): arr = scipy.array(t) self.data.append([fn, arr]) </code></pre> <p><em>ndenumerate()</em> is the key function from numpy to loop in a numpy ndarray in a right ...
python|numpy|pycharm|som
0
374,462
51,180,102
DataFrame, apply, lambda, list comprehension
<p>I'm trying to do a bit of cleanse to some data sets, I can accomplish the task with some for loops but I wanted a more pythonic/pandorable way to do this.</p> <p>This is the code I came up with, the data is not real..but it should work</p> <pre><code>import pandas as pd # This is a dataframe containing the correc...
<p>Here's one solution using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow noreferrer"><code>pd.Series.apply</code></a> with <code>next</code> and a generator expression:</p> <pre><code>def update_value(x): return next((k for k, v in correct.set_index('data...
python|pandas|dataframe|lambda|series
0
374,463
51,195,654
Converting a CNN from classification to log regression?
<p>I put together a CNN using tflearn that classifies images in terms of their scaling from some original resolution (I.e. 50%, 70%, etc.) just to see what kind of accuracy I could get for this problem. I’m new to machine learning so I figured it would be a good way to start towards the overall goal of having the netwo...
<p>Usually in classification problems, your output will use the softmax function to generate "probabilities". In neural networks, to convert this to a regression approach, remove the softmax layer and change the output dimension from the number of classes you had previously (5) to 1. Training this should yield a vector...
python|tensorflow|conv-neural-network|logistic-regression|tflearn
0
374,464
51,355,366
Invalid syntax when using apply with conditional lambda with pandas
<p>I am trying to add a <code>cost</code> column to the <code>w1_weekdays</code>. I want to multiply 'kwh_usage' by <code>onP_price</code> when the <code>end_time_hour</code> is equal to <code>0, 1, 2</code>. For all other hours, I want to multiply by <code>offP_price</code>.</p> <p><a href="https://i.stack.imgur.com/...
<p>I think better here is use vectorized solution with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> by boolean mask created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow n...
python|pandas
0
374,465
51,541,358
How to create logic to do value mapping in pandas?
<p>I have a df that looks like this (except more columns and rows): </p> <pre><code>p_id 1 2 3 </code></pre> <p>How do I create logic that is scalable to map certain values to certain numbers in the p_id column? </p> <p>example df should look like: </p> <pre><code>p_id: a b c </code></pre> <p>in other words how d...
<p>you <em>could</em> use <code>Series.map</code> &amp; pass in a dictionary. </p> <pre><code>df = pd.DataFrame({'p_id': [1,2,3]}) df.p_id.map({1: 'a', 2: 'b', 3: 'c'}) #output: 0 a 1 b 2 c Name: p_id, dtype: object </code></pre> <p>However, if your mapping an integer to an letter, you could use the <code>ch...
python|python-3.x|pandas
1
374,466
51,432,992
Keras: what does class_weight actually try to balance?
<p>My data has extreme class imbalance. About 99.99% of samples are negatives; the positives are (roughly) equally divided among three other classes. I think the models I'm training are just predicting the majority class basically all the time. For this reason, I'm trying to weight the classes. </p> <p><strong>Model</...
<p>Keras uses the class weights during training but the accuracy is not reflective of that. Accuracy is calculated across all samples irrelevant of the weight between classes. This is because you're using the metric 'accuracy' in the compile(). You can define a custom and more accurate weighted accuracy and use that or...
python|tensorflow|neural-network|keras|loss-function
2
374,467
51,371,528
Reading Images from TFrecord using Dataset API and showing them on Jupyter notebook
<p>I created a tfrecord from a folder of images, now I want to iterate over entries in TFrecord file using Dataset API and show them on Jupyter notebook. However I'm facing problems with reading tfrecord file.</p> <p>Code I used to create TFRecord</p> <pre><code>def _bytes_feature(value): return tf.train.Feature(...
<p>Is this what you may be looking for? I think once u convert to numpy array you can show in jupyter notebook using PIL.Image.</p> <p>convert tf records to numpy => <a href="https://stackoverflow.com/questions/36026892/how-can-i-convert-tfrecords-into-numpy-arrays">How can I convert TFRecords into numpy arrays?</a></...
tensorflow|tensorflow-datasets|tfrecord
1
374,468
51,151,436
Extra 'b' preceeding the actual output in TensorFlow
<p>So, I am new to TensorFlow and will be just starting to learn it. I installed TensorFlow on the IDE Canopy using 'pip' command. </p> <p>While confirming if it had been installed correctly, I entered the following code :</p> <pre><code>import tensorflow as tf hello = tf.constant('Hello, TensorFlow!') sess = tf.Sess...
<p>The 'b' indicates that it is a bytestring (rather a sequence of octets). Use decode() to get the string.</p> <pre><code>print(sess.run(hello).decode()) </code></pre>
python|tensorflow|canopy
5
374,469
51,284,161
coding values in DataFrame using table with interval description in python
<p>I have a table in pandas df1</p> <pre><code>id value 1 1500 2 -1000 3 0 4 50000 5 50 </code></pre> <p>also I have another table in dataframe df2, that contains upper boundaries of groups, so essentially every row represents an interval from the previous boundary to the current one (the fir...
<p>I suggest use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow noreferrer"><code>cut</code></a> with sorted <code>DataFrame</code> of <code>df2</code> by sorted <code>upper</code> and repalce last <code>NaN</code> to <code>np.inf</code>:</p> <pre><code>df2 = pd.DataFrame...
python|pandas|binning
0
374,470
51,548,794
Compare 2 maps together with matplotlib
<p>@Julien : I see no point in downvoting a question that could be useful to many beginners. That's ridiculous to see so much hate, your comment (which I respected) was more than enough. </p> <p>I am working on geopandas and I try to compare 2 maps of NYC, based on their BoroCode (BoroCode &amp; Borocode2). </p> <p>...
<p>Subplots in matplotlib are created e.g. as </p> <pre><code>fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(15,5)) </code></pre> <p>Geopandas' <a href="http://geopandas.org/reference.html#geopandas.GeoDataFrame.plot" rel="nofollow noreferrer"><code>plot</code></a> accepts an argument <code>ax</code> to which to su...
python|pandas|matplotlib
0
374,471
51,222,493
Circular shift of a string element
<p>Basically I have converted an integer into binary representation and after that it is stored in string format. </p> <p>I want to circularly rotate the number. </p> <p>How should I proceed? </p> <p>I have used <code>np.roll()</code> but it is not working.</p>
<p>You can just create a new string as follows to circularly shift it</p> <pre><code>bin_str = bin_str[-1] + bin_str[:-1] </code></pre> <p>If thats of no good, you can use <code>collections.deque</code> (which has a <code>rotate</code> method) to have circular shift effect</p> <pre><code>from collections import dequ...
python|numpy
2
374,472
51,291,470
Slice pandas dataframe columns with an array?
<p>This question refers to the <a href="https://stackoverflow.com/questions/51271709/interpolate-pandas-df">previous post</a>:</p> <p>Where I have a dataframe and an array of values on which I want to interpolate:</p> <pre><code>df_new = pd.DataFrame(np.random.randn(5,7), columns=[402.3, 407.2, 412.3, 415.8, 419.9, 4...
<p>IIUC, you could simply do column filtering like this.</p> <pre><code>df_int[wl] </code></pre> <p>Output:</p> <pre><code> 400.0 408.2 412.5 417.2 420.5 423.3 425.0 0 0.293797 0.383745 0.424941 0.707308 0.793880 -0.233975 0.175342 1 1.306332 -0.872758 -0.301987 -0.683450 -0.53464...
python|pandas
1
374,473
51,209,169
Matplotlib pdf Output
<p>Im new to matplotlib and wont to use the graphics in Latex. There ist a visual output as a graphic but:</p> <p>Why is there no pdf output?</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import os #to remove a file import datetime from matplotlib.backends.backend_pdf import P...
<p>In general, <code>savefig</code> should be called <em>before</em> <code>show</code>. See e.g.</p> <ul> <li><a href="https://stackoverflow.com/questions/9012487/matplotlib-pyplot-savefig-outputs-blank-image">Matplotlib (pyplot) savefig outputs blank image</a></li> <li><a href="https://stackoverflow.com/questions/511...
pandas|pdf|matplotlib
2
374,474
51,212,158
How to find angle between GPS coordinates in pandas dataframe Python
<p>I have dataframe with measurements coordinates and cell coordinates.</p> <p>I need to find for each row angle (azimuth angle) between a line that connects these two points and the north pole.</p> <p>df:</p> <pre><code>id cell_lat cell_long meas_lat meas_long 1 53.543643 11.636235 53.44758...
<p>The trickiest part of this problem is converting geodetic (latitude, longitude) coordinates to Cartesian (x, y, z) coordinates. If you look at <a href="https://en.wikipedia.org/wiki/Geographic_coordinate_conversion" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Geographic_coordinate_conversion</a> you can ...
python|pandas|dataframe|angle|azimuth
4
374,475
51,136,836
separating each stock data into individual dataframe
<p>I took historical data of 100 stocks. It is a single file with all tickers with corresponding data. How to loop such that each ticker data gets separated in dataframe with its own name? I've tried this but this doesnt work.</p> <pre><code>for ticker in stocks: print(ticker) tick=pd.DataFrame(data.loc[(data....
<p>Arbitrary variable names is considered poor practice. Instead, you can define a dictionary for a variable number of variables:</p> <pre><code>dfs = dict(tuple(data.groupby('ticker'))) </code></pre> <p>Then, if you wish, export to csv via iterating dictionary items:</p> <pre><code>for k, v in dfs.items(): v.to...
python|pandas|dataframe|stocks|ticker
1
374,476
51,535,357
How to interpolate data and angles with PANDAS
<p>I have a simple dataframe <code>df</code> that contains three columns:</p> <ul> <li><code>Time</code>: expressed in seconds</li> <li><code>A</code>: set of values that can vary between <em>-inf</em> to <em>+inf</em></li> <li><code>B:</code> set of angles (degrees) which range between <em>0</em> and <em>359</em> </l...
<p>You should be able to use the method described in <a href="https://stackoverflow.com/questions/27295494/bounded-circular-interpolation-in-python">this question</a> for the angle column:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({'Time':[0,12,23,25,44,50], 'A':[5,7,9,8,11,6], 'B':[300,...
python|pandas|dataframe|interpolation|angle
3
374,477
51,281,477
Looping through dates
<p>I am trying to loop through some dates I created, but I get an error. This is the code:</p> <pre><code>q3_2018 = datetime.date(2018,9,30) q4_2018 = datetime.date(2018,12,31) q1_2019 = datetime.date(2019,3,31) q2_2019 = datetime.date(2018,6,30) dates = [q3_2018, q4_2018,q1_2019,q2_2019] values = [] for d in d...
<p>I suggest convert <code>date</code>s to <code>datetimes</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> and then for select column use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFra...
python|pandas|loops|date|datetime
0
374,478
51,352,699
Pairwise Euclidean distance with pandas ignoring NaNs
<p>I start with a dictionary, which is the way my data was already formatted:</p> <pre><code>import pandas as pd dict2 = {'A': {'a':1.0, 'b':2.0, 'd':4.0}, 'B':{'a':2.0, 'c':2.0, 'd':5.0}, 'C':{'b':1.0,'c':2.0, 'd':4.0}} </code></pre> <p>I then convert it to a pandas dataframe:</p> <pre><code>df = pd.DataFrame(dict...
<p>You can use numpy broadcasting to compute vectorised Euclidean distance (L2-norm), ignoring NaNs using <code>np.nansum</code>. </p> <pre><code>i = df.values.T j = np.nansum((i - i[:, None]) ** 2, axis=2) ** .5 </code></pre> <p>If you want a DataFrame representing a distance matrix, here's what that would look like...
python|pandas|numpy|dataframe|euclidean-distance
6
374,479
51,544,356
how to replace a dataframe row with NaN if it doesn't contain a specific string
<p><a href="https://i.stack.imgur.com/3HDdv.png" rel="nofollow noreferrer">dataframe</a></p> <p>I am working with the data frame shown in the link above. I want to make all rows that do not contain the words 'Yes' or 'No' be replaced with NaN.</p>
<pre><code>df.Met = np.where(~df.Met.isin(['Yes', 'No']), np.nan, df.Met) </code></pre> <p>Try this.</p>
python|pandas|dataframe|replace|nan
0
374,480
51,219,358
pandas,read_excel, usecols with list input generating an empty dataframe
<p>Actually i want to read only a specific column from excel into python dataframe my code is </p> <pre><code>import pandas as pd file = pd.read_excel("3_Plants sorted on PLF age cost.xlsx",sheet_name="Age&gt;25",index_col="Developer",usecols="Name of Project") </code></pre> <p>but i am getting an empty dataframe as...
<p>As mentioned by Tomas Farias, usecols doesn't take cell values. A possible approach is to read few rows and find the location of the column and then read the file second time.</p> <pre><code>import pandas as pd col = pd.read_excel("3_Plants sorted on PLF age cost.xlsx",sheet_name="Age&gt;25", nrows=2).columns k=col...
python|pandas
0
374,481
51,373,222
Pandas dataframe.set_index() deletes previous index and column
<p>I just came across a strange phenomenon with Pandas DataFrames, when setting index using DataFrame.set_index('some_index') the old column that was also an index is deleted! Here is an example:</p> <pre><code>import pandas as pd df = pd.DataFrame({'month': [1, 4, 7, 10],'year': [2012, 2014, 2013, 2014],'sale':[55, 4...
<p>You can do the following</p> <pre><code>&gt;&gt;&gt; df_mn.reset_index().set_index('year') month sale year 2012 1 55 2014 4 40 2013 7 84 2014 10 31 </code></pre>
python|pandas|dataframe|indexing
7
374,482
51,291,382
Python Pandas: Breaking a list or series into columns of different sizes
<p>I have a single series with 2 columns that looks like </p> <pre><code>1 5.3 2 2.5 3 1.6 4 3.8 5 2.8 </code></pre> <p>...and so on. I would like to take this series and break it into 6 columns of different sizes. So (for example) the first column would have 30 items, the next 31, the next 28, and so on. I...
<p>Based on comments you can try use the index of the series to fill your dataframe</p> <pre><code>s = pd.Series([5, 2, 1, 3, 2]) df = pd.DataFrame([], index=s.index) df['col1'] = s.loc[:2] df['col2'] = s.loc[3:3] df['col3'] = s.loc[4:] </code></pre> <p>Result: </p> <pre><code> col1 col2 col3 0 5.0 NaN Na...
python|pandas|dataframe|series
1
374,483
51,557,344
Extract nominal and standard deviation from ufloat inside a panda dataframe
<p>For convenience purpose I am using pandas dataframes in order to perform an uncertainty propagation on a large set on data.</p> <p>I then wish to plot the nominal value of my data set but something like <code>myDF['colLabel'].n</code> won't work. How to extract the nominal and standard deviation from a dataframe in...
<p>Actually solved it with the <code>unumpy.nominal_values(arr)</code> and <code>unumpy.std_devs(arr)</code> functions from uncertainties.</p>
python|pandas|uncertainty
3
374,484
51,403,274
Merging two dataframes with multiples in one of them
<p>I am merging two dataframes under the common header, "COUNTERPARTYNAME". So below is an example of my df5:</p> <pre><code> CONTRACT COUNTERPARTYNAME TERM 0 450 A 300 1 400 A 350 2 27...
<p>You need to explicitly say on which column, you want your merge to be. Also you have to use <a href="https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer">merge</a> as below. </p> <pre><code>df7 = df5.merge(df6, on=['COUNTERPARTYNAME']) </code></pre> <p...
python|pandas|merge
0
374,485
51,349,215
pandas read_html clean up before or after read
<p>I'm trying to get the last table in this html into a data table. </p> <p>Here is the code:</p> <pre><code>import pandas as pd a=pd.read_html('https://www.sec.gov/Archives/edgar/data/1303652/000130365218000016/a991-01q12018.htm') print (a[23]) </code></pre> <p>As you can see it reads it in, but needs to be cleaned...
<p><code>Code</code> below extracts the table using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html" rel="nofollow noreferrer"><code>pd.read_html()</code></a> from a website. Additional parameters could be tuned further depending on the <code>table format</code>.</p> <pre><code># ...
python|html|pandas
1
374,486
51,287,665
Get index of where group starts and ends pandas
<p>I grouped my data by month. Now I need to know at which observation/index my group starts and ends. What I have is the following output where the second column represents the number of observation in each month: </p> <pre><code>date 01 145 02 2232 03 12785 04 16720 Name: date, dtype: int64 </cod...
<p>try the following - using <code>shift</code></p> <pre><code>df['data'] = df['data'].shift(1).add(1).fillna(0).apply(int).apply(str) + ' - ' + df['data'].apply(str) </code></pre> <p>OUTPUT:</p> <pre><code> data date 1 0 - 145 2 146 - 2232 3 2233 - 12785 4 12786 - 16720 5 16721 - 30386 6 3...
python|pandas|date|indexing|grouping
1
374,487
51,429,286
Generating new column of data by aggregating specific columns of dataset
<p>My dataset has a few interesting columns that I want to aggregate, and hence create a metric that I can use to do some more analysis. </p> <p>The algorithm I wrote takes around ~3 seconds to finish, so I was wondering if there is a more efficient way to do this.</p> <pre><code>def financial_score_calculation(df, ...
<p>Note that in Pandas you can index in ways other than elementwisely with <code>at</code>. In the four-liner below, <code>index</code> is a list which can then be used for indexing with <code>loc</code>.</p> <pre><code>for parameter in dictionary_of_parameters: index = df[df[parameter].isin(dictionary_of_paramete...
python|pandas|dataframe
0
374,488
51,342,528
Hyperas: 'List' object has no attribute 'shape'
<p>I'm trying to read in some data from a TSV file for use with <a href="https://github.com/maxpumperla/hyperas" rel="nofollow noreferrer">Hyperas</a>, but any way I do it, I seem to get the same error:</p> <pre><code>Traceback (most recent call last): File "/path/to/cnn_search.py", line 233, in &lt;module&gt; t...
<p>have you considered using <code>np.genfromtxt('your_file.tsv')</code>? works wonders for reading in csv and tsv data, and i have had great experiences with it lately. Also, you should problably supply more information on your specific problem (kind of data, layout etc) if you need a more detailed answer.</p>
python|csv|tensorflow|machine-learning|keras
1
374,489
51,313,086
Solving non-linear coupled differential equations in python
<p>I am working on simulation of a system that contains coupled differential equations. My main aim is to solve the mass balance in steady condition and feed the solution of steady state as initial guess for the dynamic simulation. There are basically three state variables Ss,Xs and Xbh. The rate equations look like th...
<p>This is a solution to getting negative values for your solution: instead of using fsolve, use least_squares, which allows you to set bounds to the possible values.</p> <p>In the top, import:</p> <pre><code>from scipy.optimize import least_squares </code></pre> <p>And replace the fsolve statement with:</p> <pre><...
python|numpy|scipy|simulation
0
374,490
51,452,562
pandas Dataframe Consistently falling column values
<p>I am trying to Find the <strong>number of consistently falling values</strong>, which form a part of a column in my Pandas dataframe (df), columnname is <strong>"Values"</strong> and the data snippet is given below:</p> <pre><code># sample data time values 11:55 0.940353 12:00 0.919144 12:05 0.909454 12:10...
<p>Here is a reproducible example with a function that accomplishes your goal. I'm assuming you might have multiple sequences of decreasing records, so the function returns the count of decreasing records and the percent of the total decrease from highest to lowest values for each decreasing sequence.</p> <pre><code>...
python|pandas|dataframe|iteration
1
374,491
51,299,618
pandas groupby hour and calculate stockout time
<p>I have a time series like below:</p> <pre><code>| datetime_create | quantity_old | quantity_new | quantity_diff | is_stockout | | 2018-02-15 08:12:54.289 | 16 | 15 | -1 | False | | 2018-02-15 08:14:10.619 | 15 | 13 | -2 | False | | 20...
<p>I think need first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow noreferrer"><code>resample</code></a> by minutes with forward filling <code>NaN</code>s, convert to <code>inetger</code>s and for <code>Series</code> add <a href="https://pandas.pydata.org...
python|pandas|pandas-groupby
1
374,492
51,205,502
Convert a black and white image to array of numbers?
<p><a href="https://i.stack.imgur.com/gC1x7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gC1x7.png" alt="The image is 28 pixels by 28 pixels. They can interpret this as a big array of numbers:"></a> Like the image above suggests, how can I convert the image to the left into an array that represent the dark...
<p>I would recommend to read in images with opencv. The biggest advantage of opencv is that it supports multiple image formats and it automatically transforms the image into a numpy array. For example: </p> <pre><code>import cv2 import numpy as np img_path = '/YOUR/PATH/IMAGE.png' img = cv2.imread(img_path, 0) # read...
python|image|numpy|opencv|image-processing
8
374,493
51,387,915
Error with RandomGridSearchCV in Sklearn MLPRegressor
<p>I found similar issues around the internet but with slight differences and none of the solutions worked for me. I have a set of explanatory variables X (2085,12) and an explained variable y (2085,1) which I have to do some stuff on, including the use of these sklearn classes (as title). In order to get the right hyp...
<p>The problem is caused when you define the grid parameters using list comprehension and the <strong>float argument</strong>.</p> <p>This works fine for me:</p> <pre><code>from sklearn.neural_network import MLPRegressor from sklearn.model_selection import RandomizedSearchCV import pandas as pd import numpy as np fro...
python|python-3.x|numpy|scikit-learn|joblib
2
374,494
48,428,859
How do I reinstate the GPU version of tensorflow that was running 2 days ago on my host?
<p>Just two days ago, after much work on my part downloading and installing the latest stable GPU version of tensorflow, my tensorflow installation was behaving correctly as I wanted, and it reported this:</p> <pre><code>$ source activate tensorflowgpu (tensorflowgpu) ga@ga-HP-Z820:~$ python Python 3.5.4 |Anaconda, In...
<p>You'll need to install the kernel in ipython, so that it knows about your environment. Currently, ipython is picking up the default python on your system, not the environment one. You can install the kernel by (make sure your environment is active)</p> <pre><code>pip install ipykernel python -m ipykernel install --...
tensorflow
1
374,495
47,992,947
Drop line in pandas df when string type cell's right characters don't match condition
<p>I am working on a dataframe containing demographic data for every single U.S state and county.</p> <pre><code>FIPS State Area_Name CENSUS_2010_POP ESTIMATES_BASE_2010 ... 01000 AL Alabama 4779736 4780131 ... 01001 AL Autauga County 54571 54571 .....
<p>Select the rows based on boolean indexing , boolean obtained by <code>str</code> slicing comparison i.e </p> <pre><code>df[df['FIPS'].astype(str).str[-3:] == '000'] FIPS State Area_Name CENSUS_2010_POP ESTIMATES_BASE_2010 ... 0 1000 AL Alabama 4779736 4780131 ... </code></pre>
python|string|pandas|if-statement
0
374,496
47,993,087
convert json into pandas dataframe
<p>I have this json data:</p> <pre><code>{ "current": [ [ 0, "2017-01-15T00:08:36Z" ], [ 0, "2017-01-15T00:18:36Z" ] ], "voltage": [ [ 12.891309987, "2017-01-15T00:08:36Z" ], [ 12.8952162966, "2017-01-15T00:18:36Z" ] ] } </code></p...
<p>If both the columns time is same, aftering reading json we can select the values and concat them :</p> <pre><code>ndf = pd.read_json(q) ndf = pd.concat([ndf.apply(lambda x : x.str[0]),ndf['current'].str[1].rename('time')],1) current voltage time 0 0 12.891310 2017-01-15T00:08:36Z 1...
python|json|pandas|dataframe
2
374,497
48,390,559
Slicing multiple values into single column
<p>The dataframe below is populated by pd.read_sql. How do I select the wf value for every unique Group / SubGroup pair where the book_date == start_date and store it in the column "new". </p> <p>*I have asterisk'd the rows for additional clarity, the asterisk is not in the dataset.</p> <pre><code>| | Group | S...
<p>Taking your data</p> <pre><code>df = pd.read_clipboard() df.head() df.replace({'\*': ''}, regex=True, inplace=True) def gen_new_col(frame): if frame['book_date'] == frame['start_date']: return frame['wf'] else: return 'ignore' df['new_col'] = df.apply(gen_new_col, axis=1) df['g_subg'] = df...
python-3.x|pandas|numpy|dataframe
0
374,498
48,192,836
Pandas line plot suppresses half of the xticks, how to stop it?
<p>I am trying to make a line plot in which every one of the elements from the index appears as an xtick.</p> <pre><code>import pandas as pd ind = ['16-12', '17-01', '17-02', '17-03', '17-04', '17-05','17-06', '17-07', '17-08', '17-09', '17-10', '17-11'] data = [1,3,5,2,3,6,4,7,8,5,3,8] df = pd.DataFrame(data,i...
<p>You need to use ticker object on axis and then use that axis when plotting.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as ticker ind = ['16-12', '17-01', '17-02', '17-03', '17-04', '17-05','17-06', '17-07', '17-08', '17-09', '17-10', '17-11'] data = [1,3,5,2,3...
python|pandas|matplotlib|plot
3
374,499
48,323,486
Create a tf.contrib.learn Estimator serving that takes JSON input
<p>I am after some code that I can use to export a model from a tensorflow <code>Estimator</code> that would take JSON as an input. I could make this work with <code>tf.Estimator</code> using <code>tf.estimator.export.ServingInputReceiver</code>, but for models built in <code>tf.contrib.learn</code> I could not find an...
<p>To use contrib estimator, you have to look at earlier versions of the samples. Here is an example:</p> <p><a href="https://github.com/GoogleCloudPlatform/training-data-analyst/blob/85c57e4da2e7edeffbb6652636e3c65b313c568f/blogs/babyweight/babyweight/trainer/model.py" rel="nofollow noreferrer">https://github.com/Goo...
tensorflow|google-cloud-ml
1