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
352,600
53,963,892
Return only dataframe columns that satisfy where clause
<p>Starting with an arbitrary dataframe, I would like to return a dataframe with only those columns which have more than one distinct value.</p> <p>I have:</p> <pre><code>X = df.nunique() </code></pre> <p>like:</p> <pre><code> Id 5 MSSubClass 3 MSZoning 1 LotFrontage ...
<p>You can use Boolean indexing and avoid converting your counts series to a dataframe:</p> <pre><code>counts = df.nunique() df = df[counts[counts &gt; 1].index] </code></pre> <p>The key is to note the <em>index</em> of your <code>counts</code> series are the column labels. So you can filter the series and then extra...
python|pandas
3
352,601
54,186,021
Difference between rows that share similar variables
<p>I have a table (c.14,000 or so rows / 100 or so columns) where the order cannot change. Each row is made unique by a number of columns, which I have simplified below.</p> <p>Assume we have the below table, I need to create a new column that takes the difference between rows that share the same Col2/Col3 (but are un...
<p>I have solved this, but I believe in an in-efficient manner! </p> <p>I created a new dataframe</p> <pre><code>df2 = df[['Col1','Col2','Co3','Percentgage']] </code></pre> <p>Created a new column in df2 that is the mirror of column 1 (i.e. if 2 = 5, if 5 = 2)</p> <pre><code>df2['opposite_col1'] = np.where(df2['Col...
python|pandas|dataframe|match
0
352,602
53,901,603
How to transfer weight of own model to same network but different number of classin last layer?
<p>I have my own network in Pytorch. It first trained for the binary classifier (2 classes). After 10k epochs, I obtained the trained weight as <code>10000_model.pth</code>. Now, I want to use the model for 4 classes classifier problem using the same network. Thus, I want to transfer all trained weights in the binary c...
<p>Both networks have the same layers and therefore the same keys in <code>state_dict</code>, so indeed</p> <pre><code>pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict} </code></pre> <p>does nothing. The difference between the two is the <em>weight tensors</em> (their shape) and not thei...
python|deep-learning|pytorch
2
352,603
54,147,155
Pandas: after using qcut(data,3), how to find the range of the quantile
<p>My data looks like this:</p> <pre><code> spread CPB% Bin 0 0.00000787 0.001270648030495552731893265565 B 1 0.00000785 0.003821656050955414012738853503 A 2 0.00000749 0.005821656050955414012738853503 C 3 0.00000788 0.004821656050955414012738853503 B </code><...
<p>I believe you need add parameter <code>retbins=True</code> for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.qcut.html" rel="nofollow noreferrer"><code>qcut</code></a> for return intervals, so is possible reuse it in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.ht...
python|pandas
2
352,604
53,803,361
Pandas DataFrame Conditional Groupby
<p>I have this DF:</p> <pre><code>df = pd.DataFrame(data=[[-2.000000, -1.958010, 0.2], [-1.958010, -1.916030, 0.4], [-1.916030, -1.874040, 0.3], [-1.874040, -1.832050, 0.6], [-1.832050, -1.790070, 0.8], [-1.790070, -1....
<p>You could try this to get the mean of fx every 2 rows:</p> <pre><code>result = df.groupby(np.arange(len(df))//2).mean() print(result) egystart egyend fx 0 -1.979005 -1.937020 0.30 1 -1.895035 -1.853045 0.45 2 -1.811060 -1.769075 0.50 </code></pre>
python|pandas|pandas-groupby
1
352,605
54,248,650
Fill missing values based on another column in a pandas DataFrame
<p>I'm working with Pandas and numpy, For the following data frame, lets call it 'data', for the Borough values with data['Borough'] == 'Unspecified', I need to use the zip code in the Incident Zip field to the left of it to do a lookup on the Incident Zip column for the matching zip code and Borough. Once this is fou...
<p>IIUC, you want to use other values in the DataFrame to fill missing values. You can do this with <code>map</code>.</p> <p>First, generate a Series mapping Zip codes to the Borough.</p> <pre><code>mapping = (df.query('Borough != "Unspecified"') .drop_duplicates('Incident Zip') .set_index('...
python|pandas|dataframe
2
352,606
54,055,602
Plot statistical information of multiple recordings of experiments with Seaborn
<p>I have a randomized algorithm which I repeat several times, so I can evaluate it statistically. The dataframes from the experiments can be grouped to calculate the mean and median. </p> <p>Now, I would like to plot the original information, along with the statistics I also calculated, with Seaborn. So I have up to ...
<p>I'm not sure you are using <code>lineplot</code> correctly in your second example. The whole point is to let seaborn calculate the statistics and plot the graph estimator ± ci for you. I don't see the point of calculating the mean in a dataframe, and then asking seaborn to plot the mean of the dataframe.</p> <p>But...
python|pandas|plot|seaborn
1
352,607
54,200,785
Torch C++: Getting the value of a int tensor by using *.data<int>()
<p>In the C++ version of Libtorch, I found that I can get the value of a float tensor by <code>*tensor_name[0].data&lt;float&gt;()</code>, in which instead of <code>0</code> I can use any other valid index. But, when I have defined an <code>int</code> tensor by adding option <code>at::kInt</code> into the tensor creati...
<p>Use <code>item&lt;dtype&gt;()</code> to get a scalar out of a Tensor.</p> <pre><code>int main() { torch::Tensor tensor = torch::randint(20, {2, 3}); std::cout &lt;&lt; tensor &lt;&lt; std::endl; int a = tensor[0][0].item&lt;int&gt;(); std::cout &lt;&lt; a &lt;&lt; std::endl; return 0; } ~/l/build ❯❯❯ ./e...
c++|pytorch|torch|libtorch
16
352,608
53,903,206
Compare columns of numpy matrix with array
<p>I have a numpy matrix and want to compare every columns to a given array, like:</p> <pre><code>M = np.array([1,2,3,3,2,1,1,3,2]).reshape((3,3)).T v = np.array([1,2,3]) </code></pre> <p>Now I want to compare every columns of M with v, i.e. I want a matrix with the first column consisting of True, True, True. A seco...
<p>Use broadcasted comparison:</p> <pre><code>&gt;&gt;&gt; M == v[:, None] array([[ True, False, True], [ True, True, False], [ True, False, False]]) </code></pre>
python|arrays|numpy
4
352,609
54,088,378
parse multiple tables into one csv with python
<p>i have a csv file where all tables are underneath each other. All tables have a MasterId with which I could link them. Currently I try it with pandas.pivot_table</p> <p>Here how the csv looks like now</p> <pre><code>masterId featureName featureValue 1 bar fooo 2 bar x 3 bar ...
<p>I guess it's because some indicies in <code>masterId</code> index columns don' match. First, let's look when it works correctly: </p> <pre><code>untransposedDataFrame = pd.concat((df1, df2)) # df1, df2 from your example untransposedDataFrame ...
python-3.x|pandas|pivot-table
0
352,610
53,823,596
Get a row of data in pandas as a dict
<p>To get a row of data in pandas by index I can do:</p> <pre><code>df.loc[100].tolist() </code></pre> <p>Is there a way to get that row of data as a dict, other than doing:</p> <pre><code>dict(zip( df.columns.tolist(), df.loc[100], tolist() )) </code></pre>
<p>Try with <code>to_dict</code></p> <pre><code>df.loc[1].to_dict() </code></pre>
python|pandas
8
352,611
54,233,679
How to iterate over dfs and append data with combine names
<p>i have this problem to solve, this is a continuation of a previus question <a href="https://stackoverflow.com/questions/54145284/how-to-iterate-over-pandas-df-with-a-def-function-variable-function">How to iterate over pandas df with a def function variable function</a> and the given answer worked perfectly, but now ...
<p>Here is how I will go about it, pandas.melt comes to rescue:</p> <pre><code>import pandas as pd import numpy as np from io import StringIO s = StringIO(''' Name exact_mass M+3H M+3Na M+H 2M+H M-3H 0 a 596.465179 199.829002 221.810726 597.472455 1193.937634 197.814450 1 b ...
python-3.x|pandas|slice
2
352,612
54,224,104
Difference between pandas Series category data type vs pandas Categorical data type
<p>I'm coming up against this surprising inability to access what I expected to have a <code>codes</code> attribute for a column of data in a CSV that I'm coercing to a category type via the <code>dtype</code> parameter to <code>read_csv</code>.</p> <p>If I run the following code</p> <pre><code>import pandas csv_str...
<p><code>pd.Categorical</code> returns an object of <code>Categorical</code> type:</p> <pre><code>c = pd.Categorical(df['c1']) c # [a, b, a, c, a] # Categories (3, object): [a, b, c] type(c) pandas.core.arrays.categorical.Categorical </code></pre> <p>OTOH, <code>df['c1']</code> is a <code>Series</code> of type <code...
python|pandas
1
352,613
53,953,528
How can I create a neural network with Keras that trains from tabular data?
<p>I'm relatively new to Python, so please forgive the ignorance. I have tabular data that looks like:</p> <pre><code>Type,Name,Age,Breed1,Breed2,Gender,Color1,Color2,Color3,MaturitySize,FurLength,Vaccinated,Dewormed,Sterilized,Health,Quantity,Fee,State,RescuerID,VideoAmt,Description,PetID,PhotoAmt,AdoptionSpeed 2,Nib...
<p>The default <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.loadtxt.html" rel="nofollow noreferrer">dtype</a> of numpy loadtxt is <code>float</code>. Instead use:</p> <pre><code>dataset = np.loadtxt("data/train.csv", delimiter=",", dtype=np.str) </code></pre>
python|tensorflow|keras|neural-network
1
352,614
54,087,054
Interpreting output of `model_main.py` in Tensorflow Object Detection API
<p>I was able to successfully train my model by running <code>model_main.py</code> and got this result:</p> <blockquote> <p>Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.344</p> <p>Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.514</p> <p>Average P...
<p>Part of the answer (area, mAP) can be found in this post here:</p> <p><a href="https://stackoverflow.com/questions/52068835/tensorboard-graph-recall/52097660">Tensorboard graph recall</a></p> <p>Your "Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ]" corresponds to "DetectionBoxes_Recall/AR@1" in th...
tensorflow|object-detection-api
1
352,615
53,960,914
How can I select multiple columns in python
<p>I'm working on a dataset (Rows:5000 and Columns: 60). I want to read some of the columns which are related to my analysis but the code doesn't work.</p> <blockquote> <p>Column 1, column 5, columns 22 to 28 and columns 47 to 54.</p> </blockquote> <p>I've read the manual and it seems just I can select the number o...
<p>You could create a list with the indices by <a href="https://docs.python.org/3/library/itertools.html#itertools.chain" rel="nofollow noreferrer">chaining</a> the iterables:</p> <pre><code>import numpy as np import pandas as pd from itertools import chain # create sample data-frame data = np.random.randint(1, 10, s...
python|pandas
3
352,616
54,166,164
re-shaping a pandas dataframe
<p>So I have a data frame like below:</p> <p><a href="https://i.stack.imgur.com/mXIfz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mXIfz.png" alt="enter image description here" /></a></p> <p>How can I change the data frame to make below table using pandas?</p> <p><a href="https://i.stack.imgur.com...
<p>You could try this for having the countries grouped as index :</p> <p>using <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.melt.html" rel="nofollow noreferrer"><code>pd.melt()</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" ...
python|pandas
1
352,617
53,950,972
What is the fastest way to go from a list that describes the temperature on a fine mesh to one that describes the temp. on a coarse mesh with Python?
<p>For example, say that I have a list in which the the index of the list is a particular cell number and the value for that index is the temperature of that particular cell. Let’s say that the list looks like this:</p> <pre><code>fine_mesh = [600,625,650,675,700,725,750,775,800,825] </code></pre> <p>Then, let’s say ...
<p>Using <code>numpy</code> you can vectorize addition (and multiplication, etc) and you can use slices so you can do the following</p> <pre><code>import numpy as np # ... snip ... fine_mesh = np.array(fine_mesh) coarse_mesh = 0.5 * (fine_mesh[::2] + fine_mesh[1::2]) </code></pre> <p>Since it's <code>numpy</code> it'...
python|numpy
4
352,618
54,088,858
Plotting a map using geopandas and matplotlib
<p>I have small csv that has 6 coordinates from Birmingham England. I read the csv with pandas then transformed it into GeoPandas DataFrame changing my latitude and longitude columns with Shapely Points. I am now trying to plot my GeoDataframe and all I can see are the points. How do I get the Birmingham map represent...
<p>The GeoPandas documentation contains an example on how to add a background to a map (<a href="https://geopandas.readthedocs.io/en/latest/gallery/plotting_basemap_background.html" rel="noreferrer">https://geopandas.readthedocs.io/en/latest/gallery/plotting_basemap_background.html</a>), which is explained in more deta...
python|geopandas
10
352,619
54,190,705
why does Unicode Decode Error message appear when I load a dataset?
<p>I have converted an Excel file to csv, the goal is to analyse this dataset with python. So after importing my modules and the Dataset by using this code</p> <pre><code>Import pandas as pd Import numpy as np Import matplotlib as mlt pd.read_csv('filename.csv') </code></pre> <p>I had the following message:</p> <pr...
<p>First, you need know what <strong>character encoding</strong> your file realy is. It's not UTF-8.</p> <p>There are lots of different character encodings, sometimes the Excel change encoding to 'iso-8859-1' or 'cp1252', it's crazy.</p> <p>Here is a important info that every IT person must know: <a href="https://www...
python|pandas
0
352,620
54,218,726
Why use absolute instead of relative imports in a Python package?
<p>I've recently created a Python package, and within it, used only relative imports to access functions stored in other methods. </p> <p>Now, in Numpy, I see a lot of files that make heavy use of absolute imports, e.g. <a href="https://github.com/numpy/numpy/blob/8f547f246b0c7463768adebafe0a57df9c03321b/numpy/lib/fun...
<p><a href="https://realpython.com/absolute-vs-relative-python-imports/" rel="nofollow noreferrer">Absolute vs Relative Imports in Python</a></p> <h3>Absolute Import</h3> <blockquote> <p>Absolute imports are preferred because they are quite clear and straightforward. It is easy to tell exactly where the imported resour...
python|numpy
1
352,621
54,042,737
There is an error with LSTM Hidden state dimension: RuntimeError: Expected hidden[0] size (4, 1, 256), got (1, 256)
<p>I'm experimenting with seq2seq_tutorial in PyTorch. There appears to be a dimension error with the encoder's lstm hidden state size.</p> <p>With <code>bidirectional=True</code> and <code>num_layers = 2</code>, the hidden state's shape is supposed to be <code>(num_layers*2, batch_size, hidden_size)</code>. </p> <p>...
<p>I know this was asked a while ago but I think I found the answer to this in <a href="https://discuss.pytorch.org/t/lstm-hidden-state-changing-dimensions-error/23359" rel="nofollow noreferrer">this torch discussion</a>. Relevant info:</p> <blockquote> <p>LSTM takes a tuple of hidden states: self.rnn(x, (h_0, c_0))...
python|pytorch
2
352,622
53,826,582
Pandas assign cumulative count for consecutive values in a column
<p>This is my data:</p> <pre><code>print(n0data) FULL_MPID DateTime EquipID count Index 1 5092761672035390000000000000 2018-11-28 00:36:00 1296 1 2 5092761672035390000000000000 2018-11-28 00:37:...
<p>You can use the <code>shift</code> and <code>cumsum</code> trick before <code>groupby</code>:</p> <pre><code>v = df.EquipID.ne(df.EquipID.shift()) v.groupby(v.cumsum()).cumcount() + 1 Index 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 1 11 2 12 1 13 1 14 1 15 1 16 ...
python|pandas|dataframe|group-by|pandas-groupby
2
352,623
53,928,871
Optical Character Recognition Multiple Line Detection
<p>I'm building an OCR. For that I'm using <code>CNN</code>, <code>RNN</code> and <code>CTC</code> Loss Function. My input layer gets image and output layer predicts what's written on that image. Labels are converted into integer.</p> <pre><code>['A', 'B', 'C'] -&gt; A = 0, B = 1, C = 2 </code></pre> <p>If the image ...
<p>You want to <strong>recognize text of a document containing multiple lines</strong>. There are <strong>two ways</strong> to achieve this:</p> <ol> <li><p><strong>Segment</strong> the document into <strong>lines</strong> as a <strong>pre-processing</strong> step, then feed each segmented line separately into your ne...
python|tensorflow|keras|ocr
7
352,624
54,085,258
Change column wise data using pandas
<p>I have Dataframe, in which i need to change values for one column at a time so that it does not change same values in other columns</p> <p>Data Set:</p> <pre><code>Col-a Col-b Col-c val1 abc val1 val2 bca bca bca zzs val2 val2 val3 xyz zzs </code></pre> <p>Code:</p>...
<p>Assuming the df looks like:</p> <p>df:</p> <pre><code> Col-a Col-b Col-c 0 val1 abc val1 1 val2 bca bca 2 NaN bca zzs 3 val2 NaN val2 4 val3 xyz zzs </code></pre> <p>Using <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.factorize.htm...
python|pandas
1
352,625
54,062,515
How can I select particular Columns in DataFrame based on conditions
<p>I have an <a href="https://www.kaggle.com/manasgarg/ipl" rel="nofollow noreferrer">IPL Data Set</a> called <code>matches.csv</code> which I am fetching from Kaggle, from where I am trying to find out the place where the maximum number of matches were played.</p> <p>The below code is giving me the correct value for ...
<p><strong>Find out the place where the maximum number of matches were played</strong></p> <pre><code>&gt;&gt;matches['venue'].value_counts().head(1) M Chinnaswamy Stadium 66 </code></pre> <p>Note that <code>value_counts</code> already sorts the data in a descending manner, so the first record is always the maxim...
python|pandas|numpy
2
352,626
53,867,894
Comparing values from column in date frame to column values from the other data frame in pandas
<p>I have two data frames, and I want to insert rows from data frame df2 to df1 if a value from Column "A" of df1 is contained in a cell of column "B" in df2. If it is the case, then I want to insert rows below matched value from column "A" in df1. The rows that need to be inserted are extracted from df2 based on colum...
<p>Solution working if first row with <code>Matches</code> have also value <code>test</code> in <code>Keyword</code> column:</p> <pre><code>#groups for get cumulative sum with comparing test value and not missing values df2['g1'] = df2['Keyword'].eq('test').cumsum() df2['g2'] = df2['Matches'].notna().cumsum() #get onl...
python|pandas|dataframe|contains
1
352,627
38,495,699
pandas merging two multi-level series
<p>I have two multi-level <code>Series</code> and would like to merge them according to both index. The first <code>Series</code> looks like this:</p> <pre><code> # of restaurants BORO CUISINE BRONX American 425 ...
<p>Setup:</p> <pre><code>s1 = pd.Series({('BRONX', 'American'): 425, ('BROOKLYN', 'Chinese'): 750, ('BROOKLYN', 'Cafe/Coffee/Tea'): 350, ('BRONX', 'Pizza'): 206, ('BROOKLYN', 'American'): 1254, ('BRONX', 'Chinese'): 330}) s2 = pd.Series({('BRONX', 'Caribbean'): 320, ('BRONX', 'American'): 2425, ('BROOKLYN', 'Chinese')...
pandas|dataframe|merge|series|multi-index
2
352,628
38,503,921
Generate variable length data with Tensorflow ops
<p>I am trying to learn a classifier on audio files. I read my WAV files and convert them to a sequence of spectrogram images for training in a custom Python function. The function is called with <code>tf.py_func</code> and returns an array of images with the same shape. In other words the image shape is well defined, ...
<p>You can use variable size Tensor as input and <code>enqueue_many</code> to treat this tensor as a variable size input batch.</p> <p>Below is an example of <code>py_func</code> generating variable size batches and batch with <code>enqueue_many</code> converting it to constant size batches. <img src="https://i.stack....
tensorflow
7
352,629
38,406,324
Ordinary Least Squares Regression for multiple columns in Pandas Dataframe
<p>I'm trying to find a way to iterate code for a linear regression over many many columns, upwards of Z3. Here is a snippet of the dataframe called df1</p> <pre><code> Time A1 A2 A3 B1 B2 B3 1 1.00 6.64 6.82 6.79 6.70 6.95 7.02 2 2.00 6.70 6.86 6.92 NaN...
<h3>One liner (or three)</h3> <pre><code>time = df[['Time']] pd.DataFrame(np.linalg.pinv(time.T.dot(time)).dot(time.T).dot(df.fillna(0)), ['Slope'], df.columns) </code></pre> <p><a href="https://i.stack.imgur.com/tUSg7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tUSg7.png" alt="enter image ...
python|numpy|pandas|scipy|scikit-learn
9
352,630
38,354,537
Tensorflow: Read jpg's in various directories
<p>I want to read all jpg's stored in subdirectories within another directory ('all_image_dir'). The subdirectory names are like '001', '002', etc. </p> <p>It's not a problem to read all jpg's in a certain directory, for example 'all_image_dir/001, using: </p> <pre><code>filename_queue = tf.train.string_input_produc...
<p>The <code>pattern</code> pattern parameter to <code>tf.train.match_filenames_once</code> is rather limited. For your particular case, suppose your subdirectories are <code>001</code>, <code>002</code>, ... <code>020</code>. You can do the following to achieve the same effect as <code>'all_image_dir/*/*.JPG'</code> :...
tensorflow
4
352,631
38,190,472
Pandas: Find first occurrence - on daily basis in a timeseries
<p>I'm struggling with this so any input appreciated. I want to iterate over the values in a dataframe column and return the first instance when a value is seen every day. Groupby looked to be a good option for this but when using <code>df.groupby(grouper).first()</code> with <code>grouper</code> set at daily the fo...
<p>Try this, using this data: </p> <pre><code>rng = pd.DataFrame( {'test_1': [None, None,None, None, 1,1, 1 , None, None, None,1 , None, None, None,]}, index = pd.date_range('4/2/2014', periods=14, freq='BH')) rng test_1 2014-04-02 09:00:00 NaN 2014-04-02 10:00:00 NaN 2014-04-02 11:00:00 ...
python|pandas|time-series
1
352,632
38,366,752
Bazel builds cause issues when I install TensorFlow using pip
<p>So the documentation mentions that it is better to install from source, then build a pip package. Why is this recommended over doing a direct pip install using the wheel file provided on the downloads page? <a href="https://www.tensorflow.org/versions/r0.9/get_started/os_setup.html#pip-installation" rel="nofollow">h...
<p>Installing from pip is supported, can you provide more details on your os and the specific errors you saw?</p>
tensorflow|build|bazel
0
352,633
38,336,501
Error while reading a csv file in python using pandas
<pre><code>products = pd.read_csv('C:\amazon_baby.csv') </code></pre> <blockquote> <p>Traceback (most recent call last):</p> <p>File "", line 1, in products = pd.read_csv('C:\amazon_baby.csv')</p> <p>File "C:\Users\kvsn\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 562, in parser_f ...
<p>try:</p> <p><code>products = pd.read_csv(r'C:\amazon_baby.csv')</code></p> <p>or</p> <p><code>products = pd.read_csv('C:\\amazon_baby.csv')</code></p> <p>'\' is the escape character and has to be read as either a raw string or by preceding it with another escape character. See <a href="https://docs.python.org/2....
python|pandas
1
352,634
38,245,512
Find point along line a specified distance from a polygon
<p>Given a 2-D closed polygon defined by a series of points and an infinite line, I would like to find points on that line a specified distance from the polygon. The polygon is known to be closed, not intersecting, and not containing 3 consecutive collinear points. In general there are many possible points along the ...
<p>If number of polygon edges is reasonable, you can use simple linear algorithm.</p> <p>Let's parametric equation for line is</p> <pre><code>L(u) = L0 + u * dL </code></pre> <p>where L0 is some base point, dL is direction vector, u is parameter</p> <p>and parametric equation for i-th segment is</p> <pre><code>P =...
python|numpy|geometry
0
352,635
38,188,420
Pandas: Join dataframes on selected columns
<p>I have two data frames as following </p> <pre><code> Data Set A ID type msg 1 High Lets do 2 Low whats it 3 Medium thats it Data Set B ID Accounttype 2 Facebook 3 Linkedin </code></pre> <p>How can I get an updated table with help of join in pandas, it should look like an </p> <pre><co...
<p>Try this:</p> <pre><code>df4: # ID type msg # 0 1 High Letsdo # 1 2 Low whatsit # 2 3 Medium thatsit </code></pre> <pre><code>df3: # ID Accounttype xxx # 0 2 Facebook 24 # 1 3 Linkedin 44 </code></pre> <pre><code>df4.merge(df3[['ID', 'Accounttype...
python|pandas|join|merge
8
352,636
66,323,149
Load Text File into DataFrame with Specific Format
<p>I am trying to load a text file with the following format:</p> <pre><code>PR Maybe IMPACT TASK FIST 12 SA 1450 1 12 RE 0 </code></pre> <p>I tried something like this but the formatting of the text file is weird.</p> <pre><code>df = pd.read_csv(r&quot;fi...
<p>Use <code>pd.read_fwf</code> instead if you are using a fixed-width file. <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_fwf.html" rel="nofollow noreferrer">Reference</a></p>
python|pandas
0
352,637
66,093,111
Looking Alternative other than Loops
<p>I have a data frame:</p> <pre><code>df= year_month data (1970,1) 12 (1970,1) 15 (1970,1) 3 (1970,2) 32 (1970,2) 28 </code></pre> <p>I want to rank the data per each year_month and divide each rank by the number of data in each group plus 1, where the result is:</p> <pre><code>result= year_mont...
<p>Four step process</p> <ol> <li>get the ranks using <code>groupby()</code> then <code>rank()</code></li> <li>get the max ranks within a <code>groupby()</code> using <code>translate()</code> to get a series</li> <li>calculate <em>data</em> as per requirement</li> <li>cleanup workings ...</li> </ol> <pre><code>df = pd....
pandas|performance|dataframe|loops
1
352,638
66,057,294
How can I replicate rolling.sum() in Pandas V17
<p>I am trying to calculate the rolling 3 days sum for the data below:</p> <pre><code>Date Qty 01/01/2019 4.15 02/01/2019 12.39 03/01/2019 14.15 04/01/2019 12.15 05/01/2019 3.26 06/01/2019 6.23 07/01/2019 15.89 08/01/2019 5.55 09/01/2019 12.49 10/01/2019 9.4 11/01/2019 9.11 12/01/2019 9.18 13/01/2019...
<p>For a small window, you can <code>shift</code>:</p> <pre><code>df['rolling_3d'] = np.sum([df['Qty'].shift(i) for i in range(3)], axis=0) </code></pre>
python|pandas|rolling-computation
2
352,639
66,099,060
probability of a row in one dataframe occurring in another dataframe
<p>I have 2 dataframes</p> <p>df 1 (films sent to users):</p> <pre><code> UserID Film 1 3 2 41 2 23 2 53 3 34 5 6 </code></pre> <p>df 2 (films watched by users - subset of df 1):</p> <pre><code> UserID Film 1 3 2 41 5 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>DataFrame.merge</code></a> with <code>indicator</code> parameter and then check if <code>both</code> values with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pand...
python|pandas|dataframe|data-wrangling
3
352,640
66,020,680
replace elements of prediction in custom loss function for tensor flow
<p>I am using a classification model, but would like to write my custom loss function which considers the value as 1 for two of the three categories only if the softmax value is greater than 0.75. The value of the third category is set to 1 if both of the other categories are zero.</p> <pre><code>def custom_loss(y_true...
<p>y_pred = y_pred.numpy()</p> <p>does the trick.</p>
tensorflow2.0|tf.keras
0
352,641
66,049,424
Pandas Replace all values of column with the mean of only one group
<p>I have a Pandas dataframe that looks something like this:</p> <pre class="lang-py prettyprint-override"><code> solutionType attribute 0 fixed 1 1 float 2 2 other 42 3 fixed 55 4 fixed 1010 5 float 2021 </code></pre> <p>I want to rep...
<p>You can do something like this and interchange it whatever value you want to replace it with :</p> <pre><code>df.groupby('solutionType').mean().T['fixed'] </code></pre>
python-3.x|pandas|dataframe
1
352,642
65,952,814
Pandas transform series values until condition is met without for loop
<p>I asked this question on <a href="https://codereview.stackexchange.com/questions/255319/pandas-transform-series-values-until-condition-is-met-without-for-loop">Code Review</a> first, but didn't get any response so I am posting it here.</p> <p>I have a pandas Series contain 0s and 1s. Now I want to convert all the 0s...
<p>You can shift values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.shift.html" rel="nofollow noreferrer"><code>Series.shift</code></a> with cumulative sum and compare <code>0</code> and pass to <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofo...
python-3.x|pandas
2
352,643
66,066,179
How to use adaptive loss function from google-research in Keras?
<p>Similar to <a href="https://stackoverflow.com/questions/56758060/how-to-implement-an-adaptive-loss-in-keras">this</a> question, I am having some trouble using the adaptive loss function from <a href="https://github.com/google-research/google-research/blob/master/robust_loss/adaptive.py" rel="nofollow noreferrer">rob...
<p>The <code>tf.Variable</code> of the loss function are not optimized by the call to <code>fit</code> because they don't belong to the <code>training_variables</code> collection of the model.</p> <p>A quick and dirty way is to add the latent alpha and latent scale <code>tf.Variable</code> to the keras model by using ...
python|tensorflow|keras|deep-learning|neural-network
1
352,644
66,014,344
Update a DataFrame with duplicate destination
<p>I would like to update a dataframe with another one but with multiple &quot;destination&quot;. Here is an example</p> <pre><code>df1 = pd.DataFrame({'name':['A', 'B', 'C', 'A'], 'category':['X', 'X', 'Y', 'Y'], 'value1':[None, 1, None, None], 'value2':[None, 10, None, None]}) name category value1 value2 0 A ...
<p>You can use <code>fillna</code> after mapping the column <code>A</code> in <code>df1</code> with the corresponding values from <code>df2</code>:</p> <pre><code>mapping = df2.set_index('name')['value'] df1['value'] = df1['value'].fillna(df1['name'].map(mapping)) </code></pre> <p>If you want to <code>map</code> multip...
python|pandas|dataframe
4
352,645
65,972,094
Is there any benefit to assigning a view to same name vs to a new name in python?
<p>Suppose I am creating a new view on a python object, which is the only view I need going forward. Is there any difference between assigning it to a new name vs overwriting the original name? If yes, which is preferable?</p> <p>For example, suppose I have some numpy array <code>arr</code>, and only need some reshaped...
<p>This is pretty opinion based, but I disagree with the existing answer.</p> <p>I like to retain old names and create new, long, descriptive names for each step of a transformation. It's sometimes helpful when debugging, and allows you to see intermediate steps of a transformation of data, which I like for my thought ...
python|numpy|object|memory|pep8
2
352,646
66,328,407
Sort pandas list type column values based on another list type column
<p>I have a data frame like this,</p> <pre><code>df col1 col2 col3 A ['p', 'q', 'r'] ['x', 'r', 'p'] B ['x', 'y'] ['y'] C ['t', 'u', 'p'] ['u', 'p', 'x', 't'] D ['a', 'b'] ['x', 'y'] </code></pre> <p>Now I want to sort values(...
<p>One idea is use cutom function with list comprehensions for test membership:</p> <pre><code>def f(x): a = x['col2'] b = x['col3'] yes = [x for x in b if x in a] no = [x for x in a if x not in out] return yes + no df['col2'] = df.apply(f, axis=1) print (df) col1 col2 ...
python|pandas|dataframe
3
352,647
66,239,208
Pandas: create column id based on intersections on rows
<p>I have a pandas DataFrame as follows:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id1</th> <th>id2</th> <th>id3</th> </tr> </thead> <tbody> <tr> <td>a</td> <td>x</td> <td>u</td> </tr> <tr> <td>a</td> <td>y</td> <td>j</td> </tr> <tr> <td>b</td> <td>x</td> <td>t</td> </tr> <tr> <td>c</...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a> for unpivot for possible pass 2 columns to <a href="https://networkx.github.io/documentation/stable/reference/generated/networkx.convert_matrix.from_pandas_edge...
python|pandas
1
352,648
65,933,866
what the advantage of using zip function df['full_name']=zip(df['name'],df['last name'])
<p>i am trying to understand.</p> <p>what the advantage of using zip function</p> <pre><code>df['full_name']=zip(df['name'],df['last name']) </code></pre> <p>instead of</p> <pre><code>df['full_name']=df['name']+ &quot; &quot; + df['last name'] </code></pre>
<p>For tuples by <code>name</code> and <code>last name</code> use first solution (converted to list for avoid zip objects):</p> <pre><code>df['full_name']= list(zip(df['name'],df['last name'])) </code></pre> <p>For joined columns by space is used:</p> <pre><code>df['full_name']=df['name']+ &quot; &quot; + df['last name...
python|pandas|zip
2
352,649
65,913,796
Extract distinct values from Dataframe and insert them into new Dataframe with same column Name
<p>Using python 3.7 , pandas 1.1.3 , Anaconda Jupyter Notebook</p> <p>I am new into python and I have a following dataframe.</p> <p>DF_1</p> <pre><code>Name Date AAA 2000-09-01 BBB 2001-08-01 CCC 2002-07-01 AAA 2005-05-01 </code></pre> <p>I just want to extract distinct values from 'Name' column and create a n...
<p>Try this:</p> <pre><code>df_2 = DF_1[['Name']].drop_duplicates() </code></pre>
python|pandas|dataframe
5
352,650
65,928,382
numpy: How to express a many-to-many relationship?
<p>Say I have the following logical relationships:</p> <pre><code># ANIMALS cat = [hobbes, tigger, garfield] dog = [lassie] frog = [kermit, hypnotoad] # HABITATS tree = [cat, frog] river = [dog, frog, turtle] house = [cat, dog] </code></pre> <p>There will never be duplicates within a set. I want to match them into pai...
<p>If you want selection capabilities like SQL, I'm going to suggest you think about Pandas for handling the data. It can happily store Numpy arrays, but you have very flexible filtering options for slicing the data lots of different ways.</p> <p>For what you're asking, I don't know if you even need to do much more tha...
python|python-3.x|numpy|join
0
352,651
66,304,420
How to Encode Data of Variable Input Length?
<p>I was doing some data science work when I get stuck with this issue, I'm trying to create a model for a supervised task, where both Input and Output are of variable length.</p> <p>Here is an example on how the Input and Output look like:</p> <pre><code>Input[0]: [2.42, 0.43, -5.2, -54.9] Output[0]: ['class1', 'class...
<p>A way to solve this is to:</p> <ol> <li>Find out what is the max length that the variable data can be.</li> <li>Find out what the true length of each training instance is.</li> </ol> <p>From these two things you can create a mask and have your network compute zero gradients for the stuff you want to ignore.</p> <p><...
python|tensorflow|machine-learning|nlp
1
352,652
66,096,409
Pandas dataframe find distinct value count for each group in other columns
<p>I have a <code>Pandas</code> <code>dataframe</code> a sample input of which looks like below:</p> <pre><code>vendor filename language score text Vendor 1 File 1 chinese 0.67717278 text1 Vendor 2 File 1 chinese 0.644506991 text2 Vendor 1 File 2 chinese 0.67717278 text1...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.nunique.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.nunique</code></a> with specify column <code>text</code> for count number of unique values:</p> <pre><code>df_1 = df[df[&quot;score&quot;] &gt; 0....
python|pandas|dataframe
1
352,653
65,970,842
Fastest way to create list of (X,Y) incrementing tuples with step value?
<p>I need a fast way to create a list of tuples representing image pixel coordinates <em>(<strong>X</strong>, <strong>Y</strong>)</em>.</p> <p>Where <strong>X</strong> is from <code>0</code> to <code>size</code> and <strong>Y</strong> is from <code>0</code> to <code>size</code>.</p> <p>A step value of <code>1</code> re...
<blockquote> <p>I need fast way to create a list of tuples representing image pixel coordinates (X, Y).</p> <p>Where X is from 0 to size and Y is from 0 to size</p> </blockquote> <p>A list comprehension with <code>range</code> will work:</p> <pre class="lang-py prettyprint-override"><code>xsize = 10 ysize = 10 coords =...
python|list|numpy|tuples
1
352,654
66,212,601
How to save model/checkpoints after certain epoch, save best only
<pre><code>checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='max',save_frequency=1) </code></pre> <p>basically how to periodically check if the new check val_loss is better and save the checkpoint after every epoch but only after at least 100 epoch?</p> <p>so the model wil...
<p>Tensorflow provides option to save checkpoints based on epoch number.</p> <pre><code># Create a callback that saves the model's weights cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path, save_weights_only=True, ...
python|tensorflow
0
352,655
66,187,918
Tensorflow Js No backend found in registery blazeface
<p>I'm trying to know if there is some face on an image and so I'm using tensorflow JS with blazeface model. But after getting the code an error appear:</p> <pre><code>Error: No backend found in registry. at Engine.getSortedBackends (/home/saren/project/spark/node_modules/@tensorflow/tfjs-core/dist/tf-core.node.js:...
<p>Seems that you can do two things.</p> <p>Install @tensorflow/tfjs-node and use <code>tf: require(&quot;@tensorflow/tfjs-node&quot;),</code> Or you can use <code>this.tf.getBackend();</code> (even with this <code>tf: require(&quot;@tensorflow/tfjs&quot;)</code>)</p>
javascript|node.js|tensorflow|artificial-intelligence|tensorflow.js
0
352,656
66,278,161
Read shapefile from HDFS with geopandas
<p>I have a shapefile on my HDFS and I would like to import it in my Jupyter Notebook with <code>geopandas</code> (version <code>0.8.1</code>).<br /> I tried the standard <a href="https://geopandas.org/reference/geopandas.read_file.html?highlight=read_file#geopandas.read_file" rel="nofollow noreferrer"><code>read_file(...
<p>If someone is still looking for an answer to this question, I managed to find a workaround.</p> <p>First of all, you need a .zip file which contains all the data related to your shapefile (.shp, .shx, .dbf, ...). Then, we use <code>pyarrow</code> to establish a connection to HDFS and <code>fiona</code> to read the z...
python|hadoop|geopandas
1
352,657
66,318,211
TypeError: Cannot perform 'ror_' with a dtyped [float64] array and scalar of type [bool]
<p>I want to iterate through the column <code>df['fyear']</code> and delete any row for which <code>fyear</code> isn't equal to either 2009, 2019, or 2020. But this error comes up:</p> <p><code>TypeError: Cannot perform 'ror_' with a dtyped [float64] array and scalar of type [bool]</code></p> <pre><code>df = pd.DataFra...
<p>Python uses <code>or</code> as infix keyword</p> <pre class="lang-py prettyprint-override"><code>df[&quot;fyear&quot;] != 2009 or df[&quot;fyear&quot;] !=2019 or df[&quot;fyear&quot;] !=2020 </code></pre> <p>Or even better (more pythonic and also readable)</p> <pre class="lang-py prettyprint-override"><code>df[&quot...
python|pandas|dataframe|boolean|iteration
2
352,658
66,007,863
Loading data from generator using tf.data.Dataset.from_generator()
<p>I want to load data for my metric learning model, and the data generating function is the <code>get_data()</code> function</p> <pre><code>def get_data(): def my_generator(): for i in range(10): anchor = list(np.expand_dims(cv2.imread('img1'), axis=0)) positive = list(np.expand_di...
<p>As I thought, the problem was in shapes, this worked for me</p> <pre><code> return tf.data.Dataset.from_generator( my_generator, output_types=(tf.float64, tf.float64, tf.float64), output_shapes=(tf.TensorShape(None), tf.TensorShape((1, 256, 256, 3)), tf.TensorShape((1, 256, 25...
python|tensorflow|deep-learning|generator
0
352,659
66,336,771
Condensing Multiple DataFrame Columns into a Single Indicator Column in Pandas
<p>Let's say I have a DataFrame like the following:</p> <pre><code>import pandas as pd import numpy as np d = {'ID': [1,2,3,4], 'name': ['bob','shelby','jordan','jeff'], 'type1': [1,1,0,0], 'type2':[1,0,1,0], 'type4':[1,0,0,0], 'type5':[0,0,1,0], 'type6':[0,1,0,0], 'type8':[0,0,1,0]...
<p>Using <code>any</code>:</p> <pre><code>df['other'] = df.loc[:, ['type5','type6','type8']].any(axis=1).astype(int) df = df.drop(['type5','type6','type8'], axis=1) </code></pre> <p>result:</p> <pre><code> ID name type1 type2 type4 other 0 1 bob 1 1 1 0 1 2 shelby 1 0 ...
python|pandas|dataframe|group-by
4
352,660
65,931,163
How to add Arrow annotations with an offset to a bokeh plot with a datetime x-axis
<p>I want to draw an arrow or dots when 2 ma cross each other like there will up arrow when short ma cross above long ma etc. but I don't know how to plot when it is datetime. I try to use this code and it just give me errors.</p> <pre><code>#plot short ma and long ma p.line(df['Date'], df['short_ma'], color='red') p.l...
<ul> <li>For an <code>Arrow</code>, <code>x_start</code> and <code>x_end</code> must be a <code>datetime</code> format, not a <code>string</code> or a <code>dataframe</code>. <ul> <li><code>x_start=pd.to_datetime('2010-10-09')</code></li> <li>The coordinates for the arrow may not be passed as a dataframe, they must be ...
python|pandas|bokeh
1
352,661
65,945,549
How to use TensorFlow lite on a raspberry pi 4 without keras?
<p>Basically I want to convert this code snippet to code that opens a tflite model and does not use keras. I can not install keras on my raspberry pi 4 as it needs Tensorflow 2+.</p> <pre><code>model = keras.models.load_model( saved_model_path ) image_url = tf.keras.utils.get_file('Court', origin='https://squashvideo...
<p>The error is in the way you are feeding data to the tflite Interpreter here:</p> <pre><code>input_tensor = interpreter.tensor(tensor_index)()[0] input_tensor[:, :] = image </code></pre> <p>The Image.open function return an Image object. You need to convert it into binary data before feeding it to a tensor. An you sh...
tensorflow|tensorflow-lite|raspberry-pi4
1
352,662
66,218,328
mnist CNN ValueError expected min_ndim=4, found ndim=3. Full shape received: [32, 28, 28]
<p>I define the model definition as follows.</p> <pre><code>tf.keras.datasets.mnist model = keras.models.Sequential([ tf.keras.layers.Conv2D(28, (3,3), activation='relu', input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D((2, 2)), tf.keras.layers.Conv2D(56, (3,3), activation='relu'), tf.ker...
<p>By seeing your error, I think you probably didn't add the batch axis in the training set i.e [<code>batch, w, h, channel</code>]. Here is the working code</p> <p><strong>DataSet</strong></p> <pre><code>import tensorflow as tf import numpy as np from sklearn.model_selection import train_test_split (x_train, y_trai...
python|tensorflow|machine-learning|keras|tensorflow2.0
7
352,663
66,309,358
How to find the greatest value in a column when x is in another column?
<p>I have a dataframe with a lot of songs and contains columns such as 'title', 'duration' 'artists', etc. I want to find the song where 'Adele' is in 'artist' with the longest 'duration'. The thing I am specifically struggling with is separating the 'artist', as these are separated with comma separated values. So I ne...
<p>It's tough to tell without seeing your dataframe, but if <code>Adele</code> is a string in one column and you want the max of another, you can try:</p> <pre><code>df[df['Artist'].str.contains('Adele')]['duration'].max() </code></pre>
python|pandas|dataframe
1
352,664
66,258,410
Read local psql table in pandas
<p>Currently I was given a table with psql format and would like to load its content in a pandas dataframe. The file looks like this (this is a sample of the real file which has hundreds of rows):</p> <pre><code> ,----------------------------------------------------------------. | ...
<p>It's a case of being systematic. There are cases of pipe delimited and space delimited</p> <ul> <li><code>read_sql_table()</code> is not suitable, it connects to a database</li> <li>`read_table() as first pass, skipping header rows and using pipe as delimited</li> <li>cleanup the columns <ul> <li>strip leading/tra...
python|pandas|dataframe|psql
1
352,665
66,039,432
How to explode mutiple colulms using pandas dataframe
<p>df=spark.sql(&quot;select key, name, subjects from table&quot;)</p> <p>df in from above select statement :</p> <pre><code>key name subjects 12 x,y,z 1,2,3 20 a,b 8,7 </code></pre> <p>df out :</p> <pre><code>12 x 1 12 y 2 12 z 3 20 a 8 20 b 7 </code></pre> <p>tried converting to list , explode. Still...
<p>One way using <code>pandas.DataFrame.apply</code>:</p> <pre><code># df[&quot;name&quot;] = df[&quot;name&quot;].str.split(&quot;,&quot;) # df[&quot;subjects&quot;] = df[&quot;subjects&quot;].str.split(&quot;,&quot;) # If not already split new_df = df.apply(pd.Series.explode) print(new_df) </code></pre> <p>Output:</...
python|pandas|dataframe|explode
2
352,666
66,052,253
Fast elementwise multiplication of a tensor by a list of vectors
<p>I have a tensor and I want to multiply that tensor into a list of vectors. An example of minimal code is below.</p> <pre><code>tensor=np.arange(4*5*6).reshape(4,5,6) vectorList=[] vectorList.append(np.array([0,1,2,3,4,5])) vectorList.append(np.array([6,7,8,9,10,11])) vectorList.append(np.array([12,13,14,15,16,17]))...
<p>Your 3d array (renamed from <code>tensor</code>):</p> <pre><code>In [448]: arr.shape Out[448]: (4, 5, 6) </code></pre> <p><code>vectosList</code> as array is 2d:</p> <pre><code>In [449]: np.array(vectorList).shape Out[449]: (3, 6) </code></pre> <p>And your results, as array, is 4d:</p> <pre><code>In [450]: np.array(...
python|numpy|tensorflow
2
352,667
66,320,475
Explode the list values in dataframe columns
<p>I am having a dataframe with following values:</p> <pre><code>sentence_id words labels 3822445 ['a', 'b', 'c', ''] ['B-PER', 'I-PER', 'I-PER', 'I-PER'] 3822446 ['d', 'e', ''] ['B-PER', 'I-PER', 'I-PER'] 3822447 ['f', 'g', 'h'] ['B-PER', 'I-PER', 'I-PER'] </c...
<p>If you want a simple one-liner you can use <code>explode</code> with <code>pandas&gt;=0.25.0</code></p> <pre><code>df.explode('words').assign(labels=df['labels'].explode()) </code></pre>
python|pandas|dataframe
3
352,668
66,074,684
"RuntimeError: expected scalar type Double but found Float" in Pytorch CNN training
<p>I just begin to learn Pytorch and create my first CNN. The dataset contains 3360 RGB images and I converted them to a <code>[3360, 3, 224, 224]</code> tensor. The data and label are in the <code>dataset(torch.utils.data.TensorDataset)</code>. Below is the training code.</p> <pre class="lang-py prettyprint-override">...
<p>that error is actually refering to the weights of the conv layer which are in <code>float32</code> by default when the matrix multiplication is called. Since your input is <code>double</code>(<code>float64</code> in pytorch) while the weights in conv are <code>float</code><br /> So the solution in your case is :</p...
python|deep-learning|pytorch|tensor|scalar
18
352,669
65,998,140
How to multiply specific column from dataframe with one specific column in same dataframe?
<p>I have a dataframe where i need to create new column based on the multiplication of other column with specific column</p> <p>Here is how my data frame looks.</p> <p>df:</p> <pre><code>Brand Price S_Value S_Factor A 10 2 2 B 20 4 1 C 30...
<p>Firstly, to get the columns which you have to multiply, you can use list comprehension and string function <code>startswith</code>. And then just loop over the columns and create new columns by muptiplying with <code>Price</code></p> <pre><code>multiply_cols = [col for col in df.columns if col.startswith('S_')] for ...
python|pandas|multiple-columns|calculated-columns
2
352,670
65,999,680
Python match a column name based on a column value in another dataframe
<p>Apologies if this is a duplicate of some sort, I looked at 20 different questions, but none of them helped me. If someone can point me to a question that answers this, I'll happily delete my question.</p> <p>I have two dataframes, the first is called df_full long list of various columns, one of which is called 'Indu...
<p>It looks like you can do a map:</p> <pre><code>df_full['quantile_05'] = df_full['Industry'].map(df_industry['profit_sales'].unstack()[0.5]) </code></pre> <p>Output:</p> <pre><code> Industry quantile_05 INDEX 0 Service 0.003375 1 Service 0.0033...
python|pandas|match
1
352,671
66,224,414
Finding the rows where a column value drops to zero in Python DataFrame
<p>I have the following sample data-set where I need to find the rows where overdue_amount drops to zero while loan_balance column increases by the same amount per loan_id. For instance, the rows 2-&gt; 3, 7 -&gt; 8, 11 -&gt; 12</p> <pre><code>report_date customer_id loan_id Overdue_Amount Loan_Balance Flag_1 ...
<p>You can solve this by calculating the differential of the columns <code>Overdue_Amount</code> and <code>Loan_Balance</code> and then selecting the rows where the difference in one column equals the negative of the difference in the other. Then you extract the row indices.</p> <p>Assuming your DataFrame is called <co...
python|python-3.x|pandas|dataframe
1
352,672
66,107,504
Casting Boolean Values to data frame Pandas
<p>How to cast boolean values to the given data frame.</p> <pre><code>df = pandas.DataFrame({'A': [0, 1, &quot;Yes&quot;, 3, &quot;NO&quot;], 'B': [5, &quot;true&quot;, False, 8, 9], 'C': ['tRue', 'nO', 'false', 'd', 'e']}) print (df) </code></pre> <p>I want to pass below fuction t...
<p>You should cast to str before comparison and get rid of the int in the tuple:</p> <pre><code>def str2bool(v): if str(v).lower() in ('yes', 'true', '1'): return True if str(v).lower() in ('no', 'false', '0'): return False return v </code></pre> <hr /> <pre><code>print(df.applymap(str2boo...
python|pandas|numpy
2
352,673
66,050,530
Is there a way to add more than 2 series to a chart using xlsxwriter?
<p>So my issue is that I have 3 series to plot on the same graph using xlsxwriter, however when I use the combine function listed here (<a href="https://xlsxwriter.readthedocs.io/example_chart_combined.html" rel="nofollow noreferrer">https://xlsxwriter.readthedocs.io/example_chart_combined.html</a>) the second combine ...
<p>I've done this with two different chart types: Say I have a column chart and I want to add a line chart also:</p> <pre><code>column_chart = workbook.add_chart({'type': 'column'}) column_chart.add_series({ 'name': f&quot;={variable}!A4&quot;, 'categories': f&quot;={variable}!B3:M3&quot;, 'values': f&quot;...
python|excel|pandas|xlsxwriter
0
352,674
66,099,456
replicate the seq function in R to python
<p>I am trying replicate R's seq function in Python</p> <p>For example in R:</p> <pre><code>sequence = seq(from = 1, to = 3, by = 1) output = 1 2 3 </code></pre> <p>And in Python I find the linspace commmand:</p> <pre><code>np.linspace(start=1, stop=3, num=1) output = array([1.]) </code></pre> <p>But it specifies the n...
<p>Note that <code>num</code> is not equivalent to <code>by</code>.</p> <blockquote> <p>num: <code>int</code>, optional</p> <p>Number of samples to generate. Default is 50. Must be non-negative.</p> </blockquote> <hr /> <p>Try with</p> <pre><code>&gt;&gt;&gt; np.linspace(start=1, stop=3, num=3) array([1., 2., 3.]) </co...
python|r|numpy
1
352,675
66,086,579
Long prediction time when using converter.optimization in a VGG16 model and Tensorflow lite
<p>I wrote a model that is based on VGG16 and I just only added two additional convolution layers. The output is an array of size 16x16x1 which is just the result of simple binary classification. I used TensorFlow-lite and the code is based on the documentation available. The problem is that when I'm making a predictio...
<p>First your GPU is not calculating this prediction. You have to use cuda to tranfer data to the gpu, but that is not neccesary here.</p> <ol> <li><p><strong>Reshape</strong> your images to (256,256) or even lower, with a size of (512, 512) the image is very times big for the VGG input. This is why your computations a...
python|tensorflow|machine-learning|tensorflow-lite
0
352,676
66,057,829
How to find indices for sequential NaNs at the start and end of a1D NumPy array?
<p>I have a 1D NumPy array that contains both floating point numbers and NaNs. There will almost always be multiple sequential NaNs at the start and end of the array with some NaNs throughout the middle of the array. There is no way to predict in advance the location or number of NaNs present in the array.</p> <p>What ...
<p>Start with a mask of all the NaNs, using <a href="https://numpy.org/doc/stable/reference/generated/numpy.isnan.html" rel="nofollow noreferrer"><code>np.isnan</code></a>:</p> <pre><code>mask = np.isnan(data) </code></pre> <p>Now notice that <a href="https://numpy.org/doc/stable/reference/generated/numpy.argmin.html" ...
python|numpy
1
352,677
66,095,214
Assign values in a dataframe column based on another column
<p>I have a DF that looks like this.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Index</th> <th>Strike</th> </tr> </thead> <tbody> <tr> <td>190</td> <td>92</td> </tr> <tr> <td>192</td> <td>93</td> </tr> <tr> <td>194</td> <td>96</td> </tr> <tr> <td>196</td> <td>98</td> </tr> </tbody> </t...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.rolling.html" rel="nofollow noreferrer"><code>pandas.Series.rolling</code></a>:</p> <pre><code>&gt;&gt;&gt; df.Strike.rolling(3, 2, True).apply(lambda x: x.iloc[-1] - x.iloc[0]) 0 1.0 1 4.0 2 5.0 3 2.0 Name: Str...
python|pandas|dataframe
0
352,678
65,991,271
Repeated Measures ANOVA in Pandas, dependent variable values in different Columns
<p>I am quiet new to Data-Science so maybe this will be quiet easy for more advanced coders. I want to do a repeated measures ANOVA based on pre &amp; post measurements of a test in different groups (Experimental Group vs. Control Group). Every subject only participated in one group.</p> <p>In my Pandas - df I have the...
<p>Actually, what I looked for is:</p> <pre><code>sample_df.melt(id_vars=['Subject ID', &quot;Condition&quot;]) </code></pre> <p>This results in the dataframe with a column specifying which measurement point the value is referring to.</p>
pandas|anova
0
352,679
65,948,820
Display Values either on Y-axis or on top of each bar in Python
<p>this is my code with the output:</p> <pre><code>plt.figure(figsize = (7,4)) df1.groupby([&quot;Area&quot;])[&quot;Crop_Value(hg/ha)&quot;].sum().sort_values(ascending = False).nlargest(5).plot(kind = &quot;bar&quot;) plt.title(&quot;Top 5 Countries with most crop production&quot;) plt.show() </code></pre> <p><a href...
<p>You need to use a different formatter than the standard <a href="https://matplotlib.org/api/ticker_api.html#matplotlib.ticker.ScalarFormatter" rel="nofollow noreferrer"><code>ScalarFormatter</code></a>, e.g. a <a href="https://matplotlib.org/api/ticker_api.html#matplotlib.ticker.FormatStrFormatter" rel="nofollow nor...
python|pandas|matplotlib|seaborn|data-analysis
1
352,680
66,109,120
can I get two values at time in a comprehension list?
<p>Can I have a list getting <code>[y, z]</code> at the same time with a comprehension list like this?</p> <p><code>default_list = [y,z for x,y,z in df_acc[['acc_number', 'password', 'server']].values if x == default_acc]</code></p> <p>The above code gives me a syntax error. What should be the correct one?</p>
<p>You can, but you will need nested <code>for</code>:</p> <pre><code>&gt;&gt;&gt; default_list = [elem for x,y,z in df_acc[['acc_number', 'password', 'server']].values for elem in (x, y) if x == default_acc] </code></pre> <p>But if it is a DataFrame, then it would be more efficient to do:</p> ...
python|pandas
2
352,681
66,249,631
How to parallelize classification with Zero Shot Classification by Huggingface?
<p>I have around 70 categories (it can be 20 or 30 also) and I want to be able to parallelize the process using ray but I get an error:</p> <pre><code>import pandas as pd import swifter import json import ray from transformers import pipeline classifier = pipeline(&quot;zero-shot-classification&quot;) labels = [&quot...
<p>This error is happening because of sending large objects to redis. <code>merged_df</code> is a large dataframe and since you are calling <code>get_meal_category</code> 10 times, Ray will attempt to serialize <code>merged_df</code> 10 times. Instead if you put <code>merged_df</code> into the Ray object store just onc...
python-3.x|redis|classification|huggingface-transformers|ray
1
352,682
66,141,151
check if a tensor included in bigger tensor in pytorch
<p>how to check for example if:</p> <p>torch.tensor([1, 3]) belongs to torch.tensor([3, 1], [1, 1], [3, 1])</p> <p>a in b methods compare element-wise and thus here not correct</p> <p>what I want to compute is whether the whole tensor [1, 3] is in the bigger one</p> <p>thanks</p>
<p>we illustreate the answer with the following example:</p> <pre><code>a = torch.tensor([[4,5],[2,3], [5,3]]) b = torch.tensor([[1,2], [2,3],[3,4],[7,7],[3,5]]) result = [] for i in a: try: # to avoid error for the case of empty tensors result.append(max(i.numpy()[1] == b.T.numpy()[1,i.numpy()[0] == b.T.n...
pytorch
0
352,683
65,966,050
How to plot a bar-plot with only one bar colored?
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>name</th> <th>grade</th> </tr> </thead> <tbody> <tr> <td>chandler</td> <td>A</td> </tr> <tr> <td>joey</td> <td>B</td> </tr> <tr> <td>phoebe</td> <td>B</td> </tr> <tr> <td>monica</td> <td>C</td> </tr> <tr> <td>ross</td> <td>A</td> </tr> <tr> <td>ra...
<p>If I understand correctly, you want something like this:</p> <pre><code>gb = data.groupby('grade').apply(len) for student, grade in class2: fig, ax = plt.subplots() colors = ['red' if a == grade else 'grey' for a in gb.index.values ] gb.plot(kind='bar', color = colors, ax=ax) plt.show() <...
python|pandas|matplotlib|seaborn
3
352,684
65,984,259
Get rid of all commas from each cell of a pandas dataframe
<p>Say I have a dataframe as follows:</p> <pre><code>d = {'col1': ['hello','nice to meet you', 'i like pudding, apples, bananas' ], 'col2': ['good','nice,cool','awesome']} df = pd.DataFrame(data=d) </code></pre> <p>Whereever there is a comma in a cell of the data, I would like to subset the string to become everything...
<p>You need to split each cell by comma, then keep the first string.</p> <pre><code>df = df.applymap(lambda x: x.split(',')[0]) </code></pre>
python|pandas|dataframe|substring
2
352,685
66,202,472
Pandas MultiIndex Dataframe Groupby Rolling Mean
<p>I would like to calculate Rolling Mean of dataframe groupby second level (Key2 in following code sample).</p> <pre><code>import pandas as pd d = {'Key1':[1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6], 'Key2':[2,7,8,5,3,2,7,5,8,7,2,9,8,3,9,2,7,9],'Value':[1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3]} df = pd.DataFrame(d) df = df.set_...
<p>Use lambda function for avoid lost <code>MultiIndex</code>, so assign working well:</p> <pre><code>df['MA'] = df.groupby('Key2')['Value'].apply(lambda x: x.rolling(window=3).mean()) print(df) Value MA Key1 Key2 1 2 1 NaN 7 2 NaN 8 3 ...
python|pandas|dataframe
2
352,686
66,055,838
My data has no nan but I keep getting the finite error
<p><strong>Context</strong></p> <p>I am trying to normalise my data to run a ML model. I am using np.log on my data</p> <pre><code>plt.hist(np.log(Portfolio_rtns['Aveva Returns'])) </code></pre> <p>I also tried this way:</p> <pre><code>log_Aveva = np.log(Portfolio_rtns['Aveva Returns']) log_Aveva.hist(); </code></pre> ...
<p>So having perused around Coursera, I found that using <code>log1p</code> adds 1 to all the zero numbers in the entirety of the data. Also gets rid of the negative. So the solution is:</p> <pre><code>plt.hist(np.log1p(Portfolio_rtns['Aveva Returns'])); </code></pre> <p>or</p> <ol> <li><code>data.describe()</code> #'d...
python|numpy
0
352,687
65,921,244
Pytorch already installed using Conda but fails when called
<p>I am trying to install <code>pytorch</code> for using BERT but when following the installation instructions found here: <a href="https://pytorch.org/get-started/locally/" rel="nofollow noreferrer">https://pytorch.org/get-started/locally/</a> I am getting an error.</p> <p>When I try and initalise the BERT model I get...
<p>I had the same issue (same error msg), and after using conda list | grep torch I also found it is there. What worked for me is that I restarted the jupyter notebook kernel and the error is gone.</p>
deep-learning|pytorch|conda
2
352,688
52,600,729
How to use random number in user defined tensorflow op?
<p>How to use random number in user defined tensorflow op?</p> <p>I am writing a op in cpp which need random number in the Compute function.</p> <p>but It seems I should not use cpp random library directly, since that cannot control by <code>tf.set_random_seed</code>.</p> <p>My current code is something like the fol...
<p>The core of all random number generation in TensorFlow is <a href="https://github.com/tensorflow/tensorflow/blob/v1.11.0/tensorflow/core/lib/random/philox_random.h" rel="nofollow noreferrer"><code>PhiloxRandom</code></a>, generally accessed through its wrapper <a href="https://github.com/tensorflow/tensorflow/blob/v...
c++|tensorflow
4
352,689
52,457,656
Using conditional if/else logic with pandas dataframe columns
<p>My dataframe called <code>pw2</code> looks something like this, where I have two columns, pw1 and pw2, which are probability of wins. I'd like to perform some conditional logic to create another column called <code>WINNER</code> based off <code>pw1</code> and <code>pw2</code>.</p> <pre><code>+----------------------...
<p>Do not use <code>apply</code>, which is very slow. Use <code>np.where</code></p> <pre><code>pw2 = df.pw2.fillna(-np.inf) df['winner'] = np.where(df.pw1 &gt; pw2, df.Name1, df.Name2) </code></pre> <p>Once <code>NaN</code>s always lose, can just <code>fillna()</code> it with <code>-np.inf</code> to yield same logic....
python|pandas|dataframe|if-statement
7
352,690
52,462,568
Python Pandas CSV Loop
<p>I have two csv files: androiddata.csv and iphonedata.csv</p> <p>I have to do the following:</p> <p><strong>a) Compute the average download speed(download_kbps) for android devices in United States(server_country).</strong></p> <p><strong>b) Compute the average download speed(download_kbps) for iphones in Taiwan(...
<p>You can make use of Pandas loc to fetch the row which satisfies a condition :</p> <pre><code>dUS= iPhoneData.loc[iPhoneData["server_country"]=="US","download_kbps"] avg_US = dUS.mean() </code></pre> <p>Similar procedure can be done for Taiwan also.</p>
python|pandas|csv
0
352,691
52,530,665
panda dataframe row wise iteration with referencing previous row values for conditional matching
<p>I have to find out how many times a bike was on overspeed, and in each instances for how long(for simplicity how many kms)</p> <pre><code>df = pd.DataFrame({'bike':['b1']*15, 'km':list(range(1,16)), 'speed':[20,30,38,33,28,39,26,33,35,46,53,27,37,42,20]}) &gt;&gt;&gt; df bike km speed 0 b1 1 20 1 b...
<p>You can use:</p> <pre><code>#boolean mask mask = df['speed'] &gt;= 30 #consecutive groups df['g'] = mask.ne(mask.shift()).cumsum() #get size of each group df['count'] = mask.groupby(df['g']).transform('size') #filter by mask and remove unique rows df = df[mask &amp; (df['count'] &gt; 1)] print (df) bike km spe...
python-3.x|pandas|pandas-groupby
2
352,692
52,789,646
Convert numpy array of colour images to a numpy array of gray scale images
<p>How do I convert an array of two colour images to an <strong>array</strong> of two gray scale images using the <code>to_grayscale</code> (from this <a href="http://www.degeneratestate.org/posts/2016/Oct/23/image-processing-with-numpy/" rel="nofollow noreferrer">site</a>) function below. </p> <p><strong>Important:<...
<p>I'm not sure if this is the fastest or most elegant way to do this in general, based on this <a href="https://stackoverflow.com/questions/35215161/most-efficient-way-to-map-function-over-numpy-array">answer</a></p> <pre><code>images_g = np.array([to_grayscale(images[i]) for i in range(images.shape[0])]) </code></pr...
python|numpy
0
352,693
52,768,419
Failed to load the native TensorFlow runtime. Python 3.6 on Windows 10
<p>I am installing CUDA GPU Tool (version 9.2) for Python 3.6 on Windows 10. I get the following error:</p> <p>Traceback (most recent call last):</p> <p>File "D:\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in from tensorflow.python.pywrap_tensorflow_internal import *</p> ...
<p>Last time I tried CUDA 9.1 few months back I ran into similar issues. I suggest you to install CUDA 9.0 (Reason- Tensorflow pip release may be based on older version of CUDA). You also need to install cuDNN of matching version. You can find the detailed steps guide <a href="https://mlguy.org/2018/06/03/getting-start...
python|tensorflow|nvidia
0
352,694
52,867,302
`IndexError: only integers, slices (`:`), ellipsis (`...`),` Error in python snippet in numpy
<p>I'm running the following python snippet on my data(1500x2 matrix), and trying to implement KMeans algorithm from scratch:-</p> <pre><code>def closestCentroids(arr, centroids): idx = np.zeros(arr.shape[0]); for i in range(0, arr.shape[0]): idx[i] = 0 for j in range(0, centroids.shape[0]): if(np.lina...
<p>By default, <code>numpy.zeros()</code> creates an array of floating point values, so your array <code>idx</code> is a floating point array. You use the values of <code>idx</code> to index the array <code>centroids</code>, and numpy doesn't allow indexing with floating point values, so <code>idx</code> must be an in...
python|numpy
1
352,695
52,876,128
transfer parameters between models in tensorflow slows down training time
<p>I've developed a model that requires me to have two versions of a model, one before the training step and one after. I thought I could simply do this using a tf.assign() method call but it seems that this has massively slowed down the training. </p> <p><a href="https://stackoverflow.com/questions/37966924/why-does-...
<p>Solved. Key is to define tf.assign() so that it is called once and NOT in the training loop. Otherwise if you call it every time then this adds a new node to the graph and it means you have to do additional computation after every iteration. </p> <pre><code>var = tf.trainable_variables() old_hidden = var[0] old_va...
python|tensorflow
0
352,696
52,768,233
Copy value into n previous cells of column in dataframe based on ID and date in Python/R
<p>I'm trying figure out the best way to populate a column in a DataFrame based off of the values in a combination of the remaining columns. </p> <p>I want to create a column v2, such that every time a 1 is encountered in v1, the previous 3 dates and the date at which the 1 was encountered, <strong>for the same ID onl...
<p>With R and data.table:</p> <pre><code>library(data.table) setDT(DF) DF[, v := do.call(pmax, shift(v1, 0:3, type="lead", fill=0L)), by=id] date id v1 v2 v 1: 2017-05-29 5206 0 0 0 2: 2017-05-30 5206 0 0 0 3: 2017-05-31 5206 0 0 0 4: 2017-06-01 5206 0 1 1 5: 2017-06-02 5206 0 1 1 6: 2017...
python|r|pandas|dataframe
2
352,697
52,884,843
Tensorflow SSD300 for Android
<p>I'm a college student who studies machine leraning in Japan. I'm not good at using English, but I will make efforts to convey my situation in English.</p> <p>I'm now trying to use the object detection model for android. I used SSD300_mobile_net for training and then I got .hdf5 file which has model's weights.</p> ...
<p>I sense that it's an issue with your hardware. Generally the hdf5 files are very big and even bigger is the computation that is being done on it. Since your system is giving OOM exception, I believe you are getting this error while loading weights into the model.</p>
android|tensorflow
1
352,698
52,551,895
Does anyone know how can I close LOG(INFO) info in tensorflow meta_optimizer.cc:334
<p>When I do inference by tensorflow c++ library, I always got the info "I tensorflow/core/grappler/optimizers/meta_optimizer.cc:334] Starting optimization for grappler item: tf_graph", does any one know how to close this info?</p> <p>Besides, I have tried <code>export TF_CPP_MIN_VLOG_LEVEL=X</code>, none of number X ...
<p>Forget about it, <code>export TF_CPP_MIN_LOG_LEVEL=4</code> solved this problem... </p>
tensorflow
0
352,699
52,518,204
Using vectorization in Pandas when in each row you need to use the whole data to compare
<p>I have a contact data below.</p> <pre><code> mobile email contact_code index_clone contact_day 0 0972135314 abc@gmail.com 1 0 9/26/2018 1 0972135314 cde@gmail.com 2 1 9/26/2018 2 0943360092 cmt@gmail.com 3 2 9/25/2018 3 ...
<p>You could separately get the minimum contact_code for each group of mobiles, then for each group of emails:</p> <pre><code>min_mobile_cc = df.groupby("mobile").contact_code.transform(np.min) min_email_cc = df.groupby("email").contact_code.transform(np.min) </code></pre> <p>For each row in the data, this stores eit...
python|pandas|performance|dataframe
2