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
351,900
48,815,385
Why is python only outputting 6 numbers seperated by '...', when the expectation is output of 10,000 numbers?
<p>The full problem: <strong>Generate a NumPy array of 10,000 random numbers (called x) and create a Variable storing the equation y=5x^2−3x+15</strong></p> <pre><code>import numpy as np data = np.random.randint(1000, size=10000) x = tf.constant(data, name='x') y = tf.Variable(5 * (x**2) - (3 * x) + 15) model = tf....
<p>That's just numpy summarising your array, so you don't get 1000 numbers printed to the terminal. You can control the threshold where this kicks in by using the <code>threshold</code> argument to <code>np.set_printoptions</code>:</p> <pre><code>threshold : int, optional Total number of array elements which trig...
python|numpy|tensorflow
2
351,901
48,517,655
Separate multiindex dataframe into multiple single-index dataframes in pandas
<p>I have a multiindex dataframe describing stock movements (OHLC). The indices are <code>date</code> and <code>symbol</code>. The dataframe looks like this:</p> <pre><code> open high low close volume date symbol 2017-12-03 07:00:00 4005 38.75 38.75 38.75 38.75 ...
<p>Simpliest is use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.xs.html" rel="nofollow noreferrer"><code>xs</code></a>:</p> <pre><code>print (df.xs('4338', level=1)) open high low close volume date 2018-01-22 ...
python|pandas|numpy
3
351,902
48,750,358
KL divergence between hidden layer and arbitrary distribution (Keras/TensorFlow)
<p>I'm implementing an autoencoder in Keras, let's say something like:</p> <pre><code>... x = Input(shape=(original_dim,)) h = Dense(intermediate_dim, activation='relu')(x) z = Dense(latent_dim)(h) output = Dense(intermediate_dim, activation='sigmoid')(z) ... </code></pre> <p>My goal is to make <code>z</code> behave ...
<p>I'm guessing you want something like an Empirically defined distribution like Edward has: <a href="http://edwardlib.org/api/ed/models/Empirical" rel="nofollow noreferrer">http://edwardlib.org/api/ed/models/Empirical</a>?</p> <p>Do you mind filing a request at <a href="https://github.com/tensorflow/probability" rel=...
python|tensorflow|machine-learning|deep-learning|keras
0
351,903
48,531,039
Create variable of weights from array
<p>I have an array : [1, 4, -10, 3, 5]. I'm trying to create a <code>Variable</code> of weights using that array.</p> <p>After doing training, I print the weight as: </p> <pre><code>result = sess.run(w) print(result) </code></pre> <p>the <code>result</code> is just the array in the format [1, 4, -10, 3, 5].</p> <p>...
<p>You don't have to loop through the elements; Rather simply use the whole list at once as in:</p> <pre><code>In [21]: vals = [1, 4, -10, 3, 5] # create Variable `W` In [22]: W = tf.Variable(initial_value=vals, name='weights') # initialize all variables In [23]: init = tf.global_variables_initializer() In [24]: wi...
python|tensorflow|deep-learning|tensor
0
351,904
48,579,924
How to improve performance while iterating through a pandas data frame?
<p>I have two pandas data frames. The first one contains a list of unigrams extracted from the text, count and probability of the unigram occurring in the text. The structure looks like this:</p> <pre><code>unigram_df word count prob 0 we 109 0.003615 1 investigated 20 ...
<p>This is a good question, and exercise, for new users of <code>pandas</code>. Use <code>df.iterrows</code> only as a last resort and, even then, consider alternatives. There are relatively few occasions when this is the right option.</p> <p>Below is an example of how you can vectorise your calculations.</p> <pre><c...
python|performance|pandas
1
351,905
48,485,234
Unable to install Pandas, I get multiple errors
<p>I get errors when I try to install pandas in Windows 10, several errors the last one is in red:</p> <pre><code>Command "python setup.py egg_info" failed with error code 1 in C:\Users\User1\AppData\Local\Temp\pip-build-07bztlx0\pandas\ </code></pre>
<p><strong>try with:</strong></p> <p>In python executable file-</p> <pre><code>import pip pip.main(["install","pandas"]) </code></pre>
pandas
0
351,906
48,811,652
return dynamic value from newly generated column value
<p>I have 2 columns and i want diff column as an output.I tried with loops iteration.if i am passing array of values and i want diff column array.</p> <pre><code> l h diff 100.87 100.87 max(h-l) 99.800778 100.87 max ((h-l),diff[0]) 101.1281283...
<p>IIUC, you need <code>cummax</code>:</p> <pre><code>df['diff'] = df['h'] - df['l'] df['diff'] = df['diff'].cummax() </code></pre> <p>You can do this in one line:</p> <pre><code>df['diff'] = (df['h'] - df['l']).cummax() </code></pre> <p>Output:</p> <pre><code> l h diff 0 100.870000 100...
python|pandas
3
351,907
48,492,637
Incorrect Python Numpy Eigenvector Values for Super Simple Example
<p>I am trying to learn how to use numpy to determine eigenvectors and values in a simple example but the results do not look correct. Here is my code:</p> <pre><code>import numpy as np import numpy.linalg as la # create the matrix matrix = np.array([[-2, 1, 0], [1, -2, 1], [0, 1, -2]]) print("Matrix:\n", matrix) #...
<p>Numpy is correctly calculating the eigenvectors/values. You can check this by running (answer to Question 2):</p> <pre><code>print(np.dot(vecs,np.dot(np.diag(vals),vecs.T)) - matrix) print(np.dot(vecs,vecs.T)) </code></pre> <p>The first output tells you how closely your eigenvalue decomposition approximates the ma...
python|numpy|linear-algebra
2
351,908
48,873,893
List within a dataframe cell - counting the number of items in list
<p>I currently have a dataframe that contains a list of floats within a column, and I want to add a second column to the df that counts the length of the list within the first column (the number of items within that list). What would be the easiest way to go about doing this and would I have to write a function that it...
<p>This should work:</p> <pre><code>df['list_len'] = df['list_column'].str.len() </code></pre>
python|pandas|dataframe
2
351,909
48,477,153
Unable to extract dataframe column using pandas
<p>I am new to pandas and am struggling with to rename a column and then extracting the same.</p> <p>I have read an xls file into a pandas data frame object.</p> <pre><code>df = pd.read_excel("something.xls") bank_statement.columns.values[0] = 'Din' bank_statement.columns </code></pre> <p>This showed the columns</p>...
<p>Don't update internal Pandas structures using <code>.values</code>:</p> <pre><code>bank_statement.columns.values[0] = 'Din' </code></pre> <p>Use corresponding API function/method instead:</p> <pre><code>bank_statement = bank_statement.rename(columns={'Unnamed: 0':'Din'}) </code></pre> <p>Demo:</p> <pre><code>In...
python|pandas|data-science|data-cleaning
1
351,910
48,465,683
Visualizing a multivariate normal distribution with numpy and matplotlib in 3 Dimensions
<p>I am trying to visualise a multivariate normal distribution with matplotlib. I would like to produce something like this:</p> <p><a href="https://i.stack.imgur.com/5PuaD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5PuaD.jpg" alt="enter image description here"></a></p> <p>I use the following...
<p>In the past I have done this with <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.multivariate_normal.html" rel="noreferrer"><code>scipy.stats.multivariate_normal</code></a>, specifically using the <code>pdf</code> method to generate the z values. As @Piinthesky pointed out the numpy implem...
python|numpy|matplotlib|3d
6
351,911
48,513,073
Pandas scatter plot by category and point size
<p>So I had the idea to using a single Pandas plot to show two different datum, one in Y axis and the other as the point size, but I wanted to categorize them, i.e., the X axis is not a numerical value but some categories. I'll start by illustrating my two example dataframes:</p> <pre><code>earnings: DayOfWeek ...
<p>Here's the code:</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt earnings = pd.read_csv('earnings.csv', sep=';') tips = pd.read_csv('tips.csv', sep=';') print(earnings) print(tips) earnings['index'] = earnings.index height, width = earnings.shape cols = list(earnings.colu...
python|pandas|matplotlib|scatter
2
351,912
48,468,038
list.append copies the last item only
<p>This might endup in very silly question, but being a newbie in python i am not able to find a good solution to following problem.</p> <pre><code>class Preprocessor: mPath = None; df = None; def __init__(self, path): self.mPath = path; def read(self): self.df = pd.read_csv(self.mPa...
<p>I got to understand the issue now, i was trying to mutate the dictionary object.</p> <pre><code>def tranformDataFrame(self): genres = self.__findUniqueGenres(); print('### List of genres...', genres); __df = self.__prepareDataframe(genres); # Data frame with all required columns. rowTemplate = self....
python|pandas|numpy
0
351,913
48,571,331
Efficient way to crossreference multiple columns with list of strings with pandas
<p>I need to search a dataframe text column for either country names or capital names, then save the hits in a new column. My current solution is working but takes a very long time. I'm wondering if it's possible to make this more effective, ideally in a vectorised fashion.</p> <p>The list of countries and capitals is...
<p>Here is one way. Note <code>NaN</code> ("Not a Number") is not applicable for string columns, so I have left empty strings where no match is found.</p> <pre><code>import pandas as pd df = pd.DataFrame([['2016-01-01', 'Bla bla bla bla'], ['2016-01-01', 'Blu blu Nigeria'], ['2016-01-01', 'Hey ho N...
python|pandas|vectorization
1
351,914
48,617,167
0 Training parameters in keras custom layer
<p>Recently I have switched to keras from tensorflow and I need to create a custom layer.</p> <p>I defined the class as below:<br/></p> <pre><code>class Apply_conv2d(Layer): def __init__(self, **kwargs): super(Apply_conv2d, self).__init__(**kwargs) def build(self, input_shape): super(Apply_conv2d, self).buil...
<p>After a lot of research and try various approaches Finally I found the solution.<br/> I should have used the raw conv operation from keras so the implementation should have been like this:<br/></p> <pre><code>class Apply_conv2d(Layer): def __init__(self, **kwargs): super(Apply_conv2d, self).__init__(**kwargs) ...
python|tensorflow|deep-learning|keras|layer
4
351,915
48,625,279
Python statmodels lib deprecation warning
<p>I am doing some statistical tests using the Dickey-Fuller method.</p> <p>After I made the import:</p> <pre><code>from statsmodels.tsa.stattools import adfuller </code></pre> <p>I am receiving this <code>FutureWarning</code>:</p> <blockquote> <p>/env/lib/python3.5/site-packages/statsmodels/compat/pandas.py:56: ...
<p>According to <a href="https://github.com/statsmodels/statsmodels/issues/3617" rel="nofollow noreferrer">this thread</a> this was fixed in <code>statsmodels==0.9</code>, so you should upgrade if possible. If you can't upgrade for whatever reason <a href="https://stackoverflow.com/questions/14463277/how-to-disable-pyt...
python|python-3.x|pandas|statistics|time-series
3
351,916
48,474,442
Python - From list of list of tokens to bag of words
<p>I am struggling with computing bag of words. I have a pandas dataframe with a textual column, that I properly tokenize, remove stop words, and stem. In the end, for each document, I have a list of strings.</p> <p>My ultimate goal is to compute bag of words for this column, I've seen that scikit-learn has a function...
<p>You can create <code>DataFrame</code> by filtering with <code>Counter</code> and then convert to <code>list</code>s:</p> <pre><code>from collections import Counter df = pd.DataFrame({'text':[["hello", "world"], ["hello", "stackoverflow", "hello"]]}) L = ["hello", "world", "stackoverflow...
python|pandas|scikit-learn|nlp|nltk
3
351,917
48,530,065
Keras clear all gpu memory
<p>I'm doing something like this:</p> <pre><code>for ai in ai_generator: ai.fit(ecc...) </code></pre> <p>ai_generator is a generator that instantiate a model with different configuration.<br/> My problem is gpu memory overflow, and K.clear_session() don't work because it throw this<br/> <code>ValueError: Tensor("c...
<p>I resolved removing all layer shared between models. The "shared" instance was the input. Then I did this:</p> <pre><code>for ai in aigen: ai.fit(**params) del ai # for avoid any trace on aigen tf.reset_default_graph() # for being sure K.clear_session() # removing session, it will instance another </co...
tensorflow|keras|out-of-memory
0
351,918
48,487,928
Interleave numpy arrays
<p>I'm trying to interleave arrays as below.</p> <pre><code>import numpy as np x = np.array([1,2,3,4,5]) y = np.array([4,6,2,6,9],[5,9,8,7,4],[3,2,5,4,9]) </code></pre> <p>Desired result:</p> <pre><code>[[1,2,3,4,5],[4,6,2,6,9],[1,2,3,4,5],[5,9,8,7,4],[1,2,3,4,5],[3,2,5,4,9]] </code></pre> <p>Is there an elegant w...
<p>You can try to use <code>np.insert</code></p> <pre><code>import numpy as np x = np.array([1,2,3,4,5]) y = np.array([[4,6,2,6,9],[5,9,8,7,4],[3,2,5,4,9]]) np.insert(y, obj=(0, 1, 2), values=x, axis=0) array([[1, 2, 3, 4, 5], [4, 6, 2, 6, 9], [1, 2, 3, 4, 5], [5, 9, 8, 7, 4], [1, 2, 3, 4...
python|numpy
4
351,919
48,470,221
Improve performance of difference between elements block
<p>I have a rather simple block that obtains the absolute valued difference between two selected elements from two arrays.</p> <pre><code>import numpy as np # Input data with proper format. N_bb, N_cc = np.random.randint(1e5), np.random.randint(1e5) bb = np.random.uniform(0., 1., N_bb) cc = np.random.uniform(0., 1., ...
<p>We can simply use vectorized indexing to remove the inner loop, like so -</p> <pre><code>d = np.median(np.abs(bb-cc[idx_into_cc])) </code></pre>
python|performance|numpy
3
351,920
48,864,096
Build dict from list of tuples combining two multi index dfs and column index
<p>I have two multi-index dataframes: mean and std</p> <pre><code>arrays = [['A', 'A', 'B', 'B'], ['Z', 'Y', 'X', 'W']] mean=pd.DataFrame(data={0.0:[np.nan,2.0,3.0,4.0], 60.0: [5.0,np.nan,7.0,8.0], 120.0:[9.0,10.0,np.nan,12.0]}, index=pd.MultiIndex.from_arrays(arrays, names=('id', 'comp'))) mean.columns.nam...
<p>Here is a solution using a <code>defaultdict</code>:</p> <pre><code>from collections import defaultdict mean_as_dict = mean.to_dict(orient='index') std_as_dict = std.to_dict(orient='index') mean_clean_sorted = {k: sorted([(i, j) for i, j in v.items()]) for k, v in mean_as_dict.items()} std_clean_sorted = {k: sort...
python|list|pandas|dictionary|tuples
2
351,921
48,727,964
How to pass condition into lambda?
<p>I have a dictionary like this:</p> <pre><code>Dict={'A':0.0697,'B':0.1136,'C':0.2227,'D':0.2725,'E':0.4555} </code></pre> <p>I want my output like this: Return A,B,C,D,E if the value in my dataframe is <strong>LESS THAN</strong> 0.0697,0.1136,0.2227,0.2725,0.4555 respectively; else return F</p> <p>I tried:</p> ...
<p>Let's make some test data:</p> <pre><code>saga = pd.Series([0.1, 0.2, 0.3, 0.4, 0.5, 0.9]) </code></pre> <p>Next, recognize that <code>Dict</code> is a <code>dict</code> and has no ordering, so let's get that sorted by the numbers in reverse order:</p> <pre><code>thresh = sorted(Dict.items(), key=lambda t: t[1], ...
python|pandas|lambda
2
351,922
48,877,037
How Can I Keep Rows of a Pandas Dataframe where two entries are within a week of each other?
<p>My data looks like this the following. I have a groupby to group the Visit_id's but now I want to delete all rows unless that Visit_id has two Visit_time's that are within a week of each other.</p> <pre><code>df allVisits: Visit_id Visit_time 162 2009-01-21 00:00:00.000 162 2012-09-05 00:00:00.0...
<p><strong>Interpretation 1</strong></p> <p>If you mean to keep all records with a <code>Visit_id</code> that has at least two records within a week of each other, this is one way to do that.</p> <pre><code>df.sort_values(['Visit_id', 'Visit_time'], inplace=True) # sort the rows by date # shift the records within e...
pandas|jupyter|data-science
1
351,923
48,678,380
GPUs out of memory even in reading small data? Using "Quadro m1000m 4GB GPU"
<pre><code>Resource exhausted: OOM when allocating tensor with shape[256,128,3,3] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc </code></pre> <p>Here I am trying to use vgg for learning concepts of deep learning using Fast.ai course. When I am trying to read a small data of 4 im...
<p>I solved the issue. Actually Tensowflow version was requiring a lot of memory so I changed the Keras backend to Theano and that solved the issue there is nothing to do with VGG here I guess. Switching can be done in the .keras folder in keras.json file and change the backend to theano.</p>
python-3.x|tensorflow|deep-learning|gpu|theano
1
351,924
48,483,286
How to correctly parse HTML to Unicode strings with pandas?
<p>I'm running a Python program which fetches a UTF-8-encoded web page, and I extract some text from HTML table using pandas(read_html) and write result to csv file</p> <p>However, when I write this text to a file,all spaces in it gets written in an unexpected encoding (example \xd0\xb9\xd1\x82\xd0\xb8). to solve the ...
<p>You can use the <strong><a href="https://docs.python.org/2/library/functions.html#filter" rel="nofollow noreferrer">filter</a></strong> method to remove of empty values. you can add the below snippet after <em>'i = i.split(" ")'</em></p> <pre><code>A = ['0', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '...
python|pandas|html5lib
0
351,925
48,525,724
Reading non-contiguous subsets of a variable in a fast way
<p>I have a <a href="http://unidata.github.io/netcdf4-python/#netCDF4.Variable" rel="nofollow noreferrer"><code>netCDF4.Variable</code></a> object:</p> <pre><code>&lt;class 'netCDF4._netCDF4.Variable'&gt; int16 myvar(time, latitude, longitude) standard_name: my_var long_name: Something units: (0 - 1) a...
<p>Not sure if this works memory-wise, but would you consider cutting down the file first from the command line outside python using NCO or CDO and then reading that from python? It depends on whether you need to repeatedly access different chunks of the file, or whether this is a one-off access. </p> <p>The commands...
python|python-3.x|numpy|netcdf
1
351,926
70,935,956
SpeechBrain: Cannot Load Pretrained Model from Local Path
<p>I'm trying to load a pretrained SpeechBrain HuggingFace model from local files; I don't want it to call out to HuggingFace to download. However, unless I change the <code>pretrained_path</code> in <code>hyperparams.yaml</code>, it is still calling out to HuggingFace and downloading the models from HF.</p> <pre><code...
<p>SOLVED: User Error. The steps in 1-3 above work. There was a typo in the names of one of my files: it should be <code>label_encoder.txt</code> not <code>label_encoder.ckpt</code>. You can see this by looking at <code>hyperparams.yaml</code> for <code>voxlingua107-epaca-tdnn</code> to see what it expects.</p>
speech-recognition|speech-to-text|torch|huggingface-transformers|huggingface-tokenizers
0
351,927
70,871,887
Why am I getting an empty dataFrame with no indexes
<p>I am completely new to all coding so forgive any mistakes in asking the question and please explain like I am 5. I have a file that I've converted to a dataframe but when I try to find a row number corresponding to a specific value it shows up as empty dataframe with a blank for indexes. When I use <code>len(pdf.ind...
<p>You can't compare floating point numbers directly. Floating point numbers are an approximation. Pandas is showing you the first 9 decimal places, but the number actually has 15 decimal places. You need to do something like</p> <pre><code>print(pdf[pdf['b']-0.078162).abs() &lt; 0.00001]) </code></pre>
python|pandas|dataframe|indexing|converters
1
351,928
70,827,068
The correct way of using keras sequatial()
<p>Please, someone, check what I have done in the code below. I'm not getting the result am anticipating it. I Am trying to build a model for a regression problem. My data contains 9 features and 1 target.</p> <pre><code># define the model def baseline(): # create model model = () # add one fully conne...
<p>you will need to define a model like this <code>model = Sequential()</code> but other than that everything is correct</p>
python|tensorflow2.0
0
351,929
71,040,948
How to search an element in column of a dataframe containing lists
<p>I have a pandas dataframe <code>df</code> which contains two columns. First column <code>sentence</code> contains the sentence and second column <code>keywords</code> contains the all the keywords in list from the sentence in the first column. So my dataframe looks something like this :</p> <pre><code>&gt;&gt;&gt; d...
<p>You can use <code>set.isjdisoint</code> and check if there are any overlapping words with the &quot;keywords&quot; to create a boolean mask. Then, use the mask on <code>df</code> to filter the matching sentences:</p> <pre><code>lst = [&quot;salon&quot;, &quot;usage&quot;, &quot;history&quot;] msk = df['keywords'].ap...
python|pandas|dataframe
1
351,930
70,828,018
Split features, preprocess some of them, then join them back together. (hangs forever)
<p>I'm trying to feed the all features (except the first one) to some layers (nn.Linear + nn.LeakyReLU), get the output, then reassemble the initial data structure and feed it to the last layers. But the training process just hangs forever and I don't get any output.</p> <p>To be clear, the code works fine without this...
<p>Well, as it turns out, slicing is WAY faster and easier than iterating. And I also used <code>torch.cat</code> function to put everything back in one tensor.</p> <pre><code> def forward(self, x): # save the residual for the skip connection res = x[:, :, 0:self.skip] # split features ...
python|pytorch
0
351,931
70,793,292
How to obtain a nested seaborn boxplot from a 3D numpy array
<p>I'm trying (and failing) to obtain a nested boxplot starting from a numpy array with dimension 3, for example <code>A = np.random.uniform(size = (4,100,2))</code>.</p> <p>The kind of plot I'm referring to is represented in the next picture, which comes from the seaborn <a href="https://seaborn.pydata.org/generated/s...
<p>You can use <code>np.meshgrid()</code> to generate 3 columns which index the 3D array. Unraveling these arrays makes them suitable as input for seaborn. Optionally, these arrays can be converted to a dataframe, which helps in automatically generating labels.</p> <pre class="lang-py prettyprint-override"><code>impor...
python|pandas|numpy|matplotlib|seaborn
0
351,932
70,812,332
Pandas set index name for single level
<p>I would like to set the name for a single level of a pandas dataframe with some chaining method. Consider, e.g., the dataframe</p> <pre><code> value color shape green round 0.05 -1.687948 0.95 1.280259 square 0.05 -1.733411 0.95 1.528829 red r...
<p>You can use <code>rename_axis</code>:</p> <pre><code>df.rename_axis(index={None:'quantile'}, inplace=True) </code></pre> <p>Output:</p> <pre><code> value color shape quantile green round 0.05 -1.687948 0.95 1.280259 square 0.05 -1.733411 ...
python|pandas|dataframe
2
351,933
70,864,159
Get most frequent elements across all groups in a Panda time series
<p>How one can plot the <code>count</code> of the <code>n</code> most frequent elements <strong>across all groups</strong> for a given multi group time series? Note this is different from <code>n</code> most frequent elements of <strong>each</strong> group, which could be accomplished with <code>count</code> and <code>...
<p>IIUC, you want to filter the most common Name and plot the counts?</p> <pre><code># get top Name top = df['Name'].value_counts().index[0] # filter df2 = df[df['Name'].eq(top)] # plot (df2.assign(date=df2[['year', 'month']].astype(str).apply('_'.join, axis=1)) .plot.bar(x='date', y='count') ) </code></pre> <p><...
python|pandas|matplotlib
1
351,934
71,090,703
Generate values in separate dataframe
<p>I trying to generate random data with Pandas.</p> <p>Data is need to be stored in two columns. The first column needs to contain categorical variables (from Stratum_1 until Stratum_19) each of these stratums can contain a random number of values.</p> <p>Second column needs to have data in the range between 1 to 1800...
<p>Try:</p> <pre><code>import numpy as np categorical = {'name': ['Stratum_1','Stratum_2','Stratum_3','Stratum_4','Stratum_5','Stratum_6','Stratum_7','Stratum_8','Stratum_9', 'Stratum_10','Stratum_11','Stratum_12','Stratum_13','Stratum_14','Stratum_15','Stratum_16','Stratum_17','Stratum_18','Stratum_19']} desired...
python|pandas|numpy
1
351,935
70,928,985
Creat a list with repeated terms by adding a multiplier index in Pandas Dataframe
<p>Given a dataframe like this:</p> <pre><code>row1 = ['AAA', 'BBB', 'BBB', 'CCC', 'AAA', 'AAA'] row2 = ['CCC', 'CCC', 'BBB', 'AAA', 'AAA', 'AAA'] col = {'List': [row1, row2]} df = pd.DataFrame(col) </code></pre> <p>which leads to:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>L...
<p>In your case you may need to check with <code>explode</code> ,then we create the subgroup with <code>cumsum</code> ad <code>shift</code></p> <pre><code>s = df.explode('List') s = s.groupby([s.index,s['List'].shift().ne(s['List']).cumsum()])['List'].agg(['first','count']) out = s['first'] +'x' + s['count'].astype(str...
python|pandas|list|dataframe|data-manipulation
1
351,936
70,746,137
Adapt a numerical tensorflow dataset as a textvector
<p>consider the following code:</p> <pre><code>import numpy as np import tensorflow as tf simple_data_samples = np.array([ [1, 1, 1, -1, -1], [2, 2, 2, -2, -2], [3, 3, 3, -3, -3], [4, 4, 4, -4, -4], [5, 5, 5, -5, -5], [6, 6, 6, -6, -6], [7, 7, 7, -7, -7], ...
<p>If I understood you correctly, you can use your existing dataset with the <code>TextVectorization</code> layer like this:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf input_vectorization = tf.keras.layers.TextVectorization( max_tokens=20, output_mode=&quot;int&quot;, outpu...
python|tensorflow|tensorflow2.0|tensorflow-datasets
1
351,937
71,043,300
Filter dataframe based on matching values from two columns
<p>I have a dataframe like as shown below</p> <pre><code>cdf = pd.DataFrame({'Id':[1,2,3,4,5], 'Label':[1,2,3,0,0]}) </code></pre> <p>I would like to filter the dataframe based on the below criteria</p> <pre><code>cdf['Id']==cdf['Label'] # first 3 rows are matching for both columns in cdf </code></...
<p>I think you're overthinking this. Just compare the columns:</p> <pre><code>&gt;&gt;&gt; cdf[cdf['Id'] == cdf['Label']] Id Label 0 1 1 1 2 2 2 3 3 </code></pre> <p>Your particular error though is coming from the fact that you're using square brackets to call <code>np.where</code>, e.g. <code>...
python|pandas|dataframe|numpy|series
2
351,938
70,793,873
Drop rows with NaNs from pandas dataframe based on multiple conditions
<p>I have a dataframe with a lot of NaNs.</p> <p><code>y</code> columns mean the count of events, <code>val</code> means values of each event in that yeat, and <code>total</code> means a multiplication of both columns.</p> <p>Many columns have zeros and many have NaNs because <code>values</code> are not available (up t...
<p>Just pass the condition with <code>all</code></p> <pre><code>out = df[df.iloc[:,:4].eq(0).all(1) | df.notna().all(1)] Out[386]: y17 y18 y19 y20 val17 ... val20 total17 total18 total19 total20 0 1 2 1 2 2.0 ... 2.0 1.0 4.0 2.0 4.0 1 2 2 2 2 2.0 ... ...
python|pandas|nan|drop
3
351,939
70,881,387
Pandas merge multiple value columns into a value and type column
<p>I have a pandas dataframe where there are multiple integer value columns denoting a count. I want to transform this dataframe such that the value columns are merged into one column but another column is created denoting the column the value was taken from.</p> <p>Input</p> <pre><code> a b c 0 2 5 8 1 ...
<p>You could do that with the following</p> <p><code>pd.melt(df, value_vars=['a','b','c'], value_name='count', var_name='type')</code></p>
python|pandas|dataframe
1
351,940
70,920,394
Determining Consecutive Days Using Pandas
<p>I have a Pandas DataFrame that looks something like this:</p> <pre><code> activity_id start end type ... site heart_rate grp_idx date user_id ...
<p>Try this:</p> <pre><code>count = df.groupby(df.start.diff().ne(pd.Timedelta(days=1)).cumsum()).apply(len).ge(4).sum() </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; count 3 </code></pre>
python|pandas|time-series|data-science
0
351,941
70,758,855
torch.no_grad() and detach() combined
<p>I encountered many code fragments like the following for choosing an action, that include a mix of <code>torch.no_grad</code> and <code>detach</code> (where <code>actor</code> is some actor, <code>SomeDistribution</code> your preferred distribution), and I'm wondering whether they make sense:</p> <pre><code>def f():...
<p>While it may be redundant, it depends on the internals of <code>actor</code> and <code>SomeDistribution</code>. In general, there are three cases I can think of where <code>detach</code> would be necessary in this code. Since you've already observed that <code>x</code> has <code>requires_grad</code> set to <code>Fal...
machine-learning|deep-learning|neural-network|pytorch|gradient-descent
1
351,942
70,852,361
Pandas: How to find the index of a cell from groupby values?
<p>I have a dataframe:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; dates = ['1/1/2020', '1/1/2020', '1/1/2020', '1/2/2020', '1/2/2020', '1/2/2020'] &gt;&gt;&gt; humidity = [11, 22, 33, 44, 55, 66] &gt;&gt;&gt; hours = [0,16,24,0,16,24] &gt;&gt;&gt; df = pd.DataFrame(list(zip(dates, hours, humidity)), ....
<p>You can pass <code>idxmax</code> in <code>transform</code> which will give you the 'max_humidity_idx'.</p> <p>For the 'sixteen_hr_idx' you can spot the rows that equal to 16 and create a dictionary that has as Keys the dates and Values the index which you can <code>map</code> back on your date column:</p> <pre><code...
python|pandas|dataframe
4
351,943
70,949,046
Iterating over all columns of dataframe to find list of strings
<p>Suppose I have the following <code>df</code>:</p> <pre><code>df = pd.DataFrame({ 'col1':['x1','x2','x3'], 'col2':['y1','y2','y3'], 'col3':['z1','z2','z3'], 'col4':['a1','b2','c3'] }) </code></pre> <p>and a list of elements:</p> <pre><code>l = ['x1','x2','y3'] </code></pre> <p>I want to search element...
<p>A much, <em>much</em> more efficient way of doing this would be to use numpy broadcasting.</p> <pre><code>row_mask = (df.to_numpy() == l[:, None, None]).sum(axis=0).any(axis=1) filtered = df[row_mask] </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; filtered col1 col2 col3 col4 0 x1 y1 z1 a1 1 x2 y...
pandas|dataframe|array-broadcasting
3
351,944
70,760,514
Converting Pandas Dataframe column object in MM:SS format to Datetime type?
<pre><code>0 18:30 1 24:50 2 33:21 3 28:39 4 27:30 5 21:26 6 16:42 7 16:48 8 26:07 9 18:13 10 27:15 11 24:33 12 29:43 13 ...
<p>Replace the NaN values using</p> <pre><code>df.fillna('00:00') </code></pre> <p>Followed by:</p> <pre><code>df['Minutes'] = pd.to_datetime(df['Minutes'], format='%M:%S', errors='coerce') </code></pre> <p>Followed by:</p> <pre><code>df.sort_values('Minutes') #Note Ascending is default </code></pre>
python|pandas|dataframe|datetime|timedelta
0
351,945
70,865,929
Tensorflow: Custom data augmentation
<p>I'm trying to define a custom data augmentation layer. My goal is to call the existing tf.keras.layers.RandomZoom, with a probability.</p> <p>This is what I did:</p> <pre><code>class random_zoom_layer(tf.keras.layers.Layer): def __init__(self, probability=0.5, **kwargs): super().__init__(**kwargs) ...
<p>Maybe you could try something like this:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf class random_zoom_layer(tf.keras.layers.Layer): def __init__(self, probability=0.5, **kwargs): super().__init__(**kwargs) self.probability = probability self.layer = tf.k...
python|tensorflow|keras|layer|data-augmentation
2
351,946
70,751,449
How to fix "overflow encounter in exp" when curve fitting data in Scipy?
<p>I'm using Python 3 and I'm trying to find the best fit of the following data set with the exponential function</p> <pre><code>xdata = [329.14, 339.43, 344.13, 347.02, 350.79, 353.54, 355.62, 360.51, 362.36, 364.89, 366.66, 369.0,371.87, 372.91] ydata = [13.03, 20.53, 25.08, 28.38, 33.18, 36.93, 40.13, 48.23, 51.98,...
<p>The problem is the small value for <code>a</code>. The minimization process tries to compensate via <code>b</code> resulting in an overflow. I get good results with starting values <code>p0=( 3.2e6, -4000 )</code> Alternatively, you can define the function to be <code>exp( a - b / t )</code> which the coverges well ...
python|numpy|scipy|curve-fitting
1
351,947
70,886,858
How do I apply a learning rate scheduler lr_scheduler_cls to a DARTS RNNmodel?
<p>I am trying to create an RNN with learning rate scheduler using DARTS and start fitting:</p> <pre><code>rnn_model2_cov = RNNModel(model= 'GRU', hidden_dim=30, input_chunk_length=200, output_chunk_length=100, random_state=42, n_rnn_l...
<p>You are passing <code>optimizer_kwargs</code> and <code>lr_scheduler_cls</code> as you should. See a toy <a href="https://gsamaras.wordpress.com/code/n-beats-randomized-grid-search/" rel="nofollow noreferrer">example</a> with another model from darts which trains without any problem at all:</p> <pre><code>from darts...
python|machine-learning|pytorch|u8darts
0
351,948
70,901,567
How to apply lambda function to specific column based on the values in the adjacent column
<p>I am trying a apply a lambda function to a pandas data frame. My question is how can I apply a lambda function to column a based on value in column b using if statement.</p> <pre><code>A B C 2 5 7 4 5 9 6 7 9 </code></pre> <pre><code>df['B'].apply(lambda x: x+3 if x&lt;(#the value in column C) else x) </code></pre>
<p>You need to call <code>apply</code> <em>on the dataframe, with <code>axis=1</code></em>, instead of on the <code>B</code> column:</p> <pre><code>&gt;&gt;&gt; df.apply(lambda x: x['B']+3 if x['B']&lt;x['C'] else x['B'], axis=1) 0 8 1 8 2 10 dtype: int64 </code></pre> <p>But, a <strong>much</strong> more ef...
python|pandas|if-statement|lambda|apply
4
351,949
70,763,767
ValueError: Input 0 of layer "model" is incompatible with the layer: expected shape=(None, 50), found shape=(None, 1, 512)
<p>Learning to use bert-base-cased and a classification model... the code for the model is the following:</p> <pre><code>def mao_func(input_ids, masks, labels): return {'input_ids':input_ids, 'attention_mask':masks}, labels dataset = dataset.map(mao_func) BATCH_SIZE = 32 dataset = dataset.shuffle(100000).batch(BATCH_...
<p>It seems, that your shape of the train data doen't match the expected input shape of your input layer. You can check your shape of the train data with <code>train.shape()</code></p> <p>You input layer <code>Input_ids = tf.keras.layers.Input(shape=(50,), name='input_ids', dtype='int32')</code> expects train data with...
tensorflow|keras|deep-learning|multiclass-classification
4
351,950
70,888,138
What is pandas' transpose equivalent in Julia
<p>What is <code>pandas</code>' transpose equivalent in <code>Julia</code>? thanks</p> <p>I like to transpose a data frame and <code>transpose</code> function isn't working.</p>
<p>It is <code>permutedims</code>, it turns a data frame on its side such that rows become columns and values in the column become the names.</p>
pandas|julia
5
351,951
71,040,388
PyTorch - Neural Network - Output single scalar value
<p>Let's say we have the following neural network in PyTorch</p> <pre><code>seq_model = nn.Sequential( nn.Linear(1, 13), nn.Tanh(), nn.Linear(13, 1)) </code></pre> <p>With the following input tensor</p> <pre><code>input = torch.tensor([1.0, 1.0, 5.0], dtype=torch.float32).unsqueeze(1) </code></pre> <p>I can run forward...
<p>The first dimension of input represents the number of observations in your minibatch (3), the second dimension represents instead the number of features (1).</p> <p>If you want to forward a single 3d input, the network must be modified (<code>nn.Linear(1, 13)</code> becomes <code>nn.Linear(3, 13)</code>), and you mu...
deep-learning|pytorch|reinforcement-learning
0
351,952
70,967,176
Python change multiple dictionaries to dataframe
<p>I am using jupyter notebook and getting data using API.</p> <p>I have a list of names.</p> <pre><code>names = ['a','b','c','d'] for name in names: df=library.function(name) print(df) </code></pre> <p>Then I get multiple dictionaries.</p> <pre><code>{'name':'a', 'level':2, 'quality': 12} {'name':'b', 'level':...
<p>You can put dictionaries into a list in the loop and then cast to a DataFrame:</p> <pre><code>dicts_list = [] # to hold the dictionaries names = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;] for name in names: new_dict = library.function(name) dicts_list.append(new_dict) # store it # make ...
python|pandas|dataframe|dictionary
2
351,953
71,062,552
Error when running a Graph neural network with pytorch-geometric
<p>I'm trying to get a graph neural network code to run on a cluster (where the code that I used, always used to work perfectly fine up to half a year ago). I have the following versions:</p> <p>python 3.6.9 torch 1.6.0 torch-geometric 2.0.3 torch-scatter 2.0.5...
<p>Upgrade pytorch to 1.7.0. This worked for me.</p>
python|pytorch
0
351,954
70,787,287
Conditionally merge and overwrite pandas DataFrames according to column values
<p>I have two pandas DataFrames:</p> <pre><code>df1: ID count a 20 b 3 </code></pre> <p>and</p> <pre><code>df2 ID Info count a None 1 b 2 2 </code></pre> <p>I would like to merge df2 on df1 such that the values of count in df2 gets overwritten with df1['count'] only if df2 has matching ID but &quot;None&quot; in &quo...
<p>You can merge first then update values:</p> <pre><code>df3 = df2.merge(df1, on='ID', how='left', suffixes=('', '1')) print(df3) # Intermediate output ID Info count count1 0 a None 1 20 1 b 2 2 3 </code></pre> <pre><code>df3 = df3.assign(count=np.where(df3['Info'] == 'None', df3['cou...
pandas|dataframe
-1
351,955
70,833,750
Testing the normality and correlation of the feature and label values
<p>I have a dataset which is being stored in a 2D <code>numpy</code> array. I want to test the normality and correlation of each feature which is a column of the array and then plot it.</p> <p>I know that using R, it can be easily done by running the following commands:</p> <pre><code>shapiro.test(Class$Feature) ggqqpl...
<p>After searching a lot I noticed that using <code>numpy</code> array may not be an appropriate approach to solve this issue. That's why I loaded my data set in a <code>pandas</code> Data Frame and then used the following code:</p> <pre><code>from scipy.stats import shapiro import pylab import scipy.stats as stats def...
python|r|numpy|scipy|data-visualization
0
351,956
71,082,049
how to create monthly and season 24 hours average table using pandas
<p>I have a dataframe with 2 columns: <code>Date</code> and <code>LMP</code> and there are totals of 8760 rows. This is the dummy dataframe:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'Date': pd.date_range('2023-01-01 00:00', '2023-12-31 23:00', freq='1H'), 'LMP': np.random.randint(10, 20,...
<p>try:</p> <pre><code>df['hour']=pd.DatetimeIndex(df['Date']).hour dft = df[['Season', 'hour', 'LMP']] dftg = dft.groupby(['hour', 'Season'])['LMP'].mean() dftg.reset_index().pivot(index='hour', columns='Season') </code></pre> <p>result:</p> <p><a href="https://i.stack.imgur.com/6Hj0e.png" rel="nofollow noreferrer"><i...
pandas|time|pandas-resample
1
351,957
71,009,518
How to compare column values in different dataframes?
<p>I have found this code , and it is working very well.</p> <pre><code>df1 = pd.DataFrame({'c1': [1, 4, 7], 'c2': [2, 5, 1], 'c3': [3, 1, 1]}) df2 = pd.DataFrame({'c4': [1, 4, 7], 'c2': [3, 5, 2], 'c3': [3, 7, 5]}) set(df1['c2']).intersection(set(df2['c2'])) </code></pre> <p>But I need to compare them with multiple ...
<p>You can try with <code>merge</code> follow by <code>drop_duplicates</code></p> <pre><code>df1.merge(df2,on = ['c2','c3'])[['c2','c3']].drop_duplicates() </code></pre>
pandas|dataframe|compare
1
351,958
70,876,254
Pandas column reshaping: aligning the values to the left (ignoring the outside zeros)
<p>I have a set of data, where I predict the amount of fuel I need around 10 weeks ahead. I have it all set up in a single dataframe presented as staircase date. This means, the closer I come to the last entry for a week the more accurate the values get. I want to cut all missing values and ignore the exact date so I c...
<p>Use <code>justify</code> function for remove shift non <code>0</code> values, last remove columns filled only <code>0</code> values:</p> <pre><code>c = [f'W{x + 1}' for x, _ in enumerate(df.columns)] df = pd.DataFrame(justify(df.to_numpy()), index=df.index, columns=c) df = df.loc[:, df.ne(0).any()] print (df) ...
python|pandas|dataframe|data-cleaning
0
351,959
70,840,179
pandas pivot data Cols to rows and rows to cols
<p>I am using python and pandas have tried a variety of attempts to pivot the following (switch the row and columns)</p> <p>Example: A is unique</p> <pre><code> A B C D E... (and so on) [0] apple 2 22 222 [1] peach 3 33 333 [N] ... and so on </code></pre> <p>And I would l...
<p>Think you're wanting <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.transpose.html" rel="nofollow noreferrer">transpose</a> here.</p> <pre><code>df = pd.DataFrame({'A': {0: 'apple', 1: 'peach'}, 'B': {0: 2, 1: 3}, 'C': {0: 22, 1: 33}}) df = df.T print(df) 0 1 A apple peach B...
python|pandas|pivot
1
351,960
70,925,449
Converting a dictionary to DataFrame in python for stocks - ValueError: If using all scalar values, you must pass an index
<p>Need to convert a dictionary to DataFrame in python. <a href="https://i.stack.imgur.com/aa6uh.jpg" rel="nofollow noreferrer">My current attempt and error</a></p> <p>I understand I cannot use Scalar values but the dictionary is getting picked up directly from Yahoo finance API and I need all of that data to be put in...
<p>The error of the code you posted is about the <code>index=[0]</code> argument you pass when you construct the <code>DataFrame</code>.</p> <p>From the official pandas documentation <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.from_dict.html" rel="nofollow noreferrer">site</a>, for creating a...
python|pandas|dataframe
0
351,961
70,760,238
How can I retrieve elements in a multidimensional pytorch tensor by a list of indices?
<p>I have two tensors: <code>scores</code> and <code>lists</code> <br> <code>scores</code> is of shape <code>(x, 8)</code> and <code>lists</code> of <code>(x, 8, 4)</code>. I want to filter the max values for each row in <code>scores</code> <strong>and filter the respective elements from</strong> <code>lists</code>.</p...
<p>I imagine you tried something like</p> <pre class="lang-py prettyprint-override"><code>indices = scores.argmax(dim=1) selection = lists[:, indices] </code></pre> <p>This does not work because the indices are selected for every element in dimension 0, so the final shape is <code>(x, x, 4)</code>.</p> <p>The perform t...
pytorch
3
351,962
70,760,579
Find first occurrence of a substring in a dataframe column
<p>I want to find the first occurrence of a substring in a dataframe's column. I wanted a concise way of doing this so I attempted to use argmax.</p> <p>Take for instance the following dataframe:</p> <pre><code>import pandas as pd #Create dataframe data = { 'Name':['Tom', 'Dick', 'Harry'], 'Mood':['Grum...
<p>You can do that with the following.</p> <pre><code>df.Mood.str.contains(&quot;Happy&quot;).idxmax() </code></pre>
python|pandas|dataframe
1
351,963
70,747,616
how do I succinctly create a new dataframe column based on matching existing column values with list of values?
<p>I want to create a new column in a <code>dataframe</code> by matching the values in an existing column's values with a predefined list of values. I have two approaches to this below. Both run but dont give me exactly what I want. I prefer the first approach over the second but not sure where I am going wrong with bo...
<p>Use <code>str.extract</code>: create a regex pattern of your search words and try to extract the matched pattern:</p> <pre><code>pattern = fr&quot;\b({'|'.join(search_words1)})\b&quot; df3['col4'] = df3['col3'].str.extract(pattern) </code></pre> <p>Pattern:</p> <pre><code>&gt;&gt;&gt; print(pattern) \b(man|red)\b </...
python|pandas|dataframe
1
351,964
70,856,223
How to assign a value to a cell in dataframe A based on a value in dataframe B, conditional on values of two other columns in B?
<p>I'm really amateur-level with both python and pandas, but I'm trying to solve an issue for work that's stumping me.</p> <p>I have two dataframes, let's call them dfA and dfB:</p> <pre><code>dfA: project_id Category Initiative 10 20 30 40 </code></pre> <pre><code>dfB: ...
<p>You could do something like this although it's not very elegant, there must be a better way. I had to use try/except because of the cases where the project Id is not available in the dfB. I put NaN values for the missing ones but you can easily put empty strings.</p> <pre class="lang-py prettyprint-override"><code>d...
python|pandas|numpy
0
351,965
71,005,256
Python/Pandas: Repeat row value for each row in column when multiple conditions are met
<p>I have used pd.wide_to_long() to create a longer df. I want to create a new column called &quot;Bodyweight&quot; that takes the value from the &quot;Load&quot; column when the exercise == &quot;bodyweight&quot; and displays it for each row entry for an athlete on that date. the current layout is:</p> <p>ie</p> <p><s...
<p>Create a boolean mask and <code>transform</code> to broadcast the <code>Load</code> value of <code>Bodyweight</code> to each row of the group:</p> <pre><code>m = df['Exercise'] == 'Bodyweight' bw = df.groupby(['Date', 'Player_Name'])['Load'].transform(lambda x: x[m].max())[~m] out = df.assign(Body_Weight=bw)[~m] pri...
python|pandas
0
351,966
70,876,422
Get proportion of each element of a group by (python)
<p>I would like to make a graph to show the proportion p of each element of a <code>df.groupby</code> result.</p> <p>My data looks like this: <img src="https://i.stack.imgur.com/cNE9o.png" alt="" /></p> <p>I would like to display a bar plot, using the <code>df_country</code> data.</p> <p>for the country CH : p = 920/to...
<p>You could do something like:</p> <pre><code>df_country['norm'] = df_country['nbcountry'] / df_country['nbcountry'].sum() df_country = df_country[['norm', 'country']].set_index('country') df_country.plot.bar() </code></pre> <p>And do the same for the other dataframe.</p>
python|pandas|numpy
1
351,967
70,994,160
How to read a CSV file where rows are quoted into a dataframe
<p>I have a CSV file that looks like this,</p> <pre><code>title 1 &quot;x,y,z,w&quot; &quot;1,2,3,4&quot; title 2 &quot;a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m&quot; &quot;1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7&quot; &quot;1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7&quot; &quot;1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7&quot; &quot;1,2,3,4,5,6,7,8,9,1,2,3,...
<p>Looking carefully through <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html" rel="nofollow noreferrer"><code>pd.read_csv</code>'s (many) options</a>, I can't find a way of removing these quotes during the read, and, thinking about it, I'm not sure there should be one.</p> <p>Quoting is done ...
python|pandas|dataframe|csv
2
351,968
70,996,291
How to find current upper Bollinger band in pandas-ta
<p>I have a CSV file having columns <code>Instrument, Date, Time, Open, High, Low, Close</code> I want the rows having <code>Current close greater than current upper Bollinger band(20,2)</code> I found the function <code>bbands</code> in <code>pandas-ta</code> but I don't know how to compare it with Current close and h...
<p>Run this code instead:</p> <pre><code>currunt_close.ta.bbands(close='Close', length=20, std=2, append=True) pd.set_option(&quot;display.max_columns&quot;, None) # show all columns </code></pre> <p><code>BBU_20_2.0</code> is what you looking for!</p>
python|pandas|pandas-ta
1
351,969
70,941,749
Handle NaN values (zero value) in datetime.strptime in a converter used in pd.read_fwf
<p>I have a source file which is length-delimited. My file looks as follows:</p> <pre><code>00;12345678;03122019 01;12345678;00000000 </code></pre> <p>My code so far is as follows:</p> <pre><code>import pandas as pd from datetime import datetime col_lengths = {'Column1': range(0, 2), 'Column2': range(3...
<p>You could use <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>pandas.to_datetime</code></a> as converter:</p> <pre><code>#converters={... 'Datecolumn': lambda s: pd.to_datetime(s, format='%d%m%Y', errors='coerce'), # } </code></pr...
python|pandas|python-datetime|converters|strptime
0
351,970
71,073,567
Trying to create Dataframe from lists of zip using Pandas. wanted data table result
<p>I'm scraping website and come to the part where to put it in Dataframe. I tried to follow <a href="https://stackoverflow.com/a/42049158/17470235">this answer</a> but no expected output.</p> <p>Here's my whole code</p> <pre><code>#driver chrome def website = 'https://www.bitkub.com/fee/cryptocurrency' path = r&quot;C...
<p>Some how coin_name is twice as long as your other lists. Once you fix that you can do this:</p> <pre><code>pd.DataFrame({'coin_name': coin_name[0:81], 'chain_name': chain_name, 'withdrawal_fees':withdrawal_fees}) coin_name chain_name withdrawal_fees 0 Civic(CVC) ETH (ERC20) 97.000000...
python|pandas|dataframe|web-scraping
1
351,971
70,802,375
Inserting pandas_market_calendars time value into pandas timestamp value
<p>With the <code>start_of_day()</code> function below, I'm attempting to return timestamps of the NYSE market open date and time for the current week. I am not using this in a pandas dataframe, I'm just using pandas time functions because they're some of the only functions that I've found that are specific to market ...
<p>Solution:</p> <pre><code>pandas.DateOffset(hour=nyse.open_time.hour, minute=nyse.open_time.minute, second=nyse.open_time.second) </code></pre> <p>Original question updated.</p>
python|pandas
0
351,972
70,886,317
How to reverse the legends of stacked barplot in pandas
<p>I have a dataset with a few records about some crop production by year. So I am visualizing the top produced crop by each year in a stacked bar chart. Dataset I have used can be found in <a href="https://www.kaggle.com/pyatakov/india-pmfby-statistics" rel="nofollow noreferrer">kaggle PMFBY Coverage.csv</a>.</p> <p>...
<p>First off, the same 5 crops need to be selected each year. Otherwise, you can't have a fixed ordering on the y-axis.</p> <p>The easiest way to get a plot with the <em>overall</em> 5 most-frequent crops, is seaborn's <code>sns.countplot</code> and limiting to the 5 largest. Note that seaborn is strongly objected to s...
python|pandas|matplotlib|seaborn|data-visualization
2
351,973
71,083,386
How to skip lines when reading a file with numpy.fromfile?
<p>I am reading a <code>.pksc</code> file that contains coordinates and velocities of a large number of astronomical objects. I am doing the reading with</p> <pre><code>import numpy as np f=open('halos_10x10.pksc') data = np.fromfile(f,count=N*10,dtype=np.float32) </code></pre> <p>The file can be found <a href="https:...
<p>If all you need is to chunk the big files into smaller files, so that you can operate on them independently:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np Nrecords_per_chunk = 100_000 Nitems_per_record = 10 f_in = open('halos_10x10.pksc', 'rb') headers = np.fromfile(f_in, dtype=np.int32, c...
python|numpy|file-read|fromfile
1
351,974
70,744,911
Python - pandas converts MS SQL date to nvarchar
<p>My python code runs <code>read_sql...</code> method on a sample MS SQL Server query.</p> <p>One of the columns - <code>system_type_name</code> - indicates type <code>date</code> while running in SSMS.</p> <p><a href="https://i.stack.imgur.com/YIbyM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y...
<p>The ancient &quot;SQL Server&quot; driver returns a string representation for several T-SQL types. Newer ODBC drivers return more specific types. For example:</p> <pre class="lang-py prettyprint-override"><code># with DRIVER=SQL Server # print(type(crsr.execute(&quot;SELECT CAST('2022-01-17' AS DATE) AS d&quot;).fet...
python|sql-server|pandas|pyodbc
2
351,975
51,799,234
Why does my code throwing KeyError: 'epochs' when I implemented Fully Convolutional Networks by Keras
<p>I am trying to implement FCN by TensorFlow, and I used Keras. After first epoch training , I got this error:</p> <p><img src="https://i.stack.imgur.com/rAVUo.png" alt="KeyError:&quot;epochs&quot;"></p> <p>I think it should be related to ModelCheckpoint() and model.fit(), because when I delete callbacks in model.fi...
<p>Since you get the error at the end of first epoch, it may be due to your ModelCheckpoint callback: you have placed the first <code>}</code> at the wrong place!</p> <p>Try </p> <pre><code>model_checkpoint = ModelCheckpoint('fcn32_weights.{epoch:02d}-{val_loss:.2f}.h5', monitor='val_loss', save_best_only=True) </cod...
python|tensorflow|machine-learning|keras|conv-neural-network
1
351,976
51,779,354
How does Reflection/Mirroring padding work? In numpy or in general?
<p>I am running the following against a vector say [1,2,3]. The first 2 of them I can explain. Each additional padded coordinate is mirrored around the last element (3). However after that I can't. </p> <p>There's definitely a cycle of 4 here which means a <code>mod of 2*(len(a) -1)</code>.</p> <p>I'd appreciate if s...
<p>Imagine stepping through the original array, and every time you hit a boundary you go the other direction.</p> <p>When you progress to the right and get to the end, you reflect and start iterating back to the beginning. When you progress to the left and get to the beginning, you reflect and start iterating back to ...
numpy|padding
3
351,977
51,685,606
conversion of elements in dataframe to string
<p>I want to convert bytes to string in dataframe.</p> <pre><code>data['CleanedText'].head() 0 b'witti littl book make son laugh loud recit c... 1 b'grew read sendak book watch realli rosi movi... 2 b'fun way children learn month year learn poem... 3 b'great littl book read nice rhythm well good ... 4 b...
<p>You can use <code>apply()</code> plus <a href="http://book.pythontips.com/en/latest/lambdas.html" rel="nofollow noreferrer">Lambda functions</a>:</p> <pre><code>data['newtext'] = data['CleanedText'].apply(lambda x: x.decode('utf-8')) </code></pre>
python-3.x|pandas|numpy|dataframe
0
351,978
51,931,800
Store row from matrix to column in another matrix by indexes vector
<p>Assume that I have the matrix A, zero matrix B and indices vectors i,idx:</p> <pre><code>A = np.array([[1, 1, 2], [0, 0, 1]]) B = np.array([[0, 0], [0, 0], [0, 0]]) i = np.arange(len(idx)) idx = np.array([1, 0]) </code></pre> <p>By <code>i</code> and <code>idx</code> I know that I need to store the <strong>0 r...
<p>You were close in your proposed solution:</p> <pre><code>B[:,idx] = A[i,:].T </code></pre>
python|numpy|matrix|indexing
0
351,979
51,596,740
Connecting points by overlapping indices
<p>I have a large list of arrays containing points with x and y coordinates. Each point also has it's own unique identifier. The arrays are arranged in a time sequence (each array is a single frame of a movie and the points represent "objects" in the movie). Some points appear on several frames, with slightly different...
<p>Something like this?</p> <pre><code>&gt;&gt;&gt; my_array = np.array([[np.nan,1,2],[2,3,4],[4,5,6]]) &gt;&gt;&gt; pd.Series(my_array.ravel()).drop_duplicates().values array([nan, 1., 2., 3., 4., 5., 6.]) </code></pre>
python|pandas|object|tracking
0
351,980
51,744,093
Build numpy matrix from a dictionary with coordinate and value
<p>Hi guys I'm trying to build a Numpy matrix from two dictionary. First dict has an integer key and a float64 value; the other one has coordinate as key and a integer value references to key of the first dict.</p> <p>The goal is to build a Numpy matrix with coordinate the key in the second dict and value the float va...
<p>Given your <code>dict_coord</code> keys are always sorted in that way, you can simply transform both dicts to arrays and then index one with the other:</p> <pre><code>coord_array = np.asarray(list(dict_coord.values())) values_array = np.asarray(list(dict_values.values())) values_array[coord_array].reshape(3, 3) # ...
python|numpy|dictionary|matrix
1
351,981
51,980,407
How to prepare warmup request file for tensorflow serving?
<p>Current version of tensorflow-serving try to load warmup request from assets.extra/tf_serving_warmup_requests file. </p> <blockquote> <p>2018-08-16 16:05:28.513085: I tensorflow_serving/servables/tensorflow/saved_model_warmup.cc:83] No warmup data file found at /tmp/faster_rcnn_inception_v2_coco_2018_01_28_string...
<p>At this point there is no common API for exporting the warmup data into the assets.extra. It's relatively simple to write a script (similar to below):</p> <pre><code>import tensorflow as tf from tensorflow_serving.apis import model_pb2 from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis imp...
tensorflow|tensorflow-serving|inference
8
351,982
51,698,748
pandas change dtypes only columns of float64
<p>I need to change the dtype of multiple columns (over 400) but the dataframe has different kind of dtypes. Some columns dtypes are <code>float64</code> whereas some columns' are <code>int64</code> or <code>object</code>:</p> <pre><code>print my_df.dtypes </code></pre> <p><strong>Output:</strong></p> <pre><code>x1 ...
<p>Ok, I find my way :)</p> <p>Find the columns that have dtype of <code>float64</code></p> <pre><code>cols = my_df.select_dtypes(include=[np.float64]).columns </code></pre> <p>Then change dtype only the <code>cols</code> of the dataframe.</p> <pre><code>my_df[cols] = my_df[cols].astype(np.float32) </code></pre>
python|pandas
11
351,983
51,787,548
regarding keep rows where one column value satisfy certain constraints
<p>There has a dataframe, one column, e.g., 'cost', have some zero/empty entries, I would like to keep the rows whose 'cost' column are not zero/empty. How to do it in Pandas?</p>
<p>You have to perform two filters, first drop the nan values:</p> <pre><code>df.dropna(subset = ['cost'],inplace = True) </code></pre> <p>And then drop the zeros values as well:</p> <pre><code>df = df.loc[df.cost != 0] </code></pre>
python-3.x|pandas
1
351,984
51,854,463
is it possible to retrain a previously saved keras model?
<p>i'm working in a time series prediction using keras and tensorflow. I need to retrain the model with future data. My question is, is this possible in keras and how we can do that?</p>
<p>yes.</p> <p>Save your model as .h5</p> <p>When you want to train your model, load it again and do a model.fit as normal.</p> <p>Make sure you do not compile your model after loading it as this will reset your weights.</p> <p>See this <a href="https://stackoverflow.com/questions/42666046/loading-a-trained-keras-m...
python|tensorflow|neural-network|keras
21
351,985
51,826,090
no module error when using numpy-1.15.0
<p>I am trying to compile a python program where I am using numpy.random.choices(). once I compile I get this one error: </p> <blockquote> <p>ImportError: No module named 'numpy'</p> </blockquote> <p>I read That I have to install numpy package. I did install numpy-1.11.1 it didn't work. I get the same error. I upgr...
<p>you are installing numpy from pip for python 2.x but you are working with python 3.x</p> <p>to solve your problem download pip3 and download numpy from it.</p> <p>In the solution below I used <code>python3.4</code> as binary, but it's safe to use with any version or binary of python. it works fine on windows too (...
python|numpy
1
351,986
51,964,256
Python: group by the dictionary keys and then need to perform the sum operation
<p>input={1:5,2:8,9:3,11:4,18:3,21:4,3:8,350:5}</p> <p>and I would like to do the group by operation and perform the sum operation on </p> <p>the value of that dictionary.</p> <p>like grp_1=1,11,21 ; grp_2=9,3,18 ; grp_3= 2</p> <p>and output should like as below</p> <p>grp_1= 13 (5+8+8 dict values)</p> <p>grp_2= ...
<p>First off:</p> <p>Use python 3.x not python 2.x as python 2 is dying out: <a href="https://pythonclock.org/" rel="nofollow noreferrer">https://pythonclock.org/</a></p> <p>In python 3 it is best to use the CSV library by using:</p> <pre><code>import csv </code></pre> <p>and then read in the values you have. </p> ...
python|matplotlib|pandas-groupby|xlrd
0
351,987
51,641,558
Returning the index value when using groupby
<p>Im using grouby to rearrange a dataframe that has a date time index and I'd like to be able to return the datetime index value at the first grouping. For example, if I group by the Number column, i'd like to return the index value at the first instance of each number. I'm able to use the Trade Type with the .iat[0] ...
<p>This is <code>head</code></p> <pre><code>df.groupby('Number').head(1) </code></pre>
python|pandas|numpy|dataframe|group-by
3
351,988
51,597,507
sklearn TimeSeriesSplit Error: KeyError: '[ 0 1 2 ...] not in index'
<p>I want to use TimeSeriesSplit from sklearn on the following dataframe to predict sum: <a href="https://i.stack.imgur.com/sVQiG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sVQiG.jpg" alt="dataframe"></a></p> <p>So to prepare X and y I do the following:</p> <pre><code>X = df.drop(['sum'],axis=...
<p>As @Jarad rightly said, if you have updated version of pandas, it will not automatically switch to integer based indexing as was possible in previous versions. You need to explicitly use <code>.iloc</code> for integer based slicing. </p> <pre><code>for train_index, test_index in tscv.split(X): X_train01, X_test...
pandas|scikit-learn|time-series|sklearn-pandas|train-test-split
7
351,989
51,597,849
Padding a numpy array with offsets for each data column
<p>I'm working with 2D numpy arrays which exhibit variable sizes, in terms of the number of rows and columns. I'd like to pad this array with zeros both before the start of the first row and at the end of the last row, but I'd like the start/end of the zeros to be offset in a different way for each column of data. </p>...
<p>Here's a vectorized one with <code>broadcasting</code> and <code>boolean-indexing</code> -</p> <pre><code>def create_padded_array(a, row_start, n_rows): r = np.arange(n_rows)[:,None] row_start = np.asarray(row_start) mask = (r &gt;= row_start) &amp; (r &lt; row_start+a.shape[0]) out = np.zeros(mask...
python|arrays|performance|numpy
4
351,990
51,885,687
Training c3d on Keras. Training slows down mid epoch and ETA climbs up
<p>I am trying to train c3d on keras (v2.2.0) </p> <p>Hyper-parameters and info:</p> <ol> <li>Batch Size - 32</li> <li>Number of Keras workers for generator - 32 (with max_queue_size = 30)</li> <li>Amazon EC2 p3.8xlarge machine</li> <li>Num GPU 4 </li> <li>One Data Point numpy dimension: (90x80x80x3)[video of sequenc...
<p>I have experienced that on multi-gpu-model if you have increase worker ETA will increase. I think you shall limit the number of workers maybe 2 or 4 depending upon your CPU power and increase batch size four times. </p> <p>Since batches are load by the CPU and if you updating weights on CPU then check its utilizati...
tensorflow|keras|deep-learning|conv-neural-network|nvidia
0
351,991
51,949,683
How to convert miliseconds to datetime with format: mm:ss:msmsms (minutes:seconds:miliseconds) without year , month an day
<p>Is there a simple way to convert milliseconds in a dataframe to a datetime without year, month and day?</p> <p>I have successfully converted a column of milliseconds to datetime. However, I want to get rid of the year, months and days.</p> <p>I did this:</p> <pre><code>df['Laptimes'] = pd.to_datetime(df['millisec...
<p>Just call the time() method on the datetime object:</p> <pre><code>df['Laptimes'].time() </code></pre>
python|pandas|datetime|dataframe
0
351,992
51,762,426
how to change hsv tensor into rgb tensor in tensorflow?
<p>I need to an op which can convert HSV tensor (shape:<code>[batch_size, image_width, image_height, num_channels]</code>,channels means <code>h, s, v</code>) into RGB tensor(<code>[batch_size, image_width, image_height,num_channels]</code>, channels means r, g, b]). And I know the existed <code>tf.image.hsv_to_rgb</co...
<p>Currently the HSV to RGB conversion function has no registered gradient, you could consider <a href="https://github.com/tensorflow/tensorflow/issues" rel="nofollow noreferrer">opening an issue</a> about it. However, looking at the <a href="https://github.com/tensorflow/tensorflow/blob/v1.10.0/tensorflow/core/kernels...
python|tensorflow
1
351,993
51,700,754
How to identify text related to a particular dynmamic value in Pandas/Python
<p>I have the following 2 columns in my dataframe:</p> <pre><code>COL1 COL2 12 :402:agshhhjd:45:hghghgruru:12:fghg,hgh:22:hhhh 57 :42:ags,hhhjd:57:hghg,hgruru:120:fghgh,gh:12:hhhhhh </code></pre> <p>I need to create another column COL3 which sould be like below:</p> <pre><code> COL1 COL2 ...
<p>You can just use the attribute <code>replace</code>, but first you have to change the datatype of column 1. we need to replace everything that is in COL2 save the wordings after the number in COL1 ie:</p> <p><code>.*12:(\w{7}).*</code> So we just capture the seven letters and call them by back reference ie value =...
python|python-3.x|pandas
3
351,994
51,809,076
Element-wise operations of arrays of different size
<p>What would be the fastest and most pythonic way to perform element-wise operations of arrays of different size without oversampling the smaller array?</p> <p>For example: I have a large array, A 1000x1000 and a small array B 10x10 I want each element in B to respond to 100x100 elements in array B. There is no need ...
<p>I had a similar problem, and ended up solving it like this :</p> <pre><code>import numpy as np import numba as nb import time @nb.jit(nb.void(nb.float64[:,:], nb.float64[:,:]), nopython=True, cache=True) def func(A, B): # Assume different resolution along the different axes res_row = B.shape[0]//A.shape[0]...
python|arrays|numpy|dask|python-xarray
3
351,995
51,993,599
unable to run print statements from loss function when calling model.fit in Keras
<p>I have created a custom loss function called </p> <p><code>def customLoss(true, pred) //do_stuff //print(variables) return loss</code></p> <p>Now I'm calling compile as <code>model.compile(optimizer='Adamax', loss = customLoss)</code></p> <p>EDIT: I tried tf.Print and this is my result.</p> <pre><code> def ...
<p>It's not because Keras dumps buffers or does magic, it simply doesn't call them! The loss function is called once to construct the <em>computation graph</em> and then the symbolic tensor that represents the loss value is returned. Tensorflow uses that to compute the loss, gradients etc.</p> <p>You might instead be ...
python|tensorflow|neural-network|keras
2
351,996
51,585,502
when to use iloc and loc for boolean
<p>I'm a bit confusing when using boolean series for indexing for pandas Dataframe. Should I use iloc or loc? or any better solution? for example</p> <pre><code>t1 = pd.DataFrame(np.ones([3,4])) t1.iloc[1:3,0]=3 </code></pre> <p>this line will give correct answer</p> <pre><code>t1.loc[:,(t1&gt;2).any()] </code></pre...
<p>The nuance is that <code>iloc</code> requires a Boolean <strong>array</strong>, while <code>loc</code> works with either a Boolean series or a Boolean array. The documentation is technically correct in stating that a Boolean array works in either case.</p> <p>So, for <code>iloc</code>, extracting the NumPy Boolean ...
python|pandas|indexing
5
351,997
51,710,987
select some columns in a pandas dataframe
<p>I have two data frames with many columns, D1 (with columns: V1_1, V1_2....) and D2 (with columns: V2_1, V2_2...). But I'm not interested in all the columns, I only want the columns that other third data frame indicates. This third data frame has two columns, the first one is the name of a data frame, and the second ...
<p>Your question is unclear. But if you want the names of columns from DataFrame D1 (stored separate, then you could try:</p> <p>D1.columns</p> <p>If this is not what you seek, then giving a snippet of your code might help.</p>
python|pandas|dataframe|select
0
351,998
51,782,085
How to reorder columns according to a list of new positions
<p>I have a pandas data frame of dimensions (7096, 94), each index has a name. I want to reorder the columns with that list of positions/locations :</p> <pre><code>[92, 57, 73, 81, 62, 64, 18, 93, 63, 89, 56, 72, 78, 26, 28, 79, 40, 54, 55, 53, 27, 21, 70, 25, </code></pre> <p>51, 7, 36, 23, 15, 59, 71, 0, 5, 91, ...
<pre><code>cols = [92, 57, 73, 81, 62, 64, 18, 93, 63, 89, 56, 72, 78, 26, 28, 79, 40, 54, 55, 53, 27, 21, 70, 25, 51, 7, 36, 23, 15, 59, 71, 0, 5, 91, 39, 67, 90, 77, 86, 2, 61, 69, 82, 46, 47, 45, 85, 75, 83, 6, 88, 65, 34, 52, 4, 8, 29, 38, 35, 33, 60, 84, 80, 49, 24, 13, 3, 14, 12, 68, 16, 17, 41, 31, 10, 87, 32, 1...
python|pandas
2
351,999
51,840,206
Filling Null Values
<p>I have two dataframes . One dataframe has a column - 'CUSIP' that has a lot of Null Values. where the columns look like this</p> <pre><code>|Date |Ticker |RP_ID |CUSIP |SEDOL |&lt;br/&gt; </code></pre> <p>Another dataframe has two columns 'Ticker ' And 'CUSIP' that looks like this <br/> |Ticker |CUSIP|<br/><br...
<pre><code>&gt;&gt;&gt; pandas.merge(a,b, how='left', on='Ticker', suffixes=('_', '')).drop(['CUSIP_'], axis=1) </code></pre> <p>where</p> <pre><code>a = pandas.DataFrame({'Ticker': ['A0', 'A1', 'A2', 'A3'], 'CUSIP':[None, None, None, None]}) b = pandas.DataFrame({'Ticker': ['A0', 'A1', 'A2', 'A3'], 'CUSIP':['I1', 'I...
python|pandas|dataframe
0