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
14,000
44,977,347
tf.train.shuffle_batch() ValueError: Cannot infer Tensor's rank: Tensor("PyFunc:0", dtype=uint8)
<p>I am trying to feed my image data from my <code>TFRecord</code> files into <code>tf.train.shuffle_batch()</code>. I have a <code>load_img_file()</code> function that reads the <code>TFRecord</code> files, does preprocessing, and returns the images and one-hot labels in the format [[array of images, <code>np.uint8</...
<p><a href="https://stackoverflow.com/questions/42590431/output-from-tensorflow-py-func-has-unknown-rank-shape" title="link">The link</a> in the comments helped a lot; thank you! (The answer is that you have to give the shape when using py_func.) Since I had to figure out a little bit more on top of that I will post ...
tensorflow
3
14,001
45,263,600
Add multiple LSTM layers in tflearn
<p>How do I add another LSTM layer for following neural network?</p> <pre><code>net = tflearn.input_data([None, width, height]) net = tflearn.lstm(net, 128 ) net = tflearn.fully_connected(net, classes, activation='softmax') net = tflearn.regression(net, optimizer='adam', learning_rate=learning_rate, loss='categorical_...
<pre><code>net = tflearn.lstm(net, 128, return_seq=True) net = tflearn.lstm(net, 256) </code></pre> <p>Don't forget to set <code>return_seq=True</code> on your previous LSTM layer or you will get an error</p>
tensorflow|deep-learning|lstm|tflearn
1
14,002
56,900,218
delete dataframe by index from other dataframe
<p>I have two dataframe df1 and df2. I want to delete data from df2 based on the index from df1.</p> <pre><code>import pandas as pd df1=pd.DataFrame({'index':[1,2,3,4], 'names':['andi','andrew','jhon','andreas']}) df2=pd.DataFrame({'index':[1,2], 'names':['andi','andrew']}) </code></p...
<p>If need remove rows by index values use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html" rel="nofollow noreferrer"><code>DataFrame.drop</code></a>:</p> <pre><code>df = df1.drop(df2.index) print (df) index names 2 3 jhon 3 4 andreas </code></pre> <p...
python|pandas|dataframe
4
14,003
57,000,107
I have to files and I need to fill the gaps of file LookupHere based on the dates of file AddValueHere
<p>I am totally new to python and I have no idea if this is the best way to do it. I have two txt files:</p> <p>LookupHere.txt</p> <pre><code>Date,RPM 07/03/2016 1:00,14.21 07/03/2016 1:10,13.67 07/03/2016 1:20,13.17 07/03/2016 1:30,12.98 07/03/2016 1:40,11.44 </code></pre> <p>AddValueHere.txt</p> <pre><code>Date ...
<p>You could use pandas.DataFrame.join()</p> <pre><code>import pandas as pd add_values = pd.read_csv("C:\\Python\\scripts\\AddValueHere.txt") lookup_here = pd.read_csv("C:\\Python\\scripts\\LookupHere.txt") # set date to datetime add_values['Date'] = pd.to_datetime(add_values['Date']) lookup_here['Date'] = pd.to_dat...
python|pandas
0
14,004
57,095,560
How to ensure that the index within and array contains only valid input?
<p>So, I am trying to one hot encode an array and this problem is showing up. Whenever I try to execute the code it says that there is an index error. I am coding in google colaboratory.</p> <p>I have tried using double square brackets to solve the problem, but still no solution</p> <pre><code>def read_dataset(): ...
<p>I can reproduce your error with:</p> <pre><code>In [1]: labels = ['one','two'] In [2]: arr = np.zeros((2,2)) In [3]: arr[np.arange(2), labels] ...
python|pandas
0
14,005
57,152,086
Python Pandas: if date1 == 0, copy from date2
<p>I have a dataframe with two date fields (JDRDT and JDCKDT) and at times there is a 0 in JDCKDT. I want to find those and copy the date from JDRDT to this field. </p> <p>My question is how to do this?</p> <p>Example: </p> <pre><code>Index JDCKDT JDCKDT 10994 19991231 0 11147 19991231 0 </code></...
<pre><code>df['JDCKDT'] = np.where(df['JDCKDT']==0, df['JDRDT'], df['JDCKDT']) </code></pre>
python|pandas
2
14,006
46,035,025
sum and groupby does not work for me using pandas
<p>I have the following dataset:</p> <p><a href="https://i.stack.imgur.com/JW3F3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JW3F3.png" alt="enter image description here"></a></p> <p>I want to sum column <code>cantidad</code>(Amount) grouping by <code>nombre</code>(name) using pandas, so I have...
<p>You need <code>skipinitialspace=True</code> because values in column <code>nombre</code> has trailing whitespaces - so <code>'Ana'</code>, <code>' Ana'</code>, <code>' Ana '</code> ... is grouped separately:</p> <pre><code>historical_names = pd.read_csv('nombres-1920-1924.csv', skipinitialspace =True) print (histor...
python|pandas|csv
2
14,007
45,771,554
Why "numpy.any" has no short-circuit mechanism?
<p>I don't understand why a so basic optimization has not yet be done:</p> <pre><code>In [1]: one_million_ones = np.ones(10**6) In [2]: %timeit one_million_ones.any() 100 loops, best of 3: 693µs per loop In [3]: ten_millions_ones = np.ones(10**7) In [4]: %timeit ten_millions_ones.any() 10 loops, best of 3: 7.03 ms per...
<p>It's an unfixed performance regression. <a href="https://github.com/numpy/numpy/issues/3446" rel="noreferrer">NumPy issue 3446.</a> There actually <em>is</em> <a href="https://github.com/numpy/numpy/blob/95ffd706890c472a1c06e4e07cbe4f259407216e/numpy/core/src/umath/loops.c.src#L736" rel="noreferrer">short-circuiting...
python|performance|numpy
14
14,008
45,933,066
Attribute not working
<p>i'm trying to get stock market history using pandas-datareader i install pandas-datareader by pip install pandas-datareader</p> <p>here is my code which i am trying to get data</p> <pre><code>import pandas as pd import datetime from pandas_datareader import data, wb import matplotlib.pyplot as plt from matplotl...
<p>Your import statement is wrong, change it to <code>from pandas_datareader import data, wb</code></p> <p>There is a great answer about modules and packages here <a href="https://softwareengineering.stackexchange.com/a/111882/246262">https://softwareengineering.stackexchange.com/a/111882/246262</a></p>
python|pandas
0
14,009
35,376,308
Check for duplicates in a python panda data structure
<p>I have a csv file. It looks something like this;</p> <pre><code>name,id, AAA,1111, BBB,2222, CCC,3333, DDD,2222, </code></pre> <p>I would like to extract the data in <code>id</code> column and placed inside a data structure. For this, I used python panda. Here is the code for doing this;</p> <pre><code>import pan...
<p>To find out whether there are duplicate IDs in that whole column, do</p> <pre><code>df['id'].duplicated().any() </code></pre>
python|python-2.7|pandas
5
14,010
35,444,052
Python CSV data analysis based on date time
<p>I have a large CSV file that we will be using to import assets into our asset management database. Here is a smaller example for the CSV data.</p> <pre><code>Serial number,Movement type,Posting date 2LMXK1,101,1/5/15 9:00 2LMXK1,102,1/5/15 9:30 2LMXK1,201,1/5/15 10:30 2LMXK1,202,1/5/15 13:00 2LMXK1,301,1/5/15 14:00...
<p>Pandas is a useful library for more than just reading csv files. In fact, you don't need the csv library at all here (it's not being used in the code sample you posted)</p> <p>First you need to make sure the dates are read in as dates, by using the <code>parse_dates</code> parameter of the <code>read_csv</code> fun...
python|csv|datetime|dictionary|pandas
3
14,011
35,712,689
reindex multiindex pandas dataframe
<p>Regards.</p> <p>I'm Struggling trying to figure out how to do the next operation in pandas:</p> <p>I have a csv file with timestamps of stations like the following:</p> <p><a href="http://i.stack.imgur.com/xFsaP.png" rel="nofollow">head of the file</a></p> <p>The next thing I do is the following pivot_table usin...
<pre><code>import datetime as dt import pandas as pd from pandas import Timestamp df = pd.DataFrame( {'action': ['C', 'C', 'C', 'C', 'C', 'A', 'C'], 'bike': [89, 89, 57, 29, 76, 69, 17], 'cust_id': [6, 6, 30, 30, 30, 30, 30], 'date': [Timestamp('2010-02-02 00:00:00'), Timestamp('2010-0...
python-2.7|pandas
2
14,012
28,733,090
Python: When would 0.0/0.0 =NaN or inf , when would it gives exception?
<p>I got a dataframe in python.pandas:</p> <pre><code>q v k 0 0 16 42 14 59 ... ... </code></pre> <p>Now I want let k=q/v if v!=0 else k=0. This is how I did:</p> <pre><code>&gt;&gt;&gt;df['k'] = df['q'].astype(float16) /df['v'].astype(float16) q v k 0 0 NaN &gt;&gt;&gt;df['k'][df['v']==0] =...
<p>you can use this for a one liner:</p> <pre><code>df =pd.DataFrame({'q':[0,16,14],'v':[0,42,59]}) df.astype('float64') df['k']=(df.q/df.v).replace({ np.inf : 0 }) </code></pre> <p>Numpy is handling the divide by zero error. (The behavior can be changed using sterr <a href="http://docs.scipy.org/doc/numpy/reference/...
python|exception|pandas|division
2
14,013
28,773,186
What does ret and frame mean here?
<p>When to use ret and frame? What values do these variables hold? I have just started with image processing, so if there are more changes do let me know.</p> <p>Thank you</p> <pre><code>import numpy as np import cv2 cap = cv2.VideoCapture('Sample Lap HUL_OB_1.56.641_Graphic.mpg') # Define the codec and create Video...
<p>"Frame" will get the next frame in the camera (via "cap"). "Ret" will obtain return value from getting the camera frame, either true of false. I recommend you to read the OpenCV tutorials(which are highly detailed) like this one for face recognition: <a href="http://docs.opencv.org/modules/contrib/doc/facerec/facere...
python|opencv|image-processing|numpy
12
14,014
33,256,823
numpy - resize array filling with 0
<p>I have the following numpy array:</p> <pre><code>a = np.array([[1.1,0.8,0.5,0,0],[1,0.85,0.5,0,0],[1,0.8,0.5,1,0]]) </code></pre> <p>with <code>shape = (3,5)</code>.</p> <p>I would like to reshape and resize it to a new array with <code>shape = (3,8)</code>, filling the new values in each row with <code>0</code>....
<p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html" rel="noreferrer"><code>np.lib.pad</code></a> -</p> <pre><code>np.lib.pad(a, ((0,0),(0,3)), 'constant', constant_values=(0)) </code></pre> <p>Sample run -</p> <pre><code>In [156]: a Out[156]: array([[ 1.1 , 0.8 , 0.5 , 0. , 0. ...
python|arrays|numpy
19
14,015
66,463,609
Excel to JSON format with python
<p>I have an excel sheet which is in the below format</p> <p><a href="https://i.stack.imgur.com/IrHtH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IrHtH.png" alt="enter image description here" /></a></p> <p>I want to convert this excel sheet into JSON format using Python. each JSON object is a dia...
<p>What you need is the <code>iterrows()</code> method, it will iterate over the dataframe's rows as (index, series) pairs. The <code>columns()</code> method will give you the list of column names, so you'll be able to iterate over the columns in the series, and access them by name.</p> <pre><code>import json import pa...
python|excel|pandas
1
14,016
66,597,272
using str.contains() in python, when it matches string perfectly and still not getting output
<p>I am using str.contains() for searching movie name from my dataframe and getting no output, but when I have partial string it is giving output correctly. What i want is how to make this code snippet work correctly for both partial and full string matching.</p> <p>using contains on <strong>partial string</strong>, if...
<p>Add an argument <code>regex=False</code> to to the <code>str.contains()</code> call.</p> <p><code>str.contains()</code> takes the first parameter as regex (regular expression) by default. So parenthesis is treated as regex symbols and does not match parenthesis literally.</p> <h2>Demo</h2> <pre><code>data = {'name':...
python|python-3.x|pandas|dataframe
1
14,017
66,450,562
Find all SUBSETS of a 1D array that have a specified number of UNIQUE elements (n) AND a specified sum (s)
<p>Consider a 1D numpy array and two constants as shown:</p> <pre><code>import numpy as np arr = np.arange(60) n = 5 s = 120 </code></pre> <p>arr is always of the form [0,1,2,3,4, ... 59,60] for example.</p> <p>QUESTION: From a 1D array (arr), I need to find all subsets exactly <code>n</code> <strong>UNIQUE</strong> ...
<p>A recursive solution follows.</p> <p>This is solvable in <code>o(len(arr)^(max(n, len(arr)-n)</code>.</p> <p><a href="https://stackoverflow.com/a/66525175/913098">I will come back to this...</a></p> <p>However, the following solution will be still much faster than yours.</p> <pre><code>import numpy as np def perms...
python|numpy
1
14,018
57,665,040
How to use Excel built-in format(accounting format) on dataframe of Pandas
<p>I am trying to output my dataframe in pandas to excel.</p> <pre><code>data = {'Names':['A', 'B', 'C', 'D'], Attending Cost’: [1, 1, 1, 1], 'Summary':[2, 2, 2, 2]} data_2 = pd.DataFrame.from_dict(data) writer = pd.ExcelWriter("test", engine='xlsxwriter') data_2.to_excel(writer, sheet_name='Sheet1', ...
<p>You are on the right track, you just need to add excel's accountancy format to your workbook. So continuing with your current code:</p> <pre><code>data = {'Names':['A', 'B', 'C', 'D'], Attending Cost’: [1, 1, 1, 1], 'Summary':[2, 2, 2, 2]} data_2 = pd.DataFrame.from_dict(data) writer = pd.ExcelWriter("test", engine...
python|excel|pandas
4
14,019
57,486,168
Generalize numpy.set1d to nd-arrays
<p>I am trying to using numpy's setdiff1d function on nd-arrays :</p> <pre><code>import numpy as np #a,b being ndarrays in_a_not_b = np.setdiff1d(a,b) </code></pre> <p>But it does not work as it's working nd-array element wise.</p> <p>e.g, if :</p> <pre><code>a = [[1,2,3],[4,5,6]] b = [[7,2,3],[4,5,6],[7,8,9]] <...
<p>You can broadcast the arrays against each other, such that the last dimension is aligned, and then check that all elements of the last axis are equal and that this is the case for at least one element in the second to last axis (the arrays to check against):</p> <pre><code>mask = a[:, None, :] == b[None, :, :] mask...
python|numpy
0
14,020
57,713,497
Inner workings of np.where() and how to check for emptiness/Noneness
<p>This is a fundamentals-related question so it might appear very dumb for other people but here it goes: From reading <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer">the docs</a> and <a href="https://stackoverflow.com/questions/34667282/numpy-where-detailed-s...
<p>Your test array:</p> <pre><code>In [57]: arr = np.array([4,5,6]) In [58]: arr Out[58]: array([4, 5, 6]) </code></pre> <p>the test produces a ...
python|arrays|numpy|data-structures|tuples
1
14,021
57,463,552
if else statement based on a binary array in numpy with vectorize function
<p>I have two numpy array: one has binary variables <code>T = [0,1,1,0,0,...]</code> The other has some random values: <code>X = [0.1, 0.2, 0.333...]</code>. I want to write a function that when <code>T[i]</code> equals to <code>0</code> <code>X[i] = 1 - X[i]</code>. I am wondering if there any vectorization function I...
<p>Try <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> : </p> <pre><code>np.where(T == 0, 1 - X, X) </code></pre> <p>Full example:</p> <pre><code># import module import numpy as np # Create T vector (random) T = np.random.randint...
python|numpy
1
14,022
24,236,156
Map values to higher dimension with Numpy
<p>I'm trying to apply a color map to a two dimensional gray-scale image in Numpy (the image is loaded/generated by OpenCV).</p> <p>I have a 256 entries long list with RGB values, which is my colormap:</p> <pre><code>cMap = [np.array([0, 0, 0], dtype=np.uint8), np.array([0, 1, 1], dtype=np.uint8), np....
<p>The function you are looking for is <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.take.html" rel="nofollow"><code>numpy.take()</code></a>. The only tricky bit is to specify <code>axis = 0</code> so that the returned image has the correct number of channels.</p> <pre><code>colorImg = np.take(np....
python|opencv|numpy
1
14,023
24,079,745
How to read columns of varying length from a text file in NumPy using genfromtxt()?
<p>I have hundreds of text files like these, with each column separated by three spaces. The data is for a year: 12 months and 31 days for each month.</p> <p>Below, I'm only showing below what's relevant to question: </p> <p>001 DIST - ADILABAD ANDHRA MEAN TEMP </p> <pre><code> DATE JAN FE...
<p>You data is not "delimited" by text. Instead it has fixed-width columns. As @EdChum shows in his answer, pandas has a function for reading data with fixed-width columns. You can also use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="noreferrer"><code>genfromtxt</code></a...
python|numpy|genfromtxt
5
14,024
43,502,829
sexmachine reporting None for all lines
<p>I'm trying to use sexmachine to identify the genders of names in a pandas DataFrame using the below code:</p> <pre><code>def gender(n): d.get_gender(n) df['gender'] = df['first_name'].apply(gender); </code></pre> <p>But every row is "None." </p> <p>Thanks for any help</p>
<p>You need to return the value</p> <p>Try this:</p> <pre><code>def gender(n): return d.get_gender(n) df['gender'] = df['first_name'].apply(gender); </code></pre>
python|pandas
1
14,025
43,838,566
Extract RGBA array from Figure matplotlib
<p>I have the following code which creates a waveform of an audio file:</p> <pre><code>times = np.arange(len(data))/float(samplerate) fig = plot.figure(figsize = (8,4), frameon = False) axes = fig.gca() if(channels == 1): #mono file axes.fill_between(times, data, color = 'k') else: #stereo file axes.fill_betwe...
<p>To read the RGB and alpha from a png file:</p> <pre><code>from scipy import misc im = misc.imread("figure.png") </code></pre> <p>In this case <code>im</code> is a 3D array (rows x columns x 4) with the RGB and alpha information for each pixel of a figure with dimensions rows x columns.</p>
python|numpy|matplotlib|plot|waveform
1
14,026
43,706,809
Trouble with import TensorFlow in Jupyter Notebook while runs fine in bash
<p>I installed tensor flow with "Installing with native pip" without installing anaconda and am able to import TensorFlow in Python Console launched from Terminal. <a href="https://i.stack.imgur.com/muvzd.png" rel="nofollow noreferrer">image</a></p> <pre><code>$ python Python 2.7.13 (default, Apr 4 2017, 08:47:57) [G...
<p>Python, Tensorflow &amp; Jupyter either must be on save version python2 / python3. Below are the commands to setup jupyter &amp; Tensorflow with python3</p> <pre><code>sudo apt install python3-pip pip3 install --upgrade pip ##optional pip3 install jupyter ##Install Tensorflow pip3 install --upgrade tensorflow ...
python|tensorflow|jupyter
0
14,027
73,141,418
How to split a dataframe into a list of dataframes with a staggered delay?
<p>If I were to have a dataframe example as follows:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame(np.random.randint(0,100,size=(15, 4)), columns=list('ABCD')) A B C D 0 91 96 36 89 1 17 18 40 97 2 38 12 22 63 3 38 13 17 96 4 48 68 65 59 5 45 28 6...
<p>The so called &quot;delay&quot; is given by the counter in this example</p> <pre><code>num_rows = 4 n = len(df) // num_rows dfs = [] counter = 0 for i in range(n): counter += i start = num_rows * i + counter _df = df.loc[start:start+num_rows-1] dfs.append(_df) dfs </code></pre>
python|pandas|list|dataframe|split
2
14,028
73,039,228
Difference between sum, 'sum' and np.sum *under the hood* (Python / Pandas / Numpy)
<p>How do, <strong>sum</strong>, <strong>'sum'</strong> and <strong>np.sum</strong> differ, under the bonnet, here:</p> <pre><code>df.agg(x=('A', sum), y=('B', 'sum'), z=('C', np.sum)) </code></pre> <p>as the output would, arguably, be identical,</p> <p>adapted from here:</p> <p><a href="https://pandas.pydata.org/docs/...
<p>When you call <code>df.agg('sum')</code> it invokes <code>df.sum()</code> (see <a href="https://stackoverflow.com/a/73042283/3888719">this answer</a> for an explanation).</p> <p><code>df.sum</code> and <code>np.sum(df)</code> will have very similar performance, as pandas Series objects implement numpy's array protoc...
python|pandas
1
14,029
70,507,099
How to check if XGBoost uses the GPU
<p>I'm writing a pytest file to check if my machine learning libraries use the GPU. For Tensorflow I can check this with <code>tf.config.list_physical_devices()</code>. For XGBoost I've so far checked it by looking at GPU utilization (<code>nvdidia-smi</code>) while running my software. But how can I check this in a si...
<p>The testing method I went with was running with <code>tree_method=&quot;gpu_hist&quot;</code>. Depending on circumstances I couldn't pin down, this either raises an error or prints a warning if no GPU can be found.</p> <p>So if no GPU can be found, the following test will catch it in one of two ways:</p> <ul> <li>ra...
python|tensorflow|gpu
0
14,030
70,653,751
How to Prepare a Dataset with Multilingual Text
<p>I am preparing a dataset for text classification in Jupyter Notebook.</p> <p><strong>However, one of the column have text sentences which contains words in both Indonesian and English language.</strong> <code>Example: 'ETUDE READY NO. 4 DAN 5\n\nTulis di keterangan' </code></p> <p><em>Anybody can advise how I should...
<p>There n number of ways you can translates data frames. As a developer I recommend to do some basic internet research. Here I'm dropping some links..</p> <blockquote> <p>Link1: <a href="https://pretagteam.com/question/translate-dataframe-python-to-english-and-save-the-result-into-a-cvs-file" rel="nofollow noreferrer"...
python|pandas|scikit-learn|jupyter-notebook|text-classification
0
14,031
70,541,401
Remove filter on a dataframe
<p>I would like to updating some cells after applying a filter to my dataframe.</p> <p>To be more precise:</p> <ul> <li>after filtering the column <code>[‘Item – ENTRY TYPE’]</code> for values <code>“FACTU”</code> and <code>“Avoir”</code>...</li> <li>I want to check if the total amount in <code>[“PNS BRUT PSSO”]</code>...
<p>I found a solution with the property loc. I post it here, it can help.</p> <pre><code> #Filter on AVOIR and FACTU only items_filter = table_final_df1.loc[table_final_df1[&quot;Item - Entry Type&quot;].isin(['FACTU', 'AVOIR'])] #Cast 'Code client' to string and remove '.0' table_final_df1[&quot;Code...
python|pandas|dataframe
0
14,032
70,714,423
aggregate and group three columns in pandas dataframe
<p>My dataframe is</p> <pre><code>df = pd.DataFrame({'col1': ['A', 'A', 'B', 'B', 'C', 'C', 'A', 'A'], 'col2': ['action1', 'action2', 'action1', 'action3', 'action2', 'action1', 'action1', 'action2'], 'col3': ['X', 'X', 'X', 'X', 'X', 'X', 'Y', 'Y']}) </code></pre> <p>it looks like...
<p>Probably many ways to do this, but here's a solution that uses groupby twice. Once to build the first set of actions, and next to group on the action and col3.</p> <pre><code>df = pd.DataFrame({'col1': ['A', 'A', 'B', 'B', 'C', 'C', 'A', 'A'], 'col2': ['action1', 'action2', 'action1', 'action3', ...
python|pandas
0
14,033
42,801,452
Tensorflow Deprecation Warning
<p>I am trying to create a convolutional neural network for image classification using one of the open access github codes. I have two classes of images. But, when I start running the one part of the code I keep getting this error</p> <pre><code>/Users/user/anaconda/envs/tensorflow/lib/python3.5/site-packages/ipykerne...
<p>Try <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/control_flow_ops/comparison_operators" rel="nofollow noreferrer"><code>tf.equal</code></a>:</p> <pre><code>correct = tf.equal(cls_pred, cls_true) </code></pre> <p>or, if it is a probability distribution rather than just the argmax already:</p> ...
machine-learning|tensorflow
0
14,034
27,087,921
Why would using 8 threads be faster than 4 threads on a 4 core Hyper Threaded CPU?
<p>I have a quad core i7 920 CPU. It is Hyperthreaded, so the computer thinks it has 8 cores.</p> <p>From what I've read on the interweb, when doing parallel tasks, I should use the number of physical cores, not the number of hyper threaded cores.</p> <p>So I have done some timings, and was surprised that using 8 thr...
<p>(Intel) hyperthreaded cores act like (up to) two CPUs. </p> <p>The observation is that a single CPU has a set of resources that are ideally busy continuously, but in practice sit idle surprising often while the CPU waits for some external event, typically memory reads or writes.</p> <p>By adding a bit of additiona...
python|numpy|parallel-processing|numba
5
14,035
14,497,777
Vectorized method to sync two arrays
<p>I have two Pandas TimeSeries: <code>x</code>, and <code>y</code>, which I would like to sync "as of". I would like to find for every element in <code>x</code> the latest (by index) element in <code>y</code> that preceeds it (by index value). For example, I would like to compute this <code>new_x</code>:</p> <pre><co...
<p>In some circles this operation is known as the "asof" join. <a href="https://gist.github.com/3686236" rel="nofollow">Here is an implementation</a>:</p> <pre><code>def diffCols(df1, df2): """ Find columns in df1 not present in df2 Return df1.columns - df2.columns maintaining the order which the resulting ...
numpy|pandas|vectorization
2
14,036
14,429,992
Can I rename fields in a numpy record array
<p>I am new to python so this may sound very basic. I have imported a csv file using csv2rec. The first row has headers. I want to change the headers to 'x', 'y', 'z'. What's the best way of doing this?</p> <pre><code>&gt;&gt;&gt; import matplotlib &gt;&gt;&gt; import matplotlib.mlab as mlab &gt;&gt;&gt; r= mlab.csv2r...
<p>You can simply assign to <code>.dtype.names</code>:</p> <pre><code>&gt;&gt;&gt; d = np.array([(1.0, 2), (3.0, 4)], dtype=[('a', float), ('b', int)]) &gt;&gt;&gt; d array([(1.0, 2), (3.0, 4)], dtype=[('a', '&lt;f8'), ('b', '&lt;i8')]) &gt;&gt;&gt; d['a'] array([ 1., 3.]) &gt;&gt;&gt; d.dtype.names ('a', 'b')...
python|numpy|matplotlib
25
14,037
25,046,813
Pandas: Merge array is too big, large, how to merge in parts?
<p>When trying to merge two dataframes using pandas I receive this message: "ValueError: array is too big." I estimate the merged table will have about 5 billion rows, which is probably too much for my computer with 8GB of RAM (is this limited just by my RAM or is it built into the pandas system?).</p> <p>I know that ...
<p>You can break up the first table using groupby (for instance, on 'scenario'). It could make sense to first make a new variable which gives you groups of exactly the size you want. Then <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#iterating-through-groups" rel="nofollow">iterate through these gro...
python|pandas
0
14,038
39,304,173
How do I deal with Pandas Series data type that has NaN?
<p>What happens when using max() and min() on pandas.core.series.Series type that has NaN in it? Is this a bug? See below,</p> <hr> <pre><code>%matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt mydata = pd.DataFrame(np.random.standard_normal((100,1)), columns=['No NaN']) mydata...
<p>you should use Pandas or NumPy functions instead of vanilla Python ones:</p> <pre><code>In [7]: mydata['Has NaN'].min(), mydata['Has NaN'].max() Out[7]: (-46.00309057827485, 62.430829637766671) In [8]: min(mydata['Has NaN']), max(mydata['Has NaN']) Out[8]: (nan, nan) In [125]: mydata.plot.hist(alpha=0.5) Out[125]...
python|pandas|matplotlib|dataframe
3
14,039
39,239,627
How to interpolate only between values (stopping before and after last NaN in a column) with pandas?
<p>If I have a <code>df</code> similar to this one: </p> <pre><code>print(df) A B C D E DATE_TIME 2016-08-10 13:57:00 3.6 A 1 NaN NaN 2016-08-10 13:58:00 4.7 A 1 4.5 NaN 2016-08-10 13:59:00 3.4 A 0 NaN 5.7 2016-08-10 14:00:00 3.5 A 0 NaN...
<p>For pandas <code>0.23.0</code> is possible use parameter <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#dataframe-interpolate-has-gained-the-limit-area-kwarg" rel="noreferrer"><code>limit_area</code></a> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.interpolate.h...
python|pandas|interpolation
5
14,040
19,400,820
How to classify values in a columns of a pandas data frame according to their value?
<p>I have a data frame that has a column that contains real values.</p> <p>I would like to have an additional column that classify these values according to heir size. For example I would like to know if a value belongs to the group of the smallest values of a group of the largest values. I would like these two groups...
<pre><code>import heapq import random x = range(100000) random.shuffle(x) print(heapq.nlargest(2, x)) </code></pre> <p>Gives: [99999, 99998]</p> <p>Now just do something like:</p> <pre><code>max_column = heapq.nlargest(len(x)/2, x) </code></pre> <p>That should give you half of your list in a "large" pile, and do th...
python|pandas|quantile
2
14,041
19,750,444
Vectorizing Multi-Dimensional Operations in Python
<p>I am wondering if vectorization can be applied to two vector inputs at once...</p> <p>Consider the following simple function:</p> <pre><code>def f(x,y): return(x+y,x-y) </code></pre> <p>I want to give a function like this, two vectors <code>x=arange(3)</code> and <code>y=arange(4,6)</code>. My instinct is to...
<p>This will work fine, if the dimensions of the vectors x and y are the same. You have the following code setup:</p> <pre><code>In [16]: x=arange(3) In [17]: x Out[17]: array([0, 1, 2]) In [18]: y=arange(4,6) In [19]: y Out[19]: array([4, 5]) </code></pre> <p>Obviously, x+y are not defined. Since x has 3 entities...
python|numpy|vectorization
1
14,042
19,553,464
Python Pandas Series of Datetimes to Seconds Since the Epoch
<p>Following in the spirit of <a href="https://stackoverflow.com/questions/7852855/how-to-convert-a-python-datetime-object-to-seconds">this answer</a>, I attempted the following to convert a DataFrame column of datetimes to a column of seconds since the epoch. </p> <pre><code>df['date'] = (df['date']+datetime.timedelt...
<p>Update:</p> <p>In 0.15.0 <code>Timedeltas</code> became a full-fledged dtype.</p> <p>So this becomes possible (as well as the methods below)</p> <pre><code>In [45]: s = Series(pd.timedelta_range('1 day',freq='1S',periods=5)) In [46]: s.dt.components Out[46]: days hours minutes sec...
python|datetime|pandas
15
14,043
33,875,915
How do I store a DataFrame into a BigTable in Google DataLab?
<p>I have a DataFrame df. I create a BigQuery table.</p> <pre><code># Create the schema, using the convenience of basing it on example DataFrame schema = bq.Schema.from_dataframe(df) # Create the dataset bq.DataSet('ids').create() # Create the table suri_table = bq.Table('ids.suri').create(schema = schema, overwrite...
<p>You are conflating the Cloud Datalab way with the gbq way. You should use one or the other. To do this from Cloud Datalab, once you have created the data, you can just use:</p> <pre><code>suri_table.insert_data(df) </code></pre> <p>There are a couple of options if you want to include the index, etc; see <a href="h...
python-2.7|pandas|google-cloud-datalab
1
14,044
15,046,490
Python list of numpy matrices behaving strangely
<p>I am trying to work with lists of numpy matrices and am encountering an annoying problem.</p> <p>Let's say I start with a list of ten 2x2 zero matrices</p> <pre><code>para=[numpy.matrix(numpy.zeros((2,2)))]*(10) </code></pre> <p>I access individual matrices like this</p> <pre><code>para[0] para[1] </code></pre> ...
<p>When you multiply the initial list by 10, you end up with a list of 10 numpy arrays which are in fact references to the the same underlying structure. Modifying one will modify all of them because in fact there's only one numpy array, not 10.</p> <p>If you need proof, check out this example in the REPL:</p> <pre><...
python|arrays|list|matrix|numpy
5
14,045
14,922,280
Drawing floating numbers with [0, 1] from uniform distribution by using numpy
<p>I'm currently trying to draw floating numbers from a uniform distribution.</p> <p>The Numpy provides numpy.random.uniform.</p> <pre><code>import numpy as np sample = np.random.uniform (0, 1, size = (N,) + (2,) + (2,) * K) </code></pre> <p>However, this module generates values over the half-open interval [0, 1).</...
<p>It doesn't matter if you're drawing the uniformly distributed numbers from (0,1) or [0,1] or [0,1) or (0,1]. Because the probability of getting 0 or 1 is zero.</p>
python|numpy|uniform
10
14,046
13,260,531
Validation against NumPy dtypes -- what's the least circuitous way to check values?
<p>I want to test an unknown value against the constraints that a given NumPy <code>dtype</code> implies -- e.g., if I have an integer value, is it small enough to fit in a <code>uint8</code>?</p> <p>As best I can ascertain, NumPy's <code>dtype</code> architecture doesn't offer a way to do something like this:</p> <p...
<p>If <code>a</code> is your original iterable, you could do something along the following lines:</p> <pre><code>np.all(np.array(a, dtype=np.int8) == a) </code></pre> <p>Quite simply, this compares the resulting <code>ndarray</code> to the original values, and tells you whether the conversion to <code>ndarray</code> ...
python|validation|numpy|introspection|typechecking
6
14,047
29,611,967
NumPy array sum reduce
<p>I have a numpy array with three columns of the form:</p> <pre><code>x1 y1 f1 x2 y2 f2 ... xn yn fn </code></pre> <p>The (x,y) pairs may repeat. I would need another array such that each (x,y) pair appears once and the corresponding third column is the sum of all the f values that appeared next to (x,y).</p> ...
<p>This would be one approach to solve it -</p> <pre><code>import numpy as np # Input array A = np.array([[1,2,4.0], [1,1,5.0], [1,2,3.0], [0,1,9.0]]) # Extract xy columns xy = A[:,0:2] # Perform lex sort and get the sorted indices and xy pairs sorted_idx = np.lexs...
python|performance|numpy|sum|reduce
2
14,048
29,639,819
Save numpy array in SVG format
<p>I have an image which I want to save in svg format. The image is in the form of a numpy array. Although, there exist many methods to save array in different image formats, I could not find the one which says it could be done in svg.</p> <p>Any pointers or python script would be great!</p> <p>Thanks</p>
<p>Since your image is in a raster format, the best you can do is to convert it to vector graphics with some program like <a href="https://en.wikipedia.org/wiki/Potrace" rel="nofollow noreferrer" title="potrace">potrace</a>. It has python bindings <a href="https://pypi.python.org/pypi/pypotrace" rel="nofollow noreferre...
python|image|numpy|svg
1
14,049
62,090,775
pandas clients table >> add edges to a nodes column and deltatimes
<p>I have a data table I would like to create a graph. (see data example for pasting at the end) For that I would like to create the nodes and the edges. Every client go through different process states. The edges connect two states (nodes) My aim is to get the edges as shown in the excel table screenshot and the delta...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shift.html" rel="nofollow noreferrer"><strong><code>df.shift</code></strong></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.cat.html" rel="nofollow noreferrer"><strong><cod...
python|pandas|timedelta
1
14,050
62,106,413
group by filtered pandas dataframe and select latest in each group
<p>I'm facing a problem with filtered dataframe and groupby <br> Say I have this dataframe</p> <pre> id product date 0 220 6647 2015-09-01 1 220 6647 2014-09-03 2 220 6647 2014-10-16 3 826 3380 2014-11-11 4 826 3380 2015-12-09 5 826 3380 2015-05-19 6 ...
<p>ok, I got it<br> the example I posted is taken from another article and it works perfect<br> my own example is a bit different<br> my dataframe groupby item is taype category<br> if I leave it as object it works</p>
python|dataframe|pandas-groupby
0
14,051
62,149,406
How do I predict using my type <torchvision.models> upon my set of images? Python / Torchvision / PyTorch
<p>I've trained my images upon my training and validation set, but now I wish to apply my model to my testing set (which I also have the classifications stored). The only way I've seen of even processing the testing set is via the exact same mechanisms of the validation set, but this makes it an extension of the valida...
<p>Try something like below</p> <pre><code>def predict(model, dataloader): # Set model to evaluate mode model.eval() predictions = [] with torch.no_grad() # Iterate over data. for inputs, _ in dataloader: outputs = model(inputs) _, preds = torch.max(outputs, 1) predictions.exten...
python|pytorch|torchvision
0
14,052
62,067,207
Why am I not able to import TFLearn?
<p>I'm trying to import TFLearn with this simple code:</p> <pre><code>import tflearn </code></pre> <p>But I'm getting the following error:</p> <pre><code>AttributeError: module 'tensorflow.python.framework.ops' has no attribute 'RegisterShape' </code></pre> <p>I've got installed the following versions of programs:<...
<p>This question is answered here: <a href="https://stackoverflow.com/questions/59043649/attributeerror-module-tensorflow-python-framework-ops-has-no-attribute-regis">AttributeError: module &#39;tensorflow.python.framework.ops&#39; has no attribute &#39;RegisterShape&#39;</a></p> <p>Maybe you can find help there.</p>
python|tensorflow2.0|tflearn
0
14,053
62,114,631
pytorch got None after backward()
<p>I am learning pytorch and write a simple code as below.</p> <pre class="lang-py prettyprint-override"><code>import torch x = torch.randn(3,requires_grad=True).cuda() print(x) y = x * x print(y) y.backward(torch.tensor([1,1.0,1]).cuda()) print(x.grad) </code></pre> <pre><code>tensor([ 0.5934, -1.8813, -0.7817], dev...
<p>I got it.</p> <pre class="lang-py prettyprint-override"><code>x = torch.randn(3,requires_grad=True).cuda() </code></pre> <p>x is create by <strong>cuda()</strong>. So x is not a leaf tensor.</p> <p>Change the code as below will be ok.</p> <pre class="lang-py prettyprint-override"><code>x = torch.randn(3,requires...
python-3.x|pytorch
1
14,054
62,064,513
ValueError: time data '18-Aug-08' does not match format '%d/%m/%Y' (match)
<p>I try to convert the Start Date column to particular format the below output similar to '<strong>18/August/2008</strong>'.</p> <blockquote> <pre><code> df['Start Date'] = pd.to_datetime(df['Start Date'], format='%d/%m/%Y') 0 18-Aug-08 1 20-Aug-08 2 24-Aug-08 3 27-Aug-08 4 29-Aug-08 5 ...
<p>Use <code>%d-%b-%y</code> pattern, check also <a href="https://strftime.org/" rel="nofollow noreferrer"><code>https://strftime.org/</code></a> for more information: </p> <pre><code>df['Start Date'] = pd.to_datetime(df['Start Date'], format='%d-%b-%y') print (df) Start Date 0 2008-08-18 1 2008-08-20 2 2008-08-24 3...
python|pandas|datetime
0
14,055
62,074,040
Select a specific group of a grouped dataframe with pandas
<p>I have the following dataframe:</p> <pre><code>df.index = df['Date'] df.groupby([df.index.month, df['Category'])['Amount'].sum() Date Category Amount 1 A -125.35 B -40.00 ... 12 A 505.15 B -209.00 </code></pre> <p>I ...
<p>You can use <code>IndexSlice</code>:</p> <pre><code># groupby here df_group = df.groupby([df.index.month, df['Category'])['Amount'].sum() # report only Category B df_group.loc[pd.IndexSlice[:,'B'],:] </code></pre> <p>Or query:</p> <pre><code># query works with index level name too df_group.query('Category=="B"')...
python|pandas|dataframe
2
14,056
51,178,629
What is the precise meaning of slice(-4, 4, 0.25)?
<p>In most Python tutorials, <code>slice</code> is described as a notation, such as myarray[1:] for the sub-array of myarray starting from the 2nd element.</p> <p>Now I need to invoke <code>scipy.optimize.brute</code> which needs a slice as an object in its arguments. Its example code uses <code>slice(-4,4,0.25)</co...
<p>That is a <a href="https://docs.python.org/3/library/functions.html#slice" rel="nofollow noreferrer"><code>slice</code></a> object which can be passed as an argument to an index, giving it the given slice parameters.</p> <p>e.g.</p> <pre><code>import numpy as np a = np.arange(10) s = slice(2,7,2) print(a[s]) ...
python|numpy|slice
1
14,057
48,307,008
Pandas to_sql doesn't insert any data in my table
<p>I am trying to insert some data in a table I have created. I have a data frame that looks like this:</p> <p><a href="https://i.stack.imgur.com/mslic.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mslic.png" alt="dataframe"></a></p> <p>I created a table:</p> <pre><code>create table online.ds_attribution...
<p>Try to specify a schema name:</p> <pre><code>result.to_sql('ds_attribution_probabilities', con=engine, schema='online', index=False, if_exists='append') </code></pre>
python|pandas|sqlalchemy
41
14,058
47,999,019
TensorFlow - "TypeError: Fetch Argument None"
<p>TensorFlow is throwing a <em>TypeError</em> when I execute the simplest possible graph. </p> <pre><code>sess = tf.Session() x1 = tf.placeholder(tf.float32) x2 = tf.placeholder(tf.float32) z = x1 sess.run(tf.gradients(z, [x1, x2]), feed_dict={x1: 1, x2: 1}) </code></pre> <p>This yields </p> <pre><code>TypeError: ...
<p>According to your description, I properly modify the code. </p> <pre><code>import tensorflow as tf sess = tf.Session() x1 = tf.placeholder(tf.float32) x2 = tf.placeholder(tf.float32) z = x1 print sess.run(tf.gradients(z, [x1]), feed_dict={x1: 1}) z = x1 + x2 print sess.run(tf.gradients(z, [x1, x2]), feed_dict={x...
tensorflow|machine-learning|typeerror|gradient-descent
2
14,059
48,199,077
Elementwise aggregation (average) of values in a list of numpy arrays with same shape
<p>I have a list of numpy arrays. I want to calculate the average of values in these arrays. For example:</p> <pre><code>import numpy as np arrays = [np.random.random((4,2)) for _ in range(3)] </code></pre> <p>How can I have the average of elements in this array?</p> <p>That is I want the results to be of shape <cod...
<p>Use the functional form of <code>np.mean</code>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; arrays = [np.random.random((4,2)) for _ in range(3)] &gt;&gt;&gt; np.mean(arrays, axis=0) </code></pre> <p>This converts your list of arrays to a 3D array of shape <code>(3, 4, 2)</code> and then takes the ...
python|arrays|numpy
10
14,060
48,361,376
Converting state-parameters of Pytorch LSTM to Keras LSTM
<p>I was trying to port an existing trained PyTorch model into Keras.</p> <p>During the porting, I got stuck at LSTM layer.</p> <p>Keras implementation of LSTM network seems to have three state kind of state matrices while Pytorch implementation have four.</p> <p>For eg, for an Bidirectional LSTM with hidden_layers=...
<p>They are really not that different. If you sum up the two bias vectors in PyTorch, the equations will be the same as what's implemented in Keras.</p> <p>This is the LSTM formula on <a href="http://pytorch.org/docs/0.3.0/nn.html?highlight=lstm#torch.nn.LSTM" rel="noreferrer">PyTorch documentation</a>:</p> <p><a hre...
keras|lstm|pytorch
12
14,061
48,736,753
How do you load "any" model from disk into a TensorFlow Estimator without having the model_fn source code?
<p>In Keras you can load a model that you had previously trained by using:</p> <p>trained_keras_model = tf.keras.models.load_model(model_name)</p> <p>Is there any equivalent method for doing this using TensorFlow estimator API? According to the documentation, I have to use: </p> <p>trained_estimator = tf.estimator.E...
<p>I'd use <a href="https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator#export_savedmodel" rel="nofollow noreferrer"><code>Estimator.export_savedmodel()</code></a>. This will save the weights + graph in a format suitable for serving. You might also check out <a href="https://github.com/ajbouh/tfi" rel="no...
tensorflow|keras|tensorflow-estimator
2
14,062
48,792,334
How to assign DataFrame observations to groups according to a particular distribution?
<p>I have a pandas DataFrame where each observation (row) represents a person.</p> <p>I want to assign every person who satisfies a particular condition to different groups. I need this because my final aim is to create a network and link the persons in the same groups with some probabilities depeneding on the group.<...
<p>Pandas will automatically match on the index when assigning new data. Checkout the pandas <a href="https://pandas.pydata.org/pandas-docs/stable/indexing.html#different-choices-for-indexing" rel="nofollow noreferrer">docs on indexing</a>.</p> <p>Note: You wouldn't normally create the extra <code>IN_ELEM_SCHOOL</code...
python|pandas|dataframe
1
14,063
48,737,447
How to filter a numpy array using a condition in python
<p>I am using my numpy array <code>v</code> as follows to remove elements that are &lt;=1 and then select the indexes of the top 3 elements in the numpy array.</p> <pre><code> for ele in v.toarray()[0].tolist(): if ele &lt;= 1: useless_index = v.toarray()[0].tolist().index(ele) temp_lis...
<pre><code>v = v[v &gt; 1] indices = np.argpartition(v, -3)[-3:] values = v[indices] </code></pre> <p>As mentioned <a href="https://stackoverflow.com/a/23734295/365102">here</a>, <code>argpartition</code> runs in <code>O(n + k log k)</code> time. In your case, <code>n = 1e6</code>, <code>k=3</code>.</p>
python|numpy
4
14,064
70,991,292
Creating a dataframe from strings in text file using python
<p>I have a text file which is presented in the following way</p> <pre><code>Category: name1 = value1 Category: name2 = value2 Category: name3 = value3 </code></pre> <p>I have a python script that filters through the text file to find the category name but I want to create a data frame that would drop the category name...
<p>As I can see it, there are two parts to your question. One is how to parse your file into a dataframe in a some form, and the second is transform it into a specific shape.</p> <p>For the first step, let's assume the file <code>data</code> looks like this</p> <pre><code>Category: name1 = value1 Category: name2 = valu...
python|pandas|dataframe
0
14,065
51,860,703
Appending columns to a new dataframe
<p>I have a dataframe that looks like this.</p> <pre><code>df = 0 1 2 3 4 0 0.5 0.4 0.3 0.2 0.1 1 0.5 0.4 0.3 0.2 0.1 2 0.5 0.4 0.3 0.2 0.1 3 0.5 0.4 0.3 0.2 0.1 </code></pre> <p>And a list of lists that looks like this. </p> <pre><code>dir = [[0,1,2],[3,4]] </code></pre> <p>What I want to do ...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow noreferrer"><code>numpy.hstack</code></a> for prevent align columns by columns names with <code>DataFrame</code> constructor:</p> <pre><code>L = [[0,1],[2,3]] df = pd.DataFrame(np.hstack([df[x].values.T.ravel()[...
python|list|pandas|dataframe|append
3
14,066
51,646,101
Pandas - Python - how to subtract two different date columns
<p>Trying to have a column be filled with today's date minus the created_date column, but getting the following error : TypeError: unsupported operand type(s) for -: 'str' and 'str'</p> <pre><code>import datetime now = datetime.date.today() today = '{0:%m/%d/%Y}'.format(now).format(now) today data['Aging'] = today dat...
<p>I think need subtract <code>datetime</code>s, so is necessary convert <code>date</code> in <code>now</code> and in <code>Created_Date</code> column, last for convert <code>timedelta</code>s to days use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.days.html" rel="nofollow noreferrer...
python|pandas|datetime|subtraction
3
14,067
64,185,941
How can I create a random walk (with certain probability) for stock price movement in python?
<p>I want to simulate stock price movements in Python, for 3 years, with a total of 300 steps, with 5 paths. The share price can go up or down with probability of increase = q and probability of falling = 1-q.</p> <p>If it increases, the price in period t = period price t-1 x u If it decreases, the period price t = per...
<p>You have done it correctly because it is just a Bernoulli distribution.</p> <p>By using <code>numpy</code>, you can write <code>price_path</code> more concisely:</p> <pre><code>def price_path(m,T,sigma,s0,r): u = np.exp(sigma*np.sqrt(T/m)) d = 1/u q = (np.exp(sigma*T/m) - d) / (u-d) up_or_d...
python|numpy-random
0
14,068
64,376,058
Error-Rock paper scissors game using tensorflow,(Import Error and DLL load error)
<p><strong>This is the error message received</strong></p> <pre><code>ImportError Traceback (most recent call last) ~\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py in &lt;module&gt; 63 try: ---&gt; 64 from tensorflow.python._pywrap_tensorflow_internal import...
<p>1.Check whether cpu support AVX instructions sets.See <a href="https://en.wikipedia.org/wiki/Advanced_Vector_Extensions#CPUs_with_AVX" rel="nofollow noreferrer">hardware requirements</a></p> <p>2.Check whether you are installing 64 bit version <a href="https://www.tensorflow.org/install/source_windows" rel="nofollo...
python|python-3.x|tensorflow
0
14,069
64,328,101
how to list the top ten director_name that has the highest average of director_facebook_likes
<p>i use</p> <pre><code>count = df['director_name'] count.head(10) </code></pre> <p>to find the top directors but I do not know how to implement finding the top ten directors with the most director_facebook_likes how can I do that any suggestion would be appreciated</p>
<p>I am guessing that there are two columns in your dataframe</p> <ol> <li><code>director_name</code></li> <li><code>director_facebook_likes</code></li> </ol> <p>if you want to get the top 10 directors based on Facebook likes count</p> <p>this would be the option</p> <pre><code>df.nlargest(10, 'director_facebook_likes'...
python|pandas
0
14,070
64,509,596
how to making a bar graph using pandas
<p>I'm pretty new to python and I'm trying to make a <a href="https://ars.els-cdn.com/content/image/1-s2.0-S0022283613004750-gr2.jpg" rel="nofollow noreferrer">bar plot using python</a> similar to the link using <a href="https://rostlab.org/services/snap2web/" rel="nofollow noreferrer">SNAP2</a> results. The results fr...
<p>If you remove the percent sign and convert it to a number, you get the following graph.</p> <pre><code>df['Expected Accuracy'] = df['Expected Accuracy'].apply(lambda x: float(x.rstrip('%'))) </code></pre> <p><a href="https://i.stack.imgur.com/cYRJL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c...
python|pandas|dataframe|matplotlib
0
14,071
47,686,207
Comparing game names python
<p>I am trying to create an odds matcher using python that compares game names using pandas. The problem I am having is if the data is not a 100% match, then it will not recognise the game name. </p> <p>Is there an efficient way to match game names? E.g a percentage match. Fuzzy lookup? I cannot thi...
<p>You're basically asking "what are all the ways to do string comparisons in Python" which is HUGE question.</p> <p>Some real basic stuff would be to do some string formatting:</p> <ul> <li>make everything lowercase (e.g <a href="https://pandas.pydata.org/pandas-docs/stable/text.html" rel="nofollow noreferrer">here<...
python|string|algorithm|pandas|compare
0
14,072
49,014,512
Tensorflow object detection evaluation
<p>I like to evaluate my object detection model with mAP (mean average precision). In <a href="https://github.com/tensorflow/models/tree/master/research/object_detection/utils/" rel="nofollow noreferrer">https://github.com/tensorflow/models/tree/master/research/object_detection/utils/</a> there is object_detection_eva...
<p>Although you are not so clear about it I think I found the error in your code. You mentioned you get different results for different order of bounding boxes. This seems peculiar and if true then it was surely a bug. </p> <p>But, since I tested the code myself, you probably <em>did not change the corresponding score...
tensorflow|object-detection|evaluation
0
14,073
49,189,711
Tensorflow CNN does not learn (image in - image out)
<p>i'm stuck working on a Tensorflow Convolutional Neural Network for a university project and i hope somebody can help me.<br> it's supposed to output a picture for a picture input. left is input, right is output. both are in .jpeg format.</p> <p><a href="https://i.stack.imgur.com/awRe7.jpg" rel="nofollow noreferrer"...
<ul> <li>This is an Image generation problem</li> <li>The model you selected is a very bad model for Image generation tasks</li> <li>Normal CNNs are used for image recognition and object detection tasks</li> <li>The tutorial on MNIST is image classification problem and not image generation problem</li> <li>It is very i...
python|tensorflow
0
14,074
58,680,682
Number of layers of the model
<p>I'm training a CNN. For reporting purposes, I want to find out the number of layers my model has.</p> <p>From what I see in the code below, I have a total of 6 layers, layer1, layer2, conv2_drop, fc1, fc2, fc3. Am I right?</p> <pre><code>Net( (layer1): Sequential( (0): Conv2d(3, 10, kernel_size=(5, 5), strid...
<p>It is not entirely clear what one would consider a layer (is <code>flattening</code> a layer or just an operation? What if it's implemented as <code>torch.nn.Module</code>?). Neural networks are, in essence, graphs performing operations, layers are a helpful abstraction which helps us reason about them.</p> <p>In P...
neural-network|conv-neural-network|pytorch
0
14,075
70,248,207
Numpy: Generate matrix recursively
<p>Is there a smart way to recursively generate matrices with increasing sizes in numpy? I do have a generator matrix which is</p> <pre><code>g = np.array([[1, 0], [1, 1]]) </code></pre> <p>And in every further iteration, the size of both axes doubles, making a new matrix of the format:</p> <pre><code>[g_{n-1}, 0], [g_...
<p>I don't see a straight-forward way to generate <code>g_n</code>, but you can reduce the two for-loops to one (along <code>n</code>) with:</p> <pre><code># another sample g = np.array([[1, 0], [2, 3]]) g = (np.array([[g,np.zeros_like(g)],[g, g]]) .swapaxes(1,2).reshape(2*g.shape[0], 2*g.shape[1]) ) </code...
python-3.x|numpy|matrix
1
14,076
70,074,052
How do I make a function in python which takes a list of integers as an input and outputs smaller lists with only two values?
<p>I have a list of scraped betting odds as well as team names shown <a href="https://i.stack.imgur.com/ssXK1." rel="nofollow noreferrer">here</a>. Before I can do calculations on the data to determine if I want to make a bet I want to group my data such that odds that are paired together are in their own separate list...
<p>If you only want groups of two (as opposed to groups of n), then you can hardcode n=2 and use a list comprehension to return a list of lists. This will also create a group of one at the end of the list if the length of the list is odd:</p> <pre><code>some_list = ['a','b','c','d','e'] [some_list[i:i+2] for i in range...
python|pandas|numpy
-1
14,077
55,676,038
Intrepolating between two data frames
<p>i have two data frames</p> <p>a=</p> <pre><code>x y 10 10 47 9 58 8 68 7 75 6 80 5 </code></pre> <p>b= </p> <pre><code>x y 45 10 55 9 66 8 69 7 79 6 82 5 </code></pre> <p>I want to interpolate between them and generate new data frame with N sampling rate</p> <p>assume N=3 for this example</p> ...
<p>First, you could use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sample.html" rel="nofollow noreferrer">df.sample</a> to generate new datas for x only after <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferr...
python|pandas|dataframe|interpolation
0
14,078
64,741,271
House prices: Advanced regression techniques, Feature importance and Plot barplot of top 5 Feature Importances
<p>I am working on a project where I need to plot barplot of top 5 Feature Importances, using a data set of House prices: Advanced regression techniques, I have calculated the RandomForest Regressor using :</p> <pre><code>RF_model = RandomForestRegressor() RF_model.fit(x,y) RF_model.score(x,y) pred=RF_model.predic...
<p>You can access the <code>feature_importances_</code> attribute of your trained model with <code>RF_model.feature_importances_</code>. Then you can plot them as needed. Check out the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html" rel="nofollow noreferrer"><code...
python|pandas|jupyter-notebook
0
14,079
64,974,686
Pandas Excel groupby/count
<p>Hi I'm trying to have my script count the number of times it sees the same words in specified columns with some of those columns having multiple separated by a comma.</p> <p>For example -</p> <pre><code>Labels Labs a1, b3 1 a2 3 b3 ...
<p><strong>Keys</strong></p> <ol> <li>Convert the comma-separated string into lists first.</li> <li>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer">df.explode()</a> to expand the entries.</li> <li>Pivoted aggregation (to which concept that...
python|pandas
2
14,080
64,836,989
How to display only Categories in the legend present in the data
<p>I have a data frame as below:</p> <p><a href="https://i.stack.imgur.com/jD8BR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jD8BR.png" alt="enter image description here" /></a></p> <p>In the above dataframe, <code>'Month'</code> is an ordered <code>Categorical</code> column defined as:</p> <pre>...
<p>You could create a list of &quot;used months&quot; and then set that list as <code>hue_order</code>. This also ensures that only those months will take up space for the bars.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as s...
python|pandas|seaborn|visualization|legend
2
14,081
64,962,660
How can I arrange columns in a data frame based on other columns while keeping some coulmn items constant
<p>I have been stuck on this problem for days and would appreciate any help!</p> <pre><code>data = {&quot;Fruit&quot;: ['Apples', 'Apples', 'Apples', 'Apples', 'Bananas', 'Bananas', 'Bananas', 'Bananas'], &quot;Prices&quot;: [4.2, 3.5, 4.1, 3.8, 1.2, 1.2, 1.5, 5.1], &quot;Market PLace&quot;: ['Ma...
<p>This might help;</p> <p>You need to combine the <code>sort_values</code> function with groupby(); the <code>head</code> function gets you the top two most expensive fruits.</p> <pre><code>labels = ( df.sort_values([&quot;Fruit&quot;, &quot;Prices&quot;], ascending=[True, False]) .groupby(&quot;Fruit&quot;) ...
python|pandas
1
14,082
64,663,857
Pandas - dataframe edit string from a single column with multiple (if) conditions
<p>I have a follow dataframe, I would like to edit 'contact' column according to multiple conditions.</p> <p><a href="https://i.stack.imgur.com/IccHD.png" rel="nofollow noreferrer">Input DataFrame</a></p> <pre><code>start_date contact price shop 2020-07-14 tel:858123456789 100.0 s1 2020-07-15 tel:+8581...
<pre><code>df[&quot;contact&quot;] = df.apply(lambda row: row[&quot;contact&quot;].replace(&quot;tel&quot;, &quot;&quot;).replace(&quot;:&quot;, &quot;&quot;).replace(&quot;+&quot;, &quot;&quot;), axis=1) </code></pre> <p>This is just one way that is clear. You can try with regex as well.</p>
python|pandas|dataframe
0
14,083
39,988,107
How to get point coordinates from distance matrix?
<p>I have the following data set, each data is an array with 128 elements. </p> <pre><code>[-0.08 0.23 0.21 -0.17 0.01 0.01 0.01 0.11 -0.04 0.03 -0.04 -0.1 -0.04 -0.03 0.11 -0.04 -0.07 -0.02 -0.04 -0.16 0.07 0.16 -0.07 -0.13 0.06 -0.04 0.03 0.12 0.15 0.04 -0.05 -0.19 0.06 0.02 0.1 -0.1 0.09 -0.0...
<p>Your data exist in 128 dimensions, so you're asking for a Euclidean distance-preserving projection into 3 dimensions. Nothing works perfectly. The t-SNE algorithm tends to give aesthetically pleasing results.</p>
numpy|matrix|machine-learning|pca
1
14,084
39,897,698
Convert a string with ns precision to datetime in a panda dataframe
<p>I'm having a hard time converting a string with ns precision in a datetime format in a panda dataframe.</p> <p>I have a data frame like the following :</p> <pre><code>print df Event Time 0 A 08:00:00.123456789 1 B 08:00:00.234567890 2 C 08:00:00.345678901 </code></pre> <p...
<p>The following did the trick for me:</p> <pre><code>&gt;&gt;&gt; df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S.%f') &gt;&gt;&gt; df Event Time 0 A 1900-01-01 08:00:00.123456789 1 B 1900-01-01 08:00:00.234567890 2 C 1900-01-01 08:00:00.345678901 </code></pre> <p>As n...
python|pandas
2
14,085
40,127,783
Is necessary to use to both eval and run?
<p>I understood the difference between the two from this <a href="https://stackoverflow.com/questions/33610685/in-tensorflow-what-is-the-difference-between-session-run-and-tensor-eva">answer</a>. But in most talks/code online I find people using both as below:</p> <pre><code>import tensorflow as tf a=tf.constant(5.0) ...
<p>Calling <code>sess.run(c)</code> and <code>c.eval()</code>, in the same session, provide exactly the same results.</p> <p>You can mix calls to <code>sess.run</code> and <code>&lt;tensor&gt;.eval()</code> in the code, but it makes your code less consistent.</p> <p>In my opinion, it's better to use always <code>sess...
python|tensorflow
4
14,086
44,046,519
Count already used ids pandas
<p>I have a problem where i need to count already used ids. In my data set there are attributes: <code>id, time, Bi</code> witch looks something like this:</p> <pre><code>id time Bi | wanted_results used 1 3 NAN | 0 [] 1 3 1 | 1 [1] 1 2 NAN | ...
<p>You can use a combination of expanding and apply.</p> <pre><code>df['id'].expanding().apply(lambda x: len(np.unique(x))) </code></pre> <p>This will return a Series with the results you want.</p>
python|pandas
2
14,087
43,925,146
Transform json object to dataframe in python
<p>I have a <a href="http://ucdpapi.pcr.uu.se/api/gedevents/5.0?pagesize=100&amp;Geography=47%202,49%203" rel="nofollow noreferrer">json object</a> that I would like to transform into a data frame. However, with </p> <pre><code>df = pd.read_json("http://ucdpapi.pcr.uu.se/api/gedevents/5.0?pagesize=100&amp;Geography=47...
<p>This could do it as well:</p> <pre><code>import pandas as pd import json import urllib response = urllib.urlopen("http://ucdpapi.pcr.uu.se/api/gedevents/5.0?pagesize=100&amp;Geography=47%202,49%203") data = json.loads(response.read())['Result'] df = pd.DataFrame(data) </code></pre>
python|json|pandas
1
14,088
69,582,457
Grouping data series by timestamp in Pandas Dataframe (python)
<p>I have Pandas Dataframe like below:</p> <pre><code> redacted_name_1 \ 0 [1628377576.0, 1628377939.98, 1628377942.04, 1... 1 [295.257080078125, 295.1255187988281, 295.2570... redacted_name_2 \ 0 [1628377494.927, 1628377855.377, 1628377...
<p>Use list comprehension for create <code>Series</code>, join together by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> and last rounf with convert to <code>datetime</code>s if necessary:</p> <pre><code>print (df) ...
python|pandas|dataframe
1
14,089
53,939,619
Finding a Specific Line of a File Using Numpy
<p>I am using matplotlib to make a weight chart with information from a file that contains both text and numbers. The numbers are two lines that have the weights and the dates in them. The file looks like this:</p> <pre><code>1. anonymous 2. anonymous 3. 4. 34, 76 5. 12202018, 12222018 </code></pre> <p>I want to us...
<p>This will get the values from the file into your arrays:</p> <pre><code>def process(line): line = line.rstrip() line = line.split('.')[1] line = line.split(',') return line x = list() y = list() counter = 0 with open('example.txt') as data_file: for line in data_file: if (counter == 3) ...
python|python-3.x|numpy
0
14,090
65,932,593
Unable to backpropagate through torch.rfft
<p>I have two losses: one the usual L1 loss and second one involving <code>torch.rfft()</code></p> <pre><code>def dft_amp(img): fft_im = torch.rfft( img, signal_ndim=2, onesided=False ) fft_amp = fft_im[:,:,:,:,0]**2 + fft_im[:,:,:,:,1]**2 return torch.sqrt(fft_amp) l1_loss = torch.nn.L1Loss() loss = l1_...
<p>There seems to be some issue with <code>torch.sqrt()</code> and not with the <code>torch.rfft()</code>. <code>torch.sqrt()</code> cannot handle very small values. Thus in the above code replace</p> <p><code>return torch.sqrt(fft_amp)</code></p> <p>with</p> <p><code>return torch.sqrt(fft_amp + 1e-10)</code></p> <p>an...
pytorch
0
14,091
66,318,593
How to select lists with the same id in python?
<p>I have a dataframe that look like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>place</th> <th>age</th> <th>gender</th> </tr> </thead> <tbody> <tr> <td>13</td> <td>1</td> <td>3</td> <td>1</td> </tr> <tr> <td>13</td> <td>2</td> <td>4</td> <td>1</td> </tr> <tr> <td>13</...
<p>You can select all the rows which have the <code>id</code> as 13 by doing just <code>df[df['id'] == 13]</code>.</p> <p>And if you only want the remaining columns <code>place</code>, <code>age</code> and <code>gender</code>, then:</p> <pre class="lang-py prettyprint-override"><code>df.loc[df['id'] == 13, ['place', 'a...
python|pandas|data-preprocessing
0
14,092
65,988,166
Pytorch: why does torch.where method does not work like numpy.where?
<p>In order to replace positive values with a certain number and negative ones with another number in a random vector using <code>Numpy</code> one can do the following:</p> <pre><code>npy_p = np.random.randn(4,6) quant = np.where(npy_p&gt;0, c_plus , np.where(npy_p&lt;0, c_minus , npy_p)) </code></pre> <p>However <code...
<p>I can't reproduce this error, maybe it will be better if you could share a specific example where it failed (it might be the values you try to fill the tensor with):</p> <pre><code>import torch x = torch.rand(4,6) res = torch.where(x &gt; 0.3,torch.tensor(0.), torch.where(x &lt; 0.1, torch.tensor(-1.), x)) </code></...
pytorch
1
14,093
52,635,866
How to add a conda environment in jupyter
<p>I'm try to enable a keras environmnt into jupyter.<br> Using below commands I added the conda tf environment for Keras :</p> <pre><code>C:&gt;conda create --name tf python=3.5 C:&gt;activate tf (tf) C:\Keras\Test&gt;pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tens...
<p>Well when i was in the (tf) environment made earlier and typed "conda list" I got a fairly short list of installed packages (just tensorflow) about 26 packages. Then I noted that jupyter package wasnt in this environment. Not sure if it should i added it with </p> <pre><code>conda install jupyter </code></pre> <p>...
python|tensorflow|keras|jupyter-notebook|conda
1
14,094
52,492,620
Pandas groupby.agg removes columns
<p>I've read the other questions regarding similar issues but i still couldn't figure out how to overcome this.</p> <p>This expression loses all my df columns except the one on which i groupby on and another column (do not know why that in particular).</p> <p><code>df = df.groupby('Full_name').agg(';'.join).reset_ind...
<p>Try to convert all columns to <code>string</code>s:</p> <pre><code>df = df.astype(str).groupby('Full_name').agg(';'.join).reset_index() </code></pre>
python|pandas|dataframe
2
14,095
46,554,437
Split a column of strings into 3 separate columns with Pandas
<p>I'm trying to separate a dataframe column in three parts, but I'm getting this error:</p> <pre><code>too many values to unpack </code></pre> <p>This is my code:</p> <pre><code>dimensions['store'], dimensions['country'], dimensions['store_nick'] = dimensions['dimension_value'].str.split('@').str </code></pre> <p>...
<p>I'd recommend splitting first with <code>str.split</code> and <em>then</em> concatenating, using <code>pd.concat</code>:</p> <pre><code>df = dimensions['dimension_value'].str.split('@', expand=True) df.columns = ['store', 'country', 'store_nick'] dimensions = pd.concat([dimensions, df], axis=1) </code></pre> <...
python|string|pandas|dataframe
1
14,096
58,468,073
Python Dataframe setting values for a column based on groups maximum value
<p>I have the following dataframe</p> <pre><code> id Area Country 0 11 34.45 Norway 1 12 30.25 UK 2 13 16.70 Iran 3 11 35.45 Sweden 4 13 20.22 Iraq 5 15 35.12 USA dfObj['BigCountry'] = '' dfObj['SmallCountry'] = '' </code></pre> <p>Based on the area I want to classify the country eit...
<p>One way is to use <code>set_index</code> then <code>groupby</code> and <code>agg</code> with <code>idxmax</code> and <code>idxmin</code>:</p> <pre><code>df.set_index('Country').groupby('id')['Area'].agg(['idxmax','idxmin'])\ .rename(columns = {'idxmax':'BigCountry', 'idxmin':'SmallCountry'}) </code></pre> <p>Out...
python|pandas|dataframe|group-by
0
14,097
58,295,955
Keras how to view node connections?
<p>If I understand a neural net correctly - it is just a graph of <strong>nodes</strong> and <strong>edges</strong> where each node in a given layer is connected to every node in the following layer.</p> <p>The nodes have weights and the edges have weights? And you do some multiplication of these values to get a predi...
<p>The "sources" and "destinations" of those edges don't have names like "a" and "b", they're just the <em>k</em>th neuron of the <em>n</em>th layer. The weights, then, are just an array. For example, <code>weights[n][i][j]</code> might be the weight of the edge connecting the <em>i</em>th neuron of layer <em>n</em> to...
tensorflow|keras|neural-network
1
14,098
68,884,465
counter of first occurrence of unique values of another column pandas
<p>Given an example df like below, I want to find a increment counter of all unique instances of <code>val</code>. The closest that I've gotten is <code>df.groupby('val').cumcount()</code> but obviously this isn't what I want.</p> <pre><code>df = pd.DataFrame({'val': [100, 101, 104, 104, 106, 108, 108, 108]}) </code></...
<p>We could use <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.ngroup.html" rel="nofollow noreferrer"><code>groupby ngroup</code></a> to enumerate groups (<code>sort=False</code>) if wanting groups enumerated the way the appear in the DataFrame, then <a href="https://pandas.pydata.org...
python|pandas
1
14,099
68,938,290
How to find Contour based on specific color outline or border?
<p>I'm trying to detect count of contour based on yellow color outline showing below in AutoCAD drawing. <a href="https://i.stack.imgur.com/Zs6la.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zs6la.png" alt="snippet" /></a></p> <pre><code>import numpy as np import cv2 image = cv2.imread('C:/Users/...
<p>Your upper boundary cannot detect the color of the circles. Try setting it to something like this:</p> <pre><code>upper = np.array([179, 255, 255], dtype=&quot;uint8&quot;) </code></pre> <p>Feel free to play around with boundaries more to select your color.</p>
python|numpy|opencv|machine-learning|contour
0