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
8,600
66,745,564
How to apply a row-wise function to a pandas dataframe and a shifted version of itself
<p>I have a pandas dataframe where I would like to apply a simple sign and multiply operation to each row and the row two indices back (shifted by 2). For example if we had</p> <pre><code>row_a = np.array([0.45, -0.78, 0.92]) row_b = np.array([1.2, -0.73, -0.46]) sgn_row_a = np.sign(row_a) sgn_row_b = np.sign(row_b) re...
<p>It seems the simplest way to do this prticular operation is</p> <pre><code>df.apply(np.sign) * df.shift(2).apply(np.sign) &gt;&gt;&gt; a b c d e 0 NaN NaN NaN NaN NaN 1 NaN NaN NaN NaN NaN 2 -1.0 1.0 1.0 -1.0 1.0 3 1.0 -1.0 1.0 1.0 -1.0 4 -1.0 1.0 1.0 1.0 1.0 .. ......
python|pandas|apply
2
8,601
66,604,223
Manually find the distance between centroid and labelled data points
<p>I have carried out some clustering analysis on some data <code>X</code> and have arrived at both the labels <code>y</code> and the centroids <code>c</code>. Now, I'm trying to calculate the distance between <code>X</code> and <em>their assigned cluster's centroid</em> <code>c</code>. This is easy when we have a smal...
<p>Thanks to numpy's <a href="https://numpy.org/doc/stable/reference/arrays.indexing.html" rel="nofollow noreferrer">array indexing</a>, you can actually turn your for loop into a one-liner and avoid explicit looping altogether:</p> <pre><code>distances = np.linalg.norm(X- np.einsum('ijk-&gt;ik', c[y]), axis=1) </code>...
python|numpy|cluster-analysis|k-means
2
8,602
66,529,964
pd.read_sql - Unsupported format character error (0x27)
<p>As above, I'm trying to use pd.read_sql to query our mysql database, and getting an error for double/single quotes.</p> <p>When I remove the % operators from the LIKE clause (lines 84-87) the query runs, but these are needed. I know I need to format the strings but I don't know how within such a big query.</p> <p>He...
<p>That error occurs then the DBAPI layer (e.g., mysqlclient) natively uses the &quot;format&quot; <a href="https://www.python.org/dev/peps/pep-0249/#paramstyle" rel="nofollow noreferrer">paramstyle</a> and the percent sign (<code>%</code>) is misinterpreted as a format character instead of a <code>LIKE</code> wildcard...
python|pandas|sqlalchemy|pymysql
3
8,603
66,492,618
Pandas fillna based on a condition
<p>I'm still new to pandas, but I have a dataframe in the following format:</p> <pre><code> d_title d_prefix d_header d_country d_subtitles d_season d_episode 0 NaN NaN ##### MOROCCO ##### Morocco NaN NaN NaN 1 title1 AR...
<ul> <li><strong>d_prefix</strong> is almost the grouping key you need. <code>bfill</code> it then <code>groupby()</code></li> <li>reduced to simple <code>ffill</code></li> </ul> <pre><code>df = df.assign(d_header=df.assign(t_prefix=df.d_prefix.fillna(method=&quot;bfill&quot;)) .groupby(&quot;t_prefix&quot;, as_index=...
python|pandas|dataframe|conditional-statements|nan
1
8,604
57,417,089
How can a tensor in tensorflow be sliced ​using elements of another array as an index?
<p>I'm looking for a similar function to tf.unsorted_segment_sum, but I don't want to sum the segments, I want to get every segment as a tensor.</p> <p>So for example, I have this code: (In real, I have a tensor with shapes of (10000, 63), and the number of segments would be 2500)</p> <pre><code> to_be_sliced = tf...
<p>For your case, you can do Numpy slicing in Tensorflow. So this will work:</p> <pre><code>sliced_1 = to_be_sliced[:3, :] # [[0.4 0.5 0.5 0.7 0.8] # [0.3 0.2 0.2 0.6 0.3] # [0.3 0.2 0.2 0.6 0.3]] sliced_2 = to_be_sliced[3, :] # [0.3 0.2 0.2 0.6 0.3] </code></pre> <p>Or a more general option, you can do it in the f...
python|tensorflow
0
8,605
57,564,307
Dynamically appending columns of different length while looping through an empty pandas dataframe of ncols = len(columns)
<p>Using for loops, I'm trying to append columns of different lengths to a pre-initialized empty dataframe. Within each iteration, I have to wrangle the data to return my desired output but the lengths of my desired outputs are all different. I would like to conserve every data there is (meaning that columns with shor...
<p>Inside the loop, append the <code>Series</code> to a list. Outside the loop, use <code>pd.concat</code> to concatenate the <code>Series</code>:</p> <pre><code>import numpy as np import pandas as pd column_list = ['File_A', 'File_B', 'File_C'] result = [] for i in range(len(column_list)): # "Some Code" that re...
python|pandas
2
8,606
57,574,409
Applying style to a pandas DataFrame row-wise
<p>I'm experimenting/learning Python with a data set containing customers information.</p> <p>The DataFrame structure is the following (these are made up records):</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'left_name' : ['James', 'Mary', 'John', 'Patricia'], 'left_age' : [30, 37, 30,...
<p>You can create DataFrame of styles with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.formats.style.Styler.apply.html" rel="nofollow noreferrer"><code>Styler.apply</code></a> and set rows by index value with <code>loc</code>:</p> <pre><code>def highlight(x): c1 = 'background-color:...
python|pandas|dataframe|formatting|pandas-styles
5
8,607
57,642,019
PyTorch not downloading
<p>I go to the PyTorch website and select the following options</p> <p>PyTorch Build: Stable (1.2)</p> <p>Your OS: Windows</p> <p>Package: pip</p> <p>Language: Python 3.7</p> <p>CUDA: None</p> <p>(All of these are correct)</p> <p>Than it displays a command to run</p> <p><code>pip3 install torch==1.2.0+cpu torch...
<p>I've been in same situation. My prob was, the python version... I mean, in the 'bit' way.</p> <p>It was 32 bit that the python I'd installed. You should check which bit of python you installed. you can check in the app in setting, search python, then you will see the which bit you've installed.</p> <p>After I i...
python|pip|pytorch
1
8,608
57,538,543
Why aren't some dimensions shown in the output even when according to the indexing they should be?
<pre><code>b = np.array([[[0, 2, 3], [10, 12, 13]], [[20, 22, 23], [110, 112, 113]]]) print(b[..., -1]) &gt;&gt;&gt;[[3, 13], [23, 113]] </code></pre> <p>Why does this output show the first axis but not the second axis (to show the second axis, it would have to show each number in its own list)? Is Numpy trying to ...
<blockquote> <p>Why does this output show the first axis but not the second axis (to show the second axis, it would have to show each number in its own list)?</p> </blockquote> <p>It does show the first and the second axis. Note that you have a 2d array here, and the first and second axis are retained. Only the thir...
numpy|multidimensional-array|indexing
2
8,609
57,351,939
Pandas groupby error: groupby() takes at least 3 arguments (2 given)
<p>I have the dataframe as following:</p> <p>(cusid means the customer id; product means product id bought by the customer; count means the purchased count of this product.)</p> <pre><code>cusid product count 1521 30 2 18984 99 1 25094 1 1 2363 36 1 3316 21 1 19249 228 1 13220 78 1 1226 7...
<pre><code>df.groupby(['cusid', 'product']).mean().reset_index().groupby('product')['count'].mean() </code></pre> <p>OUTPUT:</p> <pre><code>product 1 1 21 1 30 2 36 1 78 1 79 4 99 1 112 2 228 1 </code></pre> <p>python version: <code>3.7.4</code> pandas version: <code>0.25.0</code><...
python|pandas|machine-learning
0
8,610
43,923,012
TensorFlow: remember weigth of previous epochs
<p>I am experimenting with TensorFlow. I've just posted a <a href="https://stackoverflow.com/questions/43922819/tensorflow-improve-accuracy-on-training-data">question</a> regarding an issue it am facing with it. However I also have a perhaps more theoretically question but with practical consequences.</p> <p>When trai...
<p>Yes! You need to make a <a href="https://www.tensorflow.org/programmers_guide/variables" rel="nofollow noreferrer">saver and save your session periodically</a> through your training process. The pseudo-code implementation looks like:</p> <pre class="lang-py prettyprint-override"><code>model = my_model() saver = t...
python|machine-learning|tensorflow|neural-network
2
8,611
43,544,989
pandas: map more than 2 columns to one column
<p>This is an updated version of <a href="https://stackoverflow.com/questions/43543634/pandas-map-multiple-columns-to-one-column">this question</a>, which dealt with mapping only two columns to a new column.</p> <p>Now I have three columns that I want to map to a single new column using the same dictionary (and return...
<p>Try this:</p> <pre><code>In [174]: df['new'] = df.stack(dropna=False).map(codes).unstack() \ ...: .iloc[:, ::-1].ffill(axis=1) \ ...: .iloc[:, -1].fillna(0) ...: In [175]: df Out[175]: driver_action1 driver_action2 driver_action3 new 0 1 4 ...
python|pandas
1
8,612
43,921,338
Multiplying by pattern matching
<p>I have a matrix of the following format:</p> <pre><code>matrix = np.array([1, 2, 3, np.nan], [1, np.nan, 3, 4], [np.nan, 2, 3, np.nan]) </code></pre> <p>and coefficients I want to selectively multiply element-wise with my matrix:</p> <pre><code>coefficients = np.array([0.5, np...
<p><strong>Approach #1</strong></p> <p>A <em>quick</em> way would be with <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>NumPy broadcasting</code></a> -</p> <pre><code># Mask of NaNs mask1 = np.isnan(matrix) mask2 = np.isnan(coefficient...
python|numpy|matrix|pattern-matching
2
8,613
43,541,425
Pandas Reordering Dataframe to Time Series
<p>I have a dataframe with unlabeled columns with the following structure</p> <pre><code>0 101 100001 DT23 NaT 1900-01-01 20:00:00 DT24 1900-01-01 20:02:00 1 101 100002 DT24 1900-01-01 20:02:00 1900-01-01 20:04:00 DT23 1900-01-01 20:05:05 2 102 200001 DT23 NaT 1900-01...
<p>If you are successfully ending with a DataFrame, then this answer can show you how to convert a DF to a time series</p> <p><a href="https://stackoverflow.com/questions/19914944/convert-pandas-dataframe-to-time-series">Convert Pandas dataframe to time series</a></p> <p>Hope this helps.</p>
python|pandas
0
8,614
43,826,004
How to Multiply Matrix Values By a Constant if a Condition is Met?
<p>In python I have a matrix and I need to have that same matrix returned to me, except I have a rule, if there are elements in that matrix that are &lt;0 I multiply their individual values by a constant. I am not sure how to go about doing this though.</p> <p>Example: a=[[0, 2, 1, 4], [-2, 3, 5, 2]] and let's say my ...
<p>Demo:</p> <pre><code>In [55]: a = np.random.randint(-10, 10, size=(10,10)) In [56]: a Out[56]: array([[ 7, 6, 0, 2, 3, -9, 2, -2, 9, -10], [ 8, 4, -10, 5, 7, 6, 7, -3, 1, -3], [ 5, -10, -8, 4, -2, -9, 0, 8, -1, 7], [ 6, 7, 6, 2, -3, 3, 0, ...
python|numpy
2
8,615
43,648,890
How to return a specific cell that have color style and font style for iloc[1,1] only?
<p>I have a dataframe and below is my color code:</p> <pre><code> def color (val): if final.iloc[1,1]&lt;final.iloc[1,0]: return "background-color: green" else: return "background-color: red" </code></pre> <p>I wish to return only <code>final.iloc[1,1]</code> to have green color background, ...
<p>You can use:</p> <pre><code>import pandas as pd import numpy as np np.random.seed(100) df = pd.DataFrame(np.random.randn(5, 3), columns=list('ABC')) print (df) def highlight_col(x): #copy df to new - original data are not changed df = x.copy() #set default values to all values df.loc[:,:] = 'back...
python|pandas|dataframe
4
8,616
43,800,994
Pulling certain dates from a dataframe in python
<p>I am using pandas to clean a database and I have a list of dates all in format like 08-Jun-2017 , 12-Jun-2017 etc within a dataframe. I would like to pull out all the rows where the date is less than 14 days from the current date. Thanks</p>
<p>Demo:</p> <pre><code>In [118]: df = pd.DataFrame({'date': pd.date_range(end='2017-05-05', freq='9D', periods=20)}) \ .sample(frac=1).reset_index(drop=True) In [119]: df Out[119]: date 0 2016-11-15 1 2017-03-30 2 2017-01-17 3 2017-04-17 4 2017-03-12 5 2017-02-22 6 2017-01-08 7 2017...
python|date|pandas
3
8,617
1,377,130
How do you deal with missing data using numpy/scipy?
<p>One of the things I deal with most in data cleaning is missing values. R deals with this well using its "NA" missing data label. In python, it appears that I'll have to deal with masked arrays which seem to be a major pain to set up and don't seem to be well documented. Any suggestions on making this process easier ...
<p>If you are willing to consider a library, pandas (http://pandas.pydata.org/) is a library built on top of numpy which amongst many other things provides:</p> <blockquote> <p>Intelligent data alignment and integrated handling of missing data: gain automatic label-based alignment in computations and easily manipula...
python|numpy|data-analysis
4
8,618
73,128,413
Python pandas value error for code conversion
<p>I am trying to convert SQL code into equivalent python code.</p> <p><strong>My SQL code is given below:</strong></p> <pre><code>select count(*),sum(days) into :_cnt_D_DmRP_1D, :_pd_D_DmRP_1D from _fw_bfr_wgt where pk=1 and type=1 and input(zipcode,8.) not in (700001:735999) and input(zipcode,8.) not in (&amp;cal_li...
<p>Problem is in <code>df['zipcode'] not in (list(range(700001,(735999+1))))</code>, you can use <code>Series</code> in <code>in</code> operator</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; pd.Series(range(3)) in list(range(10)) Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, li...
python|python-3.x|pandas|dataframe
0
8,619
73,009,672
How to serialize named tuple with np array to file
<p>How to serialize named tuple with np array to file?</p> <p>I know how to serialize/deserialize an np_array.</p> <pre><code>import numpy as np a = [ np.arange(300), np.arange(200) ] np.save('output.pkl', a, allow_pickle=True) </code></pre> <p>But for my case, I am dealing with a named tuple with a string an...
<p>You can use <a href="https://github.com/cloudpipe/cloudpickle" rel="nofollow noreferrer"><code>cloudpickle</code></a>. Cloudpickle makes it possible to serialize Python constructs not supported by the default pickle module from the Python standard library.</p> <pre><code>import cloudpickle Point = namedtuple('Addre...
python|arrays|python-3.x|numpy|pickle
0
8,620
72,964,800
What is the proper way to install TensorFlow on Apple M1 in 2022
<p>I am facing 4 problems when I tried to install TensorFlow on Apple M1:</p> <ol> <li><p><a href="https://www.anaconda.com/blog/new-release-anaconda-distribution-now-supporting-m1" rel="noreferrer">Conda has supported M1 since 2022.05.06</a> but most of articles I googled talk about using Miniforge, e.g. So I feel the...
<p>Distilling <a href="https://developer.apple.com/metal/tensorflow-plugin/" rel="nofollow noreferrer">the official directions from Apple</a> (as of 13 July 2022), one would create an environment using the following YAML:</p> <p><strong>tf-metal-arm64.yaml</strong></p> <pre class="lang-yaml prettyprint-override"><code>...
tensorflow|conda|apple-m1
4
8,621
42,817,612
optimized way of iterating through dataframe
<p>I have a pandas dataframe, called Visits2 contains 20M records. Here are sample of records from Visits2.</p> <pre><code>num srv_edt inpt_flag 000423733A 8/15/2016 N 001013135D 7/11/2016 N 001013135D 7/11/2016 N 001047851M 4/29/2016 N 001067291M 2/29/2016 Y 001067291M 8/3/2016 N 001067...
<p>IIUC you can do it this way:</p> <pre><code>In [37]: df.loc[df.groupby('num')['srv_edt'].idxmin(), 'inpt_any'] = 'N' In [38]: df Out[38]: num srv_edt inpt_flag inpt_any 0 000423733A 2016-08-15 N N 1 001013135D 2016-07-11 N N 2 001013135D 2016-07-11 N N...
python|pandas|optimization
1
8,622
42,913,969
Python: properly iterating through a dictionary of numpy arrays
<p>Given the following <code>numpy</code> arrays:</p> <pre><code>import numpy a=numpy.array([[1,1,1],[1,1,1],[1,1,1]]) b=numpy.array([[2,2,2],[2,2,2],[2,2,2]]) c=numpy.array([[3,3,3],[3,3,3],[3,3,3]]) </code></pre> <p>and this dictionary containing them all:</p> <pre><code>mydict={0:a,1:b,2:c} </code></pre> <p>What...
<p>I think you're making this harder than it needs to be. Either sum them and divide by the number of terms:</p> <pre><code>In [42]: v = mydict.values() In [43]: sum(v) / len(v) Out[43]: array([[ 2., 2., 2.], [ 2., 2., 2.], [ 2., 2., 2.]]) </code></pre> <p>Or stack them into one big array -- wh...
python|arrays|numpy|dictionary|for-loop
1
8,623
27,186,244
compute a xi-xj matrix in numpy without loops (by api calls)
<p>How to compute a xi-xj matrix in numpy without loops (by api calls)?</p> <p>Here's what to start with:</p> <pre><code>import numpy as np x = np.random.rand(4) xij = np.matrix([xi-xj for xj in x for xi in x]).reshape(4,4) </code></pre>
<p>You can take advantage of broadcasting to subtract <code>x</code> as a column vector from <code>x</code> as a flat array and produce the matrix.</p> <pre><code>&gt;&gt;&gt; x = np.random.rand(4) </code></pre> <p>Then:</p> <pre><code>&gt;&gt;&gt; x - x[:,np.newaxis] array([[ 0. , 0.89175647, 0.80930233, ...
python|numpy|matrix|vectorization
5
8,624
27,063,962
select rows from dataframe where any of the columns is higher 0.001
<p>I would normally write</p> <pre><code>df[ (df.Col1&gt;0.0001) | (df.Col2&gt;0.0001) | (df.Col3&gt;0.0001) ].index </code></pre> <p>to get the labels where the condition holds True. If I have many columns, and say I had a tuple</p> <pre><code>cols = ('Col1', 'Col2', 'Col3') </code></pre> <p><code>cols</code> is a...
<p>You can combine <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.any.html" rel="nofollow"><code>pandas.DataFrame.any</code></a> and list indexing to create a mask for use in indexing. </p> <p>Note that <code>cols</code> has to be a list, not a tuple.</p> <pre><code>import pandas as pd i...
python|pandas
1
8,625
27,296,645
Pandas Dataseries get values by level
<p>I am dealing with pandas series like the following </p> <blockquote> <p>x=pd.Series([1, 2, 1, 4, 2, 6, 7, 8, 1, 1], index=['a', 'b', 'a', 'c', 'b', 'd', 'e', 'f', 'g', 'g'])</p> </blockquote> <p>The indices are non unique, but will always map to the same value, for example 'a' always corresponds to '1' in my sam...
<p>So long as your indices map directly to the values then you can simply call <code>drop_duplicates</code>:</p> <pre><code>In [83]: x.drop_duplicates() Out[83]: a 1 b 2 c 4 d 6 e 7 f 8 dtype: int64 </code></pre> <p>example:</p> <pre><code>In [86]: x = pd.Series(['XX', 'hello', 'XX', '4', 'hello'...
python|pandas
1
8,626
25,100,046
Building 3D arrays in Python to replace loops for optimization
<p>I'm trying to better understand python optimization so this is a dummy case, but hopefully outlines my idea...</p> <p>Say I have a function which takes two variables:</p> <pre><code>def func(param1, param2): return some_func(param1) + some_const*(param2/2) </code></pre> <p>and I have arrays for param1 and par...
<p><em>Original answer for some_func(param1) x param2</em></p> <p>Write the <code>some_func</code> in such a way that it can accept and return numpy arrays. Then use;</p> <pre><code>numpy.outer(some_func(param1), param2) </code></pre> <p>This works because in your example, both <code>param1</code> and <code>param2</...
python|arrays|optimization|numpy|matrix
3
8,627
30,750,782
NumPy vs MATLAB
<p>I've started to use NumPy instead of MATLAB for a lot of things and for most things it appears to be much faster. I've just tried to replicate a code in Python and it is much slower though. I was wondering if someone who knows both could have a look at it and see why it is the case</p> <p>NumPy:</p> <pre><code>lon...
<p>Although I can't be sure what is the primary source of the slowdown, I do notice some things that will cause a slowdown, are easy to fix, and will result in cleaner code:</p> <ol> <li>You do a lot of conversion from numpy arrays to lists. Type conversions are expensive, try to avoid them whenever possible. In you...
python|matlab|numpy
6
8,628
39,105,282
How to find min value of another column greater than current column Pandas
<p>I am sure this is an easy one, but how do I find the minimum value of a column that is greater than the value in the current column? Also, how do I find the maximum value of a column less that the value in the current column?</p> <pre><code>from io import StringIO import io text = """Order starttime ...
<p>You can try something like this:</p> <pre><code>df.endtime.apply(lambda x: min(df.starttime[df.starttime &gt; x]) if len(df.starttime[df.starttime &gt; x]) != 0 else np.nan) # 0 2016-03-01 14:31:10.806 # 1 2016-03-01 14:31:10.790 # 2 2016-03-01 14:31:10.806 # 3 NaT # Name: endtime, dtyp...
python|pandas|dataframe|aggregate|min
1
8,629
39,141,080
List most common members in Pandas group?
<p>I have a dataframe with columns like this:</p> <pre><code> id lead_sponsor lead_sponsor_class 02837692 Janssen Research &amp; Development, LLC Industry 02837679 Aarhus University Hospital Other 02837666 Universidad Autonoma de Ciudad Juar...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.nlargest.html" rel="nofollow"><code>Series.nlargest</code></a>:</p> <pre><code>print (df.groupby(['lead_sponsor', 'lead_sponsor_class']).size().nlargest(10)) </code></pre> <p>In <a href="http://pandas.pydata.org/pandas...
python|sorting|pandas|dataframe|series
2
8,630
39,148,628
Feeding dtype np.float32 to TensorFlow placeholder
<p>I am trying to feed an numpy ndarray of type : float32 to a TensorFlow placeholder, but it's giving me the following error:</p> <pre><code>You must feed a value for placeholder tensor 'Placeholder' with dtype float </code></pre> <p>My place holders are defined as:</p> <pre><code>n_steps = 10 n_input = 13 n_classe...
<p>For your first problem, are you sure that <code>batch_y</code> is also <code>float32</code>? You only provide the trace of the <code>batch_x</code> type, and <code>batch_y</code> is more likely to be integer, since it appears to be a one-hot encoding of your classes.</p> <p>For the second problem, what you do wrong...
numpy|tensorflow
2
8,631
39,044,434
Use qcut pandas for multiple valuable categorizing
<p>I am trying to use two values from two columns from a dataframe and perform <code>qcut</code> categorization. </p> <p>single value categorizing it quite simple. But two variables as pairs and vs is something I am trying get. </p> <p>Input: </p> <pre><code>date,startTime,endTime,day,c_count,u_count 2004-01-05,22:0...
<p>You can create a Series for each quantile group:</p> <pre><code>q = df[['c_count', 'u_count']].apply(lambda x: pd.qcut(x, np.linspace(0, 1, 6), labels=np.arange(5))) q Out: c_count u_count 0 4 4 1 3 3 2 3 2 3 4...
python|validation|csv|pandas
1
8,632
22,883,149
Can I configure Theano's x divided by 0 behavior
<p>I have a little problem using Theano. It seems that a <code>division by 0</code> results in <code>inf</code> not as using e.g. Numpy this results in 0 (at least the inverse function do behave like that). Take a look:</p> <pre><code>from theano import function, sandbox, Out, shared import theano.tensor as T import n...
<p><code>theano.tensor</code> calculates the <em>elementwise</em> inverse</p> <p><code>np.linalg.inv</code> calculates the inverse <em>matrix</em></p> <p>These are not the same thing mathematically</p> <hr> <p>You're probably looking for the <strong>experimental</strong> <a href="http://deeplearning.net/software/th...
python|numpy|theano
1
8,633
13,308,131
Retrieving array elements with an array of frequencies in NumPy
<p>I have an array of numbers, <code>a</code>. I have a second array, <code>b</code>, specifying how many times I want to retrieve the corresponding element in <code>a</code>. How can this be achieved? The ordering of the output is not important in this case.</p> <pre><code>import numpy as np a = np.arange(5) b = np....
<p>Thats exactly what <code>np.arange(5).repeat([1,0,3,2,0])</code> does.</p>
python|numpy
6
8,634
29,592,634
timestamp from a txt file into an array
<p>I have a txt file with the following structure:</p> <pre><code>"YYYY/MM/DD HH:MM:SS.SSS val1 val2 val3 val4 val5' </code></pre> <p>The first line look like:</p> <pre><code>"2015/02/18 01:05:46.004 13.737306807 100.526088432 -22.2937 2 5" </code></pre> <p>I am having trouble to put the time stamp into th...
<p>If this is coming from a text file, it may be simpler to parse this as text unless you want it all to end up in a numpy array. For example:</p> <pre><code>&gt;&gt;&gt; my_line = "2015/02/18 01:05:46.004 13.737306807 100.526088432 -22.2937 2 5" &gt;&gt;&gt; datestamp, timestamp, val1, val2, val3, val4, val5...
python|numpy
0
8,635
62,187,119
Proper way to extract value from DataFrame with composite index?
<p>I have a dataframe, call it current_data. This dataframe is generated via running statistical functions over another dataframe, current_data_raw. It has a compound index on columns "Method" and "Request.Name"</p> <p><code>current_data = current_data_raw.groupby(['Name', 'Request.Method']).size().reset_index().set...
<p>If want select in <code>MultiIndex</code> is possible use tuple in order of levels, but here is not specified index name like <code>'Request.Name'</code>:</p> <pre><code>val = df.loc[(some_name, some_method), 'Average'] </code></pre> <p>Another way is use <a href="https://pandas.pydata.org/pandas-docs/stable/refer...
python|pandas
1
8,636
62,116,123
Streamlit Panda Query Function Syntax Error When Finding Column in CSV Dataframe
<p>When Using Streamlit to build a data interface getting a syntax error. My downloaded csv dataframe has a column 'NUMBER OF PERSONS INJURED', after converting it into a dataframe with panda and trying to use the query function to reference it I'm getting errors like below. I converted the text to lower case in the ...
<p>You can try by edit the column name to something simpler, like injured_person. Then restart your device and try run the streamlit again</p>
python|pandas|csv|dataframe|streamlit
0
8,637
62,240,625
AttributeError: 'int' object has no attribute 'plot' in pandas
<p>I tried to visualize the nulls values in each column but got the error: <code>AttributeError: 'int' object has no attribute 'plot'.</code></p> <pre><code> columns_with_null = ['ACCTAGE', 'PHONE', 'POS','INV','INVBAL','POSAMT', 'CC', 'CCBAL','HMOWN' 'CCPURC', 'INCOME', 'LORES', 'HMVAL', 'AGE','CR...
<p>You need pass all columns with nulls instead <code>col</code> variable and also add parentheses or <code>div</code> for division:</p> <pre><code>(df[columns_with_null].isna().sum() / len(df)).plot(kind='barh') df[columns_with_null].isna().sum().div(len(df)).plot(kind='barh') </code></pre> <p>If want plot all colu...
python|pandas
0
8,638
62,204,288
Python Pandas: Merging one column to another data frame does not return the same number of rows
<p>I have two data frames: first data frame (let say df1) has 389 rows with 5 columns, the second data frame (let say df2) has 10025 rows with 10 columns. I want to merge one of the columns (let say column name is 'description') to the first data frame. I was using pd.merge() command to merge column like below:</p> <p...
<p>It looks like you have either a "<a href="https://en.wikipedia.org/wiki/One-to-many_(data_model)" rel="nofollow noreferrer">many-to-one</a>" or "<a href="https://en.wikipedia.org/wiki/Many-to-many_(data_model)" rel="nofollow noreferrer">many-to-many</a>" relationship. To eliminate this, you can do the following:</p>...
python|python-3.x|pandas
1
8,639
62,091,420
Pandas Create multiindex pivot table with year month and day from single time column
<p>I have a single column with time (time since epoch if it matters) from an sql query.</p> <pre><code>time value 1000000 10 1000001 15 1000002 20 ... </code></pre> <p>I want to create a multiindex pivot table in Pandas automatically like so based on those values.</p> <pre><code> Value 2018 ...
<p>If the column is a pandas.DateTime column, you can use the <a href="https://pandas.pydata.org/pandas-docs/stable/getting_started/basics.html#basics-dt-accessors" rel="nofollow noreferrer"><code>.dt</code> datetime accessor</a> to access attributes such as <code>df[col].dt.year</code>, <code>df[col].dt.month</code>, ...
python|pandas|pivot-table
1
8,640
51,150,199
Gcloud FileNotFound - ML Engine
<p>I'm trying to do a predict on Google Cloud ML Engine. I have the input uploaded in a bucket at Google Cloud Storage. I'm using the following flag:</p> <pre><code>--file='gs://MyBucket/Photo/example3.jpg' </code></pre> <p>I've also tried: </p> <pre><code>--file=gs://MyBucket/Photo/example3.jpg </code></pre> <p>In...
<p>To read image files from Google cloud storage, use tensorflow code like this, since native Python can not read from blob stores:</p> <pre><code>image_contents = tf.read_file(filename) image = tf.image.decode_jpeg(image_contents, channels=3) image = tf.image.convert_image_dtype(image, dtype=tf.float32) # 0-1 </code>...
tensorflow|google-cloud-storage|google-cloud-ml
0
8,641
51,139,450
How to use numpy to operate on tensors in tensorflow lite
<p>I have a tensorflow graph that attempts to split an image into three single channel images.</p> <pre><code>input_image = tf.placeholder(name="input_image", dtype=tf.float32, shape=[512 * 512 *3]) feed_dict ={input_image:resized_image_data} channel_image = tf.reshape(input_image, (512, 512, 3)) </code></pre> <p>I ...
<p>Until recently stack and unstack weren't supported by TensorFlow Lite. The "cannot allocate memory" error is likely due to the fact that the conversion failed. If you try again using tensorflow's nightly it might work.</p>
tensorflow|tensorflow-lite
0
8,642
51,536,111
How to perform a two sample t test in python using any statistics library similar to R?
<p>I can do this in R for 2 sample T-test:</p> <pre><code>t.test(x, y = NULL, alternative = c("two.sided", "less", "greater"), mu = 0, paired = FALSE, var.equal = FALSE, conf.level = 0.95) </code></pre> <p>I want some function where I can pass this mu(difference in mean) parameter in Python ttest?</p>
<p>R has one function <code>t.test()</code> to perform the Student's T test, while Python employs more methods.</p> <p>If you want to perform a <strong>one sample t-test</strong> with mu as the true mean μ of the population from which the data is sampled, you should use <code>scipy.stats.ttest_1samp</code> and pass th...
python|numpy|scipy|t-test
1
8,643
51,129,506
Converting numpy array to picture
<p>So I have got a string of characters and I am representing it by a number between 1-5 in a numpy array. Now I want to convert it to a pictorial form by first repeating the string of numbers downwards so the picture becomes broad enough to be visible (since single string will give a thin line of picture). My main pro...
<p>This would be a minimal working example to visualize with matplotlib:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt # generate 256 by 1 vector of values 1-5 img = np.random.randint(1,6, 256) # transpose for visualization img = np.expand_dims(img, 1).T # force aspect ratio plt.imshow(img, aspec...
python|python-3.x|image|numpy
1
8,644
51,259,166
pandas how to compare rows of 2 dataframes regardless of order
<pre><code>import pandas as pd df1 = pd.DataFrame(index=[1,2,3,4]) df1['A'] = [1,2,5,4] df1['B'] = [5,6,9,8] df1['C'] = [9,10,1,12] &gt;&gt;&gt; df1 A B C 1 1 5 9 2 2 6 10 3 5 9 1 4 4 8 12 </code></pre> <p>I want to compare rows of df1 and get a result of row1(1,5,9) == row3(5,9,1).</p> <p>It m...
<p>I think need sorting each row by <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.sort.html" rel="nofollow noreferrer"><code>np.sort</code></a>:</p> <pre><code>df2 = pd.DataFrame(np.sort(df1.values, axis=1), index=df1.index, columns=df1.columns) print (df2) A B C 1 1 5 9 2 2 6 10 3 ...
python|pandas
2
8,645
48,371,188
Django - how to make a complex math annotation (k Nearest Neighbors)
<p>I have this model:</p> <pre><code>class Image(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='img/') signature = models.TextField(null = True) </code></pre> <p>The signature is a numpy monodimensional vector encoded in json. In order to make my query, I have...
<p>So that's the final working code:</p> <pre><code>def image_sorted(request): query_signature = extract_feat(settings.MEDIA_ROOT + "/cache" + "/001_accordion_image_0001.jpg") # a NParray object #query_signature = extract_feat(settings.MEDIA_ROOT + "/cache" + "/003_ant_image_0003.jpg") # a NParray object ...
python|django|numpy|math|data-retrieval
0
8,646
48,017,713
Boolean Comparison across multiple dataframes
<p>I have an issue where I want to compare values across multiple dataframes. Here is a snippet example:</p> <pre><code>data0 = [[1,'01-01'],[2,'01-02']] data1 = [[11,'02-30'],[12,'02-25']] data2 = [[8,'02-30'],[22,'02-25']] data3 = [[7,'02-30'],[5,'02-25']] df0 = pd.DataFrame(data0,columns=['Data',"date"]) df1 = pd....
<h2>Problem</h2> <p>For your data:</p> <pre><code>&gt;&gt;&gt; df0['Data'] 0 1 1 2 Name: Data, dtype: int64 &gt;&gt;&gt; df1['Data'] 0 11 1 12 Name: Data, dtype: int64 </code></pre> <p>your a doing a <em>bitwise or</em> with <code>|</code>:</p> <pre><code>&gt;&gt;&gt; df0['Data']| df1['Data'] 0 11 1...
python|python-3.x|pandas|dataframe
2
8,647
48,281,285
Seclective parse BeautifulSoup
<p>I want to parse data from Drug website. This parse need to be selective and this is the code I used:</p> <pre><code>import requests from bs4 import BeautifulSoup def get_details(url): print('details:', url) # get subpage r = requests.get(url) soup = BeautifulSoup(r.text ,"lxml") # get data on...
<p>If you are looking for <code>Accession Number</code> and <code>Groups</code>, you can do the following: </p> <pre><code>def get_details(url): print('Details:', url) r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') accession_dt = soup.find('dt', text='Accession Number') access...
python|python-2.7|pandas|parsing|beautifulsoup
1
8,648
48,348,882
Faster way to remove punctuations and special characters in pandas dataframe column
<p>I'm using this below code to remove special characters and punctuations from a column in pandas dataframe. But this method of using regex.sub is not time efficient. Is there other options I could try to have better time efficiency and remove punctuations and special characters? Or the way I'm removing special charac...
<p>One way would be to keep only alphanumeric. Consider this dataframe</p> <pre><code>df=pd.DataFrame({'Text':['#^#346fetvx@!.,;:', 'fhfgd54@!#&gt;&lt;?']}) Text 0 #^#346fetvx@!.,;: 1 fhfgd54@!#&gt;&lt;? </code></pre> <p>You can use </p> <pre><code>df['Text'] = df['Text'].str.extract('(\w+)', expand = False...
python|regex|pandas
7
8,649
70,983,208
How to fill in gaps of duplicate indices in dataframe?
<p>I have a dataframe like as shown below</p> <pre><code>tdf = pd.DataFrame({'grade': np.random.choice(list('AAAD'),size=(5)), 'dash': np.random.choice(list('PPPS'),size=(5)), 'dumeel': np.random.choice(list('QWRR'),size=(5)), 'dumma': np.random.choice((1234),siz...
<p>It is only display issue:</p> <pre><code>tdf.set_index(['grade','dumeel'],inplace=True) print (tdf) dash dumma target grade dumeel A W S 855 1 R P 498 1 R P 378 0 W P 211 0 W P ...
python|pandas|dataframe|series|multi-index
1
8,650
70,928,543
What are the steps involved in creating a Tensorflow.lite model?
<p><em><strong>What are the steps involved in creating and training a Tensorflow model to use in an Android app ?</strong></em></p> <p>Below is what I think needs to be done in my scenario (based on what I've researched)</p> <ul> <li>I know I need to gather training images of various car parts and label them using lab...
<p>To answer your question: Can I write the above training model in Python locally on my PC or do I have to use Google colab? --&gt; You can try both seperately, both work. What resources can/should I use ? --&gt; If your refering to GPU you can use that through colab [runtime-&gt;change runtime-&gt;hardware/device and...
python|android|tensorflow|google-colaboratory
1
8,651
71,003,520
Find the index number of where a variable fits between in pandas column
<p>I have the following dataframe:</p> <pre><code>import pandas as pd #Create DF d = { 'Category': ['A','B','C','D','E','F','G'], 'Value':[10,20,30,40,50,60,70], } df = pd.DataFrame(data=d) df </code></pre> <p><a href="https://i.stack.imgur.com/EH7GF.png" rel="nofollow noreferrer"><img src="ht...
<p>You can just use <code>argmax</code></p> <pre><code>(df['Value'] &gt; 45).argmax() # 4 (df['Value'] &gt; 22).argmax() # 2 (df['Value'] &gt; 60).argmax() # 6 </code></pre> <p>This assumes <code>'Value'</code> is sorted, but it works because the result of the comparison is a boolean array, so it is returning the index...
python|pandas
7
8,652
51,855,777
Remove column without headers and data
<p>I have a CSV file and when I bring it to python as a dataframe, it create a new Unnamed: 1 column in dataframe. So how could I remove it or filter it. <a href="https://i.stack.imgur.com/rLTGd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rLTGd.png" alt="Here, whats my csv looks like"></a></p> <...
<p>Drop that column from your dataframe: </p> <p><code>df.drop(["Unnamed: 1"], inplace=True)</code></p>
python|pandas|csv|dataframe
2
8,653
51,722,531
Pandas bar plot with both categorical and numerical data
<p>I have a pandas dataframe named 'data' with data similar to the following table. I want to plot them in python as bar plots. </p> <pre><code>Name X Y Z Activity AAA1 0.0 0.0 2.0 Low AAA2 0.0 2.0 6.0 Medium AAA3 1.0 2.0 3.0 High AAA4 2.0 1.0 4.0 High </code></pre> <p>What I tried is, with a bi...
<p>I don't know if this solution fit you, but at first I group data by <em>Activity</em> and <em>Name</em> and then I plot barplot. Example (I get your DataFrame):</p> <pre><code>import matplotlib.pyplot as plt df.groupby(['Activity','Name']).sum().plot(kind='bar') </code></pre> <p>And the result <a href="https://i....
python|pandas|dataframe
2
8,654
51,820,952
Convert 2D numpy array into pandas pivot table
<p>I have a 2D numpy array representing depth on grid of coordinates.</p> <pre><code>z = np.array([[100, 101, 102, 103], [101, 102, 103, 104], [102, 103, 104, 105], [103, 104, 105, 106], [104, 105, 106, 107]]) </code></pre> <p>I also have a 1D numpy array listin...
<p>I think I've found a way using numpy array functions to get the data in the correct format. It's a valid answer but I hoped there was a more elegant way to do it with pandas.</p> <p>Since I can already pivot from the DataFrame returned by <code>read_csv()</code>, the simplest option is to get the data in the same f...
python|arrays|pandas|numpy|pivot-table
0
8,655
51,687,727
How to plot pandas DataFrame with date (Year/Month)?
<p>I've got a pandas dataframe populated with the following data : </p> <pre><code> Date val count 0 2013-01 A 1 1 2013-01 M 1 2 2013-02 M 2 3 2013-03 B 3 4 2013-03 M 5 5 2014-05 B 1 </code></pre> <p>I'm ne...
<p>Using <strong><code>pivot</code></strong> and <strong><code>plot</code></strong> (<code>A</code> isn't showing up because it only has a single point and is getting hidden by the first point of <code>M</code>). You also have to convert your <code>Date</code> column to <code>datetime</code> in order to accurately dis...
python|pandas
2
8,656
41,771,992
HDF5 adding numpy arrays slow
<p>First time using hdf5 so could you help me figure out what is wrong, why adding 3d numpy arrays is slow. Preprocessing takes 3s, adding 3d numpy array (100x512x512) 30s and rising with each sample</p> <p>First I create hdf with:</p> <pre><code>def create_h5(fname_): """ Run only once to create h5 file for di...
<p>The slowness is almost certainly due to the compression and chunking. It's hard to get this right. In my past projects I often had to turn off compression because it was too slow, although I have not given up on the idea of compression in HDF5 in general.</p> <p>First you should try to confirm that compression and ...
python|numpy|hdf5|h5py
2
8,657
64,610,026
CUDNN_STATUS_INTERNAL_ERROR in tensorflow 2.1 c++
<p>I face a problem as the title says when I load a pre-trained model(.pb model of YOLOv3) and infer with this model in tensorflow 2.1 c++. Error messages are as the following:</p> <pre class="lang-sh prettyprint-override"><code>2020-10-30 21:36:20.245492: E tensorflow/stream_executor/cuda/cuda_dnn.cc:329] Could not cr...
<p>Finally, I find a way to correct that error. Just pass the SessionOptions variable(call set_allow_growth with it) into LoadSavedModel function:</p> <pre class="lang-cpp prettyprint-override"><code> if(tensorflow::MaybeSavedModelDirectory(modelName.toStdString())) { // set gpu memory growth true here tenso...
c++|tensorflow
0
8,658
64,451,989
Grouping results of a groupby with too numerous cases into a "trash bin" level
<p>I need to &quot;simplify&quot; for reporting purposes rare events in a pandas DataFrame resulting from a group-by operation.</p> <p>Let's take for example this DataFrame, where I use <code>colA</code> to count the occurrences of values in <code>colB</code></p> <pre><code>df = pd.DataFrame(data={'colA':['a','b','c','...
<p>Try this</p> <pre><code>df_final = df_grouped.rename({k: 'Other' for k, v in df_grouped.colB.eq(1).items() if v == True}).sum(level=0) Out[671]: colB colA a 4 b 3 Other 3 </code></pre>
python|pandas|pandas-groupby
2
8,659
64,554,908
How to count number of elements in a row greater than zero
<p>I need to count the number of values in each row that are greater than zero and store them in a new column</p> <p>The df bellow:</p> <pre><code> team goals goals_against games_in_domestic_league 0 juventus 1 0 0 1 barcelona 0 1 ...
<p>First idea is select numeric columns, test if greater like <code>0</code> and count <code>True</code>s by <code>sum</code>:</p> <pre><code>df['total'] = df.select_dtypes(np.number).gt(0).sum(axis=1) </code></pre> <p>If want specify columns by list:</p> <pre><code>cols = ['goals','goals_against','games_in_domestic_le...
python|pandas
5
8,660
49,090,915
tensorflow installation(both 1.5.0 and 1.6.0) doesn't work on mac osx yosemite
<p>1.5.0 installs fine, but when I import tensorflow, I get this error:</p> <pre class="lang-none prettyprint-override"><code>RuntimeError: module compiled against API version 0xa but this version of numpy is 0x9 RuntimeError: module compiled against API version 0xa but this version of numpy is 0x9 Traceback (most rec...
<p>I ran into the same issue. The installation error is because the new version of tensorflow requires new dependencies (grpcio). Here is how I handle my problem.</p> <p>Force installing the binary wheels.</p> <pre><code>$ pip install --no-cache-dir --only-binary :all: grpcio==1.10.1 </code></pre> <p>Then I can upg...
python-2.7|numpy|tensorflow
0
8,661
58,898,253
transfer learning - trying to retrain efficientnet-B07 on RTX 2070 out of memory
<p>this is the training code I am trying to run work when trying on <code>64gb ram CPU</code> crush on <code>RTX 2070</code> </p> <pre><code>config = tf.ConfigProto() config.gpu_options.per_process_gpu_memory_fraction = 0.7 tf.keras.backend.set_session(tf.Session(config=config)) model = efn.EfficientNetB7() model.s...
<p>Despite the EfficientNet models having lower parameter counts than comparative ResNe(X)t models, they still consume significant amounts of GPU memory. What you're seeing is an out of memory error for your GPU (8GB for an RTX 2070), not the system (64GB).</p> <p>A B7 model, especially at full resolution, is beyond w...
python|tensorflow|keras|deep-learning|efficientnet
4
8,662
58,783,573
Pandas running division for a column
<p>I'm new to Pandas and would love some help I'm trying to take:</p> <pre><code>factor 1 1 2 1 1 3 1 2 </code></pre> <p>and produce:</p> <pre><code>factor running_div 1 1 1 1 2 0.5 1 0.5 1 0.5 3 0.1666667 1 0.1666667 2 0.083...
<p>Use numpy <code>ufunc.accumulate</code></p> <pre><code>df['cum_div'] = np.divide.accumulate(df.factor.to_numpy()) factor cum_div 0 1 1.000000 1 1 1.000000 2 2 0.500000 3 1 0.500000 4 1 0.500000 5 3 0.166667 6 1 0.166667 7 2 0.083333 </code></pre>
python|pandas
2
8,663
58,992,619
Display red channel of image with NumPy and Matplotlib only
<p>I'm trying to display the red channel of an image using Matplotlib.pyplot and NumPy only. Can someone explain, why I get different images for the following two codes?</p> <p>Code #1:</p> <pre><code>R = numpy.copy(img) # copy image into new array R[:,:,1]=0 # set green channel to 0 R[:,...
<p>You don't specify a data type in your <code>numpy.zeros()</code> call:</p> <pre class="lang-py prettyprint-override"><code>numpy.zeros(img.shape) </code></pre> <p>That way, <code>R</code> is of type <code>float64</code>, and most of its values are greater or equal <code>1</code>, such that you see "clipping" in yo...
python|image|numpy|matplotlib|matrix
2
8,664
58,938,177
subset a series of pandas df based on index
<p>I have a series of dataframes.</p> <pre><code>ind = [78, 87, 677, 900] df = pd.Series(data = [pd.DataFrame(np.arange(12).reshape(3, 4), index = [0, 1, 2], columns = ['a', 'b', 'c', 'd']) for _ in range(4)], index = ind) </code></pre> <p>Each df in the series looks like this:</p> <pre><code>df[78...
<p>Try this:</p> <pre><code>pd.concat(df.head(3).tolist()).sum(level=0) </code></pre> <p>Output:</p> <pre><code> a b c d 0 0 3 6 9 1 12 15 18 21 2 24 27 30 33 </code></pre>
python|pandas|dataframe
0
8,665
58,996,458
Count occurrences in a list for each row and specific column in a dataframe
<p>I've been trying to use <code>collection.Counter</code> or <code>value_counts</code> in <strong>Python 3.7</strong> to do something like the df below, but I had no success. So far, this is an example of what I'm trying to get: </p> <pre><code> IDs Col2 Col3 0 123 [A, A, B, B, C] {A:2,...
<p>Use dict comprehension with test if value is <code>max</code>:</p> <pre><code>from collections import Counter df = pd.DataFrame({'Col1':[123,456,789], 'Col2':[list('AABBC'), list('ABCC'), list('AAADD')]}) df['Col3'] = df['Col2'].apply(Counter) df['Max'] = df['Col3'].apply(lambda x: {k:v for k,...
python|python-3.x|pandas|dictionary|counter
4
8,666
70,287,631
How best to randomly select a number of non zero elements from an array with many duplicate integers
<p>I need to randomly select x non-zero integers from an unsorted 1D numpy array containing y integer elements including an unknown number of zeros as well as duplicate integers. The output should include duplicate integers if required by this random selection. What is the best way to achieve this?</p>
<p>One option is to select the non-zero elements first then use <code>random.choice()</code> (with the <code>replace</code> parameter set to either True or False) to select a given number of elements.</p> <p>Something like this:</p> <pre><code>import numpy as np rng = np.random.default_rng() # doing this is recommended...
python|numpy
1
8,667
70,120,222
Use multiple dates in pd.date_range
<p>I have a range of dates in date column of dataframe. The dates are scattered eg 1st feb, 5th Feb, 11th feb etc.</p> <p>I want to use pd.date_range with frequency one minute on every date in this column. So my start argument will be date and the end argument will be date + datetime.timedelta(days=1).</p> <p>I'm stru...
<p>Use <code>x</code> in lambda function instead <code>df['date']</code> and remove <code>axis=1</code>:</p> <pre><code>df = pd.DataFrame({'date':pd.date_range('2021-11-26', periods=3)}) print (df) date 0 2021-11-26 1 2021-11-27 2 2021-11-28 s = df['date'].apply(lambda x:pd.date_range(start=x,end=x+pd.Timedel...
python|pandas|date-range
0
8,668
70,177,871
Convert a NumPy array to a binary array with the condition of each element existing in a list
<p>Is there any way to convert an array to a binary array such that any element that exists within a defined list is 1, and any element not in the list is 0?</p> <p>For example, if I define a NumPy array as so:</p> <pre><code>a = np.array([[23,43,1],[43,5,0],[5,0,0]]) </code></pre> <p>and a list as so:</p> <pre><code>l...
<p>Check out <a href="https://numpy.org/doc/stable/reference/generated/numpy.isin.html" rel="nofollow noreferrer">https://numpy.org/doc/stable/reference/generated/numpy.isin.html</a></p> <pre><code>arr=np.array([[23,43,1],[43,5,0],[5,0,0]]) l = [5,43] np.isin(arr, l).astype(int) #array([[0, 1, 0], # [1, 1, 0], # ...
python|numpy|numpy-ndarray
1
8,669
70,073,499
How to keep leading zeroes from a panda column post operation?
<p>I have a column which has data as :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Date</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">'2021-01-01'</td> </tr> <tr> <td style="text-align: center;">'2021-01-10'</td> </tr> <tr> <td style="text-...
<p>The leading zeros are being dropped because of a misunderstanding about the use of <a href="https://stackoverflow.com/questions/509211/understanding-slice-notation">slice notation</a> in Python.</p> <p>Try changing your code to:</p> <pre><code>df['period'] = df['Date'].str[:4] + df['Date'].str[5:7] </code></pre> <p>...
python|pandas|string|data-cleaning
2
8,670
56,268,220
Df Headers: Insert a full year of header rows at end of month and fill non populated months with zero
<p>Afternoon All,</p> <p>Test Data as at 30 Mar 2019:</p> <pre><code>Test_Data = [ ('Index', ['Year_Month','Done_RFQ','Not_Done_RFQ','Total_RFQ']), ('0', ['2019-01',10,20,30]), ('1', ['2019-02', 10, 20, 30]), ('2', ['2019-03', 20, 40, 60]), ...
<p>You can assign columns by length of original columns and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFrame.reindex</code></a>:</p> <pre><code>c = ['Report_Mongo','Month_1','Month_2','Month_3','Month_4','Month_5','Month_6', ...
python|pandas|dataframe
1
8,671
56,034,981
How to fix the image preprocessing difference between tensorflow and android studio?
<p>I'm trying to build a classification model with keras and deploy the model to my Android phone. I use the code from <a href="https://medium.com/@elye.project/applying-tensorflow-in-android-in-4-steps-to-recognize-superhero-f224597eb055" rel="nofollow noreferrer">this website</a> to deploy my own converted model, whi...
<p>This question is old, but remains the top Google result for preprocess_input for ResNet50 on Android. I could not find an answer for implementing <code>preprocess_input</code> for Java/Android, so I came up with the following based on the original python/keras code:</p> <pre><code>/* Preprocesses RGB bitmap IAW...
android|tensorflow|keras|image-preprocessing
0
8,672
55,779,039
Pandas: Merge 2 dataframes based on a column values; for mulitple rows containing same column value, append those to different columns
<p>I have two dataframes, dataframe1 and dataframe2. They both share the same data in a particular column for both, lets call this column 'share1' and 'share2' for dataframe1 and dataframe2 respectively. </p> <p>The issue is, there are instances where in dataframe1 , there is only one row in 'share1' with a particula...
<p>Loading Data:</p> <pre><code>import pandas as pd df1 = {'key': ['c34z', 'c34z_2'], 'value': ['x', 'y']} df2 = {'key': ['c34z', 'c34z_2', 'c34z_2'], 'value': ['c34z_value', 'c34z_2_value', 'c34z_2_value']} df1 = pd.DataFrame(df1) df2 = pd.DataFrame(df2) </code></pre> <p>Convert df2 by grouping and pivoting</p> <pr...
python|pandas
1
8,673
55,688,491
Replace the value inside a csv column by value inside parentheses of the same column using python pandas
<p>I got the following csv file with sample data: <a href="https://i.stack.imgur.com/MeDQy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MeDQy.png" alt="Small part of the csv file with sample data"></a></p> <p>Now I want to replace the columns 'SIFT' and 'PolyPhen' values with the data inside the ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>Series.str.extract</code></a>:</p> <pre><code>df = pd.DataFrame({'SIFT':['tol(0.82)','tol(0.85)','tol(1.42)'], 'PolyPhen':['beg(0)','beg(0)','beg(0)']}) pat = r'...
python|python-3.x|pandas|csv|dataframe
2
8,674
55,845,173
sklearn.confusion_matrix - TypeError: 'numpy.ndarray' object is not callable
<p>I am trying to build a sklearn confusion matrix using the below</p> <p>test_Y:</p> <pre><code> Target 0 0 1 0 2 1 </code></pre> <p>the data type of test_Y is</p> <pre><code>Target int64 dtype: object </code></pre> <p>and my y_pred is</p> <pre><code>array([0,0,1]) </code></pre> <p>i then do my confusion...
<p>You have reused the name <code>confusion_matrix</code>. You need to rebind it back to your function; this is one way:</p> <pre><code>from sklearn.metrics import confusion_matrix cm = confusion_matrix(test_Y, y_pred) sns.heatmap(cm, annot=True) </code></pre>
python|pandas|numpy|scikit-learn|confusion-matrix
1
8,675
64,992,133
How to implement a velocity Verlet integrator which works for the harmonic oscillator in python?
<p>I am new to python and i am trying to implement a velocity Verlet integrator which works for the harmonic oscillator. As you can see from my notebook below (taken from: <a href="http://hplgit.github.io/prog4comp/doc/pub/._p4c-solarized-Python022.html" rel="nofollow noreferrer">http://hplgit.github.io/prog4comp/doc/p...
<p>You did not implement the velocity Verlet step correctly, the second velocity update uses the newly computed position, not the old one,</p> <pre><code>vi[n+1] = v_next - 0.5*omega**2*u[n+1]*dt </code></pre> <p>This small change should restore second order and energy/amplitude preservation.</p> <hr /> <p>Also remove ...
python|numpy|numerical-methods|verlet-integration
0
8,676
39,926,162
TensorFlow Casting Internal Tensor Pointer
<p>I <a href="https://stackoverflow.com/questions/39797095/tensorflow-custom-allocator-and-accessing-data-from-tensor">previously asked</a> how to get at the pointer within a Tensor. I would now like to figure out the datatype is stored and then be able to cast <code>void*</code>'s to this data type.</p> <p>Tensor's h...
<p>The framework is build in <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/types.h#L142" rel="nofollow"><code>types.h</code></a> and is used in <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/queue_base.cc#L31" rel="nofollow"><code>queue_ba...
c++|templates|macros|tensorflow
0
8,677
44,259,578
Faster RCNN: how to translate coordinates
<p>I'm trying to understand and use the <a href="https://arxiv.org/pdf/1506.01497.pdf" rel="nofollow noreferrer">Faster R-CNN</a> algorithm on my own data.</p> <p>My question is about ROI coordinates: what we have as labels, and what we want in the end, are ROI coordinates in the input image. However, if I understand ...
<p>It looks like it's actually an implementation question, the method itself does not answer that. </p> <p>A good way to do it though, that is used by <a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="nofollow noreferrer">Tensorflow Object Detection API</a>, is to always give co...
machine-learning|tensorflow|computer-vision|deep-learning
1
8,678
69,546,079
Python : DataFrame.to_excel should write the table vertically
<p>I am trying to write 2 Sheets in a new Excel file</p> <pre class="lang-py prettyprint-override"><code>with pd.ExcelWriter(outputDetailsFile) as writer: df1.to_excel(writer, sheet_name='FA',index = False) df2.to_excel(writer, sheet_name='TA', index = False) </code></pre> <p>The above code is working fine. The...
<p>Try transposing the index and columns using the <code>T</code> accessor:</p> <p><code>df1.T.to_excel(writer, sheet_name='FA',index = False)</code></p>
python|pandas|dataframe
0
8,679
41,103,119
Excel merge cells, from 2 sheets using Python Pandas
<p>I have two Excel sheets, <code>sheet1</code>, and <code>sheet2</code>. Sheet1 has the <code>row id</code>, <code>First name</code>, <code>Last name</code>, <code>Description</code> columns, etc. Sheet2 has also a column that stores the <code>First name</code>, <code>Last name</code>, and also two other columns, <cod...
<p>I think you should look at this. But that's mostly for context. </p> <p><a href="http://pbpython.com/excel-file-combine.html" rel="nofollow noreferrer">http://pbpython.com/excel-file-combine.html</a></p> <p>I think your issue actually boils down to this.</p> <pre><code>&gt;&gt;&gt; !cat scores3.csv ID,JanSales,...
python|excel|pandas
1
8,680
53,977,693
Pandas to_sql in django
<p>I am trying to use Django's db connection variable to insert a pandas dataframe to Postgres database. The code I use is</p> <pre><code>df.to_sql('forecast',connection,if_exists='append',index=False) </code></pre> <p>And I get the following error</p> <blockquote> <p>Execution failed on sql 'SELECT name FROM sqli...
<p>It is possible to create db configuration in setting.py file</p> <pre><code>DATABASES = { 'default': env.db('DATABASE_URL_DEFAULT'), 'other': env.db('DATABASE_URL_OTHER') } DB_URI_DEFAULT=env.str('DATABASE_URL_DEFAULT') DB_URI_OTHER=env.str('DATABASE_URL_OTHER') </code></pre> <p>If you want to create sql_a...
django|pandas
2
8,681
54,207,221
Tensorflow does not see gpu on pycharm
<p>Specifications: System: Ubuntu 18.0.4 Tensorflow:1.9.0, cudnn=7.2.1</p> <p>Interpreter project: anaconda environment.</p> <p>When I run the script on terminal with the same anaconda env, it works fine. Using pycharm, it does not work!! What is the issue ?</p>
<p>Go to <strong>File -> Settings -> Project Interpreter</strong> and set the same python environment used by Anaconda.</p>
python-3.x|tensorflow|pycharm
0
8,682
53,917,608
Is it beneficial to use OOP on large datasets in Python?
<p>I'm implementing Kalman Filter on two types of measurements. I have GPS measurement every second (1Hz) and 100 measurment of accelration in one second (100Hz). So basically I have two huge tables and they have to be fused at some point. My aim is: I really want to write readable and maintainable code. </p> <p>My fi...
<p>It sounds like you would want to use <code>pandas</code>. OOP is a concept btw, not something you explicitly code in inflexibly. Generally speaking, you only want to define your own classes if you plan on extending them or encapsulating certain features. <code>pandas</code> and <code>numpy</code> are 2 modules that ...
python|pandas|oop|data-driven
0
8,683
66,017,881
Logistic Regression Model (binary) crosstab error = shape of passed values issue
<p>I am currently trying to run logistic regression for a data set. I dummy encoded my cat variables and normalized my continuous variables, and I fill null values with -1 (which works for my dataset). I am going through the steps and I am not getting any errors until I try to run my crosstab where its complaining abou...
<p>Your target variable should be of shape (n,) not (n,1) as is your case when you call <code>y_bi = allyrs[[&quot;CM&quot;]]</code> . See the relevant <a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegressionCV.html#sklearn.linear_model.LogisticRegressionCV.fit" rel="nofollow n...
python|pandas|scikit-learn|logistic-regression|crosstab
1
8,684
52,870,521
pandas.pivot_table : How to name functions for aggregation
<p>I am trying to pivot pandas DataFrame using several aggregate functions, some of which are lambda. There has to be a distinct name for each column in order to have aggregations by several lambda functions. I tried a few ideas I found online but none worked. This is the minimal example:</p> <pre><code>df = pd.DataFr...
<p>Name the functions explicitly:</p> <pre><code>def lam1(x): return np.percentile(x, 50) def lam2(x): return np.percentile(x, 75) pivoted_df = df.pivot_table(index = ['col1', 'col2'], values = 'col3', aggfunc=[lam1, lam2]).reset_index() </code></pre> <p>Your aggregation series ...
python|pandas|lambda|pivot-table
4
8,685
52,503,035
How to find out index in numpy array python
<p>I have saved the Urdu text in <code>numpy</code> array and I want to find out the index number, however I am not able to do that. This is my code</p> <pre><code>import numpy as np wordsList = np.load('urduwords.npy') wordIndex= list(wordsList).index("آئندہ") </code></pre> <p>When I print the <code>wordsList</code...
<p>Numpy has a <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer">where</a> function which will give you the index value of the output. By the way, if you are using the latest numpy version then it will automatically detect the type.</p> <p>Try this</p> <pre><cod...
python|arrays|numpy
0
8,686
52,574,040
Min-max scaling along rows in numpy array
<p>I have a numpy array and I want to rescale values along each row to values between 0 and 1 using the following procedure:</p> <p>If the maximum value along a given row is <code>X_max</code> and the minimum value along that row is <code>X_min</code>, then the rescaled value (<code>X_rescaled</code>) of a given entry...
<p><code>MinMaxScaler</code> is a bit clunky to use; <code>sklearn.preprocessing.minmax_scale</code> is more convenient. This operates along columns, so use the transpose:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from sklearn import preprocessing &gt;&gt;&gt; ...
python|arrays|numpy|scikit-learn
10
8,687
52,596,609
Efficient way to go from iris dataset in Pandas form to sk-learn form?
<p>How can I transform the Pandas version of the iris dataset, to the form used by <code>sk-learn</code>?</p> <pre><code>#Seaborn dataset import seaborn as sns iris_seaborn = sns.load_dataset("iris") sepal_length sepal_width petal_length petal_width species 0 5.1 3.5 1.4 0.2 setosa 1 4.9 3.0 1.4 0.2 setosa...
<p>You can <code>factorize</code> the labels, then use the underlying <code>numpy</code> array for the rest of the data:</p> <pre><code>target = pd.factorize(iris_seaborn.species)[0] # alternatively: # target = pd.Categorical(iris_seaborn.species).codes # or # target = iris_seaborn.species.factorize()[0] data = iris...
python|pandas|scikit-learn
2
8,688
46,449,721
Splitting a dataframe based on the index
<p>I would like to split the below DF_input based on the index. That's from the below DF, How to obtain: </p> <pre><code> measurement value 0 0 13 1 1 3 2 2 4 0 0 8 1 1 12 2 2 34 3 ...
<p>Use a <code>groupby</code> to partition the index into separate dataframes of increasing subsequence:</p> <pre><code>for _, g in df.groupby((df.index.to_series().diff().fillna(1) &lt; 0).cumsum()): print(g, '\n') measurement value 0 0 13 1 1 3 2 2 4 meas...
python|pandas|dataframe|indexing
1
8,689
46,228,276
Create a Pandas daily aggregate time series from a DataFrame with date ranges
<p>I have a Pandas DataFrame of subscriptions, each with a start datetime (timestamp) and an optional end datetime (if they were canceled).</p> <p>For simplicity, I have created string columns for the date (e.g. "20170901") based on start and end datetimes (timestamps). It looks like this:</p> <p><code>df = pd.DataFr...
<p>It's an interesting problem, here's how I would do it. Not sure about performance</p> <p>EDIT: My first answer was incorrect, I didn't read fully the question</p> <pre><code># Initial data, columns as Timestamps df = pd.DataFrame([('20170511', None), ('20170514', '20170613'), ('20170901', None)], columns=["sd", "e...
python|pandas|datetime|filter|aggregate
2
8,690
46,246,960
Enumerate rows for each dtaaframe group based on conditions
<p>I would like to reenumerate rows in given <code>df</code> using some conditions. My question is an extension of this <a href="https://stackoverflow.com/questions/17228215/enumerate-each-row-for-each-group-in-a-dataframe">question</a>.</p> <p>Example of <code>df</code>:</p> <pre><code> ind seq status 0 1 2...
<p>Let's try <code>df.groupby</code> followed by an <code>apply</code> and <code>concatenat</code>ion.</p> <pre><code>vals = df.groupby('ind').apply( lambda g: np.where(g['status'].iloc[0] == 'up' or g['status'].iloc[-1] in {'down', 'oth'}, np.arange(1, len(g) + 1), g['seq']) ).val...
python|pandas|dataframe|group-by
2
8,691
58,359,645
A question about modifying values of one array based on values in another array
<p>Consider a 2D numpy array, a 1D numpy array, and a constant:</p> <pre><code>arr1 = [[ 4 4] arr2 = [ 1 7] k = 2 [ 3 6] [ 7 10] [-2 6] [-1 6] [-8 8]] </code></pre> <p>Here's what I need to do: If the absolute value of the values in arr1[:,0] are in arr2, t...
<p>Still learning, but this seems to work:</p> <pre><code>print(arr1[np.in1d(abs[:,0]), arr2), 1] -= k) </code></pre>
python-3.x|numpy-ndarray
0
8,692
58,194,497
Custom Early Stop Function - Stop When Cost Value Starts Accelerating Upward After Convergence?
<p>I am training a model using Tensorflow in Python 3, and have set up my own separate early stopping function. My model keeps the cost value fairly low for most of the training run, but then like normal, it reaches a certain point where not only does it no longer improve/minimize the cost function, but it gets exponen...
<p>You can do this by keeping a window of last n loss values and calculating a range (max minus min of the window). Then you put a threshold, if the range value is bigger than m times of the min of this window, then you just stop.</p>
python|python-3.x|tensorflow|reinforcement-learning
1
8,693
58,568,218
Datetime conversion format
<p>I converted the datetime from a format '2018-06-22T09:38:00.000-04:00' to pandas datetime format</p> <p>i tried to convert using pandas and got output but the output is</p> <p>o/p: 2018-06-22 09:38:00-04:00</p> <pre><code>date = '2018-06-22T09:38:00.000-04:00' dt = pd.to_datetime(date) </code></pre> <p>expected ...
<p>There is timestamps with timezones, so if convert to UTC by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.tz_convert.html" rel="nofollow noreferrer"><code>Timestamp.tz_convert</code></a>, times are changed:</p> <pre><code>date = '2018-06-22T09:38:00.000-04:00' dt = pd.to_dateti...
python-3.x|pandas
2
8,694
58,412,910
Extract key and value from json to new dataframe
<p>I have a dataframe that has JSON values are in columns. Those were indented into multiple levels. I would like to extract the end key and value into a new dataframe. I will give you sample column values below</p> <blockquote> <p>{'shipping_assignments': [{'shipping': {'address': {'address_type': 'shipping', 'ci...
<p>I came across a beautiful ETL package in python called petl. convert the json list into dict form with the help of function called fromdicts(json_string)</p> <pre><code>order_table = fromdicts(data_list) </code></pre> <p>If you find any nested dict in any of the columns, use unpackdict(order_table,'nested_col') it...
python|json|pandas|dataframe
2
8,695
58,203,166
How to draw plots on Specific pandas columns
<p>So I have the df.head() being displayed below.I wanted to display the progression of salaries across time spans.As you can see the teams will get repeated across the years and the idea is to display how their salaries changed over time.So for teamID='ATL' I will have a graph that starts by 1985 and goes all the way...
<p>You can use <code>seaborn</code> for this:</p> <pre><code>import seaborn as sns sns.lineplot(data=df, x='yearID', y='payroll_total', hue='teamID') </code></pre> <p>To get different plot for each team:</p> <pre><code>for team, d in df.groupby('teamID'): d.plot(x='yearID', y='payroll_total', label='team') </co...
python|pandas|data-visualization
1
8,696
58,405,825
How to replace particular values in dataframe column from a dictionary?
<p>So, I have a table of the following manner:</p> <pre><code>Col1 Col2 ABS 45 CDC 23 POP 15 </code></pre> <p>Now, I have a dictionary <code>aa = {'A':'AD','P':'PL','C':'LC'}</code>. So for the matching key parts only I want the values in the column to change. For the other letters which do not mat...
<h1>Solution</h1> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'Col1': ['ABS', 'CDC', 'POP'], 'Col2': [45, 23, 15], }) keys = aa.keys() df.Col1 = [''.join([aa.get(e) if (e in keys) else e for e in list(ee)]) for ee in df.Col1.tolist()] df </code></pre> <p>...
python|regex|pandas|dictionary
1
8,697
69,181,026
filter a dataframe with vectorization
<p>I have the followings:</p> <pre><code>df = pd.DataFrame({&quot;value&quot;:['A','B','B','C','B'],'my_list':[['J1','J4'],['J2','J9','J1'],['J0','J9','J2'],['J2'],['V13','X9','J1']]}) value my_list 0 A [J1, J4] 1 B [J2, J9, J1] 2 B [J0, J9, J2] 3 C [J2] 4 B [V13, X9, J1] </code></pre> <p>and...
<p>Using list, dict etc in a pandas dataframe loses the befinifit of vectorization. If storing these values with these dtypes are mandatory, list comprehension works faster:</p> <pre><code>df['value'].eq(&quot;B&quot;)&amp;['J2' not in i for i in df['my_list']] </code></pre> <p>Other methods:</p> <p>Converting to dataf...
python|pandas
2
8,698
68,996,540
Chaquopy Android Wrapper
<p><strong>Chaquopy Android</strong> I have to call the python file method with array data. then python file executes ECG Peak(PQRST) using <strong>neurokit2</strong> and got this error.</p> <p><a href="https://i.stack.imgur.com/oOnKx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oOnKx.png" alt="en...
<p>Pandas added support for the <code>string</code> dtype in <a href="https://pandas.pydata.org/pandas-docs/stable/whatsnew/v1.0.0.html#dedicated-string-data-type" rel="nofollow noreferrer">version 1.0</a>. So change the <code>pip</code> section of your build.gradle file to install <code>pandas==1.3.2</code>, which we ...
python|android|pandas
1
8,699
68,966,864
Batchsize in DataLoader
<p>I have two tensors:</p> <pre><code>x[train], y[train] </code></pre> <p>And the shape is</p> <pre><code>(311, 3, 224, 224), (311) # 311 Has No Information </code></pre> <p>I want to use DataLoader to load them batch by batch, the code I write is:</p> <pre><code>from torch.utils.data import Dataset class KD_Train(Dat...
<p>Your dataset's <code>__getitem__</code> method should return a single element:</p> <pre><code>def __getitem__(self, index): return self.imgs[index], self.index[index] </code></pre>
pytorch|dataloader
1