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
363,500
70,073,366
How to have a function repeat itself multiple times?
<p>so I want to generate random, floating-point numbers between 0 and 1 and calculate the mean. Then repeat this times. I want to do a Histogram with this later.</p> <p>This is what I came up with so far:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import random #random float number between 0 a...
<p>You don't need any loops.</p> <p>Instead of generating a random array of <code>n</code> elements <code>m</code>, times, make an <code>n x m</code> array and use numpy's API to take your mean along the second axis:</p> <pre class="lang-py prettyprint-override"><code>import numpy m = 10 n = 5 x = numpy.random.random(...
python|python-3.x|numpy
1
363,501
70,265,251
Getting "RuntimeError: CUDA error: out of memory" when memory is free
<p>I'm trying to run a test code on GPU of a remote machine. The code is</p> <pre><code>import torch foo = torch.tensor([1,2,3]) foo = foo.to('cuda') </code></pre> <p>I'm getting the following error</p> <blockquote> <pre><code>Traceback (most recent call last): File &quot;/remote/blade/test.py&quot;, line 3, in &lt;...
<p><em>To answer the comments that asked if I was able to address the issue:</em></p> <p>I had this issue in two separate occasions,</p> <ol> <li><p>First time, I was trying to use <code>conda</code> libraries while I had python packages in another directory as well (probably installed using <code>pip</code>). I ended ...
pytorch
0
363,502
70,263,573
Generate 200 data points drawn from a multivariate normal distribution with mean μ and covariance matrix S, where
<p><a href="https://i.stack.imgur.com/JNfF1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JNfF1.png" alt="where mean and covarance matrix =:" /></a></p> <pre><code>import numpy as np from numpy import sin, cos, pi from matplotlib.pyplot import * rng = np.random.default_rng(42) N = 200 ...
<p>For generating the data, you need two tricks:</p> <ul> <li>Compute a &quot;square root&quot; of covariance matrix S using eigenvalue-eigenvector factorization</li> <li>Use the standard formula for generating a random normal with given mean and covariance. With Numpy it works on vectors (quoting from help(np.random....
python|numpy|machine-learning|pca
0
363,503
70,266,586
countif (with multiple column range) in python
<p>I'm trying to do this 2 simple excel functions in python but is very hard! I'm a newbie in python...</p> <p><a href="https://i.stack.imgur.com/KSMTe.png" rel="nofollow noreferrer">example</a></p> <p>Can anyone help me? Thanks in advance, imack.</p>
<p>This is the closest I could do for now, it is not perfect but maybe you will find a way to improve it :)</p> <pre class="lang-py prettyprint-override"><code>table = [ [&quot;a&quot;, &quot;b&quot;], [&quot;b&quot;, &quot;c&quot;], [&quot;c&quot;, &quot;d&quot;], [&quot;b&quot;, &quot;c&quot;], [&...
python|pandas
1
363,504
56,072,057
Dropping rows in pandas based on a more complex condition
<p>I have the following data frame:</p> <pre><code>time id type 2012-12-19 1 abcF1 2013-11-02 1 xF1yz 2012-12-19 1 abcF1 2012-12-18 1 abcF1 2013-11-02 1 xF1yz 2006-07-07 5 F5spo 2006-07-06 5 F5spo 2005-07-07 5 F5abc </code></pre> <p>For a given id, I need to find the max date.</p> <p>...
<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> for get indices of max values, filter only columns <code>id</code> and <code>type</code> and <a href="http://pandas.pydata.org/pa...
python|pandas
3
363,505
56,244,887
How does pandas quantile( ) function works internally?
<p>In this post:</p> <p><a href="https://stackoverflow.com/questions/55009203/how-does-pandas-calculate-quartiles/55009379#55009379">How does pandas calculate quartiles?</a></p> <p>This is the explanation given by @perl on the working of quantile() function:</p> <pre><code>df = pd.DataFrame([5,7,10,15,19,21,21,22,22,23...
<p>I am not sure but you can try this.</p> <pre><code>0 &lt;= q &lt;= 1 df = pd.DataFrame([1,3,5,7,9], columns=['val']) df.quantile(0.25) output: val 3.0 </code></pre> <p>Explanation: n=5, q = 0.25. As i have used q = 0.25,then we can use <code>index = n/4 = 1.25</code></p> <p><code>Condition for index:</code></p> <...
python|pandas|quantile|percentile
0
363,506
56,157,623
How to unpack column contents to new columns determined by cell's value
<p>I have a dataframe that contains information about student grades, test scores, and other metrics. One of the columns contains comma separated text where each comma separated value is the name of a math class and the grade the student achieved in that class. So the dataframe looks as follows:</p> <pre><code>STUDENT...
<p>You can use a regular expression and <code>pivot</code> here.</p> <pre><code>u = df.MATHS.str.extractall(r'([a-zA-Z]+)_([A-F][+-]?)').reset_index(1, drop=True) # 0 1 # 0 ALGEBRA B+ # 0 GEOMETRY A- # 0 TRIGONOMETRY C # 1 ALGEBRA B # 1 GEOMETRY B+ # 1 CALCULUS C ...
python|pandas
2
363,507
56,426,228
How to convert string year-dayofyear-milliseconds to datetime object
<p>In a pandas DataFrame I have weird datetime format like so: </p> <pre><code>0 201913907050435 1 201913908520126 2 201914004163647 3 201914019315651 4 201914019320917 Name: DATETIME, dtype: object </code></pre> <p>What I know is, that it's Year followed by day of the year. I guess the number after th...
<pre><code>### try this print(pd.to_datetime('201913907050435', format="%Y%j%H%M%S%f")) ##output: 2019-05-19 07:05:04.350000 </code></pre>
python|pandas|string-to-datetime
1
363,508
56,102,699
How to find those values which are the largest ​in their own rows and columns?
<p>There is a random 5x5 matrix (2D array). An example: </p> <pre><code>[[66 27 52 63 15] [48 63 19 16 3] [35 9 45 45 88] [47 84 86 92 54] [89 79 76 49 67]] </code></pre> <p>I would like to find those values which are the largest ​​in their own rows and columns, so: 88,92,89</p> <p>I can find only the largest ...
<p>Here are two test cases demonstrating that all three answers given so far are incorrect:</p> <pre><code> TEST CASE 1 TEST CASE 2 =========== =========== [5 4 3 2 1] [0 1 2 3 4] [4 4 3 2 1] [1 2 3 4 5] [3 3 3 2 1] ...
python|performance|numpy
2
363,509
56,090,931
How to train LSTM with single label per "batch"
<p>I want to train stateful LSTM model for time-series prediction. Initially I assumed that I should write : </p> <pre><code> for batch in range(len(features) - window_size): # get arrays for the batch fb = features[batch:batch+window_size,:] lb = labels[batch:batch+window_size,:] ...
<p>Video classification is generally done using Convolutional Networks with 3D convolutional kernels. As an example, look at <a href="https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/42455.pdf" rel="nofollow noreferrer">this paper</a> by Google and Standford researcher.</p> <p>In your ca...
python|tensorflow|keras
1
363,510
56,251,620
Pandas search first row that match condition efficiently
<p>I have a Pandas DataFrame that contains few millions of rows. I want to select a value from a row based on a condition <code>C</code>.</p> <p>I have the following code that is working : </p> <pre><code>all_matches= df.loc[C, "column_name"] first_match = next(iter(all_matches), 'no match') </code></pre> <p>The pro...
<p>If <strong>always</strong> there is first value use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.iat.html" rel="nofollow noreferrer"><code>Series.iat</code></a> for fast get first value:</p> <pre><code>df.loc[C, "column_name"].iat[0] </code></pre> <p>Or:</p> <pre><code>df.loc[C...
python|pandas
3
363,511
56,187,039
Extract a single value from a pandas dataframe
<p>In Python I'm trying to extract a single value from a Pandas dataframe. I know exactly what the value contains, I just need to find it anywhere in the dataframe and extract it.</p> <p>For example, in the dataframe below:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame( {0: ['BA1234', ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></a> first for <code>Series</code>, then filter by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow no...
python|pandas|dataframe
3
363,512
56,205,931
pandas diff with date columns
<p>I have a data frame that looks something like:</p> <pre><code>d={'business':['FX','FX','IR','IR'],\ 'name':['ed','ed','a','b'],\ 'date':(['01/01/2018','05/02/2018','01/01/2018','05/01/2018']),\ 'amt':[1,2,3,4]} df=pd.DataFrame(data=d) df['date'] = pd.to_datetime(df['date'],format='%d/%m/%Y') df </code></pr...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.diff.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.diff</code></a>:</p> <pre><code>df['date diff'] = df.groupby(['business','name'])['amt'].diff().fillna(0).astype(int) print(df) bus...
python|pandas
2
363,513
56,129,032
Python comparing millions of rows and hundreds of columns between two tables from relational DB
<p>Currently our system is in live proving phase. So, we need to check whether the set of tables populated in production are matching with the tables populated in sandbox (test). At the moment we have written a query for each table comparison and then run it in sql client to check it. There will be few more tables to c...
<p>For handling this kind of data I would recommend using something like Hadoop rather than pandas/python. This isn't much of an answer but I can't comment yet.</p>
python|python-3.x|pandas|pandasql
0
363,514
56,395,124
pandas DataFrame: how to sentence into words and select rows that have more than 10 words?
<p>I have a DataFrame with each row a sentence. However the sentences are not the same length. I want to select those rows which contains more than 10 words, something like </p> <pre><code>df = df.loc[len(df[src].str.split()) &gt; 10] </code></pre> <p>But this will raise the Error of Key being True. How to do that?</...
<p>Try with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.len.html" rel="noreferrer"><code>series.str.len()</code></a>:</p> <pre><code>df[df['src'].str.split().str.len() &gt; 10] </code></pre>
python|pandas|dataframe
6
363,515
56,186,384
TypeError: 'Not JSON Serializable' while doing tf.keras.Model.save and using keras variable in loss_weights in tf.keras.Model.compile
<p><strong>System information</strong>   </p> <p>OS Platform and Distribution: Ubuntu 16.04 LTS  </p> <p>TensorFlow installed from (source or binary): binary  </p> <p>TensorFlow version (use command below): 1.12.0  </p> <p>Python version: 3.5.2  </p> <p>CUDA/cuDNN version: release 9.0, V9.0.176  </p> <p>GPU model...
<p><code>model.save</code> is trying to save a <code>tf.Variable</code> which is not JSON serializable.</p> <p><code>model.fit</code> saves everything, not just the model weights. I've seen this problem when my optimizer had a <code>tf.Tensor</code> which cannot be serialized.</p> <p>Everything points to <code>alpha</c...
python-3.x|tensorflow|keras|deep-learning|tf.keras
1
363,516
56,058,901
Pandas cumulative sum of all previous dates by group
<p>I have a Pandas dataframe like this:</p> <pre><code>df = pd.DataFrame({ 'Date': ['2018-04-01', '2018-05-01', '2018-06-01', '2018-07-01', '2018-08-01'], 'Product': ['a', 'a', 'a', 'b', 'b'], 'Volumes': [10,30,40,50,60]}) Date Product Volumes 2018-04-01 a 10 2018-05-01 a 30 2018-0...
<p>Use:</p> <pre><code>df['Result']=df.groupby('Product')['Volumes'].cumsum() </code></pre> <hr> <pre><code> Date Product Volumes Result 0 2018-04-01 a 10 10 1 2018-05-01 a 30 40 2 2018-06-01 a 40 80 3 2018-07-01 b 50 50 4 2018-08-01 ...
python|pandas
1
363,517
56,159,729
How to convert a list of indices into a cell list (numpy array of lists) in numpy with vectorized implementation?
<p>Cell list is a data structure that maintains lists of data points in an N-D meshgrid. For example, the following list of 2d indices:</p> <pre><code>ind = [(0, 1), (1, 0), (0, 1), (0, 0), (0, 0), (0, 0), (1, 1)] </code></pre> <p>is converted to the following 2x2 cell list:</p> <pre><code>cell = [[[3, 4, 5], [0, 2]...
<p>I don't think there is a good pure <code>numpy</code> but you can either use <code>pythran</code> or---if you don't want to touch a compiler---<code>scipy.sparse</code> cf. <a href="https://stackoverflow.com/q/55226662/7207392">this Q&amp;A</a> which is essentially a 1D version of your problem.</p> <p>[stb_pthr.py]...
numpy
0
363,518
56,033,954
Is there a way to check tail columns from a dataframe?
<p>I would like to see some columns in a dataframe but from the tail of columns. Not rows.</p> <p>Usually when you want to check the dataframe the following will be the easiest way to do. </p> <pre><code>print(df.head(5)) Au Ag Al As ... Zn Zr SAMPLE Alt 0 -0....
<p>You can use <code>iloc</code> for this, which allows integer-based indexing of a DataFrame. It takes the syntax <code>[i, j]</code>, where <code>i</code> indexes rows and <code>j</code> indexes columns, and allows slicing. (docs <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ilo...
python|pandas
4
363,519
56,251,349
How to plot a table with colors depending on the values in a dataframe?
<p>let's assume that I have this dataframe <code>df</code> transfered from a matrix: </p> <pre><code> 1 2 3 4 5 6 7 8 1 1399 17 4 3 0 0 0 0 2 11 374 2 3 1 4 0 1 3 7 0 187 4 0 0 1 1 4 2 3 4 308 0 0 0 3 5 2 0 0 0 280 3 ...
<p>Use <code>matplotlib.pyplot.subplots</code>:</p> <pre><code>import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.matshow(df, cmap=plt.cm.Greys) </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/QpwUo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QpwUo.png" alt="enter ...
python|pandas|dataframe|matplotlib|plot
3
363,520
56,175,757
Importing table that was created in python to docx
<p>I've created a table in python but I cannot import this table into docx, What should I do?</p> <pre><code>import docx import pandas as pd doc = docx.Document('Demo.docx') raw_data = {"Density" : [147.7, 148.6, 149.3, 153.3, 147.3, 147.8, 149.4, 147.8, 151.1, 148.5 ], "% Compaction":[95.4, 96.0, 95...
<p>The <a href="https://python-docx.readthedocs.io/en/latest/api/document.html#id1" rel="nofollow noreferrer">document</a> object supports an <code>add_table</code> method, which creates the table placeholder in the document. </p> <p>Your assignment statement is very wrong you're overwriting the package (<code>docx.ta...
python|pandas|dataframe|docx|python-3.7
0
363,521
56,125,380
resampling data - using SMOTE from imblearn with 3D numpy arrays
<p>I want to resample my dataset. This consists in categorical transformed data with labels of 3 classes. The amount of samples per class are:</p> <ul> <li>counts of class A: 6945</li> <li>counts of class B: 650</li> <li>counts of class C: 9066</li> <li>TOTAl samples: 16661</li> </ul> <p>The data shape without labels...
<p>I am considering a dummy <code>3d</code> array and assuming a <code>2d</code> array size by myself,</p> <pre><code>arr = np.random.rand(160, 10, 25) orig_shape = arr.shape print(orig_shape) </code></pre> <p>Output: <code>(160, 10, 25)</code></p> <pre><code>arr = np.reshape(arr, (arr.shape[0], arr.shape[1])) print...
python|numpy|imblearn
5
363,522
56,035,421
Parse text file in pandas dataframe
<p>I have a text file like this:</p> <pre><code>WP 000 Name Mumbai ANCHORAGE Lat 36°10.140000N Lon 5°23.860000W RL (Rumb Line) XTE= 0.30nm TurnRadius= 0.50nm WP 001 Name Mumbai PILOT OFF Lat 36°08.200000N Lon 5°23.770000W RL (Rumb Line) XTE= 0.20nm TurnRadius= 0.00nm </code></pre> <p>I want to create a dataf...
<p>Try This. I have read the file and parsed the parameters. You can make further enhancements to the code.</p> <pre><code>import re import pandas as pd from collections import ChainMap s = [] with open('readerfile.txt') as rf: s = [i.strip('\n') for i in rf.readlines()] sections = [] while(len(s)): try: ...
python|pandas|dataframe
0
363,523
56,327,448
How to rename multiple dataframes in one loop with a shared dictionary?
<p>I have multiple dataframes which all share the same number of columns with the same names. For some reason, I would like to rename all these columnes with a dictionary. </p> <p>I know how to do it for one dataframe at a time using the rename function of pandas such as: </p> <pre><code>df = df.rename(columns={"1": ...
<p>You are trying to modify a tuple, which is immutable. Use a list instead:</p> <pre><code>df_list = [df1, df2] for i in df_list: i = i.rename(columns={ '1':'a', '2':'b', '3':'c', ...}) </code></pre>
pandas|loops|multiple-columns|rename
1
363,524
56,183,815
python pandas data comparing
<p>I'm trying to compare two excels, one is the user matrix, the other one is I generated from a host. I want to know if the user settings are correct as of the matrix.</p> <p>the results I got the from the host, I imported to pandas: the user groups here is as column names!</p> <pre><code> Name Users Domain Admi...
<p>I would let the pandas imported from the host (let us call it <code>df_host</code>) unchanged, and create columns for groups in the pandas imported from the <em>matrix</em> (called <code>df_matrix</code>):</p> <pre><code>groups = ['Users', 'Domain Admins', 'Administrators', 'Schema Admins'] for g in groups: df...
python|pandas|csv
1
363,525
56,410,961
How do I turn oddly shaped arrays into a tensor
<p>I have a bunch of numpy arrays with different shapes and dimensions, and I need to turn it all into one tensorflow tensor as input to a neural network.</p> <p>I'm trying to use this network on a reinforcement learning problem, and at each time step it needs a single tensor. I have six numpy arrays, here are their s...
<p>Instead of an array containing integers you have created an array containing other arrays (note that <code>final_array.dtype</code> is not <code>dtype('int64')</code>). This is possible for numpy arrays, but not possible for tensorflow arrays (a tensorflow array can't contain other tensorflow arrays). This is why yo...
python|numpy|tensorflow
0
363,526
56,325,104
How can I convert numpy.ndarray having type object to torch.tensor?
<p>I'm trying to work on lstm in pytorch. It takes only tensors as the input. The data that I have is in the form of a <code>numpy.object_</code> and if I convert this to a <code>numpy.float</code>, then it can be converted to <code>tensor</code>.</p> <p>I checked the data type using <code>print(type(array))</code> it...
<p>The pytorch LSTM returns a tuple. So you get this error as your second LSTM layer <code>self.seq2</code> can not handle this tuple. So, change </p> <pre><code>prefix1=self.seq1(input1) suffix1=self.seq1(input2) </code></pre> <p>to something like this:</p> <pre><code>prefix1_out, prefix1_states = self.seq1(input...
python-3.x|numpy|pytorch
1
363,527
56,139,532
Pandas - column median applied on lambda function
<p>Given the dataset: </p> <pre><code>matrix = [(222, 34, 23), (333, 31, 11), (444, 16, 21), (555, 32, 22), (666, 33, 27), (777, 35, 11) ] dfObj = pd.DataFrame(matrix, columns=list('abc')) </code></pre> <p>I want to apply the formula <code>(value - column median) ...
<p>Is this what you need ? </p> <pre><code>dfObj.div(dfObj.median())**2 Out[116]: a b c 0 0.197531 1.094438 1.144402 1 0.444444 0.909822 0.261763 2 0.790123 0.242367 0.954029 3 1.234568 0.969467 1.047052 4 1.777778 1.031006 1.577069 5 2.419753 1.159763 0.261763 </code></pre...
python|pandas
2
363,528
56,303,554
Timeseries dataset split data to chunks of equal size
<p>I have time series dataset to predict stock market price, in format: Date from 2015 - 2019 and time steps t1- t300 with float values.</p> <pre><code>Date t1 t2 t3 t4 ... t300 01-01-2019 -0.34 0.40 0.50 1.2 02-01-2019 0.45 0.56 0.34 0.45 ... </code></pre> <p>I want to split each row t...
<p>IIUC, you need to split the df over <code>axis=1</code>, use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html" rel="nofollow noreferrer"><code>np.split()</code></a>:</p> <pre><code>np.split(df,df.shape[1]/50,axis=1) #or np.split(df.values,df.shape[1]/50,axis=1) </code></pre> <p>Adding...
python|pandas
4
363,529
56,023,786
Intuition behind fluctuating training loss
<p>I am trying to build a convolutional autoencoder for 28x28x5 images. Below is the summary of my model:</p> <hr> <pre><code>Layer (type) Output Shape Param # ================================================================= conv2d_1 (Conv2D) (None, 28, 28, 16) 736 ____...
<p>I think the model output is a constant. Can you check for that? How many samples are present in your validations set? If the model output is constant, the training loss would fluctuate( because of different samples in different batches) whereas the validation loss would remain constant. Maybe try altering the learni...
python|tensorflow|machine-learning|data-science|autoencoder
0
363,530
56,221,189
Why do I get a Memory Error when solving a sparse system of linear equations?
<p>When trying to solve the large, sparse system of linear equations from below, I simply get a <code>MemoryError:</code>. How can I resolve this issue?</p> <p>Also, this code is based on an implementation in Matlab which should run fine. In the original version, <code>M</code> is a three-dimensional matrix, I don't k...
<p>The traceback should show whether the problem is in the <code>spsolve</code> or while creating one or both of the arguments, <code>Mt@M</code> or <code>Mt.dot(dx)</code>.</p> <p>With <code>M</code> and <code>dx</code> shapes <code>((6891, 474721000)</code>, <code>(6891, 3)</code></p> <pre><code> Mt@M (474721000,6...
python|matlab|numpy|scipy|sparse-matrix
2
363,531
55,994,244
How to extract the X or a tuple value from openCV - findContours where Y=39
<p>I ran <code>cv2.findContours</code> on an image.</p> <p>The result is 3 contours. This is the output of findContours - </p> <pre><code>print (cnt) [array([[[149, 0]], [[149, 1]], [[148, 2]], [[148, 8]], [[149, 9]], [[149, 11]], [[148, 12]], [[148, 39]]...
<p>OpenCV contour arrays can be tricky to work with. I usually do this before working with them:</p> <pre class="lang-py prettyprint-override"><code>contour = np.array([list(pt[0]) for ctr in contours for pt in ctr]) </code></pre> <p>Then you can get your list of points:</p> <pre class="lang-py prettyprint-override"...
python|python-3.x|numpy|opencv
1
363,532
55,851,263
Use the highest value for duplicate IDs (Pandas DataFrame)
<p>I am calculating the total sum of 'price' for each 'id'. But when there are duplicates on 'loc_id' it should use the highest price for calculations and ignore the lower prices for the same 'loc_id'.</p> <p>The example below shows 3 duplicates for A-1. The highest price for A-1 is 100 so the total sum for A should b...
<p>Here is one way using <code>sort_values</code> + <code>drop_duplicates</code></p> <pre><code>df=df.sort_values(['price']).drop_duplicates(['id','loc_id'],keep='last') df.groupby(['id']).price.agg(['mean','sum']) Out[366]: mean sum id A 150 300 B 40 80 </code></pre>
python|pandas
3
363,533
55,758,240
Include rows from multiple dataframes into a new dataframe
<p>I have around 20 dataframes where I am targeting values of a specific row. For example, I'm showing a simplified version of one of my dataframe</p> <pre><code> Type N1 N2 43 121 455 23 554 52 85 74 615 </code></pre> <p>I want to get the row of every "Type" 23 from my datasets</p>...
<p>I think that:</p> <pre class="lang-py prettyprint-override"><code>df_list = [df1,df2, ...,df20] filtered_df_list = [ df[df['Type'] == 23] for df in df_list ] #Filter each mini-df on "Type" = 23 final_df = pd.concat(filtered_df_list) # Concat the small mini-dfs (hence faster concatenating) </code></pre> <p>Could b...
python|pandas|dataframe
2
363,534
55,808,067
How to extract including data with group by
<pre><code>|id|name|state| |1|A|yes| |2|B|yes| |3|B|no| |4|C|yes| |5|C|yes| |6|D|no| </code></pre> <p>When I define above Dataframe using df.groupby(['name']). I would like to extract the name item with 'yes' at state.</p> <p>In case of this, A, B, C is target data to extract.</p> <p>How can I extract that data?</p>
<p>You can extract values by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unique.html" rel="nofollow noreferrer"><code>Seri...
pandas
2
363,535
55,951,612
How to find max values of columns and arrange them in order based on condition using pandas?
<p>I have the following dataframe</p> <pre><code>import pandas as pd import numpy as np d = { 'ID':[1,2,3,4,5,6], 'Price1':[5,9,4,3,9,np.nan], 'Price2':[9,10,13,14,18,np.nan], 'Price5':[5,9,4,3,9,np.nan], 'Price6':[np.nan,10,13,14,18,np.nan], 'Price10':[9,10,13,14,18,np.nan], 'Price3':[5,9...
<p>Use:</p> <pre><code>c1 = ['Price1', 'Price2', 'Price5','Price6','Price10'] col1=[f"maxA{i+1}" for i in range(len(c1))] #['maxA1', 'maxA2', 'maxA3', 'maxA4', 'maxA5'] c2 = ['Price3', 'Price4', 'Price7', 'Price8', 'Price9'] col2=[f"maxB{i+1}" for i in range(len(c2))] #['maxB1', 'maxB2', 'maxB3', 'maxB4', 'maxB5'] </c...
pandas
2
363,536
55,718,982
extract xml to pandas dataframe with unknown number of nodes
<p>The below code sample works if there is only one node. However, our use case we dont know how many nodes we will receive</p> <p><a href="https://stackoverflow.com/questions/54651813/convert-a-xml-to-pandas-data-frame-python">Convert a xml to pandas data frame python</a></p> <p>Sample as below. How we can parse thi...
<p>I suspect you need to parse xml-data to several dataframes, e.g. as follows:</p> <pre><code>import xmltodict # install this module first data = """&lt;?xml version = '1.0' encoding = 'UTF-8'?&gt; &lt;EVENT spec="IDL:com/RfcCallEvents:1.0#Z_BAPI_UPDT_SERV_NOTIFICATION"&gt; &lt;eventHeader&gt; &lt;objectName...
python|xml|pandas|dataframe
0
363,537
55,862,118
Numpy failure while installing python(3.6.6) module pandas-0.24.2. on AIX 7.1.0.0 powerpc
<pre><code>Aix ---&gt; 7.1.0.0 (64 Bit) Python --&gt; 3.6.6 Not able to install module pandas-0.24.2 , It is failing while trying to import numpy with the below error message, ImportError: 0509-022 Cannot load module $PYTHON_HOME/lib64/python3.6/site-packages/numpy-1.16.2-py3.6-aix-7.1.egg/numpy/core/_multiar...
<p>try :</p> <ol> <li>pip uninstall -y numpy</li> <li>pip uninstall -y setuptools</li> <li>pip install setuptools</li> <li>pip install numpy</li> </ol>
pandas|numpy|python-3.6|aix
0
363,538
55,915,167
Swap gnews with ELMo in the simple colab tutorial
<p>I'm working on this colab notebook:</p> <p><a href="https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/tf2_text_classification.ipynb" rel="noreferrer">https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/tf2_text_classification.ipynb</a></p> <p>I'd like...
<p>The problem is that Keras is assuming the input to be <code>float32</code>:</p> <blockquote> <p>conversion requested dtype <code>string</code> for Tensor with dtype <code>float32</code></p> </blockquote> <p>You can tell that this is the input because of the name "Placeholder_12:0". Placeholder tensors are used f...
tensorflow|google-colaboratory|tensorflow-hub|elmo
1
363,539
55,641,241
Generalize the use of numpy.meshgrid
<p>Below, a minimal example that produce an expanded grid using the <code>meshgrid</code> function:</p> <pre><code>from numpy import array, meshgrid foo = array(([1, 2, 3], [4, 5])) array(meshgrid(foo[0], foo[1])).T.reshape(-1, 2) ## array([[1, 4], ## [1, 5], ## [2, 4], ## [2, 5], ## ...
<p>Here is how you can transform your call to have it working for any 2D input: </p> <pre class="lang-py prettyprint-override"><code>from numpy import array, meshgrid def mesh(foo): return array(meshgrid(*foo)).T.reshape(-1, foo.shape[0]) print(mesh(array(([1, 2, 3], [4, 5])))) print(mesh(array(([1, 2, 3], [4, 5],...
python|numpy
2
363,540
55,692,981
OpenCV warpPerspective with another datatype
<p>I have a picture and a depth map that belongs to that picture, I need to have the depth of each pixel(I am using a kinect). I would like to create a panorama view with this picture and it's depth, so I used some opencv methods. This line in particular is the one that is causing a problem at the moment:</p> <pre><co...
<p>It's not <a href="https://docs.opencv.org/3.4/da/d54/group__imgproc__transform.html#gaf73673a7e8e18ec6963e3774e6a94b87" rel="nofollow noreferrer"><code>warpPerspective</code></a> that doesn't want to take this datatype. It's OpenCV in general, since arrays of unsigned 32bit integers are not supported.</p> <p>You ca...
python|numpy|opencv
0
363,541
55,825,697
How can i append dataframe from pandas to the oracle table?
<p>I want to append dataframe (pandas) to my table in oracle. But this code deletes all rows in table:( </p> <p>My dataframe and my result become this:</p> <pre><code> 0, 0, 0, ML_TEST, 0, 5 0, 0, 0, ML_TEST, 0, 6 </code></pre> <p>by this code block below :</p> <pre><code>import cx_Oracle import pandas as pd fro...
<p>I think this may help :</p> <pre><code>import cx_Oracle import pandas as pd dataset = pd.read_csv(&quot;C:\\pathToFile\\denemedf.txt&quot;, delimiter=&quot;,&quot;) con = cx_Oracle.connect('uname/pwd@serverName:port/instanceName') cursor = con.cursor() sql='INSERT INTO gnl.tbl_deneme VALUES(:1,:2,:3,:4,:5,:6)' df_...
python|sql|oracle|pandas|dataframe
9
363,542
55,706,548
Adding inputs to a convolutional neural network after convolution and pooling layers
<p>I'm building a convolutional neural network which will contain a certain number of convolution and pooling layers. The problem is that i wanted to add some extra inputs after the feature extraction steps (convolution+pooling).</p> <p>This extra inputs will be added to the flattened feature maps (first layer of the ...
<p>You can create such a model with <code>tf.keras.models.Model</code> class. </p> <p>First, we can build the <code>tf.keras.models.Sequential</code> model for the Convolution and Pooling layers.</p> <pre><code>conv_model = tf.keras.models.Sequential( [ ... ] ) </code></pre> <p>Then as you said, we need a fully conn...
tensorflow|keras|conv-neural-network
2
363,543
55,854,679
How to make Pandas Excel writer append to an existing sheet in a workbook instead of creating a new worksheet?
<p>I have a excel workbook with two sheets ('variable','fixed'). In parallel, I have a data frame (pandas) with some data. I want to append the data in the data frame to the sheet ('variable') below the existing data in that sheet. But, the following code creates a new sheet called 'variable1' and dumps the data instea...
<p>To append an excel document use:</p> <pre><code># open the workbook wb = openpyxl.load_workbook('file_name.xlsx') # assign a var to worksheet ws = wb['sheet_name'] </code></pre> <p>Then you can do things like:</p> <pre><code># write to cell wb['sheet_name'].cell(row=4, column=1).value = string_to_enter_to_cell ...
pandas|openpyxl|pandas.excelwriter
0
363,544
55,826,481
Pandas function to insert rows into a table
<p>I am trying to insert records into a Netezza table by reading a CSV file into a pandas dataframe , but keep getting the key error.</p> <p><code>KeyError: ('columnname', 'totalCount', 'distinctValuesCount')</code></p> <p>Am i missing something here ... </p> <h2>Env Stack</h2> <p>python 3.7.0 DB : Netezza Connect...
<p>It looks like you are trying to extract certain columns from a pandas <code>Series</code> by doing</p> <pre class="lang-python prettyprint-override"><code>row["columnname","totalCount","distinctValuesCount"] </code></pre> <p>but that won't work. Instead, you need to use something like</p> <pre class="lang-pytho...
python|python-3.x|pandas|pyodbc
0
363,545
55,738,420
What is the desired behavior of average pooling with padding?
<p>Recently I've trained a neural network using pytorch and there is an average pooling layer with padding in it. And I'm confused about the behavior of it as well as the definition of average pooling with padding.</p> <p>For example, if we have a input tensor:</p> <pre><code>[[1, 2, 3], [4, 5, 6], [7, 8, 9]] </cod...
<p>It's basically up to you to decide how you want your padded pooling layer to behave.<br> This is why pytorch's avg pool (e.g., <a href="https://pytorch.org/docs/stable/nn.html#torch.nn.AvgPool2d" rel="nofollow noreferrer"><code>nn.AvgPool2d</code></a>) has an optional parameter <code>count_include_pad=True</code>:<b...
image-processing|machine-learning|computer-vision|pytorch|max-pooling
2
363,546
55,774,468
assign string value to a cell in pandas
<p>I've created a new row for storing mean values of all columns. Now I'm trying to assign name to the very first cell of the new row</p> <p>I've tried the conventional method of assigning value by pointing to the cell index. It doesn't return any error but it doesn't seems to store the value in the cell.</p> <pre><c...
<p>For me working nice, but here are 2 alternatives for set value by last row and column name. </p> <p>First is <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="noreferrer"><code>DataFrame.loc</code></a> with specify last index value by indexing:</p> <pre><code>data11...
python|pandas|numpy|python-3.6
5
363,547
55,889,956
Repeat ndarray n times
<p>I have a <code>numpy.ndarray</code> with <code>True</code>/<code>False</code>:</p> <pre><code>import numpy as np a = np.array([True, True, False]) </code></pre> <p>I want:</p> <pre><code>out = np.array([True, True, False, True, True, False, True, True, False]) </code></pre> <p>I tried:</p> <pre><code>np.repeat(a...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html" rel="nofollow noreferrer">np.tile</a></p> <pre><code>&gt;&gt;&gt; a = np.array([True, True, False]) &gt;&gt;&gt; np.tile(a, 3) ... array([ True, True, False, True, True, False, True, True, False]) </code></pre>
python|numpy|repeat
4
363,548
55,878,248
How to search a specific value in the whole dataframe and return its column and row indexes
<p>In pandas, I want to search for a specific value in the whole data frame and return its row and column index.</p> <p>For example: </p> <pre><code> apple pear orange banana cat 1 2 3 4 dog 5 6 7 8 fish 9 10 11 12 bird 13 14 15 16 </code></pre> <p>Input: 1...
<p>Use <code>np.where</code> for indices for match and indexing for match first value:</p> <pre><code>i, c = np.where(df == 10) print ((df.index[i][0], df.columns[c][0])) ('fish', 'pear') </code></pre> <p>If possible value not exist in data use <code>next</code> with default value:</p> <pre><code>print ((next(iter(...
python|pandas|dataframe|search
5
363,549
55,808,426
NotImplementedError: __deepcopy__() is only available when eager execution is enabled
<p>I am using GridSearchCV in order to tune hyper parameters for my LSTM Model:</p> <pre><code>def compile_lstm(self): '''create the layers''' self.model = keras.models.Sequential() self.model.add(keras.layers.LSTM(50)) self.model.add(keras.layers.Dense(1, activation='softmax')) self.model.co...
<p>As i see in TF, this happens because of Keras, TF.keras and TF Version issues.</p> <p>tf.keras and keras Model are slightly different when saving and loading Model(Cloning).</p> <p>This may help you : <a href="https://stackoverflow.com/a/52728435/9273317">https://stackoverflow.com/a/52728435/9273317</a></p>
python-3.x|tensorflow
0
363,550
55,917,020
Conditional naming for multiple columns
<p>I have a dataset;</p> <pre><code>&gt;&gt;&gt; all_transcripts ID Type Name 1 Guest Hugo 1 Guest Hugo 1 Boss Boss 1 Boss Boss 2 Boss Boss 2 Guest Calvin 2 Guest Calvin 3 Guest Klein 3 Boss Boss </code></pre> <p>Now, I want to create a column called <code>...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> by helper <code>Series</code> created by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code...
python|pandas|conditional
2
363,551
55,637,638
Create new column by sampling bits of other columns
<p>Consider the dataframe containing N columns as shown below. Each entry is an 8-bit integer.</p> <pre><code>|---------------------|------------------|---------------------| | Column 1 | Column 2 | Column N | |---------------------|------------------|---------------------| | 4 ...
<p>Same logic like before when you do the sample , but here I convert between the binary and decimal twice, with <a href="https://stackoverflow.com/questions/53218931/how-do-i-unnest-explode-a-column-in-a-pandas-dataframe">unnesting</a> , then join back the result</p> <pre><code>df1=df.applymap(lambda x : list('{0:08b...
python|pandas
2
363,552
55,922,358
Looping through dataframe rows in reverse
<p>I was trying to loop through dataframe rows in reverse order.</p> <p>Based on row position rather than index name.</p> <p>I though this code should work but its not.</p> <pre><code>for i, row in enumerate(df[::-1].iterrows()): print (i) </code></pre> <p>As when I run it, it produces</p> <pre><code>0 1 2 3...
<p>I you accept reindexing, you can also do</p> <pre><code>for i, row in enumerate(df.reindex().sort_index(ascending=False): print (i) </code></pre>
pandas|loops
3
363,553
55,773,063
Reading two Complete different dataframes from a single csv file
<p>Essentially having trouble reading all of the contents of a single csv file. The first few lines of the csv file, contains 7 columns.The rest of the file contains 13 columns. I can read them fine, separately at different times, but i want to know if there is a way i could read them at once. Some photos of the csv f...
<p>It is possible, but still better/simplier is read file twice in pandas if want correct set <code>types</code> of columns by default - not all columns to strings:</p> <pre><code>r = [0,1,3,4,5,6,7] df2 = pd.read_csv(file,skiprows = r, delimiter = '\t',header = None, names=range(13)) print (df2.head()) ...
python|pandas|csv|dataframe
1
363,554
55,579,159
One hot encoding a numpy array
<p>I'm working on an image classification problem where I got the train labels as a 1-D numpy array, like <code>[1,2,3,2,2,2,4,4,3,1]</code>. I used</p> <pre><code>train_y = [] for label in train_label: if label == 0: train_y.append([1,0,0,0]) elif label == 1: train_y.append([0,1,0,0]) elif...
<p>It's always a good habit to use numpy for arrays. <code>np.unique()</code> determins the labels you have in <code>train_labels</code>. <code>ix</code> is an array of indices. <code>np.nonzero()</code> gives the indices of <code>train_lables</code> where <code>train_labels == unique_tl[iy]</code>.</p> <pre><code>imp...
python|python-3.x|numpy
1
363,555
55,998,133
keras layers has no attribute Dense
<p>I'm currently involving Coursera-Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning course. I got an error in the following code.</p> <p>Here is my python code,</p> <pre><code># y = 2x - 1 import tensorflow as tf # helps us to represent our data as lists easily and quickly...
<p>The layername is Den<strong>s</strong>e, not Den<strong>c</strong>e.</p>
python|tensorflow|keras
1
363,556
55,624,576
Pandas Dataframe - Group by Col A and sum each groups Col C
<p>I have the below dataframe:</p> <pre><code>COLA COLB COLC a cfg 100 b gdd 100 c ert 100 d yrt 100 a yui 100 d ouo 100 a ooo 100 b qwe 100 </code></pre> <p>I want to combine all the items in COLA (groupby?) and then sum their...
<p>The GroupBy object supports column indexing in the same way as the DataFrame, and returns a modified GroupBy object</p> <pre><code>import pandas as pd df=pd.read_csv(path) df.groupby('COLA')['COLC'].sum() </code></pre>
python|pandas
2
363,557
55,741,391
How to create a new column in dataframe, which will be a function of another column and conditionals faster than a for loop?
<p>I have a relatively large data frame (8737 rows and 16 columns of all variable types, strings, integers, booleans etc.) and I want to create a new column based on an equation and some conditionals. Basically, I want to iterate over one particular column, take its values and after an operation calculate a value. Then...
<p>Not sure if this you're looking for. I think you can use .apply for this case. For example:</p> <pre><code>df=pd.DataFrame() df['A']=[5,3,7,4,3,0,1,7,8,10,9,4,3,2,0] df['S']=np.nan df['S'][0]=5 def cal(i): return i**2 df['S'] = df['A'].apply(cal) display(df) </code></pre> <p>It will assign new values on 'S'...
python|pandas|data-analysis
0
363,558
55,963,992
Python: get unsorted list of singular values from numpy/scipy svd
<p>I have a square matrix and want to use svd to reduce condition number of the matrix by elimination of some rows/columns. </p> <p>I used numpy/scipy both give sorted list of singular values. </p> <p>Using sorted list, I can easily reconstruct a smaller matrix by discarding some small singular values. But it is diff...
<p>To perform a singular value decomposition of a matrix you can look at the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.svd.html" rel="nofollow noreferrer">.linalg`</a> module in numpy.</p> <p>A SVD of a matrix factorizes it into the product of three matrices:</p> <p><strong>M</strong>...
python|numpy|scipy|svd
0
363,559
55,597,077
How to print only the first and last 5?
<p>I would like to print the first and last 5 of my one hot encoding data. The code is below. When it prints the first and last 30 are printed.</p> <pre><code>Code: from random import randint import pandas_datareader.data as web import pandas as pd import datetime import itertools as it import numpy as np import csv...
<p>You can use the <code>head</code> and <code>tail</code> function. You can read about them <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.head.html#pandas.DataFrame.head" rel="nofollow noreferrer">here</a> </p> <pre><code>&gt;&gt;&gt; DataFrame.head(n) &gt;&gt;&gt; DataFrame.ta...
python|pandas|one-hot-encoding
2
363,560
55,672,542
How to fix this error while importing tflearn library?
<p>I was importing the tflearn library and I'm getting this error message. I'm new to this and just started to learn through tensorflow. I had problems installing tensorflow through pip as well but it successfully installed after using solution in one of the posts on website</p> <pre><code>Traceback (most recent call ...
<p>Main reason for this error is not having vs C++ redistributables dowloaded.</p> <p>Make sure all the <a href="https://www.tensorflow.org/install/pip#system-requirements" rel="nofollow noreferrer">software requirements</a> mentioned are installed.</p> <p>Windows 7 or later (64-bit) <a href="https://docs.microsoft.com...
python|tensorflow|neural-network|deep-learning|tflearn
1
363,561
55,713,778
Low training loss with high validation loss and low validation accuracy
<p>I'm trying to get good accuracy with Keras (TensorFlow as the backend) using <code>categorical_crossentropy</code> for multiclass classification problem (Heart disease dataset). My model can reach good training accuracy, but the validation accuracy is low (with high validation loss). I have tried over-fitting soluti...
<p>Help yourself by increasing your validation size to more like ~30%, unless you really have a large data set. Even 50/50 is often used.</p> <p>Remember that <strong>good loss and acc with bad val_loss and val_acc implies overfitting.</strong></p> <p>Try this basic solution:</p> <pre><code>from keras.callbacks impo...
python|tensorflow|keras|neural-network
0
363,562
55,919,554
Tensorflow Error: Consider casting elements to a supported type
<p>I just use scikit-image load image from a folder, but When I run <code>get_batches()</code> function, an error occurred. I looked at some blogs, but the problem still persists. I don't know how to deal with it.</p> <p>The problem was occur in <code>image = tf.cast(image, tf.string)</code>, it's locate in function <...
<p>You're casting image to <code>string</code>. Consider using either <code>tf.float32</code> or <code>tf.int64</code>. I think that <code>tf.float32</code> is a good choice since you're casting the batch later in the code this way.</p> <pre><code>images_batch = tf.cast(image_batch, tf.float32) </code></pre> <p>Insid...
python|tensorflow|scikit-image
0
363,563
55,625,447
In Keras, is it possible to cluster the input data and then feed the data to different subnetworks depending on the cluster?
<p>Basically, what I'm trying to do is:</p> <ul> <li><p>Perform some basic clustering, like K-means, of the input data.</p></li> <li><p>Get the cluster membership of the input samples. </p></li> <li><p>Train a separate deep neural network submodel for each cluster. </p></li> </ul> <p>Below is a basic diagram of the i...
<p>I think the problem is that you cluster the data to three groups and want to use a model to learn the different distribution of each group. I have some rough ideas.</p> <ol> <li><p>You can let the cluster index be the label of each group and fit this label and your original goal at the same time. Like:</p> <p>outp...
tensorflow|keras
0
363,564
55,937,068
Operations on existing Excel sheet using Pandas
<p>I have two csv files and I have merged the csv files and exported them to an Excel sheet.</p> <p>Now can I add a new column in the existing Excel sheet where the result of the new column will be division operation of two columns existing.</p> <p>Example:</p> <pre><code>col_new=col4/col6 </code></pre> <p>I have t...
<p>You can convert the first column to an integer using <code>str.replace(',','')</code> as you have done and then use <code>pd.to_numeric()</code> to recast the entire series at once. Now that you have the two columns you're interested in as integers, just use the ability to divide one series by another and store that...
python|pandas
0
363,565
55,657,849
TypeError: Trying to split data randomly in training and test set
<p>I want to take the first 70% of my shuffeled data as training data and the rest as test data, but I receive that strange error.</p> <p>I have looked at other code examples with that error but don't get it, sorry.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np segment_relative_path = ["a", ...
<p>You are trying to use an index array for a list. Lists accept only scalar integer indices. However if you convert <em>segment_relative_path</em> into an array, it will work:</p> <pre><code>import numpy as np segment_relative_path = ["a", "b", "c", "d", "e", "f"] idx = np.random.permutation(len(segment_relative_pat...
python-3.x|numpy|typeerror
0
363,566
55,942,361
How to remove columns in group by Pandas
<p>Trying to remove a column of data that is no longer needed.</p> <p>I have tried to use .drop and it isn't doing anything that I can tell.</p> <pre><code>df=df.groupby(df['Distributor'])['Tickets Sold'].sum() df1=df[df.div(df.sum()).lt(0.01)] df2=df.drop(df1.index) yourdf=pd.concat([df2,pd.Series(df1.sum(),index=['...
<p>Try specifying <code>axis=1</code> to tell it you want to drop a column rather than an index.</p> <pre><code>yourdf.drop('Tickets Sold', axis=1, inplace=True) print(yourdf) # Distributor # 0 20th Century Fox # 1 Focus Features # 2 Lionsgate # 3 Paramount Pictures # 4 STX Entertainment...
python|pandas|csv|data-analysis
0
363,567
55,705,704
How to use groupby().apply() instead of running loop on whole dataset in Python Pandas?
<p>I have a large dataset, which looks like below: </p> <pre><code>Year Company Sales Dummy 1993 A 100 1 1994 A 50 1 1995 A 50 1 1996 A ...
<p>I know how to solve this problem. </p> <p>My defined function should return a new data frames because I aggregated data by group and need a new dataframes in this case.</p> <p>If I do not put return, pandas will only do aggregate, therefore your output will be '__'</p> <pre><code>*** Create Dummy variables ...
python|pandas
0
363,568
55,653,940
how do I implement Salt& Pepper layer in Keras?
<p>I need to implement salt &amp; pepper layer in keras like Gaussian noise, I tried to use the following code but it produces several errors. could you please tell me what is the problem? do you have any other suggestion for implementing S&amp;P layer? Thank you.</p> <pre><code>from keras.engine.topology import Layer...
<p>In image processing, salt and pepper noise basically changes the value of a ratio of pixels, which are selected randomly, to either salt (i.e. white, which is usually 1 or 255 depending on the range of image values) or pepper (i.e. black which is usually 0). Although, we can use the same idea in other domains beside...
python|tensorflow|image-processing|keras|noise
2
363,569
55,765,545
Issues with binning using pandas.cut
<p>Apologies if this was already asked and solved. I spent quite some time trying to solve what should be seemingly simple. First the error: </p> <blockquote> <p>raise ValueError("Input array must be 1 dimensional") ValueError: Input array must be 1 dimensional</p> </blockquote> <p>Code leading to the error:</p>...
<p>It may be due to you having <code>MultiIndex</code> column headers. This code works for me if I flatten the columns:</p> <pre><code>heart_data = pd.DataFrame({('Age',): {204: 62, 159: 56, 219: 48, 174: 60, 184: 50, 295: 63, 269: 56, 119: 46, 193: 60, 154: 39, 51: 66, 249: 69, 278: 58, 229: 64, 208: 49, 302: 57, 58:...
python|pandas
3
363,570
55,768,201
Python partitioning an N-dimensional volume into uniform sub-volumes
<p>I have an object occupying an underlying N-dimensional square grid (represented by a numpy array) so that only 25% of the grid points are occupied. Each 1x1x1x... N-cube (i.e., hypercube) in this grid contains the same amount of this object (located only at some of the vertices of this hypercube). I have an array of...
<p>If you have the grid as an <code>ndim+1</code>-dimensional array of coordinates like so</p> <pre><code>a = np.stack(np.mgrid[1:5, 1:5], -1) </code></pre> <p>then it is just a matter of judicious reshaping and transposing:</p> <pre><code>import itertools as it # dimensions for reshape: # split all coordinate axes...
python|arrays|numpy
0
363,571
55,933,958
how to pass an empty pandas query
<p>For improvement in a model I am passing several .query() to a pandas dataframe. In the for loop I would to have an empty query as well, but didnt find anything in documentation. It should return the full dataframe.</p> <p>I tried:</p> <pre><code>temp_df.query(None) temp_df.query() </code></pre> <p>But this doesnt...
<p>if your DataFrame isn't MultiIndexed, you can use</p> <pre><code>df.query('tuple()') </code></pre>
python|pandas
2
363,572
55,595,965
groupby .sum() takes only one element in pandas dataframe
<p>I have a Pandas dataframe with two columns: </p> <p><a href="https://i.stack.imgur.com/l9I3y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l9I3y.png" alt="enter image description here"></a></p> <p>I would like to group the numbers by the column <code>Fee_Code</code>. I do the following:</p> <...
<p>Solved it. My column of values was not numeric, so it was just taking the first element.</p> <p>To make it numeric I did the following:</p> <pre><code>df.loc[:, 'Value'] = pd.to_numeric( df.loc[:, 'Value'], downcast='float', errors='coerce') </code></pre> <p>And then <code>.groupby(..).sum(..)</code> worked perfe...
python|pandas
0
363,573
55,699,494
How to calculate Volume Weighted Average Price (VWAP) using a pandas dataframe with ask and bid price?
<p>How do i create another column called vwap which calculates the vwap if my table is as shown below?</p> <pre><code> time bid_size bid ask ask_size trade trade_size phase 0 2019-01-07 07:45:01.064515 495 152.52 152.54 19 NaN NaN OPEN 1 2019-01-07 07:45:01....
<p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a> to give you the price from the correct column (<code>bid</code> or <code>ask</code>) depending on the value in the <code>trade</code> column. Note that this gives you the b...
python-3.x|pandas|numpy|dataframe|quantitative-finance
1
363,574
64,776,987
How to plot one columns "usage" of another column in pandas
<p>I would like to plot one variable as a constant, total_cap, in this case and layer on the maxused_capacity and meanused_capacity values. Essentially I would like the visual of a stacked bar plot but I do not want the totals agg'd together, the height of the bar for each site should awlays be just the value of Total...
<p>IIUC this does what you want to achieve by scaling the values relative to <code>Total_Cap</code></p> <pre><code>df.set_index('SITE', inplace=True) df[['maxused_Cap','meanused_Cap']].div( (df['maxused_Cap']+df['meanused_Cap'])/df['Total_Cap'], axis=0).plot.bar(stacked=True, figsize=(8,6)); </code></pre> <p>Ou...
python|pandas|matplotlib
0
363,575
64,928,135
Pandas pivot_table() aggfunc aggregation conditional on multiple columns?
<p>I want to aggregate one column with a pandas pivot table, but the custom aggregation should be conditional on a different column in the dataframe.</p> <p>See the example below: Say I want to sum the &quot;Number_mentions&quot; column for each value in the &quot;Newspaper&quot; column if the value of &quot;Number_men...
<p>You need different approach, because pivot_table cannot working with 2 columns.</p> <p>So first replace non matched values to missing values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.where.html" rel="nofollow noreferrer"><code>Series.where</code></a> and then processing this...
python|python-3.x|pandas|dataframe|pivot-table
0
363,576
64,815,425
Python converting a list of different lists with different timestamps into a dataframe
<p>I have a biglist to which different dataframes where appended through a for loop operation. Now the biglist has different lists. Some of this sublists have matching timestamp and some dont. I want to convert this biglist into a dataframe with each data included. My code:</p> <pre><code>biglist = [ ...
<p>Use <code>pd.merge</code> instead:</p> <pre class="lang-py prettyprint-override"><code>df1 = pd.DataFrame([[1], [1], [4]], columns=['A'], index=['i1', 'i2', 'i3']) df2 = pd.DataFrame([[2], [3], [6]], columns=['B'], index=['i1', 'i2', 'i4']) biglist = [df1, df2] final_df = biglist[0] for df in biglist[1:]: final_...
python|pandas|list|dataframe
0
363,577
64,622,323
Error in replacing value to integer in pandas
<p>The dataset named df has a column named TExitStatus and it has the following value_counts:</p> <pre><code>df['TExitStatus'].value_counts() </code></pre> <p><img src="https://i.stack.imgur.com/hARcH.png" alt="Output" /></p> <p>I need to replace value 'W' to -1 and 'G' to 1</p> <p>I tried replacing values by the follo...
<p>you can use Numpy lib for multiple conditions apply</p> <pre><code>import numpy as np df2['TExitStatus'] = np.where(df2['TExitStatus'] == 'G',1, np.where(df2['TExitStatus'] == 'W', -1,df2['TExitStatus']) </code></pre>
python|pandas|replace
0
363,578
64,663,815
Extract corresponding df value with reference from another df
<p>There are 2 dataframes with 1 to 1 correspondence. I can retrieve an <code>idxmax</code> from all columns in <code>df1</code>.</p> <p>Input:</p> <pre><code>df1 = pd.DataFrame({'ref':[2,4,6,8,10,12,14],'value1':[76,23,43,34,0,78,34],'value2':[1,45,8,0,76,45,56]}) df2 = pd.DataFrame({'ref':[2,4,6,8,10,12,14],'value1_p...
<p>Your main problem is matching the columns between <code>df1</code> and <code>df2</code>. Let's rename them properly, melt both dataframes, merge and extract:</p> <pre><code>(df1.melt('ref') .merge(df2.rename(columns={'value1_pair':'value1', 'value2_pair':'value2'}) ....
python|pandas
1
363,579
64,695,646
How to remove duplicates when upon editing an entity the originals are not replaced?
<p>Consider that we have a dataset that represents some purchases. Products that have been bought together have the same basket ID.</p> <p>When a purchased product is edited (e.g. the wrong price was inserted at first) it does not replace the original record. Instead, a new record is made for <strong>EVERY</strong> pro...
<p>Can you remove any rows that have a <code>BasketID</code> that appears in <code>PreviousBasketID</code>?</p> <p>Something like:</p> <pre class="lang-py prettyprint-override"><code>df = df[~df[&quot;BasketID&quot;].isin(df[&quot;PreviousBasketID&quot;])] </code></pre> <p>Here the <code>~</code> means bitwise not. <a ...
python|pandas
1
363,580
64,659,356
Pandas, most efficient way to apply a two functions on entire row
<p>I have the following DataFrame:</p> <pre><code> Date Label Top1 \ 0 2008-08-08 0 b&quot;Georgia 'downs two Russian warplanes' as cou... 1 2008-08-11 1 b'Why wont America and Nato help us? If they w... 2 2008-08-12 0 b'Remember that ador...
<p>You need to pass in the rows to the apply-function. Try this:</p> <pre><code>def scorer(row): date_scores = [] for col in row: if 'Top' in col: date_scores.append(get_sentiment_score(row[col])) sentiment_daily_mean = date_scores.mean() return sentiment_daily_mean df['date_score'] = df.apply(sc...
python|pandas
0
363,581
64,631,876
Input 0 of layer max_pooling2d is incompatible with the layer: expected ndim=4, found ndim=5. Full shape received: [None, 4, 10, 8, 32]
<p>When I try to define my model, I get the following error message:</p> <pre><code>Input 0 of layer max_pooling2d is incompatible with the layer: expected ndim=4, found ndim=5. Full shape received: [None, 4, 10, 8, 32]. </code></pre> <p>The code I'm using is:</p> <pre><code>X_train = X_train.reshape(X_train.shape[0]...
<p>Input Layer is either expects data in the format of NHWC or NCHW.</p> <pre><code>N = Number of samples H = Height of the Image W = Width of the Image C = Number of Channels </code></pre> <p>In most cases, N keeps varying so N is given as None. Based on your example, you can provide input shape and to convert between...
python|tensorflow|conv-neural-network
2
363,582
64,937,718
Pandas DataFrame skip rows
<p>I am working on a weather webscraping project, and have scraped a site using selenium and exported it to excel using pandas. However, i can't find out how to make dates only appear in every fourth row, so that dates would fit in with the time. Excel Sheet: <a href="https://i.stack.imgur.com/27w0f.jpg" rel="nofollow ...
<p>Try to create a variable which ensures its the 4th multiple iteration with in loop.</p> <p>Check the below snippet.</p> <pre><code>row = 0 for dates in date: print(dates.text) a.append(dates.text) if row % 4 == 0 else a.append(&quot;&quot;) row = row + 1 df1 = pd.DataFrame(a, columns= [&quot;Date&quot;])...
python|pandas
0
363,583
65,050,473
Taking an outer subtraction between a list of tuples using Numpy
<p><strong>NOTE:</strong> I am not looking for syntax on how to use <code>np.subtract.outer</code>, instead I am trying to solve a very specific issue that I am facing during its application.</p> <p>I have a list of tuples -</p> <pre><code>a = [(0,0), (1,0), (1,1), (2,0), (2,2)] a = np.array(a) </code></pre> <p>I am tr...
<p>No need to use <code>outer</code>. Just use <code>broadcasting</code>:</p> <pre><code>In [5]: a[:,None,:]-a[None,:,:] Out[5]: array([[[ 0, 0], [-1, 0], [-1, -1], [-2, 0], [-2, -2]], [[ 1, 0], [ 0, 0], [ 0, -1], [-1, 0], [-1, -2]], ...
python|numpy|vectorization
3
363,584
64,988,010
Getting the output's grad with respect to the input
<p>I'm currently trying to implement an ODE Solver with Pytorch, my solution requires computing the gradient of each output wtr to its input.</p> <pre><code>y = model(x) for i in range(len(y)): #compute output grad wrt input y[i].backward(retain_graph=True) ydx=x.grad </code></pre> <p>I was wondering if t...
<p>You can use <code>torch.autograd.grad</code> function to obtain gradients directly. One problem is that it requires the output (<code>y</code>) to be scalar. Since your output is an array, you will still need to loop through its values.</p> <p>The call will look something like this.</p> <pre><code>[torch.autograd.gr...
python|pytorch|ode|autograd
1
363,585
64,746,846
Creating new columns with True or False value if they exist in a column in df
<p>I have a column in my <strong>df</strong> that looks like below:</p> <pre><code>Service DoorDash, Grubhub / Seamless, UberEats, Postmates DoorDash, UberEats, Caviar, Tock DoorDash None Caviar, Tock None Tock DoorDash, Grubhub / Seamless, UberEats, Postmates Grubhub / Seamless, UberEats </code></pre> <p>Is there an e...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.get_dummies.html" rel="nofollow noreferrer"><code>Series.str.get_dummies</code></a> with convert to boolean, add missing values by list in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reind...
python|python-3.x|pandas
1
363,586
64,831,266
All eigenvalues are positive , still np.linalg.cholesky is giving error that matrix is not positive definite
<p>My matrix is positive definite still while doing Cholesky decomposition , numpy is giving error as below <a href="https://i.stack.imgur.com/0wfrA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0wfrA.png" alt="enter image description here" /></a></p>
<p>Seems that the small positive eigenvalue 1.33e-10 is getting treated as zero, resulting in the matrix being treated as positive semi-definite, not positive definite. Perhaps you should explore setting tolerances in Numpy's Cholesky routine. Head over to <a href="http://scicomp.stackexchange.com/">scicomp</a> where p...
python|numpy|linear-algebra|eigenvalue
1
363,587
64,638,757
Join rows by specific value in Pandas
<p>I have the following dataframe</p> <pre><code> Name Area 0 Emmeline G 1 Erek L 2 Perrine H 3 Donelle K 4 Nichols E 5 Corinne B 6 Emilia A 7 Dierdre G 8 Hadrian K 9 Tyson B 10 Emmeline D 11 Wynne L 12 Luigi H 13 Martelle J ...
<p>Please try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="noreferrer">groupby</a> and sum.</p> <pre><code>df.groupby(by=&quot;Name&quot;).sum().reset_index() </code></pre>
python|pandas|dataframe|join|pandas-groupby
4
363,588
64,863,071
How to manipulate repeated data values in mulitple columns with python
<p>I have around 50 columns and the rows of the columns are duplicated with similar values. For exmample as:</p> <pre><code>Idx Series Col1 Col2 Col3 Col4 Col5 ..... Col50 0 A 1 1 A 1 2 A 1 3 A 1 4 ...
<p>Since your DataFrame does not contain <em>NaN</em> values, I assume that:</p> <ul> <li>Column <em>Col1</em> thru <em>Col50</em> are of <em>object</em> type,</li> <li>They contain <strong>string</strong> data, either empty string or a string containing a single digit char.</li> </ul> <p>To get your intended result, d...
python|pandas|dataframe|csv|indexing
2
363,589
64,829,186
Pandas union with parent ids in the same dataframe
<p>I have a pandas dataframe that looks like this:</p> <pre><code>id | folder | level0_parent_id | level1_parent_id | level2_parent_id | level3_parent_id 1 A 0 0 0 0 2 B 1 0 0 0 3 ...
<p>One approach with <code>melt</code></p> <pre><code>df['structure'] = df['folder'].map( df.melt(['id', 'folder'], var_name='level') .assign(child=lambda x: x['value'].map(dict(zip(df['id'], df['folder']))) .fillna(x['folder'])) .drop_duplicates(['folder', 'child...
python|pandas
1
363,590
65,023,810
Convert Pandas column with list to string
<p>I am trying to convert pandas dataframe column which has <code>list for each row</code> to <code>string in each row</code> but somehow it not converting. Here is what I have tried from <a href="https://stackoverflow.com/questions/45306988/column-of-lists-convert-list-to-string-as-a-new-column">other answer</a>.</p> ...
<p>I think what you're looking for is:</p> <pre class="lang-py prettyprint-override"><code>data['tags'] = data['Tags'].apply(lambda x: ' '.join(x)) </code></pre> <p>Example</p> <pre class="lang-py prettyprint-override"><code>ser = pd.Series([['python', 'windows', 'pip', 'pygame', 'pycharm'], ['converte...
python|pandas
4
363,591
64,722,253
Combine two date columns together to one in Python
<p>I have a dataframe, df, where I would like to combine a start and end column into one single date column.</p> <pre><code>start end id 10/01/2020 11/01/2020 a </code></pre> <p>Desired output</p> <p>Date id</p> <pre><code>10/01/2020 to 11/01/2020 ...
<pre><code>df['Date']= df.apply(lambda x: x['start'] + ' '+'to'+ ' '+x['end'],1) </code></pre> <p>Or</p> <pre><code>df['Date']=df.groupby(df.index).apply(lambda x:x['start'].str.cat(x['end'], sep=' to ')) start end id Date 0 10/01/2020 11/01/2020 a 10/01/2020 to 11/01/2020 </code></...
python|pandas|numpy
1
363,592
64,851,132
ImportError: cannot import name 'doc' from 'pandas.util._decorators' (C:\ProgramData\Anaconda3\lib\site-packages\pandas\util\_decorators.py)
<p>I am trying to import pycaret but this error holds me back. How do I solve this?</p> <p><a href="https://i.stack.imgur.com/2zuvh.jpg" rel="nofollow noreferrer">ImportError</a></p>
<p>I get this error when importing fbprophet. Actually this error happens when you import any package that contains pandas.</p> <p>I'm trying to downgrade pandas but conda says my packages are in conflict.Probably need to reinstall anaconda to solve this.</p>
python|pandas|anaconda|importerror|pycaret
0
363,593
64,926,421
Fourier transform and Full Width Half Maximum
<p>I'm trying to calculate the Fourier transform of three muon polarization signals, which are simply cosine functions multiplied by an exponential decay. So, doing the Fourier transform, we are going to see broadened peaks centered at the corresponding frequency. The problem is that I have already tried to do the Four...
<p>Currently i work in a python project with same object. I've a set of data of magnetic field B(x,y,z), i think ideal would be to organize your data periodically at event and deduce Fe (sampling_rate).</p> <pre><code>f(A, t)=A*( cos(2*pi*fe*t) - sin(2*pi*fe*t) B=[ 50, 50, 10, 3 ] # where each data is |B| normal at s...
python|numpy|scipy|fft|scipy.stats
0
363,594
64,618,983
How to append a longer list to dataframe
<p>I wanna append a longer list to dataframe .But get an error ValueError: Length of values (4) does not match length of index (3)</p> <pre><code>import pandas as pd df = pd.DataFrame({'Data': ['1', '2', '3']}) df['Data2'] =['1', '2', '3', '4'] print(df) </code></pre> <p>How can I fix it .</p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFrame.reindex</code></a> for add new rows by maximal length by new list or original DataFrame, if length of list should be changed, sometimes same length or sometimes length is sh...
python|pandas
3
363,595
64,939,075
Geopandas - plot points with their IDs
<p>I would like to paint on a map a list of points with the id of each point next to it, this is what I am doing</p> <pre><code>dfPoints[&quot;id&quot;] = dfPoints.index geomertrySensores2 = [Point(xy) for xy in zip(dfPoints['longitud'], dfPoints['latitud'])] crs = {'int':'epsg:4326'} geoSensores = gpd.GeoDataFrame(df...
<p>I managed to fix this using matplotlib:</p> <pre><code>f, ax = pl.subplots(figsize=(120,90)) geoVias.plot(color = 'grey', alpha=0.4, ax = ax) geoSensores.plot(ax=ax, markersize=20, color=&quot;blue&quot;, marker=&quot;o&quot;, column='id') for index, row in geoSensores.iterrows(): x = row.geometry.centroi...
python|pandas|matplotlib|point|geopandas
0
363,596
64,934,496
dynamically create columns in df python
<p>I have a df consisted of 3 columns and 5 rows. I want to create new columns into the df. Although the code has to be dynamic because the columns and the rows can be changable.</p> <pre><code>k=4 for o in range(0,3): for p in range(0,k): df[f'w'{op}]=0 </code></pre> <p>so in this case the columns that I h...
<p>The line <code>df[f'w'{op}]=0</code> seems wrong in the code snippet.</p> <p>It should be written in the way like <code>df[f'w{o}{p}']=0</code>.</p> <p>Try the below code sample and apply in your scenario,</p> <pre><code># Create sample dataframe with shape (10,3) df = pd.DataFrame(np.array(range(30)).reshape(10,3))...
pandas|dataframe|for-loop
0
363,597
64,690,549
How can I resolve this incompatible shape problem in my convolutionnal neural network on MNIST?
<p>I built an image classification model on MNIST (CNN) and the model works very well on the test set. However, I have a dimension error when I upload an image from google, resize it, normalize it and feed it to my model. The input tensor shape for my model is <code>(None,28,28)</code> but it says that my input is <cod...
<p>you would need to reshape the image, using numpy it can easily be done with this</p> <pre><code>import numpy as np image = np.array(image).reshape(1,28,28) </code></pre> <p>The error is probably due to tensorflow expecting many images, so if you provided 100 images the shape of the array would be (100,28,28) but si...
python|tensorflow|mnist
1
363,598
64,637,028
Having Difficulty Merging Dataframes on Pandas
<p>Trying to merge two <code>dataframes</code> of hockey data, both have player names (what I am trying to merge on) mind you the one with salary data only has 500 rows or so and the primary <code>dataframe</code> has 2000+ (if that makes a difference. Trying to merge them on name when applicable and the new df created...
<p>First reset sdf index cause now player name is index not a column:</p> <pre><code>df = pd.merge(hdf, sdf.reset_indx(), on='Player') </code></pre>
python|pandas
0
363,599
64,905,191
I need user input to point from one dataframe to another and display a column from the second dataframe-python
<p>I have 2 pandas dataframes:</p> <ol> <li>state abbreviations and states. <a href="https://i.stack.imgur.com/8sygt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8sygt.png" alt="enter image description here" /></a></li> <li>state names and all the national parks in each state. This is not the whol...
<p>The main issue you are facing is due to your data being unstructured. To fix this, you should have your data organized like this instead, which is in a 'tidy' form <a href="https://www.jeannicholashould.com/tidy-data-in-python.html" rel="nofollow noreferrer">see here</a></p> <pre><code>STATE_DICT = { 'state_name...
python|pandas|dataframe
1