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
356,600
69,012,023
Check if any element of a list is in a matrix?
<p>I have a small list:</p> <pre><code>list2 = ['hi', 'ma', 'ja'] </code></pre> <p>and I have a matrix too. for example:</p> <pre><code>matrix2 = ([['high','h ight','hi ght','h i g ht'], ['man','ma n','ma th','mat h'], ['ja cket','j a ck et','jack et','ja m'] ['ma nkind','jack',' hi ','hi']) </code...
<p>You have to loop over the matrix and then over each row of the matrix. Then you have a single string that you have to split to get the individual parts. Now you can check if any of this parts is in <code>list2</code>.</p> <p>list2 = ['hi', 'ma', 'ja']</p> <pre><code>matrix2 = [['high','h ight','hi ght','h i g ht'], ...
python|python-3.x|list|numpy|matrix
1
356,601
69,257,899
How to convert integer array to list using python pandas
<p>I had a dataframe column like as shown below</p> <pre><code>col1 &lt;NA&gt; 123.23 453.21 567.21 879.21 </code></pre> <p>To convert float with NaN into integer, I did the below</p> <pre><code>df['col1'].astype(float).astype('Int64') </code></pre> <p>When I do the below</p> <pre><code>df['col1'] = df['col1'].fillna(0...
<pre><code>nums = [] for i in df['col1']: i = int(i) nums.append(i) </code></pre>
python|pandas|dataframe|numpy
0
356,602
44,373,588
Distributed TensorFlow: Create a session in only one worker to print the results
<p>I just need to print the values of some global variables assigned within training. After closing the 'MonitoredTrainingSession', I created a session in the chief worker only using:</p> <blockquote> <pre><code> if FLAGS.task_index == 0: with tf.Session() as sess: print sess.run(some_variable) ...
<blockquote> <p>available devices: /job:localhost/replica:0/task:0/cpu:0</p> </blockquote> <p>It suggest that you should use the server you created. Try passing <code>server.target</code> when creating the session.</p> <pre><code>with tf.Session(server.target) as sess: print sess.run(some_variable) </code></pre...
python|tensorflow
1
356,603
44,563,667
Python Pandas DF Create New Variable based on List of Columns
<p>I have a df with some binary columns (1,-1) and a list with N columnnames. i need to create a new variable like that ...</p> <blockquote> <p>df['test'] = np.where(((df['Col1']==-1) &amp; (df['Col2']==-1)), -1, 0)</p> </blockquote> <p>... but dynamically. so the rule is: if all the columns from the list have the ...
<p>IIUC you can just do</p> <pre><code>df['test'] = np.where((df[list_of_col_names] == -1).all(axis=1), -1, 0) </code></pre> <p>So here you can just pass a list of cols of interest to sub-select from the orig df as all you're doing is comparing all cols of interest to a scalar value, you then do <code>all(axis=1)</co...
python|pandas|dataframe
1
356,604
44,466,875
How to replace objects with amount of objects in pandas Data Frame?
<p>I want to replace objects with amount of objects in pandas Data Frame.</p> <p>Data Frame looks like this: </p> <pre><code> [IRN, PAK, TKM, UZB, TJK, CHN] [] [MNE, GRC, MKD, KOS] [TUN, LBY, NER, ESH, MRT, MLI, MAR] [] ...
<p>In the most generic covention without knowing your column names:</p> <pre><code>df['Length'] = df.iloc[:,0].str.len().replace(0,np.nan) </code></pre> <p>Output:</p> <pre><code> Country Length 0 [IRN, PAK, TKM, UZB, TJK, CHN] 6.0 1 [] N...
pandas|object|dataframe|sum|python-3.6
0
356,605
44,716,527
Setting up Tensorflow Object Detection
<p>I've been trying to set up the Object Detection environment.</p> <p><a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md</a></p> <p>But I'...
<p>Try adding libraries to python path.<br> Run the following command from tensorflow/models directory.<br></p> <pre><code># From tensorflow/models/ export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim </code></pre> <p>Now the code will run successfully.This command needs to run from every new terminal you start. If you wi...
python|tensorflow|object-detection
2
356,606
44,618,887
Tensorflow placeholder declaration
<p>I'm trying to convert a <a href="http://machinelearningmastery.com/tutorial-first-neural-network-python-keras/" rel="nofollow noreferrer">tutorial</a> from Keras to TF. I'm getting the following error:</p> <pre><code>Traceback (most recent call last): File "/Users/spicyramen/Documents/Development/google/python/m...
<p>This is your problem here:</p> <pre><code>&gt;&gt;&gt; dataset[:, 8].shape (768,) </code></pre> <p>TensorFlow is expecting an array of shape <code>(768,1)</code> and not <code>(768,)</code> as the error references:</p> <pre><code>Cannot feed value of shape (768,) for Tensor u'Placeholder_1:0', which has shape '(?...
python|tensorflow|keras
2
356,607
44,802,902
Processing pandas data in declarative style
<p>I have a pandas dataframe of vehicle co-ordinates (from multiple vehicles on multiple days). For each vehicle and for each day, I do two things: either apply an algorithm to it, or filter it out of the dataset completely if it doesn't satisfy certain criteria. </p> <p>To acheive this I use <code>df.groupby('vehicle...
<p>Since <code>apply</code> uses a for loop anyway (meaning there are no sophisticated optimizations in the background), I suggest using an actual for loop:</p> <pre><code>arr = [] for key, dfg in df.groupby(['vehicle_id', 'day']): dfg = dfg.do_stuff1() # Perform all needed operations dfg = do_stuff2(dfg) #...
pandas|dataframe|declarative
0
356,608
44,810,739
numpy.array slicing behaviour
<p>Why does <code>numpy.array</code> behave differently than Python's list and default arrays when it comes to slicing? Please consider the examples below:</p> <p>1) using lists: the statement <code>b = a[1:3]</code> creates a new list object, and modifying <code>b</code> does not modify <code>a</code>.</p> <pre><cod...
<p>Because NumPy is a high-performance data collection. For Python to create a new list, it must construct a new list, increment all pointers to each element in the list, add the item to the list, and then return the slice. NumPy (likely) simply increments the offset of the start array and changes the end of the array....
python|arrays|numpy|slice
1
356,609
44,764,042
pandas mix position and label indexing without chaining
<p>Since <code>.ix</code> has been <a href="http://pandas-docs.github.io/pandas-docs-travis/whatsnew.html#deprecate-ix" rel="noreferrer">deprecated as of Pandas 0.20</a>, I wonder what is the proper way to mix lable-based, boolean-based and position-based indexing in Pandas? I need to assign values to a slice of datafr...
<p>Let's use .loc with the boolean indexing, and accessing the column labels via the dataframe column index with index slicing:</p> <pre><code>df.loc[df['a'] == 'x', df.columns[-12:-1]] = 3 </code></pre>
pandas|slice
7
356,610
44,684,054
Infer Series Labels and Data from pandas dataframe column for plotting
<p>Consider a simple 2x2 dataset with with Series labels prepended as the first column ("Repo")</p> <pre><code> Repo AllTests Restricted 0 Galactian 1860.0 410.0 1 Forecast-MLib 140.0 47.0 </code></pre> <p>Here are the DataFrame columns: </p> <pre><code>p(df.columns) ([u'Repo', u'All...
<p>Pandas assumes your label information is in the index and columns. Set the index first:</p> <pre><code>df.set_index('Repo').astype(float).plot() </code></pre> <p>Or</p> <pre><code>df.set_index('Repo').T.astype(float).plot() </code></pre>
pandas|matplotlib
1
356,611
44,477,851
Using numpy and lstsq to solve a 3 dimensions system
<p>I´m trying to transform <strong>x,y,z</strong> real world coordinates to my own <strong>x,y,z</strong> virtual world coordinates. As there is noise while getting the real world coordinates I need to use least squares. I have 3 variables as input: <strong>r_x,r_y,r_z</strong> and I need to have a 3 variables output <...
<p>The primary problem is that the rank of your input data was not sufficient to allow accurate inversion of your <code>A</code> matrix. Consider the following:</p> <h3>Test Code:</h3> <pre><code>import numpy as np def build_a(x_data): return np.column_stack((x_data, np.ones(len(x_data)))) def lstsq(x_data, y_...
python|numpy
1
356,612
44,591,282
Error when running Tensorflow Sequence to Sequence Tutorial
<p>I am getting the following error message when following the instructions in the Sequence to Sequence tutorial: <a href="https://www.tensorflow.org/tutorials/seq2seq" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/seq2seq</a></p> <p>When I run</p> <pre><code>python translate.py --data-dir [your data...
<p>There seems to be a problem with deepcopy of RNNCell, we're tracking it in this github bug: <a href="https://github.com/tensorflow/tensorflow/issues/8191" rel="noreferrer">https://github.com/tensorflow/tensorflow/issues/8191</a></p> <p>On a separate note, there is a new TensorFlow seq2seq repo with many models here...
python|tensorflow
5
356,613
44,470,688
TensorFlow LinearRegressor contrib.learn predict does not match manually training predict results
<p>I'm completely new to tensorflow and was just going through the GetStarted page + tutorials here: <a href="https://www.tensorflow.org/get_started/get_started" rel="nofollow noreferrer">https://www.tensorflow.org/get_started/get_started</a></p> <p>With the tf.contrib.learn example, I changed y slightly but still kep...
<p>If you call <code>tf.contrib.learn.LinearRegressor</code> without specifying the optimizer you want, it will use an Ftrl optimizer (<a href="https://www.tensorflow.org/api_docs/python/tf/contrib/learn/LinearRegressor" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/contrib/learn/LinearRegress...
tensorflow
0
356,614
44,595,325
from list variable to columns in pandas
<p>I have a Pandas Dataframe that looks like this :</p> <pre><code>user items 1 ["product1", "product2", "product3"] 2 ["product5", "product7", "product2"] 3 ["product1", "product4", "product5"] </code></pre> <p>I have 2 millions users that each have a <strong>list</strong> of 100 products. I nee...
<p>You can reconstruct with <code>df['items'].values.tolist()</code> and <code>join</code>.<br> I went this direction because it's faster than <code>apply</code>.</p> <p>Considering the large size of your data, you'll want this instead.</p> <pre><code>df.drop('items', 1).join( pd.DataFrame(df['items'].values.toli...
python|pandas
3
356,615
44,724,480
Group by one columns and find sum and max value for another in pandas
<p>I have a dataframe like this:</p> <pre><code>Name id col1 col2 col3 cl4 PL 252 0 747 3 53 PL2 252 1 24 2 35 PL3 252 4 75 24 13 AD 889 53 24 0 95 AD2 889 23 2 0 13 AD3 889 0 24 3 6 BG 024 12 89 53 66 BG1 ...
<p>The most (pandas) native way to do this, is to use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.agg.html" rel="noreferrer"><code>.agg()</code></a> method that allows you to specify the aggregation function you want to apply per column (just like you would do in SQL).</p> ...
python|pandas|dataframe|group-by
28
356,616
44,445,532
Extract rows from a pandas dataframe between two rows
<p>This is a sample of the data that I have. </p> <pre><code>T| 1.42 | Test1 | 1| 0 | 0 A| 1.42 | 1 | 1| 0 | 0 A| 1.42 | 1 | 2| 0 | 0 T| 1.42 | Test1 | 1| 0 | 0 A| 1.42 | 1 | 1| 0 | 0 A| 1.42 | 1 | 3| 0 | 0 A| 1.42 | 1 | 4| 0 | 0 T| 1.42 | Test1 | 1| 0 ...
<p>A very natural way to split into separate dataframes is to use <code>groupby</code>. I find where the first column is <code>'T'</code> and use boolean indexing and <code>cumsum</code> to identify the groups.</p> <pre><code>m = df.iloc[:, 0].eq('T') cumgrp = m.cumsum()[~m] grps = df[~m].groupby(cumgrp) </code></pre...
python|pandas|group-by|pandas-groupby
7
356,617
44,528,383
Can anyone give an example on how tf.contrib.metrics.streaming_mean_iou in tensorflow works?
<p>I am using tensorflow 0.11 and am running some image segmentation tests. In image segmentation, we usually compute the IoU. How can I make use of tensorflow's tf.contrib.metrics.streaming_mean_iou?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snipp...
<p>Your code is correct to compute the mean iou.</p> <p>If you want to compute the IoU for each class, see <a href="https://stackoverflow.com/questions/40340728/tensorflow-how-can-i-get-the-total-cm-in-tf-contrib-metrics-streaming-mean-iou">this question</a>. You can compute them via the confusion matrix. When you run...
tensorflow
2
356,618
44,775,131
How to get previous value while datetime is set as index
<p>I have pandas dataframe with datetime as index:</p> <pre><code> sys dia pul map datetime 2011-07-20 10:34:00 125 80 60 95 2011-07-20 11:00:00 103 67 55 79 2011-07-20 11:30:00 106 72 53 83 2011-07-20 12:00:00 97 61 50 73 2011-07-20 12...
<p>I think better is use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> for index from column <code>datetime</code>.</p> <p>Then need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_loc...
python|python-2.7|pandas|numpy
1
356,619
44,809,446
necessity of transposed convolution when feature maps are not downsampled
<p>I was reading a paper <a href="https://arxiv.org/pdf/1701.05957.pdf" rel="nofollow noreferrer">here</a>. The authors in the paper have proposed a symmetric generator network which contains a stack of convolution layers followed by a stack of de-convolution (transposed convolution) layers. It is also mentioned that a...
<p>In theory spatial convolution can be used as a replacement for fractionally-strided convolution. Typically this is avoided because, even without some type of pooling, convolutional layers can produce outputs that are smaller than their corresponding inputs (see the formulae for <code>owidth</code> and <code>oheight<...
image-processing|computer-vision|deep-learning|torch|pytorch
1
356,620
44,705,083
Error while using rstrip in pandas
<p>I have a dataframe df with one of the column "values". It contains -</p> <pre><code>values [u'12f4',u'ff45',u'tr23'] [u'125g4',u'ff145',u'trr523'] [u'12f34',u'ff2345',u'trg23a'] </code></pre> <p>I want to remove ']' from each cell. I am using the following code - </p> <pre><code>df['values'] = df['values'].map(la...
<p>Try use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.rstrip.html" rel="nofollow noreferrer"><code>str.rstrip</code></a>:</p> <pre><code>df['values'] = df['values'].str.rstrip(']') </code></pre>
python|pandas|jupyter-notebook
0
356,621
44,750,752
Effect of max_pool in Convolutional Neural Network [tensorflow]
<p>I'm following Udacity Deep Learning video by Vincent Vanhoucke and trying to understand the (practical or intuitive or obvious) effect of max pooling.</p> <p>Let's say my current model (without pooling) uses convolutions with stride 2 to reduce the dimensionality. </p> <pre><code> def model(data): conv = tf.n...
<p>Both of the approaches (strides and pooling) reduces the dimensionality of the input (for strides/pooling size > 1). This by itself is a good thing because it reduces the computation time, number of parameters and allows to prevent overfitting. </p> <p>They achieve it in a different way:</p> <ul> <li>you can think...
tensorflow|deep-learning|conv-neural-network
4
356,622
44,723,543
Removing elements from list corresponding to numpy array
<p>I have three lists <code>xs, ys, zs</code> of intgers, as well as a 3d numpy array <code>V</code>, which contains the value for each point. For example, the value of point <code>(x[0], y[0], z[0])</code> is <code>V[x[0], y[0], z[0]]</code>. I'm using these to create a 3d scatter plot <code>plt.scatter(xs, ys, zs, c=...
<p>In the best case the array <code>V</code> is ordered such that when it's flattened, the value at index <code>i</code> corresponds to the <code>i</code>th value in <code>x,y,z</code>. If this is the case you can filter the respective arrays by the condition:</p> <pre><code>X = np.array(xs); Y = np.array(ys); Z=np.ar...
python|numpy|matplotlib
0
356,623
44,775,676
Google Dataflow shows AttributeError: 'module' object has no attribute 'Read'
<p>I am using google cloud to do a testing, I follow the guide to run test against BigQuery . <a href="https://cloud.google.com/solutions/using-cloud-dataflow-for-batch-predictions-with-tensorflow" rel="nofollow noreferrer">https://cloud.google.com/solutions/using-cloud-dataflow-for-batch-predictions-with-tensorflow</...
<p>You are right, there's a small mistake in the code. In line <code>98</code> where it says:</p> <pre><code>images = p | 'ReadFromBQ' &gt;&gt; beam.Read(beam.io.BigQuerySource(known_args.input)) </code></pre> <p>It should be:</p> <pre><code>images = p | 'ReadFromBQ' &gt;&gt; beam.io.Read(beam.io.BigQuerySource(know...
python|tensorflow|apache-beam
2
356,624
44,821,090
Split DataFrame Randomly (dependent on unique values)
<p>I have a DataFrame <code>df</code> that looks like this:</p> <pre><code>| A | B | ... | --------------------- | one | ... | ... | | one | ... | ... | | one | ... | ... | | two | ... | ... | | three | ... | ... | | three | ... | ... | | four | ... | ... | | five | ... | ... | | five | ... | ... | </...
<p><strong>Setup</strong></p> <pre><code>df=pd.DataFrame({'A': {0: 'one', 1: 'one', 2: 'one', 3: 'two', 4: 'three', 5: 'three', 6: 'four', 7: 'five', 8: 'five'}, 'B': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8}}) </code></pre> <p><strong>Solution</strong></p> <pre><code>#get 2 unique keys...
python|pandas
2
356,625
44,707,549
How to create python/numpy array from text file?
<p>I have a white-space separated list of integers in the following format in a text file.</p> <pre><code>1 2 3 4 ...#First row can have any number of entries 3 5 6 1 6 7 8 9 ...#The next row can have a different number of entries #More such rows different number of entries in each row </code></pre> <p>How do I creat...
<p>The following function should do the trick:</p> <pre><code>def file_2_int_list (file_path): retval = [] with open(file_path, 'r') as f: for line in f: for num in line.split(' '): retval.append(int(num)) return retval </code></pre> <p>This function gets a path to a file, ...
python-2.7|numpy
0
356,626
44,500,787
Python numpy arrays elements not changing value
<p>So I am having an issue in my python code that I boiled down to this:</p> <p>Say we have a function <code>u</code>:</p> <pre><code>def u(y,t): h = float(10) U0 = float(1) return U0/h*(y) </code></pre> <p>And an array:</p> <pre><code>a=np.array([[0]*2]*2) </code></pre> <p>Then doing the following:</...
<p>I assume that you actually converted it to a <code>numpy.array</code> before you tried to set the element. So you have something like this somewhere in your code:</p> <pre><code>import numpy as np a = np.array(a) </code></pre> <p>But in that case it's an integer array (because your list of lists contains only inte...
python|arrays|numpy|pointers
8
356,627
44,633,314
How do you make a vector of strings in for loop
<p>How do convert a int array to a str array input:</p> <pre><code>x = np.array([0,1,2,3....]) </code></pre> <p>len(x)=73293</p> <p>output:</p> <pre><code>y = np.array(["0","1","2","3"....]) </code></pre> <p>We though about doing something like this:</p> <pre><code>y=[] for i in range(len(x)): y=y.append(...
<p>Try something like: </p> <pre><code>import numpy as np #with list comprehension y = [str(x) for x in np.arange(73293)] #if you prefer to use pure numpy y = np.arange(73293).astype(np.str) </code></pre> <p>Also the pure numpy as much faster:</p> <pre><code>%timeit y = [str(x) for x in np.arange(73293)] 10 loops...
python|arrays|string|numpy|for-loop
2
356,628
44,423,000
Python, Pandas: Merging several dataframes results in duplication of rows with uneven NaN values
<p>I have 4 dfs, which look like below</p> <p>df1</p> <pre><code> _id bs ds as pf 0 2017-05-01 00:00:00 0.982218 0.906662 0.614119 0.999471 1 2017-05-01 00:05:00 0.983751 0.913266 0.585237 0.999571 2 2017-05-01 00:10:00 0.983012 0.914875 0.592698 0....
<p>You can also use pd.concat with set_index</p> <pre><code>pd.concat([df1.set_index('_id'), df2.set_index('_id'), df3.set_index('_id'), df4.set_index('_id')], axis = 1).reset_index() </code></pre>
python|pandas
0
356,629
44,638,129
Sum of specific rows based on boolean indicator and return the results in new columns
<p>I have a data frame that looks like this:</p> <pre><code>DF = ID Shop Sales Ind 1 A 554 T 2 B 678 F 3 A 546 T 4 A 896 T 5 B 426 F 6 B 391 T 7 C 998 F 8 C 565 T 9 C 128 T </code></pre> <p>I am trying to sum for each ID t...
<p>Based on your effort</p> <pre><code>DF['SUM']=DF.groupby(['ID', 'Shop'])['Sales'].transform('sum') DF.loc[DF.Ind == 'F', 'SUM'] = 0 pd.concat([DF,DF.pivot(columns='Shop',values='SUM'). add_suffix('_Sum').fillna(0)],axis=1).drop(['SUM'],axis=1) Out[247]: ID Shop Sales Ind A_Sum B_Sum C_Sum 0 1 ...
python|pandas|dataframe|data-manipulation
1
356,630
44,620,483
trouble translating 11-line toy neural network code to JavaScript
<p>I am giving a short presentation on neural networks Tuesday to my fellow student web developers. I was hoping to translate <a href="https://iamtrask.github.io/2015/07/12/basic-python-network/" rel="nofollow noreferrer">this code</a> (under Part 1, a tiny toy neural network: 2 layer network) to JavaScript so it woul...
<p>It looks like you're very close, this is a nice port.</p> <p>I <em>think</em> this is a small bug in your translation of the <code>nonlin</code> function. In the case where the <code>deriv</code> parameter is true, the equation is <code>x * (1 - x)</code>. In your version you are using <code>sigmoid(x) * (1 - sigmo...
javascript|python|numpy|neural-network|mathjs
0
356,631
44,388,726
Simple one dimension array of float with numpy
<p>I want to make a simple one-dimensional array with numpy.</p> <pre><code>import numpy as np arr = np.array() # how do I initialize a float array? np.append(arr, "3453.2") np.append(arr, "1321.3") np.append(arr, "2003.6") </code></pre> <p>I have tried <code>np.zeros()</code>, <code>np.ones()</code>, <code>np.empt...
<p>Array from list of floats:</p> <pre><code>arr = np.array([1., 2., 3.]) </code></pre> <p>Empty array:</p> <pre><code>arr = np.empty(shape=()) print(arr.shape) # () </code></pre> <p>Empty 1d-array:</p> <pre><code>arr = np.empty(shape(1,)) print(arr.shape) # (1,) </code></pre> <p>It's unclear what you really wa...
python|arrays|numpy
4
356,632
44,782,200
Tensorflow(IOS) - compiled binary size
<p>i have been trying tensor-flow over the last few days, however im obtaining the following compile sizes for "libtensorflow-core.a" when using "compile_ios_tensorflow.sh" with options "-Os" or "-O3". </p> <p>I have obtained the following for arm64 and armv7: arm64 - 97.4 MB armv7 - 99,3 MB</p> <p>Edit: I know that ...
<p>You should find that the sizes that you are seeing are just what you see on your local disk. The library files you see on your local disk don't reflect the size of what's added to the final binary. May I suggest that you try and build the app and look at the package size.</p> <p>Please see this github issue thread ...
ios|tensorflow
0
356,633
44,631,259
Line-Line intersection in Python with numpy
<p>I have a relatively simple question, I know the answer but I can't seem to find the right implementation using Python and Numpy. The idea is, I have two lines and I need to find the virtual intersection point (I used the example from <a href="https://www.youtube.com/watch?v=kCyoaidiXAU&amp;t=313s" rel="nofollow nore...
<p>The line through A0 and A1 has parametric equation <code>(1-t)*A0 + t*A1</code>, where t is the parameter. The line through B0 and B1 has parametric equation <code>(1-s)*A0 + s*A1</code>, where s is the parameter. Setting these equal, we get the system <code>(A1-A0)t + (B0-B1)s == B0-A0</code>. So, the right hand s...
python|numpy|vector
6
356,634
44,376,313
Using the format function to name columns
<p>The line of code below takes columns that represent each months total sales and averages the sales by quarter.</p> <pre><code>mdf = tdf[sel_cols].resample('3M',axis=1).mean() </code></pre> <p>What I need to do is title the columns with a str (cannot use pandas .Period function).</p> <p>I attempting to use the fol...
<p>The easiest way is to perform the quarter function on the datetime list like so</p> <pre><code>mdf = tdf[sel_cols].resample('3M',axis=1).mean().rename(columns=lambda x: '{:}q{:}'.format(x.year,x.quarter)) </code></pre>
python|pandas|numpy
0
356,635
44,449,108
Pandas read_excel: only read first few lines
<p>Using pandas read_excel on about 100 excel files - some are large - I want to read the first few lines of each (header and first few rows of data).</p> <p>This doesn't work but illustrates the goal (example reading 10 data rows):</p> <pre><code>workbook_dataframe = pd.read_excel(workbook_filename, nrows = 10) </co...
<p>This isn't currently supported although looking at the code it doesn't look like it should be too hard. You can open an issue on the Github project page at <a href="https://github.com/pandas-dev/pandas/issues" rel="nofollow noreferrer">https://github.com/pandas-dev/pandas/issues</a>.</p>
pandas
1
356,636
60,920,163
How to scrape page with POST method with Python?
<p>I want to join together some pages that report Starlink constellation passages. As they are now, I need to access each single page manually, and cannot filter out according to time and visibility.</p> <p>The base page is <a href="https://heavens-above.com/StarlinkLaunchPasses.aspx?lat=50&amp;lng=12&amp;loc=Somewhere...
<p>You don't need to use <code>Scrapy</code> or <code>Selenium</code> for such a single page.</p> <p>You can achieve your target using <code>requests</code> , <code>bs4</code> and <code>pandas</code>.</p> <p>Now, Let's put the plan:</p> <hr> <p><strong>1</strong>. We will check the <a href="https://developer.mozill...
python|pandas|web-scraping|beautifulsoup
3
356,637
60,943,400
When I select multiple row names using multchoice (easygui) it is unclear how to send the entire rows to the same csv (append). Singles work well
<pre><code>import pandas as pd from easygui import * df = pd.read_csv('allfoods.csv') choices = ["Egg", "Milk" ] choice = multchoicebox(msg, title, choices) if choice == "Egg" : df2 = df[df.Food=="Egg"].head() print (df2) df2.to_csv('outfile.csv', encoding='utf-8', index=False, header=False) if choice ==...
<p>Looks like the change below fixed it. </p> <p>choice = multchoicebox(msg, title, choices) print ("Reply was: %s" % str(choice))</p> <p>for i in range(len(choice)):</p> <p>print (choice[i]) df1 = df[df.Food==choice[i]].head() print (df1)</p> <p>df1.to_csv('outfile.csv', encoding='utf-8', index=False, mode='a...
python|pandas|csv|dataframe|easygui
0
356,638
61,174,443
Split a dataframe into two but knowing already one
<p>I have a <code>dataframe</code> with one column called "label", which represents a binary feature [0,1]. The dataframe is imbalanced, with more labels 0 than 1s, therefore, to build a good estimator, I want to split the data into training and testing subsets, where the training subset has to be well balanced. I coul...
<p>I actually solved the problem...</p> <p>It was in the definition of train_class1 and train_class0, that I changed to:</p> <pre><code>train_class1=dataframe[dataframe["label"]==1].sample(len(dataframe[dataframe["label"]==0])*80//100) train_class0=dataframe[dataframe["label"]==0].sample(len(dataframe[dataframe["labe...
python|pandas|dataframe|coding-style
0
356,639
61,047,716
Does Tensorflow use specific image preprocessing normalization for each keras.application network?
<p>I'm trying to understand what kind of image preprocessing is required when using one of the base networks provided by keras.application whith tensorflow compat.v1 module</p> <p>In particular, I'm interested about the functions that converts each pixel channel value in the range [-1,1] or similar. I have digged in t...
<p>Tensorflow provides the preprocessing function for models in keras.applications, called <code>preprocess_input</code>. For example, an image can be preprocessed for InceptionV3 using <code>tf.keras.applications.inception_v3.preprocess_input</code>.</p>
python|tensorflow|tf.keras
0
356,640
61,153,529
Replace value in dataframe on condition with a different type in python
<p>I'm trying to replace values in my dataframe lower than 5.5 with 'insufficient' and higher than 5.5 with 'sufficient' using the following code:</p> <pre><code>import numpy as np df['test'] = np.where(df['grade'] &gt; 5.5, 'sufficient', 'insufficient') </code></pre> <p>This gives me the following error: <code>Typ...
<p>Check <code>df['grade']</code> include string type values. Or, try <code>df['grade'].astype(float) &gt; 5.5</code></p>
python|pandas|numpy
0
356,641
61,058,965
Plot dataframe entries using if statement
<p>I have a dataframe that looks like this:</p> <pre><code> Rank Name Pop_2019 Pop_2018 Change latitude longitude TC Risk 0 1 Tokyo 37393129 37435191 -0.0011 35.682839 139.759455 1.0 1 2 Delhi 30290936 29399141 0.0303 28.651718 77.221939 0.0 2 3 Shan...
<p>I think you just need boolean indexing and plot:</p> <pre><code>ax = plt.axes(projection=ccrs.PlateCarree()) ax.stock_img() plot_data = data[data['TC Risk']==1] ax.scatter(plot_data['longitude'], plot_data['latitude'], transform=ccrs.Geodetic()) </code></pre>
python|pandas|dataframe|cartopy
1
356,642
61,119,553
Self added text to columns based on column index in python
<p>Input Table:<a href="https://i.stack.imgur.com/VNmYh.png" rel="nofollow noreferrer">Input Table</a></p> <p>Desired Output : <a href="https://i.stack.imgur.com/uQcM8.png" rel="nofollow noreferrer">Output</a></p> <p>I want to add 'A,B,C.....' in columns as you are seeing in output. It should be governed from no. of co...
<p>In order to get the alphabet you can use <code>string</code> library:</p> <pre><code>import string chars = list(string.ascii_uppercase) </code></pre> <p>I don't which is the format of your input file. Let's assume that you have loaded it in someway and organized it with columns. For example if your input file is ...
python|python-3.x|pandas
1
356,643
60,962,461
Optimize time iteration in python for encoding labels
<p>I have these columns in a python's dataframe, named admission:</p> <pre><code>Patient ID, Regular ward, Semi-intensive, Intensive 1 0 0 0 2 1 0 0 3 0 1 0 4 0 1 ...
<pre><code>admission_copy = admission.copy() admission_copy["Semi-intensive"] = admission_copy["Semi-intensive"]*2 admission_copy["Intensive"] = admission_copy["Intensive"]*3 df["Admission type"] = admission_copy.sum(axis=1) </code></pre> <p>This is assuming that there are no patients with two types of admission types...
python|pandas|dataframe
2
356,644
61,172,273
efficient per column matrix indexing in numpy
<p>I have two matrices of the same size, A, B. I want to use the columns of B to acsses the columns of A, on a per column basis. For example,</p> <pre><code>A = np.array([[1, 4, 7], [2, 5, 8], [3, 6, 9]]) </code></pre> <p>and </p> <pre><code>B = np.array([[0, 0, 2], [1, 2, 1...
<p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing" rel="nofollow noreferrer">advanced indexing</a>:</p> <pre><code>A[B, np.arange(A.shape[0])] array([[1, 4, 9], [2, 6, 8], [3, 5, 7]]) </code></pre> <p>Or with <a href="https://docs.scipy.org/doc/nu...
python|numpy
3
356,645
61,043,320
missing value conditions Pandas in a function
<p>I would like a function where if the area column has missing values (like NULL in SQL) the result is 'A' in the target 'wanted' variable.</p> <p>I'm confused about use of None, isnull(), np.nan concepts in Python </p> <pre><code> raw_data = {'area': ['S','W',np.nan,np.nan], 'wanted': [np.nan,np.nan,'A','A']} df = ...
<p><code>np.nan</code> is not equal to <code>None</code> , <a href="https://stackoverflow.com/questions/10034149/why-is-nan-not-equal-to-nan">infact <code>NaN</code> isnot equal to <code>NaN</code> as well</a> (check <code>np.nan == None</code>) , hence you can utilize <code>pd.isna()</code> in your if condition:</p> ...
python|pandas|function|missing-data
3
356,646
61,161,072
optimizing vectorized operations made by sections in NumPy
<p>Long story short, I need to make vector operations over a 2D matrix with the values of the matrix itself for thousands of iterations, but for reasons I explain below, I need to do it in multiple sections, and I want to know the best way to do it by still getting the best possible performance and readibility.</p> <p...
<p>This is a kind of problem where one can really benefit from using <a href="http://numba.pydata.org/" rel="nofollow noreferrer">numba</a>. For the setup below, I get almost twice the speed of the <code>numpy</code> solution without sacrificing readability.</p> <pre><code>import numpy as np from numba import jit X =...
python|python-3.x|numpy|vectorization
2
356,647
60,999,430
pandas: apply filters taking into account timestamp
<p>I have the following test data:</p> <pre><code>import pandas as pd import datetime data = {'date': ['2014-01-01', '2014-01-02', '2014-01-03', '2014-01-04', '2014-01-05', '2014-01-06', '2014-01-07'], 'id': [1, 2, 2, 3, 4, 4, 5], 'name': ['Darren', 'Sabrina', 'Steve', 'Sean', 'Ray', 'Stef', 'Dany']} data = pd.D...
<p>This will work for <strong>spark2.4</strong>(<code>array_distinct</code> only in <strong>2.4</strong>). I used the <strong>DataFrame</strong> you provided, and <strong>spark inferred</strong> the column date to be of type <code>TimestampType</code>. For my spark code to work, the column date <strong>has to be of typ...
python|pandas|datetime|pyspark|timestamp
1
356,648
60,936,937
Pandas ExcelFile sheet_names returns empty list
<p>As the subject indicates, I'm creating an ExcelFile object from a raw xlsx file on my github and when I call the <code>.sheet_names</code> attribute an empty list is returned. There are two sheet names, "Trips" and "Description".</p> <pre><code>ef = pd.ExcelFile("https://github.com/j-on-son/Data/blob/master/ISyE380...
<p>the issue here is your source file is defective, </p> <p>if you use <code>openpyxl</code></p> <pre><code>import openpyxl openpyxl.load(("https://github.com/j-on-son/Data/blob/master/ISyE3803/Relay%20Bikes/Relay%20Bikes/Relay%20Trips.xlsx?raw=true") </code></pre> <p>you'll rightly get an error :</p> <pre><code>...
python|pandas
2
356,649
60,993,781
How do i check that the unique values of a column exists in another column in dataframe?
<p>I have a dataframe like this : </p> <pre><code> A= [ ID COL1 COL2 23 AA BB 23 AA AA 23 AA DD 23 BB BB 23 BB AA 23 BB DD 23 CC BB 23 CC AA 24 AA BB ] </code></pre> <p>What i want to is to check that the unique value of col1 exis...
<p>You just want to check whether a cell value exists in a container: <code>isin</code> is the way to go. But as you want to process id by ID, you also need a groupby:</p> <pre><code>df['check'] = df.groupby(['ID', 'COL1'], group_keys=False ).apply(lambda x: x['COL1'].isin(x['COL2'])) </code><...
python|pandas|dataframe
3
356,650
60,794,981
How can I put into a 2D array a list of binary string
<p>I have a binary list of string numbers as following:</p> <pre><code>['0b111', '0b1110011', '0b1110100', '0b11101001', '0b1100111', '0b1100001', '0b1101110', '0b1101111'] </code></pre> <p>And I would like to put this list into a 2D array of integers as following:</p> <pre><code>array([[0, 0, 0, 0, 0, 1, 1, ...
<p>You can use the numpy <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.unpackbits.html#numpy.unpackbits" rel="nofollow noreferrer">unpackbits</a> function to help.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np conv_bin = ['0b111', '0b1110011', '0b1...
python|numpy
2
356,651
61,141,859
How to get percentage contribution for each group in df having MultiIndex in pandas?
<p>I have a df as below:</p> <p>year and Continent are indexes. hydro_total is a column.</p> <p><a href="https://i.stack.imgur.com/8wb1e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8wb1e.png" alt="df info"></a></p> <p>I want to add a column that will have a percentage of contribution of the co...
<p>If I understand you correctly:</p> <pre><code>df['contribution'] = df.groupby(level=0)['hydro_total'] \ .transform(lambda g: g / g.sum()) * 100 </code></pre> <p>Result:</p> <pre><code> hydro_total contribution 1971 Africa 1861980.0 2.049212 America 44127920.0 ...
python|pandas|numpy|dataframe
1
356,652
60,952,332
python: Arrange in pandas dataframe
<p>I extract the data from a webpage but would like to arrange it into the pandas dataframe table.</p> <pre><code>finviz = requests.get('https://finviz.com/screener.ashx?v=152&amp;o=ticker&amp;c=0,1,2,3,4,5,6,7,10,11,12,14,16,17,19,21,22,23,24,25,31,32,33,38,41,48,65,66,67&amp;r=1') finz = html.fromstring(finviz.conte...
<p>Pandas has a function to parse HTML: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_html.html" rel="nofollow noreferrer"><code>pd.read_html</code></a></p> <p>You can try the following:</p> <pre><code># Modules import pandas as pd import requests # HTML content finviz = requests.ge...
python|pandas
0
356,653
60,832,450
Python - Group by > sample from every group
<p>I have a DataFrame with over 40.000 rows, where a certain column denotes the group membership. There are eight groups. I would like to have a smaller DataFrame, where I sample an <em>x</em> number from each group.</p> <pre><code>allthedata.groupby("groupvariable", group_keys=False).apply(lambda group_df: group_df.s...
<p>Think in this case a for loop is necessary:</p> <pre><code>groups = ["groupvariable", "groupvariable2", "groupvariable3" ...] sample_sizes = [100, 40, 10, ...] # initialise list of dataframes samples to concatenate samples = [] for group, sample_size in zip(groups, sample_sizes): samples.append(allth...
python|pandas-groupby
1
356,654
60,982,530
ValueError: Tensor("cnn/conv2d/kernel:0", shape=(), dtype=resource) must be from the same graph as Tensor("Placeholder:0", shape=(), dtype=variant)
<p>I am a newer in Deep Learning and TFF. I need to use a CNN to classify images from EMNIST. And I see the tutorials on GitHub named Federated Learning for Image Classification. I create a Network named CNN, and then I use forward_pass function to instance a cnn model to calculate the predictions. But TFF need to pass...
<p>For this use case it might be easier, rather than subclassing a <code>tff.learning.Model</code> directly, to write a <code>tf.keras.Model</code> and use TFF's <a href="https://www.tensorflow.org/federated/api_docs/python/tff/learning/from_keras_model" rel="nofollow noreferrer">utilities</a> to convert this to a <cod...
tensorflow|keras|deep-learning|conv-neural-network|tensorflow-federated
1
356,655
61,166,216
Not compile with GPU support in detectron2
<p><a href="https://i.stack.imgur.com/RSlPV.png" rel="nofollow noreferrer">enter image description here</a></p> <p>Detectron2 ran faster- RCNN when the error, from the error, should be the network RPN part caused the error.</p> <p>The GPU should be running because the backbone part did not report an error.</p> <p>Ho...
<p>The reason for this error is the server cuda version with pytorch</p> <p>Cuda version mismatches, such as between 10.1 and 10.0. So you should check whether the pytorch cuda version is the same as the machine cuda version</p>
pytorch
0
356,656
61,119,474
How to get the value of tensor in tf2.0?
<pre><code>IMAGE_FEATURE_MAP = { 'image/filename': tf.io.FixedLenFeature([], tf.string), 'image/encoded': tf.io.FixedLenFeature([], tf.string), 'image/object/bbox/xmin': tf.io.VarLenFeature(tf.float32), 'image/object/bbox/ymin': tf.io.VarLenFeature(tf.float32), 'image/object/bbox/xmax': tf.io.VarLen...
<p>There's no <code>print</code> in the code you posted. But I believe iterating through the dataset should work:</p> <pre><code>def main(): ds = load_tfrecord_dataset('../data/facemask2020_train.tfrecord', '../data/mask2020.names', size=416) for r in ds: print(r['image/...
python|tensorflow2.0
0
356,657
60,786,514
How to load a Pandas DataFrame from a csv/tsv as factorize category type?
<p>I have a huge TSV (genomic) dataset (1GB size) which has 2,504 rows and 220,001 columns. (takes 1h 11min 4s to load with <code>pd.read_table("biallelic-only.raw")</code>.</p> <p>All the columns, but 5 of them, are categorical data, and I want to convert them to factorize category.</p> <p>With small samples, this c...
<p>Read the data as categorical and specify a converter for the <em>exception</em> columns, for example, assuming a toy file named <code>'data.csv'</code> with the following data:</p> <pre><code>name type cost AB B 1 CV G 4 54 B 31 AB B 2 </code></pre> <p>You could do:</p> <pre...
python|pandas|csv|dataframe
2
356,658
60,766,199
Pandas rolling returns NaN when infinity values are involved
<p>When using <code>rolling</code> on a series that contains <code>inf</code> values the result contains <code>NaN</code> even if the operation is well defined, like <code>min</code> or <code>max</code>. For example:</p> <pre><code>import numpy as np import pandas as pd s = pd.Series([1, 2, 3, np.inf, 5, 6]) print(s....
<p><code>np.inf</code> is explicitly converted to <code>np.NaN</code> in <a href="https://github.com/pandas-dev/pandas/blob/v1.0.3/pandas/core/window/rolling.py#L276-L279" rel="nofollow noreferrer">pandas/core/window/rolling.py</a></p> <pre><code># Convert inf to nan for C funcs inf = np.isinf(values) if inf.any(): ...
python|python-3.x|pandas
5
356,659
61,084,839
Tensorflow/keras error: ValueError: Error when checking input: expected lstm_input to have 3 dimensions, but got array with shape (4012, 42)
<p>I have a pandas dataframe that is being made by a train_test_split called x_train with 4012 rows all the values in the dataframe are either int's or floats (after train/test split) and 42 columns (after train/test split). I am trying to train a recursive neural network with LSTM cells, but my program keeps giving me...
<p>The problem is that you are trying to feed 2 dimensional array for the model, but it is expecting 3 dimensional array. Instead of reshaping Dataframe convert it to array and then reshape according to the modified code below.</p> <pre><code>df = pd.read_csv("data.csv") x = df.loc[:, df.columns != 'result'] y = df....
python|pandas|tensorflow|keras|lstm
2
356,660
60,973,196
How to deploy a trigger word detection with tensorflow
<p>I'm working on the "trigger word detection" model, and I decided to deploy the model to my phone.</p> <p>The input shape of the model is <code>(None, 5511, 101)</code>. The output shape is <code>(None, 1375, 1)</code>.</p> <p>But in a real deployed App, the model can't get the 5511 timesteps all at once, instead t...
<p>This problem can be solved by making the timesteps axis dynamic. In other words, when you define the model, the number of timesteps should be set to <code>None</code>. Here is an example illustrating how it would work for a simplified version of your model:</p> <pre><code>from keras.layers import GRU, Input, Conv1D...
tensorflow|keras|lstm|recurrent-neural-network
2
356,661
61,100,113
Check to see if a combination of bools exists in an array?
<p>I have a multidimensional array of strings that looks similar to the following. The first column is the ID, column 2-4 are three different variables:</p> <pre><code> #ID Var1 Var2 Var3 comparison = [['1' 'False' 'False' 'True'] ['2' 'False' 'True' 'False'] ['3' 'Fals...
<p>try this code.</p> <pre><code>import numpy as np comparison = [['1', 'False', 'True', 'True'], ['2', 'False', 'True', 'False'], ['3', 'True', 'True', 'True'], ['100', 'False', 'True', 'False']] true_vars = np.array([]) for idx in comparison: if ((idx[1] == 'True') and (idx[2] == '...
python|arrays|numpy|loops
2
356,662
60,797,447
UserWarning: Update your `Model` call to the Keras 2 API: `Model(inputs=Tensor("in..., outputs=Tensor("co...)`
<p>I am trying to train an unet model and my main program is smth like this:</p> <pre><code>data_gen_args = dict(rotation_range=0.2, width_shift_range=0.05, height_shift_range=0.05, shear_range=0.05, zoom_range=0.05, horizontal_flip=True, ...
<p>It seems that your model is created using <code>Keras 1</code> <a href="http://faroit.com/keras-docs/1.2.2/models/model/" rel="nofollow noreferrer">syntax</a>:</p> <pre><code>model = Model(input=my_input, output=my_output) </code></pre> <p>instead of <code>Keras 2</code> <a href="https://keras.io/models/model/" re...
python|tensorflow|keras|deep-learning
0
356,663
60,939,317
Turn denormalized json dataframe column into multiple columns
<p>I am having trouble to parse a csv file formatted like this:</p> <pre><code>+--------------+------------------------------------------------------------------+ | event_type | event_properties | +--------------+--------------------------------------------------------...
<p>Here's my code that does exactly what you want :</p> <pre><code>df = pd.DataFrame([ ["event_type_1",'{"event_type_1_property_1": "a","event_type_1_property_2": "b"}'], ["event_type_2",'{"event_type_2_property_1": "1", "event_type_1_property_2": "2"}'], ["event_type_3",'{"event_type_1_property_1": "c", "event_type_1...
python|pandas
0
356,664
60,910,269
How to construct a matrix that contains all pairs of rows of a matrix in tensorflow
<p>I need to construct a matrix <code>z</code> that would contain combinations of pairs of rows of a matrix <code>x</code>.</p> <pre><code>x = tf.constant([[1, 3], [2, 4], [0, 2], [0, 1]], dtype=tf.int32) z=[[[1,2], [1,0], [1,0], [2,0], [2,0], [0,...
<p>Here is a way to do that without a loop:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf x = tf.constant([[1, 3], [2, 4], [0, 2], [0, 1]], dtype=tf.int32) # Number of rows n = tf.shape(x)[0] # Grid of indices ri = tf.range(0, n - 1) rj ...
python|tensorflow
2
356,665
60,843,156
Delete values over the diagonal in a matrix with python
<p>I have the next problem with a matrix in python and numpy</p> <p>given this matrix</p> <pre><code> Cmpd1 Cmpd2 Cmpd3 Cmpd4 Cmpd1 1 0.32 0.77 0.45 Cmpd2 0.32 1 0.14 0.73 Cmpd3 0.77 0.14 1 0.29 Cmpd4 0.45 0.73 0.29 1 </code></pre> <p>i want to obtain this:</p> <pre...
<p>Use <code>np.tril(a)</code> to extract the lower triangular matrix. Refer this : <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.tril.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/reference/generated/numpy.tril.html</a></p>
python|numpy|matrix
1
356,666
60,813,489
Numpy-thonic way to set elements given un-ordered input and corresponding IDs
<p>I have an array of values <code>a</code>, and an array of unique IDs <code>ids</code> of the same length of a.</p> <p>I then have a smaller array of values <code>v</code> and a corresponding array of IDs <code>v_ids</code> that must overwrite values of <code>a</code> where the IDs do match.</p> <h3>Small Example</...
<p>I am not sure about performance or efficency but you could just make a map of ids to values for both a and v. then update the main id map with the v_ids map.</p> <pre class="lang-py prettyprint-override"><code>a = [0,1,2,4,4,2,0,0] ids = [7,1,0,8,9,4,3,6] #unique ids v = [-1,-2] v_ids = [4,8] id_map = dict(zip(...
python|arrays|numpy
2
356,667
60,776,011
What am I doing wrong when trying to plot two numpy arrays?
<p>I'm attempting to plot: <code>x</code> and <code>y</code> values on a <code>ax.loglog</code> plot but am receiving the following error:</p> <p><code>ValueError: x and y must have same first dimension, but have shapes (4000,) and (1,)</code></p> <p>I have a list of numpy arrays called <code>holders</code>, where:</...
<p>instead of j[i] in the for-loop, use holders[i].</p> <p>j[i] is one single data point, since j is one numpy array in your list of arrays. To access the numpy array, you need holders[i].</p>
python-3.x|numpy|matplotlib|numpy-ndarray
1
356,668
61,006,383
pandas to_sql() wrongly increments most significant digit(MSD) of the index
<p>I have a Postgres table, with index ending at id 754238. But when insert a new data frame using pandas to_sql() command below. it increments the LSD, but also increments MSD <strong>8</strong>5423<strong>9</strong> </p> <blockquote> <p>df_transformed.to_sql(domain, db_local, schema='public',if_exists='append',ind...
<p>I fixed this issue, by manually aligning the index, but not sure why Pandas does this weird thing. Even in the latest version of pandas '1.0.3', I see this behaviour.</p> <pre><code>sql_get_max_id = f'select max({index_name}) as id from {table}' max_id = pd.read_sql(sql_get_max_id, db_local_otp)[index_name][0] new...
python|sql|pandas
0
356,669
61,104,277
Error when checking input: expected input_6 to have shape (80, 80, 1) but got array with shape (80, 80, 2400) in image segmentation
<p>I have a medical imaging dataset with a dimension of (80,80,2900), each image is 80*80. First I loaded the mat file of the data as follow:</p> <pre><code>data = loadmat('cardiac-dig.mat') images_LV = np.array (data['images_LV']) val_data_size = 500 valid_images = images_LV[:,:,:val_data_size] train_images = images...
<p>I found the solution. I wanted to post the answer to those may have the same issue:</p> <p>based on the shape of my dataset, (80,80,2900), I needed to change the dimension from 3 to 4. Also, it was necessary to reshape the dataset as follow: </p> <pre><code>***images = np.swapaxes(images, 0, 2) images = np.swapaxe...
python|tensorflow|keras|deep-learning|image-segmentation
0
356,670
61,134,046
Writing to a dataframe through a loop
<p>I have a dataframe with two columns, one called 'name' that is a string, and one called 'route' that is a Google polyline. I'm using the polyline library to decode the polyline into lat/long. I want to loop over each row to decode but it only seems to decode only the first row and write it to the rest of the created...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>DataFrame.apply</code></a> with function:</p> <pre><code>df = pd.DataFrame(activities) def decoder(name, route): try: return polyline.decode(route.replace('\\\\','\\'), ge...
python-3.x|pandas|loops
1
356,671
60,868,884
Python - Numpy - Converting a numpy array of hex strings to integers
<p>I have a numpy array of hex string (eg: ['9', 'A', 'B']) and want to convert them all to integers between 0 255. The only way I know how to do this is use a for loop and append a seperate numpy array. </p> <pre><code>import numpy as np hexArray = np.array(['9', 'A', 'B']) intArray = np.array([]) for value in hexA...
<p>A vectorized way with array's-view functionality -</p> <pre><code>In [65]: v = hexArray.view(np.uint8)[::4] In [66]: np.where(v&gt;64,v-55,v-48) Out[66]: array([ 9, 10, 11], dtype=uint8) </code></pre> <p><strong>Timings</strong></p> <p>Setup with given sample scaled-up by <code>1000x</code> -</p> <pre><code>In ...
python|numpy
4
356,672
61,104,096
Tensorflow inference using Java API extremely slow
<p>I downloaded the python3 example for DeepLabv3 inference which uses a pre-trained model. The runtime for the actual inference is about 19 seconds on the CPU I'm using. Tensorflow was installes with pip:</p> <p><code>pip install intel-tensorflow</code></p> <p>This is the code from the colab Jupyter notebook:</p> <...
<p>For the inference time, did you tried to run it a second time using the same session? TensorFlow can initialize some resources lazily on the first run, so you might want to keep that same session available for all other inference runs as well instead of creating a new one for each of them.</p> <p>A common practice ...
java|python|tensorflow|tensorflow2.0|deeplab
1
356,673
61,073,857
NumPy: How to retrieve the indices of the maximum values in a multidimensional array
<p>With the following array:</p> <pre><code>In [103]: da Out[103]: array([[[ 6, 22, 3], [ 4, 9, 20], [21, 16, 0]], [[ 2, 25, 11], [ 5, 17, 18], [23, 13, 7]], [[10, 14, 26], ...
<p>The <code>axis</code> argument allows you to specify a single axis of operation:</p> <pre><code>i0 = np.argmax(da, axis=0) </code></pre> <p>This means that <code>i0</code> is a <code>(3, 3)</code> array containing the index of the maximum for each corresponding <code>i1</code>, <code>i2</code>. The maximum for any...
python|numpy|indexing
3
356,674
61,032,772
Python Pandas Merge or Join of DataFrame Column wise not adding as row after each dataframe
<p>I have four data frames with different different data (assume the column may be same in some cases for each of this data frame) .</p> <p>data frame <code>df0 df1 df3 df4</code></p> <p>df0</p> <pre><code>amountC1 directionC1 index_priceC1 instrument_nameC1 ivC1 priceC1 timestampC1 trade_idC1 trade_seqC1...
<p>In addition to luc's answer, you can also merge on the index of each. For example:</p> <p>Create a sample dataframe df1</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df1 = pd.DataFrame(columns=["c1","c1a","c1b"], data = [[1,2,3],[4,5,6],[7,8,9]]) print(df1) # | c1 | c1a | c1b | # |----|-...
python|pandas|dataframe|pandas-groupby
0
356,675
60,874,661
How to increase the accurancy of an image classifier?
<p>I made a model that can classify 82 number with a dataset of images (around 10500 images)<br> the dataset is in Two folders :<br> <strong>the first folder the train folder has 8000 images in 82 folders</strong><br> <strong>the Second folder the test folder has 2000 images in 82 folders</strong><br> I have tested the...
<p>Since your model now is handling a multi-class problem, a few changes need to be made:</p> <ul> <li>The loss should be <code>categorical_crossentropy</code> rather than <code>binary_crossentropy</code></li> <li>The final activation function should be softmax rather than sigmoid</li> <li>There should be 82 neurons i...
python|tensorflow|machine-learning|keras|deep-learning
1
356,676
61,095,379
Converting json to pandas dataframe with weather datasets
<p>How can we convert this to dataframes? I have tried multiple ways on how it can be achived, i have tried with json file on w3school but it is working correctly, i am new with python, any recommendations on this? Json format is </p> <pre><code>[ { "id": 14256, "city": { "id": { "$numberLong":...
<p>You can use json_normalize() as described <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html" rel="nofollow noreferrer">here</a>:</p> <pre><code>import pandas as pd d = [ { "id": 14256, "city": { "id": { "$numberLong": "14256" }, "name...
python|json|pandas
1
356,677
61,062,180
Cannot replace text in dataframe column names
<p>See code. Both "data" and "names" are panda dataFrames. "Names" holds the names for the columns. It is both strings and years as numbers (example '2020new' and '2020'). When I inspect it it looks fine. But when I run the first line (apply it to the columns of "data") it adds '.0' to all fields from name that could b...
<p>This works (finally). There was "float NaN" which was hard to deal with (you have to find the specific type of NaN it is since there are several types... stupid. So by casting it to int I get rid of the added ".0" which I don't know why it added in the first place, and then cast to string (needed for easier comparis...
python|pandas
0
356,678
61,007,449
Plot graphs from pandas with a url somewhere on the plot
<p>I'm trying to find a way to plot many graphs in python with a clickable url corresponding to each graph (could be in the title?) At the minute I'm working with pandas dataframes, using below code:</p> <pre><code>with PdfPages("output.pdf") as pdf: for df in filtered_dfs: # get url: my_url = df['url'...
<p>You should definitely take a look at <a href="https://plotly.com/python/" rel="nofollow noreferrer">plotly graphs</a> and <a href="https://dash.plotly.com/" rel="nofollow noreferrer">plotly dash</a> that allows you to make interoperable pages all from Python.</p> <p>Dash is the API that allows you to create HTML DOM...
python|pandas|matplotlib|pdfpages
0
356,679
61,107,525
is there a way in python to subtract timestamps?
<p>I have dataframe with two cols. Both of them are timestamp however one goes all the way to fff where other to the seconds. is there a way to get difference in minutes and seconds?</p> <pre><code>col1 col2 2:21:40.756 2:21:41 2:22:30.343 2:22:31 2:24:43.342 2:24:44 i have tried following: col...
<p>You can use, as @CoryKramer said, .sub:</p> <p>In minutes:</p> <pre><code>col1.sub(col2).dt.seconds/60 0 1439.983333 1 1439.983333 2 1439.983333 dtype: float64 </code></pre> <p>If you want more precise, as microseconds:</p> <pre><code>col1.sub(col2).dt.microseconds 0 756000 1 343000 2 342000 ...
python|pandas|datetime|time|series
0
356,680
61,026,862
why "NumPy operations convert Tensors to numpy arrays automatically"? how does this feature been implemented?
<p>Reading TensorFlow docs: <a href="https://www.tensorflow.org/tutorials/customization/basics#numpy_compatibility" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/customization/basics#numpy_compatibility</a></p> <pre class="lang-py prettyprint-override"><code>import numpy as np ndarray = np.ones([3, 3...
<p>TensorFlow’s API revolves around tensors, which flow from operation to operation—hence the name TensorFlow. A tensor is usually a multidimensional array (exactly like a NumPy ndarray ), but it can also hold a scalar (a simple value, such as 42 ). These tensors will be important when we create custom cost functions, ...
python|numpy|tensorflow
-1
356,681
60,773,067
split string no delimiter with limitative field names and content
<p>I have a dataframe with bankmutations.<br> The dataframe contains a description column. In this column there are limitative field names with their content. It looks like: </p> <pre><code>AAm.loc[0, ’OmsBank'] =&gt; ‘ fieldname1: content fn1 fieldname3: content fn3 ‘ AAm.loc[1, ’OmsBank'] =&gt; ‘ fieldname...
<p>I picked up my problem and discovered regex. You can search for all kind of (text)patterns. My pattern was ' fieldname: field value secondfieldname: second field value'. You can put these blocks in brackets and refer to them with group(number), where 0 is whole search string, 1 is first group etc.</p> <p>One of the...
python|pandas|split
0
356,682
60,881,892
drop the row only if all columns contains 0
<p>I am trying to drop rows that have 0 for all 3 columns, i tried using these codes, but it dropped all the rows that have 0 in either one of the 3 columns instead.</p> <pre><code>indexNames = news[ news['contain1']&amp;news['contain2'] &amp;news['contain3']== 0 ].index news.drop(indexNames , inplace=True) </code></p...
<p>First filter by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ne.html" rel="nofollow noreferrer"><code>DataFrame.ne</code></a> for not equal <code>0</code> and then get rows with at least one match - so removed only <code>0</code> rows by <a href="http://pandas.pydata.org/pandas...
python|pandas
2
356,683
60,857,436
Calculating moving median within group
<p>I want to perform rolling median on price column over 4 days back, data will be groupped by date. So basically I want to take prices for a given day and all prices for 4 days back and calculate median out of these values.</p> <p>Here are the sample data:</p> <pre><code>id date price 1637027 2020-01-21 ...
<p>You can use <code>rolling</code> with a frequency window of 5 days to get today and last 4 days, then <code>drop_duplicates</code> to keep the last row per day. First create a <code>copy</code> (if you want to keep the original one), <code>sort_values</code> per date and ensure the date column is datetime</p> <pre>...
python|pandas|pandas-groupby|median|rolling-computation
2
356,684
60,813,157
Remove all occurrences of double quotes from text (python csv)
<p>I have a text file that I obtained by converting a dataframe using <code>csv</code> module in Python as follows:</p> <pre><code>df.to_csv(r'listfinal.txt', header=None, index=None, sep=' ', mode='a') </code></pre> <p>The text file has double quotes around many entries, i.e,</p> <pre><code>Circles "Post Malone" "Y...
<p>Have you tried:</p> <pre><code>df.to_csv(r'listfinal.txt', header=None, index=None, sep=' ', mode='a', quoting=csv.QUOTE_NONE) </code></pre> <p>you could also use csv.QUOTE_MINIMAL instead</p>
python|pandas|csv|dataframe|text
0
356,685
60,873,395
Fast Way to Perform Array Computation in Python
<p>I have an image that I want to perform some calculations on. The image pixels will be represented as <code>f(x, y)</code> where <code>x</code> is the column number and <code>y</code> is the row number of each pixel. I want to perform a calculation using the following formula:</p> <p><a href="https://i.stack.imgur.c...
<p>Since you specifically convert the input <code>f</code> to a numpy array, I am assuming you want to use numpy. In that case, the allocation of <code>D_sub_h</code> needs to change from a list to an array:</p> <pre><code>D_sub_h = np.empty_like(f) </code></pre> <p>If we assume that everything outside your array is...
python|arrays|python-3.x|function|numpy
1
356,686
61,167,529
2D array with 2D arrays on the diagonal
<p>I have matrix </p> <pre><code>J_plus = [[ 0.0609698 -0.00022921 -0.00022921 ... -0.00022921 -0.00022921 -0.00022921] [-0.00022921 0.0609698 -0.00022921 ... -0.00022921 -0.00022921 -0.00022921] [-0.00022921 -0.00022921 0.0609698 ... -0.00022921 -0.00022921 -0.00022921] ... [-0.0...
<p>The easiest way: <a href="https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.linalg.block_diag.html" rel="nofollow noreferrer"><code>scipy.linalg.block_diag</code></a>:</p> <pre><code>linalg.block_diag(J_plus, J_minus) </code></pre> <p>For a numpy based approach, we could use <a href="https://docs.s...
python-3.x|numpy|matrix|scipy
1
356,687
61,069,779
Using a boolean Mask on large numpy array is very slow
<p>I have a performance issue when coding with python. let's say I have 2 very large arrays (Nx2) of strings say with N = 12,000,000, and two variables label_a and label_b which are also strings. Here is the following code:</p> <pre><code>import numpy as np import time indices = np.array([np.random.choice(np.arange(5...
<p>As indicated in the comments, computing the values of the indices you're after only once, and combining them only once would save time.</p> <p>(I've also changed the way of timing, just for brevity - the results are the same)</p> <pre><code>import numpy as np from timeit import timeit r = 5000 n = 10000000 indic...
python|performance|numpy|boolean|masking
1
356,688
61,090,014
Query dataframe of sports data by winner/loser name, and get tables of aggregate stats per-player?
<p>I have a CSV dataset of tennis match results in winner, loser format that has similar structure to this one: <a href="https://www.kaggle.com/jordangoblet/atp-tour-20002016" rel="nofollow noreferrer">https://www.kaggle.com/jordangoblet/atp-tour-20002016</a></p> <p>I want to create another table that will show number...
<p><strong>You need to query the dataframe for player name occurring in either 'Winner' or Loser' column, to get <code>matches</code>, a dataframe of all matches involving that player. This is harder than at first glance - we can't just use a simple <code>df.groupby()</code>.</strong> Sorry for underestimating your que...
python|pandas|list|dictionary
2
356,689
60,927,080
How to check if a Dataframe contains a list or dictionary
<p>I have a dataframe :</p> <pre><code>col1 col2 col3 col4 A 11 [{'id':2}] {"price": 0.0} B 21 [{'id':3}] {"price": 2.0} C 31 [{'id':4}] {"price": 3.0} </code></pre> <p>I want to find out what all columns are of datatype 'list' and 'dictionary' and probably store the result ...
<p>IIUC,</p> <p>we can use <code>apply</code> and <code>literal_eval</code> from the ast standard library to build up a dictionary:</p> <p>for performance reasons, lets work with the first row of the data frame as <code>apply</code> is computationally quite heavy.</p> <pre><code>from ast import literal_eval data_dic...
python-3.x|pandas|list|dataframe|dictionary
2
356,690
71,702,219
Pytorch equivalent for keras Dense
<p>I'm trying to convert some code written with keras to pytorch. I'm trying to initialize multiple layers in the init function. The code to be converted is :</p> <pre><code>self.layers_li = [] for i in range(num_layers): self.layers_li.append(layers.Dense(input_dim, activation='relu')) </code></pre> <p>I think usin...
<p>Here is the most basic example of how you can achieve what you want:</p> <pre class="lang-py prettyprint-override"><code>import torch from torch import nn m = nn.Linear(20, 30) n = nn.ReLU() input = torch.randn(128, 20) output = m(input) output_activated = n(output) </code></pre> <p>So, you can actually have nonl...
keras|nlp|pytorch
0
356,691
71,457,512
How can I define a parameter from specific columns and rows from excel?
<p>I want to obtain a list of certain values from an excel file.</p> <p>I tried this:</p> <pre><code>import pandas as pd df = pd.read_excel('Data.xlsx') orders = df[['Order']].loc[[4,129]] print(orders) </code></pre> <p>I obtained this solution:</p> <pre><code> Order 4 18292839 129 83938292 </code></pre> <p...
<p>You can use <code>orders.values.tolist()</code> to convert <code>pd.Series</code> into <code>list</code>. More about converting <code>DataFrames</code> and <code>Series</code> into the <code>list</code> you can read <a href="https://note.nkmk.me/en/python-pandas-list/" rel="nofollow noreferrer">here.</a></p>
excel|pandas|list|dataframe|xlsx
0
356,692
71,752,192
Error: unable to use groupby to summarize table in Pandas
<p>I am trying to sum the elements in a df by column using Pandas, and I am obtaining an error. Here is the script Thank you very much!</p> <pre><code>from google.colab import files uploaded = files.upload() import pandas as pd import io df = pd.read_csv(io.BytesIO(uploaded['Book1.csv'])) print(df) df.groupby(['x']).su...
<p>Default separator for csv is <code>,</code>, you separator is <code>;</code>, so you should define it explicitly</p> <pre class="lang-py prettyprint-override"><code>df = pd.read_csv(io.BytesIO(uploaded['Book1.csv']), sep=';') </code></pre>
python|pandas|dataframe|pandas-groupby
0
356,693
71,728,301
wrong result shown in converting float to integer in pd
<p><img src="https://i.stack.imgur.com/26EKF.png" alt="pandas" /></p> <p>hi i want to ask why i convert to int but the result still remain as float64</p>
<p>As shown in the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.convert_dtypes.html" rel="nofollow noreferrer">pandas docs</a>, the method returns a new DataFrame. This means that you want to store the result in the variable <code>df_cleaned</code> to override the previous value:</p> <pre><cod...
pandas|integer
0
356,694
71,501,280
Removing rows from a pandas dataframe if a column contains a particular word alone
<p>I am working on a pandas dataframe from which i have to remove rows if it contains a particular word alone. For example,</p> <pre><code>df = pd.DataFrame({'team': ['Team 1', 'Team 1 abc', 'Team 2', 'Team 3', 'Team 2', 'Team 3'], 'Subject': ['Math', 'Science', 'Science',...
<p>Just use <code>!=</code> instead of <code>.str.contains</code>:</p> <pre><code>df = df[df[&quot;team&quot;] != &quot;Team 1&quot;] </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df team Subject points 1 Team 1 abc Science 8 2 Team 2 Science 10 3 Team 3 Math 6 4 ...
python|pandas
1
356,695
71,628,712
Difference of two Dataframes is not exact
<p>I am trying to get random values of dataframe DF1 and them storing them in a new variable DF2. I want to take difference to the remaining values will be not in origional dataframe DF1. I need to do this task without using sklearn library. I tried two ways to get random values and they are following: Method 1:</p> <p...
<p>You can use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html" rel="nofollow noreferrer"><code>train_test_split</code></a> from <code>sklearn</code>:</p> <pre><code># Python env: pip install sklearn # Conda env: conda install sklearn from sklearn.model_selection...
python|pandas|dataframe|numpy
0
356,696
71,620,529
Autoincrement indexing after groupby with pandas on the original table
<p>I cannot solve a very easy/simple problem in pandas. :(</p> <p>I have the following table:</p> <pre><code>df = pd.DataFrame(data=dict(a=[1, 1, 1,2, 2, 3,1], b=[&quot;A&quot;, &quot;A&quot;,&quot;B&quot;,&quot;A&quot;, &quot;B&quot;, &quot;A&quot;,&quot;A&quot;])) df Out[96]: a b 0 1 A 1 1 A 2 1 B 3 2 A...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.factorize.html" rel="nofollow noreferrer"><code>pd.factorize</code></a> after create a tuple from <code>(a, b)</code> columns:</p> <pre><code>df['c'] = pd.factorize(df[['a', 'b']].apply(tuple, axis=1))[0] + 1 print(df) # Output a b c 0 1 A 1 1...
python|pandas|pandas-groupby
2
356,697
71,465,978
Rolling Rows in pandas.DataFrame
<p>I have a <code>dataframe</code> that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">year</th> <th style="text-align: center;">month</th> <th style="text-align: center;">valueCounts</th> </tr> </thead> <tbody> <tr> <td style="text-align: cente...
<p>Assuming your dataframe are already sorted.</p> <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.shift.html" rel="nofollow noreferrer"><code>shift</code></a>:</p> <pre><code>df['valueCounts'] = df['valueCounts'].shift(-1) print(df) # Output year month valueCounts 0 2019 1 53.5...
pandas|dataframe
0
356,698
71,674,047
filling in the missing times using average for the values pythn
<p>I have this dataframe with some time missing (I want it to be every minute). Please see the sample below:</p> <pre><code>time = np.array([pd.to_datetime(&quot;2022-01-01 00:00:00&quot;),pd.to_datetime(&quot;2022-01-01 00:00:01&quot;),pd.to_datetime(&quot;2022-01-01 00:00:03&quot;), pd.to_datetime(&quot;2022-01-01 00...
<p>Create <code>DatetimeIndex</code> then add missing times by div.<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.asfreq.html" rel="nofollow noreferrer"><code>DataFrame.asfreq</code></a> and interpolate by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Dat...
python|pandas|dataframe|datetime|imputation
1
356,699
71,527,816
Slicing pandas DateTimeIndex with steps
<p>I often deal with pandas DataFrames with DateTimeIndexes, where I want to - for example - select only the parts where the hour of the index = 6. The only way I currently know how to do this is with reindexing:</p> <pre><code>df.reindex(pd.date_range(*df.index.to_series().agg([min, max]).apply(lambda ts: ts.replace(h...
<p>If your index is a DatetimeIndex, you can use:</p> <pre><code>&gt;&gt;&gt; df[df.index.hour == 6] val 2022-03-01 06:00:00 7 2022-03-02 06:00:00 31 2022-03-03 06:00:00 55 2022-03-04 06:00:00 79 2022-03-05 06:00:00 103 2022-03-06 06:00:00 127 2022-03-07 06:00:00 151 2022-03-08 06:00:00...
python|pandas|multi-index|datetimeindex
1