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
360,000
40,326,490
Why does tensorflow didn't accept np.float?
<p>I am using tensorflow to run a cnn deep learning program, but it failed? i have translated my input data 'images' to np.float32, but it still report dtype error:</p> <pre><code>E tensorflow/core/client/tensor_c_api.cc:485] You must feed a value for placeholder tensor 'Placeholder_2' with dtype float [[Node: Placeh...
<p>if it's failing here:</p> <pre><code>predictions = self.sess.run(self.y_conv, feed_dict={self.x: images}) </code></pre> <p>it's because you need to pass in a self.keep_prob</p>
numpy|tensorflow|type-conversion|placeholder
0
360,001
39,945,643
Adding values from a dataframe-A A.column1 by matching values in A.column2 to the B.column1 name of another dataframe B
<p>I have two dataframes (df) A and B. df A has a column called 'Symbol' with non-unique stock-ticker-symbols as values in random order and the corresponding amount of buy or sell quantities in another column called 'Shares'; it is indexed by non-negative integers. df B, indexed by dates in the same date-order as df A ...
<p>first of all, I highly suggest you to read <a href="https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples">how-to-make-good-reproducible-pandas-examples</a></p> <p>I think you could use pivot such has:</p> <pre><code>B = A.pivot('Date','Symbol','Shares') </code></pre> <p>Since...
python|pandas|join|dataframe
0
360,002
40,241,537
pandas split one column into multiple KeyError
<pre><code>df = age;"job";"marital";"education";"default";"housing";"loan";"contact";"month";"day_of_week";"duration";"campaign";"pdays";"previous";"poutcome";"emp.var.rate";"cons.price.idx";"cons.conf.idx";"euribor3m";"nr.employed";"y" 0 30;"blue-collar";"married";"basic.9y";"no";"ye... ...
<p>I think you missing <code>sep=';'</code> argument in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a>, because by default <code>sep=','</code>.</p> <p>But if need split first column by <code>;</code>, use <a href="http://pandas.pydata.org/...
python|pandas|split
3
360,003
39,961,716
Caching a dataset with examples of varied length
<p>My dataset is comprised of audio segments of between 5-180 seconds. The number of examples is small enough to allow caching it in memory, instead of reading from the disk over and over. Storing the data in a constant tensor / variable and using <code>tf.train.slice_input_producer</code> will allow me to cache the da...
<p>The more recent <a href="https://www.tensorflow.org/programmers_guide/datasets" rel="nofollow noreferrer"><code>tf.data</code></a> library provides a <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#cache" rel="nofollow noreferrer"><code>tf.data.Dataset.cache</code></a> method to cache an entire d...
tensorflow|tensorflow-datasets
2
360,004
39,735,068
Pandas crosstab, but with values from aggregation of third column
<p>Here is my problem:</p> <pre><code>df = pd.DataFrame({'A': ['one', 'one', 'two', 'two', 'one'] , 'B': ['Ar', 'Br', 'Cr', 'Ar','Ar'] , 'C': [1, 0, 0, 1,0 ]}) </code></pre> <p>I would like to generate something like output of <code>pd.crosstab</code> function, but values on the ...
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="noreferrer">pivot_table()</a> method, which uses <code>aggfunc='mean'</code> per-default:</p> <pre><code>In [46]: df.pivot_table(index='A', columns='B', values='C', fill_value=0) Out[46]: B Ar Br Cr A one ...
python|pandas|aggregate
9
360,005
39,796,277
Unable to evaluate dense tensor obtained from a complex sparse tensor in tensorflow
<p>I am unable to evaluate/print/run a dense tensor obtained from a complex sparse tensor in tensorflow library. I am currently using build #234 of tensorflow in macosx (cpu only).</p> <pre><code>import tensorflow as tf a = tf.SparseTensor(indices=[[0, 0, 0], [1, 2, 1]], values=[1.0+2j, 2.0], shape=[3, 4, 2]) b = tf...
<p>Looks like tf.sparse_tensor_to_dense does not support complex number yet. I have tried loss the +2j component, and it worked. I think the error dump was trying to tell you that sparse_tensor_to_dense don't support complex type, and list the type it support.</p>
tensorflow|sparse-matrix
0
360,006
39,421,350
Pandas data reduction and merging
<p>I am working with a Pandas (version 0.17.1) DataFrame that looks like this:</p> <pre><code> time type module msg_type content 36636 2016-08-25 17:59:50.051 INFO MOD_1_NAME STATUS Received Status Monitoring from MODULE_1 'Property A' = some_value_1 36637 2016-08-25 17:59:...
<pre><code>pv = df.set_index(['time', 'type', 'module', 'msg_type']) \ .content.str.extract(r"'(?P&lt;prop&gt;.+)' = (?P&lt;val&gt;.+)", expand=True) pv.groupby(level=[0, 2]).apply(lambda df: df.set_index('prop').val.to_dict()) </code></pre> <hr> <pre><code>2016-08-25 17:59:50.051,MOD_1_NAME,"{'Property A': '...
python|pandas|reduction
2
360,007
39,821,769
Tensorflow: Normal distribution broadcasting
<p>I define batch of two normal distributions:</p> <pre><code>dist = tf.contrib.distributions.Normal(mu=[1., 2.], sigma=10.) </code></pre> <p>Then I want to evalutate pdf of each of this distribution on each of points [0., 1., 2., 3.]. Unfortunately</p> <pre><code>dist.pdf([0.0, 1.0, 2.0, 3.0]) </code></pre> <p>mak...
<p>When you run <code>dist.prob([0.0, 1.0, 2.0, 3.0])</code> tensorflow tries to evaluate the pdf at each entry in the list in a different normal distribution, but your batch only has two. The solution is to evaluate the pdf at each value and then stack the tensors together:</p> <pre><code>dist = tf.contrib.distributi...
tensorflow
0
360,008
39,694,357
loop through numpy arrays, plot all arrays to single figure (matplotlib)
<p>the functions below each plot a single numpy array<br /> plot1D, plot2D, and plot3D take arrays with 1, 2, and 3 columns, respectively</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def plot1D(data): x=np.arange(len(data)) plot2D(np.hstack((np....
<p>To plot multiple data sets on the same axes, you can do something like this:</p> <pre><code>def plot2D_list(data,*args,**kwargs): # type: (object) -&gt; object #if 2d, make a scatter n = len(data) fig,ax = plt.subplots() #create figure and axes for i in range(n): #now plot data set i ...
python|arrays|numpy|matplotlib
1
360,009
39,564,372
Create new column in pandas based on value of another column
<p>I have some dataset about genders of various individuals. Say, the dataset looks like this:</p> <pre><code>Male Female Male and Female Male Male Female Trans Unknown Male and Female </code></pre> <p>Some identify themselves as Male, some female and some identify themselves as both male and female.</p> <p>Now, wha...
<p>You can use:</p> <pre><code>def gender(x): if "Female" in x and "Male" in x: return 3 elif "Male" in x: return 1 elif "Female" in x: return 2 else: return 4 df["Gender Values"] = df["Gender"].apply(gender) print (df) Gender Gender Values 0 Male ...
python|pandas
11
360,010
39,723,061
How to extract date form data frame column?
<p>I have data frame like that:</p> <pre><code> month items 0 1962-01-01 589 1 1962-02-01 561 2 1962-03-01 640 3 1962-04-01 656 4 1962-05-01 723 </code></pre> <p>I need to get year or month from this data frame and create array, but I don't know how to do that.</p> <p>expected result:</p> <p...
<p>Assuming this is <code>pandas</code> you may need to convert the month column to dtype <code>datetime</code> and then you can use <code>.dt</code> accessor for the year and month attributes:</p> <pre><code>In [33]: df['month'] = pd.to_datetime(df['month']) df.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int6...
python|python-2.7|pandas|dataframe
2
360,011
39,734,836
Join Python dataframe time series efficiently
<p>I have the following 2 dataframes with:</p> <pre><code>day date val 11740 2016-01-04 1.3970 11741 2016-01-05 1.3991 11742 2016-01-06 1.4084 11743 2016-01-07 1.4061 </code></pre> <p>and</p> <pre><code>df Adj_Close Close Date High Low 182 12927.200195 129...
<pre><code>pd.concat([day.set_index('date'), df.set_index('Date')], axis=1) &gt;&gt;&gt; val Adj_Close Close High \ 2016-01-04 1.3970 12927.200195 12927.200195 12928.900391 2016-01-05 1.3991 12920.099609 12920.099609 12954.900391 2016-01-06 1.4084 12726.799805 12726.799...
python|pandas|dataframe|time-series
1
360,012
39,584,118
dask dataframe how to convert column to to_datetime
<p>I am trying to convert one column of my dataframe to datetime. Following the discussion here <a href="https://github.com/dask/dask/issues/863" rel="noreferrer">https://github.com/dask/dask/issues/863</a> I tried the following code:</p> <pre><code>import dask.dataframe as dd df['time'].map_partitions(pd.to_datetime,...
<h3>Use <code>astype</code></h3> <p>You can use the <code>astype</code> method to convert the dtype of a series to a NumPy dtype</p> <pre><code>df.time.astype('M8[us]') </code></pre> <p>There is probably a way to specify a Pandas style dtype as well (edits welcome)</p> <h3>Use map_partitions and meta</h3> <p>When ...
python|pandas|dask
24
360,013
39,467,517
save numpy arrays to txt
<p>I have to arrays (q, I) with different number of columns each and I want to save them in a txt file preserving the order of the columns, meaning in the txt file the arrays should be like:</p> <pre><code>q, I0, I1, I2, ... </code></pre> <p>The shape of my arrays are:</p> <pre><code>q.shape = (300, ) I.shape = (300...
<p>Try <code>save_arrays = np.hstack((q[:,np.newaxis],I))</code></p>
python|arrays|numpy
2
360,014
44,123,575
How to display rows of csv file in django?
<p>I have a django app, which allows the user to upload a csv file, say a csv file of rankings of universities. I'd have to process the data that has been uploaded. For example, grey out any column which has string values and calculate the mean and std. deviation of all the values of a column. For this, I am using Pand...
<p>Pandas dataframe can be converted to html table by itself. You can try</p> <pre><code>csvfile = request.FILES['csv_file'] data = pd.read_csv(csvfile.name) data_html = data.to_html() context = {'loaded_data': data_html} return render(request, "dataflow/table.html", context) </code></pre> <p>In the html page, use <c...
django|pandas|django-tables2
14
360,015
44,301,860
Tensorflow upsample tensor of arbitrary size
<p>Let's say I have a tensor with shape</p> <pre><code>[d0, d1,.., dn] </code></pre> <p>Is it possible to create a function that will up-sample only a certain dimensions <code>k</code> times? An example </p> <pre><code>[[1,2],[3,4]] </code></pre> <p>if I apply it for dimension <code>2</code> with repetition factor...
<p>How about <code>tf.concat</code>? </p> <p>This is what I think: if the input's shape is [d1, d2, ..., dn], then output's shape should be [d1, d2, ..., dn*3]. If I am right, the code below may solve your problem.</p> <pre><code>import tensorflow as tf import numpy as np def repetition(a, factor): # get a's sh...
tensorflow
1
360,016
44,000,705
Convert Python Dataframe in 1 Line Dataframe where columns and index values are concatinated
<p>I have the following structure, but much larger</p> <pre><code> 1y 2y 3y 1w 2 8 40 2w 3 10 50 1m 4 12 60 </code></pre> <p>What is a good fast way in python to convert it to a single line dataframe:</p> <pre><code> 1w/1y 1w/2y 1w/3y 2w/1y 2w/2y 2w/3y 1m/1y 1m/2y 1m/3y New...
<pre><code>In [16]: x = df.stack() In [17]: x Out[17]: 1w 1y 2 2y 8 3y 40 2w 1y 3 2y 10 3y 50 1m 1y 4 2y 12 3y 60 dtype: int64 In [18]: new = pd.DataFrame(x.values, index=x.index.map('/'.join)).T In [19]: new Out[19]: 1w/1y 1w/2y 1w/3y 2w/1y 2w/2y 2w/...
python|python-2.7|pandas|dataframe
0
360,017
44,197,574
How do I make a pandas datatimeindex into twice daily frequency?
<p>I have a pandas df that looks like this:</p> <pre><code> Open_fut Close_fut Date 2017-05-12 20873.0 20850.0 2017-05-11 20887.0 20869.0 2017-05-10 20891.0 20888.0 2017-05-09 20943.0 20886.0 2017-05-08 21001.0 20943.0 </code></pre> <p>My dates are <code>...
<p>It seems you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.from_arrays.html" rel="nofollow noreferrer"><code>MultiIndex.from_arrays</code></a> with adding <code>times</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofoll...
pandas|time-series|datetimeindex
3
360,018
44,309,892
TypeError: 'function' object is not subscriptable in tensorflow
<p>There are some errors using tensorflow.Varaible:</p> <pre><code>import tensorflow as tf sess = tf.InteractiveSession() x = tf.placeholder(tf.float32,[None, 784]) W = tf.Variable(tf.zeros[784,10]) b = tf.Variable(tf.zeros[10]) </code></pre> <p>but it shows error: </p> <pre><code>TypeError:Traceback (most recent ca...
<p>This is what Python3 tells you when you try to subscript something that doesn't have the appropriate methods defined for subscripting. </p> <p>Try to subscript an <code>int</code>: </p> <pre><code>1[1] TypeError: 'int' object is not subscriptable </code></pre> <p>Try to subscript a <code>function</code>: </...
python-3.x|tensorflow
4
360,019
44,186,750
Comparing data across dates at different times
<p>I have a sequence of data in datetime dataFrame and need to compare the data from one date and time to the prior day's another time. In the example below, I would, for example need to calculate percentage change from 2016-11-09 09:30:00 to 2016-11-10 21:30:00 (essentially from t @ 9:30 to next_date in the table @ 21...
<p>I think the best approach might be to split the two set of records at the two different times into two DataFrames, align the dates, get rid of the times and compare them across the two DataFrames.</p>
pandas|datetime
0
360,020
44,072,716
Save the text-index encoding mapping
<p>So I am able to train a text classifier with Keras and I can save the model too. My question is when I load the model for predicting unknown texts, I have to encode my input text same way as it was encoded during the training process. How am I able to save the mapping during the training part and reload it when I ma...
<p>Figured out:</p> <pre><code>processor.save(...) </code></pre> <p>and</p> <pre><code>learn.preprocessing.VocabularyProcessor.restore(...) </code></pre>
tensorflow|keras
0
360,021
44,098,231
Efficiently updating NaN's in a pandas dataframe from a prior row & specific columns value
<p>I have a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="noreferrer"><code>pandas'DataFrame</code></a>, it looks like this: </p> <pre><code># Output # A B C D # 0 3.0 6.0 7.0 4.0 # 1 42.0 44.0 1.0 3.0 # 2 4.0 2.0 3.0 62.0 # 3 ...
<p><code>fillna</code> allows for various ways to do the filling. In this case, column <code>D</code> can just fill with <code>0</code>. Column <code>B</code> can fill via <code>pad</code>. And then columns <code>A</code> and <code>C</code> can fill from column <code>B</code>, like:</p> <p><strong>Code:</strong></p...
python|pandas|dataframe|lambda
11
360,022
44,286,607
Loop nesting issue - values not correct
<p>I have a dataframe that has two relevant columns (actually has >2, but don't think that's important), and one of the columns has duplicates in it. </p> <p>The duplicates are in the column, HAB_slice['Radial Position'], and are in increments of 0.1. </p> <p>Ideally, I want to say if two values in HAB_slice['Radial ...
<p>Try the following code. It should work.</p> <pre><code>possible_pos = np.linspace(0, 1, 1 / stepsize+1) center_sum = 0 for i in range(0, len(possible_pos)): # retriving index position of the step value indices = [i for i, x in enumerate(HAB_slice['Radial Position']) if x == possible_pos[i]] # if mu...
python|loops|pandas|numpy|if-statement
0
360,023
44,264,947
Rename Selected Cells Within Pandas String Vector
<p>I am simply trying to rename some of the cells within the 'location' column in a pandas dataframe.</p> <p>The beginning of the dataframe looks like this:</p> <pre><code>Apr 25 ASHEVILLE Apr 25 ASHEVILLE Apr 25 ASHEVILLE Apr 25 ASHEVILLE Apr 25...
<p>You can use <code>.loc</code> with .str accessor and <code>contains</code>:</p> <pre><code>postings.loc[postings.location.str.contains('ASHEVILLE'),'location'] = 'ASHEVILLE' </code></pre>
python|string|pandas|vector
1
360,024
44,159,270
How to load specific columns with varying location from a text file in python?
<p>I'm trying to read the discharge data of 346 US rivers stored online in textfiles. The files are more or less in this format:</p> <pre><code>Measurement_number Date Gage_height Discharge_value 1 2017-01-01 10 1000 2 2017-01-20 15 ...
<p>You can use the <code>names=True</code> option to <code>genfromtxt</code>, and then use the column names to select which columns you want to read with <code>usecols</code>.</p> <p>For example, to read <code>'Gage_height'</code> and <code>'Discharge_value'</code> from your data file:</p> <pre><code>data = np.genfro...
python-2.7|numpy|text-files
0
360,025
43,953,684
Combining Three 1D arrays into a 2D array?
<p>I have three numpy arrays of shape <code>(250L,)</code> called <code>c</code>, <code>I</code> and <code>error</code>. I want to be able to save the three arrays to a text file so that each array is one column in the file. So far I have tried the following:</p> <pre><code>DataArray = np.concatenate((c,I,Error),axis=...
<p><code>concatenate</code> joins existing axes, <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.stack.html" rel="nofollow noreferrer"><code>stack</code></a> inserts new ones:</p> <pre><code>DataArray = np.stack((c,I,Error),axis=1) </code></pre>
python|arrays|python-2.7|numpy|concatenation
3
360,026
44,256,561
incrementing elements of a list in python
<p>It is about 10 motivation stories where i have to "grade" them by looking at several aspects. The first if statement checks if the length of the story is more then 280 characters, the second if statement checks if the first letter is a capital letter. I want to store the scores in <code>candidscore</code> so if cand...
<p>You are using <code>=+</code> instead of <code>+=</code>, change that and it should work</p>
python|arrays|numpy|increment
5
360,027
44,345,410
'KerasRegressor' object has no attribute 'to_json'
<p>I'm unable to save the model trained using KerasRegressor wrapper...</p> <pre><code>model = KerasRegressor(build_fn=base_model, epochs=1, batch_size=10, verbose=1) model.fit(X,Y) model_json = model.to_json() with open("model.json", "w") as json_file: json_file.write(model_json) model.save_weights("model.h5...
<p>Here is a code to use:<br /> <code>model = KerasRegressor(build_fn=base_model, epochs=1, batch_size=10, verbose=1)</code><br /> <code>model.fit(X,Y)</code><br /> <code>def save_model_to_json(my_model):</code><br /> <code> json_model = my_model.model.to_json()</code><br /> <code> with open(&quot;model.json&quot;,...
tensorflow|scikit-learn|keras|keras-2
0
360,028
43,981,926
Squeeze of pandas dataframe with 1-observation (pandas 0.18)
<p>This could be considered an edge case, but I am finding an inconsistency when trying to squeeze (reduce to time series) a pandas dataframe consisting of one observation only.</p> <pre><code>import pandas as pd xx = pd.DataFrame(1, columns = ['A'], index = ['first_index']) xx.squeeze() #1 (float) pd.Series(xx) #...
<p>This introduces a bit of overhead but it may work:</p> <pre><code>pd.concat([xx,xx]).squeeze().iloc[:len(xx)] Out[1778]: first_index 1 Name: A, dtype: int64 </code></pre>
python|pandas
0
360,029
43,982,063
Slices of start, stop indices of valid (non-NaNs) portions of a NumPy array
<p>I have a large numpy 1d array which contains nans. I need to know all the slices that do not contain any nans:</p> <pre><code> import numpy as np A=np.array([1.0,2.0,3.0,np.nan,4.0,3.0,np.nan,np.nan,np.nan,2.0,2.0,2.0]) </code></pre> <p>The expected result for the example would be:</p> <pre><code> Slices=[slice(...
<p>Here is a possibility:</p> <pre><code>import numpy as np def valid_slices(array): m = ~np.isnan(array) idx = np.arange(len(array))[m] idx_diff = np.diff(idx) idx_change = np.where(idx_diff &gt; 1)[0] idx_start = np.concatenate([[0], idx_change + 1], axis=0) idx_end = np.concatenate([idx_cha...
python|numpy
1
360,030
44,073,822
Convert a column from a pandas DataFrame to float with nan values
<p>I am manipulating data using pandas and Python3.4. I am having a problem with a specific csv file. I don't know why, even with <code>nan</code> values, pandas usally reads columns as <code>float</code>. Here it reads them as <code>string</code>. Here is what my csv file looks like:</p> <pre><code>Date RR TN...
<p>You can see that if you allow pandas to detect dtypes itself, you avoid the ValueError and uncover the underlying problem.</p> <pre><code>In [4]: df = pd.read_csv(path, sep=';', index_col=0, parse_dates=True, low_memory=False) In [5]: df Out[5]: Empty DataFrame Columns: [] Index: [08/10/2015 0 10.5 19.5, 09/1...
python|pandas|python-3.4
5
360,031
44,189,048
Couldn't install tenserflow on Windows10 with python --version 3.5.3. (64 bit)
<p><strong>Trying to install TensorFlow</strong> </p> <p><strong>Installing with native pip</strong></p> <p><em>Error:</em></p> <pre><code>C:\Users\Sourav&gt;pip3 install --upgrade tensorflow Collecting tensorflow Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching dist...
<p>according to google, you probably have an old version of pip, try first</p> <pre><code>pip install --upgrade pip </code></pre> <p>try:</p> <pre><code>pip3 install tensorflow </code></pre> <p>or </p> <pre><code>pip install tensorflow </code></pre> <p>Also, I recommend to use <a href="https://www.continuum.io/...
python|tensorflow|pip|anaconda
0
360,032
44,134,491
Getting the higher order bytes from an array in python
<p>I have an a numpy array of 32bit integers and I want to convert it to 16bit integers.</p> <p>I can easily do this using astype however it appears that this always selects the LSBytes while I am interested in the MSBs</p> <pre><code>a=np.array([65536],dtype=np.int32) a.astype(np.uint16) &gt;&gt;&gt; array([0], dty...
<p>You can create a 16 bit "view" of the 32 bit array, and then use a slice to view just the higher order word.</p> <p>For example, in <code>a</code>, the lower 16 bits contain 10, 11, 12, 13, 14, 15, 16, 17, and the higher 16 bits contain 0, 1, 2, 3, 4, 5, 6, 7:</p> <pre><code>In [47]: a = np.arange(0, 8, dtype=np.i...
python|arrays|numpy|casting
4
360,033
44,196,766
Implementing CNN with TensorFlow on Anaconda
<p><a href="https://i.stack.imgur.com/J5kKg.png" rel="nofollow noreferrer">The code cannot run properly</a> I am a beginner of deep learning and python, this is my code of a convolutional neural network. I cannot understand the error at all and it doesn't look like any thing wrong with syntax.</p> <pre><code>#!/usr/bi...
<p>The strides of the sliding windows of your max pooling function returned you a different shape tensor that multiplied down to the predictions gives you the error. Change it to</p> <pre><code>def max_pool_2x2(X): return tf.nn.max_pool(X,[1,2,2,1],[1,2,2,1],padding='SAME') </code></pre> <p>to be consistent w...
python|machine-learning|tensorflow|computer-vision|deep-learning
0
360,034
44,294,936
Pandas join/merge/concat two DataFrames and combine rows of identical key/index
<p>I am attempting to <em>combine</em> two sets of data, but I can't figure out which method is most suitable (join, merge, concat, etc.) for this application, and the documentation doesn't have any examples that do what I need to do.</p> <p>I have two sets of data, structured like so:</p> <pre><code>&gt;&gt;&gt; A T...
<p><strong><code>merge</code></strong><br> <em><code>merge</code> combines on columns. By default it takes all commonly named columns. Otherwise, you can specify which columns to combine on. In this example, I chose, <code>Time</code>.</em></p> <pre><code>A.merge(B, 'outer', 'Time') Time Voltage Current 0 1...
python|pandas|join|dataframe|merge
8
360,035
43,927,611
How to force-assign indices in pandas series
<p>I have a series in pandas </p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; df = pd.DataFrame(np.array([[2,4,4],[4,3,3],[5,9,1]]),columns=['A','B','C']) &gt;&gt;&gt; df A B C 0 2 4 4 1 4 3 3 2 5 9 1 </code></pre> <p>Once I put the stacked output of this ...
<p>1.Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename_axis.html" rel="nofollow noreferrer"><code>rename_axis</code></a> or assign <code>index names</code> for new index names:</p> <pre><code>sta = sta.rename_axis(['head1','head2']) print (sta) head1 head2 0 A 2 ...
python|pandas
0
360,036
44,243,974
How to do faster opencv cv2 imread in python after reboot
<p>I have ~650,000 image files that I convert to numpy arrays with cv2. The images are arranged into subfolders with ~10k images in each. Each image is tiny; about 600 bytes (2x100 pixels RGB).</p> <p>When I read them all using:</p> <pre><code>cv2.imread() </code></pre> <p>It takes half a second per 10k images, un...
<p>I would like to suggest a concept based on REDIS which is like a database but actually a <em>"data structure server"</em> wherein the data structures are your 600 byte images. I am not suggesting for a minute that you rely on REDIS as a permanent storage system, rather continue to use your 650,000 files but cache th...
python|opencv|numpy
2
360,037
43,990,750
How to convert a Python list of lists to a 2D numpy array for sklearn.preprocessing
<p>I currently have a list which contains all of my input for an sklearn classifier. Each element in that list is a list of features, where each element represents a song in my dataset.</p> <p>I need to convert this structure to a 2D numpy array so I can scale my data via sklearn's preprocessing. This is proving to be...
<p>That error suggests that <code>all_feats</code> may not have sublists of the same size. Take a look at its contents, and once you figure out what's the right length for the sublists, and how to prune the extra elements out, you can run <code>all_feats = np.array(all_feats)</code> and it should work!</p> <p>Take a l...
python|arrays|list|numpy|scikit-learn
1
360,038
44,072,923
Pandas dataframe finding largest N elements of each row with row-specific N
<p>I have a DataFrame:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'row1' : [1,2,np.nan,4,5], 'row2' : [11,12,13,14,np.nan], 'row3':[22,22,23,24,25]}, index = 'a b c d e'.split()).T &gt;&gt;&gt; df a b c d e row1 1.0 2.0 NaN 4.0 5.0 row2 11.0 12.0 13.0 14.0 NaN row3 22.0 2...
<p>Based on @ScottBoston's comment on the OP, it is possible to use the following mask based on rank to solve this problem:</p> <pre><code>&gt;&gt;&gt; n_max.index = df.index &gt;&gt;&gt; df_rank = df.stack(dropna=False).groupby(level=0).rank(ascending=False, method='first').unstack() &gt;&gt;&gt; selected = df_rank.l...
pandas|dataframe|max|rowwise
3
360,039
44,149,880
how to merge dataframes with string timestamps of different frequency
<p>I have 2 csv datafiles from different sources that I would like to merge. Both files have a string timestamp for each row, but very different periods - one is every 2 seconds, the other every hour. I can import them to Pandas, and have tried to merge them but have 2 problems.</p> <p>1) I can convert the timestamp t...
<p>I think you need create new <code>datetime</code> columns and merge with them and last remove <code>new</code> column by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow noreferrer"><code>drop</code></a> - then original columns are not changed:</p> <pre><code>...
python|pandas
1
360,040
69,609,636
Getting the relative value of a column in pandas
<p>This is simple question (I guess), but I just can't find a way to work it out.</p> <p>I have a pandas dataset like this:</p> <pre><code>ID SCORE REGION COUNT 0 A WEST 855 1 A NORTH 1631 2 A EAST 401 3 A SOUTH 9193 4 B WEST 707 5 B NORTH 1575 6 B ...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>groupby.transform</code></a>:</p> <pre><code>df['PERCENT'] = df['COUNT'].groupby(df.SCORE).transform(lambda x: x / x.sum()) * 100 df ID SCORE REGION COUNT PERCENT 0 ...
python|pandas|dataset
1
360,041
69,464,686
How fix batch_size and epoch in such machine learning task
<p>I train a ResNet50 network.<br /> I have a dataset with 1500 images, I fix epochs = 100 and batch_size = 16, I find that accuracy reaches 0.8 from the 10th epoch and continues to increase until 0.95. Now, I add images for this dataset, it becomes 15 000 and with epochs = 100 and batch_size = 16. I observed that accu...
<p>The accuracy of a deep learning model mainly depends on the nature of the dataset and number of samples within the dataset. The more samples, the more epochs you would need. However, batch size has greater effect on the speed of training a model rather than accuracy.</p> <p>In your case, keeping epochs constant (100...
python|tensorflow|machine-learning|computer-vision
1
360,042
69,604,817
When using 'df.groupby(column).apply()' get the groupby column within the 'apply' context?
<p>I want to get the groupby column i.e. column that is supplied to <code>df.groupby</code> as a <code>by</code> argument (i.e. <code>df.groupby(by=column)</code>), within the <code>apply</code> context that comes after <code>groupby</code> (i.e. <code>df.groupby(by=column).apply(Here)</code>).</p> <p>For example,</p> ...
<p>I just figured out a one-liner solution:</p> <pre><code>df = pd.DataFrame({'Animal': ['Falcon', 'Falcon', 'Parrot', 'Parrot'], 'Max Speed': [380., 370., 24., 26.]}) df.groupby(['Animal']).apply(lambda df_: df_.apply(lambda x: all(x==df_.name)).loc[lambda x: x].index.t...
pandas|dataframe|group-by|apply
0
360,043
69,405,257
How to Group then Transpose Dataframe without summarization
<p>I need to Group <strong>ID</strong> from below Dataframe then Transpose the <strong>Value</strong> with new Dynamic incremental Header</p> <pre><code>data = {'ID': ['A', 'B', 'B', 'B', 'C', 'C', 'D', 'D', 'D', 'D'], 'Value': [30, 760, 740, 755, 1 ,4, 56, 34, 76, 12]} df = pd.DataFrame(data,columns=['ID', 'Value']) ...
<p>The following will get you well on your way there:</p> <pre><code>df.pivot(columns='ID').T.fillna('').reset_index().drop(columns='level_0') </code></pre> <p>Producing:</p> <pre><code> ID 0 1 2 3 4 5 6 7 8 9 0 A 30 1 B 760 740 755 ...
python|dataframe|pandas-groupby
0
360,044
69,379,434
seach list of strings into panda dataframe and return the entire row that contains that string to build a new csv file
<p>I have an large input file of as follows:</p> <p>Input File:</p> <pre><code>1234 3546 </code></pre> <p>And a large CSV File of millions lines as follows:</p> <pre><code>1234|2021-04-20 3546|2019-05-15 8576|2021-08-05 4332|2018-10-04 </code></pre> <p>I want to search the input file into the dataFrame and I ha...
<p>So you want to filter a dataframe based on the row values of a certain column. Pandas already has a function for this:</p> <pre class="lang-py prettyprint-override"><code>input_file = [1234, 3546] list_to_find = pd.DataFrame(input_file) data_available = pd.DataFrame([[1234, 'a'],[3546, 'b'],[8576, 'c'],[4332, 'd']]...
python|pandas
0
360,045
69,392,429
Select rows if multiple column values are same (or null)
<p>I have a dataframe df1:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>val0</th> <th>dir0</th> <th>val1</th> <th>dir1</th> <th>val2</th> <th>dir2</th> <th>val3</th> <th>dir3</th> </tr> </thead> <tbody> <tr> <td>a0</td> <td>up</td> <td>a1</td> <td></td> <td>a2</td> <td>up</td> <td>a3</td...
<p>First filter only <code>dir</code> columns by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>DataFrame.filter</code></a>, then test for <code>up</code>, missing values or <code>down</code> with test if all values per rows are <code>Tru...
python|pandas
1
360,046
69,666,144
Create a table via JSON output in Python with subfield averaging
<p>I'm having trouble generating output through more than one input json.</p> <p>json can contain varied amount of services and pointlists, but they will always have the same amount between them, the amount of services and pointlists depends on the query period. The required output is the list of services, the average ...
<p>Something like this can give you an idea on how to achieve that:</p> <pre class="lang-py prettyprint-override"><code>import os import json from pprint import pprint def get_series_data(serie): service_name = None pointlist = None scope = serie.get(&quot;scope&quot;) if scope: service_name =...
python|json|pandas|dataframe
0
360,047
69,427,332
Trouble Looping through JSON elements pulled using API
<p>I am trying to pull search results data from an API on a website and put it into a pandas dataframe. I've been able to successfully pull the info from the API into a JSON format.</p> <p>The next step I'm stuck on is how to loop through the search results on a particular page and then again for each page of results....
<p>Slightly different approach: rather than iterating through the response, read into a dataframe then save what you need. The saves the first agency name in the list.</p> <pre><code>df_list=[] for page in np.arange(0,7): url = 'https://www.federalregister.gov/api/v1/documents.json?conditions%5Bpublication_date%5D%...
python|json|pandas|loops|web-scraping
1
360,048
69,582,263
How to write the data to excel with python and keep excel number format?
<p>I'm trying to write the time data into excel with python (I'm using Pandas). When I write time data to excel I have excel number format 'General':</p> <p>Sample Screenshot<br /> <img src="https://i.stack.imgur.com/sEq8p.png" alt="Existing Screenshot" /></p> <p>But I need to have the number format as 'Time' - which I...
<p>Have you tried to use Pandas?</p> <blockquote> <p><strong>Writing Excel Files Using Pandas</strong></p> <p>We'll be storing the information we'd like to write to an Excel file in a DataFrame. Using the built-in to_excel() function, we can extract this information into an Excel file.*</p> </blockquote> <ul> <li>Step ...
python-3.x|excel|pandas
0
360,049
69,421,421
Where is the sigmoid derivative used in the backpropagation algorithm and how are weights updated
<p>I am a year 10 student trying to learn how a neural network works in python code. I don't have much calculus knowledge, only to the extent of a limited understanding of derivatives and how to find them.</p> <p>I have made a simple feed-forward network in python using numpy. I have set up layer classes with a feed_fo...
<p>I'm assuming that your backprop is the <code>sigmoid_derr</code> function, but the implementation is not right for the derivative of the sigmoid.</p> <p>S`(x) = S(x)[1-S(x)]</p> <p>Where S(x) is the sigmoid derivation. Check <a href="https://beckernick.github.io/sigmoid-derivative-neural-network/" rel="nofollow nore...
python|numpy|deep-learning|backpropagation
0
360,050
69,490,315
How to calculate the days difference between all the dates of a dataframe column and a single data in Python
<p>I would to calculate the days difference between all the days in the &quot;last_review&quot; column and 2018-08-01, and I want the output to be exact days, like if the observation is 2018-07-31, the output should be 2. And do this for every observation of the dataframe column. The output should be 48894 * 1</p> <p><...
<p>You can use:</p> <pre><code>sub_date = datetime(2018,8,1) df['last_review'] = pd.to_datetime(df['last_review']) df['diff'] = (sub_date - df['last_review']).dt.days </code></pre>
python|pandas|dataframe|date|datetime
0
360,051
69,299,007
Add row to an existing dataframe
<p>I have an existing data frame with known columns. I want to insert a row with data for each column inserted one at a time.</p> <p>I first created an empty data frame with few columns-</p> <pre><code>df = pd.DataFrame(columns=['col1', 'col2', 'col3']) df.to_csv('test.csv', sep='|', index=False) </code></pre> <p><stro...
<p>You can use <code>df.append()</code> to append a row</p> <pre><code>import pandas as pd df = pd.DataFrame(columns=['col1', 'col2', 'col3']) turn = 2 while turn: new_row = {'col1':turn, 'col2':turn, 'col3':turn} df = df.append(new_row, ignore_index=True) turn-=1 </code></pre> <pre><code>Out[11]: col1 col2 ...
pandas|dataframe
2
360,052
69,561,863
ValueError with pandastable row coloring
<p>I'm using <code>pandastable</code> to visualize a Dataframe and I want to highlight certain rows. In the <code>pandastable</code> documentation I found the function <code>setRowColors</code>. It says there to use color in hex. But when I'm applying the code I get the following error:</p> <blockquote> <p>ValueError: ...
<p>Due to the current implementation in version <code>0.12.2</code> of the <code>setRowColors</code> function, the <code>rows</code> parameter must be passed a <code>list</code> of values:</p> <pre><code>import tkinter as tk import pandas as pd from pandastable import Table root = tk.Tk() frame = tk.Frame(root) frame...
python|pandas|tkinter
2
360,053
69,550,812
pandas : reverse of a crosstab
<p>I have a data frame like the following <a href="https://i.stack.imgur.com/PymyH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PymyH.png" alt="enter image description here" /></a></p> <p>I have a code to do crosstab</p> <pre><code>print(pd.crosstab(mypd['a'],mypd['b'],mypd['c'])) </code></pre> <p...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.repeat.html" rel="nofollow noreferrer"><code>Index.repeat</code></a> by c...
python|pandas
3
360,054
69,430,320
Is it possible to store some tensors on CPU and other on GPU for training neural network in PyTorch?
<p>I designed a neural network in PyTorch, which is demanding a lot of GPU memory or else runs with a very small batch size.</p> <p>The GPU Runtime error is causing <strong>due to three lines of code</strong>, which stores two new tensors and does some operations.</p> <p>I don't want to run my code with a small batch s...
<p>It is possible.<br /> You can use the command <a href="https://pytorch.org/docs/stable/generated/torch.Tensor.to.html#torch.Tensor.to" rel="nofollow noreferrer"><code>.to(device=torch.device('cpu')</code></a> to move the relevant tensors from GPU to CPU, and back to GPU afterwards:</p> <pre class="lang-py prettyprin...
pytorch|gpu|tensor
1
360,055
69,638,499
Splitting a pandas dataframe into two subsets
<p>I'm trying to make function that partitions a pandas dataframe into two subsets based on a feature vector.</p> <p>My dataframe consists of two columns containing an <code>ndarray[10000]</code> which is my feature vector and an integer which represents the label for the vector.</p> <p>question just checks if an index...
<p>Ok, i figured it out. For some reason it would not work when my columns had deafault names (numbers).</p> <pre><code>df = df.rename(columns={0:'vector', 1:'label'}) </code></pre> <p>Did this to the dataset i was sending in and it worked.</p>
python|pandas|dataframe|numpy|partitioning
0
360,056
69,464,797
Difference between np.dtype and np.dtype.name
<p>As stated in the title, I am willing to know the difference between <code>np.dtype</code> and <code>np.dtype.name</code>. When I used them, I found that they provide same output like below:</p> <pre class="lang-py prettyprint-override"><code>dt = np.array([[(1, 5, 2), (2, 4.0, 7)], [(6, 4, 2), (2, 8, 10)]]) print('\...
<p>If you print an object it asks the object what to print i.e. it calls it's &quot;<strong>repr</strong>&quot; method. Python objects always have that but you can define them yourself. E.g.</p> <pre><code>class foo: def __init__(self): pass print(foo()) </code></pre> <p>gives me <code>&lt;__main__.foo obj...
python|numpy
1
360,057
69,555,252
python iterate / loop over two columns and drop entire row after value is first found in either column a or column b
<p>I have a dataframe with 15 columns being used to calculate a score. Two columns (a &amp; b) are my independent variables of which a &amp; b both have duplicate values. Column C represents the score being calculated- of which i have sorted the dataframe by column C descending already. The goal is to keep the highest ...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.duplicated.html#pandas.Series.duplicated" rel="nofollow noreferrer"><code>Series.duplicated</code></a></p> <pre><code>res = df[~(df[&quot;Column A&quot;].duplicated() | df[&quot;Column B&quot;].duplicated())] print(res) </code></pre> <p><strong>...
python|pandas|dataframe|loops|literate-programming
1
360,058
69,398,736
'l2' not defined as regularizer
<p>The following is my code:</p> <pre><code>from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras import layers from tensorflow.keras import regularizers model = Sequential() model.add(Dense(units=10, input_shape=[784], activation='sigmoid', kernal_regularizer=l...
<p>The syntax is</p> <pre><code>kernal_regularizer=regularizers.l1_l2(l1=0, l2=0.01) </code></pre> <p>instead of <code>kernal_regularizer=l2(0.01)</code></p> <p>Link: <a href="https://www.tensorflow.org/api_docs/python/tf/keras/regularizers/l1_l2" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/...
python|tensorflow
0
360,059
69,561,447
Using str.contains instead of .isin with pandas
<p>If my goal is to see if any values in one dataframe's column match in another dataframe's column I can use <code>.isin</code> like so:</p> <pre><code>df1 = pd.DataFrame({'name': ['Marc', 'Jake', 'Sam', 'Brad']}) df2 = pd.DataFrame({'IDs': ['Jake', 'John', 'Marc', 'Tony', 'Bob']}) print(df1.assign(In_df2=df1.name.is...
<p>Use a regex like this:</p> <pre><code>pattern = fr&quot;(?:{'|'.join(df2['IDs'])})&quot; df1['In_df2'] = df1['name'].str.contains(pattern).astype(int) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df1 name In_df2 0 Marc 1 1 Jake 1 2 Sam 0 3 Brad 0 &g...
python|pandas
1
360,060
69,665,309
How to get the cumulative sum of different linearized line plots when they are overlapped
<p>So I have the following pandas dataframe</p> <p>Start time | End time | Value| 0;50;50 20;100;800 10;45;700 which each row represents a line in plot from start time til end time linearized (time are x axis)</p> <p>the result dataframe should have x | value 0;0 10;10 20;220 45;995 50; 1050; 100; 1550</p> <p>each valu...
<p>This may not be scalable depending on the size of your <code>DataFrame</code>.</p> <p>Some data to get us started.</p> <pre><code>import pandas as pd from plotnine import * df = pd.DataFrame({ 'StartTime':(0,20,10), 'EndTime':(50,100,45), 'Value':(50,800,700) }) </code></pre> <p>First, create a <code>Da...
python|pandas|math|plot
0
360,061
69,451,946
Fastest way to find the maximum minimum value of two 'connected' matrices
<p>I want to maximize the following function:</p> <pre><code>f(i, j, k) = min(A(i, j), B(j, k)) </code></pre> <p>Where <code>A</code> and <code>B</code> are matrices and <code>i</code>, <code>j</code> and <code>k</code> are indices that range up to the respective dimensions of the matrices. I would like to find <code>(...
<p>Perhaps you could re-evaluate how you look at the problem in context of what min and max actually do. Say you have the following concrete example:</p> <pre><code>&gt;&gt;&gt; np.random.seed(1) &gt;&gt;&gt; print(A := np.random.randint(10, size=(4, 5))) [[5 8 9 5 0] [0 1 7 6 9] [2 4 5 2 4] [2 4 7 7 9]] &gt;&gt;&gt...
python|numpy|matrix|optimization|memory
3
360,062
69,431,193
Why do two numpy arrays not compare equal if they print the same?
<p>I've a piece of code to find the inverse of a matrix using Gaussian elimination. To check if the solution is correct, I match it with the numpy linalg.inv solution. They appear to be same, but it returns false when I check. This is what I mean</p> <pre><code>e = inverse(zeze) </code></pre> <pre><code>[[ 0.11111111 ...
<p>You are comparing floating point values. Only some of the actual digits are shown - and <code>0.11111111111111111111</code> is not the same as <code>0.11111111111111111112</code></p> <p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.allclose.html" rel="nofollow noreferrer">numpy.allclose</a> to ...
python|numpy|matrix|gaussian|inverse
2
360,063
69,361,685
How to flatten this Dataframe
<p>I have Dataframe that consists of ID and one column. That column has list of dictionaries in each cell. What I want is normalize it and flatten, so instead of having one column, I will have many of columns that appear from these dicts.</p> <pre class="lang-py prettyprint-override"><code> ...
<p>IIUC use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.explode.html" rel="nofollow noreferrer"><code>Series.explode</code></a>:</p> <pre><code>df = pd.json_normalize(load_only_df['LoadNodes'].explode()) </code></pre> <p>If important are also index values, here <code>SubProjectId</c...
python|pandas|dataframe|nested|flatten
0
360,064
69,391,499
pandas `read_sql_query` - read `double` datatype in MySQL database to `Decimal`
<p>I'm trying to use <code>read_sql_query()</code> to read a query from MySQL database, one of the field in the database, its type is <code>double(24, 8)</code>, I want to use <code>dtype=</code> parameter to have full control of the datatypes and read it to <code>decimal</code>, but seems like pandas can't recognize ...
<p>What &quot;the data looks like in the database&quot; is tricky. This is because the act of printing it out feeds the bits through a formatting algorithm. In this case it removes trailing zeros. To see what is &quot;in the database&quot;, one needs to get a hex dump of the file and then decipher it; this is <em>no...
python|mysql|pandas|decimal|read-sql
0
360,065
69,538,027
Error in building wheel for numpy(pyproject.toml) [python 3.10]
<p>This is the error I get:</p> <pre><code>Building wheel for numpy (pyproject.toml) ... error ERROR: Command errored out with exit status 1: command: 'C:\Users\nazee\AppData\Local\Programs\Python\Python310\python.exe' 'C:\Users\nazee\AppData\Local\Programs\Python\Python310\lib\site- packages\pip\...
<p>The error message tells you:</p> <pre><code>error: Microsoft Visual C++ 14.0 is required. Get it with &quot;Build Tools for Visual Studio&quot;: https://visualstudio.microsoft.com/downloads/ </code></pre> <p>Go install the newest version of Microsoft Visual C++ there: <a href="https://visualstudio.microsoft.com...
python|windows|powershell|numpy|cmd
-2
360,066
69,547,811
How to apply a function along an axis in numpy?
<p>For example, I have a matrix with shape:</p> <p><code>x = np.random.rand(3, 10, 2, 6)</code></p> <p>As you can see, there are only two arrays along an <code>axis=2</code>.</p> <p>I have a function that accepts these two arrays:</p> <pre><code>def f(arr1, arr2): # arr1 with shape (6, ) and arr2 with (6, ) return ...
<p>You can't do it entirely arbitrarily, but your particular case reduces to</p> <pre><code>x.sum(axis=2) </code></pre> <p>If you want to add the arrays as in your code:</p> <pre><code>x[:, :, 0, :] + x[:, :, 1, :] </code></pre>
python|numpy
1
360,067
69,506,372
I'm trying to define a function in Google Colab but im getting this error: "name 'train_data' is not defined"
<p>here is the code that im running, the version of the tensorflow is 2.6.0</p> <pre><code>import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import matplotlib.pyplot as plt from tensorflow.keras.utils import plot_model X = tf.range(-100, 100, 4) y = X + 10 # Split the data into train and test s...
<p>thanks to the @MichaelSzczesny I did fix the code. it was needed a little space before the below lines. and the <code>labels=&quot;Training data&quot;</code> was incorrect, the correct form is <code>label=&quot;Training data&quot;</code>. here is the correct and fixed code:</p> <pre><code> plt.figure(figsize=(10, 7...
python|google-colaboratory|tensorflow2.0
1
360,068
69,312,822
pairs of rows with the highest string similarity
<p>So i have this dataframe:</p> <pre><code>import pandas as pd d = {'id': [1,1,1,1,2,2,3,3,3,4,4,4,4], 'name':['ada','aad','ada','ada','dddd','fdd','ccc','cccd','ood','aaa','aaa','aar','rrp'] ,'amount':[2,-12,12,-12,5,-5,2,3,-5,3,-10,10,-10]} df1 = pd.DataFrame(d) df1 id name amount 0 1 ada 2...
<p>You can try something like this:</p> <p>please notice you can change the information you print as you wish, just need to edit the return values from the function create_sim</p> <pre><code>import pandas as pd from operator import itemgetter d = {'id': [1,1,1,1,2,2,3,3,3,4,4,4,4], 'name':['ada','aad','ada','ada'...
python|python-3.x|pandas|string|dataframe
1
360,069
69,308,416
Pandas Join creates unwanted duplicate, only want first instance
<p>So I have 2 dataframes that I'm joining by their redefined index which is the number we use to identify the study, when I'm joining them they look like this:</p> <p><strong>df1 (contains all study numbers):</strong></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: cente...
<p>Try using <code>drop_duplicates</code> with <code>keep=&quot;first&quot;</code> since it is sorted from newest to oldest. Then you merge on the key <code>Index</code></p> <pre><code>df2 = df2.drop_duplicates(subset=&quot;Index&quot;, keep=&quot;first&quot;) df = pd.merge(df1, df2, on=&quot;Index&quot;, how=&quot;lef...
python|pandas|dataframe
1
360,070
69,611,344
Open CV imshow() - ARGB32 to OpenCV image
<p>I am trying to process images from Unity3D WebCamTexture graphics format(ARGB32) using OpenCV Python. But I am having trouble interpreting the image on the Open CV side. The image is all Blue (possibly due to ARGB)</p> <pre><code>try: while(True): data = sock.recv(480 * 640 * 4) if(len(data) == 4...
<p>The reason is because of the order of the channels. I think the sender read image as a RGB image and you show it as a BGR image or vice versa. Change the order of R and B channels will solve the problem:</p> <pre class="lang-py prettyprint-override"><code>image = image[..., [0,3,2,1]] # swap 3 and 1 represent for B ...
python|python-3.x|numpy|opencv|opencv-python
3
360,071
69,473,128
How to append new rows into a column of a dataframe based on conditions in python?
<p>I want to add a new category into my existing column based on some conditions</p> <p>Trial</p> <pre><code>df.loc[df['cat'] == 'woman','age'].max()-df.loc[df['cat'] == 'man','age'].max().apend{'cat': 'first_child', 'age': age} </code></pre> <pre><code>import pandas as pd d = {'cat': ['man1','man', 'woman','woman'], '...
<p>Try:</p> <pre><code>import pandas as pd d = {'cat': ['man1','man2', 'woman1','woman2'], 'age': [30, 40, 50,55]} df = pd.DataFrame(data=d) df_man = df[df.cat.str.startswith('man')].reset_index(drop=True) df_woman = df[df.cat.str.startswith('woman')].reset_index(drop=True) childs = [f'child{i}' for i in range(1, len...
python|pandas|dataframe
3
360,072
69,446,292
Populate value for another column based on category python
<p>I have two columns:</p> <pre><code> number apple 2 banana 3 grape 25 cat 4 jelly 1 </code></pre> <p>I need to find unique values that each category contains. This is how you could create a new df</p> <pre><code>import numpy as np import pandas as pd df = pd.Data...
<p>You can apply:</p> <pre><code>import pandas as pd df = pd.DataFrame({'category':['apple', 'banana', 'grape', 'cat', 'jelly'], 'number':[2,3,25,4,1]}) df2 = pd.DataFrame({'category':['apple', 'banana', 'apple', 'grape', 'cat', 'jelly', 'cat', 'grape'], 'name':['a', 'b', 'pl...
python|pandas
0
360,073
40,874,984
Quick way of transforming a datetime column in Pandas
<p>I have a mountain of CSV's where the date column is the following: </p> <pre><code>Print df Date 0 20090501 00:00:00.831 1 20090501 00:00:00.832 2 20090501 00:00:01.078 3 20090501 00:00:01.337 4 20090501 00:00:01.580 5 20090501 00:00:01.581 6 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.time.html" rel="nofollow noreferrer"><code>dt.time</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow noreferrer"><code>dt.date</code></a>:</p> <pre><code>df['Time...
python|python-2.7|pandas|lambda
2
360,074
41,016,835
Use function to modify pandas dataframe
<p>This is a follow up of the question <a href="https://stackoverflow.com/questions/41015805/how-to-use-functions-with-pandas-dataframe/41015945#41015927">here</a>: How to modify a dataframe using function? Lets say I want to make call <code>.upper()</code> on values in <code>a</code></p> <pre><code>df = pd.DataFrame(...
<p>You can call function for column <code>a</code>:</p> <pre><code>def doSomething(x): return x.upper() print (df1.a.apply(doSomething)) 0 LONDON 1 NEWYORK 2 BERLIN Name: a, dtype: object </code></pre> <hr> <pre><code>print (df1.a.apply(lambda x: x.upper())) 0 LONDON 1 NEWYORK 2 BERLIN Nam...
python|pandas
6
360,075
41,191,358
Apply elementwise, concatenate resulting rows into a DataFrame
<p>I have a list of values (could easily become a Series or DataFrame), on which I want to apply a function element-wise. </p> <pre><code>x = [1, 5, 14, 27] </code></pre> <p>The function itself returns a single row of a DataFrame (returning the original value <code>x</code> and two result value columns), and I want t...
<p>consider the following function that returns the same stuff you show in your example</p> <pre><code>def special_function(x): idx = ['x', 'Val1', 'Val2'] d = { 1: pd.Series([x, 4, 23], idx), 5: pd.Series([x, 56, 27], idx), 14: pd.Series([x, 10, 9], idx), 27: pd.Series([x, 8,...
python|pandas
2
360,076
40,995,256
Convolutional Neural Network in Tensorflow for Prediction
<p>I am a beginner in CNN and Tensorflow.</p> <p>I saw many examples of Convolutional Neural Networks (CNNs) for classification. However, I need CNNs for regression. I am trying to implement CNN in Tensorflow with own data for prediction.</p> <p>Can I implement CNN for prediction or are CNNs only for classification?<...
<blockquote> <p>Can I implement CNN for prediction or are CNNs only for classification?</p> </blockquote> <p>Both, regression and classification, are often called prediction. And yes, you can do both with CNNs. It is only the loss function (mean squared error for regression, cross entropy for classification) and the...
neural-network|tensorflow|deep-learning|conv-neural-network
2
360,077
40,857,326
Tensorflow rnn_decoder usage : Expected size[1] in [0, 0] error message
<p>I'm new to tensorflow and I have some problems about the usage of <em>embedding_rnn_decoder</em> in tensorflow <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/seq2seq.py" rel="nofollow noreferrer">sample code</a>.</p> <p>Here is my code :</p> <pre><code>vocal_size = 407 embeddi...
<p>Clearly some shapes are mismatched, but it's hard to tell from your code snippets which ones. It would be easier to help if you posted the whole error message.</p>
python|neural-network|tensorflow
0
360,078
41,190,710
Android App TensorFlow Google Cloud ML
<p>I am studying how to use TensorFlow together with Google Cloud ML on an Android App. I already found this <a href="https://stackoverflow.com/questions/40823051/using-google-cloud-ml-with-android-app">post.</a> As far as I understand from this post and what I already found on google I always have to deploy a trained ...
<p>There is an API for running training jobs in the Cloud. For an example, see the <a href="https://cloud.google.com/ml/docs/how-tos/training-models" rel="nofollow noreferrer">training quickstart</a>.</p> <p>Note that there is not currently a straightforward way to perform streaming training directly using the CloudML...
android|machine-learning|tensorflow|google-cloud-ml
1
360,079
40,800,012
Dividing columns of a data frame group-wise?
<p>I have a df:</p> <pre><code>temp = pd.DataFrame({'Y': ['A', 'B', 'B', 'A', 'B'], 'Z': [10, 5, 6, np.nan, 12], }) </code></pre> <p>I set Y as index and then calculate counts and size group-wise:</p> <pre><code>temp.sort('Y', inplace=True) temp.set_index('...
<p>I think you can use twice <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>reset_index</code></a>:</p> <pre><code>temp.sort_values('Y', inplace=True) temp.set_index('Y', inplace=True, drop=False) temp.sort_index( inplace=True) temp['n...
python|pandas|indexing|data-manipulation
1
360,080
41,071,947
How to remove the space between subplots in matplotlib.pyplot?
<p>I am working on a project in which I need to put together a plot grid of 10 rows and 3 columns. Although I have been able to make the plots and arrange the subplots, I was not able to produce a nice plot without white space such as this one below from <a href="http://matplotlib.org/users/gridspec.html" rel="noreferr...
<p>A note at the beginning: If you want to have full control over spacing, avoid using <code>plt.tight_layout()</code> as it will try to arange the plots in your figure to be equally and nicely distributed. This is mostly fine and produces pleasant results, but adjusts the spacing at its will.</p> <p>The reason the Gr...
python|numpy|matplotlib
37
360,081
40,815,775
pandas: merge help two dataframe
<p>I have a Question in Pandas</p> <p>two dataframe I want merge.</p> <p>example)</p> <p>First DataFrame is here</p> <pre><code>Year Month Location 2006 01 NY 2006 01 CA 2006 02 CA 2006 02 NY </code></pre> <p>and Second DataFrame is here</p> <pre><code>Type A B C </code></pre> <p>how can I me...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow noreferrer"><code>merge</code></a> by new columns <code>tmp</code> if need cartesian product. Last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow noreferr...
python|pandas|dataframe|merge
2
360,082
40,839,609
Rename unnamed multiindex columns in Pandas DataFrame
<p>I created this dataframe:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd columns = pd.MultiIndex.from_tuples([("x", "", ""), ("values", "a", "a.b"), ("values", "c", "")]) df0 = pd.DataFrame([(0,10,20),(1,100,200)], columns=columns) df0 </code></pre> <p><a href="https://i.stack.imgur.com/Qw...
<p>Since pandas 0.21.0 the code should be like this</p> <pre><code>def rename_unnamed(df): """Rename unamed columns name for Pandas DataFrame See https://stackoverflow.com/questions/41221079/rename-multiindex-columns-in-pandas Parameters ---------- df : pd.DataFrame object Input dataframe...
python|pandas
6
360,083
40,900,608
cosine similarity on large sparse matrix with numpy
<p>The code below causes my system to run out of memory before it completes. </p> <p>Can you suggest a more efficient means of computing the cosine similarity on a large matrix, such as the one below?</p> <p>I would like to have the cosine similarity computed for each of the 65000 rows in my original matrix (<code>ma...
<p>Same problem here. I've got a big, non-sparse matrix. It fits in memory just fine, but <code>cosine_similarity</code> crashes for whatever unknown reason, probably because they copy the matrix one time too many somewhere. So I made it compare small batches of rows "on the left" instead of the entire matrix:</p> <pr...
python|numpy|memory|matrix|cosine-similarity
11
360,084
41,226,846
Boolean indexing with MultiIndex df (pandas)
<p>I have a MultiIndex dataframe that I'm trying to index in to based on value ranges in my columns and the outermost index levels. So, using the example below, e.g. I'm trying to select the values from <code>v2</code> that are index <code>l2</code> where <code>v1 &gt; 12</code></p> <p>I can achieve this using multipl...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#using-slicers" rel="nofollow noreferrer">slicers</a> for selecting and then modified <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <co...
python|pandas|multi-index
1
360,085
41,020,437
how to convert column in this way in pandas
<p>original data is: </p> <pre><code>df=pd.DataFrame({'A': [1]*3 + [2]*3 + [1]*4 + [3]*5, 'B': [1.5]*2 + [2]*4 + [1.5]*5 + [3.2]*4}) </code></pre> <p>how can I convert column <code>A</code> and <code>B</code> to: <a href="https://i.stack.imgur.com/Qesbb.jpg" rel="nofollow noreferrer"><img src="https:...
<p>The <code>diff</code> method takes the difference between the current row and the row above it. Anything positive will make <code>A_con</code> True. The tricky part is when the difference is 0. When 0, the immediate above value can take it's place. This is done using the <code>replace</code> with the <code>ffill</co...
python|pandas|numpy
1
360,086
41,160,572
Multiple assignment with Numpy arrays and lists, a curious example
<p>Consider the multiple assignment <code>x[0],y = y,x[0]</code>. Applied to each of the four below cases, this gives four different results.</p> <ul> <li><p>Case 1:</p> <pre><code>x = [[1,2], [3,4]] y = [5,6] </code></pre> <p>gives</p> <pre><code>x = [[5,6], [3,4]] y = [1,2] </code></pre></li> <li><p>Case 2:</p> ...
<p>The only surprising cases here should be 2 &amp; 4:</p> <pre><code>x = np.array([[1,2], [3,4]]) y = np.array([5,6]) # or [5, 6] </code></pre> <p>giving</p> <pre><code>x = array([[5,6], [3,4]]) y = array([5,6]) # where did the 1 and 2 go? </code></pre> <p>Since the others are just swapping around data types, bu...
python|numpy|assignment-operator|python-internals
5
360,087
40,803,498
Error when plotting from a pandas dataframe using matplotlib, with different IPython versions
<p>I am facing a strange problem, when trying to simply plot a dummy histogram from fake data (copy/paste from pandas documentation). What causes this crash?</p> <pre><code>#!/usr/bin/python3 # -*- coding: utf-8 -*- import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame({'A' : [1,...
<p>You should use df[c[0]], because c is an array not a string.</p>
python|pandas|matplotlib|ipython
1
360,088
40,861,105
numpy array printing in desired manner
<p>I am using numpy array to fetch values from file and do calculations. The final output is like this <br> <code>('I', 10031, 'GASAS.SW', 2024, 23067, -501, -6760.1, 1, 125 )</code> <br> But i need it to be printed like this <br> <code>I 10031 GASAS.SW 2024 23067 -501 -6760.1 1 125</code> <br></p>
<pre><code>x = ('I', 10031, 'GASAS.SW', 2024, 23067, -501, -6760.1, 1, 125 ) print " ".join([str(i) for i in x]) </code></pre>
python|arrays|numpy
0
360,089
41,051,998
ROS CompressedDepth to numpy (or cv2)
<p>Folks,</p> <p>I am using this link as starting point to convert my CompressedDepth (image of type: <strong>"32FC1; compressedDepth," in meters</strong>) image to OpenCV frames:</p> <p><a href="http://wiki.ros.org/rospy_tutorials/Tutorials/WritingImagePublisherSubscriber" rel="nofollow noreferrer">Python Compressed...
<p>The right way to decode <code>compressedDepth</code> is to first remove the header from the raw data and then convert the remaining data.</p> <p>This is documented in <a href="https://github.com/ros-perception/image_transport_plugins/blob/indigo-devel/compressed_depth_image_transport/src/codec.cpp" rel="nofollow no...
python|numpy|compression|ros|subscriber
0
360,090
40,782,271
AttributeError: module 'tensorflow' has no attribute 'reset_default_graph'
<p>I have installed tensorflow version r0.11. </p> <p>In my file name <code>cartpole.py</code> I have imported <code>tensorflow</code>:</p> <pre><code> import tensorflow as tf </code></pre> <p>and use it:</p> <pre><code> tf.reset_default_graph() </code></pre> <p>Trying to run my project in PyCharm I get this err...
<p>This function is deprecated. Use <code>tf.compat.v1.reset_default_graph()</code> instead.</p> <p><em>Update</em> This is not the only function to be out of date. Check out <a href="https://stackoverflow.com/a/55872941/8205650">this answer</a> for release notes and a conversion script. </p>
python|tensorflow|pycharm
73
360,091
41,146,648
Apply function n items at a time along axis
<p>I am looking for a way to apply a function n items at the time along an axis. E.g.</p> <pre><code>array([[ 1, 2], [ 3, 4], [ 5, 6], [ 7, 8]]) </code></pre> <p>If I apply <code>sum</code> across the rows 2 items at a time I get:</p> <pre><code>array([[ 4, 6], [ 12, 14]]) </cod...
<p>This is a reduction:</p> <pre><code>numpy.add.reduceat(a, [0,2]) &gt;&gt;&gt; array([[ 4, 6], [12, 14]], dtype=int32) </code></pre> <p>As long as by "larger" you mean longer in the "y" axis, you can extend:</p> <pre><code>a = numpy.array([[ 1, 2], [ 3, 4], [ 5, 6],...
python|numpy|multidimensional-array
3
360,092
40,894,157
Python: which is the best way to read large .csv file?
<p>I have to read large <code>.csv</code> of around <code>20MB</code>. Those files are tables composed by <code>8</code> columns and <code>5198</code> rows. I have to do some statistics over a specific column <code>I</code>.</p> <p>I have <code>n</code> different files and this what I am doing:</p> <pre><code>stat = ...
<p><strong>EDIT: Apparently this is a really bad way to do it! Don't do what I did I guess :/</strong></p> <p>I'm working on a similar problem right now with about the same size dataset. The method I'm using is numpy's genfromtxt</p> <pre><code>import numpy as np ary2d = np.genfromtxt('yourfile.csv', delimiter=',', ...
python|csv|pandas|io
-2
360,093
41,197,047
float object not attribute of str error
<p>one of my columns in my dataframe is IC no. (below), which is the country identification card number of the member. I am trying to create another column to sniff out those with 'S' infront using function and apply method. But I got the error message below. Can someone point out the problem? Thanks!</p> <p><a href="...
<p>change</p> <pre><code>if str(x['IC No_']).startswith('S'): return 1 </code></pre>
python|pandas|dataframe|error-handling
0
360,094
41,212,472
using Pandas to download/load xls from URL file
<p>I am trying to load the Excel file from the following URL into a dataframe using Python 3.5 and Pandas: </p> <pre><code>link = "https://hub.coursera-notebooks.org/user/ejquqxfjajkufidbixxvkx/notebooks/Energy%20Indicators.xls" </code></pre> <p>First I tried to download the file manually using urllib.request in orde...
<p>For this specific Coursera exercise, and not as a general case, you can use not the whole URL in read_excel function, but just 'Energy Indicators.xls'</p> <pre><code>energy = pd.read_excel('Energy Indicators.xls',...) </code></pre>
python-3.x|pandas
2
360,095
54,156,920
exporting 3D array to Excel workbook
<p>I have a 3D array (TAU) with the shape (t,l,b)=(122,40,30) that I want to export to an Excel workbook as 2D with the third dimension being the number of sheets. So basically the result would be 30 sheets, each with a table of 122 rows and 40 columns. It takes three <code>for</code> loops (t,l and b) to form this ar...
<p>The code below produces the output I think you are looking for.</p> <pre><code>data = np.zeros((122, 40, 30)) writer = pd.ExcelWriter('file.xlsx', engine='xlsxwriter') for i in range(0, 30): df = pd.DataFrame(data[:,:,i]) df.to_excel(writer, sheet_name='bin%d' % i) writer.save() </code></pre>
python|excel|python-3.x|pandas|multidimensional-array
1
360,096
53,932,468
Create a column by applying a conditional statement to multiple other columns of dtypes datetime and integer
<p>I have a dataframe called <code>df</code> that looks similar to this (except the Visits go up to 74 and there are several hundred clients - I have simplified it here).</p> <pre><code>Client Visit_1 Visit_2 Visit_3 Visit_4 Visit_5 Eligible Active Client_1 2016-05-10 2016-05-25 2016-06...
<p>I think, this is certainly a way to do this:</p> <pre><code>import pandas as pd from collections import OrderedDict df = pd.DataFrame(OrderedDict([ ("Client", ["Client_1", "Client_2", "Client_3", "Client_4"]), ("Visit_1", ["2016-05-10", "2017-05-10", "2018-09-10", "2018-10-10"]), ("Visit_2", ["2016-05-...
python|pandas|datetime
1
360,097
54,246,970
What am I doing wrong with Tensorflow?
<p>I'm currently having trouble with a machine learning project in Tensorflow. The input to the neural network is a 26x1 list of numbers, and the desired output is a 5x16 binary array. </p> <p>I am training with this data. Here is my <a href="https://raw.githubusercontent.com/stockfish8/PolySolver/master/testing_sampl...
<p>You should change the activation at the output layer to sigmoid, which will give you values in the [0, 1] range. You can then apply threshold to get binary values.</p> <pre><code>model.add(tf.keras.layers.Dense(80, activation=keras.activations.sigmoid)) </code></pre> <p>Note that keras computes binary accuracy by ...
python|tensorflow|machine-learning
0
360,098
53,959,442
Lookup values in cells based on values in another column
<p>I have a pandas dataframe that looks like:</p> <pre><code> Best_val A B C Value(1 - Best_Val) A 0.1 0.29 0.3 0.9 B 0.33 0.21 0.45 0.79 A 0.16 0.71 0.56 0.84 C 0.51 0.26 0.85 0.15 </code></pre> <p>I want to fe...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.lookup.html" rel="nofollow noreferrer"><code>DataFrame.lookup</code></a> for performance.</p> <pre><code>df['Value'] = 1 - df.lookup(df.index, df.BestVal) df BestVal A B C Value 0 A 0.10 0.29 0.30 0.90 1 ...
python|pandas|dataframe
1
360,099
53,979,631
If/Then apply different function depending on each value in array
<p>I have an allegedly easy to solve question, but i still cannot figure it out:</p> <p>I have an array with 1000 numbers called "mu" like this: </p> <pre><code>array([2.25492522e-01, 2.21059993e-01, 2.16757006e-01,....) </code></pre> <p>Now i need to plug these values in two different functions: For numbers in the ...
<p>One problem is you aren't using <code>item</code> in your <code>for</code> loop. Nor are you appending to a list or assigning to a new array to store your results. In any case, NumPy has specific functions designed for this task. For example, using <a href="https://docs.scipy.org/doc/numpy-1.15.1/reference/generated...
python|arrays|python-2.7|numpy
3