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
14,600
72,272,848
How to merge DataFrames on their columns index places?
<p>Suppose I have two dataframes (note column indices):</p> <p><a href="https://i.stack.imgur.com/mipdp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mipdp.png" alt="enter image description here" /></a> = A =</p> <pre><code> 2 3 4 0 A1 A1 A1 1 A2 A2 A2 2 A3 A3 A3 ...
<p>Let us do <code>reindex</code> after <code>join</code></p> <pre><code>C = A.join(B) C = C.reindex(range(C.columns.max() + 1), axis=1) </code></pre> <hr /> <pre><code> 0 1 2 3 4 5 6 7 8 9 0 NaN NaN A1 A1 A1 NaN B1 B1 B1 B1 1 NaN NaN A2 A2 A2 NaN B2 B2 B2 B2 2 NaN NaN A3 A3 A3 NaN...
python|pandas|dataframe
2
14,601
72,244,953
What would be the equivalent code of following google finance query in python?
<p>I'm trying to fetch weekly EOD data in python using yfinance module. I wanna use the same format of the excel code given below. gives me weekly closes (<strong>Friday</strong>)</p> <pre><code>=GOOGLEFINANCE(&quot;NIFTY_50&quot;, &quot;close&quot;, DATE(2021,2,15), DATE(2022,5,16), &quot;weekly&quot;) </code></pre> ...
<p>Whilst running daily data within <code>df = yf.download()</code>, then filtering for index in periods, i.e. <code>df = df[df.index.isin(periods)]</code> solved the &quot;Friday's only&quot; problem, you experienced that there were missing weeks.</p> <p>To solve this you could add an additional line:</p> <pre><code>d...
python|pandas|yfinance
0
14,602
50,422,404
Save and export dtypes information of a python pandas dataframe
<p>I have a pandas DataFrame named df. With <code>df.dtypes</code> I can print on screen:</p> <pre><code>arrival_time object departure_time object drop_off_type int64 extra object pickup_type int64 stop_headsign object stop_id object stop_sequence int64 trip_id ...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dtypes.html" rel="noreferrer"><code>pd.DataFrame.dtypes</code></a> returns a <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html" rel="noreferrer"><code>pd.Series</code></a> object. This means you can mani...
python|json|pandas|dataframe|series
19
14,603
50,493,027
Changing positive(+) and negative(-) signs to integers in python
<p>I have a dataframe with the following column:</p> <pre><code>A + + - + - </code></pre> <p>How do I convert this column into integer values. So that I could multiply it to other numerical values?</p> <p>Therefore, all '+' would be replaced by 1 and '-' by -1.</p>
<p>You can use:</p> <pre><code>df.A = df.A.map({'+': 1, '-': -1}) </code></pre>
python|pandas
9
14,604
50,600,091
Pandas how to skim data frame for string from another df and get all incomon to new df
<p>I have two csvs full of contact information. My aim is to check if data from any cell in the first one are anywhere in the second one, and if so copy whole row, in which info was found and append it to new DataFrame. Is there any way to get output in well formated df?</p> <pre><code>Registered = [] string = [] o = ...
<p>If I understand you right, you want to extract those records that do exist in both DataFrames? If so, the approach from Kallol is not the worst idea but instead of removing the duplicated entries we want to keep the duplicated entries:</p> <pre><code> df_result = pd.concat([df1, df2]) df_result = df_result[df_resu...
python|pandas|dataframe
0
14,605
50,492,022
How to insert a character in a list, based on the consecutive appearance of two elements from another list? Python
<p>I have a DataFrame with a lot of strings and a function that inserts a character in a string, according to a condition. The problem is that my code somehow sees the input string <code>s</code> wrongly.</p> <p>The list <code>s</code> consists of elements from two lists: (1) member list (2) non-member list. My goal i...
<p>You can use shift to figure out where that condition is met. </p> <pre><code>mask = ((df['string'].isin(members)) &amp; (df['string'].shift(-1).isin(non_members)) &amp; (df['string'].shift(-2).isin(non_members))) </code></pre> <p>One way to insert in the rows in between might be to do something...
python-3.x|list|pandas
1
14,606
45,535,946
not picking up the first row of data into dataframe
<p>I am reading in a csv which looks like:</p> <pre><code>date total_pnl_per_pos 10/01/2006 -0.027 11/01/2006 0.34400804 12/01/2006 0.894075999 13/01/2006 -0.221139488 </code></pre> <p>However when I use the following code to read the .csv into a data-frame (df):</p> <pre><cod...
<p>You need parameter <code>header=0</code> for read first row of file as column names.</p> <p>Or remove parameter <code>names</code> if same values as column names, then is necessary remove <code>header=1</code> also.</p>
python|pandas
0
14,607
45,333,683
Complex Pandas Dataframe Manipulation
<p>I have a data frame that looks something like this:</p> <pre><code>import pandas as pd df= pd.DataFrame({'ID1':['A','B','C','D','E'],\ 'ID2':['B','A','D','C','E'],\ 'Account':['94000','94500','94000','18300','94500'],\ 'Amount':[100,-100,50,-50,100],\ ...
<p>Your explanation is a bit unclear, but I think you want this:</p> <pre><code>mask = df[df.Account == '94500'].ID2 df.loc[df.ID1.isin(mask),"Match"] = True Account Amount ID1 ID2 Match 0 94000 100 A B True 1 94500 -100 B A - 2 94000 50 C D - 3 18300 -50 D C - ...
python|pandas|dataframe
2
14,608
45,281,502
Return values from one pandas data frame column that match a repeating index
<p>I have a data frame like so:</p> <pre><code>index. columnA. columnB. columnC. 1. data. data. data. 2. data. data. data. 3. data. data. data. 4. data. data. data. 1. data. data. data. 2. data. data....
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>loc</code></a>:</p> <pre><code>df = df.loc[3., 'columnA.'] print (df) index. 3.0 data. 3.0 data. 3.0 data. 3.0 data. Name: columnA., dtype: object </code></pre>
python|pandas|dataframe
2
14,609
45,662,858
Concatenate two DataFrames into one MultiIndex sharing the same DateTimeIndex
<p>I could concatenate two DataFrames df1 &amp; df2 into one df but I somehow could not get the "stack" structure that I need - see attached image.</p> <p>How do I get df1 &amp; df2 to combine to share one DateTimeIndex like the one in a "stack" structure?</p> <p><a href="https://i.stack.imgur.com/mMojg.png" rel="nof...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_frame.html" rel="nofollow noreferrer"><code>to_frame</code></a>:</p> <pre><code>df = pd.DataFrame({'AAPL':[1,3,4], 'GOOG_L':[6,7,8]}, index=pd.date_range('2012-01-01', periods=3)) print (df) ...
python|pandas|dataframe|multi-index
1
14,610
62,865,735
How to count number of identical, sequential values in a column with python/pandas?
<p>Say I have a dataframe such as:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'A': [1, 1, 2, 3, 3, 3, 1, 1]}) </code></pre> <p>I'd like to count the number of time the current column value has been seen in a row previous. For the above example, the output would be:</p> <pre class="lang-py pr...
<p>Try this method:</p> <pre><code>df.groupby((df['A'] != df['A'].shift()).cumsum()).cumcount() + 1 </code></pre> <p>Output:</p> <pre><code>0 1 1 2 2 1 3 1 4 2 5 3 6 1 7 2 dtype: int64 </code></pre> <h3>Details</h3> <p>Use equality to check between current row and next row, then <code>cumsum</co...
python|pandas|time-series|series
3
14,611
62,688,967
Calling a function is resulting in a required positional argument error
<p>I'm sure I'm just missing something obvious but here is the function and how I am calling it</p> <pre><code>def read_csv(fin): df = pd.read_csv(fin, sep='\t', low_memory=False) return df df_p = read_csv('data.txt') </code></pre> <p>I am getting the following error</p> <pre><code>TypeError: read_csv() missi...
<p>You need to indent the read_csv line. You also have an extra comma at the end of the function call.</p> <pre><code>def read_csv(fin): df = pd.read_csv(fin, sep='\t',low_memory=False) </code></pre>
python|pandas|typeerror|opencsv
0
14,612
62,744,654
How to slice the Time in Hours and Minutes in Pandas DataFrame
<p>I am trying to split the Time column from my dataset. The Time column has a value like this '2324' instead of '23:24'. I have used this command df['MINUTES']=df['MINUTES'].str[1:3]. but it didn't work accurately, since the time column is based on 24 hours. So '2324' showing as '23:32' which is incorrect.How do I spl...
<p>I am not sure where did the issue arise, since having 24 hrs time shouldn't affect the script. Here's an example that seems to match the expected output:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Example':['1242','1342','1532','1643','1758','1821','1902','0004','2324']}) df['Hour'] = df['Example'].str[:...
python|pandas
0
14,613
62,816,408
How can I limit a pandas time series to the n last seconds?
<p>I've a pandas time series</p> <pre><code>time_series = pd.Series(data=[3,4,5], index=pd.DatetimeIndex(['2020-07-07 00:06:00.283', '2020-07-07 00:06:02.542', '2020-07-07 00:06:02.829']), name='I')) </code></pre> <p>with ISO formatted <code>datetime</code> timestamps as <a href="https://pandas.pydata.org/pandas-docs/s...
<p>You can take the last value of your index and substract a custom time step from it and then select all indices with larger values</p> <pre><code>n_sec = 1 time_series.index = pd.to_datetime(time_series.index, format=&quot;%Y-%m-%d %H:%M:%S&quot;) first_value = time_series.index.max() - pd.to_timedelta(n_sec, unit='s...
python|pandas|datetime|time-series|series
1
14,614
62,787,121
Append mutliple json requests to one dataframe
<p>I have multiple json requests with same information but in different location which is differentiate by polygons. Example of url : <code>www.dummy.com/whatever?type=fruit&amp;polygon=1,1;2,2</code>. I have about 20 requests on same <code>fruit</code> but different <code>polygon</code>.</p> <p>My goal is to append al...
<p>Formalizing my comments as an answer. Using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>pandas.concat()</code></a> you can merge a list of DataFrames into a single one.</p> <pre><code>import pandas as pd frames = [] for idx, polygon in poly...
python|pandas|list|dataframe
0
14,615
54,561,274
pandas *efficiently* copy the valid value to other rows by groups
<blockquote> <p>&quot;Premature optimisation is the root of all evil (but it's nice to have once you have an ugly solution)&quot; D.Knuth</p> </blockquote> <h2> Given this dataset</h2> <pre class="lang-py prettyprint-override"><code>from io import StringIO import pandas as pd csv = StringIO(&quot;&quot;&quot;country,y...
<p>You can group the data by country and use bfill and ffill</p> <pre><code>df.groupby('country').bfill().ffill() country year surface ground tot_water enviro depend 0 Yemen 2012 2.0 1.5 2.1 0.55 0.00 1 Yemen 2013 2.0 1.5 2.1 0.55 0.00 2 Yemen 2014 ...
python|pandas|dataframe|nan
1
14,616
54,664,338
Keras: How to load a model having two outputs and a custom loss function?
<p>I have trained a Keras (with Tensorflow backend) model which has two outputs with a custom loss function. I need help in loading the model from disk using the <code>custom_objects</code> argument.</p> <p>When compiling the model I have used the loss and loss_weights argument as follows:</p> <pre><code>losses = { ...
<p>If you can recompile the model on the loading side, the easiest way is to save just the weights: <code>model.save_weights()</code>. If you want to use save_model and have custom Keras layers, be sure they implement the <code>get_config</code> method (see <a href="https://github.com/keras-team/keras/issues/1927" rel=...
python|tensorflow|keras|keras-layer
1
14,617
73,744,146
Gradients not populating as expected
<p>Sorry, I know questions of this sort have been asked a lot, but I still don't understand the behavior of autograd.</p> <p>A simple example is below:</p> <pre><code>ce_loss=torch.nn.BCELoss() par=torch.randn((1,n),requires_grad=True) act=torch.nn.Sigmoid() y_hat=[] for obs in data: y_hat.append(act(par@obs)) lo...
<p>It is simply because <code>torch.tensor(...)</code> create a <strong>new leaf</strong> of the computational graph. It means by definition that the operation inside <code>torch.tensor</code> are blocked, in particular the computation using elements of <code>par</code> (and so, the grads are never computed). Note that...
pytorch
0
14,618
73,534,045
Shapes (None, 40, 100) and (None, 64, 100) are incompatible
<p>I am trying simple model for prediction sha1 hashes of strings, which should take the dataset consisting of string:sha1_string.</p> <p>Dataset is generated in code.</p> <p>I am trying to train model, but it fails with error</p> <pre><code>Shapes (None, 40, 100) and (None, 64, 100) are incompatible </code></pre> <p>B...
<p>I suggest you flatten your input</p> <pre><code>X = X.reshape(X.shape[0], -1) y = y.reshape(y.shape[0], -1) </code></pre> <p>and adjust the input shape of the first layer from <code>(64,len(chars))</code> to <code>(64*len(chars),)</code> and the output size of the last layer from <code>len(chars)</code> to <code>40...
python|tensorflow|machine-learning|keras
1
14,619
73,568,407
Correct way to iterrate over two dataframes to set specific values based on the value of another df
<p><em>Edited to add easier to reproduce dataframe</em></p> <p>I have two dataframes that look something like this:</p> <p>df1</p> <pre><code>index = [0,1,2,3,4,5,6,7,8] a = pd.Series([John Smith, John Smith, John Smith, Kobe Bryant, Kobe Bryant, Kobe Bryant, Jeff Daniels, Jeff Daniels, Jeff Daniels],index= index) b = ...
<p>If I correctly understand the output you are after (stack overflow tip: it can be useful to provide a sample of your desired output to help people trying to answer your question), then this should work:</p> <pre><code># make the Date column into datetime type so it is easier to filter on df1 = df1.assign(Date=pd.to_...
python|pandas|dataframe
0
14,620
73,819,917
Multi-level column pivot_table pandas DataFrame
<p>I have the following <code>DataFrame</code>:</p> <pre><code>df_1 Name Date1 Date1 Date1 Date1 Date2 Date2 Date2 Date2 (...) 1 MB Prices On_net Off_net Obs Prices On_net Off_net Obs 2 0 nan nan nan nan nan nan nan nan 3 10 1 3 4 ...
<p>You can use <code>.stack()</code> to <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.stack.html#pandas.DataFrame.stack" rel="nofollow noreferrer">stack</a> the first level from columns to index. You can then drop the old index.</p> <pre class="lang-py prettyprint-override"><code>df.stack(0).re...
python|pandas|pivot-table
0
14,621
71,371,551
Torch does not find GPU on pytorch-training:1.10.0-gpu-py38 container
<p>Torch does not find Cuda on GPU instance and official SageMaker training container</p> <pre><code>763104351884.dkr.ecr.eu-west-2.amazonaws.com/pytorch-training:1.10.0-gpu-py38-cu113-ubuntu20.04-sagemaker </code></pre> <p>The same outcome is seen when running container on SageMaker Notebook instance <code>ml.p3.2xlar...
<p>You need to expose the GPUs in docker run. For example:</p> <pre><code>docker run --gpus all -it --entrypoint /bin/bash 709fa9395949 </code></pre>
pytorch|amazon-sagemaker
0
14,622
71,340,574
Pandas: Vectorize for loop when values are interdependent and based on prior values?
<p>Since for loop takes so long for data of several Mb, I have to optimize the procedure by vectorization. But I haven't found any good solution on my situation as below.</p> <pre class="lang-py prettyprint-override"><code>data = {'A':[0,0,1,0,1,0,0,0,0], 'B':[0,1,0,0,0,0,0,1,1]} df = pd.DataFrame(data) df['C']...
<p><code>df.shift()</code> shift the whole dataframe for each iteration which is very inefficient. Besides this <code>loc</code> tends to be quite slow. You can do it once. In fact, you do not need to create a new dataframe, you can store the result in temporary variables or use <code>i-1</code> (with a conditional). N...
python|pandas|performance|for-loop|optimization
1
14,623
71,300,672
SUMIFs for all the rows in python
<p>I am trying to replicate SUMIFs in Python that I have in my excel by creating a new column called SumifsZ. SumifsZ is the desired output i would need in python.</p> <p>my formula in first row of SumifsZ column is =SUMIFS(C:C,B:B,&quot;Z&quot;,A:A,A2) , i would need that to be replicated in 3rd,4th rows.... etc.</p> ...
<p><strong>Edited:</strong></p> <hr /> <p>You can approach this problem by slicing the data frame with <code>loc</code> and using <code>groupby</code> on &quot;Product&quot;. This can be converted to a <code>dict</code> and used in a lambda function via <code>apply</code> as follows:</p> <pre><code>Data = pd.DataFrame(...
python|pandas|dataframe|sumifs
1
14,624
71,178,634
question when using interpolate for missing value
<p>I had a dataset looks like below:</p> <pre><code>import pandas as pd test = pd.DataFrame({ 'date': ['2018-01-03 00:00:00', '2018-01-04 00:00:00', '2018-01-05 00:00:00'], 'coal': [2669.0, np.nan ,2731.0], 'hydro': [222.0, np.nan ,230.0], 'unit': ['Gwh', 'Gwh', 'Gwh'], }) test['date'] = pd.to_datetim...
<p>You just need to interpolate the given columns</p> <pre class="lang-py prettyprint-override"><code>cols_to_interpolate = [&quot;coal&quot;, &quot;hydro&quot;] test[cols_to_interpolate] = test[cols_to_interpolate].interpolate() </code></pre>
python|pandas
1
14,625
71,308,983
How do i set filtering conditions per group?
<p>For example, with the example dataset below, how do I set a filtering condition using jupyter notebook where I can find out who has 2 or more results of &quot;Number of Candies&quot; more than or equal to 3.1?</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">ID</...
<p>If you can use <a href="/questions/tagged/pandas" class="post-tag" title="show questions tagged &#39;pandas&#39;" rel="tag">pandas</a>, we could do this in two steps:</p> <ol start="0"> <li><p>Of course, first make sure you're using a numeric dtype in your &quot;Number of Candies&quot; column:</p> <pre><code>df[&quo...
python|pandas|dataframe
2
14,626
52,135,625
Solving functional equations with tensorflow
<p>Let us consider the functional equation </p> <p><a href="https://i.stack.imgur.com/ROtRG.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ROtRG.gif" alt="enter image description here"></a></p> <p>Mathematically, we know how to solve that equation in closed form, but what if we look for an approxi...
<p>One approach would be to simply run through the network with <code>x+1</code> as well. That is, for a two-layer network, you could have a model that looks as follows:</p> <pre><code>num_units_layer_1 = 200 num_units_layer_2 = 200 x = tf.placeholder(tf.float32, [None, 1]) seed = 42 weights = { 'hidden1': tf.V...
python|tensorflow
2
14,627
52,032,073
How to extract cell state from a LSTM at each timestep in Keras?
<p>Is there a way in Keras to retrieve the cell state (i.e., <em>c</em> vector) of a LSTM layer at every timestep of a given input?</p> <p>It seems the <code>return_state</code> argument returns the last cell state after the computation is done, but I need also the intermediate ones. Also, I don't want to pass these c...
<p>I was looking for a solution to this issue and after reading the guidance for creating your own custom RNN Cell in tf.keras (<a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/AbstractRNNCell" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/layers/AbstractRNNCell</a>), ...
tensorflow|keras|deep-learning|lstm|rnn
3
14,628
52,184,242
NumPy - calculate histogram intersection
<p>The following data, represent 2 given histograms split into 13 bins:</p> <pre><code>key 0 1-9 10-18 19-27 28-36 37-45 46-54 55-63 64-72 73-81 82-90 91-99 100 A 1.274580708 2.466224824 5.045757621 7.413716262 8.958855646 10.41325305 11.14150951 10.91949012 11.29095648 10.95054297 10.10976255 ...
<p>Since you have the same number of bins for both of the histograms you can use:</p> <pre><code>def histogram_intersection(h1, h2): sm = 0 for i in range(13): sm += min(h1[i], h2[i]) return sm </code></pre>
python|numpy|statistics|histogram
7
14,629
52,375,305
Tensorflow, large image inference - not enough memory
<p>I have trained a super-resolution model. The inference works:</p> <pre><code>def inference(self, filename): img_in = misc.imread(filename) / 255.0 res = self.sess.run(self.out, feed_dict={ self.x: [img_in], self.is_training: False, self.lr_input: 0.0 })[0] * 255.0 image = misc.toimage(res, cmin=0, cmax=...
<p>Solved it by splitting the image into pieces, processing them one by one and combining them. To avoid visible "split lines" in the output image, I repeat the process described above with different piece sizes and calculate the mean.</p> <p>I ended up with this:</p> <pre><code>def inference(self, filename, self_ens...
python|ubuntu|tensorflow|ram
2
14,630
60,522,484
Sum to dataframes based on row and column
<p>Given to Dataframes df_1 </p> <pre><code>Code | Jan | Feb | Mar a | 1 | 2 | 1 b | 3 | 4 | 3 </code></pre> <p>and df_2</p> <pre><code>Code | Jan | Feb | Mar a | 1 | 1 | 2 c | 7 | 0 | 0 </code></pre> <p>I would like to sum these to tables based on the row and colum. So my result datafra...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> and aggregate <code>sum</code>:</p> <pre><code>df = pd.concat([df_1, df_2]).groupby('Code', as_index=False).sum() print (df) Code Jan Feb Mar 0 a 2 3 3 1 b...
python|pandas
3
14,631
60,748,912
How to check if column has numbers (scientific numbers included), keep it if it is and make it blank otherwise - Python Pandas
<p>I'm trying to currently clean this dataset but with no luck. This is the initial code I used: </p> <pre><code>import pandas as pd Location =r'file.rpt' df = pd.read_fwf(Location, delim_whitespace=True) df=df.iloc[12:] #need to optimise this df2 = df.rename({'*********************************************************...
<p>As described <a href="https://stackoverflow.com/questions/36814100/pandas-to-numeric-for-multiple-columns">here</a>, the solution is:</p> <pre><code>df2 = df2.apply(pd.to_numeric, errors='coerce') </code></pre> <p>Afterwards you have NaN values in your dataframe. That is the blank in pandas.</p>
python|pandas
0
14,632
72,649,330
Update values of a dataframe based on conditions from another dataframe
<p>I'm trying to map values (Weight of Evidence) from a dataset to another.</p> <p>My original dataset looks as follows:</p> <p><a href="https://i.stack.imgur.com/cwh11.png" rel="nofollow noreferrer">dataframe 1</a></p> <p>The aim is to substitute these rows with the corresponding weight of evidence values.</p> <p>I wo...
<p>This should do the trick:</p> <pre><code>df = pd.DataFrame({'loan_type':[1,2,1,3], 'var_1':[1,0,1,2], 'var_2':[1,1,1,1], 'var_3':[1,1,1,1], 'var_4':[1,0,1,0], 'target':[0, 0, 0,0 ]}) woe_df = pd.DataFrame({'variable':['loan_type', 'loan_type', 'loan_type'...
python|pandas
0
14,633
72,766,791
How to filter like if any group in the last row is negative or positive, just show that group. Pandas
<p>I want to filter the last row of each group. For example, you can see that ID 101 in the last row, qty is 20, ID 105 is -3, ID 106 is -12. I want to filter like if any group in the last row is negative or positive, just show that group.</p> <p>Here is a sample dataframe.</p> <pre><code>import pandas as pd d = {'id':...
<p>Use a boolean mask:</p> <pre><code>m = df31.groupby('id')['qty'].transform('last') &gt;= 0 </code></pre> <p>Output:</p> <pre><code># Positive &gt;&gt;&gt; df31[m] id qty 0 101 10 1 101 -2 2 101 20 # Negative &gt;&gt;&gt; df31[~m] id qty 3 105 50 4 105 -3 5 106 50 6 106 -12 </code></pre...
python|pandas|pandas-groupby
2
14,634
72,673,338
How to select and insert value from another DataFrame by id?
<p>For example, I have two DataFrames:</p> <pre><code>a = [{'id':123, 'name': 'AAA'}, {'id':456, 'name': 'BBB'}, {'id':789, 'name': 'TTT'}] df1 = pd.DataFrame(a) print(df1) b = [{'id':123}] df2 = pd.DataFrame(b) print(df2) </code></pre> <p>I need to add the new column in DataFrame <code>df2['name']</code>and to add th...
<p>An alternative to <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>DataFrame.merge</code></a> is using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a...
python|pandas|dataframe
0
14,635
72,528,842
How to make multiple line charts in Python (or use facet charts)?
<p>I have the following dataframe:</p> <pre><code>df = {'website': ['google','google','google','google','google','google','google','google','google','google','google','google', 'facebook','facebook','facebook','facebook','facebook','facebook','facebook','facebook','facebook','facebook','facebook'...
<p>You can use <a href="https://seaborn.pydata.org/generated/seaborn.relplot.html" rel="nofollow noreferrer">seaborn.relplot</a> for this. Consider the following dataframe:</p> <pre><code>month = np.random.choice(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'Sept...
python|pandas|plotly
0
14,636
59,576,387
How to create CNN structure which is depend on the number of input images with tensorflow?
<p>I am building a CNN structure which is able to take multiple images as input. The number of inputs is varying —- for example it can be 3 or 4 or any other number ideally.</p> <p>Here is what I want:</p> <p>When input 3 images, there will be 3 streams of vgg16 which share the same weights.</p> <p>When input 4 imag...
<p>Consider an example of a <a href="https://www.tensorflow.org/api_docs/python/tf/compat/v1/placeholder" rel="nofollow noreferrer">TensorFlow placeholder</a> :</p> <pre><code>x_train_placeholder = tf.placeholder(tf.float32, [None, 256, 256, 3]) </code></pre> <p>In the above placeholder <code>None</code> is used for ...
python|tensorflow
0
14,637
59,832,578
How to use a pretrained tensorflowlite model for input interpretation
<p>I am using a pre-trained tensorflow light model to get some sample output using a short program I created:</p> <pre class="lang-py prettyprint-override"><code>import cv2 as cv import numpy as np import os import tensorflow as tf import numpy as np def decode_img(img): # convert the compressed string to a 3D uint...
<p>Was able to get it to working using the following code:</p> <pre class="lang-py prettyprint-override"><code>img = cv.imread('photos\standing\\3.jpg') img = tf.reshape(tf.image.resize(img, [257,257]), [1,257,257,3]) model = tf.lite.Interpreter('models\posenet_mobilenet_v1_100_257x257_multi_kpt_stripped.tflite') mode...
python|tensorflow|machine-learning|tensorflow2.0|tensorflow-lite
1
14,638
32,228,967
Compile numpy WITHOUT Intel MKL/BLAS/ATLAS/LAPACK
<p>I am using <code>py2exe</code> to convert a script which uses <code>numpy</code> and am getting a very large resulting folder, and it seems a lot of the large files are from parts of the <code>numpy</code> package that I'm not using, such as <code>numpy.linalg</code>.</p> <p>To reduce the size of folder that is cre...
<p>According to the <a href="http://docs.scipy.org/doc/numpy/user/install.html#disabling-atlas-and-other-accelerated-libraries" rel="nofollow noreferrer">official documentation</a>:</p> <blockquote> <h1>Disabling ATLAS and other accelerated libraries</h1> <p>Usage of ATLAS and other accelerated libraries in Numpy can b...
python|numpy|py2exe|lapack|blas
9
14,639
40,540,368
How to convert Pandas Dataframe to csv reader directly in python?
<p>I have a csv file on with millions of rows. I used to create a dictionary out the csv file like this</p> <pre><code> with open('us_db.csv', 'rb') as f: data = csv.reader(f) for row in data: Create Dictionary based on a column </code></pre> <p>Now to filter the rows based on some conditions I use pan...
<p>You could do something like this..</p> <pre><code>import numpy as np import pandas as pd from io import StringIO import csv #random dataframe df = pd.DataFrame(np.random.randn(3,4)) buffer = StringIO() #creating an empty buffer df.to_csv(buffer) #filling that buffer buffer.seek(0) #set to the start of the strea...
python|csv|pandas|dataframe
10
14,640
40,673,892
Pandas Finding Index From Values In Column
<p>In using Python Pandas on a big dataset, how can I find the index based on the value in the column, in the same row?</p> <p>For example, if I have this dataset...</p> <pre><code> Column Item 1 0 Item 2 20 Item 3 34 ... Item 1000 12 </code></pre> <p>... and if I have this value 17 in one of ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="noreferrer"><code>boolean indexing</code></a>:</p> <pre><code>df.index[df.Column == 17] </code></pre> <p>If need excluding row 0:</p> <pre><code>df1 = df.iloc[1:] df1.index[df1.Column == 17] </code></pre> <p>Sample:</p>...
python|pandas
9
14,641
40,652,830
How to define your own fill method parameter in pandas (python)?
<p>Some DataFrame and Series methods have the method parameter. For example:</p> <pre><code>DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs) </code></pre> <p>and the method parameter can take the following values: {None, ‘backfill’/’bfill’, ‘pad’/’ffill’, ‘neare...
<p>In your <strong>very specific</strong> case (average of the nearest values), you can do this:</p> <pre><code>import pandas as pd import numpy as np col1 = np.array([0, 1, np.nan, 4]) col2 = np.array([0, np.nan, 2, 5]) df = pd.DataFrame({"col1" : col1, "col2" : col2}) # Trick: average forward and backward fill df...
python|pandas|numpy
0
14,642
61,892,439
detect events of overlapping signals from two columns in a pandas dataframe
<p>I have a dataframe with two columns A and B. The values in A and B can be either 0.0 or 1.0 (binary state).</p> <p>The signals are most of the time all 0.0, with occasional 1.00. I want to detect each event whereby both A and B are 1.00 and overlapping (inner join).</p> <p>Here's a sample code:</p> <pre><code>i...
<p>What about multiplying the two signals and find the indexes where the product is non zero?</p> <pre><code>import numpy as np a = df['A'].dropna().values b = df['B'].dropna().values events_idxs = np.where(a*b &gt; 0.5)[0] </code></pre> <p>(I put a 0.5 threshold because it looks like your signals are not exactly 0...
python|pandas|dataframe
1
14,643
61,646,417
Model object has no attribute '_is_graph_network', when I try to save my model to tflite
<p>Tensorflow version - 1.14.0 Python version - 3.7.5 </p> <p>This is the model I created</p> <pre><code>from tensorflow import keras import tensorflow.python.keras.backend as K from tensorflow.python.keras import callbacks from tensorflow.python.keras import Sequential from tensorflow.python.keras.models import Mode...
<p>You need to pass <code>model_v1</code> to converter, not <code>history_v1</code>.</p> <p><a href="https://www.tensorflow.org/lite/convert/python_api#converting_a_keras_model_" rel="nofollow noreferrer">https://www.tensorflow.org/lite/convert/python_api#converting_a_keras_model_</a></p>
python|tensorflow|keras|tf.keras|tensorflow-lite
0
14,644
61,685,773
model.fit() results in 'TypeError: 'module' object is not callable'
<p>I am experiencing a TypeError anytime I am trying to train my model with tensorflow. So far: </p> <pre><code>history = model.fit(train_batches, steps_per_epoch=train_steps, class_weight=class_weights, validation_data=validation_batches, ...
<p>I was calling a module instead of the class that is contained in the module.</p> <pre><code># Create an Image Data Generator to input later into our model. data_generation = ImageDataGenerator( # Use Inception ResNet v2 preprocessing_function=tf.keras.applications.inception_resnet_v2.preprocess_input ) </c...
python|tensorflow|machine-learning|keras|deep-learning
0
14,645
57,968,999
RuntimeError: Attempting to capture an EagerTensor without building a function
<p>I use <code>tf.data.datset</code> API and use residual network. When I run code for TensorBoard for visualizing my embeddings I have this error, but when I use a two layers network I don't have this problem.</p> <pre><code>def load_and_preprocess_from_path_label(path, label): return load_and_preprocess_image(pa...
<p>The error is possibly due to Tensorflow version</p> <p>Running the following code worked for me:</p> <pre><code>import tensorflow.compat.v1 as tf </code></pre> <h1>Correct function:</h1> <pre><code>tf.disable_v2_behavior() </code></pre>
python|tensorflow|runtime-error
4
14,646
57,779,864
Resolving error when merging dataframes on two columns
<p>I am trying to merge two dataframes (D1 &amp; R1) on two columns (Date &amp; Symbol) but I'm receiving this error <code>"You are trying to merge on object and int64 columns. If you wish to proceed you should use pd.concat"</code>.</p> <p>I've been using pd.merge and I've tried different dtypes. I don't want to conc...
<p>In your description of DataFrames we can see,<br> In D1 DataFrame column Date has type "object"<br> In R1 DataFrame column Date has type "int64".</p> <p>Make types of these columns the same and everything will be OK.</p>
pandas|merge
2
14,647
57,756,541
How to make my own xticklabels on subplot containing years, using dataframe index column with monthly dates?
<p>I have two dataframes with data that I want to present in a subplot consisting of two separate plots. In the first subplot, I want to plot monthly data (df_monthly) of this format (index is Date column):</p> <pre><code>Date Col1 ... Col9 2000-01-01 00:00:00+01:00 0.45 ... 0.34 200...
<p>Here <code>df</code> is your monthly dataframe. I assume here that <code>'Date'</code> is the index of the dataframe, as suggested by your code.</p> <pre><code>fig, axes = plt.subplots(1, 2) #plotting the yearly plot, you have your code for this axes[0] = ... #plotting the monthly plot axes[1].plot(df['Col1'])...
python|pandas|plot|label
0
14,648
58,093,506
Generator not being recognized when passing validation data to .fit in Keras Sequential
<p>The exact error: </p> <blockquote> <p>ValueError: When passing validation_data, it must contain 2 (x_val, y_val) or 3 (x_val, y_val, val_sample_weights) items, however it contains 39 items</p> </blockquote> <p>I literally cannot find that error anywhere except the source code.</p> <pre><code>model.fit( tra...
<p>It's not exactly true that you have to train and validate on the same kind data, such as array or generator, but you can't do that with the same function.</p> <p>You could train on your array, and validate on your generator but this would take 2 different function calls, and means you won't get validation metrics a...
python|numpy|machine-learning|keras
1
14,649
33,997,823
TensorFlow MLP not training XOR
<p>I've built an MLP with Google's <a href="http://www.tensorflow.org/" rel="noreferrer">TensorFlow</a> library. The network is working but somehow it refuses to learn properly. It always converges to an output of nearly 1.0 no matter what the input actually is.</p> <p>The <strong>complete code</strong> can be seen <a...
<p>In the meanwhile with the help of a colleague I were able to fix my solution and wanted to post it for completeness. My solution works <strong>with cross entropy</strong> and <strong>without altering the training data</strong>. Additionally it has the desired <strong>input shape of (1, 2)</strong> and <strong>ouput ...
python|machine-learning|neural-network|tensorflow|supervised-learning
9
14,650
36,923,502
Convert Varied Text Fields of Duration to Seconds in Pandas
<p>I have a dataframe that contains the duration of a trip as text values as shown below in the column driving_duration_text.</p> <pre><code>print df yelp_id driving_duration_text \ 0 alexander-rubin-photography-napa 1 hour 43 mins 1 ...
<p><strong>UPDATE:</strong></p> <pre><code>In [150]: df['seconds'] = (pd.to_timedelta(df['driving_duration_text'] .....: .str.replace(' ', '') .....: .str.replace('mins', 'min')) .....: .dt.total_seconds()) In [151]: df ...
python|python-2.7|datetime|pandas
2
14,651
36,905,967
Counting occurrences of a string in a column of a csv file
<p>I have a large csv file (over 66k rows) and I want to count the number of times a string appears in each row. I am focusing on one column in particular and each row in that column has a small sentence, as shown below: </p> <pre><code>Example of data: Sam ate an apple and she felt great Jill thinks the sky is purple...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.count.html" rel="nofollow"><code>str.count</code></a> with column <code>sentence</code>:</p> <pre><code>print df # sentence #0 Sam ate an apple and she felt great apple ...
python|string|csv|pandas
2
14,652
36,917,944
label 3d numpy array with scipy.ndimage.label
<p>I've got a large 3d numpy array which consists of ones and zeros. I would like to use the scipy.ndimage.label tool to label the features in each sub-array (2d).</p> <p>A subset of the 3d-array looks like:</p> <pre><code>import numpy as np from scipy.ndimage import label subset = np.array([[[1, 0, 0], ...
<p>I answered this question with the help of dan-man.</p> <p>I had to define a new 3D structure for the label tool:</p> <pre><code>import numpy as np from scipy.dimage import label str_3D = np.array([[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 1, 0], ...
python|arrays|numpy|scipy|ndimage
2
14,653
55,046,831
PyTorch model validation: The size of tensor a (32) must match the size of tensor b (13)
<p>I am a very beginner in case of machine learning. So for learning purpose I am trying to develop a simple CNN to classify chess pieces. The net already works and I can train it but I have a problem with my validation function. </p> <p>I can't compare my prediction with my <code>target_data</code> because my predict...
<p>Simply run "argmax" on the target as well:</p> <pre><code>_, target = torch.max(target.data, 1) </code></pre> <p>Or better yet, just keep the target around as <code>[example_1_class, example_2_class, ...]</code>, instead of 1-hot encoding.</p>
python|machine-learning|neural-network|conv-neural-network|pytorch
1
14,654
49,602,592
Bar chart or histogram for frequency of features in one week bins in Pandas
<p>I have a data frame as seen below (three columns are shown here):</p> <pre><code>Week/Year feature 40/2017 2 147 3 32 4 21 5 21 7 8 8 1 9 10 10 10 ...
<p>I suppose you're getting <strong>"TypeError: Empty 'DataFrame': no numeric data to plot"</strong> because the return of your lambda function is a string. You have two options, you convert your column only for plotting reasons or rewrite your lambda function to return a numeric value (float or int).</p>
python|pandas|dataframe|matplotlib
0
14,655
73,334,426
How to optimize successive numpy dot products?
<p>The bottleneck of some code I have is:</p> <pre><code>for _ in range(n): W = np.dot(A, W) </code></pre> <p>where n can vary, A is a fixed size MxM matrix, W is Mx1.</p> <p>Is there a good way to optimize this?</p>
<h3>Numpy Solution</h3> <p>Since <code>np.dot</code> is just a matrix multiplication for your shapes you can write what you want as <code>A^n*W</code>. With ^ being repeated matrix multiplication &quot;matrix_power&quot; and * matrix multiplication. So you can rewrite your code as</p> <pre><code>np.linalg.matrix_power(...
python|numpy|optimization|data-science|linear-algebra
3
14,656
73,343,915
How can I format date time string which is not date time format so that I can use it with pd.to_datetime()?
<p>I have a Pandas series of date time string. However, that date time string isn't properly formatted. Therefore, can I know how can I format the date time string in order to use it with <code>pd.to_datetime()</code>?</p> <p>e.g. <code>t = pd.Series(['20201023', '20201123', '20201012'])</code></p> <p>Thank you.</p>
<p>No need to pre-process the string. Use <a href="https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow noreferrer"><code>format='%Y%m%d'</code></a> directly in <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>pandas....
python|python-3.x|pandas|dataframe|python-datetime
1
14,657
73,205,311
How to export a Dataframe to Excel with divider lines using XlsxWriter
<p>I would like to export my df to excel using xlswriter but with format depending on the value of specific cells ie i have a df that look like that :</p> <pre><code>Date Data1 data2 01/01/1979 50.0. 10.0 01/01/1979 50.0. 11.0 02/01/1979 50.0. 11.0 02/01/1979 50.0. 11.0 02/01/1979 50.0. 11.0 03/01/1979 50.0. 11.0 03/01...
<p>Below script adds line to each row when <code>Date</code> is changed :</p> <p>Please change <code>delimiter</code> variable to whatever delimiter you desire.</p> <pre><code>delimiter = '-----' def f(x): return x.append(pd.DataFrame(delimiter, columns=df.columns, index=[('')])) df_updated = df.groupby('Date', s...
python|excel|pandas|xlsxwriter
1
14,658
73,226,523
Infer date from number in pandas series
<p>I have column in a pandas DataFrame called <code>df['latestCertificationDate']</code></p> <p>It contains a series of numbers like this:</p> <pre><code>0 1570406400000 1 1479427200000 2 1506556800000 3 1527724800000 4 1490140800000 ... 4630 1473811200000 4631 1601...
<p>using fromtimestamp of datetime and removing the last three zeros from the number, I get the following dates.</p> <p>is that what you're looking for?</p> <pre><code>df['time'].apply(lambda x: datetime.datetime.fromtimestamp((x//1000)) ).to_frame() </code></pre> <pre><code> time 0 2019-10-06 20:00:00 1 ...
python|pandas|date|datetime
1
14,659
73,388,871
Apply a kernel to selected pixels only within an image
<p>I'm trying to build a customized DCGAN in PyTorch for a project. The custom part is my own gaussian blur filter on the end of the generator that blurs only pixel values over a certain threshold. The issue is when I add the filter to the forward pass of the generator, the backward() call takes much longer. Without th...
<p>Yes, for backprop in pytorch a loop over the x and y coordinates of the image will be unbearably slow. Let <code>original</code> be <code>batch[i][j]</code> and <code>blurred</code> be the result when <code>kernel</code> is applied non-selectively over <code>original</code> in its entirety. For simplicity I'm omitti...
python|machine-learning|pytorch|convolution|generative-adversarial-network
0
14,660
73,331,305
ModuleNotFoundError: No module named 'tensorflow.contrib' Error
<p>I am getting such an error in the keras codes ,wrote in pycharm.Tried the solutions on the internet but I couldn't find a solution. Do you have any suggestions?</p> <p><a href="https://i.stack.imgur.com/3XWT2.png" rel="nofollow noreferrer">Error Image</a></p> <p><a href="https://i.stack.imgur.com/rzaYv.png" rel="nof...
<p>Please install the tensorflow and pillow using <code>pip install tensorflow</code> and <code>pip install pillow</code> then do a little changes as below while importing libraries to fix this error:</p> <pre><code>import numpy as np from PIL import Image from tensorflow import keras from tensorflow.keras.application...
python|tensorflow|keras|tensorflow2.0
1
14,661
34,891,539
scikit-learn: add clf.prediction() to different dataframe
<p>I've trained my RandomForestClassifier() and am now looking to add my predictions to my newly imported test DF which I'm calling df_test. </p> <p>I have added my feature columns to the df_test dataframe, for the clf.predict method to use. </p> <p>I cannot figure out how to use my clf.predict() method in a way to a...
<p>Assuming that <code>df_test[something]</code> contains the features, you can append a new column containing the predictions writing</p> <pre><code>df_test['prediction']=clf.predict(df_test[something]) </code></pre>
python|pandas|scikit-learn
2
14,662
35,028,460
Pandas: converting pivot to JSON
<p>I have the following Pandas pivot</p> <pre><code>Apple Green 5 Red 3 Yellow 4 Grapes Red 1 Green 3 </code></pre> <p>and want to convert this data to JSON like follows:</p> <pre><code>{ Apple: { Green : 5, Red: 3, Yellow...
<p>The DataFrame.to_json has several parameters for the orientation of the JSON.</p> <p>Try something like <code>pd.to_json(orient='records')</code>, if it does not work, check the others values of the orient variable in <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.DataFrame.to_json.ht...
python|json|pandas|to-json
0
14,663
35,303,450
pandas: Is it possible to filter a dataframe with arbitrarily long boolean criteria?
<p>If you know exactly how you want to filter a dataframe, the solution is trivial:</p> <p><code>df[(df.A == 1) &amp; (df.B == 1)]</code></p> <p>But what if you are accepting user input and do not know beforehand how many criteria the user wants to use? For example, the user wants a filtered data frame where columns ...
<p>I think the most elegant way to do this is using <code>df.query()</code>, where you can build up a string with all your conditions, e.g.:</p> <pre><code>import pandas as pd import numpy as np cols = {} for col in ('A', 'B', 'C', 'D', 'E'): cols[col] = np.random.randint(1, 5, 20) df = pd.DataFrame(cols) def fi...
python|pandas
5
14,664
67,565,371
How to initialize a triangular mesh in vtk
<p>I need to create a triangular mesh on vtk from a list of points that I have. The points are stored under <em>sphere</em>, which is a nx9 numpy array where each row represents the three points that make up one triangle. Right now I am doing this:</p> <pre><code>points = vtk.vtkPoints() triangles = vtk.vtkCellArray() ...
<p>Each InsertNextPoint returns a vtkIdType. Those are the numbers that should go into the 2nd parameter of the triangle's SetID.</p>
python|numpy|vtk|triangular|numpy-stl
1
14,665
67,323,553
Reshape Tensorflow RaggedTensor
<p>I have a 4D RaggedTensor of shape (batch_size, None, None, 100), I want to create from this a tensor of shape (batch_size, None, 100). So basically merging 1st and 2nd dimensions, but not including any padding ([1,2,3], [4] =&gt; [1,2,3,4]) and not converting to a dense tensor first. Is there a way to do this? If no...
<p>After some more reading and trying, I have found the answer, which requires using <a href="https://www.tensorflow.org/api_docs/python/tf/RaggedTensor#row_starts" rel="nofollow noreferrer">row_starts</a> twice for each of the two dimensions. The result loos like this:</p> <pre><code>row_starts = [my_ragged_tensor.val...
tensorflow|ragged-tensors
1
14,666
67,478,250
How to replace a pandas DataFrame column with lookup values from a dictionary?
<p>Assume I have the following simple pandas DataFrame:</p> <pre><code>df = pd.DataFrame({&quot;id&quot;: [1, 2, 3, 4, 5], &quot;country&quot;: [&quot;Netherlands&quot;, &quot;Germany&quot;, &quot;United_States&quot;, &quot;England&quot;, &quot;Canada&quot;]}) </code></pre> <p>and a dictionary with a...
<p>You can use pandas function <code>replace()</code> especially thought for these scenarios. Careful not to confuse it with python's built-in <code>.str.repace()</code> which doesn't take dictionaries.</p> <p>Try with:</p> <pre><code>df['country'] = df['country'].replace(abr) </code></pre>
python|pandas|dataframe|dictionary
6
14,667
67,337,455
how to convert Exponential value into Int in Graph
<pre><code>plt.figure(figsize=(28,8)) plt.xticks(rotation=90) a = df2.groupby('Province/State')['Confirmed'].sum().astype('int64') print(a) a.plot(kind = 'bar') </code></pre> <p>When I am trying to create graph for above code It's converting into the Exponential. How can I prevent That?</p>
<p>I do not know the size of your data set. But you can try this.</p> <pre><code>plt.ticklabel_format(useOffset=False,style='plain', axis='y') </code></pre>
python|pandas|numpy|matplotlib|seaborn
1
14,668
60,071,273
What is a faster alternative to itertools?
<pre><code> k = 7 n = 30 def f(k,n): p = [] for i in range(n): p.append(len(list(itertools.combinations([x for x in range(2**k)],i))) </code></pre> <p>The problem that the code above works slow and breaks with error for bigger values of variable. I've tried sklearn.cartesian, but got permutationa as a...
<p>The fastest solution is given by @jdehesa which uses multiplicative formula to compute (recursively) the <a href="https://en.wikipedia.org/wiki/Binomial_coefficient" rel="nofollow noreferrer">binomial coefficients</a>. Below are couple of other attempts:</p> <pre><code>from itertools import accumulate from scipy.sp...
python|numpy|combinations|itertools
2
14,669
60,243,051
How can I save a GeoDataFrame to disk in Python?
<p>I have an GeoDataFrame called <code>merged</code> and I'm having a very hard time saving it to disk.<br> <code>merged</code> is obtained through this loop:</p> <pre><code>import pandas as pd import geopandas as gpd import osmnx as ox city=gpd.read_file('C:/folder/city.json') circ=[] for i in (0, 1): graph = o...
<p>Your version 2 will save a file, but to a relative location. Try providing an absolute path: </p> <pre><code>with open('C:/folder/x.geojson', 'w') as f: f.write(merged_short.to_json()) </code></pre>
python|json|pandas|save|geopandas
3
14,670
65,272,637
Tensorflow, can not figure out what shape my inputs and labels have
<p>I am trying to load weights and for that to work i need to perform the following:</p> <pre class="lang-py prettyprint-override"><code>dummy_input = tf.random.uniform(input_shape) # create a tensor of input shape dummy_label = tf.random.uniform(label_shape) # create a tensor of label shape hist = model.fit(dummy_inpu...
<p>This was the solution</p> <pre class="lang-py prettyprint-override"><code>dummy_input = tf.random.uniform([32, 224, 224, 3]) # create a tensor of input shape dummy_label = tf.random.uniform([32,]) # create a tensor of label shape hist = model.fit(dummy_input, dummy_label) </code></pre>
python|tensorflow|keras|deep-learning
0
14,671
65,336,175
How do I replace a value in pandas DataFrame based on a condition?
<p>I have the following DataFrame:</p> <pre><code>races_dict = { &quot;grand_prix&quot;: [ 'Australia', 'Bahrain', 'China', 'Azerbaijan', 'Spain', 'Monaco', 'Canada', 'France', 'Austria', 'Great Britain', 'Germany', 'Hungary', 'Belgium', 'Italy', 'Singapore', 'R...
<p>I think it depends of data, if need repalce multiple values use dictionary like:</p> <pre><code>df.car = df.car.replace({'RED BULL RACING HONDA': 'HONDA', 'aa':'bb'}) </code></pre> <hr /> <p>For avoid your error need specified column <code>car</code> inside <a href="http://pandas.pydata.org/pandas-docs/stable/refere...
python|pandas|dataframe
2
14,672
49,886,322
Slice assignment in loop in Tensorflow
<p>I have a 5x3 matrix of zeros that I want to update with ones while in a while_loop. I want to use the looping variable to be the indices argument of the scatter_nd_update function. I have my code like this:</p> <pre><code># Zeros matrix num = tf.get_variable('num', shape=[5, 3], initializer=tf.zeros_initializer(), ...
<p>The issue revolves around the fact that <a href="https://www.tensorflow.org/api_docs/python/tf/scatter_nd_update" rel="nofollow noreferrer"><code>tf.scatter_nd_update()</code></a> needs a <strong><em>variable</em></strong> to change, while <a href="https://www.tensorflow.org/api_docs/python/tf/while_loop" rel="nofol...
python|tensorflow
1
14,673
49,798,313
Search for the nearest array in a huge array of arrays
<p>I need to find the closest possible sentence. I have an array of sentences and a user sentence, and I need to find the closest to the user's sentence element of the array.</p> <p>I presented each sentence in the form of a vector using word2vec:</p> <pre><code>def get_avg_vector(word_list, model_w2v, size=500): ...
<p>At least if you are doing this procedure for multiple sentences, you could try using <code>scipy.spatial.cKDTree</code> (I don't know whether it pays for itself on a single query. Also <code>500</code> is quite high, I seem to remember KDTrees work better for not quite as many dimensions. You'll have to experiment)....
python|arrays|performance|numpy|word2vec
2
14,674
49,843,639
ImportError: No module named 'django_pandas'
<p>I installed <code>numpy</code>, but when I install <code>django_pandas</code> it gives me an error: </p> <blockquote> <p>Using cached pandas-0.22.0.tar.gz<br> Could not find a version that satisfies the re sions: 1.10.4, 1.11.0, 1.11.1rc1, 1.11.1, 1.11.2 .12.0rc1, 1.12.0rc2, 1.12.0, 1.12.1rc1, 1.12.1, ...
<p>I had the same issue and downgrading pip worked for me, like this:</p> <pre><code>pip install pip==9.0.1 </code></pre> <p>After that I could install django-pandas normally.</p>
python|django-pandas
0
14,675
50,088,717
Keras : Cannot feed value of shape (64, 1) for Tensor which has shape '(?,)'
<p>I am trying to create a siamese network using Keras(tf as backend), for finding duplicate questions. But I am facing a problem of shape mismatch in output layer, showing the output shape as (64, 1), even though the output is of shape (64,).</p> <p>This is how my model looks :</p> <pre><code>inp_layer_1 = Input((ma...
<p>Hey I don't know if you still have this problem. I just had the same with a mix of <code>tensorflow</code> and <code>keras</code>. In the end, precising the <code>output_shape</code> of the last lambda layer solved it. For you that would be : <code>Lambda(eucl_dist,,output_shape = (1,))([out_1, out_2])</code> (If I'...
python-3.x|tensorflow|keras
0
14,676
49,983,134
How to make an tuple that contains elements 1,2,3,...100?
<p>Sorry I know this is a very easy question, I want to make a tuple that contains 1,2,3,4,...,100. Should I first make numpy array and then convert the numpy to tuple? If yes, how can I make such a thing as a numpy first?</p>
<p>You could do it like:</p> <pre><code>x = tuple(range(1, 101)) </code></pre> <p>Or, using NumPy:</p> <pre><code>x = tuple(np.arange(1, 101)) </code></pre>
python|python-3.x|numpy|tuples
6
14,677
64,009,484
Reading in txt file as pandas dataframe from a folder within a zipped folder
<p>I want to read in a txt file that sits in a folder within a zipped folder as a pandas data frame.</p> <p>I've looked at how to read in a txt file and how to access a file from within a zipped folder, <a href="https://stackoverflow.com/questions/21546739/load-data-from-txt-with-pandas">Load data from txt with pandas...
<p>You need to add full path to the file:</p> <pre><code>txt_raw = 'hcc-survival/hcc-data.txt' </code></pre>
python|pandas|data-science|zip
0
14,678
63,928,630
How to retain 2D (or more) shape when using pytrorch masked_select
<p>Suppose I have the following two matching shape tensors:</p> <pre><code>a = tensor([[ 0.0113, -0.1666, 0.5960, -0.0667], [-0.0977, -0.1984, 0.5153, 0.0420]]) selectors = tensor([[ True, True, False, False], [ True, False, True, False]]) </code></pre> <p>When using <code>torch.masked_select</code> to find the va...
<p>As @jodag pointed out, for general inputs, each row on the desired masked result might have a different number of elements, depending on how many <code>True</code> values there are on the same row in <code>selectors</code>. However, you could overcome this by allowing trailing zero padding in the result.</p> <p>Basi...
pytorch
2
14,679
46,663,013
What is y_true and y_pred when creating a custom metric in Keras?
<p>I want to implement my custom metric in Keras. According to the documentation, my custom metric should be defined as a function that takes as input two tensors, <code>y_pred</code> and <code>y_true</code>, and returns a single tensor value. </p> <p>However, I'm confused to what exactly will be contained in these te...
<h3>y_true and y_pred</h3> <p>The tensor <code>y_true</code> is the true data (or target, ground truth) you pass to the fit method.<br /> It's a conversion of the numpy array <code>y_train</code> into a tensor.</p> <p>The tensor <code>y_pred</code> is the data predicted (calculated, output) by your model.</p> <p>Usuall...
tensorflow|keras
43
14,680
46,893,921
Converting strings to floats: ValueError: could not convert string to float: '.'
<p>I am trying to convert strings to float, but I get the error in the title. I don't understand why it doesn't recognise period ('.') as a decimal. Here is a head of my dataframe.</p> <pre><code> Country Variable \ 0 Afghanistan Inflation, GDP deflator ...
<p>Use pd.to_numeric to be on safer side with erros = 'coerce' ( there might be some bad data in real) i.e </p> <pre><code>df.iloc[:,3:].apply(pd.to_numeric,errors='coerce') </code></pre>
python|python-3.x|pandas
6
14,681
33,004,573
After groupby, how to flatten column headers?
<p>I'm trying to left join multiple pandas dataframes on a single <code>Id</code> column, but when I attempt the merge I get warning: </p> <blockquote> <p>KeyError: 'Id'. </p> </blockquote> <p>I <em>think</em> it might be because my dataframes have offset columns resulting from a <code>groupby</code> statement, but...
<p>You're looking for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="noreferrer"><code>.reset_index()</code></a>.</p> <pre><code>In [11]: df = pd.DataFrame([[2, 3], [5, 6]], pd.Index([1, 4], name="A"), columns=["B", "C"]) In [12]: df Out[12]: B C A 1 2 3 4...
python|pandas|dataframe
85
14,682
32,936,764
merge two dataframes pandas
<p>I am reading 2 dfs using:</p> <pre><code>extra = pd.read_csv('table1.txt', sep = '\s+') data = pd.read_csv('table2.dat', sep = '\s+') </code></pre> <p>The output of <code>extra.info()</code> is:</p> <pre><code>class 'pandas.core.frame.DataFrame'&gt; Int64Index: 11528 entries, 0 to 11527 Data columns: a 11528 ...
<p>What's happening is you have duplicate values of <code>key</code> in one or both dataframes. So if <code>data</code> has <code>key1</code> in it 5 times, and <code>extra</code> has <code>key1</code> in it 2 times, then you will have 10 entries for <code>key1</code> when you merge the two dataframes on the key colum...
python|pandas
1
14,683
32,948,867
ValueError: cannot copy sequence with size 5 to array axis with dimension 2
<p>using numpy 1.7.1 the below code works and produces the result as shown,</p> <pre><code>import pandas as pd import numpy as np d1 = pd.DataFrame({'Name': [1, 1, 1, 1, 1],'number': [1, 1, 1, 1, 1]}) d2 = pd.DataFrame({'Name': [1, 1, 1, 1, 1], 'number': [1, 1, 1, 1, 1]}) result = np.array([d1,d2]) Value of result ...
<p>I was able to reproduce your issue with numpy 1.9.2. It seems that numpy is trying to do a vstack. when the shape are same. I tried the following approach and it worked.</p> <pre><code>result = np.empty(2, dtype=object) result[:]= [d1, d2] result array([ Name number 0 1 1 1 1 1 2 1 ...
python-2.7|numpy|pandas
11
14,684
38,620,086
How can I add a tabbed separator to pandas dataframe rows and save the output to a file?
<p>I am trying to apply a tab as a separator to the dataframe before saving, but something wonky is happening with the Day of Week column? Any ideas? Is there an easier approach using some type of fixed-width columns instead? Thanks!</p> <pre><code>entries = [{test_columns[index][0]:column for index, column in enumer...
<p>Try this: </p> <pre><code> df["Day"] = df["Day"].str.pad(10, side='left', fillchar=' ') print df["Day"].head() 0 Tuesday 1 Tuesday 2 Tuesday 3 Wednesday 4 Wednesday Name: Day, dtype: object print df Test Day Test.1 Number 0...
python-2.7|pandas|dataframe|export-to-csv
2
14,685
38,959,365
Efficently multiply a matrix with itself after offsetting it by one in numpy
<p>I am trying to write a function that takes a matrix A, then offsets it by one, and does element wise matrix multiplication on the shared area. Perhaps an example will help. Suppose I have the matrix:</p> <pre><code>A = np.array([[1,2,3],[4,5,6],[7,8,9]]) </code></pre> <p>What i'd like returned is: (1*2) + (4*5...
<p>In this 3 column case, you are just multiplying the 1st 2 columns, and taking the sum:</p> <pre><code>A[:,:2].prod(1).sum() Out[36]: 78 </code></pre> <p>Same as <code>(A[:,0]*A[:,1]).sum()</code></p> <p>Now just how does that generalize to more columns?</p> <p>In your original loop, you can cut out the row iter...
python|numpy
0
14,686
63,253,172
How to plot points on graph with text at each point (python)
<p>I'm trying to replicate this: <img src="https://i.stack.imgur.com/cUwhI.png" alt="1" /></p> <p>I have a list of words, each of which has an x and y coordinate. I need to graph them just like the one above. What is the best way to do this? I know I could do something like...</p> <pre><code>y = [2.56422, 3.77284, 3.52...
<p>I think you can use <code>zip()</code> to get each of them in a loop.</p> <pre><code>import matplotlib.pyplot as plt y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199] z = [0.15, 0.3, 0.45, 0.6, 0.75] n = ['hello', 'xyz', 'bbb', 'fasjd', 'boy'] fig = plt.figure(figsize=(4,3),dpi=144) ax = fig.add_subplot(111) def ...
python|pandas|matplotlib
1
14,687
63,215,578
Is there a way to export a pandas Dataframe to an Excel Sheet keeping the Dataframe's float format?
<p>my goal is to export a pandas dataframe to an excel file keeping the format of the dataframe. Here is the code snipet to create and format the dataframe:</p> <pre><code>import pandas as pd import os import numpy as np df = pd.DataFrame({'A': np.linspace(100000, 1000, 5), 'B': 'line'}) df = pd.concat([df, pd.DataFra...
<p>I think you can use the ExcelWriter for this:</p> <pre><code>excel_writer = pd.ExcelWriter('/home/your_excel.xlsx', engine = 'xlsxwriter') df.to_excel(excel_writer, index=False, sheet_name='mysheet') book = excel_writer.book sheet = excel_writer.sheets['mysheet'] excel_format = book.add_format({'num_format': '0.000...
python-3.x|pandas|pandas-styles
1
14,688
63,176,844
How to make datetimes timezone aware and convert timezones
<p>I have 3 dataframes with multiple columns, with 2 of them having a datetime that is is UTC, and the other one being 'Europe/Amsterdam'. However, they are still unaware.</p> <p>How do I make these datasets timezone aware, and convert the 'Europe/Amsterdam' to UTC?</p> <p>The datetimes are in the index of each dataset...
<p>If you're using pandas Dataframes and Python 3, you can do it like this:</p> <pre><code>import pandas as pd values = {'dates': ['20190902101010','20190913202020','20190921010101'], 'status': ['Opened','Opened','Closed'] } df = pd.DataFrame(values, columns = ['dates','status']) df['dates_datet...
python|pandas|dataframe|pytz
0
14,689
67,840,364
"Could not interpret activation function identifier: 256" error in Keras
<p>I'm trying to run the following code but I got an error. Did I miss something in the codes?</p> <pre><code>from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.models import Sequential from keras.callbacks import ModelCheckpoint from keras.models import load_mod...
<p>This error indicates that, <em>you have defined an activation function that is not interpretable</em>. In your definition of a dense layer you have passed two argument as <code>layers[i]</code> and <code>layers[i+1]</code>.</p> <p>Based on the docs <a href="https://keras.io/api/layers/core_layers/dense/" rel="nofoll...
python|tensorflow|keras
1
14,690
67,813,893
How to create a new column with status based on value
<p>I have the following pandas dataframe</p> <pre><code>Suburb Percentile Rank Hume 0.20464135 Clayton 0.409162146 Moorabin 0.654550934 St Kilda 0.80464135 Point Cook 1.505447257 </code></pre> <p>I want to create a new column called Rank classifier based on the &quot;Percentile Rank&quo...
<p>Instead of applying a function look at using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html" rel="nofollow noreferrer">pandas.cut</a>.</p> <p>The code below will give you the result you indicated you expected but you might need to tweak things.</p> <pre class="lang-py prettyprint...
python|pandas
6
14,691
67,810,359
Pandas Dataframe merge with multiple keys ("AND" or "OR"?)
<p>I need to merge two data frames. To make sure that the rows are unique I need to verify that &quot;Name&quot; and &quot;Age&quot; are BOTH matched before merging. I am using the combination as a primary key. Here is my code:</p> <p><code>df = pd.merge(df, df1[['Name', 'Age', 'Date']], left_on=['Name', 'Age'], right_...
<p>I did some testing on this. The answer is Pandas merging on multiple keys is an &quot;AND&quot; function, not &quot;OR&quot;.</p> <p>Here is the test I did:</p> <p>DF1 =:</p> <pre><code>A B D ---------- a m 1 b n 2 c o 3 d q 4 e r 5 f s 6 g t 7 h u 8 i v 9 </code></pre> <p>DF2...
python|pandas|merge|key
0
14,692
67,727,853
95% confidence interval of single proportion in pandas timeseries using statsmodel
<p>I have a time-series dataframe:</p> <pre><code>df = pd.DataFrame({'year':['2010','2011','2012','2013','2014','2015','2016','2017','2018','2019'], 'total_count': [545,779,706,547,626,530,766,1235,1260,947], 'rand_count':[96,184,148,154,160,149,124,274,322,301], ...
<p>Consider assigning multiple columns which should line up by index since per <a href="https://www.statsmodels.org/stable/generated/statsmodels.stats.proportion.proportion_confint.html" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p>When a pandas object is returned, then the index is taken from the count.</p>...
python|pandas|time-series|statsmodels
2
14,693
67,771,907
Is there a function to write certain values of a dataframe to a .txt file in Python?
<p>I have a dataframe as follows:</p> <pre><code>Index A B C D E F 1 0 0 C 0 E 0 2 A 0 0 0 0 F 3 0 0 0 0 E 0 4 0 0 C D 0 0 5 A B 0 0 0 0 </code></pre> <p>Basically I would like to write the dataframe to a txt file, such that every row consists of the index and the subsequent column name only, excl...
<p>Take a matrix vector multiplication between the boolean matrix generated by &quot;is this entry <code>&quot;0&quot;</code> or not&quot; and the columns of the dataframe, and write it to a text file with <code>to_csv</code> (thanks to @Andreas' answer!):</p> <pre><code>df.ne(&quot;0&quot;).dot(df.columns + &quot; &qu...
python|pandas|dataframe|file|text-files
5
14,694
41,466,636
Pandas Dataframe, aggregate and put the data in the next column
<p>I have a dataset like this:</p> <pre><code>Country Name Match Result US Martin Win 3 US Martin Lose 1 US Martin Draw 5 UK Luther Win 5 UK Luther Draw 3 </code></pre> <p>I'd like to add two more columns with sum result from Win, Lose and Dr...
<p>IIUC you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a>, sample <code>DataFrame</code> was changed:</p> <pre><code>df['All'] = df.groupby(['Country','Name'])['Result'].transform('sum') df['P...
python|pandas|aggregate|data-science
1
14,695
61,352,776
exract number and float from string
<pre class="lang-py prettyprint-override"><code>data = {'s': 'ok', 't': [1587486600, 1587490200, 1587493800, 1587497400], 'c': [6832.0, 6905.99, 6900.0, 6880.0], 'o': [6831.0, 6849.0, 6906.0, 6900.0], 'h': [6849.0, 6916.0, 6906.0, 6900.0]} output like this = [[[1587486600, 1587490200, 1587493800, 1587497400], [...
<p>That is not an array, it is an object:</p> <pre><code>Object.values(string).filter(item =&gt; typeof item === Array) </code></pre>
python|regex|numpy|pycharm|python-re
0
14,696
68,750,186
Merging multiple columns with different column lengths
<p>I have the following two dataframes:</p> <pre><code>values = pd.DataFrame(data={'val1': ['A', 'C', 'B'], 'val2': [None, 'A', None], 'val3': [None, 'B', 'A']}, index=pd.Series([1, 2, 3])) desc = pd.DataFrame(data={'value': ['A', 'B', 'C', 'D'], ...
<p>One way to approach this would be to flip <code>values</code> into long form, merge with <code>desc</code>, pivot back to wide form, and make adjustments to the columns:</p> <pre><code>df = (values.melt(ignore_index=False) .reset_index() .merge(desc, on='value') .rename(columns={&...
python|pandas|join
0
14,697
68,703,623
How to update the weights of a model only if loss for current batch is smaller than previous
<p>I'm trying to update the weights of a model during training only for those batches in which the loss is smaller than that obtained in the previous batch.</p> <p>So, in the batches loop, I store the loss obtained at each iteration, and then I have tried evaluating a condition: if loss at time t-1 is smaller that that...
<p>Storing the loss in a list would store the whole graph for that batch for each element in losses. Instead what you can do is the following:</p> <pre class="lang-py prettyprint-override"><code>losses.append(loss.cpu().tolist()) optimizer.zero_grad() if losses[-1] &lt;= losses[-2]: # current loss is smaller loss.b...
pytorch|gradient|optimizer-hints
1
14,698
36,609,176
Groupby pandas calculate percentage
<p>I have a groupby object as follows after i ran:</p> <pre><code>grouped_mask=L2014_2.groupby(['state']) grouped_mask.mask.value_counts() state mask AL False 105931 True 77 AR False 67788 True 1774 AZ False 90068 True 151 CA False 586184 ...
<p>Also you can set the <code>normalize</code> parameter to obtain the relative frequencies:</p> <pre><code>grouped_mask.mask.value_counts(normalize=True) </code></pre> <p>just multiply by 100 to get the percentages :-)</p> <p>regards</p>
pandas
3
14,699
65,669,150
The loc function in jupyter does not work for filtering my dataframe
<p>I am pretty new to Jupyter and have imported a data set. That worked fine. Then I wanted to use the <code>loc</code> function to get just one specific value in a specific column. However the <code>loc</code> function simply doesn't work on my Jupyter notebook. I have restarted the whole system - still doesn't work.<...
<p>You made a simple mistake. df prints the whole dataframe just remove the last line</p> <pre><code>!pip install pandas import pandas as pd df = pd.read_csv(&quot;/content/pokemon.csv&quot;) df.head(10) df.loc[df[&quot;Type 1&quot;] == &quot;Fire&quot;] </code></pre>
python|pandas|filter|pandas-loc
0