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 |
|---|---|---|---|---|---|---|
363,400 | 49,232,433 | How to call one model in the other in Keras? | <p>My model structure showed below.</p>
<p>I have built the <code>model_1</code> and get the <code>loss_1</code>. Further more, I tried to add the predicting process of <code>pretrained_model</code> in function <code>get_loss()</code> where I can get <code>out_1</code>. And I want to make the sum of <code>loss_1</code... | <p>You have to build your keras model with 2 outputs.
If you compile a model with multiple outputs the compile function will take as loss parameter a list of loss function which should be the same length as the list of your outputs to init the model class(2 in your case).</p>
<p>During training the loss functions 'wil... | python|tensorflow|keras | 0 |
363,401 | 49,214,921 | Tensorflow error: ValueError: None values not supported | <p>This is my test code. But it could not run. Terminal always gave me this error:</p>
<blockquote>
<p>Traceback (most recent call last):<br>
File "desktop/test.py", line 28,
in loss =tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1])).<br>
File "/Users/sumeixu/anaconda3/lib/python3.... | <p>So I ran your code and It works just fine, after I fixed the indent in your first function. If I just copy paste it as you wrote it, I also get the None error (since you return nothing from the function). So just solve the indent and it should work!</p>
<p>To get the loss you can just fetch the value as follows:</p... | python|python-3.x|tensorflow | 3 |
363,402 | 49,304,974 | how to Find unique values in a column?Attribute Error: "DataFrame" object has no attribute | <p>I am making a generic tool which can take up any csv file.I have a csv file which looks something like this. The first row is the column name and the second row is the type of variable.</p>
<pre><code>Time,M1,M2,M3,CityName
temp,num,num,num,city
20-May-13,19,20,0,aligarh
20-May-13,25,42,7,agra
20-May-13,23,35,4,ali... | <p><code>unique</code>+<code>tolist</code></p>
<pre><code>column_work.CityName.unique().tolist()
Out[87]: ['aligarh', 'agra', 'allahabad']
</code></pre> | python-3.x|pandas|csv|numpy|unique | 2 |
363,403 | 49,310,729 | tensorflow dataset shuffle examples instead of batches | <p>How do I get a tensorflow dataset in batch mode to shuffle across all the samples? It is only shuffling the batches. </p>
<p>Below is a program that makes a dataset of 1000 items and goes through 10 epochs of it in batches of 5. I have <code>shuffle()</code> turned on. I can see that tensorflow groups the dataset i... | <p>ah, the order of batch and shuffle matters, if I set up the dataset like</p>
<pre><code>dataset = tf.data.TFRecordDataset(tfrec_output_filename) \
.shuffle(2*N) \
.batch(batch_size) \
.repeat(epochs) \
.map(parse_example, num_parallel_calls=2)
</co... | tensorflow | 2 |
363,404 | 48,971,233 | Creating array clusters in numpy dynamically | <p>I am grouping items and make tests on these groups. I use the following code segment to group 10 items into 3 groups.</p>
<pre><code># grouping into 3 clusters and getting the distribution of the elements
node_cluster_labels = sm.cluster(n_clusters=3)
data_cluster_labels =node_cluster_labels[bmus]
print(data_clus... | <p>Here is a Vectorized solution that uses the number of unique items within <code>cluster_labels</code> to clusters your array.</p>
<pre><code>def clustering(array, cluster_labels):
data_cluster_labels = cluster_labels
u = np.unique(data_cluster_labels)
x, y = np.where(u[:, None] == data_cluster_labels)
... | python|arrays|python-3.x|numpy | 0 |
363,405 | 49,122,357 | Port Upgrade Outdated fails with "Failed to patch py26-numpy" | <p>Xcode: Version 9.2 (9C40b)
OSX: 10.13.3</p>
<p>I ran port self update first and then port upgrade outdated:</p>
<pre><code>MrMuscle:Desktop mnewman$ port version
Version: 2.4.2
MrMuscle:Desktop mnewman$ sudo port -v upgrade outdated
---> Computing dependencies for py26-numpy.
---> Applying patches to py2... | <p>As the last line of the output says:</p>
<pre><code>Follow https://guide.macports.org/#project.tickets to report a bug.
</code></pre>
<p>When was numpy last working for you?</p> | python|numpy|macports | 0 |
363,406 | 49,007,149 | Got an error when trying to import Tensorflow in Anaconda | <p>I installed tensorflow with pip3, then validated it with</p>
<pre><code># Python
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
</code></pre>
<p>And all works fine in terminal. However, when i try to import tensorflow in Anaconda it throws up an error:<... | <p>Search for <em>Anaconda Prompt</em> from the <em>Start</em> menu. Right click on it and select <em>Run as Administrator</em>. In the terminal that opens up, type:</p>
<pre><code>conda install tensorflow
</code></pre>
<p>This worked for me.</p> | python|tensorflow|anaconda | 2 |
363,407 | 48,956,789 | Converting NaN in dataframe to zero | <p>I have dictionary and created Pandas using
cars = pd.DataFrame.from_dict(cars_dict, orient='index')
and
sorted the index (columns in alphabetical order<br>
cars = cars.sort_index(axis=1)
After sorting I noticed the DataFrame has NaN and I wasn't sure
if the really np.nan values?
print(cars.isnull().any()) and all... | <p>Either use <code>replace</code> or <code>np.where</code> on the values if they are strings: </p>
<pre><code>df = df.replace('NaN', 0)
</code></pre>
<p>Or,</p>
<pre><code>df[:] = np.where(df.eq('NaN'), 0, df)
</code></pre>
<p>Or, if they're actually NaNs (which, it seems is unlikely), then use <code>fillna</code>... | python|pandas|dataframe|replace|nan | 27 |
363,408 | 49,264,353 | Eval only emitting on training begin and training end on CloudML | <p>Using the code below - eval only runs twice (begin and end) when training on CloudML. I would expect this eval at least every 10 seconds.</p>
<p>If I run the same code locally this behaves as expected. </p>
<p>eval_spec = tf.estimator.EvalSpec(
input_fn = read_dataset('{}/test*'.format(OUTPUT_... | <p>I figured this out. When running in CloudML the underlying checkpoint config is overridden differently than when running locally say in Datalab.</p>
<p>Setting:
my_checkpointing_config = tf.estimator.RunConfig(save_checkpoints_secs = 1*60, keep_checkpoint_max = 3)</p>
<p>On your estimator's congfig property fixe... | tensorflow|google-cloud-ml | 1 |
363,409 | 49,093,426 | Are there hidden layers in an LSTM network cell aside from the input? | <p>For an LSTM cell, we have three type of input: Cell state and hidden state from last cell, input vector for current state input.</p>
<p>Aside from these three input layer that we are certain for the vector size, there are some functional layers contained in LSTM cell: Sigmoid layer, Tanh layer, and some vector opera... | <p>I am doubt about your explanation about the weight matrix. In my understanding we are using the below matrix.</p>
<pre><code>Input - order n
State / Output - order h
four input Matrix having order h X h+n
four output matrix having order h X h
</code></pre>
<p>In the backpropagation, we have to use the below ma... | tensorflow|neural-network|lstm | 0 |
363,410 | 49,070,668 | Amazon Fine Foods: Convert text file to pandas DataFrame | <p>I have data in a text file in this format. </p>
<p><a href="https://i.stack.imgur.com/ns5z4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ns5z4.png" alt="Text File Screen Shot"></a></p>
<p>I want to read it as a <code>pandas dataframe</code>. It should look like this</p>
<p><a href="https:/... | <p>I've downloaded a file you mentioned, and could read it to DataFrame with 568455 records and 13 columns with this code:</p>
<pre><code>import pandas as pd
with open('finefoods.txt','r', encoding='latin-1') as f:
data = f.read()
df=pd.DataFrame([
{line.split(': ')[0]:': '.join(line.split(': ')[1:])
for... | python|pandas | 0 |
363,411 | 49,130,834 | How to iterate over column values for unique rows of a data frame with sorted, numerical index with duplicates in pandas? | <p>I have a pandas <code>DataFrame</code> with the sorted, numerical index with duplicates, and the column values are identical for the same values of the index in the given column. I would like to iterate through the values of the given column for the unique values of the index.</p>
<p>Example</p>
<pre><code>df = pd... | <p>First remove duplicated index by mask and assign positions by <code>arange</code>, then select with <code>iloc</code>:</p>
<pre><code>arr = np.arange(len(df.index))
a = arr[~df.index.duplicated()]
print (a)
[0 2]
for i in a:
cell_value = df['a'].iloc[i]
print(type(cell_value))
<class 'numpy.int64'>
... | python|pandas|dataframe|iteration | 2 |
363,412 | 59,035,523 | TypeError: 'str' object is not an iterator | <p>I am trying to run a basic CNN on using macOS Anaconda.
All Keras ati is up to date (atleast i think so, but im sure it is)</p>
<p>I am able to run everything except for when i need to run this line,</p>
<pre><code>classifier.fit_generator('training_set',
steps_per_epoch = 8000,
... | <p>You are passing a string as a first argument, you want to pass the training_set variable.</p>
<pre><code>classifier.fit_generator(training_set,
steps_per_epoch = 8000,
epochs = 25,
validation_data = test_set,
validat... | python|tensorflow|keras|deep-learning | 4 |
363,413 | 58,933,422 | How to add a column from csv file in to array with framework pandas | <p>I have a CSV file <a href="https://i.stack.imgur.com/Qz4G9.png" rel="nofollow noreferrer">thnigs.csv</a> which has 2 columns : <strong>thing</strong> and <strong>date</strong>. I need to import data from CSV file in to arrays as below:</p>
<p><strong>things = [ ]</strong> <strong>thing</strong> column data from C... | <p>Try <code>.values</code>:</p>
<pre><code>things = df['things'].values
date = df['date'].values
</code></pre> | python|pandas | 1 |
363,414 | 58,912,802 | Extract values from two columns of a dataframe to make a dictionary of keys and values | <p>I have a dataframe containing several columns of data. If there are two columns 'reaction' and 'abundance'. There are multiple times each of these will show such as: </p>
<pre><code> reaction product abundance 1.0 1.5 2.0 2.5 3.0 3.5 4.0 ... \
0 023Na-a 010020.tot 1 0 0 0 0 0 0 0 .... | <pre><code>import pandas as pd
data = [['023Na-a', '010020.tot', 1, '...'],
['023Na-a', '012023.tot', 1, '...'],
['035Cl-a', '010022.tot', 0.3775, '...'],
['035Cl-a', '008018.tot', 0.3775, '...'],
['037Cl-a', '013025.tot', 0.1195, '...']]
df = pd.DataFrame(data, columns=['reaction'... | python|pandas|dictionary | 5 |
363,415 | 59,004,960 | Converting Date Format in a Dataframe from a CSV File | <p>I need to convert the date format of my csv file into the proper pandas format so I could sort it later on. My current format cannot be interacted reasonably in pandas so I had to convert it.</p>
<p>This is what my csv file looks like:</p>
<pre><code>ARTIST,ALBUM,TRACK,DATE
ARTIST1,ALBUM1,TRACK1,23 Nov 2019 02:08
... | <p>There are many options to the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer">read_csv</a> method.
Make sure to read the data in in the format you want instead of fixing it later.</p>
<pre><code>df = pd.read_csv('mycsv.csv"', parse_dates=['DATE'])... | python|pandas|csv|dataframe | 1 |
363,416 | 58,891,182 | Calculating number of entries in pandas dataframe below 0 | <p>I have a pandas dataframe with many columns of which some are numerical and other categorical.</p>
<p>I want to calculate the number of negative entries in the pandas dataframe. One way is to find which columns are numeric, subset these columns and then use simple syntax to calculate number of entries with negativ... | <p>You can use a <em>ternary operator</em> here:</p>
<pre><code>data.apply(lambda x: <b>(x < 0).sum() if (x.dtype in ('int16', 'float16')) else 0</b>).sum()</code></pre>
<p>We thus return <code>0</code> (the neutral element of the (ℕ, +, 0) monoid) for non-numerical values.</p>
<p>Note that there are more ... | python-3.x|pandas|if-statement|lambda|apply | 3 |
363,417 | 59,009,865 | Why is tensorflow having a worse accuracy than keras in direct comparison? | <p>I made a direct comparison between TensorFlow vs Keras with the same parameters and the same dataset (MNIST).</p>
<p>The strange thing is that Keras achieves 96% performance in 10 epochs, while TensorFlow achieves about 70% performance in 10 epochs. I have run this code many times in the same instance and this inco... | <p>I think it's the initialization that's the culprit. For example, one real difference is that you initialize bias in TF with <code>random_normal</code> which isn't the best practice, and in fact Keras defaults to initializing the bias to zero, which is the best practice. You don't override this, since you only set <c... | tensorflow|machine-learning|keras|deep-learning|image-recognition | 3 |
363,418 | 58,759,714 | Passing Numpy array to C with Ctypes differs between Linux and Windows | <p>I am trying to pass a Numpy array into C, but get different results in Windows and Linux.</p>
<p>In Python</p>
<pre><code>import platform
import numpy as np
import ctypes
if platform.system() == 'Windows':
c_fun = np.ctypeslib.load_library("/mypath/c_fun.dll", ".").c_fun
else: # Linux
c_fun = np.ctypes... | <p>First, don't use <code>numpy.int</code>. It's just <code>int</code>, not any sort of NumPy thing. I think it's there for backward compatibility.</p>
<p>NumPy converts Python ints to dtype <code>numpy.int_</code> (note the underscore) by default, and <code>numpy.int_</code> corresponds to C <strong><code>long</code>... | python|numpy|ctypes | 2 |
363,419 | 59,003,098 | Implementing periodic boundary conditions in multidimensional grid | <p>I try to implement an algorithm that finds the neighbours of a point in N-dimensional grids with periodic boundary conditions. </p>
<p>For example I have a cubic 3D grid with Length = 3 (3x3x3), so I have 27 points. Every point gets assigned to an index via <code>numpy.ravel_multi_index</code>(see picture).
Now I w... | <p>The easiest way is to unravel - do the neighbours - ravel:</p>
<pre><code>def nneighbour(index,dim,length):
index = np.asarray(index)
shp = dim*(length,)
neighbours = np.empty((*index.shape,dim,dim,2),int)
neighbours.T[...] = np.unravel_index(index,shp)
ddiag = np.einsum('...iij->...ij',neigh... | python|numpy|indexing|grid | 1 |
363,420 | 58,830,822 | Output dimension of a custom LSTM model in Pytorch | <p>I have a custom LSTM model in PyTorch like below:</p>
<pre><code>hidden_size = 32
num_layers = 1
num_classes = 2
class customModel(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes):
super(customModel, self).__init__()
self.hidden_size = hidden_size
self.... | <p>I have commented the <code>def forward(...)</code> method your module, have a look:</p>
<pre><code>def forward(self, x):
# Set initial hidden and cell states
h0 = torch.zeros(self.num_layers*2, x.size(0), self.hidden_size).to(device)
c0 = torch.zeros(self.num_layers*2, x.size(0), self.hidden_size).to(d... | deep-learning|pytorch|lstm | 0 |
363,421 | 58,962,237 | Pandas: Create missing combination rows with zero values | <p>Let's say I have a dataframe df:</p>
<pre><code>df = pd.DataFrame({'col1': [1,1,2,2,2], 'col2': ['A','B','A','B','C'], 'value': [2,4,6,8,10]})
col1 col2 value
0 1 A 2
1 1 B 4
2 2 A 6
3 2 B 8
4 2 C 10
</code></pre>
<p>I'm looking for a way to create any missing rows amon... | <p>Use <code>pivot</code> , then <code>stack</code> </p>
<pre><code>df.pivot(*df.columns).fillna(0).stack().to_frame('values').reset_index()
Out[564]:
col1 col2 values
0 1 A 2.0
1 1 B 4.0
2 1 C 0.0
3 2 A 6.0
4 2 B 8.0
5 2 C 10.0
</code></pre> | python|pandas | 7 |
363,422 | 58,772,181 | ColumnTransformer fails with CountVectorizer in a pipeline | <p>I'm trying to transform text using <code>sklearn</code>'s <code>CountVectorizer</code> within pipelines combined with <code>ColumnTransformer</code>. However, the pipeline returns an incorrect array. Why is my pipeline with <code>ColumnTransformer</code> giving me a wrong 1-by-1 array for <code>CountVectorize</code>... | <p>You can utilize <code>make_column_transformer</code> and do something like the following. remainder are the remaining features on which you can apply other transformations. By default, remainder is set to 'drop' which means that the remaining features without any transformations will be dropped.:</p>
<pre><code>pre... | python|pandas|scikit-learn | 2 |
363,423 | 58,857,927 | Tensorflow 2 eager execution disabled inside a custom layer | <p>I'm using TF2 installed via pip in a ubuntu 18.04 box</p>
<pre class="lang-sh prettyprint-override"><code>$ pip freeze | grep "tensorflow"
tensorflow==2.0.0
tensorflow-estimator==2.0.1
</code></pre>
<p>And I'm playing with a custom layer.</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf... | <p>By default, <code>tf.keras</code> model is compiled to a static graph to deliver the best execution performance. Just think that <code>@tf.function</code> is by default annotated for <code>tf.keras</code> model.</p>
<p><a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model#run_eagerly" rel="noreferrer">... | python|tensorflow|tensorflow2.0|eager-execution | 5 |
363,424 | 58,985,481 | How do I get this JSON time series data into a pandas dataframe? | <p>I have time series data from an API I'd like to get in to a python pandas dataframe.<br>
How would you do this?</p>
<p>The data look like this:</p>
<pre><code>[{'id': 38421212541,
'sensor_id': 12944473,
'value': '6852.426',
'date': '2015-02-05',
'min': '0.0',
'max': '833.789',
'avg': '285.5177',
'val... | <h1>Quick Answer</h1>
<p>Assuming you have the latest version of pandas.</p>
<pre><code>data = [{'date': x['date'], 'values': eval(x['values'])} for x in your_json_dict]
pd.DataFrame(data).explode('values')
</code></pre>
<p>results in</p>
<pre><code> date values
0 2015-02-05 344.336
0 2015-02-05 30... | python|json|pandas|time-series | 1 |
363,425 | 59,025,520 | how to calculate total running time for training process of CNN Model | <p>I need to get the total running time for my CNN training process, but I don't understand how to get this. Is there any package to get the total running time?</p>
<p>I have a result example of my CNN training process here. As you can see that every epoch has a running time process but I need to get the total all of ... | <p>You may try this,</p>
<pre class="lang-py prettyprint-override"><code>import time
start = time.time()
model.fit() # Training statement
print("Total time: ", time.time() - start, "seconds")
</code></pre> | tensorflow|time|model|conv-neural-network | 0 |
363,426 | 58,973,257 | How to shift axis labels, shift subplots and modify axis scaling in matplotlib | <p>I am trying to make a plot like this</p>
<p><a href="https://i.stack.imgur.com/U40NJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/U40NJ.png" alt="enter image description here"></a></p>
<p>using matplotlib.</p>
<p>Currently I have this plot:</p>
<p><a href="https://i.stack.imgur.com/G3zGA.pn... | <ul>
<li>use <a href="https://matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html?highlight=subplots_adjust#matplotlib.figure.Figure.subplots_adjust" rel="nofollow noreferrer"><code>fig.subplots_adjust()</code></a> to change the spacing between the two axes.</li>
<li>I replaced the <code>ylabel</code> with <code>f... | python|pandas|matplotlib | 1 |
363,427 | 58,613,091 | Combine multiple categories into one in Pandas | <p>I have a dataset with a column that contains categories. What I'd like to do is to combine these categories into new categories.</p>
<p>My dataset looks like follows (the categories column is a string column) and I have like 160 categories.</p>
<p>Below in my example, only four categories are shown.</p>
<pre><cod... | <p><strong>For revised question</strong>:</p>
<p>You don't need groupby. Just use <code>factorize</code> with tuple of <code>Group</code> and <code>Category</code></p>
<pre><code>df['New_Category']= (pd.factorize(list(zip(df.Group, df.Category)))[0] // 2) + 1
Out[272]:
Group Category New_Category
0 A ZA-... | pandas|categories|pandas-groupby | 5 |
363,428 | 58,642,588 | Replacing characters in entire Pandas dataframe with values from a dictionary | <p>I have a German csv file that was incorrectly encoded. I want to convert the characters back to utf-8 using a dictionary. I thought what I was doing was correct, but when I print the DF, nothing has changed. Here's my code:</p>
<pre class="lang-py prettyprint-override"><code>DATA_DIR = 'C:\\...'
translations = {
... | <p>Add <code>regex=True</code> for replace in substrings, for columns is possible convert values to <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.to_series.html" rel="nofollow noreferrer"><code>Index.to_series</code></a> and then use <code>replace</code>:</p>
<p... | python|pandas | 0 |
363,429 | 59,040,579 | Extracting the 'year' from a list of strings in a pandas data frame | <p>I have a pandas data set with a column named ['title'] and string values such as "Robert Hall 2015 Viognier", and "Woodinville Wine Cellars 2012 Reserve". I am trying to iterate through each row to extract the year as an integer, however the strings differ from each other and the years are not all in the same spots.... | <p>You can use the <code>str.extract</code> method with a regex:</p>
<pre class="lang-py prettyprint-override"><code>df['title'].str.extract('\d{4}').astype(int)
</code></pre>
<p><a href="https://regexone.com/lesson/letters_and_digits" rel="nofollow noreferrer">Here</a> is a crash course on regular expressions (look ... | python|pandas | 1 |
363,430 | 59,040,958 | Deploy function in AWS Lamda (package size exceeds) | <p>I am trying to deploy my function on AWS Lambda. I need the following packages for my code to function:</p>
<ul>
<li>keras-tensorflow</li>
<li>Pillow</li>
<li>scipy</li>
<li>numpy</li>
<li>pandas</li>
</ul>
<p>I tried installing using docker and uploading the zip file, but it exceeds the file size.</p>
<p>Is ther... | <p>publish your packages in AWS Lambda layer instead, and reference it from your code. The packages published in the AWS Lambda layer will be there all the time and will not need to instantiate whenever the Lambda cold start.</p>
<p>There is complete documentation from official AWS Websites: <a href="https://docs.aws.... | python|amazon-web-services|numpy|tensorflow|aws-lambda | 4 |
363,431 | 58,653,367 | How to Retain Columns of lists in a dataframe with a specific value? | <p>Hey I have a dataframe as shown</p>
<pre><code>id A B
1 2 ['a', 'c', 'd']
3 4 ['s', 'z', 'a', 'e']
5 6 ['b', 'z', 'd']
7 8 ['a', 'g']
</code></pre>
<p>Now, I would like to extract all rows that have 'a' in column "B"
Desired Output:</p>
<pre><code>id A B
1 ... | <p>We can do </p>
<pre><code>df[pd.DataFrame(df.B.tolist()).eq('a').any(1).values]
</code></pre> | python|pandas | 1 |
363,432 | 59,013,622 | Is there a fast way, to create a vector with 1 and x * 0? | <p>is there a fast way, to create a vector with 1 and x * 0 in python? </p>
<p>I would like to have something like </p>
<pre><code>a = [1,0,0,0,0,0,0,0,0,...,0]
b = [1,1,0,0,0,0,0,0,0,...,0]
</code></pre>
<p>I tried it with list but see yourself :(</p>
<pre><code>lst = [1, n*[0]]
lst = np.array(lst)
print(lst)
==&... | <p>A proper NumPy solution:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
n = 10
arr = np.zeros(shape=n + 1, dtype=np.int64)
arr[0] = 1
</code></pre>
<p>Results in: <code>[1 0 0 0 0 0 0 0 0 0 0]</code></p>
<hr>
<h3>Quick benchmarks</h3>
<p>Here are the functions we're going to compare:</p... | python|python-3.x|numpy | 8 |
363,433 | 58,839,917 | ValueError: not enough values to unpack (expected 3, got 1) for image opening | <p>I want to open the file for image processing, but I am facing problems </p>
<p>My code is-</p>
<pre><code> import numpy as np
import cv2
from scipy import ndimage
from matplotlib import pyplot as plt
from PIL import Image,ImageOps
from skimage import color,measure,io
img=cv2.imread('trail_image.tif')
img1=n... | <p>I tried reproducing your error with a sample <code>tiff</code> image. The error is in the line
<code>b,g,r =cv2.split(img1)</code>.
I have a hunch that you are not using the correct extension while loading the image -
<code>img=cv2.imread('trail_image.tif')</code> here. Try using <code>img=cv2.imread('trail_image.... | python|numpy | 1 |
363,434 | 58,899,030 | create a function that apply activation function on a list of numbers | <p>I want to create a method that takes as input a list or a single number x and output the result of applying the RELU function on it. For example,
Given that an array <code>a=[-1,2,3,-0.4,22,12,-0.6,22,3]</code>, I want to apply the RELU function on the array to get <code>[0,2,3,0,22,12,0,22.3]</code>. Here is what ... | <p>You can do something like this by creating your own function:</p>
<pre><code>import numpy as np
def relu(a):
return np.maximum(0, a)
a=[-1,2,3,-0.4,22,12,-0.6,22,3]
return_a = relu(a)
print(return_a)
</code></pre>
<p>Result into</p>
<pre><code>[ 0. 2. 3. 0. 22. 12. 0. 22. 3.]
</code></pre> | python|numpy | 1 |
363,435 | 58,635,318 | How do I filter a dataframe column using regex? | <p>Here is my regex
<code>date_regex='\d{1,2}\/\d{1,2}\/\d{4}$'</code></p>
<p><a href="https://i.stack.imgur.com/AbGXO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AbGXO.jpg" alt="dates_as_first_row Dataframe"></a></p>
<p>Here is my dates_as_first_row Dataframe</p>
<p>I am trying to filter out ... | <p>You can do this using <code>.str.match</code>.</p>
<p>If your column is named <code>'0'</code>, it looks like this:</p>
<pre><code>indexer=df['0'].str.match('\d{1,2}\/\d{1,2}\/\d{4}$')
df[indexer]
</code></pre>
<p>If you want to select all rows which contain the pattern in any of the string columns, you can do:</... | python-3.x|pandas | 0 |
363,436 | 58,840,655 | Python and Pandas - Sorting by Date | <p>What I've tried for a sort "should" be working; but it is not. </p>
<p>I've queried the "Alpha Vantage" API using the "alpha_vantage" Python library. Below is my code. I am requesting to sort by date; but, as you can see from the output in the df.head() the sorting by date is in the wrong direction. However, th... | <p><code>df = df.sort_values(by=['date'])</code> </p>
<p>should get it done</p> | python|pandas|alpha-vantage | 2 |
363,437 | 58,883,944 | Extracting Specific Numbers from Text Data | <p>I am working on an unsupervised machine learning algorithm studying marijuana data to offer suggestions on similar strains. I've run into a slight roadblock, which is that the CBD to THC ratio, which is a super import data point, is hidden within the 'Description' column with no real consistency on how it is phrased... | <p>You can use the "extract" function with a regex containing named groups like this :</p>
<pre class="lang-py prettyprint-override"><code>df = strain_data.Description.str.extract(r'THC:CBD ratio of about (?P<THC>[\d+]):(?P<CBD>[\d+])') # it returns a dataframe with two columns named "THC" and "CBD" with t... | python|string|pandas|if-statement|int | 2 |
363,438 | 58,746,723 | Pandas "replace" with dict input returns different results depending on dict order (where dict has no order) | <p>I have a <code>pandas</code> <code>Series</code> with values of <code>True</code>, <code>False</code> or <code>None</code>.<br></p>
<pre><code>import pandas as pd
s = pd.Series([True, True, False, False, None, None])
</code></pre>
<p>I want to replace it into 1, -1 or 0 respectively. <br>
But when I run the <code>... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/version/0.25/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a>:</p>
<pre><code>mapping = {None: 0, False: -1, True: 1}
s.map(mapping)
0 1
1 1
2 -1
3 -1
4 0
5 0
dtype: int64
</code></pre>
<p>Or using repla... | python|pandas|dictionary | 3 |
363,439 | 58,975,989 | Write output of pandas.io.parsers.TextFileReader to pandas.DataFrame | <p>I have a large CSV file which I am reading using user defined input "num_rows" (number of rows) in parts of chunks, using "chunksize" argument, which returns "pandas.io.parsers.TextFileReader" object as follows:</p>
<pre><code>num_rows = int(input("Enter number of rows to be processed
chunk = pd.read_csv("large_fi... | <p>What you did will not modify the csv because each <code>data_chunk</code> is not linked to the original data.<br>
You can write each <code>data_chunk</code> to a separate csv file</p>
<pre><code>reader = pd.read_csv("large_file.csv", chunksize = number_of_rows)
for i, data_chunk in enumerate(reader):
data_chun... | python|pandas | 1 |
363,440 | 59,036,484 | Creating a dataframe from a dictionary within tuple | <p>I have a dictionary within a tuple and I want to know how to access it and create a dataframe merging the dictionary value into single row</p>
<pre><code>Example:
({'Id': '4', 'BU': 'usa', 'V_ID': '44', 'INV': 'inv1331', 'DT': '08/1/19', 'AMT': '1500'}, {'Id': '9', 'BU': 'usa', 'V_ID': '44', 'INV': 'inv4321', 'DT'... | <pre><code>x = ({'Id': '4', 'BU': 'usa', 'V_ID': '44', 'INV': 'inv1331', 'DT': '08/1/19', 'AMT': '1500'}, {'Id': '9', 'BU': 'usa', 'V_ID': '44', 'INV': 'inv4321', 'DT': '02/6/19', 'AMT': '1000'})
data = {f"{k}_{i+1}": v for i, d in enumerate(x) for k, v in d.items()}
df = pd.DataFrame(data, index = [0])
</code></pre>... | python|pandas|dataframe|dictionary|tuples | 2 |
363,441 | 59,022,050 | Using pandas groupby to collapse rows into a single row? | <p>I have a Pandas DataFrame object that looks like this:</p>
<p><a href="https://i.stack.imgur.com/vuzyp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vuzyp.png" alt="enter image description here"></a></p>
<p>Using the first two rows as an example:</p>
<p>I'd like to transform the first two row... | <p>Wow so I guess all I had to do was call reset_index(). Thanks guys.</p> | python|pandas|group-by|pandas-groupby|data-science | 0 |
363,442 | 59,038,715 | Manipulate Excel into Pandas Dataframe | <p>I am trying to replicate a bar chart using pandas. The problem I have run into is the merged cells. Pandas data frame returns unamed for the extra column. I have tried to select my excel data using read_excel() and then creating a dataframe for it using multiindexing methods but I cannot figure it out. </p>
<p>Can ... | <p>You can use the <code>header</code> argument of the <code>read_excel</code> method, like this:</p>
<pre><code>df = pd.read_excel('/path/to/file.xlsx', header=[0, 1])
</code></pre> | python|excel|pandas | 1 |
363,443 | 58,863,472 | Count changes in a string from the previous row using pandas | <p>I have a dataframe df which looks like this:
<a href="https://i.stack.imgur.com/i60uP.png" rel="nofollow noreferrer">Data</a></p>
<pre><code>Id Input
1 A,B
2 B,C,D
3 E,F,G
4 G
</code></pre>
<p>i want to count the changes in the list, so we will compare within the list as well and with the previo... | <p>It seems to me you are only asking for additions. Also your first case seems odd, going from empty list to a list with 2 items would seem to require 2 additions.</p>
<p>All you have to do is store a hashmap of the items in each list. When you go through the next list, you can check whether it is already there in O(... | python|pandas|list|dataframe|metadata | 0 |
363,444 | 59,005,785 | How to drop rows with nan cell in dask dataframe? | <p>I have a dask dataframe in which I want to delete all the rows which have an NAN value in the "selling_price" column</p>
<pre><code>image_features_df.head(3)
feat1 feat2 feat3 ... feat25087 feat25088 fid selling_price
0 0.0 0.0 0.0 ... 0.0 0.0 2 269.00
1 0.2 ... | <p>Could you please try following, this will remove line if NaN is found in column selling_price.</p>
<pre><code>df.dropna(subset=['selling_price'])
</code></pre> | python|pandas|dataframe|nan|dask | 1 |
363,445 | 59,019,607 | Pandas string tokeniztion too slow | <p>I have a column in a Pandas DataFrame, where each row has some string containing a job description like <code>'senior data consultant'</code>, and there are approximately 1,000,000 of these rows. I want to shorten this string to just the first word (which in that example would give <code>'senior'</code>). The code b... | <p>As per <a href="https://stackoverflow.com/users/9284423/henry-yik">Henry Yik</a>'s suggestion, the following is significantly faster</p>
<pre class="lang-py prettyprint-override"><code>def proc_Profession(df):
df['Profession'] = df['Profession'].str.split().str[0]
return df
</code></pre> | python|pandas|token | 1 |
363,446 | 58,871,113 | How to set python environment variables in VS Code? | <p>I know how to add arguments for the Python script I want to run. For example, if <code>test.py</code> is my script file and it has one argument like <code>'--batch_size'</code> then I can edit <code>launch.json</code> in VS Code and set <code>"args": ["--batch_size", "32"]</code></p>
<p>But I don't know how to add ... | <p>-m is not environmental variable. It's just a regular argument.</p>
<p>To run <code>python -m torch.distributed.launch test.py --batch_size 32</code> use args <code>"args": ["-m", "torch.distributes.launch" ,"--batch_size", "32"]</code> Also you need to run python itself instead of running script to pass these arg... | python|visual-studio-code|pytorch | 3 |
363,447 | 58,998,475 | Recieve the integer values when float is needed(computing determinant with numpy arr) | <p>I am trying to create a programm computing the determinant of the matrix using raw python code and numpy array to compare with scipy function.My algotirhm is first to change matrix to the upper triangle and then computing the final answer.</p>
<p>I probably found the problem: all elements are computed in integer, w... | <p>There are a couple of standard approaches for turning arbitrary array-like input into floating point arrays.</p>
<ul>
<li><code>matrix_copy = X.astype(np.inexact, copy=True)</code>. This will pass thru all the floating point types, and guarantee a copy. This is the option you want, because you need a copy of the ar... | python|numpy | 3 |
363,448 | 58,721,519 | Filter df if more than two unique values - pandas | <p>I have a df that contains values at various time points. I have two separate columns which should display a single set of unique values for each time point. This occurs for the most part but sometimes time points contain multiple unique values. I'm hoping to filter these using conditional logic.</p>
<p>For the df b... | <p>Update use <code>duplicate</code></p>
<pre><code>df[df.duplicated(keep=False)|df.index.isin(df.groupby('Time').head(1).index)]
Out[187]:
Time Object Value
0 2019-08-02 09:50:10.1 A X
1 2019-08-02 09:50:10.1 A X
2 2019-08-02 09:50:10.2 B NaN
3 2019-08-02 09:50:10.2 ... | python|pandas | 1 |
363,449 | 58,685,390 | Python Bubble Chart Legands- TypeError | <p>Here's my code:</p>
<pre><code>import pandas
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
%matplotlib inline
pandas.set_option ('max_columns',10)
df= pandas.read_csv('C:/Users/HP/Desktop/Coding/Python/2.Python Data Analysis/Module 2- Python Data Visualization/M2-Bubble Chart with Labels ... | <p>You cannot have <code>handles=1</code> in <code>plt.legend(handles=1,loc=(2,0))</code>. </p>
<p><code>handles</code> must be a container, such as a list, tuple, etc...</p>
<p>Not only that, but a container of integers in unacceptable. Do not write <code>handles=[1, 2, 3]</code></p>
<p>The following cod... | python|r|pandas|dataframe|matplotlib | 0 |
363,450 | 58,858,026 | Merge two Dataframes based on a similar column from the First dataframe? | <p>I have to merge two dataframes based on a similar column from df1</p>
<p>df1</p>
<pre><code> A B
0 john id1
1 parker id2
2 david id3
3 will id4
</code></pre>
<p>df2</p>
<pre><code> C B
0 letterj id1
1 letterp id2... | <pre><code>you need,
df1.merge(df2,on='B')
A B C
0 john id1 letterj
1 parker id2 letterp
2 david id3 letterd
3 will id4 letterw
</code></pre> | python|pandas|dataframe | 1 |
363,451 | 58,976,781 | Convert Python XML request into Pandas Dataframe | <p>Convert XML request into data frame. Tried using following code but didn't work.</p>
<pre><code>data=requests.get('https://www.w3schools.com/xml/cd_catalog.xml')
XML_DF = data.content
print('>> XML_DF:', len(XML_DF))
root = ET.XML(XML_DF)
XML_List = []
for child in root[1]:
XML_Dict = {}
XML_Dict['CAT... | <p>you need to write a function which will convert XML to Data frame.For example </p>
<pre><code>def SOQL(SOQL):
qryResult=sf.query_all(SOQL)
print('Record count{0}'.format(qryResult['totalSize']))
isDone = qryResult['done']
if isDone == True:
df=pd.DataFrame(qryResult['records'])
df=df... | python|xml|pandas | 0 |
363,452 | 58,848,365 | How to create a new column in Pandas DataFrame based on a group of rows | <p>I have the following data frame:</p>
<pre><code>import pandas as pd
cols = 'id,seq,msg'.split(',')
data = [
['001',1,'abc aaa'],
['001',2,'bcd bbb'],
['001',3,'cde ccc'],
['001',1,'def ddd'],
['001',2,'efg eee'],
['001',3,'fgh fff'],
['001',4,'ghi ggg'],
... | <p>IIUC</p>
<pre><code>df.seq.diff().lt(0).cumsum().add(1)
Out[203]:
0 1
1 1
2 1
3 2
4 2
5 2
6 2
7 3
8 3
9 3
Name: seq, dtype: int64
</code></pre> | python|pandas|dataframe|pandas-groupby | 3 |
363,453 | 59,023,189 | Experiencing ModuleNotFoundError: No module named 'tensorflow.contrib' when I use Tensorflow GPU processing | <p>I am experiencing <code>ModuleNotFoundError: No module named 'tensorflow.contrib'</code> while executing <code>from tensorflow.contrib.cudnn_rnn.python.ops import cudnn_rnn_ops</code> command in the <code>keras\layers\cudnn_recurrent.py</code>, line <code>425</code>. This issue is specific to Tensorflow <strong>when... | <p>TensorFlow 2.0 discontinued supporting contrib. You can learn more about it <a href="https://www.tensorflow.org/guide/migrate" rel="nofollow noreferrer">here</a>. </p>
<p>Possibly, your code has been written for TF 1.* or was not ported properly.</p> | tensorflow|keras|tensorflow2.0 | 1 |
363,454 | 58,838,790 | Quickest way to apply a formula to a column which requires the last output | <p>I have a dataset for which I am calculating the "Hazard rate" defined by the below formula:</p>
<pre><code>if t = 1:
hr_t = pd_t
else:
hr_t = (pd_t * (t - (t-1)) + hr_(t-1) * (t-1)) / t
</code></pre>
<p>where t stands for time (indicated by Years)</p>
<p>The simplest way to do this would be to iterate... | <pre><code>#Create the year and PD values
data = {'Year':[1,2,3,4,5],
'PD': [0.1, 0.23, 0.22, 0.19, 0.10]}
data
#Create a dataframe
df = pd.DataFrame(data)
df
# initialize the series
df['Hazard_rate'] = 0
# iterate over the data frame rows (you need to loop since subsequent
# calculations are depending on pr... | python|pandas|loops|dataframe|lag | 2 |
363,455 | 59,001,913 | Integrating a python Tensorflow chatbot model into a Xamarin app | <p>I'm using Xamarin Forms to create a chatbot-like messaging app and I've created a simple chatbot model using TensorFlow and python. The model executes as a console app and after some testing, I've been able to run the python chatbot script in C# console using Pythonnet. I would now like to integrate it into the Xama... | <p>There is some misunderstanding of concepts. You don't need the python file been integrated into XF project. You use Python as a language and TensorFlow as a framework to get ML model. A model is a result of the training process and you could use it in other places like mobile platforms.</p>
<p>For using models on A... | c#|python|tensorflow|xamarin|python.net | 0 |
363,456 | 58,846,178 | Obtaining a 2D index from a 3D array? | <p>I have a numpy array that is (7 x 325 x 255). The seven are different bands from an image, and the 325 and 448 are rows and columns (i.e. pixels). X is an example of my setup.</p>
<pre><code> x = x = np.random.randint(5, size=(7,325,255))
</code></pre>
<p>I'm trying to create a two-dimensional index (325,255) ... | <p>Use <code>any</code> to aggregate over the bands. This yields the required 2d boolean array:</p>
<pre><code>y = np.any(x == -9999, axis=0)
</code></pre> | python|arrays|numpy|indexing | 1 |
363,457 | 58,877,166 | How to read images from pandas column in a pytorch class | <p>I need to define a pytorch dataset class that reads the absolute path from a column to pull the image. When I try this with multiple packages, I get errors. Below are the errors for each package I'm aware of:</p>
<p><code>Pathlib.Path</code>: <code>TypeError: expected str, bytes or os.PathLike object, not method</... | <p><code>single positional indexer is out-of-bounds</code> is telling you that your are trying to access a column that is not there. Make sure that the columns you are trying to access exist</p> | python|pytorch | 1 |
363,458 | 58,645,512 | How can I run my Keras net on non-square images? | <p>I trained a UNet based image segmentation model in <code>tf.keras</code> which predicts if and where an object is in a given image. I train with an input shape of <code>(None, 256, 256, 1)</code> and output a <code>(None, 256, 256, 3)</code> shaped prediction.</p>
<p>I now want to predict larger images (eg. <code>(... | <p>I found a solution – due to the fact, that I trained a UNet (with concatenation-layers after upsampling), it can only combine powers of 2 (eg. 256 / 512). I therefore have to add padding to bring it to the next power of two before prediction and remove padding from the output.</p> | python|tensorflow|keras|computer-vision | 1 |
363,459 | 58,730,427 | Pandas dataframe can't export more than 200 rows to CSV file | <p>I am trying to export the data from salesforce using python and simple salesforce, but when I try to export the data into the CSV File I get only 200 records.
<strong>Here is my code:</strong></p>
<pre><code>import pandas as pd
from simple_salesforce import Salesforce
import csv
data=Salesforce(password='*********... | <p>If the result is extremely large then query will not retrieve all the results.
Use <code>query_all</code> instead.</p>
<p><a href="https://pypi.org/project/simple-salesforce/" rel="nofollow noreferrer">https://pypi.org/project/simple-salesforce/</a></p> | python|pandas|simple-salesforce | 1 |
363,460 | 58,941,000 | One-hot encoding for list variable with customized delimiter and new column names | <p>My data:</p>
<pre><code>Rank Platforms Technology
high Windows||Linux Unity
high Linux
low Windows Unreal
low Linux||MacOs GameMakerStudio||Unity||Unreal
low GameMakerStudio
low
</code></pre>
<p>I want to convert it to something like this:<... | <p>You can do:</p>
<pre><code>s = [df[col].str.get_dummies().add_prefix(f'{col.lower()}_')
for col in ['Platforms', 'Technology']]
pd.concat([df[['Rank']]] + s, axis=1)
</code></pre> | python|python-3.x|pandas|dataframe|one-hot-encoding | 2 |
363,461 | 59,024,502 | Convert from Tensorflow -> CoreML 3.0 for slot/intent detection | <p>I am trying to use some of the models created by this codebase (<a href="https://github.com/IsaacAhouma/Slot-Filling-Understanding-Using-RNNs" rel="nofollow noreferrer">Slot-Filling-Understanding-Using-RNNs</a>) in my Swift application.</p>
<p>I was able to convert <code>lstm_nopooling</code>, <code>lstm_nopooling3... | <p>Thanks to @MatthijsHollemans I was able to figure out what to do.</p>
<p>In data_processing.py I added these:</p>
<pre><code>with open('atis/wordlist.csv', 'w') as f:
for key in ids2words.keys():
f.write("%s\n"%(ids2words.keys[key]))
with open('atis/wordlist_slots.csv', 'w') as f:
for key in ids2sl... | python|swift|tensorflow|chatbot|coreml | 0 |
363,462 | 70,141,064 | Plotting a particular set of contour line at desired point or location | <p>I want a contour plot showing contour levels corresponding to a particular set of x,y. I tried increasing the number of contour lines but it doesn't give the contour line near the required point. <a href="https://i.stack.imgur.com/D87EM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D87EM.png" al... | <p>You could use a not evenly spaced number of levels for the contour:</p>
<pre><code>VgN_min = VgN.min()
VgN_max = VgN.max()
number_of_contours = 21
power = 2
levels = np.linspace(VgN_min**(1/power), VgN_max**(1/power), number_of_contours)**power
</code></pre>
<p>Then you can use this parameter to plot the contour:</p... | python|numpy|matplotlib|seaborn|contour | 2 |
363,463 | 70,031,929 | How can i set when i use pip3 while using python3? | <p>when i boot, i use rc.local for auto start at jetson.
in rc.local,i worte like this.</p>
<pre><code>#!/bin/bash
source ~/.bashrc
python3 /home/dinsight/Desktop/test.py
</code></pre>
<p><code>test.py</code> is code for check python version, numpy version.
python3 version is <code>3.6.9</code>.
but numpy version is <c... | <p>You can set an alias in the <code>~/.bashrc</code><br />
just add this line to <code>~/.bashrc</code> :</p>
<pre><code>alias pip=pip3
</code></pre> | python|python-3.x|numpy | 0 |
363,464 | 70,041,812 | Combing and then maintaining indicies after numpy Logical Slicing | <p>I am trying to conduct logical slicing on two lists and then concatenate them together while maintaining the original indicies.</p>
<p>Here is what I currently have:</p>
<pre><code>x = np.array([0,12,2,246,13,42,245,235,26,33,235,236,23])
y = np.array([2,2,52,626,143,42,246,2,2,53,35,26,263])
r_1 = x<=y
r_2 = y&... | <p>Just use <a href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.min.html" rel="nofollow noreferrer"><code>np.min([x,y], axis=0)</code></a></p> | python|numpy|numpy-slicing | 0 |
363,465 | 70,285,990 | How to transform a Pandas dataframe so same rows become columns | <p>I have a following DataFrame:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Elle</td>
<td>567998</td>
</tr>
<tr>
<td>1</td>
<td>Rand</td>
<td>1234</td>
</tr>
<tr>
<td>1</td>
<td>Danny</td>
<td>5678</td>
</tr>
<tr>... | <p>Try this :</p>
<pre><code>df.groupby('A')['B'].apply(lambda x: pd.Series(list(x))).unstack()
</code></pre> | python|pandas|dataframe | 1 |
363,466 | 70,197,118 | np.argmax to return -1 if all values in the input are the same | <p>I want to use <code>np.argmax</code> but I want to get -1 (or any other number) when all the elements in the array input are the same or if there are multiple occurences of them. For example, <code>a = np.array([2, 2, 2])</code> -> I want to get -1 instead of 0. Is there any alternative function?</p> | <p>I do not know of such a function, but you could always write it yourself, e.g. like this:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
def my_index(arr):
"""
Input: arr should be a NumPy array.
Return -1 if at least one number in arr occurs more than once.
El... | python|numpy | 0 |
363,467 | 70,145,445 | Construct (sparse) NumPy array from code that computes the operator/matrix-vector product? | <p>In scientific computation, we often have to construct matrices that compute differential operators. It is often easier to write the code that applies the operator than to explicitly construct the matrix. Is there a library that takes the code (assuming it only uses linear operations) and outputs the matrix, ideally ... | <p>One easy way:</p>
<pre><code>In [568]: arr = np.zeros((4,5),int)
In [569]: arr[np.arange(4),np.arange(4)]=-1
In [570]: arr[np.arange(4),np.arange(1,5)]=1
In [571]: arr
Out[571]:
array([[-1, 1, 0, 0, 0],
[ 0, -1, 1, 0, 0],
[ 0, 0, -1, 1, 0],
[ 0, 0, 0, -1, 1]])
</code></pre>
<p>Ther... | python|arrays|numpy|autodiff | 0 |
363,468 | 70,328,967 | How do I display a grouped graph using a CSV file | <p><img src="https://i.stack.imgur.com/5bEYg.png" alt="enter image description here" /></p>
<pre><code>import pandas as pd
import plotly
import plotly.express as px
import plotly.io as pio
df = pd.read_csv("final_spreadsheet.csv")
barchart = px.bar(
data_frame = df,
x = "Post-Lockdown Period (M... | <p>In plotly.express you can create a grouped bar chart by passing a list of the two variables you want to group together in the argument y. In your case, you'll want to pass the argument <code>y = ['Peak-Lockdown Period (March-May)','Post-Lockdown Period (May-September)']</code> as well as the argument <code>barmode =... | python|pandas|dataframe|csv|plotly | 0 |
363,469 | 70,306,401 | How do I order my x-axis on pandas bar plot? | <p>Been struggling for a few days on a uni project I have to hand in in a week.
I'm working with a dataset (using pandas, mostly) and I have to anayze information about mountain expeditions.
My bar plots work fine but I still have the same issue every time: my x-axis is not in growing order, which isn't of the highest ... | <p><code>value_counts</code> sorts the values by descending frequencies by default. Disable sorting using <code>sort=False</code>:</p>
<pre><code>expeditions['members'].value_counts(sort=False).plot.bar(figsize=(12,8))
</code></pre>
<p>Or sort the index prior to plotting:</p>
<pre><code>expeditions['members'].value_cou... | python|pandas|dataframe|bar-chart|axis | 2 |
363,470 | 70,054,937 | Find max distance from (0,0) and add to legend matplotlib | <p>I have this code calculating a random walk that I am trying to find the max distance from (0.0) for all walks and add them to a legend. Added an image of the result I want to achieve.</p>
<p><a href="https://i.stack.imgur.com/0uwR4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0uwR4.png" alt="" ... | <p>You can plot the distance from the coordinates <code>steps</code> to <code>0,0</code> by using <code>distance=np.linalg.norm(steps, axis=1)</code>. And you can then take the max of this array to find the maximum distance. You can then add a label to your plots and a legend.
See code below:</p>
<pre class="lang-py pr... | python|numpy|matplotlib|visual-studio-code|random-walk | 1 |
363,471 | 70,318,621 | How to sample Pandas Dataframe with minimum distance between | <p>I'm trying to sample a Dataframe based on a given <strong>Minimum Sample Interval</strong> on the "timestamp" column. Every extracted value would be the closest extracted value to the last one that is at least <strong>Minimum Sample Interval</strong> larger than the last one. So what I mean is, for the tab... | <p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.diff.html" rel="nofollow noreferrer"><code>pandas.Series.diff</code></a> to compute the difference between each value and the next one:</p>
<pre><code>sample = df[df['timestamp'].diff().fillna(1) > 0.2]
</code></pre>
<p>Output:</p>
<p... | python|pandas | 0 |
363,472 | 70,374,912 | Label elements within a group in numpy | <p>I know how to label elements of one input array like the followings:</p>
<pre><code>arr_value = np.array([0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 2, 1, 1, 1, 1])
arr_res_1 = np.array([0, 1, 2, 3, 3, 4, 5, 6, 7, 7, 8, 9, 9, 9, 9]) # consider zeros in arr_value as elements
arr_res_2 = np.array([0, 1, 0, 2, 2, 0, 3, 0, 4, 4, 5,... | <p>You need to find a way to subtract maximum indices of each group before counting <code>np.cumsum</code>. <code>np.add.reduceat</code> allows you to find these results without a need to split array before. If you pass indices that separates your groups in it, you'll get sum of every group.</p>
<pre><code>def refresh_... | python|arrays|pandas|numpy | 0 |
363,473 | 70,313,129 | tensorflow_text is not importing | <pre><code>import tensorflow_hub as hub
import tensorflow_text as text
</code></pre>
<p>below is the error i am getting ..</p>
<pre><code>ModuleNotFoundError Traceback (most recent call last)
<ipython-input-1-566f9fbfe6f7> in <module>
1 import tensorflow_hub as hub
----> 2 imp... | <p>If this package is missing you can install it using <a href="https://github.com/tensorflow/text#install-using-pip" rel="nofollow noreferrer"><code>pip</code></a>.</p>
<pre><code>pip install -U tensorflow-text==2.6.0
</code></pre>
<p>Please note the comment:</p>
<blockquote>
<p>When installing TF Text with <code>pip ... | tensorflow | 1 |
363,474 | 70,337,933 | How to find Value at specific index in an array in a dataframe? | <p>I have a dataframe with columns <code>SRi</code> and <code>SAi</code>. Each row represents a different location and these columns contain arrays of <code>SRi</code> and <code>SAi</code> for each location. I want to find the index of the maximum value of <code>SAi</code> and then find the corresponding value of <code... | <p>This line isn't doing what you think it's doing:</p>
<pre><code> w=AvgT.SRi[maxsa]
</code></pre>
<p>You are accessing the value of SRi in row maxsa of the dataframe -- that is, you are getting the whole list. I assume you are getting an IndexError because in at least one instance, the argmax of SAi is higher than... | python|pandas|dataframe|numpy | 0 |
363,475 | 70,136,183 | How to loop in tabula-py data format in python | <p>I want to know how to extract particular table column from pdf file in python.</p>
<p>My code so far</p>
<pre><code> import tabula.io as tb
from tabula.io import read_pdf
dfs = tb.read_pdf(pdf_path, pages='all')
print (len(dfs)) [It displays 73]
</code></pre>
<p>I am able to access individual table column by doin... | <p>If you have only one dataframe with <code>Section ID</code> name (or are interested only in the first dataframe with this column) you can iterate over the list returned by <code>read_pdf</code>, check for the column presence with <code>in df.columns</code> and <code>break</code> when a match is found.</p>
<pre class... | python|pandas|dataframe|tabula-py | 0 |
363,476 | 70,255,094 | Python pandas column operations | <p>I'm trying to do some columnar operations on a dataframe and I'm stuck at one point. I'm new to pandas and now I'm unable to figure how to do this.</p>
<p>So wherever there is a "Yes" value in "Prevous_Line_Has_Br" buffer should be added to the "OldTop" value but whenever there is a &qu... | <p>This would be fairly easy to do if you moved away from pandas, and treated the columns as just lists. If you want to still use the apply method, you can use to decorator to keep track of the last row.</p>
<pre><code>def apply_func_decorator(func):
prev_row = {}
def wrapper(curr_row, **kwargs):
val = ... | python|pandas|dataframe | 0 |
363,477 | 70,219,481 | how to get the applying element's index while using pandas apply function? | <p>I'm trying to apply a simple function on a <code>pd.DataFrame</code> but I need the index of each element while applying.</p>
<p>Consider this <code>DataFrame</code>:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>CLM_1</th>
<th>CLM_1</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td... | <p>Use <code>to_series()</code> on the index:</p>
<pre><code>>>> df.index.to_series()
A A
B B
C C
dtype: object
</code></pre>
<p>If you want to use the index in a function, you can assign it as a column and then apply whatever function you need:</p>
<pre><code>df["index"] = df.index
>>... | python|pandas|dataframe|series | 1 |
363,478 | 70,358,350 | How to deal with tf.saved_model.save(model, filepath) Error? | <p>I use TFRS build a custom hybrid recommender; the model was trained and is able to make prediction well. But when I save it:</p>
<pre><code>model = ...
filepath = 'saved_model/model0'
tf.saved_model.save(model, filepath)
</code></pre>
<p>error:</p>
<pre><code>---------------------------------------------------------... | <p><strong>Solution:</strong></p>
<pre class="lang-py prettyprint-override"><code># define create_model()
def create_model():
"""instantiate a model and compile it"""
model = MyTFModel(...)
model.compile(optimizer=tf.keras.optimizers.Adagrad(0.1))
return model
# instantiat... | tensorflow | 1 |
363,479 | 70,218,740 | Creating a complex custom loss in Keras for a seq2seq problem | <p>I would like to write a custom loss function for a seq2seq problem.
My input (X) has shape (N, M), that is, N sequences of length M each. Each sequence has M/2 numbers (from 1 to M/2), repeated twice and randomly. Here, is an example with M=200:</p>
<pre><code>X = array([[ 60., 71., 15., ..., 73., 64., 71.],
... | <p>The problem was that I needed to use differentiable operations. I found a list of differentiable operations in Tensorflow (<a href="https://www.tensorflow.org/api_docs/python/tf/raw_ops" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/raw_ops</a>) and modified the custom loss function accordi... | tensorflow|keras|loss | 1 |
363,480 | 70,076,862 | pandas dataframe iterate over cell value that is a list and compare each element to other cell | <p>I have a dataframe with 2 columns - a tuple and a list:</p>
<pre><code>df = t l
(1,2) [1,2,3,4,5,6]
(0,5) [1,4,9]
(0,4) [9,11]
</code></pre>
<p>I want to add a new column of "how many elements from l are in the range of t.
So for example, here if will be:</p>
<pre><code>df =counter t l... | <p>Use list comprehension with generator and <code>sum</code>:</p>
<pre><code>df['counter'] = [sum(a <= i <= b for i in y) for (a, b), y in df[['t','l']].to_numpy()]
</code></pre>
<p>A bit faster solution with <code>set.intersection</code> is:</p>
<pre><code>df['counter'] = [len(set(range(a, b+1)).intersection(y)... | python-3.x|pandas|dataframe | 2 |
363,481 | 70,159,352 | Put a state on a column if an element change the state in a dataframe with Python | <p>I have the next dataframe with a lot of elements</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>code</th>
<th>status</th>
<th>Month</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>Active</td>
<td>1</td>
</tr>
<tr>
<td>b</td>
<td>Inactive</td>
<td>2</td>
</tr>
<tr>
<td>c</td>
<td>Active<... | <p>Try:</p>
<ol>
<li><code>sort_values</code> by the "code" and "Month" columns</li>
<li>Use <code>np.where</code> to assign actions when the status changes.</li>
<li><code>drop_duplicates</code> to keep only final row for each "code"</li>
</ol>
<pre><code>df = df.sort_values(["code&q... | python|pandas|dataframe | 1 |
363,482 | 70,261,880 | resampling a pandas dataframe and filling new rows with zero | <p>I have a time series as a dataframe. The first column is the week number, the second are values for that week. The first week (22) and the last week (48), are the lower and upper bounds of the time series. Some weeks are missing, for example, there is no week 27 and 28. I would like to resample this series such that... | <p>I would set <code>week</code> as index, reindex with <code>fill_value</code> option:</p>
<pre><code>start, end = df['week'].agg(['min','max'])
df.set_index('week').reindex(np.arange(start, end+1), fill_value=0).reset_index()
</code></pre>
<p>Output (head):</p>
<pre><code> week value
0 22 1
1 23 ... | python-3.x|pandas|dataframe|pandas-resample | 3 |
363,483 | 70,163,246 | How do i get the sum of a column based on the user input of that particular column in pandas | <p>my code to calculate the sum of a column:</p>
<pre><code>import json
import requests
import pandas as pd
def get_additonal_data():
import pandas as pd
file_path = '/Users/CIS5357/Assignments/'
data = file_path + 'grades.csv'
df_grades = pd.read_csv(data)
print (df_grades)
return df_grades
de... | <pre><code>import pandas as pd
import requests
file_path = '/Users/CIS5357/Assignments/'
data = file_path + 'grades.csv'
df_grades = pd.read_csv(data)
user_input_grade = input("enter the grade: ")
Print_grades = df_grades[user_input_grade].sum()
print(Print_grades)
</code></pre> | python|pandas | 1 |
363,484 | 70,155,096 | How to iterate over columns and connacenate two columns into one | <p>I have a dataframe:</p>
<pre><code> Border #1 [from] Border #1 [to] Border #2 [from] Border #2 [to]
index
0 BE BE_AL PL SK
1 BE BE_AL P... | <p>Create <code>MutliIndex</code> by split by <code>[</code> with space, so possible select both levels by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.xs.html" rel="nofollow noreferrer"><code>DataFrame.xs</code></a> and join by <code>+</code>:</p>
<pre><code>df.columns = df.colum... | python|pandas | 2 |
363,485 | 70,075,505 | find the count of each date in dataframe | <p>I need to group the columns according to the date.</p>
<p><a href="https://i.stack.imgur.com/TA9Qw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TA9Qw.png" alt="enter image description here" /></a></p>
<pre><code>starttime Dates COUNT
0 2019-09-01 00:00:01.9580 2019-09-01 0
1 2019-09... | <p>Try this :</p>
<pre><code>output = df.Dates.value_counts().reset_index()
output.columns = ["Date", "Count"]
</code></pre> | python|pandas | 1 |
363,486 | 70,241,395 | ValueError: Shape of passed values is (3, 3), indices imply (3, 7) site:stackoverflow.com | <p>Please i need help fast...</p>
<p>Here is the <strong>code</strong>:</p>
<pre><code>list_of_categories = categories +['Others']
print("Classification Report: \n Target: %s \n Labels: %s \n Classifier: %s:\n%s\n"
% (target,list_of_categories,classifier, metrics.classification_report(y_test, y_pred)))... | <pre><code>ValueError: Shape of passed values is (3, 3), indices imply (3, 7)
</code></pre>
<p>The error refer to wrong data-frame size calling in a sense calling rows that do not exist.</p> | python|python-3.x|pandas|dataframe | 0 |
363,487 | 70,379,769 | Check and return Boolean when there is substring in string | <p>Hi I am searching only the exact substring from string column and return True/False.</p>
<p><a href="https://i.stack.imgur.com/xuln0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xuln0.png" alt="enter image description here" /></a></p>
<p>Row-3,4,5 has sting 'abc' (case-sensitive) but when i tri... | <p>I don't think <code>str.contains</code> is what you are looking for here, rather, you are looking for an exact match that will not consider upper / lower cases. Therefore, you can simply convert to upper, <code>str.upper()</code>, and check whether it equals to 'ABC':</p>
<pre><code>df['output'] = df.string_1.str.up... | python|pandas | 3 |
363,488 | 70,265,959 | How to put pandas df column values into extract regular expression | <p>I am wondering how to pass pandas data frame column values into a regular expression. I have tried the below but get "TypeError: 'Series' objects are mutable, thus they cannot be hashed"</p>
<p>Im after the result below. (I could just use a different regex but was wondering how this might be done dynamical... | <p>I know that you want an efficient solution, but typically these pandas functions do not take values such as <code>Series</code>es. Here is an <code>apply</code>-based solution, which I think, besides simplifying the regular expression, is the only viable solution here:</p>
<pre><code>searched = df.apply(lambda row: ... | python|regex|pandas | 1 |
363,489 | 70,286,011 | how to let one column keep two decimal point, another column` without decimal point(int) in dataframe/Pandas | <p>Supposed I have both <code>sum</code> and <code>mean</code> value in <code>dataframe</code>, how to let <code>difference</code> column keep two decimal point, and <code>value_a</code> and <code>value_b</code> keep int(without decimal point)</p>
<pre class="lang-py prettyprint-override"><code>df.columns=['value_a','v... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.astype.html" rel="nofollow noreferrer"><code>DataFrame.astype</code></a> and for 2 decimals <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.round.html" rel="nofollow noreferrer"><code>DataFrame... | python|pandas|dataframe | 1 |
363,490 | 70,223,752 | How to apply a command to multiple column elements? | <p>I have the table below and would like to apply onde command to compare and eliminate duplicate values in row <code>n</code> and <code>n + 1</code> in multiple dataframes <code>(df1, df2)</code>.<br></p>
<p><strong>Comand sugestion:</strong> <code>.diff().ne(0)</code> <br></p>
<p>How to apply this command only to... | <p>Based on <a href="https://stackoverflow.com/questions/19463985/pandas-drop-consecutive-duplicates">this</a> answer, you can create a mask for a single column in your dataframe (here for example for column <code>A</code>) with</p>
<pre><code>mask1 = df['A'].shift() == df['A']
</code></pre>
<p>Since this shows <code>T... | python|pandas|function|lambda|apply | 1 |
363,491 | 70,041,392 | Setting Values with pandas DataFrame.loc | <p>Consider I have a data frame :</p>
<pre><code>>>> data
c0 c1 c2 _c1 _c2
0 0 1 2 18.0 19.0
1 3 4 5 NaN NaN
2 6 7 8 20.0 21.0
3 9 10 11 NaN NaN
4 12 13 14 NaN NaN
5 15 16 17 NaN NaN
</code></pre>
<p>I want to update the values in the c1 and c2 columns w... | <p>I recommend <code>update</code> after <code>rename</code></p>
<pre><code>df.update(df[['_c1','_c2']].rename(columns={'_c1':'c1','_c2':'c2'}))
df
Out[266]:
c0 c1 c2 _c1 _c2
0 0 18.0 19.0 18.0 19.0
1 3 4.0 5.0 NaN NaN
2 6 20.0 21.0 20.0 21.0
3 9 10.0 11.0 NaN NaN
4 12 13.0... | python|pandas|dataframe | 1 |
363,492 | 70,278,385 | Cant create index with dataframe columns | <p>I'm trying to use dataframe columns to create an index.</p>
<pre><code>#columns in file [<TICKER>,<PER>,<DATE>,<TIME>,<OPEN>,<HIGH>,<LOW>,<CLOSE>,<VOL>]
df = pd.read_csv('DSKY_210101_211106.csv', header=0, parse_dates=[2, 3])
#projection
project = df[['<DATE&g... | <p><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>pandas.DataFrame.set_index()</code></a> is not in-place, i.e., it creates a <em>new</em> dataframe and modifies that. You need to reassign to <code>project</code>:</p>
<pre><code>project = project.s... | python|pandas|dataframe | 2 |
363,493 | 70,250,099 | Convert any currency to USD using Python | <p>I have a dataframe
<code>rates=</code></p>
<pre><code> from_currency to_currency exc_rate date
CAD USD 13 1/1/2020
AED USD 50 2/1/2020
GBP USD 36 2/1/2020
INR USD 72 1/1/2020
</code></pre>
<p>a... | <p>First convert <code>rates</code> to a lookup table:</p>
<pre><code>exc_rate = rates.set_index(['from_currency', 'to_currency', 'date'])['exc_rate']
</code></pre>
<pre class="lang-none prettyprint-override"><code>from_currency to_currency date
CAD USD 1/1/2020 13
AED USD ... | python|pandas|currency | 0 |
363,494 | 70,345,630 | What should I download and how should I download so this code can work? | <pre><code>%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pandas_datareader.data as web**
df = web.DataReader("AAPL", "yahoo", start="2012-9-1", end="2017-8-31")
</code></pre>
<blockquote>
<p>RemoteDataError Traceback (most r... | <p>I usually do this:</p>
<pre><code>%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pandas as pd
import yfinance as yf
from yahoofinancials import YahooFinancials
aapl_df = yf.download('AAPL',
start='2012-09-01',
end='20... | pandas|web|download | 0 |
363,495 | 70,168,760 | Unable to build docker image with tensorflow 2.0 | <p>I have to build a docker image with <code>tensorflow==2.0.0</code> but while issuing the build command I am getting the below error</p>
<pre><code>Could not find a version that satisfies the requirement tensorflow==2.0.0 (from -r requirements.txt (line 6)) (from versions: 0.12.1, 1.0.0, 1.0.1, 1.1.0, 1.2.0, 1.2.1, 1... | <p>Upgrading <code>pip</code> before installing the dependencies from <code>requirements.txt</code> solves the problem</p>
<pre><code>RUN python3 -m pip install --upgrade pip
</code></pre> | python|docker|tensorflow | 0 |
363,496 | 70,364,542 | Concatenate string and Pandas field in an apply lambda | <p>I try to use/concatenate the value from a pandas field with a string in apply-lambda-endswith, but no success...</p>
<p>I explain, I have a df:</p>
<pre><code>FieldA FieldB
U xxx-U.pdf
O zzz-O.pdf
P yyy-Q.pdf
</code></pre>
<p>I would like to get lines where the FieldB does not finish w... | <p>I guess you want to check if values in one column end with another. You can achieve that by calling apply on multiple columns.
Provided that <code>df</code> is:</p>
<pre><code> Field B Field A
0 1/a.pdf a
1 2/b.pdf b
2 3/b.pdf c
3 4/c.pdf d
</code></pre>
<p>You can apply some lambda alo... | python|pandas | 3 |
363,497 | 70,257,052 | Get the whole data frame based on time freq and groupby | <p>Am trying to group by based on time freq for a dataframe. Can I get all the columns instead of just the specified columns in the group by.</p>
<p>code:</p>
<pre><code>df.columns = ['time', 'age', 'salary', 'amount','university', 'gender', 'place', 'education']
</code></pre>
<p>DF:</p>
<pre><code>time age salary ... | <p>First idea is create new column by counts and then remove duplciates by some columns, e.g. :</p>
<pre><code>data['counts'] = data.groupby([pd.Grouper(key='time', freq='4min'),'age', 'salary', 'amount','university'])['age'].transform('size')
df = data.drop_duplicates(['age', 'salary', 'amount','university'])
</code>... | python|pandas|dataframe | 1 |
363,498 | 70,071,209 | How to compare several unordered list and get the list names if there are matching values | <p>I have several lists containing values. just like below.</p>
<pre><code>Alc=['P-111127759','111157751','1123104714']
FItems=['1123104714','797917266','79791761','79791765','79791763']
kuVItem=['1110234713','161231437','756623557','1123104714','7630672177', '754955924','712969245','963176673','181104711']
Products=['... | <p>I assumed that the values are gonna be supplied through a dictionary(which is the only way I can think of for named values whose name change often).</p>
<p>Then just iterate through the keys, and for each key, compare the value with other entries. Since we just want to know if there is overlap, <code>set.intersectio... | python|pandas|list | 4 |
363,499 | 70,211,166 | plotly is labeling my xaxis wrong. how to fix this? | <p>in the image, you can see the final bar is Nov, but plotly is calling Oct Nov 2021. Why and how to fix?</p>
<pre><code>orders_month = orders[['createdAt', 'order_total_usd']]
orders_month_grouped = orders_month.groupby(pd.Grouper(key='createdAt', axis=0, freq='M')).sum().reset_index()
orders_month_grouped['value_lab... | <p>here's a fix: added xaxis_tick0...</p>
<pre><code>fig2 = px.bar(orders_month_grouped, x='createdAt', y="order_total_usd", text='value_labels')
fig2.update_layout(
title="Order Value by Month",
xaxis_title="Month",
yaxis_title="Order Value",
xaxis_tick0 = orde... | python|plotly|pandas-groupby | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.