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
350,300
32,947,781
Pandas sum integers separated by commas in a string column
<p>I have a pandas data frame with a column as type string, looking like:</p> <pre><code>1 1 2 3,1 3 1 4 1 5 2,1,2 6 1 7 1 8 1 9 1 10 4,3,1 </code></pre> <p>I want to sum all integers separated by the commas, obtaining as a result:</p> <pre><code>1...
<p>Use <code>apply</code> on column to do <code>df['B'].apply(lambda x: sum(map(int, x.split(','))))</code></p> <pre><code>In [81]: df Out[81]: A B ...
python|pandas
2
350,301
32,840,743
Excel Table into Organized Pandas Dataframe
<p>I have an excel worksheet with data stored in the following way.</p> <p><a href="https://i.stack.imgur.com/8wtTj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8wtTj.png" alt="enter image description here"></a></p> <p>I would like to organize this data into a Pandas dataframe so that it looks l...
<p>This is how I would tackle the problem with Python, though there may be a more elegant solution.</p> <p>First I would parse the Month/Year values using openpyxl</p> <pre><code>from openpyxl import load_workbook wb = load_workbook('data_so.xlsx') sheet_ranges = wb['Sheet1'] year = str(sheet_ranges['A1'].value) mo...
python|excel|pandas
1
350,302
33,059,190
python merge panda dataframes keep dates
<p>I'd like to merge two dataframes together but add in a column based on some logic. A simplified example of my dataframes are below:</p> <pre><code> DF_1: domain ttl nameserver file_date fakedomain.com 86400 ns1.fakedomain.com 8/8/2008 fakedomainz.com ...
<p>I am not sure which process produces these frames or whether it is a continuous stream of new data, but to just comment on the substance of the question, you could do like so:</p> <pre><code>import pandas as pd from StringIO import StringIO s1=""" domain ttl nameserver file_da...
python|pandas|merge
0
350,303
32,737,086
Python function to calculatate a new column using values from other columns in the dataframe
<p>My dataframe looks like this:</p> <pre><code>OrderID Status Amount Item 1000 complete 10 Item A 1000 complete 7 Item B 1000 refund -10 Item A 1000 refund -7 Item B 1001 complete 8 Item A 1002 complete...
<p>I am focusing on your sample data and your question</p> <p><em>I want to calculate #NetOrders (2 orders), NetAmount (14) and, maybe, AvgOrderValue (14/2=7).</em> </p> <pre><code>gp = df[['OrderID','Amount']].groupby('OrderID').sum() gp = gp[gp['Amount']!=0] print "#NetOrders: " + str(len(gp.index)) # it is groupe...
python|function|pandas
0
350,304
32,727,762
cut time spells into calendar months in pandas
<p>I have data on spells (hospital stays), each with a start and end date, but I want to count the number of days spent in hospital for calendar months. Of course, this number can be zero for months not appearing in a spell. But I cannot just attribute the length of each spell to the starting month, as longer spells ru...
<p>It's simpler than you think: just subtract the dates. The result is a time span. See <a href="https://stackoverflow.com/questions/22132525/add-column-with-number-of-days-between-dates-in-dataframe-pandas">Add column with number of days between dates in DataFrame pandas</a></p> <p>You even get to do this for the e...
python|date|pandas|calendar
-2
350,305
32,870,709
Conversion: np.array of indices to np.array of corresponding dict entries
<p>I have a numpy array of indices in <strong>Python 2.7</strong> that correspond to a value in a dictionary. So I want to create a numpy array of the corresponding values from the dictionary. The code might be clear immediately:</p> <pre><code>import numpy as np indices = np.array([(0, 1), (2, 0), (2, 0)], dtype=[('A...
<p>I believe you can use a list comprehension for this (it would be a bit faster than a normal <code>for</code> loop method). Example -</p> <pre><code>values = [d[tuple(a)] for a in indices] </code></pre> <p>Please note, I am using <code>d</code> instead of <code>dict</code>, since it would not be recommended to use ...
python|arrays|numpy
3
350,306
32,722,861
Using filter in pandas to get an exact match and partial match at the same time
<p>I have a dataframe that looks like this:</p> <pre><code>Y2000 Y2001 Y2002 Item Item Code 34 43 65 12 Test </code></pre> <p>I want to extract the columns Y2000, Y2001, Y2002 and Item. I do not want to extract the 'Item Code' column. How do I do this without explicitly specifying col...
<p>IIUC then you can use a regex pattern:</p> <pre><code>In [2]: df = pd.DataFrame(columns=['Y2000','Y2001','Y2002','Item','Item Code']) df Out[2]: Empty DataFrame Columns: [Y2000, Y2001, Y2002, Item, Item Code] Index: [] In [8]: df.filter(regex='^Y\d{4}$|^Item$') Out[8]: Empty DataFrame Columns: [Y2000, Y2001, Y20...
python|pandas
1
350,307
32,915,172
How to write a list of tuple in python with header mapping
<p>I have to process python list of tuples where each tuple contains header name as below- I want all the tuple will be mapped to respectives header in that tuple.</p> <pre><code> [[(u'Index', u' Broad Market Indices :')], [(u'Index', u'CNX NIFTY'), (u'Current', u'7,950.90'), (u'% Change', u'0.03'), (u'Open', u...
<p>I found workaround at last-</p> <p>Convert nested lists into dictionary and use dictwriter-</p> <pre><code>import csv my_d = [] for i in datalist: my_d.append({x:y for x,y in i}) with open("file.csv",'wb') as f: # Using dictionary keys as fieldnames for the CSV file header writer = csv.DictWriter(f, my_...
list|python-2.7|csv|pandas|tuples
0
350,308
32,766,438
Get CParserError. Does pandas post a limit to the maximum size of a value in a cell?
<p>I have been trying to use pandas to analyze some genomics data. When reading a csv, I get the <code>CParserError: Error tokenizing data. C error: out of memory</code> error, and I have narrowed down to the particular line that causes it, which is 43452. As shown below, the error doesn't happen until the parser goes ...
<p>Well, the last line says it all, it doesn't have enough memory to split a chunk of data. I'm not sure how the archive block reading works and how much data it loads into memory, but it's clear that you will have to somehow control the size of the chunks. I found a solution here:</p> <p><a href="https://stackoverflo...
python|csv|pandas|bioinformatics
0
350,309
38,805,326
Confirmation that I am not training on test set here
<p>I am new to tensorflow and just wanted to clarify that I am not training on the test set if I don't call for the optimization node in the graph.</p> <p>Here is an optimizer node; </p> <pre><code>opt = tf.train.GradientDescentOptimizer(learning_rate = learning_rate) opt_operation = opt.minimize(mse) </code></pre> ...
<p>Yes, correct. The training step is executed only when <code>opt_operation</code> is performed.</p> <p>Your last step:</p> <pre><code>loss,score = sess.run([mse,diceScore], feed_dict={x:batchX,y_:batchY}) </code></pre> <p>Evaluates only the <code>mse</code> and the <code>diceScore</code> tensors:...
tensorflow
1
350,310
38,681,821
Reshape pandas dataframe from rows to columns
<p>I'm trying to reshape my data. At first glance, it sounds like a transpose, but it's not. I tried melts, stack/unstack, joins, etc.</p> <p><strong>Use Case</strong></p> <p>I want to have only one row per unique individual, and put all job history on the columns. For clients, it can be easier to read information ac...
<p><code>.T</code> within <code>groupby</code></p> <pre><code>def tgrp(df): df = df.drop('Name', axis=1) return df.reset_index(drop=True).T df2.groupby('Name').apply(tgrp).unstack() </code></pre> <p><a href="https://i.stack.imgur.com/4b3Nx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4b3Nx.png" ...
python|pandas|dataframe|reshape|pandas-groupby
9
350,311
38,961,547
Unicode in the standard TensorFlow format
<p>Following the documentation <a href="https://www.tensorflow.org/versions/r0.10/how_tos/reading_data/index.html#standard-tensorflow-format" rel="noreferrer">here</a>, I am trying to create features from unicode strings. Here is what the feature creation method looks like,</p> <pre><code>def _bytes_feature(value): ...
<p>BytesList <a href="https://github.com/tensorflow/tensorflow/blob/89e1cc59681b78e8193f899dca16474c19a7fc5b/tensorflow/core/example/feature.proto#L65" rel="noreferrer">definition</a> is in feature.proto and it is of type <code>repeated bytes</code>, this means that you need to pass it something that's convertible to a...
python|unicode|tensorflow|protocol-buffers
6
350,312
38,898,828
Drawing circles around a certain area with opencv
<p>I am working on a code which accesses my camera, turns the output into grayscale, applies a gaussian blur finds the brightest area/pixel and circles it. Everything but the drawing-a-circle-part works fine. The command I am trying to use does nothing for me. Does anybody have an idea? I am working with opencv, pyth...
<p>You are trying to draw a colour circle on gray image , instead you can make the circle on the original colour frame</p> <pre><code>cv2.circle(frame, maxLoc, 10, (255, 0, 0) ) cv2.imshow("spot",frame) </code></pre>
python|opencv|numpy|camera|gaussianblur
0
350,313
38,540,144
pandas ImportError C extension when io.py in same directory
<p>Not sure if this is a pandas issue, or my lack of understanding with absolute/relative imports.</p> <pre><code>$ python -c "import pandas; print pandas.__version__" 0.17.1 $ python -V Python 2.7.12 :: Anaconda 2.4.1 (x86_64) # this runs fine (ie it doesn't raise exception) $ mkdir x; echo "import pandas" &gt; x/ma...
<p>By default, the first element of <code>sys.path</code> is an empty string, which means the directory of the top-level script. So if you have any modules in that directory with the same name as a standard library module, they will override the standard module. </p>
python|numpy|pandas|importerror
2
350,314
38,657,138
scikits learn SVM - 1-dimensional Separating Hyperplane
<p>How to plot the separating "hyperplane" for 1-dimensional data using scikit svm ?</p> <p>I follow this guide for 2-dimensional data : <a href="http://scikit-learn.org/stable/auto_examples/svm/plot_svm_margin.html" rel="nofollow">http://scikit-learn.org/stable/auto_examples/svm/plot_svm_margin.html</a>, but don't kn...
<p>The separating hyperplane for two-dimensional data is a line, whereas for one-dimensional data the hyperplane boils down to a point. The easiest way to plot the separating hyperplane for one-dimensional data is a bit of a hack: the <strong>data are made two-dimensional</strong> by adding a second feature which takes...
python|numpy|matplotlib|scikit-learn|svm
5
350,315
38,678,520
Merge every dataframe in a folder
<p>I have <code>.csv</code> files within multiple folders which look like this:</p> <p>File1</p> <pre><code>Count 2002_Crop_1 2002_Crop_2 Ecoregion 20 Corn Soy 46 15 Barley Oats 46 </code></pre> <p>File 2</p> <pre><code>Count 2003_Crop_1 2003_Crop_2 Ecoreg...
<ul> <li><p>Use <code>glob.glob</code> to <a href="https://stackoverflow.com/a/7159726/190597">traverse a directory at a fixed depth</a>.</p></li> <li><p>Try to avoid calling <code>pd.merge</code> repeatedly if you can help it. Each call to <code>pd.merge</code> creates a new DataFrame. So all the data in each intermed...
python|csv|pandas
2
350,316
38,740,495
Transform numpy array to RGB image array
<p>Consider the following code:</p> <pre><code>import numpy as np rand_matrix = np.random.rand(10,10) </code></pre> <p>which generates a 10x10 random matrix.</p> <p>Following code to display as colour map:</p> <pre><code>import matplotlib.pyplot as plt plt.imshow(rand_matrix) plt.show() </code></pre> <p>I would li...
<p>You can save time by saving to a <code>io.BytesIO</code> instead of to a file:</p> <pre><code>import io import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg from PIL import Image def ax_to_array(ax, **kwargs): fig = ax.figure frameon = ax.get_frame_on() ax.set_frame_on(Fa...
python|image|numpy|rgb
1
350,317
38,842,975
Pairing images as np arrays into a specific format
<p>So I have 2 images, X and Y, as numpy arrays, each of shape (3, 30, 30): that is, 3 channels (RGB), each of height and width 30 pixels. I'd like to pair them up into a numpy array to get a specific output shape: </p> <pre><code>my_pair = pair_up_images(X, Y) my_pair.shape = (2, 3, 30, 30) </code></pre> <p>Such tha...
<p>Simply:</p> <pre><code>Z = np.array([X, Y]) Z.shape Out[62]: (2, 3, 30, 30) </code></pre>
python|arrays|numpy
1
350,318
38,818,862
python numpy.ndarray.max using axis return swapped results
<p>As I now that numpy.ndarray.max using axis argument, it should return array of maximums over that axis. But I get results as if the axes are swapped. </p> <pre><code>import numpy as np a = np.array([[1,5,50],[89,7,14]]) a.max(axis=0) array([89, 7, 50]) a.max(axis=1) array([50, 89]) </code></pre> <p>Isn't thes...
<p>The <a href="http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html#index-4" rel="nofollow">docs</a> says:</p> <blockquote> <p>If axis is an integer, then the operation is done over the given axis (for each 1-D subarray that can be created along the given axis).</p> </blockquote> <p>so along the rows ax...
python|numpy
0
350,319
38,605,182
Why Python Pandas append to DataFrame like this?
<p>I want to add l in column 'A' but it creates a new column and adds l to the last one. Why is it happening? And how can I make what I want?</p> <pre><code>import pandas as pd l=[1,2,3] df = pd.DataFrame(columns =['A']) df = df.append(l, ignore_index=True) df = df.append(l, ignore_index=True) print(df) A 0 0...
<p>You can just pass a dictionary in the dataframe constructor, that if I understand your question correctly.</p> <pre><code>l = [1,2,3] df = pd.DataFrame({'A': l}) df A 0 1 1 2 2 3 </code></pre>
python|pandas
2
350,320
38,816,646
Python: Write all combinations of a pd.Series in a text file
<p>I have several Pandas Series of unique strings:</p> <pre><code> First Series P0A8V2 P36683 P15254 Second Series P09831 P0AFG8 </code></pre> <p>I want to write a textfile that looks like this (tab seperator):</p> <pre><code>P0A8V2 P36683 P0A8V2 P15254 P36683 P15254 P09831 P0AFG8 </code...
<p>Looks like you are almost there.</p> <pre><code>combi_list = [] for cluster in df_list: combi_list.append(pd.DataFrame(list(itertools.combinations(cluster.index, 2)))) result_df = pd.concat(combi_list, ignore_index=True) result_df.to_csv(filename, sep='\t', index=False, header=False) </code></pre> <p>This wou...
python|pandas|combinations
3
350,321
38,732,502
TensorFlow Master and Worker Service
<p>I am trying to understand the exact roles of the master and worker service in TensorFlow.</p> <p>So far I understand that each TensorFlow task that I start is associated with a <code>tf.train.Server</code> instance. This instance exports a "master service" and "worker service" by implementing the <a href="https://w...
<blockquote> <p>1st Question: Am I right that this means, that ONE task is only associated with ONE worker?</p> </blockquote> <p>This is the typical configuration, yes. Each <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#Server" rel="noreferrer"><code>tf.train.Server</code></a> insta...
python|tensorflow
14
350,322
38,615,306
Pandas: add several dataframes to a single Excel file
<p>I need to add several <code>df</code> to one excel and I want that they looks like <a href="https://i.stack.imgur.com/iUIbM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iUIbM.png" alt="enter image description here"></a>. Is any function in <code>pandas</code>. that can make it?</p>
<p>For the layout, see <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html" rel="nofollow"><code>to_excel</code></a> docs. Note that you will have to pass it a <code>pd.ExcelWriter</code> object instead of a path string and then call its <code>save</code> method to be able to s...
python|pandas
1
350,323
38,593,771
Numerically Representing Mathematica's Root Object in Open-Source Language
<h2>Question</h2> <p>I would like to reproduce a <code>Root[]</code> object, <em>ideally</em> in a <code>python</code> function.</p> <p>Is there any particular library that would be suited for this process?</p> <h2>Attempts</h2> <p>If I understand the <code>Root[]</code> function properly, it is simply finding the nth ...
<p>If you are interested in symbolic calculations, you can use <a href="http://www.sympy.org/en/index.html" rel="nofollow">SymPy</a>. In particular, SymPy has polynomial objects and the classes <code>RootOf</code> and <code>CRootOf</code> to represent the roots of polynomials.</p> <p>For example,</p> <pre><code>In [...
python|numpy|scipy|wolfram-mathematica|solver
2
350,324
38,806,411
Keeping track of number of samples in each bin usings pandas pd.resample
<p>When using <code>pandas</code> is it possible to keep track of the number of samples within each resampled bin?</p> <p>For example given the sample data:</p> <pre><code>2000-01-01 00:00:00 1 2000-01-01 00:01:00 2 2000-01-01 00:06:00 3 </code></pre> <p>With resampling on the <code>time_scale</code> 5min, ...
<p>Assume this is your DataFrame:</p> <pre><code>df Out: C1 2000-01-01 00:00:00 1 2000-01-01 00:01:00 2 2000-01-01 00:06:00 3 </code></pre> <p>You can apply multiple functions to groups using <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-o...
pandas
1
350,325
38,527,444
Fill NA-values with Mean across column and row values
<p>I have next dataframe</p> <pre><code> A B C D E F 0 158 158 158 177 1 10 1 158 158 158 177 2 20 2 177 177 177 177 3 30 3 1 3 5 7 NaN 10 4 177 177 177 177 6 50 </code></pre> <p>Now I try to get a new one dataframe where <strong>E3</strong> = AVG[AVG(E)=3, AV...
<p>I couldn't find a one-liner however if you can keep three data frames in memory</p> <ul> <li>one with row averages </li> <li>another with column averages </li> <li>third with the average of the above two</li> </ul> <p>then <code>fillna</code> will replace <code>NaN</code> values based on the exact location in the ...
python|python-2.7|pandas
1
350,326
38,679,666
Slicing a Python list with a NumPy array of indices -- any fast way?
<p>I have a regular <code>list</code> called <code>a</code>, and a NumPy array of indices <code>b</code>.<br> (No, it is not possible for me to convert <code>a</code> to a NumPy array.)</p> <p>Is there any way for me to the same effect as "<code>a[b]</code>" efficiently? To be clear, this implies that I don't want to...
<p>Write a cython function:</p> <pre><code>import cython from cpython cimport PyList_New, PyList_SET_ITEM, Py_INCREF @cython.wraparound(False) @cython.boundscheck(False) def take(list alist, Py_ssize_t[:] arr): cdef: Py_ssize_t i, idx, n = arr.shape[0] list res = PyList_New(n) object obj ...
python|arrays|performance|numpy|optimization
3
350,327
38,797,872
Extracting data using pandas from a CSV file with a special condition
<p>This is example of the data I have </p> <pre><code>1, "dep, anxiety", 30 2, "dep" , 40 4, "stress" , 30 7, "dep, fobia" , 20 </code></pre> <p>I want to use pandas to filter rows having "dep" and save it in a new cvs file. output should be:</p> <pre><code>1, "dep, anxiety", 30 7, "dep, fobia" , 20 ...
<p>you can do it this way:</p> <pre><code>In [213]: patients Out[213]: ID dis rank 0 1 dep, anxiety 30 1 2 dep 40 2 4 stress 30 3 7 dep, fobia 20 In [214]: patients[(patients['dis'].str.contains('dep')) &amp; (patients['rank'] == 30)] Out[214]: ID di...
csv|pandas|filtering
1
350,328
38,509,107
Sliding window iterator using rolling in pandas
<p>If it's single row, I can get the iterator as following</p> <pre><code>import pandas as pd import numpy as np a = np.zeros((100,40)) X = pd.DataFrame(a) for index, row in X.iterrows(): print index print row </code></pre> <p>Now I want each iterator will return a subset <code>X[0:9, :]</code>, <code>X[5:1...
<p>I'll experiment with the following dataframe.</p> <h3>Setup</h3> <pre><code>import pandas as pd import numpy as np from string import uppercase def generic_portfolio_df(start, end, freq, num_port, num_sec, seed=314): np.random.seed(seed) portfolios = pd.Index(['Portfolio {}'.format(i) for i in uppercase[:...
python|pandas|numpy|dataframe|pandas-groupby
7
350,329
38,683,709
How to set Dataframe Column value as X-axis labels
<p>Say I have data in following format:</p> <pre><code>Region Men Women City1 10 5 City2 50 89 </code></pre> <p>When I load it in Dataframe and plot graph, it shows index as X-axis labels instead of <code>Region</code> name. How do I get names on X-axis?</p> <p>So far I tried:</p> <pre><code>import pa...
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.bar.html" rel="noreferrer">plot.bar()</a> method inherits its arguments from <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="noreferrer">plot()</a>, which has <code>rot</code> argument...
python|pandas|dataframe|matplotlib|bar-chart
17
350,330
38,855,222
Pandas - Parse time data with and without milliseconds
<p>How do you parse time data if the time is in the format <code>2007-08-06T18:11:44.688Z</code>, but treats no milliseconds as <code>2007-08-06T18:11:44Z</code>? </p> <p><code>pd.to_datetime(x.split('Z')[0], errors='coerce', format='%Y-%m-%dT%H:%M:%S.%f')</code> to remove remove the Zulu marker fails due to the <code...
<p>IIUC you can simply use <code>pd.to_datetime(df_column_or_series)</code> without specifying the <code>format</code> parameter should properly parse both your datetime formats</p> <p>having or not having <code>Zulu</code> marker, doesn't change anything - you will have the same dtype after your string is converted t...
python|pandas
1
350,331
63,232,108
Pandas new column based on row values
<p>I have a dataframe:</p> <pre><code> Item SW_test HW_test QA_test 0 PC Pass Pass Pass 1 Laptop Fail Fail Pass 2 Mouse Pass Pass Fail </code></pre> <p>I want to create a final column which will give <code>Pass</code> if all tests were pass (not case sensitive) and <code>Fail</code...
<p>Use <code>eq</code> with <code>all</code>:</p> <pre><code>df['Final'] = df.iloc[:,1:].eq('Pass').all(1) #If case sensitive you can use df['Final'] = df.iloc[:,1:].isin(['Pass','pass']).all(1) #or df['Final'] = df.iloc[:,1:].apply(lambda x: x.str.lower().eq('pass')).all(1) #or df['Final'] = df.iloc[:,1:].applymap(str...
python|pandas
6
350,332
63,218,202
Reading & processing CSV Files individually, outputting results to new individual files
<p>I am making what i suspect to be a very silly error here but vast majority of what i've found online talks about reading multiple files into a single dataframe or outputting results into a single file which is not my goal here.</p> <p><strong>Aim</strong>: read hundreds of CSV files, one by one, filter each one and ...
<p>The error message is nice because it shows you exactly what is wrong--your filename for the output save is wrong because the <code>c:/users/...</code> is repeated twice and concatenated together.</p> <p>Try something with <code>os.path.basename()</code> to strip file extension and path:</p> <pre><code>fileout = path...
python|pandas
0
350,333
62,994,814
Siamese network with third component error
<p>I was able to create a siamese network similar to :</p> <p><a href="https://github.com/aspamers/siamese/" rel="nofollow noreferrer">https://github.com/aspamers/siamese/</a></p> <p>The problem happens if I try to add a third model as an input to the head of my network. I will get the following error :</p> <pre><code>...
<p>pay attention to the dimensionality that you define when u initialize the model input and output. the first dimension is always the batch size (None) and this can cause u some problem. here the correct example:</p> <pre><code>def getModel1(input_shape): model_input = Input(shape=input_shape) layer = Dense(32...
tensorflow|keras|tf.keras
1
350,334
63,067,343
pandas dataframe groupby and fill with first row values
<p>I have a df like this,</p> <pre><code>df = pd.DataFrame({ &quot;Name&quot; : [&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;,&quot;E&quot;,&quot;F&quot;,&quot;G&quot;], &quot;part number&quot; : [&quot;1&quot;,&quot;3&quot;,&quot;2&quot;,&quot;1&quot;,&quot;5&quot;,&quot;1&quot;,&quot;2&quot;], ...
<p>Use <code>groupby</code> on <code>part number</code> and transform column <code>detail1</code>, <code>detail2</code> using <code>first</code> and assign this transformed columns back to <code>df</code>:</p> <pre><code>cols = ['detail1', 'detail2'] df[cols] = df.groupby('part number')[cols].transform('first') </code>...
python|pandas|group-by|transform
6
350,335
63,261,386
Split one dataframe into multiple based on index in Pandas
<p>Given a small dataset as follows, say for each city there are two entries:</p> <pre><code> city price quantity 0 bj 10104 5934 1 bj 5423 623 2 sh 15728 9105 3 sh 533 76 4 gz 4012 3558 5 gz 523 7632 6 sz 3770 1946 7 sz 6237 7364 </code></pr...
<p>You can select pair and unpair rows by indexing:</p> <pre><code>df1 = df.iloc[::2] print (df1) city price quantity 0 bj 10104 5934 2 sh 15728 9105 4 gz 4012 3558 6 sz 3770 1946 df2 = df.iloc[1::2] print (df2) city price quantity 1 bj 5423 623 3 sh 533 ...
python-3.x|pandas|dataframe
3
350,336
62,979,068
Add column to DataFrame based on grouped values
<p>I have this DataFrame:</p> <pre><code>df = pd.DataFrame({'site': ['a', 'a', 'a', 'b', 'b', 'b', 'a', 'a', 'a'], 'day': [1, 1, 1, 1, 1, 1, 2, 2, 2], 'hour': [1, 2, 3, 1, 2, 3, 1, 2, 3], 'clicks': [100, 200, 50, 0, 20, 30, 10, 0, 20]}) # site day hour click...
<p>This looks like a job for <code>GroupBy.transform</code>:</p> <pre><code>(df.eval('has_clicks = hour == 1 and clicks &gt; 0') .groupby(['site', 'day'])['has_clicks'] .transform('any')) 0 True 1 True 2 True 3 False 4 False 5 False 6 True 7 True ...
python|pandas
4
350,337
63,316,514
Python pandas dataframes - trying to access/print certain fields from read_csv causes a type error - how to fix?
<p>Whenever I try to run a simple print operation on a variable within my data frame, it displays the following errors:</p> <blockquote> <p>TypeError: 'str' object cannot be interpreted as an integer</p> </blockquote> <blockquote> <p>During handling of the above exception, another exception occurred:</p> </blockquote> ...
<p>You have leading <em>space</em> in column names</p> <pre><code>data = '''Date, Type, Description, Value, Balance, Account Name, Account Number,, 05/08/2020,POS,&quot;1234 03AUG20 , PAY *NAME, 2135655&quot;,-20,28.4,bobsley bobbington,1234 04/08/2020,POS,&quot;1234 03AUG20 , WWW.AMAZON.COM, 123 123 132 42 GG&quot;,-1...
python|pandas|dataframe|csv
1
350,338
62,967,079
tensorflow-gpu installing issue on win10
<p>while I installed tensorflow-gpu 2.2.0 including</p> <p>tf-gpu 2.2.0 cuda 10.1 cudnn 7.6.5 for cuda 10.1 nvidia GTX 1060 driver 426.00</p> <p>and meet the following error traceback</p> <pre><code>Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32 Type &quot;help&quot;, &quot;co...
<p>the best way to solve this is downgrading to <code>tensorflow 2.0</code>. but you can also try the following:</p> <p>create a new <code>conda environment with python 3.x</code> and install necessary libraries.</p> <p>For future use please check if your python is added in path variable.</p> <p>installing visual studi...
python|tensorflow
0
350,339
63,222,007
Loading tensorfow model from native file system using TensorflowJS 2.0.1
<p>Am trying to load a pre-trained Keras model to my small react-App. Since with the 2.0 version of TensorFlow, few things were added and changed. I would like to know how one should load the model from the native file system.</p> <ol> <li>First I import tensorflowJS</li> </ol> <pre class="lang-py prettyprint-override"...
<p>You have to set the path to the model weights and JSON using require()</p> <pre><code>const modelJSON = require(&quot;../model/model.json&quot;); const modelWeights = require(&quot;../model/group1-shard1of1.bin&quot;); const model = await tf.loadLayersModel(bundleResourceIO(modelJSON, modelWeights)) </code></pre> ...
tensorflow|tensorflow2.0|tensorflow.js|tensorflowjs-converter
3
350,340
63,034,847
create numpy array in for loop without usage of concatenation
<p>i am creating a simulation with multiple for-loops. My goal is to create a numpy array with all the values. I first used numpy.concatenate, since this does the job. I read, though, that np.concatenate is very slow so i am looking for a faster method on how to create the array with the values My code:</p> <pre><code>...
<p><code>itertools</code> would be very convenient for this. E.g.</p> <p>(modified this answer, also addressing follow up questions)</p> <pre><code>import numpy as np import itertools n_list, m_list, rho_list = [100,1000], [2,10,100], [0.0,0.5,0.9] f1, f2 = lambda mat: 1, lambda mat: 2 # change accordingly def f(n, m...
python-3.x|numpy|concatenation
2
350,341
63,270,966
Covnert a List of Tensors to a Tensor
<p>I have a list of tensors like this:</p> <pre><code>[tensor(-2.9222, grad_fn=&lt;SqueezeBackward1&gt;), tensor(-2.8192, grad_fn=&lt;SqueezeBackward1&gt;), tensor(-3.1894, grad_fn=&lt;SqueezeBackward1&gt;), tensor(-2.9048, grad_fn=&lt;SqueezeBackward1&gt;)] </code></pre> <p>I want it to be in this form:</p> <pre><code...
<p>Since these tensor are 0-dimensional, <code>torch.cat</code>will not work but you can use <code>torch.stack</code> (which creates a new dimension along which to concatenate):</p> <pre><code>a = torch.tensor(1.0, requires_grad=True) b = torch.tensor(2.0, requires_grad=True) torch.stack([a,b], dim=0) &gt;&gt;&gt;tenso...
pytorch|tensor|backpropagation
1
350,342
63,194,238
Create a list of latest datetimes in a range of dates PANDAS PYTHON
<p>I have a dataframe that reads from a .csv file. The dataframe has two columns, 'timestamp' and 'users_holding'. The 'timestamp' column has multiple datetimes for each day, and the 'users_holding' column shows the amount of users holding a stock at the corresponding datetime. How would I create a list of datetimes th...
<p>Make sure to set your datetime column and create a new one as index:</p> <pre><code>df['start_timestamp_index'] = pd.to_datetime(df.start_timestamp) df = df.set_index('start_timestamp_index') </code></pre> <p>Then,</p> <pre><code>last_of_each_day = df.groupby([df.index.year, df.index.month, df.index.day]).last()['s...
python|pandas|datetime
1
350,343
63,107,594
How to deal with multi-level column names downloaded with yfinance
<p>I have a list of tickers (<code>tickerStrings</code>) that I have to download all at once. When I try to use Pandas' <code>read_csv</code> it doesn't read the <a href="https://en.wikipedia.org/wiki/Comma-separated_values" rel="nofollow noreferrer">CSV</a> file in the way it does when I download the data from <a href...
<h3>Download all tickers into single dataframe with single level column headers</h3> <h4>Option 1</h4> <ul> <li>When downloading single stock ticker data, the returned dataframe column names are a single level, but don't have a ticker column.</li> <li>This will download data for each ticker, add a ticker column, and cr...
python|python-3.x|pandas|dataframe|yfinance
28
350,344
63,019,559
How can I animate Pandas dataframe using matplotlib
<p>I have a dataframe that I want to animate (line chart) using matplotlib. My x and y values:</p> <hr /> <p>here x = df.index and y = df['Likes']</p> <p>x y</p> <p>0 200000</p> <p>1 50000</p> <p>2 1000000</p> <p>.so on.. ....</p> <hr /> <p>Code I tried:</p> <pre><code>from matplotlib import pyplot as plt fro...
<p>I have solved it myself, I have used code of &quot;vkakerbeck&quot; from github as a guide to add more data points:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np df = pd.read_csv(&quot;C:\\Users\\usr\\Documents\\Sublime\\return_to_wind...
python|pandas|dataframe|matplotlib
1
350,345
62,957,509
how to train model to identify patterns for predicting only one label '1' in binary classification. while any other pattern will be predicted as '0'
<p>Can i make my LSTM RNN model focus on predicting '1' while it dose not cares to predict '0'. To make my question more clear. i am trying to make LSTM binary classification where i want to predict buy signals. model can only focus of what pattern is essential to predict 1. and it neglects patterns that predict '0'/do...
<p>The patterns of both 0 and 1 are intertwined, to say, you will optimize for one is not right because if you are trying to optimize for 1, you are inadvertently also, optimizing for 0. What you can do is make your model better:</p> <ol> <li>Trying changing the number of layers and the number of units in your layer.</...
python|tensorflow|keras|lstm|recurrent-neural-network
0
350,346
63,308,011
How to parse the datetime
<p>I am trying to parse the datetime, dataset shown below;</p> <h1>Data</h1> <pre class="lang-py prettyprint-override"><code> Date sell_B buy_B 0 2016-01-03 22:00:01.446 1.0873 1.0875 1 2016-01-03 22:00:01.799 1.08714 1.08748 2 2016-01-03 22:00:01.981 1.08702 1.08748 3 2016-01-03 22:00:04.548 1.08706000...
<p>Use the datetime Format - <code>%Y-%d-%m %H:%M:%S.%f</code>. Alternatively, you can use the <code>parse_dates</code> parameter in <code>read_csv</code></p> <pre><code>In [6]: import pandas as pd In [7]: df = pd.read_csv(&quot;a.csv&quot;, parse_dates=[&quot;Date&quot;]) In [8]: df.dtypes Out[8]: Date datetime...
python|pandas|datetime|parsing
1
350,347
63,005,290
Why is my get_forecast index different from the index of my endog and exog variables?
<p>I'm trying to forecast a univariate time series and when I'm using the get_forecast or forecast function for SARIMAX from statsmodels, the outputted index is a RangeIndex instead of a DateTimeIndex like my inputs' indexes are</p> <p>It works fine, however, when I use the get_prediction function to see the validity o...
<p>Fixed it by changing the DateTimeIndex to be 1-01-14,2-01-14, etc. And it fixed the issue.</p>
python|pandas|time-series|statsmodels|arima
0
350,348
63,181,462
Creating a reverse dummy variable
<p>I would like to create a reverse dummy variable from different columns of my dataframe.</p> <p>The dataframe columns look like this:</p> <pre><code>client booking_by_phone booking_online booking_online ... no_call_ad no_sms_ad no_ad_other 2q332 1 0 0 1 ...
<p>Let's look at booking channel. Here's a way with boolean masks:</p> <pre><code>df['booking channel'] = 'agency' # default value mask = df['booking_by_phone'] == 1 df.loc[mask, 'booking channel'] = 'phone' mask = df['booking_online'] == 1 df.loc[mask, 'booking channel'] = 'online' </code></pre> <p>You could creat...
python|pandas|numpy
1
350,349
62,938,139
Keras tensorflow modify model NN to CNN
<p>I'm trying to rewrite a Neural Network model which used to classify satellite images, I want to use some conv layers in that model,like <code> #keras.layers.Conv2D(filters=64, kernel_size=(3, 3), activation='relu', padding = 'same',input_shape=(1,nBands)),</code> but I can't get the <code>input_shape</code> param...
<p>Great question, and I think you'll find CNNs perform much better than training NNs on flattened images. For the input shape in <code>Conv2D</code> layers, the shape can be given in one of two forms:</p> <ol> <li><p>&quot;Channels last&quot; (Keras uses this by default): <code>(image height, image width, 6)</code>, ...
python|tensorflow|machine-learning|keras|neural-network
1
350,350
62,931,907
I am facing ValueError: Shapes (1, 14) and (1, 139, 14) are incompatible
<pre><code>import keras from keras_self_attention import SeqSelfAttention inputs = keras.layers.Input(shape=(None,)) embd = keras.layers.Embedding(vocab_size, 300, weights=[embedding_matrix], trainable=False, mask_zero=True, name='Encoder-Word-Embedding')(inp...
<p>Try to add activation='softmax' in your last Dense layer.</p>
python|tensorflow|machine-learning|deep-learning|nlp
0
350,351
63,021,317
Can you serve models from different tensorflow versions in the same binary of tensorflow/serving?
<p>Say I have two saved models one from tensorflow 1.8 and the other from tensorflow 2.2. Serving both of those could run into <a href="https://www.tensorflow.org/guide/versions#semantic_versioning_20" rel="nofollow noreferrer">compatibility issues</a>.</p> <p>Would it be possible to serve both of those in the same ten...
<p>I'm definitely not an expert on the deep inner workings of TensorFlow, so take this with a grain of salt. But I think what you want to do may actually be pretty easy.</p> <p>My very approximate (and possibly completely incorrect) understanding is that the TensorFlow APIs are a sort of wrapper that creates a graph re...
tensorflow|tensorflow-serving
0
350,352
63,270,933
Reshaping 2D Grayscale into 4D for Keras Model Inference
<p>I have a pre-trained Keras model that I need to use to classify a 512x 512 image that is originally in grayscale format. The input to the Keras model should be in the shape (None, 512, 512, 1). <a href="https://i.stack.imgur.com/S1gGW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S1gGW.png" alt=...
<p>try reshaping the array</p> <pre><code>img_array = img_array.reshape((1, 512, 512, 1)) </code></pre> <p>here 1st and last dimension are batch size and channels respectively</p>
python|tensorflow|keras|neural-network
0
350,353
63,024,900
How to train and deploy model in script mode on Sagemaker without using jupyter notebook instance (serverless)?
<p>I have been using a jupyter notebook instance to spin up a training job (on separate instance) and deploy the endpoint (on another instance). I am using sagemaker tensorflow APIs for this as shown below:</p> <pre><code># create Tensorflow object and provide and entry point script tf_estimator = TensorFlow(entry_poin...
<p>I recommend <code>AWS Step Functions</code>. Been using it to schedule <code>SageMaker Batch Transform</code> and preprocessing jobs since it integrates with <code>CloudWatch</code> event rules. It can also train models, perform hpo tuning, and integrates with <code>lambda</code>. There is a SageMaker/Step Functi...
amazon-web-services|tensorflow|jupyter-notebook|amazon-sagemaker
2
350,354
63,269,740
Replace Object in Pandas Series by Attribute of the Object
<p>Let's assume we have a Class Foo:</p> <pre><code>Class Foo: def __init__(self, name): self.name = name </code></pre> <p>Now I have 2 of these Objects:</p> <pre><code>foo1 = Foo(&quot;foo&quot;) foo2 = Foo(&quot;bar&quot;) </code></pre> <p>Now I have a pandas Series:</p> <pre><code>series = pd.Series([foo...
<p>Thanks to the suggestion of using &quot;apply&quot; I found the following solution:</p> <pre><code>series = series.apply(getattr, args=(&quot;name&quot;,)) </code></pre>
python|pandas
0
350,355
63,037,979
Merging Panda Dataframes - perserve orginial order and overwrite columns
<pre><code>df1 = pd.DataFrame([(1,5),(2,10),(3,15)],columns=[&quot;2009&quot;,&quot;2008&quot;],index=[&quot;C&quot;,&quot;A&quot;,&quot;B&quot;]) 2009 2008 C 1 5 A 2 10 B 3 15 df2 = pd.DataFrame([(5,7),(11,14),(14,15)],columns=[&quot;2008&quot;,&quot;2007&quot;],index=[&quot;D&quot;,&quot;B...
<p>You can try this using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.difference.html" rel="nofollow noreferrer"><code>pd.Index.difference</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html" rel="nofollow noreferrer"><cod...
python|pandas
3
350,356
63,031,346
Shift "nan" to the beginning of an array in python
<p>If I have an array with nan, which looks like this:</p> <pre><code>array([[ 0., 0., 0., 0.], [ 0., 0., nan, nan], [ 0., 1., 3., nan], [ 0., 2., 4., 7.], [ 0., nan, 2., nan], [ 0., 4., nan, nan]]) </code></pre> <p>how can I shift all the nans to the start of the array, wi...
<p>Here's one way:</p> <pre><code># find the position of nan itms in &quot;a&quot; In [19]: mask = np.isnan(a) # put them at the beginning by s...
python|arrays|python-3.x|numpy|nan
4
350,357
63,111,284
How can I optimise this pandas workflow?
<p>This logic will be applied to BIG data, I really need to optimise for speed and minimise RAM usage as much as possible and I have taken it about as far as my skills go.</p> <pre><code>df = pd.DataFrame([['chr1',33329,17,'''33)'6'4?1&amp;AB=?+..''','''X%&amp;=E&amp;!%,0(&quot;&amp;&quot;Y&amp;!'''], ...
<p>Use list comprehension:</p> <pre><code>df['phred2'] = [(sum(map(ord,i))-len(i)*33)/len(i) for i in df[&quot;phred&quot;]] df[&quot;map2&quot;] = [(sum(map(ord,i)))/len(i) for i in df[&quot;map&quot;]] chrom pos depth phred map phred2 map2 0 chr1 33329 17 33)'6'4?1&...
python-3.x|pandas|optimization|apply|bioinformatics
2
350,358
63,293,975
unstacking a data frame with repeated value in a column
<p>This is a part of data frame I have:</p> <pre><code>index value category 1 ff a 2 ss a 3 hl a 4 dn a 5 fs b 6 lm b 7 fds b 8 dn b 9 hs b 10 ho c 11 ycs c 12 dl c </code></pre> <p>I want to convert it to this format:</p> <pre><code>a b ...
<p>You have a hidden key here create by <code>cumcount</code></p> <pre><code>s = df.assign(key=df.groupby('category').cumcount()).pivot(index='key',columns='category',values='value') Out[91]: category a b c key 0 ff fs ho 1 ss lm ycs 2 hl fds dl 3 ...
python|pandas
1
350,359
63,275,479
IndexError: index n is out of bounds for axis 1 with size n
<p>I have an empty matrix <code>M.shape</code>:</p> <p><code>(179, 179)</code></p> <p>Now I want to populate it using the following loop:</p> <pre><code>for game in range(len(games)-1): df_round = df_games_position[df_games_position['rodada_id'] == games['rodada_id'][game]] players_home = df_round[df_round['ti...
<p>Matrix is <code>numpy</code> <code>array</code>, and the <code>index</code> for it is start with 0 not 1</p> <pre><code>np.array([1,2,3,4]).shape Out[29]: (4,) np.array([1,2,3,4])[3] Out[30]: 4 </code></pre> <p>We can simple fix it create the empty M with shape (180,180)</p> <pre><code>M = M[1:,1:] </code></pre>
python|pandas|matrix|index-error
0
350,360
63,099,785
Pandas quantile on a multi-level columns MultiIndex groupby object with a list of q's
<p>I have a Pandas df with MultiIndex column-labels like this:</p> <p><strong>in:</strong></p> <pre><code>import pandas as pd import numpy as np np.random.seed(123) df = pd.DataFrame(np.random.randint(100,size=(3, 4)),columns = pd.MultiIndex.from_product([['exp0','exp1'],['rnd0','rnd1']],names=['experiments','rnd_ru...
<p>Using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.T.html" rel="nofollow noreferrer"><code>DataFrame.T</code></a> transpose the dataframe and use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>...
python|pandas|pandas-groupby|multi-index
1
350,361
63,128,335
Cumulative sum, refreshing at intervals, python pandas
<p>I have some timestamped data, and I would like to run an expanding sum, that will refresh, say every day at 7:00 (restart from zero), kind of a &quot;saw-teeth&quot; sum. How can I do that in pandas? Thank you very much, JT2</p>
<ol> <li>simplest case is to <code>groupby()</code> the <code>floor(&quot;D&quot;)</code> of the date. To meet your requirement, subtract 7 hours before doing floor</li> <li>then use <code>transform(&quot;cumsum&quot;)</code> so you get the running total with same cardinality of original dataframe</li> <li>showed resu...
python|pandas|dataframe|datetime
0
350,362
63,238,438
Python pandas: Applying rolling sum on pivot table
<p>I created a dataframe using pivot_table command.Dataframe has 351 rows and 120 columns. The dataframe looks like follow:</p> <pre><code>RY 2011 ... 2020 Month 1 2 3 4 5 6 7 8 9 10 ... 3 4 5 6 7 8 9 10 11 12 ID ...
<p>Try running that code <em>before</em> creating a pivot table. But, make sure that you first create a datetime column with something like:</p> <p><code>df['Date'] = pd.to_datetime(df['Year'].astype(str) + '-' + df['Month'].astype(str) + '-01')</code></p> <p>and then:</p> <p><code>df.groupby('ID').rolling(12,on='Date'...
python|python-3.x|pandas
1
350,363
63,240,852
Shape of librosa.feature.melspectrogram
<p>I'm trying to understand the output of <code>librosa.feature.melspectrogram</code>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from librosa.feature import melspectrogram &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; melspectrogram(np.random.randn(128), n_mels=128).shape (128, 1) &gt;&gt;&gt; melspectrogram...
<p>It's the length of the signal in <em>frames</em> (not samples), depending on window and hop length. See <a href="https://stackoverflow.com/a/62733609/942774">this answer</a>.</p> <p>Concretely: <code>1 + len(y) // hop_length</code></p>
python|numpy|signal-processing|spectrogram|librosa
1
350,364
62,912,305
How to print NAN instead of 0 if one of a column has NAN in it
<p>I'm trying to check the number of time a condition is true for my product in each file but only needs to check when the condition is satisfied AND both the column are populated, so I'm using this code</p> <pre><code>cnt = big_frame.groupby('Symbol').apply(lambda g:((g.A001 &gt; g.A002) &amp; g.A001.notnull() &amp; g...
<p>Why not just replace the 0's with Nans with this:</p> <pre class="lang-py prettyprint-override"><code>df['Data_Count'].replace(0, np.nan) </code></pre> <p>But you could also do this:</p> <pre class="lang-py prettyprint-override"><code>cnt = big_frame.groupby('Symbol').apply(lambda g: True if ((g.A001 &gt; g.A002) &a...
python|python-3.x|pandas
0
350,365
63,221,992
Pythonic way to assign labels based on percentile of values in a dataframe
<p>I want to know what's a good way to approach solving the following problem I have.</p> <p>I have a python dataframe containing 3 pre-calculated values associated to an ID. I want to assign a label to that ID based on the percentile associated to the value corresponding to one of the calculated columns</p> <p>given d...
<p>From what I can tell in your question, this is close to what you're looking for:</p> <pre><code>#take 1-the proportion to get the inverse that you want df[&quot;VAL1_LABEL&quot;] = 1 - df.VAL1/sum(df.VAL1) df[&quot;VAL1_LABEL&quot;] = np.where(df.VAL1_LABEL&lt;df.VAL1_LABEL.mean(),&quot;bottom50%&quot;,&quot;top50%&...
python|pandas|numpy|lambda|pandas-groupby
1
350,366
63,225,707
Plotly dash refreshing global data on reload
<p>Imagine I have a <code>dash</code> application where I want the global data to refresh on page reload. I'm using a function to serve the layout as described <a href="https://dash.plotly.com/live-updates" rel="nofollow noreferrer">here</a>. However, I'm note sure how/where I should define <code>df</code> such that I ...
<p>The most common approach for sharing data between callbacks is to save the data in a <code>dash_core_components.Store</code> object,</p> <pre><code>def serve_layout(): df = # Fetch data from DB store = Store(id=&quot;mystore&quot;, data=df.to_json()) # The store must be added to the layout return # Layo...
python|pandas|plotly-dash
8
350,367
63,273,046
find the first occurrence of a specific value in different groups
<p>I have this toy dataframe that I was have a column of accuracy values and another column of group ID. I am hoping that I can get the position index, for each group, that the accuracy value gets up to 0.9. Could anyone help out, please?</p> <pre><code>df = pd.DataFrame({&quot;acc&quot;:[0.6,0.9,0.5,0.1,0.9,0.9], ...
<p>The following code finds, for each <code>id</code>, the earliest index at which <code>acc</code> exceeds <code>threshold</code>:</p> <pre><code>threshold = 0.9 df[df['acc'] &gt;= threshold]\ .sort_index()\ .drop_duplicates(subset='id', keep='first')\ .index </code></pre> <p>Not sure what the difference i...
python|pandas
1
350,368
62,946,604
Fitting an Orthogonal Grid to Noisy Coordinates
<h3>Problem</h3> I have a list of coordinates that are meant to form a grid. Each coordinate has a random error component and some of the coordinates are missing. <i>Grid could be rotated (update).</i> I want to fit a orthogonal grid to the data points and return a list of the grid's vertices. For example:<br/><br/> <p...
<p>A numpy implementation of your code can be found below. As the size AvgGrid is known, I pre-allocate the required memory (rather than append). This should have speed advantages, especially if the number of output vertices is large.</p> <pre><code>import numpy as np # Input of [x, y] coordinates of a sparse grid wit...
python|numpy|image-processing|scipy|linear-algebra
0
350,369
62,999,425
Installing geopandas
<p>I've tried installing geopandas, but I keep running into issues. I've followed the instructions here: <a href="https://geopandas.org/install.htm" rel="nofollow noreferrer">https://geopandas.org/install.htm</a></p> <p>Trying <code>conda install geopandas</code> in my terminal produced a number of conflicts. Similarly...
<p>I'm not quite sure the issues with the conda install. I was able to install it properly in a new environment in Anaconda-Navigator, but still unable to access it through a jupyter notebook.</p> <p>However I tried <code>pip install geopandas</code> instead of conda install, and that seems to have worked perfectly. Fu...
python|installation|jupyter|conda|geopandas
0
350,370
63,116,880
Trying to obtain closest value to known key from user input | numpy.core_exception
<p>Im trying to write a text-based sports game and part of that game is deciding who wins tip off based on comparing user input to a known value, and deciding the winner based on which user is closest.</p> <p>I used NumPy to convert a list containing the values, into an array, then find the absolute difference of each ...
<p>That's because your <code>input</code> takes the number as string.</p> <p>You should change to:</p> <pre><code>player_one_tip = int(input(&quot;Player one, select a number between 1 and 100&quot;)) player_two_tip = int(input(&quot;Player two, select a number between 1 and 100&quot;)) </code></pre>
python|python-3.x|numpy
2
350,371
63,132,384
How to re order rows in matrix base on their values?
<p>My matrix contains binary arrays. How to re-order them based on their values?</p> <pre><code>input = [[0,1,0] [0,0,0] [1,1,1]] result = [[0,0,0] [0,1,0] [1,1,1]] </code></pre>
<pre><code>sorted(input) </code></pre> <p>Based on @PremAnand answer.</p>
python|numpy|sorting
0
350,372
62,904,242
Training loss is not decreasing for roberta-large model but working perfectly fine for roberta-base, bert-base-uncased
<p>I have a pytorch lightning code that works perfectly for a binary classification task when used with bert-base-uncased or roberta-base but doesn't work with roberta-large i.e the training loss doesn't come down.</p> <p>I have no clue why this is happening. I'm looking for reasons for such an issue.</p> <p>Edit: I'm ...
<p>I decreased the learning rate slightly and the issue seems to be fixed. It's amusing to observe that changing the learning from 5e-5 to 5e-6 can have so much impact.</p> <p>Now, the bigger question is &quot;How do I find the right set of hyperparameters?&quot;</p>
huggingface-transformers
1
350,373
63,034,797
Python Pandas: get column names from inbetween comments
<p>Similar to this post <a href="https://stackoverflow.com/questions/36772656/get-one-specific-line-of-comment-as-header-with-python-pandas">get one specific line of comment as header with python Pandas</a></p> <p>How can I get the column names in between comments using only pandas?</p> <p>File.csv:</p> <pre><code>#Com...
<p>Try this:</p> <pre><code>import pandas as pd lines = [] with open('file.csv', 'r') as file: for line in file: if line[0] == '#': continue lines.append(line)) split_lines = ['|'.split(line) for line in lines] df = pd.DataFrame([{'Col1' : split_lines[0], 'Col2' : split_lines[1], 'Col3' ...
pandas
0
350,374
63,183,065
How to select specific datetime-indidices by intraday time?
<p>I have a timeindex and need all of the timeindices in it which are between these daytimes: (EDIT: its multiple days)</p> <pre><code>a,b = &quot;07:21:39&quot;,&quot;22:00:01&quot; index_ = DatetimeIndex(['2019-08-20 10:21:00', '2019-08-20 10:22:00', '2019-08-20 10:23:00', '2019-08-20 10:24:00', '2019-08-20 10:25:0...
<p>The problem comes from .time -&gt; this is a method.</p> <p>Using .time() with the braces fixed the problem^^</p>
python|pandas|datetime|time
0
350,375
63,051,321
Caching a large dataframe in database
<p>I was trying to cache a large pandas dataframe to using django.core.cache.backends.db.DatabaseCache backend into MySQL database. It works for 300,000 items but not anything bigger (e.g. 400,000 items). Can I increase the maximum length for the cache value? Thanks in advance.</p> <pre><code>import pandas as pd import...
<p>It turns out the reason was MySQL 5.7's default value for max_allowed_packet was 4194304.</p> <pre><code>SET GLOBAL max_allowed_packet=1073741824; </code></pre> <p>has solved the problem. Thanks danblack for the advises.</p>
mysql|django|pandas|caching
1
350,376
63,215,665
Perform a different neighbourhood operation for specified pixels
<p>I have an <code>HxW</code> &quot;feature map&quot;, <code>F</code>. Let us assume that it is a <code>HxWx1</code> map. Through some other operation, I have a set of pixels that are of interest to me, (say <code>N</code> pixels). Each of these pixels is associated with a different value, thus my set is of the form Nx...
<p>If I understand correctly, you want this:</p> <pre><code>from skimage.util.shape import view_as_windows idx = pixels[:,0:2].astype(int) print((np.unravel_index((view_as_windows(F,(3,3))[tuple(idx.T-1)]*pixels[:,-1][:,None,None]).reshape(-1,9).argmax(1),(3,3))+idx.T).T-1) #if you need to replace the values of F with ...
python|arrays|numpy|opencv|pytorch
3
350,377
63,241,356
Trying to convert a list of scraped values to Pandas DataFrame in Python. df = DataFrame (your_list,columns=['Name']) only takes text and not full str
<p>I have a list with scraped values like:</p> <pre><code>[&lt;a href=&quot;shropshire.html&quot;&gt;A Shropshire Lad (David Austin Rose, Austin, 1997) &lt;/a&gt;, &lt;a href=&quot;agiraud.html&quot;&gt;Abbé Giraudier (Hybrid Perpetual, Levet, 1869)&lt;/a&gt;, &lt;a href=&quot;abelcarr.html&quot;&gt;Abel Carrière (Hy...
<p>Posting the answer here for other developers.</p> <p>You need to extract the href and text from tag</p> <p>typically something like</p> <pre><code>soup = BeautifulSoup(html.text,'lxml') with open(filename,'w',newline='',encoding='utf-8') as f: w = csv.writer(f) for a in soup.find_all('a',href=True): ...
python|html|pandas|dataframe|web-scraping
1
350,378
63,137,140
Python - Groupby Multiple Criteria and Closest Integer
<p>Here, I am trying to assign groups based on multiple criteria and the closest date diff prior to the zero. The groupby should look only within each ID, then find the closest negative datediff value prior to each zero (not positive, I am trying to look back in time), and based on the Location integer, assign a group....
<p>Because the order of rows matter, the most straightforward answer that that I can think of (that will have a somewhat <em>readable code</em>) can use a <em>loop</em>... So I sure hope that performance is not an issue.</p> <p>The code is less cumbersome than it seems. I hope that the code comments are clear enough.</...
python|pandas|dataframe|datetime|pandas-groupby
1
350,379
68,013,574
How to solve gradient-exploding in YOLO v1
<p>Now I am trying to train object detection - YOLOv1 using <a href="https://github.com/yakhyo/YOLOv1-pt" rel="nofollow noreferrer">this</a> code. At the beginning I was using <code>momentum</code> and <code>weight_decay</code> but the training loss after couples of epochs becomes <code>NaN</code>. As far as I know it'...
<p>After checking your code, I saw after the first epoch, you would set the learning rate to <code>0.01</code> until epoch 75. In my opinion, that large learning rate is the main reason made your parameters became vanishing/exploding. Normally, the learning rate is scaling around <code>0.001</code> with the factor of <...
python|pytorch|object-detection|nan|yolo
2
350,380
67,693,137
Need help finding a file that is corrupting my NN
<p>I have created a Neural Network to help identify children's images and give them grades based on a pre-trained criteria. The problem is the web <strong>scraper</strong> I used must've downloaded either an unknown file or a file not supported by tensorflow for use with the NN. I have the two training and validation d...
<p>checking the extension is probably not sufficient. I think you should read in the images and test the shape as in</p> <pre><code>import cv2 # put the code below inside the loop bad_listt=[] try: img=cv2.imread(fp) shape=img.shape except: print ('file ', fp, ' is not a proper image file') bad_list.a...
python|tensorflow|neural-network|tf.keras
2
350,381
67,735,545
How to view data from another column based on row value of another?
<p>I have a dataframe:</p> <pre><code>data = [['Alex',10],['Alex',11],['Alex',8],['Bob',12],['Bob',14],['Clarke',13]] df2 = pd.DataFrame(data,columns=['Name','Age']) </code></pre> <p>I want to print the age values for unique values of Names. For example, I want to print all age values for the name 'Alex' and so on. I t...
<p>You can try this</p> <pre><code>unique = df2.groupby(by='Name')['Age'].apply(list) for i in unique.iteritems(): print(i) </code></pre> <p>output</p> <pre><code>('Alex', [10, 11, 8]) ('Bob', [12, 14]) ('Clarke', [13]) </code></pre>
python|pandas|dataframe
1
350,382
67,684,113
MLP for speech recognition
<p>I am trying to learn speech recognition and so I am using a simple MLP for starters.</p> <p>Below is the code:</p> <pre><code>#Simple MLP model num_labels = Y.shape[1] filter_size = 2 # Construct model model = Sequential() model.add(Dense(256, input_shape=(32,))) model.add(Activation('relu')) model.add(Dropout(0...
<p>In this particular line, <code>model.add(Dense(256, input_shape=(32,)))</code>, you define the input shape to be (32, ) which means the shape is going to be of the form <code>(batch_size, 32)</code> which isn't really the case, because your inputs are of the shape <code>(batch_size, 99, 32)</code> so that's the reas...
python|tensorflow|speech-recognition|mlp
0
350,383
67,977,084
Forward looking average
<p>I have a data frame and I want to take the average of three points forward.. I know how to do the min but I need the mean any ideas?</p> <pre><code>!pip install yfinance import yfinance as yf from scipy.stats import linregress import pandas as pd import numpy as np # test data df = yf.download('^GSPC',start='2009-...
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.mean.html" rel="nofollow noreferrer"><code>numpy.mean()</code></a> with <code>axis=0</code> on the <a href="https://numpy.org/doc/stable/reference/generated/numpy.array.html" rel="nofollow noreferrer"><code>numpy.array()</code></a> consistin...
python|pandas|dataframe|numpy
1
350,384
67,711,484
Add n columns between every column for a 2d numpy array
<p>I would like to create a function that adds n columns between every existing column of a 2d numpy array. The values of the additional columns doesn't really matter, it could be zeros or nans. I know I can add the columns one at the time using a for loop but since I'm working with large arrays, I was wondering if the...
<p>How about something like</p> <pre><code>b = np.zeros((a.shape[0], a.shape[1] * (n + 1) - n)) b[:, ::n+1] = a </code></pre>
python|arrays|numpy
3
350,385
67,706,135
make dataframe condition wise
<p>we have to Entered or choose any DPD value</p> <p>i have df like this:</p> <pre><code> NPA Status MSME Classifcation (Sub segment) Contact Number Scheme Type 0 N MICRO nan CCA 1 N MICRO 6359434643.0 LAA 2...
<p>Try using several boolean indexes together:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'NPA Status': ['N', 'Y', 'N', 'N'], 'MSME Classifcation (Sub segment)': ['MICRO', 'MICRO', 'MICRO', 'MICRO'], 'Contact Number': ['', '6359434643', '6359434643', '6359434643'], 'Scheme Type': ['CCA', 'L...
python|pandas
1
350,386
67,810,671
What does intial_clip_norm mean in gaussian adaptive clipping in TFF?
<p>I am trying to implement a Differentially private FL binary classification model using gaussian adaptive clipping geometric method.</p> <pre><code>aggregation_factory = tff.aggregators.DifferentiallyPrivateFactory.gaussian_adaptive( noise_multiplier=0.6, clients_per_round=10, init...
<p>One thing I would flag is that 13 training rounds is relatively few in general. If you run the training for longer, I would expect the clip norm will eventually stabilize around the same value, regardless of the initial value.</p> <p>The point of the adaptive selection of the clipping norm is that the hyper paramete...
tensorflow-federated|federated-learning
2
350,387
67,697,427
Keeping preferred value of a column and removing the less preferred one
<p>The data-frame, df:</p> <pre><code>ID status year 1 0 2000 1 1 2000 2 0 2001 3 1 2002 3 0 2002 4 1 2002 </code></pre> <p>I want to drop '0' status when '1' status is available for the same ID under the same year, such that:</p> <pre><code>ID status year 1 1 2000 2...
<p>Let us try <code>transform</code> with <code>max</code></p> <pre><code>m = df.status.eq(df.groupby('ID').status.transform('max')) df = df[m] df ID status year 1 1 1 2000 2 2 0 2001 3 3 1 2002 5 4 1 2002 </code></pre>
python|pandas|data-cleaning
1
350,388
67,834,475
Pandas comparing two rows in a database
<p>I have a dataframe like this;</p> <pre><code>df = pd.DataFrame(np.array([['apple', 'golden', 3], ['apple', 'green', 6], ['banana', 'golden', 9], ['apple', 'golden', 5], ['apple', 'green', 6], ['banana', 'golden', 6]]), columns=['Column1', 'Column2', 'Column3']) df Column1 Column2 Column3 0 ...
<p>Compare shifted values for not equal with replace first value to original <code>Column1</code> by <code>fillna</code>:</p> <pre><code>df['Column4'] = df.Column1.shift().fillna(df.Column1).ne(df.Column1) print (df) Column1 Column2 Column3 Column4 0 apple golden 3 False 1 apple green 6 ...
python|pandas|compare|row
2
350,389
67,749,813
TFRecord parsing for 3-D features
<p>I have similar question to <a href="https://stackoverflow.com/questions/49588382/how-to-convert-float-array-list-to-tfrecord">this</a>, but what if my feature shape is 3-D? Instead of prices <code>(1,288)</code>, it is <code>(1,288,3)</code> for example. What should I put as the shape of <code>tf.io.FixedLenFeature(...
<p>There's a few ways you can do this. One is using a <a href="https://www.tensorflow.org/api_docs/python/tf/train/BytesList" rel="nofollow noreferrer">BytesList</a> feature</p> <pre class="lang-py prettyprint-override"><code>def _bytes_feature(value): return tf.train.Feature( bytes_list=tf.train.BytesList(value=...
python|tensorflow
2
350,390
67,751,478
Facing problems when training a Convolutional Neural Network (CNN) using TPU when using ImageDataGenerator class for Data Augmentation of Images?
<p>Recently I have been training a CNN i.e. AlexNet for classifying Brain MRI images into four classes but when I am training it on CPU or GPUs on my Google Colab Runtime it is taking a lot of time i.e. approximately around 5 hrs. I thought to migrate my training process to TPU because the hardware is specially built f...
<p>Try using <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image_dataset_from_directory" rel="nofollow noreferrer"><code>tf.keras.preprocessing.image_dataset_from_directory</code></a> or <a href="https://www.tensorflow.org/guide/data" rel="nofollow noreferrer"><code>tf.data.Dataset</code></...
tensorflow|keras|deep-learning|data-augmentation|tpu
1
350,391
67,692,245
Applying a function to all but one column in Pandas
<p>I'm looking to apply a function to all but one column in pandas, whilst maintaining that column as it is originally. I have a working version that does what I need, but it seems unusually long for something so simple. I'm wondering if there is a better approach...</p> <pre><code>df = pd.DataFrame(columns = ['firstco...
<p>IIUC, you can select the non-numeric data type columns and replace their values:</p> <pre><code>non_numerics = df.select_dtypes(exclude=&quot;number&quot;).columns df[non_numerics] = df[non_numerics].apply(lambda x: x.str.replace(r&quot;[^\d.]&quot;, &quot;&quot;).astype(float)) </code></pre> <p>where I used your r...
python|pandas
7
350,392
67,763,805
How to calculate matching percentage difference between two dataframe
<p>I am looking to find the percentage difference between two dataframes. I have tried using fuzzywuzzy but not getting the expected output for the same.</p> <p>Suppose i have 2 dataframes with 3 columns each, i want to find the match percentage between these 2 dataframes.</p> <p><strong>df1</strong></p> <pre><code>sco...
<p>IIUC rename the columns to match then use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.eq.html#pandas-dataframe-eq" rel="nofollow noreferrer"><code>eq</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mean.html" rel="nofollow nor...
python|pandas
1
350,393
67,643,800
MLPclassifier from sklearn shows different accuracies when executed on other machine?
<p>It looks like running the sklearn MLPclassifier with the same input on different devices will give different accuracy results, even if a global seed is set.</p> <p>MWE:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from sklearn.neural_network import MLPClassifier from sklearn.model_selection...
<p>I cannot reproduce this.</p> <p>If there is something wrong, this would probably need more information about the different machines. What is the result of calling <code>python -c 'import sklearn; sklearn.show_versions()'</code> on each?</p> <hr /> <p>The following code gives me the same result on Ubuntu/Red Hat when...
python|numpy|random|scikit-learn
1
350,394
67,701,192
Transfer Learning with ResNet50 for image classification
<p>Hello guys I could use some advice on whether my approach that I employed in order to apply transfer learning on the resNet50 model is correct, after reading many articles and resources online, it is hard to say if the method I adopted is correct. I should mention that I am using 500 images/labels (with labels rangi...
<p>I think your dataset is quite small so you don't need so much Fully Connected layer. Or you can try to shuffle the data in your <code>train_test_split</code></p>
python|tensorflow|deep-learning|transfer-learning|resnet
0
350,395
67,833,218
How to get argmax for indices in a matrix/tensor?
<p>Is there any way to perform a top-k operation on a matrix or tensor so that the relevant indices are returned?</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; import torch &gt;&gt;&gt; matrix = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) &gt;&gt;&gt; print(matrix) tensor([[1, 2, 3], [4, 5, 6], [7...
<p>how about <code>topk</code>?</p> <pre><code>import torch matrix = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) values, indices = matrix.flatten().topk(k=3) print(values) # tensor([9, 8, 7]) print(indices) # tensor([8, 7, 6]) </code></pre> <p>Note that the indices are now pointing to the flattened vector. You ca...
python|pytorch
2
350,396
67,959,995
Python Flask App - failed building wheel for pandas
<p>I'm trying to deploy a simple python flask application. I have deployed a very similar app in the past with all the same requirements in the requirements.txt folder.</p> <p>While trying to push my repo to heroku using 'git push heroku master', heroku does its thing and eventually gives the following errors:</p> <pre...
<p>Try using latest pandas version. <code>pandas==1.2.4</code> works fine for me. You will have to update numpy as well, as it might create compatibility issues. Update numpy to <code>numpy==1.20.3</code>.</p>
python|pandas|flask|heroku
5
350,397
67,676,912
Store multiple print output values from for loop into a list or variable
<p>I am a few days into python and pandas and I am running into a situation that I can not seem to resolve on my own. I have a for loop to fetch status codes and print out the results if they meet certain criteria. The for loop I have is as followed:</p> <p>For loop:</p> <pre><code>import requests from requests.excepti...
<p>You can create a new list, for example <code>status_codes</code> and append the status to it after each iteration. Then you can use <code>zip()</code> to tie URL and status codes together or create new dataframe. For example:</p> <pre class="lang-py prettyprint-override"><code>import requests from requests.exception...
python|pandas|list|for-loop|variables
1
350,398
67,804,704
Taking average between two values in pandas Data frame
<p>lets say that i have the following Dataframe,</p> <pre><code>A B C D E 0 1.625627 8.910396 9.171640 1.980580 8.429633 1 7.228290 6.431085 5.399684 8.442247 2.609367 2 NaN NaN NaN NaN NaN 3 2.533768 3.877104 8.199575 5.138173 7.248905...
<p>Use <code>fillna()</code> and <code>shift()</code>. <code>shift(1)</code> will give you upper value (as its shift the dataframe downward) and <code>shift(-1)</code> will give you lower value(as its shift the dataframe upword).</p> <pre><code>df = df.fillna((df.shift(1)+df.shift(-1))/2) </code></pre> <p>or</p> <pre><...
python|pandas|dataframe|loops
3
350,399
67,613,939
Pandas - Extracting all text after the 4th character
<p>I am trying to see how can we extract all characters in a column after the 4th character.</p> <pre><code>col_a XYZ123 ABCD001 </code></pre> <p>Expecting the below</p> <pre><code>col_a, new_col XYZ123, 23 ABCD001, D001 </code></pre>
<p>Try with string slicing:</p> <pre><code>df['new_col']=df['col_a'].str[4:] </code></pre> <p><strong>OR</strong></p> <p>Via re module:</p> <pre><code>import re df['new_col']=df['col_a'].apply(lambda x:re.findall('[0-9]+', x)[0]) </code></pre>
pandas
6