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
362,700
66,398,502
Any solution for compare and copy multiple pandas dataframes
<pre class="lang-py prettyprint-override"><code>datanew = [{&quot;version&quot;: &quot;Adobe 1.0.2&quot;}, {&quot;version&quot;: &quot;Microsoft 1.3.27&quot;}, {&quot;version&quot;: &quot;Test 0.0.2&quot;}] datasum = [{&quot;version&quot;: &quot;Adobe 1.0.2&quot;,&quot;number&quot; : 1}, {&quot;version&quot;: &quot;Mi...
<pre class="lang-py prettyprint-override"><code>import pandas as pd datanew = [{&quot;version&quot;: &quot;Adobe 1.0.2&quot;}, {&quot;version&quot;: &quot;Microsoft 1.3.27&quot;}, {&quot;version&quot;: &quot;Test 0.0.2&quot;}] datasum = [{&quot;version&quot;: &quot;Adobe 1.0.2&quot;,&quot;number&quot; : 1}, {&quot;ve...
python|pandas|dataframe|compare
0
362,701
66,351,768
Get a set three random variable follow uniform distribution from 0 to 1 in which X1+X2+X3=1
<p>My approach</p> <pre><code>N=20 X1 = np.zeros((N,)) X2 = np.zeros((N,)) X3 = np.zeros((N,)) for i in range(N): while (X1[i]+X2[i]+X3[i]&gt;1+sys.float_info.epsilon) or (X1[i]+X2[i]+X3[i]&lt;1-sys.float_info.epsilon): X1[i]= np.random.random() X2[i]= np.random.random() X3[i]= np.random.ran...
<p>You can't have a uniform distribution on all 3 variables.</p> <p>In any valid triple, at least 2/3 of the variables must be &lt; 1/2. If you want all the variables to have the same distribution, then the average density &lt;= 1/2 must be at least twice the average density &gt;= 1/2.</p> <p>One particularly nice way...
python|numpy|math
2
362,702
66,743,740
How can I use pandas.groupby.agg() for subcolumns?
<p>I would like to group this dataframe by equipment 2 <code>EQ2</code> and compute the mean and standard deviation of the subcolumn <code>['A']['mean']</code> (i.e. the mean of the mean and the std of the mean)</p> <pre><code>&gt;&gt;&gt; df2 EQ EQ2 A mean std 0 a1 b1 -0.875496 0.532...
<p>I found the answer, in case anyone finds it useful:</p> <pre><code>&gt;&gt;&gt; df3 = df2.groupby(['EQ2']).agg({('A','mean') : ['mean','std']}).reset_index() &gt;&gt;&gt; df3 EQ2 A mean mean std 0 b1 -0.055529 1.159608 </code></pre>
pandas|dataframe|pandas-groupby
0
362,703
66,542,790
Data transformation with python
<p>I have a log-scaled dataset, and I want to transform the data to measure the density of the dataset in each group. I made a scatterplot with dashed support lines. Its only purpose is to visualize the data.</p> <p><a href="https://i.stack.imgur.com/2ANUs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur....
<p>You can multiply the coordinates by the rotation matrix:</p> <pre><code># sample dataframe df = pd.DataFrame({ 'x': np.arange(100), 'y': np.arange(100) + np.random.randint(-10, 10, 100)}) # rotation angle, degrees theta_deg = -45 theta = theta_deg / 180 * np.pi # rotation matrix rot = np.array([ [np.co...
python|pandas|dataframe
1
362,704
66,351,236
creating a progress bar for a validation test Python
<p>The following code is used to find p-values for a significant test on Cifar-10 database. Because we need a min of 1000 permutations, it is a very slow process, and I want to inlude a progress bar to show how time for each permutation. I was thinking of using the tqdm library and sleep function, but am stuck on where...
<pre><code>from tqdm import tqdm def validate_significance(val_loader, model, criterion, args): model.eval() vec_acc1 = [] vec_acc1_chance = [] vec_acc5 = [] vec_acc5_chance = [] for ss in tqdm(range(0, args.num_permutations)): .... </code></pre>
python|validation|pytorch|progress-bar
2
362,705
66,568,225
Weird memory usage of looped pandas GroupBy function
<p>I am working on this problem for several hours and can't find a solution. I am running a loop and do some calculations on a relatively big DataFrame. But with every loop, the virtual memory usage increases, until I am running out of memory. I tried manual garbage collection, setting the default thresholds of gc and ...
<p>Using the most up-to-date Pandas version resolved this issue. It even halved memory allocation!</p>
python|python-3.x|pandas|memory-leaks|out-of-memory
0
362,706
66,489,729
Handle ValueError while creating date in pd
<p>I'm reading a csv file with <code>p, day, month</code>, and put it in a <code>df</code>. The goal is to create a date from day, month, current year, and I run into this error for 29th of Feb:</p> <pre><code>ValueError: cannot assemble the datetimes: day is out of range for month </code></pre> <p>I would like when th...
<p>You could try something like this :</p> <pre><code>df['datex'] = pd.to_datetime(df[['year', 'month', 'day']], errors='coerce') </code></pre> <p>Indeed, you get NA :</p> <pre><code> p day year month datex 0 p1 29 2021 2 NaT 1 p2 18 2021 7 2021-07-18 2 p3 12 2021 9 2021-09-...
python-3.x|pandas|datetime|valueerror
1
362,707
66,507,232
How to use an isinstance qualifier on the elements of a numpy array
<p>I can do</p> <pre class="lang-py prettyprint-override"><code>arr = np.random.randint(0, 1, size=(10,10)) arr == 1 </code></pre> <p>and get a boolean array as an output.</p> <p>What if my array is an <code>object</code> data type and I want to check that certain elements are an instance of some class? Is there a <str...
<p>Looks like <a href="https://numpy.org/doc/stable/reference/generated/numpy.vectorize.html" rel="nofollow noreferrer"><code>numpy.vectorize</code></a> is an option that <code>numpy</code> provides for doing so:</p> <pre><code>&gt;&gt;&gt; np_isinstance = np.vectorize(isinstance) &gt;&gt;&gt; np_isinstance(arr, str) ...
python|numpy
2
362,708
66,406,662
Randomly Filling NaN values of a Column with Non-Null String Values
<p>I'm working with the following DataFrame containing <code>.str</code> values</p> <pre><code>maturity_rating 0 NaN 1 Rated: 18+ (R) 2 Rated: 7+ (PG) 3 NaN 4 Rated: 18+ (R) </code></pre> <p>and I'm trying to fill the NaN values randomly with other Non-Null values present in the same column</p> <p>My expected...
<p>Let us try <a href="https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html" rel="nofollow noreferrer"><code>np.random.choice</code></a>:</p> <pre><code>m = df['maturity_rating'].isna() df.loc[m, 'maturity_rating'] = np.random.choice(df.loc[~m, 'maturity_rating'], m.sum()) </code></pre> <p><...
python|pandas|dataframe
4
362,709
66,691,844
How can I filter rows based on a regex from one column to another
<p>I have the following dataframe</p> <pre><code> ClientCode FileName 0 123 123--filename 1 234 456--filename 2 345 345--filename 3 456 123--filename 4 567 567--filename </code></pre> <p>Basically I need to return the rows where Cli...
<p>Use this:-</p> <pre><code>df[~df['ClientCode'].eq(df['FileName'].str.split('--',expand=True)[0].astype(int))] </code></pre>
python|regex|pandas
1
362,710
66,394,648
How do I create Dataframe in Pandas?
<p>I have the below code and the dataframe only include the latest file parse on my list. How can I get a full list ?</p> <pre><code>for filename in os.listdir(path): fullpath = os.path.join(path, filename) soup=BeautifulSoup(open(fullpath,encoding=&quot;utf8&quot;)) text=(soup.body.find('div', {'class':[Cl...
<p>Append your results in a list then convert them to a dataframe:</p> <pre><code>lst_text = [] for filename in os.listdir(path): fullpath = os.path.join(path, filename) soup=BeautifulSoup(open(fullpath,encoding=&quot;utf8&quot;)) text=(soup.body.find('div', {'class':[Class]}).text) text=sent_tokenize(t...
python|pandas|dataframe|beautifulsoup
0
362,711
66,404,737
Loading multiple CSVs into a single pandas dataframe
<p>I am trying to load multiple CSVs into a single pandas dataframe. They are all in one file, and all have the same column structure. I have tried a few different methods from a few different threads, and all return the error 'ValueError: No objects to concatenate.' I'm sure the problem is something dumb like my fi...
<p>It might not be as helpful as other answers, but when I tried running your code, it work perfectly fine. The only difference that conflicted was that I changed the path to be like this:</p> <pre><code>temps_csvs = glob.glob(os.path.join(os.getcwd(), &quot;*.csv&quot;)) df_for_each_csv = (pd.read_csv(f) for f in tem...
python|pandas|csv|import
1
362,712
66,554,530
Scraping table (several pages) to Pandas Dataframe
<p>I'm trying to transfer the data of a long table <em>(24 pages)</em> to a Pandas Dataframe, but facing some issues with <em>(i think)</em> the for-loop code.</p> <pre><code>import requests from bs4 import BeautifulSoup import pandas as pd base_url = 'https://scrapethissite.com/pages/forms/?page_num={}' res = request...
<p>I agree with @mxbi.</p> <p>Try it:</p> <pre><code>import requests from bs4 import BeautifulSoup import pandas as pd base_url = 'https://scrapethissite.com/pages/forms/?page_num={}' l = [] for n in range(1, 25): scrape_url = base_url.format(n) res = requests.get(scrape_url) soup = BeautifulSoup(res.text...
python|pandas|beautifulsoup
2
362,713
66,410,343
How to join two df's on the basis of column values and row values?
<p>I have a column of df (<code>df1</code>), let's say, <code>column1</code> consisting of random months and years in the format <code>%b-%y</code> and <code>column2</code> consisting of some numbers. I have another df (<code>df2</code>) which has <strong>column headers</strong> of random months and years in the same f...
<p>You do not need to introduce &quot;placeholder&quot; months to achieve this. You can set a DatetimeIndex and reindex your DataFrame to fill in the missing dates. Afterward, it's just a pivot table.</p> <p>Here is an example:</p> <pre><code>import pandas as pd import io from datetime import (date, datetime) df1_te...
python|pandas
3
362,714
66,527,661
How to convert time into specific format in python?
<p>I have a column of time in my pandas DataFrame containing more than 800,000 rows. The time format is something like this:</p> <pre><code>08:28:31 08:28:35 08:28:44 08:28:44 </code></pre> <p>I want to convert this format into hourly, which means if the first time comes 08:28:31 then the second-time time should come i...
<p>Use:</p> <pre><code>#convert values to datetimes df['date'] = pd.to_datetime(df['date']) #count number of repeated values df = df.loc[df.index.repeat(24 - df['date'].dt.hour)] #generate hour timedeltas hours = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='H') #add to dates and generate times with convert i...
python|pandas|datetime|time|rows
1
362,715
66,738,490
Efficient way to create similarity matrix (pandas)
<p>I've got one list with 1M vectors. What I want to do is calculate the similarity between each of them!</p> <pre><code>len(list_vec) = 1000000 </code></pre> <p>Result:</p> <pre><code> V1 V2 ... V1000000 V1 1 a ... b V2 a 1 ... d ... ... V1000000 b d ... 1 </code></pre> ...
<p>Don't compute the full distance matrix on your samples. It doesn't scale well, and with 1 million samples you'll need 4TB of memory.</p> <p>If you're looking to find the nearest neighbours (i.e. for K-nearest neighbours), perhaps use a <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.KDTre...
python|pandas
0
362,716
16,230,848
Blitz code produces different output
<p>I want to use weave.blitz to improve the performance of the following numpy code:</p> <pre><code>def fastIteration(self): g = self.grid nx,ny = g.ux.shape uxold = g.old_ux ux = g.ux ux[0:,1:-1] = uxold[0:,1:-1] + ReI* (uxold[0:,2:] - 2*uxold[0:,1:-1] + uxold[0:,0:-2]) g.setBC() g.old_u...
<p>It looks like a bug in <code>weave.blitz</code> (reproduced, filed and <a href="https://github.com/scipy/scipy/issues/2422" rel="nofollow">fixed</a>. There's more information about the actual bug there). </p> <p>I thought it was odd to write <code>0:</code> instead of the shorter <code>:</code> to get a full slice ...
python|numpy|scipy
2
362,717
16,060,790
2d matrix composed from 1d matrices in python
<p>A newbie question and possible duplicate: How can one compose a matrix in numpy using arrays or 1d matrices? In matlab, I would use following syntax for the matrix consisting of three arrays treated as rows:</p> <pre><code>A=[1; 1; 1]; B=[2; 2; 2]; C=[3; 3; 3]; D=[A B C] </code></pre> <p>The result is:</p> <pre><...
<p>You should do</p> <pre><code>import numpy as np A = np.array([1, 1, 1]) B = np.array([2, 2, 2]) C = np.array([3, 3, 3]) D = np.vstack((A, B, C)) </code></pre> <p>See <a href="http://mathesaurus.sourceforge.net/matlab-numpy.html" rel="nofollow">NumPy for MATLAB users</a> (official link seems to be down)</p>
python|matlab|numpy
4
362,718
16,395,446
Pandas: extract and select data from columns using a pattern
<p>My data contains a structure similar to this (reduced to 2 elements, but there are tens):</p> <pre><code>Variable elem_1_pre elem_1_post elem_2_pre elem_2_post Observation1 present absent absent present Observation2 absent present present absent </code></p...
<p>You wondered if <code>groupby</code> could be used here, so I'll mention how it can be. Short version, although I'd probably write this in two lines for clarity:</p> <pre><code>(df == 'present').groupby(lambda x: x.rsplit("_", 1)[0], axis=1).sum() == 1 </code></pre> <hr> <p>First, we can start from an example da...
python|group-by|pandas
2
362,719
57,457,982
Upgrade Tensorflow model or Retrain for SavedModel
<p>I followed "Tensorflow for poets" in 2017 and retrained my own collection of images and created "retrained_graph.pb" and "retrained_labels.txt"<br> Today I need to run this model on Tensorflow Serving. There are two options to accomplish this: </p> <ol> <li><p>Upgrade the old model to save it as under the "saved_m...
<p>In my opinion, either using <strong><code>Tensorflow Hub</code></strong> or using the <strong><code>Pre-Trained Models</code></strong> inside <strong><code>tf.keras.applications</code></strong> is preferable because, in either cases, there won't be many code changes required to Save the Model, to make it compatible ...
tensorflow|tensorflow-serving|imagenet|tensorflow-hub
0
362,720
57,368,881
How to filter by Time from DateTime values in Pandas
<p>My <code>df</code> dataset looks likes this:</p> <pre><code>time Open 2017-01-03 06:00:00 5.2475 2017-01-03 07:00:00 5.2475 2017-01-03 08:00:00 5.2180 2017-01-03 09:00:00 5.2128 2017-01-03 10:00:00 5.2128 2017-01-04 06:00:00 5.4122 2017-01-04 07:00:00 5.4122 2017-01-04...
<p>Compare values by time and create helper <code>Series</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumsum.html" rel="nofollow noreferrer"><code>Series.cumsum</code></a>, then remove values with <code>0</code>, because it is first values non matched first time from condit...
python-3.x|pandas|dataframe
0
362,721
57,529,443
Merge 2 DataFrame and sum up one of the column
<p>I have 2 Dataframes that I would like to merge in pandas (Python 2.7).</p> <p>In the merge (DataFrame C) the same ID and Sub_id must be only one line and their Views must add up.</p> <p>My DataFrame A</p> <pre><code>-------------------------------- ID | Sub_ID | Views -------------------------------- 345 | 4 | 1...
<p>IIUC, you could use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>pandas.concat</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>pandas.DataFrame....
pandas|python-2.7|dataframe
0
362,722
57,391,830
Pro Guard rules for Tensor flow lite module
<p>Hie, I am using tensor flow lite for an android project. when I am running with pro-guard I am receiving the following error and unfortunately, I couldn't find any pro-guard rules of that library</p> <pre><code>org.tensorflow.lite.Interpreter: can't find referenced class org.checkerframework.checker.nullness.qual.N...
<p>Add this line to your proguard file:</p> <pre><code>-dontwarn org.checkerframework.** </code></pre> <p>It should fix your problem.</p>
tensorflow|proguard|tensorflow-lite
0
362,723
57,540,745
What is the difference between register_parameter and register_buffer in PyTorch?
<p>Module's <a href="https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.register_buffer" rel="noreferrer">parameters</a> get changed during training, that is, they are what is learnt during training of a neural network, but what is a <a href="https://pytorch.org/docs/stable/generated/torch.n...
<p>Pytorch <a href="https://pytorch.org/docs/1.1.0/nn.html#torch.nn.Module.register_buffer" rel="noreferrer">doc</a> for <code>register_buffer()</code> method reads</p> <blockquote> <p>This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s <code>runni...
machine-learning|deep-learning|neural-network|pytorch
51
362,724
57,360,906
Is there a faster way to pass python numpy to java array in JPype
<p>Is there any better way to pass a big numpy array to java array in JPype with low memory costing?</p> <p>Because the data in numpy is so big, which really takes a long time and costs lots of memory. I also want to save memory, after searcheing in user-guide, it said 'you can pre-convert it once using the wrappers, ...
<p>Preconverting it means creating a series of <code>jpype.JArray(jpype.JDouble)</code> and <code>jpype.JArray(jpype.JDouble,2)</code> structures copying the data into the arrays. There should be an optimized fill routine for transferring the data once from numpy to Java when it finds the memory view interface, but it ...
java|python|arrays|numpy|jpype
0
362,725
57,358,992
How to combine groupby results without NaN?
<p>I have the following dataframe:</p> <pre><code>import pandas as pd data = [['10', '20'], ['10', '15'], ['15', '14']] df = pd.DataFrame(data, columns = ['dt', 'ct']) df.groupby('dt')['dt'].count() </code></pre> <p>returns</p> <pre><code>dt 10 2 15 1 </code></pre> <p>and</p> <pre><code>df.groupby('ct')[...
<p>Use <code>stack</code> + <code>value_counts</code> instead of two groupbys</p> <pre><code>df.stack().value_counts() </code></pre> <p></p> <pre><code>10 2 15 2 20 1 14 1 dtype: int64 </code></pre> <hr> <p>If you have more than these columns, index first</p> <pre><code>df[['dt', 'ct']].stack().value_...
python|pandas|dataframe
6
362,726
57,719,908
How to aggregate information from a data-set to produce a result table
<p>Suppose I have a data-set in csv format:</p> <pre><code>Date | Payment Method | Amount ($) 01-08-19 Cash 10.00 01-08-19 Cash 5.00 01-08-19 Credit 13.00 01-08-19 Credit 6.00 02-08-19 Cash 2.00 02-08-19 Credit 18.00 02-08-19 Credit ...
<p>Does this solve ?</p> <pre><code>df1=df.groupby(['Day','Payment'])['Amount'].sum().reset_index() df1 Out[28]: Day Payment Amount 0 1/08/2019 Cash 15 1 1/08/2019 Credit 19 2 2/08/2019 Cash 2 3 2/08/2019 Credit 42 df1['days Pay exceeded $10']=np.where(df1['Amount']&gt;10,...
python|pandas|pandas-groupby
1
362,727
57,315,730
How to create new column based on top and bottom parts of single dataframe in PANDAS?
<p>I have merged two dataframes having same column names. Is there a easy way to get another column of mean of these two appended dataframes?</p> <p>Maybe code explains it better.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd df1 = pd.DataFrame({'a':[1,2,3,4],'b':[10,20,3...
<p><strong><code>melt()</code></strong></p> <pre><code>df=df.assign(a_mean=df1.add(df2).div(2).melt().value) </code></pre> <p>Or taking only <code>df</code>, you can do:</p> <pre><code>df=df.assign(a_mean=df.groupby(df.index)['a'].mean()) </code></pre> <hr> <pre><code> a b a_mean 0 1.0 10.0 1.1 1 2...
python|pandas|dataframe
1
362,728
57,702,145
Merge dataframes of different sizes and simultaneously overwrite NaN values
<p>I would like to combine two dataframes in Python of different sizes. These dataframes are loaded from Excel files. The first dataframe has many empty values containing NaN, and the second dataframe has the data to replace the NaN values in the first dataframe. The two dataframes are linked by the data in the first c...
<pre><code>d = dict(zip(df2.A,df2.B)) df1["B"] = df1["A"].map(d) del df2["B"] df1.merge(df2,how='left',on='A',sort=True) </code></pre>
python|pandas|dataframe
0
362,729
57,549,691
How To Identify days before and after a holiday within pandas?
<p><em>Objective</em>: to identify 2 days before the holiday and 3 days after a holiday by making things binary.</p> <p><em>Details</em>: Specifically I am trying to get a result to df['is_2_days_before'] and df['is_3_days_after'] with a TRUE or FALSE.</p> <pre><code>import pandas as pd from pandas.tseries.holiday im...
<p>We just need to using <code>DateOffset</code></p> <pre><code>df['2 day before holiday'] = df['Date'].isin(holidays-pd.DateOffset(2)) df['3 day after holiday'] = df['Date'].isin(holidays+pd.DateOffset(3)) </code></pre>
python-3.x|pandas|date
2
362,730
57,702,957
Calculating time difference in minutes between a date and a timestamp columnn
<p>I cant seem to figure out what I am doing wrong, I have 2 columns in my df that look like below,</p> <pre><code> Date Time 2019-07-23 21:17:47.599 22:00:00.000 2019-07-23 21:11:46.973 21:50:00.000 </code></pre> <p>I want to create a new column in the df that calculates the difference in minute...
<p>You are close, only cannot convert <code>Time</code> column to <code>datetime</code>s, but only to <code>timedelta</code>s and if there are python object times first cast to strings:</p> <pre><code>df3['new'] = ((pd.to_timedelta(df3.Time.astype(str))- pd.to_timedelta(df3.Date.dt.strftime('%H:%M:%S')...
python|python-3.x|pandas|datetime|data-science
1
362,731
57,702,368
Nan row values shifted while using read clipboard in Pandas
<p>In my excel I have a data like this:</p> <pre><code> year quarter 2017 Q1 2018 Q2 2019 Q3 Q4 </code></pre> <p>When I use <code>read_clipboard</code> to copy it and get a data frame, I get this:</p> <pre><code> year quarter 0 2017 Q1 1 2018 Q2 2 2019 Q3 3 ...
<p>You can pass the <code>sep</code> </p> <pre><code>pd.read_clipboard(sep='/s+') year quarter 0 2017 Q1 1 2018 Q2 2 2019 Q3 3 Q4 </code></pre>
python|pandas
1
362,732
57,559,817
Remove consecutive duplicate entries from pandas in each cell
<p>I have a data frame that looks like </p> <pre><code>d = {'col1': ['a,a,b', 'a,c,c,b'], 'col2': ['a,a,b', 'a,b,b,a']} pd.DataFrame(data=d) </code></pre> <p>expected output</p> <pre><code>d={'col1':['a,b','a,c,b'],'col2':['a,b','a,b,a']} </code></pre> <p>I have tried like this : </p> <pre><code>arr = ['a', 'a', '...
<p>From what I understand, you don't want to include values which repeat in a sequence, you can try with this custom function:</p> <pre><code>def myfunc(x): s=pd.Series(x.split(',')) res=s[s.ne(s.shift())] return ','.join(res.values) print(df.applymap(myfunc)) </code></pre> <hr> <pre><code> col1 co...
python-3.x|pandas|pandas-groupby
1
362,733
57,575,484
Is there something similar to tf.cond but for vector predicates?
<p>Say I have a 5D tensor <code>x</code> and a 1D boolean mask <code>m</code> where <code>m.shape[0] == x.shape[0]</code>, and I want to decide which sub-network should be applied on each 4D sample inside <code>x</code> based on the corresponding boolean entry of <code>m</code>. </p> <p>To my knowledge <code>tf.cond</...
<p>The simplest thing would be to evaluate the data on both models and the use <code>tf.where</code> to select the final output.</p> <pre><code>import tensorflow as tf def model1(x): return 2 * x def model2(x): return -3 * x with tf.Graph().as_default(), tf.Session() as sess: x = tf.placeholder(tf.float...
python|python-3.x|tensorflow
1
362,734
57,367,401
How to plot only one half of a scatter matrix using pandas
<p>I am using pandas scatter_matrix (couldn't get PairgGrid in seaborn to work) to plot all combinations of a set of columns in a pandas frame. Each column as 1000 data points and there are nine columns. </p> <p>I am using the following code:</p> <pre><code>pandas.plotting.scatter_matrix(df, alpha=0.2, figsize=(8,8))...
<p>This is probably not the cleanest way to do it, but it works:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt </code></pre> <pre><code>axes = pd.plotting.scatter_matrix(iris, alpha=0.2, figsize=(8,8)) for i in range(np.shape(axes)[0]): for j in range(np.shape(axes)[1]): ...
python|pandas|matplotlib
8
362,735
57,548,443
getting date of change based on column values in pandas dataframe
<p>I have the following dataframe:</p> <pre><code>fid date stage test_fid 4/22/2019 a1 test_fid 4/23/2019 a1 test_fid 4/24/2019 a2 test_fid 4/25/2019 a2 test_fid 4/26/2019 a2 test_fid 4/27/2019 a3 test_fid 4/28/2019 a3 test_fid 4/29/2019 a3 test_fid1 4/30/2019 ...
<p>Use <code>sort_values</code> on date and <code>groupby</code>. Then aggregate for the first and last date.</p> <p><code>df.sort_values('date').groupby(['stage','fid']).agg({'date':['first', 'last']}).reset_index()</code></p> <p>result</p> <pre><code> stage fid date first last 0 a1...
python|pandas
3
362,736
57,618,076
OpenCv raising error when numpy array fed into it
<p>I'm making a mandelbrot set zoom video maker and openCV is not allowing me to feed in my numpy array.</p> <p>My end goal is to make a video that zooms in on "interesting" points in the mandelbrot set automaticly, but for now all I'm doing is zooming in on the center.</p> <p>This is my code for making the video.</p...
<p>opencv is expecting an 8-bit unsigned type (<code>CV_8U</code>, which can contain values 0 to 255) but you're passing an 8-bit signed type (<code>np.int8</code>, which can contain values -128 to 127). Try using <code>np.uint8</code> instead of <code>np.int8</code> for the array type</p>
python|numpy|opencv
3
362,737
57,716,919
How to select pandas series rows based on length of index name?
<p>I have a pandas series like shown below, how to select only rows where the length of the index is greater than 3?</p> <pre><code>s = pd.Series([1,2,3,4,5], index=['a','bb','ccc','dddd','eeeee']) </code></pre> <p>Required output:</p> <pre><code>dddd 4 eeeee 5 </code></pre> <p>My attempt:</p> <pre><code>s[...
<p>I'll enrich a collection of approaches with additional one powered by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.filter.html" rel="nofollow noreferrer"><code>pandas.Series.filter</code></a> routine:</p> <pre><code>In [216]: s.filter(regex='.{4,}') ...
python|pandas
4
362,738
57,527,788
Function giving error when run on the same dataframe more than once
<p>Function giving error when run on the same data frame more than once. it works fine the first time but when run again on the same df it gives me this error:</p> <blockquote> <p>IndexError: single positional indexer is out-of-bounds</p> </blockquote> <pre class="lang-py prettyprint-override"><code>def update_data...
<p>Using <code>inplace=True</code> in a function changes the input data frame. Of course there it doesn't work, your function presumes the data is in some format at the start of the function. That assumption is broken.</p> <pre><code>df = pd.DataFrame([{'x': 0}]) def change(df): df.drop(columns=['x'], inplace=True...
pandas
0
362,739
57,516,164
alter characters in between two defined words
<p><strong>Background</strong></p> <p>I have the following df</p> <pre><code>import pandas as pd df = pd.DataFrame({'Text' : ['But the here is SERG BATH # : S00-1111 MR # 111 is Here ', 'Found here SERG BATH # : E22-22222 MR # 000', 'So so SERG B...
<p>Try:</p> <pre><code>df['New_Text'] = df['Text'].str.replace('BATH \# \:(.+?)MR \#','BATH # :*** Block *** MR #') </code></pre>
regex|python-3.x|pandas|text|replace
3
362,740
57,409,544
How to remove one specific duplicate named column in columns of a dataframe?
<p>I have a sample dataframe df with columns as:</p> <pre><code> a b c a a b b c c 0 2 2 1 2 2 1 1 2 2 1 2 2 2 2 2 1 2 1 2 . . . . . . </code></pre> <p>I want to remove the duplicate columns named with only 'a' and keep other as same The expected o/p is:</p> <pre><code> a b c b b c c 0 2 2 1 1 1 2 2 1 2 2 2 1 ...
<p>Here is a general solution to drop any duplicates of a column, no matter where these columns are in the dataframe and what the content of these columns is.<br> First we get all column indexes for the given column name and drop the first occurrence. Then we "substract" these indexes from all indexes and return the re...
pandas
3
362,741
57,455,517
Trying to save a tensorflow model but failing to create directory "failed to create a directory: /tmp/serving_savemodel\1565577669"
<p>I'm trying to save a DNN classifier model so I can generate a tflite model, but in the last line, when trying to export to directory, I get error below:</p> <blockquote> <p>failed to create a directory: /tmp/serving_savemodel\1565577669</p> </blockquote> <pre><code>feature_spec = tf.feature_column.make_parse_exa...
<p>I faced a similar problem in my windows machine. I solved it by using as path separator "\" instead of "/".</p> <p>Example for your case:</p> <pre><code> servable_model_dir = r"\tmp\serving_savemodel" </code></pre> <p>Related question: <a href="https://stackoverflow.com/questions/57093053/tensorflow-error-fail...
tensorflow|tensorflow-serving|tensorflow-estimator
0
362,742
57,673,818
Python: Insert 2D array into 3D NumPy array along different rows
<p>I am trying to insert a 2D array of size <code>[2, 2]</code> into a 3D array of size <code>[2, 3, 2]</code>. For every page of the 3D array (axis=0), the position to insert the 2D array (read: row number) may be different. I tried to use the <code>np.insert</code> function. However, I am struggling...</p> <pre><co...
<p>Here's one based on array-assignment and <code>masking</code> -</p> <pre><code>from skimage.util.shape import view_as_windows def insert_into_arr(arr, row_number_before_insertion, val_to_insert): ma,na,ra = arr.shape L = len(val_to_insert) N = len(row_number_before_insertion) out = np.zeros((ma,na...
python|numpy|multidimensional-array
1
362,743
57,527,059
Filter a data-set from a dictionary keys and values
<p>let's say I have a <code>pd.DataFrame</code> :</p> <pre><code>df = pd.DataFrame({'Press':['A', 'B', 'A', 'B', 'A'], 'Model':[1, 2 ,2 , 2, 1], 'Count':[1, 1 ,1 , 1, 1]}) </code></pre> <p>After sorting, I only want to keep data matching <code>somedict = {'A':2, 'B':2}</code>. (k...
<p>Here you go using <code>merge</code> </p> <pre><code>s=pd.Series(somedict).to_frame('Model').rename_axis('Press').reset_index() yourdf=df.merge(s) Out[231]: Press Model Count 0 B 2 1 1 B 2 1 2 A 2 1 </code></pre>
python|pandas
5
362,744
57,298,402
Pandas Merge multiple dataframes on index and column
<p>I am trying to Merge multiple dataframes to one main dataframe using the datetime index and id from main dataframe and datetime and id columns from other dataframes</p> <h1>Main dataframe</h1> <pre><code>DateTime | id | data (Df.Index) ---------|----|------ 2017-9-8 | 1 | a 2017-9-9 | 2 | b </code></pre> <h1>...
<p>I'm not sure how your dictionaries are set up so you will most likely need to modify this but I'd try something like:</p> <pre class="lang-py prettyprint-override"><code>for sensorDevice in dictOfSensor: df = dictOfSensor[sensorDevice] # set df index to match the main_df index df = df.set_index(['DateTi...
python|pandas|merge
0
362,745
57,468,268
How can I keep values without aggregation when resampling in pandas
<p>I have minute financial data and want to resample for the day however I want to retain the open for the first observation of the day and the close from the last observation of the day.</p> <pre><code> DDate/Time | Symbol| Open |High |Low Close| Volume 2011-01-03 07:07:00| BTP#| **58.92** |58...
<pre><code> btp = btp.resample('d').apply({'Open':'first', 'High':'max', 'Low':'min', 'Close':'last'}) </code></pre>
python|pandas|resampling
0
362,746
57,369,148
what do hidden layers mean in a neural network?
<p>in a standard neural network, I'm trying to understand, intuitively, what the values of a hidden layer mean in the model.</p> <p>I understand the calculation steps, but I still dont know how to think about the hidden layers and how interpret the results (of the hidden layer)</p> <p>So for example, given the standa...
<p>A hidden layer in a neural network may be understood as a layer that is neither an input nor an output, but instead is an intermediate step in the network's computation.</p> <p>In your MNIST case, the network's state in the hidden layer is a processed version of the inputs, a reduction from full digits to abstract ...
python|tensorflow|neural-network
0
362,747
57,719,181
How to change the array entries with order = 'F' in numpy
<p>I am trying to replace some entries of an array. I have to use the order='F' for compatibility reasons. The array I am working with is big, yet to reproduce the problem try the following. </p> <p>This works: </p> <pre><code>a = numpy.array([[1, 2], [4, 5]]) a.reshape((4, 1), order = 'C')[2] = 8 a = array([[1, 2...
<p>For the <code>'C'</code> type array this will get you a new 4x1 array that references all the same elements as the original array:</p> <pre><code>a = numpy.array([[1, 2], [4, 5]]) a.reshape((4, 1), order = 'C')[2] = 8 </code></pre> <p>So, the result is the same as doing this:</p> <pre><code>a = numpy.array([[1, 2...
python|arrays|numpy
2
362,748
57,665,770
Why tf.gradients doesn't work with integer constants?
<p>Why the function below prints <code>None</code>?</p> <pre class="lang-py prettyprint-override"><code>a = tf.constant(4) b = tf.constant(2) gr = tf.gradients(a + b, [a, b]) print(sess.run(gr)) </code></pre> <p>But when I change </p> <pre class="lang-py prettyprint-override"><code>-a = tf.constant(4) -b = tf.cons...
<p>According to <a href="https://github.com/tensorflow/tensorflow/issues/20524" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/20524</a> tensorflow team made <code>tf.gradients</code> incompatible with integer tensors for this reason:</p> <blockquote> <p>In effect, allowing gradients on i...
python|tensorflow
2
362,749
57,346,233
AttributeError: module 'pandas' has no attribute 'Dataframe' with rapsberry Pi
<p>I know there are similar questions, but none was able to provide me with an answer. I am running a python script on a raspberry pi (model 3). I am using python 3 and pandas is installed trough pip install pandas. My code is able to run the line <code>import pandas as pd</code>, but <code>test = pd.Dataframe</code> g...
<p>Use </p> <pre><code>data = pd.DataFrame() </code></pre> <p>With a capital ‘F’. pd.Dataframe() (without the capital ‘F’) doesn’t exist, so it will throw the error shown. </p>
python|pandas|raspberry-pi3
7
362,750
57,527,582
Pandas - For Each Index, Put All Columns Into Rows
<p>I'm trying to avoid looping, but the title sort of explains the issue.</p> <pre><code>import pandas as pd df = pd.DataFrame(columns=['Index',1,2,3,4,5]) df = df.append({'Index':333,1:'A',2:'C',3:'F',4:'B',5:'D'}, ignore_index=True) df = df.append({'Index':234,1:'B',2:'D',3:'C',4:'A',5:'Z'}, ignore_index=True) df.s...
<p>You need:</p> <pre><code>df.stack().reset_index(1, name='value').rename(columns={'level_1':'newcol'}) # OR df.reset_index().melt('Index',var_name='new_col',value_name='Value').set_index('Index') #(cc: @anky_91) </code></pre> <p>Output:</p> <pre><code> newcol value Index 333 1 A 3...
python|pandas
3
362,751
57,591,748
export dataframe to excel but I came across printing problem
<p>I want to export my dataframe that is created differently in everyday to same excel everyday. When I create new dataframe, I read the fixed excel file and append my new dataframe to older one and then I export the final dataframe to excel but I can not solve the printing problem.</p> <p>When I print my dataframe be...
<p>Check your dataframe right after <code>df_BUY = df_BUY.append(BUY, sort=False)</code> OR try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html" rel="nofollow noreferrer">to_csv()</a></p> <h1>Code</h1> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame([['...
pandas|dataframe|append
0
362,752
57,710,920
How can I find a solution for the "FileNotFoundError"
<p>I'm currently working on an image classifier project. During the testing of the predict function, I receive the error: FileNotFoundError: [Errno 2] No such file or directory: 'flowers/test/1/image_06760'</p> <p>the path of the file is correct. You can find the whole notebook here: <a href="https://github.com/Marti...
<p>These are the images you have </p> <p><a href="https://i.stack.imgur.com/YZjME.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YZjME.png" alt="enter image description here"></a></p> <p>You should have it as </p> <p><code>image_name = data_dir + '/test' + '/1/' + 'image_06760.jpg'</code> </p> <...
python|pytorch
2
362,753
57,584,365
Columns are lost after using groupby().sum() function
<p>I am working on grouping some data together by a certain column name and sum all the values. </p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np data = pd.read_excel('Data_Cleaning.xlsx', sheetname='Expenses reclassification') data.columns = data.iloc[1,:] data = data.drop([...
<p>The aggregation function, a sum in this case, will be performed on the columns which support such aggregation, i.e. numerical columns. It seems you have just 36 numerical columns. </p> <p>If you think there should be more numerical columns, you may want to check types of each column, and if you sense something's wr...
python-3.x|pandas-groupby
0
362,754
57,438,160
How to speed up computation over multiple arrays in python
<p>Suppose we have <code>a</code>, <code>b</code>, <code>c</code>, three arrays of same dimension, and that we need to do computations based on each column of <code>a</code>, <code>b</code>, <code>c</code>. </p> <p>An example would be like: </p> <pre><code>import numpy as np col = 10 row = 1000000 a = np.random.nor...
<p>When using <code>numpy</code> you need to consider vectorizing the computation in <code>my_func</code> to speed up your code. In this case you could try something like this:</p> <pre><code>cond = np.broadcast_to(a[0] + b[0] + b[-1] &gt; c[0], a.shape) result = np.where(cond, a * b * c, a * (b[1] + b[-1]) + c[-1]) <...
python|performance|numpy
2
362,755
57,414,773
Summing specific columns in a panda dataframe
<p>I'm trying to sum specific columns in a panda dataframe. I'm starting with text in the dataframe, given specific words I change the text to a number and then carry out my sum. </p> <p>I start by creating a sample DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame({'a': [1,'produces','produces','und...
<p>There are two problems: the summation and the insertion of a column with different indexes.</p> <h2>1) Summation</h2> <p>Your <code>df</code> is of type <code>objects</code> (all strings, including empty strings). The dataframe <code>counter</code> is of mixed types too (ints and strings):</p> <pre><code>counter....
python|pandas|dataframe
1
362,756
57,316,716
Create column with value one year later for every group in pandas
<p>I'm working with a DataFrame with the following format:</p> <pre><code>id Period value 1 201308 A 1 201309 A . 1 201408 C 1 201409 D . . 2 201308 B 2 201309 C . 2 201408 A 2 201409 B </code></pre> <p>A...
<p>Try:</p> <pre><code>df['Period_'] = df['Period'] + 100 (df.merge(df.drop('Period_', axis=1), left_on=['id','Period_'], right_on=['id','Period'], suffixes=['','_t1']) .drop('Period_', axis=1) ) </code></pre> <p>Output:</p> <pre><code> id Period value Period_t1 value_t1 0 1 ...
python|pandas|date
0
362,757
57,318,930
calculating the number of parameters of a GRU layer (Keras)
<p>Why the number of parameters of the GRU layer is 9600?</p> <p>Shouldn't it be ((16+32)*32 + 32) * 3 * 2 = 9,408 ?</p> <p>or, rearranging,</p> <p>32*(16 + 32 + 1)*3*2 = 9408</p> <pre><code>model = tf.keras.Sequential([ tf.keras.layers.Embedding(input_dim=4500, output_dim=16, input_length=200), tf.keras.l...
<p>The key is that tensorflow will separate biases for input and recurrent kernels when the parameter <code>reset_after=True</code> in <code>GRUCell</code>. You can look at some of the <a href="https://github.com/tensorflow/tensorflow/blob/e706a0bf1f3c0c666d31d6935853cfbea7c2e64e/tensorflow/python/keras/layers/recurren...
tensorflow|lstm|gated-recurrent-unit
8
362,758
57,705,412
counting unique number of dates to count ocuurance
<p>Want to find the number of unique dates corresponds to a set of values. If the values of Col1, Col2, Col3 are same then how many instances are there. I could do with only year or month or day, but want to combine all so that I can find for every unique date(yyyy/mm/dd). </p> <pre><code>BldgID BldgHt Device Date...
<p>The follwing soloution works for me. Let's generate your data first:</p> <pre><code>df = pd.DataFrame({'BldgID': [108, 108, 108, 108, 104, 104, 104, 104, 104, 104, 104, 104, 104, 104], 'BldgHt': [28, 28, 28, 28, 36, 36, 41, 41, 41, 41, 41, 41, 45, 45], 'Device': [760, 760, 760, 760, 758, 758, 758, 758, 758, 758, 7...
python|pandas|date
4
362,759
57,365,283
How to show columns that have different values in rows?
<p>I have pandas DataFrame with 2 rows:</p> <pre><code>+---------+---------+-----------+------------+ | ID| Type| Index| Code| +---------+---------+-----------+------------+ |111111111| aa| 1| XXX| |111111111| aa| null| XXX| </code></pre> <p>How can I s...
<p>You can simply select the column/s (or the dataframe) with columns having unique values more than 1. You can get those columns whose values are distinct with</p> <pre><code>def cols_having_unique(df): my_cols = [] for col in df.columns: if df[col].nunique(dropna=False) &gt; 1: my_cols.ap...
python|pandas
2
362,760
57,502,221
How to convert 1D numpy arrays element-wire into new 1D numpy array?
<p>I've <code>n</code> numpy 1D arrays <code>ì_0 = [i00, i01, i02, ...]</code>, <code>i_1 = [i10, i11, i12, ...]</code>, ... and would like to put the values into <code>m</code> new 1D arrays <code>o_0 = [i00, i10, 120, ...]</code>, <code>o_1 = [i01, i11, i21, ...]</code>, ... where <code>m</code> is the element count ...
<p>First a question: why element-wise? Do you want to do things to each point on its way from input to output array? If so, you either need to simply loop over input arrays and maybe use python's <code>yield</code> (saving maybe on working memory). Alternatively, if possible, you can encompass your steps into a single ...
python|numpy
2
362,761
57,403,239
How to update multiple Numpy arrays in a loop
<p>I would like to update (prepend each one with additional elements) many numpy arrays in a loop, without having to repeat the code for each one.</p> <p>I tried creating a list of all the arrays and looping through the items in that list and updating each one, but that doesn't change the original array.</p> <pre><co...
<p><code>array = np.concatenate((np.zeros(3, dtype=int), array))</code> does not change the current array but creates a new one and stores it inside the variable <code>array</code>. So for the solution you have to change the values of the array itself, which can be done with <code>array[:]</code>.</p> <p>That means th...
python|arrays|loops|numpy|updates
0
362,762
57,396,902
Matching multiple array value to row in csv file slow
<p>I have a numpy array consisting of about 1200 arrays containing 10 values each. np.shape = 1200, 10. Each element has a value between 0 and 5,7 million. </p> <p>Next I have a .csv file with 3800 lines. Every line contains 2 values. The first value indicates a range the second value is an identifier. The first and l...
<p>Setup:</p> <pre><code>import numpy as np import collections np.random.seed(100) numpy_file = np.random.randint(0, 5700000, (1200,10)) #'''range, identifier''' read_file = io.StringIO('''509,47222 1425,47220 2404,47219 4033,47218 6897,47202 5793850,211 5794901,186 5795820,181 5796176,43 5796467,33''') csv_reader =...
python|algorithm|performance|csv|numpy
1
362,763
57,437,165
NaN at First Position of Two Columns, By Each Unique Value
<p>I'm trying to change the first observation for each unique ID in a dataframe to an NaN. I'm working with a dataframe of timestamps and coordinate points that are already sorted by unique ID and timestamp.</p> <p>Sample:</p> <pre><code> ID timestamp latitude longitude 0 1 6/9/2017 11:20 38.795333...
<p>Since your df is already sorted by the ID column, you can use the following trick to get the first occurrence of each unique ID as a boolean mask:</p> <pre class="lang-py prettyprint-override"><code>mask = df.ID != df.ID.shift() </code></pre> <p>Then set the corresponding data to <code>NaN</code></p> <pre class="...
python|pandas|numpy|dataframe|pandas-groupby
1
362,764
57,715,248
TensorFlow: Help creating a serving input function
<p>I'm new to TensorFlow Serving. I trained a wide and deep model using an estimator. Now I want to serve my model. I create my serving input receiver function and save the model. When I try to predict using the saved model I always receive <code>InternalError: Unable to get element as bytes</code>. I don't really unde...
<p>It looks like your <code>serialized_tf_example</code> placeholder has <code>shape=[]</code> which is a single example. You should pass a single <a href="https://www.tensorflow.org/api_docs/python/tf/train/Example" rel="nofollow noreferrer">tf.train.Example</a>, serialized as a string:</p> <pre><code># I assume here...
python|tensorflow|tensorflow-serving
2
362,765
57,402,088
I want to get/print df by range instead of head or tail
<p>I can't find or understand how to get the data I want by range I want to know how to get df['Close']from x to y then .mean to sum it up</p> <p>I have tried "costomclose = df['Close'],range(dagartot,val)" But it gives me something else like heads and tails from df</p> <pre><code>if len(df) &gt;= 34: dagarto...
<p>Here is an example of slicing out the middle of something based on the encounter index:</p> <pre><code>&gt;&gt;&gt; s = pd.Series(list('abcdefghijklmnop')) &gt;&gt;&gt; s Out[135]: 0 a 1 b ... 12 m 13 n 14 o 15 p dtype: object &gt;&gt;&gt; s.iloc[6:9] Out[136]: 6 g 7 h 8 i dtype: ob...
python-3.x|pandas
1
362,766
24,153,278
How to get output of pandas .plot(kind='kde')?
<p>When I plot density distribution of my pandas Series I use</p> <pre><code>.plot(kind='kde') </code></pre> <p>Is it possible to get output values of this plot? If yes how to do this? I need the plotted values.</p>
<p>There are no output value from <code>.plot(kind='kde')</code>, it returns a <code>axes</code> object. </p> <p>The raw values can be accessed by <code>_x</code> and <code>_y</code> method of the <code>matplotlib.lines.Line2D</code> object in the plot</p> <pre><code>In [266]: ser = pd.Series(np.random.randn(1000)) ...
python|pandas
13
362,767
23,995,461
python Pandas: transform dataframe adding grouped columns
<p>I have the following dataframe:</p> <pre><code> n startdate enddate count 0 1 2014-02-01 2014-02-01 6069 1 1 2014-02-01 2014-03-01 1837 2 1 2014-02-01 2014-04-01 107 3 1 2014-02-01 2014-05-01 54 4 1 2014-03-01 2014-03-01 10742 5 1 2014-03-01 2014-04-01 2709 6 1 201...
<p>without recreating your dataframe, i think it's going to be something like:</p> <pre><code>df.groupby(['n', 'startdate', 'enddate']).sum().unstack() </code></pre> <p>you might need to fill some nan values as well:</p> <pre><code>df.fillna(0, inplace=True) </code></pre>
python|pandas|dataset
5
362,768
24,168,507
Create csv file with metadata header followed by timeseries in Python / Pandas
<p>I am trying to create a csv file that contains metadata in the first few rows, followed by timeseries data, so it can be processed by another web application. My csv file should look like this:</p> <pre><code>Code: ABC1 Frequency: Monthly Description: Blah Blah ------------------- 2/1/1947 11.7 3/1/1947 ...
<pre><code>&gt;&gt;&gt; with open('test.csv', 'w') as fout: ... fout.write('meta data\n:') ... meta_data.to_csv(fout) ... ts.to_csv(fout) </code></pre>
python|csv|pandas|metadata
1
362,769
24,114,026
Using numpy.array in cython
<p>I want to rewrite a class in <strong>cython</strong> format and save it as demo.pyx. The input parameter for the class would be either a <strong>2D np.array</strong> with an <code>Nx2</code> shape, e.g. <code>a=np.array([[0.2,-0.8],[3.7,0.02],..,[-0.92,-3.33]])</code>, or a list for <code>instance a=[0.1,2.7]</code>...
<p>When you do <code>positions[:,0]</code> or <code>positions[:,1]</code> you are creating a new, 1D and undeclared buffer in Cython. This is not an element from which you can take the address. The address will correspond to a single value in the array, so you should do something like:</p> <pre><code>cimport numpy as ...
python|arrays|pointers|numpy|cython
3
362,770
24,027,040
How to extract all columns but one from an array (or matrix) in python?
<p>Given a numpy 2d array (or a matrix), I would like to extract all the columns but the i-th.</p> <p>E. g. from</p> <pre><code>1 2 3 4 2 4 6 8 3 6 9 12 </code></pre> <p>I would like to have, e.g.</p> <pre><code>1 2 3 2 4 6 3 6 9 </code></pre> <p>or</p> <pre><code>1 2 4 2 4 8 3 6 12 </code></pre> <p>I cannot fin...
<p>Since for the general case you are going to be returning a copy anyway, you may find yourself producing more readable code by using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html"><code>np.delete</code></a>:</p> <pre><code>&gt;&gt;&gt; a = np.arange(12).reshape(3, 4) &gt;&gt;&gt; np....
python|arrays|numpy|matrix
44
362,771
24,164,249
Parsing CSV file in pandas with commas in last column
<p>I'm stuck with some poorly formatted CSV data that I need to read into a Pandas dataframe. I cannot change how the data is being recorded (it's coming from someplace else), so please no solutions suggesting that. </p> <p>Most of the data is fine, but some rows have commas in the last column. A simplified example:</...
<p>Fix the csv, then proceed normally:</p> <pre><code>import csv with open('path/to/broken.csv', 'rb') as f, open('path/to/fixed.csv', 'wb') as g: writer = csv.writer(g, delimiter=',') for line in f: row = line.split(',', 2) writer.writerow(row) </code></pre> <hr> <pre><code>import pandas as ...
python|pandas
4
362,772
43,518,038
Estimate the number of unique occurences per group
<p>This is my data frame <code>df</code>:</p> <pre><code>CITY ID_C abc 123 abc 123 abc 456 def 123 def 456 def 789 def 789 </code></pre> <p>I need to calculate the number of unique values of <code>ID_C</code> grouped by <code>CITY</code>:</p> <pre><code>CITY TOTAL_UNIQUE_COUNT abc 2 def 3...
<p>There is a direct method for that:</p> <pre><code>df.groupby('CITY')['ID_C'].nunique() Out: CITY abc 2 def 3 Name: ID_C, dtype: int64 </code></pre> <p>For formatting:</p> <pre><code>df.groupby('CITY')['ID_C'].nunique().to_frame('TOTAL_UNIQUE_COUNT') Out: TOTAL_UNIQUE_COUNT CITY a...
python|pandas
2
362,773
43,514,840
Pandas differences between p2.7 and p3.6
<p>I just started a new project, for the first time in python 3. Recycling some code from another python 2.7 project, I have this piece of code</p> <pre><code> it = df.itertuples() ... return it.next() </code></pre> <p>Both pandas versions are 0.19.2 In python2 it has the type</p> <pre><code>&lt;itertools...
<p>Ok, looks like next(iterator) is the python 3 way to go instead of it.next()</p>
pandas
0
362,774
43,745,884
Python - can't figure out how to multiply 2 panels (3D arrays) without looping
<p>I have a panel like this:</p> <pre><code>values = ['count1','count2','price1','price2'] fruit = ['apple','orange'] days = ['d1','d2'] dictx = {} list_count = [] list_price = [] for v in values: if 'count' in v: dictx[v] = pd.DataFrame(np.random.randint(0,10,size=(len(days), len(fruit))), columns=frui...
<p>If I understand correctly you might be looking for this:</p> <pre><code>sum(pan.ix[list_count].values * pan.ix[list_price].values) </code></pre> <p>The <code>.values</code> attribute is a numpy array which then lets you do your elementwise multiplication, addition, etc. </p> <p><strong>Example</strong></p> <pre>...
python|pandas|multidimensional-array
2
362,775
43,636,171
Pandas: convert date in month to the 1st day of next month
<p>I am wondering if there are any efficient methods or one-liner that, given a pandas DatetimeIndex <em>date1</em>, return a DatetimeIndex <em>date2</em> that is the first day of the next month?</p> <p>For example, if <em>date1</em> is '2011-09-30' then <em>date2</em> is '2011-10-01'?</p> <p>I have tried this one line...
<p>You can use <code>pd.offsets.MonthBegin()</code></p> <pre><code>In [261]: d = pd.to_datetime(['2011-09-30', '2012-02-28']) In [262]: d Out[262]: DatetimeIndex(['2011-09-30', '2012-02-28'], dtype='datetime64[ns]', freq=None) In [263]: d + pd.offsets.MonthBegin(1) Out[263]: DatetimeIndex(['2011-10-01', '2012-03-01'...
pandas|python-datetime
40
362,776
43,888,969
List comprehension several frames
<p>I will ask this question by using pd.DataFrames because the problem emerged from working with them. But it may be generalised to mutables in python.</p> <p>I want to create a list of DataFrames with one value differing. At the moment I do:</p> <pre><code>data = pd.DataFrame(np.full((2, 2), 0), columns=['A', 'B']) ...
<p>Sure you can pass a <code>slice</code>, use a <code>slice</code> object:</p> <pre><code>&gt;&gt;&gt; [loc_set_copy(data, [slice(None), 'A'], i) for i in range(3)] [ A B 0 0 0.0 1 0 0.0, A B 0 1 0.0 1 1 0.0, A B 0 2 0.0 1 2 0.0] </code></pre> <p>More prettily:</p> <pre><code>&gt;&gt;&g...
python|pandas|mutable|sanity-check
1
362,777
43,745,078
How to clip a numpy array?
<p>I have a 5x5 matrix:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; x=np.random.rand(5,5) &gt;&gt;&gt; x array([[ 0.47231299, 0.02139265, 0.05321461, 0.06338545, 0.98003833], [ 0.81340571, 0.81404643, 0.87641499, 0.29969447, 0.13871426], [ 0.91088258, 0.02642179, 0.03657303, 0....
<p>Basic <a href="https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow noreferrer">numpy indexing/slicing</a>:</p> <pre><code>x[1:-1,1:-1] #array([[ 0.81404643, 0.87641499, 0.29969447], # [ 0.02642179, 0.03657303, 0.91060929], # [ 0.54428098, 0.21511229, 0.2177599 ]]) </cod...
python|numpy
3
362,778
43,555,164
update specific array in DataArray
<p>I have a (4,6,3) dimensional DataArray. I want to update particular rows and columns. </p> <p>Lets say I want to update first row of n1 [18, 4, 81] to [0,0,0] and update last column of n4 [15,20,31,91,27,39] to [1,1,1,1,1,1]. Please show how to? </p> <pre><code>tmp=xr.DataArray(np.random.randint(99,size=(4,6,3)...
<pre><code>tmp[0][0] = np.zeros(3) tmp[3][:, 2] = np.ones(6) [[[ 0 0 0] [13 17 33] [61 97 6] [29 43 37] [ 5 36 21] [31 85 55]] [[69 92 69] [61 63 45] [10 58 56] [30 53 9] [10 83 95] [23 19 71]] [[88 83 26] [ 1 1 34] [ 7 80 2] [46 47 55] [ 5 22 63] [40 76 37]] [[54 15 1] [95...
python|pandas|python-xarray
1
362,779
43,615,758
How to make network graph of twitter (Python3)
<p>I'm beginner programing who try to analyze network of my twitter account. I am writing this code:</p> <pre><code>api = twitter.Api(consumer_key = my_consumer_key, consumer_secret = my_consumer_secret, access_token_key = my_access_token_key, access_token_secret = my_access_token_secre...
<p>If I understand your question correctly, you want to choose a maximum of 5/6 followers and their interconnections.</p> <p>If that is the case, I suggest you change your for loop such that at most five nodes are added to the graph. Further, you need to make sure that you only add the followers of the five followers ...
python-3.x|numpy|twitter|networkx
2
362,780
43,684,048
Tensorflow: building graph with batch sizes varying in dimension 1?
<p>I'm trying to build a CNN model in Tensorflow where all the inputs within a batch are equal shape, but between batches the inputs vary in dimension 1 (i.e. minibatch sizes are the same but minibatch shapes are not). </p> <p>To make this clearer, I have data (Nx23x1) of various values N that I sort in ascending orde...
<p>There is no way to do this, as you want to use a differently shaped matrix (for fully-connected layer) for every distinct batch. </p> <p>One possible solution is to use global average pooling (along all spatial dimensions) to get a tensor of shape <code>(batch_size, 1, 1, NUM_CHANNELS)</code> regardless of the seco...
tensorflow|conv-neural-network
2
362,781
43,530,701
numpy: get indices where condition holds per row
<p>I have an array such as the following:</p> <pre><code>In [70]: x Out[70]: array([[0, 1, 2], [3, 4, 5]]) </code></pre> <p>I am trying to get the indices per row where a condition holds, for example, <code>x &gt; 1</code>.</p> <p>Expected output is like <code>([2], [0, 1, 2])</code></p> <p>I have tried <co...
<p>One approach -</p> <pre><code>r,c = np.where(x&gt;1) out = np.split(c, np.flatnonzero(r[1:] &gt; r[:-1])+1) </code></pre> <p>Sample run -</p> <pre><code>In [140]: x Out[140]: array([[0, 2, 0, 1, 1], [2, 2, 1, 2, 0], [0, 2, 1, 1, 0], [1, 0, 0, 2, 2]]) In [141]: r,c = np.where(x&gt;1) In [14...
numpy
0
362,782
43,507,767
Pandas: Fill NaNs with next non-NaN / # consecutive NaNs
<p>I'm looking to take a pandas series and fill <code>NaN</code> with the average of the next numerical value where: <code>average = next numerical value / (# consecutive NaNs + 1)</code></p> <p>Here's my code so far, I just can't figure out how to divide the <code>filler</code> column among the <code>NaN</code>s (and...
<ul> <li>Take a reverse <code>cumsum</code> of <code>notnull</code></li> <li>Use that to <code>groupby</code> and <code>transform</code> with <code>mean</code></li> </ul> <hr> <pre><code>csum = df.num.notnull()[::-1].cumsum() filler = df.num.fillna(0).groupby(csum).transform('mean') df.assign(filler=filler) ...
python|pandas|pandas-groupby
12
362,783
43,833,361
Recovering a checkpoint after reaching NaN loss?
<p>I'm training an RNN and sometime overnight the loss function reached NaN. I've been reading that a solution to this is to decrease the learning rate. When attempting to restart training from the (only) checkpoint I have and using a smaller learning rate, I still get NaN. Does this mean my checkpoint is beyond repair...
<p>If your checkpoint has <code>NaN</code> values in it, there is probably not a lot you can do to recover it. I guess you could replace the NaNs with something else, but that isn't that principled.</p> <p>You probably want to see if there is an earlier checkpoint without <code>NaN</code> values. <code>tf.train.Saver<...
tensorflow|loss|checkpoint
0
362,784
43,762,731
Comparing two data frames using for loop
<p>I have two data frames, df1 and df2. I want to create a for loop that "runs" over the first columns of both df1 and df2 (column 1) and return me the element found on column 0 of df2. My code so far is the following, but something goes wrong.</p> <pre><code>import pandas as pd def user_return(df1,df2,list): for...
<p>In case you're wondering how to implement my suggestion from the comments:</p> <pre><code>import pandas as pd df1 = pd.DataFrame(columns=["Col1", "Col2", "Col3"], data=[[1,2,3],[2,1,3],[3,2,1]]) df2 = pd.DataFrame(columns=["Col1", "Col2", "Col3"], data=[[1,2,3],[2,1,3],[3,2,1]]) merged = df1.merge(df2, on="Col1")...
python|pandas|dataframe
0
362,785
43,691,066
Numpy array modification in-place
<p>I have a file that looks like this:</p> <pre><code>row column layer value1 value2 8 454 1 0.000e+0 1.002e+4 8 455 1 0.000e+0 1.001e+4 8 456 1 0.000e+0 1.016e+4 8 457 1 0.000e+0 1.016e+4 . . . </code></pre> <p>I want to do some calculations on the last column (for example multiply by 10) and s...
<p>Your example has columns indexed only 0 to 4, so <code>usecols=(0,1,2,5)</code> produces an error with the file in your example. Assuming <code>usecols=(0,1,2,4)</code>:</p> <p>You can modify the array in-place with</p> <pre><code>for i in range(0,len(ic)): ic[i]['value2'] *= 10 </code></pre> <p>and save it to t...
arrays|python-2.7|numpy|in-place
1
362,786
43,793,353
How do I efficiently parse a substring in a Pandas Dataframe based on a value in a column?
<p>Assume, I have the following table:</p> <pre><code>random_string|end_location|substring -------------|------------|--------- HappyBirthday| 4 |Happ GoodBye | 5 |GoodB NaN | NaN |NaN Haensel | 2 |Ha ... | ... |... </code></pre> <p>This table repre...
<pre><code>df random_string end_location 0 HappyBirthday 4.0 1 GoodBye 5.0 2 NaN NaN 3 Haensel 2.0 </code></pre> <p>Work with subset</p> <pre><code>d1 = df.dropna() rs = d1.random_string.values.tolist() el = d1.end_location.values.astype(int).toli...
python|pandas|dataframe
2
362,787
43,791,193
Equivalent of numpy.dot (python) in Fortran
<p>I have code in python that I need to "translate" to Fortran (that I don't know that much....) </p> <p>I have :</p> <pre><code>&gt;&gt;&gt;Mat1 array([[ 0.2], [ 0.4], [-0.2], [-0.8]]) &gt;&gt;&gt; X array([[0, 0, 1, 1], [0, 1, 1, 0], [1, 0, 1, 0], [1, 1, 1, 1]]) </code></pr...
<p>For this, MATMUL is the way you want to go. See <a href="http://www.tutorialspoint.com/fortran/Vector_and_matrix_multiplication.htm" rel="nofollow noreferrer">here</a>. DOT_PRODUCT is only for vectors. MATMUL can handle any matrices whose dimensions allow matrix multiplication.</p> <p>In your example, your matrices...
python|numpy|matrix|fortran
1
362,788
43,814,878
Python/Pandas TypeError: 'list' object is not callable
<p>This is not a duplicate question, or at least I don't think so.</p> <p>When I try to run this code snippet of just two lines:</p> <pre><code>import pandas as pd mydates = pd.date_range('2010-01-22', '2010-01-26') </code></pre> <p>On trying the foll:</p> <pre><code>In [16]:import pandas as pd In [17]:mydates = ...
<p>Looks like python thinks <code>pd.date_range</code> is a list and that you're trying to call it. You may have accidentally done something like this:</p> <pre><code>pd.date_range = [] </code></pre> <p>Check to see what its type is</p> <pre><code>type(pd.date_range) list </code></pre> <p><strong><em>solution</em...
python|list|pandas|datetime
14
362,789
43,675,124
Python - Split array into multiple arrays dependent on array values
<p>I have a list which needs to be split into multiple lists of differing size. The values in the original list randomly increase in size until the split point, where the value drops before continuing to increase. The values must remain in order after being split.</p> <p>E.g. Original list</p> <pre><code>[100, 564, 5...
<p><strong>Approach #1</strong></p> <p>Using NumPy's <code>numpy.split</code> to have list of arrays as output -</p> <pre><code>import numpy as np arr = np.array(a) # a is input list out = np.split(arr,np.flatnonzero(arr[1:] &lt; arr[:-1])+1) </code></pre> <p><strong>Approach #2</strong></p> <p>Using loop comrehen...
python|arrays|numpy|split
7
362,790
43,625,353
Pandas rewriting columns
<p>I have a data file. It has several columns with data and two columns have the same names. When I get a pandas frame with the data from this file, it turns out that the columns with the same names exist in a single instance. That is, one of the columns is rewritten.</p> <p>I get data using <code>pd.read_table</code>...
<p>I think last version of pandas (<code>0.19.2</code>) add <code>.number</code> to same column names:</p> <pre><code>temp=u"""A;A;B;B 1;1;1;1 2;3;1;2""" #after testing replace 'StringIO(temp)' to 'filename.csv' df = pd.read_csv(StringIO(temp), sep=";") print (df) A A.1 B B.1 0 1 1 1 1 1 2 3 1 2 ...
python|pandas
0
362,791
43,575,180
Hough Transform in Python - Results incorrectly offset - index error?
<p>I'm writing a basic Hough Transform in Python - I believe I have got it conceptually correct however, my result is appearing to be offset such that it is split top and bottom, rather than continuous. What I want to get should look like this:</p> <p><a href="https://i.stack.imgur.com/Y7VCjm.png" rel="nofollow norefe...
<p>You've mixed up the indices when you create <code>houghspace</code> as a list of lists. Please prefer using numpy arrays as it will make things much clearer with indices. Along the x-axis, the angle <code>theta</code> changes and along the y-axis the <code>rho</code> changes. But, you've got it the other way when de...
python|numpy|image-processing|indexing|hough-transform
1
362,792
43,691,573
How to pass all the data in dataframe that extract from excel sheet to highchart?
<p>I have a raw data and right now I need to used the raw data to plot a highchart and pass to Django, any one can share me the basic how to plot a highchart in order to shown in HTML page? I'm very new to python, Django and Highchart, I have read through all the related material on Highchart but I still not understand...
<p>Based on your error message, It seems that Django is unable to determine the url named as <code>bar</code> in your <code>urls.py</code> files, I think you forgot to put a <a href="https://docs.djangoproject.com/en/1.10/topics/http/urls/#naming-url-patterns" rel="nofollow noreferrer">named urls</a> as <code>bar</code...
python|django|pandas|highcharts
1
362,793
43,601,074
Zipf Distribution: How do I measure Zipf Distribution using Python / Numpy
<p>I have a file (lets say corpus.txt) of around 700 lines, each line containing numbers separated by <code>-</code>. For example:</p> <pre><code>86-55-267-99-121-72-336-89-211 59-127-245-343-75-245-245 </code></pre> <p>First I need to read the data from the file, find the frequency of each number, measure the Zipf d...
<p>As stated <code>numpy.random.zipf(a, size=None)</code> will produce plot of Samples that are drawn from a <code>zipf</code> distribution with specified parameter of a > 1.</p> <p>However, since your question was difficulty in using <code>numpy.random.zipf</code> method, here is an naive attempt as discussed on <a...
python|numpy|statistics|numpy-random|zipf
3
362,794
43,826,246
How does one convert a data set with two labels +1 and -1 to a hot one vector representation in a vectorized way in Python?
<p>I have a data set in numpy with a x vector and a y vector. The y vectors is only two values +1 or -1 (or 0 or 1) because its a binary valued function. I know I can just loop over the data set and if I see a +1 to map it to 1 and if I see and -1 map it to 0 one by one. However, I was hoping that given the whole vecto...
<p>A few simple observations to making this efficient:</p> <ul> <li>Preallocate the result, rather than using <code>concatenate</code></li> <li><code>empty</code> is faster than <code>zeros</code> if you're just going to overwrite those zeros</li> <li>Use the <code>out</code> argument, to avoid temporaries</li> </ul> ...
python|numpy|vector
2
362,795
43,561,749
How to force numpy to accept objects as float?
<p>Right now numpy throws an error if I try to feed it objects when dtype = 'float'</p> <p>However floats are also an object. How can I make numpy treat my object like a float?</p> <p>Edit: I have an object that returns a float upon multiplication and addition. I want to treat it as a float as it becomes a float afte...
<p>If you want to typecast your resultant numpy array to float values then use <code>astype($TYPE)</code> </p> <pre><code>&gt;&gt;&gt; x = np.array([1, 2, 2.5]) &gt;&gt;&gt; x array([ 1. , 2. , 2.5]) &gt;&gt;&gt; &gt;&gt;&gt; x.astype(float) array([ 1. , 2. , 2.5]) </code></pre> <p>Refer <a href="https://docs.sci...
python|numpy|object|floating-point
1
362,796
1,972,877
MATLAB's griddata3 for NumPy?
<p>I realize that there is a griddata for <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow noreferrer">NumPy</a> via <a href="http://en.wikipedia.org/wiki/Matplotlib" rel="nofollow noreferrer">Matplotlib</a>, but is there a griddata3 (same has griddata, but for higher dimensions)?</p> <p>In other words, I ha...
<p>Not sure how you intend to render a surface of a scalar function of 3 variables, except perhaps using cutplanes or something similar. <a href="http://code.enthought.com/projects/mayavi/" rel="nofollow noreferrer">Mayavi</a> (really <a href="http://www.vtk.org/" rel="nofollow noreferrer">VTK</a> which powers Mayavi) ...
python|numpy|analysis|interpolation|scientific-computing
1
362,797
72,883,534
Fill the dataframe values from other dataframe in pandas python
<p>I have 2 dataframes df1 and df2. df1 is filled with values and df2 is empty.</p> <p>df1 and df2, as it can be seen, both dataframes's index and columns will always be same, just difference is df1 doesn't contain duplicate values of columns and indexes but df2 does contain.</p> <p>How to fill values in df2 from df1, ...
<p>IIUC, you want to <code>update</code>:</p> <pre><code>df2.update(df1) print(df2) 1 1 2 2 3 4 1 1.0 1.0 0.2 0.2 0.2 0.8 1 1.0 1.0 0.2 0.2 0.2 0.8 2 0.2 0.2 1.0 1.0 0.2 0.8 2 0.2 0.2 1.0 1.0 0.2 0.8 3 0.2 0.2 0.2 0.2 1.0 0.8 4 0.8 0.8 0.8 0.8 0.8 1.0 </code></pr...
python|pandas|dataframe
2
362,798
73,105,390
Making two dictionaries from a pandas dataframe
<pre><code>df = pd.DataFrame({'A':['a_o','a','b_o','b','c'],'B':[1,0,1,1,0],'C':[99,24,67,89,91]}) </code></pre> <p>For the above dataframe df, I want to make two dictionary as below:</p> <pre><code> dict1 = {'a_o':99,'b_o':67} dict2 = {'a':0,'b':1,''c':0} </code></pre> <p>What I want to do is, for all entries ending ...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>m = df.A.str.endswith(&quot;_o&quot;) dict1 = dict(zip(df.loc[m, &quot;A&quot;], df.loc[m, &quot;C&quot;])) dict2 = dict(zip(df.loc[~m, &quot;A&quot;], df.loc[~m, &quot;B&quot;])) print(dict1) print(dict2) </code></pre> <p>Prints:</p> <pre class="lang-py pret...
pandas|dataframe|dictionary
1
362,799
72,837,772
Download all of csv files of tensorboard at once
<p>I wanted to download the data of all my runs at once in tensorboard: <a href="https://i.stack.imgur.com/GPKJL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GPKJL.png" alt="enter image description here" /></a></p> <p>But it seems there's not a way to download all of them in one click. Does anyone...
<p>This can lead to your answer!</p> <p><a href="https://stackoverflow.com/a/73409436/11657898">https://stackoverflow.com/a/73409436/11657898</a></p> <p>that's for 1 file, but, it's ready to put into a loop</p>
python-3.x|tensorflow|tensorboard
1