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
365,500
68,465,330
How to assign a set value to a column if a condition is met?
<p>I have a set of products that I need to assign google taxonomy codes to. All up there is roughly 213000 products I need to add these codes to. I have entered a small sample of 7000 into pandas to see if I can write something to run off keywords and assign a code to a column if the keyword is in found.</p> <p>I am st...
<p>Try:</p> <pre><code>conditions=['BRAKE','MIRROR','GENRIC','LIGHTS','SUSPENSION','TYRES'] labels=[2977,2642,5613,3318,2935,911] </code></pre> <p>Finally use <code>str.extract()</code> and <code>map()</code>:</p> <pre><code>pat='('+'|'.join(conditions)+')' product_data['googlecode']=product_data['category'].str.extrac...
python|pandas|bigdata
2
365,501
68,764,926
Add value or text to column a if condition in column b is met pandas
<p>I keep getting nan for this, so hoping for a quick fix.</p> <p>df:</p> <pre><code>cola colb 5 30 10 95 </code></pre> <p>I'd like to add 20 to cola if colb is between 90 and 100, like this:</p> <pre><code>cola colb 5 30 30 95 </code></pre> <p>Code i'm working with:</p> <pre><code>df['cola'...
<p>Use:</p> <pre><code># Create input dataframe using copy to clipboard df = pd.read_clipboard() df['colc'] = 'some text' # No need to iterate use pandas intrinsic data # alignment with the addition assignment operator df.loc[df['colb'].between(90,100), 'cola'] += 20 df.loc[df['colb'].between(90,100), 'colc'] += ', c...
python|pandas
2
365,502
68,481,424
Where does the "call" function used in TensorFlow?
<p>I am writing a RESNET but I can not understand where does the &quot;call&quot; function is used.</p> <p>Maybe this is automatically called by the TensorFlow, so it means we must write a function named &quot;call&quot;? If so, what should be the exact requirement for this &quot;call&quot; function? Thank you!!</p> <p...
<p>The call function is used in the following manner:</p> <pre><code>basic_block = BasicBlock() basic_block(args) </code></pre> <p>so it comes instead of:</p> <pre><code>basic_block.call(args) </code></pre>
python|function|tensorflow|keras|call
0
365,503
68,546,670
Fill dataframe values per column, by row index, if position is present in range
<p>I have a list of start and stop coordinates of ranges and would like to fill a pandas df according to their being present in a range.</p> <p>The numbers of rows are predetermined and filled with '0'. If for example a range is 1,3 for a column then rows (index) 1-3 would be filled with '1'.</p> <pre><code>d={ 'a'...
<p>You can do <a href="https://stackoverflow.com/questions/55681792/how-to-count-overlaps-and-find-overlapping-partners-for-pandas">something like this</a>:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd refpositions = pd.DataFrame({'pos':range(50)}) intervals = pd.arrays.IntervalArray([pd.Int...
python|python-3.x|pandas|bioinformatics
1
365,504
68,593,357
What is the difference between pd.isna for columns in single bracket vs multiple bracket? It does not return na values in multiple brackets
<p>while I was scripting a column, I came into something very interesting. There are two ways in which I was using pd.DataFrame.isna for single and multiple columns. While I am scripting in multiple brackets pd.df.isna is returning the entire code back to me.</p> <pre><code>override[override.ORIGINAL_CREDITOR_ID.notna(...
<p>So, I found a way where once I've got the data frame of True and False, I then take a bitwise operation by using all or any. You can refer to:</p> <pre><code>override[override[['ORIGINAL_CREDITOR_ID']].notna().all(1)].shape </code></pre> <p>This would help me in filtering the results I want and that too much faster ...
python|pandas|numpy|missing-data|isnan
0
365,505
68,788,774
Convert and replace a string value in a pandas df with its float type
<p>I have a value in pandas df which is accidentally put as a string as follows:</p> <pre><code>df.iloc[5329]['values'] '72,5' </code></pre> <p>I want to convert this value to float and replace it in the df. I have tried the following ways:</p> <pre><code>df.iloc[5329]['values'] = float(72.5) </code></pre> <p>also,</p>...
<p>iloc needs specific row, col positioning.</p> <pre><code>import pandas as pd df = pd.DataFrame( { 'A': np.random.choice(100, 3), 'B': [15.2,'72,5',3.7] }) print(df) df.info() </code></pre> <p>Output:</p> <pre><code> A B 0 84 15.2 1 92 72,5 2 56 3.7 &lt;class 'pandas.core.frame....
pandas
1
365,506
68,710,987
Python When match two columns then
<p>What is the equivalent of this code</p> <pre><code>df_train['uf'] = (df_train['home_score'] + df_train['away_score'] &lt; 4) * 1 </code></pre> <p>for</p> <pre><code>df_train['d'] = (df_train['home_score'] = df_train['away_score']) * 1 </code></pre> <p>When <code>True</code> = <code>1</code> when <code>False</code> =...
<p>The comparison operator is <code>==</code> not <code>=</code>:</p> <pre><code>df_train['d'] = (df_train['home_score'] == df_train['away_score']).astype(int) </code></pre> <p>or:</p> <pre><code>df_train['d'] = df_train['home_score'].eq(df_train['away_score']).astype(int) </code></pre> <p>or:</p> <pre><code>df.eval('h...
python|pandas|dataframe
3
365,507
68,607,955
Methods for increasing accuracying of a CNN for image classification
<p>I'm currently working on a image classification task, involving a large datasets of grayscale images of cartoons and my CNN needs to classify them. Atm my model has a test accuracy of about 88% but I know a higher accuracy is possible.</p> <p>I've tried:</p> <ul> <li>improving / changing the actual model / architect...
<p>From what you've described, it sounds like it might be worth spending some time on the data preparation. <a href="https://machinelearningmastery.com/best-practices-for-preparing-and-augmenting-image-data-for-convolutional-neural-networks/" rel="nofollow noreferrer">Here</a> is a good article on how to do that for im...
python|deep-learning|neural-network|pytorch|conv-neural-network
1
365,508
68,554,191
How can I convert a Data Frame to {"key":"xxxx","value":"xxxx"} structure?
<p>Let's say I have a Data Frame as follows:</p> <pre><code> id name dob 0 1 Joe 16 Jun 1999 1 2 John 04 Aug 1997 </code></pre> <p>Now I want this data frame to be transformed as follows:</p> <pre><code>{ &quot;items&quot;: [ { &quot;id&quot;: &quot;1&quot;, &quo...
<p>Here is a solution you can give it a try, using <code>list comprehension</code></p> <pre><code>dict_ = df.set_index('id').to_dict(orient='index') items = {&quot;items&quot;: [ {&quot;id&quot;: k, &quot;attributes&quot;: [{&quot;key&quot;: i, &quot;value&quot;: j} for i, j in v.items()]} for k, v in dict_.it...
python|pandas|dataframe|dictionary
1
365,509
68,773,573
How to do Linear Regression and get Standard Deviation (Python)
<p>I have this very simple problem, but somehow I have not found a solution for it yet:</p> <p>I have two curves, A1 = [1,2,3] A2 = [4,5,6]</p> <p>I want to fit those curves to another curve B1 = [4,5,3] with Linear Regression so B1 = a<em>A1 + b</em>A2</p> <p>This can easily be done with sklearn LinearRegression - but...
<p>If your formula is <code>B1 = aA1 + bA2</code>, then the array b is your endogenous and the array a is your exogenous. You need to transpose your exogenous:</p> <pre><code>ols = sm.OLS(b, a.T) res = ols.fit() res.summary() OLS Regression Results ==============...
python|numpy|statsmodels
1
365,510
68,797,184
regular expression x.group()
<p>Please advise the step by step that leads to the results which includes below question as well. Thanks!</p> <p><code>df['text'].str.replace(r'(\w+day\b)', lambda x: x.groups()[0][:3])</code></p> <ol> <li>What is the transformation of <code>Series.str</code>? I can't examine it.</li> <li>What is the <code>x</code> in...
<p>In complement to @AnuragDabas comment, here is a breakdown of the processing using python's <code>re</code> module:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = &quot;Monday: The doctor's appointment is at 2:45pm.&quot; &gt;&gt;&gt; re.search(r'(\w+day\b)', s) # find any word ending in &quot;day&quot; &lt...
pandas|python-re
1
365,511
68,630,503
Drawing Worldmap Whose Center Is Japan With Geopandas
<p><strong>Before reading my question, my english skill is poor, so please send me feedback or advise in easy words. Thank you.</strong></p> <h1>What I wand to do:</h1> <p>I want to draw an worldmap whose center is Japan with geopandas library on python 3.x.</p> <h1>My Environment:</h1> <ul> <li>Windows10 (64bit)</li> ...
<p>I found working with <code>geopandas</code> (+ <code>pyproj</code> as its dependency) to get the shifted map is too difficult. In my code below, <code>geopandas</code> is used to provide the geodataframe of the world to manipulate and plot. <code>Cartopy</code> is used to provide the <code>geoaxis</code> for proper ...
python-3.x|windows|geopandas
1
365,512
68,549,118
pandas.read_sql not returning all records
<p>I have a complex query that I'm running against a SQL Server database. When I run that query in SSMS, it returns 15,652 rows.</p> <p>However, when I use that query in my python it only returns 10,617 records. This only started happening recently.</p> <p>This is how I'm executing the query in python:</p> <pre><code>d...
<p>Nevermind. My code was pointing to an old version of the query. It's working fine.</p>
python|sql-server|pandas|sqlalchemy
0
365,513
68,454,396
Rename columns of excel using Pandas
<p>I am learning pandas for data cleaning. I am reading one excel file like below.</p> <p><a href="https://i.stack.imgur.com/8mIhz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8mIhz.png" alt="Excel Image" /></a></p> <p>What I am looking to do is to rename column names like, <em><code>First Cost Q3...
<p>You can rename a column name by using:</p> <p><code>df.rename(columns = {'Q3 2020':'First Cost Q3 2020'}, inplace = True)</code></p> <p>To update all column names, you can do this:</p> <p><code> df.columns = ['First Cost Q3 2020', 'First Cost Q4 2020', 'First Cost Q1 2021']</code></p>
python|pandas|dataframe
2
365,514
68,464,454
python rand function conditional operator combination
<p>what does this line of code actually do? Case 1: if number returned by the rand function is <strong>less than 0.8</strong> what it does? Case 2: if number returned by the rand function is <strong>greater than 0.8</strong> what it does? Here is the line of code - <strong>msk = np.random.rand(len(df)) &lt; 0.8</strong...
<pre><code>Case 1: if number returned by the rand function is less than 0.8 what it does? &gt; The code will return 'True' because the value is less than 0.8 Case 2: if number returned by the rand function is greater than 0.8 what it does? &gt; Again the result will be 'False' as the value here is outside the scope...
python|numpy
0
365,515
68,764,828
Using grouper for two groups or more in gives the wrong plot pandas
<p>I have the following dataset:</p> <pre><code>my_df = pd.DataFrame({'id':[1,2,3,4,5,6,7,8], 'date':['2019-01-01 07:59:54','2019-01-01 08:00:07','2019-01-01 08:00:07', '2019-01-02 08:00:14','2019-01-02 08:00:16','2019-01-02 08:00:24', '2...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html" rel="nofollow noreferrer"><code>unstack</code></a> <code>group</code> after <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.count.html" rel="nofollow noreferrer"><code>gr...
python|pandas
1
365,516
68,604,098
Parse output to dataframe
<p>I need to parse a BOT output and convert to a table format. Below is the link to the raw file and also it looks like this</p> <p><a href="https://www.dropbox.com/s/ab7sdl74krwltrd/raw_file.txt?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/ab7sdl74krwltrd/raw_file.txt?dl=0</a></p> <pre><code>Invoice: 1361...
<p>Try this code</p> <pre><code>import pandas as pd filename = 'Completed_07202021.csv' a_list = ['Invoice'] a_list.extend(['HEAD Segment '+ str(x) for x in range(1,100 + 1)]) a_list.extend(['BODY Segment '+ str(x) for x in range(1,10 + 1)]) df = pd.DataFrame(columns = a_list) l = [] l.append(df) out={} wit...
python|python-3.x|pandas|parsing
1
365,517
68,805,223
pandas Int64 data type fails in the describe or quantile functions
<p>My pandas problem is with the use of the describe() function and pandas nullable integer data type, Int64 (or Int32). I believe that I have a data problem but am lost on how to find the data causing the problem. Alternatively, does pandas have a bug computing of percentile statistics?<br/></p> <p>I created a panda...
<p>I am using pandas version: 1.3.1. The csv file is available at <br> <a href="https://data.cdc.gov/api/views/8xkx-amqh/rows.csv?accessType=DOWNLOAD" rel="nofollow noreferrer">https://data.cdc.gov/api/views/8xkx-amqh/rows.csv?accessType=DOWNLOAD</a> <br><br> I have re-read the data but specified the data type to be an...
python|pandas
1
365,518
68,826,508
How can I replace a string in all column headers of a Pandas Dataframe?
<p>I'm using Python in Databricks on Azure. I've attempted to use <em>str.replace</em> but I get an error saying that the column names are not string type. The original file was uploaded as a <em>parquet</em> file; I'm not sure if this has something to do with the string error. Any ideas on how to remove the first two ...
<p>$ has a special meaning in str.replace. Best to escape it using a backslash as follows.</p> <pre><code>df.columns = df.columns.str.replace('T\$', '') </code></pre>
python|pandas|apache-spark|pyspark
1
365,519
68,607,475
count plot for each categorical variable
<p>I have a dataset as below, where Q1,Q2,Q3 are categorical.</p> <pre><code> Q1,Q2,Q3 0 4,1,5 1 1,5,1 2 1,2,1 3 1,4,1 4 5,1,5 </code></pre> <p>How can I plot the x axis for each column, and y as the count of the value for each column, all in one plot.</p> <p>Sample out put</p> <p><a href="https://i.sta...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>value_counts</code></a> on the columns and then plot:</p> <pre><code># grouped by quartile df.apply(pd.Series.value_counts).T.plot.bar() </code></pre> <p><a href="https://i.stack.imgur.c...
python|pandas
1
365,520
68,529,702
Loop on pandas DataFrame
<p>I would like to run a loop over rows of pandas DataFrame such that based on indices in columns <code>a</code> and <code>b</code> I can sum the values given in column <code>f</code> and can tag them in a separate column by a string name.</p> <pre><code> a b c d e f 0 1.0 2.0 0 0 0 2.567483 1 1....
<p>You can use <code>iterrows()</code>:</p> <pre><code>import pandas as pd df = pd.DataFrame({'a': [10, 11, 12], 'b': [100, 11, 120], 'f': [100, 110, 120]}) for index, row in df.iterrows(): if row['a'] == row['b']: print(row['f']) </code></pre> <p>Outputs:</p> <pre><code>110 </code></pre> <p>Or you can us...
python|pandas|dataframe|loops|sum
0
365,521
68,681,808
Splitting dataframe in smaller dataframe when value in column match and export them to excel fromat (pandas)
<p>I have a dataframe A. I need to divide it in smaller dataframes with matching street names.</p> <p>Here is the dataframe I have:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>Location_name</th> <th>Street_Number</th> <th>Street_name</th> <th>Object_needed</th> </tr> </thead...
<p>If you want your streets in seperate excel sheets in one file, you can use the Pandas ExcelWriter:</p> <pre><code>streets = set(df.Street_name) with pd.ExcelWriter('all_streets_excel.xlsx', mode='w') as writer: for street_name in streets: street_df = df[df.loc[:, 'Street_name'] == street_name] st...
python|pandas|dataframe|google-colaboratory|export-to-excel
0
365,522
68,525,151
RuntimeError: expand(torch.cuda.FloatTensor{[3, 3, 3, 3]}, size=[]): the number of sizes provided (0) must be >= number of dimensions in the tensor(4)
<p>Why <em>[3, 3, 3, 3]</em> for the <a href="https://github.com/promach/gdas/blob/main/gdas.py#L469" rel="nofollow noreferrer">variable w</a> ?</p> <p><a href="https://i.imgur.com/CkYXEhf.png" rel="nofollow noreferrer"><img src="https://i.imgur.com/CkYXEhf.png" alt="runtime_error" /></a></p>
<p>Problem is solved using <a href="https://github.com/promach/gdas/commit/6ccc7ac0e19f36042b70ae6beecf92895733cbe4" rel="nofollow noreferrer">this github commit</a></p>
python|pytorch
-1
365,523
68,805,056
Python plot 1D array
<p>I would like to plot the difference between each individual point.</p> <p>I have one series <code>y_test</code> which is one-dimensional and contains continuous values. The index is kinda whacky (<code>7618, 276, 7045, 6095, 2296, 7191, 1213, 2408...</code>).</p> <p>And I have another numpy array ypred which is one...
<p><code>plt.scatter(y_test, y_pred)</code>?</p> <p>Many points close to the equality line (diagonal) means good predictions, far away means not so good.</p>
python|numpy|matplotlib|plot|data-visualization
2
365,524
68,677,510
How to make clustered heatmap of a large dataset look nicer?
<p>I have a distance matrix which I normalized, trimmed the row and column headers with python regular expressions and tried to make a clustered heatmap from it with the following code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns df = pd.read_csv('distan...
<p>The problem is in your <code>vmax = 1</code> argument. If you look at the maximum value in the whole dataset using <code>new_matrix.max().max()</code> , it is about 0.17. So, just removing vmax as:<a href="https://i.stack.imgur.com/BufIT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BufIT.png" a...
python|pandas|matplotlib|seaborn
0
365,525
68,466,828
Can't get output shape of a keras layer inside a custom layer
<p>I am using Keras custom layer built form multiple Keras layers. I am trying to get the output_shape of the inner layers form a callback (on_train_batch_end) and get the following error: &quot;AttributeError: The layer has never been called and thus has no defined input shape.&quot;</p> <p>I don't understand how this...
<p>It is not really an answer but I will share my workaround for other people. The idea is just to calculate the sizes on dummy data and save them.</p> <pre><code>def _calculate_shape(self, input_tensor_shape: tf.TensorShape): self.conv.trainable = False self.m_max.trainable = False self.relu.trainable = Fa...
tensorflow|keras
0
365,526
68,868,309
df fill up values
<p>I have the following df in python:</p> <pre><code>Course |Student 1 | Student 2 | Student 3 --------|----------|-----------|--------- Course2 | 1.1 | empty | empty Course2 | empty | 5.3 | empty Course2 | empty | empty | 4.2 </code></pre> <p>However, I want to have the following df:</p> <pre...
<p>As numbers evaluate before letters, you can groupby &quot;Course&quot; and take the min:</p> <pre><code>df.groupby('Course').agg('min') </code></pre>
python|pandas|dataframe
3
365,527
68,719,486
ChecksumMismatchError: Conda detected a mismatch between the expected content and downloaded content
<p>I have installed many many packages including <code>torch, gpytorch, ...</code> in the past in Windows, Ubuntu and Mac following this scenario:</p> <pre class="lang-sh prettyprint-override"><code>conda create -n env_name conda activate env_name conda install pytorch torchvision torchaudio cudatoolkit=11.1 -c pytorch...
<p>The PyTorch channel maintainers had an issue when uploading some new package builds, which has since been resolved (see <a href="https://github.com/pytorch/pytorch/issues/63006" rel="nofollow noreferrer">GitHub Issue</a>). The technical cause was uploading new builds with identical versions and build numbers as bef...
python|pytorch|conda|torch
1
365,528
68,783,406
How to delete a certain value from all columns in a dataframe?
<p>I need to delete a certain value from all the column in my data frame.</p> <p>Data frame description:</p> <pre><code> Data columns (total 13 columns): Column Non-Null Count Dtype --- ------ -------------- ----- 1 age_group_5_years 34842 non-null int64 ...
<p>I'm reading between the lines here: assuming the OP wants to drop all rows where at least one column contains <code>9</code> (<code>int</code>) or <code>9.0</code> (<code>float</code>) or <code>9 + 0j</code> (<code>complex</code>):</p> <pre class="lang-py prettyprint-override"><code>df_new = df.replace(9, np.NaN).dr...
python|pandas|dataframe
1
365,529
68,559,291
KeyError in Pandas for a correct key
<p>Code run in jupyter notebook</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np myindex = ['USA','Canada','Mexico'] mydata = [1776,1867,1821] myser = pd.Series(data=mydata,index=myindex) myser['USA'] </code></pre> <p>code image <img src="https://i.stack.imgur.com/5ehY8.png" al...
<p>Try running the code you have mentioned as 'Code in Jupyter' it will run. In your image you have not assigned the pd.series to a variable. That is the issue.</p> <p>I have tried the following and it works:</p> <pre><code>import pandas as pd my_index = ['Usa', 'Canada', 'Mexico'] my_data = [10, 20, 30] my_ser_1 = pd....
python|pandas|jupyter-notebook|series|keyerror
1
365,530
68,598,205
Python, Pandas dataframe, merge dataframe's rows that have same two column values and aggregate data in rows
<p>I have this DF and I am trying to merge any two rows with similar <code>workDate</code> and <code>ID</code>. I do not know how many columns this DF will have. it might have hundreds of columns so I am looking for a way to merge without having to specify all column names</p> <pre><code> |workDate |ID | Hou...
<p><strong>Try:</strong></p> <pre><code>import pandas as pd import numpy as np #only required because the example df creation needs np.nan df = pd.DataFrame({'workDate': {0: '2020-01-09', 1: '2020-01-09', 2: '2020-01-10', 3: '2020-01-10', 4: '2020-01-10'}, 'ID': {0: 13702, 1: 13702, 2: 13702, 3: 13702, 4: 137...
python|python-3.x|pandas|dataframe|pandas-groupby
3
365,531
68,517,741
Extracting all 10 digit numbers from a data frame entry (text)
<p>I have a pandas data frame with just one column which contains text (words and numbers). I want to extract all 10 digit numbers from the text but can't manage to convert the pd.series object in an iterable object like a list.</p> <p>I tried something like:</p> <pre><code>def find_number(text): num = re.findall(r...
<p>Change the regex from <code>'[0-9]+'</code> to <code>'\d{10}'</code> to get only results with 10 digits and remove <code>&quot; &quot;.join()</code> to leave the results as list</p> <pre><code>def find_number(text): return re.findall(r'\d{10}', text) df['List1'] = df['Header 1'].apply(lambda x: find_number(x)) ...
python|pandas|dataframe|object
2
365,532
68,699,028
cannot import name 'get_config' from 'tensorflow.python.eager.context'?
<p>I'm trying to follow this repo's tutorial on colab<a href="https://github.com/divamgupta/image-segmentation-keras" rel="nofollow noreferrer">https://github.com/divamgupta/image-segmentation-keras</a></p> <p>but I'm getting this error again and again</p> <pre><code>cannot import name 'get_config' from 'tensorflow.pyt...
<p>From comments</p> <blockquote> <p>It was just a matter of version with <code>tensorflow</code> and <code>keras</code>. I looked into traceback tensorflow error messages and opened it and changed <code>import keras</code> to <code>from tensorflow import keras</code> issue was resolved (Paraphrased from z2ouu).</p> </...
tensorflow|keras|conv-neural-network|google-colaboratory|semantic-segmentation
1
365,533
68,719,305
Find minimum for every row in array with unique columns
<p>I need to find the row-wise minimum in an array where each minimum must stem from a unique column.</p> <p><code>np.min(arr, axis=1)</code> provides the row-wise minimum but might contain the same column several times.</p> <p>For example, given:</p> <pre><code>a = np.array([ [4, 5, 6], [1, 2, 3], [7, 8, 9...
<p>It appears that what you're looking for are N minimum values where the row and column index for each value is unique (assuming an NxN matrix). If we tag each value in the matrix with it's initial coordinates, we can rearrange them without losing the ability to tell where they came from. I'm not sure there's a slick ...
python|arrays|numpy|constraints|minimum
1
365,534
36,655,525
pass openpyxl data to pandas
<p>I am splitting &quot;full name&quot; fields into &quot;first name&quot;, middle name&quot; and &quot;last name&quot; fields from data from an excel file. I couldn't figure out how to do that in pandas, so I turned to openpyxl. I got the variables split as I desired. But, <a href="https://groups.google.com/forum/#!to...
<p>A couple of things. First, your code is only ever going to get you one line, because you overwrite the values every time it passes an if test. for example,</p> <pre><code> if len(namelist) == 2: lastname = namelist[1] </code></pre> <p>This assigns a string to the variable <code>lastname</code>. You are no...
python|excel|pandas|openpyxl
4
365,535
36,364,188
Python - dataframe conditional index value selection
<p>I have a dataframe similar to the below:</p> <pre><code> close_price short_lower_band long_lower_band Equity(8554) 180.530 184.235603 183.964306 Equity(2174) 166.830 157.450404 157.160282 Equity(23921) 124.670 127.2434...
<p>try this:</p> <pre><code>In [334]: df Out[334]: close_price short_lower_band long_lower_band Equity(8554) 180.53 184.235603 183.964306 Equity(2174) 166.83 157.450404 157.160282 Equity(23921) 124.67 127.243468 126.072039 Equity(26807) ...
python|numpy|pandas|dataframe
0
365,536
36,428,157
Understanding Tensorflow LSTM models input?
<p>I have some trouble understanding LSTM models in TensorFlow.</p> <p>I use the <a href="http://tflearn.org/" rel="nofollow noreferrer">tflearn</a> as a wrapper, as it does all the initialization and other higher level stuff automatically. For simplicity, let's consider <a href="https://github.com/tflearn/tflearn/blo...
<p>Basically, lstm takes the size of your vector for once cell:</p> <pre><code>lstm = rnn_cell.BasicLSTMCell(lstm_size, forget_bias=1.0) </code></pre> <p>Then, how many time series do you want to feed? It's up to your fed vector. The number of arrays in the <code>X_split</code> decides the number of time steps:</p> ...
python|machine-learning|tensorflow|deep-learning|lstm
-1
365,537
36,565,430
Adding multiple layers to TensorFlow causes loss function to become Nan
<p>I'm writing a neural-network classifier in TensorFlow/Python for the <a href="http://yaroslavvb.blogspot.kr/2011/09/notmnist-dataset.html">notMNIST</a> dataset. I've implemented l2 regularization and dropout on the hidden layers. It works fine as long as there is only one hidden layer, but when I added more layers...
<p>Turns out this was not so much a coding issue as a Deep Learning Issue. The extra layer made the gradients too unstable, and that lead to the loss function quickly devolving to NaN. The best way to fix this is to use <a href="https://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflo...
python|neural-network|tensorflow|deep-learning
19
365,538
36,425,234
Loop over dataframe, calculate correlation between columns for unique values of column?
<p>I've got a dataframe that looks like this (but longer...):</p> <pre><code> imd code sum 0 1 010101 1048171 1 2 010101 911003 2 3 010101 852023 3 4 010101 790893 4 5 010101 923344 5 6 010101 681473 6 7 010101 600303 7 8 010101 ...
<p>I've apparently understood the question differently than the others. IIUC, what you want is, per <code>code</code> value, treat the other two columns as vectors, and find their correlation coefficient. This would be something like:</p> <pre><code>import numpy as np &gt;&gt;&gt; df.groupby(df.code).apply(lambda g: ...
python|pandas
2
365,539
36,465,481
Equivalent for str.join in pandas
<p>Is there a clean way to concatenate an arbitrary number of string series similar to the <code>' '.join</code> idiom? If I know the columns I want in advance I can do </p> <pre><code>import pandas as pd df = pd.DataFrame([['word1','word2', 'word3']]) df[0] + ' ' + df[1] + ' ' + df[2] 0 word1 word2 word3 </code><...
<p>If you don't mind about space at the end of your rows you could use <code>sum</code> which is a bit faster then manually typing <code>df[0] + ' ' + df[1] + ' ' + df[2]</code>:</p> <pre><code>In [25]: (df + ' ').sum(axis=1) Out[25]: 0 word1 word2 word3 dtype: object </code></pre> <p>Hovewer, if you need to strip...
python|pandas
3
365,540
36,438,276
applymap - filling data frame with values from exponential distribution
<p>I want to fill my data frame with values from exponential distribution. As I understood, it can be done like that:</p> <pre><code>cumLosses1 = pd.DataFrame(np.zeros((size,size))) cumLosses1.applymap(np.random.exponential(scale = 1.0)) </code></pre> <p>As mentioned in documentation, applymap applies a function to a...
<p><code>np.random.exponential(scale=1.0)</code> isn't callable. You want:</p> <p><code>lambda x: np.random.exponential(scale=1.0)</code>, which can be "called" with every element in your series, even if those elements are not used.</p> <p>It'd would be much less convoluted, however, to do this:</p> <p><code>cumLoss...
python|pandas
0
365,541
36,674,322
Setting the TensorFlow is_training training flag (in batch_normalize)
<p>I'd like to use batch normalization in TensorFlow and came across this <code>batch_normalize</code> function on the GitHub: <a href="https://github.com/tensorflow/tensorflow/blob/e8494eacfb552c4bf33c15657238aabecc2a6343/tensorflow/contrib/learn/python/learn/ops/batch_norm_ops.py" rel="nofollow" title="link">link</a>...
<p>That function is part of scikit-flow a.k.a TF learn, not "base" TF - you can see how they set the flag in the estimator part of the library: <a href="https://github.com/tensorflow/tensorflow/blob/ec0552f1bc0e7c6ec6bd84ea1c3c92ff046d6d3c/tensorflow/contrib/learn/python/learn/estimators/base.py" rel="nofollow">GitHub ...
python|tensorflow
0
365,542
36,593,552
Saving a pandas dataframe into sqlite with different column names?
<p>I have a a sqlite database and dataframe with different column names but they refer to the same thing. E.g. </p> <ol> <li><p>My database Cars has the car Id, Name and Price.</p></li> <li><p>My dataframe <em>df</em> has the car Identity, Value and Name.</p></li> </ol> <p>Additional : I would also like to add an ad...
<p>You can do:</p> <p><code>cur.executemany("INSERT INTO Cars (Id, Name, Price) VALUES(?,?,?)", list(df.to_records(index=False)))</code></p> <p>Besides, you should specify the <code>dtype</code> attribute of your dataframe as <code>numpy.int32</code> to meet the constraint of table 'Cars'</p> <pre><code>con = sqlite...
python|pandas|sqlite
0
365,543
36,462,962
Loss clipping in tensor flow (on DeepMind's DQN)
<p>I am trying my own implementation of the DQN paper by Deepmind in tensor flow and am running into difficulty with clipping of the loss function. </p> <p>Here is an excerpt from the nature paper describing the loss clipping:</p> <blockquote> <p>We also found it helpful to clip the error term from the update to be...
<p>I suspect they mean that you should clip the <em>gradient</em> to [-1,1], not clip the <em>loss function</em>. Thus, you compute the gradient as usual, but then clip each component of the gradient to be in the range [-1,1] (so if it is larger than +1, you replace it with +1; if it is smaller than -1, you replace it...
neural-network|tensorflow|deep-learning|conv-neural-network
15
365,544
36,500,348
convert a SAS datetime in Pandas
<p>I am using <strong>Pandas</strong> to read a <strong>Sas</strong> dataset using <code>read_sas</code></p> <p>There is a datetime variable in the SAS dataset, which appears in Pandas as:</p> <p><code>1.775376e+09</code></p> <p>Once I convert it to <code>str</code> the date is:</p> <p><code>1775376002.0</code></p>...
<blockquote> <p>SAS date value</p> <p>is a value that represents the number of days between January 1, 1960, and a specified date. <a href="https://v8doc.sas.com/sashtml/lrcon/zenid-63.htm" rel="nofollow noreferrer">link</a></p> </blockquote> <p>So you can convert number <a href="http://pandas.pydata.org/pandas-docs/st...
python|datetime|pandas|sas
11
365,545
36,624,862
Choose Pandas dataframe index after which data in a column is all higher than a specific value
<p>I have a dataframe in pandas, something like:</p> <pre><code>df.head() P1'S1 P1'S2 P1'S3 P1'S4 Year_Day_Hour_Min_Sec. 2005-01-20 00:01:00 10.292887 5.849372 5.154812 5.824268 2005-01-20 00:02:00 ...
<p>This is a little indirect, but if we take the cumulative minimum of the reversed column, we'll know the lowest value seen at or beyond that point. The first value of <em>that</em> which is > 400 is the location you're looking for:</p> <pre><code>&gt;&gt;&gt; ((df["P1'S1"].iloc[::-1].cummin().iloc[::-1]) &gt; 400)....
python|pandas|dataframe|comparison
2
365,546
36,482,559
Python. Get structure from a data.frame
<p>In <a href="/questions/tagged/r" class="post-tag" title="show questions tagged &#39;r&#39;" rel="tag">r</a>, with the <code>str()</code> function you can see structure from an object like this:</p> <pre><code>&gt; str(mari) 'data.frame': 25834 obs. of 6 variables: $ Xcoor: num 0.0457 0.0469 0.0481 0.0495 0.051...
<p>I realize this is an old question, but wanted to provide clarification for anyone else that comes across this question in the future like I did.</p> <p>As MaxNoe said, <code>pandas</code> is what is needed and the <code>pandas.DataFrame.info</code> method is the equivalent to the <code>str()</code> function in R.</...
python|r|pandas
23
365,547
36,453,144
Manipulating nested numpy array
<p>I have a numpy array: </p> <pre><code>array([[ 0, 1, 2, 3, 4, 5, 6], [14, 15, 16, 17, 18, 19, 20], [28, 29, 30, 31, 32, 33, 34]]) </code></pre> <p>I want to divide elementwise by 10 and then round elementwise (&lt;0.5 rounding down to 0).</p>
<p>try:</p> <pre><code>import numpy as np array = np.array([[ 0, 1, 2, 3, 4, 5, 6], [14, 15, 16, 17, 18, 19, 20], [28, 29, 30, 31, 32, 33, 34]], dtype=float) result = np.round(array / 10) </code></pre> <p><code>result</code> will be <code>array([[ 0., 0., 0., 0., 0., 0....
python|arrays|numpy|multidimensional-array
1
365,548
36,365,118
How do you write and retrieve TFRecord features that are lists?
<p>I have a CNN model that takes N classification labels per training example and I am trying to create TFRecords from my data set that have a label feature that is a list of int64s.</p> <p>On the shard creation side I am using something like the following. I have put the label data explicitly in the code but obviousl...
<p>Try setting default value= [-1]*4</p>
tensorflow
3
365,549
36,435,100
Permute groups in Pandas
<p>Say I have a <code>Pandas</code> <code>DataFrame</code> whose data look like</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd n = 30 df = pd.DataFrame({'a': np.arange(n), 'b': np.random.choice([0, 1, 2], n), 'c': np.arange(n)}) </code>...
<p>Here's an answer inspired by the accepted answer to <a href="https://stackoverflow.com/questions/13838405/custom-sorting-in-pandas-dataframe">this SO post</a>, which uses a temporary <a href="http://pandas.pydata.org/pandas-docs/stable/categorical.html" rel="nofollow noreferrer"><code>Categorical</code></a> column a...
python|pandas
2
365,550
36,440,177
Use Python/Pandas indexed date as condition in holiday list
<p>I'm opening a CSV file with two columns and about 10,000 rows. The first column has a unique date and time stamp (ascending in 30-minute intervals, called 'date_time') and the second column has an integer, 'intnum'. I use the date_time column as my index and then use conditions to sum only the integers that fall i...
<p>Can't you just access the date from your timestamp and see if it is in your list of federal holidays? I don't know why you need your second integer index column; I would think a boolean value should suffice (e.g. fed_holiday).</p> <pre><code>df = pd.DataFrame(pd.date_range(start='2016-1-1', end='2016-12-31', freq=...
python|pandas|conditional
1
365,551
36,601,956
How can I iterate through multiple dataframes to select a column in each in python?
<p>For my project I'm reading in a csv file with data from every State in the US. My function converts each of these into a separate Dataframe as I need to perform operations on each State's information.</p> <pre><code>def RanktoDF(csvFile): df = pd.read_csv(csvFile) df = df[pd.notnull(df['Index'])] # drop all...
<p>One way would be to index into vars(), e.g.</p> <pre><code>for name in dfList: newIndex = vars()[name]["Population"] </code></pre> <p>Alternatively I think it would be neater to store your dataframes in a container and iterate through that, e.g.</p> <pre><code>frames = {} for name, s in zip(glob.glob('*.csv'...
python|pandas|dataframe|analytics|jupyter
4
365,552
5,330,368
Python: how to convert a complex array to a 2D array?
<p>As a C++ programmer, I'm used to access vectors in C++ style:</p> <pre><code>for (i=0; i&lt;max_x; i++) { for (j=0; j&lt;max_y; j++) { vec[i][j] = real(complex_number(j+i*max_x)) } } </code></pre> <p>Now I have in Python</p> <pre><code> x = np.linspace(x1, x2, step) y = np.linspace(y1, y2, step) ...
<p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="nofollow"><code>reshape</code></a> to turn a 1D array to 2D (or any other shapes).</p> <pre><code>&gt;&gt;&gt; x_max = 12 &gt;&gt;&gt; y_max = 4 &gt;&gt;&gt; vec1d = np.arange(x_max*y_max, dtype=complex) &gt;&gt;&gt; vec1d.res...
python|numpy|scipy
2
365,553
5,205,345
Using numpy.bincount with array weights
<p>I would like to use <code>bincount</code> to sum arrays, however it supports only doubles. For example this works:</p> <pre><code>np.bincount([1, 1, 0],weights=np.array([1, 2, 4])) Out: array([ 4., 3.]) </code></pre> <p>However I would like to use a dimension 2 array as:</p> <pre><code>np.bincount([1, 1, 0],weig...
<p>As per the numpy documentation:</p> <pre><code>numpy.bincount(x, weights=None, minlength=None) </code></pre> <blockquote> <p>weights : array_like, optional; <strong>Weights, array of the same shape as x.</strong></p> </blockquote> <p>So you can't use <code>bincount</code> directly in this fashion unless you a...
python|numpy
3
365,554
4,974,290
Reading non-uniform data from file into array with NumPy
<p>Suppose I have a text file that looks like this:</p> <blockquote> <p>33 3<br> 46 12<br> 23 10 23 11 23 12 23 13 23 14 23 15 23 16 24 10 24 11 24 12 24 13 24 14 24 15 24 16 25 14 25 15 25 16 26 16 27 16 28 16 29 16<br> 33 17 33 18 33 19 34 17 34 18 34 19 35 17 35 18 35 19 36 19<br> 41 32 41 33 42 32 42 ...
<p>Here's a one-liner:</p> <pre><code>arrays = [np.array(map(int, line.split())) for line in open('scienceVertices.txt')] </code></pre> <p><code>arrays</code> is a list of numpy arrays.</p>
python|file-io|numpy
17
365,555
53,025,739
Create a new Pandas df column with boolean values that depend on another column
<p>I need to add a new column to a Pandas dataframe. </p> <p>If the column "Inducing" contains text (not empty and not "") I need to add a 1 otherwise 0 </p> <p>I tried with </p> <p><code>df['newColumn'] = np.where(df['INDUCING']!="", 1, 0)</code> </p> <p>This command works only for the values that are Strings ...
<p>By <a href="https://en.wikipedia.org/wiki/De_Morgan%27s_laws" rel="nofollow noreferrer">De Morgan's laws</a>, NOT(cond1 OR cond2) is equivalent to AND(NOT(cond1) AND NOT(cond2)).</p> <p>You can combine conditions via the bitwise "and" (<code>&amp;</code>) / "or" (<code>|</code>) operators as appropriate. This gives...
python|pandas
2
365,556
53,015,716
Gensim LDA model topic diff resulting in nan
<p>I am pretty new at topic modeling and Gensim. So, I am still trying to understand many of concepts. I am trying to run gensim's LDA model on my corpus that contains around 25,446,114 tweets. I created a streaming corpus and id2word dictionary using gensim. I am using num_topics = 100, chunk size = 85000 (loading 850...
<p>From what I have understood reading the thread in Gensim Github Issues page <a href="https://github.com/RaRe-Technologies/gensim/issues/217" rel="nofollow noreferrer">issue 217</a> it seems that is a bug and some people there have reported that the problem was resolved by changing some of the parameters. Please firs...
python|python-3.x|numpy|gensim|lda
0
365,557
53,114,814
Given program for replace string with sequence of number should be written in pandas
<p>Hello everyone i have a program that read the csv file and replace the string to squence of number and it have other column like date/time which is have to print date only for all operation this program working very well but i want to this program in Pandas dataframe please can somebody take this code and use all o...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>split</code></a> with <code>str[0]</code> for select first lists and replace by datetime converted to strings by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Times...
python|pandas
4
365,558
53,128,407
Tensorflow. NxD matrix multiply NxD matrix to give NxDxD matrix
<p>for example</p> <pre><code> A=[[3,2], [1,3], [4,3]] B=[[4,1], [2,1], [2,4]] </code></pre> <p>For each row vector of matrix; I want to perform column-row multiplication</p> <pre><code>result = [] for i in range(3): x = tf.matmul(tf.reshape(A[i],[2,1]), tf.reshape(B[i],[1,2])) # g...
<p>Luckily, Tensorflow supports "batched" matrix multiplies, so the following should be sufficient:</p> <pre><code>A = tf.placeholder(tf.float32, [3,2]) B = tf.placeholder(tf.float32, [3,2]) AA = tf.reshape(A,[3,2,1]) BB = tf.reshape(B,[3,1,2]) print(tf.matmul(AA,BB)) &gt;&gt;&gt; &lt;tf.Tensor 'MatMul_1:0' shape=(3, ...
python|tensorflow
0
365,559
53,044,548
How to extract domain from email address with Pandas
<p>I have no idea to extract domain part from email address with pandas. In case if it is 'kkk@gmail.com' I would like to get 'gmail.com'.</p> <p>Please give me an idea.</p>
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="noreferrer"><code>split</code></a> and select second value of lists by indexing:</p> <pre><code>df = pd.DataFrame({'email':['kkk@gmail.com','aa@yahoo.com']}) df['domain'] = df['email'].str.split('@'...
pandas|python-3.6
16
365,560
53,095,983
Select complement columns between DataFrames
<p>Say I have a pandas.DataFrame <code>x</code>, <code>x</code> was fed to function <code>filter</code> and returned <code>y</code>, a DataFrame with some columns from <code>x</code> removed. The function is a blackbox and the column number is large. How could I find the columns in 'x' that are removed?</p> <p>Or, <co...
<p>Use <a href="https://docs.python.org/3/library/stdtypes.html#set" rel="nofollow noreferrer"><code>sets</code></a> or pandas <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.difference.html" rel="nofollow noreferrer"><code>difference</code></a> as:</p> <pre><code>x[x.columns.difference(y....
python|pandas|dataframe
1
365,561
53,137,782
Duplicating rows with certain value in a column
<p>I have to duplicate rows that have a certain value in a column and replace the value with another value.</p> <p>For instance, I have this data:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Date': [1, 2, 3, 4], 'B': [1, 2, 3, 2], 'C': ['A','B','C','D']}) </code></pre> <p>Now, I want to duplicate the ...
<p>You can use <code>append</code>, to append the rows where <code>B == 2</code>, which you can extract using <code>loc</code>, but also reassigning <code>B</code> to <code>4</code> using <code>assign</code>. If order matters, you can then order by <code>C</code> (to reproduce your desired frame):</p> <pre><code>&gt;&...
python|pandas|dataframe
5
365,562
53,055,101
Why does Pytorch expect a DoubleTensor instead of a FloatTensor?
<p>From everything I see online, <code>FloatTensors</code> are Pytorch's default for everything, and when I create a tensor to pass to my generator module it is a <code>FloatTensor</code>, but when I try to run it through a linear layer it complains that it wants a <code>DoubleTensor</code>. </p> <pre><code>class Gene...
<p>The Problem here is that your numpy input uses <code>double</code> as data type the same data type is also applied on the resulting tensor. </p> <p>The <code>weights</code> of your layer <code>self.fully_connected</code> on the other hand are <code>float</code>. When feeding data trough the layer a matrix multiplic...
python|pytorch|tensor
8
365,563
53,347,763
rolling sum of a column in pandas dataframe at variable intervals
<p>I have a list of index numbers that represent index locations for a DF. list_index = [2,7,12]</p> <p>I want to sum from a single column in the DF by rolling through each number in list_index and totaling the counts between the index points (and restart count at 0 at each index point). Here is a mini example. </p...
<p>You can try of cummulative sum and retrieving only 1 values related information , rolling sum with diffferent intervals is not possible </p> <pre><code>a = df['col'].eq(1).cumsum() df['output'] = a - a.mask(df['col'].eq(1)).ffill().fillna(0).astype(int) </code></pre> <p>Out:</p> <pre><code> col output 0 0 ...
pandas|dataframe|sum
0
365,564
53,190,981
Use pandas pivot_table() to convert attribute-value pairs to table
<p>I have a set of attribute,value pairs like this:</p> <pre><code>date,01-01-2018 product,eggs price, 5 date,01-10-2018 product,milk price,3 </code></pre> <p>And I want to create a table like</p> <pre><code>date,product,price 01-01-2018,eggs,5 01-10-2018,milk,3 </code></pre> <p>I've tried adding headers 'attribute...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot.html" rel="nofollow noreferrer"><code>pandas.pivot</code></a> and count new indices by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>cumcount</co...
python|pandas
1
365,565
53,200,373
Calculating discrete PDF from discrete CDF in python
<p>If we have discrete cdf for quantiles like</p> <pre><code>quantiles = array([1.000e-04, 1.000e-03, 1.000e-02, 2.000e-02, 3.000e-02, 4.000e-02, 5.000e-02, 6.000e-02, 7.000e-02, 8.000e-02, 9.000e-02, 1.000e-01, 2.000e-01, 3.000e-01, 4.000e-01, 5.000e-01, 6.000e-01, 7.000e-01, 8.000e-01, 9.000e-01, 9.100e-01,...
<p>I assume that when you write "pdf" you mean "sample" and not an actual <a href="https://en.wikipedia.org/wiki/Probability_density_function" rel="nofollow noreferrer">probability density function</a>; and when you write "matching_discrete_cdf", you mean the "percent point function" (PPF) which is the inverse of CDF. ...
python|numpy|probability-density|cdf
0
365,566
53,022,372
Improve the performance of nested for loops in Python
<p>I have <code>A</code>, which is a very large quadratic <code>numpy</code> matrix of size <code>n</code> in upper triangular form with non-negative entries above the diagonal.</p> <p>How can I improve the performance of the following nested for-loops as much as possible:</p> <pre><code>import numpy as np A = np.ar...
<p>Well, one obvious small improvement are the lines:</p> <pre><code>if A[i, j] &lt; A[i, k] * A[k, j]: A[i, j] = A[i, k] * A[k, j] </code></pre> <p>which can be improved to this:</p> <pre><code>aux = A[i, k] * A[k, j] if A[i, j] &lt; aux: A[i, j] = aux </code></pre> <hr> <p>Testing the two versions:</p> ...
python|python-3.x|performance|numpy|for-loop
1
365,567
53,148,088
beautiful soup - turning attributes into dataframe - BEA API
<p>I'm attempting to use the BEA's API to query income data. API Instructions - <a href="https://apps.bea.gov/api/_pdf/bea_web_service_api_user_guide.pdf" rel="nofollow noreferrer">https://apps.bea.gov/api/_pdf/bea_web_service_api_user_guide.pdf</a></p> <p>My goal is to parse the XML generated and turn it into a dataf...
<p>To take the data out of a "melted" format, I pivoted based on the <code>Year</code> and <code>Income</code> columns. </p> <pre><code>income_pivot = income_data[['Year','Income']].pivot(columns='Year')['Income'] Year 2014 2015 2016 0 41,818 NaN NaN 1 NaN 41,651 NaN 2 NaN Na...
python|pandas|beautifulsoup
0
365,568
53,309,511
How do you remove values not in a cluster using a pandas data frame?
<p>If I have a pandas data frame like this made up of 0 and 1s:</p> <pre><code> 1 1 1 0 0 0 0 1 0 1 1 1 1 1 0 0 0 0 1 1 1 0 0 0 0 1 0 1 0 0 0 0 1 0 0 0 </code></pre> <p>How do I filter out outliers such that I get something like this:</p> <pre><code> 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 0 1 0...
<p>We can do this with a <em>cummulative product</em> over the second axis with <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.cumprod.html" rel="noreferrer"><strong><code>pandas.cumprod</code></strong> [pandas-doc]</a>:</p> <pre><code>&gt;&gt;&gt; df.cumprod(axis=1) 0 1 2 3 4 ...
python|python-2.7|pandas
11
365,569
53,281,990
How to only detect humans in object detection API Tensorflow
<p>I am using <code>tensorflow</code> object detection API to detect objects. It is working fine in my windows system. How can I make changes in it to only detect mentioned objects, for example, I only want to detect humans and not all the objects.</p> <p>As per the 1st comment in this <a href="https://stackoverflow.c...
<p>I assume from your question, that you did not finetune your model yourself, but just used a pretrained one from the <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md" rel="nofollow noreferrer">model zoo</a>!?</p> <p>In this case, I think the model alrea...
tensorflow|object-detection-api
3
365,570
53,126,255
Frequent pattern mining in Python
<p>I want to know how to get the absolute support and relative support of itemsets in python. Presently I have the following:</p> <pre><code>import pandas as pd import pyfpgrowth from mlxtend.preprocessing import TransactionEncoder from mlxtend.frequent_patterns import apriori from collections import Counter datase...
<p>The relative support is part of your <code>frequen_itemsets</code> <code>DataFrame</code>. You can get it from:</p> <pre><code>frequent_itemsets['support'] </code></pre> <p>And you can calculate the absolute support multiplying support by the number of baskets:</p> <pre><code>frequent_itemsets['support']*len(data...
python|pandas|dataframe|mining
3
365,571
53,114,687
How can I populate a pandas DataFrame with the result of a Snowflake sql query?
<p>Using the <a href="https://docs.snowflake.net/manuals/user-guide/python-connector-example.html#querying-data" rel="noreferrer">Python Connector</a> I can query Snowflake:</p> <pre><code>import snowflake.connector # Gets the version ctx = snowflake.connector.connect( user=USER, password=PASSWORD, accoun...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_records.html" rel="noreferrer"><code>DataFrame.from_records()</code></a> or <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html" rel="noreferrer"><code>pandas.read_sql()</code></a> with ...
pandas|dataframe|snowflake-cloud-data-platform
22
365,572
53,070,867
Python pandas data frame remove row where index name DOES NOT occurs in other data frame
<p>I have two data frames. I want to remove rows where the indexes do not occur in both data frames. </p> <p>Here is an example of the data frames:</p> <pre><code>import pandas as pd data = {'Correlation': [1.000000, 0.607340, 0.348844]} df = pd.DataFrame(data, columns=['Correlation']) df = df.rename(index={0: 'GINI...
<p>You can just compare the indexes and use <code>.loc</code> to pull the relevant rows:</p> <pre><code>In [19]: df1 = pd.DataFrame(list(range(50)), index=range(0, 100, 2)) In [20]: df2 = pd.DataFrame(list(range(34)), index=range(0, 100, 3)) In [21]: df2.loc[df2.index.difference(df1.index)] Out[21]: 0 3 1 9 ...
python|pandas|dataframe
1
365,573
53,339,134
Copying dataframe data effectively
<p>I have a dataframe:</p> <pre><code>dataframe = pd.DataFrame() dataframe['column'] = [10,20,30,40] </code></pre> <p>I want to effectively duplicate each element 3 times so it becomes the equivalent of:</p> <pre><code>dataframe['column'] = [10,10,10,20,20,20,30,30,30,40,40,40] </code></pre> <p>I need a solution th...
<pre><code>magic_list = [10,20,30,40] dataframe['column'] = [x for y in [[a for i in range(3)] for a in magic_list] for x in y] </code></pre>
python|pandas|dataframe
0
365,574
52,944,659
Prediction based on more dataframes
<p>I'm trying to predict a score that user gives to a restaurant. </p> <p>The <a href="https://archive.ics.uci.edu/ml/datasets/Restaurant+%26+consumer+data" rel="nofollow noreferrer">data</a> I have can be grouped into two dataframes </p> <ul> <li>data about user (taste, personal traits, family, ...) </li> <li>data a...
<p>1) The second dataset is essentially characteristics of the restaurant which might influence the first dataset. Example-opening timings or location are strong factors that a customer could consider. You can use them, merging them at a restaurant level. It could help you to understand how people treat location, timin...
python|python-3.x|pandas|scikit-learn
0
365,575
53,012,831
Pandas copy rows using loops
<p>I have a DataFrame that looks like this:</p> <pre><code> SNFrom SNTo Name Age 0 1 4 John 8 1 5 7 Jack 6 </code></pre> <p>Using <code>pandas</code>, I want to produce a result like this:</p> <pre><code> Name Age SN 0 John 8 1 1 John 8 2 2 John 8 3 3 John 8...
<p>Here is a relatively naïve way using <code>apply</code>:</p> <h1>Setup:</h1> <pre><code>df = pd.DataFrame({'SNFrom':[1,5],'SNTo':[4,7],'Name':['John','Jack'],'Age':[8,6]}) &gt;&gt;&gt; df Age Name SNFrom SNTo 0 8 John 1 4 1 6 Jack 5 7 </code></pre> <h1>Solution:</h1> <pre><code>...
python|pandas|numpy
1
365,576
53,218,356
How to prevent pandas resample from resampling id columns
<p>I have a dataframe with id columns (site_id,type_id,equipment_id), a timestamp and a value as below.</p> <pre><code>&gt;&gt;&gt;print(df.head()) site_id type_id equipment_id timestamp value 47 9 332859965468 2018-07-04 10:30:04.052000+10:00 23.000000 47 9 33...
<p>This happens to a <code>MultiIndex</code> if the index isn't sorted. If you'd like to have the index looking "clean" again, you could do:</p> <pre><code>df.sort_index(inplace=True) </code></pre> <p>For instance,</p> <pre><code>df = pd.DataFrame( data=np.random.rand(5, 4), index=pd.MultiIndex.from_tuples([...
pandas|pandas-groupby
0
365,577
53,350,905
pytorch delete model from gpu
<p>I want to make a cross validation in my project based on Pytorch. And I didn't find any method that pytorch provided to delete the current model and empty the memory of GPU. Could you tell that how can I do it?</p>
<p>Freeing memory in PyTorch works as it does with the normal Python garbage collector. This means once all references to an <em>Python-Object</em> are gone it will be deleted.</p> <p>You can delete references by using the <a href="https://stackoverflow.com/questions/20847149/how-does-del-operator-work-in-list-in-pyth...
gpu|pytorch|allennlp
14
365,578
52,937,315
Joining 2 text files using pandas, 1st text file into header, the 2nd as the body
<p>I am using jupyter and I have 2 text file. dataset.txt and feature_names.txt. I input the following code. </p> <pre><code>header1 = r'./data/feature_names.txt' main = r'./data/dataset.txt' df = pd.read_csv(main, names=[header1]) </code></pre> <p><a href="https://i.stack.imgur.com/2WK1v.png" rel="nofollow noreferre...
<pre><code>header1 = r'./data/feature_names.txt' #header1 header2 header3 with open(header1,'r') as file: header_values = file.read().split() # you need to read the headers from file main = r'./data/dataset.txt' df = pd.read_csv(main, names=header_values) </code></pre>
python|pandas|jupyter
0
365,579
53,103,071
Re-Sorting 3D-Numpy Array
<p>I got a 3d-array</p> <pre><code>&gt;&gt;&gt; a array([[[[9, 6, 1], [2, 8, 6], [3, 5, 6]], [[9, 1, 9], [6, 6, 7], [3, 0, 7]], [[9, 2, 7], [6, 1, 4], [9, 2, 2]], [[3, 7, 0], [4, 0, 6], [7, 4, 8]]]]) </code></pre> <p>N...
<p><a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.transpose.html" rel="nofollow noreferrer"><strong><code>numpy.transpose(..)</code></strong></a> is a function that can permutate the axes in any order.</p> <p>If I understood it correctly, you basically want the third and fourth axis to be t...
python|numpy
3
365,580
52,914,389
python pandas - get matching and non matching records between two dataframes
<p>I'm new to use pandas in python whereas I have good knowledge in working with python.</p> <p>I've two data frames from which I've to get matching records and non matching records into new data frames.</p> <p>Example :</p> <p>DF1 :</p> <pre><code>ID Name Number DOB Salary 1 AAA 1234 12-05-1996 100000 2...
<p><strong>Simplistic Answer to your question is with <code>df1.where</code> :</strong></p> <p><strong>Note:</strong> The resulting cells with NaN do not satisfy the conditions, i.e. they are not equal in the two dataframes. The ones that have a real value are the ones that are equal in the two dataframes</p> <pre><c...
python|pandas|compare
7
365,581
53,341,962
How to use tensorflow js (tfjs) from typescript?
<p>I've tried to install typings:</p> <pre><code>npm install --save @type/tfjs npm install --save @type/tenforflowjs npm install --save @type/tensorflow </code></pre> <p>But it doesn't exist. On <a href="https://github.com/tensorflow/tfjs" rel="noreferrer">tensorflow js github repository</a> I can see that it is deve...
<p>Note that there is unfortunately no simple way to tell whether types are available in a library since type definitions can be exported in a variety of ways.</p> <p>If you do <code>npm install --save @tensorflow/tfjs</code>, you will see that there is a <code>node_modules/@tensorflow/tfjs/dist/index.d.ts</code>. Add...
typescript|typescript-typings|tensorflow.js
9
365,582
53,236,348
I am trying to build Motion Detector using openCV and python but display window is not responding when I terminate program
<p>Here is the code for the same, have a look at it. In this, below code I am creating a Motion Detector and with this I will be recording the timings of when the various objects appeared and disappeared for which I am using dataframe. </p> <p><strong>The issue with this is that the program executes but when the outpu...
<p>I had faced the same issue bcz of this piece of code from geeksforgeeks Please chck the last line of the code:</p> <blockquote> <blockquote> <p>cv2.destroyAllWindows #will be closing all the windows</p> </blockquote> </blockquote> <p>Add parenthesis, it shud b:</p> <blockquote> <blockquote> <p>cv2.destroyAllWindows(...
python|pandas|opencv|motion-detection
0
365,583
53,196,621
Plot diagram in Pandas from CSV without headers
<p>I am new to plotting charts in python. I've been told to use Pandas for that, using the following command. Right now it is assumed the <code>csv</code> file has headers (<code>time</code>,<code>speed</code>, etc). But how can I change it to when the <code>csv</code> file doesn't have headers? (data starts from row 0...
<p>You can specify x and y by the index of the columns, you don't need names of the columns for that:</p> <p>Very simple: <code>df.plot(figsize=(15,5), kind='line',x=0, y=1)</code></p> <p>It works if <code>x</code> column is first and <code>y</code> column is second and so on, columns are numerated from <code>0</code...
python|python-3.x|pandas|numpy|matplotlib
2
365,584
53,220,560
Speed up logical merging of rows in pandas (based on conditions)
<p>I have a data frame with millions of sales orders. Each row represents one item of a shopping cart. I need to merge orders, that are split despite being ordered on the same day. More precisely, all orders from the same customer on the same day which were also shipped on the same day should be assigned to the same o...
<p>This is a great job for <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.transform.html" rel="nofollow noreferrer"><code>transform</code></a>, which performs a transformation on a grouped series but ensures that the index of the result matches the index of the input (rather than collapsi...
pandas|performance|pandas-groupby
2
365,585
53,283,734
Recreating lost seconds + milliseconds in Pandas DatetimeIndex
<p>I have data from a gps unit which measures at 10 Hz but for some reason the vendor provides the timestamps up to minute precision. Thus, I end up with multiple replicates.</p> <p>Is there a simple way to recreate the missing seconds and milliseconds assuming tat the order of the timestamps is correct and time start...
<p>IIUC, you can redefine your dataframe indexing using <code>pd.date_range</code>:</p> <pre><code>np.random.seed(0) id_like = pd.date_range(start = '12:01:05', end = '12:04:05', freq='100ms') ive_got = id_like.floor('1Min') df = pd.DataFrame(np.random.random(1801), index=ive_got) </code></pre> <p>Input dataframe pri...
python|pandas|datetime
0
365,586
53,193,008
function for multiplication of two 2d-array row by row
<p>I need a simple and fast function to multiply each row of numpy array 'a' to array 'b' a , b have same 2d dimention like the result of this is example(c): but I want a numpy function insted of this loop</p> <pre><code>a=np.arange(6).reshape(3,2) b=np.arange(6,12).reshape(3,2) c=np.array([[a[i,:]@b[i,:]]for i in ran...
<p>An easy way would be to write it yourself with vectorized <code>numpy</code> methods:</p> <pre><code>np.sum(a*b,axis=1,keepdims=True) array([[ 8], [ 48], [104]]) </code></pre>
python|numpy|matrix-multiplication|multiplication|numpy-ndarray
0
365,587
53,043,713
Pytorch is not using GPU even it detects the GPU
<p>I made my windows 10 jupyter notebook as a server and running some trains on it.</p> <p>I've installed CUDA 9.0 and cuDNN properly, and python detects the GPU. This is what I've got on the anaconda prompt.</p> <pre><code>&gt;&gt;&gt; torch.cuda.get_device_name(0) 'GeForce GTX 1070' </code></pre> <p>And I also pla...
<p>I had a similar problem with using PyTorch on Cuda. After looking for possible solutions, I found the following post by Soumith himself that found it very helpful.</p> <p><a href="https://discuss.pytorch.org/t/gpu-supposed-to-be-used-but-isnt/2883" rel="nofollow noreferrer">https://discuss.pytorch.org/t/gpu-supposed...
python|gpu|pytorch
1
365,588
53,183,222
Numpy einsum_path reports more FLOP and "speeddown"
<p>For the topic <code>np.einsum</code>, I already read a bunch of discussions at: </p> <ul> <li><p><a href="https://stackoverflow.com/questions/18365073/why-is-numpys-einsum-faster-than-numpys-built-in-functions">Why is numpy's einsum faster than numpy's built in functions</a></p></li> <li><p><a href="https://stackov...
<p>I just digged into the source code of <code>np.einsum_path</code>. According to the comment here (i.e. <a href="https://github.com/numpy/numpy/blob/v1.15.4/numpy/core/einsumfunc.py#L889" rel="nofollow noreferrer">here</a>):</p> <pre><code># Compute naive cost # This isn't quite right, need to look into exactly how ...
python|numpy|numpy-einsum
0
365,589
65,844,350
Get word frequency of pandas column containing lists of strings
<p>I have a pandas dataframe:</p> <pre><code>import pandas as pd test = pd.DataFrame({'words':[['foo','bar none','scare','bar','foo'], ['race','bar none','scare'], ['ten','scare','crow bird']]}) </code></pre> <p>I'm trying to get a word/phrase count of all the...
<p>Let's try <strong><a href="https://numpy.org/doc/stable/reference/generated/numpy.hstack.html" rel="nofollow noreferrer"><code>.hstack</code></a></strong> with <strong><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>.value_counts</c...
python|pandas|dataframe
3
365,590
65,501,878
GaussianDropout vs. Dropout vs. GaussianNoise in Keras
<p>Can anyone explain the difference between the different dropout styles? From the <a href="https://tensorflow.google.cn/api_docs/python/tf/keras/layers/GaussianDropout" rel="nofollow noreferrer">documentation</a>, I assumed that instead of dropping some units to zero (dropout), GaussianDropout multiplies those units ...
<p>you are right... GaussianDropout and GaussianNoise are very similar. you can test all the similarities by reproducing them on your own</p> <pre><code>def dropout(x, rate): keep_prob = 1 - rate scale = 1 / keep_prob ret = tf.multiply(x, scale) random_tensor = tf.random.uniform(tf.shape(x)) keep_m...
python|tensorflow|keras|gaussian|dropout
2
365,591
65,851,102
Random selection, probabilistic placement
<p>I have two lists, <code>X</code> and <code>Y</code>, of equal length. I have a third list, <code>locations</code>. The values in <code>X</code> and <code>Y</code> are related to the indexes of the list <code>locations</code>. I also have an equation, which is below.</p> <pre><code>def equat(x): return np.pow...
<p>First of all, you don't need <code>zip(X[:10], Y[:10])</code> because you never used <code>i</code>. You can just use <code>for j in Y[:10]</code>.</p> <p>Second of all, for your first question (A != j) you can easily replace <code>A</code> assignment row with this one :</p> <pre><code>A = j while A==j : A = np....
python|numpy|random|probability
0
365,592
65,714,375
Neural Network predicts same sequence of answers for every example in dataset
<p>thanks in advance for your help. My problem is the following: I have dataset of images and I'm trying to predict properties for images in this dataset. It is multi-label classification meaning that one image can have multiple properties. If I count all these properties across dataset and put their amount in descendi...
<p>Does your test sample during prediction follow same pre-processing steps as the training one (eg: are both samples normalized)? This might be one of the reason for your problem.</p>
python|deep-learning|neural-network|pytorch
0
365,593
65,701,024
Issue concatenating datafames inside loops scraping a web
<p>I have the following code</p> <pre><code>import pandas as pd import requests from bs4 import BeautifulSoup import datetime import time # url = 'https://www.pccomponentes.com/procesadores?page=' url_list = [ 'https://www.pccomponentes.com/procesadores?page=', 'https://www.pccomponentes.com/discos-duros/500-...
<p>Usually, what I like to do when collecting data through webscraping is to build either :</p> <ul> <li>A list of dictionaries (which contains metadata) (<strong>option 1</strong>)</li> <li>Lists of metadata in a single dictionary with corresponding column names (data, title, price, etc.) (<strong>option 2</strong>)</...
python|pandas|dataframe|web-scraping
0
365,594
65,848,854
Pandas Group By multiple Columns and return sorted list
<p>In a DataFrame df, group using multiple colunms, and for each group, find elements of third column, make a sorted list of those elements and attach it to the original Data Frame.</p> <p>Example Given</p> <pre><code>df = pd.DataFrame({'c':[1,1,2,2,3,3],'l1':['a','a','a','a','b','b'],'l3':['b','a','b','a','a','a'],'l4...
<p>Using your function you can use:</p> <pre><code>cols = ['c','l1'] out = (df.set_index(cols).assign(pair=df.groupby(cols)['l3'] .agg(makePair)).reset_index() .reindex(df.columns.union(['pair'],sort=False),axis=1)) </code></pre> <hr /> <p>Full code:</p> <pre><code>def makePair(l3): k=l3.sort_valu...
python|pandas
1
365,595
65,720,276
How can I swap values in PyTorch Tensor?
<p>I have the following tensor:</p> <pre><code>vector = torch.tensor([[1,5,3], [2,3,4]]) </code></pre> <p>How can I swap values in the second axis? e.g.</p> <p><code>tensor([[1, 5, 3], [2, 3, 4]])</code></p> <p>becomes:</p> <p><code>tensor([[1, 3, 3], [2, 5, 4]])</code></p>
<p>You can use numpy's style of indexing :</p> <pre><code>&gt;&gt;&gt; vector = torch.tensor([[1,5,3], [2,3,4]]) tensor([[1, 3, 4], [2, 5, 3]]) &gt;&gt;&gt; vector[[0,1],1] = vector[[1,0],1] &gt;&gt;&gt; vector tensor([[1, 3, 3], [2, 5, 4]]) </code></pre> <p>In that case, we switch the value between th...
python|pytorch
3
365,596
65,702,453
"The TensorFlow library was compiled to use FMA instructions, but these aren't available on your machine." in VirtualBox
<p>My tensorflow has been able to run normally in the WIN10 system, and with cuda and cudnn installed, the GPU can be used normally. I have a whim, I want to open a tf on my own virtual machine Ubuntu, maybe I can try distributed? The result is that after finally installing tensorflow, it cannot run. When import tensor...
<p>I am experiencing the same problem and just peeped this from another question:</p> <p><a href="https://stackoverflow.com/questions/49345786/how-to-install-tensorflow-gpu-version-on-virtualbox-ubuntu-os-and-host-os-is-wi">How to install tensorflow GPU version on VirtualBox Ubuntu OS. And host OS is windows 10</a></p>...
tensorflow|ubuntu|virtual-machine
2
365,597
65,713,772
Create a new column based on values in an existing column
<p>I would like to create a new column to classify if certain address is a residential or non-residential address.</p> <p>Below is a column in the original dataframe:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Building_name</th> </tr> </thead> <tbody> <tr> <td>Fung Chak House, Choi Wan...
<p>I chose to add this community wiki, for study:</p> <p>on my Jupyter Notebook, I compared the answers from @MayankPorwal and @Ferris. Here is the result:</p> <p>First, the <code>str.contains</code> with <code>np.where</code> method:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy ...
python-3.x|regex|pandas|dataframe
2
365,598
65,486,230
Weight constrains in TensorFlow Neural Networks
<p>I'm training Neural Networks for classification using TensorFlow/Keras, and I would like the weights in the output layer to have the following property:</p> <p>Suppose the weight or kernel matrix is a <code>3 by 4 matrix W</code>, and its elements are <code>W_ij</code></p> <p>I would like <strong>for each column j, ...
<p>Are you sure you want to control the weight???? If you try to enforce that type of constraint to the weight, your NN will probably never learn anything.</p> <p>It seems to me that you just want a softmax layer in the output.</p> <p>A softmax would have exactly what you are saying. Let's supposed you are classifying ...
python|tensorflow|keras
0
365,599
65,864,265
Create list of lists from Groupedby dataframe in Pandas
<p>Assume my df is as follows:</p> <pre><code>df = pd.DataFrame({'Order ID': [1, 1, 2, 3, 3, 3, 4, 4], 'Product': ['USB', 'Bat', 'Ball', 'USB', 'Phone', 'Toy', 'Bike', 'Apple']}) </code></pre> <p>I want to group by Order ID, and then put the Product values in a list of lists depending on the frequency of their Order ID...
<p>In Trial 1, instead of using <code>extend</code>, you should use <code>append</code>. Or you can use list comprehension:</p> <pre><code>[g.values.tolist() for _, g in df.Product.groupby(df['Order ID'])] # [['USB', 'Bat'], ['Ball'], ['USB', 'Phone', 'Toy'], ['Bike', 'Apple']] </code></pre>
python|pandas|list|pandas-groupby
1