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
5,000
37,153,692
write_formula gives error unless i copy and paste exactly the same formula
<p>I have a python script that writes excel file in the end with xlsxwriter. Everything works but a formula is giving error upon launching and if i copy and paste the exactly same formula it gives the results expected. here is the line:</p> <pre><code>worksheet.write_formula('I2', '=SUMIF(B2:B{0};1;F2:F{0})'.format(le...
<p>Goto the given link i believe you will find your answer: <a href="https://xlsxwriter.readthedocs.io/working_with_formulas.html" rel="nofollow">XlsxWriter: Working with Formulas</a> </p> <p>Specifically the Non US Excel functions and syntax says:</p> <p>Excel stores formulas in the format of the US English version,...
python|pandas|xlsxwriter
2
5,001
37,267,806
How to use pd.read_table with StringIO file object?
<p>I checked out <a href="https://stackoverflow.com/questions/18383711/read-table-with-stringio-and-messy-file">read_table with stringIO and messy file</a> but it has some stuff I can't reproduce like this raw object. Anyways, I want to write a table to a <code>StringIO</code> file object and then open that <code>Stri...
<p>StringIO uses a pointer to track the current position in the stream. Once you have written all data to the stream, use <code>f.seek(0)</code> to set the pointer back to the start.</p> <pre><code>import numpy as np import pandas as pd from io import StringIO #StringIO to write to f = StringIO() #Write to StringIO ...
python|pandas
4
5,002
41,962,580
Concatenate Using Lambda And Conditions
<p>I am trying to using lambda and map to create a new column within my dataframe. Essentially the new column will take column A if a criteria is met and column B is the criteria is not met. Please see my code below.</p> <pre><code>df['LS'] = df.['Long'].map(lambda y:df.Currency if y&gt;0 else df.StartDate) </code></p...
<p>Just do </p> <pre><code>df['LS']=np.where(df.Long&gt;0,df.Currency,df.StartDate) </code></pre> <p>which is the good vectored approach.</p> <p><code>df.Long.map</code> apply to each row, but return actually <code>df.State</code> or <code>df.current</code> which are Series.</p> <p>An other approach is to conside...
python|pandas|lambda
1
5,003
41,925,592
python plotting data marker
<p>I am trying to make a data marker on a python plot that shows the x and y coordinates, preferably automatically if this is possible. Please keep in mind that I am new to python and do not have any experience using the marker functionality in matplotlib. I have FFT plots from .csv files that I am trying to compare to...
<p>Create a <code>pd.Series</code> from <code>data</code></p> <pre><code>s = pd.DataFrame({ 'Frequency [Hz]': data[:, 0], 'Intensity [dBm]': data[:, 1] }).set_index('Frequency [Hz]')['Intensity [dBm]'] </code></pre> <p>Then plot with <a href="http://matplotlib.org/users/annotations_intro.html" rel...
python|python-2.7|pandas|matplotlib
1
5,004
37,865,177
Trouble creating dataframe using pandas: ValueError/data type not understood
<p>I'm a bit new to pandas/numpy and have had trouble with this issue.</p> <p>I have a group of 10 lists, each of which have 58 elements in them (strings). When I try to join them into a dataframe</p> <pre><code>df = pd.Dataframe(a, b, c, d, e, f, g, h, i, j) </code></pre> <p>I get the error <code>"ValueError: Shape...
<p>Use this:</p> <pre><code>df = pd.Dataframe([a, b, c, d, e, f, g, h, i, j]) </code></pre> <p>The difference</p> <pre><code># You had df = pd.Dataframe( a, b, c, d, e, f, g, h, i, j ) # ^ \________________________/ # | | # data argument | # ...
python|pandas|dataframe
0
5,005
37,851,796
low_memory parameter in read_csv function
<p>What does the <code>low_memory</code> parameter do in the <code>read_csv</code> function from the pandas library?</p>
<p>This come from the docs themselves. Have you read them?</p> <blockquote> <p>low_memory : boolean, default True Internally process the file in chunks, resulting in lower memory use while parsing, but possibly mixed type inference. To ensure no mixed types either set False, or specify the type wi...
python|pandas|ipython|spyder
1
5,006
37,730,760
np.gradient - correct use?
<p>I'm trying to use np.gradient to calculate a derivative, but I'm getting strange results and want to check that I'm using it correctly to eliminate that as a possible error.</p> <p>A have a function y(x) over a range of equally spaced (but not unity) x-value data points. I compute the derivative by </p> <pre><code...
<p>Looks right to me. Derivative of sin is cos. When I plot <code>np.gradient</code> of my sin function, it looks identical to when I plot cos directly.</p> <p>An example:</p> <pre><code>import numpy as np import pandas as pd x = np.arange(-2 * np.pi, 2 * np.pi, 0.01) y = np.sin(x) pd.Series(y).plot() </code></pre...
python|numpy|derivative
1
5,007
31,332,264
pandas plot xticks on x-axis
<p>I have a working code that displays a panda dataframe as 2 line graphs in a chart. I also have a dataframe that displays a bar graph on the same chart. For the 2 dataframes, i have date for the x-axis. Because the two dataframes have dates, my axis end up just having integers (1,2,3,4,5,6...) instead of the date.</p...
<p>You can just use <code>ax.plot(df1.date, df1.line1)</code> and <code>matplotlib.pyplot</code> will automatically take care of the date.</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt # your data # =================================== np.random.seed(0) df1 = pd.DataFrame(dict(d...
python|pandas|matplotlib|plot|dataframe
1
5,008
31,676,627
Unexpected Numpy / Py3k coercion rules
<p>I was looking for a bug in a program, and I discovered that it was produced by an unexpected behavior from Numpy...</p> <p>When doing, e.g., a simple arithmetic operation on different integer types using Python3k and Numpy, like</p> <p>(numpy.uint64) + (int)</p> <p>the result is... a numpy.float64</p> <p>Here's ...
<p>As noted above:</p> <p>It works fine with:</p> <pre><code>dtype=np.int64 </code></pre> <p>instead of:</p> <pre><code>dtype=np.uint64 </code></pre> <p>both for python 2 and 3, numpy 1.6 and 1.9. </p> <p>Just use:</p> <pre><code>np.int64 </code></pre> <p>there is no reason to use <code>uint64</code>, overflo...
python|numpy|typing|coerce
0
5,009
64,287,610
How to sum up values of 'D' column for every row with the same combination of values from columns 'A','B' and 'C?
<p>I need to <strong>sum up values of 'D' column for every row with the same combination of values from columns 'A','B' and 'C</strong>. Eventually I need to create DataFrame with unique combinations of values from columns 'A','B' and 'C' with corresponding sum in column D.</p> <pre><code>import numpy as np df = pd.Dat...
<pre><code>df.groupby(['A','B','C']).sum() </code></pre>
python|pandas|dataframe|apply|nan
1
5,010
64,575,922
How is it possible for Numpy to use comma-separated subscripting with `:`?
<p>Consider the following example:</p> <pre><code>&gt;&gt;&gt; a=np.array([1,2,3,4]) &gt;&gt;&gt; a array([1, 2, 3, 4]) &gt;&gt;&gt; a[np.newaxis,:,np.newaxis] array([[[1], [2], [3], [4]]]) </code></pre> <p>How is it possible for Numpy to use the <code>:</code> (normally used for slicing arrays)...
<p>Define a simple class with a <code>getitem</code>, indexing method:</p> <pre><code>In [128]: class Foo(): ...: def __getitem__(self, arg): ...: print(type(arg), arg) ...: In [129]: f = Foo() </code></pre> <p>And look at what different indexes produce:</p> <pre><code>In [130]: f[:] &lt;cla...
python|python-3.x|numpy
2
5,011
48,957,011
using sklearn linear regression fit on timeseries + plotting
<p>I have the following timeseries outputted by get_DP():</p> <pre><code> DP date 1900-01-31 0.0357 1900-02-28 0.0362 1900-03-31 0.0371 1900-04-30 0.0379 ... ... 2015-09-30 0.0219 [1389 rows x 1 columns] </code></pre> <p><em>note: There is a DP value for every month from ...
<p>try this one </p> <pre class="lang-py prettyprint-override"><code>reg = linear_model.LinearRegression() df = get_DP() df=df.reset_index() reg.fit(df.date.values.reshape(-1, 1), df.DP.values.reshape(-1, 1)) print("beta: {}".format(reg.coef_)) print("alpha: {}".format(reg.intercept_)) plt.scatter(df.date.dt.date, df....
python|pandas|plot
2
5,012
49,215,929
AttributeError: 'numpy.string_' object has no attribute 'items'
<p>In the following code</p> <pre><code>import time import nltk from nltk import word_tokenize import pandas as pd import numpy as np import matplotlib.pyplot as plt import networkx as nx import community ###############################################################################################################...
<p>This code</p> <pre><code>for k in range(10): num=np.log(p_rank[k])*7 nx.draw_networkx_labels(G,pos=pos_new[k],labels=labeldict[k], font_size=num, font_family='ubuntu') </code></pre> <p>should be </p> <pre><code>for node in range(10): font_size =...
python|numpy|matplotlib|networkx
1
5,013
59,042,282
Training my simple model for colored images instead of grayscale
<p>I'm new to Python and Deep Learning with Keras. With some tutorials online for cat vs non-cat classification, I was able to compile this simple training code for my classification. However, my target application is <strong>fire</strong> detection so I think I need to use color images instead of this grayscale versio...
<p>for transforming your images, you have to duplicate the channels of your single image. Note that you need only the "convered image afte duplicating the channels. you can write a function that does the following and pass it to the comprehension list</p> <pre><code>&gt;&gt;&gt; img = np.random.randint(low=0,high=255,...
python|tensorflow|keras|deep-learning|classification
0
5,014
58,940,304
Split output variable into similarly sized dataframes and merge those
<p>My problem: Trying to <strong>split an output variable into similarly sized dataframes and merge those</strong>.</p> <p>Model output: "var"</p> <pre><code>{('Product1', 0): &lt;gurobi.Var listing[Product1,0] (value 1.0)&gt;, ('Product1', 1): &lt;gurobi.Var listing[Product1,1] (value 0.0)&gt;, ('Product1', 2): &lt;...
<p>You can try from this</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd from io import StringIO txt = """ listing (Product1,0) 1.0 (Product1,1) 0.0 (Product1,2) 0.0 (Product1,3) 0.0 (Product2,0) 1.0 (Product2,1) 0.0 (Product2,2) 0.0 (Product2,...
python|pandas|gurobi
1
5,015
58,664,602
Why do I lose indexes and column header information on using np.hstack when concatenating two df in python?
<p>I have two dataframes: Reprex:</p> <p>DF1</p> <pre><code>X Yes No Maybe </code></pre> <p>DF2</p> <pre><code>Y Yes No Maybe import pandas as pd import numpy as np train = pd.DataFrame(np.hstack([DF1,DF2])) </code></pre> <p>train</p> <pre><code>0 1 Yes Yes No No Maybe Maybe </code></pre> <p>Why do my headers ...
<p>The reason is that <em>Numpy</em> methods operate not on DataFrames, but on underlying <em>Numpy</em> arrays, <strong>without</strong> any index or column data (indices of rows and columns names).</p> <p>To check this, run: <code>np.hstack([DF1, DF2])</code> and you will get:</p> <pre><code>array([['Yes', 'Yes'], ...
pandas|numpy|dataframe|concat
1
5,016
55,975,707
Replace a string with a shorter version of itself using pandas
<p>I have a pandas dataframe with one column of model variables and their corresponding statistics in another column. I've done some string manipulation to get a derived summary table to join the summary table from the model.<br> <code>lost_cost_final_table.loc[lost_cost_final_table['variable'].str.contains('class...
<p>The index of <code>lost_cost_final_table</code> is not unique, which can be fixed by running <code>reset_index</code>:</p> <pre><code>lost_cost_final_table.reset_index(inplace=True) </code></pre>
python|pandas
1
5,017
64,971,704
How to mix many distributions in one tensorflow probability layer?
<p>I have several <code>DistributionLambda</code> layers as the outputs of one model, and I would like to make a Concatenate-like operation into a new layer, in order to have only one output that is the mix of all the distributions, assuming they are independent. Then, I can apply a log-likelihood loss to the output of...
<p>The problem is your Input, not your output layer ;)</p> <p>Input:0 is referenced in your error message. Could you try to be more specific about your input?</p>
python|tensorflow|keras|tf.keras|tensorflow-probability
0
5,018
39,731,669
Merge Variables in Keras
<p>I'm building a convolutional neural network with Keras and would like to add a single node with the standard deviation of my data before the last fully connected layer.</p> <p>Here's a minimum code to reproduce the error:</p> <pre><code>from keras.layers import merge, Input, Dense from keras.layers import Convolut...
<p><code>std</code> is no Keras layer so it does not satisfy the layer input/output shape interface. The solution to this is to use a <a href="https://keras.io/layers/core/#lambda" rel="nofollow"><code>Lambda</code></a> layer wrapping <code>K.std</code>:</p> <pre><code>from keras.layers import merge, Input, Dense, Lam...
python|tensorflow|keras
1
5,019
69,661,048
Stacking multiple arrays with multiple dimensions python
<p>I am trying to create and stack multiple multi-dimensional arrays in python and I seem not to be able to get it right.</p> <p>I have:</p> <pre><code> y_0 = np.random.uniform(-1.0,1.0, size=(1,1,s_conn.weights.shape[0],1)) y_1 = np.random.uniform(-500.0, 500.0, size=(1,1,s_conn.weights.shape[0],1)) y_2 = np.r...
<p>np.stack joins a sequence of arrays along a new axis, so it will create an undesired dimension to your matrix, consider using np.concatenate.</p> <pre><code>np.concatenate([y_0,y_1,y_2,y_3,y_4,y_5],axis = 1) </code></pre> <p>Note, your can also use Array.squeeze() to remove undesired dimensions (that may arise when ...
python|arrays|numpy
0
5,020
69,451,925
Numpy matmul, treat each row in matrix as individual row vectors
<p>I have a code below:</p> <pre><code>import numpy as np wtsarray # shape(5000000,21) covmat # shape(21,21) portvol = np.zeros(shape=(wtsarray.shape[0],)) for i in range(0, wtsarray.shape[0]): portvol[i] = np.sqrt(np.dot(wtsarray[i].T, np.dot(covmat, wtsarray[i]))) * np.sqrt(mtx) </code></pre> <p>Nothing wrong wi...
<pre class="lang-py prettyprint-override"><code>portvol = np.sqrt(np.sum(wtsarray * (wtsarray @ covmat.T), axis=1)) * np.sqrt(mtx) </code></pre> <p>should give you what you want. It replaces the first <code>np.dot</code> with elementwise multiplication followed by summation and it replaces the second <code>np.dot(covma...
python|numpy
2
5,021
40,873,279
Geopandas : sort a sample of points like a cycle graph
<p>I'm trying geopandas to manipulate some points data. My final GeoDataFrame is represented there :</p> <p><a href="https://i.stack.imgur.com/UgKLf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UgKLf.png" alt="20 little points"></a></p> <p>In order to use <a href="http://geoffboeing.com/2016/11/...
<p>If I understand your question correctly, you want to rearrange the order of points in a way that they would create the shortest possible path. </p> <p>I have run into the same problem also. Here is the function that accepts regular dataframe (= with separate fields for each coordinate. I am sure you will be able t...
python|sorting|pandas|geopandas
1
5,022
53,923,354
Reorder columns based on column suffixes
<p>This is my code:</p> <pre><code>all_data = pd.merge(all_data, meanData, suffixes=["", "_mean"], how='left', on=['id', 'id2']) </code></pre> <p>Now, I want to merge <code>all_data</code> and <code>meanData</code>, but I want the columns of meanData to appear first. </p> <p>Like this:</p> <blockquote> <p>a_mean,...
<p>I think you can use <a href="https://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation" rel="nofollow noreferrer"><code>transform</code></a> after the <code>groupby</code> to get the <code>mean</code> related to each row, and then <code>pd.concat</code> the dataframes such as:</p> <pre><code>new_df =...
python|pandas
2
5,023
38,069,417
"ImportError: cannot import name SkipTest" while importing numpy in python
<p>I am having problem while importing numpy.</p> <p>Please fin below version information:</p> <pre><code># cat /etc/redhat-release CentOS release 6.5 (Final) # python -V Python 2.6.6 </code></pre> <p>I have already installed numpy (re-installed several times) using pip.</p> <pre><code># pip install numpy </code><...
<p>Seems like I have to upgrade my python version. In fact, after installing python2.7 everything is smooth.</p> <p>I have installed python2.7 followed by numpy as below:</p> <pre><code>yum install python27 scl enable python27 bash pip2.7 install numpy </code></pre> <p>Then I was able to import numpy using python2.7...
python|numpy|importerror
1
5,024
38,484,896
R Iterate a calculation from a variable
<p>I have a data base of postal code. I want to create for each postal code, 4 variables which are the year, the month, the day and the hour from 01.01.2008 to 30.06.2008 The goal is to create an indicator that calculate a number of alarms that have been pulled.</p>
<p>I tried this :</p> <p>for (elt in c$CP) For each elt do</p> <pre><code> time_index=seq(from = as.POSIXct("2008-01-01 00:00"), to = as.POSIXct("2016-06-30 23:00"), by = "hour")) </code></pre> <p>At the end i want a unique database where i have 2 column CP (postal code) and time_index I will have to app...
r|database|pandas|data-science
0
5,025
38,383,477
numpy meshgrid filter out points
<p>I have a meshgrid in numpy. I make some calculations on the points. I want to filter out points that could not be calcutaled for some reason ( division by zero).</p> <pre><code>from numpy import arange, array Xout = arange(-400, 400, 20) Yout = arange(0, 400, 20) Zout = arange(0, 400, 20) Xout_3d, Yout_3d, Zout_3d ...
<p>To perform <code>z / ( y - x )</code> using those <code>3D</code> mesh arrays, you can create a mask of the valid ones. Now, the valid ones would be the ones where any pair of combinations between <code>y</code> and <code>x</code> aren't identical. So, this mask would be of shape <code>(M,N)</code>, where <code>M</c...
python|numpy
1
5,026
66,284,509
Iterating each row with remaining rows in pandas data frame
<p>I am trying to iterate each row in dataframe with subsequent row. The first iteration works but I want to iterate for all other iterations like [111,.....] with remaining and continues. How can I achieve it using iterator?</p> <pre><code>test = [[1,2,3,4,5,6,7,8,9,10],[11,22,33,44,55,66,77,88,99,100],[111,222,333,44...
<p>You don't need to use <code>next</code> these cases, a for loop &quot;knows&quot; how to deal with iterators. Skip the <code>next</code>, just use the iterator directly:</p> <pre class="lang-py prettyprint-override"><code>for i, row in df.iterrows(): print(i, row) </code></pre>
python|pandas|database|iterator|iteration
0
5,027
66,041,108
Sorting a pandas dataframe based on number of values of a categorical column
<p>The sample dataset looks like this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">col1</th> <th style="text-align: center;">col2</th> <th style="text-align: right;">col3</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">A</td> <td style="text-align...
<p>Create helper column by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="noreferrer"><code>Series.map</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="noreferrer"><code>Series.value_counts</code></a...
python|pandas|dataframe
5
5,028
52,657,837
Python Pandas grouping columns
<p>This is a Pandas question - my brain is too tired to figure this out today. Could someone please help me? I have a dataframe with many columns with one column as a category:</p> <pre><code>Category B C D .... Z 1 2 11 1.0 'HOME' .... 1 3 21 1.0 'HOME' .... 1 1 33 .9 'GOPHER' .... 2 4 3...
<p>You can use <code>GroupBy</code> + <code>agg</code> to specify a different function for each series. I have linked <code>C</code> and <code>Z</code> series to <code>'first'</code>, i.e. extract the first value from each group, as this is consistent with your desired output.</p> <pre><code>agg_rules = {'B': 'sum', '...
python|pandas|dataframe|pandas-groupby
1
5,029
46,240,895
expanding multipolygon in geopandas dataframe
<p>I have a shapefile which contains both polygons and multipolygons as following:</p> <pre><code> name geometry 0 AB10 POLYGON ((-2.116454759005259 57.14656265903432... 1 AB11 (POLYGON ((-2.052573095588467 57.1342600856536... 2 AB12 (POLYGON ((-2.128066321470298 57.03...
<p>We can use numpy for more speed if you have only two columns. </p> <p>If you have a dataframe like </p> <pre> name geometry 0 0 polygn(x) 1 2 (polygn(x), polygn(x)) 2 3 polygn(x) 3 4 (polygn(x), polygn(x)) </pre> <p>Then numpy meshgrid will help </p...
python|pandas|shapefile|geopandas
2
5,030
46,502,685
How to join several big arrays into one?
<p>I'm fairly new to python, and I have 5 big arrays A,B,C,D,E with shapes:</p> <pre><code>((1000000, 8), (1000000, 7), (1000000, 13840), (1000000, 204), (1000000, 3)) </code></pre> <p>dtypes:</p> <pre><code>(dtype('float64'), dtype('float64'), dtype('int64'), dtype('int64'), dtype('float64')) </code></pre> <p>Now ...
<p>Given 64-bit (8 byte) values, you are trying to process:</p> <pre><code>1000000 * 14062 * 8 * 2 = 224'992'000'000 bytes </code></pre> <p>The 2 on the end is because you have inputs plus equal-size outputs.</p> <p>That is 209 GiB of data. You have 16 GiB of RAM. It is not feasible. You'll need to think harder a...
python|arrays|numpy|memory-management|cpu-usage
3
5,031
58,369,571
Creating a new column via file name
<p>I will like to read multiple file and add a new column year. File Name: Shirt_2016, Shirt_2017, Shoe_2018, Shoe_2019,</p> <pre><code>rawfolder = 'c:/users/a/desktop/item' A = pd.DataFrame(pd.read_excel('%s/Shirt_2016' %(rawfolder), sheetname="sheet1", header=None) B = pd.DataFrame(pd.read_excel('%s/Shirt_2017' %(r...
<p>I would create list with filenames </p> <pre><code>filenames = ['Shirt_2016', 'Shirt_2017', 'Shoe_2018', 'Shoe_2019', ...] </code></pre> <p>and then use <code>for</code>-loop to read files </p> <pre><code>rawfolder = 'c:/users/a/desktop/item' all_df = [] for name in filenames: path = os.path.join(rawfolder, n...
python|pandas
0
5,032
69,094,812
Plotting a vector field using quiver
<p>I'm trying to reproduce a 2D vector map with components</p> <pre><code> v = 100/a * exp(-1/a^2 * ((x+0.55)^2+y^2))(-y,x) - 100/a * exp(-1/a^2 * ((x-0.55)^2+y^2))(-y,x) </code></pre> <p>and here are my codes. It did not give the map I want (see attached <a href="https://i.stack.imgur.com/Xqkjm.png" rel="nofollow nore...
<p>In the last passage, when you compute <code>vx[i,j]</code> and <code>vy[i,j]</code>, you are computing vector field components in <code>(x0, y0)</code>, while you should compute it in the current point, so <code>(x0 ± 0.55, y0)</code>. Moreover, you should change the sign of <code>vx</code> and <code>vy</code> in or...
python|numpy|matplotlib|math|plot
3
5,033
44,479,384
pandas rolling apply doesn't do anything
<p>I have a DataFrame like this:</p> <pre><code>df2 = pd.DataFrame({'date': ['2015-01-01', '2015-01-02', '2015-01-03'], 'value': ['a', 'b', 'a']}) date value 0 2015-01-01 a 1 2015-01-02 b 2 2015-01-03 a </code></pre> <p>I'm trying to understand how to apply a custom rollin...
<p>Here is one way this could be approached. Noting that <code>rolling</code> is a wrapper for <code>numpy</code> methods and the efficiency associated with those, this is <em>not</em> that. This merely provides a similiar api, to allow rolling on non-numeric columns:</p> <h3>Code:</h3> <pre><code>import pandas as pd ...
python|pandas
3
5,034
44,779,315
Detrending data with nan value in scipy.signal
<p>I have a time series dataset with some nan values in it. I want to detrend this data:</p> <p>I tried by doing this:</p> <pre><code>scipy.signal.detrend(y) </code></pre> <p>then I got this error:</p> <pre><code>ValueError: array must not contain infs or NaNs </code></pre> <p>Then I tried with:</p> <pre><code>sc...
<p>For future reference there is a digital signal processing Stack site, <a href="https://dsp.stackexchange.com/">https://dsp.stackexchange.com/</a>. I would suggest using that in the future for signal processing related questions.</p> <hr> <p>The easiest way I can think of is to manually detrend your data. You can d...
python|numpy|scipy|trend
5
5,035
60,974,056
Tensorflow Keras - feeding input to multiple model layers in parallel
<p>With tensorflow.keras (Tensorflow 2), I want to feed my input into different layers of my model. So we are looking at a graph where the input layers branches off into 3 lines to go to 3 different convolutional layers. It has 3 outputs.</p> <p>Pseudocode is something like this:</p> <pre><code>inputs = Input() conv1...
<p>Issue solved. I should be providing a 3-array of labels.</p>
tensorflow|keras|neural-network
0
5,036
61,118,179
How to replace row value without changing the other values in dataframe pandas?
<p>I am running one python script. I want to change particular row value without changing the other value. Can you please help me how to do this?</p> <p>example:</p> <pre><code>df1 Table Count case 20 recordtype 50 consumer 70 settlement 150 address 250 bridge 13...
<p>I fixed the issue using below code:</p> <pre><code>if(os.path.isfile('/medaff/Scripts/python/count.txt')): df_s1 = pd.read_csv('/medaff/Scripts/python/count.txt', delimiter='|') for index, row in df_s.iterrows(): print(row) print(row['Master Job Name']) ...
python|pandas|csv|dataframe
0
5,037
71,532,830
How do I parse a multi nested (5/6) JSON object and convert it to a dataframe?
<p><strong>Problem:</strong> I have a multi nested JSON file that I need to parse and convert to a pandas dataframe where every field is a column. I've taken 2 approaches:</p> <ol> <li>Convert raw file to data dictionary</li> <li>Convert raw file to JSON object</li> </ol> <p><strong>For data dictionary I've tried:</str...
<p>I wrote a function to flatten a dict like yours.</p> <pre><code>def flatten(d): ret = {**d} for k, v in d.items(): if isinstance(v, dict): ret.pop(k) ret = {**ret, **flatten(v)} elif isinstance(v, list): ret.pop(k) for item in v: ...
python|json|pandas|dataframe|nested
0
5,038
71,724,930
Improve speed of getpixel and putpixel
<p>Using PIL, I'm applying a rainbow filter to the given image using <code>getpixel</code> and <code>setpixel</code>. One issue, this method is very slow. It takes around 10 seconds to finish one image.</p> <pre class="lang-py prettyprint-override"><code>def Rainbow(i): x = 1 - abs(((i / 60) % 2) - 1) i %= 360 ...
<p>I was intrigued by this and decided to have a go at optimising the code from @I'mahdi.</p> <p>My ideas were as follows:</p> <ul> <li><p>Create and zero the output image up-front and avoid writing the already zeroed elements in the main loops</p> </li> <li><p>Only use parallelised <code>nb.prange()</code> for the <e...
python|numpy|image-processing|python-imaging-library
2
5,039
71,565,032
How to see city map when ploting with Geopandas lib
<p>I have just started learinig Geopandas lib in Python. I have a dataset with Lat(E) and Lon(N) of car accidents in Belgrade.</p> <p>I want to plot those dots on the map of Belgrade.</p> <p>This is my code:</p> <pre><code>import pandas as pd import geopandas as gpd import matplotlib.pyplot as plt pd.set_option('displ...
<ul> <li>as per comments, <strong>folium</strong> provides base map of overall geometry</li> <li>have added two layers <ol> <li>Belgrade, I have obtained this geometry from <strong>osmnx</strong> this is beyond the scope of this question so have just included the polygon as a <strong>WKT</strong> string</li> <li>the ...
python|gis|geospatial|geopandas
2
5,040
71,771,578
df.drop_duplicates, is not working what am i doing wrong?
<p>i am trying to search a text for chapters and then extract the text chapter by chapter. my search array returns the chapter name and the start and end positions in the text. it looks like this.</p> <pre><code> SearchTerm Start End 0 ITEM 1. 7219 47441.0 1 ITEM 2. 47441 57712.0 2 ITEM 3. 57712 7673...
<pre><code>How about using group by to pick the last one? (You can change the max of End if that's what you want) df = pd.read_csv(&quot;/tmp/Book2.csv&quot;) df.sort_values(by=['Search Term', 'Start']).groupby('Search Term').max('Start') Search Term Start End ITEM 1 91387...
python|pandas
0
5,041
42,473,383
Django Pandas AWS
<p>I am attempting to deploy a Django project on AWS Elastic Beanstalk. One of my views makes use of Pandas to generate some data.</p> <p>I was able to get Pandas to compile properly on my EBS hosted site. I was noticing however that the browser would become "hung" when I tried to access any pages. I removed the view ...
<p>I've had problems using panda w/django on a micro aws ec2 instance because of too little memory. Upgrading the instance solved the problem for me - </p> <p>If you are using a t2.micro for example, i might be worth upgrading to a larger instance just to see if the problem magically disappears - like it did for me.</...
python|django|pandas|amazon-web-services|amazon-elastic-beanstalk
2
5,042
43,354,696
Trying to append content to numpy array
<p>I have a script that searches Twitter for a certain term and then prints out a number of attributes for the returned results.</p> <p>I'm trying to Just a blank array is returned. Any ideas why?</p> <pre><code>public_tweets = api.search("Trump") tweets_array = np.empty((0,3)) for tweet in public_tweets: user...
<p><code>np.append</code> doesn't modify the array, you need to assign the result back:</p> <pre><code>tweets_array = np.append(tweets_array, [[username, location, tweetText]], axis=0) </code></pre> <p>Check <code>help(np.append)</code>:</p> <blockquote> <p>Note that <code>append</code> does not occur in-pla...
arrays|loops|numpy|tweepy|textblob
0
5,043
43,195,510
Speeding up a linear transform using parallel Cython
<p>I need to speed up the calculation of a linear transform which is roughly of the following form:</p> <pre><code>import numpy as np N=10000 input=np.random.random(N) x=np.linspace(0,100,N) y=np.linspace(0,30,N) X,Y=np.meshgrid(x,y,sparse=True) output=np.dot(np.cos(X*Y),input) </code></pre> <p>That is, I evaluate...
<p>On my laptop, the following <a href="https://github.com/serge-sans-paille/pythran" rel="nofollow noreferrer">pythran</a> version:</p> <pre><code>#pythran export transform(float64[], float64[], float64[]) import numpy as np def transform(x, y, input): N = x.shape[0] output = np.zeros(N) #omp parallel f...
numpy|parallel-processing|cython|numexpr
1
5,044
43,058,241
Applying a function to a 3D array in numpy
<p>I have a 3D numpy.ndarray (think of an image with RGB) like</p> <pre><code>a = np.arange(12).reshape(2,2,3) '''array( [[[ 0, 1, 2], [ 3, 4, 5]], [[ 6, 7, 8], [ 9, 10, 11]]])''' </code></pre> <p>and a function that handles a list input;</p> <pre><code>my_sum = lambda x: x[0] + x[1] + x[2] </code></pre> <p>...
<p>One option is to transpose the numpy array, swap the third axis to the first, and then you can apply the function directly to it:</p> <pre><code>my_sum(a.transpose(2,0,1)) #array([[ 3, 12], # [21, 30]]) </code></pre> <p>Or rewrite the sum function as:</p> <pre><code>my_sum = lambda x: x[..., 0] + x[..., 1]...
python|numpy|image-processing|matrix
4
5,045
72,155,950
how to set the gradient for a network in pytorch
<p>I have a model in pytorch. The model can take any shape but lets assume this is the model</p> <pre><code>torch_model = Sequential( Flatten(), Linear(28 * 28, 256), Dropout(.4), ReLU(), BatchNorm1d(256), ReLU(), Linear(256, 128), Dropout(.4), ReLU(), BatchNorm1d(128), ReLU...
<p>In PyTorch, with a model defined as yours above, you can iterate over the layers like this:</p> <pre><code>for layer in list(torch_model.modules())[1:]: print(layer) </code></pre> <p>You have to add the <code>[1:]</code> since the first module returned is the sequential module itself. In any layer, you can access ...
python|neural-network|pytorch|gradient-descent|stochastic-gradient
0
5,046
72,322,230
Looping (for) through some data, concatenating along the way, appending to a list in final, but dimensions don't match in python
<p>Here is the code:</p> <pre><code>#new_right_v2 = [] for i in range(rows): r1_p5_first_half = np.concatenate( (new_right[i,:312].reshape(1,-1), new_right[i,625:937].reshape(1,-1), new_right[i,1250:1562].reshape(1,-1), new_right[i,1875:2187].reshape(1,-1)),axis=1) #print(r1_p5_first_half.shape) r1_p5_secon...
<p>I am actually not sure what dimensions are you checking, as <code>new_right_v2</code> seems to be a list</p> <p>Maybe you can apply the operations matrix-wise to all rows at once?</p> <pre><code>first_half = np.concatenate( new_right[:,:312], new_right[:,625:937], new_right[:,1250:1562], new_right[:,...
python|numpy
1
5,047
72,355,950
How to change function values inside an if loop
<pre><code>import numpy as np from ufl import cofac, sqrt def f(X): fx = sqrt(X[0]**2+X[1]**2) return fx X = np.array([1.0, 2.0]) Y = f(X) print(Y) if f(X)&lt;=3: f(X)=0.0 print(f(X)) exit() </code></pre> <p>The above function calculates the distance of a point from the origin. If the distance is less than...
<p>Sounds like you want the <code>f()</code> function to return different results depending on the values in X.</p> <pre><code>def f(X): fx = sqrt(X[0]**2+X[1]**2) if fx &gt; 3: return fx else: return 0.0 </code></pre>
python|arrays|numpy
1
5,048
62,560,844
Python: Average over bins
<p>I created bins for age and have a productivity factor (Prod). Now I want to group the bins and calculate average over Prod. So that in the end I have age categories with their average productivity.</p> <pre><code> bin Prod 1 (40, 50] 72.920192 2 (30, 40] 51.582848 3 (20, 30] 17.478928 4 (...
<p>Use <code>df.groupby('bin')['Prod'].mean()</code>.</p>
python|numpy
0
5,049
62,781,688
Two different styles of Tensorflow implementation for the same network architecture lead to two different results and behaviors?
<ul> <li>OS Platform: Linux Centos 7.6</li> <li>Distribution: Intel Xeon Gold 6152 (22x3.70 GHz);</li> <li>GPU Model: NVIDIA Tesla V100 32 GB;</li> <li>Number of nodes/CPU/Cores/GPU: 26/52/1144/104;</li> <li>TensorFlow installed from (source or binary): official webpage</li> <li>TensorFlow version (use command below): ...
<p>As it is pointed in the comment I made mistake in using the evaluation metrics. I should have used BinaryAccuracy.</p> <p>Moreover, it is better to edit the call in the advance version as follows:</p> <pre><code>def call(self, x, training=False): x = self.d1(x) if training: x = self.d2(x, training=tr...
python|tensorflow|machine-learning|keras
0
5,050
62,503,373
TypeError: get_file() missing 1 required positional argument: 'origin'
<p>I'm trying to use my own .txt file in tensorflow, but when I run it in jupyter notebook i get this</p> <pre><code>TypeError Traceback (most recent call last) &lt;ipython-input-28-b7f323158fac&gt; in &lt;module&gt; 5 import time 6 ----&gt; 7 path_to_file = tf.keras.utils.g...
<p>I believe what you want here is:</p> <pre class="lang-py prettyprint-override"><code>path_to_file = tf.keras.utils.get_file('Jezuz.txt', 'https://storage.googleapis.com/jezuz/Jezuz.txt?x-goog-signature=287cd6ea9dbdc21b1002c85e9c064a70b422b3cf7458bf047cb5e476a5073e248d1c25c1ee9b7bfe6c981b3ef2cec705426beb592d5d6feeb8b...
python|tensorflow
0
5,051
62,502,529
Understanding the double star notation in Python in an algorithm
<p>I am confused about the following code in Python:</p> <pre><code>import numpy as np from numpy.random import rand, randn def generate_data (beta, n): u= np.random.rand(n,1) y= (u**np.arange(0,4))@beta return y np.random.seed(12) beta = np.array([[10,-140,400,-250]]).T n = 5 y = generate_d...
<p>The ** will do the power operation element wise. Here is some example code that will make it clear:</p> <pre><code>&gt;&gt;&gt; a = np.array([2,3,4]) &gt;&gt;&gt; b = np.array([1,2,3]) &gt;&gt;&gt; a**b array([ 2, 9, 64], dtype=int32) </code></pre> <p>As you can see, the 0th element of a is raised to the power of t...
python|python-3.x|numpy
1
5,052
54,497,443
Exporting pandas dataframe to CSV
<p>I'm loading a SQL table into a dataframe, and then pushing it directly into a CSV. The Problem is the export. I require:</p> <pre><code>value|value|value </code></pre> <p>and I'm getting:</p> <pre><code>"(value|value|value)" </code></pre> <p>How do I get out of that?</p> <p>Here's my code:</p> <pre><code>for...
<p>Provided that you can use <code>sqlalchemy</code> package, you would be able to take advantage of the <code>pd.read_sql</code> function which handles querying the database and retrieving the data.</p> <pre><code>import pandas as pd pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) from...
python|pandas|csv
0
5,053
73,543,076
How to transform Array into CSV Format in Python using DataFrame?
<p>I am currently fetching data from an RestAPI which I then want to process. However, the platform I use needs the data to be transformed with the pandas dataframe. In order to get it into the correct format, I need to transform this response:</p> <pre><code>data = { &quot;apple&quot;:{ &quot;price&quot;: ...
<p>You can use:</p> <pre><code>df = pd.DataFrame(data) out = df.T.rename_axis('product').reset_index() </code></pre> <p>output:</p> <pre><code> product price category weight 0 apple 0.89 fruit 13.88 1 carrot 1.87 vegetable 3.23 </code></pre> <p>as dictionary:</p> <pre><code>out = df.T.rename_axis('pro...
python|pandas|dataframe
2
5,054
73,689,334
Keras save model with named layers
<p>I have a keras model where each layer has a specific name</p> <pre><code>def build_model(): input_layer = keras.Input(shape=input_shape, name='input') conv1 = layers.Conv2D(32, kernel_size=(3, 3), activation=&quot;relu&quot;, name='conv1')(input_layer) maxpool1 = layers.MaxPooling2D(pool_size=(2, 2), name='max...
<p>In order to save the entire model I would use the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/models/save_model" rel="nofollow noreferrer">SavedModel</a> format, that saves your model as a <code>.pb</code>:</p> <pre><code>import tensorflow as tf tf.keras.models.save_model(model, &quot;test_model&quo...
python|python-3.x|tensorflow|keras|tf.keras
0
5,055
73,623,626
Why is my pytorch Autoencoder giving me a "mat1 and mat2 shapes cannot be multiplied" error?
<p>I know this is because the shapes don't match for the multiplication, but why when my code is similar to most example code I found:</p> <pre><code>import torch.nn as nn ... #input is a 256x256 image num_input_channels = 3 self.encoder = nn.Sequential( nn.Conv2d(num_input_channels*2**0, num_input_channels...
<p>All <code>torch.nn</code> Modules require batched inputs, and it seems in your case you have no batch dimension. Without knowing your code I'm assuming you are using</p> <pre><code>my_input.shape == (3, 256, 256) </code></pre> <p>But you will need to add a batch dimension, that is, you need to have</p> <pre><code>my...
python|pytorch|autoencoder
1
5,056
71,298,878
Convert JSON response from request into Pandas DataFrame
<p>I want to iterate over a dataframe by rows and use cell values to pull data from an api and assign the response to a new column. I got the response and everything works but i need to convert the json response into a dataframe column so i wrote a function similar to this</p> <pre><code>def get(): response=requests....
<p>Did you try <code>json_normalize</code> method?</p> <p>There is an example of using:</p> <pre><code>import json # load data using Python JSON module with open('data/nested_mix.json','r') as f: data = json.loads(f.read()) # Normalizing data df = pd.json_normalize(data, record_path =['students']) </code></pre...
python|json|pandas|dataframe
1
5,057
71,384,835
Merge two lines into one and create Pandas DataFrame
<p>I have a file with data which is not easy to make stucure ready to create dataframe.</p> <pre><code>SFE, 8924, 3,CONV,1,R5.0 1.267065000E-04 1.267065000E-04 1.267065000E-04 1.267065000E-04 SFE, 8924, 3,CONV,2,R5.0 761.000000 761.000000 761.000000 761.000000 SFE, 8925, 3,CONV,1...
<p>This should work:</p> <pre><code>data = [] with open(&quot;7HA03_thermal_final_filled.txt&quot;) as f: content = f.readlines() for i in range(1, len(content)+1): if i % 2 == 0: first_line = content[i-2].strip() first_line = &quot;&quot;.join(first_line.split()) sec...
python|pandas
0
5,058
71,354,133
Python how to round Timestamp object to the previous full hour
<p>Hi have a list of timestamp objects:</p> <pre><code>Timestamp('2021-07-07 10:00:03'), Timestamp('2021-07-07 10:02:13'), Timestamp('2021-03-07 12:40:24') </code></pre> <p>And I want to round each element at the hour level, to get:</p> <pre><code>Timestamp('2021-07-07 10:00:00'), Timestamp('2021-07-07 10:00:00'), Time...
<p>Given</p> <pre><code>&gt;&gt;&gt; df time 0 2021-07-07 10:00:03 1 2021-07-07 10:02:13 2 2021-03-07 12:40:24 </code></pre> <p>Use</p> <pre><code>&gt;&gt;&gt; df['time'] = df['time'].dt.floor('1h') &gt;&gt;&gt; df time 0 2021-07-07 10:00:00 1 2021-07-07 10:00:00 2 2021-03-07 12:00:0...
python|pandas|dataframe|datetime|timestamp
0
5,059
71,153,198
How to find a word with letters in specific places within a dataframe - Jupyter
<p>I am trying to find words with letters in specific positions within my dataframe. My dataframe is a list of all 5 letter words in English in all lower-case and no special characters (i.e. only alpha characters).</p> <p>df = list of 5 letter words</p> <p>word = column of words</p> <p>Code:</p> <pre><code>firstLetter...
<p>Here is necessary return Trues if no value is typing in input (empty string), so mask for test values by positions is:</p> <pre><code>firstLetter = input('First Letter = ') secondLetter = input('Second Letter = ') thirdLetter = input('Third Letter = ') fourthLetter = input('Fourth Letter = ') fifthLetter = input('Fi...
python|pandas|jupyter-notebook
2
5,060
60,731,718
Pandas group by and filter
<p>I have the following .csv</p> <pre><code> Name Location Product Type number Greg 1 Fruit grape 1 Greg 1 Fruit apple 2 Greg 1 Bakery bread 5 Greg 1 Bakery roll 8 Greg 2 Fruit grape 7 Greg 2 Fruit apple 1 Greg 3 Fruit grap...
<p>IIUC use <code>transform</code> with <code>nunique</code> </p> <pre><code>df1=df[df.groupby(['Name','Location']).Product.transform('nunique')&gt;1] Name Location Product Type number 0 Greg 1 Fruit grape 1 1 Greg 1 Fruit apple 2 2 Greg 1 Bakery bread ...
python|pandas
1
5,061
72,527,661
How to merge 2 rows into 1 row with 2 different columns?
<p>I would like to merge 2 or 3 row into 1 row like below.</p> <p>Original chart:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>CaseNr</th> <th>AccType</th> <th>Vehicle</th> <th>Model</th> <th>VehicleMass</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>1</td> <td>PassengerCar</td> <td>A1<...
<p>Use <code>pivot</code> to reshape your data. This is called reshaping to wide and not merging.</p> <pre><code>df1 = df.assign(name = df.groupby('CaseNr').cumcount() + 1).pivot(['CaseNr', 'AccType'], 'name') df1.columns = df1.columns.map(lambda x:f'{x[0]}_{x[1]}') df1.reset_index() CaseNr AccType Vehicle_1 ....
python|pandas|dataframe|merge|concatenation
1
5,062
59,481,023
Seaborn: how to get labels nicely centered in a column?
<p>This is the code of my plot:</p> <pre class="lang-py prettyprint-override"><code>from matplotlib import pyplot as plt import pandas as pd import seaborn as sns data = pd.read_csv('titanic.csv') ax = sns.countplot(x='Survived', hue='Pclass', data=data, palette="pastel") ax.set_title("Survival in terms of Pclass", f...
<p>What you want is to have the text centered with respect to the patch. You already have the x-position. The width of the patch is <code>p.get_width()</code>. Just divide it by 2 and add it to the x-position to get the center.</p> <p>You can add <code>plt.tight_layout()</code> to nicely fit the plot and its labels int...
python|pandas|seaborn
4
5,063
59,831,473
How to loop over dataframe and remove rows?
<p>I'm trying to loop over a dataframe and remove rows where the value in the 'player_fifa_api_id' column is equal to the value in the previous row. For some reason, my code isnt working:</p> <pre><code>for i in range(0,len(test)-1): print("{} lines out of {} processed".format(i,len(test))) if test['player_fif...
<p>You should avoid looping through a dataframe. There is often much faster and more elegant solutions using vectorized functions. In your case, filter for the rows you want:</p> <pre><code>player_id = test['player_fifa_api_id'] # if the current row is not equal to the previous row, then keep the current row keep = p...
python|pandas|dataframe
3
5,064
59,837,519
Pandas read_excel - returning nan for cells having formula
<p>I have an excel file that contains accounting data and also the file use formula for some of the cells. When I use pandas read_excel to read the values in the file, it returns <code>nan</code> value for cells having formula's. I have also used openpyxl, but still having the same issue.</p> <p>Is there any way to re...
<p>Before working with your excelsheet make sure you have set the permissions of your excel file to read and write,if it is a read only file,then change to read-write.</p> <pre><code>import pandas as pd your_data = pd.read_excel('yourfile.xlsx',sheet_name='your_sheet_name') print(your_data) #checking your_data.dropna(...
python|pandas
2
5,065
59,874,176
TF_NewTensor Segmentation Fault: Possible Bug?
<p>I'm using Tensorflow 2.1 git master branch (commit id:db8a74a737cc735bb2a4800731d21f2de6d04961) and compile it locally. Playing around with the C API to call <code>TF_LoadSessionFromSavedModel</code> but seems to get segmentation fault. I've managed to drill down the error in the sample code below.</p> <p><code>TF_...
<p>You set <code>ndata</code> to be <code>sizeof(int32_t)</code> which is 4. Your <code>ndata</code> is passed as <code>len</code> argument to <code>TF_NewTensor()</code> which represents the number of elements in <code>data</code> (can be seen in <a href="https://github.com/tensorflow/tensorflow/blob/v2.1.0/tensorflow...
c++|c|linux|tensorflow|tensorflow-c++
3
5,066
40,656,632
Add successive rows in Pandas if they match on some columns
<p>I have a dataframe like the following one:</p> <pre><code>ID URL seconds 1 Email 9 1 Email 3 1 App 5 1 App 9 1 Faceboook 50 1 Faceboook 7 1 Faceboook 39 1 Faceboook 10 1 Email 39 1 Email 5 1 Email 57 1 Faceboook 7 1 Faceboook 3...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> by <code>Series</code> created by compare by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.ne.html" rel="nofollow noreferrer"><co...
python|pandas
3
5,067
40,725,188
How to calculate the mean of n consecutive columns?
<p>I have a dataframe like this:</p> <pre><code>import pandas as pd df = pd.DataFrame({'A_1': [1, 2], 'A_2': [3, 4], 'A_3': [5, 6], 'A_4': [7, 8], 'B_1': [0, 2], 'B_2': [4, 4], 'B_3': [9, 6], 'B_4': [5, 8]}) A_1 A_2 A_3 A_4 B_1 B_2 B_3 B_4 0 1 3 5 7 0 4 9 5 1 2...
<p>This might work for you:</p> <pre><code>In [15]: df.rolling(window=2,axis=1).mean().iloc[:,1::2] Out[15]: A_2 A_4 B_2 B_4 0 2.0 6.0 2.0 7.0 1 3.0 7.0 3.0 7.0 </code></pre> <p>But I haven't tested it against your "straightforward" implementation.</p>
python|performance|pandas|optimization|vectorization
4
5,068
40,515,418
Filter columns based on a value (Pandas): TypeError: Could not compare ['a'] with block values
<p>I'm trying filter a DataFrame columns based on a value.</p> <pre><code>In[41]: df = pd.DataFrame({'A':['a',2,3,4,5], 'B':[6,7,8,9,10]}) In[42]: df Out[42]: A B 0 a 6 1 2 7 2 3 8 3 4 9 4 5 10 </code></pre> <p>Filtering columns:</p> <pre><code>In[43]: df.loc[:, (df != 6).iloc[0]] Out[43]: A ...
<p>You are trying to compare string 'a' with numeric values in column B.</p> <p>If you want your code to work, first promote dtype of column B as numpy.object, It will work. </p> <pre><code>df.B = df.B.astype(np.object) </code></pre> <p>Always check data types of the columns before performing the operations using</p...
python-3.x|pandas
1
5,069
40,556,159
Read_CSV file faster
<p>I'm having a bit of trouble reading 203 mb file quickly within the pandas dataframe. I want to know if there is a faster way I may be able to do this. Below is my function: </p> <pre><code>import pandas as pd import numpy as np def file(filename): df = pd.read_csv(filename, header=None, sep='delimiter', engine...
<p><strong>UPDATE:</strong> looking at your logic you don't seem to need to use first <code>sep='delimiter'</code> as you will use (split) only the first (index=0) column, so you can simply do this:</p> <pre><code>df = pd.read_csv(filename, header=None, usecols=[0,1,2,3], names=['time','id1','id2','a...
python|csv|pandas|dataframe|data-science
2
5,070
61,635,934
Python /Pandas / pd.to_datetime
<p>I want to convert date column (datetime64[ns]) into day-month-year format with this code , </p> <pre><code>pd.to_datetime(final['Date'],format = ('%d-%b-%Y')) </code></pre> <p>but it remains the same:</p> <pre><code>0 2019-12-31 1 2020-01-01 2 2020-01-02 3 2020-01-03 4 2020-01-04 ... ...
<p>you can use </p> <pre><code>df['Date'] = df['Date'].dt.strftime('%d-%m-%Y') </code></pre> <p>are you spelling month wrong? it says -%b instead of -%m</p>
python|pandas|datetime
0
5,071
57,910,344
Plot horizontal duration with pandas
<p>I'm trying to create a horizontal graph that would illustrate duration of processes. Here's my sample data:</p> <p><a href="https://i.stack.imgur.com/7tvvM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7tvvM.png" alt="enter image description here"></a></p> <p>Some code to put in Jupyter Notebo...
<p>Got it! Big thanks to @jdhao for this <a href="https://stackoverflow.com/a/50444098/2834065">answer</a>. (C'mon, check it out and upvote!)</p> <p>Here's the code for the source data again - I've added some more data to improve the example:</p> <pre><code>Id | PROC_NAME | START_TS | END_TS ---...
python|pandas|matplotlib|charts
2
5,072
57,973,920
Failed to convert Tensorflow .pd to json
<p>Trying to convert the saved model to json for tensorflow js. Followed the example from <a href="https://github.com/tensorflow/tfjs/tree/master/tfjs-converter" rel="nofollow noreferrer">https://github.com/tensorflow/tfjs/tree/master/tfjs-converter</a></p> <p>Version: tensorflowjs 1.2.9</p> <p>Dependency versions: ...
<p>It seems that the converter only works on Google Colab without any issue. Thanks everyone for the input.</p>
tensorflow.js|tensorflowjs-converter
0
5,073
57,768,344
how to visualize columns of a dataframe python as a plot?
<p>I have a dataframe that looks like below:</p> <pre><code>DateTime ID Temperature 2019-03-01 18:36:01 3 21 2019-04-01 18:36:01 3 21 2019-18-01 08:30:01 2 18 2019-12-01 18:36:01 2 12 </code></pre> <p>I would like to visualize thi...
<p>you can try:</p> <pre><code>df.set_index('DateTime').plot() </code></pre> <p>output:</p> <p><a href="https://i.stack.imgur.com/wCAgq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wCAgq.png" alt="enter image description here"></a></p> <p>or you can use: </p> <pre><code>df.set_index('DateTime...
python|pandas|data-visualization|scatter-plot
1
5,074
57,949,435
Replacing with Nan
<p>I am trying to replace the placeholder '.' string with NaN in the total revenue column. This is the code used to create the df. </p> <pre><code>raw_data = {'Rank': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'Company': ['Microsoft', 'Oracle', "IBM", 'SAP', 'Symantec', 'EMC', 'VMware', 'HP', 'Salesforce.com', 'Intuit'...
<p>In my opinion "replace" is not required as user wanted to change "." Whole to nan. Inistead this will also work. It finds rows with "." And assign nan to it</p> <pre class="lang-py prettyprint-override"><code>df.loc[df['Total_revenue']==".", 'Total_revenue'] = np.nan </code></pre>
pandas
0
5,075
49,500,510
How can I do this pandas lookup with a series?
<p>I have a Series <code>S</code>:</p> <pre><code> attr first last visit andrew alexander baseline abc andrew alexander followup abc bruce alexander baseline abc bruce alexander followup xyz fuzzy dunlop baseline xyz fuzzy dunlop followup ab...
<p>IIUC, you can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.lookup.html" rel="nofollow noreferrer">DataFrame.lookup()</a>:</p> <pre><code>In [7]: pd.Series(df.lookup(s.index, s['attr']), index=df.index) Out[7]: first last visit andrew alexander baseline 1 ...
python|pandas
3
5,076
49,582,555
How to check if the argmax of a tensor is equal to any argmax of another tensor which has several equal max?
<p>So usually in single label classification, we use the following</p> <pre><code>correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(self.label, 1)) </code></pre> <p>But I am working with multi label classification so I'd like to know how to do that where there are several ones in the label vector. So what I hav...
<p>I don't think you can achieve this with softmax so I am assuming that you are using sigmoids for your preds. If you are using sigmoids, your outputs will be each (independently) be between 0 and 1. You can define a threshold for each, perhaps 0.5, and then convert your sigmoid <code>preds</code> into the <code>label...
tensorflow|indices|tensor|argmax
1
5,077
73,189,717
How can i transform the dataset so that one line has one id based on column value?
<p>I have such type of dataset</p> <p><img src="https://i.stack.imgur.com/v8rne.png" alt="1" /></p> <p>and want to do this dataset based on column 't_value'</p> <p><img src="https://i.stack.imgur.com/p2qcp.png" alt="2" /></p> <p>I am pretty new to Python, I understand that we need to use loop but in what way? Also i do...
<p>You can use <code>pivot_table()</code> from <code>pandas</code></p> <p>try:</p> <pre><code>new_df = pd.pivot_table( df, # the first dataframe index = &quot;id&quot;, # aggregating column columns = &quot;t_value&quot; # mapped column aggfunc = &quot;first&quot; ...
python|pandas|dataframe
1
5,078
35,277,207
Pandas Set Data From the Last Period As New DataFrame Column
<p>I have a Pandas DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame([['A', '2014-01-01', '2014-01-07', 1.2], ['B', '2014-01-01', '2014-01-07', 2.5], ['C', '2014-01-01', '2014-01-07', 3.], ['A', '2014-01-08', '2014-01-14', 13.], ...
<p>Suppose we compute the duration between <code>Start</code> and <code>End</code> for each row:</p> <pre><code>df['duration'] = df['End']-df['Start'] </code></pre> <p>and suppose we also compute the previous Start value based on that duration:</p> <pre><code>df['Prev'] = df['Start'] - df['duration'] - pd.Timedelta(...
python|pandas
1
5,079
30,969,282
How to use geopy vicenty distance over dataframe columns?
<p>I have a dataframe with location column which contains lat,long location as follows</p> <pre><code> deviceid location 1102ADb75 [12.9404578177, 77.5548244743] </code></pre> <p>How to get the distance between consecutive rows using geopy's vicenty function? I tried follow...
<p>Based on <a href="https://github.com/geopy/geopy/blob/ba50914042dea4ee1ce45deb9ef226751faefc3b/geopy/distance.py#L301-304" rel="nofollow">geopy's github</a> you should pass two tuples to the <code>vincenty</code> function:</p> <pre><code> &gt;&gt;&gt; from geopy.distance import vincenty &gt;&gt;&gt; point_a ...
python|pandas|dataframe|geopy
3
5,080
67,291,957
Is there a Python Function for this?
<p>Ok, So I manually wrote out a function to do this, but I am wondering if there is a built in python/pandas/numpy/... function for this. Essentially what I want is</p> <pre><code>data_col = data.loc[data['col3'] == 'a'] data_final = data_col['col2'] </code></pre> <p>But I want it for all of the values of col3. So it ...
<p><strong>Code</strong></p> <pre><code>df = df.pivot_table( 'col2', columns='col3', aggfunc=(lambda x:x.to_list()) ).apply(pd.Series.explode).rename_axis(None, axis=1).reset_index(drop=True)) </code></pre> <p><strong>Output</strong></p> <pre><code> a b c d e 0 6 7 8 9 10 1 10 9 8 7 6 ...
python|pandas
2
5,081
67,482,379
Are individual gradients in a batch summed or averaged in a Neural Network?
<p>I am building a neural network from scratch. Currently having a batch of 32 training examples, and for each individual example, I calculate the derivatives (gradient) and sum them.</p> <p>After I sum the 32 training examples' gradients, I apply:<code>weight += d_weight * -learning rate;</code></p> <p>The question is...
<p>Well, it depends on what you want to achieve. The loss function acts as a guide to train the neural network to become better at a task.</p> <p>If we sum the cross entropy loss outputs, we incur more loss in proportion to the batch size, since our loss grows linearly in proportion to the mini-batch size during traini...
python|tensorflow|math|neural-network
1
5,082
67,572,955
How to groupby other column and get the last date without NaT in pandas?
<p>I want to group by ID column and get the last date without NaT in pandas. When I try <code>dropna</code> , I got an error<code>Cannot access callable attribute 'dropna' of 'SeriesGroupBy' objects,try using the 'apply' method</code> If I don't drop or ignore the NaT, this will use NaT to be the last date. How can I i...
<p>I think there are several issues in your code.</p> <p>First I would propose that you transform your date in <code>LAST_DATE_PURCHASE</code> into datetime and not into a string. Then you can apply <code>.max(numeric_only=True)</code> instead of transform. I assign the resulting dataframe to a new one, which I join af...
python|pandas|dataframe|date
2
5,083
67,276,357
Pandas Error: Reading one column as python Values (Float / Int Values) and other column as numpy.float64
<p>I'm using Pandas to transform some sporting data. One column is the home team stats and the 2nd column is away team stats.</p> <p>The stats are read from an excel file. When i print a dictionary from the dataframe all of the away team stats are floats (but many should be integers). When I print the type of each colu...
<p>The issue is that the int data type does not have Nan values by default: Many of the values may be blank for away. Resolution is</p> <p>In version 0.24.+ pandas has gained the ability to hold integer dtypes with missing values.</p> <p>Nullable Integer Data Type.</p> <p>Pandas can represent integer data with possibly...
python|python-3.x|pandas|dataframe|numpy
1
5,084
34,602,356
Creating a new column that combines content of two other columns in a list
<p>Say I have a <code>DataFrame</code> as follows: </p> <p><a href="https://i.stack.imgur.com/7NZNA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7NZNA.png" alt="enter image description here"></a></p> <p>I'd like to create a new <code>column</code> whose value is the 2nd and 3rd columns combined ...
<p>Try:</p> <pre><code>df['combined'] = list(zip(df.chicago_bound1, df.chicago_bound2)) </code></pre> <p>or</p> <pre><code>df['combined'] = df.apply(lambda x: [[x.chicago_bound1, x.chicago_bound2]], axis=1) </code></pre>
python|pandas|dataframe
4
5,085
34,661,318
REPLACE rows in mysql database table with pandas DataFrame
<p>Python Version - 2.7.6</p> <p>Pandas Version - 0.17.1</p> <p>MySQLdb Version - 1.2.5</p> <p>In my database ( <code>PRODUCT</code> ) , I have a table ( <code>XML_FEED</code> ). The table XML_FEED is huge ( Millions of record ) I have a pandas.DataFrame() ( <code>PROCESSED_DF</code> ). The dataframe has thousands o...
<p>With the release of pandas 0.24.0, there is now an <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-sql-method" rel="noreferrer">official way</a> to achieve this by passing a custom insert method to the <code>to_sql</code> function. </p> <p>I was able to achieve the behavior of <code>REPL...
python|mysql|pandas|replace
15
5,086
60,119,503
How to format datetime in a dataframe the way I want?
<p>I cannot find the correct format for this datetime. I have tried several formats, <code>%Y/%m/%d%I:%M:%S%p</code> is the closest format I can find for the example below.</p> <pre><code>df['datetime'] = '2019-11-13 16:28:05.779' df['datetime'] = pd.to_datetime(df['datetime'], format="%Y/%m/%d%I:%M:%S%p") </code></p...
<p>You can solve this probably by using the parameter <code>infer_datetime_format=True</code>. Here's an example:</p> <pre><code>df = {} df['datetime'] = '2019-11-13 16:28:05.779' df['datetime'] = pd.to_datetime(df['datetime'], infer_datetime_format=True) print(df['datetime']) print(type(df['datetime']) </code></pre> ...
python|pandas|dataframe|datetime
4
5,087
60,104,458
Pyarrow: TypeError: an integer is required (got type str)
<p>I have a dataframe with following dtype:</p> <pre><code>[2020-02-06 19:15:06,579] {logging_mixin.py:95} INFO - campanha object chave_sistema_origem int64 valor_ajustado object </code></pre> <p>The column <code>valor_ajustado</code> has some value that is throwing me an ...
<p>There is no data type in Apache Arrow to hold Python objects so a supported strong data type has to be inferred (this is also true of Parquet files). I would cleansing the <code>valor_adjustado</code> column to make sure all the values are numeric (there must be a string or some other bad value within). </p>
python|pandas|parquet
4
5,088
60,182,142
Adding columns of list within list in pandas
<p>I have column names in list within list with different size like [["a","b","c"],["d","e"],["f"]] also few of the columns contains NaN. </p> <h2>|a b c d e f|</h2> <h2>|1 2 3 4 5 6|</h2> <h2>|1 2 3 Nan NaN 6|</h2> <h2>|1 2 3 4 inf 6|</h2> <p>The result should be the sum of a list within a list ...
<p>Use list comprehension:</p> <pre><code>L = [["a","b","c"],["d","e"],["f"]] a = [df[x].sum(axis=1, min_count=1) for x in L] </code></pre> <p>Loop solution:</p> <pre><code>a = [] for x in L: a.append(df[x].sum(axis=1, min_count=1)) </code></pre> <hr> <pre><code>print (a) [0 6 1 6 2 6 dtype: int64, 0...
python|pandas
3
5,089
65,136,547
How to do Transfer Learning without ImageNet weights?
<p>This is a description of my project:</p> <p><strong>Dataset1:</strong> The bigger dataset, contains binary classes of images.</p> <p><strong>Dataset2</strong>: Contains <code>2</code> classes that are very similar in appearance to <code>Dataset1</code>. I want to make a model that is using transfer learning by learn...
<h2>Update</h2> <p>Based on your query, it seems that the class number won't be different in <strong>Dataset2</strong>. At the same time, you also don't want to use image net weight. So, in that case, you don't need to map or store the weight (as described below). Just load the model and weight and train on <strong>Dat...
python|tensorflow|keras
2
5,090
50,014,314
Append string of column index to DataFrame columns
<p>I am working on a project using Learning to Rank. Below is the example dataset format (taken from <a href="https://www.microsoft.com/en-us/research/project/letor-learning-rank-information-retrieval/" rel="nofollow noreferrer">https://www.microsoft.com/en-us/research/project/letor-learning-rank-information-retrieval/...
<p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.radd.html" rel="nofollow noreferrer"><code>DataFrame.radd</code></a> for add columns names from right side and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferr...
python|pandas|dataframe
1
5,091
49,872,843
pandas reading excel tables from pandas-exported json
<p>So I have a small table from excel, which I'd like to read in Pandas. Actually, I have several of the likes, and I'd like to just embed them directly in my script rather than keeping track of separate files.</p> <p>My file could be a table like this <a href="https://i.stack.imgur.com/tGuw9.png" rel="nofollow norefe...
<p>OK, finally I understand what you want: include the content of your Excel file (i.e. a 2D matrix) directly as a variable in the source code of your script, so that you don't have to read the file anymore. Am I right ?</p> <p>The native data structure able to store 2D matrices is a <strong>list of lists</strong>. Th...
python|pandas
1
5,092
63,915,693
Imput NaNs with the mean in column and find percentage of missing values
<p>I want to impute the mean value at all the missing values of the column <code>Product_Base_Margin</code> and then print the percentage of missing values in each column.</p> <p>My current code:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd df = pd.read_csv('https://query.d...
<p>Please try this:</p> <pre><code>df['Product_Base_Margin'] = df['Product_Base_Margin'].mean() print(round(100*(df.isnull().sum()/len(df.index)), 2)) </code></pre>
python|pandas|numpy
0
5,093
63,802,819
Hide a line on plotly line graph
<p>Imagine I have lines A, B, C, D, and E. I want lines A, B, and C to appear on the plotly line chart. I want the user to have the option to add lines D and E but D and E should be hidden by default.</p> <p>Any suggestions on how to do this?</p> <p>Example, how would I hide Australia by default.</p> <pre><code>impor...
<p>You need to play with the parameter <code>visible</code> setting it as <code>legendonly</code> within every trace</p> <pre class="lang-py prettyprint-override"><code>import plotly.express as px countries_to_hide = [&quot;Australia&quot;] df = px.data.gapminder().query(&quot;continent=='Oceania'&quot;) fig = px.line(...
python|pandas|plotly
13
5,094
63,935,283
How to create a mask for all relatively white parts of an image using numpy?
<p>Say I have 2 white images (RGB 800x600 image) that is 'dirty' at some unknown positions, I want to create a final combined image that has all the dirty parts of both images.</p> <p>Just adding the images together reduces the 'dirtyness' of each blob, since I half the pixel values and then add them (to stay in the 0-...
<p>I would suggest you convert to <a href="https://en.wikipedia.org/wiki/HSL_and_HSV" rel="nofollow noreferrer">HSV colourspace</a> and look for saturated (colourful) pixels like this:</p> <pre><code>import cv2 # Load background and foreground images bg = cv2.imread('A.jpg') fg = cv2.imread('B.jpg') # Convert to HSV ...
python|numpy|opencv
1
5,095
47,060,565
Tensorflow only works under root after drivers update
<p>I had a working Tensorflow for Python installation on my Ubuntu 16.04.3 LTS Xenial / nVidia GTX 1080 Ti machine. Then, the <strong>nVidia drivers got updated</strong> from 374 to 384.90 (<code>nvidia-smi</code> reports <code>NVIDIA-SMI 384.90</code>).</p> <p>Since then, I've <strong>only been able to run my program...
<p>We worked on this together with Jan Benes and found that the solution was to add to add our non-root user to <code>nvidia-persistenced</code> group. For example by <code>sudo usermod -a -G nvidia-persistenced our-nonroot-user</code>.</p> <p>The reason behind this is, that default installation of nvidia driver (<cod...
tensorflow|cuda|nvidia
2
5,096
46,980,958
Generating all the possible values in a ndarray in numpy?
<p>I am using gambit in python to simulate a world in a game theoretic manner. One construct of gambit is to save the "outcomes" for a set of decisions each player involved takes. This is of the form: </p> <p><code>game[d1,d2,d3,...,dn][n] = payoff </code></p> <p>where <code>d1</code> is the index of decision made b...
<p>Take a look at python's <code>itertools</code> module. It sounds like the <code>product</code> function will do what you want. </p> <p>Example:</p> <pre><code>import itertools as it list(it.product(*[range(2)]*3)) </code></pre> <p>Gives all lists of length three with two elements</p> <pre><code>[(0, 0, 0), (0...
python|numpy|multidimensional-array|game-theory|gambit
0
5,097
46,682,285
Fill array based on sparse information
<p>I have the following sparsity structure to describe the underlying dense array <code>A</code>:</p> <pre><code>a = np.array([1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1]) b = np.array([1, 5, 2, 3]) </code></pre> <p><code>a</code> contains <code>1</code> whenever <code>A</code> changes the value. <code>b</code> contains the new...
<p>Pretty simple really with <code>cumsum</code>. Use <code>cumsum</code> to get those <em>intervaled</em> indices and then index into the data array.</p> <p>Thus, for <code>1D</code> data -</p> <pre><code>idx = a.cumsum(-1)-1 out = b[idx] </code></pre> <p>For <code>2D</code> data -</p> <pre><code>out = bb[np.arang...
python|numpy
2
5,098
38,671,630
initialization of multiarray raised unreported exception python
<p>I am a new programmer who is picking up python. I recently am trying to learn about importing csv files using numpy. Here is my code:</p> <pre><code>import numpy as np x = np.loadtxt("abcd.py", delimiter = True, unpack = True) print(x) </code></pre> <p>The idle returns me with:</p> <pre><code>&gt;&gt; True &gt;&...
<p>I have experienced this problem too. This is cuased by a file named "datetime.py" in the same folder (exactly the same problem confronted by <a href="https://groups.google.com/a/continuum.io/forum/#!topic/anaconda/VqRUdoA-LnA" rel="nofollow noreferrer">Bruce</a>). Actually "datetime" is an existing python module. Ho...
python|numpy
4
5,099
38,954,251
Python - find closest position and value
<p>I m trying to find the closest point for a couple X and Y given as to access to its values. In my case, in X directions (np.arrange(0,X.max(),1), i would like to extract the closest values from Y = 0 to obtain its values in "values array" :</p> <pre><code>import numpy as np import matplotlib.pyplot as plt #My coord...
<p>You can use something faster than a <code>for</code> loop:</p> <pre><code>import numpy as np def find_nearest(array, value): ''' Find nearest value is an array ''' idx = (np.abs(array-value)).argmin() return idx haystack = np.arange(10) needle = 5.8 idf = find_nearest(haystack, needle) print haystack...
python|numpy|indexing
4