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
374,000
50,965,178
Converting a list of time stamps into integers
<p>I have a list of Timestamp objects:</p> <pre><code>`[Timestamp('2018-01-02 00:00:00'), Timestamp('2018-01-03 00:00:00'), Timestamp('2018-01-04 00:00:00'), Timestamp('2018-01-05 00:00:00'), Timestamp('2018-01-08 00:00:00'), Timestamp('2018-01-09 00:00:00'), Timestamp('2018-01-10 00:00:00'), Timestamp('...
<p>Pandas TimeStamp has a method <em>strftime</em> (string from time) to convert a TimeStamp object into a given format. The Format you want is '%Y%m%d'. To apply this to all elements in your list, you can use list comprehension to build a new list with the formatted values.</p> <p>If you want integers instead of stri...
python-3.x|pandas|datetime|timestamp|integer
0
374,001
50,676,296
scatter update tensor with index obtained using argmax
<p>I'm trying to update a tensor's max value with another value, like so:</p> <pre><code>actions = tf.argmax(output, axis=1) gen_targets = tf.scatter_nd_update(output, actions, q_value) </code></pre> <p>I'm getting an error: <code>AttributeError: 'Tensor' object has no attribute 'handle'</code> on <code>scatter_nd_up...
<p>You are trying to update the value of <code>output</code> which is of type <code>tf.placeholder</code>. Placeholders are immutable objects, you cannot update the value of the placeholder. The tensor you are trying to update should be of type of a variable, e.g. <a href="https://www.tensorflow.org/api_docs/python/tf/...
python|tensorflow|reinforcement-learning
2
374,002
50,970,156
join to dataframe with substrings and sorting
<p>I wish to appen some data from a dataframe to another. the problem is I need to build a key to be able to make map the values between the two dataframe. so I built an example, with df1 has a column "RAW". this column contains a string that needs to be split, first 3 characters from left and 3 from the right, then so...
<p>Change your <code>buildcodefromrow</code> function to the following:</p> <pre><code>def buildcodefromrow(mystring): return mystring[0:3] + mystring[4:] if mystring[0:3] &lt; mystring[4:] else mystring[4:] + mystring[0:3] </code></pre> <p>and the <code>BUILTCODE</code> row in df1 can be acheived using:</p> <...
python|pandas|merge|substring
0
374,003
51,018,104
How to group phone number with and without country code
<p>I am trying to detect phone number, my country code is <code>+62</code> but some phone manufacturer or operator use <code>0</code> and <code>+62</code>, after query and pivoting I get pivoted data. But, the pivoted data is out of context</p> <p>Here's the pivoted data</p> <pre><code>Id +623684682 03684682 +...
<p>I think need <code>replace</code> with aggregate <code>sum</code>:</p> <pre><code>df = df.groupby(lambda x: x.replace('+62','0'), axis=1).sum() </code></pre> <p>Or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>replace</code></a> colum...
python|pandas|dataframe
4
374,004
50,792,130
RNN classifier, how to show the weight to understand how the neraul network make the decision
<p>I am using a RNN to build a simple classifier to classify a paragraph of words into different catalogs. it has an embedding layer, followed by RNN and then a Dense layer show as below.</p> <p>It can predict correctly but besides the prediction, how can I know why the RNN got this prediction, for example, what is th...
<p><a href="https://github.com/keras-team/keras/issues/3088" rel="nofollow noreferrer">This post on GitHub</a> proposes a way to see the parameters' name while printing them:</p> <pre><code>for e in zip(model.layers[0].trainable_weights, model.layers[0].get_weights()): print('Param %s:\n%s' % (e[0],e[1])) </code></...
python|tensorflow|recurrent-neural-network
1
374,005
50,905,236
Grouping and calculating data
<p>I'm almost a newbie with Pandas, so I'd like to know if a certain operation is possible before start coding around it.</p> <p>I have a set of data of employees' working hours, like this (These are oversemplified, the real stuff is thousand and thousand of records)</p> <pre><code> ID Name Date Hou...
<p>Convert the hours to <code>datetime</code>, <code>groupby</code> the In's and Outs' and take the difference. Later sum the difference grouping by <code>'ID'</code> and <code>'Date'</code> i.e </p> <pre><code>df['Hour'] = pd.to_datetime(df['Hour']) df['diff'] = df.groupby((df['Type'] == 'In').cumsum())['Hour'].diff...
python|pandas|dataframe|pandas-groupby
4
374,006
50,812,838
Error in pip install torchvision on Windows 10
<p>on <a href="https://pytorch.org/" rel="noreferrer">pytorch</a>, installing on Windows 10, conda and Cuda 9.0.</p> <p>cmd did not complain when i ran <code>conda install pytorch cuda90 -c pytorch</code>, then when I ran <code>pip3 install torchvision</code> I get this error message.</p> <pre><code>Requirement alrea...
<p>I tried to use:</p> <pre><code>pip install torchvision </code></pre> <p>but it didn't work for me. So, I googled this problem more carefully and found another solution:</p> <pre><code>pip install --no-deps torchvision </code></pre> <p>I hope it will be helpful.</p> <p>Update: I want to add: "--no-deps" means th...
python|python-3.x|pytorch
9
374,007
50,782,385
Sort IP's as sets of numerical octets (__not__ lexicographically)
<p>I'm looking to sort entries in each row/cell of a specific column 'D' via IP address in ascending order. The entries are stored on a new line and have the associated protocol and port listed at the end of the IP, which I am not concerned about sorting just the 4 octets of the IP address. I feel this needs some sort ...
<p>assuming you have your original DF, <strong>before</strong> grouping:</p> <pre><code>In [70]: df Out[70]: ID A B C D 0 1.0 x x x 10.0.0.50/TCP/50 1 1.0 x x x 192.168.1.90/TCP/51 2 1.0 x x x server1/TCP/80 3 1.0 x x x 10.0.0.9/TCP/78 4 2.0 y y y 19...
python|pandas|csv|dataframe|pandas-groupby
1
374,008
50,847,374
Convert multiple columns to string in pandas dataframe
<p>I have a pandas data frame with different data types. I want to convert more than one column in the data frame to string type. I have individually done for each column but want to know if there is an efficient way?</p> <p>So at present I am doing something like this:</p> <pre><code>repair['SCENARIO']=repair['SCENA...
<p>To convert <a href="https://stackoverflow.com/q/15891038/6060083">multiple</a> columns to string, include a <em>list</em> of columns to your above-mentioned command:</p> <pre><code>df[['one', 'two', 'three']] = df[['one', 'two', 'three']].astype(str) # add as many column names as you like. </code></pre> <p>That me...
python|python-2.7|pandas
62
374,009
50,864,087
Accessing MxM numpy array that is first index of a tuple
<p>As stated in the title, I have a list of tuples that look like (numpy_array,id) where the numpy array is m x m. I need to access each element of the numpy array (i.e. all m^2 of them) but am having a tough time doing this without unpacking the tuple.</p> <p>I would rather not unpack the tuple because of how much d...
<p>If you just want to access directly to a element in a specific position of the ndimensional numpy array, you can just use a <b>ndimensional indexing</b>. <br>For example:<br> I want to access the element in the third column of the first row of a 3x3 array <em>c</em>, then I will do <em>c[0,2]</em>.</p> <pre><code>...
python|numpy|indexing|tuples
1
374,010
50,950,045
Create list from pandas dataframe for distinct values in a column
<p>From the following Pandas dataframe. </p> <pre><code>df = pd.DataFrame({'Id': [102,102,102,303,303,944,944,944,944],'A':[1.2,1.2,1.2,0.8,0.8,2.0,2.0,2.0,2.0],'B':[1.8,1.8,1.8,1.0,1.0,2.2,2.2,2.2,2.2], 'A_scored_time':[10,25,0,33,0,40,0,90,0],'B_scored_time':[0,0,30,0,41,0,75,0,95]}) </code></pre> ...
<p>To answer the question in your title use:</p> <pre><code>df.groupby('Id')[['A_scored_time','B_scored_time']]\ .agg(lambda x: x[x != 0].tolist())\ .reset_index() </code></pre> <p>Output:</p> <pre><code> Id A_scored_time B_scored_time 0 102 [10, 25] [30] 1 303 [33] [41] 2 9...
python|pandas|dataframe
4
374,011
51,087,335
Tensorflow Performing Feature Extraction (on the whole Dataset) is very time consuming
<p>I want to perform a Feature Extraction on the TensorFlow's standard MNIST dataset, (before training my Neural Network) which is a simple tf.matmul() but it takes about 3 hours to be done. Any tuning tricks or Ideas to reduce the time ? The code looks like below</p> <pre><code>def apply_feature_extraction(data, feat...
<p>You should not create any operations while executing the graph!</p> <p>Each time when you call <code>apply_feature_extraction</code> you put a new operation <code>tf.add(tf.matmul(...)</code> to your graph. As a result your graph gets bloated.</p> <p>First, create a fully defined graph that contains all variables ...
python|tensorflow
1
374,012
50,723,226
able to read one file but failed to read multiple json files from a folder into a padas dataframe
<p>I have a folder that has many jason files, say folder is "myfolder" and files are: data1.json, data2.json, data3.json.... and so forth.</p> <p>There are total 6 key names and these jason files all have same key names, say: col1, col2, col3, col4, col5, and col6 (i.e. the columns of df when these are converted into ...
<p>You can make a list of dataframes via a <code>for</code> loop. Then use <code>pd.concat</code> to combine in a final step.</p> <p>It's not advisable to continually append to an existing dataframe, as <code>pd.DataFrame.append</code> is expensive relative to <code>list.append</code> and a single <code>pd.concat</cod...
python|json|pandas|dataframe
0
374,013
50,950,614
Converting column into multi index column
<p>I am new to python, As a result of groupby I got a data frame which looks like this. </p> <pre><code>temp = pd.DataFrame({'Year' : [2018,2017], 'week' : [200, 100], 'mtd' : [100, 200], 'qtd' : [300, 345], 'ytd': [400, 500]}) temp.set_index('Year', inplace ...
<p>Use, <code>stack</code>, <code>to_frame</code> and <code>T</code>:</p> <pre><code>temp.stack().to_frame().T </code></pre> <p>Output:</p> <pre><code>Year 2018 2017 week mtd qtd ytd week mtd qtd ytd 0 200 100 300 400 100 200 345 500 </code></pre>
python-3.x|pandas|dataframe
6
374,014
50,929,426
How can I multiply each column of a Tensor by all columns of an another using Tensorflow?
<p>Let <code>a</code> and <code>b</code> be tensors defined as:</p> <pre><code>a = tf.constant([[1, 4], [2, 5], [3, 6]], tf.float32) b = tf.constant([[10, 40], [20, 50], [30, 60]], tf.float32) </code></pre> <p>I am looking for a way to multiply each...
<p>Do I miss something? Why not just</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf a = tf.constant([[1, 4], [2, 5], [3, 6]], tf.float32) b = tf.constant([[10, 40], [20, 50], [30, 60]], tf.float32) h_b, w_a = a.shape.as...
tensorflow|linear-algebra|matrix-multiplication
3
374,015
50,779,261
Adding metadata to a Keras LSTM
<p>I looked at several answers, and was not able to see a clear solution to what I'm trying to do.</p> <p>I have an LSTM for binary text classification that takes the top 40k words in a corpus, then operates on the first 50 tokens. Prepared like this:</p> <pre><code>max_words = 40000 max_review_length = 50 embedding_...
<p>It would be wise to now switch to the <a href="https://keras.io/getting-started/functional-api-guide/" rel="nofollow noreferrer">functional API</a> and create a multi-input network which will take the text as well the meta data:</p> <pre><code>text_in = Input(shape=(max_review_length,)) meta_in = Input(shape=(1,)) ...
python|tensorflow|keras
4
374,016
50,938,182
Combining Excel worksheets over multiple loops
<p>I've got a number of Excel workbooks, each with multiple worksheets, that I'd like to combine. </p> <p>I've set up two sets of loops (one while, one for) to read in rows for each sheet in a given workbook and then do the same for all workbooks. </p> <p>I tried to do it on a subset of these, and it appears to wor...
<p>As the error says, <code>pd.concat()</code> requires an iterable, like a list: <code>pd.concat([df1, df2])</code> will concatenate <code>df1</code> and <code>df2</code> along the default axis of 0, which means <code>df2</code> is appended to the bottom of <code>df1</code>.</p> <p>Two issues need fixing:</p> <ol> <...
python|pandas
2
374,017
51,039,857
Pandas count values greater than current row in the last n rows
<p>How to get count of values greater than current row in the last n rows?</p> <p>Imagine we have a dataframe as following:</p> <pre><code> col_a 0 8.4 1 11.3 2 7.2 3 6.5 4 4.5 5 8.9 </code></pre> <p>I am trying to get a table such as following where n=3.</p> <pre><code> col_a col_b 0 8...
<p>In pandas is best dont loop because slow, here is better use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html" rel="noreferrer"><code>rolling</code></a> with custom function:</p> <pre><code>n = 3 df['new'] = (df['col_a'].rolling(n+1, min_periods=1) ...
python|pandas|dataframe
7
374,018
50,681,501
Tensorflow Graph, Session management for cross-validation
<p>What is the proper way of managing (initialize, close, reset) sessions and graphs when implementing cross-validation in Tensorflow?</p> <p>Should I reset the session and graph for each fold, or is it better/possible to keep a single session throughout the entire process? One advantage of doing the latter is that re...
<p>I prefer to create a session and use it as long as I require, this is much better in terms of speed and performance, and later if we close the session, then we can claim the resources back. Moreover, if we use allow_growth config to True, then other programs will also be able to use the resources.</p>
session|tensorflow|graph|cross-validation
0
374,019
51,040,682
Split integer into digits using numpy
<p>I have a question. The question is asked before but as far as i can see never using numpy. I want split a value in the different digits. do somthing and return back into a number. based on the questions below i can do what i want. But i prefere to do it all in numpy. I expect it is more efficient because i'm not cha...
<p>Pretty simple:</p> <ol> <li>Divide your number by 1, 10, 100, 1000, ... rounding down</li> <li>Modulo the result by 10</li> </ol> <p>which yields</p> <pre><code>l // 10 ** np.arange(10)[:, None] % 10 </code></pre> <p>Or if you want a solution that works for</p> <ul> <li>any base</li> <li>any number of digits an...
python|python-3.x|numpy
2
374,020
51,053,155
matplot pandas plotting multiple y values on the same column
<p>Trying to plot using matplot but lines based on the value of a non x , y column.</p> <p>For example this is my DF:</p> <pre><code>code reqs value AGB 253319 57010.16528 ABC 242292 35660.58176 DCC 240440 36587.45336 CHB 172441 57825.83052 DEF 148357 34129.71166 </code></pre> <p>Which yields this plot d...
<p>So I worked out how to do exactly ^ if anyone is curious:</p> <pre><code>plt_df = df fig, ax = plt.subplots() for key,grp in plt_df.groupby(['code']): ax = grp.plot(ax=ax, kind ='line',x='reqs',y='value',label=key,figsize=(20,4),title = "someTitle") plt.show() </code></pre>
pandas|matplotlib|plot|jupyter
0
374,021
50,731,887
Pandas GroupBy two columns, calculate the total based on one column but calculate the percentage based on the total for the agregator
<p>I have derived my desired groupings but would like to calculate a percentage column based on the totals per month i.e. regardless of the string in originating_system_id</p> <pre><code>d = [('Total_RFQ_For_Month', 'size')] df_RFQ_Channel = df.groupby(['Year_Month','originating_system_id'])['state'].agg(d) #df_RFQ_Ch...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="noreferrer"><code>transform</code></a> for <code>Series</code> with same size as original <code>DataFrame</code>, so is possible divide by <code>Total_RFQ_For_Month</code> column:</p> <pre><code>#crea...
python|pandas|dataframe|pandas-groupby
7
374,022
51,012,775
Slicing based on a range of column in a multiindex column dataframe
<p>I am creating my dataframe by doing the following:</p> <pre><code>months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] monthyAmounts = [ "actual", "budgeted", "difference" ] income = [] names = [] for x in range( incomeIndex + 1, expensesIndex ): amounts = [ ...
<p>If need select by <code>MultiIndex</code>, need boolean masks:</p> <pre><code>index = pd.Index( [1,2,3,4], name = 'category' ) budgetMonths = pd.date_range( "January, 2018", periods = 12, freq = 'BM' ) months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'No...
python|pandas|dataframe|slice|multi-index
1
374,023
51,084,768
ValueError: Input 0 of node incompatible with expected float_ref.**
<p>I'm getting below exception while trying to import my optimized frozen graph.</p> <pre><code># read pb into graph_def with tf.gfile.GFile(pb_file, "rb") as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) # import graph_def with tf.Graph().as_default() as graph: tf.import_graph_def(grap...
<p>Make sure your <code>pb_file</code> is in the right format (something like <a href="https://github.com/timctho/convolutional-pose-machines-tensorflow/blob/master/run_freeze_graph.py" rel="nofollow noreferrer">this</a>) and also try to have some value in the 'name' parameter of <code>import_graph_def()</code> to try ...
python|python-3.x|tensorflow|pycharm|tensorflow-lite
2
374,024
50,839,884
Filtering pandas dataframe by introspecting each element of a row
<p>I have a dataframe that contains an object in a column. </p> <p>for example:</p> <pre><code>df['id_original'].iloc[0].Class Out[20]: u'Classtype1' df['id_original'].iloc[1].Class Out[20]: u'Classtype2' </code></pre> <p>How can I filter the dataframe that I only get the rows where the row 'id_original' contains a...
<p>You can use:</p> <pre><code>df.loc[df['id_original'].apply(lambda x: x.Class in allowed_class_type_list)] </code></pre> <p>Consider below minified example:</p> <pre><code>class Example: def __init__(self, class_): self.Class = class_ ex1 = Example('class1') ex2 = Example('class2') ex3 = Example('clas...
python|pandas|filtering|series
3
374,025
50,978,117
How to plot loss curve in Tensorflow without using Tensorboard?
<p>Hey I am new to Tensorflow. I used DNN to train the model and I would like to plot the loss curve. However, I do not want to use Tensorboard since I am really not familiar with that. I wonder whether it is possible to extract the loss info info in each step and plot it use other plotting package or scikit-learn?</p...
<p>Change your <code>sess.run(training_function, feed_dict)</code> statement so it includes your loss function as well. Then use something like Matplotlib to plot the data.</p> <pre><code>_, loss = sess.run((training_function, loss_function), feed_dict) loss_list.append(loss) import matplotlib.pyplot as plt plt.plot(l...
python-3.x|tensorflow|machine-learning
4
374,026
50,718,146
Creating a dataframe from values extracted from a json column in Pandas
<p>I loaded a .csv file into a df, and one of the row of a columns contains a list of dictionary like below. </p> <pre><code>data = [{"character": "Jake Sully", "gender": 2,}, {"character": "Neytiri", "gender": 1}, {"character": "Dr. Grace Augustine","ge...
<p><code>pd.DataFrame</code> accepts a list of dictionaries directly:</p> <pre><code>data = [{"character": "Jake Sully", "gender": 2,}, {"character": "Neytiri", "gender": 1}, {"character": "Dr. Grace Augustine","gender": 1}, {"character": "Col. Quaritch", "gender": 2}] df = pd.DataFrame(data) ...
python|pandas
2
374,027
51,023,386
Tensorboard for Windows for Tensorflowsharp
<p>Is it posssible to run a standalone version of Tensorboard on Windows WITHOUT installing tensorflow and python.</p> <p>I want to look at output from Tensorflowsharp only.</p>
<p>There is a standalone version. You can find it <a href="https://github.com/dmlc/tensorboard" rel="nofollow noreferrer">here</a>.</p>
tensorflow|tensorboard|tensorflowsharp
0
374,028
50,798,172
Pytorch: how to make the trainloader use a specific amount of images?
<p>Assume I am using the following calls:</p> <pre><code>trainset = torchvision.datasets.ImageFolder(root="imgs/", transform=transform) trainloader = torch.utils.data.DataLoader(trainset,batch_size=4,suffle=True,num_workers=1) </code></pre> <p>As far as I can tell, this defines the trainset as consisting of all the i...
<p>You can wrap the class <a href="https://github.com/pytorch/vision/blob/3f6c23c0d3056d66a14635bacc7e4b8a8a067069/torchvision/datasets/folder.py#L53" rel="nofollow noreferrer"><code>DatasetFolder</code></a> (or ImageFolder) in another class to limit the dataset:</p> <pre><code>class LimitDataset(data.Dataset): de...
pytorch
4
374,029
50,965,844
Using Boolean Logic to clean DF in pandas
<p>df </p> <pre><code>shape square shape circle animal NaN NaN dog NaN cat NaN fish color red color blue </code></pre> <p>desired_df</p> <pre><code>shape square shape circle animal dog animal cat animal fish color red color blue </code></pre> <p>I have a df contains information that needs to be...
<p>If your identified pattern is a heuristic which, nevertheless, I struggle to follow, you can instead try <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.ffill.html" rel="nofollow noreferrer"><code>pd.Series.ffill</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/gener...
python|pandas|boolean|series
3
374,030
50,891,974
Concatenating dataframes in loop
<p>I am struggling with something simple and it drives me crazy. </p> <p>Why concatenating like below doesn't replace df1 with df1 + additional column??</p> <pre><code>df1 = pd.DataFrame({'A':[1, 2, 3], 'B':[4, 5, 6]}) df2 = pd.DataFrame({'A':[1, 2, 3], 'B':[4, 5, 6]}) df3 = pd.DataFrame({'C':[999, 999, 999]}) for t...
<p>You have two DataFrames. These variables are referenced by two variable names "df1" and "df2". Now, you loop over these dataFrames in a loop under the alias "table". Inside the loop, "table" is reassigned to the result of <code>concat</code>. Since <code>concat</code> is not inplace, <em>none</em> of the original Da...
python|pandas|dataframe|concatenation
1
374,031
51,083,770
TensorflowJS: Training multiple models simultaneously (for performance)
<p>In my project, I am training many small graphs. Seeing as how the work is being done on the GPU, and the GPU is running at a low 5%, would it make sense to train many graphs simultaneously for a performance boost? I'm just a bit concerned, as I know JS isn't really a thread-capable language.</p> <p>Are there any ...
<p>In theory when training on the GPU with Tensorflow.js, you've got a number of elements that all need balancing:</p> <h2>1: GPU usage</h2> <p>Of course, the amount that the GPU is being used matters - the ultimate goal is to max out the GPU to train as efficiently as possible in terms of time.</p> <p>If you're seein...
tensorflow.js
0
374,032
51,053,219
sampling from list of dicts
<p>I have data like the sample below. It's very large and I would like to sample first 10 items from it. It looks like a list of dicts, but if I try user_train[:5] I get an error. I can sample one item at a time like user_train[4] works. Any tips are greatly appreciated. </p> <p>code:</p> <pre><code>user_train[0]...
<p>If you wanted to find a way around it. You could go:</p> <p><code>sample = [user_train[x] for x in range(10)]</code></p> <p>This is called a list comprehension, unhashable type error is usually due to trying to convert a dict to a list.</p>
python|python-2.7|numpy-ndarray
1
374,033
51,064,456
Principal component analysis dimension reduction in python
<p>I have to implement my own PCA function function Y,V = PCA(data, M, whitening) that computes the first M principal components and transforms the data, so that y_n = U^T x_n. The function should further return V that explains the amount of variance that is explained by the transformation.</p> <p>I have to reduce the...
<h2>Here is a simple example <code>for the case</code> where the initial matrix A that contains the samples and features has <code>shape=[samples, features]</code></h2> <pre><code>from numpy import array from numpy import mean from numpy import cov from numpy.linalg import eig # define a matrix A = array([[1, 2], [3,...
python|numpy|machine-learning|scikit-learn|pca
0
374,034
50,774,747
Randomly remove 30% of values in numpy array
<p>I have a 2D numpy array which contains my values (some of them can be NaN). I want to remove the 30% of the non-NaN values and replace them with the mean of the array. How can I do so? What I tried so far:</p> <pre><code>def spar_removal(array, mean_value, sparseness): array1 = deepcopy(array) array2 = arra...
<p>There's likely a better way, but consider:</p> <pre><code>import numpy as np x = np.array([[1,2,3,4], [1,2,3,4], [np.NaN, np.NaN, np.NaN, np.NaN], [1,2,3,4]]) # Get a vector of 1-d indexed indexes of non NaN elements indices = np.where(np.isfinite(x).ravel())[0] # Shuffl...
python|arrays|numpy
5
374,035
50,744,565
How to handle non-determinism when training on a GPU?
<p>While tuning the hyperparameters to get my model to perform better, I noticed that the score I get (and hence the model that is created) is different every time I run the code despite fixing all the seeds for random operations. This problem does not happen if I run on CPU.</p> <p>I googled and found out that this i...
<p><strong>TL;DR</strong></p> <ul> <li>Non-determinism for <em>a priori</em> deterministic operations come from concurrent (multi-threaded) implementations.</li> <li>Despite constant progress on that front, TensorFlow does not currently guarantee determinism for all of its operations. After a quick search on the intern...
python|tensorflow|machine-learning|deep-learning
25
374,036
51,066,894
Improve performance of a for loop comparing pandas dataframe rows
<p>I'm facing a performance problem with Python/Pandas. I have a for loop comparing consequent rows in a Pandas DataFrame:</p> <pre><code>for i in range(1, N): if df.column_A.iloc[i] == df.column_A.iloc[i-1]: if df.column_B.iloc[i] == 'START' and df.column_B.iloc[i-1] == 'STOP': df.time.iloc[i]...
<p>I think you can use <code>shift</code> and a <code>mask</code>:</p> <pre><code>mask = ((df.column_A == df.column_A.shift()) &amp; (df.column_B == 'START') &amp; (df.column_B.shift() == 'STOP')) df.loc[mask, 'time'] -= df.time.shift().loc[mask] </code></pre> <p>The mask select the row where the value in 'c...
python|performance|pandas
4
374,037
50,704,445
Remove NoneType from BeautifulSoup
<p>I'm trying to remove the commas from the numbers I extracted with the following code:</p> <pre><code>with requests.Session() as s: url = 'https://www.zoopla.co.uk/for-sale/property/london/paddington/?q=Paddington%2C%20London&amp;results_sort=newest_listings&amp;search_source=home' r = s.get(url, headers=req...
<p>With <code>df['price'].replace(',','', inplace = True)</code> , you are replacing <code>inplace</code>, which does not return anything.</p> <p>You need:</p> <pre><code>df['price'] = df['price'].str.replace(',','') </code></pre> <p>Output:</p> <pre><code>0 NaN 1 1875000 2 4950000 3 500000 4 6...
python|pandas|beautifulsoup|nonetype
2
374,038
50,786,597
custom sort in python pandas dataframe needs better approach
<p>i have a dataframe like this</p> <pre><code>user = pd.DataFrame({'User':['101','101','101','102','102','101','101','102','102','102'],'Country':['India','Japan','India','Brazil','Japan','UK','Austria','Japan','Singapore','UK']}) </code></pre> <p>i want to apply custom sort in country and Japan needs to be in top f...
<p>Create a new key help sort by using <code>map</code></p> <pre><code>user.assign(New=user.Country.map({'Japan':1}).fillna(0)).sort_values(['User','New'], ascending=[True, False]).drop('New',1) Out[80]: Country User 1 Japan 101 0 India 101 2 India 101 5 UK 101 6 Austria 101 4 ...
python|python-2.7|pandas
2
374,039
50,694,066
Error during training using Tensorflow with our own data
<p>I am using <a href="https://www.tensorflow.org/" rel="nofollow noreferrer">Tensorflow</a> for training for developing the model to detect whether the message is spam or not. I am using <strong>Python</strong>.</p> <p>My training data size is 3000 rows and 3 columns, and the size of test data is 2700 rows and 3 colu...
<p>I think the problem is where you are generating your input data(batch_x). It seems that your input shape is <code>[batch_size,12]</code> that you are multiplying(matmul) your hidden layer( <code>hidden_layer1["weight"]</code>) of shape of [<code>3000,n_nodes_hl1</code>] causing the matrix mutliplication operation to...
python|pandas|tensorflow|nltk
0
374,040
51,078,625
How to ignore some input layer, while predicting, in a keras model trained with multiple input layers?
<p>I'm working with neural networks and I've implemented the following architecture using <code>keras</code> with <code>tensorflow</code> backend:</p> <p><a href="https://i.stack.imgur.com/P4wDh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P4wDh.png" alt="enter image description here"></a></p> <...
<blockquote> <p>How to ignore some input layer ?</p> </blockquote> <p>You <strong>can't</strong>. Keras cannot just ignore an input layer as the output depends on it.</p> <p>One solution to get nearly what you want is to define a custom label in your training data to be the null value. Your network will learn to <e...
python-3.x|tensorflow|keras|disabled-input
3
374,041
50,846,719
Cannot replace special characters in a Python pandas dataframe
<p>I'm working with Python 3.5 in Windows. I have a dataframe where a <code>'titles'</code> str type column contains titles of headlines, some of which have special characters such as <code>â</code>,<code>€</code>,<code>˜</code>. </p> <p>I am trying to replace these with a space <code>''</code> using <code>pandas.rep...
<p>We can only assume that you refer to non-ASCI as 'special' characters. </p> <p>To remove <em>all</em> non-ASCI characters in a pandas dataframe column, do the following:</p> <pre><code>df['clean_titles'] = df['titles'].str.replace(r'[^\x00-\x7f]', '') </code></pre> <p>Note that this is a scalable solution as it w...
python|regex|string|pandas|dataframe
4
374,042
50,741,335
Calculating sum of a combination of columns in pandas, row-wise, with output file with the name of said combination
<p>I am looking for a way of generating a csv file for a specific combination of data from columns in a dataframe.</p> <p>My data looks like this (except with 200 more rows)</p> <pre><code>+-------------------------------+-----+----------+---------------+--------------+--------------+--------------+--------------+---...
<p>Something like this?</p> <pre><code>def subset_to_csv(cols): df['Sum of percentage'] = your_data[list(cols)].sum(axis=1) df.to_csv(cols + '.csv') df = your_data[['Species', 'OGT']] for c in your_list_of_combinations: subset_to_csv(c) </code></pre> <p>Where <code>cols</code> is a string containing the...
python|pandas|dataframe|combinatorics
2
374,043
50,868,147
Use .filter within a function
<p>I'm trying to create a function that creates a pivot table, and I need to filter one column based on a string.</p> <pre><code>df = DataFrame({'Breed': ['Sheltie', 'Bernard', 'Husky', 'Husky', 'pig', 'Sheltie','Bernard'], 'Metric': ['One month walked', 'two month walked', 'three month walked', 'four mon...
<p>Assuming to want to find the sum of ages for each breed, which completion word in their metric. You can take the following approach.</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame({'Breed': ['Sheltie', 'Bernard', 'Husky', 'Husky', 'pig', 'Sheltie','Bernard'],'Metric': ['One month wal...
python|pandas
1
374,044
50,866,385
Efficient grouping into dict
<p>I have a list of tuples:</p> <pre><code>[('Player1', 'A', 1, 100), ('Player1', 'B', 15, 100), ('Player2', 'A', 7, 100), ('Player2', 'B', 65, 100), ('Global Total', None, 88, 100)] </code></pre> <p>Which I wish to convert to a dict in the following format:</p> <pre><code>{ 'Player1': { 'A': [1, 12....
<p>Everyone seems attracted to a dict-only solution, but why not try converting to <code>pandas</code>?</p> <pre><code>import pandas as pd # given tuple_list = [('Player1', 'A', 1, 100), ('Player1', 'B', 15, 100), ('Player2', 'A', 7, 100), ('Player2', 'B', 65, 100), ('Global Total', None, 88, 100)] # make a datafram...
python|pandas
2
374,045
50,678,866
how to save model filters in keras
<p>I am visualizing my cnn model filters (kernels) using code from <a href="https://github.com/julienr/ipynb_playground/blob/master/keras/convmnist/keras_cnn_mnist.ipynb" rel="nofollow noreferrer">here</a>, which is following:</p> <pre><code>from mpl_toolkits.axes_grid1 import make_axes_locatable def nice_imshow(ax, d...
<p>I had a similar issue trying to save figures in Keras with <code>plt.savefig</code>. It always resulted in blank images.</p> <p>I never really found out why it happened, if I recall correctly it only occurred when using multiprocessing, but I may be wrong.</p> <p>I solved it using a non-interactive backend, which ...
python|numpy|matplotlib|keras
1
374,046
50,777,871
Does TensorFlow use all of the hardware on the GPU?
<p>The <a href="https://images.nvidia.com/content/pdf/tesla/whitepaper/pascal-architecture-whitepaper.pdf" rel="nofollow noreferrer">NVidia GP100</a> has 30 TPC circuits and 240 "texture units". Do the TPCs and texture units get used by TensorFlow, or are these disposable bits of silicon for machine learning? </p> <p...
<p>None of those things are separate pieces of individual hardware that can be addressed separately in CUDA. Read this passage on page 10 of your document:</p> <blockquote> <p><strong>Each GPC inside GP100 has ten SMs</strong>. Each SM has 64 CUDA Cores and four texture units. <strong>With 60 SMs</strong>, GP100...
tensorflow|gpu|gpgpu
6
374,047
50,993,978
How to get Keras network to not output all 1s
<p>I have a bunch of images that look like this of someone playing a videogame (a simple game I created in Tkinter):</p> <p><a href="https://i.stack.imgur.com/8N4pe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8N4pe.png" alt="Ball falling in videogame; player&#39;s box is at the bottom"></a></p> ...
<p>Of course, a deeper model might give you a better accuracy, but considering the fact that your images are simple, a pretty simple (shallow) model with only one hidden layer should give a medium to high accuracy. So here are the modifications you need to make this happen:</p> <ol> <li><p>Make sure <code>X</code> and...
python|tensorflow|machine-learning|neural-network|keras
1
374,048
51,027,339
DataFrame - table in table from nested dictionary
<p>I use python 3.</p> <p>This is my data structure:</p> <pre><code>dictionary = { 'HexaPlex x50': { 'Vendor': 'Dell Inc.', 'BIOS Version': '12.72.9', 'Newest BIOS': '12.73.9', 'Against M &amp; S': 'Yes', 'W10 Support': 'Yes', 'Computers': { 'someName00...
<p>As already emphasized in the comments, pandas does not support "sub-dataframes". For the sake of KISS, I would recommend duplicating those rows (or to manage two separate tables... if really necessary).</p> <p>The answers in the question you referred to (<a href="https://stackoverflow.com/questions/39640936/parsing...
python|html|python-3.x|pandas
2
374,049
20,490,994
How to avoid rate-limiting 429 error in Twython
<p>I've created a function designed to run through a column of Twitter handles pandas dataframe, yet it always seems to hit rate-limiting error after just 14 calls.</p> <p>Here's the code.</p> <pre><code>def poll_twitter(dfr): followers = twitter.get_followers_ids(screen_name = dfr['handle']) time.sleep(5) ...
<p>Twitter GET followers/ids <a href="https://dev.twitter.com/docs/api/1.1/get/followers/ids" rel="nofollow">endpoint</a> in API 1.1 version has 15 requests/per window (15 mins) limit, i.e. about 60 requests per hour.</p> <p>Note also, that it also returns up to 5000 ids per request, so you have to issue more requests...
python|twitter|pandas|twython
3
374,050
20,862,068
Merging Pandas DataFrames with the same column name
<p>I have a dataset, lets say:</p> <pre><code>Column with duplicates value1 value2 1 5 0 1 0 9 </code></pre> <p>And what I want</p> <pre><code>Column with duplicates value1 value2 1 ...
<p>IIUC, you can use <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow"><code>groupby</code></a> and then aggregate:</p> <pre><code>&gt;&gt;&gt; df Column with duplicates value1 value2 0 1 5 0 1 1 0 9 [2 rows x 3 c...
python|pandas
2
374,051
20,478,949
How to force larger steps on scipy.optimize functions?
<p>I have a function <code>compare_images(k, a, b)</code> that compares two 2d-arrays <code>a</code> and <code>b</code></p> <p>Inside the funcion, I apply a <code>gaussian_filter</code> with <code>sigma=k</code> to <code>a</code> My idea is to estimate how much I must to smooth image <code>a</code> in order for it to ...
<p>Quick check: you probably really meant <code>fmin(compare_images, init_guess, (a,b))</code>?</p> <p>If <code>gaussian_filter</code> behaves as you say, your function is piecewise constant, meaning that optimizers relying on derivatives (i.e. most of them) are out. You can try a global optimizer like <a href="http:/...
python|optimization|numpy|scipy|gaussian
4
374,052
20,808,393
Python: Defining a minimum bounding rectangle
<p>I have data in the following format, a list of 2d x,y coordinates:</p> <pre><code>[(6, 7), (2, 4), (8, 9), (3, 7), (5, 4), (9, 9)] </code></pre> <p>and I'm trying to iterate through the list to find the minimum bounding box in the format [(minx,miny),(maxx,miny),(maxx,maxy),(minx,maxy)]</p> <p>Thus I've written t...
<p>Why don't you just iterate through the list with four counters: <code>min_x</code>, <code>min_y</code>, <code>max_x</code>, and <code>max_y</code></p> <pre><code>def bounding_box(coords): min_x = 100000 # start with something much higher than expected min min_y = 100000 max_x = -100000 # start with something...
python|list|numpy|2d|gis
2
374,053
33,229,140
How do I drop a table in SQLAlchemy when I don't have a table object?
<p>I want to drop a table (if it exists) before writing some data in a Pandas dataframe:</p> <pre><code>def store_sqlite(in_data, dbpath = 'my.db', table = 'mytab'): database = sqlalchemy.create_engine('sqlite:///' + dbpath) ## DROP TABLE HERE in_data.to_sql(name = table, con = database, if_exists = 'append') ...
<p>From the panda docs;</p> <p>"You can also run a plain query without creating a dataframe with execute(). This is useful for queries that don’t return values, such as INSERT. This is functionally equivalent to calling execute on the SQLAlchemy engine or db connection object."</p> <p><a href="http://pandas.pydata.or...
python|pandas|sqlalchemy
10
374,054
33,344,359
How to add conditional columns to pandas df
<p>I want to create a column in a dataframe that is conditionally filled with values. Basically my dataframe loks like this</p> <pre><code> Origin X 0 Guatemala x 1 China x 2 Kenya x 3 Venezuela x 4 Bangladesh x </code></pre> <p>What I want to do now is create an additional column 'Continent', which ...
<p>You can construct the lists for each continent and <code>apply</code> a func:</p> <pre><code>In [35]: asia = ['Thailand','Indonesia','China','Japan','Bangladesh'] south_america = ['Boliva' , 'Guatemala' , 'Venezuela' , 'Mexico' , 'Argentinia'] africa = [ 'Guinea Bissau' , 'Egypt' , 'Zaire' , 'Kenya'] def find_conti...
python|if-statement|pandas|conditional|dataframe
1
374,055
33,424,503
Pandas usecols all except last
<p>I have a csv file, is it possible to have <code>usecols</code> take all columns except the last one when utilizing <code>read_csv</code> without listing every column needed.</p> <p>For example, if I have a 13 column file, I can do <code>usecols=[0,1,...,10,11]</code>. Doing <code>usecols=[:-1]</code> will give me s...
<p>Starting from version <code>0.20</code> the <code>usecols</code> method in pandas accepts a callable filter, i.e. a <code>lambda</code> expression. Hence if you know the name of the column you want to skip you can do as follows:</p> <pre><code>columns_to_skip = ['foo','bar'] df = pd.read_csv(file, usecols=lambda x:...
python|pandas
17
374,056
33,189,971
Numpy loadtxt works with urllib2 response but not requests response
<p>I am attempting to load a csv file from a url such as <a href="http://real-chart.finance.yahoo.com/table.csv?s=PXD&amp;d=9&amp;e=17&amp;f=2015&amp;g=d&amp;a=11&amp;b=12&amp;c=1970&amp;ignore=.csv" rel="nofollow">http://real-chart.finance.yahoo.com/table.csv?s=PXD&amp;d=9&amp;e=17&amp;f=2015&amp;g=d&amp;a=11&amp;b=12...
<p>With <code>requests</code>, I think you need to explicitly iterate over the lines of the response, otherwise <code>loadtxt</code> won't pick up the individual rows properly. Try:</p> <pre><code>Date,Open,High,Low,Close,Volume,AdjClose = np.loadtxt(file.iter_lines(), unpack=True, delimiter=',', skiprows=...
python|csv|numpy|python-requests|urllib2
1
374,057
33,359,411
Mean Absolute Error - Python
<p>I'm new to Python</p> <p>I have to implement a function that can calculate MAE between 2 images</p> <p>Here is the MAE formula i have learnt:<a href="https://i.stack.imgur.com/Qegha.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Qegha.png" alt="enter image description here"></a></p> <p>Here is my code:...
<p>The absolute sign in the mean absolute error is in each entry in the sum, so you can't check whether <code>mae &lt; 0</code> after you summed it up - you need to put it inside the sum!</p> <p>Hence you should have something like</p> <pre><code>mae = np.sum(np.absolute((imageB.astype("float") - imageA.astype("float...
python|numpy
21
374,058
33,342,702
how to convert a string type to date format
<p>My source data has a column including the date information but it is a string type. Typical lines are like this:</p> <pre><code>04 13, 2013 07 1, 2012 </code></pre> <p>I am trying to convert to a date format, so I used panda's <code>to_datetime</code> function:</p> <pre><code>df['ReviewDate_formated'] = pd.to_da...
<p>Your format string is incorrect, you want <code>'%m %d, %Y'</code>, there is a <a href="http://strftime.org/" rel="nofollow">reference</a> that shows what the valid format identifiers are:</p> <pre><code>In [30]: import io import pandas as pd t="""ReviewDate 04 13, 2013 07 1, 2012""" df = pd.read_csv(io.StringIO(t)...
python|date|pandas
0
374,059
33,303,314
Confusing behaviour of Pandas crosstab() function with dataframe containing NaN values
<p>I'm using Python 3.4.1 with numpy 0.10.1 and pandas 0.17.0. I have a large dataframe that lists species and gender of individual animals. It's a real-world dataset and there are, inevitably, missing values represented by NaN. A simplified version of the data can be generated as:</p> <pre><code>import numpy as np im...
<p>I suppose one workaround would be to convert the NaNs to 'missing' before creating the table and then the cross-tubulation will include columns and rows specifically for missing values:</p> <pre><code>pd.crosstab(tempDF['species'].fillna('missing'),tempDF['gender'].fillna('missing'),margins=True) gender female ...
python|pandas|dataframe|nan|crosstab
21
374,060
33,121,760
Python: create a new dataframe column and write the index correspondig to datetime intervals
<p>I have the following dataframe :</p> <pre><code> date_time value member 2013-10-09 09:00:00 664639 Jerome 2013-10-09 09:05:00 197290 Hence 2013-10-09 09:10:00 470186 Ann 2013-10-09 09:15:00 181314 Mikka 2013-10-09 09:20:00 969427 Cristy 2013-10-09 09:25:00 261473 James 2013-10-09 09:30:0...
<p>I'm assuming you want the actual index location (zero-based), you can call <code>apply</code> on your 'date_time' column and call <code>np.searchsorted</code> to find the index location of where in <code>bounds</code> df it falls in:</p> <pre><code>In [266]: df['Session'] = df['date_time'].apply(lambda x: np.search...
python|pandas|dataframe
2
374,061
9,296,658
How to filter a numpy array using another array's values?
<p>I have two NumPy arrays, e.g.:</p> <pre><code>a = [1,2,3,4,5] </code></pre> <p>and a filter array, e.g.:</p> <pre><code>f = [False, True, False, False, True] len(a) == len(f) </code></pre> <p>How can I get a new numpy array with only the values in a where the same index in <code>f</code> is True? In my case: <c...
<p>NumPy supports <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#boolean-array-indexing" rel="noreferrer">boolean indexing</a></p> <pre><code>a[f] </code></pre> <p>This assumes that <code>a</code> and <code>f</code> are NumPy arrays rather than Python lists (as in the question). You can conv...
python|arrays|filter|numpy
38
374,062
9,412,500
Image Interpolation in python
<p>I am trying to use interpolation to remove chromatic aberration from an image. The code I have generates the following error: TypeError: unhashable type: 'numpy.ndarray'. Below is my code - any help would be greatly appreciated. Thank you- Areej This is an input explanation</p> <pre><code>#splitting an image into...
<p>A possible explanation of the error message is that you are trying to use a NumPy array as a dict key or a set element. Look at where the error occurs and study the type of every variable referenced on that line. If you need help, post a runnable example and the full traceback of the exception.</p>
python|numpy|scipy
1
374,063
6,030,906
Merging a list of numpy arrays into one array (fast)
<p>what would be the fastest way to merge a list of numpy arrays into one array if one knows the length of the list and the size of the arrays, which is the same for all?</p> <p>I tried two approaches:</p> <ul> <li><p><code>merged_array = array(list_of_arrays)</code> from <a href="https://stackoverflow.com/questions/...
<p>You have 80 arrays 320x320? So you probably want to use <code>dstack</code>:</p> <pre><code>first3 = numpy.dstack(firstmatrices) </code></pre> <p>This returns one 80x320x320 array just like <code>numpy.array(firstmatrices)</code> does:</p> <pre><code>timeit numpy.dstack(firstmatrices) 10 loops, best of 3: 47.1 ms...
python|arrays|numpy
22
374,064
5,896,747
numpy.memmap for an array of strings?
<p>Is it possible to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.memmap.html" rel="nofollow"><code>numpy.memmap</code></a> to map a large disk-based array of <strong>strings</strong> into memory?</p> <p>I know it can be done for floats and suchlike, but this question is specifically about st...
<p>If all the strings have the same length, as suggested by the term "array", this is easily possible:</p> <pre><code>a = numpy.memmap("data", dtype="S10") </code></pre> <p>would be an example for strings of length 10.</p> <p><strong>Edit</strong>: Since apparently the strings don't have the same length, you need to...
python|string|numpy|memory-mapped-files|large-data
5
374,065
5,935,893
Any reason why Octave, R, Numpy and LAPACK yield different SVD results on the same matrix?
<p>I'm using Octave and R to compute SVD using a simple matrix and getting two different answers! The code is listed below:</p> <p>R </p> <pre><code>&gt; a&lt;-matrix(c(1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1), 9, 4) &gt; a [,1] [,2] [,3] [,4] [1,] 1 1 0 0 [2,] 1 ...
<p>In SVD decomposition $A=UDV^T$ only $D$ is unique (up to reordering). It is more or less easy to see that $cU$ and $\frac{1}{c}V$ will give the same decomposition. So it is not surprising that different algorithms can give different results. What matters is that $D$ must be the same for all algorithms.</p>
r|numpy|octave|lapack|svd
8
374,066
6,114,115
Windows + virtualenv + pip + NumPy (problems when installing NumPy)
<p>On Windows, I normally just use the binary installer, but I would like to install <a href="http://en.wikipedia.org/wiki/NumPy" rel="noreferrer">NumPy</a> only in a virtualenv this time, so I created a virtual env:</p> <pre><code>virtualenv --no-site-packages --distribute summary_python cd summary_python/Scripts act...
<p>I've had success installing NumPy binaries into a virtualenv with good 'ol <code>easy_install</code> and a little bit of un-archiving magic.</p> <p>The <code>numpy-1.x.x-win32-superpack-python2.x.exe</code> release you download from <a href="http://en.wikipedia.org/wiki/SourceForge" rel="nofollow noreferrer">Source...
python|windows|numpy|pip|virtualenv
48
374,067
6,022,359
Python "list order"
<p>I have 2 troubles with my data, can anyone help me:</p> <p>How can I get from this:</p> <p><strong>1.</strong></p> <pre><code>k=[['1','7', 'U1'], ['1.5', '8', 'U1'], ['2', '5.5', 'U1']] </code></pre> <p>get this</p> <pre><code>1,7,U1 1.5,8,U1 2,5.5,U1 </code></pre> <hr> <p><strong>EDIT 2 I MAKE SOME CHANG...
<p>One-line functional style:</p> <pre><code>print '\n'.join(','.join(x) for x in k) </code></pre>
python|numpy
5
374,068
66,633,109
Aggregating row repeats in pandas (run lengths)
<p>In the following dataframe of snapshots of a given system, I am interested in recording any changes in <code>var1</code> or <code>var2</code> <em>over time</em>, assuming that the state of the system remains the same until something changes. This is similar to run length encoding, which condenses sequences in which...
<p>For contiguous grouping you can group on <code>(df.col != df.col.shift()).cumsum()</code></p> <p>You want it for either column so you can <code>|</code> them together.</p> <pre><code>&gt;&gt;&gt; ((df.var1 != df.var1.shift()) | (df.var2 != df.var2.shift())).cumsum() 0 1 1 1 2 2 3 3 4 4 5 4 6 5 7...
python|pandas|numpy|duplicates|partitioning
3
374,069
66,745,856
Change values in a Python dataframe, based on values in another dataframe
<p>I have two dataframes:</p> <pre><code>import pandas as pd import numpy as np data1 = {1: [1,2,3], 2: [1,2,3]} df1 = pd.DataFrame(data1) data2 = {1: [50,60,12], 2: [14,70,60]} df2 = pd.DataFrame(data2) </code></pre> <p>Where a value is &lt; 30 in df2, I want to change the respective value in df1 to a semicolon.</p> ...
<p>If same index and columns names in both DataFrames use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mask.html" rel="nofollow noreferrer"><code>DataFrame.mask</code></a> and pass mask from compare another DataFrame:</p> <pre><code>df1 = df1.mask(df2 &lt; 30, ':') print (df1) ...
python|pandas
0
374,070
66,659,528
Difference between scipy.stats.norm.pdf and plotting gaussian manually
<p>I'm plotting a simple normal distribution using scipy.stats, but for some reason when I try to compare it to the regular gaussian formula the plot looks very different:</p> <pre><code>import numpy as np import scipy.stats as stats x = np.linspace(-50,175,10000) sig1, mu1 = 10.0, 30.0 y1 = stats.norm.pdf(x, mu1, s...
<p><code>stats.norm.pdf</code> requires sigma, but in your calculation you are using it as variance. Also there are two brackets missing.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import scipy.stats as stats x = np.linspace(-50, 175, 10000) sig1, mu1 = 10.0, 30.0 var1 = sig1 ** 2 y1 = stats.no...
python|numpy|scipy|gaussian
2
374,071
66,546,186
How can you prepare data with time series and static data for classficiation?
<p>I am trying to build a binary classifier to predict the propensity of customers transitioning from one account to another. I have age, gender, cust-segment data but also a time-series of their bank balances for the last 18mths on a monthly basis and also have a lot of high cardinality categorical variables.</p> <p>S...
<p>I would generate descriptive statistics for each time serie. Standard deviation seems interesting, but you coud also use percentiles, mean, min and max... or all of them.</p> <pre class="lang-py prettyprint-override"><code># add a column for the standard deviation (and/or percentiles etc.) df['standard_deviation']= ...
python|pandas|dataframe|deep-learning|data-cleaning
0
374,072
66,676,823
FileNotFoundError: [Errno 2] No such file or directory: [Instert file path]
<p>I have an issue. Here is my code:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd from pandas import ExcelFile test = pd.read_excel(&quot;C:\\Users\\John\\Desktop\\Python_work\\stock\\zen\\OutputFiles\\Test_file.csv&quot;, header=0) print(test) </code></pre> <p>My problem is the code does ...
<p>You could try using raw string instead (r&quot;&quot;)</p> <pre><code>amzn = pd.read_excel(r&quot;C:\Users\John\Desktop\Python_work\stock\zen\OutputFiles\Test_file.csv&quot;, header=0) </code></pre>
python|pandas
0
374,073
66,654,257
Find no of days gap for a specific ID when it has a flag X in other column
<p>I want to calculate the no. of days gap for when the 'flag' column is equal to 'X' for same IDs.</p> <p>The dataframe that I have:</p> <pre><code>ID Date flag 1 1-1-2020 X 1 10-1-2020 null 1 15-1-2020 X 2 1-2-2020 X 2 10-2-2020 X 2 15-2-2020 X 3 15...
<p>First filter rows by <code>X</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> and then subtract shifted column per groups by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.c...
python-3.x|pandas|dataframe
1
374,074
66,600,784
Get category "Date" in Excel when writing data from pandas
<p>I am trying to write a dataframe into an excel, but I specifically need the column (in excel) to be of category &quot;Date&quot;.</p> <p>What I'm trying to achieve therefore is:</p> <pre><code>x = pandas.DataFrame(data=['04/01/2020'], columns=['Date']) x.to_excel(&quot;&lt;path&gt;/ExcelFile.xlsx&quot;) </code></pre...
<p>You could use pd.ExcelWriter, class for writing DataFrame objects into excel sheets:</p> <pre><code>import pandas as pd x = pd.DataFrame(data=['04/01/2020'], columns=['Date']) x['Date'] = pd.to_datetime(x['Date']) with pd.ExcelWriter('&lt;path&gt;/ExcelFile.xlsx', datetime_format='DD/MM/YYYY') as writer: x.to_...
python|python-3.x|excel|pandas|dataframe
0
374,075
66,450,324
Get the sum of a multikey dict by one key and add it to a datfarme column in Python?
<p>I have a dataframe and a dict as follows:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.array([[1, 2], [4, 5]]),columns=['a', 'b']) df a b 0 1 2 1 4 5 dict {(0, 'A', 1): 1, (0, 'A', 2): 2, (1, 'B', 1): 3, (1, 'B', 2): 4} </code></pre> <p>I am trying to get the total sum by the f...
<blockquote> <p>I am trying to get the total sum by the first key of the dict and add the result as a new column to my dataframe</p> </blockquote> <p>You can convert to series and sum on level 0:</p> <pre><code>df['new'] = pd.Series(d).sum(level=0) </code></pre> <hr /> <pre><code>print(df) a b new 0 1 2 3 1 ...
python|pandas|dictionary
3
374,076
66,410,694
Python - Can't match strings from file
<p>I have this <code>textfile.txt</code>:</p> <pre><code>i car air me </code></pre> <p>And a dictionary is defined as:</p> <pre><code>dictionary = {&quot;me&quot;:3, &quot;you&quot;:4, &quot;else&quot;: 10, &quot;i&quot;:2} </code></pre> <p>I'm looking for a way to delete the words in textfile.txt from the dictionary i...
<p>You need to trim the whitespaces (or in this case <code>\n</code> which is a newline. Call the strip method on the strings that have <code>\n</code> at the end. (like s.strip())</p>
numpy
1
374,077
66,471,525
Summarize several columns with looping through columns in python
<p>I have a very strange survey data structure like the below sample. During the survey number of smartphone per household were collected and then collect information about how many individuals use each device for a particular activity.</p> <p>Exmple : F3_{smartphone number}_{HH_member_id} so F3_1_4 will be F3 &amp; {...
<p>Clearly you have encoded multi-index columns. You can decode as follows.</p> <pre><code>df = pd.DataFrame.from_dict(d, orient='index').set_index(&quot;respid&quot;) # d is the name of the dict # remove redundant &quot;f3_&quot; from column name df = df.rename(columns={c:c[3:] for c in df.columns if c.startswith(&q...
python|pandas|for-loop|pivot-table|reshape
1
374,078
66,743,171
Training using object detection api is not running on GPUs in AI Platform
<p>I am trying to run the training of some models in tensorflow 2 object detection api.</p> <p>I am using this command:</p> <pre><code>gcloud ai-platform jobs submit training segmentation_maskrcnn_`date +%m_%d_%Y_%H_%M_%S` \ --runtime-version 2.1 \ --python-version 3.7 \ --job-dir=gs://${MODEL_DIR} \ --...
<blockquote> <p>Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/local/cuda/extras/CUPTI/lib64:/usr/local/cuda/lib64:/usr/local/nvidia/lib64</p> </blockquote> <p>I'm not sure as I couldn't test anyhow. With a...
tensorflow|object-detection|object-detection-api|gcp-ai-platform-training|google-ai-platform
0
374,079
66,616,312
Numpy - count nonzero elements in 3d array
<p>I have a soduko board stored as <code>blocks = np.full(81, fill_value=0 ).reshape((9,3,3))</code>(<em>Important note: blocks are indexed sequentially, but to take up less space I show them as a single 9x9 block instead of <code>9x3x3</code>; middle block is index 4 (instead of <code>(1,1)</code>, bottom left is inde...
<p>I think this is what you are trying to do if I understand your requirements correctly:</p> <pre><code>&gt;&gt;&gt; z array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 5, 7, 4, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, ...
python|numpy|multidimensional-array
0
374,080
66,398,540
How to set new columns in a multi-column index from a dict with partially specified tuple keys?
<p>I have a pandas dataframe initialized in the following way:</p> <pre><code>import pandas as pd my_multi_index = pd.MultiIndex.from_tuples([('a', 'a1'), ('a', 'a2'), ('b', 'b1'), ('b', 'b2')], names=['key1', 'key2']) df = pd.Dat...
<p>We can leverage the fact that we can pass tuples as a MultiIndex slicer. Also we slightly adjust your <code>my_dict</code>. Then we apply a simple for loop:</p> <pre><code>my_dict = { ('a',): 'x', ('b', 'b1'): 'y1', ('b', 'b2'): 'y2' } for idx, value in my_dict.items(): df.loc[idx, 'desc1'] = value ...
python|pandas|dataframe|slice|multi-index
2
374,081
66,666,342
Filter a pandas row without repetition based on combination of values in separate columns
<p>I have a dataframe as follows</p> <pre><code>criteria 1 criteria 2 value a1 a2 99 b1 a2 88 c1 a2 77 a1 b2 66 b1 b2 55 c1 b2 44 a1 c2 33 b1 c2 22 ...
<p>Try this.</p> <pre><code>df_new = df.sort_values('value', ascending=False) result = df_new.iloc[[0],] for i in range(1,df_new.criteria1.nunique()): df_new = df_new[~df_new.criteria1.isin(result.criteria1)&amp; ~df_new.criteria2.isin(result.criteria2)] result=result.append(df_new.iloc[[0],]) </code></pre>...
python|python-3.x|pandas|dataframe
1
374,082
66,558,764
Can't Train SSD Inception-V2 with Larger Input Resolution with TensorFlow Object Detection API
<p>I am looking to use the TensorFlow Object Detection API to train SSD Inception-V2 from scratch on a custom dataset with resolution larger than 300x300.</p> <p>I am referencing this as a sample config file: <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/samples/configs/ssd_incepti...
<p>The original <a href="https://arxiv.org/pdf/1512.02325.pdf" rel="nofollow noreferrer">SSD paper</a> that came out in 2016 was designed with 2 specific input image sizes, <code>300x300</code> and <code>512x512</code>. However, the backbone for that was Mobilenet (considering speed as the main factor). You can try res...
python|tensorflow|deep-learning|object-detection|object-detection-api
0
374,083
66,343,293
Danfo dataFrame - Replace values by index, column
<p>In Panda DataFrames in python, replacing values by column and index is very straight-forward.</p> <p>Example DataFrame:</p> <pre><code>df = pd.DataFrame({'A': [1, 2, 3], 'B': [200, 300, 400]}) A B 0 1 200 1 2 300 2 3 400 </code></pre> <p>Replacing values is as simple as:</p> <pre><code>df['A'][0] = 80...
<p>Please try:</p> <pre><code>let df_rep = df.replace({ &quot;replace&quot;: 1, &quot;with&quot;: 800, &quot;in&quot;: [&quot;A&quot;] }) </code></pre> <p>You probably noticed, but just in case, 1 here is the value not the index.</p> <p><strong>Official documentation</strong></p> <p>{replace: int, float, str. The value...
pandas|dataframe|danfojs
0
374,084
66,583,713
resize video data to fit model.predict
<p>The model was trained the following way</p> <pre><code>model = keras.Sequential() model.add(Conv2D(64, (3, 3), input_shape=(16, 120, 120, 3), padding='same', activation='relu')) </code></pre> <p>How can I resize videos to pass them to <code>trained_model.predict</code> below for prediction?</p> <pre><code>trained_mo...
<p>It worked this way</p> <pre><code>import cv2 import numpy as np file = '7.avi' cap = cv2.VideoCapture(file) frameCount = 16 frameWidth = 120 frameHeight = 120 buf = np.empty((frameCount, frameHeight, frameWidth, 3), np.dtype('uint8')) fc = 0 ret = True while (fc &lt; frameCount and ret): buf[fc] = cv2.resize...
python|tensorflow|keras
0
374,085
66,685,673
tf.io.decode_raw return tensor how to make it bytes or string
<p>I'm struggling with this for a while. I searched stack and check tf2 doc a bunch of times. There is one solution indicated, but I don't understand why my solution doesn't work.</p> <p>In my case, I store a binary string (i.e., bytes) in tfrecords. if I iterate over dataset via as_numpy_list or directly call numpy() ...
<p>I found one solution but I would love to see more suggestions.</p> <pre><code>def test_callback(example_proto): from_string = creator.FromString(example_proto.numpy()) encoded_seq = encoder.encoder(from_string) return encoded_seq raw_dataset = tf.data.TFRecordDataset(filenames=[&quot;main.tfrecord&quot;...
tensorflow|tensorflow2.0|tensorflow-datasets
0
374,086
66,693,034
Use pandas.apply with multiple arguments to return several columns
<p>I am trying to preprocess a dataset with pandas. I want to use a function with multiple arguments (one from a column of the dataframe, others are variables) which returns several outputs like this:</p> <pre><code>def preprocess(Series,var1,var2,var3,var4): return 1,2,3,4 </code></pre> <p>I want to use the native ...
<p>You need to re-write your function to return a series, that way, <code>apply</code> returns a dataframe:</p> <pre><code>def preprocess(Series,var1,var2,var3,var4): return pd.Series([1,2,3,4]) </code></pre> <p>Then your code would run and return</p> <pre><code> A B C D E F 0 4 9 0 1 2 3 1 4 9 0 1...
python-3.x|pandas|dataframe
1
374,087
66,610,067
Is there a faster/better way to apply a function in order to create a new column, across different axes?
<p>I have two DataFrames that look like this:</p> <p>df1 (pretty small):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>index</th> <th>sales</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>10</td> </tr> <tr> <td>2</td> <td>20</td> </tr> </tbody> </table> </div> <p>and df2 (very large &gt;5...
<p>This should be faster than <code>apply</code>:</p> <pre><code>df2['totalSales'] = df2.idx1.map(df1.sales) + df2.idx2.map(df1.sales) df2 # idx1 idx2 totalSales #0 1 2 30 </code></pre>
python|pandas|dataframe
1
374,088
66,376,207
how to change a array of a single column to a row of values instead of arrays in python
<p>I am trying to convert an array of arrays that each contain only one integer to a single array with just the integers.</p> <p>This is my code below. k=1 after the first for loop and the next code deletes all the rows of except the first one and then transposes it.</p> <pre><code>handles.Background = np.zeros(((len(i...
<p>if <code>handles.Background[n]</code> returns an array, you can index into that, too, using the same [n] notation.</p> <p>So you are looking for</p> <pre><code>handles.Background[n][0] </code></pre> <p>If you want to unpack the whole array at once, you can use this:</p> <pre><code>handles.Background = [bg[0] for bg ...
python|arrays|numpy|transpose
0
374,089
66,397,600
Name pandas dataframe from a for loop with the use of range and the year in question
<p>I'm trying to get some data from a website, and the data consists of one Excel file per year (from 2015 to 2021). I feel I'm nearly done, but what is missing is to be able to save every annual result into a separate dataframe with a distinct name (with year as suffix). This probably have a simple solution and possib...
<p>Create an empty dictionary, add each dataframe to the dictionary with the name, e.g. df_long_2015, as the key and the dataframe as the value.</p>
python|pandas|dataframe|for-loop
1
374,090
66,704,609
function for multiple conditions in pandas using dictionaries
<p>I am trying to build a function that uses a dataframe and a dictionary and returns a dataframe based on the conditions in the dictionary. My code looks like:</p> <pre><code>import pandas as pd column_names=['name','surname','age'] lfa=[(&quot;tom&quot;,&quot;jones&quot;,44),(&quot;elvis&quot;,&quot;prestley&quot;,50...
<p>Use:</p> <pre><code>df = lfa[lfa[list(f.keys())].eq(f).all(axis=1)] print (df) name surname age 0 tom jones 44 </code></pre> <p><strong>Details</strong>:</p> <p>First filter columns by keys of dictionary:</p> <pre><code>print (lfa[list(f.keys())]) name age 0 tom 44 1 elvis 50 2 jim 30 </co...
python|pandas
1
374,091
66,671,232
Calculate FLOPS (Floating Point Operations per Second) of TensorFlow lite model
<p>Is there any way to measure directly the FLOPS of a .tflite model? I've found some topics about this, but just to the unconverted model.</p>
<p>There is a tool that measures the TFLite model performance. Please take a look at <a href="https://www.tensorflow.org/lite/performance/measurement" rel="nofollow noreferrer">https://www.tensorflow.org/lite/performance/measurement</a>.</p> <p>The benchmark tool can measure useful metrics including initialization time...
tensorflow|tensorflow-lite
1
374,092
66,622,761
How to speed up scipy.stats.truncnorm for 3D array?
<p>For 1D array, I found that the generation of <code>rsv</code> by <code>truncnorm</code> is at least 1 order of magnitude faster than using <code>norm</code> and <code>np.where</code>. The 1D test code is shown below. Timing result is:</p> <pre><code>atotal time= 0.0018085979972966015 # norm and np.where btotal time...
<p><code>truncnorm.rvs</code> is so much slower in the 3d case because the parameters you feed in for <code>a</code>, <code>b</code>, <code>loc</code>, and <code>scale</code> are arrays the same shape as your desired output. So, for the numbers you show, you need to create four 270,000-element arrays, which will clog y...
python|numpy|scipy
0
374,093
66,718,311
Why pandas convert UNIX timestamps to multiple different date-time values?
<p>I have a pandas dataframe with UNIX timestamps (these are integers and not time objects). I'd like to convert the UNIX timestamps into local time (according to China timezone). So, based on this, I tried to do the following:</p> <pre><code>import pandas as pd data = {'timestamp': [1540651297, 1540651300, 15406513...
<pre><code>df['timestamp1'] = pd.to_datetime(df.timestamp, unit='s') </code></pre> <p>This statement here creates a column with datetime value with current time. The datetime values are time-zone naive and in UTC.</p> <pre><code>df['timestamp2']=df['timestamp'].apply(lambda d: datetime.datetime.fromtimestamp(int(d)).st...
python|pandas|datetime|timezone
2
374,094
66,562,140
How do I vectorize a function which has multiple outputs with Numba?
<p>For example, I want to vectorize the following function:</p> <pre><code>@nb.njit(nb.types.UniTuple(nb.float64,2)(nb.float64, nb.float64)) def add_subtract(x,y): return x+y, x-y </code></pre> <p>However, when I use @numba.vectorize like this:</p> <pre><code>@nb.vectorize([nb.types.UniTuple(nb.float64,2)(nb.float6...
<p><code>vectorize</code> only works on a single scalar output (broadcasted to the dimensions of your input vector). As a workaround you can use <code>guvectorize</code>:</p> <pre><code>import numpy as np from numba import guvectorize @guvectorize( [&quot;void(float64[:], float64[:] , float64[:], float64[:])&quot...
python|numpy|numba
2
374,095
66,378,218
How to suppress KeyError in Python when dataframe is empty when mapping multiple Foursquare results and an API result is blank
<p>I'm retrieving Foursquare venue data and plotting it on a Folium map. I'm plotting several API call results on the same map.</p> <p>When the API returns an empty JSON result because there are no queried venues within the search, it throws a KeyError because the code is referencing columns in the dataframe that doesn...
<p>If you would just like to silence a KeyError then try this:</p> <pre><code>try: ... except KeyError as ke: pass </code></pre>
python|pandas|foursquare|keyerror|folium
0
374,096
66,429,404
xtensor : How to write an vector to an array
<p>What is the equivalent in <a href="https://github.com/xtensor-stack/xtensor" rel="nofollow noreferrer">xtensor</a> or the most optimized way to write a vector to an array.</p> <p>Thanks</p> <pre class="lang-py prettyprint-override"><code>import numpy as np array = np.zeros((4, 4)) array[0] = np.array([1, 2, 3, 4])...
<p>The easiest way is</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;xtensor/xtensor.hpp&gt; #include &lt;xtensor/xarray.hpp&gt; #include &lt;xtensor/xview.hpp&gt; #include &lt;xtensor/xio.hpp&gt; int main() { xt::xtensor&lt;double, 2&gt; array = xt::xtensor&lt;double&gt;({4, 4}); xt::xtenso...
python|c++|numpy|xtensor
1
374,097
66,532,414
Tensorflow saved model does not contain input names
<p>We are currently training an object detection model in tensorflow 2.4.0 which is working fine. However, to be able to serve it we need to wrap it with an image pre-processing layer that takes the image bytes as input and converts them to the image tensor required by the detection model. See the following code:</p> <...
<p>The problem stems from the way you defined your lambda layer, and the way you setup your model.</p> <p>Your lambda function should be able to treat a batch, which is currently not the case. You can naively use <code>tf.map_fn</code> to make it handle a batch of images, like so:</p> <pre><code>def preprocessing_layer...
python|tensorflow|keras|tensorflow-serving|tensorflow2.x
2
374,098
66,464,851
Flattening dictionary with pd.json_normalize
<p>I am currently working on flattening this dictionary file and have reached a number of road blocks. I am trying to use <code>json_normalize</code> to flatten this data. If I test with individual instances it works but if I want to flatten all the data it will return an error stating <code>key error '0'</code> I'm no...
<h2>Setup</h2> <p>Your data is structured inconveniently. I want to focus on:</p> <ol> <li>Getting the lists in <code>'IDs'</code> into a list of dictionaries, which would be far more convenient.</li> <li>Getting rid of the useless keys in the parent dictionary. All we care about are the values.</li> </ol> <p>Your <c...
python|json|pandas|dictionary|json-normalize
3
374,099
66,711,799
RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. GPU not detected by pytorch
<p>Having trouble with CUDA + Pytorch this is the error. I reinstalled CUDA and cudnn multiple times.</p> <p>Conda env is detecting GPU but its giving errors with pytorch and certain cuda libraries. I tried with Cuda 10.1 and 10.0, and cudnn version 8 and 7.6.5, Added cuda to path and everything.</p> <p>However anacond...
<p>Solved.</p> <p>Pytorch was installing CPU only version for some reason, reinstalling pytorch didn't help.</p> <p>Uninstalling pytorch: <code>conda uninstall pytorch</code></p> <p>Followed by uninstalling cpu only: <code>conda uninstall cpuonly</code></p> <p>Then installing pytorch again solved it.</p>
python-3.x|pytorch
0