Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
4,200
67,932,445
Least-squares optimization in Python with single equal constraint
<p>I am looking to solve a least-squares problem in python such that I minimize <code>0.5*||np.dot(A,x) - b||^2</code> subject to the constraint <code>np.dot(C,x) = d</code>, with the bounds <code>0&lt;x&lt;np.inf</code>, where</p> <pre><code>A : shape=[m, n] C : shape=[m, n] b : shape=[m] d : shape=[m] </code></pre> <...
<p>If you stick to <code>scipy.optimize.lsq_linear</code>, you could add a penalty term to the objective function, i.e.</p> <pre><code>minimize 0.5 * ||A x - b||**2 + beta*||Cx-d||**2 subject to lb &lt;= x &lt;= ub </code></pre> <p>and choose the scalar <code>beta</code> sufficiently large in order to transform your co...
python|numpy|optimization|scipy|least-squares
3
4,201
67,716,457
How to find out combination of two columns in Dataframe? when there is multiple columns in dataframes?
<p>I have the following dataframe...</p> <pre><code>df1: playerA playerB PlayerC PlayerD kim lee b f jackson kim d g dan lee a d </code></pre> <p>I want to generate a new data frame with all possible combinations of two columns. For example,</p> <pre><code>df_new: T...
<p>Here's an approach using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html?highlight=melt#pandas.DataFrame.melt" rel="nofollow noreferrer"><code>pandas.DataFrame.melt()</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge.html?hi...
python|pandas|itertools
2
4,202
67,680,199
getting the index of min values with Numpy Python
<p>The function below separates each value into chunks separated by indexes <code>index</code> with the values in <code>L_list</code>. So it outputs the minimum value between indexes <code>3-5</code> which is -5 and the index of the value. Both the <code>numpy_argmin_reduceat(a, b)</code> and the <code>Drawdown</code> ...
<p>If you change the line</p> <pre class="lang-python prettyprint-override"><code>id_arr[b[1:]] = 1 </code></pre> <p>to</p> <pre class="lang-python prettyprint-override"><code>id_arr[b] = 1 </code></pre> <p>I think the function will behave as you hope.</p>
arrays|python-3.x|function|numpy|indexing
0
4,203
61,358,401
How to use a function that returns numpy array within pandas apply
<p>I have a Data Frame that looks like this:</p> <pre><code>import pandas as pd df_dict = {'var1': {(1, 1.0, 'obj1'): 1.0, (1, 1.0, 'obj4'): 1.0, (1, 1.0, 'obj3'): 2.0, (1, 1.0, 'obj5'): 2.0, (1, 1.0, 'obj2'): 3.0, (1, 2.0, 'obj1'): 1.0, (1, 2.0, 'obj4'): 1.0, (1, 2.0, 'obj3'): 2.0, (1, 2.0, 'obj5'): 2.0, (1, 2.0, 'ob...
<pre><code>import scipy.signal as signal df['var4'] = signal.savgol_filter(df.var2.values, window_length=3, polyorder=2) </code></pre> <p>gives you this output as well:</p> <pre><code>print(df) var1 var2 var3 var4 measurement_id repeat_id object ...
python|pandas
2
4,204
68,685,947
Proper method to make a class of other class instances
<p>I'm working on building a simple report generator that will run a query, put the data into a formatted excel sheet and email it.</p> <p>I am trying to get better at proper coding practices (cohesion, coupling, etc) and I am wondering if this is the proper way to build this or if there's a better way. It feels somewh...
<p>This isn't a bad solution, but I think it can be improved.</p> <p>If you'll continue this correctly, ReportGenerator should never know about query/connection and other members of Extractor, thus it shouldn't be passed to his constructor. What you can do instead is create an Extractor and an Emailer before the creati...
python|pandas
0
4,205
68,595,055
Python multiprocessing manger.list() not being pass to Matplotlib.animation correctly
<p>I have this 2 processes with a list created with manager.list() being shared between them, one is called DATA() and it is &quot;generating&quot; data and appending to the list and the other is plotting that data using Matplotlib animation FuncAnimation.</p> <p>The issue I am having, is that once I pass the list to t...
<p>Turns out the animate function was receiving 2 arguments. this response has a better explanation <a href="https://stackoverflow.com/questions/23944657/typeerror-method-takes-1-positional-argument-but-2-were-given">TypeError: method() takes 1 positional argument but 2 were given</a>. I had to modify my function from ...
python|pandas|matplotlib|python-multiprocessing|multiprocessing-manager
0
4,206
68,622,776
Make dictionary keys into rows and dict values as columns with one value as column name and one as column value
<p>I have the following data:</p> <pre><code>print(tables['T10101'].keys()) dict_keys(['Y033RL', 'A007RL', 'A253RL', 'A646RL', 'A829RL', 'A008RL', 'A191RP', 'DGDSRL', 'A822RL', 'A824RL', 'A006RL', 'A825RL', 'A656RL', 'A823RL', 'Y001RL', 'DNDGRL', 'DDURRL', 'A021RL', 'A009RL', 'A020RL', 'DSERRL', 'A011RL', 'DPCERL', 'A...
<p>We can use <code>dict</code> comprehension to normalize the given dictionary in a standard format which is suitable for creating a dataframe</p> <pre><code>d = tables['T10101'] df = pd.DataFrame({k: dict(map(reversed, v)) for k, v in d.items()}).T </code></pre> <hr /> <pre><code>print(df) 1930 1931 19...
python|pandas|dictionary|merge
3
4,207
68,492,761
Converting yfinance dataframe into multi-index dataframe
<p>Trying to convert this dataframe(df_long) into a multi-index dataframe (df_wide)</p> <p>Imported this data from yfinance. New to python so would really appreciate the help :)</p> <p><a href="https://i.stack.imgur.com/Ssi73.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>To get rid of the multi-index, use <code>.reset_index()</code>:</p> <pre><code>df_long.pivot_table(index=[&quot;Data&quot;], columns='tickers', values='grade').reset_index() </code></pre> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_i...
python-3.x|pandas|dataframe
1
4,208
68,757,454
Pandas dataframe how to make element-wise mean of list columns
<p>I have a dataframe with categorical features and values features. Value features are always lists with the exact same size (let's say 3 for the example). So the dataframe is:</p> <pre><code>Sub Model iter key l1 l2 l3 01 b 0 0 [8,8,5] [3,8,1] [6,7,8] 01 b 1 1 [4,3,6] [3,4,0] [4,...
<p>You can use <code>agg</code> and a custom function:</p> <pre><code>def mean_list(sr): return sr.apply(pd.Series).mean() out = df.groupby(['Sub', 'Model'])[['l1', 'l2', 'l3']].agg(mean_list) </code></pre> <pre><code>&gt;&gt;&gt; out l1 l2 l3 Sub Model 01 b ...
python|pandas|dataframe|pandas-groupby|data-munging
1
4,209
68,707,747
ViVIT PyTorch: RuntimeError: multi-target not supported at /pytorch/aten/src/THCUNN/generic/ClassNLLCriterion.cu:15
<p>I am trying to run Video Vision Transformer (ViViT) code with my dataset but getting an error using <strong>CrossEntropyLoss</strong> from Pytorch as the Loss function.</p> <p>There are 6 classes I have:</p> <pre><code>['Run', 'Sit', 'Walk', 'Wave', 'Sit', 'Stand'] </code></pre> <p><strong>Optimizer</strong></p> <pr...
<p>Multi target appears to be a feature supported since version 1.10.0. <a href="https://discuss.pytorch.org/t/crossentropyloss-vs-per-class-probabilities-target/138331" rel="nofollow noreferrer">https://discuss.pytorch.org/t/crossentropyloss-vs-per-class-probabilities-target/138331</a></p> <p>Please check your pytorch...
nlp|pytorch|computer-vision|loss-function|transformer-model
0
4,210
68,450,653
Python - efficient way to save an array with multiple labels
<p>I am currently saving some data from a process.</p> <pre><code>np.save('stochastic_data',(rho_av,rho_std)) </code></pre> <p>where rho_av and rho_std are arrays.</p> <p>However, this data depends on some parameters, say E, k, and M. For each of them, I get different data. But I am only saving the data for a given set...
<p>You are saving a tuple of arrays.</p> <p>Look what happens with a simple case of 2 arrays with same shape:</p> <pre><code>In [763]: np.save('test.npy',(np.arange(3), np.ones(3))) In [764]: np.load('test.npy') Out[764]: array([[0., 1., 2.], [1., 1., 1.]]) </code></pre> <p>I got back one array - it made an arr...
python|arrays|numpy|dictionary|save
1
4,211
53,137,588
pytorch backports.functools_lru_cache conflict
<p>I'm using <em>Windows 10</em>, and my the installation dir is: <code>anacoda2/python2.7/python3.6/opencv/cdua10/cudnn ....</code> </p> <p>Now I want to install pytorch, with this command: <code>conda install pytorch -c pytorch</code></p> <p>But as result I'm getting this error:</p> <pre><code>C:\Users\MM&gt;conda...
<p>I faced a similar problem while installing pytorch. I was able to resolve it by creating another environment on anaconda which had python version 3.6. </p>
python-2.7|pytorch
0
4,212
65,864,234
Timestamp format not being matched in pandas to_datetime format specifier
<p>I have a pandas dataframe with some timestamp values in a column. I wish to get the sum of values grouped by every hour.</p> <pre><code> Date_and_Time Frequency 0 Jan 08 15:54:39 NaN 1 Jan 09 10:48:13 NaN 2 Jan 09 10:42:24 NaN 3 Jan 09 20:18:46 NaN 4 Jan 09 12:08:23 NaN </code></pre> <p>I started off remo...
<p>I suggest you create a self defined lambda function which selects the needed format string. You may have to edit the lambda function:</p> <pre><code>df = pd.DataFrame({'Date_and_Time':['Jan 08 15:54:39', 'Jan 09 10:48:']}) df &gt;&gt;&gt; Date_and_Time 0 Jan 08 15:54:39 1 Jan 09 10:48: </code></pre> <p>With...
python|pandas
0
4,213
65,629,540
select a row index weighted by value
<p>weight dictionary: <code>{1:0.1, 2:0.9}</code> (there is a 10% probability of an item with the value 1 of being selected, 90% with value 2)</p> <p>exmple value row: <code>[0, 0, 1, 0, 2, 1]</code> (the will only be 0s and values that are contained in the dictionary)</p> <p>The output should be a randomly chosen inde...
<p>You can use <code>np.select</code> here.</p> <pre><code>wt = {1:0.1, 2:0.9} a = np.array([0, 0, 1, 0, 2, 1]) choicelist = [a==i for i in wt.keys()] condlist = [v/np.count_nonzero(a==k) for k,v in wt.items()] np.select(choicelist, condlist) # array([0. , 0. , 0.05, 0. , 0.9 , 0.05]) </code></pre>
python|pandas|numpy|random|python-3.8
3
4,214
65,737,094
get the maximum element in an array using "=="
<p>I have an array <code>x</code> :</p> <pre><code>numpy.random.seed(1) #input x = numpy.arange(0.,20.,1) x = x.reshape(5,4) print(x) [[ 0. 1. 2. 3.] [ 4. 5. 6. 7.] [ 8. 9. 10. 11.] [12. 13. 14. 15.] [16. 17. 18. 19.]] </code></pre> <p>I want to access the maximum element in this array. In my assignment, th...
<p>This is called <strong>Boolean array indexing</strong>.</p> <p>With <code>x == x.max()</code>, the below boolean array is generated:</p> <pre class="lang-py prettyprint-override"><code>[[ False False False False] [ False False False False] [ False False False False] [ False False False False] [ False...
python|arrays|numpy
2
4,215
63,418,400
For loop into a pandas dataframe
<p>I have the following piece of code and it works but prints out data as it should. I'm trying (unsuccessfully) to putting the results into a dataframe so I can export the results to a csv file. I am looping through a json file and the results are correct, I just need two columns that print out to go into a dataframe...
<p>In this instance, it's likely easier to just write the csv file directly, rather than go through Pandas:</p> <pre><code>with open(&quot;enterprise_attack.csv&quot;, &quot;w&quot;) as f: my_writer = csv.writer(f) for obj in objects: ext_ref = obj.get('external_references',[]) revoked = obj....
python-3.x|pandas|dataframe
2
4,216
63,361,442
Is it good to use scipy sparse data structure for non-sparse matrices?
<p>Using <code>scipy.sparse</code> is very efficient both in storing and doing computations on sparse matrices. What if it is used for non-sparse matrices? More specifically, It is clear that we cannot exploit the sparsity benefits of that data structure, however, is it worse (in storage and computation complexity) tha...
<p>Yes, it is worse in both storage and performance, let alone cognitive load for whoever reads your code.</p>
python|arrays|python-3.x|numpy|scipy
1
4,217
63,666,847
" value_counts()" and "agg('count')" returning different results
<p>I have a dataframe and one of its columns (named '<code>income</code>') has int values. Some fields have 0 as set value.</p> <p>When I call</p> <pre><code>print(df[df['income'] == 0].agg('count')) </code></pre> <p>It returns the exact count of 0 values in the DF column.</p> <p>Occurs that if I call</p> <pre><code>p...
<p>You can select <code>Series</code> after <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>Series.value_counts</code></a> by index - here <code>0</code> for count of <code>0</code> values:</p> <pre><code>df = pd.DataFrame({ 'i...
python|pandas
1
4,218
71,905,124
Second to_replace to dataframe is not updating dataframe in Python
<p>I am replacing values of an existing dataframe in Python during a <code>for loop</code>. My original dataframe is of this format:</p> <p><a href="https://i.stack.imgur.com/qyySn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qyySn.png" alt="enter image description here" /></a></p> <p>After tryin...
<p>If I understand correctly what you are looking for 'fsID', would this work (after your 'slice_file_name' is updated) ?</p> <pre><code>df['fsID']=df['fsID']+'_'+df['slice_file_name'].str.split('_',expand=True)[1].str.replace('.wav','') </code></pre>
python|pandas|dataframe
0
4,219
72,026,216
How to create a rolling unique count by group using pandas
<p>I have a dataframe like the following:</p> <pre><code>group value 1 a 1 a 1 b 1 b 1 b 1 b 1 c 2 d 2 d 2 d 2 d 2 e </code></pre> <p>I want to create a co...
<p>Also cab be solved as :</p> <pre><code>df['group_val_id'] = (df.groupby('group')['value']. apply(lambda x:x.astype('category').cat.codes + 1)) df group value group_val_id 0 1 a 1 1 1 a 1 2 1 b 2 3 1 b ...
pandas
0
4,220
71,874,683
Compare column name with a row value and getting other row value
<p>I have a dataframe like this:</p> <pre><code> request_created_at sponsor_tier is_active status cash_in 2019/10 ... 2021/07 0 2019/10 2019/10 2.0 True 1 8901.00 ... 1 2019/10 2019/10 2.0 Tr...
<pre><code>def check_status (row, data): if (row.status == 1) &amp; (row.request_created_at == data): return row.total_cash_in elif (row.status == 4) &amp; (row.request_created_at == data): return row.total_cash_in elif (row.status == 7) &amp; (row.request_created_at == data): return...
python|pandas|dataframe|data-wrangling
0
4,221
71,904,826
How can i calculate for Average true range in pandas
<p>how can I calculate the Average true range in a data frame</p> <p>I have tried to using <code>np where()</code> and is not working</p> <p>I have all this value below</p> <p>Current High - Current Low</p> <p>abs(Current High - Previous Close)</p> <p>abs(Current Low - Previous Close)</p> <p>but I don't know how I to s...
<p>It looks like you might be trying to do the following :</p> <pre><code>import pandas as pd from numpy.random import rand df = pd.DataFrame(rand(10,5),columns={'High-Low','High-close','Low-close','A','B'}) cols = ['High-Low','High-close','Low-close'] df['true_range'] = df[cols].max(axis=1) print(df) </code></pre> ...
python|arrays|pandas|dataframe|numpy
1
4,222
56,486,295
In a pandas dataframe (python 3) column, I need to standardize all instances of (for example) "PO BOX", or "P O Box" or "POBOX", etc. to "BOX"
<p>I have a list of 30 or so synonyms that could be found in an address to indicate a PO Box. I would like to be able to scan an address and if one of these synonyms are in the address, change it to simply BOX.</p> <p>First of all, I'm new to Python. I am a seasoned SAS programmer, trying to learn Python. I've tried...
<p>I'm just going to use a pd.Series but it's the same as one dataframe columns. </p> <pre><code>rep = {'PO BOX': 'BOX', 'P BOX': 'BOX', 'POSTBOX': 'BOX', 'P O BOX': 'BOX', 'POBOX':'BOX', 'POB': 'BOX'} address = [ "13943 PO BOX 1234", "14738 510 BLUE BELL RD", "27455 5887 CORNERS AVENUE", "27457 200 NEW HAVEN DR SUI...
python-3.x|pandas|dataframe
0
4,223
47,133,934
Pandas search in ascending index and match certain column value
<p>I have a DF with thousands of rows. Column 'col1' is repeatedly from 1 to 6. Column 'value' is with unique numbers:</p> <pre><code>diction = {'col1': [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6], 'target': [34, 65, 23, 65, 12, 87, 36, 51, 26, 74, 34, 87]} df1 = pd.DataFrame(diction, index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1...
<pre><code>df1['Per_col']=df1.groupby('col1').target.shift(1).fillna(0) df1 Out[1117]: col1 target Per_col 0 1 34 0.0 1 2 65 0.0 2 3 23 0.0 3 4 65 0.0 4 5 12 0.0 5 6 87 0.0 6 1 36 34.0 7 2 51 65....
pandas
1
4,224
47,257,390
TensorFlow - Difference between tf.VariableScope and tf.variable_scope
<p>Have found two links on TensorFlow website referring to <code>variable scope</code>, one is <a href="https://www.tensorflow.org/api_docs/python/tf/variable_scope" rel="nofollow noreferrer">tf.variable_scope</a> which is the one most commonly used, and the other <a href="https://www.tensorflow.org/api_docs/python/tf/...
<p><a href="https://www.tensorflow.org/api_docs/python/tf/VariableScope" rel="nofollow noreferrer"><code>tf.VariableScope</code></a> is an actual scope class that holds the <code>name</code>, <code>initializer</code>, <code>regularizer</code>, <code>partitioner</code>, and many other properties that are propagated to t...
python|tensorflow|contextmanager
1
4,225
47,321,133
sklearn Hierarchical Agglomerative Clustering using similarity matrix
<p>Given a distance matrix, with similarity between various professors :</p> <pre><code> prof1 prof2 prof3 prof1 0 0.8 0.9 prof2 0.8 0 0.2 prof3 0.9 0.2 0 </code></pre> <p>I need to perform hierarchical clustering on this data, where...
<p>Yes, you can do it with <code>sklearn</code>. You need to set:</p> <ul> <li><code>affinity='precomputed'</code>, to use a matrix of distances</li> <li><code>linkage='complete'</code> or <code>'average'</code>, because default linkage(Ward) works only on coordinate input.</li> </ul> <p>With precomputed affinity, in...
python|pandas|scikit-learn|hierarchical-clustering
11
4,226
68,359,857
Multiple dataframe groupby Pandas
<p>I have 2 datasets to work with:</p> <pre><code>ID Date Amount 1 2020-01-02 1000 1 2020-01-09 200 1 2020-01-08 400 </code></pre> <p>And another dataset which tells which is most frequent day of week and most frequent week of month for each ID(there are multiple such IDs)</p> <pre><code>ID Pref_Day_Of_Week...
<p>Idea is filter only matched <code>dayofweek</code> and <code>week</code> and aggregate <code>sum</code>, last join together by <code>concat</code>:</p> <pre><code>#https://stackoverflow.com/a/64192858/2901002 def weekinmonth(dates): &quot;&quot;&quot;Get week number in a month. Parameters: date...
python|pandas|numpy|scipy
1
4,227
68,117,247
Applying function to pandas dataframe column after str.findall
<p>I have such a dataframe <code>df</code> with two columns:</p> <pre><code>Col1 Col2 'abc-def-ghi' 1 'abc-opq-rst' 2 </code></pre> <p>I created a new column <code>Col3</code> like this:</p> <pre><code>df['Col3'] = df['Col1'].str.findall('abc', flags=re.IGNORECASE) </code></pre> <p>And got such a dataframe afterwards:...
<p>Just do</p> <pre><code>df['Col4'] = df.Col3.astype(bool).astype(int) </code></pre>
python|pandas|python-re
3
4,228
68,102,569
numpy create Mx2 matrix based on Mx1 matrix
<p>I have a np.array with 800 values. Each value is either 0 or 1.</p> <p>If the value is 0, I want to replace it with <code>mu_0</code>, which is a 1x2 array; else, I want to replace it with <code>mu_1</code>, which is also a 1x2 array.</p> <p>I tried using <code>np.where(y == 0, mu_0, mu_1)</code>, but python would o...
<p>You can indeed expand <code>y</code> into <code>(800, 2)</code> with, for example, <code>np.repeat</code> so that 0s are 0s, 1s are 1s for each row. Then we can use <code>np.where</code>:</p> <pre><code># first casting to (800, 1) with `newaxis` then repetition y_rep = np.repeat(y[:, np.newaxis], repeats=2, axis=1) ...
python|arrays|numpy
1
4,229
57,194,049
Merging two csv files and extracting out useful information using python
<p>I have two .csv files that look like following: </p> <p>file_1:</p> <pre><code>id a b c 10 1 2 3 11 2 3 4 </code></pre> <p>file_2:</p> <pre><code>id d e 10 2 3 11 2 3 12 2 3 </code></pre> <p>My expected output is:</p> <pre><code>id a b c d e 10 1 2 3 2 3 11 2 3 4 2 3 </code></pre> <p>I wish to...
<p>Try using <code>pd.DataFrame.merge</code>:</p> <pre><code>print(file_1.merge(file_2, on='id')) </code></pre> <p>Output:</p> <pre><code> a b c id d e 0 1 2 3 10 2 3 1 2 3 4 11 2 3 </code></pre> <p>If you care about the order of the columns do:</p> <pre><code>print(file_1.merge(file_2, on='id')...
python|pandas
0
4,230
57,186,587
Pandas: replace repeated values with blanks groupby like
<p>I got dataframe with columns got groups of repeated values. What i want is to keep only first item in such columns.</p> <p>I've tried <code>df = df.groupby(['author', 'key'])</code> but don't know how to correctly get all rows. With <code>df.first()</code> only first rows will be printed.</p> <pre><code>import pan...
<p>Looks like you need <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer"><code>df.duplicated()</code></a> to find duplicates and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow nore...
python|pandas|pandas-groupby
1
4,231
46,036,607
Transforming a Cassandra OrderedMapSerializedKey to a Python dictionary
<p>I have a column in Cassandra composed of a map of lists which when queried with the Python driver it returns an OrderedMapSerializedKey structure. This structure is a map of lists. I would like to put the whole query into pandas.</p> <p>To extract data from that OrderedMapSerializedKey structure, meaning to get the...
<p>I think an ultimate solution could be to store <code>OrderedMapSerializedKey</code> Cassandra structure as a <code>dict</code> in your dataframe column then you could transfer this value / column to anyone you want. Ultimate because you may not know the actual keys in Cassandra rows (maybe different keys are inserte...
python|python-3.x|pandas|cassandra
3
4,232
50,975,649
Pandas Drop levels and attach to column title
<p>Using pivot function I have managed to obtain flatten data frame:</p> <pre><code>q_id 1 2 a_id 1 2 3 4 5 6 7 8 movie_id user_id start_rating 931 284 2.0 0 0 ...
<p>The function <a href="https://docs.python.org/2/library/string.html#string.join" rel="nofollow noreferrer"><code>join</code></a> works with strings, and the element of col are <code>int</code> as the error shows. You need to convert the element of <code>col</code> to <code>str</code>.</p> <pre><code>df.columns = ['...
pandas
1
4,233
51,057,924
Validate in merge function pandas
<p>Today I was trying to go a little deeper in the <code>merge()</code> function of pandas, and I found the option <code>validate</code>, which, as reported in the documentation, can be:</p> <blockquote> <p>validate : string, default None</p> <p>If specified, checks if merge is of specified type.</p> <p>“one_to_one” or...
<p>The new <code>valdate</code> param will raise a <code>MergeError</code> if the validation fails, example:</p> <pre><code>df1 = pd.DataFrame({'a':list('aabc'),'b':np.random.randn(4)}) df2 = pd.DataFrame({'a':list('aabc'),'b':np.random.randn(4)}) print(df1) print(df2) a b 0 a -2.557152 1 a -0.145969 2 ...
python|pandas|validation|merge
15
4,234
66,522,791
Create a subset by filtering on Year
<p>I have a sample dataset as shown below:</p> <pre><code>| Id | Year | Price | |----|------|-------| | 1 | 2000 | 10 | | 1 | 2001 | 12 | | 1 | 2002 | 15 | | 2 | 2000 | 16 | | 2 | 2001 | 20 | | 2 | 2002 | 22 | | 3 | 2000 | 15 | | 3 | 2001 | 19 | | 3 | 2002 | 26 | </code></pre> <p>I w...
<p>Per the comments, <code>Year</code> is type <code>object</code> in the raw data. We should first cast it to <code>int</code> and then compare with numeric <code>end_year</code>:</p> <pre class="lang-py prettyprint-override"><code>df.Year=df.Year.astype(int) # cast `Year` to `int` end_year=2002 # now we can use `int`...
python|pandas|subset
1
4,235
66,359,164
How to normalize and create similarity matrix in Pyspark?
<p>I have seen many stack overflow questions about similarity matrix but they deal with RDD or other cases and I could not find the direct answer to my problem and I decided to post a new question.</p> <h1>Problem</h1> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd import pyspark...
<pre><code>import pyspark.sql.functions as F df.show() +-------+-----+-----------+------+ |user_id|apple|good banana|carrot| +-------+-----+-----------+------+ | user_0| 0| 3| 1| | user_1| 1| 0| 2| | user_2| 5| 1| 2| +-------+-----+-----------+------+ </code></pre> <p>Sw...
python|pandas|apache-spark|pyspark|apache-spark-sql
6
4,236
57,695,946
pandas change attribute values to row values of object
<p>data aggregation parsed from file at the moment:</p> <pre><code>obj price1*red price1*blue price2*red price2*blue a 5 7 10 12 b 15 17 20 22 </code></pre> <p>desired outcome:</p> <pre><code>obj color price1 price2 ...
<p>A solution that makes use of a <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#" rel="nofollow noreferrer">MultiIndex</a> as an intermediate step:</p> <pre><code>import pandas as pd # Construct example dataframe col_names = ["obj", "price1*red", "price1*blue", "price2*red", "price2*b...
python|pandas|pivot|multiple-columns|rows
0
4,237
57,303,028
How to work out mean after specific number of months for different customers using python?
<p>I have a <code>dataframe</code> of customers and how much they spend each month as shown below:</p> <pre><code>data =[['Armin',12,5,11,24,5,4,10,5],['Benji',10,12,10,32,4,18,0,0],['Casey',0,0,30,15,25,5,0,0]] df = pd.DataFrame(data, columns = ['Name','2019-01','2019-02','2019-03','2019-04','2019-05','2019-06','201...
<p>First get positions by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_indexer.html" rel="nofollow noreferrer"><code>Index.get_indexer</code></a> in <code>df</code>, then select next 3 values with <code>np.add.outer</code> and get <code>mean</code>:</p> <pre><code>N = 3 a = df.co...
python|pandas|mean
4
4,238
57,522,916
Round Datetime Object DOWN in Python
<p>I'm trying to round a <code>datetime</code> object DOWN in Python, and am having a few problems. There is lots on here about rounding <code>datetime</code> but I can't find anything specific to my needs.</p> <p>I'm trying to get a date range of 15 minute intervals, with <code>.now()</code> being the end point. To g...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.floor.html" rel="nofollow noreferrer"><code>Timestamp.floor</code></a>:</p> <pre><code>print (pd.Timestamp('2019-08-16 11:15:00').floor('15min')) 2019-08-16 11:15:00 print (pd.Timestamp('2019-08-16 11:23:00').floor('15min')) 201...
python|pandas|datetime
3
4,239
57,350,239
DecisionTreeRegressor score not calculated
<p>I'm trying to calculate the score of a DecisionTreeRegressor with the following code:</p> <pre><code>from sklearn import preprocessing from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.metrics import accuracy_score from sklearn i...
<p>The first argument of the score function shouldn't be the target value of the test set, it should be the input value of the test set, so you should do</p> <pre><code>classifier.score(X_test, y_test) </code></pre>
python|pandas|scikit-learn|data-science|decision-tree
2
4,240
70,504,394
How to use Wildcard in Numpy array operations?
<p>For instance, define a numpy array with <code>numpy.str_</code> format and doing the replace operation supported by <code>numpy.char</code>:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np a = np.array(['a-b-c-d','e-f-g-h'],np.str_) print (np.char.replace(a,'*-','i-')) </code></pre> <p>The ret...
<p>Is there any reason to use numpy arrays? You can't use wildcards with <code>numpy.char.replace</code>.</p> <p>I would suggest to use python lists here and the <code>re</code> module:</p> <pre><code>l = ['a-b-c-d', 'e-f-g-h'] import re out = [re.sub('.-', 'i-', i) for i in l] </code></pre> <p>Output: <code>['i-i-i-d'...
python|numpy
3
4,241
51,152,776
How to save lmplot in pandas
<p>For reg plot, this is working:</p> <pre><code>sns_reg_plot = sns.regplot(x="X", y="y", data=df) sns_reg_fig = sns_reg_plot.get_figure() sns_reg_fig.savefig(path) </code></pre> <p>But for lm plot I get an error:</p> <pre><code>sns_lm_plot = sns.lmplot(x="X", y="y", hue="hue", data=df) .. sns_lm_fig = sns_lm_pl...
<p>Just remove the .get_figure line</p> <pre><code> sns_im_plot = sns.lmplot(x="X", y="y",hue="hue" data=df) sns_im_plot.savefig(path) </code></pre>
python|pandas|matplotlib|visualization|figures
1
4,242
51,614,014
Merging Pandas dataframes on same column identifier with improper output
<p><strong>Scenario:</strong> I have a code that reads a set of excel files from a directory and gathers the contents of each to a dataframe in a list then concatenates it. The code also reads another file where it gets the data for some identifiers into another dataframe.</p> <p><strong>Example of data in the concate...
<p>You need to use a left join here. As per the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer">documentation</a>, left join preserves all of the values in the first DataFrame, subbing in values from the second dependent on the structure of the firs...
python|pandas|dataframe
2
4,243
37,819,082
Error reached while attempting to create a numpy array
<p>Here's my code: </p> <pre><code>import numpy as np x = np.array[[1,2]] print x </code></pre> <p>Here's the output:</p> <pre><code>Traceback (most recent call last): File "Shear_Moment_Test.py", line 2, in &lt;module&gt; x = np.array[[1,2]] TypeError: 'builtin_function_or_method' object has no attribute '__g...
<p>The syntax which you used is wrong. Use this <code>x = np.array([1,2])</code></p>
python|arrays|numpy
1
4,244
31,331,358
Unicode Encode Error when writing pandas df to csv
<p>I cleaned 400 excel files and read them into python using pandas and appended all the raw data into one big df.</p> <p>Then when I try to export it to a csv:</p> <pre><code>df.to_csv("path",header=True,index=False) </code></pre> <p>I get this error:</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode c...
<p>You have <code>unicode</code> values in your DataFrame. Files store bytes, which means all <code>unicode</code> have to be encoded into bytes before they can be stored in a file. You have to specify an encoding, such as <code>utf-8</code>. For example, </p> <pre><code>df.to_csv('path', header=True, index=False, enc...
python|pandas|export-to-csv|python-unicode
69
4,245
47,912,449
Pandas 0.21 reindex() after get_dummies()
<p><strong>Background</strong></p> <p>My project is doing a Pandas upgrade from 0.19.2 to 0.21.0. In the project, I have a DataFrame with one categorical column. And I use get_dummies() to encode it, and then use reindex() to filter columns. However, if the columns arg in reindex() contain non-encoded column, the rein...
<p>This certainly seems like a bug. As of v0.21, they've reworked a lot of their <code>reindex</code> API, so it seems something could've broken somewhere.</p> <p>I don't have an answer, but I do have a workaround, hopefully it should do: You'll need to first transpose, and <em>then</em> reindex.</p> <pre><code>df.T....
python|pandas|dataframe
2
4,246
58,686,226
How add element to a NumPy array in a Python function
<p>I am trying to create a series of NumPy arrays from a text file using a pool of workers with multiprocessing module.</p> <pre><code>def process_line(line, x,y,z,t): sl = line.split() x = np.append(x,float(sl[0].replace(',',''))) y = np.append(y,float(sl[1].replace(',',''))) z = np.append(z,float(sl[...
<p>You are passing the values as part of a tuple in the code here:</p> <pre><code> jobs.append(pool.apply_async(process_line,(line,x,y,z,t))) </code></pre> <p>Then you unpack this tuple implicitly in the function:</p> <pre><code>def process_line(line, x,y,z,t): </code></pre> <p>Then you do not change the exi...
python|pass-by-reference|numpy-ndarray
1
4,247
58,651,915
pandas split cumsum to upper limits and then continue with remainder in different column
<p>I have a <code>DataFrame</code> such that:</p> <pre><code> Amt Date 01/01/2000 10 01/02/2000 10 01/03/2000 10 01/04/2000 10 01/05/2000 10 01/06/2000 10 01/07/2000 10 </code></pre> <p>Now suppose I have two storage facilities to store the <code>Amt</code> of product that...
<p>Use <code>np.select</code> to get the storage amount:</p> <pre><code>s = df["Amt"].cumsum() df["Storage 1"] = np.select([s&lt;=45, s&gt;45], [s/2,22.5]) df["Storage 2"] = np.select([s&lt;=52.5, s&gt;52.5], [s-df["Storage 1"], 30]) df["Sell"] = s-df["Storage ...
python|pandas|cumsum
2
4,248
58,947,771
Python Pandas - convert list into series
<p>I have an excel data set looks like this:</p> <p><a href="https://i.stack.imgur.com/Gr2yU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gr2yU.png" alt="enter image description here"></a></p> <p>for copy purpose:</p> <pre><code>ID buffer LocalHub@3c183d50 [intraCity_Simulator.Parcel@5507854...
<p>Solution for pandas 0.25+ is remove <code>[]</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.strip.html" rel="nofollow noreferrer"><code>Series.str.strip</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel...
python|pandas
1
4,249
58,920,176
Pandas_datareader error SymbolWarning: Failed to read symbol: 'T', replacing with NaN
<p>I have this code which gets a list of symbols from wikipedia and then gets the stock data from yahoofinance. This is a simple code which was working fine up till a couple days ago but for some reason i getting the <code>unable to read symbol</code> error on many stocks. Is yahoo doing this? What can i do to fix this...
<p>Looks like the date issue could be fixed by replacing tickers with a <code>'.'</code> to <code>'-'</code> per this <a href="https://github.com/pydata/pandas-datareader/issues/617#issuecomment-497620900" rel="nofollow noreferrer">github issue</a></p> <p>Also you do not need <code>requests</code> or <code>BeautifulSo...
python-3.x|pandas|pandas-datareader
1
4,250
70,075,182
'list' object has no attribute 'items' for saving list of array as mat file
<p>I want to save a list of NumPy array as a mat file but raised with error <code>'list' object has no attribute 'items'</code>. You can see my try below:</p> <pre><code>import numpy as np import scipy.io output=[] for i in range(10): a=np.random.randint(0,100,size=(60,60,4)) output.append(a) scipy.io.savemat('tes...
<p>Here is the answer:</p> <pre><code>import numpy as np import scipy.io output=[] for i in range(10): a=np.random.randint(0,100,size=(60,60,4)) output.append(a) scipy.io.savemat('test.mat', mdict={'my_list': output}) </code></pre>
python|list|numpy|scipy|mat-file
1
4,251
70,170,938
Convert Pandas dataframe with multiindex to a list of dictionaries
<p>I have a pandas dataframe, which looks like</p> <pre><code> df = Index1 Index2 Index3 column1 column2 i11 i12 i13 2 5 i11 i12 i23 3 8 i21 i22 i23 4 5 </code></pre> <p>How to convert this into list of dictionaries with keys as <cod...
<pre><code>d = {'Index1': [&quot;i11&quot;, &quot;i12&quot;, &quot;i13&quot;], 'Index2': [&quot;i21&quot;, &quot;i22&quot;, &quot;i23&quot;], 'Index3': [&quot;i31&quot;, &quot;i32&quot;, &quot;i33&quot;], 'column1': [2, 3,4], 'column2': [5, 8, 5]} df = pd.DataFrame(data=d) </code></pre...
python-3.x|pandas|dictionary
1
4,252
70,203,246
Speeding up similarity function using numpy and parallel processing?
<p>I've got a matrix of points (real shape is generally in the neighborhood of (8000,127000)):</p> <p><code>M = [[1,10,2],[10,2,2],[8,3,4],[2,1,9]]</code></p> <p>And a target:</p> <p><code>N = [1,2,10]</code></p> <p>I'm using this function to create an array of distances from N (which I then sort by distance):</p> <pre...
<p>Depending on what your exact needs are, you may want to consider an alternate data structure. If you are searching for something like the <code>k</code> nearest neighbors to a given <code>N</code>, you might consider using <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.KDTree.html" rel="...
python|numpy|multiprocessing
0
4,253
64,941,304
Unable to give Keras neural network multiple inputs
<p>I am trying to get a data pipeline of text based data into a neural network with two heads. Made use of the official documentation that tells you to zip it into a dictionary of values, but it did not work.</p> <pre><code>&lt;MapDataset shapes: (None, 32), types: tf.int64&gt; &lt;MapDataset shapes: (None, 32), types:...
<p>From what I can tell of your problem it seems that your two input layers are <em>already</em> datasets. from_tensors likely is expecting tensor objects, not datasets. For instance given a model of this shape:</p> <pre><code>input_a = keras.Input(10,name=&quot;initial_input&quot;) input_b = keras.Input(5, name=&quo...
tensorflow2.0|tensorflow-datasets|tf.keras
1
4,254
39,730,528
TypeError: Signature mismatch. Keys must be dtype <dtype: 'string'>, got <dtype:'int64'>
<p>While running the <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/learn/wide_n_deep_tutorial.py" rel="nofollow noreferrer">wide_n_deep_tutorial</a> program from TensorFlow on my dataset, the following error is displayed.</p> <pre><code>"TypeError: Signature mismatch. Keys must be d...
<p>would help to see the output prior to the error message to determine which part of the process this error tripped out at, but, the message says quite clearly that the key is expected to be a string whereas an integer was given instead. I am only guessing, but are the column names set out correctly in the earlier par...
python|pandas|tensorflow
0
4,255
39,626,432
how to calculate entropy from np histogram
<p>I have an example of a histogram with:</p> <pre><code>mu1 = 10, sigma1 = 10 s1 = np.random.normal(mu1, sigma1, 100000) </code></pre> <p>and calculated </p> <pre><code>hist1 = np.histogram(s1, bins=50, range=(-10,10), density=True) for i in hist1[0]: ent = -sum(i * log(abs(i))) print (ent) </code></pre> <p>No...
<p>You can calculate the entropy using vectorized code:</p> <pre><code>import numpy as np mu1 = 10 sigma1 = 10 s1 = np.random.normal(mu1, sigma1, 100000) hist1 = np.histogram(s1, bins=50, range=(-10,10), density=True) data = hist1[0] ent = -(data*np.log(np.abs(data))).sum() # output: 7.1802159512213191 </code></pre>...
python|numpy|histogram|entropy
9
4,256
69,554,229
How to convert the prediction of pytorch into normal text
<p>I have a PyTorch model and i am doing prediction on it. After doing prediction i am getting the output as</p> <pre><code>tensor([[-3.4333]], grad_fn=&lt;AddmmBackward&gt;) </code></pre> <p>But i need it as normal integer <code>-3.4333</code>. How can i do it.</p>
<p>Call <a href="https://pytorch.org/docs/stable/generated/torch.Tensor.item.html" rel="nofollow noreferrer"><code>.item</code></a> on your tensor to convert it to a standard python number.</p>
python|pytorch|tensor
1
4,257
69,427,862
PyTorch attach extra connection when building model
<p>I have the following Resnet prototype on Pytorch:</p> <pre><code>Resnet_Classifier( (activation): ReLU() (model): Sequential( (0): Res_Block( (mod): Sequential( (0): Conv1d(1, 200, kernel_size=(5,), stride=(1,), padding=same) (1): ReLU() (2): BatchNorm1d(200, eps=1e-05, momentum...
<p>The model visualization seems incorrect, the main branch and skip connection are encapsulated inside your <code>Res_Block</code> definition, it should not appear outside of the red <code>Res_Block[0]</code> box, but instead inside.</p>
pytorch|tensorboard|tensorboardx
0
4,258
69,384,704
Filtering large data set by year
<p>Working with a very large dataset that I need to be able to filter by year. I read the text file as a csv:</p> <pre><code>df1=pd.read_csv(filename, sep=&quot;\t&quot;, error_bad_lines=False, usecols=['ID','Date', 'Value1', 'Value2']) </code></pre> <p>And co...
<p>You could also specify to parse <code>Date</code> when reading it. As @ALollz mentioned you have some NaN values in <code>Date</code> and when you replace them with 0 this changes the type of the column. If you just want to filter by the year then the code below should work. If you wanted to filter by year/month the...
python|pandas|datetime|large-data
0
4,259
53,913,511
How to implement SQL Row_number in Python Pandas?
<p>I am trying to number my dataframe records using SQL "Row_number over" function available in SQL but it results in error as shown in the image. Please note that I don't wish to number records using Pandas function. </p> <p>Here is the code</p> <pre><code>df1.head() </code></pre> <p>output of df1.head statement</p...
<p>The problem is pretty simple and you might have figured it out already. The # breaks the whole thing as that is an unrecognized token.</p> <p>If you leave that out, your code should work.</p> <pre><code>from pandasql import sqldf q1='select beef, veal, ROW_NUMBER() OVER (ORDER BY date ASC) as RN FROM df1' df_new...
python|sql|pandas
2
4,260
54,208,890
Function with IF and ELIF using pandas
<p>What is a better way (if there is one) to define a function that checks whether a pandas column is within a given range of integers?</p> <p>I have a column in a Pandas dataframe which I wanted to check whether the values are between a set range. I chose to do so by creating a function which accepts the dataframe as...
<p>You can make use of <code>np.select</code> to manage your conditions and options. This allows you to maintain your conditions and options easily and makes use of the <code>numpy</code> library functions which may help speed up your code</p> <pre><code>def fn(dframe): import numpy as np condlist = [ ...
python|pandas|function
0
4,261
38,218,691
Building and linking shared Tensorflow library on OSX El Capitan to call from Ruby via Swig
<p>I'm trying to help build a Ruby wrapper around <a href="https://www.tensorflow.org/versions/r0.9/get_started/os_setup.html" rel="nofollow">Tensorflow</a> using <a href="http://www.swig.org/Doc1.3/Ruby.html#Ruby_nn11" rel="nofollow">Swig</a>. Currently, I'm stuck at making a shared build, <code>.so</code>, and exposi...
<p>After more digging around, discovering <code>otool</code> (thanks Kristina) and better understanding what a <a href="https://stackoverflow.com/questions/2339679/what-are-the-differences-between-so-and-dylib-on-osx"><code>.so</code></a>-file is, the solution didn't require much change in my setup:</p> <h3>Shared Bui...
ruby|macos|tensorflow|swig|bazel
4
4,262
38,413,913
numpy einsum: nested dot products
<p>I have two <code>n</code>-by-<code>k</code>-by-<code>3</code> arrays <code>a</code> and <code>b</code>, e.g.,</p> <pre><code>import numpy as np a = np.array([ [ [1, 2, 3], [3, 4, 5] ], [ [4, 2, 4], [1, 4, 5] ] ]) b = np.array([ [ [3, 1, 5], ...
<p>You are loosing the third axis on those two <code>3D</code> input arrays with that sum-reduction, while keeping the first two axes aligned. Thus, with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a>, we would have the first two strings identic...
python|numpy|numpy-einsum
3
4,263
38,298,452
compatibility of tensorflow and hadoop
<p>I want to use tensorflow as a machine learning library and hadoop as a big data framework. But i don know these are compatible. I can't search any reference in website.</p> <p>my question is</p> <ol> <li>Can I use tensorflow with hadoop?</li> <li>(if no) please recommend big data framework can be use with tensorfl...
<p>They are compatible. In my company we have application running on Hadoop using TensorFlow. To make it clear think of TensorFlow as python library which can be used within python. One example will be to write a Map-Reduce code in which mapper groups/accumulates data and in reducer your learning code is present in red...
hadoop|tensorflow
0
4,264
38,216,848
Tensorflow Serving on Docker | write too long
<p>Trying to follow the tutorial "Using TensorFlow Serving via Docker": <a href="https://tensorflow.github.io/serving/docker" rel="nofollow">https://tensorflow.github.io/serving/docker</a></p> <p>I'm getting the error below:</p> <pre><code>$ docker build --pull -t $USER/tensorflow-serving-devel -f Dockerfile.devel . ...
<p>The mistake was running this command on the command line outside the docker machine. Once this command was run inside the docker machine, it worked fine.</p>
docker|tensorflow|tensorflow-serving
0
4,265
52,691,128
Group by ID and complet time series Pandas
<p>I have a pandas Dataframe with observations of one ID and I have a problem similar to the one solved <a href="https://stackoverflow.com/questions/27823273/counting-frequency-of-values-by-date-using-pandas">here</a>. </p> <pre><code>Timestamp ID 2014-10-16 15:05:17 123 2014-10-16 14:56:37 148 2014...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow noreferrer"><code>pd.pivot_table</code></a>:</p> <pre><code>res = df.pivot_table(index='ID', columns='Week/Year', aggfunc='count', fill_value=0) print(res) Timestamp Week/Year 41/...
python|pandas|dataframe|time-series
3
4,266
46,352,688
accessing arrays stored in pandas dataframe
<p>I have a pandas dataframe in which one column contains 1-D numpy arrays and another contains scalar data for instance:</p> <pre><code>df = A B 0 x [0, 1, 2] 1 y [0, 1, 2] 2 z [0, 1, 2] </code></pre> <p>I want to get B for the row where <code>A=='x'</code> So I tried <code>df[df.A == 'x'].B.values...
<p>The difference isn't the fact that the array is an object, but that the query you specify could return more than one object (hence the outer array()). If you're confident that the query will return only a single object, then you can use @Wen 's solution to use <code>.item()</code>:</p> <pre><code>In [1]: import pan...
python|arrays|pandas|numpy
2
4,267
46,558,735
numpy - create polynomial by its roots
<p>I'm trying to create a <code>numpy.polynomial</code> by the roots of the polynomial.</p> <p>I could only find a way to do that by the polynomial's a's</p> <p>The way it works now, for the polynomial <code>x^2 - 3x + 2</code> I can create it like that:</p> <p><code>poly1d([1, -3, 2])</code></p> <p>I want to creat...
<p>Numpy has a function that does this: <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.polynomial.polynomial.polyfromroots.html#numpy.polynomial.polynomial.polyfromroots" rel="nofollow noreferrer"><code>numpy.polynomial.polynomial.polyfromroots</code></a></p> <p>Note that</p> <blockquote> ...
python|numpy
0
4,268
58,212,973
Deep learning for computer vision: What after MNIST stage?
<p>I am trying to explore computer vision using deep learning techniques. I have gone through basic literature, made a NN of my own to classify digits using MNIST data(without using any library like TF,Keras etc, and in the process understood concepts like loss function, optimization, backward propagation etc), and the...
<p>You should try hyperparameter tuning, it will help improve your model performance. Feel free to surf around various articles, fine tuning your model will be the next step as you have fundamental knowledge regarding how model works.</p>
tensorflow|deep-learning|computer-vision|mnist|kaggle
1
4,269
58,491,488
Iterate Through Python Dict for Specific Values
<p>I am using Python 3.6 and I have a dictionary like so:</p> <pre><code>{ "TYPE": { "0": "ELECTRIC", "1": "ELECTRIC", "2": "ELECTRIC", "3": "ELECTRIC", "4": "TELECOMMUNICATIONS" }, "ID": { "0": 13, "1": 13, "2": 13, "3": 13, "...
<h1>Solution</h1> <p>You could do this using <code>pandas</code> library. Also, consider trying <code>pd.DataFrame(d)</code> to see if that could be of any use to you (since I don't know your final usecase).</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd # d is your dictionary df = pd.DataFr...
python|pandas|dictionary
1
4,270
58,456,116
Format pandas output to csv
<p>I am new to python and pandas and have created a test web page with html code to use to help with learning how to pull the data and then format into CSV for use in excel. Below is the code I have come up with that puts it into a nice format but I am stuck on how to format it into a CSV file to import.</p> <p>Code: ...
<p>so to format your questions you can show us an example of what you want. try something like this:</p> <pre><code>|id|name|data1|data2|date3|-url-| |--|----|-----|-----|-----|-----| |1 |xyz |datax|datay|dataz|x:url| |2 |xyz |datax|datay|dataz|x:url| |3 |xyz |datax|datay|dataz|x:url| ... </code></pre> <p>Then you ca...
python|pandas
1
4,271
69,048,548
why is tensorflow/keras and training and validation metrics way off from each other?
<p>a description of my project, I am trying to train a network that recognizes a picture containing a number from 0 to 9 and categorizing it as such. my model is as follows</p> <pre><code>model = Sequential( [ tf.keras.applications.MobileNetV2(include_top=False, input_shape=(224, 224, 3)), Flatten(), Dense(...
<p>The problem is with the batch normalization layers in the MobileNetV2 model, specifically with batch normalization momentum parameter as discussed in :</p> <p><a href="https://stackoverflow.com/questions/65415799/fit-works-as-expected-but-then-during-evaluate-model-performs-at-chance">fit() works as expected but the...
python|tensorflow|keras
0
4,272
69,111,142
Pandas - Add value to a Column on a For
<p>Im trying a script and i want to add value to each row on my Column login:</p> <p>If the result on For is 200 i want add &quot;yes&quot; to the login Column on the correct row.</p> <p>thank u!</p> <pre><code>import pandas as pd from requests import get lista = pd.read_csv('sites.csv', sep=',') df = pd.DataFrame(list...
<p>One way you could do it is to just iterate over the rows and add it in that way:</p> <pre><code>for i in range(newdf.shape[0]): result = get(newdf.iloc[i,0]) if result == 200: newdf.iloc[i,1] = &quot;yes&quot; </code></pre> <p>etc.</p>
python|pandas
0
4,273
69,082,127
Plot heatmap (kdeplot) with geopandas
<p>I have the following data stored in a <code>geopandas.DataFrame</code> object. <code>geometry</code> are polygons and <code>x</code> are the values I want to use as a heat scale.</p> <pre><code> id geometry x 9 01001 POLYGON ((-102.10641 22.06035, -102.10368 22.0....
<p>I was recommended to use <code>geoplot</code>.</p> <p><code>geoplot.kdeplot</code> expects a <code>geopandas.DataFrame</code> object with one row per Point. That is, something along the lines of:</p> <pre><code> PointID geometry 0 204403876 POINT (-101.66700 21.11670) 1 204462769 ...
python|matplotlib|heatmap|geopandas
0
4,274
61,056,779
Serialize custom dynamic layer in keras tensorflow
<p>I am rather new to tensorflow as well as Python (transfering from R). Currently I am working on a recommendation system in python using keras and tensorflow. The data is "unary", so I only know if someone clicked on something or if he didn't. </p> <p>The core model is build with the functional API and is a basic wi...
<p>I managed to get around the Issue by using tf.functions instead of dynamic=True. I did not however manage to save a dynamic layer in Tensorflow. Maybe that helps someone.</p>
python|tensorflow2.0|keras-layer|tf.keras
0
4,275
60,931,377
Efficiently select elements from an (x,y) field with a 2D mask in Python
<p>I have a large field of 2D-position data, given as two arrays <code>x</code> and <code>y</code>, where <code>len(x) == len(y)</code>. I would like to return the array of indices <code>idx_masked</code> at which <code>(x[idx_masked], y[idx_masked])</code> is masked by an N x N <code>int</code> array called <code>mas...
<p>Given that <code>mask</code> overlays your field with identically-sized bins, you do not need to define the bins explicitly. <code>*_bin_idx</code> can be determined at each location from a simple floor division, since you know that each bin is <code>1 / N</code> in size. I would recommend using <code>1 - 0</code> f...
python|arrays|numpy
2
4,276
71,650,564
Pandas DataFrame styler - How to style pandas dataframe as excel table?
<p><a href="https://i.stack.imgur.com/sT4sK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sT4sK.png" alt="enter image description here" /></a></p> <p>How to style the pandas dataframe as an excel table (alternate row colour)?</p> <p>Sample style:</p> <p><a href="https://i.stack.imgur.com/4qCoM.png"...
<p>If your final goal is to save <code>to_excel</code>, the only way to retain the styling after export is using the <code>apply</code>-based methods:</p> <ul> <li><a href="https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.apply.html" rel="noreferrer"><code>df.style.apply</code></a> / <a href=...
python|pandas|dataframe|pandas-styles
6
4,277
71,549,682
Transform dictionary list into python dataframe
<p>I have a file with several dictionaries and I want to turn it into a pandas dataframe, but I can't. When I try to get the first value to be in a column, like &quot;Fuel station 1&quot; and everything else is in a second column all together.</p> <pre><code>{'Fuel station 1': {'00404850000317': {'01-01-2019': {'DataDa...
<p>Well your data is nested on multiple levels. So first of all you are going to have to transform it into a format that pandas can handle. One way would be a records format (list of dicts), where each of the keys which belong to multiple entries are their own fields:</p> <pre><code>import pandas # slightly fixed your...
python|pandas|dataframe|dictionary
2
4,278
71,640,786
Dask to_parquet throws exception "No such file or directory"
<p>The following Dask code attempts to store a dataframe in parquet, read it again, add a column, and store again the dataframe with the column added.</p> <p>This is the code:</p> <pre><code>import pandas as pd import dask.dataframe as dd pdf = pd.DataFrame({ 'height': [6.21, 5.12, 5.85], 'weight': [150, 126, ...
<p>This works, use a different file name when you do a <code>to_parquet</code> and then delete the old parquet directory:</p> <pre><code>ddf = dd.from_pandas(pdf, npartitions=3) ddf.to_parquet('C:\\temp\\OLD_FILE_NAME', engine='pyarrow', overwrite=True) ddf2 = dd.read_parquet('C:\\temp\\OLD_FILE_NAME') ddf2['new_colu...
python|pandas|dask|dask-distributed
1
4,279
69,946,709
Filling a new column with values from a different column
<p>Supposing I have a dataframe like so : <a href="https://i.stack.imgur.com/rvi0P.png" rel="nofollow noreferrer">dataframe</a></p> <p>If I have to make a new column, which has the values from column 3 like so 4 N/A -1.135632 -1.044236 1.071804 0.271860 -1.087401 0.524988 -1.039268 0.844885 -1.469388 -0.968914</p> <p>i...
<p><code>df['column_4'] = df['column_3'].shift(1)</code></p>
python|pandas
1
4,280
69,980,921
.isin() function is returning an empty set when filtering an object column in DataFrame
<p>Reading and appending excel files to create DataFrame:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import os folder = r'C:\mypathtodocuments' files = os.listdir(folder) df = pd.DataFrame() for file in files: if file.endswith('.xlsx'): df = df.append(pd.read_excel(os.path.jo...
<p>Try this:</p> <pre class="lang-py prettyprint-override"><code>df1[&quot;CITY_AD&quot;] = df1[&quot;CITY_AD&quot;].str.strip() df1[df1[&quot;CITY_AD&quot;].isin([&quot;HOUSTON&quot;,&quot;CONROE&quot;])] </code></pre>
python|pandas|dataframe|isin
1
4,281
43,243,319
Is it possible to keep reference link between list and numpy array
<p>If I create a list in python, and assign a different list to it, changes of the first list are reflected in the second list:</p> <pre><code>a = [1, 2, 3] b = a a[0] = 0 print(b) &gt;&gt;&gt; [0, 2, 3] </code></pre> <p>Is it possible to achieve this behavior when creating a numpy array from a list? What I want:</p>...
<p>Fundamentally the issue is that Python lists <em>are not really arrays</em>. OK, CPython lists are ArrayLists, but they are arrays of Py_Object pointers, so they can hold heterogenous data. See <a href="http://www.laurentluce.com/posts/python-list-implementation/" rel="nofollow noreferrer">here</a> for an excellent ...
python|arrays|numpy
3
4,282
72,450,166
Pandas Regex: Read specific columns only from csv with regex patterns
<p>Given a large CSV file(large enough to exceed RAM), I want to read only specific columns following some patterns. The columns can be any of the following: <code>S_0, S_1, ...D_1, D_2</code> etc. For example, a chunk from the data frame looks like this:</p> <p><a href="https://i.stack.imgur.com/fW1es.png" rel="nofoll...
<p>You can first read few rows and try <code>DataFrame.filter</code> to get possible columns</p> <pre class="lang-py prettyprint-override"><code>cols = pd.readcsv('path', nrows=10).filter(regex='S_\d*').columns df = pd.readcsv('path', usecols=cols) </code></pre>
python|regex|pandas|dataframe
2
4,283
72,268,400
How to proceed with calculations on dataframe
<p>I dont know how to proceed with a calculation on this database.</p> <p>Database example:</p> <pre><code>Indicator Market Sales Costs Volume Real Internal 30512 -16577 12469 Real External 23 -15 8 Real Other 65 -38 25 ... ... ... ... ... ......
<p>This works</p> <pre><code># aggregate Costs and Volumes by Indicator aggregate = df.groupby('Indicator')[['Costs', 'Volume']].sum() # plug the values into the cost effect formula cost_effect = (aggregate.loc['Real', 'Costs'] / aggregate.loc['Real', 'Volume'] - aggregate.loc['Budget', 'Costs'] / aggregate.loc['Budget...
python|pandas|dataframe|formula
1
4,284
72,287,885
Concatenate two List in a 2D Array in Python with Numpy
<p>So, i have 2 list that i want to concatenate with numpy. For now, i'm tring to do something like this :</p> <p><code>LeGraphiqueMatLab = np.array([LesDatesMatLab, LeGraphique], dtype=np.float64)</code></p> <p>But it gives me an error saying : &quot;ValueError: setting an array element with a sequence. The requested ...
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html" rel="nofollow noreferrer">np.concatenate</a> like that:</p> <pre><code>a = [1, 2] b = [5, 6] np.concatenate((a, b)) #output array([1, 2, 5, 6]) </code></pre>
python|arrays|numpy
0
4,285
72,280,810
I am getting "Failed precondition" error message
<p>I am attempting to run a GoogLeNet code, but when I run the following via the terminal:</p> <pre><code>python.exe googlenet_cifar10.py --model output/minigooglenet_cifar10.hdf5 --output output </code></pre> <p>I am new to python, so I attempted to research it but having issues finding a solution for it. This is out ...
<p>I fixed the issue. The solution was: replacing <strong>[&quot;acc&quot;]</strong> with <strong>[&quot;accuracy&quot;]</strong> everywhere.</p> <p>In my case, I was unable to plot the parameters of the history of my training. I had to replace</p> <pre><code>plt.plot(N, self.H[&quot;acc&quot;], label = &quot;train_acc...
python|tensorflow|deep-learning|conv-neural-network
0
4,286
72,194,578
How to merge two different versions same dataframe in python pandas?
<p>I have the two different versions of same data frame. In fact, they were two different excels with the same columns updated by two different persons. They may have their own entries as well as the same data. And it looks like this.</p> <pre><code>df1 df2 A B C A B ...
<p>You can mutually patch the data frames both ways, stack them, and then eliminate duplicates:</p> <pre><code>pd.concat([df1.fillna(df2), df2.fillna(df1)])\ # Patching and Stacking .drop_duplicates(subset=['A']) # Dropping dups # A B C #0 prod1 cat1 type1 #1 prod2 cat2 type2 #2 prod3 cat4 typ...
python|pandas|dataframe
0
4,287
45,553,038
How to compile custom ops in tensorflow without having to dynamically import them in python?
<p>I checked through tensorflow documentation and they seem to only give information about compiling a custom op through a bazel rule:</p> <pre><code>load("//tensorflow:tensorflow.bzl", "tf_custom_op_library") tf_custom_op_library( name = "zero_out.so", srcs = ["zero_out.cc"], ) </code></pre> <p>Once bazel b...
<p>There is no officially supported extension point to pull in your own ops other than dynamically loading them.</p> <p>If you build tensorflow from source and are willing to hack it it's not hard to pretend your ops are core ops, but it's not supported.</p>
python|tensorflow|bazel
0
4,288
45,428,326
Pandas resample on OHLC data from 1min to 1H
<p>I use OHLC re-sampling of 1min time series data in Pandas, the 15min will work perfectly, for example on the following dataframe:</p> <pre><code>ohlc_dict = {'Open':'first', 'High':'max', 'Low':'min', 'Close': 'last'} df.resample('15Min').apply(ohlc_dict).dropna(how='any').loc['2011-02-01'] Date Time O...
<p>I had the same issue and could'nt find help online. So i wrote this script to convert 1 min OHLC data into 1 hour.</p> <p>This assumes market timings 9:15am to 3:30pm. If market timings are different simply edit the start_time and end_time to suit your needs.</p> <p>I havent put any additional checks in case trading...
pandas|dataframe|resampling
2
4,289
45,564,922
pandas how to groupby a period time and then get back a df after filtration inside the group?
<p>Basically, now I have a set of data from some routers(AP). The routers would probe user's devices every 3 seconds and give us user's MAC number(tag_mac). </p> <p>In order to clean those data(since at a period of time, different APs would give us back same tag_macs if the user is near other aps ), I just need the AP...
<p>I am assuming <code>df</code> as the DataFrame</p> <pre><code>#this makes sure that the 'date' column is in the required format df['time'] = pd.to_datetime(df['time'] , format='%Y-%m-%d %H:%M:%S') new_df = pd.DataFrame(columns=['ap_mac','tag_mac','rssi','to','from']) #start date - first date in the dataframe 'df...
python|pandas|dataframe|pandas-groupby
1
4,290
62,699,627
TypeError: Parameter value is not iterable or distribution
<p>I am new to Python and wanted to implement a simple Matrix Factorization Classifier.</p> <p>As I read in another post, there are some possibilities which one can use and I chose <code>sklearn decomposition.NMF</code>: <a href="https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.NMF.html" rel="nof...
<p>For <strong>n_estimators</strong>, Try passing a list of variable , I think it will work !</p> <p>self.clf = ensemble.RandomForestClassifier()<br /> self.random_parameters = [ {&quot;n_estimators&quot;: <strong>[20,50,100,200]</strong>, &quot;criterion&quot;: [&quot;gini&quot;], &quot;max_depth&quot;: stats.randint(...
python|scikit-learn|sklearn-pandas|matrix-factorization
0
4,291
54,255,230
Status of final rank in pandas
<p>I am working on the ranking of domestic competition of soccer, I have the following dataframe.</p> <pre><code>df = pd.DataFrame() df ['Season'] = ['1314','1314','1314','1314','1314','1314','1314','1314','1314','1415','1415','1415','1415','1415','1415','1415','1415','1415'] df ['Team'] = ['A','B','C','A','B','C','A'...
<p>IIUC you need something like below:</p> <pre><code>df1 = df.groupby(['Season','Team'])['Position'].apply(lambda x : np.select([(x.iloc[-1]==1),(x.iloc[-1]==2),(x.iloc[-1]==3)],['Champion','Second','Third'])).reset_index().rename(columns={'Position':'Status'}) print(df.merge(df1,on=['Team','Season'])) Season Te...
python|pandas
2
4,292
54,387,512
cv2 convert Range and copyTo functions of c++ to python
<p>I'm writing a python video stabilizer and in some part of the code i need to copy 2 images into a canvas.</p> <p>I tried to convert this c++ code to python but i wasn't able.</p> <pre><code>Mat cur2; warpAffine(cur, cur2, T, cur.size()); cur2 = cur2(Range(vert_border, cur2.rows-vert_border), Range(HORIZONTAL_BO...
<p>cv::Mat are actually numpy arrays in python. And in this case, you should use numpy functions and not OpenCV ones.</p> <p>For the copyTo as clone, use copy() as in:</p> <pre><code>a = np.zeros((10,10,3), dtype=np.uint8) b = a.copy() </code></pre> <p>For ranges, in numpy is easier... just use:</p> <pre><code>a[y1...
python|c++|numpy|opencv|cv2
2
4,293
54,437,652
How to create a Keras face classifier between myself and others with a restrictive data set?
<p>For the past 2 months I've been trying to create a classification model that can distinguish between myself and other people with Keras. I started from the dogs vs cats classifier and substituted the data set. Since then I have tweaked the network and the data set with some success. Also I have tried to augment my d...
<p>Given the amount of data you have, a better approach would be to use transfer learning instead of training from scratch. You can start with one of the pre-trained models for ImageNet like Resnet or Inception. But I suspect models trained on large face dataset may perform better. You can check the facenet implementat...
python|tensorflow|machine-learning|keras|classification
1
4,294
73,531,628
Apply numpy broadcast_to on each vector in an array
<p>I want to apply something like this:</p> <pre><code>a = np.array([1,2,3]) np.broadcast_to(a, (3,3)) array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) </code></pre> <p>On each vector in a multi-vector array:</p> <pre><code>a = np.array([[1,2,3], [4,5,6]]) np.broadcast_to(a, (2,3,3)) ValueError: operands could ...
<p>One way is to use list-comprehension and broadcast each of the inner array:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; np.array([np.broadcast_to(i, (3,3)) for i in a]) array([[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[4, 5, 6], [4, 5, 6], [4, 5, 6]]]) </code></...
python|numpy|array-broadcasting
3
4,295
71,184,758
Using multiprocessing to speed up filling of a numpy array
<p>I am trying to solve a problem that involves minimizing a certain function. The function contains a numpy array whose elements are filled by calling a function. The array generation is taking a huge amount of time, and I mean that. The array that I'm generating is defined below</p> <pre><code>def cov_p(Phi, l_mat, s...
<p>You can easily parallelize the outermost loop using <code>Pool</code> of multiprocessing. The idea is to split the <code>ans</code> array in the last dimension and merge it once each part has been computed. Note that the <code>tstep</code> variable needs to be sent to processes. Here is the resulting code containing...
python|numpy|optimization|scipy|multiprocessing
0
4,296
60,391,111
Pandas Series Calculation
<p>My column (faq_helpful) have values <strong>either</strong> 0,1 or blanks. If it is blank, i wont bother about it. I want to find how many 0 and 1 are there but apparently, its returning the same value for both which is wrong. </p> <pre><code>for question, question_df in df_raw.groupby(['faq_question']): ...
<p>Solution based on your code:</p> <pre><code>count = [] for question, question_df in df_raw.groupby(['faq_question']): count.append(len(question_df['faq_question'])) print(count) [6, 9] # numbers based on my example total = sum(count) print(total) 15 </code></pre> <p>Pandas has an in-built function to count v...
pandas|pandas-groupby|series
0
4,297
60,448,067
Can't import gpu version of tensorflow
<p>I can't use tensorflow because I get this error message when I try to import tensorflow:</p> <pre><code>2020-02-28 09:31:24.742077: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_100.dll'; dlerror: cudart64_100.dll not found Traceback (most recent call last)...
<p>At this point I would simply completely remove (e.g. de-install) both CUDA packages (10.0 and 10.1), as it is probably not a good idea to have both at the same time. After de-installing, make sure you check all your folders so that nothing is left. </p> <p>Then, check whether or not your NVIDIA drivers are up to da...
python|tensorflow|nvidia
0
4,298
72,623,353
how to convert datetime.date to datetime.datetime?
<p>in below I got datetime.date and datetime.datetime class.</p> <pre><code> start=df.index[0] start_input_1=datetime.strptime(start_input[:10],'%Y-%m-%d') print(start_input[:10]) print(type(start)) print(type(start_input_1)) 2021-09-01 &lt;class 'datetime.date'&gt; &lt;class 'datetime.datetime'&gt; </code></pre...
<p>You can either check if dates are the same by taking date from the <code>datetime</code> object, or add default time (00:00:00) to the <code>date</code> object to make it <code>datetime</code>:</p> <pre class="lang-py prettyprint-override"><code>from datetime import datetime, date dt = datetime.fromisoformat(&quot;...
python|pandas
1
4,299
59,784,212
i need to solve this "ModuleNotFoundError: No module named 'tensorflow'"
<p>I have installed <code>tensorflow</code> using link and installed it from cmd in windows 10.</p> <p>But what is happening is when i run my program in <code>pycharm</code> it says the above error.</p> <p>And i even installed <code>tensorflow</code> in my <code>pycharm</code> also still it is the same thing**</p> <...
<p>Check which version of Python you are using vs the library installed in which location.</p> <p>Check </p> <p><code>import sys</code></p> <p><code>print(sys.path)</code></p> <p>It will be you <code>site-packages</code> folder. Usually the libraries will be there. </p> <p>Check the above in PyCharm and Command Pr...
python|tensorflow|keras
0