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
373,900
57,011,858
Not able to delete 'matchId' column from pandas dataframe
<p>I have a dataframe which looks like this</p> <p><a href="https://i.stack.imgur.com/3r7to.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3r7to.png" alt="enter image description here"></a> </p> <p>I tried to delete <strong>matchId</strong> but no matter what I use to delete it, for preprocessing,...
<p>What you attempted to do (which you should have mentioned in the question) is probably failing because you assume that the <code>matchID</code> column is a normal column. It is actually a special, <strong>index</strong> column and so cannot be accessed in the same way other columns can be accessed.</p> <p>As sugges...
python|pandas
1
373,901
56,873,709
Pandas append sheet to workbook if sheet doesn't exist, else overwrite sheet
<p>I am updating an existing Excel workbook using pandas. When using an <code>ExcelWriter</code> object, can I overwrite a sheet if it exists and otherwise create a new sheet? The code I have appends new sheets, but when I try to overwrite an existing sheet it appends a new sheet with a slightly varied name (ex: If she...
<p>Pass the sheets to the <code>writer</code> with <code>writer.sheets = dict((ws.title, ws) for ws in book.worksheets)</code>:</p> <pre><code>import pandas as pd import openpyxl path = 'test-out.xlsx' book = openpyxl.load_workbook(path) df1 = pd.DataFrame({'a': range(10), 'b': range(10)}) writer = pd.ExcelWriter(path...
python|excel|pandas
6
373,902
57,038,085
how to create shared weights layer in multiple input models with no grads
<p>I want to create a model with 2 inputs x and y. And I want make loss function only concerned about x. So the model can optimize former layer only with x. But now even the loss is only concerned about x, the optimazition will still calculate x and y in the former layer.</p> <p>I have tried to make y to y.detach() to...
<p>What you did should work, you just need to put your <code>y.detach()</code> at the end, and if the loss doesn't contain <code>y</code> it shouldn't modify the weights through <code>y</code> anyway.</p> <pre><code>def forward(self, x, y=None): x = self.conv1(x) x = self.bn1(x) x = self.maxpool(x) x =...
python|neural-network|deep-learning|pytorch
0
373,903
57,148,617
RuntimeError: Expected hidden size (2, 24, 50), got (2, 30, 50)
<p>I am trying to build a model for learning assigned scores (real numbers) to some sentences in a data set. I use RNNs (in PyTorch) for this purpose. I have defined a model:</p> <pre><code>class RNNModel1(nn.Module): def forward(self, input ,hidden_0): embedded = self.embedding(input) output, hi...
<p>This error happens when the number of samples in data set is not a multiple of the size of the batch. Ignoring the last batch can solve the problem. For identifying the last batch, check the number of elements in each batch. If that was less than BATCH_SIZE then it is the last batch in data set.</p> <pre><code>if(l...
python|pytorch|lstm|recurrent-neural-network|gated-recurrent-unit
1
373,904
57,060,488
pandas.Series.div() vs /=
<p>I'm curious why pandas.Series.div() is slower than /= when applying to a pandas Series of numbers. For example:</p> <pre><code>python3 -m timeit -s 'import pandas as pd; ser = pd.Series(list(range(99999)))' 'ser /= 7' 1000 loops, best of 3: 584 usec per loop python3 -m timeit -s 'import pandas as pd; ser = pd.Seri...
<p>Pandas <code>.div</code> obviously implement division similarly to <code>/</code> and <code>/=</code>.</p> <p>The main reason to have a separate <code>.div</code> is that Pandas embraces a syntax model where operations on dataframes are described by the applications of consecutive <em>filters</em>, e.g. <code>.div<...
python|pandas|performance
3
373,905
56,955,962
What is the best way to count the number of entries across 3 dataframes that aren't shared?
<p>I have three dataframes that are summaries of various statistics about countries. I've created a join of the three dataframes on the 'Country Name' column. But I want to know how many entries exist in the three original dataframes that were excluded from the join. Whats the best way code wise to count this?</p>
<p>As you didn't provide your code and dataframes, it is not clear what is the output of your three dataframes join. also you should consider the pandas default <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html#pandas.DataFrame.join" rel="nofollow noreferrer">join</a> is lef...
python|python-3.x|pandas|dataframe
0
373,906
56,980,886
Partial Pivoting In Pandas SQL Or Spark
<p>Partial Pivoting In Pandas SQL Or Spark</p> <p>Make the Year remain as Rows, and have the States Transpose to columns Take Pecentage value of a Gender Male Race White,</p> <p><strong>Input</strong></p> <blockquote> <p><a href="https://i.stack.imgur.com/qz2mj.png" rel="nofollow noreferrer"><img src="https://i.stack.i...
<p>Answer Posted By @Peter Leimbigler as comment</p> <pre><code>df.pivot_table(index='Year', columns='States', values='Percentage') </code></pre> <p>I tried it works.. Thanks Peter</p>
python|pandas|scala|apache-spark|xlsx
0
373,907
57,059,576
Why is np.pad not working the way I expect it to?
<p>My code generates an array that is 4x2. It also generates another array that is 10x6 I want to pad each array with zeros so that it is centered in an array that is 14x12 after padding. </p> <p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html" rel="nofollow noreferrer">https://docs.scipy....
<p>Like this you get an array with shape(14,12) with the smaller array centered.</p> <pre><code>source_array = np.random.rand(10,6) target_array_shape = (14,12) pad_x = (target_array_shape[0]-source_array.shape[0])//2 pad_y = (target_array_shape[1]-source_array.shape[1])//2 target_array = np.pad(source_array, ((pad_x...
python|numpy|runtime-error
1
373,908
57,228,323
How do I export multiple lists to one csv?
<p>How do I add each iteration of this list to a csv file for an unknown number of columns. </p> <p>This is because the genre list and not the same length for each film.</p> <p>If the film only has less than the max then the other columns I would expect to be empty.</p> <p>I would expect the output to look a little ...
<p>To extract all genres you could use this script - it will save it to the CSV and print to the screen too:</p> <pre><code>import csv import requests from bs4 import BeautifulSoup url = 'https://www.imdb.com/search/title/?pf_rd_i=moviemeter&amp;genres=action&amp;explore=title_type,genres' soup = BeautifulSoup(reque...
python|numpy|beautifulsoup
1
373,909
57,260,045
Replace values between dataframes with different sizes and multiple conditions
<p>So I have 2 dataframes, from different sizes, <code>df1 = (578, 81)</code> and <code>df2 = (1500, 59)</code>, all lines on <code>df1 exists in df2</code>, and all columns in <code>df2 exists in df1</code>, my problem is, I have a value that i want to update in df1 based on <code>6 conditions</code>, so to update the...
<p>You can easily use <code>numpy.where</code>. And i think it should work best in this case too.</p> <p>Let's say you have the following DataFrames</p> <pre><code>import pandas as pd df1=pd.DataFrame({'X':[1,3,4,6,5], 'X1':[2,3,4,6,3], 'Y1':[4,2,1,51,3], 'Z1':[2...
python|pandas|dataframe
2
373,910
56,946,934
How to convert key and value of dictionary to a dataframe column?
<p>I have a Python dictionary and I am unable to convert key and value of dictionary to a dataframe column.</p> <pre><code>import pandas as pd data={'form-0-publish': ['05/28/2019'], 'form-0-cell': ['81'], 'form-0-cell_name': ['13a'], 'form-0-jam': ['07.00-08.00'], 'form-0-target': ['60'], 'form-1-publish': ['05...
<p>I think directly there is no function to perform this type of task, but I have made 2 <code>for</code> loops to get your result:-</p> <pre><code>data={'form-0-publish': ['05/28/2019'], 'form-0-cell': ['81'], 'form-0-cell_name': ['13a'], 'form-0-jam': ['07.00-08.00'], 'form-0-target': ['60'], 'form-1-publish': ['0...
python|python-3.x|pandas|dictionary|jupyter-notebook
0
373,911
57,177,262
How to upsample an array to arbitrary sizes?
<p>I am trying to resize an array to a larger size in Python by repeating each element proportionally to the new size. However, I want to be able to resize to arbitrary sizes.</p> <p>I know that I can do it with <code>numpy.repeat</code> if for example I have to double the size but lets say I want to convert an array ...
<p>Without a clear idea about the final result you would like to achieve, your question opens multiple paths and solutions. Just to name a few:</p> <ol> <li>Using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.resize.html" rel="nofollow noreferrer"><code>numpy.resize</code></a>:</li> </ol> <pre><...
python|arrays|python-3.x|numpy|resize
3
373,912
56,890,822
Pandas - add a row at the end of a for loop iteration
<p>So I have a for loop that gets a series of values and makes some tests:</p> <pre><code>list = [1, 2, 3, 4, 5, 6] df = pd.DataFrame(columns=['columnX','columnY', 'columnZ']) for value in list: if value &gt; 3: df['columnX']="A" else: df['columnX']="B" df['columnZ']="Another value only to...
<p>I am not sure to understand exactly but I think this may be a solution:</p> <pre><code>list = [1, 2, 3, 4, 5, 6] d = {'columnX':[],'columnY':[]} for value in list: if value &gt; 3: d['columnX'].append("A") else: d['columnX'].append("B") d['columnY'].append(value-1) df = pd.DataFrame(d) </c...
python|pandas
1
373,913
57,043,614
Is there any faster way in python to split strings to sublists in a list with 1million elements?
<p>I'm trying to help my friend to clean an order list dataframe with one million elements.</p> <p><a href="https://i.stack.imgur.com/hy3KZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hy3KZ.jpg" alt="enter image description here"></a></p> <p>you can see that the product_name column should be a ...
<h1>EDIT</h1> <p><strong>(I did not like last answer, it was too much confused, so I reordered it and tested I little bit more systematically).</strong></p> <h1>Long story short:</h1> <p>For speed, just use:</p> <pre><code>def str_to_list(s): return s[1:-1].replace('\'', '').split(', ') df['product_name'].apply(s...
python|python-3.x|pandas|performance|dataframe
4
373,914
57,174,889
How to get last n-number of rows with datetime index in a pandas dataframe?
<p>I am trying to get the last 32 data points from a pandas dataframe indexed by date. I have multiple re-sampled dataframes numbered data1, data2, data3, ect... that have been re-sampled from 1 hour, 4 hour, 12 hour, 1 day.</p> <p>I already tried to use get_loc with the datetime index that I want to end on for each d...
<p>I think you need <code>iloc</code> for select by positions:</p> <pre><code>pos = data2.index.get_loc(end_index) c = data2.iloc[pos - 32: pos].bfill().ffill() pos = data3.index.get_loc(end_index) d = data3.iloc[pos - 32: pos].bfill().ffill() pos = data2.index.get_loc(end_index) e = data4.iloc[pos - 32: pos].bfill(...
python|pandas|datetime|indexing
2
373,915
57,188,182
How to evaluate difference between RGB numpy arrays?
<p>I'm building a software for a LED Canvas with 24 x 30 pixels. And I want to save the current state in a numpy array, then get a new state as a numpy array and slowly fade from the first state to the second state.</p> <p>To do so I was thinking i have to compare my two numpy arrays:</p> <pre><code>currentState = np...
<p>Literally just subtract them:</p> <pre><code>difference = newState - currentState </code></pre>
python|numpy
0
373,916
57,262,885
How is the memory allocated for numpy arrays in python?
<p>I tried to understand the difference caused by numpy "2D" arrays, that is, numpy.zeros((3, )), numpy.zeros((3, 1)), numpy.zeros((1, 3)).</p> <p>I used <code>id</code> to look at the memory allocation for each element. But I found some weird outputs in iPython console.</p> <pre class="lang-py prettyprint-override">...
<p>Numpy array saves its data in a memory area seperated from the object itself. As following image shows:</p> <p><img src="https://i.stack.imgur.com/EeBUb.png" alt="enter image description here"></p> <p>To get the address of the data you need to create views of the array and check the <code>ctypes.data</code> attrib...
python|numpy|memory|mpi4py
5
373,917
57,089,861
How to convert a set to an array?
<p>How to convert a set to an array?</p> <p>I tried:</p> <pre><code>import numpy as np mySet = {1,2,3,4,5} myRandomArray = np.asarray(mySet, dtype=int, order="C") print(myRandomArray) </code></pre> <p><strong>Output</strong></p> <blockquote> <p>return array(a, dtype, copy=False, order=order)</p> <p>TypeEr...
<pre><code>myset = {1,2,3,4,5} np.array(list(myset)) </code></pre>
python|numpy
1
373,918
56,937,088
How to get the index of duplicated values, while dropping NAs? Resulting index is smaller than original dataframe
<p>I'm working with a df:</p> <pre><code>df.shape[0] 82208 </code></pre> <p>And I want to index duplicates based on firstname, lastname and email:</p> <pre><code>indx = (df.dropna(subset=['firstname', 'lastname', 'email']) .duplicated(subset=['firstname', 'lastname', 'email'], keep=False)) indx 0 ...
<p>Instead of dropping the nans and then creating the boolean mask, add to the boolean mask that returns False for <code>nan</code> so you have all indexes retained, but false for nans. using <code>df.isna()</code> and <code>df.any()</code> for <code>axis=1</code> we can use the below:</p> <pre><code>cols=['firstname'...
python|pandas
1
373,919
57,147,356
class 'numpy.int32' wanted, but type() function only shows: numpy.ndarray
<p>I want to send a numpy array as a digital output through a NI card. I am using the nidaqmx package from NI (national instruments). For the digital output they expect a array. I converted my numpy arrays to int32, but it still does not work and when I checked the array with the type() function it gave numpy.ndarray ...
<p>You should use <code>vec.dtype</code> to see the type of what the array contains. <code>type(vec)</code> tells you the type of <code>vec</code>, which is obviously a <code>numpy.array</code>. The output of <code>vec.dtype</code> is <code>dtype('int32')</code>. It is the same as <code>np.int32</code>, check for yours...
python|numpy|output
0
373,920
57,116,361
How to make a pivot table from this data?
<p>I have data like </p> <pre><code>data = { "Person": ["A", "A", "A", "B", "B", "B"], "Month": [1, 2, 3, 1, 2, 3], "Value 1": [5, 6, 7, 8, 9, 10], "Value 2": [10, 11, 12, 13, 5, 4] } df = pd.DataFrame(data) </code></pre> <p>I want it to look like: </p> <pre><code> Person Value Month 1 Month...
<p>IIUC, can <code>pivot_table</code>+<code>unstack</code></p> <pre><code>df.pivot_table(columns='Month', index='Person')\ .unstack()\ .reset_index()\ .rename(columns={'level_0': 'Value'})\ .pivot_table(columns='Month', index=['Person', 'Value']) </code></pre> <p>Outputs</p> <pre><code> Month ...
python|pandas
1
373,921
56,887,503
Implement gradient descent in python
<p>I am trying to implement gradient descent in python. Though my code is returning result by I think results I am getting are completely wrong. </p> <p>Here is the code I have written:</p> <pre><code>import numpy as np import pandas dataset = pandas.read_csv('D:\ML Data\house-prices-advanced-regression-techniques\\...
<p>try to reduce the learning rate with iteration otherwise it wont be able to reach the optimal lowest.try this</p> <pre><code>import numpy as np import pandas dataset = pandas.read_csv('start.csv') X = np.empty((0, 1),int) Y = np.empty((0, 1), int) for i in range(dataset.shape[0]): X = np.append(X, dataset.at[i...
python|numpy|machine-learning|gradient-descent
1
373,922
45,724,633
Down-sampling specific period on dataframe using Pandas
<p>I have a long time serie that starts in 1963 and ends in 2013. However, from 1963 til 2007 it has an hourly sampling period while after 2007's sampling rate changes to 5 minutes. Is it possible to resample data just after 2007 in a way that the entire time serie has hourly data sampling? Data slice below.</p> <pre>...
<p>Give your dataframe proper column names</p> <pre><code>df.columns = 'year month day hour minute second sl'.split() </code></pre> <p><strong>Solution</strong> </p> <pre><code>df.groupby(['year', 'month', 'day', 'hour'], as_index=False).first() year month day hour minute second sl 0 2007 11 30 ...
python|pandas|dataframe|downsampling
2
373,923
45,741,649
(Python2) Combining pandas dataframe of mulilayer columns
<p>I want to add values of dataframe of which format is same. for exmaple</p> <pre><code>&gt;&gt;&gt; my_dataframe1 class1 score subject 1 2 3 student 0 1 2 5 1 2 3 9 2 8 7 2 3 3 4 7 4 6 7 7 &gt;&gt;&gt; my_dataframe2 class2 s...
<p>IIUC:</p> <pre><code>df_out = df['class1 score'].add(df2['class2 score'],fill_value=0).add_prefix('scores_') df_out.columns = df_out.columns.str.split('_',expand=True) df_out </code></pre> <p>Output:</p> <pre><code> scores 1 2 3 student 0 5.0 4 7...
python-2.7|pandas|dataframe
0
373,924
45,766,829
Pandas ordered categorical data on exam grades 'D',...,'A+'
<p>I have the following data in pandas, I was surprized that the output was: D+ A I was expecting A+ D</p> <p>can someone explain please</p> <pre><code>df = pd.DataFrame(['A+','A','A-','B+','B','B-','C+','C','C-','D+','D'], index = ['excellent','excellent','excellent','good','good','good','ok','o...
<p><code>max</code> is a Python function and it does not respect the category ordering. It uses lexicographical ordering based on unicode codes.</p> <p>If you want to take into account categorical orders, you need to use the methods defined on Series/DataFrames:</p> <pre><code>print(grades.min(), grades.max()) </code...
pandas|sorting|categorical-data
2
373,925
45,805,720
find indeces of grouped-item matches between two arrays
<pre><code>a = np.array([5,8,3,4,2,5,7,8,1,9,1,3,4,7]) b = np.array ([3,4,7,8,1,3]) </code></pre> <p>I have two lists of integers that each is grouped by every 2 consecutive items (ie indices [0, 1], [2, 3] and so on). The pairs of items cannot be found as duplicates in either list, neither in the same or the reverse...
<p>Since you are grouping your arrays by pairs, you can reshape them into 2 columns for comparison. You can then compare each of the elements in the shorter array to the longer array, and reduce the boolean arrays. From there it is a simple matter to get the indices using a reshaped <code>np.arange</code>.</p> <pre><...
python|numpy
2
373,926
46,005,286
pytorch inception model outputs the wrong label for every input image
<p>For the pytorch models I found <a href="http://blog.outcome.io/pytorch-quick-start-classifying-an-image/" rel="nofollow noreferrer">this tutorial</a> explaining how to classify an image. I tried to apply the same prcedure for an inception model. However the model fails for every image I load in</p> <p>Code:</p> <p...
<p>I found out that one needs to call <code>model.eval()</code> before applying the model. Because of the batch normalisations and also dropout layers, the model bahaves differently for training and testing.</p>
pytorch
2
373,927
45,953,647
TensorFlow restore throwing "No Variable to save" error
<p>I am working through some code to understand how to save and restore checkpoints in tensorflow. To do so, I implemented a simple neural netowork that works with MNIST digits and saved the .ckpt file like so:</p> <pre><code> from tensorflow.examples.tutorials.mnist import input_data import numpy as np learning_r...
<p>A <code>Graph</code> is different to the <code>Session</code>. A graph is the set of operations joining tensors, each of which is a symbolic representation of a set of values. A <code>Session</code> assigns specific values to the <code>Variable</code> tensors, and allows you to <code>run</code> operations in that gr...
python|tensorflow
1
373,928
45,884,288
Pandas Series.dt.total_seconds() not found
<p>I need a datetime column in seconds, everywhere (<a href="http://pandas.pydata.org/pandas-docs/version/0.20.3/generated/pandas.Series.dt.total_seconds.html" rel="noreferrer">including the docs</a>) is saying that I should use <code>Series.dt.total_seconds()</code> but it can't find the function. I'm assuming I have ...
<p><code>total_seconds</code> is a member of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.total_seconds.html#pandas.Series.dt.total_seconds" rel="noreferrer"><code>timedelta</code></a> not <code>datetime</code> </p> <p>Hence the error</p> <p>You maybe be wanting <code>dt.second</cod...
python|pandas
29
373,929
46,021,931
Tensorflow Installation in Ubuntu14.04
<p>I install tensorflow on my Ubuntu14.04,and I installed it with Anaconda.I follow the official installation guide.After I installed it,when I ran this code step by step.It went wrong.</p> <pre><code>import tensorflow as tf hello = tf.constant('Hello, TensorFlow!') sess = tf.Session() print(sess.run(hello)) </code></...
<p>This is not an actual "error". It is <a href="https://www.tensorflow.org/performance/performance_guide#best_practices" rel="nofollow noreferrer">informing you</a> that the computations could be faster if you have installed from source with support to the mentioned instructions, e.g., SSE4.1, SSE4.2, etc.</p> <p>You...
python|tensorflow
0
373,930
45,871,154
How to efficiently create a pivot table?
<p>I do have a dataframe like this:</p> <pre><code>import pandas as pd df = pd.DataFrame({"c0": list('ABC'), "c1": [" ".join(list('ab')), " ".join(list('def')), " ".join(list('s'))], "c2": list('DEF')}) c0 c1 c2 0 A a b D 1 B d e f E 2 C s F </code></pre> <...
<p><strong>Option 1</strong> </p> <pre><code>import numpy as np, pandas as pd s = df.c1.str.split() l = s.str.len() newdf = df.loc[df.index.repeat(l)].assign(c1=np.concatenate(s)).set_index(['c0', 'c1']) newdf c2 c0 c1 A a D b D B d E e E f E C s F </code></pre> <hr> <p><strong>Op...
python|performance|pandas
3
373,931
45,962,669
pandas.DatetimeIndex.snap timestamps to left occurring frequency
<p>I would like to have the same functionality that snap but using the <strong>left</strong> occurring frequency instead of the nearest. </p> <p>This is what I am trying:</p> <pre><code>date = pd.date_range('2015-01-01', '2015-12-31') week_index = pd.DatetimeIndex.snap(date, 'W-MON') week_index DatetimeIndex(['2014...
<p>I find the solution in pandas snap source code:</p> <p>use rollback instead:</p> <pre><code>from pandas.tseries.frequencies import to_offset freq = to_offset('W-MON') date.map(freq.rollback) </code></pre>
python|pandas|datetimeindex
5
373,932
45,976,234
module 'tensorflow.contrib.rnn' has no attribute 'BasicLSTMCell'
<p>When I try to run</p> <pre><code>lstm_fw_cell = rnn.BasicLSTMCell(num_hidden, forget_bias=1.0) </code></pre> <p>I get the error mentioned in the title. </p> <p>Is this due to the tensorflow version? How to resolve this issue?</p>
<p>Try to replace <code>rnn.BasicLSTMCell</code> with <a href="https://www.tensorflow.org/versions/r0.12/api_docs/python/rnn_cell/rnn_cells_for_use_with_tensorflow_s_core_rnn_methods#BasicLSTMCell" rel="nofollow noreferrer"><code>tf.nn.rnn_cell.BasicLSTMCell</code></a>. See more details <a href="https://github.com/tens...
tensorflow|lstm|rnn
1
373,933
46,026,834
Creating pd.dataframe from multiline String object
<p>I am new to Python and I have already found the posts here very helpful but now I am stuck. I have parsed trading data from an email and saved it into a string object that looks like this:</p> <p>=E2=84=96\tOrderID\tInstrument/ISIN\tDirection\tQuantity\t=\nPrice\tAmount\tDeal time\tSlippage\tConfirmation time\t=\n...
<p>A messy one.</p> <p>The first thing I did, having saved that text to a file, was to split it on the <code>\\n</code>s, to make it easier to understand, and write out the pieces. This enabled me to see several features of the data:</p> <ul> <li>There are three lines of 'header' and then three lines in each 'record'...
python-3.x|pandas
0
373,934
45,911,225
How to use Tensorflow to train Poisson regression?
<p>I want to train a Poisson regression to compare with the log(Y) linear regression in Tensorflow. However, I've only found <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/distributions/Poisson" rel="nofollow noreferrer">tf.contrib.distributions.Poisson</a>. Can anyone offer some insight to help me? Th...
<p>those days I find one function maybe help: </p> <pre><code>loss = tf.nn.log_poisson_loss(targets=batch_labels, log_input=logits) </code></pre>
tensorflow|regression
1
373,935
46,071,295
Can't get a new tf.Operation to work in Python shell in Tensorflow
<p>I am trying to add a new integer Matrix Multiplication OP in tensorflow and I am not able to successfully register it as a tf operation so that it can be called as tf.intmatmul in python. </p> <p>Steps I did : 1) Added a new REGISTER_OP - IntMatMul in the math_ops.cc file.</p> <p>2) Added a new kernel implementati...
<p><em>UPDATE:</em></p> <p>So this turned out to be more complicated than expected. These are the things that had to be taken into account:</p> <ul> <li>Apparently, in order for a function to be exposed as public API (that is, at <code>tf.</code> level), its name must be listed at the beginning of the module in its d...
python|c++|tensorflow
2
373,936
46,102,671
How to show distributions of multiple features in one tensor in TensorBoard
<p>I have a tensor <code>X</code> which is an output of the batch normalization layer (<code>tf.layers.batch_normalization</code>) and has the shape of <code>[batch_size, 15]</code>. To monitor its distribution, I created a histogram for <code>X</code> with <code>tf.summary.histogram('out_BN_0', X)</code>. The graph is...
<p>How about building a histogram per each feature?</p> <pre><code>import tensorflow as tf import numpy as np batch_size = 100 num_features = 15 X = tf.constant(np.random.uniform(size=(batch_size, num_features))) hists = {feature_index: tf.summary.histogram(f'hist_{feature_index}', X[:, feature_index]) ...
tensorflow|visualization|tensorboard
2
373,937
46,141,690
How do I write a PyTorch sequential model?
<p>How do I write a sequential model in PyTorch, just like what we can do with Keras? I tried:</p> <pre><code>import torch import torch.nn as nn net = nn.Sequential() net.add(nn.Linear(3, 4)) net.add(nn.Sigmoid()) net.add(nn.Linear(4, 1)) net.add(nn.Sigmoid()) net.float() </code></pre> <p>But I get the error:</p> <blo...
<p><code>Sequential</code> does not have an <code>add</code> method at the moment, though there is some <a href="https://github.com/pytorch/pytorch/issues/358" rel="noreferrer">debate</a> about adding this functionality. </p> <p>As you can read in the <a href="http://pytorch.org/docs/master/nn.html#torch.nn.Sequential...
python|sequential|pytorch
43
373,938
46,148,302
What is the best way to access values in a dataframe column?
<p>For example I have</p> <pre><code>df=pd.DataFrame({'a':[1,2,3]}) df[df['a']==3].a = 4 </code></pre> <p>This does not assign 4 to where 3 is </p> <pre><code>df[df['a']==3] = 4 </code></pre> <p>But this works.</p> <p>It confused me on how the assignment works. Appreciate if anyone can give me some references or e...
<p>You do <em>not</em> want to use the second method. It returns a dataframe subslice and assigns the same value to every single row.</p> <p>For example,</p> <pre><code>df a b 0 1 4 1 2 3 2 3 6 df[df['a'] == 3] a b 2 3 6 df[df['a']==3] = 3 df a b 0 1 4 1 2 3 2 3 3 </code></pre> <p>The...
python|pandas|dataframe|indexing
3
373,939
46,086,136
Shipping and using virtualenv in a pyspark job
<p>PROBLEM: I am attempting to run a spark-submit script from my local machine to a cluster of machines. The work done by the cluster uses numpy. I currently get the following error:</p> <pre><code>ImportError: Importing the multiarray numpy extension module failed. Most likely you are trying to import a failed bu...
<p>With <code>--conf spark.pyspark.{}</code> and <code>export PYSPARK_PYTHON=/usr/local/bin/python2.7</code> you set options for your local environment / your driver. To set options for the cluster (executors) use the following syntax:</p> <pre><code>--conf spark.yarn.appMasterEnv.PYSPARK_PYTHON </code></pre> <p>Furt...
numpy|pyspark|virtualenv
6
373,940
45,786,083
Change 1 point color in scatter plot regardless of color palette
<p>I have a pandas data frame <code>df</code> like this </p> <p><code>NAME VALUE ID A 0.2 X B 0.4 X C 0.5 X D 0.8 X ... Z 0.3 X </code></p> <p>I would like to color all the points by the 'NAME' column by specifying the hue='NAME' but specify the color for ONE point: B. </p> <p>Ho...
<p>You can replace one color in the palette by converting it to a list of colors and then replace one of the colors by some other color of your liking.</p> <pre><code>import pandas as pd import numpy as np;np.random.seed(42) import matplotlib.pyplot as plt import seaborn as sns letters = list(map(chr, range(ord('A'),...
python|pandas|matplotlib|seaborn|scatter
4
373,941
45,852,289
Adding multiple columns of unique calculated values to a pandas dataframe
<p>I would like to add new columns to a data frame using function and values from the original data frame </p> <p>Create the dataframe</p> <pre><code>df = pd.DataFrame({'f1' : np.random.randn(10), 'f2' : np.random.randn(10), 'f3' : np.random.randn(10), '...
<p>You can try this</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'f1' : np.random.randn(10), 'f2' : np.random.randn(10), 'f3' : np.random.randn(10), 'f4' : np.random.randn(10), 'f5' : np.random.randn(10)...
python|pandas|dataframe|assign
0
373,942
46,151,185
Calculate jaccard distance using scipy in python
<p>I have two separate lists as follows.</p> <pre><code>list1 =[[0.0, 0.75, 0.2], [0.0, 0.5, 0.7]] list2 =[[0.9, 0.0, 0.8], [0.0, 0.0, 0.8], [1.0, 0.0, 0.0]] </code></pre> <p>I want to get a list1 x list2 jaccard distance matrix (i.e. the matrix includes 6 values: 2 x 3)</p> <pre><code> For example; [0.0, 0.75, 0...
<p>You need to pass to pdist a <code>m x n</code> 2D array. To construct it, you can use a simple nested loop. You could probably do something like this :</p> <pre><code>import scipy.spatial.distance as dist list1 =[[0.0, 0.75, 0.2], [0.0, 0.5, 0.7]] list2 =[[0.9, 0.0, 0.8], [0.0, 0.0, 0.8], [1.0, 0.0, 0.0]] distance...
python|numpy|scipy
1
373,943
45,754,067
Error in plotting line graph
<p>Appreciate it if someone could explain to me what went wrong?</p> <p>1) Couldnt plot line graph....I managed to plot my data only with point marker('r.') or round marker('r.'), the plot just blank with no data when I tried to plot it with line graph changing it to ('r-') </p> <p>Below is my code to produce the fig...
<p>The data is stored in a list of a list. I.e. you have <code>[[1,2,3]]</code> instead of <code>[1,2,3]</code>. This will not be understood correctly by matplotlib, such that no lines are drawn in between the points. </p> <p>To correctly produce the required lists, use </p> <pre><code>y = myBlueList x = myList y1 =...
python|opencv|numpy|matplotlib
3
373,944
45,917,524
Why NumPy is casting objects to floats?
<p>I'm trying to store intervals (with its specific arithmetic) in NumPy arrays. If I use my own Interval class, it works, but my class is very poor and my Python knowledge limited.</p> <p>I know <a href="http://pyinterval.readthedocs.io/en/latest/" rel="nofollow noreferrer" title="pyInterval">pyInterval</a> and it's ...
<p>To be fair, it is really hard for the <code>numpy.ndarray</code> constructor to infer what kind of data should go into it. It receives objects which resemble lists of tuples and makes do with it.</p> <p>You can, however, help your constructor a bit by not having it guess the shape of your data:</p> <pre><code>a = ...
python|class|numpy|intervals
2
373,945
45,788,433
How to enable Dataset pipeline has distributed reading and consuming
<p>It is easy to use two threads that one keeps feeding data to the <a href="https://www.tensorflow.org/programmers_guide/threading_and_queues" rel="nofollow noreferrer">queue</a> and the other consumes data from the queue and perform the computation. Since the TensorFlow recommends <a href="https://www.tensorflow.org/...
<p>Distributed <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/data" rel="nofollow noreferrer"><code>tf.contrib.data</code></a> pipelines are not yet supported as of TensorFlow 1.3. We are working on support for splitting datasets across devices and/or processes, but that support is not yet ready.</p> <...
python|machine-learning|tensorflow|distributed-computing
1
373,946
45,765,809
Python input function explanation
<p>Could someone explain the role of the following functions:</p> <pre><code>list() map() split() </code></pre> <p>In the context of this line of code please:</p> <pre><code>input = list(map(int,input().split())) </code></pre> <p>Finally, should it be:</p> <pre><code>int,input() </code></pre> <p>rather than:</p> ...
<p>All of these functions are members of the standard library and are as such covered by the <a href="https://docs.python.org/3.6/library/functions.html" rel="nofollow noreferrer">official documentation</a>.</p> <p>That being said, I'll summarise them briefly.</p> <ol> <li><p><code>list</code> turns an <a href="https:/...
python|numpy|input
2
373,947
46,049,389
Error: tuple index out of range python 3
<p>Maybe you can give me your advise? </p> <p>I have a web page <code>clarity-project.info/tenders/…</code> and I need to extract <code>data-id="&lt;some number&gt;"</code> and write them in a new file</p> <p>Here is my code: </p> <pre><code>from urllib.request import urlopen, Request from bs4 import BeautifulSoup ...
<p>Is this what you wanted? It'll give you all the value of "data-id" with a text file with those data written within.</p> <pre><code>import requests from bs4 import BeautifulSoup file = open("testfile.txt","w") res = requests.get('https://clarity-project.info/tenders/?entiy=38163425&amp;offset=100').text soup = Bea...
python|python-3.x|numpy|web-scraping|beautifulsoup
0
373,948
46,121,278
Retrain InceptionV4's Final Layer for New Categories: local variable not initialized
<p>I'm still newbie in tensorflow so I'm sorry if this is a naive question. I'm trying to use the <code>inception_V4</code> <a href="http://download.tensorflow.org/models/inception_v4_2016_09_09.tar.gz" rel="noreferrer">model pretrained</a> on <code>ImageNet</code> dataset published on this <a href="https://github.com/...
<p>Variables that are not restored with the saver need to be initialized. To this end, you could run <code>v.initializer.run()</code> for each variable <code>v</code> that you don't restore.</p>
python|tensorflow
3
373,949
45,741,552
Do I need to install keras 2.0 seprately after installing tensorflow 1.3?
<p>I just upgraded my tf from 1.0 to tf 1.3 (pip install --upgrade tensorflow) . I know keras 2.0 became part of tensorflow since tf version 1.2. However, when I import keras and check its version it still shows 1.2. Am I supposed to upgrade keras also? if so, then what does "<a href="https://blog.keras.io/introducing-...
<p>Nope, you don't need to install keras 2.0 separately. (See: <a href="https://www.tensorflow.org/guide/keras" rel="nofollow noreferrer">https://www.tensorflow.org/guide/keras</a>)</p> <p><strong>Do</strong> this:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf model = tf.keras.Sequentia...
tensorflow|keras
3
373,950
46,058,500
How to correctly save a dictionary in .npz format
<p>I am writing a program that loads an npz file, makes some changes to the values and stores it again. The .npz file varies in shape (dimensions).</p> <p>I have gotten to the point where I can do everything, with exception that the individual numpy arrays are out of order. </p> <p>Code flow: </p> <pre><code>data = ...
<p>That's because at the beginning you convert the data to a dictionary:</p> <pre><code>data = dict(np.load(my_npz_file)) </code></pre> <p>Dictionaries don't preserve order in Python (<a href="https://stackoverflow.com/questions/39980323/dictionaries-are-ordered-in-python-3-6">at least in your Python version</a>), bu...
python|numpy
9
373,951
46,037,548
Stata to Pandas: even if there are repeated Value Labels?
<p>i try to open a .dta as DataFrame. But an Error appears: "ValueError: Value labels for column ... are not unique. The repeated labels are:" followed by labels wich apper twice in a column.</p> <p>I know labeling multiplie codes with the exact same value label in stata is not clever (not my fault :)) After some rese...
<p>Since at least pandas 0.22, you can pass <code>convert_categoricals=False</code> to <code>read_stata</code> and it will not attempt to map the numerical values to their definitions.</p> <p><code>d = pd.read_stata('fooy_labels.dta', convert_categoricals=False)</code></p> <p>Your resulting DataFrame will have the nume...
python|pandas|stata|label
3
373,952
45,810,417
OpenCV, Python: How to use mask parameter in ORB feature detector
<p>By reading a few answers on stackoverflow, I've learned this much so far:</p> <p>The mask has to be a <code>numpy</code> array (which has the same shape as the image) with data type <code>CV_8UC1</code> and have values from <code>0</code> to <code>255</code>.</p> <p>What is the meaning of these numbers, though? Is...
<p>So here is most, if not all, of the answer:</p> <blockquote> <p>What is the meaning of those numbers</p> </blockquote> <p>0 means to ignore the pixel and 255 means to use it. I'm still unclear on the values in between, but I don't think all nonzero values are considered "equivalent" to 255 in the mask. See <a h...
python|opencv|numpy|feature-detection
7
373,953
45,942,222
KeyError when extracting data from a pandas.core.series.Series
<p>In the following ipython3 session, I read differently-formatted tables and make the sum of the values found in one of the columns:</p> <pre><code>In [278]: F = pd.read_table("../RNA_Seq_analyses/mapping_worm_number_tests/hisat2/mapped_C_elegans/feature_count/W100_1_on_C_elegans/protein_coding_fwd_counts.txt", skip ...
<p>I think you need:</p> <pre><code>#select first value of one element series f = F.iat[0] #alternative #f = F.iloc[0] </code></pre> <p>Or:</p> <pre><code>#convert to numpy array and select first value f = F.values[0] </code></pre> <p>Or:</p> <pre><code>f = F.item() </code></pre> <p>And I think you get error, be...
python|pandas
7
373,954
45,947,951
plotly, not showing coordinates with np.array dataset
<p>I wish to display a dataset of 1000 float, I have decided to do this with plotly, and I want to do it offline, I am getting in to a problem I really can't understand - I simply don't know what I am doing wrong at all.</p> <p>Let's jump in to the code. First of I will show that the code should work, with a small np....
<p><code>fetchall</code> returns tuples, so you end up with a <code>Numpy</code> array which has a shape of <code>(n, 1)</code> where n is the number of results. You could get the data in the correct format for <code>Plotly</code> using the following index:</p> <pre><code>np.array(graph_test_q())[:,0] </code></pre> <...
python|numpy|ipython|data-visualization|plotly
0
373,955
45,901,315
Pandas read_table returns ’ characters
<p>I'm seeing things like <code>’</code> after reading a text file with read_table(). The input file contents appear as ordinary ASCII characters in Windows Notepad. </p> <pre><code>dataRaw = pd.read_table('data.txt', header=None) </code></pre> <p>Do I need to include some character set parameter to prevent this?</...
<p>I figured it out. It took two steps: (1) use the correct encoding; (2) convert things that are supposed to be apostrophes to apostrophes.</p> <pre><code>for line in open(dataPath, encoding='utf-8'): outstr = re.sub(r'[´]', '’', line) # replace non-ASCII tick with apostrophe outstr = re.sub('[\']', '’', outst...
python|file|pandas|text|encoding
1
373,956
46,099,109
OutOfRangeError: RandomShuffleQueue '_2_shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 1, current size 0)
<p>I am getting the outOfRange error when trying to feed the data to the model. I am guessing that data never reaches the queue, hence the error. Just for the testing I am feeding it the tfrecord with one tuple (image,ground_truth). I also tried tensorflow debugger(tfdbg) but it would also just throw the same error I c...
<blockquote> <p>If the Annotation image is wrong, this error will be shown. Please see the annotation image matrix value. It should be differ. For example the annotation image matrix value have gray color(matrix value[1 1 1]) but your image not gray(matix value[1 3 6]). So check the matrix value of your annot...
debugging|tensorflow
0
373,957
45,813,400
Sort two lists of lists by index of inner list
<p>Assume I want to sort a list of lists like explained <a href="https://stackoverflow.com/questions/4174941/how-to-sort-a-list-of-lists-by-a-specific-index-of-the-inner-list">here</a>:</p> <pre><code>&gt;&gt;&gt;L=[[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']] &gt;&gt;&gt;sorted(L, key=itemgetter(2)) [[9, 4, 'afsd'], [0,...
<p>If I understood you correctly, you want to order <code>B</code> in the example below, based on a sorting rule you apply on <code>L</code>. Take a look at this:</p> <pre><code>L = [[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']] B = ['a', 'b', 'c'] result = [i for _, i in sorted(zip(L, B), key=lambda x: x[0][2])] print(r...
python|list|sorting|numpy
2
373,958
45,989,249
Pandas pivot table ValueError: Index contains duplicate entries, cannot reshape
<p>I have a dataframe as shown below (top 3 rows):</p> <pre><code>Sample_Name Sample_ID Sample_Type IS Component_Name IS_Name Component_Group_Name Outlier_Reasons Actual_Concentration Area Height Retention_Time Width_at_50_pct Used Calculated_Concentration Accuracy Index ...
<p>You can use <code>groupby()</code> and <code>unstack()</code> to get around the error you're seeing with <code>pivot()</code>. </p> <p>Here's some example data, with a few edge cases added, and some column values removed or substituted for <a href="https://stackoverflow.com/help/mcve">MCVE</a>:</p> <pre><code># d...
python|pandas
12
373,959
46,114,462
TensorFlow allocating large amounts of main memory at session startup time
<p>Consider the following two line Python/TensorFlow interactive session:</p> <pre><code>import tensorflow as tf s=tf.Session() </code></pre> <p>If these commands are executed on an Ubuntu Linux 14.04 machine, using Anaconda Python 2.7.13 and TensorFlow r1.3 (compiled from sources), with 32G physical memory and 2 GPU...
<p>The default behavior of TensorFlow on GPU is to use all the memory available. However, if you want to avoid this behavior, you can specify to the session to dynamically allocate the memory.</p> <p>From the <a href="https://github.com/tensorflow/tensorflow/blob/r1.3/tensorflow/core/protobuf/config.proto" rel="nofoll...
python|tensorflow
1
373,960
45,897,179
string argument without an encoding
<p>Can someone please tell why am I receiving the following error on python 3. The following is the traceback:</p> <pre><code>TypeError Traceback (most recent call last) &lt;ipython-input-24-a81d4875414b&gt; in &lt;module&gt;() 7 filename = [("id"), ("name"), ("email"), ("amount"),("sent")] 8 writ...
<p>The error seems to be from using Python 3, but using Python 2 requirements for opening <code>csv</code> files. If using Python 3, CSV files should not be opened in binary mode, and the the newline parameter should be the empty string. The temporary file defaults to binary mode as well, so I've overridden it. I al...
python|python-2.7|python-3.x|numpy|data-analysis
0
373,961
22,965,747
Deleting Array Element in Python, Issues with np.delete
<p>I have a list of coordinates among other things, I want to delete the number of objects I have in, say, quadrant I. I tried using np.delete, but perhaps my loop is wrong since it only deletes one single object. Here's what I have so far:</p> <pre><code>import sys import os import numpy as np from pylab import * i...
<p>In your for loop build a list of i's that need to be deleted (e.g. del_list). Once you are done with the loop, you can delete the list of i's from c1 and c2</p> <pre><code>new_a = np.delete(c1, del_list) new_b = np.delete(c2, del_list) </code></pre>
python|arrays|numpy
1
373,962
22,995,762
pandas to_csv: suppress scientific notation in csv file when writing pandas to csv
<p>I am writing a pandas df to a csv. When I write it to a csv file, some of the elements in one of the columns are being incorrectly converted to scientific notation/numbers. For example, <code>col_1</code> has strings such as <code>'104D59'</code> in it. The strings are mostly represented as strings in the csv fil...
<blockquote> <p>For python 3.xx (<code>Python 3.7.2</code>)&amp;</p> <p><code>In [2]: pd.__version__</code> <code>Out[2]: '0.23.4'</code>:</p> </blockquote> <p><a href="https://pandas.pydata.org/pandas-docs/stable/options.html" rel="noreferrer">Options and Settings</a></p> <p><a href="https://pandas.pydata.org/pandas-d...
python|csv|pandas|type-conversion|scientific-notation
17
373,963
23,023,878
Why to convert a python list to a numpy array?
<p>There's <a href="https://stackoverflow.com/questions/7717380/how-to-convert-2d-list-to-2d-numpy-array">a simply way</a> way to convert a list of numbers in python to a numpy array.</p> <p>But the simple functions that I have tried, for instance <code>numpy.average(x)</code>, would work regardless of whether <code>x...
<p>The answers that have been given thus far are very good. The simple convenience of having much of the NumPy functionality bound to the array object through its methods is very helpful. Here's something that hasn't been mentioned yet.</p> <p>One very good reason to convert your lists to arrays <em>before</em> passin...
python|python-2.7|numpy
3
373,964
23,232,463
Python: Replace a cell value in Dataframe with if statement
<p>I have a matrix with that looks like this:</p> <pre><code> com 0 1 2 3 4 5 AAA 0 5 0 4 2 1 4 ABC 0 9 8 9 1 0 3 ADE 1 4 3 5 1 0 1 BCD 1 6 7 8 3 4 1 BCF 2 3 4 2 1 3 0 ... </code></pre> <p>Where <code>AAA, ABC</code> ... is the dataframe index. The dataframe columns are <code>com 0 1 3 4 5 6</code></p> ...
<p>Just require some <code>numpy</code> trick</p> <pre><code>In [22]: print df 0 1 2 3 4 5 0 5 0 4 2 1 4 0 9 8 9 1 0 3 1 4 3 5 1 0 1 1 6 7 8 3 4 1 2 3 4 2 1 3 0 [5 rows x 6 columns] In [23]: #making a masking matrix, 0 where column and index values equal, 1 elsewhere, kind of th...
python|pandas
2
373,965
23,232,989
Boxplot stratified by column in python pandas
<p>I would like to draw a boxplot for the following pandas dataframe:</p> <pre><code>&gt; p1.head(10) N0_YLDF MAT 0 1.29 13.67 1 2.32 10.67 2 6.24 11.29 3 5.34 21.29 4 6.35 41.67 5 5.35 91.67 6 9.32 21.52 7 6.32 31.52 8 3.33 13.52 9 4.56 44.52 </code></pre> <p>...
<p>Pandas has the <code>cut</code> and <code>qcut</code> functions to make stratifying variables like this easy:</p> <pre><code># Just asking for split into 4 equal groups (i.e. quartiles) here, # but you can split on custom quantiles by passing in an array p1['MAT_quartiles'] = pd.qcut(p1['MAT'], 4, labels=['0-25%', ...
python|matplotlib|pandas|boxplot
10
373,966
22,991,318
TypeError in Python when using Pyalgotrade
<p>I trying to write a Stochcastic Oscillator in python using the list function in Pyalgotrade library.</p> <p>My code is below:</p> <pre><code>from pyalgotrade.tools import yahoofinance from pyalgotrade import strategy from pyalgotrade.barfeed import yahoofeed from pyalgotrade.technical import stoch from pyalgotrade...
<p>Either <code>bar.getClose()</code> or <code>self.__stoch[-1]</code> is returning a <code>numpy.ndarray</code> while both should be returning <code>float</code>s.</p>
python|numpy|pyalgotrade
0
373,967
23,159,791
Find the indices of non-zero elements and group by values
<p>I wrote a code in python that takes a numpy matrix as input and returns a list of indices grouped by the corresponding values (i.e. output[3] returns all indices with value of 3). However, I lack the knowledge of writing vectorized code and had to do it using ndenumerate. This operation only took about 9 seconds whi...
<p>Here's an O(n log n) algorithm for your problem. The obvious looping solution is O(n), so for sufficiently large datasets this will be slower:</p> <pre><code>&gt;&gt;&gt; a = np.random.randint(3, size=10) &gt;&gt;&gt; a array([1, 2, 2, 0, 1, 0, 2, 2, 1, 1]) &gt;&gt;&gt; index = np.arange(len(a)) &gt;&gt;&gt; sort_...
python|optimization|numpy
3
373,968
35,769,944
Manipulating matrix elements in tensorflow
<p>How can I do the following in tensorflow? </p> <pre><code>mat = [4,2,6,2,3] # mat[2] = 0 # simple zero the 3rd element </code></pre> <p>I can't use the [] brackets because it only works on constants and not on variables. I cant use the slice function either because that returns a tensor and you can't assign to a t...
<p>You can't change a tensor - but, as you noted, you can change a variable.</p> <p>There are three patterns you could use to accomplish what you want:</p> <p>(a) Use <a href="https://www.tensorflow.org/api_docs/python/tf/scatter_update" rel="noreferrer"><code>tf.scatter_update</code></a> to directly poke to the par...
matrix|indexing|element|variable-assignment|tensorflow
19
373,969
35,640,364
Python Pandas max value in a group as a new column
<p>I am trying to calculate a new column which contains maximum values for each of several groups. I'm coming from a Stata background so I know the Stata code would be something like this:</p> <pre><code>by group, sort: egen max = max(odds) </code></pre> <p>For example: </p> <pre><code>data = {'group' : ['A', 'A', ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="noreferrer"><code>groupby</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.transform.html" rel="noreferrer"><code>transform</code></a>:</p> <pre><code>df['max'] = df.g...
python|pandas|dataframe|grouping|pandas-groupby
38
373,970
35,663,705
how to plot time on y-axis in '%H:%M' format in matplotlib?
<p>i would like to plot the times from a datetime64 series, where the y-axis is formatted as '%H:%M, showing only 00:00, 01:00, 02:00, etc. </p> <p>this is what the plot looks like without customizing the y-axis formatting.</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt from mat...
<p>For that to work you need to pass <code>datetime</code> objects (and I mean <code>datetime</code>, not <code>datetime64</code>). You can convert all timestamps to the same date and then use <code>.tolist()</code> to get the actual <code>datetime</code> objects.</p> <pre><code>y = df['a'].apply(lambda x: x.replace(y...
python|pandas|matplotlib|python-datetime
6
373,971
35,636,896
return a list of all datasets in a hdf file with pandas
<p>This may be a stupid question, but i have yet to find an answer in the pandas docs or elsewhere. The same question has been asked before <a href="https://stackoverflow.com/questions/24236252/read-the-properties-of-hdf-file-in-python">here</a>. But the only answer was to look at the pandas docs, which as I stated don...
<p>Yes, there is.</p> <pre><code>store = pd.HDFStore('test.h5') print(store) &lt;class 'pandas.io.pytables.HDFStore'&gt; File path: test.h5 /df1 frame (shape-&gt;[10,2]) /df2 frame (shape-&gt;[10,2]) </code></pre>
python|pandas|hdf
11
373,972
35,644,847
python numpy slice notation (COMMA VS STANDARD INDEX)
<p>Is there a performance difference between using a comma and explicitly exploding out the index references for perhaps more conventional readers? Since both seem to yield the same results but the latter may be more intuitive to some</p> <pre><code>x = numpy.array([[1,2,3,4], [5,6,7,8]]) comma_metho...
<p>Pretty much always go for the comma, not for performance reasons, but because indexing twice isn't quite equivalent:</p> <pre><code>In [2]: x = numpy.array([[0, 1], [2, 3]]) In [3]: x[:1, :1] Out[3]: array([[0]]) In [4]: x[:1][:1] Out[4]: array([[0, 1]]) </code></pre> <p>That said, the comma also appears to have...
python|numpy|performance|slice
3
373,973
35,564,063
comparing ndarray with values in 1D array to get a mask
<p>I have two numpy array, 2D and 1D respectively. I want to obtain a 2D binary mask where each element of the mask is true if it matches any of the element of 1D array.</p> <p>Example</p> <pre><code> 2D array ----------- 1 2 3 4 9 6 7 2 3 1D array ----------- 1,9,3 Expected output --------------- Tru...
<p>You could use <code>np.in1d</code>. Although <code>np.in1d</code> returns a 1D array, you could simply reshape the result afterwards:</p> <pre><code>In [174]: arr = np.array([[1,2,3],[4,9,6],[7,2,3]]) In [175]: bag = [1,9,3] In [177]: np.in1d(arr, bag).reshape(arr.shape) Out[177]: array([[ True, False, True], ...
python|numpy
2
373,974
35,458,365
Use numpy arrays to count similar tuples
<p>I have 32 arrays like this one::</p> <pre><code>&gt;&gt;&gt; d01 array([[8, 4, 1, 0, 0], [6, 8, 5, 5, 2], [1, 1, 1, 1, 1]]) &gt;&gt;&gt; d02 ... &gt;&gt;&gt; d32 array([[8, 7, 1, 0, 3], [2, 8, 5, 5, 2], [1, 1, 1, 1, 1]]) </code></pre> <ul> <li>they have only ones in line 3, dxy[2, i] ...
<p>You can use the Counter container, which is a boosted dictionnary (see the <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow">documentation</a>).</p> <pre><code>import numpy as np from collections import Counter d01 = np.array([[8, 4, 1, 0, 0], [6, 8, 5, 5, 2], ...
python|numpy
2
373,975
35,383,388
Modify pandas dataframe in python based on multiple rows
<p>I am working with a DataFrame in Pandas / Python, each row has an ID (that is not unique), I would like to modify the dataframe to add a column with the secondname for each row that has multiple matching ID's. </p> <pre><code>Starting with: ID Name Rate 0 1 A 65.5 1 2 B 67.3 2 2 C 78.8 3 3...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with custom function <code>f</code>, which use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html" rel="nofollow noreferrer...
python|python-3.x|pandas
4
373,976
35,528,472
By dumping a python list, creating a python ".py" file which returns the same python list
<p>I have a ".csv" file which involves more than 1 million rows of data.</p> <p>In python, I have to process this data. In this case, after each running, I have to wait almost 1 minute in order to load the data.</p> <p>In order not to wait for such a long time, automatically I want to create a ".py" file which has th...
<p>You can use NumPy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.save.html" rel="nofollow">save()</a> and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.load.html" rel="nofollow">load()</a>:</p> <pre><code>import numpy as np </code></pre> <p>Save:</p> <pre><code>np.save('...
python|list|csv|numpy
2
373,977
35,531,367
In pandas, how to get 2nd mode
<p>So I'm generating a <code>summary report</code> from a <code>data set</code>. I used <code>.describe()</code> to do the heavy work but it doesn't generate everything I need i.e. the second most common thing in the data set.</p> <p>I noticed that if I use <code>.mode()</code> it returns the most common value, is the...
<pre><code>df['column'].value_counts() </code></pre> <p>What this does, according to the docs:</p> <blockquote> <p>The resulting object will be in descending order so that the first element is the most frequently-occurring element.</p> </blockquote>
python|pandas
5
373,978
35,744,140
Selecting rows by a list of values without using several ands
<p>I have a dataframe with columns <code>(a,b,c)</code>. I have a list of values <code>(x,y,z)</code> How can I select the rows containing exactly this three values, something like:</p> <pre><code>df = df[df[(a,b,c)] == (x,y,z)] </code></pre> <p>I know that</p> <pre><code>df = df[(df[a] == x) &amp; (df[b] == y) &amp...
<h1>Solution using Indexing</h1> <p>I would set the columns as the index and use the <code>.loc</code> function</p> <p>Indexing like this is the fastest way of accessing rows, while masking is very slow on larger datasets.</p> <pre><code>In [4]: df = pd.DataFrame({'a':[1,2,3,4,5], 'b':['a','b...
python|pandas
2
373,979
35,439,723
Using pandas TimeStamp with scikit-learn
<p>sklearn classifiers accept pandas' <code>TimeStamp</code> (=<code>datetime64[ns]</code>) as a column in X, as long as <em>all</em> of X columns are of that type. But when there are both <code>TimeStamp</code> and <code>float</code> columns, sklearn refuses to work with TimeStamp.</p> <p>Is there any workaround besi...
<p>You can translate it to a proper integer or float</p> <pre><code>test_df['date'] = test_df['date'].astype(int) </code></pre>
python|python-3.x|datetime|pandas|scikit-learn
0
373,980
35,689,248
Train Tensorflow model without using command line
<p>I want to call <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/embedding/word2vec_optimized.py#L408" rel="nofollow">this <code>main(_)</code> function</a> from another Python script without spawning a new process (so that it's easier to debug). However, that function is written to wor...
<p>You can import <code>FLAGS</code> and then define the required args (train_data, eval_data, save_path).</p> <pre><code>In [13]: from tensorflow.models.embedding.word2vec_optimized import FLAGS In [14]: from tensorflow.models.embedding.word2vec_optimized import main In [16]: main(_) --train_data --eval_data and --sa...
python|argparse|tensorflow|gflags
4
373,981
35,397,821
Neural Network cannot learn
<p>I am trying to implement a neural network with python and numpy. The problem is when I try to train my network the error stocks around 0.5. It cannot learn further. I tried learning rates 0.001 and 1. I guess I am doing something wrong during the back propagation. But I haven't been figured what is wrong. </p> <p>p...
<p>Here are some issues I found:</p> <ol> <li>The array slicing softmax_probs[r, y] in calculateLoss() is incorrect. This slicing produces a 10000x10000 matrix and slows down the code.</li> <li>Similarly, the slicing of delta3[r, y] in backPropagate() is incorrect.</li> <li>As of yet, I'm unsure if backprop is done co...
python|python-2.7|numpy|neural-network|softmax
0
373,982
11,460,806
Multiply a 1d array x 2d array python
<p>I have a 2d array and a 1d array and I need to multiply each element in the 1d array x each element in the 2d array columns. It's basically a matrix multiplication but numpy won't allow matrix multiplication because of the 1d array. This is because matrices are inherently 2d in numpy. How can I get around this probl...
<p>Due to the NumPy broadcasting rules, a simple</p> <pre class="lang-py prettyprint-override"><code>Result = FrMtx * elem </code></pre> <p>Will give the desired result.</p>
python|numpy
4
373,983
12,044,043
Python: py2app "ImportError: dlopen(): Library not loaded"
<p>I've written a python script that does some work with numpy and scikit's audiolab. I want to create a standalone app using py2app but I keep getting the same error no matter which OS X computer I test it on. </p> <pre><code>ImportError: dlopen(/Users/transfer15/Desktop/app/dist/PCMAlign/app/Contents/Resources/lib/p...
<p>Having encountered the same problem recently (Python 2.7, trying to import numpy version 1.11), downgrading the version of numpy cleared up the error.</p> <p>If you used pip to install numpy, you can downgrade with: <code>pip install 'numpy&lt;1.7'</code>. It is possible that a higher version may work out for you.<...
python|macos|numpy|importerror|py2app
0
373,984
11,889,537
Arithmetic Operations with Nested Lists in Python
<p>I am attempting to subtract values in a nested list (a list of historical stock price data from Yahoo finance) and I have been running into problems. I am attempting simple subtraction (i.e. high - low), but I am unable to implement this. I am probably missing something fundamental on the nature of lists, but I am...
<p>You can use a list comprehension:</p> <pre><code>from decimal import Decimal result = [(row[0], Decimal(row[2]) - Decimal(row[3])) for row in data] </code></pre>
python|numpy|python-2.7|nested-lists
3
373,985
11,679,716
Comparing DateOffsets in pandas
<p>Is there a way to compare the size of two <code>DateOffset</code> objects?</p> <pre><code>&gt;&gt;&gt; from pandas.core.datetools import * &gt;&gt;&gt; Hour(24) &gt; Minute(5) False </code></pre> <p>This works with <code>timedelta</code>, so I assumed that pandas would inherit that behavior - or is the time system...
<p>pandas DateOffsets does not inherit from timedelta. It's possible for some DateOffsets to be compared, but for offsets like MonthEnd, MonthStart, etc, the span of time to the next offset is non-uniform and depends on the starting date.</p> <p>Please feel free to start a github issue on this at <a href="https://gith...
python|datetime|pandas
1
373,986
11,800,544
Why does my python process use up so much memory?
<p>I'm working on a project that involves using python to read, process and write files that are sometimes as large as a few hundred megabytes. The program fails occasionally when I try to process some particularly large files. It does not say 'memory error', but I suspect that is the problem (in fact it gives no reaso...
<p>Just because you've deferenced your variables doesn't mean the Python process has given the allocated memory back to the system. See <a href="https://stackoverflow.com/q/1316767/3924118">How can I explicitly free memory in Python?</a>.</p> <p>If <code>gc.collect()</code> does not work for you, investigate forking a...
python|optimization|memory|numpy
15
373,987
11,686,720
Is there a numpy builtin to reject outliers from a list
<p>Is there a numpy builtin to do something like the following? That is, take a list <code>d</code> and return a list <code>filtered_d</code> with any outlying elements removed based on some assumed distribution of the points in <code>d</code>.</p> <pre><code>import numpy as np def reject_outliers(data): m = 2 ...
<p>Something important when dealing with outliers is that one should try to use estimators as robust as possible. The mean of a distribution will be biased by outliers but e.g. the median will be much less.</p> <p>Building on eumiro's answer:</p> <pre><code>def reject_outliers(data, m = 2.): d = np.abs(data - np.me...
python|numpy
219
373,988
28,765,696
How do I get a text output from a string created from an array to remain unshortened?
<p>Python/Numpy Problem. Final year Physics undergrad... I have a small piece of code that creates an array (essentially an n×n matrix) from a formula. I reshape the array to a single column of values, create a string from that, format it to remove extraneous brackets etc, then output the result to a text file saved in...
<p>Generally you should iterate over the array/list if you just want to write the contents.</p> <pre><code>zmatrix = np.reshape(matrix, (matsize*matsize, 1)) with open(completeName, &quot;w&quot;) as zbfile: # with closes your files automatically for row in zmatrix: zbfile.writelines(map(str, row)) ...
python|arrays|string|numpy|text
1
373,989
28,569,548
Point Python Launcher to Anaconda Installation
<p>I am using Python 3.4 on Windows 7.</p> <p>I would like to run a .py and .pyc file from the command line using my Anaconda python3 installation. </p> <p>I also have a default python installation which comes bundled with the "Python Launcher" per <a href="https://www.python.org/dev/peps/pep-0397/" rel="nofollow">PE...
<p>If you have created an environment through conda, you should first activate that environment before running the script.</p> <pre><code>activate envname python scriptname.py </code></pre>
python|numpy|pandas|anaconda
1
373,990
28,641,542
export pandas dataframe object to the console
<p>Is there a way to export/print/IO a pandas dataframe object to either the python console or ipython notebook output? </p> <p>It would be nice if there is some IO mechanism that lets you quickly export a dataframe object so it can be copied to the clipboard and then pasted in another window. For example, if I'm tryi...
<p>see docs here: <a href="http://pandas.pydata.org/pandas-docs/dev/io.html#io-clipboard" rel="nofollow">http://pandas.pydata.org/pandas-docs/dev/io.html#io-clipboard</a></p> <p>df.to_clipboard() exports to the clipboard. pd.read_clipboard() is the reverse.</p>
pandas|io|dataframe
1
373,991
28,744,190
Pandas ExcelFile.parse has NaNs in index when index_col is specified
<p>I have an excel file that I am reading into a pandas DataFrame that has the header on row 1 (python index) and a blank row between the header and the data. When I specify index_col it treats the blank row as part of the index as a NaN. What is the best way to avoid this behavior?</p> <p>Test file:</p> <pre><code...
<p>You can pass <code>skiprows=[1]</code> to skip the blank line, I tested this on a dummy xl sheet, see <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.ExcelFile.parse.html#pandas.ExcelFile.parse" rel="nofollow"><code>ExcelFile.parse</code></a>:</p> <pre><code>In [44]: xs = pd.ExcelFile(r'c:\da...
pandas
1
373,992
28,562,997
Refactoring a bad 'code smell' in multiplication of columns in a dataframe
<p>I've another question about efficiency. I have the following kind of multiplication:</p> <pre><code>df['Allocated'] = df['Base Days'] * df['Base (MW) Allocated'] * 24 df['Bought'] = df['Base Days'] * df['Base (MW) Bought'] * 24 df['Sold'] = df['Base Days'] * df['Base (MW) Bought'] * 24 df['Remaining'] = df['Base D...
<p>There's no inherent 'bad code smell' about this sort of thing. For example, suppose that in the future one of the columns, say <code>'Base (MW) Bought'</code> will need to be treated differently than the others. In that case, it would actually be a virtue that each different multiplication step was handled explicitl...
python|pandas
2
373,993
28,656,736
Using Scikit's LabelEncoder correctly across multiple programs
<p>The basic task that I have at hand is</p> <p>a) Read some tab separated data.</p> <p>b) Do some basic preprocessing</p> <p>c) For each categorical column use <code>LabelEncoder</code> to create a mapping. This is don somewhat like this</p> <pre><code>mapper={} #Converting Categorical Data for x in categorical_li...
<p>According to the <a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/preprocessing/label.py#L55" rel="noreferrer"><code>LabelEncoder</code></a> implementation, the pipeline you've described will work correctly if and only if you <code>fit</code> LabelEncoders at the test time with data that hav...
python|pandas|scikit-learn
60
373,994
28,585,367
Python Pandas: How I can determine the distribution of my dataset?
<p>This is my dataset with two columns of NS and count.</p> <pre><code> NS count 0 ns18.dnsdhs.com. 1494 1 ns0.relaix.net. 1835 2 ns2.techlineindia.com. 383 3 ns2.micr...
<p>From your comment, I'm guessing your data table is actually much longer, and you want to see the distribution of name server <code>counts</code> (whatever count is here).</p> <p>I think you should just be able to do this:</p> <pre><code>df.hist(column="count") </code></pre> <p>And you'll get what you want. IF tha...
python|pandas|plot|histogram
7
373,995
28,651,079
Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape
<p>I am trying to unstack a multi-index with pandas and I am keep getting:</p> <pre><code>ValueError: Index contains duplicate entries, cannot reshape </code></pre> <p>Given a dataset with four columns:</p> <ul> <li>id (string)</li> <li>date (string)</li> <li>location (string)</li> <li>value (float)</li> </ul> <p>I...
<p>Here's an example DataFrame which show this, it has duplicate values with the same index. The question is, do you want to aggregate these or keep them as multiple rows?</p> <pre><code>In [11]: df Out[11]: 0 1 2 3 0 1 2 a 16.86 1 1 2 a 17.18 2 1 4 a 17.03 3 2 5 b 17.28 In [12]: df.pivot_ta...
python|pandas
68
373,996
51,113,982
TensorFlow: How to use 'tf.data' instead of 'load_csv_without_header'?
<p>2 years ago I wrote code in TensorFlow, and as part of the data loading I used the function 'load_csv_without_header'. Now, when I'm running the code, I get the message:</p> <pre><code>WARNING:tensorflow:From C:\Users\Roi\Desktop\Code_Win_Ver\code_files\Tensor_Flow\version1\build_database_tuple.py:124: load_csv_wit...
<h2>Using <code>tf.data</code> to work with a <code>csv</code> file:</h2> <p>From TensorFlow's <a href="https://www.tensorflow.org/guide/datasets" rel="noreferrer">official documentation</a>:</p> <blockquote> <p>The tf.data module contains a collection of classes that allows you to easily load data, manipulate it, ...
python|tensorflow|deep-learning|pycharm|tensorflow-datasets
7
373,997
50,858,746
Ignore errors in pandas astype
<p>I have a numeric column that could contain another characters different form <strong>[0-9]</strong>. Say: <code>x = pandas.Series(["1","1.2", "*", "1", "**."])</code>. Then I want to <b> convert </b> that serie into a numerical column using <code>x.astype(dtype = float, errors = 'ignore')</code> . I just can't figur...
<p>I think you want to use <a href="http://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.to_numeric.html" rel="noreferrer">pd.to_numeric(x, errors='coerce')</a> instead:</p> <pre><code>In [73]: x = pd.to_numeric(x, errors='coerce') In [74]: x Out[74]: 0 1.0 1 1.2 2 NaN 3 1.0 4 NaN dtype: ...
pandas
48
373,998
50,904,496
How to use TensorFlow's WALSMatrixFactorization
<p>I'm trying to use TensorFlow's WALSMatrixFactorization estimator, but I can't figure out how to use it. The fit method takes an input_fn as argument, but what should this function return? As input, I basically have a matrix, that I want factorized with the WALS method, but I can't find out how to pass this matrix to...
<p>If you are still looking for the answer to this question check this <a href="https://github.com/GoogleCloudPlatform/training-data-analyst/blob/ahybrid_fewer_vms/courses/machine_learning/deepdive/10_recommend/wals.ipynb" rel="nofollow noreferrer">notebook</a> has a lot to offer on how to use WALSMatrixFactorization w...
tensorflow|tensorflow-estimator
0
373,999
50,967,353
Pandas custom functions in returning column values
<p>Please help me out in writing pandas custom functions, in the confusion loop in returning specific row and col values as custom results,i want to return col means without using slicing no user defined functions like numpy(np.mean) and i need only parameter to pass is dataset 'df' to custom function. In layman way i...
<p>Instead of using <code>range(df.shape[1])</code> use <code>enumerate(df.columns)</code>, so you keep both name and position:</p> <pre><code>df = pd.DataFrame({'A': [10,20,30], 'B': [20, 30, 10]}) def col_men(df): means=[0 for i in range(df.shape[1])] for index, k in enumerate(df.columns): col_values...
python|pandas|dataframe
1