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
364,800
57,943,475
Getting ValueError when performing np.dot
<p>I have to find annual returns and volatility of a portfolio. I have a dataframe with 5 columns, each containing the closing price of a stock</p> <pre><code> ABC FINE GAYA RITES LEMON 0 98.00 1203.70 1.00 260.30 69.00 1 98.25 1200.45 1.00 263.10 69.55 2 99.25 1202.55 1.05 267.50 71...
<ol> <li>In dot product, inner dimensions of the two structures have to conform, e.g., consider the row vector <em>v</em>`<sub>1x5</sub>, to be able to <em>dot product</em> it, the other structure has to be S<sub>5xX</sub> (where <code>X</code> is any dimension). So, your line: </li> </ol> <pre><code>weights = np.full...
python|pandas|numpy
0
364,801
58,065,741
Calculate euclidean distance between groups in a data frame
<p>I have weekly data for various stores in the following form:</p> <pre><code>pd.DataFrame({'Store':['S1', 'S1', 'S1', 'S2','S2','S2','S3','S3','S3'], 'Week':[1, 2, 3,1,2,3,1,2,3], 'Sales' : [20,30,40,21,31,41,22,32,42],'Cust_count' : [2,4,6,3,5,7,4,6,8]}) Store Week Sales Cust_count 0 ...
<p>We can <code>pivot</code> then use <code>numpy</code> to do these calculations</p> <pre><code>df1 = (df.pivot(index='Store', columns='Week', values=['Sales', 'Cust_count']) # .fillna(0) # Uncomment if you want to treat missing store-weeks as 0s ) arr1 = df1['Sales'].to_numpy() arr2 = df1['Cust_coun...
python|pandas|dataframe|scipy|euclidean-distance
3
364,802
57,953,795
How to bin nan values using pd.cut
<p>I am trying to write a code that creates bins from a dataframe(account_raw) that contains blank values. My problem is that python bins blank values with my first bin label: 0 - 25k. What I want ot do is to create a separate bin for blank values.Any ideas how to fix this?Thanks</p> <pre><code>Bucket = [0, 25000, 500...
<p>I think simpliest is processing values after <code>pd.cut</code> and set custom catagory for missing values by <code>IfrsBalanceEUR</code> column:</p> <pre><code>account_raw['LoanGBVBuckets'] = pd.cut(account_raw['IfrsBalanceEUR'], bins=ls_LoanGBVBucket, ...
python|pandas|nan
4
364,803
57,743,774
Check the number of parameters from state_dict in pytorch
<p>SO has an answer about how to check the total # of params from the model: <code>pytorch_total_params = sum(p.numel() for p in model.parameters())</code></p> <p>However, how does one check the total # of params from the <code>state_dict</code>?</p> <p><code>state_dict = torch.load(model_path, map_location='cpu')</c...
<p>You can count the number of saved entries in the state_dict:</p> <pre class="lang-py prettyprint-override"><code>sum(p.numel() for p in state_dict.values()) </code></pre> <p>However, there's a snag here: a state_dict stores both <a href="https://pytorch.org/docs/1.1.0/nn.html#parameters" rel="noreferrer">parameter...
pytorch
5
364,804
58,163,276
Merge two table
<p>I have two tables, one table has FROM_SERIAL, TO_SERIAL and TRANSACTION_DATE. And another table has SERIAL_NO and ACTIVATION_DATE. I want to merge both two table within a particular range. </p> <p>Example: </p> <p>First Table</p> <pre><code> FROM_SERIAL TO_SERIAL TRANSACTION_DATE 10003000100 ...
<p>Consider:</p> <pre><code>SELECT t1.from_serial, t1.to_serial, t2.serial_no, t2.activation_date FROM table1 t1 INNER JOIN table2 t2 ON t2.serial_no &gt;= t1.from_serial AND t2.serial_no &lt; t1.to_serial </code></pre> <p>You may ajust the inequalities as you wish. Beware that, if a given <cod...
python|pandas|oracle
1
364,805
57,837,067
How to create two columns having cumulative sum based on a column value and having group by
<p>I am having following dataframe in pandas using python3.7</p> <pre><code>data = {'s':['a','a','a','a','b','b'], 'cp':['C','P','C','C','C','P'], 'st':[300,300,300,300,310,310], 'qty':[3000,3000,3000,6000,9000,3000], 'p':[16,15,14,10,8,12]} df=pd.DataFrame(data) df['t']=df['p']*df['q...
<p>Here's my solution</p> <pre><code>df['x'] = df['qty'].mul(df['cp'].eq('C')).groupby(df['s']).cumsum() df['y'] = df['qty'].mul(df['cp'].eq('P')).groupby(df['s']).cumsum() </code></pre> <p>Output:</p> <pre><code> s cp st qty p t ct x y 0 a C 300 3000 16 48000 48000 3000 0 1 ...
python|python-3.x|pandas
4
364,806
57,856,010
Automatically Optimizing Pandas Dtypes
<p>I am working on an algorithm using the pandas library. I encountered an interesting problem while working.</p> <p>when I write the dataframe object to the file and read it again, the dataframe changes. When I investigated the cause, I found that it was caused by types. For example I am creating a dataframe like the...
<p>After some research, the to_numeric function works fine. I have implemented my own implementation as follows.</p> <p>I created a dataframe object from numpy data types.</p> <pre><code>np_types = [np.int8 ,np.int16 ,np.int32, np.int64, np.uint8 ,np.uint16, np.uint32, np.uint64] np_types = [np_type.__name...
python|pandas|dataframe
3
364,807
58,130,624
Pandas data frame repeat each row a certain number of times
<p>I have a pandas dataframe consisting of 7 values:</p> <pre><code> Minutiae LR 0 1 1.975476 1 2 1.082983 2 3 0.269608 3 4 0.878350 4 5 2.820141 5 6 8.686183 6 7 24.340116 7 8 46.475523 8 9 66.139377 </code></pre> <p>Wha...
<p>Create dictionary for number of repeats for each <code>Minute</code>, <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a> and then repeat index with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas....
python|pandas
1
364,808
57,945,299
How to form a Pandas DataFrame from multiple multi dimensional numpy array
<p>Given a multi dimensional array <code>x_train_pad.shape = (900, 3)</code> , and <code>x2_train_pad.shape = (900, 7)</code> , and <code>x_train_data.shape = (900, 5)</code>. Now the DataFrame to be created should of shape <code>outDF.shape = (900, ( 3+7+5) ) which is 900,15</code>.</p> <p>Where x_train_data is a...
<pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd arr1 = np.random.rand(10,3) arr2 = np.random.rand(10,5) arr3 = np.random.rand(10,7) c_array = np.c_[arr1,arr2,arr3] cols = [f"x{j+1}_{i+1}" for j, arr in enumerate([arr1[0],arr2[0],arr3[0]]) for i,_ in enumerat...
python|pandas|numpy
1
364,809
58,116,701
How to create subplot from various data frames
<p>I have a list of data frames:</p> <pre><code>list_df = [df1, df2, df3, df4, df5, df6] </code></pre> <p>of which are are defined by fairly identical commands:</p> <pre><code>df6 = df_2016['Incident Type Description'].value_counts()[:20] </code></pre> <p>Where <code>df1 = df_2011['Incident Type Description'].valu...
<p>I don't know if you planned to use another package. But Seaborn is quite often used to display nicely and quickly different kinds of plots. You can check the complete package doc : <a href="https://seaborn.pydata.org/index.html" rel="nofollow noreferrer">Seaborn Doc</a>. There are some nice tutorials.</p> <p>Especi...
python|pandas|matplotlib
0
364,810
57,937,938
Failed to get convolution algorithm
<p>im trying to train a convolutional network, i will omit the part of the code that import and create folders for the pictures and clases, now this is the main code of the net, this example was taken from the book "deep learning in python" from François Collet</p> <pre><code>from keras import layers from keras import...
<p>the problem was that my gpu have not enough ram for the complexity of the net, this can be solved by trying a smaller model, thank you all</p>
python|tensorflow|keras|deep-learning
0
364,811
58,037,682
How to train a Regression model for single input and multiple output?
<p>I have trained a regression model that approximates the weights for the equation : <strong>Y = R+B+G</strong> For this, I provide pre-determined values of R, B and G and Y, as training data and after training the model, the model is successfully able to predict the value of Y for given values of R, B and G. I used a...
<p>Here is an example to start solving your problem using neural network in tensorflow.</p> <pre><code>import numpy as np from tensorflow.python.keras.layers import Input, Dense from tensorflow.python.keras.models import Model X=np.random.random(size=(100,1)) y=np.random.randint(0,100,size=(100,3)).astype(float) #R...
python|tensorflow|machine-learning|linear-regression
1
364,812
57,837,019
append large number to numpy array
<p>I have a Xmatrix of Row=12584 and Col 784. I want to extract each row based on another Tmatrix of Row=12584 Col 1 and append the values to numpy array X1 or X2. Even with smaller row size of 1500 it takes over 10 mins. I am sure there is better and efficient way to extract entire row and append to an array</p> <pr...
<p>try this:</p> <pre><code>import numpy as np import time start_time = time.time() Row = 12584 #Row = 1500 Col = 784 Xmatrix = np.random.rand(Row,Col) Tmatrix = np.random.randint(1,3,(Row,1)) X1 = Xmatrix[(Tmatrix==1).reshape(-1)] X2 = Xmatrix[(Tmatrix==2).reshape(-1)] print(X1.reshape(-1)) print(time.time() - s...
python|numpy|append
2
364,813
58,002,600
How do sessions and parallelism work in TF2.0?
<p>I am trying to run two tensorflow models in parallel in the same process.</p> <p>In Tensorflow 1.x we could do e.g. <a href="https://stackoverflow.com/questions/46725323/keras-tensorflow-exception-while-predicting-from-multiple-threads">Keras Tensorflow - Exception while predicting from multiple threads</a></p> <p...
<p>Try to allow fraction of GPU for each model.</p> <pre><code>import tensorflow as tf config = tf.compat.v1.ConfigProto(gpu_options = tf.compat.v1.GPUOptions(per_process_gpu_memory_fraction=0.8) # device_count = {'GPU': 1} ) config.gpu_options.allow_growth = True session = tf.compat.v1.Session(c...
python|tensorflow|tensorflow2.0|tf.keras
0
364,814
58,057,186
Unable to find the first occurrence of substring using regex for set of values in pandas
<p>I have a dataframe as below, i need to find only the first occurrence in a string for set of values. </p> <p>I'm unable to use "find" function along with regex and dictionary. And if i use "findall" function, it is ofcourse finding all occurrence which is not what i need.</p> <pre><code>Text 51000/1-PLASTIC 150 P...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.findall.html" rel="nofollow noreferrer"><code>Series.str.findall</code></a> instead <code>find</code> with select first value of lists returned of <code>findall</code> by indexing <code>str[0]</code>:</p> <pre><code>import re ...
python|python-3.x|pandas|substring|findall
2
364,815
57,864,089
How to avoid unicode issue when read data from excel
<p>I use pandas dataframe to read data from an excel file. The text becomes this: </p> <pre><code>u"\u200bDuring the QA, bla bla bla,\xa0Head of bla bla\xa0for NZ,\xa0was labelled bla bal. With further investigation, bla bla bla bla bla bla." </code></pre> <p>I tried to replace all of these 'u200b', '\xa0', etc. but ...
<p>Maybe adding encoding works when importing the file.</p> <pre><code>import pandas as pd pd.read_csv('data.csv' encoding='utf-8') </code></pre>
python|pandas
0
364,816
57,994,290
Pandas aggregate with dynamic column names
<p>I have a script that generates a pandas data frame with a varying number of value columns. As an example, this df might be</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'group': ['A', 'A', 'A', 'B', 'B'], 'group_color' : ['green', 'green', 'green', 'blue', 'blue'], 'val1': [5, 2, 3, 4, 5], 'val2' : [4, 2,...
<p>More easy like </p> <pre><code>df.groupby('group').agg(lambda x : x.head(1) if x.dtype=='object' else x.mean()) Out[63]: group_color val1 val2 group A green 3.333333 4.666667 B blue 4.500000 6.000000 </code></pre>
python|pandas|aggregate|pandas-groupby
16
364,817
58,143,211
How to compute euclidean distance between all column vector pairs for a given matrix without using loops? (using only numpy)
<p>As titled, I need to calculate the euclidean distance between all possible column vector pairs of a given matrix without using loops and using numpy only.</p> <p>This produces the output I'm looking for (but with loops):</p> <pre><code>import numpy as np def all_column_euclidean(x): output = np.zeros((len(x[0]...
<p>There are functions for that in <code>scipy.spatial.distance</code>:</p> <pre><code>import numpy as np from scipy.spatial.distance import pdist,squareform a = np.random.randint(0,10,(3,4)) # pairwise dist, compressed pdist(a.T) # array([ 8.60232527, 8.77496439, 10.29563014, 6.70820393, 8.1240384 , # 3....
python|numpy|matrix|euclidean-distance
0
364,818
57,948,753
How do I sort and rank the data set
<p>I have a data set and I need to sort and rank something like this:</p> <pre><code> d0 d1 d2 d3 configuration theta0 1.0 2.0 2.0 1.0 theta1 3.0 1.0 3.0 3.0 theta2 2.0 3.0 4.0 2.0 theta3 4.0 4.0 1.0 4.0 </code></pre> <...
<p>you can do</p> <pre><code>df.rank(ascending=False, method='first') </code></pre> <p>this will rank with highest first and rank entries as they are ordered in the column if there are multiple occurances of the same value</p>
python|pandas
2
364,819
57,836,508
numpy polynomial linear regression with sklearn
<p>I am trying to fit a linear system of polynomials to data. <code>numpy</code>'s <code>polynomial</code> module has a fitting function included, which works perfectly. When I try to fit the model with an <code>sklearn</code> linear solver, the fit is terrible! I don't understand what is going wrong. I construct a mat...
<p>Your <code>omp.coef_.dot(X.T)</code> doesn't include the intercept; add that manually or simply use <code>omp.predict</code> directly.</p> <p>I.e.:</p> <pre class="lang-py prettyprint-override"><code>plt.scatter(xnorm, omp.coef_.dot(X.T) + omp.intercept_, label='linear regression') plt.scatter(xnorm, evals, label=...
python|numpy|scikit-learn|linear-regression|polynomials
1
364,820
57,916,260
How to round the value, python
<p>How do I round each row of my dataframe? I have tried looking on so, but cannot seem to find the right solution I have some code :</p> <pre><code>skrip, si3 = konten(skripsi2, 'proba.sav') berita1['hasil_sentimen'] = pd.Series(skrip) berita1['probability'] = pd.Series(si3) print(berita1) berita1.to_csv('tes3.csv') ...
<p>Looks like you want to change the probability to a percentage and round up:</p> <pre><code>berita1['probability'] = berita1['probability'].apply(lambda x: round(x[0]*100)) </code></pre>
python|pandas|dictionary|rounding
-1
364,821
57,809,141
How to merged a column of list, extract unique string value, put into dataframe
<p>Going crazy, cant figure out where went wrong.</p> <blockquote> <p>Have a file with dataframe, consist of single column, each row consist of 1 list</p> </blockquote> <p>i am lost, please advice</p> <pre><code>fruits 0 ['apple', 'orange','grape'] 1 ['apple','pineapple','coconut'] </code></pre> # <p>expec...
<p>Flatten your <code>data</code> into a single list first then read it as column in your DataFrame:</p> <pre><code>&gt;&gt;&gt; data = [[['apple', 'orange','grape']],[['apple','pineapple','coconut']]] &gt;&gt;&gt; data = np.unique(np.ravel(data)) &gt;&gt;&gt; df = pd.DataFrame(data, columns = ['fruit']) &gt;&gt;&gt; ...
python|pandas|list|dataframe
2
364,822
58,135,790
While using custom callback in Earlystopping callback not works
<p>I am working on a project where I am using custom callback with earlystopping callback, in this my model training not stops even <code>val_loss</code> not improving much.</p> <p>Here is my implmentation:</p> <pre class="lang-py prettyprint-override"><code>class CustomCallback(keras.callbacks.Callback): def __i...
<p>Why not use a custom metric instead of a callback?</p> <pre><code>def error_rate(y_true, y_pred): rate = K.cast(K.equal(y_true, y_pred), K.floatx()) return keras.backend.sum(rate) </code></pre> <p>Are you passing label numbers or one hot tensors as y?? Usually it should be rounding first (there will be not...
python-3.x|tensorflow|keras
1
364,823
57,921,778
How do I make my x labels increment in months?
<p>So I have this dataframe: <a href="https://i.stack.imgur.com/QRuSH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QRuSH.png" alt="img"></a></p> <p>And I want to create a graph with the xlabels corresponding with the months the records are in. I've tried:</p> <pre><code>df['date'] = pd.to_dateti...
<p>Thanks for the comments, I figured out the problem was that i didnt set the new dataframe to have a changed index:</p> <pre><code>df = df.set_index('date') </code></pre>
pandas|dataframe|datetime|matplotlib|seaborn
0
364,824
57,791,838
Fastest way to remove date part from pandas Timestamp
<p>pandas <code>Timestamp</code> has an efficient way (i.e. <code>normalize()</code> method) to remove the time part leaving only date, e.g.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd timeStamp = pd.to_datetime('2019-01-01 13:15:17') print('date only:',timeStamp.normalize()) </code></pre> ...
<pre><code>import pandas as pd timeStamp = pd.to_datetime('2019-01-01 13:15:17').time() print(timeStamp) </code></pre>
python|pandas|date|time|timestamp
1
364,825
58,082,177
Optimize K-Nearest Neighbors Algorithm on 50 variables x 100k row dataset
<p>I want to optimize a piece of code that helps me to calculate a nearest neighbour for every item in a given dataset with 100k rows. The dataset contains 50 variable-columns, which helps to describe each row-item and most of cells contains a probability value between 0 - 1.</p> <p><strong>Question:</strong> I am fai...
<p>I would recommand to Use <a href="https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.NearestNeighbors.html" rel="nofollow noreferrer">NearestNeighbors</a>. (set n_jobs to -1 to use all processors)</p> <pre><code>import numpy as np from sklearn.neighbors import NearestNeighbors from sklearn.preproce...
python|scikit-learn|knn|sklearn-pandas|euclidean-distance
1
364,826
57,994,468
ImportError: Missing required dependencies ['numpy']. Nothing helps
<p>I'm working on AWS (ubuntu server 18.04). When I try to run the code with " import numpy", I get an error:</p> <pre><code> Traceback (most recent call last): File "main.py", line 1, in &lt;module&gt; import pandas as pd File "/usr/lib/python3/dist-packages/pandas/__init__.py", line 19, in &lt;module&gt; ...
<h1>Quick Solution</h1> <pre><code>pip uninstall pandas -y pip uninstall numpy -y pip install pandas pip install numpy </code></pre> <p>Follow first uninstall and install it will works</p>
python|python-3.x|numpy|ubuntu|unix
1
364,827
57,897,642
Complex Grouping of dataframe with operations and creation of new columns
<p>I have a question and was not able to find a good answer which I can apply. It seems to be more complex than I thought:</p> <p>This is my current dataframe df=</p> <pre><code>[customerid, visit_number, date, purchase_amount] [1, 38, 01-01-2019, 40 ] [1, 39, ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.agg.html" rel="nofollow noreferrer">groupby.agg</a>:</p> <pre><code>import datetime df['date']=pd.to_datetime(df['date']) g=df.groupby('customerid') df.index=df['customerid'] df_new=g.agg({'purchase_amount':'sum','visit...
python-3.x|pandas|pandas-groupby
0
364,828
57,807,305
Pandas: Drop duplicates in col[A] keeping row based on condition on col[B]
<p>Given the dataframe:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'col1': ['A', 'A', 'A','B','B'], 'col2': ['type1', 'type2', 'type1', 'type2', 'type1'] , 'hour': ['18:03:30','18:00:48', '18:13:46', '18:11:29', '18:06:31'] }) </code></pre> <pre class="lang-py prettyprint-override"><code>co...
<pre><code>df.drop_duplicates(['col1','col2'] , keep = 'last') </code></pre>
python|pandas|dataframe|group-by
1
364,829
57,956,737
Pandas Duplicated returns some not duplicate values?
<p>I am trying to remove duplicates from dataset. </p> <p>Before using <code>df.drop_duplicates()</code>, I run <code>df[df.duplicated()]</code> to check which values are treated as duplicates. Values that I don't consider to be duplicates are returned, see example below. All columns are checked.</p> <p>How to get ac...
<p>Encountered the same problem.</p> <p>At first, it looks like</p> <pre><code>df.duplicated(subset='my_column_of_interest') </code></pre> <p>returns results which actually have unique values in <em>my_column_of_interest</em> field.</p> <p>This is not the case, though. The <a href="https://pandas.pydata.org/docs/refer...
pandas|duplicates
1
364,830
34,079,787
Tensor with unspecified dimension in tensorflow
<p>I'm playing around with tensorflow and ran into a problem with the following code:</p> <pre><code>def _init_parameters(self, input_data, labels): # the input shape is (batch_size, input_size) input_size = tf.shape(input_data)[1] # labels in one-hot format have shape (batch_size, num_classes) num_c...
<p>As Ishamael says, all tensors have a static shape, which is known at graph construction time and accessible using <a href="http://www.tensorflow.org/api_docs/python/framework.html#Tensor.get_shape" rel="noreferrer"><code>Tensor.get_shape()</code></a>; and a dynamic shape, which is only known at runtime and is access...
python|tensorflow
46
364,831
34,387,320
Installing pymc - Lapack issues
<p>Hoping someone might have some experience with this issue, I checked google but had no luck even finding the error message.</p> <p>I'm trying to install pymc (using <code>pip install --user pymc</code>) on a server with Wakari and Anaconda python installed.</p> <p>I am getting back an error <code>/usr/bin/ld: cann...
<p>If you have Anaconda installed, why not install the <a href="https://conda.anaconda.org/pymc" rel="nofollow">pymc package</a> with the conda package manager?</p> <p><code>conda install -c https://conda.anaconda.org/pymc pymc</code></p>
numpy|lapack|pymc|intel-mkl
1
364,832
34,279,378
python pandas- apply function with two arguments to columns
<p>Can you make a python pandas function with values in two different columns as arguments?</p> <p>I have a function that returns a 1 if two columns have values in the same range. otherwise it returns 0:</p> <pre><code>def segmentMatch(RealTime, ResponseTime): if RealTime &lt;= 566 and ResponseTime &lt;= 566: ...
<p>Why not just do this?</p> <pre><code>df['NewCol'] = df.apply(lambda x: segmentMatch(x['TimeCol'], x['ResponseCol']), axis=1) </code></pre> <p>Rather than trying to pass the column as an argument as in your example, we now simply pass the appropriate entries in each row as argument, and store...
python|function|pandas|dataframe
102
364,833
34,308,786
Numpy : read data from CSV having numerals as string
<p>I'm reading a .csv file in python using command as:</p> <pre><code>data = np.genfromtxt('home_data.csv', dtype=float, delimiter=',', names=True) </code></pre> <p>this csv has one column with zipcode which are numerals but in string format, for eg "85281". This column has values as nan:</p> <pre><code>data['zipco...
<p>Maybe not the most efficient solution, but read your data as <code>string</code> and convert it afterwards to <code>float</code>:</p> <pre><code>data = np.genfromtxt('home_data.csv', dtype=float, delimiter=',', names=True) zipcode = data['zipcode'].astype(np.float) </code></pre> <p>Btw., is there a reason you wa...
python|csv|numpy
1
364,834
34,223,207
What does mpf in the mpmath mean?
<p><code>x</code> in the following has the value:</p> <pre><code>[mpf('0.0') mpf('0.10000000000000001') mpf('0.20000000000000001') mpf('0.30000000000000004') mpf('0.40000000000000002') mpf('0.5') mpf('0.60000000000000009') mpf('0.70000000000000007') mpf('0.80000000000000004') mpf('0.90000000000000002')] </code></pr...
<p>Your <code>x</code> just a list:</p> <pre><code>&gt;&gt;&gt; x = mp.arange(0, 1, 0.1) &gt;&gt;&gt; type(x) list </code></pre> <p>That means you get the normal list behavior:</p> <pre><code>&gt;&gt;&gt; x * 2.0 TypeError: can't multiply sequence by non-int of type 'float' &gt;&gt;&gt; y = [e * 2.0 for e in x] </co...
python|numpy|sympy|mpmath
2
364,835
33,984,737
Python - parse csv data - algorithm error
<p>I need to parse a big csv file (1Gb), which contains weather data.<br><br>The file itself is here:<br> <a href="ftp://ftp.ncdc.noaa.gov/pub/data/ghcn/daily/by_year/2014.csv.gz" rel="nofollow">ftp://ftp.ncdc.noaa.gov/pub/data/ghcn/daily/by_year/2014.csv.gz</a> <br>Additional info (stations code and file format):<br> ...
<p>Maybe you could use pandas here, but you do not need them to solve current problem. What happens is that you store a monthly average only when you find a line with a new month. But when you reach end of file, you should alse process last month.</p> <p>Your loop should be:</p> <pre><code>for row in reader: if r...
python|algorithm|parsing|csv|pandas
0
364,836
34,097,845
Determine the endianness of a numpy array
<p>I have a <code>numpy.array</code> and I want to find out what endianness is used in the underlying representation.</p> <p>A <code>byteorder</code> property is documented <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.byteorder.html" rel="noreferrer">here</a>, but none of the given examples...
<p><code>byteorder</code> is a data type objects <a href="http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html" rel="nofollow"><code>dtype</code></a> attribute so you need to do this:</p> <pre><code>In [10]: import numpy as np In [11]: arr = np.array([1,2,3]) In [12]: arr.dtype.byteorder Out[12]: '=' </code>...
python|numpy|endianness
5
364,837
34,066,533
Drop Elements from Pandas Series by Index
<p>I have a pandas series df (dates = index):</p> <pre><code>2015-09-10 58 2015-09-11 40 2015-09-12 33 2015-09-13 42 2015-09-14 22 2015-09-15 88 2015-09-16 99 2015-09-17 124 </code></pre> <p>I'd like to drop the dates from 2015-09-11 to 2015-09-15, so my df would look like:</p> <pre><c...
<p>Try that:</p> <pre><code>s = pd.Series([58,40,33,42,22,88,99,124], index =["2015-09-10","2015-09-11","2015-09-12","2015-09-13","2015-09-14","2015-09-15","2015-09-16","2015-09-17"]) In [140]: s Out[140]: 2015-09-10 58 2015-09-11 40 2015-09-12 33 2015-09-13 42 2015-09-14 22 2015-09-15 88 2015...
python|pandas|dataframe
5
364,838
34,160,692
Error using dropout in tensorflow
<p>I'm trying to use the dropout functionality in tensorflow: </p> <pre class="lang-py prettyprint-override"><code>sess=tf.InteractiveSession() initial = tf.truncated_normal([1,4], stddev=0.1) x = tf.Variable(initial) keep_prob = tf.placeholder("float") dx = tf.nn.dropout(x, keep_prob) sess.run(tf.initialize_...
<p>This is a bug in the implementation of <code>tf.nn.dropout</code> that was fixed in a recent commit, and will be included in the next release of TensorFlow. For now, to avoid the issue, either <a href="https://www.tensorflow.org/versions/master/get_started/os_setup.html#source">build TensorFlow from source</a>, or m...
tensorflow
8
364,839
34,240,114
pandas frequency table histograms distribution fitting
<p>I have a frequency table <code>df</code> with large frequencies like this </p> <pre><code>... freq (20, 21] 5235211 (21, 22] 5232121 (22, 23] 1241228 (23, 24] 9412034 (24, 25] 2356336 (25, 26] 3782721 (26, 27] 9978733 ... </code></pre> <p>The bins are indices.</p> <p>I want to plot ni...
<p>Found it, <code>plt.hist</code> has a parameter named <code>weights</code>, to which I can pass an array of weights. Simply passing the <code>freq</code> column to <code>plt.hist</code> does the trick. With Seaborn:</p> <pre><code>sns.distplot(df.index, hist_kws={"weights":list(df.freq)}) </code></pre>
python|pandas|matplotlib
1
364,840
34,279,588
Python Pandas - sum a boolean variable by hour
<p>I have a pretty simple question: I have a pandas DataFrame that looks like:</p> <pre><code> y 2015-12-09 09:00:00 1 2015-12-09 08:48:00 1 2015-12-09 08:24:00 1 2015-12-09 08:12:00 1 2015-12-09 08:00:00 1 2015-12-09 06:36:00 1 2015-12-09 06:24:00 1 ... .. 2015-12-08 10:12:0...
<p>The solution is relatively straightforward, but it does implicitly assume that in your data set, <code>0</code> equates to <code>False</code> (which seems logical to me). If so, this works:</p> <p><code>df.resample('1H', how='sum').fillna(0)</code></p> <p>Else you may have to look into a different way of sorting t...
python|numpy|pandas
1
364,841
34,274,692
Pandas - Merge and Groupby different dataframes and create new columns
<p>Have <code> n </code> number of dataframes with <code>n</code> number of <code>City</code> columns. </p> <p>df1: </p> <pre><code> ID City City1 City2 .... CityN 444x Lima DC 222x Rica Dallas 555x Rio London 333x NYC Tokyo 777x SF ...
<p>IIUC you could use <code>pd.merge</code> without <code>left</code> parameter:</p> <pre><code>In [14]: df1 Out[14]: ID City City1 City2 0 444x Lima - DC 1 222x Rica Dallas - 2 555x Rio London - 3 333x NYC Tokyo - 4 777x SF - Nairobi In [15]: df2 ...
python|pandas|group-by
0
364,842
37,081,335
How can I combine several numpy arrays to a single string representation?
<p>I have a few numpy arrays:</p> <pre><code>X = np.array([0,0,0,0,1,1,1,1]) Y = np.array([0,0,1,1,0,0,1,1]) Z = np.array([0,1,0,1,0,1,0,1]) </code></pre> <p>How can I use those to generate this:</p> <pre><code>array(['0_0_0', '0_0_1', '0_1_0', '0,1,1', ... ], dtype='|S1') </code></...
<h3>Solution</h3> <pre><code>np.array(["_".join(row.astype('|S1')) for row in np.concatenate([[X], [Y], [Z]]).T]) </code></pre>
arrays|numpy
0
364,843
36,956,600
How can I install tensorflow framework on NAO robot?
<p>I want to install TensorFlow framework to try my MNIST model (a deep neural network to recognize digits) on NAO! I downloaded OpenNAO OS virtual machine in the terminal I tried the commands</p> <p>$ sudo apt-get install python-pip python-dev $ sudo pip install --upgrade <a href="https://storage.googleapis.com/tenso...
<p>OpenNao runs on linux but not on ubuntu. It runs on Gentoo, the commands are different.</p>
installation|frameworks|tensorflow|nao-robot
-1
364,844
36,708,265
why do I keep getting the same answer with this conditional, python pandas
<p>This might be a really dumb problem but I've been stuck on it for awhile. </p> <p>Here's the csv</p> <pre><code>DATE,TIME,OPEN,HIGH,LOW,CLOSE,VOLUME 02/03/1997,09:30:00,3045.00,3045.00,3045.00,3045.00,28 02/04/1997,09:30:00,3077.00,3078.00,3077.00,3077.50,280 02/05/1997,09:30:00,3094.00,3094.50,3094.00,3094.00,50...
<p>You works with Series, so you have to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.all.html" rel="nofollow"><code>all</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.any.html" rel="nofollow"><code>any</code></a>:</p> <pre><code>b930 = df...
python-2.7|date|pandas|dataframe
2
364,845
36,924,149
Python: Scatter plot using group_by function in Pandas
<p>I have a dataframe which has a column named genres. Each genres has multiple values as movie name. The format is given below:</p> <pre><code> Movie_val Genre 2 Fantasy 11 Adventure 12 Comedy 2 Fantasy 2 Adventure 11 Adventure 13 Thri...
<p>The seaborn library can probably give you what you're after. Of course you still need to pick which columns of your data frame will provide the coordinates for the scatter plot.</p> <pre><code>import seaborn as sns g = sns.FacetGrid(df, hue="Genre", size=5) g.map(plt.scatter, "column name for x dimension", "column ...
python|pandas|matplotlib|plot|dataframe
0
364,846
36,942,399
How to check whether the content of Column A is contained in Column B using Python DataFrame?
<p>I have two columns in a pandas DataFrame: <code>authors</code> and <code>name</code>. I want to create a third column: a cell's value is <code>True</code> if the corresponding row's <code>name</code> is contained in the corresponding row's <code>authors</code>, and <code>False</code> otherwise.</p> <p>So the result...
<p>IIUC then you can <a href="http://pandas.pydata.org/pandas-docs/version/0.18.0/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a> a lambda row-wise to check if the Name string is present in Authors:</p> <pre><code>df['Check'] = df.apply(lambda row: row['Name'] in row['Authors'], axis=1) </...
python|pandas|dataframe
5
364,847
36,989,365
Theano: arguments for calling Theano functions
<p>The nature of python makes it very hard for me to find a kind of formal definition how to call a theano function.</p> <p>When given a list of matrices <code>batch</code> with length 4, I call </p> <pre><code>validationFunction(batch[0],batch[1],batch[2],batch[3]) </code></pre> <p>and this works.</p> <p>When I ca...
<p>I found the solution in this <a href="https://stackoverflow.com/questions/4979542/python-use-list-as-function-parameters">stackoverflow</a>, I simply had to call it:</p> <pre><code>validationFunction(*batch) </code></pre> <p>instead of </p> <pre><code>validationFunction(batch) </code></pre> <p>Oh dear, the m...
python|numpy|theano
0
364,848
36,888,695
Can't import tensor flow
<p>I have successfully installed tensorflow using pip. I have python 2.7.11. To double check when I do <strong>pip show tensorflow</strong>, It shows me that tensorflow 0.8.0 version is succesfully installed.</p> <p>But to test the installation I did </p> <pre><code>$python import tensorflow as tf </code></pre> <p>t...
<p>Are you sure that when yo call python interpreter version 2.7 is default? try type in your shell</p> <pre><code>python -V </code></pre> <p>to verify which version is default. If it isn't 2.7, try type</p> <pre><code>python2.7 -c "import tensorflow as tf" </code></pre> <p>and see if you get any error</p>
python-2.7|ubuntu|tensorflow|tensorboard
0
364,849
37,042,786
Calculating autocorrelation function with Python
<p>All that I am trying to do is to calculate the auto correlation of an array jx for which I am using the following formula,</p> <p><a href="https://i.stack.imgur.com/7J9X0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7J9X0.png" alt="autocorrelation formula"></a></p> <p>where n is the time at w...
<p>It seems that you have a division by zero. It works this way:</p> <p>1) In the line <code>for n in linspace(0,Mt-1,Mt):</code> you have <code>n==Mt-1</code>,</p> <p>2) So, in the next line <code>ac=Hcacf(n+1)</code> you call the function <code>Hcacf(Mt)</code>,</p> <p>3) But inside this function <code>Hcacf</code...
python|numpy|runtime-error|correlation
2
364,850
36,922,518
Store the counts for a specific value in a column in Pandas dataframe
<p>I have a dataframe with two columns as <code>SESSION</code> and <code>PRICE_POINT</code>. </p> <p><code>SESSION</code> is a category variable (values with various ip sessions)</p> <p><code>PRICE_POINT</code> has two values such as 'high', 'low'</p> <p>I am running the following:</p> <pre><code>n = pd.value_count...
<p>How about:</p> <pre><code>n = df.price_point.value_counts().high m = df.price_point.value_counts().low df = pd.DataFrame(data={'price':['high', 'high', 'low', 'low', 'low', 'low']}) df.price.value_counts().high 2 </code></pre> <p>or, in two steps:</p> <pre><code>counts = df.price_point.value_counts() n = counts...
python|pandas|count
1
364,851
36,797,435
PCR (Dollar-weighted Put Call Ratio) calculation issues
<p>I am trying to generate a Put / Call Ratio calculation program for my own purpose. Here is the code: problem is I am stuck in some places.</p> <ol> <li>I need to generate a summation of all strikes volume * all strikes prices</li> <li>and final one is generating the ratio i.e. summation (all strikes PUT volume * al...
<pre><code> from nsepy import get_history from datetime import date import pandas as pd import requests from io import BytesIO import certifi from scipy import stats from dateutil.relativedelta import relativedelta import numpy as np #import matplotlib.pyplot as plt import datetime import numpy as np import matplot...
python|pandas|numpy
-1
364,852
36,966,213
A pythonic approach to extracting data from array
<p>Is there a more pythonic way of extracting data from this txt file? It seems cumbersome to declare global variables beforehand and iterate using range rather than python's for i in i approach.</p> <pre><code>data1 = np.loadtxt("testProfil5.txt",float,delimiter=None) x,y = [],[] for i in range(np.size(data1)/2): ...
<p>Avoid using Python lists whenever possible when you have NumPy arrays containing your data. In your case:</p> <pre><code>x = data1[:,0] y = data1[:,1] </code></pre> <p>Then you can plot the data directly, with no copying.</p> <p>P.S.: if you do need <code>np.size(data1)/2</code> someday, you can simply say <code...
python|arrays|numpy
1
364,853
36,988,123
pandas groupby and rolling_apply ignoring NaNs
<p>I have a pandas dataframe and I want to calculate the rolling mean of a column (after a groupby clause). However, I want to exclude NaNs.</p> <p>For instance, if the groupby returns [2, NaN, 1], the result should be 1.5 while currently it returns NaN.</p> <p>I've tried the following but it doesn't seem to work:</p...
<p>As always in pandas, sticking to vectorized methods (i.e. avoiding <code>apply</code>) is essential for performance and scalability.</p> <p>The operation you want to do is a little fiddly as rolling operations on groupby objects are not NaN-aware at present (version 0.18.1). As such, we'll need a few short lines of...
python|pandas|dataframe|nan|pandas-groupby
10
364,854
36,762,283
Skip loop if a function is taking too long?
<p>I have Python code which is taking too long, and I would like to stop and skip execution of this function if it takes longer than a few seconds.</p> <p>For example, the function I want to time is:</p> <pre><code>batch_xs, batch_ys = train_loadbatch_from_lists(batch_size) </code></pre> <p>In some instances this funct...
<p>When you call a function in the same thread, it will normally not return until complete. The function you call really has to be designed to be interruptible in the first place. There are many ways to achieve this, with varying degrees of complexity and generality.</p> <p>Probably the simplest way is to pass the ti...
python|numpy
2
364,855
36,933,725
Pandas time series - join by closest time
<p>I have two dataframes which can be represented by the following MWE:</p> <pre><code>import pandas as pd from datetime import datetime import numpy as np df_1 = pd.DataFrame(np.random.randn(9), columns = ['A'], index= [ datetime(2015,1,1,19,30,1,20), ...
<p>Pandas now provides the functionality I believe you are looking for:</p> <pre><code>pd.merge_asof(df1, df2, direction='nearest') </code></pre> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html#pandas.merge_asof" rel="nofollow noreferrer">See merge_asof docs</a></p> <p>Exam...
python|pandas|time-series
1
364,856
37,122,157
Trouble resampling data in Pandas
<p>I'm trying to resample weather data with Pandas. The original data is in roughly 5 minute intervals. Eventually, I would like to export separate excel files with data resampled at 5 minute, 15 minute, and 1 hour intervals.</p> <p>I have successfully set 'Time' column as datetime index, but when I try to resample, I...
<p>This is what is happening with your data.</p> <p><a href="https://i.stack.imgur.com/G0TrJ.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G0TrJ.gif" alt="enter image description here"></a></p> <p>To fix it:</p> <pre><code>&gt;&gt;&gt; df[df.Time.notnull()].set_index('Time').astype(float).resamp...
python|pandas|resampling
2
364,857
54,737,179
Convert a Pandas DataFrame into a list
<p>How do I go from a data frame:</p> <pre><code>df = pd.DataFrame({'a': range(0, 10), 'b': range(10, 20), 'c': range(20, 30)}) </code></pre> <p>that looks like:</p> <pre><code> a b c 0 0 10 20 1 1 11 21 2 2 12 22 3 3 13 23 4 4 14 24 5 5 15 25 6 6 16 26 7 7 17 27 8 8 18 28 9 9 19 ...
<p>Using numpy:</p> <pre><code>list(np.reshape(df.values, -1, order='F')) </code></pre> <p>Your df has a shape of (10,3), and you want a shape of (30,). You can achieve this with numpy's reshape.</p> <p><code>-1</code> is simply a shortcut for <code>(30,)</code> in this instance.</p> <p><code>order='F'</code> ensur...
python|pandas
3
364,858
54,742,816
Groupby and find difference from min value of group : Pandas
<p>I have a group like following, how can I know the difference of every observation with it's group minimum value</p> <pre><code>GROUP VALUE 1 5 2 2 1 10 2 20 1 7 </code></pre> <p>So, my desired output should be like </p> <pre><code>GROUP VALUE diff 1 5 3 2 2 0 1 10 5...
<p>I think 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> with subtract:</p> <pre><code>df['diff'] = df['VALUE'] - df.groupby('GROUP')['VALUE'].transform('min') print (df) GROUP VALUE ...
python|pandas|group-by
4
364,859
54,975,586
Assign new Column based off values in separate Column
<p>I am trying to find a more efficient way to assign values to a <code>Column</code> based off values in a separate <code>Column</code>. For the <code>df</code> below, I want to assign a <code>0</code> to weekdays and <code>1</code> to weekends. </p> <p>This is my attempt:</p> <pre><code>import pandas as pd import n...
<p>Each time you do <code>df['Group'] = np.where(...)</code> you are setting the values of the <code>Group</code> column from the beginning. So, in your series of statements, the only one that really counts is the last one:</p> <pre class="lang-py prettyprint-override"><code>df['Group'] = np.where(df['Day'] == 'Sunday...
python|numpy|assign
1
364,860
55,066,710
Computing gradients wrt model inputs in Tensorflow eager mode
<p>I am interested in calculating gradients wrt. the inputs of a keras model in Tensorflow. I understand that previously this can be done by building a graph and using <code>tf.gradients</code>. For example <a href="https://github.com/maziarraissi/PINNs/blob/master/main/continuous_time_identification%20(Navier-Stokes)/...
<p>Here is an example of retrieving the gradients of the predictions with respect to the inputs using eager execution</p> <p>Basically, you need to use tape.watch(inputs) [I am using features in my example - whatever you want to call your x ... ] for Tensorflow to record the change in the model output (you can do the ...
python|tensorflow|eager-execution
4
364,861
54,931,882
Comparing daily value in each year in DataFrame to same day-number's value in another specific year
<p>I have a daily time series of closing prices of a financial instrument going back to 1990. </p> <p>I am trying to compare the daily percentage change for each trading day of the previous years to it's respective trading day in 2019. I have 41 trading days of data for 2019 at this time.</p> <p>I get so far as filte...
<p>I also came up with my own answer more along the lines of what I was trying to originally accomplish. DataFrame I'll work with for the example. <code>df</code>:</p> <p><code>Dates last perc year tdoy 0 2016-01-04 29.93 -0.020295 2016 2 1 2016-01-05 29.63 -0.010023 2016 3 2 ...
python|pandas|dataframe|compare|time-series
0
364,862
54,696,367
Normalizing data in a Pandas GroupBy dataframe using a reference group
<p>I have a Pandas dataframe resulting from a groupby() operation. This dataframe has two indexes (year, month). How can I normalize a column relative to the corresponding month in a specific year?</p> <p>My dataframe looks like the following:</p> <pre><code> value year month 2000 1 1234 2 ...
<p>Use <code>DataFrame.div</code> with a <code>level</code> argument.</p> <pre><code>df.div(df.xs(2002), level=1, axis=0) value year month 2000 1 0.357060 2 0.672706 2001 1 0.678530 2 0.836353 2002 1 1.000000 2 1.000000 </code></pre> <p>Where,</p>...
python|pandas|dataframe|pandas-groupby
2
364,863
54,723,282
Random choice over specific values of a DF
<p>I have a big df with 17520 rows and 1000 columns. The df has only two values [0,0.05]. I would like to go to each cell of the df with the value of 0.05 and change it for a random value. The random value can only be 0 or 0.05.</p> <p>I tried the following line of code:</p> <pre><code> y = np.array([0,0.05]) df.rep...
<p>Instead of looping, you coulde use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.update.html" rel="nofollow noreferrer"><code>df.update()</code></a> like this, to get a speed-up of >20x:</p> <pre><code>df = pd.DataFrame(np.random.choice([0, 0.05], size=(4000, 1000))) %timeit...
python|numpy|dataframe
1
364,864
55,064,303
How to read date and time from csv in python?
<p>I am getting an error in time series date-time parsing function. The data is <a href="https://ufile.io/jbe10" rel="nofollow noreferrer">attached</a>. I tried this to read the Date and time column.</p> <pre><code>Data = pd.read_csv('Data.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser) ...
<p>Your <code>strptime()</code> function needs to be formatted exactly as the timestamp is formatted, including slashes and colons. You can find the details on <a href="https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior" rel="nofollow noreferrer">the python documentation</a>.</p> <p>In this cas...
python|pandas|datetime|timestamp|time-series
0
364,865
55,066,006
quotations in arrays of strings in pandas to_csv read_csv on jupyter
<p>This post is a follow up from <a href="https://stackoverflow.com/questions/21147058/pandas-to-csv-output-quoting-issue">pandas to_csv output quoting issue</a>.</p> <p>Say, I create a data frame with text data. This text data is stored as a list of strings:</p> <pre><code>In [1]: import pandas as pd In [2]: text =...
<p>CSV needs to be able to store the data in a way that it can be loaded back in, so it <a href="https://en.wikipedia.org/wiki/Escape_character" rel="nofollow noreferrer">escapes</a> the characters that have meaning (notably the commas, which are the default column delimiters, and the single quotes, which would otherwi...
python|pandas
0
364,866
54,788,058
Keras NASNet training
<p>I intend to:</p> <ol> <li>Train NASNet from scratch on a dataset</li> <li>Re-train only the last layer of NASNet (transfer learning)</li> </ol> <p>and compare their relative performance. From the documentation i see:</p> <p><code>keras.applications.nasnet.NASNetLarge(input_shape=None, include_top=True, weights='i...
<p>Here are the answers for your questions:</p> <pre><code>For transfer learning, do I set include_top = True and classes = (num_classes), freeze all the layers except the last one, then train that? </code></pre> <p>When loading any model that you want to use for transfer learning, if you set the “include_top” argu...
python|tensorflow|keras
0
364,867
54,915,584
How do I split text with multiple sentences in a column into multiple rows in Python pandas?
<p>I am trying to split Comments column into multiple rows containing each sentence. I used the following StackOverflow thread for my reference as it tends to give similar result. <strong>Reference Link:</strong> <a href="https://stackoverflow.com/questions/17116814/pandas-how-do-i-split-text-in-a-column-into-multiple-...
<p>In the example that you put in your code, The result of the <code>join</code> was printed, so if you want to change the value of your survey_text, the code should be:</p> <p><code>survey_text = survey_text.join(x)</code></p> <p>or if you wanted to simplify your code, this code below is just fine:</p> <pre><code>i...
python|pandas|text-mining|sentence-synthesis
4
364,868
55,020,741
math operations between column in multiindex dataframe
<p>I have a dataframe with column multiindex that I need to slice and perform math operations between the slices.</p> <pre><code># sample df idx=pd.IndexSlice np.random.seed(123) tuples = list(zip(*[['one', 'one', 'two', 'two', 'three', 'three'],['foo', 'bar', 'foo', 'bar', 'foo', 'bar']])) index = pd.MultiIndex.from_...
<p>If need MultiIndex in output use <code>rename</code> for same level od MultiIndex:</p> <pre><code>df = df.loc[:,idx['three',:]] - df.loc[:,idx['two',:]].rename(columns={'two':'three'}) print (df) first three second foo bar A -0.861579 3.157731 B -1.944822 0.772031 C 2.64...
python|pandas|dataframe
6
364,869
54,989,613
Error that numpy library import is not available?
<pre><code>from numpy import * from pylab import * </code></pre> <p>Why am I getting a warning next to both of these lines "unable to detect undefined names" </p>
<p>Because numpy module don't come with python standard library. you should first install numpy by using python pakage manager : pip if you are in windows then you can run following command in cmd pip install numpy to install numpy and then you can import in your python file</p>
python-3.x|numpy|matplotlib|spyder
0
364,870
55,124,857
pandas wide_to_long with float in columns name
<p>I can use the example for the wide_to_long and it works fine.</p> <pre><code>df = pd.DataFrame({"A1970" : {0 : "a", 1 : "b", 2 : "c"}, "A1980" : {0 : "d", 1 : "e", 2 : "f"}, "B1970" : {0 : 2.5, 1 : 1.2, 2 : .7}, "B1980" : {0 : 3.2, 1 : 1.3, 2 : .1}, ...
<p>The default capturing group for suffixes is <code>'\d+'</code>, which does what it's supposed to, but the documentation is misleading/incorrectly worded:</p> <blockquote> <p>'\d+’ captures numeric suffixes.</p> </blockquote> <p><code>'(\d+)'</code> is not the correct capturing group for decimal numbers, and woul...
python-3.x|pandas
5
364,871
54,765,818
AttributeError: 'NoneType' object has no attribute 'fit_generator'
<p>Code :</p> <pre><code>import numpy as np import pandas as pd import os from tqdm import tqdm # Fix seeds from numpy.random import seed seed(639) from tensorflow import set_random_seed set_random_seed(5944) # Import float_data = pd.read_csv("train.csv", dtype={"acoustic_data": np.float32, "time_to_failure": np.fl...
<p>your issue is here:</p> <pre><code>model = model.compile(optimizer=adam(lr=0.0005), loss="mae") history = model.fit_generator(train_gen, steps_per_epoch=1000, epochs=30, verbose=0, callbacks=cb, ...
python|tensorflow|machine-learning|keras|deep-learning
5
364,872
55,034,347
Extract interpolated values from a 2D array based on a large set of xy points
<p>I have a reasonably large 1000 x 4000 pixel <code>xr.DataArray</code> returned from an <a href="https://www.opendatacube.org/" rel="nofollow noreferrer">OpenDataCube</a> query, and a large set (> 200,000) of <code>xy</code> point values. <strong>I need to sample the array to return a value under each <code>xy</code>...
<p>To avoid the full grid, you need to introduce a new dimension.</p> <pre><code>x = xr.DataArray(x_points, dims='z') y = xr.DataArray(y_points, dims='z') val_array.interp(x=x, y=y) </code></pre> <p>Will give you an array just along the new z dimension:</p> <pre><code>&lt;xarray.DataArray (z: 10000)&gt; array([4.368...
python|numpy|scipy|interpolation|python-xarray
12
364,873
54,744,340
Trying to plot a system of linear equation using matplotlib in a 2D plane
<p>As the title says, I am trying to plot a system of linear equations to get the intersection point of the 2 equations. </p> <p>8a-b = 9</p> <p>4a+9b = 7.</p> <p>below is the code i have tried.</p> <pre><code>import matplotlib.pyplot as plt from numpy.linalg import inv import numpy as np a = np.array([[8,-1],[4,9...
<p>To plot the lines it's easiest if you rearrange your equations to in terms of <code>b</code>. This way <code>8a-b=9</code> becomes <code>b=8a-9</code> and <code>4a+9b=7</code> becomes <code>b=(7-4a)/9</code></p> <p>It also looks like you were trying to draw the "axis" of the graph, I've fixed this in the code below...
python|numpy|matplotlib
3
364,874
54,819,369
Problem with Opening Tensorboard in Github for windows
<p>I am using Github for windows and I have installed Anaconda and tensorflow. I would like to open Tensorboard. Following <a href="https://itnext.io/how-to-use-tensorboard-5d82f8654496" rel="nofollow noreferrer">https://itnext.io/how-to-use-tensorboard-5d82f8654496</a>, I type </p> <pre><code>tensorboard --logdir="./...
<p>Did you try to open browser and go to <a href="http://DESKTOP-VSHNRU0:6006" rel="nofollow noreferrer">http://DESKTOP-VSHNRU0:6006</a> web page? And maybe even better <a href="http://localhost:6006" rel="nofollow noreferrer">http://localhost:6006</a>?</p>
python|windows|tensorflow|github
0
364,875
55,084,276
How to get x and y value pairs of pandas in python
<p>I have created a co-occurrence matrix as follows using pandas.</p> <pre><code>import pandas as pd import numpy as np lst = [ ['a', 'b'], ['b', 'c', 'd', 'e', 'e'], ['a', 'd', 'e'], ['b', 'e'] ] u = (pd.get_dummies(pd.DataFrame(lst), prefix='', prefix_sep='') .groupby(level=0, axis=1) ...
<p>You can try <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="noreferrer">np.where</a>:</p> <pre><code>arr = np.where(v&gt;=1) corrs = [(v.index[x], v.columns[y]) for x, y in zip(*arr)] corrs [('a', 'b'), ('a', 'd'), ('a', 'e'), ('b', 'a'), ('b', 'c'), ('b', 'd'), ('b', 'e'...
python|pandas
5
364,876
54,910,277
Creating a curve from dataframe
<p>I have a dataframe that looks like this : </p> <pre><code> 0 1 2 ... 147 148 149 Columns 0 190.2 190.5 189.9 ... 146.7 146.4 146.1 Values 0 -49.3892 -47.0297 -39.528 ... -30.7926 -30.7561 -30.719 Columns 1 190.2 190.5 ...
<p>To change the values of the <code>Columns #</code> rows, I used: </p> <pre><code>df2 = df2.apply(pd.to_numeric) </code></pre> <p>Then for teh purpose of plotting only the first pair:</p> <pre><code>i = 0 x_data = df2.values[[i]] y_data = df2.values[[(i+1)]] #line = plt.plot(x_data, y_data) #plt.setp(line, color...
python|pandas|matplotlib|area|curve
0
364,877
54,714,397
Tensorflow failure with Python Anaconda 3.7.1
<p>I installed Anaconda Anaconda3-2018-12 (Python 3.7.1) (<a href="https://repo.anaconda.com/archive/Anaconda3-2018.12-Windows-x86_64.exe" rel="nofollow noreferrer">this</a> version).</p> <p>Then I opened the "Anaconda prompt", and did <code>pip install keras</code> and <code>pip install tensorflow</code>. The install...
<p>As mentioned in a comment, this solved it:</p> <pre><code>pip install numpy --upgrade </code></pre>
python|numpy|tensorflow|keras|anaconda
1
364,878
54,974,905
AttributeError: 'numpy.ndarray' object has no attribute 'target
<p>I get the error an <strong>"AttributeError: 'numpy.ndarray' object has no attribute 'target'"</strong> when executing the <code>grid.fit()</code> command. I am not sure what this means and how to fix it. Can anybody advise?</p> <pre><code>#Grid Search Parameter Tuning import numpy as np from sklearn import datasets...
<p>You have given created random array as your dataset, you are passing that data set in fit but that data does not have target, you need to define another array which define labels.</p> <pre><code>x = np.random.rand(1000,2) y3 = np.concatenate((np.zeros(500),np.ones(500))) random = np.random.permutation(1000) y = y3[r...
python-3.x|numpy|scikit-learn|grid-search
0
364,879
55,096,990
Query date range and product size from xlsx file
<p>I'm using python 3.6 to do this. Below are just a few important columns that I'm interested to query out.</p> <pre><code> Auto-Gen Index : Product Container : Ship Date :....... 0 : Large Box : 2017-01-09:....... 1 : Large Box : 2012-07-15:....... 2 : Smal...
<p>If your question is when to use <code>loc</code> vs <code>where</code>, see my answer <a href="https://stackoverflow.com/questions/54900717/python-pandas-difference-between-loc-and-where/54900803#54900803">here</a>:</p> <blockquote> <p>Think of <code>loc</code> as a filter - give me only the parts of the df that ...
python-3.x|pandas|where-clause
1
364,880
54,736,060
How to replace NaN values in a column A with respect to average value that is related to column B?
<p>I am working on famous <a href="https://www.kaggle.com/c/titanic" rel="nofollow noreferrer">Titanic dataset</a>. Am trying to fill the <code>X.Age.isna()</code> NaN values with <code>Avg_Age_byTitle</code>,which i have calculated using <code>X.groupby('Name').mean()['Age']</code></p> <pre><code>Avg_Age_byTitle = ...
<p>IIUC you need:</p> <pre><code>df['Age'] = df.groupby('Pclass')['Age'].apply(lambda x: x.fillna(x.mean())).round(1) </code></pre> <p>this fills the NaN in Age based on the average of groups of <code>Pclass</code>.</p>
python|pandas
0
364,881
54,875,041
Read CSV from desktop of MacBook Pro into Pandas dataframe
<pre><code>crpcdf=pd.read_csv("/Users/gina/Desktop/LynnCrimeRatePerCapita.csv") crpcdf.head() </code></pre> <p>The above are a sample of the approaches I've tried. I always get the nonexistent file or path message. Doing this from Jupyter notebook. While trying other tricks, it would also not let me change my working...
<p>This is a tricky problem to help with, since I think we need more information about the file and perhaps post your error code and what you expect the file to be called. A very basic step that has caused me to me stumble many times is to be sure that there aren't any typos in the file path. You could also try moving ...
pandas|macos|csv|jupyter-notebook
2
364,882
54,831,241
Multiply all pairs of rows in a Numpy array
<p>I have an MxN Numpy array. I'd like to take each row of the array and multiply it element-wise by each row of the array, resulting in an MxMxN numpy array of the products.</p> <pre><code>le_input = np.array([ [0, 0, 1], [0, 1, 0] ]) le_expected_output = np.array([ [ [0, 0, 1], [0, 0, 0]...
<p>You can use <code>np.einsum</code>:</p> <pre><code>np.einsum('ik,jk-&gt;ijk', le_input, le_input) # array([[[0, 0, 1], # [0, 0, 0]], # [[0, 0, 0], # [0, 1, 0]]]) </code></pre> <p>Or create a new axis and use array's broadcasting property to calculate the outer product on the first dimension:...
python|arrays|numpy|matrix
5
364,883
55,006,336
Pandas - rolling mean with groupby
<p>I'm new to Pandas. I have a dataframe where I'm looking at Horse results. I'm trying to get a rolling mean for position finished results in a column for the last 30 days for each horse. Here's an example of two horses from the dataframe:</p> <pre><code> Horse Position OR RaceDate Weight 1252...
<p>Using <code>set_index()</code> will delete the original index, so use <code>reset_index()</code> first which will create a new column called 'index' containing your original index. Then inset of reset_index() at the end (which just creates an index 0, 1, 2...etc) use <code>set_index('index')</code> to go back to the...
python|pandas
7
364,884
54,997,899
Pandas Add a List to New Column or Append at the End
<p>I am adding new lists to a column of a dataframe of pandas. Since i am doing this in a loop, I want to first create a new column and put some values inside this column. Then, over other loop, I am adding new values to the column which is just created. How can I do this?</p> <p>I have a python list named all_materia...
<p>Below is a more pythonic way to do it:</p> <pre><code>import pandas as pd # first initialize your data frame with the columns # columns with empty data has been initialized, now you can just add data to it df = pd.DataFrame(columns=input_material_name) # to avoid any confusion I would advise you to first build t...
python|excel|pandas
0
364,885
54,856,726
Pandas - How to group-by and plot for each hour of each day of week
<p>I need help figuring out how to plot sub-plots for easy comparison from my dataframe shown:</p> <pre><code> Date A B C 2017-03-22 15:00:00 obj1 value_a other_1 2017-03-22 14:00:00 obj2 value_ns other_5 2017-03-21 15:00:00 obj3 value_kdsa othe...
<p>You can accomplish this with multiple <code>groupby</code>. Since we know there are 7 days in a week, we can specify that number of panels. If you <code>groupby(df.Date.dt.dayofweek)</code>, you can use the group index as the index for your subplot axes:</p> <h3>Sample Data</h3> <pre><code>import pandas as pd impo...
python|pandas|matplotlib
5
364,886
55,006,864
Removing rows from a dataframe based on condition or value
<p>Is there a way I can remove data from a df that has been grouped and sorted based on column values?</p> <pre><code> id time_stamp df rank 002 2019-02-23 20:01:13.362 mdf 0 002 2019-02-23 20:02:06.939 tof 1 004 2019-03-01 02:30:33.332 mdf 0 004 ...
<p>You could use boolean masking:</p> <pre><code>mask = df['df'].ne('mdf') &amp; df['rank'].eq(0) excl_id = df.loc[mask, 'id'].unique() df[~df['id'].isin(excl_id)] </code></pre>
python|python-3.x|pandas|dataframe|group-by
2
364,887
54,845,665
Groupby with finding highest value in subset
<p>I have data as follows:</p> <pre><code>In [16]: game_df.head(9) Out[16]: team_id game_id game_date w l wins losses winning% 0 1 1 11/16/18 1 0 20 10 0.666667 1 1 3 11/18/18 0 1 20 11 0.645161 2 1 6 11/21/18 0 1 20 12 0.625000 ...
<pre><code>df = df.sort_values(by='game_date') # sort by date # add a column for each team's latest %age, fill forward NaN (but not back) for team_id in df['team_id'].unique(): df[str(team_id) + 'win_%'] = df.loc[df.team_id == team_id, ['winning%', 'game_date']].set_index( 'game_date').reindex(df.game_dat...
python|pandas
0
364,888
55,079,682
Python: How can I check if an item in a list contains a string within an elif statement where two conditions must be met?
<p>I'm making a scraper in python that executes a search, then opens each link in the search and makes a list of everything within a strong tag.</p> <p>Then it append the list to a Dataset. Not all of the pages are the same so I am organizing them according to how many strong tags and in some cases if a particular tag...
<p>Just use <code>in</code> the other way around, you want to check if <code>strong[3]</code> is <code>in</code> the array <code>['Admin', 'Abandoned', ...]</code>:</p> <pre><code>l = ['Admin', 'Abandoned', 'Withdrawn', 'Dissolved', 'Terminated'] if len(strong) == 13 and strong[3] in l: values = strong[:5] + [''] ...
python|string|pandas|list|append
1
364,889
54,971,408
different element data types within numpy array?
<p>Just like list in python where [1,"hello", {"python": 10}] it can have all different types within, can numpy array have this as well?</p> <p>when numpyarray.dtype => dtype('float64') is it implying all elements are of type float? </p>
<p>From the docs:</p> <blockquote> <p>dtype : data-type, optional</p> <p>The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to ‘upcast’ the array. For downcasting, use the .ast...
python|numpy
1
364,890
54,800,780
How to capture specific fields from elasticsearch and convert into a pandas dataframe
<p>Using query <code>http://abc:9200/abc/_search?q=aid:123</code> I'm able to get the following result. First thing I would like to filter is 'aid' and then capture only the needed fields ("act_timestamp", "act_type", "mod_path", "mod_size) along with "procguid" and put them together in a table.</p> <p>Providing the e...
<p>You could break your task into parts. At first you focus on</p> <pre><code>df = pd.io.json.json_normalize(d['hits']['hits']) </code></pre> <p>This has the columns </p> <pre><code>['_id', '_index', '_score', '_source.activity', '_source.aid', '_source.doc_id', '_source.event_timestamp', '_source.procguid', '_sourc...
python|json|pandas|elasticsearch
0
364,891
54,731,343
When does Pandas default to broadcasting Series and Dataframes?
<p>I came across something curious (to me) while trying to answer <a href="https://stackoverflow.com/questions/54687567/pandas-loc-dynamic-conditional-list/54687856#54687856">this question</a>.</p> <p>Say I want to compare a series of shape (10,) to a df of shape (10,10):</p> <pre><code>np.random.seed(0) my_ser = pd....
<p>What is happening is pandas using intrinsic data alignment. Pandas almost always aligns the data on indexes, either row index or column headers. Here is a quick example:</p> <pre><code>s1 = pd.Series([1,2,3], index=['a','b','c']) s2 = pd.Series([2,4,6], index=['a','b','c']) s1 + s2 #Ouput as expected: a 3 b ...
python|pandas|array-broadcasting
7
364,892
55,080,465
Two parallel but different datasets in Keras as multiple inputs?
<p>I have been googling all day trying to find an example of the functional input for two parallel datasets in Keras but I can't find one. </p> <p>My problem is that I have dataset 1, a set of images of people performing different actions. It is formatted as a csv as follows:</p> <pre><code>image_url,class example1.p...
<p>Please check if this is useful. Tested with Keras 2.2.4.</p> <pre><code>from keras.layers import Conv2D, MaxPooling2D, Input, Dense, Flatten, concatenate from keras.models import Model import numpy as np img_input = Input(shape=(64, 64, 1)) ## branch 1 with image input x = Conv2D(64, (3, 3))(img_input) x = Conv2D...
python|tensorflow|keras
6
364,893
54,902,811
How to match and merge two dataframes having completely different values except numericals in columns of dataframe?
<p>have a dataframe ABC of value</p> <pre><code> id | price | type 0 easdca | Rs.1,599.00 was trasn by you | unknown 1 vbbngy | txn of INR 191.00 using | unknown 2 awerfa | Rs.190.78 credits was used by you | unknown 3 zxcmo5 ...
<p>You can do the following:</p> <pre><code>''' First we make a artificial key column to be able to merge We basically just substract the floating numbers from the string And convert it to type float ''' df1['price_key'] = df1['price'].str.replace(',', '').str.extract('(\d+\.\d+)').astype(float) # After that we do a...
python|python-3.x|pandas|dataframe|epoch
1
364,894
55,115,214
Convert dataframe into dictionary
<p>I have a dataframe and i want it to select a few columns and convert it into Dictionary in the a certain manner</p> <p>Dataframe:</p> <p><a href="https://i.stack.imgur.com/geLqv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/geLqv.png" alt="Dataframe :"></a></p> <p>and here's the output I want</p> <pr...
<p>Set parameter <code>drop=False</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="noreferrer"><code>DataFrame.set_index</code></a>, because default parameter <code>drop=False</code> move column to index:</p> <pre><code>cols = ["Length","Width","Height"...
python|python-3.x|pandas|dataframe|dictionary
13
364,895
54,905,141
Calculate dot product of array of nxn arrays with nx1 arrays
<p>Given:</p> <pre><code>A = np.array([[[10, -1], [-1, 10]], [[30, 4], [5, 10]]]) B = np.array([[[5],[2]], [[3],[4]]]) </code></pre> <p>I would like to take the dot product between the two arrays with the 2x2 arrays in A, with the 2x1 arrays in B, so what I ...
<pre><code>In [60]: A = np.array([[[10, -1], ...: [-1, 10]], ...: [[30, 4], ...: [5, 10]]]) ...: B = np.array([[[5],[2]], ...: [[3],[4]]]) In [61]: A ...
python|arrays|numpy
1
364,896
55,006,640
Plotting Matplotlib Histogram of one pandas dataframe column with average of another represented by a dot
<p>Basically have a pandas dataframe that looks like :</p> <pre><code>d = {'Percentage' : [8,20,24,27, 58], 'Assets' : [10,12,53,32,11]} df = pd.DataFrame(d) </code></pre> <p>I want to create a histogram of the Percentage column with the frequency a percentage falls with in bin, which I did with :</p> <pre><code>bi...
<p>A histogram would work here, but I think it's easier to calculate it yourself and use a bar graph--given that you have to deal with <code>Assets</code> as well.</p> <p>The idea is that you need to determine which bin each data point belongs. Then you can group by bin and average to calculate your average <code>Asse...
python|pandas|matplotlib|histogram
0
364,897
54,916,883
Pandas - Datatype Object - .loc not working on numbers
<p>so I have a very simple pandas script that I use to replace values in excel with other values. There is one colum (Fm) that does not work when I am trying to replace the numerical values. Column Fm dtype is object. But it just will not work when I try to replace the 350 value, (Commented in my code the line) but eve...
<p>I had a similar situation doing a merge, I think what might happen is that while the column is an object, each cell is considered separately when doing comparisons. Meaning that if you want to or have mixed data types in your columns, you want to set that column (in this case) to strings before doing the comparison...
python|excel|pandas
2
364,898
49,768,839
Can device run tensorflow lite be used as a work task when performing distribute training?
<p>Can a device running tensorflow lite be used as a work task of parameter server when performing distribute training?</p>
<p>At this point TensorFlow Lite performs only the forward pass (aka inference), not the back propagation (BP), so it doesn't fit into the training pattern (many iterations of forward and BP).</p> <p>Plus, TensorFlow Lite is designed to be small and fast on resource constrained devices so it does not make much sense t...
tensorflow
0
364,899
49,372,868
How to add blank rows before a data frame while using pandas.to_csv
<p>I want to write a dataframe to a file </p> <pre><code> dataToGO = {'Midpoint': xdata1, '': "", 'Avg Diam': ydata1, '' : ""} colums = ['Midpoint', '', 'Avg Diam', ''] ToFile = pad.DataFrame(data=dataToGO, columns=colums) ToFile.to_csv("processed"+filname+".csv", index...
<p>you can try something like this, open the file first, write whatever you want, then write the dataframe</p> <pre><code>a = open("test.csv","w") a.write("\n") df.to_csv(a) a.close() </code></pre>
python|pandas|file|csv|dataframe
0