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
372,900
46,637,452
how to condition encoder final hidden state on the inputs of RNN dynamic decoder with ScheduledOutputTrainingHelper?
<p>I'm trying to use tensorflow to code RDD encoder and decoder and with different length sequence inputs, so hope both encoder and decoder can be dynamic. Additionally, a decoder inputs is conditioned by the encoder final hidden states (context vector), which is similar to the <a href="https://arxiv.org/pdf/1702.05538...
<p>Just Find the mistake I made:</p> <p>using "context_vector_shape" to define the shape of auxiliary_inputs tensor will result no dimension size in all as (?,?,?), which lead to "ValueError: Could not infer input size from inputs.get_shape()[-1]",</p> <p>directly define the shape of auxiliary_inputs tensor as (?,?,c...
dynamic|tensorflow|decoder|rnn
0
372,901
46,739,028
How to assign variable to merged Pandas dataframe within function
<p>I'd like the dataframe passed into this function to be modified.</p> <pre><code>def func(df): left_df = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B']) right_df = pd.DataFrame([[5, 6], [7, 8]], columns=['C', 'D']) df = pd.merge(left_df, right_df, how='outer', left_index=True, right_index=True) pr...
<p>IIUC, something like this?</p> <pre><code>def func(df): left_df = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B']) right_df = pd.DataFrame([[5, 6], [7, 8]], columns=['C', 'D']) df = pd.merge(left_df, right_df, how='outer', left_index=True, right_index=True) print("df is now a merged dataframe!") ...
pandas|outer-join|pass-by-value
1
372,902
46,949,437
keep dataframe numeric after concatenation
<p>Is there a way to keep the resulting dataframe numeric after concatenating a numeric dataframe and an empty dataframe?</p> <pre><code>df1 = pd.DataFrame(data=[[1,2],[3,4]], columns=['a','b'], index=[0,1]) df1.dtypes Out[25]: a int64 b int64 dtype: object df2 = pd.DataFrame(columns=['c','d']) df2.dtypes Out[...
<p>Set <code>dtype</code> parameter to <code>float</code>:</p> <pre><code>df2 = pd.DataFrame(columns=['c','d'], dtype=float) df = pd.concat([df1,df2], axis = 1) print (df) a b c d 0 1 2 NaN NaN 1 3 4 NaN NaN print (df.dtypes) a int64 b int64 c float64 d float64 dtype: object </code></pre...
pandas|numpy|dataframe|concatenation
2
372,903
46,756,556
Cannot re-add column to pandas multi-index dataframe after deletion
<p>It seems odd that after deleting a column, I cannot add it back with the same name. So I create a simple dataframe with multi labeled columns and add a new column with level0 name only, and then I delete it.</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame([[1,2,3],[4,5,6]]) &gt;&gt;&g...
<p>There is problem your <code>MultiIndex</code> level are not removed after calling <code>del</code>:</p> <pre><code>del df['d'] print(df) a b c e f g 0 1 2 3 1 4 5 6 </code></pre> <p>Check columns:</p> <pre><code>print (df.columns) MultiIndex(levels=[['a', 'b', 'c', 'd'], ['e', 'f', 'g', '']], ...
python|pandas
1
372,904
46,740,638
Streamlining appending of boolean column in pandas dataframe
<p><strong>Disclaimer: My code is very amateurish as I am still undergoing course work activities. Please bear with me if my code is inefficient or of poor quality.</strong></p> <p>I have been learning the power of pandas in a recent Python tutorial and have been applying this to some of my course work. We have learnt...
<p>This should do the same; It's unnecessary to sum a one column data frame by row, <code>df[['Efficiency_%']].sum(axis=1)</code> is the same as <code>df['Efficiency_%']</code>, and also <em>Boolean Series == True</em> is not necessary as it yields the same result as Boolean Series itself.</p> <pre><code>df['Classific...
python|pandas|boolean
1
372,905
46,999,146
In Pandas, how to filter a Series based on the type of the values?
<p>Given a <code>Series</code> like</p> <pre><code>import pandas as pd s = pd.Series(['foo', 'bar', 42]) </code></pre> <p>I would like to obtain a 'sub-series' <code>pd.Series(['foo', 'bar'])</code> in which all values are strings. I've tried Boolean indexing like so:</p> <pre><code>s[isinstance(s, str)] </code></p...
<p>Use <code>apply</code> or list comprehension:</p> <pre><code>s[s.apply(lambda x: isinstance(x, str))] </code></pre> <p>Same as, thanks <code>Jon Clements♦</code>:</p> <pre><code>s[s.apply(isinstance, args=(str,))] </code></pre> <hr> <pre><code>s[[isinstance(x, str) for x in s]] </code></pre> <p>All return:</p>...
python|pandas
35
372,906
46,905,419
Apply on pandas' categorical Series with None
<p>The following code</p> <pre><code>df = pd.DataFrame({ 'animals': 'kot pies lis kot'.split() + [None] }, dtype='category') df.animals.apply(len) </code></pre> <p>returns <code>4</code> for None:</p> <pre><code>0 3 1 4 2 3 3 3 4 4 Name: animals, dtype: int64 </code></pre> <p>Is it a bug in pand...
<p>It seems bug, but better is use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.len.html" rel="nofollow noreferrer"><code>str.len</code></a> for correctly handling <code>NaN</code>s and <code>None</code>s:</p> <pre><code>print (df.animals.str.len()) 0 3.0 1 4.0 2 3.0 3 3...
python|pandas
2
372,907
46,962,198
Indexes of removed leading/trailing zeros from array
<p>Given a 1D array</p> <pre><code>import numpy as np arr = np.array([0, 0, 0, 0, 0, 0, 8, 83, 120, 111, 31, 37, 10, 0, 0, 0, 0, 0, 0, 0]) </code></pre> <p>I can remove the leading/trailing zeros using <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.trim_zeros.html" rel="nofollow noreferre...
<p>Use <code>argmax()</code> -</p> <pre><code>In [40]: m = arr!=0 In [41]: m.argmax()-1, m.size - m[::-1].argmax() Out[41]: (5, 13) </code></pre> <p>With <code>arr</code> as all <code>zeros</code> or all <code>non-zeros</code>, we need to define the expected output if those are to be dealt too.</p>
python|arrays|numpy
6
372,908
46,917,459
Save same image pair over epochs with tf.summary.image for semantic segmentation
<p>When training a deep network for semantic segmentation we can get a qualitative understanding of network performance by looking at the triad of image/ground truth/prediction. During training, I would like to be able to view this set in tensorboard but keep the <em>same</em> triad throughout training. </p> <p>If on...
<p>Just a quick hack. I would suggest narrowing down the set of images you forward to the summary:</p> <pre><code>#image example save tf.summary.image("input", test_x[:3], max_outputs=3) tf.summary.image("ground_truth", test_t[:3], max_outputs=3) tf.summary.image("prediction_output",output[:3],...
machine-learning|tensorflow|computer-vision
0
372,909
47,075,677
Tensorflow, FailedPreconditionError: Attempting to use uninitialised value Variable_3
<p> When I run my code I get an error that says: </p> <pre class="lang-py prettyprint-override"><code>FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Variable_3 </code></pre> <p>I have no variable in my code called Variable_3. </p> <p>Tracing back the error I can see that it ...
<p>It looks like you're not calling global_variables_initializer(). You need code like <code>sess.run(tf.global_variables_initializer())</code> where <code>sess</code> is your Session. This should be at a point in your code where all TensorFlow Variables have already been declared.</p>
macos|tensorflow
0
372,910
46,770,733
Python - How to avoid dependency of buffer variable in for loop
<p>I want to implement a very easy Insertion-Sort algorithm in python where i can sort an array row/column-wise in dependency of the nth element of the row/column</p> <pre><code>A = [(2,1,2),(1,4,1),(3,2,3)] </code></pre> <p>becomes to </p> <pre><code>A = [(1,4,1),(2,1,2),(3,2,3)] </code></pre> <p>when sorting row-...
<p>NumPy arrays are stored in contiguous memory locations. Therefore, <code>A[j+1] = A[j]</code> cannot be done by copying memory address (doing so would cause <code>A[j+1]</code> and <code>A[j]</code> to have the same addresses), and hence the assignment is done by copying the value.</p> <p>You may check the memory l...
python|arrays|numpy|for-loop|dependencies
0
372,911
46,824,441
Rearrange columns by name and number in Pandas dataframe
<p>I have a dataframe with columns like this for example (as 1 being any values to simplify things here:</p> <pre><code> ID App R1 Pear R1 Oro R1 App R2 Pear R2 Oro R2 App R3 Pear R3 Oro R3 0 1 1 1 1 1 1 1 1 1 ...
<p>Use custom <code>sorted</code> with lookup key</p> <pre><code>In [4291]: look = {'I':0, 'A':1, 'P':2, 'O':3} # order for letters In [4292]: sorted(df.columns, key=lambda x: look.get(x[0], '')) # first letter key Out[4292]: ['ID', 'App R1', 'App R2', 'App R3', 'Pear R1', 'Pear R2', 'Pear R3', 'Oro R1', '...
python|pandas
4
372,912
46,726,937
AttributeError: 'module' object has no attribute 'rnn_cell'
<p>PLEASE HELP ME</p> <pre><code>tf.nn.rnn_cell.GRUCell(self.model_parameters["num_bidirectional_units"]) </code></pre> <p>the code:<a href="https://github.com/jdbermeol/deep_voice_2" rel="nofollow noreferrer">deep_voice_2</a></p> <p>python:2.7.5 tensorflow:1.1.0</p>
<p>@Abhishek Bansal</p> <p>thank you, and i do <code>pip install -U tensorflow</code></p>
python|tensorflow
-1
372,913
46,967,312
python sklearn accuracy score for two different list
<p>I have two lists</p> <p><code>y_test = array('B', [1, 2, 3, 4, 5])</code></p> <p>and </p> <p><code>labs = [1, 2, 3, 4, 5]</code></p> <p>In sklearn, when i do <code>print accuracy_score(y_test,labs)</code>, i get error</p> <blockquote> <p>ValueError: Expected array-like (array or non-string sequence), got arra...
<p>You have to convert the array to list to make it work This should do for you accuracy_score(y_test.tolist(),labs)</p>
python|numpy|scikit-learn
0
372,914
46,896,105
Set dataframe column using values from matching indices in another dataframe
<p>I would like to set values in <code>col2</code> of <code>DF1</code> using the value held at the matching index of <code>col2</code> in <code>DF2</code>:</p> <p><code>DF1</code>:</p> <pre><code> col1 col2 index 0 a 1 b 2 c 3 d 4 e 5 f </code></pre...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" rel="noreferrer"><code>join</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="noreferrer"><code>assign</code></a>:</p> <pre><code>df = df1.join(df2['col2'...
python|pandas
9
372,915
46,840,266
Is there a drop duplicates option with combine first (pandas)
<p>Question: </p> <p>I currently have a process of taking a file from yesterday, comparing it to today's file, and dropping all values that haven't changed. The idea is to limit the amount of data being uploaded to a database to only data that has changed and is not currently in the DB. </p> <p>I was recently introdu...
<p>You don't need <code>combine_first</code> anymore, just compare and see what changed.</p> <pre><code>r = source[~(source == dest)] r['inventory number'] = source['inventory number'] print(r) cat cost inventory number map 1236 NaN 21.80 110 NaN 19497 Electronics ...
python|pandas
1
372,916
46,793,956
importing pandas error with jupyter notebook on windows 10
<p>So I deleted and reinstalled the most up to date version of Anaconda Navigator with Python 3.6 on Windows 10. I launched Jupyter notebook and tried to import </p> <p>1, numpy,</p> <p>2, matplotlib </p> <p>and 3, pandas</p> <p>It was able to import Numpy and Matplotlib but for Pandas it gave me a very long error ...
<p>from the error message it seems that Pandas is not on of the pre-installed libraries in the Anaconda that you installed. It is the not the problem with the OS. Run the following command:</p> <p>conda install -c anaconda pandas </p> <p>then run the import statement.</p>
python|pandas|jupyter-notebook
0
372,917
46,913,989
Matplotlib for google stock price example in python data science handbook
<p>Using the Python data science handbook (pg.198 Fig 3.6 resampling and converting frequencies for anyone from google), I'm trying to follow the example, which is as below:</p> <pre><code>%matplotlib inline import pandas as pd import numpy as np from pandas_datareader import data import matplotlib.pyplot as plt impor...
<p>There is nothing really wrong, just that the resampling rule <code>BA</code> with <code>mean()</code> returns only two points, thus the straight line.</p> <p>Playing with the different <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases" rel="nofollow noreferrer">available offset rul...
python|pandas|matplotlib|pandas-datareader
1
372,918
47,042,936
How do I put objects at specific indices of a NumPy array without for loop?
<p>How do I do the following without a for loop?</p> <pre><code>import numpy as np l = np.array([[1, 3], 1, np.nan, [3, 53, 13], ['225gg2g']], dtype=object) loc = [1, 2] for i in loc: l[i] = ['wgwg', 23, 'g'] </code></pre>
<pre><code>In [424]: l = np.array([[1, 3], 1, np.nan, [3, 53, 13], ['225gg2g']], dtype=object) In [425]: loc = [1,2] In [426]: l[loc] Out[426]: array([1, nan], dtype=object) In [427]: l[loc] = ['wgwg',23,'g'] --------------------------------------------------------------------------- ValueError ...
python|numpy
1
372,919
46,901,247
New Pandas DF with index from one DF and columns from another
<p>I have two dataframes. DF1 and DF2. I am comparing absolute distances between coordinate pairs from both. I want to populate a new dataframe that has rows for each df1 coordinate pair and a column for each df2 coordinate pair.</p> <p>This would result in the absolute distance between each df1 pair and each df2 pair...
<p>I had to break down df2 into smaller dfs to not throw a memory error. I changed the for loop to this and it works...just took a while to get there:</p> <pre><code>df_new = pd.DataFrame(index = df1.index.copy(),columns = df2.index.copy()) for idx_crime, x_crime in enumerate(df2['X_COORD']): y_crime = df2['Y_COO...
python|pandas
0
372,920
46,712,633
Seaborn heatmap showing incorrect x-axis values
<p>I have a Pandas dataframe ("<code>df</code>") that looks something like:</p> <pre><code> Variable1 Var2 Parameters Values 0 10.000 1.1 0.296342 0.170009 1 10.015 1.1 0.297013 0.168656 2 10.030 1.1 0.297659...
<p>Copying your sample data,</p> <pre><code>Variable1 Var2 Parameters Values 0 10.000 1.1 0.296342 0.170009 1 10.015 1.1 0.297013 0.168656 2 10.030 1.1 0.297659 0.167326 3 10.045 ...
python-2.7|pandas|dataframe|heatmap|seaborn
1
372,921
46,998,199
Remove elements from 2D numpy array based on specific value
<p>I've got a numpy array with machine learning data, with over 500000 rows. </p> <p>It looks like this: </p> <pre><code>[[1,2,3,4,1,0.3], [1,3,2,4,0,0.9], [3,2,5,4,0,0.8] ...] </code></pre> <p>The first 4 values are parameters, fifth is a class and sixth is probability for class 0.</p> <p>Problem is, that the dat...
<p>Assuming that <code>in[:, 4] = (in[:, 5] &lt; t).astype(int)</code> where <code>t</code> is some threshhold value (probably <code>0.5</code>):</p> <pre><code>n = np.sum(in[:, 4]) # number of ones i = np.argpartition(in[:, 5], 2 * n)[:2 * n] # index of bottom 2n p values out = in[i] ...
python|arrays|numpy|scipy
0
372,922
46,676,311
fromiter() gives "int() argument must be a string"
<p>I am having a trouble with running fromiter over the array:</p> <pre><code>&gt;&gt;&gt;import numpy as np &gt;&gt;&gt;arr = np.array([0,0,0,0,0,0,0,0,0,0]) &gt;&gt;&gt;brr = np.array([2, 4]) &gt;&gt;&gt;def fnc(arr, b): &gt;&gt;&gt; ar[br] += 2 &gt;&gt;&gt; ar[br-1] += 1 &gt;&gt;&gt; ar[br+1] += 1 &gt;&gt;...
<p>It was my mistake, there is no need in vectorizing it, Python can do it by itself:</p> <pre><code>&gt;&gt;&gt;import numpy as np; a = np.zeros(10); b = np.array([1,3,5]); a; b; array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) array([1, 3, 5]) &gt;&gt;&gt;def fnc(arr, b): &gt;&gt;&gt; ar[br] += 2 &gt;&gt...
python|numpy|vectorization
0
372,923
46,950,766
Python code not working as intended
<p>I started learning Python &lt; 2 weeks ago.</p> <p>I'm trying to make a function to compute a 7 day moving average for data. Something wasn't going right so I tried it without the function.</p> <pre><code>moving_average = np.array([]) i = 0 for i in range(len(temp)-6): sum_7 = np.array([]) avg_7 = 0 ...
<p>Hey you can using rolling() function and mean() function from pandas. Link to the documentation : <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.rolling.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.rolling.html</a></p> <pre><code...
python|pandas|numpy
2
372,924
46,639,551
'int' object has no attribute 'item' in numpy array
<p>Here's my code</p> <pre><code>import numpy as np x = np.array([2, 3, 1, 0]) </code></pre> <p>when I print x</p> <pre><code>array([2, 3, 1, 0]) </code></pre> <p>I'm using <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.item.html" rel="nofollow noreferrer">this tutorial</a> and d...
<p>Somewhere in your code, between </p> <pre><code>x = np.array([2, 3, 1, 0]) </code></pre> <p>and</p> <pre><code>x.item(1) </code></pre> <p>there is some code which changes the value of <code>x</code>. It's likely to be on a line that starts with <code>x =</code></p>
python|python-3.x|numpy
3
372,925
46,937,898
Delayed echo of sin - cannot reproduce Tensorflow result in Keras
<p>I am experimenting with LSTMs in Keras with little to no luck. At some moment I decided to scale back to the most basic problems in order finally achieve some positive result.<br> However, even with simplest problems I find that Keras is unable to converge while the implementation of the same problem in Tensorflow g...
<p>Ok, I have managed to solve this. Keras implementation now converges steadily to a sensible solution too:<br> <a href="https://i.stack.imgur.com/VwLTm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VwLTm.png" alt="keras_new_training_loss"></a> <a href="https://i.stack.imgur.com/FL78m.png" rel="no...
tensorflow|keras|lstm|rnn
0
372,926
46,919,873
Resource Exhausted OOM while loading VGG16
<p>I am apologizing in advance if this issue seems to basic, but I am new to Tensorflow and appreciate any help.</p> <p>I find that I have to frequently keep rebooting my computer to be able to load models such as VGG16 from keras.applications. I have a fairly high-end machine with 4 GeForce GTX 1080 Ti GPUs and Intel...
<p>If you have batch size > 1, try to use lower batch size, which could lower the memory requirements gor GPU.</p> <p>Also, if you end with working with the network, check the GPU memory by <code>nvidia-smi</code>, if it was released or not. If not, kill the process which loaded the network (usually some python interp...
tensorflow|keras|neural-network|gpu
1
372,927
32,740,592
Taking fourier transform after phase shift
<p>I am trying to change the phase of an image and taking the Fourier transform of it. But this change in phase causes a leakage of power along x an y axis.</p> <p>Suppose my image is a all ones matrix. If i take the Fourier transform i get <a href="https://i.stack.imgur.com/44VFA.png" rel="nofollow noreferrer"><img s...
<p>If you plot your <code>new_image</code>, you see that it is not a sinusoid:<a href="https://i.stack.imgur.com/F2mcJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F2mcJ.png" alt="enter image description here"></a></p> <p>Here's a brute-force approach to creating a sinusoid pattern without using ...
python|numpy|fft|scientific-computing
4
372,928
32,972,856
Comparing two dataframes of different length row by row and adding columns for each row with equal value
<p>I have two dataframes of different length in python pandas like this:</p> <pre><code>df1: df2: Column1 Column2 Column3 ColumnA ColumnB 0 1 a r 0 1 a 1 2 b u 1 1 d 2 3 c ...
<p>I recommend you to use DataFrame API which allows to operate with DF in terms of <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="noreferrer"><em>join</em>, <em>merge</em></a>, <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="noreferrer"><em>groupby</em></a>, etc. You ca...
python|pandas|compare|dataframe
5
372,929
33,020,656
From pandas to excel via xlwings - do not deposit index
<pre><code>Range("A1").value = p.df_sector[["A","B","C"]].sort(columns=["C"],ascending=False).head(4) </code></pre> <p>Works wonderfully! But - I do not want/need to see the <code>index</code> column</p> <pre><code>p.df_sector[["A","B","C"]].sort(columns=["C"],ascending=False).head(4).to_string(index=False) </code></...
<p>The documentation and syntax seems to have changed a bit, since 2015. </p> <p><a href="https://docs.xlwings.org/en/stable/converters.html#pandas-series-converter" rel="noreferrer">Here</a> is the documentation for dealing with Pandas via xlwings.</p> <p>Instead of a parameter in <code>Range</code>, <code>index=Fa...
python|pandas|xlwings
7
372,930
32,929,171
Match and count two files by time and column
<p>I am trying to work out these two csv files by using Pandas to look up in rows:</p> <p>File1:</p> <pre><code>--------------------------------------------------------------- Day Mth Yr Hr Min Loc_Nu Lat Long Rain --------------------------------------------------------------- 1 1 2005 9...
<p>You can try this solution, if you don't understand, you can ask in comments:</p> <pre><code>import pandas as pd import io, datetime df = pd.read_csv(r'E:\project\test\file1.csv') df1 = pd.read_csv(r'E:\project\test\file2.csv') #set column date to datetime df1["date"] = pd.to_datetime(df1["date"], format="%d/%m/%Y...
python|datetime|pandas|dataframe
0
372,931
32,873,739
How to compare dates from Excel sheets for value filling purposes on python
<p>I have an excel file with 2 sheets. </p> <p>one sheet containing the data:</p> <pre><code>DATE TMAX TMIN 20110706 317 211 20110707 322 211 20110708 317 211 20110709 322 211 20110710 328 222 20110711 333 244 20110712 356 250 20110713 356 222 </code></pre> <p>and the other sheet includ...
<p>It's critical to parse the date columns as pandas Timestamps/ numpy datetime64. The best way is to use to_datetime with a format.</p> <pre><code> In [11]: df Out[11]: DATE TMAX TMIN 0 20110706 317 211 1 20110707 322 211 2 20110708 317 211 3 20110709 322 211 4 20110710 32...
python|excel|pandas
2
372,932
33,046,623
pandas: MultiIndex Slicing - Mixing slices and lists
<p>I am attempting to use the (not really) new slicing operator in pandas, but there is something I am not quite getting. Suppose I generate the following hierarchical dataframe:</p> <pre><code>#Generate container to hold component DFs df_list=[] #Generate names for third dimension positions third_names=['front','mi...
<p><code>d3_long</code> is actually a <code>Series</code>, so you don't need the last <code>:</code> in your slicer. Note that your second level <code>slice('two','four')</code> doesn't select anything (it'd be equivalent to <code>[-1:1]</code>).</p> <p>But if you reverse the order, it should give what you expect.</p...
python|pandas|slice|multi-index
0
372,933
32,828,978
Equivalent of R rbind.fill in Python Pandas
<p>R's plyr function has: rbind.fill() which is a way to append data frames with unequal number of columns.</p> <p>Is there a similar function for python / pandas DataFrame?</p>
<p>You are looking for the function <code>concat</code>:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'col1':['a','b'],'col2':[33,44]}) df2 = pd.DataFrame({'col3':['dog'],'col2':[32], 'col4':[1]}) In [8]: pd.concat([df1, df2]) Out[8]: col1 col2 col3 col4 0 a 33 NaN NaN 1 b 44 NaN Na...
python|r|pandas
8
372,934
32,748,678
Apply same permutation for every row in a 2D numpy array
<p>To permute a 1D array <code>A</code> I know that you can run the following code:</p> <pre><code>import numpy as np A = np.random.permutation(A) </code></pre> <p>I have a 2D array and want to apply exactly the same permutation for every row of the array. Is there any way you can specify the numpy to do that for you...
<p>Generate random permutations for the number of columns in A and index into the columns of <code>A</code>, like so -</p> <pre><code>A[:,np.random.permutation(A.shape[1])] </code></pre> <p>Sample run -</p> <pre><code>In [100]: A Out[100]: array([[3, 5, 7, 4, 7], [2, 5, 2, 0, 3], [1, 4, 3, 8, 8]]) In...
python|arrays|algorithm|numpy
8
372,935
32,665,755
Rearrange order of for-loops with setting
<p>I'm working with arrays having the following kind of structure/entries (for a masters project in quantum info games); The 1st column entries <code>{0,1}</code>, 2nd col <code>{0,1}</code>, 3rd col <code>{0,2**(d-1)}</code> , last col <code>{0,d-1}</code>. As follows for <code>d=3</code>:</p> <pre><code>G = [[0 0 0...
<p>The thing you're calculating is called the "Cartesian product" and by <s>chance</s> popular demand the <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow">itertools module</a> from the standard library has a function to construct it without all the explicit loops. By permuting...
python|numpy|macros|bitstring
1
372,936
32,723,993
How to exclude few ranges from numpy array at once?
<p>Say, one have a following numpy array:</p> <pre><code>X = numpy.array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5]) </code></pre> <p>Now, how one can exclude from the array <code>X</code> ranges <code>X[0:2]</code>, <code>X[6:8]</code> and <code>X[12:14]</code> at once, so one will get in result <code>X= [2, 2, 2...
<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html" rel="nofollow"><code>np.r_</code></a> to combine the ranges into a 1D array:</p> <pre><code>In [18]: np.r_[0:2,6:8,12:14] Out[18]: array([ 0, 1, 6, 7, 12, 13]) </code></pre> <p>Then use <a href="http://docs.scipy.org/doc/n...
python|arrays|numpy
4
372,937
38,917,076
python pandas get index boundaries from a series of Booleans
<p>I am trying cut videos based on some caracteristics. My current strategy leads on a <code>pandas</code> series of booleans for each frame, indexed by timestamp. <code>True</code> to keep it, <code>False</code> to dump it.</p> <p>As I plan to cut videos, i need to extract boundaries from this list, so that i can tel...
<p>You could use <a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.ndimage.measurements.label.html" rel="nofollow"><code>scipy.ndimage.label</code></a> to identify the clusters of <code>True</code>s:</p> <pre><code>In [102]: ts Out[102]: 0.069347 False 0.131956 False 0.143948 False 0....
python|pandas
4
372,938
38,930,932
How do I make one data frame to keep the same rows as another one?
<p>I have one data frame (df) x,</p> <pre><code> A B O 2 3 1 4 4 3 2 1 </code></pre> <p>You may notice that the number 2 row is missing. That is because i have used x.dropna() and therefore the no.2 row is dropped as it is NAN.</p> <p>Now I have another df y:</p> <pre><code> C D O 1 2 1 4 3...
<p>You can also use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.isin.html" rel="nofollow"><code>index.isin</code></a> to check if each index value of <code>y</code> is found in index value of <code>x</code>.</p> <pre><code>In [3]: y = y[y.index.isin(x.index)] In [4]: y Out[4]: ...
python|pandas|dataframe
1
372,939
38,721,194
Does Spark Dataframe have an equivalent option of Panda's merge indicator?
<p>The python Pandas library contains the following function :</p> <pre><code>DataFrame.merge(right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), copy=True, indicator=False) </code></pre> <p>The indicator fie...
<p>Try this:</p> <pre><code>&gt;&gt;&gt; from pyspark.sql.functions import * &gt;&gt;&gt; sdf1 = sqlContext.createDataFrame(df1) &gt;&gt;&gt; sdf2 = sqlContext.createDataFrame(df2) &gt;&gt;&gt; sdf = sdf1.join(sdf2, sdf1["col1"] == sdf2["col1"], "outer") &gt;&gt;&gt; sdf.withColumn("_merge", when(sdf1["col1"].isNull()...
python|pandas|pyspark|spark-dataframe
8
372,940
38,655,042
Merge columns in Pandas based on date criteria
<p>I have a dataframe like this</p> <pre><code>In[337]: df Out[337]: 2013 2014 2015 2013-01-31 0.705935 0.983307 0.714397 2013-05-31 0.492020 0.532103 0.897666 2013-09-30 0.187822 0.779611 0.774774 2014-01-31 0.789511 0.383665 0.353669 2014-05-31 0.347580 0.540767 0.732863 201...
<p>Assuming the dates are parsed you can do this:</p> <pre><code>df.apply(lambda row: row[str(row.name.year)], axis=1) </code></pre> <p><strong>Edit:</strong></p> <p>This was what I was looking for:</p> <pre><code>pd.Series( df.lookup( row_labels=df.index, col_labels=df.index.year.astype(str) ...
python|pandas
3
372,941
38,578,505
Tensorflow: Convert Tensor to numpy array then pass into a feed_dict
<p>I'm trying to build a softmax regression model for CIFAR classification. At first when I tried to pass in my images and labels into the feed dictionary, I got an error that said that feed dictionaries do not accept Tensors. I then converted them into numpy arrays using .eval() but the program hangs at the .eval() li...
<p>Theres a couple of things that you not are understanding really well. Throughout your graph you will work with Tensors. You define Tensors by either using <code>tf.placeholder</code> and feeding them in the <code>session.run(feed_dict{})</code> or with <code>tf.Variable</code> and initializing it with <code>session....
python|neural-network|tensorflow|mnist|softmax
0
372,942
38,608,127
TensorFlow MNIST example feeding own images
<p>I am trying to learn TensorFlow, so I was trying to understand their example with smaller dimensions. Suppose I have image1, image2, image3 three 28x28 matrices which hold grayscale values (0..255). image1 is the training image, image2 is the validation image, and image3 is the test image. I was trying to understand...
<p>Suppose your image is a numpy array, of shape <code>[1, 28, 28, 1]</code>.</p> <p>You can just feed this numpy array to the node <code>X</code> or <code>textX</code>. Even though X is not a placeholder, you can provide its value to TensorFlow.</p> <pre class="lang-py prettyprint-override"><code>X_value = ... # nu...
tensorflow|mnist
1
372,943
38,955,736
TensorFlow GPU Epoch Optimization?
<p>So this code works, and it gives me a 2x boost over CPU only, but I think its possible to get it faster. I think the issue boils down to this area...</p> <pre><code>for i in tqdm(range(epochs), ascii=True): sess.run(train_step, feed_dict={x: train, y_:labels}) </code></pre> <p>I think what happens is that eve...
<p>The overhead of <code>session.run</code> is around 100 usec, so if you do 10k steps, this overhead adds around 1 second. If this is significant, then you are doing many small iterations, and are incurring extra overhead in other places. IE, GPU kernel launch overhead is 5x larger than CPU (5 usec vs 1 usec).</p> <...
python|tensorflow
3
372,944
38,925,082
how to compare two columns in pandas to make a third column ?
<p>i have two columns age and sex in a pandas dataframe </p> <pre><code>sex = ['m', 'f' , 'm', 'f', 'f', 'f', 'f'] age = [16 , 15 , 14 , 9 , 8 , 2 , 56 ] </code></pre> <p>now i want to extract a third column : like this if age &lt;=9 then output ' child' and if age >9 then output the respective gender </p> <p...
<p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="noreferrer"><code>numpy.where</code></a>:</p> <pre><code>df['col3'] = np.where(df['age'] &lt;= 9, 'child', df['sex']) </code></pre> <p>The resulting output:</p> <pre><code> age sex col3 0 16 m m 1 15 f f ...
python|pandas
18
372,945
38,858,582
Finding the maximum value between certain row and columns in pandas df
<p>Suppose, I have the dataframe below:</p> <pre><code>df = pd.DataFrame({'group1': ['x','xincr','xmin','xzero','yzero','ymin','s','0','1','2','3','4','5'], 'value1': [1.1,2,3,4,5,6,7,8,9,1,2,3,4]}) </code></pre> <p>I want to find the maximum value in column <code>'value1'</code> starting in row 7...
<p>This is an example of mixed indexing. Meaning you want to use labels for the columns and positions for the rows. There are a few ways to do this.</p> <p><strong><em>Option 1</em></strong></p> <p>Use <code>.value1</code> to specify the columns then <code>iloc</code> to specify the rows 7 through 12 using <code>6:...
csv|pandas|dataframe
1
372,946
38,608,159
Tensorflow entropy in NaN for large inputs when training CNN
<p>I've created a simple convolution neuron network with TensorFlow. When I use input images with edge = 32px the network works fine, but if I increase edge twice to 64px then entropy retutrs as NaN. The question is how to fix that?</p> <p>CNN structure is pretty simple and looks like: <strong>input->conv->pool2->conv...
<p>As far as I know, <strong>NAN</strong> happen when you calculate <strong>log(0)</strong>. I had the same problem.</p> <pre><code>tf.log(prediction) #This is a problem when the predicted value is 0. </code></pre> <p>You can avoid this by adding a little noise to the prediction (<a href="https://stackoverflow.com/qu...
tensorflow|deep-learning|convolution|entropy|cross-entropy
2
372,947
38,755,672
Python, Oracle DB, XML data in a column, fetching cx_Oracle.Object
<p>I am using python to fetch data from Oracle DB. All the rows have a column which has XML data. When I print the data fetched from Oracle DB using python, the column with XML data is printed as - cx_Oracle.OBJECT object at 0x7fffe373b960 etc. I even converted the data to pandas data frame and still the data for this ...
<p>Please read inline comments.</p> <pre><code>cursor = connection.cursor() # you know what it is for # here getClobVal() returns whole xml. It won't work without alias I don't know why. query = """select a.columnName.getClobVal() from tablename a""" cursor.execute(query) #you know what it is for result = cursor.f...
python|xml|oracle|pandas|clob
3
372,948
38,771,274
Failed to `pip install numpy` in pypy2 virtual environment on Ubuntu
<p>I build a virtual environment of <strong>PyPy 5.3.1 with GCC 4.6.3</strong> on <strong>Ubuntu Linux 16.04.1 LTS</strong>, and <strong>Python 2.7.10</strong> is the base interpreter. When I do <code>pip install numpy</code> in this virtual environment the following error occurrs: </p> <blockquote> <p>Running setu...
<p>PyPy has its own working version of <code>numpy</code>. Instructions for installation are documented on <a href="https://bitbucket.org/pypy/numpy" rel="nofollow">its repo</a>.</p>
ubuntu|numpy|pip|pypy
0
372,949
38,952,269
python2.7 - average of multiple opencv histograms
<p>I am using python2.7 opencv library to calculate histograms of some images, all of the exact same size (cv2.calchist)</p> <p>i have a need to do 2 things: 1. calculate the average of multiple images - multiple images who represent a similar object, and therefor i want to have a "representive" histogram of that obj...
<p>Since OpenCV (since 2.2) natively uses numpy arrays and since <code>len(images)</code> is constant, you can get avg between all your histograms and stores in mongo by simply:</p> <pre><code>h, b = np.histogram(images, bins=[0, 256]) db.histograms.insert({hist:(h/len(images)), bins:b }) </code></pre> <p>I do not kn...
python-2.7|opencv|numpy|image-processing|histogram
0
372,950
38,686,926
Write multiple Dataframes to same PDF file using matplotlib
<p>I'm stuck at a point where I have to write multiple pandas dataframe's to a PDF file.The function accepts dataframe as input.</p> <p>However, I'm able to write to PDF for the first time but all the subsequent calls are overriding the existing data, leaving with only one dataframe in the PDF by the end.</p> <p>Plea...
<p>Your PDF's are being overwritten, because you're creating a new PDF document every time you call <code>fn_print_pdf()</code>. You can try keep your <code>PdfPages</code> instance open between function calls, and make a call to <code>pp.close()</code> only after all your plots are written. For reference see <a href="...
python|pdf|pandas|matplotlib
1
372,951
38,588,675
python program debugging product of adjacent numbers
<p>I am currently working on project Euler question 8, which asks to find the largest product of 13 adjacent numbers in a 1000 digit long number. I imported the numpy prod function to compute products. It seems to work without the while loop but with the while loop it gives out a weird error message. can someone please...
<p>You could start by converting the multiline string <code>z</code> into a list of digits through a list comprehension and the built-in function <code>int()</code>:</p> <pre><code>z = """73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737...
python|debugging|numpy
1
372,952
38,679,614
Finding values based on specific categories
<p>I was wondering how would find estimated values based on several different categories. Two of the columns are categorical, one of the other columns contains two strings of interest and the last contain numeric values I have a csv file called sports.csv</p> <pre><code>import pandas as pd import numpy as np #loading...
<p>I had to add an instance that would actually meet your criteria, or else you will get an empty result. You want to use <code>df.loc</code> with conditions as follows:</p> <pre><code>In [1]: import pandas as pd, numpy as np, io In [2]: in_string = io.StringIO("""Region Type enroll estimates price Gym .....
python|csv|pandas
0
372,953
38,708,621
How to calculate percentage of sparsity for a numpy array/matrix?
<p>I have the following 10 by 5 numpy array/matrix, which has a number of <code>NaN</code> values:</p> <pre><code>array([[ 0., 0., 0., 0., 1.], [ 1., 1., 0., nan, nan], [ 0., nan, 1., nan, nan], [ 1., 1., 1., 1., 0.], [ 0., 0., 0., 1., 0.], [ ...
<p><strong>Definition:</strong></p> <p><a href="https://i.stack.imgur.com/RAlAt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RAlAt.png" alt="enter image description here"></a></p> <h2>Code for a general case:</h2> <pre><code>from numpy import array from numpy import count_nonzero import numpy as np # c...
python|arrays|numpy|matrix|sparse-matrix
16
372,954
38,942,790
Python Pandas Dataframe Append Rows
<p>I'm trying to append the data frame values as rows but its appending them as columns. I have 32 files that i would like to take the second column from (called dataset_code) and append it. But its creating 32 rows and 101 columns. I would like 1 column and 3232 rows.</p> <pre><code>import pandas as pd import os ...
<p>You already have two perfectly good answers, but let me make a couple of recommendations.</p> <ol> <li>If you only want the <code>dataset_code</code> column, tell <code>pd.read_csv</code> directly (<code>usecols=['dataset_code']</code>) instead of loading the whole file into memory only to subset the dataframe imme...
python|python-2.7|pandas|dataframe
8
372,955
38,724,777
Pandas - ValueError on datetime format mismatch
<p>This is my data:</p> <pre><code>date = df['Date'] print (date.head()) 0 2015-01-02 1 2015-01-02 2 2015-01-02 3 2015-01-02 4 2015-01-02 Name: Date, dtype: datetime64[ns] </code></pre> <p>my code:</p> <pre><code>def date_to_days(date): return date2num(datetime.datetime.strptime(date, '%Y-%m-%d')) </c...
<p>It works fine for me without any errors. </p> <pre><code>In [74]: from matplotlib.dates import date2num In [75]: df['Number of days'] = df['Date'].apply(lambda x: date2num(datetime.datetime.strptime(x, '%Y-%m-%d'))) In [76]: df Out[76]: Date Number of days 0 2015-01-02 735600.0 1 2015-01-02 ...
python|datetime|pandas
0
372,956
38,556,574
Matrix using only one column for header and row
<p>Let's say I have a list of names like this one in a csv:</p> <pre><code>Nom;Link;NonLink Deb;John; John;Deb; Martha;Travis; Travis;Martha; Allan;; Lois;; Jayne;; Brad;;Abby Abby;;Brad </code></pre> <p>I imported it using numpy:</p> <pre><code>import numpy as np file = np.genfromtxt('liste.csv', dtype=None, delimi...
<p>You can use pandas and create a dataframe using <code>Nom</code> variable. Something like this:</p> <pre><code>import pandas as pd df = pd.DataFrame([[0] * len(Nom)] * len(Nom), Nom, Nom) print(df) </code></pre>
python|numpy|pandas
1
372,957
38,529,632
Trouble writing pivot table to excel file
<p>I am using pandas/openpyxl to process an excel file and then create a pivot table to add to a new worksheet in the current workbook. When I execute my code, the new sheet gets created but the pivot table does not get added to the sheet.</p> <p>Here is my code:</p> <pre><code>worksheet2 = workbook.create_sheet() wo...
<p>You can't do this because openpyxl does not currently support pivot tables. See <a href="https://bitbucket.org/openpyxl/openpyxl/issues/295" rel="nofollow">https://bitbucket.org/openpyxl/openpyxl/issues/295</a> for further information.</p>
python|pandas|openpyxl
2
372,958
38,961,054
How can we reshape Python Pandas DataFrame to C-Contiguous memory?
<p>I am loading a two dimensional dataset in memory with Pandas, and doing 4 simple Machine Learning pre-processing task like adding/removing columns, reindexing, train/test split.</p> <pre><code>#Read file MLMe = pd.read_table("data/dtCTG.txt", ",") #Label target column to "class" MLMe.rename(columns={'NSP' : 'class'...
<p>We have no direct control about how the DataFrame stores its values, which can be c-contiguous or not. However, it's easy to get C-contiguous data by using the numpy function <code>ascontiguousarray</code> on the underlying numpy array, which is returned by the <code>value</code> property of the array. You can test ...
python|python-3.x|pandas|numpy|scikit-learn
0
372,959
63,075,984
Numpy unpack uint16 to 1-5-5-5 bit chunks
<p>I am trying to convert a binary string to an image in Python using numpy but i am having a hard time finding a good way of approaching it with a an unconventional bit distribution (as far as my knowledge goes).</p> <p>these are the specifics of how and what to convert. 16-bit texture tile (256*256). Each bitu16 repr...
<p>You are right regarding the lack of bit numpy bit level support in this case. A high-level (yet functional) approach for handling the bits can be done as follows:</p> <pre class="lang-py prettyprint-override"><code>image_16_bit = 123 # A 16bit integer. bits = '{:016b}'.format(image_16_bit) transparency = int(bits...
python|numpy|python-imaging-library|bin
2
372,960
63,016,766
Pandas: Getting new dataframe from existing dataframe from list of substring present in column name
<p>Hello I have dataframe called df and list of substring present in dataframe main problem i am facing is some of the substrings are not present in dataframe.</p> <pre><code> ls = [&quot;SRR123&quot;, &quot;SRR154&quot;, &quot;SRR655&quot;, &quot;SRR224&quot;,&quot;SRR661&quot;] data = {'SRR123_em1': [1,2,...
<p>Do filter with <code>str.contains</code></p> <pre><code>sub_df=df.loc[:,df.columns.str.contains('|'.join(ls))].copy() Out[295]: SRR123_em1 SRR123_em2 SRR661_em1 SRR661_em2 0 1 4 7 6 1 2 5 8 7 2 3 6 9 ...
python-3.x|pandas
2
372,961
63,236,768
How to delete row in Pandas Dataframe using 2 colums as condition?
<p>Basically, I got a table like the following:</p> <pre><code>Name Sport Frequency Jonas Soccer 3 Jonas Tennis 5 Jonas Boxing 4 Mathew Soccer 2 Mathew Tennis 1 John Boxing 2 John Boxing 3 John ...
<p>This is one way about it, by iterating through the groups :</p> <pre><code>pd.concat( [ value.assign(temp=lambda x: x.loc[x.Sport == &quot;Soccer&quot;, &quot;Frequency&quot;]) .bfill() .ffill() .query(&quot;Frequency &lt;= temp&quot;) .drop('temp', axis = 1) for k...
python|pandas|dataframe
1
372,962
62,910,622
Transforming pandas data frame into excel with below format
<p>I have my pandas data frame as line below.</p> <p><a href="https://i.stack.imgur.com/VWYne.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VWYne.jpg" alt="enter image description here" /></a></p> <p>I need to convert the above dataframe as below in python and save result in Excel sheet with proper...
<pre><code>df = pd.DataFrame({&quot;CLIENTID&quot;:[&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;I&quot;,&quot;I&quot;], &quot;Key1&quot;:[&quot;VI&quot;,&quot;SA&quot;,&quot;SU&quot;,&quot;RA&quot;,&quot;RA&quot;], &quot;Key2&quot;:[&quot;NA&quot;,&quot;RA&quot;,&quot;VI&quot;,&quot;VI&quot;,&quot;VI...
python-3.x|excel|pandas|excel-formula
0
372,963
63,104,255
from keras.backend.tensorflow_backend import set_session
<p>I am trying to run a code using keras. The program uses <code>from keras.backend.tensorflow_backend import set_session</code> and i am getting an underhanded Exception thats says No module named 'keras.backend.tensorflow_backend'; 'keras.backend' is not a package with the following error code<code> File &quot;c:/Use...
<p>I guess you are <code>importing</code> it incorrectly.</p> <p>The command to <code>import set_session</code>, for <code>Tensorflow 2.3</code> (latest version) is shown below.</p> <p><strong><code>from tensorflow.compat.v1.keras.backend import set_session</code></strong></p> <p>Please find <a href="https://colab.rese...
python|tensorflow|keras
5
372,964
63,234,189
Reformatting and Reordering Dates in a Python Pandas Series
<p>I have a pandas DataFrame and I want to reformat AND order the Date Range column. This is the <code>df.head()</code>:</p> <pre><code>Numeric Index Origin Movement ID Origin Display Name Destination Movement ID Destination Display Name Date Range Mean Travel Time (Seconds) Range - Lower Bound Travel Time (Sec...
<p>You can split by first space, select first value and convert to datetime with <code>format</code> parameter by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a>, last if necessary use <a href="http://pandas.pydata.org/pa...
python|pandas|dataframe|datetime|format
1
372,965
63,303,822
How to represent those types of values in a tensor?
<p>I have a dataset like this:</p> <pre><code>(0, 1), UpDownUpUp (2, 3), UpUpUpDownDownDown (0, 2), DownUp (0, Undefined), DownUp </code></pre> <p>How to represent this type of data in a PyTorch tensor? So I can then train a neural network with it?</p>
<p>Here is one way to do it:</p> <ul> <li>You keep the values as they are, replacing the undefined with 9 (we will use 9 to represent [do nothing])</li> <li>You encode the labels into integers 5, 6</li> <li>Convert your variables into lists</li> <li>For every batch, take the length of the longest sequence</li> <li>Pad ...
pytorch|tensor
1
372,966
63,041,555
Timeseries generator with LSTM
<p>Trying to create a generator for a LSTM and am running into an error during the .fit_generator(), after I run it the error is</p> <p><code>ValueError: Error when checking input: expected lstm_3_input to have 3 dimensions, but got array with shape (1, 5)</code></p> <p>and I'm not really sure how to reshape the data w...
<p>Try printing the shape of input vectors being generated by <code>TimeseriesGenerator</code> and compare it with input shape of your <code>LSTM layer</code>. Looking at the exception i guess your input shape should be <strong>(5, )</strong> and not <strong>(5, 1)</strong></p>
python|tensorflow|keras|deep-learning|lstm
0
372,967
62,956,916
Loop through list of lists and divide list values
<p>I would like to iterate through two lists of lists and divide them by eachother.</p> <p>Starting with:</p> <pre><code>patient1_list_A = [1,2,3] patient2_list_A = [4,5,6] patient3_list_A = [7,8,9] patient1_list_B = [10,11,12] patient2_list_B = [13,14,15] patient3_list_B = [16,17,18] list_A=[patient1_list_A, patient2...
<p>you can use <code>zip</code> to concatenate the sublist and there element and use metric operations</p> <pre><code>patient1_list_A = [1,2,3] patient2_list_A = [4,5,6] patient3_list_A = [7,8,9] patient1_list_B = [10,11,12] patient2_list_B = [13,14,15] patient3_list_B = [16,17,18] list_A=[patient1_list_A, patient2_li...
python|pandas|list
1
372,968
63,042,780
All training samples are not loading during training
<p>I'm just starting with NLP. I loaded the 'imdb_reviews' dataset from tensorflow_datasets.</p> <p>There were 25000 testing samples, but when I run I only train for 782 samples. I didn't use batch_size, just loaded entire dataset at once as you can see</p> <p><a href="https://i.stack.imgur.com/2ddV4.jpg" rel="nofollow...
<p>By default the fit method of tf.keras.model will set the batch size to be 32. <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/Model</a></p> <p>As 32*782 = 25,024 it probably just drops the last batch.</p>
python|tensorflow|nlp|tensorflow2.0|tensorflow-datasets
1
372,969
62,975,553
Pandas DataFrame: Add Column with Sum of Row Values using Column Axis indices?
<p>Looking through previously asked questions, I couldn't find the answer that helped, since my columns are generated by using a mix of both pytrends and yfinance values.</p> <p>Here is the code to get the dataframe in question:</p> <pre><code>import yfinance as yf from pytrends.request import TrendReq as tr ticker = ...
<p>Drop a column</p> <pre><code>del search_rank['isPartial'] </code></pre> <p>Add a calculated column</p> <pre><code>search_rank['Rank'] = df.apply(lambda row: row[0]+row[1] + row[2], axis=1) </code></pre> <p>I tested your code with above modification here is the full code</p> <pre><code>import yfinance as yf from pytr...
python|pandas|dataframe|yfinance
0
372,970
63,138,442
sqlalchemy dynamic use of and_ in where clause
<p>I am attempting to use sqlalchemy to build a delete query. The where portion of the delete clause should be constructed dynamically to satisfy multiple conditions. For example:</p> <pre><code>DELETE FROM table WHERE table.col1 = x1 AND table.col2 = x2 AND ... </code></pre> <p>The following is a simplified portio...
<p>SQLAlchemy will accept multiple <code>.where</code> constructs and AND them together, e.g.,</p> <pre class="lang-py prettyprint-override"><code>import sqlalchemy as sa engine = sa.create_engine(&quot;mssql+pyodbc://@mssqlLocal64&quot;, echo=True) detail_table = sa.Table( &quot;#detail_table&quot;, sa.MetaD...
python|sql|pandas|sqlalchemy
1
372,971
62,984,496
Fetching an op from a SavedModel in TF2
<p>Is it possible to get a reference to an internal op in a saved model?</p> <p>I have downloaded a saved model from tfhub and know which op I need after inspecting the <code>saved_model.pb</code> file. I'd like to get a reference to the op so I can record values during inference.</p> <p>More concretely, I want to extr...
<ul> <li><p>exhaustive and useful tutorial -&gt; <a href="https://www.tensorflow.org/guide/saved_model" rel="nofollow noreferrer">https://www.tensorflow.org/guide/saved_model</a></p> </li> <li><p>Keras detailed guide to save models -&gt;<br /> <a href="https://www.tensorflow.org/guide/keras/save_and_serialize" rel="nof...
python|tensorflow|keras|tensorflow2.0
0
372,972
62,957,110
Pandas: Selecting multiple rows based on column pair
<p>I am adapting my data analysis pipeline from a wide to the tidy/long format right now and have a problem with filtering it and I just cannot wrap my head around it.</p> <p>My data (simplified) looks like this (microscopy intensity data): in each <em>measurement</em> of a <em>group</em> I have several <em>regions of ...
<p>A solution would be the following:</p> <p>First, we calculate <code>df_pre_activated_t0</code> by filtering <code>df</code> with the condition:</p> <pre class="lang-py prettyprint-override"><code>threshold = 0.4 df_pre_activated_t0 = df[(df['timepoint'] == 0) &amp; (df['value'] &gt; threshold)] </code></pre> <p><cod...
python|pandas
2
372,973
62,927,308
How can i speed up my model training process using tensorflow and keras
<p>My batch size = 128 number of epochs = 15</p> <p>Single epoch takes 4 hours to complete the task, so the full training process takes a huge time. In my case, I need to increase the speed of my model training process to save my weight values how can I do this</p> <pre><code># Training Process results = model.fit_gene...
<p>There are two things you can do:</p> <ol> <li>Switch on XLA.</li> </ol> <pre><code>import tensorflow as tf tf.config.optimizer.set_jit(True) </code></pre> <ol start="2"> <li>Switch on mixed precision.</li> </ol> <pre><code>from tensorflow.keras.mixed_precision import experimental as mixed_precision policy = mixed_p...
python|tensorflow|keras|model
1
372,974
63,214,965
Why are my data not displayed in this Pandas graph?
<p>I have a <code>pandas.DataFrame</code> <code>daily_data_f_no_nr</code> with following content (result of <code>print(daily_data_f_no_nr)</code>):</p> <pre><code> Day Total TODO/TODOE count First Derivative 0 2020-05-16 35 0.0 1 2020-05-17 35 ...
<h1>Option 1: use <code>Day</code> column as <code>x</code> parameter</h1> <p>You should add the <code>x = 'Day'</code> parameter:</p> <pre><code>fig = daily_data_f_no_nr.plot(kind='line', figsize=(20, 16), fontsize=26, xticks=daily_data_f_no_nr['Day'], yticks=daily_data_f_no_nr['Total TODO/TODOE count'], x = 'Day', y=...
python|pandas|datetime|matplotlib|data-visualization
1
372,975
63,297,481
Getting error in creating pex from TF-YARN library for distributed training
<p>We are trying out TF-YARN library for training DL on tendorflow since our data is in Hadoop. But we are getting error in cluster_pack.upload_env()</p> <p>Following is the complete error:</p> <p>ERROR:cluster_pack.packaging:Cannot create pex Traceback (most recent call last): File &quot;/data1/python3.6.10/lib/python...
<p>What is failing a the pex creation with one of your dependencies. You really have a lot of dependencies. The best would be to isolate your dependencies for each use case you have and create a smaller virtual environment or just try it out with tensorflow only.</p> <p>What you can try is to execute pex cli command wi...
apache-spark|tensorflow|hadoop|pex|distributed-tensorflow
0
372,976
62,961,637
Fitting a 1d vector to SVC linear kernel
<p>I am trying to use SVC with the linear kernel for image recognition task. My current data is a 2x5 matrix</p> <pre><code>[['Face 1' 'Face2' 'Face 3' 'Face 4' 'Face 5'] ['229.0' '230.0' '231.0' '230.0' '230.0']] </code></pre> <p>My second row is my X features, which are pixel intensity value from different images.</...
<p>sklearn is expecting your X_train array to be a two dimensional array like (n_examples, 1) for example and the Y_train to be a 1d array of labels like (n_examples, ).</p> <p>I reformatted your code to remove some unnecessary steps and fix the problem:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt...
python|python-3.x|numpy|machine-learning|scikit-learn
1
372,977
63,220,461
Set every second row's index to one new value
<p>What is a simple and direct way to set the index of every second row of my dataframe to, say, ''? The method I used to use, <code>df.loc[1::2, 'index'] = ''</code> used to work but no longer does. I'm using Pandas version 1.1.0.</p> <p>It now gives the following error:</p> <pre><code>ValueError: The truth value of a...
<p>One way,</p> <pre><code>df = df.set_axis(pd.Index([index if i not in range(1, df.shape[0], 2) else '' for i, index in enumerate(df.index)], name=df.index.name)) print(df) </code></pre> <p><strong>Output</strong></p> <pre><code> foo bar 0 0....
python|pandas
2
372,978
62,983,674
The Absolute Value of a Complex Number with Numpy
<p>I have the following script in Python. I am calculating the Fourier Transform of an array. When I want to plot the results (Fourier transform) I am using the absolute value of that calculation. However, I do not know how the absolute value of complex numbers is being produced. Does anyone know how it calculates? I n...
<pre><code>sqrt(Re(z)**2 + Im(z)**2) </code></pre> <p>for <code>z = a + ib</code> this becomes:</p> <pre><code>sqrt(a*a + b*b) </code></pre> <p>It's just the euclidean norm. You have to sum the square of real part and imaginary part (without the i) and do the sqrt of it.</p> <p><a href="https://i.stack.imgur.com/ertoI....
python|numpy|absolute-value
8
372,979
62,996,413
How to convert a tflite model into a frozen graph (.pb) in Tensorflow?
<p>I would like to convert an integer quantized <strong>tflite</strong> model into a <strong>frozen graph</strong> (.pb) in Tensorflow. I read through and tried many solutions on StackOverflow and none of them worked. Specifically, toco didn't work (output_format cannot be TENSORFLOW_GRAPHDEF).</p> <p>My ultimate goal ...
<p>The ability to convert tflite models to .pb was removed after Tensorflow version r1.9. Try downgrading your TF version to 1.9 and then something like this</p> <pre><code>bazel run --config=opt \ //tensorflow/contrib/lite/toco:toco -- \ --input_file=/tmp/foo.tflite \ --output_file=/tmp/foo.pb \ --input_format...
tensorflow|quantization|onnx|tensorflow-lite
2
372,980
62,931,961
Python - Pandas Series - Intraday Data - Daily Average
<p>I have a dataset (Pandas dataframe called df) that looks like:</p> <pre><code> var1 var2 var3 0 2018-05-02 04:53:46 150785 2018-05-02 04:53:46 1 2018-05-02 06:38:58 150785 2018-05-02 06:38:58 2 2018-05-03 00:35:25 145510 2018-05-03 00:35:25 3 2018-05-03 06:33:53...
<p>use <code>pd.Grouper</code>:</p> <pre><code># df['var1'] = pd.to_datetime(df['var1']) df = df.groupby(pd.Grouper(key='var1', freq='1d'))['var2'].mean().reset_index() df </code></pre> <p>output:</p> <pre><code> var1 var2 0 2018-05-02 150785 1 2018-05-03 145510 </code></pre>
python|pandas
2
372,981
62,946,271
How is batching normally performed for sequence data for an RNN/LSTM
<p>This <a href="https://github.com/udacity/deep-learning-v2-pytorch/blob/master/recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb" rel="nofollow noreferrer">Udacity course notebook</a> batches data in a way that is not intuitive to me.</p> <p>For a long sequence of data, they first truncates the da...
<p>You should check the documentation on padded sequences from pytorch. (If I had more experience with it I would give you a more detailed explanation, but truth if that I never really understood them!)</p> <p>Packed Sequence: <a href="https://pytorch.org/docs/master/generated/torch.nn.utils.rnn.PackedSequence.html#tor...
machine-learning|neural-network|pytorch|lstm
1
372,982
62,941,861
python - pandas ffill with groupby
<p>I am trying to forward fill the missing rows to complete the missing time-series rows in the dataset.</p> <p>The size of the dataset is huge. More than 100 million rows.</p> <p>The original source dataset is as shown below.</p> <pre><code> col1 col2 col3 col4 col5 col6 0 2020-01-01 b1 c1 1 9 ...
<p>Looks like a <code>resample</code> on <code>groupby</code> would work:</p> <pre><code>(df.set_index('col1').groupby(['col2', 'col3']) .resample('D').ffill() .reset_index(['col2','col3'], drop=True) .reset_index() ) </code></pre> <p>Output:</p> <pre><code> col1 col2 col3 col4 col5 col6 0 2020-01-...
python|pandas|numpy|dataframe|pandas-groupby
3
372,983
62,921,495
Grouping Pandas Dataframe by Elements in Column of Lists
<p>I am attempting to get the aggregate sum of columns within a pandas dataframe by grouping by elements in a column of lists. I will create a dummy dataset to represent the data I am working with:</p> <pre class="lang-py prettyprint-override"><code>preg_df = pd.DataFrame({'Diag_Codes': [['O1414', 'O4103X0', 'O365930'...
<p>Let's try:</p> <pre><code>preg_df.explode('Diag_Codes').groupby('Diag_Codes').sum() </code></pre> <p>Output:</p> <pre><code> First_Trimester Second_Trimester Third_Trimester Diag_Codes M545 1 0 0 N300...
pandas|list|dataframe|group-by|aggregate
3
372,984
63,269,201
How to convert pandas dataframe to a sparse matrix using scipy's csr_matrix?
<p>I want to cast a DataFrame to sparse matrix using <code>csr_matrix</code> from scipy library, but first I have to convert it to a SparseDataFrame. In previous versions of pandas I used <code>pd.SparseDataFrame(df).to_coo()</code> for such purposes, but since <code>pandas 1.0.0</code> this method is deprecated. Does...
<p>IIUC and using the third link you shared, you can convert your <code>df</code> data to sparse data using <code>pd.SparseDtype</code>, like this</p> <pre><code>df_sparsed = df.astype(pd.SparseDtype(&quot;float&quot;, np.nan) </code></pre> <p>You can read more about <code>pd.SparseDtype</code> <a href="https://pandas....
python|pandas|scipy|sparse-matrix
2
372,985
63,230,198
Pandas .plot() method won't take the specified colors in a bar diagram
<p>I'm trying to graph how much each key in the keyboard is used, classifying by side of the keyboard.</p> <p>For that I get a long string of text, I count the values for each letter and then make it into a pandas.DataFrame().</p> <p>The DataFrame has this structure</p> <pre><code> kp e 12.534045 a 12.167107 o ...
<p>I didn't find out where is wrong with color defined in <code>df.plot()</code>. But I find out a working one with <code>plt.bar()</code>.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import matplotlib.pyplot as plt data = {'kp': [12.534045, 12.167107, 9.238939, 7.103866, 6.470274]} df = p...
python|pandas|matplotlib
3
372,986
62,984,882
Problem with building an ANN for Iris Dataset
<p>I am new to machine learning. I have been trying to get this code working but the loss is stuck as 1.12 and is neither increasing or decreasing. Any help would be appreciated.</p> <pre><code>import pandas as pd import numpy as np import tensorflow as tf import matplotlib.pyplot as plt dataset = pd.read_csv('Iris.cs...
<p>This is a classification problem where you have to predict the class of Iris plant (<a href="https://archive.ics.uci.edu/ml/datasets/iris" rel="nofollow noreferrer">source</a>). You have specified <a href="https://keras.io/api/losses/regression_losses/#meansquarederror-class" rel="nofollow noreferrer">mse</a> loss w...
python|tensorflow|machine-learning
0
372,987
63,288,355
How do I invert my DataFrame (the first value --> last value, the last value --> first value)
<p>I am trying to flip (the first value becomes the last value, the last value becomes the first value) the dates column in my DataFrame with <code>.iloc[:,::-1]</code> and it does not appear to be working. Here is the sample code:</p> <pre><code># Clients's Data file_name = '/Users/x/Desktop/CharlesSchwab.Client.PV.cs...
<p>Would maybe <code>PV.sort_values(&quot;Dates&quot;, ascending=False)</code> give you what you need? :)</p>
python|pandas|finance
0
372,988
62,993,214
Pandas resample using a text column
<p>thanks for taking the time to read this! I have a question regarding pandas. I have a dataset that looks like this:</p> <pre><code> close high low open volume symbol date 2020-07-20 11:40:00 ...
<p>For me your solution working, maybe is necessary upgrade pandas:</p> <pre><code>df1=(df.groupby('symbol').resample('1D').agg({ 'high' : 'max', 'low': 'min', 'open' : 'first', 'close': 'last', 'volume' : 'sum' })) print (df1) h...
python|pandas
0
372,989
62,995,530
Exe file failed to execute
<p>I'm building a simple Prediction GUI using Python and tkinter. It works fine in the Jupyter notebook and when I converted the file to .py using <code>nbconvert</code>. As I want to pass around the tool to people who don't have python, I have converted it to exe using <code>pyinstaller --onefile Prediction.py</code>....
<p>you should put your file 'SRV_Platforms_Yield.csv' and .exe file in the same folder</p>
python|python-3.x|pandas|tkinter|pyinstaller
1
372,990
63,244,304
Merge lines that share the same key into one line
<p>I have a Dataframe and would like to make another column that combines the columns whose name begins with the same <code>value</code> in <code>Answer</code> and <code>QID</code>.</p> <p>That is to say, having the following Dataframe</p> <pre><code> QID Category Text QType Question: Answer0 Answe...
<p>This is logically grouping by <em>QID</em> getting a list of <em>Answers</em> then splitting list back into columns</p> <pre class="lang-py prettyprint-override"><code>import re data = &quot;&quot;&quot; QID Category Text QType Question: Answer0 Answer1 Country 0 16 Automotive Access to ...
python|python-3.x|pandas|dataframe
1
372,991
62,934,932
concatenate two numpy arrays row-wise
<p>I would like to concatenate these two arrays row-wise. thanks in advance</p> <p><img src="https://i.stack.imgur.com/MXsZb.png" alt="See intended output here" />.</p>
<p>You can concatenate 2 NumPy Arrays Row-wise doing this:</p> <pre><code># concatenate 2 numpy arrays: row-wise &gt;np.concatenate((array2D_1, array2D_2)) array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [10, 11, 12], [13, 14, 15], [16, 17, 18]]) </code></pre> <p>More info in <a hr...
python|arrays|numpy
0
372,992
63,273,951
Using pd.DataFrame.sample on dask dataframe with groupby
<p>I have a very large dataframe that I am resampling a large number of times, so I'd like to use dask to speed up the process. However, I'm running into challenges with the groupby apply. An example data frame would be</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd import ra...
<p>It's not quite clear to me what you are trying to achieve and why you need to add <code>replace=False</code> (which is default) but the following code work for me. I just need to add <code>meta</code>.</p> <pre class="lang-py prettyprint-override"><code>import dask.dataframe as dd df1 = dd.from_pandas(test_df.reset...
python|dataframe|pandas-groupby|dask
3
372,993
62,925,440
how to write a for loop with if elif and delete statement in python?
<p>I have a dataframe with 5000 records.</p> <pre><code>Data: Month Heat Number wts gcs 1 HA 8.2 98 1 HB 7.6 86 2 HB 4.2 76 3 HC 6.9 46 4 HD 7.4 36 5 HD ...
<p>We need create the condition dataframe first then <code>merge</code></p> <pre><code>df=df.merge(pd.DataFrame({'Month': [1,2,3,4,5,6],'Heat Number':['HA','HB','HC','HD','HE','HF']}),how='inner') Month Heat Number wts gcs 0 1 HA 8.2 98 1 2 HB 4.2 76 2 3 HC 6.9 4...
python|pandas|python-2.7|dataframe
1
372,994
63,158,314
Tensorflow 2.3.0 - Warning: get_next_as_optional (from tensorflow.python.data.ops.iterator_ops) is deprecated and will be removed in a future version
<p>I've just updated to TF-2.3. In a model using <code>tf.data.Dataset.from_tensor_slices</code> as data source, I get the folowing warning:</p> <pre><code>WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/data/ops/multi_device_iterator_ops.py:601: get_next_as_optional (from tensorflow.py...
<p>You can ignore this warning in 2.3. This is here to let you know that one of the libraries you're using is calling a method that TensorFlow plans on removing in a future release. For your current usage it'll work fine.</p>
python|tensorflow|keras|tensorflow2.0
3
372,995
63,203,500
Tensorflow & Keras: LSTM performs bad on seq2seq problem with clear solution
<p>I am learning about tensorflow, and seq2seq problems for machine translation. For this I gave me the following task:</p> <p>I created an Excel, containing random dates in different types, for example:</p> <ol> <li>05.09.2192</li> <li>martes, 07 de mayo de 2329</li> <li>Friday, 30 December, 2129</li> </ol> <p>In my d...
<p>So, in case this helps anyone in the future: The model did exactly what I asked it to do.</p> <p>BUT</p> <p>You need to be careful, that your data preprocession does not lead to ambiguity. So you have to prevent something like:</p> <pre><code>a -&gt; b and also a -&gt; c </code></pre> <p>While improving one equatati...
tensorflow|keras|deep-learning|lstm|seq2seq
1
372,996
63,177,098
Python - How to make a matrix using sub-matrix?
<p>Imagine we have an array with 100 elements. we want to turn it into a 2x2 matrix which every sub-matrix is a 5x5 matrix itself. I've write it to this level:</p> <pre><code>import numpy as np M = np.linspace(1,100,100) MUL = M[0:25].reshape([5,5]) MUR = M[25:50].reshape([5,5]) MLL = M[50:75].reshape([5,5]) MLR = M[...
<p>This works for this specific case.</p> <pre><code>M.reshape(2,2,5,5) </code></pre> <p>If you want more control over the order of the data you could build a new array manually.</p> <pre><code>A = np.zeros((2,2,5,5)) A[0,0,:,:] = MUL A[0,1,:,:] = MUR A[1,0,:,:] = MLL A[1,1,:,:] = MLR </code></pre>
python|arrays|numpy|matrix|submatrix
0
372,997
63,069,464
Correlation between the the columns of the matrix when there are columns with constant value ( Very Slow!)
<p>I am writing a customized correlation code in python that does not return &quot;nan&quot;, infact it returns 0 whenever it tries to calculate the correlation between any two columns where either or both of them are constant</p> <pre><code>def getCorreCustom(matrix,columns=30): A=np.zeros((columns,columns)) for i...
<p>You can just use pandas like this</p> <pre><code>from datetime import datetime import pandas as pd Test = np.random.random((50, 30)) Test[:, 0] = 1 Test[:, 10] = 1 start_time = datetime.now() R = getCorreCustom(Test) print(&quot;Custom Method&quot;) print(datetime.now() - start_time) print(R.shape) start_time = date...
python|numpy
1
372,998
63,099,808
pandas convert NA values to the value before it
<p>I want to convert a pandas series of <code>1, NA, NA, 1, NA, NA, NA, 2, NA, NA, NA, 2, NA, NA, 3, etc</code> to <code>1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, etc</code>.</p> <p>What should do in order to replace the NA values with the integer before it.</p>
<p>Try <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.fillna.html" rel="nofollow noreferrer">series.fillna(method='ffill')</a></p>
pandas|pandas-groupby
0
372,999
63,005,093
How to add certain rows of a pandas dataframe to a list based on value of another column
<p>I have a csv file, with one column labeled 'count', and then 10 columns, labeled 1-10. There are a total of 100 rows. For each of the ten columns, I would like to add all the values in that column, where the 'count' value is between 100-400, to a list. This would result in 10 lists. I have attached a sample of what ...
<p>You're nearly there, conceptually, but you probably just want the in-built <code>pandas</code> function to help you do this: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer"><code>to_dict</code></a>.</p> <pre><code># Get the data which falls...
python|pandas|csv
0