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
373,700
47,104,617
deleting columns in tflearn producing strange output
<p>I am using <code>tflearn</code> and I am using the following code to load my csv file...</p> <p>data, labels = load_csv('/home/eric/Documents/Speed Dating Data.csv', target_column=0, categorical_labels=False)</p> <p>Here is a snippet of my csv file (there are a lot more columns)...</p> ...
<p>What's happening is that the line <code>[data.pop(col_del) for position in data]</code> is deleting half your rows, and then you're displaying the first 20 rows of what's left. (It would delete all the rows, but the call to <code>pop</code> is advancing the loop iterator.)</p> <p>If you don't want certain columns ...
python|csv|tensorflow|tflearn
1
373,701
47,318,119
No module named 'pandas._libs.tslibs.timedeltas' in PyInstaller
<p>I am trying to wrap a Python script into an exe using PyInstaller (development version) for windows. </p> <p>The script uses Pandas and I have been running into an error when running the exe.</p> <pre><code>Traceback (most recent call last): File "site-packages\pandas\__init__.py", line 26, in &lt;module&gt; F...
<p>PyInstaller 3.3, Pandas 0.21.0, Python 3.6.1.</p> <p>I was able to solve this thanks to not-yet published/committed fix to PyInstaller, see <a href="https://github.com/pyinstaller/pyinstaller/issues/2978" rel="nofollow noreferrer">this</a> and <a href="https://github.com/lneuhaus/pyinstaller/blob/017b247064f9bd51a6...
python|windows|python-3.x|pandas|pyinstaller
50
373,702
47,419,943
PyMySQL Warning: (1366, "Incorrect string value: '\\xF0\\x9F\\x98\\x8D t...')
<p>I'm attempting to import data (tweets and other twitter text information) into a database using Pandas and MySQL. I received the following error:</p> <blockquote> <p>166: Warning: (1366, "Incorrect string value: '\xF0\x9F\x92\x9C\xF0\x9F...' for column 'text' at row 3") result = self._query(query)</p> <p...
<p>You need <code>utf8mb4</code>, not <code>utf8</code>, when connecting to MySQL and in the columns involved.</p> <p>More python tips: <a href="http://mysql.rjweb.org/doc.php/charcoll#python" rel="noreferrer">http://mysql.rjweb.org/doc.php/charcoll#python</a> (Except use <code>utf8mb4</code> in place of <code>utf8<...
python|mysql|pandas|utf-8|pymysql
11
373,703
47,267,433
How to generate a new Tensor with different vectors in PyTorch?
<p>I want to generate new a○b vector with <code>a</code> and <code>b</code> (○ means element wise multiply). My code is below, but the performance looks bad because of <code>for</code>. Are there any efficient way?</p> <pre><code>a = torch.rand(batch_size, a_len, hid_dim) b = torch.rand(batch_size, b_len, hid_dim) # a...
<p>From your problem definition, it looks like you want to multiply two tensors, say <code>A</code> and <code>B</code> of shape <code>AxE</code> and <code>BxE</code> and want to get a tensor of shape <code>AxBxE</code>. It means you want to multiply, each row of tensor <code>A</code> with the whole tensor <code>B</code...
python|pytorch
2
373,704
47,293,164
Feed tensorflow or keras neural nets input with custom dimensions
<p> I would like to feed a neural net inputs of following shape: Each training entry is a 2D array with dimensions 700x10. There are in total 204 training entries. Labels is just 1-dimensional array of size 204 (binary output)</p> <p>I tried to just use Dense layers:</p> <pre class="lang-py prettyprint-override"><cod...
<p>The <code>Dense</code> layers works on only one dimension, the last.</p> <p>If you're inputting <code>(700,10)</code> to it, it will output <code>(700,units)</code>. Check your <code>model.summary()</code> to see this. </p> <p>A simple solution is to flatten your data before applying dense:</p> <pre><code>model.a...
tensorflow|neural-network|keras
3
373,705
47,226,351
How to extract value from other dataframe based on key and set to the current dataframe
<p>I have this two columns</p> <pre><code>df1 = pd.DataFrame([['A','h1',None],['B','h2',None],['C','h3',None]],columns=['id','HH','VV']) id HH VV 0 A h1 None 1 B h2 None 2 C h3 None df2 = pd.DataFrame([['A','XX',10],['B','XX',15],['B','YY',15],['A','ZZ',10],['C','GG',28]],columns=['id','NO','VV']) i...
<p>You can remove duplicates by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer"><code>drop_duplicates</code></a> first by column(s) in <code>keys</code>:</p> <pre><code>keys = ['id'] a = df1.assign(VV=df1[keys].join(df2.drop_duplicates(key...
python|pandas
2
373,706
47,379,512
Saving a specific TensorFlow Checkpoint in time
<p><strong>Is it possible to mark checkpoints not to be deleted?</strong></p> <p>A little context:</p> <p>I am creating a reinforcement learning model and I want to save my best model throughout the training. In order to do that, I am keeping the best score and whenever it is updated saving a checkpoint at that momen...
<p>Looking at the issues posted <a href="https://github.com/tensorflow/tensorflow/issues/8658/" rel="nofollow noreferrer">here</a> and <a href="https://github.com/tensorflow/tensorflow/issues/9918/" rel="nofollow noreferrer">here</a>, this appears to be a requested feature which is not yet implemented. You can prevent...
machine-learning|tensorflow|reinforcement-learning
1
373,707
47,111,443
Pandas Cumulative on sign concept
<p>I have a dataframe column like, it has lot of values, some +ve and some -ve</p> <pre><code> V -1 -4 -3 -2 +1 +2 +1 +5 -3 -1 +1 +4 -5 -2 -4 +4 +6 </code></pre> <p>I want to create another column, which has cumulative such that </p> <p>if current position value is not of same sign of previous one then cumulative fo...
<p>Good question :-),I break down the steps </p> <pre><code># restore the value change(positive to negative) in and assign the group number , in the group you will only see all positive or negative. df['g']=df.gt(0).diff().ne(0).cumsum() # find the last value of the group DF=df.groupby('g').last() # shift the value ...
python|pandas
3
373,708
47,394,793
Pandas: Split a dataframe rows and re-arrange column values
<p>I have a <code>DataFrame</code> :</p> <pre><code>import pandas as pd df = pd.DataFrame({'Board': ['A', 'B'], 'Off': ['C', 'D'], 'Stops': ['Q/W/E', 'Z'], 'Pax': [10, 100]}) </code></pre> <p>which looks like:</p> <pre><code> Board Off Pax Stops 0 A C 10 Q/W/E 1 B D 100 Z </code...
<p>I break down the steps </p> <pre><code>df['New']=df[['Board','Stops','Off']].apply(lambda x : '/'.join(x),1) df['New2']=df['New'].str.split('/').apply(lambda x : list(zip(x[:-1],x[1:]))) namedict = {0 : 'Board',1:'Off'} df[['Pax','New2']].set_index('Pax').New2.apply(pd.Series).\ stack().apply(pd.Series).re...
python|pandas|numpy|dataframe
4
373,709
47,229,501
keyword based extraction from text in pandas
<p>I have a dataset having two columns:</p> <pre><code>Index Text 1 *some text* address13/b srs mall, indirapuram,sann-444000 *some text* 2 *some text* 3 *some text* contactus 12J 1st floor, jajan,totl-996633 *some text* 4 .......... 5 ...
<p>Use <code>str.extract</code>:</p> <pre><code>df['location'] = df.Text.str.extract('(?:address|contactus)(.*?\d{6})', expand=False) df.drop('Text', 1) Index location 0 1 13/b srs mall, indirapuram,sann-444000 1 2 NaN 2 3 12...
python|string|pandas
1
373,710
47,226,407
pandas: GroupBy .pipe() vs .apply()
<p>In the example from the <a href="https://pandas.pydata.org/pandas-docs/stable/groupby.html#groupby-pipe" rel="noreferrer">pandas documentation</a> about the new <code>.pipe()</code> method for GroupBy objects, an <code>.apply()</code> method accepting the same lambda would return the same results. </p> <pre><code>I...
<p>What <code>pipe</code> does is to allow you to pass a callable with the expectation that the object that called <code>pipe</code> is the object that gets passed to the callable.</p> <p>With <code>apply</code> we assume that the object that calls <code>apply</code> has subcomponents that will each get passed to the ...
python|python-3.x|pandas|pandas-groupby
66
373,711
47,477,699
pandas how to aggregate sum on a column depending on values in other columns
<p>I am trying to sum values in a column by <code>groupby</code> on values in a second column, but meanwhile also considering values on a 3rd column, the <code>df</code> is like,</p> <pre><code>id memo amount 1 pos 1.0 1 pos 2.0 1 neg 3.0 2 pos 4.0 2 pos 5.0 2 neg ...
<p>Splitting the operation in two steps, you can achieve what you want through</p> <pre><code>df['temp'] = np.where(df.memo == 'pos', df.amount, -df.amount) df['total_amount'] = df.groupby('id').temp.transform(sum) </code></pre>
python|pandas|dataframe|aggregation|pandas-groupby
2
373,712
47,376,222
TensorFlow RNN example from book (word2vec, embeddings, )
<p>Guided by the book with name "Learning TensorFlow. A Guide to Building Deep Learning Systems (Tom Hope, Yehezkel S. Reshe , and Itay Lieder)" I'm trying to implement simple RNN network with word2vec approach.</p> <p>On page 101 (Chapter 6, Text II: Word Vectors, Advanced RNN, and Embedding Visualization) authors gi...
<p>You should add merged value in your run function:</p> <pre><code>summary, _ = sess.run( [merged, train_step], feed_dict = { train_inputs: x_batch, train_labels: y_batch } ) </code></pre> <p>Or delete it if you do not want this information...
python|tensorflow|nonetype|sess.run
0
373,713
47,257,265
Why tensorflow 1.4 does not allow to assign "None" to FLAGS
<p>I just try to transfer to tensorflow 1.4. </p> <p>But I noticed that TF1.4 does not support None value flag.</p> <pre><code>FLAGS = tf.app.flags.FLAGS FLAGS.something = None # ERROR!(in TF1.4) </code></pre> <p>Here is my error.</p> <pre><code>File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/platfor...
<p>As said <a href="https://stackoverflow.com/a/33938519/5330223">here</a>, Tensorflow is trying to make it as close as <code>python-gflags</code>. That's why this module is changed like this.</p> <p>Also look at the commit message </p> <blockquote> <p>Add mark_flag_as_required functions to make the APIs compatible...
tensorflow
0
373,714
47,452,901
Plotting issues with python library lifelines
<p>I try to use pythons lifelines package <a href="https://lifelines.readthedocs.io/en/latest/Quickstart.html" rel="nofollow noreferrer">Package website</a> and <a href="https://github.com/CamDavidsonPilon/lifelines" rel="nofollow noreferrer">Github</a>. After trying to run the example from the website which reads:</p>...
<p>Update matplotlib to >= 2.0! </p> <p>If you look at the <a href="https://github.com/CamDavidsonPilon/lifelines/blame/master/lifelines/plotting.py#L223" rel="nofollow noreferrer">blame view for the line of code that bugs you</a>, you can see it was last changed when CamDavidsonPilon bumped the required matplotlib ve...
python-3.x|pandas|plot|data-science|lifelines
1
373,715
47,389,988
How to control GPU memory size with tf.estimator
<p>I'm trying to control the size of GPU memory allocated for one tensorflow estimator tf.estimator.Estimator. The purpose is to only allocate half to run other tensorflow net on the same GPU. I found for the contrib version but not for the official. Someone knows if it's possible?</p>
<p>When you create an <code>Estimator</code> instance, you can pass in the constructor's <code>config</code> a <a href="https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig" rel="noreferrer"><code>tf.estimator.RunConfig</code></a> instance. The <code>RunConfig</code> has a <code>session_config</code> attri...
tensorflow
8
373,716
47,488,744
how can i create these columns in python
<p>I have a dataset like the one below</p> <pre><code>Date Price 2017-01-01 100 2017-01-02 187 2017-01-03 183 </code></pre> <p>How can I create a column that gets the previous days info like</p> <pre><code>Date Price Previous_Days_Price 2017-01-01 100 NaN 2017-01-02 18...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html" rel="nofollow noreferrer"><code>pandas.Series.shift</code></a> is what you want...</p> <pre><code>df['Price'].shift(1) </code></pre>
python|pandas|dataframe
1
373,717
47,111,218
how to get for multiple columns
<p>I have a data frame like this:</p> <pre><code> Id row Date BuyTime SellPrice App 1 1 2017-10-30 94520 0 9:00:00 1 2 2017-10-30 94538 0 9:00:00 1 3 2017-10-30 94609 0 9:00:00 1 4 2017-10-30 94615 0 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.zfill.html" rel="nofollow noreferrer"><code>str.zfill</code></a> with <code>str[]</code> for select by positions of string and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofol...
python|pandas|data-analysis
1
373,718
47,300,215
merge two pandas data frame and skip common columns of right
<p>I am using pandas DataFrame as a lightweight dataset to maintain some status and need to dynamically/continuously merge new DataFrames into existing table. Say I have two datasets as below: </p> <p>df1:</p> <pre><code> a b 0 0 1 1 2 3 2 4 5 3 6 7 4 8 9 </code></pre> <p>df2:</p> <pre><code> b ...
<p>First identify the columns in <code>df2</code> not in <code>df1</code></p> <pre><code>cols = df2.columns.difference(df1.columns) </code></pre> <p>Then <code>pd.DataFrame.join</code> </p> <pre><code>df1.join(df2[cols]) a b c 0 0 1 11 1 2 3 13 2 4 5 15 3 6 7 17 4 8 9 19 </code></pre> <p>Or <...
python|pandas
6
373,719
47,260,809
In place insertion into list (or array)
<p>I'm running a script in Python, where I need to insert new numbers into an array (or list) at certain index locations. The problem is that obviously as I insert new numbers, the index locations are invalidated. Is there a clever way to insert the new values at the index locations all at once? Or is the only solutio...
<p>Insert those values in backwards order. Like so:</p> <pre><code>original_list = [0, 1, 2, 3, 4, 5, 6, 7] insertion_indices = [1, 4, 5] new_numbers = [8, 9, 10] new = zip(insertion_indices, new_numbers) new.sort(reverse=True) for i, x in new: original_list.insert(i, x) </code></pre> <hr> <p>The reason this w...
python|arrays|numpy|indexing|list-comprehension
8
373,720
47,135,539
If/Elseif Condition on a Dataframe combined with multiple actions
<p>I have a dataframe object column which looks like 104.5 and always has a suffix like K, B or M standing for Kilo, Billions or Millions. For instance 104.5B.</p> <p>What I would like to do is to check for the suffix and multiple the value by 10^3, 10^6 or 10^9 'inplace'. </p> <p>I found some explanations for labeli...
<p>You can use a dictionary and a map, like so:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Values': ['104.5B', '102.4K', '951M']}) multipliers = {'B': 1, 'K': 1000, 'M': 1000000} df['Values'] = df['Values'].str[:-1].astype(float) * df['Values'].str[-1].map(multipliers) pr...
python|pandas|numpy|if-statement
3
373,721
47,464,747
Too many indices for array numpy/python
<p>So I am trying to upload the file <a href="http://www.ice.csic.es/personal/aldos/Solar_Data_files/nudistr_b16_agss09.dat" rel="nofollow noreferrer">http://www.ice.csic.es/personal/aldos/Solar_Data_files/nudistr_b16_agss09.dat</a><br> into my code. </p> <pre><code>data= np.genfromtxt('nudistr_b16_agss09.csv',delimi...
<p>It looks like your data file uses newlines (not commas) as delimiters. Try removing the delimiter argument:</p> <pre><code>data= np.genfromtxt('nudistr_b16_agss09.dat',skip_header=21) </code></pre>
python|arrays|numpy|indices
1
373,722
47,432,905
AttributeError on variable input of custom loss function in PyTorch
<p>I've made a custom loss function to compute cross-entropy (CE) for a multi-output multi-label problem. Within the class, I want to set the target variable I'm feeding to not require a gradient. I do this within the forward function using a pre-defined function (taken from pytorch source code) outside the class.</p> ...
<p>The problem is in "target.float()" line which converts your t Variable to Tensor. You can directly use target without any problems in your CE calculation.</p> <p>Also, I guess you do not really need "self.save_for_backward(ce_out)" as I guess you are defining nn.Module class which will take care of the backward pas...
python|pytorch
0
373,723
47,357,870
Get all coordinates points within known boundaries in a numpy matrix for each dot
<p>Given the following numpy matrix</p> <pre><code>import numpy as np np_matrix = np.array( [[0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,3,0,2,0,0,1,0,0,0,0,0,0] ,[0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,3,0,2,2,0,0,0,0,0,0,0,0] ,[0,0,0,3,0,0,0,0,2,2,2,0,0,0,0,0,3,0,0,0,3,0,0,2,2,2,2,2,2,2,2,2] ,[0,0,0,3,0,0,0,2,0,0,0,2...
<p><strong>Question 1 Solution using a recursive floodfill algorithm:</strong></p> <p><em>See the floodfill algorithm in this <a href="http://joeiddon.github.io/paint/floodfill" rel="nofollow noreferrer">JavaScript demonstration</a> I made. <a href="https://joeiddon.github.io/paint" rel="nofollow noreferrer">GitHub So...
python|arrays|numpy|flood-fill
4
373,724
47,477,744
Create variable with multiple return of numpy where
<p>Hi i am stata user and now iam trying to pass my codes in stata to python/pandas. In this case i want to create a new variables <code>size</code> that assign the value 1 if the number of jobs is between 1 and 9, the value 2 if jobs is between 10 and 49, 3 between 50 and 199 and 4 for bigger than 200 jobs.</p> <p>An...
<p>What you are trying to do is called binning use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow noreferrer"><code>pd.cut</code></a> i.e </p> <pre><code>df['new'] = pd.cut(df['jobs'],bins=[1,10,50,201,np.inf],labels=['micro','small','medium','big']) </code></pre> <p>Ou...
python|python-3.x|pandas|numpy
2
373,725
47,164,230
correct column containing list of single element in pandas dataframe
<p>I have the foll. dataframe:</p> <pre><code> a_name Season yl yl 4.939 cherka 2000.0 [4.939] 4.441 cherka 2001.0 [4.441] 4.320 cherka 2002.0 [4.32] 3.718 cherka 2003.0 [3.718] 4.533 cherka 2004.0 [4.533] </code></pre> <p>How do I convert it to:</p> <pre><code> a_name Season yl yl ...
<p>By using numpy:</p> <p><code>df["y1"] = np.vstack(df["y1"])</code></p>
python|pandas
1
373,726
47,451,126
Tensorflow- How to display accuracy rate for a linear regression model
<p>I have a linear regression model that seems to work. I first load the <code>data</code> into <code>X</code> and the target column into <code>Y</code>, after that I implement the following...</p> <pre><code>X_train, X_test, Y_train, Y_test = train_test_split( X_data, Y_data, test_size=0.2 ) rng = np.r...
<p>Turns out, since this is a multi-class Linear Regression problem, and not a classification problem, that <code>tf.metrics.accuracy</code> is not the right approach. </p> <p>Instead of displaying the accuracy of my model in terms of percentage, I instead focused on reducing the Mean Square Error (MSE) instead.</p> ...
python-3.x|machine-learning|tensorflow|linear-regression
5
373,727
47,539,511
how to get range of index of pandas dataframe
<p>What is the most efficient way to get the range of indices for which the corresponding column content satisfy a condition .. like rows starting with tag and ending with "body" tag.</p> <p>for e.g the data frame looks like this</p> <p><a href="https://i.stack.imgur.com/gFnSp.png" rel="nofollow noreferrer"><img sr...
<p>What condition are you looking to satisfy?</p> <pre><code>import pandas as pd df=pd.DataFrame([['This is also a interesting topic',2],['&lt;body&gt; the valley of flowers ...',1],['found in the hilly terrain',5], ['we must preserve it &lt;/body&gt;',6]],columns=['description','count']) print(df) print...
python|pandas
1
373,728
47,447,033
Merging 2 data frames without changing associated values
<p>I currently have 2 datasets 1 = Drugs prescribed per hospital 2 = Crimes committed</p> <p>I have been able to assign the located hospital ID to the various crimes so therefore I can identify which hospital is closer.</p> <p>What I really would like to do is to assign the amount of drugs prescribed using the count_...
<p>If the columns you are merging on share the same name, you don't need on parameter. Since you need column added to crime, we can use parameter how = left</p> <pre><code>Crimes = Crimes.merge(Hosp[['Hosp No', 'Total Quantity']], how = 'left') ID Type Hosp No Total Quantity 0 0 Anti-Social 222 10...
python|python-2.7|pandas|merge|jupyter-notebook
0
373,729
47,397,419
correct apply of pandas.apply with lambda
<p>i would like the column 'extrema' of my DataFrame beeing 'max2015' if 'max215' is bigger than 'max' or smaller than min2015 if 'min2015' is smaller than 'min'</p> <p>i think it's the most elegant way to solve this with an df.apply - lambda combination but i can't get a correct solution with this.</p> <p>Code:</p> ...
<p>Maybe you are looking for <code>np.select</code> i.e </p> <pre><code>Import numpy as np df = x.copy() df['extrema'] = np.select([df['max2015']&gt;df['max'],df['min2015']&gt;df['min']],[df['max2015'],df['min2015']],np.nan) </code></pre>
pandas|dataframe
1
373,730
47,216,716
Adding one dictionary to another based on values (python 3)
<pre><code>import pandas as pd yod_user = pd.read_excel("C:\\Users\\Desktop\\yod_user.xlsx") yod_bank = pd.read_excel("C:\\Users\\Desktop\\yod_bank.xlsx") #converting DataFrames into dictionary userd = yod_user.to_dict() bankd = yod_bank.to_dict() #Definitions userd = [{"id":2, "username":"pk@gmail.in","password...
<p><strong>Setup</strong></p> <pre><code>df1 # yod_user id password username 0 2 YkxJNWNDT pk@gmail.in 1 4 VjNUYWh test@gmail.com 2 6 dddd zz113@gmail.com 3 8 ssss faulmike@aol.com 4 10 errfs newr10@gmail.com df2 # yod_bank acc_number bank_name bankid u...
python|pandas|dictionary
1
373,731
47,340,860
Evaluation of Regression Neural Network
<p>Hej,</p> <p>I am trying to write a small program to solve a Regression problem. My dataset is hereby 4 random x (x1,x2,x3 and x4) and 1 y value. One of the rows looks like this:</p> <pre><code>0.634585 0.552366 0.873447 0.196890 8.75 </code></pre> <p>I know want to predict the y-value as close as poss...
<p>This is because the <strong>Relu</strong> activation function causes the exploding gradient. Therefore, you need to reduce the learning rate accordingly. Moreover, you can try a different activation function also (for this you may have to normalize your dataset first)</p> <p>Here, (<a href="https://stackoverflow.co...
python|tensorflow|neural-network|regression
1
373,732
47,089,749
One end clamped and other end free cubic spline using scipy.interpolate.splprep and splev
<p>I have the following data:</p> <pre><code>x_old = [ 0.00000000e+00, -5.96880765e-24, -8.04361605e-23, -2.11167774e-22, -2.30386081e-22, -7.86854147e-23, 1.17548440e-22, 1.93009272e-22, 1.49906866e-22, 9.66877465e-23, 1.48495705e-23] y_old = [ 0. , 0.03711505, 0.03780602, 0.0252445...
<p>It seems you want an interpolating spline, which means the smoothing parameter s should be set to 0. </p> <pre><code>tckp, u = splprep([x_old,y_old,z_old], s=0.0, k=3, nest=-1) </code></pre> <p>A clamped spline (or a spline with other boundary conditions) can be made with <a href="https://docs.scipy.org/doc/scipy/...
python|numpy|scipy|interpolation
1
373,733
11,387,975
What kind of noise is this?
<p>What kind of noise does <code>numpy.random.random((NX,NY))</code> create? White noise? If it makes a difference, I sometimes instead make 3D or 1D noise (argument is <code>(NX,NY,NZ)</code> or <code>(N,)</code>).</p>
<pre><code>&gt;&gt;&gt; help(numpy.random.random) Help on built-in function random_sample: random_sample(...) random_sample(size=None) Return random floats in the half-open interval [0.0, 1.0). Results are from the "continuous uniform" distribution over the stated interval. To sample :math:`Unif[a, ...
python|random|numpy|noise
7
373,734
11,331,854
How can I generate an arc in numpy?
<p>If I know the center(x,y,z) of the arc and the diameter, and the starting and ending point, how can I generate the values between the start and the end? </p>
<p>It sounds like your "arc" is an circular approximation to a curve between two known points. I guessing this from the word "diameter" (which is twice the radius) in your post. To do this you <a href="http://en.wikipedia.org/wiki/Circle" rel="noreferrer">parameterize the circle</a> <code>(t) -&gt; (x,y)</code> where <...
python|math|numpy
11
373,735
68,179,640
Computing gradient in Tensorflow vs PyTorch
<p>I am trying to compute the gradient for a loss of a simple linear model. However, I face the problem that while using TensorFlow the gradient is computed as 'none'. Why is this happening and how to compute the gradient using TensorFlow?</p> <pre><code>import numpy as np import tensorflow as tf inputs = np.array([[7...
<p>Your code doesn't work because in tensorflow, gradients are only computed for <code>tf.Variable</code>s. When you create a layer, TF automatically marks its weights and biases as a variable (unless you specify <code>trainable=False</code>).</p> <p>So, in order to make your code work, all you need to do is wrap your ...
python|tensorflow|pytorch|gradient
1
373,736
68,098,536
Pandas new col with indexes of rows sharing a code in another col
<p>Let say I've a DataFrame indexed on unique Code. Each entry may herit from another (unique) entry: the parent's Code is given in col Herit.</p> <p>I need a new column giving the list of children for every entries. I can obtain it providing the Code, but I don't succeed in setting up the whole column.</p> <p>Here is ...
<p>You can group by the <code>Herit</code> column and then reduce the corresponding <code>Code</code>s into lists:</p> <pre><code>&gt;&gt;&gt; herits = df.groupby(&quot;Herit&quot;).Code.agg(list) &gt;&gt;&gt; herits Herit [a, b, c] a [aa, ab] b [ba] </code></pre> <p>Then you can <code>map</code> the ...
python|pandas
1
373,737
68,289,120
Custom loss function in TensorFlow 2: dealing with None in batch dimension
<p>I'm training a model which inputs and outputs images with same shape <code>(H, W, C)</code> in RGB color space.<br/><br/> My loss function is MSE over these images, but in another color space.<br/> The color space conversion is defined by <code>transform_space</code> function, which takes and returns <strong>one ima...
<p>Batching is basically hard coded into TF's design. It's the best way to take advantage of GPU resources to run deep learning models fast. Looping is strongly discouraged in TF for the same reason - the whole point of using TF is vectorization: running many computations in parallel.</p> <p>It's possible to break thes...
python|tensorflow|keras
1
373,738
68,112,869
Count the values that are repeated, even those that are absent
<p>I have a database which contains in index, the date in first column the name of a company and in second column the method it uses.</p> <pre><code>test = pd.DataFrame({&quot;name_normalized&quot; : [&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;C&quot;,&quot;C&quot;], ...
<p>From where you left off, you can <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.unstack.html" rel="nofollow noreferrer"><code>unstack</code></a> with <code>fill_value=0</code> for the missing repetitions:</p> <pre><code>&gt;&gt;&gt; test.groupby([&quot;name_normalized&quot;, &quot;method&quot;])...
python|pandas
1
373,739
68,418,121
Mapping Output Tensor of Residual/Convolutional Block to Fully Connected Layer without Flattening Keras
<p>i am implementing a Deep Learning model to learn to classify between 10,000 classes.</p> <p>The architecture is the model is it takes (100, 100, 4) image into a 4 block residual network which outputs a (100, 100, 64) tensor. this has a output layer of dimension of (10000, ).</p> <p>is there any way to map (100, 100,...
<p>the solution is really simple, i was able to get a reply from the authors for the paper itself. i was going to delete this question but realized that someone might need this( i have wasted months on this problem). so i am posting it here.</p> <p>in keras you can directly map a 3D tensor such as (100, 100, 64) to a d...
tensorflow|machine-learning|keras|deep-learning|tensor
0
373,740
68,222,506
Downsample from 1second to 1minute is creating new rows using resample pandas
<p>I am new to python programming. I have a timeseries dateset in seconds which starts at 9.15am and ends at 3.30pm each day. I am trying to downsample it to 1 min timeframe.</p> <p>Example of original data set:</p> <pre><code> Px_NIFTY 20140130 0.0 FF Px_NIFTY 20140130 4500.0 CE \ Time ...
<p>Could you check if the following works for you:</p> <pre><code>df = (df.groupby(df.index.date).resample('T', label='right').last() .reset_index(level=0, drop=True)) </code></pre> <p>Grouping over days (<code>.date</code>) restricts the <code>resample</code> to the &quot;local&quot; range of the group, a day....
python|pandas|time-series|resampling|downsampling
0
373,741
68,137,733
nested operations on two numpy arrays, one 2d and one 1d
<p>Say I have one 2d numpy array X with shape (3,3) and one numpy array Y with shape (3,) where</p> <pre><code> X = np.array([[0,1,2], [3,4,5], [1,9,2]]) Y = np.array([[1,0,1]]) </code></pre> <p>How can I create a numpy array, Z for example, from multiplying X,Y element-wise a...
<p>You can do the following:</p> <pre class="lang-py prettyprint-override"><code>sum_row = np.sum(X*Y, axis=1) # axis=0 for columnwise </code></pre>
python|numpy|numpy-ndarray
2
373,742
68,441,502
How to find difference in months between 2 columns and save it in a new column?
<p>I have a big data frame (the fragment is below):</p> <pre><code> start_date finish_date 2842 2019-02-16 19:35:55.125766+00:00 2019-06-23 08:10:42.867492+00:00 2844 2019-05-29 18:03:54.230822+00:00 2019-06-05 08:06:37.896891+00:00 2846 2019-03-26 10:...
<p>Since both dates are of dtype datetime you can calculate the difference between months by using <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.month.html" rel="nofollow noreferrer"><code>Series.dt.month</code></a> attribute:</p> <pre><code>df['length']=(df['finish_date'].dt.month-df['start_da...
python|pandas
2
373,743
68,266,213
Split values of a python dataframe into multiple rows
<p>I want to split the values of the columns &quot;words&quot; and &quot;frequency&quot; into multiple rows of the dataframe <code>df</code>.</p> <p><strong>[1]: Problem</strong> <a href="https://i.stack.imgur.com/7i1p6.png" rel="nofollow noreferrer">https://i.stack.imgur.com/7i1p6.png</a></p> <p>I use the following pi...
<p>you were close! The problem might be in the reset of indices... For a csv file looking like:</p> <pre><code>&quot;document&quot;,&quot;words&quot;,&quot;frequency&quot; &quot;document 1&quot;,&quot;(cat,dog,bird)&quot;,&quot;(12,34,354)&quot; &quot;document 2&quot;,&quot;(berlin,new_york,paris)&quot;,&quot;(1,13,25...
python|pandas|dataframe
0
373,744
68,319,391
Validation phonenumbers column python pandas with phonenumbers library
<p>I want to check multiple phone numbers from my dataframe with phonenumbers library <a href="https://pypi.org/project/phonenumbers/" rel="nofollow noreferrer">https://pypi.org/project/phonenumbers/</a></p> <p>I want to validate the phone numbers and eventually i want to know from which country the number is. So for e...
<p>The specific issue causing this error is a misplaced parantheses after <code>axis</code> instead of before:</p> <pre> df['phone_number_clean'] = df.apply(lambda x: phonenumbers.is_valid_number(phonenumbers.is_valid_number(str(x.phoneNumber), str(x.<b>phone</b>Country))<b>)</b>, axis='columns') </pre> <p>I think belo...
python|pandas|libphonenumber
0
373,745
68,034,235
pandas products analysis getting pairs according to purchases
<p>Here's an example of my dataframe:</p> <pre><code>df.head(10) , customer_id order_id, product, purchased_at 0, 2, 2000, B, 2021-05-01 21:51:13 1, 1, 1996, A, 2021-04-06 13:02:37 2, 1, 2540, B, 2021-05-0...
<pre><code>result= pd.DataFrame() df.purchase_at = pd.to_datetime(df.purchase_at) df = df.sort_values(by='purchase_at') unique_customers = df.customer_id.unique() result = pd.DataFrame() for customer in unique_customers: temp = df[df.customer_id == customer].copy() if len(temp) &gt; 1: temp['previous_sa...
python|pandas|numpy|data-science
0
373,746
68,399,917
I want to vlookup dataframe.If value is present in another df ,keep same value,otherwise put #N/A in pandas python
<pre><code>import pandas as pd data = {'Car':['Jeep', 'Maruti Suzuki', 'Audi','Kia'], 'order':[10,15,2,5]} # Create DataFrame df = pd.DataFrame(data) </code></pre> <pre><code>print (df) output: Car order 0 Jeep 10 1 Maruti Suzuki 15 2 Audi 2 3 K...
<p>Use <code>merge</code> with <code>indicator</code> parameter:</p> <pre><code>out = pd.merge(df, df2['Car'], on='Car', how='left', indicator=True) out['Available'] = np.where(out['_merge'] == 'both', out['Car'], '#N/A') # out = out.drop(columns='_merge') </code></pre> <pre><code>&gt;&gt;&gt; out[['Car', 'Available', ...
python|pandas|dataframe|numpy|merge
0
373,747
68,414,014
Faster way than nested for loops for custom conditions on multiple columns in two DataFrames
<p>I have two Dataframes as below:</p> <pre><code>df1 +------------+-------------------+-------------+ | Name | Topic | Date | +------------+-------------------+-------------+ | ABC | Data Science | 2020-01-01 | | DEF | Machine Learning | 2021-03-06 | | ABC | Cyber...
<p>try those steps:</p> <pre><code># drop dup rows in df1 df1 = df1.drop_duplicates() # merge df2 with df1 on name df2 = df2.merge(df1, how='inner', left_on='Name', right_on='Name') future_date = df2['Date'] + relativedelta(months=6) # now select based on requirement df2 = df2[(df2['Date'] &gt; df2['Created Date']) &am...
python|pandas|dataframe
2
373,748
68,347,571
Convert numpy array with NaN values to 1e-9 values, (trouble with coherency matrix conversion)
<p>I am currently processing RADARSAT2 images to visualise targets on the images. I am doing this through using detection algorithms, each output of which is a numpy array.</p> <p>These numpy arrays output with a lot of NaN values that I want to change into 1e-9 values. The reason is because I need to change a singular...
<p>Alright so I figured it out.</p> <pre><code>C11[np.isnan(C11)] = 1e-9 C12[np.isnan(C12)] = 0 C13[np.isnan(C13)] = 0 C22[np.isnan(C22)] = 1e-9 C23[np.isnan(C23)] = 0 C33[np.isnan(C33)] = 1e-9 </code></pre> <p>This code assumed that my C11, C22 and C33 arrays had NaN values in them. They did not. Therefore I was...
python|arrays|numpy|matrix|nan
0
373,749
68,430,065
Generate random tuple combination based on their score in Python
<p>I am trying to create a python program, I have 4 list of tuples, I would like to create different 'words', each letter having it's own probability to appear, I would also like the words to be unique.</p> <p>I first tried creating by assigning probability to each letter, which worked using <code>numpy.random.choice()...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>import random liste1 = [ (&quot;A&quot;, 1), (&quot;E&quot;, 1), (&quot;I&quot;, 1), (&quot;O&quot;, 1), (&quot;U&quot;, 1), (&quot;M&quot;, 2), (&quot;N&quot;, 2), (&quot;B&quot;, 2), (&quot;Y&quot;, 2), (&quot;R&quot;...
python|list|numpy|random|tuples
2
373,750
68,394,088
How to train tensorflow.keras models in parallel using gpu? Tensorflow version 2.5.0
<p>I have the following code running a custom model that I have in a different module and takes as input several parameters (learning rate, convolution kernel size, etc)</p> <p><code>custom_model</code> is a function that compiles a <code>tensorflow.keras.models.Model</code> in tensorflow and return the model.</p> <ul>...
<p>I found that this solution works fine for me. This enables to run parallel model training in the gpus using MPI with mpi4py. There is only one issue with this when I try to load big files and run many process together so that the number of processes times the data that I load exceeds my ram capacity.</p> <pre class=...
tensorflow|keras|mpi|hdf5|mpi4py
2
373,751
68,319,759
Find beginning and end of the steepest slope
<p>I have to find start and endpoint of steepest slope in dataset. Dataset shows temperature changes during experiment. Cooling down start about <strong>420 frame</strong> and ends around 500 frame. Could someone help me how I can calculate this points?</p> <pre class="lang-py prettyprint-override"><code>y = [308.09262...
<p>When I hear slope I think of derivative so I want a function having one. I get one by using a spline interpolation. If you're not familiar with splines they are basically polynomials stitched together to make a smooth function.</p> <pre><code>from scipy.interpolate import UnivariateSpline x = np.arange(len(y)) f = U...
python|numpy|dataset
1
373,752
68,365,506
Pandas apply formula to each row and find minimum
<p>I'm looking for an efficient way to apply a formula using variables from a single row of one dataframe (df1) against every row in another datframe (df2), then find the minimum value of this operation and store the row from df2 in which this minimum value occured as a new dataframe (df3). example input/output is give...
<p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow noreferrer"><code>scipy.spatial.distance.cdist</code></a> can be used for this with its default Euclidean distance metric:</p> <pre><code>from scipy.spatial.distance import cdist df3 = df2.iloc[cdist(df1, ...
python|pandas|dataframe|function
1
373,753
68,401,257
Resample and aggregate data according to another column value
<p>My time series is something like this:</p> <pre><code>TranID,Time,Price,Volume,SaleOrderVolume,BuyOrderVolume,Type,SaleOrderID,SaleOrderPrice,BuyOrderID,BuyOrderPrice 1,09:25:00,137.69,200,200,453,B,182023,137.69,241939,137.69 2,09:25:00,137.69,253,300,453,S,184857,137.69,241939,137.69 3,09:25:00,137.69,47,300,200,B...
<p>One way is to create the columns Volume_B (and _S) before with <code>np.where</code> like you did, then aggregate, so:</p> <pre><code>res = ( df.assign(Volume_B= lambda x: np.where(x['Type']=='B', x['Volume'], 0), Volume_S= lambda x: np.where(x['Type']=='S', x['Volume'], 0))\ .groupby(df['Ti...
python|pandas|aggregation
2
373,754
68,376,731
How to read picke files using pyarrow
<p>I have a bunch of code for reading multiple <code>pickle</code> files using <em><strong>Pandas</strong></em>:</p> <pre><code>dfs = [] for filename in glob.glob(os.path.join(path,&quot;../data/simulated-data-raw/&quot;, &quot;*.pkl&quot;)): with open(filename, 'rb') as f: temp = pd.read_pickle...
<p>FYI, <code>pyarrow.read_serialized</code> is deprecated and you should just use arrow <code>ipc</code> or python standard <code>pickle</code> module when willing to serialize data.</p> <p>Anyway I'm not sure what you are trying to achieve, saving objects with Pickle will try to deserialize them with the same exact t...
python|pandas|pickle|apache-arrow
2
373,755
68,372,197
Pandas GUI like tool for Web Applications for making charts from Python Data frame without coding
<p>I am looking for a GUI tool that can be deployed through a web application to end users. Users should be able to create charts from the given Pandas Data frame as per their requirements using point and click methods without coding.</p> <p>I came across <a href="https://pypi.org/project/pandasgui" rel="nofollow noref...
<p>I know this is 2 months old question but anyways. I was also looking for something similar and I found this great library: <a href="https://pypi.org/project/dtale/" rel="nofollow noreferrer">dtale</a>. This can be used from a jupyter notebook as well as you can run it via flask application like this (Credits to @Mic...
python|pandas|web-deployment|pandasgui
1
373,756
68,111,941
How to assign numeric values to multile strings in a dataframe column using python?
<p>I am trying to train my model with a data frame containing company_name (Categorical feature) and some values in int (that i want to predict).</p> <p>Since there are multiple different values in the column 'company_name' how can I convert them to numeric type? (It is easier to convert them to int/float when there ar...
<p>You can use Category Codes <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html" rel="nofollow noreferrer">here</a> -</p> <pre><code>import pandas as pd import numpy as np # creating initial dataframe bridge_types = ('Arch','Beam','Truss','Cantilever','Tied Arch','Suspension','Cable') ...
python|pandas
0
373,757
68,437,901
Pandas Dataframe.apply return Dataframe instead of Series
<p>Code snippet</p> <pre><code>def func(a_val, b_val): ... return new_df mydf = mydf.append(existing_df.apply(lambda x: func(x['A'], x['B']), axis=1), ignore_index=True) </code></pre> <p>As per the code snippet shows, I am trying to use apply to iterate over each row in existing_df and return a new_df that nee...
<p><strong>UPDATE (no apply but iterrows)</strong></p> <p><strong>Reason:</strong> I found similar question (<a href="https://stackoverflow.com/a/45946771/7035448">https://stackoverflow.com/a/45946771/7035448</a>) requiring multiple rows per apply and found this as working and somehow accepted answer which uses pd.appl...
python|pandas
0
373,758
68,181,227
Pytorch Dataset for video
<p>Hi I made a video frames loader Dataset to be fed into a pytorch model. I want to sample frames from a video, but the frames should be uniformly sampled from each video. This is the class I came up with. I was wondering if there was any better method to speed up the sampling process.<br /> Do you have any suggestion...
<p>If you are happy with extracting the frames of each video to disk beforehand, this library is exactly what you're looking for: Video-Dataset-Loading-PyTorch on Github <a href="https://github.com/RaivoKoot/Video-Dataset-Loading-Pytorch" rel="nofollow noreferrer">https://github.com/RaivoKoot/Video-Dataset-Loading-Pyto...
pytorch|conv-neural-network|dataloader|pytorch-dataloader
0
373,759
68,094,922
PyTorch throws OSError on Detectron2LayoutModel()
<p>I've been trying to read pdf pages as an image, for extraction purposes.</p> <p>I found that layoutparser serves this purpose by identifying blocks of text. However, when I try to <code>Create a Detectron2-based Layout Detection Model</code>, I encounter the following error:</p> <p>codeblock:</p> <pre><code>model = ...
<p>The <code>config.yaml</code> basically only has configurations for the model as well as a URL for downloading the model weights. I'm not sure why it isn't automatically downloading for you, but you can also download them from the model zoo page: <a href="https://layout-parser.readthedocs.io/en/latest/notes/modelzoo....
python|python-3.x|opencv|deep-learning|pytorch
1
373,760
68,139,675
Parsing Complicated JSON in Python
<p>I have a code:</p> <pre><code>import requests import pandas as pd import json headers = {&quot;Accept&quot;: &quot;application/json&quot;, &quot;Authorization&quot;:&quot;bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6ImIzNzkwODExLWIxM2QtNDYxZS04MWE0LWFmOTI3YjRjNDQxNiIsImlzcyI6IkNlcnRpZnkiLCJh...
<p>Try this to completely flatten the dictionary:</p> <pre class="lang-py prettyprint-override"><code>import requests headers = { &quot;Accept&quot;: &quot;application/json&quot;, &quot;Authorization&quot;: &quot;bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6ImIzNzkwODExLWIxM2QtNDYxZS04MWE0LW...
python|json|pandas|dataframe|dictionary
0
373,761
68,395,901
Pandas select row based on user input of column names and values
<p>I have a dataframe with many columns. I would like to select the row based on user input for the four variables below</p> <ul> <li>column 1 selected (user can select any column),</li> <li>value 1 selected (user can select any value in column 1),</li> <li>column 2 selected (user can select any column),</li> <li>val...
<p>maybe try this,</p> <pre><code># given col1, val1, col2, val2 result_rows = df[(df[col1] == val1) &amp; (df[col2] == val2)] </code></pre> <p>you can take a look at how to select data in pandas: <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html" rel="nofollow noreferrer">https://pandas.py...
pandas|dataframe|user-input
0
373,762
68,320,552
Concatenate two arrays into a new array
<p>I have two arrays,</p> <pre><code>A = np.array([[1,2,3],[4,5,6]]) b = np.array([100,101]) </code></pre> <p>I want to concatenate them so that <code>b</code> is added a column on the right-hand side so we have a new array <code>A | b</code> that would be something like:</p> <p>1 2 3 100</p> <p>4 5 6 101</p> <p>I a...
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.column_stack.html" rel="nofollow noreferrer"><code>column_stack</code></a>:</p> <pre><code>&gt;&gt;&gt; np.column_stack((A, b)) array([[ 1, 2, 3, 100], [ 4, 5, 6, 101]]) </code></pre> <p>which takes care of <code>b</code> n...
python|arrays|numpy|concatenation
2
373,763
68,382,961
Panda dataframe conversion of series of 03Mar2020 date format to 2020-03-03
<p>I'm not able to convert input</p> <pre><code>Dates = {'dates': ['05Sep2009','13Sep2011','21Sep2010']} </code></pre> <p>to desired output</p> <pre><code>Dates = {'dates': [2019-09-02,2019-09-13,2019-09-21]} </code></pre> <p>using Pandas Dataframe.</p> <pre><code>data = {'dates': ['05Sep2009','13Sep2011','21Sep2010']}...
<p>Currently the months are abbreviated and are not numeric, so you can't use <code>%m</code>. To convert abbreviated months and get the expected output use <code>%b</code>, like this:</p> <pre><code>df['dates'] = pd.to_datetime(df['dates'], format='%d%b%Y') </code></pre> <p><strong>Update:</strong> to convert the Data...
python|pandas|dataframe
1
373,764
68,189,696
Is there an easy way to collapse multiple rows with the same unique identifier into one row using numpy/ pandas?
<p>I have a dataframe for loans, which looks like this:</p> <p><a href="https://i.stack.imgur.com/hMkNE.png" rel="nofollow noreferrer">Loan Dataframe</a></p> <p>My goal is to have only one row per loan ID, instead of multiple rows. I want to have separate columns for the age of co-borrowers and main borrower. I know th...
<p>I think <code>pivot</code> is likely what you're looking for.</p> <pre class="lang-py prettyprint-override"><code>df.pivot(index='Loan ID', columns='Borrower', values='Age') </code></pre>
python|pandas|dataframe|numpy
0
373,765
68,327,021
Keras monitor on val_recall reports not improve although it is improving
<p>Monitoring Keras metric of val_reall. It has been improving but it keeps the best value as the lowest 0.9958 although better values 0.9978 or 0.9985 have been recorded. The monitor mode is set to 'auto'.</p> <p>Please help understand why the Keras thinks the metric is not improving.</p> <pre><code>Epoch 1/10 6883/68...
<p>From Comments:</p> <blockquote> <p>Setting <code>mode=max</code> in the Callbacks has resolved the issue.</p> </blockquote>
tensorflow|keras
0
373,766
68,079,567
Remove/sum duplicate row with pandas
<p>I have this dataframe, How can i make condition that if i have a duplicate row if that they are exactly the same(Mercedes exp) I keep only one (without making the sum) Or make the sum (kia case) if there is a diffrence in rent/sale value</p> <p><strong>Df example</strong></p> <pre><code> cars rent sale Kia ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer"><code>DataFrame.drop_duplicates</code></a> before aggregate <code>sum</code> - this looking for duplciates together in all columns:</p> <pre><code>df1 = df.drop_duplicates().groupby...
python|pandas|dataframe
2
373,767
68,195,550
Saving an image as a numpy array in a file and loading it back from the file as an image using Python
<p>I am trying to convert an image to a numpy array and save it as a text/csv file. I am then trying to load the contents of the text/csv file back into an image.</p> <p>In the whole process, the dimension, datatype pixel values must not change in order to reconstruct the original image accurately (without distortions)...
<p><em>These don't look to be the same and I fail to understand what is going wrong.</em></p> <p>For representing color image <code>OpenCV</code> uses three-dimensional array. To access single value you have to provide 3: Y-cordinate, X-cordinate, which color channel (<code>0</code> for <em>Blue</em>, <code>1</code> fo...
python|image-processing|numpy-ndarray|save-image|loadimage
1
373,768
68,331,174
Applying abbreviation to the column of a dataframe based on another column of the same dataframe
<p>I have two columns in the dataframe, one of which is a class and another is a description. In the description I have some abbreviations. I want to expand these abbreviations based on the class value. I have a dictionary with class as key and in the value I have another dictionary with abbreviations and its full form...
<p>Input data:</p> <pre><code>abb = {'IT':{'SQL':'Structured Query Language', 'BLAH': 'blah blah'}, 'Sales':{'SQL':'Sales Qualified Lead'}} data = [{'class':'IT', 'description':'SQL developer'}, {'class':'IT', 'description':'SQL developer BLAH'}, {'class':'Sales', 'description':'senior SQL'}] df = pd.D...
python|pandas|nlp|pandas-groupby|text-classification
1
373,769
68,367,396
What is the syntax to select from pandas dataframe column, those elements which begin with particular alphabets using a single line of code?
<p>For example, if</p> <pre><code>df_table = pd.DataFrame({'Name':['Jason', 'Chris', 'Harry', 'Jacob', 'Arthur'], 'Salary':[7543,2387,6749,1472,8748]}) </code></pre> <p>I want to select and show only the names starting with A and J.</p> <p>I know I can select elements starting with A using:</p> <pre><code>df_table[(df_...
<p>Try:</p> <pre><code>df_table[df_table['Name'].str[0].isin(['A','J'])] df_table[df_table['Name'].str.contains('^[AJ]')] </code></pre>
python|pandas|dataframe
1
373,770
68,225,703
Comparing 2 dataframes to add rows if between dates
<p>completely new here, I tried looking up my problem but couldn't find anything quite similar!</p> <p>I'm trying to set up a dataframe that contains the data for a schedule and its activity types. For example, if it's '1' it's a normal activity, and if it's '2' it's canceled, and compare that dataframe to another one ...
<p>To present a more instructive example, I created <em>Schedule</em> as containing <strong>multiple</strong> rows:</p> <pre><code> Start Date End Date Activity Type 0 2021-01-01 2021-05-31 10 1 2021-06-01 2021-12-31 20 </code></pre> <p>I created <em>Holidays</em> as:</p> <pre><code> Holida...
python|pandas|date|for-loop|python-holidays
0
373,771
68,131,345
How to join matrices like puzzle pieces in python
<p>I've got three puzzle pieces defined as a number of arrays, 7x7, in a following manner:</p> <pre><code>R3LRU = pd.DataFrame([ [1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1] ]) ...
<p>I take it you want to concatenate if the last column and first columns match and then &quot;overlap&quot; both parts. I dont think, pandas is a good fit for this problem as you only need values, no columns or basically any features you would use pandas for.</p> <p>I would recommend simple numpy arrays. Then you coul...
python|pandas|matrix|concatenation|puzzle
1
373,772
68,261,553
Stack 2D array vertically
<p>I want to stack the first n columns of a 2D array vertically. My realization is in the following: <code>np.vstack(input_seq[:,:n].flatten().tolist())</code></p> <p>I am wondering if stacking 1D array directly would be faster? <code>np.vstack(input_seq[:,:n].flatten())</code></p> <p>Or are there any faster approaches...
<p>Just reshape your array:</p> <pre><code>new = input_seq[:, :n].reshape(-1) </code></pre> <p>Since you're indexing, the reshaped array is already a copy, so you can manipulate it without changing the original array (a reshaped array points to the same data otherwise).</p> <p>Note that this method makes <code>new</cod...
python|numpy
0
373,773
68,152,914
Pandas: Apply agg on two columns at a time
<p>I am migrating some of pySpark code into Pandas and stuck with implementing <code>collect_set</code> on two columns. <br/> pySpark code looks like this:</p> <p><code>df_collect = df.groupBy('col1').agg(collect_set('col2').alias('Col2Arr'), collect_set('col3').alias('Col3Arr'))</code></p> <p>I can easily implement fo...
<p>Depending on what you're looking for, as <a href="https://stackoverflow.com/questions/68152914/pandas-apply-agg-on-two-columns-at-a-time#comment120453364_68152914">@anky</a> suggests, a standard <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.aggregate.html#pa...
python|pandas|dataframe
1
373,774
68,313,826
How to combine repeated header columns for multi-index pandas dataframe?
<p>Current dataframe:</p> <pre><code> a a b b c k l m n o a 1 2 9 1 4 b 2 3 9 2 4 c 3 8 7 8 3 d 8 8 9 0 0 </code></pre> <p>desired dataframe:</p> <pre><code> a b c k l m ...
<p>The two dataframes are exactly the same. If you want to change the style of the display you can do the following:</p> <pre><code>df = pd.DataFrame(np.array([[1, 2, 9, 1, 4], [2, 3, 9, 2, 4], [3, 8, 7, 8, 3], [8, 8, 9, 0, 0]]), ...
python|pandas|dataframe|data-science|data-manipulation
0
373,775
68,313,364
tensorflow.js adding many image samples to model fills video card memory and crashes
<p>I refer to this example</p> <p><a href="https://github.com/tensorflow/tfjs-examples/tree/master/webcam-transfer-learning" rel="nofollow noreferrer">https://github.com/tensorflow/tfjs-examples/tree/master/webcam-transfer-learning</a></p> <p><a href="https://storage.googleapis.com/tfjs-examples/webcam-transfer-learnin...
<p>Try this:</p> <pre><code>async function readFileToImageElement(file) { const img = new Image() img.src = URL.createObjectURL(file) await img.decode() return img } // when the image is not needed anymore call: URL.revokeObjectURL(img.src) </code></pre>
javascript|tensorflow|tensorflow.js
0
373,776
68,432,078
Cannot parse strings correctly to remove special characters
<p>I have one column of a df, which contains strings, which I wish to parse:</p> <pre><code>df = pd.DataFrame({'name':'apple banana orange'.split(), 'size':&quot;2'20 12:00 456&quot;.split()}) </code></pre> <p>which gives <a href="https://i.stack.imgur.com/QIwhc.png" rel="nofollow noreferrer"><img src="https://i.stack....
<p>If you only need to test for the <code>'</code> and the <code>:</code> in the time stamp this will do the job:</p> <pre><code>df[&quot;size&quot;] = df[&quot;size&quot;].str.replace(&quot;'&quot;, &quot;&quot;).str.split(&quot;:&quot;).map(lambda x: x[0]) </code></pre> <p>Output:</p> <pre><code> name size 0 ap...
python|pandas
1
373,777
68,333,886
Renaming the value returned by Lambda Function in Aggregate Operation
<p>I am looking to display the value of various percentiles against each group of Publishers in a dataset. I am trying the below:</p> <pre><code>vg.groupby(['Publisher']).agg({'Global_Sales':['mean','min','max','median',lambda x: x.quantile(0.5)]}) </code></pre> <p>The few rows of the dataset are:</p> <pre><code> Ran...
<p>From the <a href="https://pandas.pydata.org/pandas-docs/version/1.2.0/reference/api/pandas.DataFrame.agg.html" rel="nofollow noreferrer">doc of <code>.agg()</code></a> you can also directly specify the column name in the <code>agg()</code> function as keyword arguments:</p> <pre><code>&gt;&gt;&gt; vg.groupby(['Publi...
pandas|dataframe|data-analysis|exploratory-data-analysis
0
373,778
68,032,242
Updating excel files functions
<p>I am trying to create a function that can update (add data) to existing .xlsx files.</p> <pre><code>def update_excel(path, sheetname, data): filename = path with pd.ExcelWriter(filename, mode='a',engine=&quot;openpyxl&quot;) as writer: print('SHEETNAME', sheetname) df = pd.read_excel(path, sheetname) ...
<p>Create, write to and save a workbook:</p> <pre><code>df1 = pd.DataFrame([['a', 'b'], ['c', 'd']], index=['row 1', 'row 2'], columns=['col 1', 'col 2']) df1.to_excel(&quot;output.xlsx&quot;) </code></pre> <p>To specify the sheet name:</p> <pre><code>df1.to_excel(&quot;output.xlsx...
python|excel|pandas|xlsxwriter
0
373,779
68,085,566
Pandas | selecting all rows within a group and a specific column
<p>As an example, if I were to have a DataFrame that looked like the following:</p> <pre><code> CONTINENT COUNTRY POPULATION Europe France 67.06 Europe Italy 60.36 Europe Denmark 5.80 Asia Japan 126.30 Asia China 1398.00 N. ...
<p>When you use <code>df.loc</code> the first item refers to the index. You want the values of a column where other column has a certain value. You should find the indices of the places where this condition is True and then use <code>df.loc</code>. Try the following:</p> <pre><code>df.loc[(df['CONTINENT'] == 'Europe'),...
python|pandas|dataframe
1
373,780
68,401,645
How to multiply matricies with algebra in numpy
<p>I have two numpy matrix objects in my code, one is a matrix of numbers and the other is a matrix of variables that I do not want to assign values to. The result I want is this:</p> <pre><code>[[ 1., 0., 0., 0., 0., 1., 0., 0., 0.], [ 0., 1., 0., 0., 0., 1., -1., 1., -1.], [ 0., 0., 1., 0., 0., 1...
<p>With object dtype arrays, functions like <code>np.dot</code> try to delegate the action to the multiply and add methods of the elements.</p> <p>Thus I define a class:</p> <pre><code>In [467]: class Y: ...: def __init__(self,astr): ...: self.value = astr ...: def __repr__(self): .....
python|numpy|matrix|linear-algebra
1
373,781
68,268,531
window function for moving average
<p>I am trying to replicate SQL's window function in pandas.</p> <pre><code>SELECT avg(totalprice) OVER ( PARTITION BY custkey ORDER BY orderdate RANGE BETWEEN interval '1' month PRECEDING AND CURRENT ROW) FROM orders </code></pre> <p>I have this dataframe:</p> <pre><code>from io import StringIO import pan...
<p>You can use the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rolling.html" rel="nofollow noreferrer">rolling</a> function on the last 30 days</p> <pre><code>df['date'] = pd.to_datetime(df['date']) df['my_average'] = (df.groupby('customer_id') .apply(lambda d: d.ro...
pandas
2
373,782
68,121,629
Trying to extract y_val from dataset throws "all the input arrays must have same number of dimensions"
<p>I am very new to machine learning and python in general. I'm working on a project requiring to make an image classification model. I've read the data from my local disk using <code>tf.keras.preprocessing.image_dataset_from_directory</code> and now I'm trying to extract <code>x_val</code> and <code>y_val</code> to ge...
<p>You don't need <code>argmax</code> operation while getting the true classes.</p> <p>Since you did not specify <code>class_mode</code> in <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image_dataset_from_directory" rel="nofollow noreferrer">tf.keras.preprocessing.image_dataset_from_directo...
python|numpy|tensorflow|machine-learning|keras
1
373,783
68,172,115
Generate a sequence by appending values without clash in other values
<p>I have a dataframe like as shown below</p> <pre><code>df = pd.DataFrame({'person_id': [101,101,101,101,202,202,202], 'login_date':['5/7/2013 09:27:00 AM','09/08/2013 11:21:00 AM','06/06/2014 08:00:00 AM','06/06/2014 05:00:00 AM','12/11/2011 10:00:00 AM','13/10/2012 12:00:00 AM','13/12/2012 11...
<p>I tried appending zeroes based on the length of the dataframe to avoid any clash with existing ids. Any suggestions to improve this solution is welcome. This works on small data but fails on larger dataframe</p> <pre><code>cumcount = df.groupby(['person_id','login_id']).login_id.cumcount() df.login_id = df.groupby([...
python|pandas|dataframe|numpy|pandas-groupby
1
373,784
68,326,398
Pandas - Generate Columns Based on Condition
<p>Here is sample dataset:</p> <pre><code>&gt;&gt;&gt; df vn pt st nst stb mid 0 a 0.1 a b 0 3 1 a 0.2 a b 4 3 2 a 0.3 a b 1 3 3 a 0.3 b a 1 3 4 a 0.4 a b 1 3 5 a 0.4 a b 2 3 6 a 0.5 c b 6 3 7 a 0.5 c b ...
<p>Here is the partial solution so far, based on question and discussions in comments:</p> <p><code>sr</code> column already got the expected results but <code>nsr</code> need some further works:</p> <pre><code>df['sr'] = df.groupby(['mid', 'st'])['stb'].cumsum() </code></pre> <p><strong>Result:</strong></p> <pre><code...
python|pandas|dataframe
1
373,785
59,042,623
Filtering of records between sysdate and sysdate+7 from Oracle Sql is not working correctly
<p>I am firing an SQL query to filter records between sysdate and sysdate+7 but I am getting records outside the range as well. What is wrong my SQL</p> <pre><code>cursor.execute(""" select 'Shipment' as object_type , trunc(sc.effective_timestamp) reference_date , sc.location_name location from ma...
<p>You are filtering on <code>c.ets</code>.</p> <p>You are selecting <code>sc.effective_timestamp</code>.</p> <p>I suspect that you are confused about the dates. If you filter on the same column you are selecting, then you should not see out-of-range dates.</p>
python|sql|pandas|oracle
1
373,786
59,370,130
In Pandas, How do you cumsum rows with only a True series boolean
<p>This question is an extension of a question from moys, as i'm interested in an answer to how to cumsum based on truth series of a boolean. Let's say i have this dataframe and i only want to cum sum the True rows.:</p> <pre><code> id log loc pos_evnts neg_evnts As non_As pos_wrds neg_wrds As/Ac Truth T...
<p>You can filter only <code>True</code> rows with only numeric columns, also excluded <code>T</code> column for prevet cumulative sum and assign back:</p> <pre><code>cols = df.select_dtypes(np.number).columns.difference(['T']) df.loc[df['Truth'], cols] = df.loc[df['Truth'], cols] .groupby(df['T']).cumsum() print (df...
python|pandas
0
373,787
59,418,174
Set per_process_gpu_memory_fraction in tensorflow.js tfjs-node-gpu
<p>is it possible to set the max allocate GPU memory for tfjs-node-gpu ? By default it take 100%, and I haven't view any information on the API doc.</p> <p>thanks</p>
<p>For now it is not possible to set a memory limit on the GPU; node does not yet offer a control over the gpu used and neither <code>tfjs-node-gpu</code> in itself.</p> <p>However, you can use the memory footprint to check manually the size allocated with <code>tf.memory</code></p>
tensorflow.js
0
373,788
59,307,485
In Pandas, following a grouby and a pd.cut, how do I rearrange the data frame to plot by each bin over time?
<p>I have a dataframe with 50 data points per month. I'd like to run a groupby on the date, and then calculate the median value for each decile within each month. I've been able to accomplish this with the code below:</p> <pre><code>import numpy as np import pandas as pd datecol = pd.date_range('12/31/2018','12/31/20...
<p>You can do:</p> <pre><code>dfg.unstack(-1).plot() </code></pre> <p>output:</p> <p><a href="https://i.stack.imgur.com/8oEos.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8oEos.png" alt="enter image description here"></a></p>
python|pandas|group-by
1
373,789
59,131,050
TypeError: 'set' object is not subscriptable. 3 CSV files
<p>When trying to build my data set an error of "TypeError: 'set' object is not subscriptable" is received.</p> <pre><code>dataDir = '/content/drive/My Drive/Colab Notebooks/HW 3/' # Directory with input files trainFile = 'q2train.csv' # Training examples labelFile = 'q2label.csv' # Test label validFile = 'q2valid.csv...
<p>Use a dictionary:</p> <pre class="lang-py prettyprint-override"><code>train = pd.read_csv(dataDir+trainFile) valid = pd.read_csv(dataDir+validFile) label = pd.read_csv(dataDir+labelFile) data_sets = { 'train': train, 'label': label, 'valid': valid } </code></pre> <p>Then <code>data_sets[data_set_name]...
python|pandas|scikit-learn
1
373,790
59,165,595
how to conditionnally copy an above case in a column of a dataframe using nested np.where statement
<p>I have 3 columns in my Dataframe df : In the 3rd column 'Entry Price Repeat', i would like to copy the above case of the same column IF the case of the 2nd column 'Position' is 1 for the same raw and the raw above. Else, i want to copy the case of the 1st column 'Adj Close' in the column 'Entry Price Repeat'. This b...
<p>If I understood your question correctly the code below should do it. First you populate the 'Entry Price Repeat' with the current or previous row in that 'Position' is equal to 0. Once you have done that, you just need to use pandas fillna method with front fill.</p> <pre><code>df2['Entry Price Repeat'] = df2['Adj ...
python|pandas|numpy|where-clause|algorithmic-trading
0
373,791
59,191,271
Calculate the total occurence of specific elements in an array of lists
<p>I am getting the below array list as an output of my for loop. How can I calculate the total number of true and false (separate) coming in each list.</p> <pre><code>[array(['false', 'false', 'false', 'true', 'true', 'true', 'false', 'true', 'false', 'true', 'false', 'false'], dtype='|S5')] [array(['false', '...
<p>I believe you need list comprehension with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>Series.value_counts</code></a>:</p> <pre><code>cutoff_list_neg = [(df['score']&gt;=0).value_counts() for df in df_elements] </code></pre> <p...
python|pandas
0
373,792
59,305,439
Merge CSV files in a Pandas Dataframes based on a Text Field
<p>I have two csv files I am trying to merge into one data frame using the code below: </p> <pre><code>import pandas as pd df_1 = pd.read_csv('A.csv') df_2 = pd.read_csv('B.csv') df_3 = df_1.merge(df_2, on='Material_Number_ID', how='left') </code></pre> <p>The field I am trying to use to merge them on (Material_...
<p>From this <a href="https://stackoverflow.com/questions/49909710/suppress-scientific-format-in-a-dataframe-column">thread</a>, when you import from the csv pandas reads the numbers as floats. If you convert them to int64 using the following code, it should display all numbers of the <code>Material_Number_ID</code>.</...
python|pandas|dataframe|text|merge
0
373,793
59,367,784
Is ArcFace strictly a loss function or an activation function?
<p>The answer to the question in the header is potentially extremely obvious, given it is commonly referred to as "ArcFace Loss". </p> <p>However, one part is confusing me:</p> <p>I was reading through the following Keras implementation of Arcface loss:</p> <p><a href="https://github.com/4uiiurz1/keras-arcface" rel=...
<p>Based on my understanding. The two things that you are confused about are as follows -</p> <ol> <li>Is ArcFace is a loss or an activation function ?</li> <li>Is softmax a loss or an activation function ?</li> </ol> <h1>Is ArcFace is a loss or an activation function</h1> <p>Your assumption that ArcFace is an activati...
tensorflow|keras|deep-learning|computer-vision|classification
8
373,794
59,234,659
How to split multiple columns in Pandas
<p>I have a data frame like below:</p> <pre><code>df = pd.DataFrame({'var1': ['0,3788,99,20.88', '3,99022,08,91.995'], 'var2': ['0,929,92,299.90', '1,38333,9,993.11'], 'var3': ['8,9332,99,29.10', '7,922111,07,45.443']}) Out[248]: var1 var2 ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a> , <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>str.split()</code></a> with...
python|pandas
1
373,795
59,238,934
Check GPU memory used from python in Tensorflow 2.0
<p>There are several threads <a href="https://stackoverflow.com/questions/40190510/tensorflow-how-to-log-gpu-memory-vram-utilization">here</a> and <a href="https://stackoverflow.com/questions/36123740/is-there-a-way-of-determining-how-much-gpu-memory-is-in-use-by-tensorflow">here</a> on SO covering how to get GPU memor...
<p>For now, it seems that this option is not available in TF 2. Some alternatives include:</p> <ul> <li>Use python bindings for the NVIDIA Management Library as explained <a href="https://stackoverflow.com/a/58014617">in this issue</a></li> <li>Get the info by the <code>nvidia-smi</code> command</li> </ul> <p>For the s...
python|python-3.x|tensorflow|tensorflow2.0
2
373,796
59,050,019
Tensorflow Issue in the Shortest Path Graph Learning Model of OctavianAI
<p>I am setting a a Graph Machine Learning application using Ocatvian AI Graph ML toolset. In this particular case, I am trying to setup Shortest Path library. It is failing with error with Tesnforflow backend. </p> <pre><code>AttributeError: module 'tensorflow_core._api.v2.nn' has no attribute 'rnn_cell'` </code></pr...
<p>As per the investigations into the Tensorflow library in Github and other online forums, it can be understood that the python environment is looking for Tensorflow 2.0 version. However the Octavian AI Shortest Path package seems to be on Tensorflow 1.0. This seems to be the reason for this build error in training t...
python|tensorflow|machine-learning|graph-databases|machine-learning-model
0
373,797
59,345,990
Creating modified version of SparseCategoricalAccuracy, getting ValueError: tf.function-decorated function tried to create variables on non-first call
<p>I'm trying to create a masked version of <code>SparseCategoricalAccuracy</code> in tf 2.0 that can be passed to the Keras api via <code>compile(metrics=[masked_accuracy_fn()]</code>.</p> <p>The function looks like:</p> <pre class="lang-py prettyprint-override"><code>def get_masked_acc_metric_fn(ignore_label=-1): ...
<p>This seems to work as a temporary workaround:</p> <pre class="lang-py prettyprint-override"><code>class MaskedSparseCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy): def __init__(self, name="masked_sparse_categorical_accuracy", dtype=None): super(MaskedSparseCategoricalAccuracy, self).__i...
tensorflow2.0|tf.keras|eager-execution
0
373,798
59,224,165
Insert random data string into a new dataframe column
<p>have a df </p> <pre><code>a b mark 50 john 60 jack 30 harry 80 jacob 10 </code></pre> <p>Need to make a new column in df with some random values</p>
<p>Create 2d random array of letters and join them in list comprehension:</p> <pre><code>L = list('abcdefghijklmnopqrstuvwxyz') df['c'] = ['test'+ ''.join(x) for x in np.random.choice(L, size=(len(df), 3))] print (df) a b c 0 mark 50 testpje 1 john 60 testrmn 2 jack 30 testoud 3 harry 80...
python|pandas|dataframe
2
373,799
59,116,831
How can I do to evaluate mean and std for a dataset?
<p>I am using pytorch and the dataset fashion MNIST but I do not know how can I do to evaluate the mean and the std for this dataset. Here is my code : </p> <pre><code>import torch from torchvision import datasets, transforms import torch.nn.functional as F transform = transforms.Compose([transforms.ToTensor(), tra...
<p>Use this to calculate mean and std-</p> <pre><code>loader = data.DataLoader(dataset, batch_size=10, num_workers=0, shuffle=False) mean = 0. std = 0. for images, _ in loader: batch_samples = images.size(0) # batch size (the last batch ca...
python|python-3.x|deep-learning|artificial-intelligence|pytorch
4