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
367,800
44,819,119
How to convert the value_counts() output into a dataframe?
<p>I have a dataframe like this:</p> <pre><code>match team1 team2 winner 1 MI KKR MI 2 DD CSK DD 3 RCB DC RCB..... </code></pre> <p>What I wanted to calculate is how many times has a team won against another team in ...
<p>You can simplify your search a bit, or make it more readable anyway</p> <pre><code>def my_comp(df, team): matches_with_team = df[(df[['team1', 'team2']] == team).any(axis=1)] other_teams = (set(matches_with_team['team1']) ^ set(matches_with_team['team2'])) - {team} comparison_df = pd.DataFrame(index=oth...
python|pandas|dataframe
1
367,801
44,455,481
How can I vectorize a function that uses lagged values of its own output?
<p>I'm sorry for the poor phrasing of the question, but it was the best I could do. I know exactly what I want, but not exactly how to ask for it.</p> <p>Here is the logic demonstrated by an example: </p> <p>Two conditions that take on the values 1 or 0 trigger a signal that also takes on the values 1 or 0. Condition...
<p>I don't think there is a way to vectorize this operation that will be significantly faster than a Python loop. (At least, not if you want to stick with just Python, pandas and numpy.)</p> <p>However, you can improve the performance of this operation by simplifying your code. Your implementation uses <code>if</cod...
python|pandas|numpy|ipython|vectorization
3
367,802
44,593,141
Stacking copies of an array/ a torch tensor efficiently?
<p>I'm a Python/Pytorch user. First, in numpy, let's say I have an array M of size LxL, and i want to have the following array: A=(M,...,M) of size, say, NxLxL, is there a more elegant/memory efficient way of doing it than :</p> <pre><code>A=np.array([M]*N) ? </code></pre> <p>Same question with torch tensor ! Cause,...
<p>Note, that you need to decide whether you would like to allocate new memory for your expanded array or whether you simply require a new view of the existing memory of the original array. </p> <p>In PyTorch, this distinction gives rise to the two methods <code>expand()</code> and <code>repeat()</code>. The former on...
arrays|numpy|pytorch|tensor
13
367,803
44,416,865
Issuse: Scipy Fitting Normal Data
<p>I currently have some experiemental data imported and plotted which is normally distributed.</p> <p><a href="https://i.stack.imgur.com/6IIAd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6IIAd.png" alt="Normally Distributed Experiemental Data"></a></p> <p>I then tried using Scipy to fit a norm...
<p>I played with similar problem <a href="https://stackoverflow.com/questions/42882309/curve-fiting-of-normal-distribution-in-python/42884014#42884014">Curve fiting of normal distribution in Python</a></p> <p>added <code>b</code>, a offset to the curve fit, seems to need a halfway OK guess value</p> <p>then the scale...
python|numpy|scipy|data-fitting
0
367,804
44,819,249
How to delete more lines in between lines you like python?
<p>I have a weird file format</p> <pre><code>########################################################### # Name of file# # stuff[hh:mm:ss:ms] stuff[num] stuff[num] stuff[] stuff[]# ########################################################### 00:00:00.000 -1000 -1000 0.000001 20 00:00:00.001 -1000 -1000 0.000001 20 00:0...
<p>You can use <code>skiprows</code> parameter to get odd rows (or even). From the documentation:</p> <blockquote> <p>If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise. An example of a valid callable argument would be lam...
python|file|pandas|lines
1
367,805
44,600,752
Datetime in pandas dataframe will not subtract from each other
<p>I am trying to find the difference in times between two columns in a pandas dataframe both in datetime format.</p> <p>Below is some of the data in my dataframe and the code I have been using. I have triple checked that these two columns dtypes are datetime64.</p> <p>My data:</p> <pre><code>date_updated ...
<p>I encountered the same error using the above syntax (worked on another machine though):</p> <pre><code>data['Diff'] = data['date_updated'] - data['date_scored'] </code></pre> <p>It worked on my new machine with:</p> <pre><code>data['Diff'] = data['date_updated'].subtract(data['date_scored']) </code></pre>
python|pandas|datetime|subtraction
23
367,806
61,004,075
Pandas using matplot displays an incorrect year on the x-axis date
<p>In the graph, the date axis is not being displayed correctly with date formatting, the year that should be "2020" and is displayed as "51". Text text text Text text text Text text text Text text text Text text text Text text text Text text text Text text text Text text text </p> <pre><code># -*- coding: latin-1 -*-...
<p>I'm not very experienced. I have been unable to improve it by changing various settings as far as I know. We responded in the following way. for your information</p> <pre><code># ax.xaxis.set_major_locator(mdates.DayLocator(interval=1)) # ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y')) </code></pre> ...
python|pandas|matplotlib|data-science
1
367,807
60,985,365
change values in column if duplicate and corresponding meets criteria
<p>I have a dataframe where there are duplicates in first column. In the third column there is another label but, these have duplicated data. I want to change all the duplicated data, if not matching to 'covered' if there is a duplicate in initial column and 'covered'apparent.</p> <p>Picture below: SAWAD should both b...
<p>Idea is test if at least one <code>Covered</code> per group by compre by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.eq.html" rel="nofollow noreferrer"><code>Series.eq</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.an...
python|pandas|dataframe
1
367,808
60,912,043
Pandas - Unexpected results when indexing a DataFrame containing missing entries
<p>First, we create a large dataset with MultiIndex whose first record contains missing values <code>np.NaN</code></p> <pre><code>In [200]: data = [] ...: val = 0 ...: for ind_1 in range(3000): ...: if ind_1 == 0: ...: data.append({'ind_1': 0, 'ind_2': np.NaN, 'val': np.NaN}) ...
<p>Use boolean arrays i1, i2 instead of indexes</p> <pre><code>In [27]: i1 = df.index.get_level_values('ind_1') &lt; 3 In [28]: i2 = ~(df.index.get_level_values('ind_2') &gt; 2) In [29]: i1 Out[29]: array([ True, True, True, ..., False, False, False]) In [30]: i2 Out[30]: array([ True, True, True, ..., False, F...
pandas|indexing
0
367,809
60,985,896
Returning a unique row if condition returns multiple rows
<p>I am writing an algorithm for a Vehicle Routing Problem. When the driving time from some seed city to some other city is minimal, it should be added to my route. To check this, I use </p> <pre><code>new_point_row_df = emte_df[emte_df["seed_time"] == emte_df.seed_time.min()] </code></pre> <p>Which gives me the enti...
<p>Simply do:</p> <pre class="lang-py prettyprint-override"><code>ew_point_row_df = emte_df[emte_df["seed_time"] == emte_df.seed_time.min()].iloc[0] </code></pre> <p>This will just select the first row every time.</p>
python|pandas|dataframe|unique
1
367,810
61,147,000
How do I create several df's out of one original df based on a condition and then assign them individual names
<pre><code>df_collection = {} for country in country_names: df_collection[country] = df.loc[df['CountryName'] == country].copy </code></pre> <p>I want to create several df's (about 70 for each country one) out of one original df (each country is differing in frequency) and then assign them individual names (therefo...
<p>You assigned a method to each of your dictionary keys. You need to call copy with <code>()</code>, i.e. <code>df.loc[df['CountryName'] == country].copy()</code>.</p> <p>However there's no need to subset your DataFrame in a loop. This is exactly what <code>groupby</code> is made for and you can create the dict succi...
python|pandas
2
367,811
61,064,494
Looking up a column value based on two column values in a pandas dataframe
<p>I need to get the value from a column based on two specific column values. </p> <p>Example Dataframe: </p> <pre><code> Charge Code Billing Number Date 0 1250-001 500220 1/2/20 1 1230-002 300220 2/6/20 2 1250-001 500320 3/8/20 3 1225-001 250120 4/9/20 4 ...
<p>You need parenthesis:</p> <pre><code>the_date = df_hold.loc[(df_hold['Charge Code'] == '1250-001') &amp; (df_hold['Billing Number'] == 500320), 'Date'] </code></pre> <p>update:</p> <pre><code>the_date = df_hold.loc[(df_hold['Charge Code'] == '1250-001') &amp; (df_ho...
pandas|dataframe|pandas-loc
0
367,812
61,010,699
Pairwise interaction pandas columns
<p>I want to make columns with the pairwise interactions of my existing columns. The code below returns all the possible interactions (two-way, three-way and so on) while I want only the pairs of columns. Any idea on how to make it work would be appreciated.</p> <pre><code>import pandas as pd for i in range(0, df.col...
<p>It is kind of tricky but the following is happening, df.columns.size is changing in the loop since you are creating new columns, you can just create size_col outside the loop so it won't be computed every time:</p> <pre><code>import pandas as pd size_col = df.columns.size for i in range(0, size_col): for j in ...
python|arrays|python-3.x|pandas
1
367,813
61,087,110
How can I reshape a repeating wide pandas DataFrame to be stacked?
<p>I have a Pandas DataFrame where respondents answer the same question over multiple sales accounts. My input Dataframe is of the following format</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({"Sales_Acc1":[100,300], "Sales_Acc2":[200,500], "Time_Acc1":[2,5], ...
<p>This is a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html" rel="nofollow noreferrer"><code>wide_to_long</code></a> problem given your column are in the format <code>'stub_SomeSuffix'</code>. Because you have some inconsistent cases we'll make everything lower. We also nee...
python|pandas|dataframe
3
367,814
60,769,333
tensorflow v2.1 training DCGAN using tf.keras failed, what happend?
<p>I want to use tensorflow.keras (ver 2.1) to train DCGAN.</p> <p>When I followed official tutorial (<a href="https://www.tensorflow.org/tutorials/generative/dcgan" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/generative/dcgan</a>), official code is trained successfully.</p> <p>However, when I trie...
<p>I solved</p> <pre class="lang-py prettyprint-override"><code># get loss #loss_G = loss_fn(tf.ones_like(Gz), Gz) loss_G = loss_fn(tf.ones_like(DGz), DGz) </code></pre>
python|tensorflow|deep-learning|tensorflow2.0|dcgan
0
367,815
60,902,033
pandas replace id number by entry in dataframe
<p>I have 2 different dataframes. One looks like this </p> <pre><code>arriv depart stop_id 12:35 12:40 a2b 23:00 01:00 a1e </code></pre> <p>Ther other looks like this:</p> <pre><code>stop_id lon lat name a1e 12.1 13.2 Old Church a2b 12.2 13.1 Postal Service </code></pre> <p>now I would like to ...
<p>I believe what you want is: "for every instance in the first dataframe , merge the lon lat and name columns (available in another dataframe)."</p> <p>If that's the case, you could use pd.merge():</p> <pre><code>import pandas as pd timeDF = pd.DataFrame({ "arriv":["12:35","23:00","13:35","12:35"], ...
python|pandas
5
367,816
60,973,464
Where is the code Tensorflow uses to implement RMSProp
<p>I've cloned Tensorflow from <code>https://github.com/tensorflow/tensorflow.git</code> and am trying to find the code where RMS_Prop is implemented. </p> <p>I have found the file <code>tensorflow/tensorflow/python/training/rmsprop.py</code>, which has calls to <code>training_ops.apply_centered_rms_prop</code> and to...
<p>The main computational code is implemented in C++; the Python layer abstracts this. The files you are interested in are the <a href="https://github.com/tensorflow/tensorflow/blob/83d65b152b6b1ed1e622c59d908e76d8d2e7d07b/tensorflow/core/kernels/training_ops.cc" rel="nofollow noreferrer">CPU kernel</a> and <a href="ht...
python|tensorflow|mathematical-optimization
1
367,817
61,100,358
Jacobian matrix of logits with respect to image using tf.GradientTape
<p>I am trying to find the Jacobian of logits with respect to input but I do get <code>None</code> and I could not figure it why.</p> <p>Let'say I have a model, I trained it and saved it.</p> <pre><code>import tensorflow as tf print("TensorFlow version: ", tf.__version__) tf.keras.backend.set_floatx('float64') impor...
<p>Please check the batch_jacobian method of the GradinetTape. <a href="https://www.tensorflow.org/api_docs/python/tf/GradientTape#batch_jacobian" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/GradientTape#batch_jacobian</a></p> <p>Convert your input to the tf variable if you are getting None...
tensorflow|gradient|tensorflow2.0|tf.keras|gradienttape
0
367,818
60,782,232
How to fill space to border with in Matplotlib
<p>I need to fill space between 3 graphs but I don't understand how to limit the area on the graph y2</p> <pre><code>import numpy as np import matplotlib.pyplot as plt y = lambda z: (4 * z - z ** 2) ** (1 / 2) y1 = lambda x: (8 * x - x ** 2) ** (1 / 2) y2 = lambda c: c * 3 ** (1 / 2) x = np.linspace(0, 12, 100) z = ...
<p>To fill the space that is both above <code>y</code> and above <code>y2</code>, you can take the maximum of both. In order to only fill where <code>y1</code> is above <code>y2</code>, you can you the <code>where</code> parameter:</p> <pre class="lang-py prettyprint-override"><code>plt.fill_between(x, np.maximum(y(z)...
python|numpy|matplotlib|math|plot
2
367,819
60,841,122
How to fix this "Key Error:t" i got while i was writing a while loop?
<p><strong>I wrote this code and then i took an error which i wrote below. There is a while loop which lets me take the data which is limited by 1000 columns as much time as i described in reapeat_rounds variable but when i tried to use that loop, a "keyerror:t" raises.If i do reapeat_rounds = 0, i dont get such error ...
<p>Don't you want to replace the line</p> <pre class="lang-py prettyprint-override"><code>df2 = self.GetSymbolData(symbol, interval, limit=1000, end_time=df['time'[0]]) </code></pre> <p>with something like</p> <pre class="lang-py prettyprint-override"><code>df2 = self.GetSymbolData(symbol, interval, limit=1000, end...
python|python-3.x|pandas|dataframe|keyerror
0
367,820
61,050,345
Pandas assign value in one column based on top 10 values in another column
<p>I have a table:</p> <pre><code> A B C D 0 NaN 2.0 NaN 0 1 3.0 4.0 NaN 1 2 NaN NaN NaN 5 3 NaN 3.0 NaN 4 </code></pre> <p>I would like to make a new column called 'flag' for the top 2 values in column D.</p> <p>I've tried:</p> <pre><code>for i in df.D.nlargest(2): df.['flag']= 1 </code></pre>...
<p>IIUC:</p> <pre><code>df['flag'] = 0 df.loc[df.D.nlargest(2).index, 'flag'] = 1 </code></pre> <p>Or:</p> <pre><code>df['flag'] = df.index.isin(df.D.nlargest(2).index).astype(int) </code></pre> <p>Output:</p> <pre><code> A B C D flag 0 NaN 2.0 NaN 0 0 1 3.0 4.0 NaN 1 0 2 NaN NaN NaN 5 ...
pandas
0
367,821
61,030,730
Installed tensorflow in an anaconda env but cannot import (Tensorflow 1.15, Python 3.6, PyCharm)
<p>I recently created an environment in PyCharm using anaconda and i'm using Python version 3.6. I want to import tensorflow but unfortunately i keep getting the error message "ModuleNotFoundError: No module named 'tensorflow'". I installed tensorflow versions (1.20 &amp; 1.15) on my environment with no major issues, i...
<p>If you get this error, you have installed everything in one environment but you work in another. Try installing tensorflow from another command line (in another shell).</p>
python|tensorflow|pycharm
2
367,822
61,051,095
Altering groupby and value_counts output for mapping to dataframe
<p>I have a scenario where I am trying to filter a dataframe by a particular value, and count how many times another identifier is present. I'm then turning that into a dictionary and mapping back to the dataframe. The issue I am having is that the resulting dictionary cannot be mapped back to the dataframe because I'm...
<pre><code>df = pd.read_csv('spot.txt', sep=r"[ ]{1,}", engine='python', dtype='object') print(df) CELL_ID Grid_Type 0 001 Spot 1 001 Square 2 001 Spot 3 001 Square 4 001 Square 5 002 Spot 6 002 Square 7 002 Square 8 003 Square 9 003 Spot 10 003 Spot 11 003 Spot df_gb = df['Grid_Type'].grou...
python|pandas|dataframe|pandas-groupby
1
367,823
61,173,703
Loading .npz in colab using mounted drive
<p>How do I load an <code>.npz</code> file that has been mounted from google drive in a google colab notebook?</p> <p>Given the following code</p> <pre class="lang-py prettyprint-override"><code>from google.colab import drive import numpy as np drive.mount('/content/drive') data = np.load('/content/drive/My Drive/Col...
<pre><code>from scipy.sparse import load_npz data = load_npz('/content/drive/My Drive/ColabNotebooks/project/data/dat.npz') </code></pre> <p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.load_npz.html" rel="nofollow noreferrer">Documentation</a></p>
python|numpy|google-colaboratory
0
367,824
61,166,307
Should we train the original data point when we do data augmentation?
<p>I am confused about the definition of data augmentation. Should we train the original data points and the transformed ones or just the transformed? If we train both, then we will increase the size of the dataset while the second approach won't. </p> <p>I got this question when using the function RandomResizedCrop. ...
<p>transform.compose is just as preprocessing an image ,convert one form to particular suiatable form </p> <p>On apply transformation on single image means changing it pixel value and it does not increases dataset size </p> <p>for more dataset you have to perform operation such below:</p> <pre><code>final_train_data...
deep-learning|computer-vision|pytorch|transform|data-augmentation
0
367,825
60,992,438
ValueError in Sklearn
<p>I put together the following function that read csv, train the model and predict the request data. </p> <p>I've got the following ValueError : Column ordering must be equal for fit and for transform when using the remainder keyword</p> <p>The training data and the data used for prediction has exact the same numbe...
<p>The issue has resolved by adding the specific columns that I used to train x in the df_resp. </p>
python|pandas|function|scikit-learn|sklearn-pandas
0
367,826
61,172,627
Choosing the learning_rate using fastai's learn.lr_find()
<p>I am going over this <a href="https://www.kaggle.com/kageyama/fastai-heroes-recognition-resnet34" rel="noreferrer">Heroes Recognition ResNet34</a> notebook published on Kaggle.</p> <p>The author uses fastai's <code>learn.lr_find()</code> method to find the optimal learning rate.</p> <p>Plotting the loss function a...
<p>The idea for a learning rate range test as done in lr_find comes from this paper by Leslie Smith: <a href="https://arxiv.org/abs/1803.09820" rel="noreferrer">https://arxiv.org/abs/1803.09820</a> That has a lot of other useful tuning tips; it's worth studying closely.</p> <p>In lr_find, the learning rate is slowly r...
pytorch|conv-neural-network|kaggle|fast-ai
16
367,827
60,793,624
Pandas Advanced: How to get results for customer who has bought at least twice within 5 days of period?
<p>I have been attempting to solve a problem for hours and stuck on it. Here is the problem outline:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd df = pd.DataFrame({'orderid': [10315, 10318, 10321, 10473, 10621, 10253, 10541, 10645], 'customerid': ['ISLAT', 'IS...
<p>First, to be able to count the difference in days, convert <em>orderdate</em> column to <em>datetime</em>:</p> <pre><code>df.orderdate = pd.to_datetime(df.orderdate) </code></pre> <p>Then define the following function:</p> <pre><code>def fn(grp): return grp[(grp.orderdate.shift(-1) - grp.orderdate) / np.timed...
python|pandas
2
367,828
60,906,284
How can I change part of a PyTorch tensor based on the values of another tensor?
<p>This question may not be clear, so please ask for clarification in the comments and I will expand.</p> <p>I have the following tensors of the following shape:</p> <pre><code>mask.size() == torch.Size([1, 400]) clean_input_spectrogram.size() == torch.Size([1, 400, 161]) output.size() == torch.Size([1, 400, 161]) </...
<p>You can do something like this, where:</p> <ul> <li><code>m</code> is your mask;</li> <li><code>x</code> is your spectogram;</li> <li><code>o</code> is your output;</li> </ul> <pre class="lang-py prettyprint-override"><code>import torch torch.manual_seed(2020) m = torch.tensor([[0, 1, 0]]).to(torch.int32) x = tor...
python|pytorch
2
367,829
60,839,898
Is there a way to use bokeh box annotation to highlight the same time frame each day?
<p>I have been unable to find any way to add a box annotation to a bokeh plot between the same set of hours for each day on a graph. For example, if I had a line graph of hourly data for an entire month, is it possible to add a box annotation between the hours of 5 and 10 each day without explicitly coding the left/rig...
<p>Box annotations don't accept neither a data source nor an array of values.</p> <p>You have 3 options:</p> <ol> <li>Just as you said, explicitly specify the bounds</li> <li>If it's possible, replace them with rect glyphs that accept data sources and/or arrays</li> <li>Create a custom annotation class that renders m...
python|pandas|bokeh|pandas-bokeh
1
367,830
61,076,672
Resnet-50 adversarial training with cleverhans FGSM accuracy stuck at 5%
<p>I am facing a strange problem when adversarially training a resnet-50, and I am not sure whether is's a logical error, or a bug somewhere in the code/libraries. I am adversarially training a resnet-50 thats loaded from Keras, using the FastGradientMethod from cleverhans, and expecting the adversarial accuracy to ris...
<p>It is a side-effect of the way we estimate the moving averages on BatchNormalization.</p> <p>The mean and variance of the training data that you used are different from the ones of the dataset used to train the ResNet50. Because the momentum on the BatchNormalization has a default value of 0.99, with only 10 iterat...
tensorflow|keras|cleverhans
0
367,831
61,127,919
Chua's circuit using python and graphing
<p>I tried to implement the Chua system using Python. But the graph is very different from what we need. Implementation with such a system</p> <p><a href="https://i.stack.imgur.com/ICxl2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ICxl2.png" alt="enter image description here" /></a></p> <p>I have...
<p>As I don't know particularly well Chua's oscillator and unless I'm mistaken, I did suppose there is just an error in your ODE system definition. </p> <p>Simply based on wikipedia english page of <a href="https://en.wikipedia.org/wiki/Chua%27s_circuit" rel="nofollow noreferrer">Chua's circuit</a>. It seems that you ...
python|python-3.x|numpy|graphics
1
367,832
61,074,798
Deploy pre-trained tensorflow model on the aws sagemaker - ModelError: An error occurred (ModelError) when calling the InvokeEndpoint operation
<p>This is the first time I am using amazon web services to deploy my machine learning pre-trained model. I want to deploy my pre-trained TensorFlow model to Aws-Sagemaker. I am somehow able to deploy the endpoints successfully But whenever I call the <code>predictor.predict(some_data)</code> method to make prediction ...
<p>After a lot of searching and try &amp; error, I was able to solve this problem. In many cases, the problem arises because of the TensorFlow and Python versions.</p> <p><strong>Cause of the problem:</strong> To deploy the endpoints, I was using the <code>TensorflowModel</code> on TF 1.12 and python 3 and which exactl...
amazon-web-services|tensorflow|tensorflow-serving|amazon-sagemaker
4
367,833
60,975,054
Pandas. Trying to delete rows on condition but code replaces column with another column
<p>So in the beginning I get a look over my db.</p> <pre><code>print(sales.head) print(sales['SALE PRICE'].describe()) </code></pre> <p>After that I use a trick to keep rows that don't contain this kind of NULL value</p> <pre><code>sales['SALE PRICE'] = sales[sales['SALE PRICE'] != ' - '] </code></pre> <p>After th...
<p>You just need to assign result back to <code>sales</code> instead of column.</p> <pre><code>sales = sales[sales['SALE PRICE'] != ' - '] </code></pre> <ul> <li><code>sales['SALE PRICE'] != ' - '</code> This will return Indexes with <code>True</code> and <code>False</code> Values.</li> <li>So <code>sales[sales['SA...
python|pandas
0
367,834
60,932,025
Loading csv with pandas, wrong columns
<p>I loaded a csv into a DataFrame with pandas.</p> <p>The format is the following:</p> <pre><code>Timestamp | 1014.temperature | 1014.humidity | 1015.temperature | 1015.humidity .... ------------------------------------------------------------------------------------- 2017-... | 23.12 | 12.2 | ...
<pre><code>import pandas as pd from io import StringIO # create sample data frame s = """Timestamp|1014.temperature|1014.humidity|1015.temperature|1015.humidity 2017|23.12|12.2|25.10|10.34""" df = pd.read_csv(StringIO(s), sep='|') df = df.set_index('Timestamp') # split columns on '.' with list comprehension l = [col....
pandas|csv|format
0
367,835
60,780,598
Groupby and loop Pandas
<p>My DataFrame:</p> <pre><code>Id | date | date_2 1 2020-02-19 2020-02-18 1 2020-02-18 2020-02-17 1 2020-02-17 2020-02-16 2 2020-02-19 2020-02-24 2 2020-02-24 2020-02-12 etc. </code></pre> <p>I would like to choose date "2020-02-19" in each Id and also give me next next date 2</p> <pre><code>Id ...
<p>IIUC,</p> <pre><code>df.assign(date_2=df['date_2'].shift(-1)).loc[df['date'].eq('2020-02-19')] </code></pre> <p><strong>Output</strong></p> <pre><code> Id date date_2 0 1 2020-02-19 2020-02-17 3 2 2020-02-19 2020-02-12 </code></pre>
pandas|pandas-groupby
0
367,836
61,026,722
Subsequent distances between vectors stored in two data frame
<p>I have two <code>numpy</code> arrays:</p> <pre><code>import numpy as np A = np.random.rand(20).reshape(-1, 2) B = np.random.rand(8).reshape(-1, 2) </code></pre> <p>where columns can be treated as x and y coordinates in 2-dimensional euclidean space. For each row of <code>A</code> I need to calculate minimum distan...
<h1>Solution</h1> <p>You can do this using numpy broadcasting. The array <code>R2</code> has a shape <code>(A_rows, B_rows)</code>, i.e. (10, 4). For <strong>very large arrays <code>A</code> and <code>B</code></strong>, you may have to apply batch processing. For that purpose use the custom-defined function <strong><c...
python|numpy
1
367,837
60,957,525
loop through Pandas Dataframe and return columns name and type
<p>How do I loop through Pandas Dataframe and return columns name and type? </p> <pre><code>#return types for i in df.dtypes: print(i) # return column name for col in df: print(col) </code></pre> <p>I'm able to return them separately but how can I return them from the same column? </p>
<p>You could just do this:</p> <pre><code>df.dtypes </code></pre> <p>Or if you're set on a loop:</p> <pre><code>for i, col in zip(df.dtypes, df): print(i, col) </code></pre>
python-3.x|pandas
2
367,838
60,874,739
Python: How to create a surface-plot from a collection of 3D coordinates
<p>I am given three numpy-arrays, which contain the x, y, and z- coordinates of multiple points, respectively. In fact, there are 100 points, which are arranged in a grid: </p> <p><a href="https://i.stack.imgur.com/Y7vqa.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y7vqa.jpg" alt="grid"></a></p> ...
<p>Are you sure if your z array can be reshaped into (10,10)? I quickly ran the following as I didn't know specifics of your z array, it seems the plotting works as you wanted?</p> <pre><code>import numpy as np import matplotlib.pylab as plt from mpl_toolkits.mplot3d import Axes3D def plot_surface(): x = np.arang...
python|numpy|matplotlib
0
367,839
61,059,421
Numpy Python: How to change 2d array elements based on condition?
<p>I have a numpy 2D array representing some x,y coordinates. Given a reference point [a,b] and a distance 'c', I want to replace the elements in my 2D array, such that all points whose distance from [a,b]>c are set to [0,0] and those with a distance smaller than c are set to [1,1]. I tried to use where() in many varia...
<pre><code>np.array([[int(np.linalg.norm(a - refPoint, 2) &lt; c)]*len(refPoint) for a in arr2D]) </code></pre> <p>This gives exactly the format you are looking for, the "*len(refPoint)" seems a bit redundant though.</p>
python|numpy
0
367,840
60,975,485
pandas isin function on a for loop
<p>1.csv</p> <pre><code> cut price depth carat table 0 Good 327 57.9 0.23 65.0 1 Good 335 63.3 0.31 58.0 2 Very Good 336 62.8 0.24 57.0 3 Very Good 336 62.3 0.24 57.0 4 Very Good 337 61.9 0.26 55.0 5 Premium 326 59.8 0.21 61.0 6 Premium 334 62.4 0.29 58.0...
<p>IIUC, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>DataFrame.merge</code></a> with <strong><code>indicator = True</code></strong>:</p> <pre><code>f2_filtered = (f2.merge(f1, how='outer', indicator=True) .query('_me...
python|pandas|dataframe|for-loop|isin
2
367,841
61,018,067
Apply z-score across all attributes by country
<p>I'm trying to clean up a dataset that has data on every country in the world from 2000-2015. The population data by year is quite bad - I want to assign a z scores for each country's population data by year so I can see which data points to drop as outliers. How would I do this? I'm thinking I need to use groupby(),...
<p>Maybe, something like this might work - </p> <pre><code>import numpy as np, pandas as pd l1 = ['a'] * 5 + ['b'] * 10 + ['c'] * 8 l2 = list(np.random.randint(10,20,size=5)) + list(np.random.randint(100,150, size=10)) + list(np.random.randint(75,100, size=8)) df = pd.DataFrame({'cat':l1, 'values':l2}) #creating a dum...
pandas-groupby|outliers
0
367,842
60,859,352
Pandas string regex problem to extract muliple digit numbers
<p>In the following problem how to extract only the number using regex?</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd df = pd.DataFrame({'A': ['&lt; 1 year','1 year', '2 year', '10+ years',np.nan]}) df </code></pre> <h1>My attempt</h1> <pre class="lang-py prettyprint-ove...
<p>Why not just put a '\d+' for regex? That whould give the correct answer and </p> <p>extract all the numbers for an item in a list</p> <p>And as sammywemmy said try it like that:</p> <pre><code>df.A.str.extract(r'(\d+)') </code></pre>
python|regex|pandas
1
367,843
61,080,747
Find the mean of array1 scores when array2 has scored less than 10
<pre><code>&gt;&gt;&gt; ravi = np.arange(1,13).reshape(3,4) &gt;&gt;&gt; sai = np.random.randint(1,50,12).reshape(3,4) &gt;&gt;&gt; print(ravi) &gt;&gt;&gt; print(sai) ravi= [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] sai = [[40 3 7 31] [15 16 30 20] [28 1 27 5]] </code></pre> <p>for...
<p>If you mean, the mean of all the scores corresponding to the ones where Sai scored less than 10, you can do that with <code>np.mean(ravi[sai &lt; 10])</code></p>
python|arrays|numpy|random
3
367,844
61,093,696
Iterating form over rows and columns at once on DataFrame Python
<p>I have a data set, say df, which has following information. Basically i want iterate over columns &amp; create new columns</p> <pre><code>df ID Day1 Day2....Day10 1 High Low 2 Medium High 3 Low Medium 4 Low Low 5 High High . . . . . . . . . </code></pre> ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>DataFrame.filter</code></a> for <code>Day</code> columns, then <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferre...
python|python-3.x|pandas
2
367,845
61,002,151
Importing covid stats into pandas
<p>I have been looking for ways to import this Google sheets data into a pandas dataframe without much luck. I have tried all the methods I could find for reading it in and specifying particular pages/sheets, but to me it looks like Google has changed the format since those documents have been written.</p> <p>I can co...
<p>maybe this may help if panda will be able to read the url:</p> <p><a href="https://i.stack.imgur.com/WcYeD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WcYeD.png" alt="0"></a></p>
pandas|dataframe|google-sheets|import
0
367,846
60,978,254
pandas - create true/false column if column header is substring of another column
<p>I am following <a href="https://stackoverflow.com/questions/43855685/python-pandas-check-if-string-in-one-column-is-contained-in-string-of-another-c">this post</a> to create a number of columns that are true/false based on if a substring is present in another column.</p> <p>Prior to using the code in the above post...
<p>Two steps,</p> <p>first, we explode your list and create a pivot table to re-concat to your original df based on the index.</p> <pre><code>s = df['LANGUAGES'].str.replace("'",'').str.split(',').explode().to_frame() cols = s['LANGUAGES'].drop_duplicates(keep='first').tolist() df2 = pd.concat([df, pd.crosstab(s.i...
python|pandas|dataframe|boolean|substring
1
367,847
60,956,715
Determine counts for each column by label
<p>I have a very large (308801, 256) <code>dataframe</code> I am working with. In the <code>dataframe</code>, there is a column, <code>ON_TIME</code>, which holds the values 1 or 0 (yes, we made the delivery on time, or no, we did not).</p> <p>I would like to, for each column, count the amount of times each value was ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>pd.crosstab</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.add_prefix.html" rel="nofollow noreferrer"><code>DataFrame.add_prefix</code></...
python|pandas
2
367,848
60,996,584
BERT embedding for semantic similarity
<p>I earlier posted this <a href="https://stackoverflow.com/questions/60767089/bert-get-sentence-level-embedding-after-fine-tuning">question</a>. I wanted to get embedding similar to this <a href="https://www.youtube.com/watch?v=_eSGWNqKeeY" rel="noreferrer">youtube</a> video, time 33 minutes onward.</p> <p>1) I dont ...
<p>Google's BERT model consist of 12 layers of Transformer Encoders with 12 heads of attention each, and every layer embedding size (or hidden size) is 768. Hence it's label in TF hub: <code>bert_uncased_L-12_H-768_A-12</code>. Uncased is to indicate that BERT is case insensitive i.e. every word is lower cased before p...
python|tensorflow|keras|bert-language-model
5
367,849
60,762,636
Projecting from Irish Transverse Mercator (ITM) to WGS84 latitude-longitude
<p>Unfortunately my projection from Irish Transverse Mercator (ITM) to WGS84 latitude-longitude seems to have gone wrong as the plotted coordinates don't line up with a map of Dublin <a href="https://data.gov.ie/dataset/local-electoral-areas-osi-national-statutory-boundaries" rel="nofollow noreferrer">sourced from the ...
<p>Very simple fix thanks to @joris</p> <p>Altered function using x &amp; y as arguments for gpd.points_from_xy instead of the previously mixed up longitude &amp; latitude:</p> <pre><code>def create_geodf_from_GPS (df, x, y, crs): locations = gpd.points_from_xy(x, y) geo_df = gpd.GeoDataFrame(df, geometry=loca...
python|geopandas|pyproj
0
367,850
60,962,813
encounter error 'str' object has no attribute 'log' when perform np.log()
<p>after I set date to date object and make it index, when I use np.log(), i got the error message: AttributeError:'str' object has no attribute 'log' TypeError: loop of ufunc does not support argument 0 of type str which has no callable log method my input value is a series of data, which shouldn't be a problem <a hre...
<p>have you tried taking the values and placing them in an array before applying the log?</p> <pre><code>np.log(np.array(ts_data.values)) </code></pre>
python|numpy|attributeerror|logarithm
1
367,851
61,107,068
Why is the file csv in pandas stored incorrectly?
<p>I'm practicing csv files in pandas.But their output is like this Does anyone know the problem?</p> <p><a href="https://i.stack.imgur.com/cfI1h.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cfI1h.png" alt="enter image description here"></a></p> <pre><code>import pandas as pd df=pd.DataFrame({ ...
<p>use "sep=';'" in your to_csv method. It could be that your Excel default settings are not on importing csv with ",". First try to add the comma in the Excel import csv settings. Otherwise you can use sep=';' to get work faster. But it depends to you. Hope you are doing fine. Kind regards.</p>
pandas|csv
0
367,852
61,162,874
Pandas Dataframe not returning results for 1 string value in a column using .loc
<p>I am currently working on a discord bot for a webapp that I am planning to make in the future that utilizes Pandas to make a dataframe that stores all of the possible drops from an instance in WoW. I have created this bot to take user input, such as "!loot cloth" to store 'cloth' as an argument and pass it to a .loc...
<p>The problem is lstrip removes all the characters you specify that are on the left of the string. 'l' is part of the list of characters you are specifying. lstrip receives a list of characters not a particular string you want to remove. Try this:</p> <pre><code>#import re #This way we use a regular expression to mak...
python|pandas|dataframe|discord.py
1
367,853
61,122,561
training by batches leads to more over-fitting
<p>I'm training a sequence to sequence (seq2seq) model and I have different values to train on for the <code>input_sequence_length</code>. </p> <p>For values <code>10</code> and <code>15</code>, I get acceptable results but when I try to train with <code>20</code>, I get <em>memory errors</em> so I switched the train...
<p>Batch size affects regularization. Training on a single example at a time is quite noisy, which makes it harder to overfit. Training on batches smoothes everything out, which makes it easier to overfit. Translating back to regularization: </p> <ul> <li>Smaller batches add regularization.</li> <li>Larger batches red...
python|machine-learning|neural-network|pytorch|training-data
6
367,854
71,678,851
pandas groupby, counting unique in a group and summing across groups
<p>I have a <code>df</code> as follows:</p> <pre><code>Date Stock Category 2020-01-01 AAA 1 2020-01-01 BBB 2 2020-01-01 CCC 1 2020-01-02 AAA 1 2020-01-02 BBB 2 </code></pre> <p>What I am looking to achieve is <code>sum</code> by <code>Date</code> and then <c...
<p>You pretty much had it, but in your second <code>groupby</code> operation you'll want to group on <code>&quot;Category&quot;</code> in to calculate a cumulative sum across your dates.</p> <p>An implicit assumption is that your dates will be sorted after the first groupby operation. So make sure your keep <code>sort=...
pandas
1
367,855
71,580,632
How to drop columns if a row in a column has a "url"or "http" in it without knowing the column name?
<p>How can drop column A because it has the following &quot;https://&quot; in python?</p> <p>Back story: I have a 500 column Data Frame where 250 columns are &quot;https://&quot; links in the rows explaining what the prior variable is.</p> <p>The goal is to loop through the df to drop columns that have &quot;http://&qu...
<p>The following code snippet should work, removing <strong>any columns</strong> that contain urls:</p> <pre><code>to_drop = [] for column in df: try: has_url = df[column].str.startswith('https://').any() except AttributeError: pass # dtype is not string if has_url: to_drop.append(column) d...
python|pandas|dataframe|parsing
1
367,856
71,768,064
Create a dataframe combination and keep unique column values
<p>I am attempting a problem similar to <a href="https://stackoverflow.com/questions/29777702/aggregate-all-dataframe-row-pair-combinations-using-pandas">this link here.</a> I was able to get assistance for the first part, but am facing difficulties on the second part of creating the final dataframe.</p> <p>Assuming a ...
<p>You can try with <code>cross</code> <code>merge</code></p> <pre><code>out = df.merge(df,how='cross',suffixes = ('_1', '_2')).query('base1_1&lt;base1_2') Out[50]: Gene_1 base1_1 Gene_2 base1_2 1 ABC1 1 ABC2 2 2 ABC1 1 ABC3 3 3 ABC1 1 ABC4 4 4 ABC1 ...
pandas
1
367,857
71,496,937
How can I iterate in dataframe and get output for each group? Now I get only one line and one group is not recognized
<p>I need to iterate through each dataset in the dataframe based on multiple indexes ('Treatment', 'individual', 'regime'). I want to apply curve fit using x and y for each Treatment, individual and regime. Currently I am able to use only one index.</p> <p>This is the dataframe</p> <pre><code>df_tot Treatment ...
<p>You can absolutely iterate through a dataframe with more than 1 index.</p> <p>First of all, there are some major issues with your code :</p> <ol> <li>Add some toy data with your problem, so we can play with it to find a solution to the problem you're facing (and not an output of your data)</li> <li>Don't ever use <c...
pandas|pandas-groupby|curve-fitting|literate-programming
0
367,858
71,606,712
Transforming many columns into 3 column categories which contains lists?
<p>I have a DataFrame with 31 columns, which contains 3 categories &quot;Classic&quot;, &quot;Premium&quot; and &quot;Luxe&quot; I want to swap the way the DataFrame works to have only 3 comumns &quot;Classic&quot;, &quot;Premium&quot; and &quot;Luxe&quot; and 31 categories which can be listed inside.</p> <p>Since I'm ...
<p>You were right with melt. After that you need a pivot table:</p> <pre><code>out = df.replace('',np.nan).melt(&quot;Name&quot;)\ .pivot_table(index=&quot;Name&quot;,columns=&quot;value&quot;,values=&quot;variable&quot;,aggfunc=','.join)\ .rename_axis(None,axis=1).reset_index() </code></pre> <hr /> <pre><code>print(ou...
python|pandas
2
367,859
71,623,319
Creating batches based on city in pandas
<p>I have two different dataframes that I want to fuzzy match against each other to find and remove duplicates. To make the process faster/more accurate I want to only fuzzy match records from both dataframes in the same cities. So that makes it necessary to create batches based on cities in the one dataframe then runn...
<p>You can pass to <code>locals</code></p> <pre><code>variables = locals() for i,j in df1.groupby('group'): variables[&quot;df1_{0}&quot;.format(i)] = j df1_g1 Out[314]: A B origin group duplicate_count 6 3 L file7 g1 2 7 3 L file8 g1 2 </code></pre>
pandas|pandas-groupby
1
367,860
71,625,085
Pandas rearrange groupby objects ( many-to-many)
<p>I have a many-to-many dataframe that look something like this, where and id could have contains multiple lands, and a land could too contains multiple ids:</p> <pre><code>t = pd.DataFrame({ 'id': ['a', 'a', 'b', 'c', 'c', 'c'], 'land': ['A', 'B', 'A', 'A', 'B', 'C'], 'area': [123, 234, 123, 23, 342, 12],...
<p>Option 1 is simple enough. Just <code>set_index</code> + <code>sort_index</code>:</p> <pre><code>option1 = t.set_index(['land','id']).sort_index() </code></pre> <p>Output:</p> <pre><code> area info land id A a 123 Im b 123 gonna c 23 give B a 234 never ...
python|pandas|dataframe|group-by|pandas-groupby
1
367,861
71,543,335
How to count id's per name in a dataframe
<p>I have a list of names:</p> <pre><code>lst = ['Albert', 'Carl', 'Julian', 'Mary'] </code></pre> <p>and I have a DF:</p> <pre><code>target id name A 100 Albert A 110 Albert B 200 Carl D 500 Mary E 235 Mary </code></pre> <p>I want to make another dat...
<p>Check with <code>value_counts</code></p> <pre><code>pd.Categorical(df['name'],lst).value_counts() Out[894]: Albert 2 Carl 1 Julian 0 Mary 2 dtype: int64 </code></pre> <p>Or</p> <pre><code>df['name'].value_counts().reindex(lst,fill_value=0) Out[896]: Albert 2 Carl 1 Julian 0 Mary 2 N...
python|python-3.x|pandas
2
367,862
71,553,274
Regular expression meaning in R : "( \n|\n )"
<p>I am new to R programming and was trying out the gsub function for text replacement in pandas dataframe series(i.e new_text).</p> <p>It a vast series so will not be able to print all here. It is just a series with strings containing postal address.</p> <p>I came across this gsub code : <code>gsub(pattern = &quot;( \...
<p>Your pattern, slightly rewritten, is <code>[ ]\n|\n[ ]</code>, which says to match:</p> <pre class="lang-regex prettyprint-override"><code>[ ]\n a space followed by a newline | OR \n[ ] a newline followed by a space </code></pre> <p>Note that you <em>might</em> be able to use <code>[ ]?\n[ ]?</code> to the sa...
r|pandas|dataframe
1
367,863
71,565,107
Replace dataframe missing value with the given default value by dictionary
<p>I have datarame and I need to replace the missing value with the given default value from dictionary. the dictionary:</p> <pre><code>col_to_def_val = {'director_name':'unknown', 'actor_1_name':'unknown', 'actor_2_name':'unknown', 'actor_3_name':'unknown', 'genres':'unknown', 'plot_keywords':'unknown', 'movie_title':...
<p>All your columns need to be replaced with <code>unknown</code> from what I see. Therefore, you can simply pass:</p> <pre><code>df['key'] = df['key'].fillna(&quot;unknown&quot;) </code></pre> <p>There's no need to do it column-wise for this particular case, where all columns are defaulted to the same value.</p>
python|pandas|dataframe
0
367,864
71,744,814
Removing partial duplicates from a csv file
<p>I have a csv file of ~1800 lines. The file contains multiple duplicates that I want to get rid of while keeping only one original line. E.g.:</p> <ol> <li>We are joining the protest #protest #join http://someurl</li> <li>We are joining the protest #victory</li> <li>#letsrock We are joining the protest! http://anothe...
<p>Maybe you could get rid of all the hashtags and urls and leave only the text, normalize it and try with unique()?</p>
python|pandas|duplicates
2
367,865
71,507,561
Replacing value after groupby
<p>I have a data frame of a grocery store record:</p> <pre><code>df = pd.DataFrame(np.array([['Tom', 'apple1'], ['Tom', 'banana35'], ['Jeff', 'pear0']]), columns=['customer', 'product']) </code></pre> <p>| customer | product | | -------- | --------| | Tom| apple1| | Tom| banana35| |Jeff| pear0| I want to...
<p>You can first replace and then aggregate:</p> <pre><code>product_by_customer = df[&quot;product&quot;].str.replace('[0-9]', '') .groupby(df['customer']).unique() print(product_by_customer) customer Jeff [pear] Tom [apple, banana] Name: product, dtype: object </code></pre> <p>Or aggregate with r...
python|regex|pandas|group-by|series
1
367,866
71,477,899
wrong values from python queues while using two threads
<p>Here I am using two threads. One thread create a dataframe and pass it to another thread through queue. Another thread collect the dataframe from the queue and append it to a csv file. Here when I run the code ,sometimes I got wrongvalues in entire dataframe. shoudl i have to do any corrections in the code ?</p> <p>...
<p>After having played around with the code a bit more, I think the issue is not the increasing queue size, but the global df, which gets reused by getpoints all the time.</p> <p>Try replacing <code>q.put(df)</code> by <code>q.put(df.copy())</code>, which stores a copy of the dataframe in the queue, instead of the &quo...
python|python-3.x|pandas|dataframe|queue
1
367,867
71,757,091
Aproximating a point to a region fill in Plotly Scatter Region Fill
<p>I am using plotly with Python, and I am trying to approach a point to the nearest region boundary considering either x or y axis.</p> <pre><code>import pandas as pd import numpy as np import plotly.graph_objects as go def plot_graph5(points_x, points_y): fig = go.Figure() dx = np.array([[0,129,129,3...
<p>This really is a geometry operation, snapping a point to a line. Hence have used <strong>shapely</strong> to perform the geometric operations. This is use of <a href="https://shapely.readthedocs.io/en/stable/manual.html#linear-referencing-methods" rel="nofollow noreferrer">linear referencing</a></p> <pre><code>imp...
python|numpy|plotly|scatter-plot|plotly.graph-objects
0
367,868
71,784,253
Problem with python while loop going over every element in 2d array
<p>I am having problems with while loops in python right now:</p> <pre><code>while(j &lt; len(firstx)): trainingset[j][0] = firstx[j] trainingset[j][1] = firsty[j] trainingset[j][2] = 1 #top print(trainingset) j += 1 print(&quot;j is &quot; + str(j)) i = 0 while(i &lt; len(firsty)): trainin...
<p>In this case, I would recommend a <code>for</code> loop instead of a <code>while</code> loop; <code>for</code> loops are great for when you want the index to increment and you know what the last increment value should be, which is true here.</p> <p>I've had to make some assumptions about the shape of your arrays bas...
python|numpy
0
367,869
71,452,120
Numpy - list of lists to flat array
<p>I am in the processing phase of my machine learning algorithm where I need to see if a cat is going outside or not. Currently my images are presented by multiple lists like below. (this is how 1 image is shown, an array containing an array that represents 1 row of pixels in the image)</p> <p><div class="snippet" dat...
<p>Try using <code>flatten()</code></p> <pre><code>arr = np.array(arr).flatten().tolist() </code></pre>
python|numpy
0
367,870
71,554,318
Condition Based Custom Flag
<p>I've a dataset</p> <br> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>ref</th> <th>name</th> <th>conditionCol</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>123</td> <td>a</td> <td>no_error</td> </tr> <tr> <td>1</td> <td>456</td> <td>b</td> <td>error</td> </tr> <tr> <td>1</td>...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> with test if at least one value <code>error</code> per groups by <code>id</code>:</p> <pre><code>m = df['id'].isin(df.loc[df['conditionCol'].eq('error'), 'id']) #alternative #m = df[...
python-3.x|pandas|data-wrangling|eda
0
367,871
71,518,661
Does Gpytorch use Analytic gradient or Automatic differentiation for training?
<p>I am confused about how gpytorch calculates the gradients with respect to parameters of the model. For instance, lets say I am using ExactGP with Gaussian likelihood, RBF kernel, and constant mean and using MLE (maximum likelihood estimate) for finding the parameters of the model (mean, kernel parameters, and noise)...
<p>The &quot;automatic differentiation provided by PyTorch&quot; does compute the analytic gradient (via back-propagation, note that there is no finite differencing or anything like that involved) - it just does so automatically.</p> <p><a href="https://github.com/cornellius-gp/gpytorch/discussions/1949#discussioncomme...
pytorch|gaussian|autograd|gaussian-process|gpytorch
0
367,872
71,745,399
How do I feature engineer more than 2 new variables in a pandas dataframe?
<p>I'm making a model that predicts whether an invidual will buy a product after watching an ad.</p> <p>Here's the data, (sorry for the size I don't know how to make it smaller):</p> <p><a href="https://i.stack.imgur.com/iAEeV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iAEeV.png" alt="Data" /></...
<p>You can use <code>apply</code> and <code>lambda</code> function to achieve this in a simple means:</p> <pre><code>eng_data['AgeRange'] = eng_data['Age'].apply(lambda x: 0 if x &lt; 27 else (1 if x &lt; 53 else 2)) </code></pre>
python|pandas|dataframe|feature-engineering
1
367,873
71,482,442
Use previous row value to calculate next value in Pandas MultiIndex DataFrame
<p><a href="https://stackoverflow.com/a/34856727">This</a> SO answer comes close to what I am looking for, but I cannot apply it to a MultiIndex <code>DataFrame</code>.</p> <p>I define a hierarchically-indexed <code>Dataframe</code> like this:</p> <pre><code>arrays = [[&quot;bar&quot;, &quot;bar&quot;], [&quot;one&quot...
<p>IIUC, what you want is a <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.cumprod.html" rel="nofollow noreferrer"><code>cumprod</code></a> where you initialize the value to 100. The rest is just indexing:</p> <pre><code>START = 100 df[('foo', 'one')] = (df[('bar', 'one')] .ad...
python-3.x|pandas|iteration|multi-index
1
367,874
71,540,771
Implementation difference between TensorFlow LSTMBlockFusedCell and PyTorch LSTM
<p>I am attempting to translate a tensorflow <a href="http://man.hubwiz.com/docset/TensorFlow.docset/Contents/Resources/Documents/api_docs/python/tf/contrib/rnn/LSTMBlockFusedCell.html" rel="nofollow noreferrer">LSTMBlockFusedCell</a> model to pytorch <a href="https://pytorch.org/docs/stable/generated/torch.nn.LSTM.htm...
<p>I believe I solved this by changing the order of weight associated with each gate and setting <code>forget_bias=0.0</code> in <code>LSTMBlockFusedCell</code>:</p> <pre><code>import tensorflow as tf import numpy as np import torch import itertools as it time_len, batch_size, input_size, num_units = 50, 1, 64, 100 # ...
tensorflow|pytorch|lstm
0
367,875
71,447,177
Is there a way to remove specific elements in an array using numpy functions?
<p>Is there a way to remove specific elements in an array using <a href="https://numpy.org/doc/stable/reference/generated/numpy.delete.html" rel="nofollow noreferrer"><code>numpy.delete</code></a>, boolean mask (or any other function) that meet certain criteria such as conditionals on that data type?, this by using <st...
<p>Yes, this is part of numpy's magic indexing. You can use comparison operator or the <code>apply</code> function to produce an array of booleans, with True for the ones to keep and False for the ones to toss. So, for example, to keep all the elements less than 5::</p> <pre><code>selections = array &lt; 5 array = ar...
python|numpy
2
367,876
71,505,897
Can not squeeze dim[1], expected a dimension of 1, got 2 [[{{node predict/feature_vector/SpatialSqueeze}}]] [Op:__inference_train_function_253305]
<p>I am finding it difficult to train the following model when using the 'Mobilenet_tranferLearning'. I am augmenting and loading the files from the directory using ImageDataGenerator and flow_from_directory method. What is interesting is that my code does not throw any errors when using InceptionV3, but does when I u...
<p>Make sure you have the <em>same</em> image size <code>(224, 224)</code> in <code>flow_from_directory</code> and in the <code>hub.KerasLayer</code>. Here is a working example:</p> <pre><code>import tensorflow_hub as hub import tensorflow as tf img_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255,...
python|tensorflow|keras|conv-neural-network|transfer-learning
1
367,877
71,494,657
How to write a for-loop/if-statement for a dataframe (integer) column
<p>I have a dataframe with a column of integers that symbolise birthyears. Each row has 20xx or 19xx in it but some rows have only the xx part.</p> <p>What I wanna do is add 19 in front of those numbers with only 2 &quot;elemets&quot; if the integer is bigger than 22(starting from 0), or/and add 20 infront of those tha...
<p>Instead of iterating through the rows, use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.where.html" rel="nofollow noreferrer"><code>where</code></a> to change the whole column:</p> <pre><code>y = df[&quot;Year&quot;] # just to save typing df[&quot;Year&quot;] = y.where(y &gt; 99, (y + 1900)...
python|pandas|dataframe|for-loop|if-statement
1
367,878
71,517,750
How to replace pandas append with concat?
<p>Can you help me replace append with concat in this code?</p> <pre><code>saida = pd.DataFrame() for x, y in lCodigos.items(): try: df = consulta_bc(x) logging.info(f'Indice {y} lido com sucesso.') except Exception as err: logging.error(err) logging.warning('Rotina Indice falhou!') exit() df['nome'...
<p>Just save the &quot;dataframe parts&quot; using a list and use <a href="https://pandas.pydata.org/docs/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>pd.concat</code></a> on that list of dataframes at the end:</p> <pre class="lang-py prettyprint-override"><code>saida = list() # Now use a list for...
python|pandas
1
367,879
71,662,436
Extract a selective list of entries from an Excel sheet using pandas
<h1>How do I extract the x,y and z rows with the corresponding values in the &quot;Value&quot;, &quot;Value %&quot; and &quot;Upper Limit %&quot; columns without including the rest of the contents?</h1> <h2>Current Python code being used</h2> <pre><code>data = sheet_data.iloc[:,[0,1,2,4]] data['Item Copy'] = data.loc[...
<p>if I understand correctly, you want to extract the contents of all cells from 'x' at the top left corner, down to the bottom right corner.</p> <p>I'm not sure if your 'Current Python code being used' is initially reducing your spreadsheet down from a much larger file, or if it is attempting to make the extraction yo...
python|excel|pandas
0
367,880
71,579,367
How to replace string in pandas data frame to NaN?
<p>Let's consider following data frame:</p> <p><a href="https://i.stack.imgur.com/Vdww9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vdww9.png" alt="enter image description here" /></a></p> <p>I want to change string-type elements of this DataFrame into <code>NaN</code>. Example of an solution wou...
<p>Use df.replace regex</p> <pre><code>import numpy as np df.replace(regex='[A-Za-z]', value=np.nan) </code></pre>
python|pandas
2
367,881
71,650,793
Expanding Records Based On Date Range Pandas
<p>I am attempting to expand the records in a data frame between two dates. Given the input file of single entry for each record, I want to expand it based on a given date.</p> <p>Here is an example of the input: <a href="https://i.stack.imgur.com/BeOu6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com...
<pre><code>df_merged = pd.read_excel(&quot;inputdatawithtestcase.xlsx&quot;) df_merged['DATE'] = [pd.date_range(s, e, freq='6M') for s, e in zip(pd.to_datetime(df_merged['Exposure Start']), pd.to_datetime(df_merged['Exposure Stop']))] df_merged = df_merged.explode('DATE') df_merged['c...
python|pandas|dataframe|pandas-explode
0
367,882
71,572,843
What does a Keras TimeDistributed layer actually do?
<p>Given a time-series, I have a multi-step forecasting task, where I want to forecast the same number of times as time steps in a given sequence of the time-series. If I have the following model:</p> <pre><code>input1 = Input(shape=(n_timesteps, n_channels)) lstm = LSTM(units=100, activation='relu')(input1) outputs = ...
<p>Based on the example you posted, the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/TimeDistributed" rel="nofollow noreferrer">TimeDistributed</a> will essentially apply a <code>Dense</code> layer with a <code>softmax</code> activation function to each timestep:</p> <pre><code>import tensorflow ...
python|tensorflow|keras|lstm
2
367,883
71,595,212
SKlearn pipelines cannot work when creating new Dataframe inside custom transformer
<p>I have a pipeline with pipelines and columntransformers, with some custom transformers How can I fix this:</p> <pre><code>Input In [8], in &lt;cell line: 21&gt;() 19 # Fit all (1) models defined in our model-search object 20 print(X_train.shape) ---&gt; 21 best = cv_model_search.fit(X_train,y_train) File ...
<p>set <code>columns = X.columns</code> in your custom transfomer.</p>
python|pandas|scikit-learn
1
367,884
71,486,063
Filter pandas dataframe rows where a specific row with column A and value X has column B with value Y greater than a parameter Z
<p>I wonder if there's a simpler way to filter a pandas DataFrame rows where a specific row with column A and value X has column B with value Y greater than a parameter Z.</p> <hr /> <p>For example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;"></th> <th style=...
<p>You could chain the two with <code>|</code>:</p> <pre><code>out = df[(df.A.isin(['X1', 'X2']) &amp; (df.B &gt; Z)) | (df.A == 'X3')] </code></pre> <p>or using the definitions you already have:</p> <pre><code>out = df[(mask1 &amp; mask2) | mask3] </code></pre> <p>Output:</p> <pre><code> A B 72154 X1 ...
python|pandas|dataframe|filter
2
367,885
71,514,413
Matrix are not aligned for dot product
<p>Here is my df matrix:</p> <pre><code> 0 Rooms Area Price 0 0 0.4 0.32 0.307692 1 0 0.4 0.40 0.461538 2 0 0.6 0.48 0.615385 3 0 0.6 0.56 0.646154 4 0 0.6 0.60 0.692308 5 0 0.8 0.72 0.769231 6 0 0.8 0.80 0.846154 7 0 1.0 1.00 1.000000 </code></pre> <p>H...
<p>You can just do <code>mul</code></p> <pre><code>out = df.mul(B['weights'].values,axis=1) Out[207]: 0 Rooms Area Price 0 0 34.8 14.08 14.153832 1 0 34.8 17.60 21.230748 2 0 52.2 21.12 28.307710 3 0 52.2 24.64 29.723084 4 0 52.2 26.40 31.846168 5 0 69.6 31.68 35.384626 6 0 ...
python|pandas|numpy|matrix|matrix-multiplication
2
367,886
71,746,861
Android Media Image to Bitmap Conversion for Tensorflow Lite
<p>I am taking the camera input and processing it with <strong>Tensorflow Lite</strong> model to detect the image and gesture. Tensorflow lite model is <strong>taking bitmap as an input</strong>. I am taking the camera image which is in <strong>android media image</strong> format. Here my problem is I am trying to conv...
<p>The null return value suggests that the image data could not be decoded when you call <code>BitmapFactory.decodeByteArray</code>. You may check your input contents first.</p> <p>Here is a link to another similar question about how to convert android.media.image to Bitmap : <a href="https://stackoverflow.com/question...
java|android|image|tensorflow|bitmap
1
367,887
71,766,462
Merging columns with Python and Pandas
<p>I'm using Python 3.0 and Pandas to clean some data.</p> <p>I've the following table :</p> <pre><code># Item_ID Date_1 Date_2 0 1857 2020-11-05 00:00:00 2020-12-05 00:00:00 1 1569 2020-12-09 00:00:00 2021-01-07 00:00:00 2 2569 2020-12-09 00:00:00 Na...
<p>You can use a mask with help of <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>pandas.to_datetime</code></a> to ensure that you have dates:</p> <pre><code>mask = pd.to_datetime(df['Date_2'], errors='coerce').isna() df['Date_3'] = df['Date_1'].where(mask...
python|pandas
1
367,888
71,543,363
How to drop the index after creating the csv file in pandas
<p>I am trying to select couple of columns based on column heading with wild card and one more column. When I execute the below code , I am getting the expected result, but there is an index which is appearing. how to drop the index . Any suggestions.</p> <p>infile:</p> <pre><code>dir,name,ct1,cn1,ct2,cn2 991,name1,em,...
<p>Pass false for index when you save to csv :</p> <pre><code>df_merge.to_csv('outfile.csv', index=False) </code></pre>
python|pandas|csv
0
367,889
71,455,648
Couldn't convert pytorch model to ONNX
<p>I used this repo : <a href="https://github.com/Turoad/lanedet" rel="nofollow noreferrer">https://github.com/Turoad/lanedet</a> to convert a pytorch model that use mobilenetv2 as backbone To ONNX but I didn't succeeded.</p> <p>i got a Runtime error that says:</p> <blockquote> <p>RuntimeError: Exporting the operator e...
<p>Use torch&gt;=1.7.0 to convert the model, because operation <a href="https://github.com/pytorch/pytorch/blob/e85d494707b835c12165976b8442af54b9afcb26/torch/onnx/symbolic_opset9.py#L1648" rel="nofollow noreferrer">Eye</a> is added.</p>
python|pytorch|transfer-learning|onnx|onnxruntime
0
367,890
71,728,982
SQLAlchemy + Pandas: saving array of strings to Postgres saves them as array of chars
<p>I am trying to save an array of strings to Postgres but when I check, the array of strings is saved as an array of chars. Example using sqlalchemy for my database engine</p> <pre><code>df = pd.read_csv('data.csv') df.to_sql('tablename', dtypes={'array_col':sqlalchemy.dialects.postgresql.Array(sqlalchemy.dialects.pos...
<p>I think you need to convert the string from the csv into an array first using <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html#pandas-read-csv" rel="nofollow noreferrer">converters</a> argument in <code>read_csv()</code> before calling <code>to_sql</code>.</p> <p>This example assumes they a...
python|pandas|sqlalchemy
1
367,891
71,732,430
Pandas: How to look at the shape of a dataframe?
<p>I want to process raw data <code>data_mrna_agilent_microarray_zscores_ref_all_samples.txt</code> and look at the shape of the dataframe.</p> <pre><code>import pandas as pd dir = &quot;/content/gdrive/MyDrive/Cancer_Pathways/gbm_tcga/&quot; class DataProcessing: def __init__(self, data, header=0): self...
<p>More of a python question than of a pandas question. Dataframes indeed have a property called shape but again, it is the dataframes that have that property, not your own custom class. The dataframe here is in <code>rna.df</code>which means to get the shape of that you need to access the df instead. <code>rna.df.shap...
python|pandas|dataframe
0
367,892
71,628,546
Operating large .csv file with pandas/dask Python
<p>I've got a large .csv file (5GB) from UK land registry. I need to find all real estate that has been bought/sold two or more times.</p> <p>Each row of the table looks like this:</p> <pre><code>{F887F88E-7D15-4415-804E-52EAC2F10958},&quot;70000&quot;,&quot;1995-07-07 00:00&quot;,&quot;MK15 9HP&quot;,&quot;D&quot;,&qu...
<p>Some minor suggestions:</p> <ul> <li><p>if 5GB is the full dataset, it's best to use plain pandas. The strategy you outlined might involve communication across partitions, so it's going to be computationally more expensive (or will require some work to make it more efficient). With <code>pandas</code> all the data w...
python|pandas|data-science|dask|dask-dataframe
2
367,893
71,450,463
I'm getting KeyError: 'bbox' in my code and I don't see why
<p>This code is related to my research work. I am using the Yolo model for which I am creating bounding boxes. Now I am using this code for creating bounding boxes.</p> <pre><code>bboxs= np.stack(df['bbox'].apply(lambda x: np.formstring(x[1:-1], sep=','))) for i, column in enumerate(['xmin','ymin','w','h']) df[...
<p>KeyError: 'bbox' when accessing the column of a dataframe (df) indicates that there is no column with the name 'bbox' in df. To check which columns exist, they could be output as follows: <code>print(df.columns)</code>.</p>
python|pandas|dataframe
1
367,894
71,702,376
TypeError: 'int' object is not subscriptable in dataframe.iterrows
<p>I am trying to loop over a dataframe like the following:</p> <pre><code>for row, index in split[0].iterrows(): kitname = row['kit_name'][0] print(kitname) </code></pre> <p>where <code>split</code> is a list of dataframes</p> <pre><code>split[0] : kit_name kit_info part_name part_n...
<p>Problem is you swap <code>index</code> and <code>row</code> variables, so <code>row</code> are integers so select <code>['kit_name']</code> failed:</p> <pre><code>for row, index in split[0].iterrows(): kitname = row['kit_name'][0] print(kitname) </code></pre> <p>Need:</p> <pre><code>for index, row in split[0...
python|pandas
3
367,895
71,596,864
Identifying partial character encoding/compression in text content
<p>I have a CSV (extracted from BZ2) where only some values are encoded:</p> <pre><code>hoxvh|c1x6nos c1x6e26|0 1 hqa1x|c1xiujs c1xj4e2|1 0 hpopn|c1xeuca c1xdepf|0 1 hpibh c1xcjy1|c1xe4yn c1xd1gh|1 0 hqdex|c1xls27 c1xjvjx|1 0 </code></pre> <p>The <code>|</code>, <code>0</code> and <code>1</code> characters are definite...
<p>From <a href="https://nlp.cs.princeton.edu/SARC/2.0/readme.txt" rel="nofollow noreferrer">readme.txt</a>:</p> <blockquote> <p>File Guide:</p> <ul> <li>raw/key.csv: column key for raw/sarc.csv</li> <li>raw/sarc.csv: contains sarcastic and non-sarcastic comments of authors in authors.json</li> <li>*/comments.json: dic...
python|pandas|csv|encoding|dataset
1
367,896
71,483,303
Automatic import of multiple CSV files with pandas
<p>I have 2 folders with 365 CSV files each. However, I only need certain columns from these CSV files. I have already solved this problem with pandas usecols. But only for one file. I want to automate the whole thing. With an incrementing variable date</p> <pre><code>f{date}_sds011_sensor_3659.csv </code></pre> <p>I d...
<p>Possible solution is the following:</p> <pre><code>import glob import pandas as pd all_files = glob.glob('folder_name/*.csv', recursive=True) all_data = [] for file in all_files: df = pd.read_csv(file, index_col=None, header=0, usecols=['col1', 'col2']) all_data.append(df) result = pd.concat(all_data, ax...
python|pandas|sqlite|csv
0
367,897
71,617,778
Get Address from latitude and longitude using geopy pandas
<p>I have an excel file containing multiple latitude and longitude and I need state, district, and city against in excel. Can anyone help me with this? (Read from excel and insert into excel)</p> <p>Sample excel data is like below</p> <p><a href="https://i.stack.imgur.com/pXuyS.png" rel="nofollow noreferrer"><img src="...
<pre><code>from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent=&quot;geoapiExercises&quot;) df = pd.read_excel('latlong.xlsx') # Your excel file location result = [] for index in df.index: result.append(geolocator.reverse(f&quot;{df.iloc[index,0]}&quot;+&quot;,&quot;+f&quot;{df.iloc[index,1]}&qu...
python|pandas|geopy
0
367,898
71,747,003
Python Pandas DataFrame Meessage
<p>please how can I replace this message with my own?</p> <pre><code>Empty DataFrame Columns: [Airline, Destination, Passengers] Index: [] </code></pre>
<p>You should overwrite <code>__repr__</code> method:</p> <pre><code>class MyDataFrame(pd.DataFrame): def __repr__(self): if self.empty: return 'some stuff' else: return super().__repr__() # print(MyDataFrame()) # some stuff </code></pre>
python|pandas|dataframe
0
367,899
71,742,242
Interpreting geopandas latitude/longitude data from shapefile
<p>I am using geopandas to extract the latitude and longitude coordinates (rather than the polygon coordinates) for a shapefile. Currently, I am using the centroid x/y methods to get the coordinates from my geopandas df <strong>data</strong>:</p> <pre><code>lon = data.centroid.x lat = data.centroid.y </code></pre> <p...
<p>&quot;Why are the values so large? Is it because I am using the wrong CRS?&quot;</p> <p>--&gt; Because these coordinates are planar projections and their values are in meters. The most common planar projection is UTM so probably it's the case. You can find more about UTM coordinates <a href="https://youtu.be/LcVlx4G...
python|maps|latitude-longitude|geopandas
1