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,800
69,124,347
How to combine/union two separate numpy Gaussian sets?
<p>I want to combine two separate random Gaussian data sets, one with its own mean and std and the other with an outlier mean and std. My code that I have is this:</p> <pre><code>import random import numpy as np import numpy.random as ra from numpy.random import seed #This makes the random numbers generated not chang...
<p>In order to combine two numpy arrays by column you might use the <a href="https://numpy.org/doc/stable/reference/generated/numpy.append.html" rel="nofollow noreferrer">append</a> method.</p> <pre class="lang-py prettyprint-override"><code>np.append(data, dataoutlier, axis=1) </code></pre>
python|numpy|statistics
0
352,801
69,104,293
Difficulty setting batch size correctltly in 2 layer RNN
<p>I am building an RNN that makes a multi-class classification output for 11 dimensions in the output. The input are word embeddings that I took from a pretrained glove model.</p> <p>The error I get is (full traceback at the end of the question):</p> <blockquote> <p>ValueError: Expected input batch_size (1) to match t...
<p>You should not be using <code>.view(-1)</code>. This line:</p> <pre class="lang-py prettyprint-override"><code>loss = criterion(output, target.view(-1)) </code></pre> <p>should be:</p> <pre><code>loss = criterion(output, target) </code></pre> <p>It is effectively removing your batch dimension. For <code>batch_size=1...
python|pytorch|recurrent-neural-network
1
352,802
69,112,634
Dataframe row/column calculations [cell dependency]
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Year</th> <th>PresentValue</th> <th>InterestRateChange</th> <th>ShortTermRates</th> <th>CouponRates</th> <th>LoanRates</th> <th>DeltaPrice</th> <th>CouponEarning</th> <th>LoanPayment</th> <th>Earnings/Loss</th> <th>FinalPresentValue</th> </tr> </t...
<p>To replace NaN value in PresentValue Column you can take average of PresentValue and replace it with NaN</p> <p>Since other column values are different the Final Output value calculated will be different and there won't be any problem</p> <p>Also the <strong>diversified data will be generated if you replace mean wit...
pandas|dataframe|jupyter-notebook|shift
0
352,803
69,167,467
Counting weight of unique combinations within groups
<p>I have the following dataframe:</p> <pre><code> Group from to 1 2 1 1 1 2 1 3 2 1 3 1 2 1 4 2 3 1 2 1 2 2 3 1 </code></pre> <p>I want create a 4th column that counts the of unique combinations (from, to)...
<p>In your case we just need <code>groupby</code> with <code>size</code></p> <pre><code>out = df.groupby(df.columns.tolist()).size().to_frame(name='weight').reset_index() Out[258]: Group from to weight 0 1 1 2 1 1 1 2 1 1 2 1 3 1 1 3 1 3 2 1 4 ...
python|pandas|numpy
1
352,804
68,999,839
pandas/python: filter by condition within same column grouping
<p>i have a df that has multiple pairs of related items; example: fxr_dl2_rank.r1 and fxr_dl2_rank.r1_wp. Is it possible to fliter all the related pairs with both positive results?</p> <pre><code>data = {'item':['fxr_dl2_rank.r1','fxr_dl2_rank.r2','fxr_dl2_rank.r3', 'fxr_dl2_rank.r4','fxr_dl2_rank.r5', ...
<p>First rework the 'item' to get the common part, use it to group the rows, check whether all elements are positive and use the output for slicing:</p> <pre><code>group = df['item'].str.replace('_wp$', '', regex=True) df[df.groupby(group)['result'].transform(lambda s: all(s.ge(0)))] </code></pre> <p>output:</p> <pre><...
python|pandas|filter
1
352,805
69,271,095
When to use "accuracy" string or tf.keras.metrics.Accuracy() in a classifier neural network model
<p>I'm learning about neural network and I have a question about metrics. In the book I'm reading it says I could use as &quot;metrics&quot; at model.compile() a string or the full name of the function like bellow. I'm using Google Colab Research.</p> <pre><code>model.compile(loss=tf.keras.losses.binary_crossentropy, ...
<p>It seems that <code>'accuracy'</code> actually corresponds to <code>tf.keras.metrics.BinaryAccuracy()</code> in this case, see the code below.</p> <pre class="lang-py prettyprint-override"><code>from sklearn.datasets import make_circles from sklearn.model_selection import train_test_split import tensorflow as tf n_...
python|tensorflow|keras|neural-network
2
352,806
69,055,069
How do I add a column based on selected row filter in pandas?
<p>Hi I would like to give a final score to the students based on current Score + Score for their favourite subject.</p> <pre><code>import pandas as pd new_data = [['tom', 31, 50, 30, 20, 'English'], ['nick', 30, 42, 23, 21, 'Math'], ['juli', 39, 14, 40, 38, 'Science']] df = pd.DataFrame(new_data, columns = ['Name','Cu...
<p>We can use <code>lookup</code> to find the scores corresponding to the <code>Favourite_Subject</code> then add them with the <code>Current_Score</code> to calculate <code>Final_Score</code></p> <pre><code>i = df.columns.get_indexer(df['Favourite_Subject']) df['Final_Score'] = df['Current_Score'] + df.values[df.index...
python|pandas
4
352,807
68,966,167
Does this LSTM loop code break the computational graph in PyTorch?
<p>The code below is from <a href="https://pytorch.org/tutorials/beginner/nlp/sequence_models_tutorial.html" rel="nofollow noreferrer">https://pytorch.org/tutorials/beginner/nlp/sequence_models_tutorial.html</a></p> <pre><code>for i in inputs: # Step through the sequence one element at a time. # after each step...
<p>In this case, no: you are providing the hidden state from one layer to the other at every loop iteration. This means the gradient flow is kept the and backpropagation will occur through the hidden states as well.</p> <p>To give a clear answer to your question: yes the <code>hidden</code> variable is been overwritten...
pytorch
2
352,808
69,183,773
How can i split df row based on containing semicolon ;
<p>my DataFrame having 2 values in one row separated by semicolon ;</p> <p>every row (containing 2 values separated by semicolon ; )</p> <p>How can I split the value after ; to the next column (where two values will by side by side in two columns)?</p> <h2>Heading ## needed output:</h2> <p>First row value (before ;) ...
<p>You will want to use <code>Pandas.str.split()</code> method:</p> <p><code>split_vals = df['col_to_split'].str.split(&quot;;&quot;, expand = True)</code></p> <p>This will produce a new Data frame, <code>split_vals</code> that contains two columns, one containing all the string before the &quot;;&quot;, and another fo...
python|pandas|dataframe
0
352,809
68,959,719
Converting GeoJSON object to shapely object
<p>I have a geodataframe:</p> <pre><code>gdf name ... geometry 0 INET_PL_273_EE_0_Seg_0_Seg_0 ... {'type': 'LineString', 'coordinates': [[23.896... 1 INET_PL_273_EE_1_Seg_0_Seg_0 ... {'type': 'LineString', 'coordinates': [[22.241... 2 ...
<p><code>shape()</code> function converts it back:</p> <pre><code>gdf['geometry'] = gdf['geometry'].apply(lambda x: shapely.geometry.shape(x)) </code></pre>
python|dataframe|geojson|geopandas|shapely
1
352,810
68,906,152
How to index a dataframe using a condition on a column that is a column of numpy arrays?
<p>I currently have a pandas dataframe that has a column of values that are numpy arrays. I am trying to get the rows of the dataframe where the value of the column is an empty numpy array but I can't index using the pandas method. Here is an example dataframe.</p> <pre><code>data = {'Name': ['A', 'B', 'C', 'D'], 'stat...
<p>You can check length by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.len.html" rel="nofollow noreferrer"><code>Series.str.len</code></a>, because it working with all Iterables:</p> <pre><code>print (df['stats'].str.len()) 0 3 1 0 2 3 3 0 Name: stats, dtype: int64 <...
python|pandas
1
352,811
68,989,171
export dataframe to csv staking the columns with header and date index
<p>I have a dataframe that I'd like to export to a csv file where each column is stacked on top of one another. I want to use each header as a label with the date in this format, Allu_1_2013.</p> <pre><code>date Allu_1 Allu_2 Alluv_3 year 2013-01-01 2.00 1.45 3.54 2013 2014-01-01 3.09 ...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.melt.html" rel="nofollow noreferrer">melt</a>:</p> <pre><code>new_df = df.melt(id_vars=[&quot;date&quot;, &quot;year&quot;], var_name=&quot;Date&quot;, value_name=&quot;Value&quot;).drop(columns=['date']) new_df['idx'] = new_...
python|pandas|dataframe|stack|export-to-csv
0
352,812
69,168,083
Pandas DataFrame - Add a character after every 2 position in a series
<p>I have the following dataframe</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>comment</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>abcdefg</td> </tr> <tr> <td>2</td> <td>xkie</td> </tr> <tr> <td>3</td> <td></td> </tr> <tr> <td>4</td> <td>yvv12</td> </tr> </tbody> </table>...
<p>Use <code>str.replace</code>. Insert dot <code>.</code> every 2 characters <code>\w{2}</code> except if this is the end of line <code>(?!$)</code>:</p> <pre><code>df['comment'] = df['comment'].str.replace(r'(\w{2}(?!$))', r'\1.', regex=True) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df ID comment 0...
python|regex|pandas
2
352,813
69,228,873
Loop over pandas groupby and assign the operations back to parent DataFrame
<p>I have a <code>Month, Year, Market and Value</code> columns in pandas dataframe. I'd perform / calculate percent change operation for each group and assign a new column back to parent DataFrame.</p> <p>Here's a mock DataFrame:</p> <pre><code>df = pd.DataFrame({'Market': ['LA','SF','NY','LA','SF','NY'], ...
<p>IIUC, you can try:</p> <pre><code>df['value_pct'] = (df.sort_values(by=['Year', 'Month']) .groupby('Market') ['Value'] .pct_change() ) </code></pre> <p>Output:</p> <pre><code> Market Month Year Value value_pct 0 LA 4 2017...
python|pandas
1
352,814
69,206,434
Difference of Timestamp Rows in Pandas where Difference condition will be updated everytime
<p>I have a Sample <code>DataFrame</code> which has 2 Columns ID, Datetime.</p> <pre><code>ID Datetime 123 12Sep2021 10:00 123 12Sep2021 10:10 123 12Sep2021 10:25 123 12Sep2021 10:40 123 12Sep2021 10:52 123 12Sep2021 11:20 456 01Oct202...
<p>My solution is this. I am not sure if there is a simple way of doing this.</p> <pre><code>d={i:j.Datetime.to_numpy() for i,j in df.groupby(&quot;ID&quot;)} di=dict() for id in d.keys(): n=1 times=d[id] empty_list=list() first=times[0] for time in times: diff=time-first if diff ...
python|pandas
1
352,815
69,057,361
how to use np.ix_ for submatrices
<p>I have a 3D array in numpy of shape (4, 13, 13) where each of the 4 rows is a submatrix of 13x13.</p> <p>How do I use np.ix_ to index subarrays across all rows?</p> <pre><code>a = np.zeros((4,13,13)) to_select = np.ix_([0,2], [0,2]) a[:, to_select] # returns the error below a[to_select] # works without error, but is...
<p><a href="https://numpy.org/doc/stable/reference/generated/numpy.ix_.html" rel="nofollow noreferrer"><code>np._ix</code></a> returns a tuple of arrays for each axis instead of int/bool arrays as the index, hence they can't be used in conjunction with other slicing methods. Here is a workaround by including all of the...
numpy-slicing
1
352,816
69,141,777
Calculate column values in pandas based on previous rows of data in another column
<p>Let's say I have a table with two columns: Date and Amount. Number of rows are not more than 3000.</p> <p>Row Date Amount</p> <p>1 15/05/2021 248</p> <p>2 16/05/2021 115</p> <p>3 17/05/2021 387</p> <p>4 18/05/2021 214</p> <p>5 19/05/2021 678</p> <p>6 20/05/2021 489</p> <p>7 21/05/2021 875</p> <p>8 22/05/2021 123</p>...
<p>We can calculate the <code>trim_mean</code> by applying the function over a <code>rolling</code> window of size <code>90</code> and <code>min_periods=1</code></p> <pre><code>from scipy.stats import trim_mean df['Amount'].rolling(90, min_periods=1).apply(trim_mean, args=(0.1, )).shift() </code></pre> <hr /> <pre><co...
python|pandas|calculated-columns|calculation
2
352,817
69,275,133
What is different between The MaxPool1D API in tensorflow 2.X and MaxPool1d in pytorch
<p>I'm trying to re-implement code generated in tensorflow into pytroch, but I came across maxpooling, looked into the documentation of the two frameworks, and found that their behavior is not the same. Can someone please explain to me why they are different, and which one is more efficient (I ask this because they giv...
<h2>MaxPool vs GlobalMaxPool</h2> <p><a href="https://pytorch.org/docs/stable/generated/torch.nn.MaxPool1d.html" rel="nofollow noreferrer"><code>torch.nn.MaxPool1d</code></a> pools every <code>N</code> adjacent values by performing max operation.</p> <p>For these values:</p> <pre><code>[1, 2, 3, 4, 5, 6, 7, 8] </code><...
tensorflow|pytorch
1
352,818
69,173,811
Pandas pivot_table: "merge" column values
<p>Assume I have the following table:</p> <pre><code>from datetime import datetime import pandas as pd d = [[datetime(year=2021, month=1, day=1, minute=5), &quot;A&quot;, &quot;new&quot;, 3], [datetime(year=2021, month=1, day=1, minute=5), &quot;B&quot;, &quot;new&quot;, 6], [datetime(year=2021, month=1, day...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.swaplevel.html" rel="nofollow noreferrer"><code>DataFrame.swaplevel</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_index.html" rel="nofollow noreferrer"><code>DataFrame.so...
python|pandas|dataframe|pivot-table
3
352,819
69,174,223
ValueError: Input 0 is incompatible with layer model_2: expected shape=(None, 160, 160, 3), found shape=(32, 160, 3)
<p>I'm trying to build an image classifier using the base model from the pre-trained model MobileNet V2. Here is the code of the model:</p> <pre><code> img_size = (160, 160) img_shape = img_size + (3,) print(img_shape) base_model = tf.keras.applications.MobileNetV2(input_shape=img_shape, ...
<p>Your model is expecting input of shape 4-D, but you are giving 3-D input. Need to add extra batch dimension as mentioned in comment by @Frightera .</p> <pre><code>image = (160, 160, 3) tf.expand_dims(image, axis=0).shape.as_list() output: (1, 160, 160, 3) </code></pre>
python|tensorflow|keras
0
352,820
68,974,487
Is there a way to count the number of values in a row that are greater than a "variable" value in Pandas?
<p>I have two separated DataFrames:</p> <p>df1:</p> <pre><code>Col1 Col2 Col3 Col4 Col5 ID1 2 3 5 0 ID2 7 6 11 5 ID3 9 16 20 12 </code></pre> <p>df2:</p> <pre><code>Col1 ColB ID1 2 ID2 7 ID3 9 </code></pre> <p>Is there a way to count how many values in the ...
<p>The prior assumption is that 'Col1' is the index. If not, add <code>.set_index('Col1')</code> after df1/df2 in the right part of the commands:</p> <p>You can use the underlying numpy array:</p> <pre><code>df1['COUNT'] = (df1.values&gt;df2.values).sum(axis=1) # if &quot;Col1&quot; is not index df1['COUNT'] = (df1.se...
pandas|dataframe|countif
0
352,821
68,977,780
Replace value based on condition within groups in a dataframe
<p>My dataframe is something like</p> <p><strong>df</strong></p> <pre><code>group cat_col g1 r g1 nr g1 r g1 nr g2 nr g2 nr </code></pre> <p>I need to replace &quot;nr&quot; for &quot;r&quot; whenever the group has at least 1 &quot;r&quot;. In this case, I need it to return:</p> <p><strong>df_new</str...
<p>Use <code>groupby.transform</code>:</p> <pre><code>df.cat_col.groupby(df.group).transform(lambda g: 'r' if g.eq('r').any() else g) 0 r 1 r 2 r 3 r 4 nr 5 nr Name: cat_col, dtype: object </code></pre> <p>If only need to replace <code>nr</code> with <code>r</code>:</p> <pre><code>df.cat_col = df...
python|pandas
3
352,822
68,954,508
validation and train metrics very low values (images and masks generator)
<p>I have images(X_train) and masks data (y_train).</p> <p>I want to train a unet network. I am currently using iou metric and the validation iou is very low and constant!</p> <p>I am not sure if I can handle right the scaling preprocessing of images and masks.</p> <p>I have tried either to use only <code>rescale=1.0/2...
<p>The problem is with the pre-processing. According to <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator" rel="nofollow noreferrer">tf.keras.preprocessing.image.ImageDataGenerator</a> documentation:</p> <blockquote> <p>preprocessing_function: function that will be appl...
deep-learning|tensorflow2.0|tf.keras
0
352,823
69,153,324
Combine multiple text files into only one text file
<p>I would like to combine multiple text files into only one text file, and read all the contents in it. However, the codes read only one text file and save data taken from only one text file. The codes;</p> <pre><code>path = &quot;/home/Documents/Python/&quot; read_files = glob.glob(path+&quot;*.txt&quot;) with...
<p>in case someone wants to use another method, these codes have worked for me. i have followed another path to find out a solution for my own question.</p> <pre><code>all_files = glob.glob(path + &quot;/*.txt&quot;) all = [] for filename in all_files: df = pd.read_csv(filename, index_col=None, header=0) all.ap...
arrays|python-3.x|string|numpy|file
1
352,824
69,217,189
how to convert image from rgb to grayscale in flutter?
<p>I'm working with tensorflow lite model and flutter, where the model receive grayscale image as an input. is there any way to convert RGB Image to Grayscale image using flutter?</p>
<p>The ColorFiltered widget can help. Please note that this will effect transparent pixels as well.</p> <pre><code>ColorFiltered( colorFilter: const ColorFilter.mode( Colors.grey, BlendMode.saturation, ), child: Your Image Here), ) </code></pre>
flutter|tensorflow-lite
0
352,825
69,253,601
Multiple inputs and outputs, parallelize it using what?
<p><code>Pool.map()</code> accepts only one iterable as an argument, that's not my case, and I find it difficult to reduce it to a single iterable variable.</p> <p><code>mp.Process()</code> only allows me one variable output, which is not my case either, my outputs are 4 list of geodataframe which is created in the par...
<p>You can <code>zip</code> together the multiple <em>iterable</em> arguments and call <code>Pool.map</code> with that result as the single <em>iterable</em> argument in which case the <em>func</em> argument to <code>map</code> then will be a function that takes a <code>tuple</code> as its argument or you can call <cod...
python|multiprocessing|geopandas
0
352,826
68,953,476
conditions inside conditions pandas
<p>below is my DF in which I want to create a column based on other columns</p> <pre><code>test = pd.DataFrame({&quot;Year_2017&quot; : [np.nan, np.nan, np.nan, 4], &quot;Year_2018&quot; : [np.nan, np.nan, 3, np.nan], &quot;Year_2019&quot; : [np.nan, 2, np.nan, np.nan], &quot;Year_2020&quot; : [1, np.nan, np.nan, np.na...
<p>You can forward or back filling missing values and then select last or first column:</p> <pre><code>test['Final'] = test.ffill(axis=1).iloc[:, -1] </code></pre> <hr /> <pre><code>test['Final'] = test.bfill(axis=1).iloc[:, 0] </code></pre> <p>If there is only one non missing values per rows and numeric use:</p> <pre>...
python|pandas|numpy
2
352,827
69,258,128
How can I use different encoder and decoder transformers models
<p>simply input is image ===&gt; output text(feature extractor ) I want to use separate encoder and decoder models for Handwriting recognition TrOCR shows an error that the input image is diff size for each model How can I modify the config of model or do normalize fro input image to models</p> <pre><code>from transfor...
<p>I think the way you've worded your question doesn't line up with the example you've given. Firstly, the example array you've given is 3D, not 2D. You can do</p> <pre><code>&gt;&gt;&gt; arr.shape (1,2,3) &gt;&gt;&gt; arr.ndim 3 </code></pre> <p>Presumably this is a mistake, and you want your array to be 2D, so you wo...
python|nlp|pytorch|huggingface-transformers
1
352,828
69,227,098
merge one to many without duplicates
<p>Hi could someone please help, how to merge the below 2 tables, without using the remove duplicates function.</p> <pre><code> import pandas as pd df = pd.DataFrame({'ID' : [1,2,3], 'product' : ['Phone','Car','Bike']}) df2 = pd.DataFrame({'ID2':[1,1,1,2,2,3,3,3], 'price' : [30,50,30,50,50,20,60,40], 'location' :...
<p>You can to a classical <code>merge</code>, then hide the duplicated<code>columns using</code>mask`:</p> <pre><code>df3 = df.merge(df2, left_on='ID', right_on='ID2') cols = df.columns df3[cols] = df3[cols].mask(df3[cols].duplicated(), '') </code></pre> <p>output:</p> <pre><code> ID product ID2 price location 0 1 ...
python|pandas|dataframe|join|merge
0
352,829
69,066,279
Is it possible to call a function inside another function in Python? (Web-Scraping problem)
<p>I'm working on a web-scraping task and I can already collect the data in a very rudimentary way.</p> <p>Basically, I need a function to collect a list of songs and artists from the Allmusic.com and then add the data in df. In this example, I use this link: <a href="https://www.allmusic.com/mood/tender-xa0000001119/s...
<p>You can just add the soup.findAll code from performer in the first function.</p> <pre><code> import requests from bs4 import BeautifulSoup import pandas as pd headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0'} link = &quot;https://www.allmusic.co...
python|pandas|web-scraping|beautifulsoup
2
352,830
69,171,596
Filter list of list column then split (explode) row-wisely in Python
<p>Let's say I have one column in a dataframe which has list of list:</p> <pre><code> id pos 0 1 [[['Malaysia','NR'], [':','PU'], ['Natural','JJ'], ['selling price','NN']]] 1 2 [[['Spot Price','NN'], [':','PU'], ['cotton','NN'], ['India', ' NR']]] </code></pre> <p>...
<p>You could try this with <code>explode</code>:</p> <pre><code>x = df.explode('pos').explode('pos') x = x[['id']].reset_index(drop=True).join(pd.DataFrame(x['pos'].tolist()).set_axis(['words', 'part_of_speech'], axis=1)) x.loc[x['part_of_speech'].isin(['NN', 'NR'])] </code></pre> <hr /> <pre><code> id words...
python|python-3.x|pandas|dataframe
3
352,831
68,874,634
cv2.error : OpenCV(4.5.3) Error: bad argument & overload resolution failed in cv.line
<p>I have a simple project with Raspi 4 with camera which the project is similar with car's reverse camera but without sensor. Here my code:</p> <pre class="lang-python prettyprint-override"><code>import time import cv2 import numpy as np from picamera.array import PiRGBArray from picamera import PiCamera camera = PiC...
<p>The value assigned to pt1 and pt2 should not have a floating point.</p> <p>So this is working fine.</p> <pre class="lang-py prettyprint-override"><code>import cv2 import numpy as np h,w=100,100 im = ~np.zeros((h,w,3), np.uint8) cv2.line(im, (0,10), (100,100),(0,0,255),2) cv2.imshow('line',im) cv2.waitKey(0) </code...
python-3.x|numpy|opencv
1
352,832
69,271,135
Combine duplicate rows into one row in Pandas data frame
<p>Let's say I have the following data: <a href="https://i.stack.imgur.com/48vwN.png" rel="nofollow noreferrer">one person can have multiple Constituency Code</a></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Unique_ID</th> <th>Name</th> <th>Constituency Code</th> </tr> </thead> <tbody> <...
<p>Setting up data - very important to provide working examples</p> <pre><code>test_data = [ [404, 'Mark', 'Teacher'], [404, 'Mark', 'Staff'], [404, 'Mark', 'Staff'], [659, 'Julio', 'Student'], [1025, 'Jasmine', 'Staff'], [1025, 'Jasmine', 'Student'] ] cols = ['Unique_ID', 'Name', 'Constinuency ...
python|pandas|numpy
2
352,833
69,231,636
Extract h3's and a href's contents and save as dataframe in Python
<p>I'm trying to extract categories and items from <a href="https://www.meishichina.com/YuanLiao/category/rql/" rel="nofollow noreferrer">this link</a> shown as in the images below and storing them into dataframe:</p> <p><a href="https://i.stack.imgur.com/fzJHA.png" rel="nofollow noreferrer"><img src="https://i.stack.i...
<p>To get all sections/categories/items into a dataframe, you can use this example:</p> <pre class="lang-py prettyprint-override"><code>import requests import pandas as ps from bs4 import BeautifulSoup url = &quot;https://www.meishichina.com/YuanLiao/&quot; headers = { &quot;User-Agent&quot;: &quot;Mozilla/5.0 (X...
python-3.x|pandas|web-scraping|beautifulsoup|python-requests
1
352,834
69,260,835
Fine-tune BERT model by removing unused layers
<p>I came across this code for BERT sentiment analysis where the unused layers are removed, Update trainable vars/trainable weights are added and I am looking for documentation which shows what are the different layers in bert, how can we remove the unused layers, add weights, etc. However, I am unable to find any docu...
<p>As mentioned in the comments, you can't actually delete layers from the model architecture. However, you can freeze layers that you do not want to be trained. So the layer you freeze is not trained and the parameters on that layer are not updated</p> <p>You can see the layers with this;</p> <pre><code>bert_model = A...
python|tensorflow|keras|sentiment-analysis|bert-language-model
0
352,835
69,111,302
How do I use separate types of gpus (e.g. 1080Ti vs 2080Ti) on the same docker image without needing to re-run `python setup.py develop`?
<p>I'm using a pytorch-based <a href="https://github.com/CVMI-Lab/ST3D/tree/315a2fd60195cbd7e196789223a0bff25ba94b47" rel="nofollow noreferrer">repository</a> where the installation step specifies to run <code>python setup.py develop</code> with this <a href="https://github.com/CVMI-Lab/ST3D/blob/315a2fd60195cbd7e19678...
<p>The problem was solved by building the docker image with the following:</p> <pre><code>RUN git clone https://github.com/CVMI-Lab/ST3D.git WORKDIR /ST3D RUN nvidia-smi RUN pip install -r requirements.txt RUN TORCH_CUDA_ARCH_LIST=&quot;6.1 7.5&quot; python setup.py develop </code></pre> <p>Where the <code>TORCH_CUDA_A...
python|docker|pytorch|gpu|nvidia
2
352,836
69,178,534
Pandas using the previous rank values to filter out current row
<p>As the title states I am trying to use the previous rank to filter out the current</p> <p>Here's an example of my starting df:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({ 'rank': [1, 1, 2, 2, 3, 3], 'x': [0, 3, 0, 3, 4, 2], 'y': [0, 4, 0, 4, 5, 5], 'z': [1, 3, 1.2, 2.95, 3...
<p>This is a bit tricky as your need to access the previous group. You can compute the groups using <code>groupby</code> first, and then iterate over the elements and perform your check with a custom function:</p> <pre><code>def check_previous_group(rank, d, groups): if not rank-1 in groups.groups: # check ...
python|python-3.x|pandas
2
352,837
69,028,097
Is their a way to add the new NER tag found in a new column?
<p>I want to be able to compare the NER tag found compared to a known location of the original tweet. I am using twitter data and adding it to a pandas dataframe columns ; id, tweet, location. I then use spacy and NER to find the location using the below code (ideally just finding the NER entities; GPE and LOC), I need...
<p>Assuming you have your data in a variable called <code>df</code> using the <code>apply</code> method should give you straightforward solution. Maybe this helps:</p> <pre><code>import spacy import pandas as pd df = &lt;YOUR DATAFRAME OBJECT THAT HAS COLS id, tweet, location&gt; nlp = spacy.load(&lt;SPACY MODEL OF CH...
python|pandas|nlp|spacy|named-entity-recognition
1
352,838
68,895,926
Convert str into float but problems with multiple dots in numbers
<p>I downloaded this datafile from the TCGA database but I am not sure how to process it in python. After importing it with pd.read_csv, I wanted to convert the <code>reads_per_million_miRNA_mapped</code> column to floats, as they are strings now, but it gives me the following error can't be done because of the dots.</...
<p>Assuming all numbers will be floats (i.e. the last dot acts as a decimal point), you can get rid of all but the last dot and then cast into floats:</p> <pre><code>example = '1.024.089' num = example.replace('.', '', example.count('.') - 1) print(float(num)) </code></pre> <p>Output:</p> <pre><code>1024.089 </code></p...
python|pandas|string|csv|floating-point
3
352,839
68,934,346
Keyerror, when using pandas read the .csv
<p>When I preprocess the LIDC-IDLI dataset, I want to read the csv file and drop the keyword with Modality:</p> <pre><code>meta = pd.read_csv(metadatapath, header=None, delimiter=&quot;,&quot;, names=column_names) meta=meta.drop(meta[meta['Modality']!='CT'].index) meta=meta.reset_index() </code></pre> <p>The error is:<...
<p>I don't the keyerror when I run the following code</p> <pre><code>meta = pd.read_csv(metadatapath) meta=meta.drop(meta[meta['Modality']!='CT'].index) meta=meta.reset_index() </code></pre>
python|pandas
0
352,840
69,057,950
Seaborn barplot behaves unexpectedly with dodge argument
<p>I am trying to produce a nested barplot with seaborn. Without the dodge argument, the plot looks like this</p> <p><code>sns.barplot(data=pos_data, x='bin', y='%', hue='POS')</code></p> <p><a href="https://i.stack.imgur.com/Eny1t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Eny1t.png" alt="Real ...
<p>The solution below allows to compare the values of the bars, but <strong>it is not stacking</strong>.</p> <p>As it appears that bars are drawn in the order the rows appear in the dataframe - to visualize all the bars you can sort the data in the descending order of Y-value before feeding it to sns.barplot</p> <pre c...
python|pandas|seaborn|bar-chart
1
352,841
69,217,879
How can I assign a pandas dataframe to a class variable?
<p>I have different methods in my class which are using the same pandas dataframe. Instead of passing the same dataframe as an argument to each method, is there a way I can declare the dataframe as a class variable so that all the methods can share it.</p> <p>I tried the solution given here but couldn't make it work. <...
<p>You can pass your dataframe while constructing the object and assign it into an instance variable like this:</p> <pre><code>class Weather: def __init__(self, df): self.df = df </code></pre> <p>Then you can access the dataframe in all your methods like this:</p> <pre><code>def HU_monthly(self, month): ...
python|pandas|dataframe|class
1
352,842
69,285,092
Precision of rounded decimals giving nans for linear equation solving
<p>Apologies for the butchered title, not sure what I should call this.</p> <p>I'm solving for the upper limit of integration of a linear equation, like in this question: <a href="https://math.stackexchange.com/questions/3878448/solving-for-limit-of-integration-of-a-linear-equation">https://math.stackexchange.com/quest...
<p>So what I ended up doing was I encased the function in a <code>while</code> loop with an enclosed <code>try/except</code> block that catches the <code>RuntimeWarning</code> given when a <code>nan</code> is produced.</p> <p>I recorded the precision of <code>xvals</code> prior,</p> <pre><code>precision = max([str(i)[:...
python|numpy|precision
1
352,843
68,892,456
PySpark pattern matching and assigning associated values
<p><strong>df1</strong>:</p> <pre><code>campaign_name campaign_team einsurancep09 other estoreemicardcdwpnov06 other estoreemicardwmnov06 other estoreemicardgenericspnov06 other </code></pre> <p><strong>df2</strong>:</p> <pre><code>terms product_category product insurance insurance null def emi store a...
<p>Assumption</p> <p>Dataset df1 should have an order to meet the OP requirement. So I introduce the rec_no column</p> <pre><code>df = spark.sql(&quot;&quot;&quot; select 'abcdefcdwpnovo6' campaign_name, 'other' campaign_team union all select 'abcdefdwpnovo6' , 'other' union all select 'abcdefgenericpnovo6' , 'other' ...
python|pandas|apache-spark|pyspark|apache-spark-sql
1
352,844
44,808,812
How to prepare a dataset of images to train and test tensorflow
<p>I am using Windows 10 pro, Visual Studio 10, Python 3.6.2rc1 and Tensorflow. I am trying to build a convolutional neural network (CNN) to classify images of fruits with Tensorflow. I have only two fruits, pineapple and banana. It's less than a week I am working with python and this is my first experience.</p> <p>I ...
<p>These are the lines where the MNIST data is fed in: </p> <pre><code># Load training and eval data mnist = learn.datasets.load_dataset("mnist") train_data = mnist.train.images # Returns np.array train_labels = np.asarray(mnist.train.labels, dtype=np.int32) eval_data = mnist.test.images # Returns np.array eval_labe...
python|tensorflow|windows-10
0
352,845
44,640,613
What is the output of tf.split?
<p>So assuming I have this:</p> <blockquote> <p>TensorShape([Dimension(None), Dimension(32)])</p> </blockquote> <p>And I use tf.split on this tensor _X with the dimension above:</p> <pre><code>_X = tf.split(_X, 128, 0) </code></pre> <p>What is the shape of this new tensor? The output is a list so its hard to kno...
<p>tf.split() returns the list of tensor objects. You could know shape of each tensor object as follows</p> <pre><code>import tensorflow as tf X = tf.random_uniform([256, 32]); Y = tf.split(X,128,0) Y_shape = tf.shape(Y[1]) sess = tf.Session() X_v,Y_v,Y_shape_v = sess.run([X,Y,Y_shape]) # numpy style print X_v.shap...
python|arrays|tensorflow|tensor
10
352,846
44,502,306
Pandas dataframe to_csv - split into multiple output files
<p>What is the best /easiest way to split a very large data frame (50GB) into multiple outputs (horizontally)?</p> <p>I thought about doing something like:</p> <pre><code>stepsize = int(1e8) for id, i in enumerate(range(0,df.size,stepsize)): start = i end = i + stepsize-1 #neglect last row ... df.ix[start...
<p>Use id in the filename else it will not work. You missed <code>id</code>, and without <code>id</code>, it gives an error.</p> <pre><code>for id, df_i in enumerate(np.array_split(df, number_of_chunks)): df_i.to_csv('/data/bs_{id}.csv'.format(id=id)) </code></pre>
python|pandas
15
352,847
44,603,960
How to index multidimensional numpy array with another numpy array
<p>Let's assume I have following numpy arrays:</p> <pre><code>idx = [1,2] A = [[1,2,3], [4,5,6], [7,8,9]] </code></pre> <p>I want to get <code>A[idx[0],idx[1]]</code></p> <p><code>A[idx]</code> gets a slice. And I don't want to use <code>A[idx[0],idx[1]]</code> for clarity reasons</p>
<p>I have found a solution:</p> <pre><code>A[tuple(indx)] </code></pre>
python|numpy
2
352,848
44,423,036
Pandas: to_excel() float_format
<p>I'm trying to get the <code>float_format</code> parameter working with pandas' <code>to_excel()</code> function, but it doesn't seem to do anything. </p> <p><strong>Code:</strong></p> <pre><code>df = pd.DataFrame({ 'date':['1/15/2016','2/1/2016','2/15/2016','3/15/2016'], 'numA':[1000,2000,3000,400...
<p>I believe Excel formatting changes how floats are displayed. I tried <code>to_csv</code> method and <code>float_format</code> worked. For excel, telling excel how to display the column helps:</p> <pre><code>df = pd.DataFrame({ 'date':['1/15/2016','2/1/2016','2/15/2016','3/15/2016'], 'numA':[1000,200...
excel|pandas|formatting
12
352,849
44,551,348
I have a pandas dataframe with weeks and days in each week. How do I consider the rows where the date matches with the day?
<pre><code>2016-07-04 2016-06-24 154.0 320.0 923.0 1243.0 100.0 330.0 2016-07-04 2016-06-27 195.0 384.0 1051.0 1501.0 117.0 413.0 2016-07-04 2016-06-28 214.0 404.0 1066.0 1590.0 127.0 443.0 2016-07-04 2016-06-29 232.0 420.0 1089.0 1677.0 139.0 466.0 2016-07-04 2016-06-...
<p>IIUC:</p> <pre><code>df[df.iloc[:, 0] == df.iloc[:, 1]] 0 1 2 3 4 5 6 7 7 2016-07-04 2016-07-04 406.0 442.0 1092.0 1718.0 142.0 476.0 </code></pre>
python|date|pandas|dataframe
3
352,850
44,535,111
Error when restoring model (Multiple OpKernel registrations match NodeDef)
<p>I'm getting an error when attempting to restore a model from a checkpoint.</p> <p>This is with the nightly Windows GPU build for python 3.5 on 2017-06-13.</p> <pre><code>InvalidArgumentError (see above for traceback): Multiple OpKernel registrations match NodeDef 'Decoder/decoder/GatherTree = GatherTree[T=DT_INT3...
<p>I also faced the same issue a day ago. Turns out it was a <a href="https://github.com/tensorflow/tensorflow/issues/11277" rel="nofollow noreferrer">bug</a> in tensorflow. It's resolved now and BeamSearchDecoder should work with the latest build of tensorflow. </p>
tensorflow
0
352,851
44,378,266
Using Python 3, how to print a panda series with categories
<p>How do I print the car_data Series using Python 3?</p> <pre><code>import pandas as pd car_colors = pd.Series(['Blue', 'Red', 'Green'], dtype='category') car_data = pd.Series(pd.Categorical(['Yellow', 'Green', 'Red', 'Blue', Purple'], categories=car_colors, ordered=False)) print(str(car_colors)) # works # both p...
<p>Let's try this, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Categorical.html#pandas.Categorical" rel="nofollow noreferrer"><code>pd.Categorical</code></a>, category takes and index-like values</p> <pre><code>car_colors = ['Blue', 'Red', 'Green'] car_data = pd.Series(pd.Categorical(['Yello...
python-3.x|pandas
0
352,852
44,741,331
Assigning column of first data frame to the second one, if data frames have different size
<p>Suppose I have 2 data frames:</p> <pre><code>df1 = pd.DataFrame(np.arange(0,301),columns = ['id']) df2 = pd.DataFrame(np.arange(200,387),columns = ['id']) df1['2'] = np.random.randint(0,2,301) df2['2'] = np.random.randint(0,2,187) </code></pre> <p>Then I match id's from second data frame to first and create third...
<p>First assign a column in <code>df1</code> with <code>NA</code> by default. Next for each row in <code>df1</code> get <code>id</code> value for the <code>row</code> and look if same <code>id</code> is in <code>temp</code> <code>dataframe</code>. If it returns non empty then assign corresponding row of <code>df1</code...
pandas
1
352,853
44,532,555
How to get an integer array from numpy.bincount when the weights parameter are integers
<p>Consider the numpy array <code>a</code></p> <pre><code>a = np.array([1, 0, 2, 1, 1]) </code></pre> <p>If I do a bin count, I get integers</p> <pre><code>np.bincount(a) array([1, 3, 1]) </code></pre> <p>But if I add weights to perform the equivalent bin count</p> <pre><code>np.bincount(a, np.ones_like(a)) arra...
<blockquote> <p>Why doesn't numpy assume the same dtype as what was passed as weights?</p> </blockquote> <p>There are two reasons:</p> <ul> <li><p>There are several ways to weight a count, either by it multiplying the value with the weight or by multiplying the value with the weight divided by the sum of the weight...
python|numpy
3
352,854
44,508,049
What is this called: Melting? Pivoting? Reshaping?
<p>This is a question about using pandas and ggplot in Python, but an R answer would also be very much appreciated.</p> <p>I am trying to plot some timeseries data that look somewhat like what's shown below. X, Y, Z are well-plate ids (names of experiments), and 0,1,2 are different times. I want to be able to plot the...
<p>It is called reshaping a a dataframe with methods such as pivot or melting and can include stack and unstack, pivot_table and various other methods.</p> <h1>To go from 'wide' to 'long'</h1> <pre><code>print(df) X Y Z 0 0.1 0.2 0.3 1 1.1 1.2 1.3 2 2.1 2.2 2.3 </code></pre> <p>You can reshape i...
python|pandas
6
352,855
44,489,629
Pandas: List-like indexing for .loc[...]
<p>I think I'm missing something very simple, but I'm trying to use list-like indexing with <code>.loc[...]</code> to select all but the last row in a dataframe. </p> <p><strong>Setup:</strong></p> <pre><code>import pandas as pd df = pd.DataFrame({ 'a':[1,2,3,4,5], 'b':[6,7,8,9,0] }) </code></pr...
<p>You're trying to mix label-based indexing with integer indexing/slicing. You can't use <code>loc</code> for that, which is for label-<em>loc</em>ation based indexing.</p> <p>Pandas currently provides <code>ix</code> for mixing label and integer based indexing. But that will be deprecated in a future version.</p> <...
python|pandas|indexing
3
352,856
44,578,733
Vectorized version of finding the maximum positive value or else the minimum negative value
<p>Let's say I have a pandas DataFrame called <code>purity_list</code> as follows:</p> <pre><code>In[]: purity_list Out[]: 48 49 50 2 0.1 0.9 0.3 A 0.2 -0.5 -0.6 4 0.3 0.8 0.9 </code></pre> <p>I would like to compare this to another numpy array and get the maximum +ve value and if there ar...
<p>The logic isn't quite right in your version of <code>np.where</code>. Consider what happens when there is a negative value of greater magnitude than a positive value it is compared with. The choice of tool, though, is sound. So all you need to do is correct the condition to better match what you're aiming for:</p> ...
python|performance|python-3.x|pandas|numpy
1
352,857
44,549,658
tf.norm error ValueError: 'ord' must be a supported vector norm, got fro
<p>I am trying to calculate the Frobenius Norm of my tensor</p> <pre><code>W = tf.Variable(tf.random_normal([3072,20],stddev=0.1)) temp = tf.matmul(tf.transpose(W),W) fro_W = tf.norm(temp, ord ='fro') </code></pre> <p>This produces the following error:</p> <p>ValueError: 'ord' must be a supported vector norm, got fr...
<p>From the <a href="https://www.tensorflow.org/api_docs/python/tf/norm" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>The Frobenius norm fro is not defined for vectors</p> </blockquote> <p>Also,</p> <blockquote> <p>If axis is <code>None</code> (the default), the input is considered a vector</...
python|image-processing|tensorflow|neural-network|norm
4
352,858
44,617,331
Python vertical stack not working
<p>I have a matrix X which has <code>len(X)</code> equal to 13934 and <code>len(X[i])</code>, for all i, equal to 74, and I have an array Y which has <code>len(Y)</code> equal to 13934 and <code>len(Y[i])</code> equal to <code>TypeError: object of type 'numpy.int64' has no len()</code> for all i.</p> <p>When I try <co...
<p>You can try this:</p> <pre><code># use Y[:,None] to make Y 2d array so it can be concatenated with X which is also 2d np.concatenate((X, Y[:,None]), axis=1) </code></pre> <p>Or:</p> <pre><code>np.hstack((X,Y[:,None])) </code></pre>
python|numpy
1
352,859
44,406,819
pytorch custom layer "is not a Module subclass"
<p>I am new to PyTorch, trying it out after using a different toolkit for a while.</p> <p>I would like understand how to program custom layers and functions. And as a simple test, I wrote this:</p> <pre><code>class Testme(nn.Module): ## it _is_ a sublcass of module ## def __init__(self): super(Tes...
<p>That's a simple one. You almost got it, but you forgot to actually create an instance of your new class Testme. You need to do this, even if the creation of an instance of a particular class doesn't take any parameters (as for Testme). But it's easier to forget than for a convolutional layer, to which you typically ...
torch|pytorch|autograd
7
352,860
44,697,590
Unable to generate accurate result from mnist dataset
<p>I have been practicing machine learning, And i came across mnist tutorials. While learning, I have made this code. </p> <p>` import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import numpy as np</p> <pre><code>mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) ...
<p>There are couple of issues with your code: </p> <ol> <li><p>Remove relu activation on the final_output. The softmax_cross_entropy_with_logits will apply softmax activation on your final_output.</p> <pre><code>final_output = tf.add(tf.matmul(hidden_layer_3_output, output_layer['weights']), output_layer['bias']) <...
python|machine-learning|tensorflow|mnist
2
352,861
44,384,495
numpy package not defined when importing function from another .py file
<p>In my master file I have:</p> <pre><code>import matplotlib.pyplot as plt import seaborn import numpy as np import time import sys sys.path.append("C:/.../python check/createsplit") import createsplit data='MJexample' X,Y,N,Ntr=create_training_data(data) </code></pre> <p>where I am calling <em>create_training_dat...
<p>I think this issue raises just because of a wrong call of the function. Try</p> <pre><code>X, Y, N, Ntr = createsplit.create_training_data(data) </code></pre> <p>instead, and it should work.</p>
python|python-2.7|numpy
1
352,862
44,810,459
Tensorflow Object Detection API
<p>I decided to take a dip into ML and with a lot of trial and error was able to create a model using TS' inception.</p> <p>To take this a step further, I want to use their <a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="nofollow noreferrer">Object Detection API</a>. But their...
<p>The training jobs in the Tensorflow Object Detection API expect to get TF Record files with certain fields populated with groundtruth data.</p> <p>You can either set up your data in the same format as the Pascal VOC or Oxford-IIIT examples, or you can just directly create the TFRecord files ignoring the XML formats....
machine-learning|tensorflow|object-detection
12
352,863
44,808,617
Filtering pandas dataframe for a steady speed condition
<p>Below is a sample dataframe which is similar to mine except the one I am working on has 200,000 data points.</p> <pre><code>import pandas as pd import numpy as np df=pd.DataFrame([ [10.07,5], [10.24,5], [12.85,5], [11.85,5], [11.10,5], [14.56,5], [14.43,5], [14.85,5], [14.95,5], [10.41,5], ...
<p>Let use <code>rolling</code>,<code>shift</code> and <code>std</code>:</p> <p>Calculate the rolling std for a window of 3, the find those stds less than 0.5 and use shift(-2) to get the values at the start of the window where std was less than 0.5. Using boolean indexing with <code>|</code>(or) we can get the entir...
python|pandas|dataframe|filtering
0
352,864
44,579,107
Variable not created when restore graph with import_meta_graph?
<p>I am trying to restore graph from model which I train with <a href="https://github.com/tensorflow/models/blob/master/tutorials/rnn/ptb/ptb_word_lm.py" rel="nofollow noreferrer">TensorFlow tutorials</a>, then I try to restore the model: </p> <pre><code>import tensorflow as tf import reader from ptb_word_lm import PT...
<p>I think, since you set reuse=True in your variable scope, it tries to find that variable instead of creating it when you call PTBModel(). If you use get_variable() with reuse=True in a scope, it will never create a variable.</p>
python|tensorflow
0
352,865
44,570,632
Creating a matrix-Tensor of operations
<p>I am trying to implement a kind of nonlinear filter in TensorFlow, but I am having trouble with the implementation for one step. The step is basically something like:</p> <pre class="lang-py prettyprint-override"><code>x_update = x.assign(tf.matmul(A, x)) </code></pre> <p>The problem is that the matrix <code>A</co...
<p>The easiest way to update a submatrix is to use tensorflow's python slicing ops.</p> <pre><code>import numpy as np import tensorflow as tf A = tf.Variable(np.zeros((5, 5), dtype=np.float32), trainable=False) new_part = tf.ones((2,3)) update_A = A[2:4,2:5].assign(new_part) sess = tf.InteractiveSession() tf.global_...
python|numpy|tensorflow
2
352,866
44,453,986
fill columns of dataframe with groups python
<p>i have a pandas dataframe which has 1 row</p> <pre><code>key 1 2 3 ... 93 </code></pre> <p>and i am having <code>no. of machines = 3</code></p> <p>i want to allocate equal no. of keys to each machine. i.e</p> <p>there are 9 keys and 3 machines, so, 3 keys should be associated with each machine. below is the requ...
<p>You can use floor division of <code>arange</code>:</p> <pre><code>df = pd.DataFrame({'key' : range(1, 10)}) N = 3 N1 = len(df.index) / N df['machine allocated'] = ((np.arange(len(df.index)) // N1) + 1).astype(int) print (df) key machine allocated 0 1 1 1 2 1 2 3 ...
python|pandas
3
352,867
44,747,057
How to faster 3 consecutive for loops for positioning data into new matrix
<p>I want to create new matrix <code>experiment2</code> from <code>experiment</code>. The dimension of <code>experiment</code> is 13500 * <strong>12000</strong>. I want to sum each 10 columns (but preserves row number) to reduce the dimension. </p> <p>The first set is sum of column index <code>0-9, 10-19, 20-29..., 13...
<p>If you think about it, you have to loop over all 13500 * 12000 items at least once in order to calculate the sums. You cannot do it below that, so you should attempt to solve it in exactly 13500 * 12000 iterations. That means, you should only iterate the items in the original array, and only once.</p> <p>To calcula...
python|arrays|python-2.7|numpy|matrix
2
352,868
44,701,507
Using iloc to replace a column when identical names exist
<p>Suppose I have the following DataFrame with some identical column names</p> <pre><code>test = pd.DataFrame([[1, 2, 3, np.nan, np.nan], [1, 2, 3, 4, 5], [1, 2, 3, np.nan, np.nan], [1, 2, 3, 4, np.nan]], columns=['One', ...
<p>The answer to your second question as to why the first technique doesn't work could be because of the way Pandas treats duplicate columns. While the constructor for a <code>DataFrame</code> doesn't have any setting for that, the <code>read_csv</code><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pand...
python|pandas|indexing
1
352,869
44,375,092
Handling data from csv file with Python
<p>I know Python is almost made for these kind of purposes, but I am really struggling to understand how I get access to specific values in the dataset, and I tried both with pandas and csv modules. It is probably a matter of syntax. Here's the thing: I have a csv file in the form of</p> <pre><code>Nation, Year, No. o...
<p>Since you tagged pandas in the question, here's a pandas solution to getting the number of refugees per year.</p> <p>Let's say my input csv looks like this (note that I've eliminated the extra space before the column names):</p> <pre><code>Nation,Year,No. of refugees Afghanistan,2013,6657 Albania,2013,199 Algeria,...
python|csv|pandas
6
352,870
44,463,092
Using dask to import many MAT files into one DataFrame
<p>I have many mat files of the same format and I wish to join these mat files into one DataFrame with a DatetimeIndex. Currently, a for loop reads in these mat files and load the contents of each into a pandas DataFrames using scipy.io.loadmat and then each DataFrame is appended to an hdf5 table.</p> <p>Each mat file...
<p>In order to query the data, you don't need to write to a data format explicitly supported by dask. You could define your dataframe as follows:</p> <pre><code>def mat_to_dataframe(rot_file): time_stamps = pd.DataFrame(scipy.io.loadmat(rot_file)['LineInfo'][0][0][2][0]) polar_image = pd.DataFrame(scipy.io.loa...
python|pandas|hdf5|pytables|dask
2
352,871
44,572,930
KeyError exception using dataframe
<p>I get a <code>KeyError: ('user rating score', 'occurred at index title')</code> traceback when I try to execute the code below. I tried changing the axis after the <code>remove_na_scores</code> in my <code>apply()</code> function, however nothing is working.</p> <pre><code>import pandas as pd import pprint shows =...
<p>The line:</p> <pre><code>if pd.isnull(row['user rating score']): </code></pre> <p>Is where the error occurs.</p> <p>It occurs because <code>remove_na_scores</code> is being applied along the wrong axis. Adding <code>, axis=1</code> to <code>shows.apply</code> should resolve the issue for which you posted the trac...
python|pandas|dataframe
0
352,872
60,879,881
Python: read the date indices of a pandas dataframe
<p>I have a pandas dataframe:</p> <pre><code>df2.index[0:10] Out[35]: Index([2000-01-03 00:00:00, 2000-01-04 00:00:00, 2000-01-05 00:00:00, 2000-01-06 00:00:00, 2000-01-07 00:00:00, 2000-01-10 00:00:00, 2000-01-11 00:00:00, 2000-01-12 00:00:00, 2000-01-13 00:00:00, 2000-01-14 00:00:00], dty...
<p>You can use <code>pandas.to_datetime</code> function to convert the given index to <code>datetime</code>. You can find out more about <code>pandas.to_datetime</code> at <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer">pandas docs</a></p> <p>Try t...
python|pandas
1
352,873
61,085,008
Rank a column based on 2 conditions in pandas
<p>I have a df as such</p> <p><code>df col_a col_b 0 ADD 5 1 ADD 2 2 ADD 8 3 DELETE 3 4 DELETE 7 5 DELETE 4 </code> now i want to rank the values in col_b when col_a = ADD and then rank the values in col_b where col_a = DELETE. So have two separate rank values but within one ...
<p>Use <code>df.groupby().rank()</code></p> <pre><code>df['rank'] = df.groupby('col_a')['col_b'].rank() </code></pre>
pandas|conditional-statements|rank
1
352,874
61,149,173
How to partition by in pandas and output to a word doc?
<p>I have a table I have filtered from data. It is my highlights across the web. I want to, ultimately, output these to a doc file I have by the page they came from</p> <p>I have the api data filtered down to two columns</p> <p>url|quote</p> <p>How do I, for each url, output the quote to a doc file. or just for star...
<p>it would be great if you could provide some source code to help explain your problem. From looking at your question, I would say all you need to do is put your columns into a DataFrame, then export this to excel.</p> <pre><code>df = pd.DataFrame({"url":url,"quote":quote}) df["quote"].to_excel("filename.xlsx") </c...
pandas|numpy
0
352,875
60,933,474
Trying to split csv column data into lists after reading in using pandas library
<p>I have a csv file containing 3 columns of data: column 1 = time vector, column 2 is untuned circuit response and column 3 is the tuned circuit response. I am reading in this csv data in python using pandas:</p> <pre><code>df = pd.read_csv(filename, delimiter = ",") </code></pre> <p>I am now trying to create 3 list...
<p>You can use pandas series tolist method:</p> <pre><code>time = df['time vector'].tolist() untuned = df['untuned circuit'].tolist() tuned = df['tuned circuit'].tolist() </code></pre>
python|pandas|csv
0
352,876
61,141,830
Pandas/Python: Set value of new column based on row value and other DataFrame
<p>Is it possible to add a value in a column when the province name of second dataframe matches with the province name of the first dataframe? I searched for answers and weren't able to find anything useful for my case.</p> <p>This is first DataFrame</p> <pre><code> date province confirmed rele...
<p>The <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html#pandas.DataFrame.merge" rel="nofollow noreferrer">pandas.DataFrame.merge</a> method is what you want to use here.</p> <p><strong>Using your example DataFrames:</strong></p> <pre><code>import pandas as pd df1 = pd.D...
python|pandas|conditional-statements
4
352,877
60,922,607
Tensorflow 2.0: How to implement a network with fusion at feature level?
<p>I'm trying to implement in tensorflow a small model for a prediction task with two signals as input, that pass individually over a few layers and then are combined in later layers to generate the output prediction. Essentially, the model works like this:</p> <pre><code>(Signal A) -&gt; [L 1] -&gt; [L 2] -&gt; ... -...
<p>This is a template for your model in functional API, you can change the layers according to your needs.</p> <p>Your base model (common for both) - </p> <pre><code>from tensorflow.keras.layers import Input, Conv1D, Concatenate, MaxPooling1D, Flatten, Dense, GlobalMaxPooling1D, subtract, BatchNormalization from tens...
python|deep-learning|tensorflow2.0
2
352,878
61,055,393
python reading json string with headers in initial part
<p>I am trying to grab output from a package (defined in the package documentation as 'jsonDICT') and eventually write it as csv. I will call this PackResult, and it is a dictionary.</p> <p>The first, and last, few characters of print(PackResult) looks like this:</p> <pre><code>{'startDate': '2019-11-01T00:00:00', 'e...
<p>Ah. A new day and some rest gives me the obvious thing I was missing: </p> <pre><code>df = pand.read_json(json.dumps(PackResult["volume"]),'records','frame') </code></pre> <p>This results in </p> <pre><code># startDate endDate numberOfDocuments 0 2019-11-01T00:00:00 2019-11...
python|pandas
0
352,879
61,064,603
how do I get around a 'certificate has expired' error code
<p>I have been working with a data set from the machine learning repository from UCI, I have been working with this code for about 5 weeks now. I am trying to continue to work with this data set and when I read in the data as I have been with the following code:</p> <pre><code>import numpy as np ##Import necassary pac...
<p>The certificate is expired. Try using http instead of https </p> <p><a href="http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data" rel="nofollow noreferrer">http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data</a></p> <p>However, http exposes data to some security vulnerab...
python|pandas|url
1
352,880
61,116,067
distribution of times grouped by weeks
<p>I want to find the distribution of times grouped by weeks for timeseries data. For example timeseries is: </p> <pre><code>2019-04-01 02:00:00 0.6 2019-04-02 10:45:00 2.0 2019-04-03 02:00:00 3.0 2019-04-10 00:00:00 0.6 2019-04-11 10:45:00 2.0 2019-04-13 10:45:00 6.0 2019-04-17 11:45:00 2.5 2019-...
<p>What about something very simple like that?</p> <pre class="lang-py prettyprint-override"><code># I'm starting with a Series here s.head(2) # time # 2019-04-01 02:00:00 0.6 # 2019-04-02 10:45:00 2.0 # Name: value, dtype: float64 # Resampling the series to the expected bin, say 15 min # filling with NaN un...
python|pandas|dataframe|datetime|time-series
0
352,881
60,815,938
How update weights of two separate neural network with a computed loss?
<p>I have an encoder and a proxy network that help the encoder to maximize information between its input(an image) and output (feature vector of image). to get this done, I used a loss function that estimate MI and by an optimizer the weights of both networks get updated with computed loss, but I'm not sure that does t...
<p>If you have multiple networks, this is an example of how they would train</p> <pre><code>encoder = Encoder(args).to(device) decoder = Decoder(args).to(device) params = list(encoder.parameters()) + list(decoder.parameters()) optimizer = torch.optim.Adam(params, learning_rate) </code></pre> <p>And this is called on...
deep-learning|pytorch|information-theory
1
352,882
61,054,174
Send a Keras model with gRPC
<p>I am trying to implement a Federated Learning system with gRPC. Tensorflow Federated currently supports multi-machine remote learning, but something looks weird to me that it prepares client dataset on the server side. I expected that the dataset for client only resides and is prepared only in client's device, not o...
<p>A quick note on TFF--currently many of the examples do have datasets materialized server-side, simply because of the FL-research-first design, for example improving federated optimization algorithms. TFF can currently support the kind of application desired here by simply using a different method to materialize data...
python|tensorflow|keras|protocol-buffers|grpc
1
352,883
60,824,064
Importing Pandas problems
<p>Although I have the latest version of Python, NumPy, Pandas, and SciPy installed, whenever I simply type <code>import pandas as pd</code>. I get the error:</p> <p><code>ModuleNotFoundError: No module named 'numpy.testing.decorators'</code> </p> <p>This is super strange since I used pandas earlier on in the day, an...
<p>Hopefully you weren't using your system's python when you did this. I would suggest using the <a href="https://www.anaconda.com/distribution/#download-section" rel="nofollow noreferrer">latest version of Anaconda for this</a>. when you restart the terminal after an install you can create an environment using</p> ...
python|pandas|numpy
1
352,884
60,854,228
Low validation accuracy after InceptionResNetV2 model transfer learning
<p>I need a Tensorflow model to classify images into 4 distinct categories for which I am doing transfer learning on pretrained InceptionResNetV2 model(weights='Imagenet'). During model.fit() I get an accuracy of 97.4% with loss of 0.3 while my validation accuracy remains stuck at 84% with a loss of 0.4. Am I overfitti...
<p>Try adding data augmentation to your code; that'll fix the overfitting issue. Something like the code below:</p> <pre><code>data_augmentation = tf.keras.Sequential([ tf.keras.layers.experimental.preprocessing.RandomRotation(0.01), tf.keras.layers.experimental.preprocessing.RandomContrast(0.25), tf.keras....
tensorflow|machine-learning|image-processing|keras|computer-vision
0
352,885
60,839,967
Keyword arguments in BERT call function
<p>In the HuggingFace TensorFlow 2.0 BERT library, the <a href="https://huggingface.co/transformers/model_doc/bert.html#tfbertmodel" rel="nofollow noreferrer">documentation</a> states that:</p> <blockquote> <p>TF 2.0 models accepts two formats as inputs:</p> <ul> <li><p>having all inputs as keyword arguments ...
<p>It seems that internally, they are interpreting the <code>inputs</code> as <code>input_ids</code>, if you do not put more than just a single tensor as the first argument. You can see this in <a href="https://huggingface.co/transformers/_modules/transformers/modeling_tf_bert.html#TFBertModel" rel="nofollow noreferrer...
tensorflow|nlp|arguments|huggingface-transformers
2
352,886
60,853,792
Handling multiple column headers and same column names in csv - pandas/python
<p>I have a csv file that looks like this </p> <pre><code> PROD1 PROD1 PROD2 PROD2 X Y X Y AA A 1 2 9 10 BB B 3 4 11 12 CC C 5 6 13 14 DD D 7 8 15 16 </code></pre> <p>The output I am tryin...
<p>You do not want to transpose the dataframe but stack one column level. Simply you must declare to pandas that the csv file has a 2 rows header:</p> <pre><code>data=pd.read_csv('transposedata.csv', header=[0,1]).stack(level=0).sort_index(level=2) </code></pre> <p>It should give:</p> <pre><code> X Y A...
python|pandas|csv
4
352,887
60,906,667
Is there a proper way to install tensorflow in Blender using python console?
<p>MY setup: </p> <p><strong>Blender 2.82</strong></p> <p><strong>Python 3.7.4</strong> </p> <p>I am trying to <em>pip install</em> tensorflow in blender</p> <pre><code> **pip.main(['install','tensorflow'])** </code></pre> <p><strong>However i receive this error and the tensorflow is not installing.</strong></p> ...
<p>Steps that solved my issue: - set the path of blender's python in environment variables: C:\Program Files\Blender Foundation\Blender 2.82\2.82\python\bin - where exe is located C:\Program Files\Blender Foundation\Blender 2.82\2.82\python\Scripts - go to python.exe folder in blender and sta...
python|tensorflow|blender
0
352,888
61,171,223
How can I read in row names as they were originally, using pandas.read_csv( )?
<p>I need to read in a .csv file which contains a distance matrix, so it has identical row names and column names, and it's important to have them both. However, the code below can only get me a dataframe where row names are included in an extra "Unnamed: 0" column and the index become integers again, which is very inc...
<p>Use <code>index_col=0</code> parameter for first column to index:</p> <pre><code>url = "https://raw.githubusercontent.com/PawinData/UC/master/DistanceMatrix_shortestnetworks.csv" DATA = pd.read_csv(url, index_col=0) </code></pre> <hr> <pre><code>print (DATA.head()) Imperial Kern Los Angeles Orange...
python|pandas|dataframe
1
352,889
60,940,266
Rotating a color clip in MoviePy?
<p>I'm trying to rotate a moviepy color clip without animating it, so that it is rotated at the start, and remains rotated until the end of the video.</p> <p>I tried some code hoping that it would rotate a still image in MoviePy, without animating it. So that it is rotated by the input angle for the entire duration o...
<p>Update 2: This fix is included in v2.0.0.dev1. Install from pip with <code>pip install --pre --upgrade moviepy</code>.</p> <p>Update: I’ve found the bug, and you can track the progress of the bug fix here: <a href="https://github.com/Zulko/moviepy/pull/1139" rel="nofollow noreferrer">https://github.com/Zulko/moviep...
python|numpy|python-imaging-library|moviepy
1
352,890
60,926,470
Pandas: Add bool column if two fields match in dataframes
<p>I'm new to pandas and struggling a little. I have two large dataframes with several 100000s lines. I extracted two columns of both and want to add a bool in the first dataset if two fields match exactly in both dataframes. As an example:</p> <pre><code> 0 1 0 a b 1 a c 2 a d 3 a e 4 b a 5 b b 6 b c...
<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 left join and no parameter <code>on</code> for join by intersection of columns in both <code>DataFrame</code>s, then <code>rename</code> column and test ...
python|pandas|statistics
3
352,891
61,110,186
Cannot improve model accuracy
<p>I am building a general-purpose NN that would classify images (Dog/No Dog) and movie reviews(Good/Bad). I have to stick to a very specific architecture and loss function so changing these two seems out of the equation. My architecture is a two-layer network with relu followed by a sigmoid and a cross-entropy loss fu...
<p>The issue you're facing is <strong>overfitting</strong>. With 100% accuracy on the training set, your model is effectively memorizing the training set, then failing to <strong>generalize</strong> to unseen samples. The good news is this is a very common major challenge!</p> <p>You need regularization. One method is...
python|machine-learning|computer-vision|pytorch
1
352,892
61,156,121
numpy ifft output has much larger power than original signal
<p>I'm having a weird problem using the numpy fft class. I have the following bit of test code:</p> <pre><code>import numpy as np import scipy.io.wavfile import matplotlib.pyplot as plt fs, a = scipy.io.wavfile.read('test.wav') # import audio file spectrum = np.fft.fft(a) # create spectrum b ...
<p>Okay I managed to find the solution myself in the end. </p> <p>The problem arises because the output of wavfile.read is an integer array. For some reason, the fft function handles integers in a different manner than floats. The problem is solved by typecasting a to an np.float64 type. </p> <p>Why this happens is s...
python-3.x|numpy|signal-processing|fft
0
352,893
61,056,780
counting the occurrences of a specific label in a sliding window
<p>I have the below DataFrame.</p> <pre><code> t_msec ID 0 1.1 0200 1 1.4 020a 2 8.9 01f4 3 11.1 0200 4 13.2 02e2 ... ... ... 85454 189915.3 02e4 85455 189915.6 02e6 85456 189921.8 0200 85457 189922.3 01f4 85458 189924.0 020a </code></...
<p>For my test I used the following DataFrame:</p> <pre><code> t_msec ID 0 60 0200 1 70 020a 2 445 01f4 3 555 0200 4 660 02e2 5 1005 0200 6 1510 02e2 7 2105 0200 8 2260 02e2 </code></pre> <p>So if we look for e.g. <em>ID == '0200'</em>, within <em>1 s</em> from the init...
python|pandas|dataframe|data-manipulation
0
352,894
60,823,457
Calculate linear percentage difference
<p>I have two related datasets, with one of them that can be slightly below 0. </p> <p>I am trying to calculate the 'linear' percent difference between the two.</p> <p>I have written some example code: perc[1] is the proper percentage method, however in the last two example cases, the percentage differences are not '...
<p>Referencing this <a href="https://en.wikipedia.org/wiki/Relative_change_and_difference" rel="nofollow noreferrer">Wikipedia article</a>, the <em>relative percentage</em> is, in general, of the form</p> <p>|x - y| / |f(x, y)|</p> <p>The absolute value in |x - y| can be removed if you have a reference point, so as t...
python|numpy|statistics
1
352,895
60,797,259
Remove all values below certain threshold and shift columns up in Pandas
<p>I have growth data. I would like to calibrate all the columns to a certain (arbitrary) cutoff by removing all values below this threshold and "shift" the values up in each individual column. </p> <p>To illustrate: </p> <pre><code>import pandas as pd df = pd.DataFrame([[1, 2], [3, 4],[5, 6]], columns=list('AB')) ...
<p>Use <code>justify</code> function for improve performance:</p> <pre><code>df = pd.DataFrame([[1, 2], [3, 4],[5, 6]], columns=list('AB')) df = df.where(df &gt; 3, np.nan) arr = justify(df.to_numpy(), invalid_val=np.nan, axis=0, side='up') #oldier pandas versions arr = justify(df.values, invalid_val=np.nan, axis=0, ...
python|pandas
1
352,896
60,894,148
How to access a valuein a Python dictionary of Pandas dataframes, modify the dataframe and update the dictionary value
<p>Quite new to Python, especially dictionaries and can't find anything specific about what I am trying to do.</p> <p>Essentially, I have an OrderedDict of Pandas Dataframes (a bunch of excel sheets that I read in and converted to dataframes) and I would like to individually access those dataframes, modify them and th...
<p>You can try this out with some sample data:</p> <pre><code>#DataFrames generated from the excel files value_df1 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns= ['a', 'b', 'c']) value_df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns= ['a', 'b', 'c...
python|pandas|dictionary
0
352,897
60,836,597
Iteration over a list in a Pandas DataFrame column
<p>I have a dataframe <code>df</code> as this one:</p> <pre><code> my_list Index 0 [81310, 81800] 1 [82160]...
<p>Write a helper: <code>def find_min(lst):</code> -- it is clear you know how to do that. The helper will consult a global named <code>code</code>.</p> <p>Then apply it:</p> <pre><code>df['my_min'] = df.my_list.apply(find_min) </code></pre> <p>The advantage of breaking out a helper is you can write separate unit te...
python-3.x|pandas|list-comprehension
1
352,898
60,950,352
How do I convert a column having month in a dataframe to alphabetical numbers (not numeric) based on a specific condition
<p>I have a dataframe in which a column contains months.</p> <p>I want to update values of months with alphabetical numbers (one, two, three, etc and not 1,2,3 etc) Is there any library that I can use to make this conversion for the entire column?</p> <p>P.S. - The column contains more than 1200 rows so there's no po...
<p>There is no library which will do this automatically for you. You have to give values for each month, since you mentioned you have month 'names' and not numbers. try this:</p> <pre><code>df['arrival_date_month'] = df['arrival_date_month'].str[:3] df.loc[df["arrival_date_month"] == "Jan", 'arrival_date_month'] = 'On...
python|pandas
3
352,899
61,066,142
unable to use tf.contrib
<p>I imported tensorflow module but I'm unable to use tf.contrib. I don't know what the problem is. I tried running it in different versions but I keep getting the same output.</p> <p>ModulesImported:</p> <pre><code>import tensorflow.compat.v1 as tf1 tf1.disable_v2_behavior() import tensorflow as tf2 </code></pre> ...
<p>I think the problem is in the version, i have tried it in 1.15.2 version and it worked for me. After installing the mentioned version try the below code, it should work.</p> <pre><code>import tensorflow.compat.v1 as tf1 tf1.disable_v2_behavior() import tensorflow as tf2 #Tensorflow 1.15.2 from tensorflow.contrib.r...
python|tensorflow|machine-learning|lstm|attributeerror
6