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
4,100
48,520,478
pandas replace NaT with strings in columns when trying to get timedelta object days
<p>I have the following <code>df</code>,</p> <pre><code>A B 3 days NaT NaT 1 days 4 days 3 days NaT NaT </code></pre> <p>the <code>dtype</code> of <code>A</code> and <code>B</code> is <code>timedelta64[ns]</code>, I am tring to get <code>days</code> from each <code>timedelta</code> of the tw...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.days.html" rel="nofollow noreferrer"><code>dt.days</code></a> which working with <code>NaT</code> too:</p> <pre><code>print (df['A'].dt.days) 0 3.0 1 NaN 2 4.0 3 NaN Name: A, dtype: float64 df[['A', 'B']] = df[['A', 'B'...
python|python-3.x|pandas|dataframe
1
4,101
48,549,101
How to calculate cost for softmax regression with pytorch
<p>I would to calculate the cost for the softmax regression. The cost function to calculate is given at the bottom of the page.</p> <p>For numpy I can get the cost as follows:</p> <pre><code>""" X.shape = 2,300 # floats y.shape = 300, # integers W.shape = 2,3 b.shape = 3,1 """ import numpy as np np.random.seed(100)...
<p>Your problem is that you cannot use <code>range(N)</code> with <code>pytorch</code>, use the slice <code>0:N</code> instead:</p> <pre><code>hyp = torch.exp(scores - torch.max(scores)) probs = hyp / torch.sum(hyp) correct_probs = probs[0:N,y] # problem solved logprobs = torch.log(correct_probs) cost_data = -1/N * to...
python|machine-learning|deep-learning|pytorch|softmax
3
4,102
48,646,684
Pandas: conditional shift
<p>There is a way to shift a dataframe column dependently on the condition on two other columns? something like:</p> <pre><code>df["cumulated_closed_value"] = df.groupby("user").['close_cumsum'].shiftWhile(df['close_time']&gt;df['open_time]) </code></pre> <p>I have figured out a way to do this but it's inefficient:</...
<p>I am using a new para here record the condition <code>df2['close_time']&lt;df2['open_time']</code></p> <pre><code>df['New']=((df.open_time-df.close_time.shift()).dt.days&gt;0).shift(-1) s=df.groupby('user').apply(lambda x : (x['value']*x['New']).cumsum().shift()).reset_index(level=0,drop=True) s.loc[~(df.New.shift(...
python|pandas|datetime|data-analysis
9
4,103
48,854,581
How to create a python dataframe containing the mean and standard deviation of some rows of another dataframe
<p>I have a pandas DataFrame containing some values:</p> <pre><code> id pair value subdir taylor_1e3c_1s_56C taylor 6_13 -0.398716 run1 taylor_1e3c_1s_56C taylor 6_13 -0.397820 run2 taylor_1e3c_1s_56C taylor 6_13 -0.397310 run3 taylor_1e3c_1s_56C taylor 6_13 -0.390520 ...
<p>You could promote your index to a column and perform a single <code>groupby</code>:</p> <pre><code>import pandas as pd df = pd.DataFrame([['taylor', '6_13', -0.398716, 'run1'], ['taylor', '6_13', -0.397820, 'run2'], ['taylor', '8_11', -0.389959, 'run4'], ['...
python|pandas|dataframe|pandas-groupby
4
4,104
48,525,582
Minimizing if statements in python function
<p>I have following function, which takes values from pandas dataframe columns and supplies arguments(s0_loc,s1_loc,.. upto ..,s12_loc if and only if their respective s0,s1,s2...,s12 is not-null) to another function. Also It will check whether s1 is null or not if and only if s0 is not null... Similarly it will check w...
<p>To go with Sandeep's answer, you can build the two lists locally from the giant list of arguments:</p> <pre><code>def compare_locality(p,p_loc,s0,s0_loc,s1,s1_loc,s2,s2_loc,s3,s3_loc,s4,s4_loc,s5,s5_loc,s6,s6_loc,s7,s7_loc,s8,s8_loc,s9,s9_loc,s10,s10_loc,s11,s11_loc,s12,s12_loc): locs = [] ss = [s0, s1, s2,...
python|pandas|dataframe
6
4,105
70,835,416
Why sorting a pandas column causing reordering the sub-groups?
<p>The goal of my question is to understand why this happens and if this is a defined behaviour. I need to know to design my unittests in a predictable way. I <strong>do not</strong> want or need to change that behaviour or work around it.</p> <p>Here is the initial data on the left side complete and on the right side ...
<p>As explained in the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>sort_values</code></a> documentation, the <a href="https://en.wikipedia.org/wiki/Sorting_algorithm#Stability" rel="nofollow noreferrer">stability of the sort</a> is not always ...
pandas
3
4,106
70,910,213
pandas named aggregation without multilevel dataframe
<p>I am trying to remove the multi level but unable to do so.</p> <pre><code>import pandas as pd k = pd.DataFrame([['x',2], ['y',4],['x',6]], columns=['name','value']) agg_item={'value': [('n', 'count')]} k=k[['name','value']].groupby(['name'],dropna=False).agg(agg_item).reset_index() k name value ...
<p>You can use a named aggregation with <code>pd.NamedAgg</code> to avoid creating a MultiIndex in the first place:</p> <pre><code>n_agg = pd.NamedAgg(column='value', aggfunc='count') k = k[['name','value']].groupby(['name'],dropna=False).agg(n=n_agg).reset_index() </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; k...
python|pandas
2
4,107
51,658,122
Keras loss is in negative and accuracy is going down, but predictions are good?
<p>I'm training a model in Keras with Tensorflow-gpu backend. Task is to detect buildings in satellite images. loss is going down(which is good) but in negative direction and accuracy is going down. But good part is, model's predictions are improving. My concern is that why loss is in negative. Moreover, why model is i...
<p>Your output is not normalized for a binary classification. (Data is also probably not normalized). </p> <p>If you loaded an image, it's probably 0 to 255, or even 0 to 65355.</p> <p>You should normalize <code>y_train</code> (divide by <code>y_train.max()</code>) and use a <code>'sigmoid'</code> activation function...
tensorflow|machine-learning|keras|deep-learning|conv-neural-network
5
4,108
41,746,206
Pandas search for duplicate rows in one column which have different values in another column
<p>I have a Pandas dataframe <code>df</code> for which I want to find all rows for which the value of column <code>A</code> is the same, but the value of column <code>B</code> different, e.g.:</p> <pre><code> | A | B ---|---|--- 0 | 2 | x 1 | 2 | y </code></pre> <p>I know I can use <code>pd.conc...
<p>Thinking about this, it makes sense to call <code>unique</code> on the <code>groupby</code>:</p> <pre><code>In [213]: df = pd.DataFrame({'A':2, 'B':list('xxyzz')}) df Out[213]: A B 0 2 x 1 2 x 2 2 y 3 2 z 4 2 z In [229]: df.groupby('A')['B'].apply(lambda x: x.unique()).reset_index() Out[229]: A ...
python|pandas
6
4,109
42,114,381
Bollinger bands in Python. Where/How rm and rstd get defined in code below?
<p>I have a small problem with code snipped below. It works perfectly, but its not written by me and there is one part I do not understand. In my head I would need to return rm &amp; rstd from <code>get_rolling_mean()</code> and <code>get_rolling_std()</code>, but that is not really happening here. So my questions is: ...
<p>The Get rollinger bands function gets its variables from the user:</p> <pre><code> get_bollinger_bands(rm, rstd): upper_band = rm + (rstd * 2) lower_band = rm - (rstd * 2) return upper_band, lower_band </code></pre> <p>The only variables used are the ones between the parentheses after the f...
python|python-3.x|pandas
3
4,110
64,210,138
Define function that takes string value, searches for it in dataframe column, and returns TRUE if it is in the column and contains the word "Sales"
<p>I have to define a function called isSales() that takes the job title of an employee as a string and returns <strong>True</strong> if the job title indicates that the person works in Sales and returns <strong>False</strong> otherwise.</p> <p>For this problem, I've created a dataframe(df) from reading an excel spread...
<p>In general, when writing Pandas code, you should avoid row-by-row iteration unless you have no choice. This is a situation where you have a choice.</p> <p>Rather than calling your isSales function on each row, I would suggest using the builtin <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/panda...
python|pandas
0
4,111
64,307,480
Reading .txt file using pandas and slicing it based on some range in one column
<p>I have multiple .txt files that are full of rubbish data and only need a portion of it based on some range that changes between files. I'm still learning Python and not very experienced.</p> <p>I am using VS code 1.50 and Python 3.8.1</p> <p>Sample of my data: <a href="https://pastebin.com/kZm1spnz" rel="nofollow no...
<p>You should use &amp; instead of and:</p> <pre><code>Data_result_1 = Data[ (Data['Depth'] &gt;= 7711) &amp; (Data['Depth'] &lt;= 7786)] </code></pre>
python|python-3.x|pandas|dataframe
1
4,112
64,259,052
Adding rows to pandas dataframe with date range, created_at and today, python
<p>I have a dataframe <a href="https://i.stack.imgur.com/KNrlw.png" rel="nofollow noreferrer">dataframe</a> consisting of two columns, customer_id and a date column, created_at.</p> <p>I wish to add another row for each month the customer remains in the customer base.</p> <p>For example, if the customer_id was created ...
<p>Try this:</p> <pre><code>import pandas as pd import datetime from dateutil.relativedelta import relativedelta from dateutil import rrule, parser outList = [] operations_date = datetime.datetime.now().date() dfDict = df.to_dict(orient='records') for aDict in dfDict: created_at = aDict['created_at'] start_da...
python|pandas|numpy|date|expand
1
4,113
49,103,830
CTC LossTensor is inf or nan: Tensor had Inf values?
<p>I keep encountering this error right on the first step of training (or after 300 hundred steps or so). Can anyone point out the reason why this is happening? If you're interested to about the model I used, here it is:</p> <pre><code>{ "network":[ {"layer_type": "input_layer", "name": "inputs", "shape": [-1, 1...
<p>It's definitely the sequence length of the input that causes the problem. Apparently, the sequence length should be a bit greater than the ground truth length.</p>
tensorflow
2
4,114
49,252,574
Deleting points on grid outside of boundary condition - Python
<p>I have a grid of points (e.g. (1,1), (1,2), (1,3)...(100,99), (100,100)) that is contained in a a pandas dataframe, and also exported as a .csv file. </p> <p>I then have a boundary condition, for example a circle in the centre of this grid with a diameter of 25. I want to be able to delete all the points outside of...
<p>Since your question is...</p> <blockquote> <p>Is it possible to save all the points internal to the circle?</p> </blockquote> <p>Yes, it is possible, and there is a formula for this. The function below <code>distance_from</code> is basic euclidean distance for 2D plans.</p> <pre><code>def encloses(center_of_cir...
python|pandas|dataframe|data-manipulation
0
4,115
49,088,759
Finding the min. value in a specific column for range of future rows with pandas/python
<p>I have the following data:</p> <pre><code>datetime price 2017-10-02 08:03:00 12877 2017-10-02 08:04:00 12877.5 2017-10-02 08:05:00 12879 2017-10-02 08:06:00 12875.5 2017-10-02 08:07:00 12875.5 2017-10-02 08:08:00 12878 2017-10-02 08:09:00 12878 2017-10-02 08:10:00 12878 2017-10-02 08:11:00 12881 2017-10-02 08:12...
<p>Since it looks like you have 1 minute intervals, you may want to take advantage of <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow noreferrer"><code>resample</code></a>, that way you can define the window using datetime</p> <pre><code>df.resample('3T',on...
python|pandas
2
4,116
58,854,893
Python duplicate list values from index to another
<p>Let's say I have this numpy array :</p> <pre><code>first_array = [[1. 0. 0. 0. 0.] [1. 0. 0. 0. 0.] [0. 1. 0. 0. 0.] [0. 0. 1. 0. 0.] [0. 0. 1. 0. 0.] [0. 0. 1. 0. 0.] [0. 0. 0. 0. 1.]] </code></pre> <p>and I have this 2 list...
<p>It's working now. I forgot to add the k column index at the output_array. Here's the final working code if anyone needed this.</p> <pre><code>first_array = [[1, 0, 0, 0, 0,], [1, 0, 0, 0, 0,], [0, 1, 0, 0, 0,], [0, 0, 1, 0, 0,], [0, 0, 1, 0, 0,], ...
python|numpy
2
4,117
58,680,157
Fill in the missing data using Pandas
<p>What's the best way to fill in the missing data using Pandas . I have a list of visitors where the exit time or the entry time is missing . </p> <pre><code>visitor entry exit A 16/02/2016 08:46 16/02/2016 09:01 A 16/02/2016 09:20 16/02/2016 17:24 A 17/02/2016 09:12 17/02/2016 09:42 A 17/...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ffill.html" rel="nofollow noreferrer"><code>DataFrame.ffill</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.bfill.html" rel="nofollow noreferrer"><code>DataFrame.bfill</c...
python-3.x|pandas|dataset|data-science|fillna
0
4,118
58,957,367
Merge 2 dictionaries and store them in pandas dataframe where one dictionary has variable length list elements
<p>I'm iterating through some HTML divs like this with Beautiful Soup:</p> <pre><code>for div in soup.findAll('a', {'class': 'result'}): adLink = div.a.get('href') adInfo= { u'adLink':adLink, u'adThumbImg':...some code..., ...
<p>After you get the full ad, convert that to a 1 row dataframe, then just append that into a final dataframe. That will take care of the mismatch lengths and if there is data not available on an ad that is there for others. You'll have to work out the logic, as you haven't provided that part of your code to test. So q...
python|pandas|dictionary|beautifulsoup
3
4,119
58,867,907
what is the difference between as_matrix() and to_numpy() methods?
<p>what is the difference between as_matrix() and to_numpy() methods? I know that both are used to convert pandas dataframe into numpy ndarray, but what is the difference between these 2 methods?</p>
<p>I guess <code>as_matrix()</code> is confusing sometimes compared with Numpy metrix, then was deprecated. AS to what we get is <code>Numpy-array</code> from <code>.as_matrix()</code>, instead of <code>Numpy-matrix</code>. As for the defference bwt numpy narrays and nmpy matrices, hear is a good answer <a href="http...
python|pandas|list
0
4,120
58,783,496
How can I assign a name to the 'intersection' of index and columns in a pandas dataframe?
<p>If I create a dataframe and than generate a pivot table from it, it keeps appearing a string in the upper left "cell" of the resulting table, like below. In this example it appears the string "n":</p> <pre><code>import pandas as pd df = pd.DataFrame({'col1':['a','a','b','b','c','c'], 'col2':['str_a1'...
<p>I got the answer by 'looking' at the dataframe 'horizontally' instead of 'vertically'. The 'n' that I was mentioning above was not the index name as splash58 pointed out. I must say that I used to think this way.</p> <p>Than I noticed that the 'n' was in the same line as the other columns names's. Therefore it must...
python|pandas|indexing|pivot-table|rename
0
4,121
70,351,924
How to use filter condition along with groupby in pandas
<p>I am trying to filter the dataset with multiple columns and by filtering with a particular value in the column using groupby . I am able to filter using groupby but not able to apply the filter</p> <p>I have tried using below code</p> <pre><code>df.groupby(['city','season','toss_winner','toss_decision'])['winner'].s...
<p>Filter city=CapeTown first and then groupby:</p> <pre><code>out = (df.query(&quot;city =='Cape Town'&quot;) .groupby(['city','season','toss_winner','toss_decision'])['winner'].size()) </code></pre>
python|pandas|group-by|filtering
0
4,122
70,275,939
Return to previous tensorflow version
<p>I have been running with tensorflow 2.3.0</p> <p>A few days ago I tried installing a library with this</p> <pre><code>pip install tensorflow_decision_forests </code></pre> <p>This upgraded my tensorflow to 2.7.0 and now I'm having problems including not being able to use gpu in my training. Is there any way to rever...
<p>Runnig: pip install tensorflow==2.3.0</p> <p>Solved my problem. Sorry for not trying it earlier but was afraid it would make it worse</p>
python|tensorflow|conda
1
4,123
70,178,163
How do I create new pandas dataframe by grouping multiple variables?
<p>I am having tremendous difficulty getting my data sorted. I'm at the point where I could have manually created a new .csv file in the time I have spent trying to figure this out, but I need to do this through code. I have a large dataset of baseball salaries by player going back 150 years. <a href="https://i.stack.i...
<p>You just need to <code>reset_index()</code></p> <p>Here is sample code :</p> <pre><code>salaries = pd.DataFrame(columns=['yearID','teamID','igID','playerID','salary']) salaries=salaries.append({'yearID':1985,'teamID':'ATL','igID':'NL','playerID':'A','salary':10000},ignore_index=True) salaries=salaries.append({'year...
python|pandas|dataframe|sorting|pandas-groupby
1
4,124
70,282,491
Pandas dataframe too slow when using loc function to create a new dataframe (I want to flatten a dataframe)
<p>this is not the most butiful code. And it's too slow when doing what I want it to, so I was hoping someone could tell me a faster way of doing this.</p> <p>I have a file (of about 800K+ lines) looking something like the example below, I want to flatten the file so that one userident has all the answers after it (in ...
<p><code>pivot</code> might do what you need</p> <pre><code>import pandas as pd import io long_df = pd.read_csv(io.StringIO( &quot;&quot;&quot; userident,qustion,time,answer j/n,amount,text,flag 1,FMTA DYN 01 - PERSON,13:00,j,14,some info,0 1,FMTA DYN 02 - PERSON,13:00,j,14,some info,0 1,FMTA DYN 03 - PERSON,13:00,j,1...
python|pandas|dataframe
0
4,125
70,168,153
Python's numpy array of doubles to and from a HDF file without unnecessary conversions
<p>I have a numpy array of doubles. np.array([double1, double2, double3, ... , doublen]) All array's elements are successive in memory. I want to use a HDF file as a data container (save / load).</p> <p>save is implemented as: hdf.create_dataset(name='data', data=np.array([double1, double2, double3, ... , doublen]))</p...
<p>The variable dtype remains unchanged throughout the process. You can verify by checking dtype as you go. Code below demonstrates behavior. (I created variable <code>arr</code> to hold the array of np.doubles before loading to HDF5.)</p> <pre><code>double1 = np.double(1) double2 = np.double(2) double3 = np.double(3)...
python|numpy|h5py|hdf
0
4,126
56,050,604
How to makeup FSNS dataset with my own image for attention OCR tensorflow model
<p>I want to apply attention-ocr to detect all digits on number board of cars. I've read your README.md of attention_ocr on github(<a href="https://github.com/tensorflow/models/tree/master/research/attention_ocr" rel="nofollow noreferrer">https://github.com/tensorflow/models/tree/master/research/attention_ocr</a>), and...
<p>Please reread the <a href="https://stackoverflow.com/a/44461910/743658">mentioned answer</a> it has a section explaining how to store the annotation. It is stored in the three features <code>image/text</code>, <code>image/class</code> and <code>image/unpadded_class</code>. The <code>image/text</code> field is used f...
tensorflow|dataset|ocr|attention-model
0
4,127
56,066,544
Creating a Clustered Bar chart with Matplotlib
<p>This is extremely trivial, so I apologize!</p> <p>I'm just getting into matplotlib and pandas and I think I'm over complicating it... I'm trying to create a clustered bar chart (like the one below).</p> <p><a href="https://i.stack.imgur.com/d4o3F.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d...
<p>Try this:</p> <pre><code>new_df = (df.groupby('Days of Week')['Type'] .value_counts() .unstack() ) new_df.plot.bar() </code></pre>
python|pandas|matplotlib
0
4,128
55,765,320
Incorrect output: Extracting text from pdf's,docx's pptx's will not output in their own spearte line
<p>I created a function that will open each file in a directory and extract the text from each file and output it in an excel sheet using Pandas. The indexing for each file type seems to be working just fine.However the extracted text from each file comes out next to each other in a list and not separated and next to t...
<p>The appends called by each filetype_out function look like they are adding the contents of each file to the end of the list pertaining to that filetype. If you want to generate a unique list with the contents of each individual file, I'd recommend creating a separate <a href="https://stackoverflow.com/questions/1024...
python|pandas|anaconda|pdfminer|pathlib
1
4,129
64,750,931
Compared grouped minimum of one column to a group of timestamps in pandas
<p>I have the following dataframe (extract only for one value of id3):</p> <pre><code>id1 id2 id3 id4 id5 id6 status id7 max_snsr_ts max_ts_fs k 292 346 1041 656 578 5780 on 53 10/21/2020 23:59 10/22/2020 23:30 48 292 346 1041 657 708 7080 on 53 10/21/2020 23:59 10/22/20...
<p>If want compare original columns use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> for Series with same size like original filled by aggregated values, also <code>np.where</code> is here not ...
python|pandas|pandas-groupby
0
4,130
64,790,864
Problem with new_row = dict.fromkeys(df, 0) statement
<p><a href="https://i.stack.imgur.com/xhqY9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xhqY9.png" alt="2nd name should be under name category" /></a></p> <p>Here is the code snippet:</p> <pre><code>df = pd.read_csv(&quot;data.csv&quot;) new_row = dict.fromkeys(df, 0) new_row[df.columns[0]] =...
<p>Why append the new DataFrame, you can just assign to the original DF columns:</p> <pre><code>df[df.columns[0]] = filename df[df.columns[326]] = &quot;Scanware&quot; </code></pre> <p>And while exporting the DataFrame to CSV you can add <code>index=False</code> argument to the <code>.to_csv()</code></p>
python|pandas
0
4,131
64,817,970
list index out of range when crawling data and adjust data
<p>I am trying to crawl data from a list of url (1st loop) . And in each url (2nd loop), I want to adjust the product_reviews['reviews'] ( list) by adding more data. Here is my code :</p> <pre><code>import requests import pandas as pd df = pd.read_excel(r'C:\ids.xlsx') ids = df['ids'].values.tolist() link = 'https://...
<p>Please, in the future, try to create a <a href="https://stackoverflow.com/help/minimal-reproducible-example">Minimal, Reproducible Example</a>. We don't have access to your 'ids.xlsx' so we can't verify if the problem is with a specific id in your list or a general problem.</p> <p>Taking a random id, <code>338661983...
python|pandas|web-scraping|request|web-crawler
1
4,132
65,042,321
BeautifulSoup find.all() web scraping returns empty
<p>When trying to scrape multiple pages of this website, I get no content in return. I usually check to make sure all the lists I'm creating are of equal length, but all are coming back as <code>len = 0</code>.</p> <p>I've used similar code to scrape other websites, so why does this code not work correctly?</p> <p>Some...
<p>As commented you probably need to use Selenium. You could replace the requests lib and replace the request statements with sth like this:</p> <pre><code>from selenium import webdriver wd = webdriver.Chrome('pathToChromeDriver') # or any other Browser driver wd.get(url) # instead of requests.get() soup = BeautifulS...
python|pandas|dataframe|web-scraping|beautifulsoup
1
4,133
40,215,510
ValueError: Unknown label type: array while using Decision Tree Classifier and using a custom dataset
<p>Given below is my code</p> <pre><code>dataset = np.genfromtxt('train_py.csv', dtype=float, delimiter=",") X_train, X_test, y_train, y_test = train_test_split(dataset[:,:-1],dataset[:,-1], test_size=0.2,random_state=0) model = tree.DecisionTreeClassifier(criterion='gini') #y_train = y_train.tolist() #X_train = X_tra...
<p>python (scikit-learn) expects you to pass something that is label-like, thus: integer, string, etc. floats are not a typical encoding form of finite space, they are used for regression.</p> <p>docu: <a href="http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.Decis...
python|numpy|scikit-learn|decision-tree
8
4,134
41,058,760
Subtract a different reference value for each group of rows in pandas
<p>I searched and found this answer which is close but I can't quite see how to apply it to my own situation, as my reference values are not stored within the same dataframe. </p> <p><a href="https://stackoverflow.com/questions/30258974/subtracting-group-specific-value-from-rows-in-pandas?noredirect=1&amp;lq=1">Subtra...
<p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a> column <code>Nucleus</code> by <code>dict</code> and then substract by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sub.html" rel="nofollow nor...
python|pandas|dataframe
3
4,135
53,815,562
How to use TensorFlow tf.print with non capital p?
<p>I have some TensorFlow code in a custom loss function.</p> <p>I'm using <code>tf.Print(node, [debug1, debug2], "print my debugs: ")</code></p> <p>It works fine but TF says <code>tf.Print</code> is depricated and will be removed once i update TensorFlow and that i should be using <code>tf.**p**rint()</code>, with s...
<p>Both the documentation of <a href="https://www.tensorflow.org/api_docs/python/tf/print" rel="noreferrer"><code>tf.print</code></a> and <a href="https://www.tensorflow.org/api_docs/python/tf/Print" rel="noreferrer"><code>tf.Print</code></a> mention that <code>tf.print</code> returns an operation with no output, so it...
python|tensorflow|keras
7
4,136
53,878,992
Dict of two non-header rows in pandas
<p>I have a dataframe that I need to keep without a header, and have the header on the first row. What would be the best way to create a <code>dict</code> of those two rows. For example:</p> <pre><code>df.loc[0:1] </code></pre> <p>Currently I would do something like:</p> <pre><code>dict(zip(df.loc[0].tolist(), df.lo...
<p>Use <code>header=None</code> in the <code>read_csv</code> function. Like so:</p> <pre><code>df = pd.read_csv(path_to_file,header = None) </code></pre> <p>Check the docs <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer">read_csv</a>.</p> <p>Then to crea...
python|pandas
0
4,137
66,221,070
is there a pandas function for evaluating values in different columns with a rolling function?
<pre><code>import pandas as pd import numpy as np # setting up the dataframe data = [ ['day 1','day 2', 2, 50], ['day 2','day 4', 2, 60], ['day 3','day 3', 1, 45], ['day 4','day 7', 2, 45], ['day 5','day 10', 3, 90], ['day 6','day 7', 3, 10], ['day ...
<p>This is less technology and more business modelling</p> <ul> <li>really you are looking at accounting concepts</li> <li>an approach is to consider the data as payables and receivables</li> <li>then you can run whatever rolling functions you want after modelling using these basic accounting business concepts</li> </u...
python|pandas
0
4,138
65,924,090
SimpleTransformers Error: VersionConflict: tokenizers==0.9.4? How do I fix this?
<p>I'm trying to execute the simpletransformers example from their site on google colab.</p> <p>Example:</p> <pre><code>from simpletransformers.classification import ClassificationModel, ClassificationArgs import pandas as pd import logging logging.basicConfig(level=logging.INFO) transformers_logger = logging.getLogg...
<p>I am putting this here incase someone faces the same problem. I was helped by the creator himself.</p> <blockquote> <pre><code>Workaround: Install tokenizers==0.9.4 before install simpletransformers In Colab for example; !pip install tokenizers==0.9.4 !pip install simpletransformers </code></pre> <p><a href="https...
tensorflow|nlp|bert-language-model|simpletransformers|sentence-transformers
3
4,139
52,482,115
Tensorflow histogram with custom bins
<p>I have two tensors - one with bin specification and the other one with observed values. I'd like to count how many values are in each bin. I know how to do this in either NumPy or bare Python, but I need to do this in <em>pure TensorFlow</em>. Is there a more sophisticated version of <code>tf.histogram_fixed_width</...
<p>This seems to work, although I consider it to be quite memory- and time-consuming. </p> <pre><code>import tensorflow as tf bins = [-1000, 1, 3, 10000] vals = [-3, 0, 2, 4, 5, 10, 12] vals = tf.constant(vals, dtype=tf.float64, name="values") bins = tf.constant(bins, dtype=tf.float64, name="bins") resh_bins = tf.r...
python-3.x|tensorflow
2
4,140
46,467,416
How to reshape a multi-column dataframe by index?
<p>Following from <a href="https://stackoverflow.com/questions/45677788/how-to-reshape-dataframe-if-they-have-same-index?noredirect=1#comment79889384_45677788">here</a> . The solution works for only one column. How to improve the solution for multiple columns. i.e If I have a dataframe like</p> <pre><code>df= pd.Data...
<p>Use <code>flatten/ravel</code></p> <pre><code>In [4401]: df.groupby(level=0).apply(lambda x: pd.Series(x.values.flatten())) Out[4401]: 0 1 2 3 0 a b b c 1 c z d b </code></pre> <p>Or, <code>stack</code></p> <pre><code>In [4413]: df.groupby(level=0).apply(lambda x: pd.Series(x.stack().values)) Out[44...
python|pandas|numpy|dataframe
3
4,141
58,576,772
How do i merge table index name using pandas in python?
<p>I want to set two columns with their index in a single index. But i can not merge table index. How could i merge table index using pandas or row python code? </p> <p>I tried and get this <a href="https://ibb.co/7nZyxCM" rel="nofollow noreferrer">https://ibb.co/7nZyxCM</a></p> <p>Here is the sample code using Prett...
<p>You can create the new MultiIndex (to be used for columns) e.g. from tuples:</p> <pre><code>cols = pd.MultiIndex.from_tuples([ ('August', 'Invoice'), ('August', 'Sells'), ('September', 'Invoice'), ('September', 'Sells'), ('Growth', '1'), ('Growth', '2') ]) </code></pre> <p>Then just set it as <em>colu...
python|pandas|prettytable
1
4,142
69,279,946
Why dataframe exports only last value of iteration to csv? (Python)
<p>I am exporting results from dataframe to CSV, but it only exports the last value of the iteration. Please check my code and let me know, where I am doing wrong. Thank you for your support.</p> <pre><code>from pyswmm import Simulation, LidGroups, Nodes from pyswmm.swmm5 import SWMMException import os import pandas as...
<p>In each iteration over <code>results</code> you write to csv file overwriting the previous file. Not sure if that's what you want, but specify <code>mode='a'</code> in <code>to_csv()</code>. The default mode is <code>w</code></p> <p><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html" ...
python|pandas|dataframe|csv
0
4,143
69,233,364
Why does Matplotlib saved figure look weird?
<p>I am using the plotting pandas data frame and, saved the resulting figure using the following code. The output file looks weird when opened in image viewer as shown here.I don't understand why the background is not fully white.</p> <p>I am using Linux OS called Zorin, which is a derivative of Ubuntu if that makes a ...
<p>This is the default behaviour, you can set the background color using: <code>fig.patch.set_facecolor('white')</code></p>
python-3.x|pandas|matplotlib
0
4,144
69,233,701
Finding the coordinates of pixels over a line in an image
<p>I have an image represented as a 2D array. I would like to get the coordinates of pixels over a line from point 1 to point 2.</p> <p>For example, let's say I have an image with size 5x4 like in the image below. And I have a line from point 1 at coordinates <code>(0, 2)</code> to point 2 at <code>(4, 1)</code>. Like ...
<p>You can do this with <a href="https://scikit-image.org/docs/dev/api/skimage.draw.html?highlight=line#skimage.draw.line" rel="nofollow noreferrer">scikit-image</a>:</p> <pre><code>from skimage.draw import line # Get coordinates, r=rows, c=cols of your line rr, cc = line(0,2,4,1) print(list(zip(rr,cc))) [(0, 2), (1,...
python|numpy|image-processing
3
4,145
60,907,540
Use of 1W offset - Would like that offset by one week pushes current TS to begining of next week
<h1>Initial problem statement</h1> <p>Given timestamp '2020-03-24 10:00' (a Tuesday), I would like to get next week start (Monday 00:00) by use of a week DateOffset.</p> <p>I intend to understand the way DateOffset work.</p> <p>Here are my attempts, all failing so far.</p> <pre><code># ts being timestamp for Tuesda...
<p>Please, consider this code:</p> <pre><code># ts being timestamp for Tuesday the 24th ts = pd.Timestamp('2020-03-24 10:00') # use right offset to start with monday off1 = pd.tseries.frequencies.to_offset('W-MON') # add values ts1 = ts + off1 # call normalize to start at midnight ts1 = ts1.normalize() </code></pre> ...
python|pandas|timestamp
1
4,146
71,635,940
Move a set of rows of a dataframe to the beginning
<p>I want to move a set of dataframe rows to the beginning</p> <p>The indexes of the corresponding rows are these ones:</p> <pre><code>indexes = [2188, 2163, 37, 47, 36, 41, 61, 1009, 40, 39, 123, 121, 2151, 19, 2, 8, 117, 205, 204] </code></pre> <p>So:</p> <pre><code>index 204 -&gt; index 0 index 205 -&gt; index 1 . ....
<p>Here's an approach that reindexes the DataFrame based on using sets theory to create a new set list from indexes. This partially assumes that the indexes will be unique.</p> <pre><code>import pandas as pd ## sample DataFrame d = {'col1': [0, 1, 2, 3, 4], 'col2': [4, 5, 6, 9, 5], 'col3': [7, 8, 12, 1, 11]} df = pd.D...
python|pandas|dataframe
1
4,147
71,510,471
numpy.eigh and matlab give inconsistent answers for eigenvectors?
<p>I'm writing a code that diagonalizes a 4x4 hermitian matrix. It's a simple enough code but the eigenvectors given by matlab and numpy disagree wildly.</p> <p>Reproducible code:</p> <pre><code>import numpy as np # symbreak_h_bound generates a 4x4 matrix based on input kpt, then returns the eigenvals and eigenvecs w,...
<p>The <code>v</code> in your example is quite close to orthogonal.</p> <pre class="lang-python prettyprint-override"><code>&gt; v.H*v matrix([[ 1.00000000e+00 +0.00000000e+00j, 2.49800181e-16 +0.00000000e+00j, -1.11022302e-16 +4.16333634e-17j, -1.94289029e-16 +3.46944695e-17j], ...
python|numpy|matlab|linear-algebra
2
4,148
69,981,281
Create count for series of values grouped by specific column in Python
<p>I have a dataset, df, where I would like to create a count for a series of values grouped by specific column in Python</p> <p><strong>Data</strong></p> <pre><code>id date type aa q1 23 hi aa q1 23 hi aa q1 23 bye aa q1 23 bye aa q2 23 hi aa q2 23 bye bb q1 23 hi </code></pr...
<p>You can use:</p> <pre><code>df['count'] = df['type'] + df.groupby([*df]).cumcount().add(1).astype(str).str.zfill(2) </code></pre> <p>Output:</p> <pre><code> id date type count 0 aa q1 23 hi hi01 1 aa q1 23 hi hi02 2 aa q1 23 bye bye01 3 aa q1 23 bye bye02 4 aa q2 23 hi hi01 5 aa q2 2...
python|pandas|numpy
3
4,149
69,777,346
how to use np.diff with reference point in python
<p>I have a dataset given with time stamps.</p> <pre><code>import pandas as pd data = pd.DataFrame({'date': pd.to_datetime(['1992-01-01', '1992-02-01', '1992-03-01', '1992-04-01', '1992-05-01']), 'sales': [10...
<p>We can use the <code>prepend</code> parameter of <a href="https://numpy.org/doc/stable/reference/generated/numpy.diff.html" rel="nofollow noreferrer"><code>np.diff</code></a> to set the reference value (4100) at the beginning of the Series:</p> <pre><code>reference_value = 4100 data['diff_price'] = np.diff(data['pri...
python|pandas|diff|np
1
4,150
69,970,206
How can I apply an expanding window to the names of groupby results?
<p>I would like to use pandas to group a dataframe by one column, and then run an expanding window calculation on the groups. Imagine the following dataframe:</p> <pre><code>G Val A 0 A 1 A 2 B 3 B 4 C 5 C 6 C 7 </code></pre> <p>What I am looking for is a way to group the data by column <code>G</code> (resulting in g...
<p><code>cummean</code> not exist, so possible solution is aggregate <code>counts</code> and <code>sum</code>, use cumulative sum and for mean divide:</p> <pre><code>df = df.groupby('G')['Val'].agg(['size', 'sum']).cumsum() s = df['sum'].div(df['size']) print (s) A 1.0 B 2.0 C 3.5 dtype: float64 </code></pre> ...
pandas|pandas-groupby
2
4,151
70,013,488
Why does model training take significantly way longer when I include validation data?
<p>Obviously, I know that adding in validation data would make training take longer but the time difference I am talking here is absurd. Code:</p> <pre><code># Training def training(self, callback_bool): if callback_bool: callback_list = [] else: callback_list = [] s...
<p>I assume validation works as intended, and you have a problem in the training process itself. You are using batch_size = 1 and steps_per_epoch = 10, which means <strong>the model will see only 10 data points during every epoch</strong>. That's why it takes only few seconds. On the other hand, you don't use the valid...
python|tensorflow|machine-learning|keras|scikit-learn
3
4,152
69,974,412
What's a good way of setting most elements of an ndarray to zero?
<p>I've got an <code>ndarray</code> with, say, 10,000 rows and 75 columns, and another one with the same number of rows and, say, 3 columns. The second one has integer values.</p> <p>I want to end up with an array of 10,000 rows and 75 columns with all the elements set to zero except the elements in each row indexed by...
<p>It seems like you are looking for something similar to <code>np.put_along_axis</code></p> <p>Taking the example you have there if you run: <code>np.put_along_axis(z_array, i_array, 0, axis=1)</code></p> <pre><code>z_array = [[ 0 11 0 13 14 15] [10 0 12 0 14 15] [10 0 12 13 0 15] [10 11 0 0 14 15]] </code><...
python|arrays|numpy|numpy-ndarray
1
4,153
43,264,153
How to find the output of a trained network for a random input in tensor flow?
<p>So I am trying to write a NN that predicts whether an input number is positive or negative, so I modelled this and trained, also checked the accuracy of it. But I can not use this model, to explicitly check whether a number is positive or negative. I can only, check the accuracy, I can not use this for individual in...
<p>You didn't sigmoid your output, that's the unscaled value, and it looks normal. The loss function is applying the sigmoid function to those values before applying cross entropy. The values you see there are the unscaled values you feed to the loss function. If you look at the numbers without applying sigmoid then al...
python|tensorflow|neural-network
0
4,154
43,396,135
Check that png image and csv file has the same name before processing them
<p>l have a dataset (5000 data) composed of images and csv files. Each image is mapped with its csv files. for instance <code>img_33e_78.png</code> is mapped with<code>img_33e_78.csv</code>. For each image l have a csv file which contains a given pixels to process. To do so l need to check that l'm processing the image...
<p>i suppose i would start with making sets of your images and csv files. i remove the file extensions because they are the real issue of comparing the files. This is done using a list comprehension. could also be done using map. </p> <pre><code>image_names = set([x.rsplit('.', 1)[0] for x in glob.glob('*.png')]) csv_...
python|string|csv|pandas|png
1
4,155
43,141,620
ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'dict'
<p>I'm trying to insert a dataframe using the query <br></p> <pre><code>engine = create_engine('scot://pswd:xyz@ hostnumb:port/db_name') dataframe.to_sql('table_name', engine, if_exists='replace') </code></pre> <p>but one column is a dictionary and I'm unable to insert it, only the column name is getting inserted. ...
<p>Try specifying the dtype. So in your example, you would say</p> <pre><code>dataframe.to_sql('table_name', engine, if_exists='replace',dtype = {'relevant_column':sqlalchemy.types.JSON}) </code></pre>
python|json|postgresql|pandas
5
4,156
45,559,846
How to remove deconvolution noise in style-transfer neural network
<p>Im studying style-transfer networks and right now working with this <a href="https://github.com/lengstrom/fast-style-transfer" rel="nofollow noreferrer">work</a> and here is <a href="https://github.com/lengstrom/fast-style-transfer/blob/master/src/transform.py" rel="nofollow noreferrer">network description</a>. The ...
<p>The <code>deconvolution</code> noise is because of the uneven overlaps between the input and the kernel which creates a checkerboard-like pattern of varying magnitudes. One fix is to use <code>resize-conv</code> method as mentioned in this <a href="https://distill.pub/2016/deconv-checkerboard/" rel="nofollow norefer...
machine-learning|tensorflow|neural-network|conv-neural-network|style-transfer
1
4,157
62,733,389
Image Segmentation Tensorflow tutorials
<p>In this <a href="https://www.tensorflow.org/tutorials/images/segmentation" rel="nofollow noreferrer">tf tutorial</a>, the U-net model has been divided into 2 parts, first contraction where they have used Mobilenet and it is not trainable. In second part, I'm not able to understand what all layers are being trained. ...
<p>The code for the <code>Image Segmentation Model</code>, from the <a href="https://www.tensorflow.org/tutorials/images/segmentation" rel="nofollow noreferrer">Tutorial</a> is shown below:</p> <pre><code>def unet_model(output_channels): inputs = tf.keras.layers.Input(shape=[128, 128, 3]) x = inputs # Downsampli...
tensorflow|conv-neural-network|image-segmentation|autoencoder|unet-neural-network
1
4,158
54,370,998
How to compare current excel cell to previous excel cell in same column
<p>I am trying to write a quick function to compare the current cell in a column to the cell just above (before) it. The idea is to perform a different operation on data that is in the same column but different value. </p> <pre><code>if (df.loc() != df.loc[::-1] &amp; df1.loc() != df1.loc[:-1]): df = df.iloc() df1 = d...
<p>Considering the below dataframe:</p> <pre><code>print(df) Connector Pin Adj. 0 F123 1 2 6 7 1 F123 2 1 3 6 7 8 2 F123 3 2 4 7 8 9 3 F123 4 3 5 8 9 10 4 F123 5 4 9 10 5 F123 6 1 2 7 6 F123 7 1 2 3 6 8 7 F123 8 ...
python|pandas
0
4,159
71,145,865
Dataframe doesn't modify in a for loop
<p>I have this for loop and I would like to change the value of a part of a df.</p> <pre><code>for col in last_df: last_df.loc[last_df[col]!=0, col]='stop' stop=last_df[last_df[col]=='stop'][col].index[0] last_df[col].loc[:(stop-1)]='NaN' </code></pre> <p>At the end, the last_df doesn't modify, the error I...
<p>Try without the loc.</p> <pre><code>for col in last_df: last_df[last_df[col]!=0]='stop' stop=last_df[last_df[col]=='stop'][col].index[0] last_df[col][:(stop-1)]='NaN' </code></pre> <p>this is a issue with view and copy of the DataFrame for more information quick understand you can read in th...
python|pandas|dataframe|for-loop|copy
2
4,160
52,137,745
How to mask some cells of a heatmap plot?
<p>I plotted the following heatmap: <a href="https://i.stack.imgur.com/p0Twi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p0Twi.png" alt="enter image description here" /></a></p> <p>using this code:</p> <pre><code>data = {'Month':['August','August','August','August','August','August','August','Aug...
<p>I believe need filter <code>DataFrame</code> by subset of list of columns name:</p> <p>So change:</p> <pre><code>sns.heatmap(corr, annot=kwargs.get('annot',True), fmt=kwargs.get('fmt','.2f')) </code></pre> <p>to:</p> <pre><code>c1 = ['WorkingHours','Temperature'] c2 = ['Day','Month'] sns.heatmap(corr.loc[c1, c2]...
python-3.x|pandas|data-visualization|visualization|heatmap
1
4,161
52,266,352
Converting a long list of sequence of 0's and 1's into a numpy array or pandas dataframe
<p>I have a very long list of sequences(suppose of length 16 each) consisting of 0 and 1. e.g.</p> <pre><code>s = ['0100100000010111', '1100100010010101', '1100100000010000', '0111100011110111', '1111100011010111'] </code></pre> <p>Now I want to treat each bit as a feature so I need to convert it into numpy array or ...
<p>Using the <code>np.array</code> constructor and a list comprehension:</p> <pre><code>np.array([list(row) for row in s], dtype=int) </code></pre> <p></p> <pre><code>array([[0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1], [1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1], [1, 1, 0, 0, 1, 0, 0, 0, 0, 0...
python|string|python-3.x|pandas|numpy
3
4,162
52,392,953
Find and remove rows in 1 data frame that do not exist in another using python pandas
<p>I have 2 csv files of different length. I need to find and remove the rows in one file that do not exist in the other file. Is there an easy way to do this, other than looping through the 2nd file n times?</p>
<p>Assuming you load your csv file into df1, and df2</p> <pre><code>df1[df1.apply(tuple,1).isin(df2.apply(tuple,1))] </code></pre>
pandas
1
4,163
60,450,235
Grouping data based on month wise as a column and row with user data using pandas dataframe
<p>I have few doubts with subsetting grouping the data.</p> <p>My actual data format looks like this </p> <pre><code> month userId usage_count userEmail January aabzhlxycj 2 jakiyah@academy.com January aacuvynjwq 1 jack@gmail.com December aabzhlxycj 2 jakiya...
<p>You can use a pivot table:</p> <pre><code>import pandas as pd result = pd.pivot_table(df, values="usage_count", index=["userId", "userEmail"], columns="month").fillna(0).reset_index() print(result) </code></pre> <p>Output:</p> <pre><code>month userId userEmail December January 0 aabzhlxycj...
python|pandas|dataframe|grouping|data-manipulation
0
4,164
60,577,492
How can I get predicted the following value of stock using predict method of Tensorflow?
<p>I am wondering how to predict and get future time series data after model training. I would like to get the values after N steps. I wonder if the time series data has been properly learned and predicted. How do I do this right to get the following(next) value? I want to get the next value using <code>model.predict</...
<p>In the Second approach, Output is not expected, as per my understanding, because of a small mistake in the code.</p> <p>The line of code,</p> <pre><code>a = y_val[-look_back:] </code></pre> <p>should be replaced by</p> <pre><code>look_back = 20 x = x_val_uni a = x[-look_back:] a.shape </code></pre> <p>In other ...
python|tensorflow|machine-learning|deep-learning|prediction
3
4,165
60,372,038
make syntax automatically from pandas table column
<p>I have the following Dataframe</p> <pre><code>NAME DDGNWW ABC 123 DEF 456 GHI 789 JKL 012 MNO 110 </code></pre> <p>Code to reproduce: </p> <pre><code>import pandas as pd df = pd.DataFrame([ ['ABC', 123], ['DEF', 456], ['GHI', 789], ['JKL', 12], ...
<p>You could use:</p> <pre><code>' OR '.join(df['DDGNWW'].apply(lambda x: '"DDGNWW"={}'.format(x))) </code></pre> <p>Orther way to do with or:</p> <pre><code>'"DDGNWW" IN ' + str(tuple(df['DDGNWW'])) </code></pre>
python|pandas|dataframe
0
4,166
72,721,956
dropout, recurrent_dropout in LSTM layer
<p>I am training a GRU neural network and added dropout and recurrent dropout in my GRU layer but since then I can't get reproducible results every time I run the program again and I can't fix this problem even with :</p> <pre><code>recurrent_initializer=tf.keras.initializers.Orthogonal(seed=42), kernel_initializer=tf...
<p>I had already set the seed at the beginning of the programme with:</p> <pre><code>import numpy as np import tensorflow as tf import random as rn np.random.seed(1) tf.random.set_seed(2) rn.seed(3) </code></pre> <p>but by adding before the 3 rows of seed fixation:</p> <pre><code>import os os.environ['PYTHONHASHSEED'] ...
tensorflow|keras|seed|dropout
0
4,167
72,538,480
Create column in dataframe that divides number by days in a month
<p>I have a Panda's DataFrame with a column of months and a column that gives a total for each month. What I need to do is divide the total for each month by the number of days in that month and put it in a new column.</p> <p>So something like this</p> <pre><code>Month Total Daily Total Nov. 2019 4...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.daysinmonth.html" rel="nofollow noreferrer">.dt.daysinmonth</a></p> <pre class="lang-py prettyprint-override"><code>df['Daily Total'] = df['Total'] / pd.to_datetime(df['Month']).dt.daysinmonth </code></pre> <pre><code>print(df) ...
python|pandas|date|divide
1
4,168
59,741,210
Image clustering - allocating memory on GPU
<p>I've written this code for image classification by pretrained googlenet:</p> <pre><code>gnet = models.googlenet(pretrained=True).cuda() transform = transforms.Compose([transforms.Resize(256), transforms.CenterCrop(32), transforms.ToTensor()]) images = {} resultDist = {} i = 1 for f in glob.iglob("/data/home/stude...
<p>Since you're not doing backprop wrap your whole loop with a <code>with torch.no_grad():</code> statement since otherwise a computation graph is created and intermittent results may be stored on the GPU for later application of backprop. This takes a fair amount of space. Also you probably want to save <code>out.cpu(...
python|image|classification|pytorch
0
4,169
59,726,576
Create different files based off value in dataframe column A and save to different existing folders based off value in dataframe column A
<ol> <li>First, I would like to create different files based off the value in dataframe column A <code>FTP_FOLDER_PATH</code></li> <li>Second, I would like to save these files to different folders depending on the value in dataframe column A 'FTP_FOLDER_PATH'. These folders already exist and do not need to be created.<...
<p>I discovered a minor basic error. I should have included <strong>/{i}</strong> in line 2. i would be the subfolder of the masterfolder in this case, so adding this in allows the files to go to their destinations, so that solves part two of my problem quite easily.</p> <pre><code>for i, x in df_joined.groupby('FTP_F...
python|pandas
0
4,170
59,495,151
Reading pandas from disk during concurrent process pool
<p>I've wrote a cli tool to generate simulations and i'm hoping to generate about 10k (~10 minutes) for each cut of data I have ~200. I have functions that do this fine in a for loop but when I converted it to <code>concurrent.futures.ProcessPoolExecutor()</code> I realized that multiple processes can't read in the sa...
<p>Three things I would try:</p> <ul> <li><p>Pandas has <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_parquet.html" rel="nofollow noreferrer">an option</a> for using either PyArrow or FastParquet when reading parquet files. Try using a different one - this seems to be a bug.</p></li> ...
python|python-3.x|pandas|concurrent.futures
2
4,171
59,677,007
I need to extract Ports for Vlan Id using Python
<pre><code>VLAN Name Status Ports ---- -------------------------------- --------- ------------------------------- 1 default active Po10, Po20, Po30, Po40, Po50 Eth1/1, Eth1/2, Eth1/3, Eth1/4 ...
<p>Your dictionary is not valid, if want dict of lists use:</p> <pre><code>d = df.set_index('VLAN')['Ports'].str.split(', ').to_dict() print (d) {1: ['Po10', 'Po20', 'Po30', 'Po40', 'Po50', 'Eth1/1', 'Eth1/2', 'Eth1/3', 'Eth1/4', 'Eth1/5', 'Eth1/6', 'Eth1/7', 'Eth1/8'], 2: ['Po10', 'Po20', 'Po30', 'Po40', 'Po5...
python|python-3.x|pandas
1
4,172
59,638,464
Efficient way to get row with closest timestamp to a given datetime in pandas
<p>I have a big dataframe that contains around 7,000,000 rows of time series data that looks like this</p> <pre><code>timestamp | values 2019-08-01 14:53:01 | 20.0 2019-08-01 14:53:55 | 29.0 2019-08-01 14:53:58 | 22.4 ... 2019-08-02 14:53:25 | 27.9 </code></pre> <p>I want to create a co...
<p>Hmmmm, not sure if this will work out to be more efficient, but <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer">merge_asof</a> is an approach worth looking at as won't require a udf. </p> <pre><code>df['date'] = df.timestamp.dt.date df2 = df.copy...
python|pandas|timestamp|time-series
1
4,173
61,775,334
Testing for a value in a MultiIndex
<p>I have a pandas data frame with a large MultiIndex. I'm selecting columns from this dataframe with various metadata that is in the index, like for example </p> <pre><code>current_row = df.xs(number, level='counter', drop_level=False, axis=1) </code></pre> <p>So far, so good. However, <code>number</code> comes from...
<p>Tried a search with some different keywords again* and of course it's rather easily done with <code>in</code>:</p> <pre><code>if number in df.columns.get_level_values('counter'): #do stuff else: #print my custom error </code></pre> <p>found for example <a href="https://stackoverflow.com/questions/24870306/...
pandas|multi-index
0
4,174
61,993,941
NoneType Error when trying to create new column from existing columns with Pandas on Jupyter Notebook
<p>so I recently tried to start using Jupyter notebooks, as I find they are far more convenient than me keeping lengthy comments in my code files.</p> <p>That being said to test out basic functionality I wanted to simulate moving averages. However, as the title says, I was unable to even create a new column using Pand...
<p>you need to handle your missing values, try</p> <pre><code>fb['MA10'] = fb['Close'].fillna(0).rolling(10).mean() </code></pre>
python|pandas|typeerror|iterable|nonetype
1
4,175
57,874,436
Tensorflow Data Adapter Error: ValueError: Failed to find data adapter that can handle input
<p>While running a sentdex tutorial script of a cryptocurrency RNN, link here</p> <p><a href="https://www.youtube.com/watch?v=yWkpRdpOiPY&amp;list=PLQVvvaa0QuDfhTox0AjmQ6tvTgMBZBEXN&amp;index=11" rel="noreferrer">YouTube Tutorial: Cryptocurrency-predicting RNN Model</a>,</p> <p>but have encountered an error when atte...
<p>Have you checked whether your training/testing data and training/testing labels are all numpy arrays? It might be that you're mixing numpy arrays with lists. </p>
python|tensorflow|keras|lstm
89
4,176
54,994,658
How does pytorch's nn.Module register submodule?
<blockquote> <p>When I read the source code(python) of torch.nn.Module , I found the attribute <code>self._modules</code> has been used in many functions like <code>self.modules(), self.children()</code>, etc. However, I didn't find any functions updating it. So, where will the <code>self._modules</code> be upd...
<p>Add some details to Jiren Jin's answer:</p> <ul> <li><p>Layers of a net (inherited from <code>nn.Module</code>) are stored in <code>Module._modules</code>, which is initialized in <code>__construct</code>:</p> <pre class="lang-py prettyprint-override"><code>def __init__(self): self.__construct() # initiali...
python|pytorch
4
4,177
54,854,356
Keras LSTM How to loop for predict by model.predict()
<p>I want to predict lstm 7 time. I have to get output from model.predict() and use the output to predict again to 7 time. </p> <p>This is code.</p> <pre><code>data = 0 y_pred=0 data[0] = model.predict(X_test_t) for i in range(7): data[i+1] = model.predict(data[i]) print(data) </code></pre> <p>when I run it ...
<p>You need to have a list for your data. Currently it is an int and you can't index an int. So you need to do </p> <pre><code>data =[] </code></pre> <p>And to append you do</p> <pre><code>data.append(model.predict(data[i])) </code></pre>
python|tensorflow|keras
0
4,178
73,208,925
Consolidate column values into one column as a list with column name as key in python
<p>I have data frame that looks like this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>id address city pincode 1 here is address 1 city1 1234 2 here is addr...
<p>Can be accomplished with <code>to_dict(orient='records')</code>:</p> <pre><code>import pandas as pd from io import StringIO # create dataframe data = StringIO(&quot;&quot;&quot;id;address;city;pincode 1;here is address 1;city1;1234 2;here is address 2;city2;4321 3;here is address 3;city3;7654 4;here is address 4;ci...
python|pandas|join|multiple-columns
1
4,179
73,256,800
Resampling a numpy array logarithmically
<p>I have a numpy array representing magnitudes of a fourier transform, and I want to resample it logarithmically:</p> <p>Lets say it was from 100hz to 10khz, and each bucket was 100hz, I want to take that discrete distribution, create a continuous distribution, and then resample that continuous distribution logarithmi...
<p>A possible implementation is given below. The <code>logspace()</code> routine from numpy creates the bucket boundaries and I subsequently draw a random index.</p> <pre><code>import random import numpy as np NumberOfBuckets = 10 LogGrid = np.logspace(2.0, 4.0, num=NumberOfBuckets) % 10^2 to 10^4 IntDraw = random.ran...
python|numpy
0
4,180
67,264,061
How to match ID between two columns?
<p>I have, I guess a simple question but I cannot find the right answer. I have two pandas series (let's say &quot;A&quot; and &quot;B&quot;) with ID in there (string). Series A is bigger than series B. What I am looking for is a way to have a resulting dataframe with 2 columns where the matching elements are on the sa...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.reindex.html" rel="nofollow noreferrer"><code>Series.reindex</code></a> with helper <code>Series</code> by index from values of <code>s2</code>:</p> <pre><code>df = pd.Series(s2.to_numpy(), index=s2).reindex(s1).rename_axis('A').res...
python|pandas
0
4,181
67,373,908
Reshaping a dataframe by splitting list to append rows
<p>What is the best way to reshape my dataframe please (split the list to new rows):</p> <pre><code>df = pd.DataFrame({'A': [[1,2], [1,2], 3], 'B': [x, y, z]}) A B 0 [1, 2] x 1 [1, 2] y 2 3 z </code></pre> <p>to the desired output:</p> <pre><code>out = pd.DataFrame({'A': [1, 2, 1, 2, 3], 'B': ...
<p>You can use <code>explode</code></p> <pre><code>df = df.explode('A') </code></pre> <p><strong>Output</strong></p> <pre><code> A B 0 1 x 0 2 x 1 1 y 1 2 y 2 3 z </code></pre>
python|pandas|dataframe
0
4,182
67,188,443
String splitting and joining on a pandas dataframe
<p>I have a dataframe containing devices and their corresponding firmware versions (e.g. 1.7.1.3). I'm trying to shorten the firmware version to only show three numbers (e.g. 1.7.1).</p> <p>I know how to do this on a single string but how would I make it efficient for a large dataframe?</p> <pre><code>test = &quot;1.2....
<pre><code>#sample dataframe: import pandas as pd df=pd.DataFrame({'data': {0: '1.2.3.4', 1: '1.2.3.9', 2: '1.2.3.8'}}) </code></pre> <p>For this you can use:</p> <pre><code>df['data']=df['data'].str.split('.').str[0:3].apply('.'.join) </code></pre> <p><strong>OR</strong></p> <pre><code>df['data']=df['data'].str[0:5] <...
python|pandas|dataframe|split
3
4,183
60,019,727
Adding legends into a Graph made using Matplotlib and Numpy (multiple plots from a txt file)
<p>I had some really good help from here when I asked a question before so I thought I'd jump on again to get some help, here's my code so far:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import os os.chdir("C:\Users\Chloe\Desktop") data=np.loadtxt("tree_rings.txt") for column in data.T[1:]: ...
<p>Does your data have column names? If so you can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="nofollow noreferrer"><code>np.genfromtxt()</code></a> like this:</p> <pre><code>data = np.genfromtxt('tree_rings.csv',delimiter=',',names=True) </code></pre> <p>To answer yo...
python|numpy|matplotlib|legend
0
4,184
59,915,944
Apply qcut for complete dataframe
<p>I want to replace the column values with bin numbers based on quantiles but for each and every column present in the dataframe.</p> <p>I know how to do this with qcut and labels as its parameter for a single column, but do not know whether it can be applied for complete dataframe or not. say the dataframe looks lik...
<p>you have to use pandas.cut() </p> <pre><code>import pandas as pd df['CC'] = pd.cut(df['CC'], [0, 5, 10,20]) </code></pre> <p>Similarly you can do for other columns as well.</p>
python|pandas|dataframe
0
4,185
65,095,801
reindex (1,N) dimension dataframe
<pre><code>A = pandas.DataFrame({&quot;A&quot; : [1, 4], &quot;Output1&quot; : [6, 8]}).set_index([&quot;A&quot;]).fillna(0) new_A = A.reindex(pandas.MultiIndex.from_tuples([['Output1', &quot;-&quot;]]) , axis=&quot;columns&quot;) </code></pre> <p>I'm expecting to get</p> <pre><code> Output1 - A 1 ...
<p>Don't use <code>reindex</code>, which aligns the columns by names. Just reassign the columns:</p> <pre><code>A.columns = pd.MultiIndex.from_tuples([['Output1', &quot;-&quot;]]) </code></pre> <p>Output:</p> <pre><code> Output1 - A 1 6 4 8 </code></pre>
pandas|dataframe|matrix|indexing|series
1
4,186
65,345,469
How do I save the tflearn logs into tflearn.model?
<p>So basically I forgot to save my model for each training loops. how do I save the /tmp/tflearn_logs/subdir into the model? is there any way to collect it as model like:</p> <pre><code># Save a model model.save('my_model.tflearn') </code></pre> <p>from the event logs?</p> <p>And after that I can automatically load it...
<p>Nevermind, There's no method to do that. Because logs only save our events data for visualization purpose, while model used for learning model using tflearn. they both working in the opposite way. Solution: Recreate save('.model.tflearn') and run it from 0. :)</p>
tensorflow|google-colaboratory|tflearn
0
4,187
65,095,890
group by pandas dataframe and select next upcoming date in each group
<p>Same question as here: <a href="https://stackoverflow.com/questions/41525911/group-by-pandas-dataframe-and-select-latest-in-each-group">group by pandas dataframe and select latest in each group</a>, except instead of latest date, would like to get next upcoming date for each group.</p> <p>So given a dataframe sorted...
<p>Filter the dates first, then drop duplicates:</p> <pre><code>df[df['date']&gt;'2020-12-01'].sort_values(['id','date']).drop_duplicates('id') </code></pre> <p>Output:</p> <pre><code> id product date 2 220 6647 2020-12-16 4 826 3380 2020-12-09 8 901 4555 2021-11-01 </code></pre>
python|pandas|datetime|pandas-groupby
0
4,188
65,406,713
Unflatten a tensor back to an image
<p>I am working on GANs and I want to visualize the image formed.</p> <p>For this, I was trying</p> <pre><code>def show_images(image_tensor, num_images=9, size=(1, 28, 28)): image_unflat = image_tensor.detach().cpu.view(-1, *size) image_grid = make_grid(image_unflat[:num_images], nrow=3) plt.imshow(image_gr...
<p>You need to call <a href="https://pytorch.org/docs/stable/tensors.html#torch.Tensor.cpu" rel="nofollow noreferrer"><code>cpu()</code></a> before broadcasting with <code>view</code>.</p> <pre><code>image_unflat = image_tensor.detach().cpu().view(-1, *size) </code></pre>
python|pytorch|tensor
1
4,189
50,092,322
get second largest value in row in selected columns in dataframe in pandas
<p>I have a dataframe with subset of it shown below. There are more columns to the right and left of the ones I am showing you </p> <pre><code>M_cols 10D_MA 30D_MA 50D_MA 100D_MA 200D_MA Max Min 2nd smallest 68.58 70.89 69.37 **68.24** 64.41 70.89 64.41 68.24 **68.32**71....
<p>For example you have following df </p> <pre><code>df=pd.DataFrame({'V1':[1,2,3],'V2':[3,2,1],'V3':[3,4,9]}) </code></pre> <p>After pick up the value need to compare , we just need to sort value by axis=0(default)</p> <pre><code>sortdf=pd.DataFrame(np.sort(df[['V1','V2','V3']].values)) sortdf Out[419]: 0 1 2...
pandas
5
4,190
50,119,131
Merge returns empty dataframe in pandas
<p>I run Python 3.6 on Windows 10.</p> <p>My code is the following:</p> <pre><code>data1 Loan_ID Gender 1 LP001003 Male 2 LP001005 Male 3 LP001006 Male 4 LP001008 Male 5 LP001011 Male data2 Loan_ID2 LoanAmount 1 LP001003 128.0 2 LP001005 66.0 3 LP001006 120.0 4 ...
<p>You do not need <code>right_index</code> within <code>merge</code></p> <pre><code>df1.merge(df2,left_on='Loan_ID',right_on='Loan_ID2') Out[54]: Loan_ID Gender Loan_ID2 LoanAmount 0 LP001003 Male LP001003 128.0 1 LP001005 Male LP001005 66.0 2 LP001006 Male LP001006 120.0 3 LP00...
python|pandas|merge
3
4,191
64,076,919
Pandas split a column of unequal length lists into multiple boolean columns
<p>Given a DataFrame <code>df1</code> as follows:</p> <pre><code>df1 = pd.DataFrame({ 'col1': [1,2,3,4], 'col2': [['a', 'b'], ['c'], ['a', 'd', 'b'], ['e']] }) </code></pre> <p>Which looks like:</p> <pre><code> col1 col2 0 1 [a, b] 1 2 [c] 2 3 [a, d, b] 3 4 [e] </code></pre...
<p>Alternative approach using <code>str.get_dummies</code> probably more efficient than <code>apply</code> + <code>pd.Series</code>:</p> <pre><code>df1['col2'].str.join(',').str.get_dummies(sep=',').astype(bool) </code></pre> <hr /> <pre><code> a b c d e 0 True True False False False 1 ...
python|pandas
4
4,192
46,976,483
Set initial value of a tf.Variable Python/TensorFlow
<p>I have this function:</p> <pre><code>def new_weights(shape): return tf.Variable(tf.truncated_normal(shape, stddev=0.05)) </code></pre> <p>And I call it like this, for example:</p> <pre><code># shape = [filter_size, filter_size, num_filters, num_input_channels] shape = [1, 1, 8, 1] weights = new_weights(shape...
<p>You can use assign function</p> <pre><code>shape = [1, 1, 8, 1] weights = new_weights(shape) ws = [1, 2, 3, 4, 5, 6, 7, 8] ws = np.array(ws).reshape(shape) weights = weights.assign(ws) </code></pre>
python|python-2.7|tensorflow
1
4,193
46,752,078
How to implement LSTM layer with multiple cells in Pytorch?
<p>I intend to implement an LSTM with 2 layers and 256 cells in each layer. I am trying to understand the PyTorch LSTM framework for the same. The variables in torch.nn.LSTM that I can edit are input_size, hidden_size, num_layers, bias, batch_first, dropout and bidirectional.</p> <p>However, how do I have multiple cel...
<p>These cells will be automatically unrolled based on your sequence size in the input. Please check out this code: </p> <pre class="lang-py prettyprint-override"><code># One cell RNN input_dim (4) -&gt; output_dim (2). sequence: 5, batch 3 # 3 batches 'hello', 'eolll', 'lleel' # rank = (3, 5, 4) inputs = Variable(tor...
deep-learning|lstm|pytorch
1
4,194
63,110,015
I don't understand Keras function "fit"
<p>When I was building a DataGenerator and trying to fit it into a model, it didn't work. So I've taken a look into the Keras function 'fit' directly. But I don't understand what this down below code is meaning especially backslash sign. May I ask what this code is for and how that works?</p> <pre><code>with self.distr...
<p>as far as I know, the &quot;\&quot; is just there for the <em><strong>linebreak</strong></em></p>
python|keras|tensorflow2.0|training-data|tf.keras
1
4,195
63,309,400
Get mean of lowest axis in a 3D array
<p>I have a 3D array and want to take the mean along <code>axis=0</code>. I tried to convert to a numpy array and do <code>arr.mean(axis=0)</code>, but that throws an error because the lists in <code>axis=2</code> do not have equal lengths.</p> <p>To reproduce:</p> <pre><code>arr = [[[0,1,2,3,4], [1,2,3,4,5], [2,3,4,5,...
<p>If you don't mind Tensoflow, you can do this with ragged tensors.</p> <pre><code>&gt;&gt;&gt; arr = tf.ragged.constant(arr) &gt;&gt;&gt; tf.reduce_mean(arr, axis=0).numpy() array([array([10., 11., 12., 13., 14.]), array([11., 12., 13., 14., 15.]), a...
python|python-3.x|list|numpy
1
4,196
67,944,611
merge_asof with multiple columns and forward direction
<p>I have 2 dataframes:</p> <pre><code>q = pd.DataFrame({'ID':[700,701,701,702,703,703,702],'TX':[0,0,1,0,0,1,1],'REF':[100,120,144,100,103,105,106]}) ID TX REF 0 700 0 100 1 701 0 120 2 701 1 144 3 702 0 100 4 703 0 103 5 703 1 105 6 702 1 106 </code></pre> <p>and</p> <pre><code>p =...
<p>Does this work?</p> <pre><code>pd.merge_asof(q.sort_values(['REF', 'ID']), p.sort_values(['REF', 'ID']), on='REF', direction='forward', by='ID').sort_values('ID') </code></pre> <p>Output:</p> <pre><code> ID TX REF NOTE 0 700 0 100 A 5 701 0 ...
python|pandas|merge
0
4,197
67,905,081
Integer Counter when value in next row changes
<p>I'm having a problem adding a &quot;counter column&quot; in my dataframe.</p> <p>I parsed values from multiple columns into so called &quot;merged_attributes&quot; and now I want to create a counter that increments by 1 when value of &quot;merged attributes&quot; columns changes.</p> <p>I have below dataframe, last ...
<p>Try the following:</p> <pre class="lang-py prettyprint-override"><code>df['COUNTER'] = df.groupby('MERGED_ATRIBUTE').ngroup() + 1 </code></pre> <p>This creates a group for each value of <code>MERGED_ATRIBUTE</code> and then uses <a href="https://pandas.pydata.org/pandas-docs/version/1.2.0/reference/api/pandas.core.g...
pandas|cumsum
0
4,198
67,971,947
Best approach to return multiple objs from function
<p>Lets say i have 2 classes , i want to take from class First two dfs, to second class, should I return them and unpack or use sefl.df and do not use return if i want to use those dfs in more than one function in other class?</p> <p>I can unpack but its only one per program runs and i cannot unpack two times same func...
<p>The &quot;best&quot; approach really depends on what you are trying to achieve and what restrictions you are dealing with (<em>and usually has a significant subjective component</em>). <br /> It doesn't seem to be clear whether flexibility or efficiency is more important from the information you have given, so here ...
python|pandas
0
4,199
68,026,764
Sum based on multiple columns with pandas groupby
<p>I want to create a new column that sums up the <em>value</em> column based on groupings of multiple columns. In this example I want to get the sum per <em>ISIN</em>, <em>date</em> and <em>portfolio</em>.</p> <pre><code>df = pd.DataFrame({&quot;ISIN&quot;: [&quot;IS123&quot;, &quot;IS123&quot;, &quot;UN123&quot;, &qu...
<p>Try <code>groupby</code> on the DataFrame instead of the Series (<code>value</code>) then select the column from the grouper:</p> <pre><code>df[&quot;Sum per ISIN, date and portfolio&quot;] = ( df.groupby([&quot;ISIN&quot;, &quot;date&quot;, &quot;portfolio&quot;])[&quot;value&quot;].transform(&quot;sum&quot;) )...
python|pandas|sum|pandas-groupby
1