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
353,800
30,849,018
Scikit Learn - Identifying target from loading a CSV
<p>I'm loading a csv, using Numpy, as a dataset to create a decision tree model in Python. using the below extract places columns 0-7 in X and the last column as the target in Y.</p> <pre><code>#load and set data data = np.loadtxt("data/tmp.csv", delimiter=",") X = data[:,0:7] #identify columns as data sets Y = data[:...
<p>If you have >4 columns, and the 4th one is the target and the others are features, here's one way (out of many) to load them:</p> <pre><code># load data X = np.hstack([data[:, :3], data[:, 5:]]) # features Y = data[:,4] # target # process X &amp; Y </code></pre> <p><em>(with belated thanks to @omerbp for remindi...
python|csv|numpy|scikit-learn|classification
2
353,801
30,793,178
Alternatives to nested numpy.where for multiconditional pandas operations?
<p>I have a Pandas DataFrame with conditional column A and numeric column B. </p> <pre><code> A B 1 'foo' 1.2 2 'bar' 1.3 3 'foo' 2.2 </code></pre> <p>I also have a Python dictionary that defines ranges of B which denote "success" given each value of A. </p> <pre><code>mydict = {'foo': [1, 2], 'bar': [2, 3]} <...
<p>For your question about how to map multiple columns, you do it with </p> <pre><code>DataFrame.apply( , axis =1) </code></pre> <p>For your question I don't think you need this, but I think it's clearer if you do your calculation in a few steps:</p> <pre><code>df['low'] = df.A.map(lambda x: mydict[x][0]) df['high']...
python|numpy|pandas
6
353,802
30,958,670
Pandas map to DataFrame from dictionary
<p>I am currently mapping and renaming various string values to columns in <code>pandas</code> via this function:</p> <pre><code>df["fundbenchmark"] = df["name"].map(lambda x: "American Express" if "AXP" in x else "Apple" if "AAPL" in x else "Google" if "GOOG" in x else "") </code></pre> <p>I will however do this for...
<p>You can use <code>map</code></p> <pre><code>Current DataFrame: Name "BULL AXP UN X3 VON" "BEAR AXP UN X3 VON" "BULL GOOG UN X5 VON" "BEAR GOOG UN X5 VON" "BEAR ABC123 X2 CBZ" companies = {"AXP": "American Express", "GOOG": "Google"} </code></pre> <p>we create a new column that extract the tickers...
python|dictionary|pandas
2
353,803
30,934,126
Pandas append list to list of column names
<p>I'm looking for a way to append a list of column names to existing column names in a DataFrame in <code>pandas</code> and then reorder them by <code>col_start</code> + <code>col_add</code>.</p> <p>The DataFrame already contains the columns from <code>col_start</code>.</p> <p>Something like:</p> <pre><code>import ...
<p>Your code is nearly there, a couple things:</p> <pre><code>df = pd.concat([df,pd.DataFrame(columns = list(col_add))]) </code></pre> <p>can be simplified to just this as <code>col_add</code> is already a list:</p> <pre><code>df = pd.concat([df,pd.DataFrame(columns = col_add)]) </code></pre> <p>Also you can also j...
python-2.7|pandas
3
353,804
67,441,163
How to get dataset from prepare_data() to setup() in PyTorch Lightning
<p>I made my own dataset using <code>NumPy</code> in the <code>prepare_data()</code> methods using the <code>DataModules</code> method of PyTorch Lightning. Now, I want to pass the data into the <code>setup()</code> method to split into training and validation.</p> <pre><code>import numpy as np import pytorch_lightnin...
<p>The same answer as your previous question...</p> <pre><code>def prepare_data(self): a = np.random.uniform(0, 500, 500) b = np.random.normal(0, self.constant, len(a)) c = a + b X = np.transpose(np.array([a, b])) # Converting numpy array to Tensor self.x_train_tensor = torch.from_numpy(X).flo...
pytorch|pytorch-lightning|pytorch-dataloader
1
353,805
67,451,719
How can i reconstruct this dataset so i can compare these two companies?
<p>I have this table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>company</th> <th>store type</th> <th>year</th> <th>average_spend</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>food</td> <td>y1</td> <td>123.4</td> </tr> <tr> <td>B</td> <td>food</td> <td>y2</td> <td>340</td> </tr> <tr>...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>idx = pd.MultiIndex.from_product( [df[&quot;company&quot;].unique(), df[&quot;year&quot;].unique()], names=[&quot;company&quot;, &quot;year&quot;] ) x = df.pivot( values=&quot;average_spend&quot;, index=&quot;store_type&quot;, columns=[&quot;company&q...
python|pandas|dataframe|pivot
2
353,806
67,547,108
Creating a dataframe from different length subject response pairs
<p>I have several dictionaries with country, response pairs, like this:</p> <pre><code>survey_1: {'France': 'Not answered', 'Germany': 'No', 'UK':'Yes'} survey_2: {'France': 'Yes', 'Germany': 'Not answered', 'USA':'Maybe'} survey_3: {'China': 'Yes', 'Germany': 'Yes', 'United Arab Emirates':'Yes'} </code></pre> <p>The l...
<p>Converting multiple dict to a single dict and then use <code>pd.DataFrame</code></p> <p><strong>Ex:</strong></p> <pre><code>data = {&quot;survey_1&quot;: {'France': 'Not answered', 'Germany': 'No', 'UK':'Yes'}, &quot;survey_2&quot;: {'France': 'Yes', 'Germany': 'Not answered', 'USA':'Maybe'}, &quot;survey_3&quot;: {...
python|pandas|dataframe|dictionary
1
353,807
67,510,845
Given multiple prediction vectors, how to efficiently obtain the label with most votes (in numpy/pytorch)?
<p>I have 3 vectors representing the 3 different predictions of labels for the same data:</p> <pre><code>P1=[31, 22, 11, 10, 9, 9, 0, 0, 23 ....] # length over 1M P2=[31, 22, 12, 10, 8, 9, 0, 0, 30 ....] # length over 1M P3=[30, 22, 12, 11, 8, 9, 0, 1, 31 ....] # length over 1M Ans= [31, 22, 12, 10, 8, 9, 0, 0, ...
<p>Using <code>scipy.mode</code> :</p> <pre><code>import numpy as np from scipy.stats import mode combined = np.array([P1, P2, P3]) majority_vote = mode(combined)[0] </code></pre>
python|numpy|machine-learning|pytorch|ensemble-learning
2
353,808
67,592,748
Sample a tensor of probability distributions in pytorch
<p>I want to sample a tensor of probability distributions with shape (N, C, H, W), where dimension 1 (size C) contains normalized probability distributions with ‘C’ possibilities. Is there a pytorch function to efficiently sample all the distributions in the tensor in parallel? I just need to sample each distribution o...
<p>There was no single function to sample that I saw, but I was able to sample the tensor in several steps by computing the cumulative probabilities, sampling each point independently, and then picking the first point that sampled a 1 in the distribution dimension:</p> <pre><code>reverse_cumulative = torch.flip(torch.c...
pytorch
0
353,809
67,358,348
Convert torch model (torch.save) into matricial formulas that can be handled with basic Python
<p>Please could you tell me if it is feasible to transform a torch model (torch.save) into algebraic matrices/ equations that can be operated with numpy or basic Python, without the need to install torch and other related libraries (that occupy a lot of space)? In an afirmative case, could you please give me some hints...
<p>I'm not aware of any way to do this without a lot of your own work. Basically you'd have to port most of the pytorch library to numpy, which would be a huge project. If space is an issue check if you can save some space by e.g using earlier torch versions or using only the CPU-versions of pytorch.</p>
numpy|torch
0
353,810
67,600,810
Find local duplicates (which follow each other) in pandas
<p>I want to find local duplicates and give them a unique id, directly in pandas.</p> <p><strong>Reallife example:</strong></p> <p>Time-ordered purchase data where a customer id occures multiple times (because he visits a shop multiple times a week), but I want to identify occasions where the customer purches multiple ...
<p>You can compare whether your column test is not equal to it's shifted version, using <code>shift()</code> with <code>ne()</code>, and use <code>cumsum()</code> on that:</p> <pre><code>df['out'] = df['test'].ne(df['test'].shift()).cumsum() </code></pre> <p>Which prints:</p> <pre><code>df test out 0 A 1 1 ...
python|pandas
2
353,811
67,284,093
How can I use nltk to get resonse
<p>I am going to get response from nltk. I don't have any idea for this.</p> <p>If you have a source code or reference link, please share it. I tried myself several time but it was failed.</p>
<p>I found one link for this question. <a href="https://www.nltk.org/_modules/nltk/chat/eliza.html" rel="nofollow noreferrer">https://www.nltk.org/_modules/nltk/chat/eliza.html</a></p>
python|tensorflow
1
353,812
67,406,029
How can I do multiple pandas dataframes samples iterating over a dictionary?
<p>I have a dictionary like this:</p> <pre><code> dic= {'AGS': array([1, 1, 1, 2, 2, 2, 3, 3, 3], dtype=int64), 'CM': array([1, 1, 2, 2], dtype=int64), 'COA': array([1, 1, 1, 2, 2, 3, 3], dtype=int64), 'COL': array([1, 2], dtype=int64)} </code></pre> <p>And a dataframe like this:</p> <pre><code>c = pd.DataFrame(data={'...
<p>IIUC, you may need a dictionary comprehension:</p> <pre><code>d = {key: c[c['CTY'].eq(key) &amp; c['DIST'].isin(set(val))].sample(n=2) for key,val in dic.items()} </code></pre> <hr /> <p>Post this you can access each key to access the dataframes:</p> <p>Example:</p> <pre><code>print(d['AGS']) CTY DIST F...
python|pandas|dictionary|list-comprehension
1
353,813
67,528,560
Need to show column name in a row after taking transpose in python
<pre><code>features_df = (pd.concat(feature_weight_list) .pivot(index='n', columns='features', values='values')) print(features_df) features_df.to_csv (r'C:/Users/USER12/Downloads/AB.csv', index = False, header=True) </code></pre> <p>I am saving this file at its pattern is like that</p> <p>feature 1 , ...
<p>Setting the <code>index</code> to <code>False</code> in the <code>DataFrame.to_csv</code> method will remove the indexing, which has become the column names after the transposition of the dataframe. Try removing <code>index=False</code> when saving the dataframe to a csv file.</p> <pre><code>features_df_T.to_csv(r'C...
python|pandas|numpy|matrix
1
353,814
67,522,863
Generate a random bool with Tensorflow
<p>How to efficiently generate a random bool with Tensorflow? Doesen't need to be cryptographically safe. Ideally only using <code>tensorflow as tf</code>.</p>
<p>TensorFlow (2.9.1) documentation seems to give this:</p> <p>Code:</p> <pre><code># samples has shape [1, 5], where each value is either 0 or 1 with equal # probability. samples = tf.random.categorical(tf.math.log([[0.5, 0.5]]), 5) print(samples) # I added this line </code></pre> <p>Result:</p> <pre><code>tf.Tensor([...
python|tensorflow
0
353,815
67,225,341
How to go forward/backward from a specific date in PANDASQL e.g. as in oracle date-1 ,and in impala DAYS_ADD(date,-1)
<p>I am new to python and I am using <code>pandasql</code> to perform condition-based joins:</p> <pre><code>from pandasql import sqldf pysqldf = lambda q: sqldf(q, globals()) q = &quot;&quot;&quot; SELECT * FROM a_Df A INNER JOIN b_Df B ON a.effective_da...
<p>as this <code>pandasql/sqldf</code> work on <code>sqlite</code> so anyone can try any function that <code>sqlite</code> support, hence the syntax would be like this..</p> <pre><code>from pandasql import sqldf pysqldf = lambda q: sqldf(q, globals()) q = &quot;&quot;&quot; SELECT * FROM a_Df A...
python|pandas|data-science|pandasql
-1
353,816
67,574,070
Derive the Minimum value in the pandas dataframe and its respective column derivation
<p>I have a dataframe:</p> <pre><code>data = np.array([[10,50,75,'test1','test2','test3'], [1000,500,175,'test1','test2','test3'], [500,50,750,'test1','test2','test3'], [1,500,5,'test1','test2','test3'], [50,500,15,'test1','test2','test3']]) df = ...
<p>This is essentially a <code>lookup</code> problem where we first select the <code>distance</code> columns then find the index of minimum values by using <code>argmin</code> along <code>axis=1</code> , then using these indices lookup the values in the corresponding <code>_rep</code> like columns</p> <pre><code>c = df...
python|pandas|dataframe
2
353,817
67,584,932
New rolling mean column which group by one column and find rolling mean of another column
<p>I have a dataframe df</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Orders</th> <th>Group</th> </tr> </thead> <tbody> <tr> <td>1/1/2021 00:00:00</td> <td>20</td> <td>A</td> </tr> <tr> <td>1/1/2021 00:12:00</td> <td>100</td> <td>B</td> </tr> <tr> <td>2/1/2021 00:00:00</td>...
<p>This worked for me:</p> <pre><code>df['Rolling Mean'] = df['Orders'].rolling(window=pd.Timedelta(days=14)).mean() </code></pre> <p>Note that the <code>min_periods</code> argument in the <code>pd.rolling()</code> method takes an integer and doesn't handle time series easily, so you'll need to overwrite the first 14 d...
python|pandas|group-by|mean|rolling-computation
0
353,818
67,291,750
Matching two identical groups of characters in pandas with some number of characters in between
<p>I'm trying to extract two numbers of interest from a string of docket text in a pandas dataframe. Here's an example with a couple of the idiosyncrasies that exist in the data</p> <pre><code>import pandas as pd df = pd.DataFrame([&quot;Fee: $ 15,732, and Expenses: $1,520.62.&quot;]) </code></pre> <p>I used regexr to...
<p>I am not sure if the text stays the same across all of the values but you can use the following regex:</p> <pre><code>r'Fee: \$\s?([\d,.]+), and Expenses:\s*\$\s?([\d,.]+)\.' </code></pre> <p><a href="https://pythex.org/?regex=Fee%3A%20%5C%24%5Cs%3F(%5B%5Cd%2C.%5D%2B)%2C%20and%20Expenses%3A%5Cs*%5C%24%5Cs%3F(%5B%5Cd...
python|regex|pandas
2
353,819
67,233,536
Populate dict and json with pandas dataframe data
<p>I need help populating a json with a pandas dataframe that looks like this:</p> <pre><code> vacantes = pd.DataFrame([{'reg': 'Apodaca', 'puesto': 'Agente telefónico', 'info': 'izzi estamos buscando personas con vocación en el #Servicio al #Cliente que pueda ayudarnos a brindarle una excelente experienc...
<p>You could try this:</p> <pre class="lang-py prettyprint-override"><code># Use list() to get column values elements = [ { &quot;title&quot;: list(vacantes[&quot;puesto&quot;]), &quot;image_url&quot;: list(vacantes[&quot;imagen&quot;]), &quot;subtitle&quot;: list(vacantes[&quot;info&quot;])...
python|json|pandas|dictionary|parsing
0
353,820
67,206,800
Convert Rows as Column Headers
<p>I have the following dataframe:</p> <pre><code>--------------------------------------------------------------- | | TORA | PS | Hutan Adat | Tahun | Bulan | Dashboard Name | --------------------------------------------------------------- |0| 0 | 0 | 0 | 2021 | Jan | Potensi | |1| 0 | ...
<p>First set <code>Bulan</code> columns to ordered Categoricals, for correct sorting:</p> <pre><code>months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] df.Bulan = pd.Categorical(df.Bulan, ordered=True, categori...
python|pandas|dataframe|pandas-groupby|transpose
1
353,821
67,423,230
Training a model with metadata instead of images
<p>I want to do a Multi-layer perceptron that has only Metadata(age, gender) as input. After some research, I've decided on a single Fully Connected layer with 500 neurons followed by a softmax layer of size 8(there are 8 categories).</p> <p>I've arranged my metadata in arrays using one hot encoding. One array is of si...
<p><code>fit()</code> is a generic method that you'll find in most machine learning libraries (Keras/Tensorflow, scikit-learn, etc). It means to train your model, and it isn't dependent on the input data being images. The name comes from &quot;fitting&quot; the output of the model to match the target (if you picture ...
python|tensorflow|keras
1
353,822
67,463,806
Vectorizing thetas, rs combinations with numpy
<p>I am generating thetas, radius ranges, cos_thetas and sin_thetas using numpy.</p> <p>I am still left with code that is highly inefficient, in terms of getting those combinations.</p> <p>I have tried to go down the path of vectorization but reshaping makes things worse.</p> <p>I currently have the following code:</p>...
<p><a href="https://numpy.org/doc/stable/user/basics.broadcasting.html#broadcasting" rel="nofollow noreferrer">Broadcasting</a> is your friend:</p> <pre><code>d = np.zeros((num_thetas*rs.size, 3), order = &quot;F&quot;, dtype = int) d[:,0] = np.repeat(rs, num_thetas) d[:,1] = np.ravel(rs[:,None] * cos_thetas[:num_theta...
python|numpy
3
353,823
67,220,134
How to select a previous row with pandas
<p>I'm using pandas to read the data frame, I want to divide the value of a row with the previous value of the same row and so on. For example:</p> <pre><code>1017.0 1000.0 969.0 </code></pre> <p>I want 1000/1017 then 969/1000 ... Thanks in advance!</p>
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.shift.html" rel="nofollow noreferrer"><strong><code>Series.shift()</code></strong></a> for a specific column or <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.shift.html" rel="nofollow noreferrer"><strong><code>DataF...
python|pandas|dataframe
2
353,824
67,294,255
How to fit train and validation data together
<pre><code>history = model.fit( train_generator, validation_generator, steps_per_epoch= 2403//32, epochs= 5, ) </code></pre> <p>This is the code , that I'm currently using and I'm getting the following error: <code>ValueError: 'y' argument is not supported when using 'keras.utils.Sequence' as input.</co...
<p>You need to pass your validation data as follows when your inputs are generated from the generator.</p> <pre><code>history = model.fit( train_generator, validation_data=validation_generator, steps_per_epoch= 2403//32, epochs= 5, ) </code></pre>
tensorflow|model-fitting
0
353,825
67,461,657
triple nested for loops in python to update pandas dataframe
<p>I have honestly tried all possible solutions, I think I am nearly there but still something is not working I have a dataframe with coin names and their tags.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>coin</th> <th>tags</th> </tr> </thead> <tbody> <tr> <td>bitcoin</td> <td>[mineable...
<p>You can use <code>get_dummies</code>:</p> <pre><code># After you have generated `tags` DataFrame with # tags = df_new[['name','tags']] pd.get_dummies(tags.set_index('name')['tags'].explode()).sum(level=0) </code></pre> <p>Output (only showing the first 3 columns here to illustrate the result):</p> <pre><code> ...
python|pandas
0
353,826
67,409,042
Use Adam optimizer for LSTM network vs LBGFS
<p>I have modified <a href="https://github.com/pytorch/examples/blob/master/time_sequence_prediction/train.py" rel="nofollow noreferrer">pytorch tutorial</a> on LSTM (sine-wave prediction: given [0:N] sine-values -&gt; [N:2N] values) to use Adam optimizer instead of LBFGS optimizer. However, the model does not train we...
<p>I've just executed your code and the original code. I think the problem is you didn't train your code with ADAM long enough. You can see your training loss is still getting smaller at step 15. So I changed the number of steps from 15 to 45 and this is the figure generated after step 40:</p> <p><a href="https://i.sta...
python|optimization|pytorch|lstm|lstm-stateful
1
353,827
67,388,244
Why conda cannot install tensorflow gpu properly on Windows?
<p>I was using Linux at work and am used to install tensorflow GPU version via Conda.</p> <p>The Linux machine has NVIDIA driver, and nvidia-smi runs properly.</p> <p>The command I use is</p> <pre><code>conda install python tensorflow-gpu </code></pre> <p>Magically, conda takes care of everything. It installs cudatoolk...
<p>I do not have much expertise with how conda works as I have manually downloaded and configured tensorflow with CUDA and cuDNN.</p> <p>To answer your question I'd recommend going through this blog, <a href="https://towardsdatascience.com/setting-up-tensorflow-gpu-with-cuda-and-anaconda-onwindows-2ee9c39b5c44" rel="no...
windows|tensorflow|conda|nvidia
0
353,828
67,479,134
How to add additional text to matplotlib annotations
<p>I have used seaborn's titanic dataset as a proxy for my very large dataset to create the chart and data based on that.</p> <p>The following code runs without any errors:</p> <pre><code>import seaborn as sns import pandas as pd import numpy as np sns.set_theme(style=&quot;darkgrid&quot;) # Load the example Titanic ...
<ul> <li><code>dfl2.T</code> is being plotted, but <code>'survival rate %'</code> is in <code>result</code>. As such, the indices for the values from <code>dfl2.T</code> do not correspond with <code>'survival rate %'</code>.</li> <li>Because all of values in <code>result['% total dist by xdim']</code> <strong>are not u...
python|pandas|matplotlib|seaborn|bar-chart
3
353,829
67,267,440
torch concat 1D to a 2D tensor
<p>I have a issue on concat 2 tensor,</p> <p>say I have x and y:</p> <pre><code>x = torch.randn(35, 50) y = torch.randn(35) </code></pre> <p>How do I concat every y value in to x[0] to make x has a shape 35,51?</p> <p>I tried:</p> <pre><code>for i in y: for a in range(x.shape[0]): x[a] = torch.cat((x[a],i),...
<p>This should work:</p> <pre class="lang-py prettyprint-override"><code>z = torch.cat([x,y.reshape(-1,1)], axis=1) print(z.shape) </code></pre> <p>Output:</p> <pre><code>torch.Size([35, 51]) </code></pre>
vector|pytorch|concatenation
2
353,830
67,283,857
Flutter - Isolate : NoSuchMethodError: The method 'toRawHandle' was called on null
<h2>Goal</h2> <p>I'm trying to perform real-time object detection with a Flutter app, using Tensorflow 2, with a SSD Mobilenet V2 model</p> <ul> <li>I managed to get this work, using <a href="https://github.com/shaqian/flutter_realtime_detection" rel="nofollow noreferrer">this git repo</a></li> <li>However, I am encoun...
<p>Isolates don't share memory between them, which means you can only use primitive values and static/top-level functions. The <code>entryPoint</code> is not a static/top-level function in your case.</p> <p>Check out the easy_isolate plugin, it provides an easy way to work with isolates with well-explained documentatio...
flutter|tensorflow|dart|object-detection|dart-isolates
1
353,831
67,557,958
Building tf.data pipeline with list of files i.e. pickle dataframe
<p>I am not able to build the <code>tf.data</code> pipeline (with Tensorflow 2.1.0 on python 3.7.7 &amp; Windows 10) for a list of pickled dataframes. To get started use the below code:</p> <pre><code>import numpy as np import pandas as pd import os, pickle import tensorflow as tf from tensorflow.keras.preprocessing.se...
<p>Replace read_pickles function as</p> <pre><code>def read_pickles(filename): with open(filename, 'rb', encoding=&quot;utf8&quot;) as f: df_ = pickle.load(f) return df_ </code></pre>
python|tensorflow|data-preprocessing
0
353,832
67,303,539
How to encode categorical data for a multiclass classification in Tensorflow to avoid Shape mismatch
<p>I have a dataframe with a column for article body <code>text</code>, and a column for topic labels <code>topic</code>. <code>topic</code> contains lists of labels.</p> <pre><code>&gt;&gt;&gt; df.topic.head(5) 0 [ECONOMIC PERFORMANCE, ECONOMICS, EQUITY MARKE... 1 [CAPACITY/FACILITIES, CORPORATE/INDUSTRIAL...
<blockquote> <p>num_labels=df['topic_encoded'].unique().shape[0]</p> </blockquote> <p>do not get unique - in such a way you are reducing the shape of your labels in its size... the errorValue tells you exactly about this &quot;<em>Shape mismatch: The shape of labels (received (1,)) should equal the shape of logits</em>...
python|pandas|tensorflow|encoding|bert-language-model
0
353,833
67,545,122
Can't fix: RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation
<p>Currently, I’m trying to replicate a DeblurGanV2 network. At the moment, I’m working on performing the training. Here is my current status of my trainings pipeline:</p> <pre><code>from torch.autograd import Variable torch.autograd.set_detect_anomaly(mode=True) total_generator_loss = 0 total_discriminator_loss = 0 ps...
<p>try changing the last line to:</p> <pre class="lang-py prettyprint-override"><code>discriminator_loss = discriminator_loss + discriminator_loss_per_update.item() </code></pre>
python|deep-learning|pytorch|generative-adversarial-network
0
353,834
67,324,351
How to get value from a row in Pandas DataFrame?
<p>I have a pandas data frame that contains one row. I know what the column names are in this row. I would like to pull the value (just the value, not the type, or other metadata) from each cell in this row. How do I do this? I am using Python 3.</p> <p>I have tried the following, but it always fails, because you can't...
<p>If it's single row, You should be fine using something like this:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; data_frame['colName'].values[0] Out[8]: 1 </code></pre> <p>Or,</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; data_frame['colName'].iloc[0] Out[9]: 1 </code></pre> <p>O...
python|python-3.x|pandas|dataframe
1
353,835
67,242,249
How I write a python code for multiply each element in row?
<p>Here is a data frame I wanted same output.<br /> Please tell me how should I write a python code to solve question...</p> <p>DF</p> <pre><code> A B C 1 1 2 3 2 1 3 5 3 1 1 1 </code></pre> <p>And I need A output like</p> <p>Answer:</p> <pre><code> Multiplication 1 6 2...
<p>Use <code>DataFrame.prod</code> over <code>axis=1</code></p> <pre><code>df.prod(axis=1) 1 6 2 15 3 1 dtype: int64 </code></pre>
python|python-3.x|dataframe|pandas
3
353,836
67,265,479
How do Linear regression - predict more efficient?
<p>I need to change the following method to calculate and return the linear regression prediction (for either the multivariate or the univariate case).</p> <p>Note: the 'predict' method should be used both for the predictions on the test-set, as well as during the training process.</p> <p><strong>input parameters:</str...
<p>Assuming you have a fictive column, the prediction is just vector of dot products of each row with weight vector:</p> <pre><code>def predict(x_featureVectors, trained_w): return np.dot(x_featureVectors, trained_w) </code></pre>
python|pandas|numpy|machine-learning|linear-regression
1
353,837
67,203,664
How to change PyTorch sigmoid function to be steeper
<p>My model works when I use <code>torch.sigmoid</code>. I tried to make the sigmoid steeper by creating a new sigmoid function:</p> <pre><code>def sigmoid(x): return 1 / (1 + torch.exp(-1e5*x)) </code></pre> <p>But for some reason the gradient doesn't flow through it (I get <code>NaN</code>). Is there a problem in...
<p>You put a dilation of 1e5 in your exponential. The exponential of 1e5 is so unbelievably high that there is no hope to get meaningful result here. You are probably getting a NaN because you are trying to backpropagate through a computational graph which at some point is evaluated to <code>inf</code> (and beyond!)</p...
python|pytorch|sigmoid
2
353,838
67,361,295
Best way to store pandas df data for recall in analysis
<p>I have a large df in pandas that has a company's product information. Here is a small sample of rows with only the columns I believe are needed to get the information I desire.</p> <pre><code>df = pd.DataFrame({'Customers': [1,2,3,4,5,6]*3, 'Product':['Beer1','Beer2','Beer1','Beer4', 'Beer3', 'Bee...
<p>If what you are looking for is the total revenue each packaging type is bringing, you can simply do groupby.</p> <p><code>df.groupby('Packaging')['Sale_Price'].sum()</code></p> <p>output:</p> <pre><code>Packaging 12pack 102 18pack 297 22 oz bottle 162 6pk 75 big_keg 225 keg ...
python|pandas
-1
353,839
67,522,402
Export data from MSSQL to Excel 'template' saving with a new name using Python
<p>I am racking my brain here and have read a lot of tutorials, sites, sample code, etc. Something is not clicking for me.<br /> Here is my desired end state.</p> <ol> <li>Select data from MSSQL - Sorted, not a problem</li> <li>Open an Excel template (xlsx file) - Sorted, not a problem</li> <li>Export data to this Exc...
<p>Your method is work. The problem is you don't need to write the data into excel file right after you read the data from the database. My suggestion is first read the data into different data frame.</p> <pre><code>df1 = pd.read_sql(script) df2 = pd.read_sql(script) df3 = pd.read_sql(script) </code></pre> <p>You can t...
python|excel|pandas
0
353,840
67,245,671
ValueError: unconverted data remains: 72
<p>Im trying to change the object of the first column into Datatime format. The data looks like this.</p> <p>23.08.1972 798 800 795 800</p> <p>If tried this function</p> <pre><code>df.loc[:, &quot;Datum&quot;] = pd.to_datetime(df.Datum, format = &quot;%d.%m.%y&quot; ) </code></pre> <p>where &quot;Datum&quot; i...
<p>use one extra argument error = 'coerce' it'll convert the value to NaN if the format is wrong -</p> <pre><code>df.loc[:, &quot;Datum&quot;] = pd.to_datetime(df.Datum, format = &quot;%d.%m.%y&quot; ,errors= 'coerce') </code></pre> <p>Then check for NAN values in that particular column.</p>
python|pandas
0
353,841
67,248,686
Neural network learning to sum two numbers
<p>I am learning Pytorch, and I am trying to implement a really simple network which takes an input which is of length 2, i.e. a point in the plane, and aims to learn the sum of its components.</p> <p>In principle the network should just learn a linear layer with weight matrix W = [1.,1.] and zero bias, so I expect to ...
<p>There are 2 problems.</p> <p><strong>The first problem</strong> is that you forgot to backpropogate the loss:</p> <pre class="lang-py prettyprint-override"><code>optimizer.zero_grad() loss.backward() # you forgot this step optimizer.step() </code></pre> <p>It is important that <code>optimizer.zero_grad()</code> IS N...
deep-learning|neural-network|pytorch|linear-regression
3
353,842
67,479,348
ValueError: Input arrays should have the same number of samples as target arrays. Found 0 input samples and 121 target samples
<p>I'm trying to do a 6-class classification. Here is the code:</p> <pre><code>############### CONFIG_CNN3D ############## RESULT_PATH = 'results3d' MODEL_NAME = 'saved3d' MODEL = 'cnn3d' CHANCE = .01 TEST_TRAIN_SPLIT = .2 SIZE3D = (64, 64) DEPTH = 3 CHANNELS = 1 BATCH_SIZE = 128 EPOCHS = 30 EXTRACT = False ###########...
<blockquote> <p>Considering the channels and depth you are mentioning is same. You can replace your code using this snippet. The output shape of the X_train should be (121, 64, 64, 1).</p> </blockquote> <pre><code> X = np.array(data) X = X.reshape((X.shape[0], *config3d.SIZE3D, config3d.CHANNELS)) ...
python|arrays|tensorflow|keras
0
353,843
67,500,065
Open large geotif file
<p>I have very large geotif file. But I can not open it in colabs. RAM is not enough. So all the time I run it began crash. can come one help me with this?</p> <pre><code>import numpy as np from rasterio.plot import show import os import matplotlib.pyplot as plt %matplotlib inline # Data dir data_dir = &quot;data&quot...
<p>You can work on smaller portions more like windows. Below code reads 400x400 window from (0, 0) point.</p> <pre><code>with rasterio.open('/content/drive/MyDrive/LINEasia/test2.tif') as f: w = f.read(1, window=Window(0, 0, 400, 400)) </code></pre>
python|raster|ram|geopandas|geotiff
3
353,844
67,588,162
Pands - Error: "No numeric types to aggregate" on numeric column
<p>I am trying to groupby a dataframe by a string column (<code>b</code>) and get mean over the other column (<code>a</code>). When doing this I get an error I don't currently understand.</p> <pre><code>import pandas as pd df = pd.DataFrame({ 1 : {'a':10,'b':'string1'}, 2 : {'a':20,'b':'string1'}, 3 : {'a'...
<p>You are getting the error because <code>both columns are object type</code>.</p> <pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 4 entries, 1 to 4 Data columns (total 2 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 a 4 non-null object 1 b ...
python|pandas|dataframe
1
353,845
67,461,147
numpy shape inconsistent with array structure
<p>I am going mad over this thing.</p> <p>I have 2 lists</p> <pre><code>A = [ [[1,2,3],[1,2,3],[1,2,3]], [[1,2,3],[1,2,3],[1,2,3]]] B = [ [[1,2,3],[1,2,3],[1,2,3]], [[1,2,3],[1,2,3]]] </code></pre> <p>When I call the shape of A and B as numpy array I get this:</p> <pre><code>In [33]: np.asarray(A).shape Out[33]: (2, 3,...
<p>Your 2 lists:</p> <pre><code>In [232]: A Out[232]: [[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]] In [233]: B Out[233]: [[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3]]] </code></pre> <p>Now, explain why the <code>B</code> result is better than the <code>A</code> one?</p> <pre><code...
arrays|list|numpy|object|shapes
0
353,846
67,409,990
How to deal with misssing values in Pandas
<p>I´d like to know when we have a dataset with missing values, what´s the best way to treat them? Remove them directly or replace with zeros?</p> <p>Suppose i have these dates:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">id</th> <th style="text-align: center;"...
<p>It is possible to index the <code>'nd'</code> rows inside the <code>product_group</code> column, and then drop them from the original dataframe:</p> <pre><code>import pandas as pd i= order[(order.product_group=='nd')].index order.drop(i) </code></pre>
python|pandas|product|nan|missing-data
0
353,847
67,397,927
Successive zeroing of columns of a numpy array
<p>I have an array <code>a</code> of ones and zeroes (it might be rather big)</p> <pre><code>a = np.array([[1, 0, 0, 1, 0, 0], [1, 1, 0, 0, 1, 0], [0, 1, 1, 0, 0, 1], [0, 0, 0, 1, 1, 1]) </code></pre> <p>in which the &quot;upper&quot; rows are more &quot;important&quot; in the ...
<p>An alternative solution is to do a forward fill followed by the cumulative sum and then replace all values which are <em>not</em> 1 with 0:</p> <pre><code>a = np.array([[1, 0, 0, 1, 0, 0], [1, 1, 0, 0, 1, 0], [0, 1, 1, 0, 0, 1], [0, 0, 0, 1, 1, 1]]) ff = np.maximum.accumula...
python|arrays|numpy
2
353,848
67,189,640
How to convert vstack code to for-loop (Python)?
<p>I currently have a list (list_arr) containing 8 numpy arrays with the following sizes:</p> <pre><code>0. (6300, 6675, 3) 1. (5560, 6675, 3) 2. (5560, 6675, 3) 3. (5560, 6675, 3) 4. (6300, 6675, 3) 5. (5560, 6675, 3) 6. (5560, 6675, 3) 7. (5560, 6675, 3) </code></pre> <p>I want to stack the arrays in batches of 4 (e....
<p>You can slice your array list and pass the required sliced array to your function</p> <p>check the below sample code:</p> <pre><code>arr_list = [1,2,3,4,5,6,7,8,9,0,12,33,45,66,77,88,23,21] start = 0 for i in range(0,len(arr_list),4): if i == 0: continue print(arr_list[start:i]) start = i if star...
python|arrays|numpy|for-loop|vstack
0
353,849
67,385,342
Sequential network with the VGG layers
<p>I want to have a sequential network with the characteristics of VGG network (I want to pass my network to another function, which doesn't support VGG objects and supports nn.sequential).</p> <p>I added the function getSequentialVersion method to VGG class to have the sequential network with the linear layer. However...
<p>The problem is quite simple. When <code>flag=True</code> (as in <code>getSequentialVersion()</code>), there's a missing <code>Flatten</code> operation. Therefore, to fix the problem, you need to add this operation like this:</p> <pre class="lang-py prettyprint-override"><code>if flag: # for Cifar10 layers +=...
python|deep-learning|neural-network|pytorch|vgg-net
1
353,850
67,428,236
Code syntax for retrieving, adding multiple return values from funciton
<p>Lets say i have a dataframe df with columns a, b like below: a b 1 4 2 5 3 6</p> <p>Lets assume we have similar function which returns 2 values</p> <pre><code>fun calc(a, b, type): if type=='both': c=a+b d=a-b return c, d </code></pre> <p>how to store the returned values to a new column in dataframe df i tried ...
<p>You use the following code</p> <pre class="lang-py prettyprint-override"><code>df[['c', 'd']] = df['a', 'b'].apply(calc, type='both', axis=1) </code></pre> <p>There are several issues:</p> <ol> <li>To select multi columns, you need to use a list of column names, like <code>df[['a', 'b']]</code>.</li> <li><a href="ht...
python|python-3.x|pandas|dataframe
0
353,851
67,315,688
Converting a dataframe into a nested JSON after groupby and melt
<p>I have a dataframe as follows:</p> <pre><code>PayeeID TransactionID Res_1 Res_2 1001 aa1001234 OK OK 1001 aa1001235 OK NOT OK 1002 aa1002567 NOT OK NOT OK 1002 aa1002568 NOT OK OK </code></pre> <p>Now I want to have this converted...
<p>Pandas doesn't know your desired data format. You need to create that in the dataframe first and then output to JSON. The following gets you one entry per payee.</p> <pre><code>df = pd.DataFrame([ [1001, &quot;aa1001234&quot;, &quot;OK&quot;, &quot;OK&quot;,], [1001, &quot;aa10012...
python|pandas
1
353,852
67,549,390
how to loop through columns of a dataframe which have intezers as column names
<p>I have a dataframe with column names as <code>1,2,3,4..10</code> . I have sub category of columns as</p> <pre><code>sub_cols = ['1','2','3'] </code></pre> <p>I want to loop through these sub_cols</p> <pre><code>for col in sub_cols: print('column: '+str(col)) data[col] len(data[col]) </code></pre> <p>I ge...
<p>Your code corrected:</p> <pre class="lang-py prettyprint-override"><code>for col in sub_cols: print('column: '+str(col)) print(data[col]) print(len(data[col]) </code></pre>
python|pandas|dataframe
0
353,853
67,515,685
Basic regression example not fitting
<p>I am trying to convert a code sample from a Tensorflow 1.3.x course to Tensorflow 2.x. Why is this fit so wildly off?</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import tensorflow as tf np.random.seed(101) tf.random.set_seed(101) x_data = np.linspace(0, 10, 100) + np.random.uniform(-1.5, 1.5, ...
<p><code>minimize</code> computes the gradients(using <a href="https://www.tensorflow.org/api_docs/python/tf/GradientTape" rel="nofollow noreferrer">GradTape</a>) and applies gradients by <code>apply_gradients</code> method. So you are basically, computing the gradients and optimizing for one iteration.</p> <p>You can ...
python|tensorflow
1
353,854
67,226,923
tf.image.decode_jpeg often taking forever to load file
<p>The following code is part of my code for a tf graph to read images. When I use this code to iterate through the data, the program gets stuck in <code>tf.io.read_file(path)</code> after a few hundred images forever and doesn't do anything. More specifically, the code even can't be paused and I had to restart the ses...
<p>As mentioned in the comment, try the following function to decode the image file as it can handle mixed extension file format (<code>jpg</code>, <code>png</code> etc), <a href="https://www.tensorflow.org/api_docs/python/tf/io/decode_image" rel="nofollow noreferrer">ref</a>.</p> <pre><code>tf.io.decode_image(image, e...
python|tensorflow|keras
1
353,855
67,352,535
Merge data frames based on substrings- python
<p>I have two data frames where I want to merge based on a column in one df having substring in second df, how can I do it ?</p> <p>Here is 1st dataframe</p> <pre><code>Flower Id city Jasmine 1023 hawai Lotus 3405 st Jose BudRose 4409 Miami Lily 2457 Washington </code></pre> <p>2nd dataframe</p> <pre><co...
<pre><code>df1.merge(df2.groupby('Flower').first(), how='inner', on='Flower').rename(columns={'Id_y':'Id', 'city_y':'city'}).drop(['Id_x', 'city_x'], 1) </code></pre> <p><strong>Output</strong></p> <pre><code> Flower Id city 0 Jasmine 1023LD Hawai 1 Lily 2457MH Washington </cod...
python|pandas|substring
0
353,856
67,434,675
Vectorizing nested for-loops
<p>I have 2 for loops, which I would like to modify with vectorization, since the 2 for loops take ages till they finish.</p> <p>prerequisites:</p> <pre><code>import osmnx as ox ox.config(use_cache=True, log_console=True) # Create Graph of any city place_name = &quot;any city in the world&quot; ### Enter your city G ...
<p>Not every problem can be vectorized. Dijkstra's algorithm (for shortest path calculation) is an example of this. However, other parts of your code can be vectorized or otherwise made more efficient, and shortest path calculation can be <em>parallelized</em>.</p> <ol> <li>Move all of your <code>iloc</code> code out o...
python-3.x|numpy|for-loop|vectorization|osmnx
2
353,857
67,544,800
How normalize the tensor signal in tensorflow 1.x
<p>I have a tensor signal X (a signal which represent the output of neural network). I want to normalize it as the following line written in matlab:</p> <pre><code>Y = X*sqrt(length(X))/norm(X); </code></pre> <p>following Tf1 guide, I did it as below:</p> <pre><code>Y = tf.math.divide(tf.math.multiply(X , tf.math.sqr...
<p>As per our discussion, TensorFlow is sensitive to the data types that are used in the math operators. The solution to this problem is to use the first dimension of the data's shape, i.e., <code>tf.shape(X)[0]</code>, and then cast it to <code>tf.float32</code> type, since the output of your neural network is in that...
python|tensorflow|deep-learning|neural-network
1
353,858
34,552,284
Vectorize haversine distance computation along path given by list of coordinates
<p>I have a list of coordinates and can calculate a distance matrix among all points using the <a href="https://en.wikipedia.org/wiki/Haversine_formula" rel="noreferrer">haversine distance</a> metric. </p> <p>Coordinates come a as <code>numpy.array</code> of shape <code>(n, 2)</code> of <code>(latitude, longitude)</co...
<p>Here's one way you can vectorize that calculation without creating a big matrix. <code>coslat</code> is the array of cosines of the latitudes, and <code>coslat[:-1]*coslat[1:]</code> is the vectorized version of the expression cos(ϕ<sub>1</sub>)cos(ϕ<sub>2</sub>) in the Haversine formula.</p> <pre><code>from __fut...
python|numpy|vectorization|distance|haversine
9
353,859
34,859,683
Reorder a dictionary to fit a data frame
<p>I have I <code>dictionary</code> in this format:</p> <pre><code>d = {'Name 1': list_of_links,'Name 2': list_of_links,'Name 3': list_of_links} </code></pre> <p>need to put this data in a <code>DataFrame</code>, with two <code>columns</code>:</p> <pre><code>Names and Links Name 1 -&gt; Link Name 1 -&gt; Link ...
<p>Starting with a <code>dict</code> of two names and 10 different <code>links</code> each:</p> <pre><code>d = {'Name 1': ['link{}'.format(l) for l in list(range(10))], 'Name 2': ['link{}'.format(l) for l in list(range(10, 20))]} {'Name 1': ['link0', 'link1', 'link2', 'link3', 'link4', 'link5', 'link6', 'link7', 'lin...
python|dictionary|pandas
2
353,860
34,794,725
How can I substitute various long strings for a shorter strings throughout my dataframe?
<p>I'd like to replace a long string in my dataframe with a much shorter string. I have a short dictionary of replacements I want to make.</p> <pre><code>import pandas as pd from StringIO import StringIO replacement_dict = { "substring1": "substring1", "substring2": "substring2", "a short substring": "sub...
<p>You can do this type of thing with <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.DataFrame.replace.html" rel="nofollow"><code>.replace()</code></a>. However, you will have to modify your dictionary slightly to get the result you expect.</p> <pre><code>replacement_dict = { ".*subs...
python|pandas
1
353,861
34,597,776
Join two python arrays via index
<p>i have a problem in Python. I am creating two numpy arrays from dict entries. I want to join those two numpy arrays in a specific way like this:</p> <pre><code># create array with classes probVec = filePickle['classID'] a = np.empty([0, 1]) for x in np.nditer(probVec): a = np.append(a,x) timeVec = filePickle[...
<p>Using a comparison operator on an array, like <code>a == 3.0</code>, you get a boolean array that can be used for indexing, selecting the rows where the condition is true.</p> <pre><code>In [87]: a = np.random.randint(low=1, high=4, size=10) # example data In [88]: a Out[88]: array([3, 1, 3, 1, 1, 3, 2, 2, 2, 2]...
python-3.x|numpy|multidimensional-array
1
353,862
34,714,092
How to compute gradients to fool an image classifier?
<p>I am trying to get the standard trick-an-image-classifier example working in <code>TensorFlow</code>. </p> <p>(That is, adjust the input image by following the gradient so it is misclassified, e.g., <a href="https://codewords.recurse.com/issues/five/why-do-neural-networks-think-a-panda-is-a-vulture" rel="nofollow"...
<p>The reason that <code>tf.gradients()</code> returns <code>[None]</code> is that <code>input_tensor</code> is subjected to a non-differentiable transformation (i.e., JPEG decoding and a cast) before it is fed into the Inception network. Instead, you should operate on the <strong>result</strong> of the JPEG decoding ...
python|computer-vision|tensorflow
2
353,863
34,860,596
Read a custom formatted datetime with numpy
<p>I'm trying to load time series data from some files. The data has this format </p> <pre><code>04/02/2015 19:07:53.951,3195,1751,-44,-25 </code></pre> <p>I'm using this code to load the whole file as a numpy object. </p> <pre><code> content = np.loadtxt(filename, dtype={'names': ('timestamp', 'tick', 'ch', 'NodeI...
<p>Use the <code>converters</code> argument in order to apply a converter function to the data on the first column:</p> <pre><code>import datetime def parsetime(v): return np.datetime64( datetime.datetime.strptime(v, '%d/%m/%Y %H:%M:%S.%f') ) content = np.loadtxt( filename, dtype={ ...
python|datetime|numpy
3
353,864
34,639,746
id() of numpy.float64 objects are the same, even if their values differ?
<p>I get the following:</p> <pre><code>import numpy print id(numpy.float64(100)) == id(numpy.float64(10)) print numpy.float64(100) == numpy.float64(10) </code></pre> <p>gives:</p> <pre><code>True False </code></pre> <p>Note that if I create the two float64 objects and then compare them then it appears to work as e...
<p>Imagine that you put a book on a shelf, and then someone notices that you're not using it and takes the book off the shelf to free some space. You then move to put a different book on the shelf at a convenient location.</p> <p>If you suddenly realize that you had two different books at the very same location, do y...
python|numpy
4
353,865
34,445,184
Python Pandas Least Extreme of Three Row Dataframes
<p>I have 3 rows of <code>DataFrame</code> each stored in separate variables. How can I create a new <code>pandas</code> <code>DataFrame</code> so that it contains the least extreme element of each <code>columns</code>?</p> <p>So if I had:</p> <pre><code>x: C2 CL2 ED ES RB2 1...
<p>You can temporarily concatenate them, then take the index of minimum of the absolute values:</p> <pre><code>pd.concat([x, y, z]).ix[pd.concat([x, y, z]).abs().idxmin()] </code></pre>
python|pandas
2
353,866
34,430,454
Multiplying within a nested dictionary or using Matrices?
<p>EDIT: THE OBJECTIVE: to do something for a nested dictionary with n number of the nested keys (i.e. the A,B,C,D) to get a number in Cell A10. See image below of excel depiction of the problem.</p> <p><a href="https://i.stack.imgur.com/4qkrj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4qkrj.pn...
<p>What you definitely should use is to use the key lookup that should definitely be better than <code>O(n)</code> in a dictionary.</p> <p>What you're basically doing is iterating over all keys in the outer dictionary and then all keys on the inner and first then you check if the key in the outer is one of three and r...
python|numpy|dictionary|matrix|linear-algebra
1
353,867
34,668,181
Python Pandas Regression
<p>[enter image description here][1]I am struggling to figure out if regression is the route I need to go in order to solve my current challenge with Python. Here is my scenario:</p> <ul> <li>I have a Pandas Dataframe that is 195 rows x 25 columns</li> <li>All data (except for index and headers) are integers</li> <li>...
<p>Your goals sound very much like exploratory data analysis at this point. You should probably first calculate the <code>correlation</code> between your target <code>column B</code> and any other <code>column</code> using <code>pandas.Series.corr</code> (which really is the same as bivariate regression), which you cou...
python|pandas|machine-learning|statistics|regression
2
353,868
34,433,468
Apply functon with a condition on the first row
<p>I would like to convert data. For instance, I would like to apply (lambda x: x+273.15) on each columns which contain °C data. </p> <p>A set of data :</p> <p>Before</p> <pre><code>TIME Temp Pressure s °C Pa 0 20 10^5 1 30 10^5 </code></pre> <p>After</p> <pre><cod...
<p>Increasing a Celsius column by 273.15 (<code>x = x + 273.15</code>) makes it a Kelvin column without updating the description, so at some point your data is inconsistent.</p> <p>The best solution is not to put units into the first row of real data at all. Can't you name your columns <code>Temp [°C]</code> or <code>...
python|pandas
0
353,869
60,094,864
Pandas - A rolling cumulative count of distinct values
<p>I have a df like so:</p> <pre><code>df = pd.DataFrame({ 'date': ['01/01/2020', '01/01/2020', '01/01/2020', '02/01/2020', '02/01/2020', '03/01/2020', '03/01/2020'], 'id': [101, 102, 103, 101, 104, 105, 106] }) </code></pre> <p>Output:</p> <pre><code> date id 0 01/01/2020 101 1 01/01/...
<p>I believe is necesary first remove duplicates per <code>id</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer"><code>DataFrame.drop_duplicates</code></a>, then get counts per <code>date</code>s by <a href="http://pandas.pydata....
python|python-3.x|pandas|dataframe
4
353,870
60,329,785
Converting tensorflow session-based code to distribute.Mirroredstrategy
<p>I'm pretty new to Tensorflow and I'll be the first to admit I'm a bit confused and turned around and might very well be barking up the wrong tree.</p> <p>First: This is NOT a question about getting my GPUs working and seen by tensorflow(TF); I have verified from inside the container the GPU's are detected by TF. (u...
<p>It's doable, but the short answer to this is no. There's no straightforward way.</p> <p>Everything I've been able to find requires a good understanding of tensorflow and a fair amount of work to port a 'stock' tensorflow session over to multi GPU. It requires running multiple sessions with assigned GPUs and figurin...
tensorflow
0
353,871
60,123,001
sampling from MultivariateNormalDiag with placeholders
<p>I'm running tensorflow 2.1 and tensorflow_probability 0.9. I'd like to parameterize a multivariatenormal distribution with placeholders and sample from it. Here's what I've tried</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf import tensorflow_probability as tfp @tf.function() def samp...
<p>I was able to get around this using <a href="https://www.tensorflow.org/probability/api_docs/python/tfp/layers/DistributionLambda" rel="nofollow noreferrer">DistributionLambda</a></p> <pre class="lang-py prettyprint-override"><code>vae_mu = tf.keras.layers.Input(shape=(1, 5), dtype=tf.float16) vae_logvar = tf.keras...
tensorflow2.0|tensorflow-probability
0
353,872
60,032,505
What is the Pythonic Way of doing a subset in-place update to a Pandas Dataframe (and Numpy)
<p>Assume 'data' is a Pandas DataFrame where 'rows' are all rows, and 'cols' is some number less than or equal to the actual number of columns. I have the following code which works fine to multiply all data in that space by 'scale'. I'm specifically avoiding using column names, I need to use column indexes.</p> <pre>...
<p>Not sure if this is what you want: It uses the iloc method to change the values of the columns. basic idea of iloc is to use the index numbers for rows and columns. You can read more about it <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#indexing-integer" rel="nofollow noreferrer">he...
python|pandas|numpy|dataframe
1
353,873
60,115,031
How do I make a 3D Scatter Plot but I want an "x" or an "o" depending on a fourth parameter?
<p>Basically, I am making a basketball simulation. I have textfile with over 100,000 simulations. The axes of the 3D scatter plot should take the 2nd,3rd, and 4th columnns (representing 3 different physics parameter) of a basketball. However, there is a 5th column that represents if it the basketball has gone in or mis...
<p>I don't know how to do it with <code>plotly</code>. But in <code>matplotlib</code> it can be easily done:</p> <p><strong>Code:</strong></p> <pre class="lang-py prettyprint-override"><code>import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d # generate some data x = np.random....
python|pandas|matplotlib|plotly-python|scatter3d
0
353,874
60,125,935
New column by Slicing string from another column on transpose of a dataframe python pandas
<p>I am trying to slice a substring from a column and get it in another column. I have read multiple links but this problem exists because my dataframe that I will be working on is Transpose. (This is a minimum reproducible example, the original dataframe is huge and I have to work with the transposed data only).</p> ...
<p>I am not sure what did you mean by "I dont want to set the first column SKU as index to slice", but here is my solution.</p> <pre><code>dft1['dateField'] = dft1.index dft1['month'] = dft1['dateField'].map(lambda x : x[:3]) dft1['year'] = dft1['dateField'].map(lambda x : '20' + x[3:5]) dft1['Date'] = dft1.apply(lamb...
python|pandas|dataframe
1
353,875
59,997,686
Python gpt-2-simple, load multiple models at once
<p>I'm working on a discord bot and one of the functions I want to implement responds with text generated by the gpt-2-simple library. I want to have more then one model loaded to have multiple models available to respond to messages from my users.</p> <p>However I get the following error when i run the <code>load_gpt...
<p>Per @Kedar suggestion, you could use separate Python Processes to isolate execution and load the model in each process separately. Alternatively, you could ensure that only one instance of the model is loaded at a time using a Singleton pattern, or more simply, add the <code>lru_cache</code> decorator (<a href="http...
python|python-3.x|tensorflow|gpt-2
2
353,876
60,216,039
Isolation Forest Length of values does not match length of index
<p>I was running isolation forest trying to apply it on a 10049972 rows x 19 columns database, but after 2 hours of running I got the following error. I really don't understand why did I get it, nor how do I resolve it?</p> <p>Code:</p> <pre><code> import numpy as np import pandas as pd import matplotlib.pyplot as ...
<p>I think the problem might be with</p> <p><code>df.values.reshape(-1,1)</code></p> <p>Look at this example</p> <pre><code>df = pd.DataFrame([(.2, .3), (.0, .6), (.6, .0), (.2, .1)], columns=['dogs', 'cats']) df dogs cats 0 0.2 0.3 1 0.0 0.6 2 0.6 0.0 3 0.2 0.1 df.values.reshape(-1,1) array([[...
python|pandas|csv|machine-learning|jupyter-notebook
1
353,877
60,030,104
how to convert a pandas dataframe to a list of dictionaries in python?
<p>I have a dataframe like this:</p> <pre><code>data = {'id': [1,1,2,2,2,3], 'value': ['a','b','c','d','e','f'] } df = pd.DataFrame (data, columns = ['id','value']) </code></pre> <p>I want to convert it to a list of dictionary like:</p> <pre><code>df_dict = [ { 'id': 1, 'value':['a','b'] }, { 'id': 2, 'va...
<p>You can groupby and then use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer">to_dict</a> to convert it to a dictionary.</p> <pre><code>&gt;&gt;&gt; df.groupby(df['id'], as_index=False).agg(list).to_dict(orient="records") [{'id': 1, 'value'...
python|pandas|dataframe|dictionary
3
353,878
60,178,182
Using Two Variables In Lambda Python
<p>I want to make a new column based on two variables. I want my new column to have the value "Good" if (column 1 >= .5 or column 2 &lt; 0.5) and (column 1 &lt; .5 or column 2 >= 0.5) otherwise "Bad". </p> <p>I tried using <code>lambda</code> and <code>if</code>. </p> <pre><code>df["new column"] = df[["column 1", "co...
<p>Use <code>np.where</code>, pandas does intrinsic data alignment, meaning you don't need to use apply or iterate row by row, pandas will align the data on index:</p> <pre><code>df['new column'] = df['new column'] = np.where(((df['y'] &lt;= .5) | (df['x'] &gt; .5)) &amp; ((df['x'] &lt; .5) | (df['y'] &gt;= .5)), 'Goo...
python|pandas|lambda
5
353,879
60,143,292
At column, Count word in comma-separated sentence
<p>Supposed my dataframe is</p> <pre><code> Name Value 0 K apple,banana 1 Y banana 2 B orange,banana 3 Q grape,apple 4 C apple,grape </code></pre> <p>I want to count word in 'Value' column so when I applied like</p> <p><code>pd.Series(np.concatenate([x.split() for x in df.Value])).value_counts(...
<p>Try this instead:</p> <pre><code>df['Value'].str.split(',', expand=True).stack().value_counts() </code></pre> <p>Output:</p> <pre><code>apple 3 banana 3 grape 2 orange 1 dtype: int64 </code></pre> <p>Using the <code>str</code> accessor for pandas then <code>split</code> on ',', <code>stack</code> t...
python|database|pandas|count
4
353,880
60,143,037
Creating a comma seperated column in python based on two column range values
<p>I need to create a new column having values from column1 value (start) to column2 (end) value in intervals python For example, I have an interval range 0 to 5 My dataframe has column1 value (start) 3 and column2 value (end) 50 I need to create a column with comma seperated value 3,4,5,0,1,2,3,4,5.... total 50 of su...
<pre><code>import itertools as it l = [0,1,2,3,4,5] first = 3 end = 50 col = [] c = it.cycle(l) begin = next(c) while begin != first: begin = next(c) col. append(begin) for i in range(first,end-1): col.append(next(c)) </code></pre> <p>col comes out [3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4...
python|pandas
0
353,881
60,200,088
How to make early stopping in image classification pytorch
<p>I'm new with Pytorch and machine learning I'm follow this tutorial in this tutorial <a href="https://www.learnopencv.com/image-classification-using-transfer-learning-in-pytorch/" rel="nofollow noreferrer">https://www.learnopencv.com/image-classification-using-transfer-learning-in-pytorch/</a> and use my custom datas...
<p>This is what I did in each epoch</p> <pre><code>val_loss += loss val_loss = val_loss / len(trainloader) if val_loss &lt; min_val_loss: #Saving the model if min_loss &gt; loss.item(): min_loss = loss.item() best_model = copy.deepcopy(loaded_model.state_dict()) print('Min loss %0.2f' % min_loss) epo...
python|pytorch|early-stopping
3
353,882
60,129,509
Check for equality between two numpy arrays
<p>I wish to check that the categories in one dataframe column match the categories in another, ie that there are no mismatches in spelling etc.</p> <p>I now have two arrays representing all the unique values in the columns of interest, and I would like to return any values that are in the first, smaller array but are...
<p>You can use <code>set</code> operations.</p> <pre><code>import numpy as np a=np.array(['Barnet', 'Camden', 'Wandsworth', 'Hounslow', 'Southwark', 'Westminster', 'Kensington &amp; Chelsea', 'Tower Hamlets', 'Islington', 'Kingston', 'Barking &amp; Dagenham', 'Waltham Forest', 'Haringey', 'Lambeth...
python|python-3.x|pandas|list|numpy
3
353,883
59,906,252
How do I split data out from one column of a pandas dataframe into multiple columns of a new dataframe
<p>I would like to split data from this pandas dataframe (let's call it df1):</p> <pre><code>YEAR CODE DIFF 2013 XXXX 5.50 2013 YYYY 8.50 2013 ZZZZ 6.50 2014 XXXX 4.50 2014 YYYY 2.50 2014 ZZZZ 3.50 </code></pre> <p>Such that I create a new dataframe (let's call it df2) that looks like this...
<p>Using <strong><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>pivot</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>filter</code></a> + <a hr...
python|python-3.x|pandas
3
353,884
60,245,019
How to Create a New Dataframe from Missing Values Between Two Dataframes
<p>I have two dataframes:</p> <p><code>df1</code></p> <pre><code> Person Date Company Name Symbol ID 0 Dale 2019 Q4 A Corp AAA 10 1 Bill 2019 Q4 B Corp NaN 20 2 Hank 2019 Q4 C Corp NaN 30 3 Rusty 2019 Q4 C Corp CCC 30 4 Peggy 2019 Q4 X Corp NaN ...
<p>Index based on <code>'ID'</code> of both dataframes</p> <pre><code>df1[~df1['ID'].isin(df2['ID'])] </code></pre>
python|pandas
1
353,885
60,095,053
Draw the borders of a binary Numpy array with Matplotlib
<p>I'm using image-segmentation on some images, and sometimes it would be nice to be able to plot the borders of the segments.</p> <p>I have a 2D NumPy array that I plot with Matplotlib, and the closest I've gotten, is using contour-plotting. This makes corners in the array, but is otherwise perfect. </p> <p>Can Mat...
<p>I wrote some functions to achieve this some time ago, but I would be glad to figure out how it can be done quicker.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection def get_all_edges(bool_img): &quot;&quot;&...
python-3.x|numpy|matplotlib
4
353,886
60,136,711
how to plot variation of variable of 10 sample in a dataframe.?
<p>I have the value of 21 variable and their variation in 10 samples. now I want to plot all the variables to see their variation in all the samples. i want a plot like this. <a href="https://i.stack.imgur.com/9AqQQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9AqQQ.png" alt="enter image descripti...
<p>It goes something like this:</p> <ul> <li>In a pandas DataFrame, you can assume each column as one variable. Hence by 21 variables, I'll assume you'll have 21 columns in your dataframe.</li> <li>In a pandas DataFrame, each row can be considered as a subsample. So I'll assume here that you have 10 rows in your dataf...
python|pandas
1
353,887
60,102,571
Compare values in two different pandas columns
<p>I have a dataframe that looks like this:</p> <pre><code>Fruit Cost Quantity Fruit_Copy Apple 0.5 6 Watermelon Orange 0.3 2 Orange Apple 0.5 8 Apple Apple 0.5 7 Apple Banana 0.25 8 Banana Banana 0.25 7 Banana Apple 0.5 6 Apple Apple 0.5 3 Apple </code></pre> <p>I want to w...
<p>Lets say your dataframe is 'fruits'. Then you can make use of the Pandas Series Equals function <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.eq.html#pandas.Series.eq" rel="nofollow noreferrer">pd.Series.eq</a> as,</p> <pre><code>fruits['Match'] = pd.Series.eq(fruits['Fruit'],fru...
python-3.x|pandas
2
353,888
60,317,148
Grouping by and filtering for column value containing string and aggregate function?
<p>How can I group by a couple of columns for only values that contain a string anywhere in that column value?</p> <p>For example if I want to look at state and theatre name but only look at the count or number of times a title as the word dog anywhere in it how can I group by to filter with that?</p> <pre><code>Stat...
<p>Compare column by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>Series.str.contains</code></a> for mask, convert to integers for <code>True-&gt;1</code> and <code>False-&gt;0</code> mapping and count number of <code>1</code> by <co...
python|python-3.x|pandas
2
353,889
60,152,241
Pandas explode and drop duplicates for multiple columns
<p>I am having some issues when trying to perform <code>explode</code> on multiple (4) columns. The first problem is that I run into <code>MemoryError</code> if I try to explode all the columns at once. There are many duplicates after exploding each column individually so I could use <code>drop_duplicates()</code>, how...
<p>Can you to something like this:</p> <pre><code>df[['id']].join((df[i].explode() for i in df.iloc[:,1:])) </code></pre> <p>Output:</p> <pre><code>| | id | col_1 | col_2 | col_3 | col_4 | |---:|-----:|:--------|:--------|:--------|:--------| | 0 | 1 | a | nan | c | nan | | 0 | ...
python|pandas
2
353,890
60,143,536
How can I count the number of rows per group in Pandas?
<p>I have a dataset with several Oscar winners. I have the following columns: Name of winner, award, place of birth, date of birth and year. I want to check how many rows are filled per year. Let's say for 2005 we have the winner of best director and best actor and for 2006 we have the winner for best supporting actor....
<p>Try for pandas 0.25+</p> <p><code>df.groupby(['year_of_award']).agg(number_of_rows=('award': 'count'))</code></p> <p>else</p> <p><code>df.groupby(['year_of_award']).agg({'award': 'count'}).rename(columns={'count': 'number_of_rows'})</code></p>
python|pandas|pandas-groupby
2
353,891
60,010,044
Find where three separate DataFrames overlap and create a new DataFrame
<p>I have three separate DataFrames. Each DataFrame has the same columns - <code>['Email', 'Rating']</code>. There are duplicate row values in all three DataFrames for the column <code>Email</code>. I'm trying to find those emails that appear in all three DataFrames and then create a new DataFrame based off those rows....
<p>You want to do a merge. Similar to a join in sql you can do an inner merge and treat the email like a foreign key. Here is the docs: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pa...
python|pandas|dataframe|pandas-groupby|data-science
1
353,892
60,116,523
Map values from one DataFrame to another
<p>I have two DataFrames:</p> <ul> <li><code>df</code> - the core DataFrame with columns/cells that I want to expand</li> <li><code>maptable</code> - a maptable DataFrame that maps certain columns</li> </ul> <p>An example:</p> <pre><code>maptable: id | period A | winter B | summer A | summer nan | summer B | na...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> and then fill <code>NaN</code> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>Ser...
python|pandas
3
353,893
60,136,393
X-Y Coordinates to box number
<p>Let's say I have some grid </p> <p>Total No. rows = 170 </p> <p>Total No. columns = 200 </p> <p>How do I find cell No., if I only know the x-y coordinates in lengths. Cell no is assigned sequentially, starting from top left . </p>
<p>According to the attached picture, we do have connected 4 areas with a given geometry. The number of cells in horzontol and vertical direction is given. The cell width and height are defined as well. So pretty much everything is known, to calculate where, in which part and it which cell we are for a given coordinate...
python|numpy
1
353,894
60,328,681
Automatization reading in .csv files in Python with adaptive paths
<p>I am a rookie when it comes to python or coding in general. I set up a script, reading in various .csv files. I got a private notebook and a work notebook. </p> <p>How can I automate the .csv reading for files with the names "1.txt", "2.txt" ... "22.txt" etc? And how can I automatically adapt the path where the dat...
<p>You can use string formatting to put number in place of <code>{}</code></p> <pre><code>name = "path/filename{}.txt".format(number) </code></pre> <p>and you can do it in loop <code>for number in range(1, 9):</code></p> <p>You could also use list to keep files as <code>c[0]</code>, <code>c[1]</code> because you ma...
python|pandas|csv|path
0
353,895
60,266,182
event start-end into hot encoding in python
<p>I have a pandas dataframe with 2 columns "type" and "sign" as follows</p> <pre><code> type sign 0 open A 1 open B 2 open D 3 close B 4 close D 5 open B 6 close B 7 close A </code></pre> <p>"A" + "open" means that event A has started happening. "A" + "close" means that even...
<p>IIUC let do <code>get_dummies</code> then do <code>cumsum</code> </p> <pre><code>s=df.sign.str.get_dummies().reindex(columns=list('ABCD'),fill_value=0).\ mul(df.type.map({'open':1,'close':-1}),axis=0).cumsum() A B C D 0 1 0 0 0 1 1 1 0 0 2 1 1 0 1 3 1 0 0 1 4 1 0 0 0 5 1 1 0 0 6 1...
python|pandas|machine-learning|one-hot-encoding
5
353,896
59,913,500
Add value in NULL column
<p>How to add value to a cell of column in pandas Excel? The data in Excel is coming from a database.</p> <p>The last column of my sheet is null in database I want to add manually a value to that column.</p> <pre><code>c.execute('select * from employee where id = (?);', (ids,)) result2 = c.fetchall() today = str(dat...
<p>Possible approaches. </p> <ul> <li>Change the sql to select by column name and use a <code>CASE</code> statement or a constant instead of the actual last column (remember to alias a name for it).</li> <li>Add an iterator over result2 to populate the last column before it is processed further.</li> </ul>
python|pandas|sqlite
0
353,897
60,021,054
Split a pandas dataframe header into multiple columns
<p>I'm trying to split the dataframe header <code>id;signin_count;status</code> into more columns where I can put my data into. I've tried <code>df.columns.values</code>, but I couldn't get a string to use <code>.split</code> in, as I was hoping. Instead, I got:</p> <pre><code>Index(['id;signin_count;status'], dtype='...
<p>If you are reading your data from a csv file you can define <code>sep</code> to <code>;</code> and read it as:</p> <pre><code>df=pd.read_csv('filename.csv', sep=';', index_col=False) </code></pre> <p>Output:</p> <pre><code> id signin_count status 0 353 20 done 1 374 94 pending 2 377 4 ...
python|pandas
2
353,898
60,115,895
Converting a table of fixed width in text format into dataframe/excel/csv
<p>I have some <a href="http://txt.do/16l94" rel="nofollow noreferrer">data</a> in txt format with 38 columns which looks like this:</p> <p><img src="https://i.stack.imgur.com/uCaOb.png" alt="screenshot"></p> <p>With the exception of the header row, most of the rows have missing values. I want to convert this table i...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_fwf.html" rel="nofollow noreferrer"><code>pandas.read_fwf</code></a> (fixed-width format):</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df = pd.read_fwf('data.txt') &gt;&gt;&gt; df INDEX YEAR MN DT...
python|excel|pandas|dataframe|text-database
2
353,899
60,329,724
Keras Tensorflow Validation Accuracy different when using Subclass Syntax vs Functional or Sequential
<p>I have reimplemented the Keras MINST CNN example using Sequential, Functional and SubClass syntax.</p> <ul> <li><a href="https://keras.io/examples/mnist_cnn/" rel="nofollow noreferrer">https://keras.io/examples/mnist_cnn/</a></li> <li><a href="https://github.com/JamesMcGuigan/kaggle-digit-recognizer/tree/master/src...
<p>I think in ClassCNN last layer activation is 'relu' which should be 'softmax' as is the case with other models... It is just a human mistake ..... Thankyou...</p>
python|tensorflow|machine-learning|keras|deep-learning
2