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
4,300
59,579,316
Can I use a str in np.mean()?
<pre><code>stdev = 3 value_1 = array value_2 = array value_3 = array for h in range(1,4): name = ('value' + str(h)) globals()['new_name_'+ str(h)] = np.mean(name) * stdev </code></pre> <p>It should give something like this: </p> <pre><code>new_name_1 = #result1 new_name_2 = #result2 new...
<p>you can use a list to keep your arrays:</p> <pre><code>stdev = 3 my_list = [array_1, array_2, array_3] new_vars = [] for arr in my_list: new_vars.append(np.mean(arr) * stdev) </code></pre> <p>also, you can keep your variables using a dict:</p> <pre><code>stdev = 3 my_dict = { 'value_1': array_1, ...
python|string|numpy|for-loop|global-scope
0
4,301
59,887,851
"Error while extracting" from tensorflow datasets
<p>I want to train a tensorflow image segmentation model on COCO, and thought I would leverage the dataset builder already included. Download seems to be completed but <strong>it crashes on extracting the zip files.</strong></p> <p>Running with TF 2.0.0 on a Jupyter Notebook under a conda environment. Computer is 64-b...
<p>I have a similar problem with Windows 10 &amp; COCO 2017. My solution is simple. Extract the ZIP file manually according to the folder path in the error message.</p>
python|tensorflow|image-segmentation|tensorflow-datasets|mscoco
2
4,302
40,441,631
Get average counts per minute by hour
<p>I have a dataframe with a time stamp as the index and a column of labels</p> <pre><code>df=DataFrame({'time':[ datetime(2015,11,2,4,41,10), datetime(2015,11,2,4,41,39), datetime(2015,11,2,4,41,47), datetime(2015,11,2,4,41,59), datetime(2015,11,2,4,42,4), datetime(2015,11,2,4,42,11), datetime(2015,11,2,4,42...
<p>Start by squeezing you DataFrame into a Series (after all, it only has one column):</p> <pre><code>s = df.squeeze() </code></pre> <p>Compute how many times each label occurs by minute:</p> <pre><code>counts_by_min = (s.resample('min') .apply(lambda x: x.value_counts()) .unstack...
python|pandas|group-by
1
4,303
40,432,081
Check if numpy array is masked or not
<p>Is there an easy way to check if numpy array is masked or not? </p> <p>Currently, I do the following to check if <code>marr</code> is masked or not:</p> <pre><code>try: arr = marr.data except: arr = marr </code></pre>
<p>You can use the python function <code>isinstance</code> to check if an object is an instance of a class.</p> <pre><code>&gt;&gt;&gt; isinstance(np.ma.array(np.arange(10)),np.ma.MaskedArray) True &gt;&gt;&gt; isinstance(np.arange(10),np.ma.MaskedArray) False </code></pre>
python|numpy
9
4,304
40,663,543
theory behind array manipulation
<p>I'm about to be asked to implement an array manipulation functionality somewhat akin to numpy (largish homogeneous arrays used to manipulate unpacked sequences of images and whatever our customers may derive from those images) for in-house scripting language. Naturally I'd like to limit it to the smallest amount of ...
<p>Travis Oliphant's 2006 book might be a good start.</p> <pre><code>Guide to NumPy - Complexity Sciences Center </code></pre> <p><a href="https://www.google.com/url?sa=t&amp;source=web&amp;rct=j&amp;url=http://csc.ucdavis.edu/~chaos/courses/nlp/Software/NumPyBook.pdf&amp;ved=0ahUKEwjzlrv67bDQAhVUzWMKHV-tDToQFggjMAE&...
arrays|numpy
1
4,305
40,572,910
Most efficient method to combine pandas DataFrames which have the same column value
<p>For example, I have two dataframe which contain some identical sample name with different feature data. </p> <p>I want to compare how many samples existed in both dataframe. </p> <h3>data here</h3> <p><a href="https://drive.google.com/file/d/0B7FE0kxAL8kQQlRFSmR6Q1RoNXM/view?usp=sharing" rel="nofollow noreferrer...
<p>Here's a vectorized approach using <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>NumPy broadcasting</code></a> to get <code>hit</code> value -</p> <pre><code>np.count_nonzero(df1.Sample_name.values[:,None] == df2.Sample_name.values) </code></pre>
python|performance|python-2.7|pandas|join
2
4,306
18,241,359
"Error: setting an array element with a sequence"
<p>I am trying to convert Matlab code into Python, but I'm receiving an error when I append zeros in my array.</p> <p>Matlab Code:</p> <pre><code>N_bits=1e5; a1=[0,1]; bits=a1(ceil(length(a1)*rand(1,N_bits))); bits=[0 0 0 0 0 0 0 0 bits]; </code></pre> <p>Python Code:</p> <pre><code>a1=array([0,0,1]) N_bits=1e2 a2=...
<p>You want to join the list with the array, so try</p> <pre><code>bits=concatenate(([0,0,0,0,0,0,0,0], bits)) </code></pre> <p>where <code>concatenate()</code> is <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html#numpy.concatenate" rel="nofollow noreferrer"><code>numpy.concatenate()...
python|matlab|numpy
5
4,307
61,693,747
How to specify dt.week to use north american week number in dataframe pandas?
<p>How can I specify dt.week to use north american week number?</p> <p><em>2019 Calendar:</em></p> <p><a href="https://i.stack.imgur.com/Ye5to.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ye5to.png" alt="enter image description here"></a></p> <p>For example: <strong>Date -> 01.01.2020 is Week 1...
<p>You can do this:</p> <pre><code>df['Date'] = pd.to_datetime(df['Date']) df['Week'] = df['Date'].dt.strftime('%U').astype(np.int) + 1 </code></pre> <p><strong>Output</strong>:</p> <pre><code> SENDER_NAME Induction Date InductionPlant Week 0 0 b'XXXXXXXXXXXX' 2020-01-03 b'XXXXXXXXXX' ...
python|pandas|dataframe
1
4,308
61,900,343
Python np.logical_and operands could not be broadcast together with shapes
<p>I have <code>Y_1</code> and <code>X_1</code> as a matrix of (506,1) as shape, both. I'd like to know the Y_1 values when X_1 values are greater than 5 and less than 6. Just like this.</p> <pre><code>np.logical_and(Y_1[X_1 &gt; 5], Y_1[X_1 &lt; 6]) </code></pre> <p>But I got this error.</p> <blockquote> <p>Value...
<p>You are using the logical and in a wrong way here. The arguments you are passing here, namely, Y_1[X_1>5] and Y_1[X_1&lt;6] have different shapes as given in the error. Their shapes have to be same. There are 490 elements in X_1 greater than 5 and 173 elements less than 6.</p> <p>It should be like np.logical_and(X_...
python|numpy
0
4,309
61,780,569
How many addition operations are being performed by np.sum()?
<p>Lets consider I have an array of shape <code>(1, 3, 4, 4)</code> and I apply <code>numpy.sum()</code> on this and reduce against <code>axes [2,3]</code>. Below is a sample code --</p> <pre><code>import numpy as np data = np.random.rand(1, 3, 4, 4) res = np.sum(data, axis=(2,3), keepdims=True) </code></pre> <p>How...
<pre><code>In [202]: data = np.arange(3*4*4).reshape(1,3,4,4) </code></pre> <p>do your sum:</p> <pre><code>In [203]: res = np.sum(data, axis=(2,3), keepdims=True) In [204]: res ...
python|numpy
1
4,310
61,653,697
Pandas str.replace() with regex
<p>Say I have this dataframe:</p> <pre><code>df = pd.DataFrame({'Col': ['DDJFHGBC', 'AWDGUYABC']}) </code></pre> <p>And I want to replace everything ending with <code>ABC</code> with <code>ABC</code> and everything ending with <code>BC</code> (except the <code>ABC</code>-cases) with <code>BC</code>. The output would ...
<p>You could match as least word chars using <code>\w*?</code> and then capture in group 1 matching an optional A followed by BC <code>(A?BC)</code> followed by a word boundary.</p> <pre><code>\w*?(A?BC)\b </code></pre> <p><a href="https://regex101.com/r/2EaKua/1" rel="nofollow noreferrer">Regex demo</a></p> <p>In t...
python|regex|string|pandas
3
4,311
61,838,277
Faster Outer-Product-Like find closest lat long with function pandas
<p>I have a pandas dataframe A, with latitude longitudes.</p> <pre><code>import pandas as pd df_a = pd.DataFrame([['b',1.591797,103.857887], ['c',1.589416, 103.865322]], columns = ['place','lat','lng']) </code></pre> <p>I have another dataframe of locations B, also with latitude long...
<p>Using an approach from <a href="https://stackoverflow.com/questions/10549402/kdtree-for-longitude-latitude">KDTree for longitude/latitude</a></p> <p>Based upon <a href="https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.BallTree.html" rel="nofollow noreferrer">sklearn.balltree</a></p> <p><strong>C...
python|pandas
1
4,312
57,982,376
Pytorch tensor multiplication with Float tensor giving wrong answer
<p>I am seeing some strange behavior when i multiply two pytorch tensors.</p> <pre class="lang-py prettyprint-override"><code>x = torch.tensor([99397544.0]) y = torch.tensor([0.1]) x * y </code></pre> <p>This outputs </p> <pre><code>tensor([9939755.]) </code></pre> <p>However, the answer should be <code>9939754.4</...
<p>In default, the tensor dtype is <code>torch.float32</code> in pytorch. Change it to <code>torch.float64</code> will give the right result. </p> <pre class="lang-py prettyprint-override"><code>x = torch.tensor([99397544.0], dtype=torch.float64) y = torch.tensor([0.1], dtype=torch.float64) x * y # tensor([9939754.400...
pytorch
2
4,313
58,095,242
Numpy: Understanding Array to the power of Array
<p>I was reviewing operators with numpy arrays and I found something I did not expect and that I do not know how to interpret.</p> <p>The operation I am performing is an array A to the power of an array B, clearly with A and B having the same shape. The behaviour I am expecting is 'element-wise power': each element of...
<p><code>dtype=int32</code> you're overflowing integers and looping back:</p> <pre><code>1099511627776 % (2**32) == 0 298023223876953125 % (2**32) == 167814181 ... </code></pre>
python|arrays|numpy|matrix
1
4,314
58,089,395
Usage of str.contains() applied to pandas data frame
<p>I am new to Python and Jupyter Notebook and I am currently following this tutorial: <a href="https://www.dataquest.io/blog/jupyter-notebook-tutorial/" rel="nofollow noreferrer">https://www.dataquest.io/blog/jupyter-notebook-tutorial/</a>. So far I've imported the pandas library and a couple other things, and I've ma...
<p>The expression <code>[^0-9.-]</code> is a so-called <em>regular expression</em>, which is a special text string for describing a search pattern. With regular expressions (or in short '<em>RegEx</em>') you can extract specific parts of a string. For example, you can extract <code>foo</code> from the string <code>123f...
python|string|pandas|jupyter
3
4,315
58,152,368
Graph a multi index dataframe in pandas
<p>I have a multi indexed file with values such as these</p> <p><a href="https://i.stack.imgur.com/5OjXc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5OjXc.png" alt=""></a></p> <p>How could I plot a dataframe that has separate lines for each symbol in the same graph?</p>
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot.html" rel="nofollow noreferrer"><code>pivot</code></a> for all unique <code>symbol</code> values :</p> <pre><code>df1 = df.pivot(index='4.timestamp', columns='1.symbol', values='2.price') </code></pre> <p>If possible...
python|pandas
1
4,316
57,886,871
Variables are same for all Epochs
<p>I am experimenting the image classifier using CNN with keras</p> <p>My code -</p> <pre><code>model = Sequential() model.add(Conv2D(32, (3, 3), padding='same', input_shape=(224, 224, 3), activation="relu")) model.add(Conv2D(32, (3, 3), padding='same', activation="relu")) model.add(MaxPooling2D(pool_size=(2, 2))) ...
<p>Try changing this</p> <pre><code>model.compile(loss = "categorical_crossentropy", optimizer = "rmsprop") </code></pre> <p>to </p> <pre><code>model.compile(loss = "categorical_crossentropy", optimizer = 'adam') </code></pre>
python|tensorflow|keras|neural-network|conv-neural-network
1
4,317
34,178,751
Extract unique values and number of occurrences of each value from dataframe column
<p>I'm trying to extract the number of each unique entry from one dataframe column and store it as a new dataframe, something like this:</p> <p><strong>Input</strong></p> <pre><code>sample_name sample1 sample2 sample2 sample3 sample3 sample3 </code></pre> <p><strong>Desired output</strong></p...
<p>You want <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="noreferrer"><code>value_counts</code></a>:</p> <pre><code>In [142]: df['sample_name'].value_counts() Out[142]: sample3 3 sample2 2 sample1 1 Name: sample_name, dtype: int64 </code></pr...
python|pandas
5
4,318
37,091,953
array manipulation from MATLAB to Python
<p>from MATLAB code:</p> <pre><code>a = rand(1,120); d=zeros(1,124); state=[1:120]; fibre = [1 5 9 13 17 2 6 10 14 18 3 7 11 15 19 4 8 12 16 20 21 69 65 61 57 22 68 64 60 56 71 67 63 59 55 70 66 62 58 54 53 49 45 41 37 52 48 44 40 36 51 47 43 39 ...
<p>Your python script has two problem regarding to Matlab code: In the second line you should generate random numbers such as:</p> <pre><code>a = np.random.rand(120) </code></pre> <p>and in the last line, like in comments said, you should know indexing in Matlab starts with 1 and python starts with 0, so your last li...
python|arrays|matlab|numpy
1
4,319
55,098,643
list augmentation in python with numpy or other library
<p>I would like to augment list from</p> <pre><code>[1, 2, 3, 4, 5] </code></pre> <p>to</p> <pre><code>[1, 1, 2, 2, 3, 3, 4, 4, 5, 5] </code></pre> <p>If I want to augment likewise n times (like 100 or 500 times), how can I do it? I do not want to do it with regular loop, but using some library like numpy. Any help...
<p>You can do this with numpy's <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow noreferrer"><code>np.repeat</code></a>:</p> <pre><code>import numpy as np a = np.array([1, 2, 3, 4, 5]) np.repeat(a,2) # array([1, 1, 2, 2, 3, 3, 4, 4, 5, 5]) </code></pre>
python|list|numpy|data-augmentation
2
4,320
49,626,150
Python list-dictionary algorithm with big data
<p>I'm trying to make a program using two python dictionaries. 'multiple dic1 and dic2 value if dic1 and dic2 key is common, otherwize 0' the key order and the length of the output list is the same as those of dic1.</p> <pre><code>dic1 = {'foo': 100,'bar': 200,'baz': 300,'qux': 400,'quux': 500} dic2 = {'foo': 1,'quux'...
<p>Hmm, I don't think there is much you can do. Where is this data coming from? If it's a csv or something then a <code>pandas</code> solution would probably be quicker. If they must be <code>dict</code>s then I think the best thing I can think of is to change it to a comprehension</p> <pre><code>output = [v * dic2[k]...
python|python-3.x|list|numpy|python-3.6
4
4,321
73,189,955
Serializing complex object containing multiple nested objects with data frames
<p>Below should be a runnable sample of code. i have a Chart1 object which can contain many panes, and each pane can can contain many series. I would like to serialize this to json so i can send to a flask application to render. To do deal with the dataframes, i am using a custom encoder (ChartEncoder below):</p> <...
<p>For starters, the JSON that is emitted is perfectly parsble by Javascript <code>JSON.load</code>, the issue is that your <code>default</code> implementation returns a <code>str</code> object, so that gets serialized as a JSON <code>str</code>.</p> <p>You probably want to use <code>to_dict</code> (which returns a <co...
python|json|pandas
1
4,322
35,212,271
Numpy create two arrays using fromiter simultaneously
<p>I have an iterator that looks something like the following</p> <pre><code>it = ((x, x**2) for x in range(20)) </code></pre> <p>and what I want is two arrays. one of the <code>x</code>s and the other of the <code>x**2</code>s but I don't actually know the number of elements, and I can't convert from one entry to th...
<p>You could use <code>np.fromiter</code> to build one array with all the values, and then slice the array:</p> <pre><code>In [103]: it = ((x, x**2) for x in range(20)) In [104]: import itertools In [105]: y = np.fromiter(itertools.chain.from_iterable(it), dtype=float) In [106]: y Out[106]: array([ 0., 0., ...
python|arrays|numpy
2
4,323
59,920,461
Python 3.8.1: ModuleNotFoundError: No module named '_pywrap_tensorflow_internal' - Is tensorflow only supported up to 3.7?
<p>I am using Python 3.8.1 on Windows 10 and am trying to install TensorFlow. </p> <p>I have tried many methods to install it, but I keep getting the following error upon importing TensorFlow. This time, I installed it using</p> <pre><code>conda install -c conda-forge tensorflow </code></pre> <p>Here is the stack tr...
<p>Per the installation documents, only Python 3.5-3.7 are supported. <a href="https://www.tensorflow.org/install" rel="nofollow noreferrer">https://www.tensorflow.org/install</a></p>
python-3.x|tensorflow|anaconda|conda
0
4,324
60,087,418
Iterate over pandas dataframe and apply condition
<p>Consider I have this dataframe, wherein I want to remove toy as a topic from the topics column and if there is row with a single topic as a toy , remove that row. How can we do that in pandas?</p> <pre><code>+---+-----------------------------------+-------------------------+ | | Comment ...
<p>Try using <code>str.replace</code> with <code>str.rstrip</code> and <code>ne</code> inside <code>[...]</code>:</p> <pre><code>df['topic'] = df['topic'].str.replace('toy', ' ').str.replace(' , ', '').str.rstrip() print(df[df['topic'].ne('')]) </code></pre>
python|pandas
1
4,325
59,971,737
Numpy Gaussian from /dev/urandom
<p>I have an application where I need <code>numpy.random.normal</code> but from a crypgoraphic PRNG source. Numpy doesn't seem to provide this option.</p> <p>The best I could find was <code>numpy.random.entropy.random_entropy</code> but this is only uint32 and it's buggy, with large arrays you get "RuntimeError: Unabl...
<p>I came across <code>scipy.stats.rvs_ratio_uniforms</code> and adapted their code for my purpose. It's only 3 times slower than <code>np.random.normal</code> despite sampling twice the randomness from a cryptographic source.</p> <pre><code>import numpy as np import os def uniform_0_1(size): return np.frombuffe...
python|numpy|random|gaussian|normal-distribution
1
4,326
50,020,683
which one is effecient, join queries using sql, or merge queries using pandas?
<p>I want to use data from multiple tables in a <code>pandas dataframe</code>. I have 2 idea for downloading data from the server, one way is to use <code>SQL</code> join and retrieve data and one way is to download dataframes separately and merge them using pandas.merge.</p> <h1>SQL Join</h1> <p>when I want to down...
<p>To really know which is faster, you need to try out the two queries using your data on your databases.</p> <p>The rule of thumb is to do the logic in a single query. Databases are designed for queries. They have sophisticated algorithms, multiple processors, and lots of memory to handle them. So, relying on the ...
python|sql|postgresql|pandas
3
4,327
64,080,487
How to groupby, aggregate and plot a bar plot?
<p>I used this code from starting</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('odi.csv') df=pd.DataFrame(dataset) </code></pre> <p>I am using dataset and then i groupby in a column by country and then i took average run scored by each country. I used this ...
<ul> <li><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer"><code>pandas.read_csv</code></a> creates a DataFrame, so it's not correct to create <code>dataset</code>, and then <code>df = pd.DataFrame(dataset)</code></li> <li><a href="https://pandas.pydata....
python|pandas|matplotlib|bar-chart
1
4,328
64,099,194
AttributeError: 'Concatenate' object has no attribute 'shape'
<p>I'm trying to do some image segmentation in tensorflow, here is my model :</p> <pre><code>inputs = Input((IMAGE_HEIGHT, IMAGE_WIDTH, 3)) s = Lambda(lambda x: x / 255) (inputs) conv1 = Conv2D(16, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (inputs) conv1 = BatchNormalization() (conv1) c...
<p>Try to use:</p> <pre><code>upsample7 = Concatenate()([upsample7, conv3]) </code></pre> <p>and update each upsample and where you use the Concatenate function.</p> <p>Note the <code>()</code> in Concatenate ^^</p>
python|tensorflow|keras|tensorflow2.0
3
4,329
64,002,915
While running tensorboard command and i am getting error?
<p><code>!tensorboard --logdir=drive/My Drive/Proj/fer/checkpoint/logs/</code></p> <p>**i am running this command in google colab **</p> <p><a href="https://i.stack.imgur.com/ZQhgw.png" rel="nofollow noreferrer">getting this error</a></p>
<p>You get this error because of the empty space in 'My Drive'. So you need to escape the whitespace or rename it:</p> <pre><code>!tensorboard --logdir=drive/My\ Drive/Proj/fer/checkpoint/logs/ </code></pre>
python|tensorflow|tensorboard
0
4,330
64,020,403
Pandas multiply selected columns by previous column
<p>Assume I have a 3 x 9 Dataframe with index from 0 - 2 and columns from 0 - 8</p> <pre><code>nums = np.arange(1, 28) arr = np.array(nums) arr = arr.reshape((3, 9)) df = pd.DataFrame(arr) </code></pre> <p>I want to multiply selected columns (example [2, 5, 7]) by the columns behind them (example [1, 4, 6]) My obstacle...
<p>Let's try working with the numpy array:</p> <pre><code>cols = np.array([2,5,7]) df[cols] *= df[cols-1].values </code></pre> <p>Output:</p> <pre><code> 0 1 2 3 4 5 6 7 8 0 1 2 6 4 5 30 7 56 9 1 10 11 132 13 14 210 16 272 18 2 19 20 420 22 23 552 25 650 27 </...
python|pandas
3
4,331
63,902,183
How do I plot a beautiful scatter plot with linear regression?
<p>I want to make a beautiful <code>scatter plot</code> with <code>linear regression</code> line using the data given below. I was able to create a scatter plot but am not satisfied with how it looks. Additionally, I want to plot a <code>linear regression</code> line on the data.</p> <p>My data and code are below:</p> ...
<p>Please check the snippet. You can use <code>numpy.polyfit()</code> with degree=1 to calculate slope and y-intercept of line to <code>y=m*x+c</code> <a href="https://i.stack.imgur.com/TZBA3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TZBA3.png" alt="graph" /></a></p> <pre><code>import numpy as ...
python|pandas|matplotlib|seaborn|python-ggplot
3
4,332
64,102,826
Efficient method comparing 2 different tables columns
<p><img src="https://i.stack.imgur.com/Lopgz.png" alt="Example_List" /></p> <p>Hi all guys,</p> <p>I have got 2 dfs and I need to check if the values from the first are matching on the second, only for a specific column on each, and save the values matching in a new list. This is what I did but it is taking quite a lot...
<p>Let's create both dataframes:</p> <pre><code>df1 = pd.DataFrame({ 'Building_Name': ['Exces', 'Excs', 'Exec', 'Executer', 'Executor'] }) df2 = pd.DataFrame({ 'Source_String': ['Executer', 'Executor', 'Executor Of', 'Executor For', 'Exeutor'] }) </code></pre> <p>Perform inner merge between dataframes and conv...
python|python-3.x|pandas|list|string-matching
0
4,333
47,040,238
Cleanest way to bin using Pandas.cut
<p>The purpose of this post is discussion primarily, so even loose ideas or strings to pull would be appreciated. I'm trying to bin some data for analysis, and was wondering what is the cleanest way to bin my data using <code>Pandas.cut</code>. For some context, I'm specifically trying to bin ICD-9 diagnostic data into...
<p>I would simply write a small helper function. Here's one idea:</p> <pre><code>import pandas as pd def bin_helper(code_dict): break_points = [0] + sorted(code_dict) #0 added for lower bound on binning labels = [code_dict[value] for value in sorted(code_dict)] return break_points, labels # Setting up so...
python|pandas|icd
2
4,334
46,693,557
Finding closest point in array - inverse of KDTree
<p>I have a very large ndarray A, and a sorted list of points k (a small list, about 30 points).</p> <p>For every element of A, I want to determine the closest element in the list of points k, together with the index. So something like:</p> <pre><code>&gt;&gt;&gt; A = np.asarray([3, 4, 5, 6]) &gt;&gt;&gt; k = np.asar...
<p>Update:</p> <p>The builtin function <a href="https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.digitize.html" rel="nofollow noreferrer"><code>numpy.digitize</code></a> can actually do exactly what you need. Only a small trick is required: <code>digitize</code> assigns values to <em>bins</em>. We can...
python|arrays|algorithm|numpy|scipy
2
4,335
32,816,410
Parallelize loop over numpy rows
<p>I need to apply the same function onto every row in a numpy array and store the result again in a numpy array.</p> <pre><code># states will contain results of function applied to a row in array states = np.empty_like(array) for i, ar in enumerate(array): states[i] = function(ar, *args) # do some other stuff o...
<h3>Dask solution</h3> <p>You could do with with dask.array by chunking the array by row, calling <code>map_blocks</code>, then computing the result</p> <pre><code>ar = ... x = da.from_array(ar, chunks=(1, arr.shape[1])) x.map_blocks(function, *args) states = x.compute() </code></pre> <p>By default this will use thr...
python|numpy|dask
6
4,336
38,657,341
Pandas: groupby by date and transform nunique returning too many entries
<p>I am trying to do a simple group-by in Pandas and it is not working as it should:</p> <pre><code>url='https://raw.githubusercontent.com/108michael/ms_thesis/master/raw_bills' bills=pd.read_csv(url) bills.date.nunique() 11 bills.dtypes date float64 bills object id.thomas int64 dtype: object ...
<p>I'm not sure what you're asking, but don't you want to use:</p> <pre><code>bills[['date', 'bills']].groupby('date').bills.nunique() date 2005.0 6820 2006.0 3738 2007.0 7454 2008.0 3627 2009.0 7324 2010.0 3297 2011.0 5787 2012.0 4647 2013.0 5694 2014.0 3211 2015.0 5 Name: bills, ...
python|pandas|group-by
2
4,337
38,588,668
Why is prediction not plotted?
<p>Here is my code in Python 3:</p> <pre><code>from sklearn import linear_model import numpy as np obj = linear_model.LinearRegression() allc = np.array([[0,0],[1,1],[2,2],[3,3],[4,4],[5,5],[6,6]]) X=allc[:,0] X=X.reshape(-1, 1) Y=X.reshape(X.shape[0],-1) obj.fit(X, Y) print(obj.predict(7)) import matplotlib.pyplot as...
<p>The plot method is taking an array for the X-axis and an array for the Y-axis, and draws a <strong>line</strong> according to those arrays. You tried to draw a <strong>point</strong> using a method for <strong>lines</strong>...<br></p> <p>For your code to work (I have tested it and it worked) switch this line:</p> ...
python|python-3.x|numpy|matplotlib|linear-regression
0
4,338
63,296,247
print column values of one dataframe based on the column values of another dataframe
<p><img src="https://i.stack.imgur.com/U32iE.png" alt="enter image description here" /> <img src="https://i.stack.imgur.com/VWHgj.png" alt="enter image description here" /></p> <p>So here is my first dataframe df1. In the columns, Starting DOY and Ending DOY, for example, 3.0 and 6.0, I want to print column values By, ...
<p>Here is a simple tutorial how you can do it:</p> <pre><code>from pandas import DataFrame if __name__ == '__main__': data1 = {'Starting DOY': [3.0, 3.0, 13.0], 'Ending DOY': [6.0, 6.0, 15.0]} data2 = {'YEAR': [1975, 1975, 1975], 'DOY': [1.0, 3.0, 6.0], 'HR': [0, 1, 2],...
python|pandas|numpy|matplotlib|math
0
4,339
63,107,329
Generation of 3-D array
<p>I want to generate a 3-D array by assigning an array to an array.<br/> Following are codes written by me.<br/></p> <pre><code>import numpy as np def func01(a): b = np.array([[a, 3], [4, 5]]) return b a = np.array([1, 2]) b = func01(a) print(b) </code></pre>...
<pre><code>In [210]: res = np.zeros((2,2,2),int) In [211]: res[:] = np.array([[0,3],[4,5]]) In [212]: res Out...
python|arrays|numpy|scipy
1
4,340
68,017,780
Stack rows over two columns
<p>i want to stack the rows with the same ID and OP Date in one row toghether.</p> <p>Source:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>OP Date</th> <th>OP Code</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>01.01.2021</td> <td>X1</td> </tr> <tr> <td>1</td> <td>01.01.2021...
<p>You can parse it:</p> <pre><code>import pandas as pd from collections import defaultdict data=[{&quot;id&quot;: 1, &quot;OP Date&quot;: &quot;01.01.2021&quot;, &quot;OP Code&quot;: &quot;X1&quot;}, {&quot;id&quot;: 1, &quot;OP Date&quot;: &quot;01.01.2021&quot;, &quot;OP Code&quot;: &quot;X2&quot;}] parsed_op...
python|pandas
0
4,341
67,645,828
Passing arguments to extended keras.model without init
<p><a href="/questions/tagged/keras" class="post-tag" title="show questions tagged &#39;keras&#39;" rel="tag">keras</a> documentation provides an <a href="https://keras.io/guides/customizing_what_happens_in_fit/" rel="nofollow noreferrer">example</a> of extending the <a href="/questions/tagged/keras" class="post-tag" t...
<p>The CustomModel example allows one to override specific methods of the Model class (<code>train_step</code>) in the example. When you call</p> <pre><code>model = CustomModel(inputs, outputs) </code></pre> <p>inputs is a tensor or list of input tensors to the custom model and outputs the output tensor(s).</p> <p>You...
python|tensorflow|keras
0
4,342
67,704,886
pytorch : retain_graph=True error even though i add this
<p>I keep getting this error <strong>&quot;Trying to backward through the graph a second time, but the saved intermediate results have already been freed. Specify retain_graph=True when calling .backward() or autograd.grad() the first time.&quot;</strong></p> <p>in the beginning, it was without retain_graph=True and th...
<p>Basically you can only call <code>optimizer.step()</code> after these three lines.</p> <pre><code> output = net2(inputs) loss = criterion(outputs, labels) loss.backward() </code></pre> <p>I don't know the rest of your code so I can only guess.</p> <p>But I think you didn't have <code>net(input...
python|machine-learning|pytorch
0
4,343
41,429,956
Python: Create a model for reports (using pandas)
<p>This is more of a model design question with python.</p> <p>I need to parse and extract data from several log files into a pandas DataFrames. From these dataframes I need to create reports (as csv, excel and so on).</p> <p>One way of design such is to create a file with 2 functions: 1. function to extract data fro...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.nlargest.html" rel="nofollow noreferrer"><code>SeriesGroupBy.nlargest</code></a>:</p> <pre><code>df = names.groupby(['year', 'sex'])['births'].nlargest(1000) </code></pre> <p>Sample:</p> <pre><code>names = pd...
python|pandas
2
4,344
61,412,939
Python Tensorflow-GPU: "Successfully opened dynamic libraray cudart64_101.dll"
<p>I am currently just trying to get tensorflow-gpu to work on my PC. When I run my script, consisting only of:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow print("Test") </code></pre> <p>... then I get the output:</p> <pre><code>2020-04-24 18:16:53.660911: I tensorflow/stream_executor/platf...
<p>I have the same problem , that's the only solution works with me:</p> <ol> <li><p>check the folder path <code>C:\Users\user\Anaconda3\Lib\site-packages</code> . if any folder begins with <code>~</code>, delete it.</p> </li> <li><p>in the anaconda prompt run the following commands :</p> <pre class="lang-sh prettyprin...
python|tensorflow
0
4,345
61,537,916
Map column birthdates in python pandas df to astrology signs
<p>I have a dataframe with a column that includes individuals' birthdays. I would like to map that column to the individuals' astrology sign using code I found (below). I am having trouble writing the code to creat the variables. </p> <p>My current dataframe looks like this</p> <pre><code> birthdate answer YEAR...
<p>Change previous answer by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.month_name.html" rel="nofollow noreferrer"><code>Series.dt.month_name</code></a> with lowercase strings:</p> <pre><code>def zodiac_sign(day, month): # checks month and date within the valid range ...
python|pandas
1
4,346
61,472,491
For Loop and The truth value of a Series is ambiguous
<p>Looked through the answers to similar queries here but still unsure. Code below produces:</p> <pre><code> for i in range(len(df)): if df[0]['SubconPartNumber1'].str.isdigit() == False : df['SubconPartNumber1'] = df['SubconPartNumber1'].str.replace(',', '/', regex = True) ...
<p>In pandas you can <a href="https://stackoverflow.com/a/55557758/2901002">avoid loops</a> if possible. Your solution should be replace by <code>boolean mask</code> with <code>~</code> for invert instead <code>== False</code> and passed to <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataF...
python|pandas|series|valueerror
2
4,347
61,233,759
Find value close to number in python array and index it
<p>This is the code I have so far:</p> <pre><code>import numpy as np #make amplitude and sample arrays amplitude=[0,1,2,3, 5.5, 6,5,2,2, 4, 2,3,1,6.5,5,7,1,2,2,3,8,4,9,2,3,4,8,4,9,3] #print(amplitude) #split arrays up into a line for each sample traceno=5 #number of traces in file samplesno=6 ...
<p>IIUC, you could do the following:</p> <pre><code># find the indices of the min absolute difference indices = np.argmin(np.abs(amplitude_split - amp_90[:, None]), axis=1) # get the values at those positions result = amplitude_split[np.arange(5), indices] print(result) </code></pre>
python|arrays|numpy
1
4,348
61,239,125
Join Dataframes by column and create new columns by value Pandas Python
<p>I have 2 dataframes df1 and df2, I'm trying to merge then by column (product). </p> <pre><code>df1 product name Exist 0 1 foo False 1 2 bar True 2 3 lorem False 3 4 ipsum False . . df2 product date_search sold 0 1 2020-04-10 10 1 1 2020-04-...
<p>@Quang Hoang nailed it -- just do this:</p> <pre><code>import pandas as pd dict1 = {"product" : [1,2,3,4], "name" : ['foo','bar','lorem','ipsum'], "exists": ['false','true','false','false']} dict2 = {"product" : [1,1,2,2,3,3,4,4], "date": ['2020-01-01','2020-01-02','2020-01-01','2020-01-02','2020-01-01','2020-01-0...
python|pandas|dataframe|join|merge
0
4,349
61,370,108
tf.data: Parallelize loading step
<p>I have a data input pipeline that has:</p> <ul> <li>input datapoints of types that are not castable to a <code>tf.Tensor</code> (dicts and whatnot)</li> <li>preprocessing functions that could not understand tensorflow types and need to work with those datapoints; some of which do data augmentation on the fly</li> <...
<p>You can try to add <code>batch()</code> before <code>map()</code> in your input pipeline.</p> <p>It is usually meant to reduce the overhead of the map function call for small map function, see here: <a href="https://www.tensorflow.org/guide/data_performance#vectorizing_mapping" rel="nofollow noreferrer">https://www...
python|tensorflow|tensorflow2.0|tensorflow-datasets
2
4,350
61,211,861
Why my autoencoder model is not learning?
<p>I'm trying to solve captcha dataset using autoencoder. The <a href="https://www.kaggle.com/fournierp/captcha-version-2-images" rel="nofollow noreferrer">dataset</a> is RGB images.</p> <p>I converted the RGB images to one channel, i.e.:</p> <p><a href="https://i.stack.imgur.com/1DXbH.png" rel="nofollow noreferrer">...
<ol> <li>Your architecture doesn't have any sense. If you want to create an autoencoder you need to understand that you're going to reverse process after encoding. That means that if you have three convolutional layers with filters in this order: 64, 32, 16; You should make the next group of convolutional layers to do ...
keras|conv-neural-network|tensorflow2.0|autoencoder
1
4,351
68,505,527
Pandas Sales Analysis Help - ValueError: could not convert string to float: ''
<p>I'm currently running a sales analysis on an excel file with roughly 500 transactions. I have a category called &quot;Sale Price&quot; which should be read in as a float. Pandas read in the dtype as an object, and when trying to change the dtype to a float using:</p> <pre><code>df['Sale Price'].fillna(0).astype(floa...
<p>You could replace your empty strings with 0 before changing it to float:</p> <pre><code>df[&quot;Sale Price&quot;] = df[&quot;Sale Price&quot;].astype(str).str.strip().replace(&quot;&quot;,0).astype(float) </code></pre>
python|pandas
1
4,352
53,300,337
variable_scope does not get reused when using default scope name
<p>I have a question regarding sub-scopes when reusing variables. This</p> <pre><code>import tensorflow as tf def make_bar(): with tf.variable_scope('bar'): tf.get_variable('baz', ()) with tf.variable_scope('foo') as scope: make_bar() scope.reuse_variables() make_bar() </code></pre> <p>works perfectly ...
<p>You're not actually using the scope 'foo' in your example. You need to pass the parameter to <code>tf.variable_scope('foo', 'bar')</code> or <code>tf.variable_scope(scope, 'bar')</code>. you're calling the method <code>make_bar</code> without the parameter in either case, which means in your first example <code>name...
python|tensorflow
4
4,353
52,922,647
Rotate covariance matrix
<p>I am generating 3D gaussian point clouds. I'm using the scipy.stats.multivariate.normal() function, which takes a mean value and a covariance matrix as arguments. It can then provide random samples using the rvs() method.</p> <p>Next I want to perform a rotation of the cloud in 3D, but rather than rotate each point...
<p>I edited the question with the answer, but again it is</p> <pre><code>new_cov = rotation_matrix @ cov @ rotation_matrix.T </code></pre>
numpy|scipy|linear-algebra|covariance|covariance-matrix
2
4,354
63,342,185
Crosstab Output in Python
<p>Firstly I am pretty new to Python and I'm trying to output the view from a crosstab:</p> <pre><code>import pandas as pd Data_18['age_50_flag'] = (Data_18['age'] &gt; 50).astype(int) pd.crosstab(Data_18.age_50_flag, Data_18.age) </code></pre> <p>The output however, is being buried:</p> <pre><code>age 16 17 18 19...
<p>assume you have person and age pairs of data then find the individuals whose age is greater than 50 and display the results in a crosstab</p> <pre><code>age=[16, 17, 20, 24,96] name=['A','B','C','D','E'] df=pd.DataFrame({'name':name,'age':age}) df['greater50']=df['age'].apply(lambda person: 1 if person&gt;50 else 0)...
python|pandas|crosstab
0
4,355
63,532,399
Incompatible Shapes: Tensorflow/Keras Sequential LSTM with Autoencoder
<p>I am trying to set up an LSTM Autoencoder/Decoder for time series data and continually get <code>Incompatible shapes</code> error when trying to train the model. Following steps and using toy data from <a href="https://towardsdatascience.com/step-by-step-understanding-lstm-autoencoder-layers-ffab055b6352" rel="nofol...
<p>As the message clearly says, it's the shape issue which you are passing to the model for fit.</p> <p>From the above data which you have given X is having the shape of <code>(6, 3, 2)</code> and Y is having the shape of <code>(6, 2)</code> which is incompatible.</p> <p>Below is the modified code with the same input a...
python|tensorflow|keras|deep-learning|lstm
0
4,356
63,381,217
Make lists out of column values from one column, filtering on values from another
<p>I have a pandas dataframe like :</p> <pre><code> Fields Player bio Team 0 Name 1 2 1 city 2 2 2 state 1 1 3 stage 0 0 4 effec 2 2 5 points 1 2 </code></pre> <p>I would like to make lists named...
<p>You can do it like this:</p> <pre><code>selected_fields = ['Player bio', 'Team'] s = (df==2).T.dot(','+df['Fields']).str.strip(',')\ .str.split(',').reindex(selected_fields) s </code></pre> <p>Output:</p> <pre><code>Player bio [city, effec] Team [Name, city, effec, points] dtype:...
python|pandas
3
4,357
63,682,850
Can't reference column by using predefined parameter as part of string
<p>I have a dataset where I would like to reference my column by using predefined parameter as a part of the string. The reason for this is that the columns I want to keep will change depending on the time of the year and the year.</p> <p>My parameter are:</p> <pre><code>year = '20' </code></pre> <p>This is working fin...
<p>I found the my mistake, I was trying to test the code in an instance before I did the required cleaning of the data.</p> <p>When I replaced the actual code with my parameter it worked. I do however still not understand why I didn't get any KeyError when I was writing out the full string.</p> <p>Thanks a lot everybod...
python|pandas
0
4,358
63,506,954
Why is this dictionary comprehension so slow? Please suggest way to speed it up
<p>Hi Please help me either: speed up this dictionary compression; offer a better way to do it or gain a higher understanding of why it is so slow internally (like for example is calculation slowing down as the dictionary grows in memory size). I'm sure there must be a quicker way without learning some C!</p> <p><code>...
<p>Here is one approach:</p> <pre><code>import pandas as pd # create data frame df = pd.DataFrame({'idx': [1, 2, 3, 4], 'col': ['1|2', '1|2|3', '2|3', '1|4']}) # split on '|' to convert string to list df['col'] = df['col'].str.split('|') # explode to get one row for each list element df = df.explode('col') # create...
python|pandas|list|list-comprehension|dictionary-comprehension
3
4,359
21,769,162
Running a groupby on a pivot table with Pandas
<p>I have a pivot table that looks like this:</p> <pre><code>In [41]: counts Out[41]: SourceColumnID 3029903181 3029903182 3029903183 3029903184 ResponseCount ColID QuestionID RowID 3029903193 316923119 3029903189 ...
<p>You'll want to groupby <code>'RowID'</code>. Since it's a level on the MultiIndex you pass <code>'RowID'</code> to the <code>level</code> keyword.</p> <pre><code>In [5]: df.groupby(level='RowID').sum() Out[5]: 3029903181 3029903182 3029903183 3029903184 ResponseCount RowID ...
python|pandas|pivot-table
2
4,360
24,922,315
Merging pandas dataframe based on relationship in multiple columns
<p>Lets say you have a DataFrame of regions (start, end) coordinates and another DataFrame of positions which may or may not fall within a given region. For example:</p> <pre><code>region = pd.DataFrame({'chromosome': [1, 1, 1, 1, 2, 2, 2, 2], 'start': [1000, 2000, 3000, 4000, 1000, 2000, 3000, 4000], 'end': [2000, 30...
<p>One solution would be to do an inner-join on <code>chromosome</code>, exclude the violating rows, and then do left-join with <code>position</code>:</p> <pre><code>&gt;&gt;&gt; df = pd.merge(position, region, on='chromosome', how='inner') &gt;&gt;&gt; idx = (df['BP'] &lt; df['start']) | (df['end'] &lt; df['BP']) # ...
python|pandas|merge
5
4,361
17,595,912
Gaussian Smoothing an image in python
<p>I am very new to programming in python, and im still trying to figure everything out, but I have a problem trying to gaussian smooth or convolve an image. This is probably an easy fix, but I've spent so much time trying to figure it out im starting to go crazy. I have a 3d .fits file of a group of galaxies and have ...
<p>Something like this perhaps?</p> <pre><code>import numpy as np import scipy.ndimage as ndimage import matplotlib.pyplot as plt img = ndimage.imread('galaxies.png') plt.imshow(img, interpolation='nearest') plt.show() # Note the 0 sigma for the last axis, we don't wan't to blurr the color planes together! img = ndim...
python|numpy|scipy|gaussian|smoothing
30
4,362
20,112,760
python pandas convert dataframe to dictionary with multiple values
<p>I have a dataframe with 2 columns Address and ID. I want to merge IDs with the same addresses in a dictionary</p> <pre><code>import pandas as pd, numpy as np df = pd.DataFrame({'Address' : ['12 A', '66 C', '10 B', '10 B', '12 A', '12 A'], 'ID' : ['Aa', 'Bb', 'Cc', 'Dd', 'Ee', 'Ff']}) AS=df.set_inde...
<p>I think you can use <code>groupby</code> and a dictionary comprehension here:</p> <pre><code>&gt;&gt;&gt; df Address ID 0 12 A Aa 1 66 C Bb 2 10 B Cc 3 10 B Dd 4 12 A Ee 5 12 A Ff &gt;&gt;&gt; {k: list(v) for k,v in df.groupby("Address")["ID"]} {'66 C': ['Bb'], '12 A': ['Aa', 'Ee', 'Ff'],...
python|dictionary|pandas
19
4,363
15,889,998
Pandas force matrix multiplication
<p>I would like to force matrix multiplication "orientation" using Python Pandas, both between DataFrames against DataFrames, Dataframes against Series and Series against Series.</p> <p>As an example, I tried the following code:</p> <pre><code>t = pandas.Series([1, 2]) print(t.T.dot(t)) </code></pre> <p>Which output...
<p>Here:</p> <pre><code>In [1]: import pandas In [2]: t = pandas.Series([1, 2]) In [3]: np.outer(t, t) Out[3]: array([[1, 2], [2, 4]]) </code></pre>
python|pandas|matrix-multiplication|dot-product|dataframe
4
4,364
15,933,045
Numpy max slow when applied to list of arrays
<p>I carry out some computations to obtain a list of numpy arrays. Subsequently, I would like to find the largest values along the first axis. My current implementation (see below) is very slow and I would like to find alternatives.</p> <p><strong>Original</strong></p> <pre><code>pending = [&lt;list of items&gt;] mat...
<p>You can use <code>reduce(np.maximum, matrix)</code>, here is a test:</p> <pre><code>import numpy as np np.random.seed(0) N, M = 1000, 1000 matrix = [np.random.rand(N) for _ in xrange(M)] %timeit np.max(matrix, axis = 0) %timeit np.max(np.vstack(matrix), axis = 0) %timeit reduce(np.maximum, matrix) </code></pre> ...
python|numpy
5
4,365
15,944,171
Python: Differences between lists and numpy array of objects
<p>What are the advantages and disadvantages of storing Python objects in a <code>numpy.array</code> with <code>dtype='o'</code> versus using <code>list</code> (or <code>list</code> of <code>list</code>, etc., in higher dimensions)?</p> <p>Are numpy arrays more efficient in this case? (It seems that they cannot avoid...
<p>Slicing works differently with NumPy arrays. <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="noreferrer">The NumPy docs devote a lengthy page on the topic.</a> To highlight some points:</p> <ul> <li>NumPy slices can slice through multiple dimensions</li> <li>All arrays generated by Nu...
python|numpy
11
4,366
12,140,417
pandas: normalizing a DataFrame
<p>I have input data in a flattened file. I want to normalize this data, by splitting it into tables. Can I do that neatly with <code>pandas</code> - that is, by reading the flattened data into a <code>DataFrame</code> instance, and then applying some functions to obtain the resulting <code>DataFrame</code> instances?<...
<pre><code>In [30]: df = pandas.read_csv('foo1.csv', sep='[\s]{2,}') In [30]: df Out[30]: ItemId ClientId PriceQuoted ItemDescription 0 1 1 10 scroll of Sneak 1 1 2 12 scroll of Sneak 2 1 3 13 scroll of Sneak 3 2 ...
python|pandas|database-normalization
12
4,367
72,009,695
How do I check for null or string values ​in columns in the whole dataset in python?
<pre><code>def check_isnull(self): df = pd.read_csv(self.table_name) for j in df.values: for k in j[0:]: try: k = float(k) Flag=1 except ValueError: Flag = 0 break if Flag==1: QMessageBox.information(self, &quot;Information&quot;, ...
<p>try</p> <pre><code>pd.to_numeric(df['estimated'],errors='coerce') </code></pre> <p>then use this to get rid of those rows and also rows with NANs</p> <pre><code> df.dropna(subset='estimated') </code></pre>
python|pandas|dataframe
0
4,368
72,000,915
Warning when fitting the LSTM model
<p>When I try to fit my model i get an error. Here is the code:</p> <pre><code>model = Sequential() model.add(LSTM(128, activation='relu', input_shape=(trainX.shape[1], trainX.shape[2]), return_sequences=True)) model.add(LSTM(64, activation='relu', return_sequences=False)) model.add(Dropout(0.2)) model.add(Dense(trainY...
<p>You can use the following code to suppress the Warnings.</p> <pre><code>import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import tensorflow as tf </code></pre> <p>In detail:-</p> <pre><code>0 = all messages are logged (default behavior) 1 = INFO messages are not printed 2 = INFO and WARNING messages are not printed...
python|tensorflow|keras|lstm|warnings
0
4,369
55,392,853
Dataframe value not updating when iterating over rows
<p>I am fairly new to Pandas, and am trying to use it to analyse a large dataset. I have read everything I can find about it, but just can't get it to work. I am trying to update values in a dataframe whilst iterating over it row by row, but the values are not being updated in the dataframe.</p> <pre><code>for index, ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.at.html" rel="nofollow noreferrer"><code>DataFrame.at</code></a>:</p> <pre><code>df.at[index, j] = this_value </code></pre> <p>instead combination <code>loc</code> and <code>at</code>:</p> <pre><code>df.loc[index].at[j] = this...
python|pandas
0
4,370
55,377,044
What does this 'single' value represent in gradient?
<p>I tried to calculate gradient of output layer w.r.t. input and i am expecting a matrix of gradient (as gradient of different nodes in output layer w.r.t. each input) but i am getting a single value. I want to know what this value represent here?</p> <p>My aim was to calculate gradient of categorical-cross-entropy l...
<p><code>k.gradients</code> is a wrapper that actually runs <code>tf.gradients</code>. As described in the document</p> <blockquote> <p>Constructs symbolic derivatives of <strong>sum</strong> of ys w.r.t. x in xs.</p> </blockquote> <p>The result of <code>tf.gradients</code> is the sum of all <code>ys</code> deriva...
python|tensorflow|input|keras|gradient
1
4,371
55,463,251
Why does multi-class classification fails with sigmoid?
<p>MNIST trained with Sigmoid fails while Softmax works fine</p> <p>I am trying to investigate how different activation affects the final results, so I implemented a simple net for MNIST with PyTorch.</p> <p>I am using NLLLoss (Negative log likelihood) as it implements Cross Entropy Loss when used with softmax.</p> ...
<p>Sigmoid + crossentropy can be used for multilabel classification (assume a picture with a dog and a cat, you want the model to return "dog and cat"). It works when the classes aren't mutually exclusive or the samples contain more than one object that you want to recognize.</p> <p>In your case MNIST has mutually exc...
deep-learning|pytorch|loss-function|multiclass-classification|activation-function
0
4,372
7,656,665
How to repeat elements of an array along two axes?
<p>I want to repeat elements of an array along axis 0 and axis 1 for M and N times respectively:</p> <pre><code>import numpy as np a = np.arange(12).reshape(3, 4) b = a.repeat(2, 0).repeat(2, 1) print(b) [[ 0 0 1 1 2 2 3 3] [ 0 0 1 1 2 2 3 3] [ 4 4 5 5 6 6 7 7] [ 4 4 5 5 6 6 7 7] [ 8 ...
<p>You could use the <a href="https://en.wikipedia.org/wiki/Kronecker_product" rel="nofollow noreferrer">Kronecker product</a>, see <a href="https://numpy.org/doc/stable/reference/generated/numpy.kron.html" rel="nofollow noreferrer"><code>numpy.kron</code></a>:</p> <pre><code>&gt;&gt;&gt; a = np.arange(12).reshape(3,4)...
python|numpy
16
4,373
56,624,946
Calculating Quantiles based on a column value?
<p>I am trying to figure out a way in which I can calculate quantiles in pandas or python based on a column value? Also can I calculate multiple different quantiles in one output?</p> <p>For example I want to calculate the 0.25, 0.50 and 0.9 quantiles for </p> <p><strong>Column Minutes in df where it is &lt;= 5 and w...
<p><code>DataFrame.quantile</code> accepts values in array,</p> <p>Try</p> <pre><code>df['minute'].quantile([0.25, 0.50 , 0.9]) </code></pre> <p>Or filter the data first,</p> <pre><code>df.loc[df['minute'] &lt;= 5, 'minute'].quantile([0.25, 0.50 , 0.9]) </code></pre>
python|python-3.x|pandas|data-science
3
4,374
56,590,300
Simultaneously change occurrences in a numpy array
<p>I have a numpy array that looks something like this:</p> <pre><code>h = array([string1 1 string2 1 string3 1 string4 3 string5 4 string6 2 string7 2 string8 4 string9 3 string0 2 ]) </code></pre> <p>In the second column, I would like to change all occu...
<p>You can use a look up table and advanced indexing:</p> <pre><code>A = np.rec.fromarrays([np.array("The quick brown fox jumps over the lazy dog .".split()), np.array([1,1,1,3,4,2,2,4,3,2])]) A # rec.array([('The', 1), ('quick', 1), ('brown', 1), ('fox', 3), # ('jumps', 4), ('over', 2), ('the', 2), ('lazy'...
python|numpy
2
4,375
56,672,105
Transpose column in a DataFrame into a binary matrix
<p><strong><em>Context</em></strong></p> <p>Lets say I have a pandas-DataFrame like this:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; data.head() values atTime date 2006-07-01 00:00:00+02:00 15.10 0000 2006-07-01 00:15:00+02:00 16.10 0015 2006-07-01 00...
<p>This is a use case for <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html" rel="nofollow noreferrer"><code>get_dummies</code></a>:</p> <pre><code>pd.get_dummies(df, columns=[&quot;atTime&quot;]) </code></pre> <pre><code> values atTime_0 atTime_15...
python|pandas|dataframe
8
4,376
56,460,344
How to iterate over the n-th dimenstion of a numpy array?
<p>I use to concatenate my numpy arrays of arbitrary shape to make my code cleaner, however, it seems pretty hard to me to iterate over it in a pythonesque way.</p> <p>Lets consider a 4 dimension array x (thus <code>len(x.shape) = 4</code>), and that the index I want to iterate is 2, the naive solution that I usually ...
<p>One possible solution is to use a dict().</p> <p>What you can do is:</p> <pre><code>x = dict() x['param1'] = [1, 1, 1, 1] x['param2'] = [2, 2, 2, 2] print(x['param1']) # &gt; [1, 1, 1, 1] </code></pre>
python|numpy
0
4,377
56,575,877
shuffling two tensors in the same order
<p>As above. I tried those to no avail:</p> <pre><code>tf.random.shuffle( (a,b) ) tf.random.shuffle( zip(a,b) ) </code></pre> <p>I used to concatenate them and do the shuffling, then unconcatenate / unpack. But now I'm in a situation where (a) is 4D rank tensor while (b) is 1D, so, no way to concatenate.</p> <p>I al...
<p>You could just shuffle the indices and then use <code>tf.gather()</code> to extract values corresponding to those shuffled indices:</p> <p><strong>TF2.x (UPDATE)</strong></p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf import numpy as np x = tf.convert_to_tensor(np.arange(5)) y = tf.conv...
tensorflow|tensorflow2.0|tensorflow2.x
17
4,378
56,751,703
Why .argmax returns 1 instead of the maximum?
<p>I'm looking for the max value of two arrays, and I tried to get the max of each and add to another 'np.array'. However, I got 1.</p> <pre><code>maximums = [x_train.argmax(), x_test.argmax()] print(maximums) maximums = np.array(maximums) print(maximums) maximum = maximums.argmax() print(maximum) </code></pre> <p>I ...
<p><code>np.argmax</code> returns the index for the maximum value. In this case, the index for maximum value <code>577</code> is 1. Offcial docs reference: <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/reference/generated/nump...
python|numpy
1
4,379
67,140,409
python pandas apply function in groupby, and add results as column in data frame
<p>IM practicing with sample data to learn pandas. I have sample data like the following:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">symbol</th> <th style="text-align: center;">date_time</th> <th style="text-align: center;">close</th> <th style="text-align:...
<p>It was index related.</p> <p>setting the series index before passing it back works:</p> <pre><code>quote_data['rsi'] = quote_data.groupby(&quot;sym&quot;)[&quot;close&quot;].apply(calc_rsi) def calc_rsi(series): rsi_arr=np.array(series) RSI = talib.RSI(rsi_arr, timeperiod=14) rsi_series=pd.Series(RSI,se...
python|pandas|dataframe
0
4,380
47,356,322
Pandas: fill column based on data in different column
<p>I Have the following Dataframe:</p> <pre><code>test_df['A'] = [100, 100, 100, 0, 0, 100, 100, 0, 100, 100, 100] test_df['B'] = [100, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0] </code></pre> <p>What I want to achieve is a new column C where if I iterate on column B and I find a 100 value then I want to forward fill until the ...
<p>You can use the apply method. </p> <pre><code>def my_func(input): #do whatever test_df['B'] = test_df['A'].apply(my_func) </code></pre> <p>You obviously have to fill it in with your own code...</p>
python|pandas
-2
4,381
68,125,847
'>' not supported between instances of 'str' and 'int' pandas function for getting threshold
<p>I have a df</p> <pre><code>import pandas as pd df= pd.DataFrame({'ID': [1,2,3], 'Text':['This num dogs and cats is (111)888-8780 and other', 'dont block cow 23 here', 'cat two num: dog and cows here'], ...
<p>Since you're trying to change only the <code>Match</code> column, you might as well only pass that column to <code>apply</code>:</p> <pre><code>df.Match.apply(threshold) </code></pre> <p>where we don't use <code>axis</code> argument anymore since it is a Series we are applying over and it has only one axis anyway.</...
python|pandas|list|function|tuples
3
4,382
68,133,846
ERROR: Could not install packages due to an OSError: [WinError 5]
<p>i was trying to install tensorflow-gpu on my pycharm (<code>pip install tensorflow-gpu</code>), but unfortunately im getting a Error Message. How can i install this package on my pycharm? What is wrong here? Should i install it directly with cmd? How can I install them with pycharm? However, I was able to install th...
<p>You need to run the command prompt or terminal as an administrator. This will permit you to install packages. And also, you need to upgrade pip to the latest version - <code>python -m pip install –-upgrade pip</code> in cmd or terminal.</p>
python|tensorflow|pip|pycharm
14
4,383
68,090,432
How to map the integer values in a column in a pandas datfarme to random n-digit numbers?
<p>I have a pandas data frame like df:</p> <pre><code>df=pd.DataFrame([[111, 7,8], [409,6,4], [333, 9,0],[111,3,2],[111,0,0], [409,7,0]], columns=['A','B','C']) df A B C 0 111 7 8 1 409 6 4 2 333 9 0 3 111 3 2 4 111 0 0 5 409 7 0 </code></pre> <p>How to map column A to 10-digit random integers ...
<p>One way via <code>hashlib</code>:</p> <pre><code>import hashlib df['A'] = df['A'].apply(lambda s: int(hashlib.sha1(str(s).encode(&quot;utf-8&quot;)).hexdigest(), 16) % (10 ** 8)) </code></pre> <h4>OUTPUT:</h4> <pre><code> A B C 0 22445762 7 8 1 63857454 6 4 2 61248669 9 0 3 22445762 3 2 4 224...
python|pandas|dataframe
4
4,384
68,377,243
Pandas transform rows to columns
<p>I have a pandas dataframe that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">index</th> <th>p1</th> <th>a1</th> <th>phase</th> <th>file_number</th> <th style="text-align: right;">e1</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;...
<pre class="lang-py prettyprint-override"><code>d = {'p1': {388: 19.288,389: 40.91,390: 31.31,391: 28.42,392: 17.94,393: 38.02,394: 31.23,395: 26.902}, 'a1': {388: 21.63,389: 71.489,390: 43.952,391: 30.25,392: 22.0,393: 68.75,394: 48.352,395: 29.88}, 'phase': {388: 0.0,389: 1.0,390: 2.0,391: 3.0,392: 0.0,393:...
python|pandas|dataframe
1
4,385
68,117,724
Tensorflow-gpu not detecting GPU
<p>I have reinstalled tensorflow-gpu many times.Cuda and Cudnn already installed with path added but available gpu for tensorflow is always 0 for me.</p>
<p>I reinstalled tensorflow-gpu again but with following command.</p> <pre><code>conda install tensorflow-gpu=2.3 tensorflow=2.3=mkl_py38h1fcfbd6_0 </code></pre> <p><a href="https://github.com/ContinuumIO/anaconda-issues/issues/12194" rel="nofollow noreferrer">For more info</a></p>
python|tensorflow
0
4,386
59,166,618
getting a histogram of a JaggedArray
<p>Hi I have a ROOT TTree with a bit of a complicated structure. When I use uproot to create an array: </p> <pre><code>analysis = uproot.open("/b/LJ_data/02Oct2019/FRVZ/FRVZprompt2zd_mH125_mzd01.root")["analysis"] el_Eratio = analysis.arrays(["el_Eratio"], cache=mycache); print(el_Eratio) </code></pre> <p>I get a Jag...
<p>Because you said <code>analysis.arrays</code> (plural), you got back a Python dict. The only array it contains (because you asked for only one, <code>["el_Eratio"]</code>) has one key: <code>b"el_Eratio"</code>. Note that this is a bytestring (starts with <code>b</code>). If you know the encoding, such as <code>"utf...
python|numpy|matplotlib|uproot
0
4,387
59,171,235
Pandas data not being plotted
<p>I have the following simple code to plot specific data sets from this file <a href="https://easyupload.io/mdci9u" rel="nofollow noreferrer">https://easyupload.io/mdci9u</a></p> <pre><code>import pandas as pd import matplotlib.pyplot as plt url=r'/path_to_file/Book.xlsx' df1 = pd.read_excel(url, sheet_name=0,sep=...
<p>You made a mistake in the <strong>last line</strong>. It should be </p> <blockquote> <p>axs.plot(x,y)</p> </blockquote> <p>Instead, you have used an equal sign which is why you got an empty graph.</p>
python|pandas|matplotlib
2
4,388
59,314,762
Inconsistent matrices in SymPy
<p>I'm calculating reduced echelon forms in SymPy. I'm trying to get the pivot columns of the following matrix:</p> <pre><code>exercise4 = Matrix([[1,3,5,7],[3,5,7,9],[5,7,9,1]]) </code></pre> <p>I examine the matrix with the following:</p> <pre><code>exercise4.rref()[0] Matrix([ [1, 0, -1, 0], [0, 1, 2, 0], [0, 0...
<p>Doing your pivot on [2,3] produces the <code>rref</code> matrix:</p> <pre><code>In [269]: M Out[269]: array([[ 1., 0., -1., -2.], [ -0., 1., 2., 3.], [ 0., 0., 0., -10.]]) In [271]: M[0]-=M[2]*(-2/-10) ...
python|numpy|matrix|linear-algebra|sympy
0
4,389
45,180,564
Unit Testing Pandas DataFrame
<p>I'm looking to develop a unit test where it compares two DataFrames and returns True if their lengths are the same and if not returns the difference in length as well as what the missing output rows are.</p> <p>For instance: Example 1:</p> <pre><code>df1 = {0,1,2,3,4} df2 = {0,1,2,3,4} </code></pre> <blockquote> ...
<p>I think first you must decide on what you want: either an unit test or a function that returns the difference between two data frames.</p> <p>If the former case, you could use <code>pd.util.testing.assert_frame_equal</code>:</p> <pre><code>first = pd.DataFrame(np.arange(16).reshape((4,4)), columns=['A', 'B', 'C', ...
python|unit-testing|pandas|dataframe|diff
3
4,390
45,122,044
Plot partial stacked bar chart in pandas
<p>I have a DataFarme df in the following form. I want to plot a graph with 4-pair bars. It means for each of the four days, there are two bars representing 0 and 1. For both of the 2 bars, I want to have a stacked bar.So each bar have 3 colors, representing &lt;30, 30-70 and >70. I tried to use the "stacked = True" bu...
<p>You can use <code>bottom</code> parameter. Here is the way to go</p> <pre><code>&gt;&gt; import matplotlib.pyplot as plt &gt;&gt; import numpy as np &gt;&gt; import pandas as pd &gt;&gt; &gt;&gt; columns = pd.MultiIndex.from_tuples([(r, b) for r in ['&lt;30', '30-70', '&gt;70'] &gt;&gt; ...
python|pandas
3
4,391
45,225,814
Pandas: Best way to filter bottom 10% and top 25% of data within a groupby using quantile
<p>I have a time series in pandas with prices and times. I would like to group the dates by 1 month time intervals, calculate the 10-75% quantile of prices for each month and then filter the original dataframe using these values (so that only the prices that fall between 10% and 75% are left).</p> <p>The dataframe loo...
<p>First, define a function to check whether a Series is between the specified quantiles:</p> <pre><code>def in_qrange(ser, q): return ser.between(*ser.quantile(q=q)) </code></pre> <p>This returns a boolean array. If you pass this to resample.transform, you will have:</p> <pre><code>df.resample('1M')['price'].tr...
python|pandas|numpy
3
4,392
57,084,473
Return rows with max/min values at bottom of dataframe (python/pandas)
<p>I want to write a function that can look at a dataframe, find the max or min value in a specified column, then return the entire datafrane with the row(s) containing the max or min value at the bottom.</p> <p>I have made it so that the rows with the max or min value alone get returned.</p> <pre><code>def findAggre...
<h3>Focus on the index values</h3> <p>And use one <code>loc</code></p> <pre><code>i = df.col2.idxmin() df.loc[[*df.index] + [i]] col1 col2 col3 0 blue 2 dog 1 orange 18 cat 2 black 6 fish 0 blue 2 dog </code></pre> <hr> <p>Same idea but with Numpy and <code>iloc</code></p> <p...
python|pandas|csv|max|min
6
4,393
57,165,842
Extract info from original dataframe after doing some analysis on it
<p>So I had a dataframe and I had to do some cleansing to minimize the duplicates. In order to do that I created a dataframe that had instead of 40 only 8 of the original columns. Now I have two columns I need for further analysis from the original dataframe but they would mess with the desired outcome if I used them i...
<p>You can merge the new "clean" dataframe with the other two variables by using the indexes. Let me use a pratical example. Suppose the "initial" dataframe, called "df", is:</p> <pre><code>df name year reports location 0 Jason 2012 4 Cochice 1 Molly 2012 24 Pima 2 Tina 2013 ...
python|pandas
1
4,394
56,944,018
One-hot encoding in pytorch/torchtext
<p>I have a <code>Bucketiterator</code> from <code>torchtext</code> that I feed to a model in <code>pytorch</code>. An example of how the iterator is constructed:</p> <pre><code>train_iter, val_iter = BucketIterator.splits((train,val), batch_size=batch_size, ...
<p>def get_one_hot_torch_tensor(in_tensor): &quot;&quot;&quot; Function converts a 1d or 2d torch tensor to one-hot encoded &quot;&quot;&quot;</p> <pre><code>n_channels = torch.max(in_tensor)+1 # maximum number of channels if in_tensor.ndim == 2: out_one_hot = torch.zeros((n_channels, in_tensor.shape[0], in_tensor...
python|machine-learning|deep-learning|pytorch|torchtext
0
4,395
46,003,577
pandas: how to save to hdf dataframe with string columns containing np.nan
<p>I am wondering if there is a good way to save a pandas dataframe to hdf when it contains string columns.</p> <p>Given the dataframe :</p> <pre><code>In [6]: df.head() ...
<p>Columns in an HDF file must be of a single dtype. <code>nan</code> is represented by a <code>float</code> internally to numpy. You could replace the <code>nan</code> values with empty strings via:</p> <pre><code>df['src'].fillna('') </code></pre> <p>HDF performs much better on numeric types than strings, so it may...
python|pandas|hdf5
3
4,396
45,819,258
numpy inverse matrix not working for full rank matrix - hessian in logistic regression using newtons-method
<p>I am trying to compute the inverse of a full-rank matrix using numpy, but when I test the dot product, I find that it does not result in the identity matrix - which means it did not invert properly. </p> <p>My code:</p> <pre><code>H = calculateLogisticHessian(theta, X) #returns a 5x5 matrix Hinv = np.linalg.inv(H...
<p>Hessian matrix are often <a href="https://en.wikipedia.org/wiki/Condition_number" rel="nofollow noreferrer">ill-conditioned</a>. <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.cond.html" rel="nofollow noreferrer"><code>numpy.linalg.cond</code></a> lets you compute the <em>condition numbe...
numpy|logistic-regression|matrix-inverse|newtons-method|hessian
2
4,397
46,078,287
Plotting lines and bars from pandas dataframe on same graph using matplotlib
<p>I want to plot temperature data as a line, with rainfall data as a bar. I can do this easily in <a href="https://ibb.co/hWy2Bv" rel="nofollow noreferrer">Excel</a> but I'd prefer a fancy python graph to show it in a nicer way. </p> <p>Some sample code to illustrate the problem:</p> <pre><code>import pandas as pd i...
<p>A simple way would be to use the <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html#suppressing-tick-resolution-adjustment" rel="nofollow noreferrer"><code>x_compat</code></a> property:</p> <pre><code>ax = df.plot(x=index, y="A", x_compat=True) # plot lines first df.plot(x=index, y="B", kind="...
python|pandas|matplotlib
2
4,398
23,190,799
Capturing Datetime Objects in Pandas Dataframe
<p>If I'm reading the docs correctly for Pandas 0.13.1, read_csv should yield columns of datetimes when <code>parse_dates = [&lt;col1&gt;,&lt;col2&gt;...]</code> is invoked during the read. What I'm getting instead is columns of Timestamp objects. Even with the application of .to_datetime, I still end up with Timestamp...
<p>Timestamps are the way that pandas deals with datetime, you can <a href="https://stackoverflow.com/questions/13703720/converting-between-datetime-timestamp-and-datetime64">move between Timestamp, datetime64 and datetime</a>, but <strong>most of the time using Timestamp is what you want</strong> (and pandas just conv...
python|datetime|pandas
3
4,399
23,298,751
Filtering on data with a cast string->float type
<p>a few issues here but i think the code is relatively straight forward.</p> <p>the code is as follows:</p> <pre><code> import pandas as pd def establishAdjustmentFactor(df): df['adjFactor']=df['Adj Close']/df['Close']; df['chgFactor']=df['adjFactor']/df['adjFactor'].shift(1);...
<p>So it appears as if I have found the issue after poking around a little bit, and changing the way I was thinking about the problem.</p> <p>Any input on if there is a more efficient way to do this would be great.</p> <pre><code> def operateOverSetToCreateEasyKey(df): for i in df.index: df.ix[...
python|pandas
0