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
369,500
29,996,968
Numpy with Blas and OpenBlas take the same time
<p>I install <code>Numpy</code> (in a virtualenv <code>env</code>) with <code>OpenBlas</code> (from the system).</p> <pre><code>$ sudo apt-get install libopenblas-dev (env)$ mkdir evn/download (env)$ pip install -d env/download numpy (env)$ mkdir env/build (env)$ cd env/build (env)$ tar xzf ../download/numpy-1.9.2.ta...
<p>If you use <code>pip</code> to install <code>numpy</code>, I believe that will build it without OpenBLAS support, no matter what you put in the <code>site.cfg</code> file.</p> <p>You have to explicitly call <code>python setup.py build</code> etc. You can follow for instance this <a href="https://stackoverflow.com/...
python|numpy|openblas
0
369,501
29,836,716
Pandas Pivot Table Subsetting
<p>My pivot table looks like this:</p> <pre><code>Symbol DIA QQQ SPY XLE DIA QQQ SPY XLE DIA QQQ \ Open Open Open Open High High High High Low Low Date 19930129 NaN NaN 29.0832...
<p>An alternative is to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.xs.html" rel="nofollow">xs</a>, "cross-section":</p> <pre><code>In [21]: df.xs(axis=1, level=1, key="Open") Out[21]: Symbol DIA QQQ SPY XLE Date 19930129 NaN NaN 29.083294 NaN 19930201 NaN NaN ...
python|pandas
2
369,502
29,834,729
pandas not saving content of table into csv
<p>I have done something like this to create an empty dataframe and filling it. However, it looks like the output is empty, that is, only the header is created, not the rest of the data. </p> <pre><code>def create_data(self): mydf = pd.DataFrame(columns=&lt;some header&gt;) data = [] for i in xrange(0, 10)...
<p>You need to assign the result of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html#pandas.DataFrame.append" rel="nofollow"><code>append</code></a> as it returns the result of the append:</p> <pre><code>def create_data(self): mydf = pd.DataFrame(columns=&lt;some header&g...
python|csv|pandas
0
369,503
30,246,804
Is there a way to parallelize Pandas' Append method?
<p>I have 100 XLS files that I would like to combine into a single CSV file. Is there a way to improve the speed of combining them all together?</p> <p>This issue with using concat is that it lacks the arguments that to_csv affords me: </p> <pre><code>listOfFiles = glob.glob(file_location) frame = pd.DataFrame() ...
<p>Using <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">multiprocessing</a>, you could read them in parallel using something like:</p> <pre><code>import multiprocessing import pandas as pd dfs = multiprocessing.Pool().map(df.read_excel, f_names) </code></pre> <p>and then concatenate ...
python|csv|pandas
3
369,504
29,935,056
Pandas: How to extract rows of a dataframe matching Filter1 OR filter2
<p>I have a pandas dataframe that look like this for exemple:</p> <pre><code>label Y88_N diff div fold 0 25273.626713 17348.581851 2.016404 2.016404 1 29139.510491 -4208.868050 0.604304 -0.604304 2 34388.439717 -30147.834699 0.458903 -0.458903 3 69704....
<p>You could do</p> <pre><code>In [276]: df[(df['fold'] &gt;= 2) | (df['fold'] &lt;= -0.6)] Out[276]: label Y88_N diff div fold 0 0 25273.626713 17348.581851 2.016404 2.016404 1 1 29139.510491 -4208.868050 0.604304 -0.604304 5 5 28996.634708 10934.944533 2.031293...
python|pandas
3
369,505
30,128,130
Efficient way to slice a numpy array based on unknown identical values in first column
<p>I have a relatively large data file on the order of 10GB with three columns that looks something like: </p> <pre><code>X Y Z ---- ---- ---- .10000E+05 100 35 .10000E+05 101 45 . . . . . . . . . .10000E+05 400 45 .16730E+05 100 43 ....
<p><code>numpy</code> has some functions, that help you to accomplish your task:</p> <pre><code>borders = data[0,:].searchsorted(numpy.unique(data[0,:])) part0 = data[borders[0]:borders[1]] </code></pre> <p>But I wouldn't suggest to break the big array apart, but to index into it with <code>borders</code>, whenever n...
python|arrays|numpy
3
369,506
30,081,216
Adding multiple rows in an existing dataframe
<p>Hi I'm learning data science and am trying to make a big data company list from a list with companies in various industries.</p> <p>I have a list of row numbers for big data companies, named comp_rows. Now, I'm trying to make a new dataframe with the filtered companies based on the row numbers. Here I need to add ...
<p>It seems you are trying to filter out an existing dataframe based on indices (which are stored in your variable called <code>comp_rows</code>). You can do this without using loops by using <code>loc</code>, like shown below:</p> <pre><code>In [1161]: df1.head() Out[1161]: A B C D ...
python|pandas|ipython
7
369,507
30,133,411
Numpy linalg norm not accepting scalar when order is specified
<p>Well, the title says it all:</p> <pre><code>from numpy import linalg as LA import numpy as np fortytwo = np.array(42) LA.norm(42) # works LA.norm(fortytwo) # works # All the lines below raise a ValueError: LA.norm(fortytwo,np.inf) LA.norm(fortytwo,-np.inf) LA.norm(fortytwo,1) LA.norm(42,1) </code></pre> <p>I had t...
<p>Here's part of the code (all Python and available for all to see):</p> <pre><code>if ord is None and axis is None: return sqrt(add.reduce((x.conj() * x).real, axis=None)) </code></pre> <p>This is your case that works.</p> <p>But when you specify <code>ord</code>, it looks at the dimensions. In your case <cod...
python|numpy
1
369,508
29,934,697
Match Exactly column name in a data frame
<p>I have the following </p> <pre><code>for col in Features: My_Features = pd.merge(My_Features,Drug.ix[:,[col]], left_index = True,right_index=True) </code></pre> <p>which produces the following </p> <pre><code>My_Features.columns Out[373]: Index([u'**PCBD1_x**', u'**PCBD1_y**', u'KLK8', u'TNFSF13 /// TNFSF12-...
<p>You can use pandas.DataFrame.filter(). It has a regex argument [as well as a "like" argument]. <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html</a></p>
python|pandas
0
369,509
29,926,698
Pivoting a pandas dataframe with duplicate index values
<p>I have a data frame which has rows for each user joining my site and making a purchase.</p> <pre><code>+---+-----+--------------------+---------+--------+-----+ | | uid | msg | _time | gender | age | +---+-----+--------------------+---------+--------+-----+ | 0 | 1 | confirmed_settings | 1/29/1...
<p>I suspect there are indeed duplicate <code>uid</code>-<code>msg</code> entries/keys (e.g. <code>uid</code> 2 has 2 confirmed_settings entries under <code>msg</code>), which you alluded to in the comments for fixxxer's answer. If there are, you can't use <code>pivot</code>, because you can't tell it how to treat the ...
python|pandas
6
369,510
29,960,345
Python / Pandas Tables
<p>First: thank you for the great help so far! I have a question on working with table formatting in iPython.</p> <p>I currently run this script to print the Augmented Dickey-Fuller (ADF) Test for Stationarity: </p> <pre><code>print "Stationarity" print sm.tsa.stattools.adfuller(df['temperature'], maxlag=None, autola...
<p>So I basically knocked up some dummy data, basically I build a dict for each col to store the adf test results and then construct a df for each result:</p> <pre><code>In [12]: df = pd.DataFrame(index = pd.date_range(start=dt.datetime(2014,1,1), end = dt.datetime(2014,6,1))) import statsmodels.tsa.stattools as ts d...
python|pandas|dataframe
2
369,511
53,798,843
exec name "templet_1h" is not defined
<p>I'm trying to write a code with exec and eval function to read lists of variables from a numpy .npz file.</p> <p>When I ran the code without defining it as a function def, the code worked. However, when I ran the code as a function, i.e. read_file_npz("file_address") , the python 3.7 kept pop up message saying that...
<p>Use <code>exec(evaluate_1, globals())</code> instead to use the global dictionary for global and local variables in <code>exec</code>.</p> <p>The code adds the defined variable to the global dictionary. Adding it as local variable of a function is not possible.</p>
python|numpy|exec|eval
0
369,512
53,681,419
Shift the values in a record by a column.
<p>I have a dataframe, where one of the observations has mismatched columns. Kind of like this : </p> <pre><code> Names Age Dept 0 John 21 sales 1 Joe 22 IT 2 Ann 20 IT 3 24 sales NaN </code></pre> <p>I want to shift the values, to the next column and assign NaN on the first col...
<p>Or use a <code>df[...]=df[...]</code> structure:</p> <pre><code>df[df['Dept'].isnull()]=df[df['Dept'].isnull()].shift(axis=1) </code></pre> <p>And now:</p> <pre><code>print(df) </code></pre> <p>Is:</p> <pre><code> Names Age Dept 0 John 21 sales 1 Joe 22 IT 2 Ann 20 IT 3 NaN 24 sales </co...
python|pandas|dataframe|data-cleaning
1
369,513
53,381,590
Quickest way to map lookup table to pandas column
<p>I have a pandas data frame (<code>DF1</code>), as below:</p> <pre><code>Col1 Col2 A 1 A 5 B 2 C 3 C 4 </code></pre> <p>I would like to map the values to another data frame (<code>DF2</code>), which looks like this:</p> <pre><code>ColX ColY Mon 2 Tues 3 Weds 5 Thurs ...
<p>Using <code>map</code> </p> <pre><code>df2['Colz']=df2.ColY.map(df1.set_index('Col2').Col1) df2 Out[211]: ColX ColY Colz 0 Mon 2 B 1 Tues 3 C 2 Weds 5 A 3 Thurs 4 C 4 Fri 1 A </code></pre>
python|pandas|dataframe
1
369,514
53,686,109
How to build a DataFrame with an indexed dictionary?
<p>I use a DF of numbers (which are Y) with an index of 'Names' and columns of 'Date' and compute a PLS regression on 3 other variables (X) not in the DF. I want to extract the beta 'o' for each names at each dates of this DF, which are computed with a loop indexed on dates. The problem is that there are a lot of miss...
<p>You can try and do it the following way:</p> <pre><code># Create the dataframe df = pd.concat(list(map(pd.DataFrame, o.values()))) # Reindex by Date and Names df = df.set_index(['Date', 'Names']) </code></pre> <p>resulting in</p> <pre><code> Beta Date Names 1995-12-12 Jack 0.2...
python|pandas
0
369,515
53,732,267
converting multi dictionary from json to dataframe
<p>I have the following output I received from using a for loop to parse a JSON i believe. I was wondering how I could convert this output into a Dataframe</p> <pre><code>01E8jn7u387ZHexw2mOo =&gt; {'email': 'a4@yahoo.com ', 'agreed_to_terms': True, 'toy_duration': 2, 'dog_name': 'Oakley', 'dog_breeds': ['Mixed Bree...
<p>looks like a job for json_normalize.</p> <pre><code>import json from pandas.io.json import json_normalize a = {'email': 'a4@yahoo.com ', 'agreed_to_terms': True, 'toy_duration': 2, 'dog_name': 'Oakley', 'dog_breeds': ['Mixed Breed / Mutt'], 'zip': '95355', 'human_name': 'Alina'} df_a = json_normalize(a) </cod...
python|json|pandas
0
369,516
53,766,807
subplots based on records of two different pandas DataFrames ( with same structure) using Seaborn or Matplotlib
<p>I have two DataFrames like below. Both have the same structure (columns names and index) but different values. DataFrame 1 is observed values and DataFrame 2 is predicted. I wanted to draw a single figure using subplots each representing one of the columns, Y- axis to be the values from both dataframes ( two differe...
<p>You can modify below code according to your needs -</p> <pre><code>actual = pd.DataFrame({'a': [5, 8, 9, 6, 7, 2], 'b': [89, 22, 44, 6, 44, 1]}) predicted = pd.DataFrame({'a': [7, 2, 13, 18, 20, 2], 'b': [9, 20, 4, 16, 40, 11]}) # Creating a tidy-dataframe to input und...
python|pandas|matplotlib|seaborn|subplot
1
369,517
53,400,895
How to add a second input argument (the first is an image) to a CNN model built with Keras?
<p>Let's say I have a list of <em>images</em> (converted to numpy arrays) downloaded from Instagram, along with their corresponding <em>likes</em> and user <em>followers</em>. And let's say I have a <strong>CNN model</strong> (using <strong>Keras</strong> on <strong>Tensorflow</strong>) which I train on these images (2...
<p>One approach is to use a two branch model, where one branch processes the image and another branch processes other non-image inputs (such as posts texts or number of followers and followings, etc.). Then you can merge the result of these two branches and possibly add a few other layers afterwards to act a the final ...
python|tensorflow|machine-learning|keras|conv-neural-network
1
369,518
53,677,891
Sort number of observations by category order
<p>I have the following code which produces a Seaborn stripplot and then writes the number of observations below each category. Except the numbers are out of order if I specify a different category order in my stripplot() call.</p> <p>I need help figuring out a way to sort my nobs series so that the numbers matches t...
<p>You want to reindex the <code>nobs</code> series on the category order used for plotting the stripplot.</p> <pre><code>nobs = df.groupby(['Fuel'])['MW'].agg(['count'])['count'].reindex(cat_order) </code></pre> <p><a href="https://i.stack.imgur.com/NM1sH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgu...
python|pandas|seaborn
2
369,519
53,609,697
Keras - what accuracy metric should be used along with sparse_categorical_crossentropy to compile model
<p>When I have 2 classes I used <code>binary_crossentropy</code> as <code>loss</code> value like this to compile a model:</p> <pre><code>model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) </code></pre> <p>But right now I have 5 classes &amp; I'm not using on hot encoded features. So ...
<blockquote> <p><code>sparse_categorical_accuracy</code> is a correct metrics for <code>sparse_categorical_entropy</code>.</p> </blockquote> <p>But why are you using <code>sparse_categorical_entropy</code>? What kind of classes do you have? <code>sparse_categorical_entropy</code> is being used for <strong>Integer<...
python|tensorflow|keras|cross-entropy
2
369,520
53,475,580
PyTorch: get input layer size
<p>I want to programatically find the size of my input layer.</p> <p>If my first layer is called <code>fc1</code>, how do I find out its input?</p>
<p>Assuming your model is called <code>model</code>, this will give the number of input features of the <code>fc1</code> layer:</p> <pre><code>model.fc1.in_features </code></pre> <p>This is useful inside the <code>.forward()</code> method:</p> <pre><code>def forward(self, x): x = x.view(-1, self.fc1.in_features)...
pytorch
4
369,521
53,441,874
Strange plot created based on two numpy arrays and matplotlib
<p>Now I just want to plot a line graph based on two numpy arrays. My x and y are both two (150,1) arrays. After running the following code:</p> <pre><code>plt.plot(x,y) </code></pre> <p>What I get is: <a href="https://i.stack.imgur.com/ZBz35.png" rel="nofollow noreferrer">Line graph based on two numpy arrays</a></p>...
<p>The pairs of <code>x</code> and <code>y</code> represent the points on your graph. With plt.plot() you join the points with a line. If the array <code>x</code> is not in order, what you have is a line that goes back and forward across the graph. To avoid this you should order the <code>x</code> array, and the <code>...
python|numpy|matplotlib
1
369,522
53,761,949
Python tabulate: how to print specific cell content?
<p>I have this code:</p> <pre><code>from tabulate import tabulate import pandas ...
<p>No. Keep in mind that <code>tabulate</code>'s sole purpose is as mentioned in the documentation is to:</p> <blockquote> <p>Pretty-print tabular data in Python</p> </blockquote> <p>Moreover if you run <code>type(nice_table)</code> you'll see that <code>tabulate</code> returns a <code>string</code>. Therefore for ...
python|pandas|tabulate
1
369,523
53,789,336
How do I update value in DataFrame with mask when iterating through rows
<p>With the below code I'm trying to update the column <code>df_test['placed']</code> to = 1 when the if statement is triggered and a prediction is placed. I haven't been able to get this to update correctly though, the code compiles but doesn't update to = 1 for the respective predictions placed.</p> <pre><code>df_te...
<h1>Answering your question</h1> <p><em>Edit: changed suggestion based on comments</em></p> <p>The assignment part of your code, <code>df_test['placed'][mask][j] = 1</code>, uses what is called <a href="https://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy" rel="nofollow noreferrer">cha...
python|pandas|dataframe|mask
3
369,524
53,402,243
Applying io.imread to Dataframe Column
<p>I have a dataframe df with a column 'Poster' full of links to jpeg images. If I apply</p> <pre><code>img_data = io.imread(url) </code></pre> <p>theres is no problem because I'm using an specific url.</p> <p>I want to make something like this:</p> <pre><code>x = np.asarray(io.imread(df['Poster']).tolist()) </code...
<p>Try this:</p> <pre><code>posters = [] for poster in df['Poster']: posters.append(np.asarray(io.imread(poster).tolist())) </code></pre> <p>A fancier way:</p> <pre><code>posters = [np.asarray(io.imread(poster).tolist()) for poster in df['Poster']] </code></pre>
python|pandas|numpy
0
369,525
53,491,293
Linear regression and Estimator returning wrong loses. Tensorflow
<p>I implemented this model using Keras, and the result was as expected. Now im trying with Tensorflow and I just can't get it right. As you can see at bellow my loss is just not right.</p> <p>what am I doing wrong here?</p> <p>ps: I prefer to use estimators instead of multiply tensors and etc.</p> <pre><code>X = nu...
<p>You are missing the number of epochs to train together with a batch size. Add these parameters to your definition of the input functions, e.g., in case of train input for linear regression it may look like this</p> <pre><code>train_input_func = \ tf.estimator.inputs.numpy_input_fn({'X': X_train},\ ...
tensorflow|machine-learning|linear-regression
0
369,526
53,541,157
Extract particular string which appears in multiple lines in cell Pandas
<p>I have to extract string which starts with "Year" and finishes with "\n", but for each line that appears in a cell in Pandas data frame. Additionally, I want to remove \n at the end of cell.</p> <p>This is data frame:</p> <p>df</p> <pre><code> Column1 not_important1\nnot_important2\nE012-855 Year-1972\nE012-85...
<p>You can use <a href="https://docs.python.org/2/library/re.html#re.findall" rel="nofollow noreferrer">findall</a> with this regex <code>r'Year.*?\\n'</code> to catch the substrings. Then create a string from the list of the found elements with <code>''.join</code> and then remove the last <code>\n</code> with <code>[...
python|regex|string|pandas|extract
1
369,527
53,705,582
What is meant by static monolithic build when building tensorflow from source?
<p>While installing tensorflow from source there is an option to configure the build with this command.</p> <pre><code>--config=monolithic —Configuration for a mostly static, monolithic build. </code></pre> <p>What is meant by static monolithic build and how does it affect my tensorflow build if i use it / don't use ...
<p>AFAIK it basically disables the support for adding your own operations to TensorFlow, (like described in <a href="https://www.tensorflow.org/guide/extend/op" rel="noreferrer">https://www.tensorflow.org/guide/extend/op</a>) by removing the dependency to <code>libtensorflow_framework.so</code>. So if you don't want to...
tensorflow
5
369,528
53,568,501
Is there any way to copy all parameters of one Pytorch model to another specially Batch Normalization mean and std?
<p>I have found many correct ways online to copy one pytorch model parameters to another but somehow the copy-paste operation always misses the batch normalization parameters. Everything works fine as long as I only use modules such as conv2d, linear, drop out, max pool etc in my model. But as soon as I add Batch norm...
<p><code>net.load_state_dict(copy_net.state_dict())</code> should work.</p> <p>As per @dxtx, in pytorch's philosophy, the state dict should cover all the states in a 'module', e.g. in batch norm module , the running mean and var, if I remembered correctly, should be part of the state dict. But in fact, if you wrote m...
python|pytorch
3
369,529
53,561,294
Python DB2 SSL connection
<p>I have been running SQL queries (client side) from <strong>DB2</strong> databases using <strong>ibm_db</strong> &amp; <strong>ibm_db_dbi</strong> with pandas. However our company implemented new security standards and I would need a way to secure the connection as well. Running <strong>Python3.7</strong> and <strong...
<p>This is, unfortunately, a little complicated, and (hopefully) your DBA can help with some of this.</p> <p>If you're using a Db2 10.5 Fixpack 5 (or newer) client, then you just need to add a couple of parameters in your DSN string:</p> <pre><code>Security=ssl; SslServerCertificate=/path/to/file.arm; </code></pre> ...
python|pandas|ssl|db2|keystore
1
369,530
53,538,138
Save and load checkpoint pytorch
<p>i make a model and save the configuration as:</p> <pre><code>def checkpoint(state, ep, filename='./Risultati/checkpoint.pth'): if ep == (n_epoch-1): print('Saving state...') torch.save(state,filename) checkpoint({'state_dict':rnn.state_dict()},ep) </code></pre> <p>and then i want load this c...
<p>You need to load <code>rnn.state_dict()</code> stored in the <em>dictionary</em> you loaded:</p> <pre><code>rnn.load_state_dict(state_dict['state_dict']) </code></pre> <p>Look at <a href="https://pytorch.org/docs/stable/nn.html#torch.nn.Module.load_state_dict" rel="nofollow noreferrer"><code>load_state_dict</code>...
python-3.x|pytorch|rnn|checkpointing
0
369,531
53,691,426
how to drop rows by using query
<p>I'm trying to drop rows based on query result but it gives me this error</p> <pre><code> df2.drop(df.query('group == "treatment" and landing_page !="new_page" or group != "treatment" and landing_page =="new_page"'),axis=1) </code></pre> <p>the error shown is</p> <pre><code>ValueError: labels ['user_id' 'timestam...
<p>Use <code>index</code> of <code>query</code> output with <code>axis=0</code> for rows as:</p> <pre><code>df2.drop(df.query('group == "treatment" and landing_page !="new_page" or group != "treatment" and landing_page =="new_page"').index, axis=0) </code></pre>
python|pandas
0
369,532
53,556,092
Numpy obtain dtype per column
<p>I need to obtain the type for each column to properly preprocess it. </p> <p>Currently I do this via the following method:</p> <pre><code>import pandas as pd # input is of type List[List[any]] # but has one type (int, float, str, bool) per column df = pd.DataFrame(input, columns=key_labels) column_types = dict(d...
<p>It would help if you gave a concrete example, but I'll demonstrate with <code>@jpp's</code> list:</p> <pre><code>In [509]: L = [[0.5, True, 'hello'], [1.25, False, 'test']] In [510]: df = pd.DataFrame(L) In [511]: df Out[511]: 0 1 2 0 0.50 True hello 1 1.25 False test In [512]: df.dtypes Ou...
python|pandas|numpy|types|data-science
3
369,533
53,621,241
Bad image quality after resizing/scaling bitmap from IP Camera
<p>I have been working on tensorflow object detection API on Android from quite sometime using the Android Camera2 API and never faced any issue scaling the image to the required 300x300 size for Tensorflow Mobilenet SSD model using the code provided in the tensorflow android sample git repository to resize the image a...
<p>Consider import org.tensorflow.demo.env.ImageUtils;</p> <p>such as <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/examples/android/app/src/main/java/org/tensorflow/demo/CameraActivity.java" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite...
android|tensorflow|tensorflow-lite
-2
369,534
53,416,772
plotting stacked bar graph on column values
<p>I have a Pandas data frame that looks like this:</p> <pre><code>ID Management Administrative 1 1 2 3 2 1 4 3 3 10 1 3 </code></pre> <p>essentially the 1-3 is a grade of low medium or high. I want a stacked bar chart that has Management and ...
<p>You will need to chain several operations: First <code>melt</code> your dataset to move the <code>Department</code> as a new variable, after that you can <code>groupby</code> the <code>Department</code> and the <code>Rating</code> to <code>count</code> the number of IDs that fall into that bucket, then you <code>gro...
python|pandas|bar-chart
1
369,535
53,561,648
Extracting multiple values from a column to a new column in pandas
<p>I have a dataframe <strong>df</strong> having a column name <em>Category</em> and the values inside are <br> <strong>Category</strong> <br> Furniture <br> Technology <br> Office Supply <br> <br> These three values are repeated having total of 1000 values in the column. I want to create a new column name <strong>Cate...
<p>If i underst0od you correctly, you are looking for the total counts of values repeated for each element in the column.</p> <p>Example dataFrame:</p> <pre><code>&gt;&gt;&gt; df Category 0 Furniture 1 Technology 2 Office Supply 3 Furniture 4 Technology 5 Office Supply 6 Furniture 7 ...
python|python-3.x|pandas|dataframe
0
369,536
53,651,111
Serving Multiple TF Models in TF Serving and Creating Appropriate Client Request to Interact with Specific Model as per the Request
<p>Can you please suggest any blog or tutorial which will help in Serving Multiple TF Models in TF Serving and Creating Appropriate Client Request to Interact with Specific Model as per the Request.</p> <p>My Requirement: 1. I have to host multiple models in the tensorflow serving 2. Client request comes for whatever...
<p>What do you mean by "create/modify the client.py file for multiple models in one single client file"?</p> <p>You could specify model name and model version like this </p> <pre><code>request = predict_pb2.PredictRequest() request.model_spec.name = 'model1' request.model_spec.version.value = 1 # Or any other number...
docker|tensorflow|tensorflow-serving|tensor
0
369,537
53,499,263
Compare multiple columns in two dataframes and select rows with differing values
<p>I'm trying to compare 2 columns in one dataframe(df1) with 2 columns in another dataframe(df2). After comparison, I want to select the rows where the first two columns do not match. You can see my attempts below and this what the dataframes look like [<a href="https://i.stack.imgur.com/ZqD1i.png" rel="nofollow noref...
<p>The problem is that df1 and df2 are of different shapes hence the loc will not work. You first need to merge df1 and df2 like</p> <pre><code>df3 = df1.merge(df2,on='common_key',how='left',suffixes=('_df1','_df2')) df3['select'] = 0 df3.loc[(df3['Code_df1'] == df3['Code_df2']) &amp; ...
python|excel|pandas|dataframe|conditional-formatting
0
369,538
53,630,502
Tensorflow with Pycharm : inacurrate rise of tensorflow.python.framework.errors_impl.InternalError: cudaGetDevice() failed
<h1>Context</h1> <p>After installing Tensorflow-GPU and all its requirements (namely CUDA and cuDNN), I try to run Tensorflow <strong>with GPU support</strong> under Pycharm.</p> <h1>Problem</h1> <p>When I run a simple program under Pycharm, session.run <strong>rises an exception</strong>.</p> <h3>Exception</h3> <...
<p>The problem actually came from a stupid mixing up of conda environments. I was running another conda environment with a similar name on Pycharm but with a different Tensorflow install (from conda, not pip).</p> <p>Putting back the correct conda env did the job.</p>
python|tensorflow|pycharm
0
369,539
53,387,122
Counting frequency of values by date using pandas - Part II
<p>I have dataset (dataset1) that looks as follows:</p> <pre><code>Date Company Weekday 2015-01-01 Company1 Monday 2015-01-02 Company1 Tuesday 2015-01-03 Company1 Wednesday 2015-01-04 Company1 Thursday 2015-12-09 Company2 Monday 2015-12-10 Company2 Tuesday ………………………………………...
<p>Working with <code>Series</code>, so need:</p> <pre><code>dataset2 = dataset1.groupby(['Company','Weekday']).size().sort_values(ascending=False) dataset2 = dataset2[dataset2 &gt; 50] </code></pre> <p>Another solution is add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.reset_index.ht...
python|pandas
3
369,540
53,486,607
Pandas group like values together and sum
<p>Have a dataframe which looks like the following:</p> <pre><code>Index Quarter Average Location 0 2000Q1 1234 London 1 2000Q1 5678 Brighton ... ... ... ... 99 2018Q3 9876 London 100 2018Q3 9987 Brighton </code></pre> <p>To ...
<p>This code should work for you:</p> <pre><code>df.groupby('Quarter').agg('sum') </code></pre>
python|pandas|pandas-groupby
1
369,541
53,706,923
several charts in one csv python pandas
<p>First of all let me thank you for your great help here. I am a silent follower of many items and they held me much to get better in python pandas.</p> <p>To my question: I do have a csv file including several information:</p> <p><a href="https://i.stack.imgur.com/f08Vu.png" rel="nofollow noreferrer"><img src="http...
<p>After long searching and try and error process, I found the solution, at least a working solution for me.</p> <p>For those who might have the same issue: it helps focus on the region you are interested and load these regions into panda. For example I am interesed in the region beginning from row=10 to row=20, then ...
python|pandas
1
369,542
53,484,055
Iterate pandas.DataFrame efficiently while accessing more than one index row at a time
<p>I already read answers and blog entries about how to iterate pandas.DataFrame efficient (<a href="https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6" rel="nofollow noreferrer">https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html" rel="nofollow noreferrer"><code>pd.DataFrame.shift</code></a> to add shifted series to your dataframe, then feed into your function via <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataF...
python|pandas|performance|loops|dataframe
2
369,543
53,614,617
Equivalent code and classical approach of roll "shifting function" into loop
<p>I have a basic loop (actually time loop where values of an array are updated ) :</p> <pre><code>for i in range(1,nt): #Using roll u = u - cfl/2*(roll(u,-1)- roll(u,1)) # Update time t = t+dt </code></pre> <p>With this loop and <code>roll</code> function, simulation is working fine.</p> <p>I precise t...
<p>Two equivalent functions:</p> <pre><code>nt=7 nx=10 cfl=1.1 def old(u0,cfl=-cfl): u=u0.copy() for i in range(1,nt): utemp1=u[0] - cfl/2*(u[nx-1] - u[1]) utemp2=u[nx-1] - cfl/2*(u[nx-2] - u[0]) u[1:nx-1] = u[1:nx-1] - cfl/2*(u[0:nx-2] - u[2:nx]) u[0] = utemp1 u[nx-1] =...
python|arrays|numpy
0
369,544
53,707,288
Performance of various sparse matrix products using scipy
<p>I have a term document matrix as a sparse matrix (either a csr or coo matrix), and a feature vector for which I want to do similarity comparisons. I have the following methods I want to try:</p> <p>1.) with the doc matrix as a csr matrix, turn it into an ndarray and then iterate over the rows and do a cosine simila...
<p>You don't need to cast your sparse matrix as a dense numpy array, you can use its <code>.dot()</code> attribute: <code>term_doc.dot(feat_vec)</code></p> <p><code>sparse.linalg</code> is useful to compute the row-wise norm without casting to an array: </p> <pre><code>from scipy import sparse sparse.linalg.norm(term...
python|numpy|performance-testing|sparse-matrix
0
369,545
53,602,620
Missing required dependencies ['numpy'] in AWS Lambda function
<p>I guess many people have come across the same issue. I have tried to find every possible blog and try every method. I have reached this point and stuck here.</p> <p>I am using Serverless framework and virtualenv.</p> <p>serverless.yml:</p> <pre><code> service: test-pandas provider: name: aws runtime: pytho...
<p>I used Docker to package and deploy the Lambda function with the libraries.</p> <p>Add the following in serverless.yml:</p> <pre><code>custom: pythonRequirements: dockerizePip: non-linux </code></pre> <p>Make sure Docker is running on your machine and deploy it using serverless commands. Another thing I not...
pandas|python-2.7|numpy|aws-lambda
2
369,546
53,716,596
pandas groupby count and proportion of group total
<p>I'm trying to do the following with pandas. Counting item by state then expressing that number as a percentage of the subtotal. My dataframe has the raw data. I can get the counts but how to append another column for the percentages?</p> <pre><code>state_grp = df.groupby(by=['date', 'state','ad_type']) state_grp.ad...
<p>You can do with <code>transform</code> + <code>sum</code> </p> <pre><code>state_grp = df.groupby(by=['date', 'state','ad_type']) state_grp=state_grp.ad_type.agg(['count']) state_grp['%']=state_grp['count']/state_grp.groupby(level=[0,1])['count'].transform('sum') </code></pre>
python|sql|pandas
1
369,547
53,571,021
Pandas time series count an event till specific date
<p>I'm a pandas beginner and I'm using tennis data from <a href="https://www.kaggle.com/jordangoblet/atp-tour-20002016" rel="nofollow noreferrer">https://www.kaggle.com/jordangoblet/atp-tour-20002016</a> so a data sample will be like this</p> <pre><code>ATP Location Tournament Date Series Court Su...
<p>Try slicing your dataframe based on the date variable of the events. Then you can use the <code>groupby</code> function on an auxiliary column. To get the auxiliary column:</p> <pre><code>df['aux'] = df.apply(lambda x: '_'.join(sorted([x['Winner'], x['Loser']])), axis = 1) </code></pre> <p>After grouping it, you c...
python-3.x|pandas|pandas-groupby
0
369,548
53,576,915
sample n zeros from a sparse.coo_matrix
<p>How do I (efficiently) sample zero values from a scipy.sparse.coo_matrix?</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from scipy.sparse import coo_matrix &gt;&gt;&gt; # create sparse array &gt;&gt;&gt; X = np.array([[1., 0.], [2., 1.], [0., 0.]]) &gt;&gt;&gt; X_sparse = coo_matrix(X) &gt;&gt;&gt; ...
<p>Since you know the shape of <code>X</code>, you could use <code>np.random.choice</code> to generate random <code>(row, col)</code> locations in <code>X</code>:</p> <pre><code>h, w = X.shape rows = np.random.choice(h, size=n) cols = np.random.choice(w, size=n) </code></pre> <p>The main difficulty is how to check if...
python|numpy|scipy|sparse-matrix
3
369,549
53,688,322
Picking out certain indexes from a pandas data frame
<p>I have a pandas data frame with hundreds of entries and an array of random entries in the array. For example: </p> <pre><code>import pandas as pd list1 = [13,2,32,34,15,7,19] list2 = [15,65,95,9,90,88,10] df1 = pd.DataFrame(list1) df2 = pd.DataFrame(list2) cols = [df1, df2] df1.loc[:, cols] </code></pre> <p>and...
<pre><code>import pandas as pd list1 = [13,2,32,34,15,7,19] df1 = pd.DataFrame(list1) M =[1, 2, 5, 6] df1[df1.index.isin(M)] </code></pre> <p>Note that in your problem statement, <code>cols</code> is a list of dataframes, not a two-column dataframe. I am not sure if that was not clear from your code and question.</...
python|pandas
0
369,550
53,443,684
group by pandas removes duplicates
<p>I have a dataframe (df)</p> <pre><code>a b c 1 2 20 1 2 15 2 4 30 3 2 20 3 2 15 </code></pre> <p>and I want to recognize only max values from column c </p> <p>I tried </p> <pre><code>a = df.loc[df.groupby('b')['c'].idxmax()] </code></pre> <p>but it group by remo...
<p>I think you need:</p> <pre><code>df = df[df['c'] == df.groupby('b')['c'].transform('max')] print (df) a b c 0 1 2 20 2 2 4 30 3 3 2 20 </code></pre> <p>Difference in changed data:</p> <pre><code>print (df) a b c 0 1 2 30 1 1 2 30 2 1 2 15 3 2 4 30 4 3 2 20 5 3 2 15 #only 1...
python|pandas|dataframe
2
369,551
53,358,689
Object dtype dtype('O') has no native HDF5 equivalent
<p>Well, it seems like a couple of similar questions were asked here in stack overflow, but none of them seem like answered correctly or properly, nor they described the exact examples.</p> <p>I have a problem with saving array or list into hdf5 ...</p> <p>I have a several files contains list of (n, 35) dimensions, w...
<p>I was running into a similar issue with <code>h5py</code>, and changing the type of the NumPy array using <code>array.astype</code> worked for me (I believe this changes the type from <code>dtype('O')</code> to the data type you specify). Please see the code snippet below:</p> <pre><code>import numpy as np print(X...
numpy|hdf5
8
369,552
53,611,862
Predicting and Training in different threads Keras Tensorflow
<p>I am using Keras and Tensorflow to make a kind-of online learning, where I receive new data periodically and I retrain my models with this new data. I can have several models stored in ".h5" files so that when i need to train or predict I load the model and then I perform the necessary operations.</p> <p>Currently ...
<p>Easiest solution is to have two separate keras models - the first runs in inference mode, and the second runs in training mode. Every time the inference model gets a new dataset to predict on, it first checks to see if it has the most "up to date" <code>.h5</code> file, if not then it loads it in first then runs the...
python|multithreading|tensorflow|keras
1
369,553
53,441,938
Trying to install tensorflow 1.12.0 in an Anaconda 3 virtual python environment
<p>Trying to install tensorflow on a virtual environment (<code>Anaconda 3</code> and <code>Python 3.6</code>) on a Windows 10 computer.</p> <p>After installing Anaconda, I go to the Anaconda prompt and key in the Following:</p> <pre><code>conda create -n tensorflow_cpu pip python=3.6 activate tensorflow_cpu pip instal...
<pre><code>conda create -n tensorflow==1.12.0 conda activate tensorflow==1.12.0 </code></pre> <p>Try theses lines in anaconda prompt</p>
python|tensorflow|anaconda
0
369,554
53,687,204
Check one-on-one relationship between two columns
<p>I have two columns A and B in a pandas dataframe, where values are repeated multiple times. For a unique value in A, B is expected to have "another" unique value too. And each unique value of A has a corresponding unique value in B (See example below in the form of two lists). But since each value in each column is ...
<p>Consider you have some dataframe:</p> <pre><code> d = df({'A': [1, 3, 1, 2, 1, 3, 2], 'B': [4, 6, 4, 5, 4, 6, 5]}) </code></pre> <p><code>d</code> has <code>groupby</code> method, which returns <a href="https://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow noreferrer"><code>GroupBy</code> object...
python|pandas|dataframe
1
369,555
53,438,193
Quadratic n term equation using multiindex
<p>I have two DFs which I would like to use to calculate the following:</p> <pre><code>w(ti,ti)*a(ti)^2 + w(tj,tj)*b(sj,tj)^2 + 2*w(si,tj)*a(ti)*b(tj) </code></pre> <p>The above uses two terms (a,b). w is the weight df where i and j are index and column spaces pertaining to the Tn index of a and b.</p> <p><strong>Se...
<p>One way could be first <code>reindex</code> your dataframe <code>df1</code> with all the possible combinations of the lists <code>I</code>, <code>Q</code> and <code>Tn</code> with <code>pd.MultiIndex.from_product</code>, filling the missing value in the column 'V' with 0. The column has then <code>len(I)*len(Q)*len(...
python|numpy|dataframe|multi-index|quadratic
1
369,556
53,719,606
matplotlib marker type order not consistent after each run?
<p>Without changing any code, the graph plotted will be different. Correct at the first run in a fresh bash, disordered in the next runs. (maybe it can cycle back to correct order)</p> <p>To be specific: Environment: MacOS Mojave 10.14.2, python3.7.1 installed through homebrew.<br> To do: Plot <code>scatter</code> for...
<p>Since your code is incomplete it is difficult to say for sure, but it seems that the order of markers is being messed up by the <code>cycle</code> iterator. Why don't you just try:</p> <pre><code>markerTypes = ['o', 's', '^'] strainLegends = [] for strain, markerType in zip(strains, markerTypes): strainSamples...
python|pandas|matplotlib
1
369,557
53,600,294
Replace groups that have size > 1 with the mean in pandas dataframe
<p>So I want to groupby certain columns and for each group that has size bigger than 1 take the mean in the rest of the columns (if all values are nan then this should be nan if not I want the nans dropped in the mean calculation, which is the default behaviour). Then I want the extra rows dropped. The code below does ...
<p>The mean of one value is the value itself, so unless I'm missing something there's no need to make a distinction by group size.</p> <p>Consider</p> <pre><code>&gt;&gt;&gt; df group value value2 dummy 0 1 NaN 100 63 1 2 NaN 101 63 2 2 12.0 102 63 3 2 14.0 ...
python|python-3.x|pandas|pandas-groupby
1
369,558
53,362,971
Plus or minus an array by an array and store in a dictionary
<p>I have done a ton of preprocessing and math on this data to arrive at two equally sized 3xN numpy arrays. A and B. </p> <p>A = integers that have been classified as labels to predict B. B = time series data.</p> <p>I also have C which is just B[1:] </p> <p>A and B are equal at their respective time steps and I ca...
<p>Just to give an example, if I understand what you are looking for:</p> <pre><code>a = [2,3,4] b = [5,2,1] c = set(b[1:]) sums = set([ aa + bb for aa in a for bb in b ]) subs1 = [ (aa - bb) for aa in a for bb in b if (aa - bb) &gt; 0] subs2 = [ bb - aa for bb in b for aa in a if (bb - aa) &gt; 0] subs = set(subs1 +...
python|pandas|numpy|data-science|preprocessor
0
369,559
53,400,752
Generalize a formula for an entire list of lists
<p>I want to do this</p> <pre><code>firstdates = dates[0] paystring = [] for i in range(len(payment_months)): if payment_months[i] &lt; firstdates[i]: paystring.append(0) else: paystring.append(((payment_months[i] + 12 - firstdates[i]) + 1) % 12) print(paystring) </code></pre> <p>But I want to...
<p>After fiddling around with it for a bit, it eventually become apparent you're using the wrong index for your <code>payment_months</code> and are iterating over the wrong <code>range</code> if you want each row in <code>dates</code>.</p> <p>Setup:</p> <pre><code>In [35]: dates Out[35]: [[8, 8, 7, 7, 6, 5, 4, 4, 11...
python|list|numpy|matrix
0
369,560
17,496,331
Python 3 code to read CSV file, manipulate then create new file....works, but looking for improvements
<p>This is my first ever post here. I am trying to learn a bit of Python. Using Python 3 and numpy. </p> <p>Did a few tutorials then decided to dive in and try a little project I might find useful at work as thats a good way to learn for me. </p> <p>I have written a program that reads in data from a CSV file which ha...
<p>You can greatly simplify your code using more of <code>numpy</code> capabilities.</p> <pre><code>A = np.loadtxt('stack.txt',skiprows=2,delimiter=',',dtype=str) keep_headers=np.loadtxt('keepheader.csv',delimiter=',',dtype=str) headers = A[0,:] cols_to_keep = np.in1d( headers, keep_headers ) B = np.float_(A[1:,cols...
csv|numpy|python-3.x
1
369,561
17,544,649
Pandas fillna with list/array
<p>Is there a convenient way of filling na values with (the first) values of an array or column?</p> <p>Imagine the following DataFrame:</p> <pre><code>dfcolors = pd.DataFrame({'Colors': ['Blue', 'Red', np.nan, 'Green', np.nan, np.nan, 'Brown']}) Colors 0 Blue 1 Red 2 NaN 3 Green 4 NaN 5 NaN 6 Brow...
<p>This is rather awful, but iterating over the index of the nulls works:</p> <pre><code>In [11]: nulls = dfcolors[pd.isnull(dfcolors['Colors'])] In [12]: for i, ni in enumerate(nulls.index[:len(dfalt)]): dfcolors['Colors'].loc[ni] = dfalt['Alt'].iloc[i] In [13]: dfcolors Out[13]: Colors 0 Blue 1 ...
python|pandas
3
369,562
17,454,116
iterating over numpy arrays
<p>I am having a very difficult time vectoring, I can't seem to think about math in that way yet. I have this right now:</p> <pre><code>#!/usr/bin/env python import numpy as np import math grid = np.zeros((2,2)) aList = np.arange(1,5).reshape(2,2) i,j = np.indices((2,2)) iArray = (i - aList[:,0:1]) jArray = (j -...
<p>With a little help from broadcasting, I get this, with data based on your last example:</p> <pre><code>import numpy as np grid = np.zeros((3, 3)) aList = np.array([[2, 0], [2, 2]]) important_rows, important_cols = aList.T rows, cols = np.indices(grid.shape) dist = np.sqrt((important_rows - rows.ravel()[:, None]...
python|numpy|multidimensional-array
3
369,563
17,662,768
h5py selective read in
<p>I have a problem regarding a selective read-in routine while using h5py.</p> <pre><code>f = h5py.File('file.hdf5','r') data = f['Data'] </code></pre> <p>I have several positive values in the 'Data'- dataset and also some placeholders with -9999. How I can get only all positive values for calculations like <code>np...
<p>You could use:</p> <pre><code>mask = f['Data'] &gt;= 0 data = f['Data'][mask] </code></pre> <p>although I am not sure how much memory the mask calculation itself uses.</p>
numpy|hdf5|h5py
1
369,564
17,256,294
pandas dataframe - remove values from a group with less than X rows
<p>I need to calculate a std mean from a time series (monthly frequence), but i also need to exclude from the calculation the "incomplete" Years (with less then 12 moths)</p> <p>Numpy/scipy "working" version :</p> <pre><code>import numpy as np import scipy.stats as sts url='http://www.cpc.ncep.noaa.gov/data/indices/...
<p>i found this way :</p> <pre><code>import pandas as pd url='http://www.cpc.ncep.noaa.gov/data/indices/sstoi.indices' ts_raw = pd.read_table(url, sep=' ', header=0, skiprows=0, parse_dates = [['YR', 'MON']], ...
python|numpy|scipy|pandas
0
369,565
17,534,624
Getting list of numpy.random distributions
<p>How can I get a get a list of the available <code>numpy.random</code> distributions as described <a href="https://numpy.org/doc/stable/reference/random/generator.html#distributions" rel="nofollow noreferrer">in the docs</a>?</p> <p>I'm writing a command-line utility which creates noise. I'd like to grab each availab...
<p>Just as they did in <a href="http://docs.scipy.org/doc/numpy/_sources/reference/routines.random.txt" rel="nofollow">the documentation</a>, you must list them manually. It is the only way to be sure you won't get undesirable functions that will be added in future versions of numpy. If you don't care about future addi...
python|numpy|random
2
369,566
17,591,104
In pandas, can I deeply copy a DataFrame including its index and column?
<p>First, I create a DataFrame</p> <pre><code>In [61]: import pandas as pd In [62]: df = pd.DataFrame([[1], [2], [3]]) </code></pre> <p>Then, I deeply copy it by <code>copy</code></p> <pre><code>In [63]: df2 = df.copy(deep=True) </code></pre> <p>Now the <code>DataFrame</code> are different.</p> <pre><code>In [64]:...
<p>Latest version of Pandas does not have this issue anymore</p> <pre><code> import pandas as pd df = pd.DataFrame([[1], [2], [3]]) df2 = df.copy(deep=True) id(df), id(df2) Out[3]: (136575472, 127792400) id(df.index), id(df2.index) Out[4]: (145820144, 127657008) </code></pre>
python|pandas
26
369,567
20,293,099
Scipy GMRES Iteration Taking Longer than Expected Time
<p>I am trying to invert a dense matrix of size 50,000 + rows. I have been slowly trying to work to getting the SciPy GMRES operation to work. It seems to be taking an inordinate amount of time for one iteration. I am entering the following information:</p> <pre><code>x_gm = scipy.sparse.linalg.gmres(A,b,tol=1e-08,max...
<p><code>maxiter</code> controls the number of <em>restart cycles</em>, not dot products. The bound for dot products is <code>restart*maxiter</code>, where <code>restart</code> has the default value of 20. Indeed, <code>20*50 s = 1000 s</code>, so the time is indeed dominated by matrix-vector products.</p> <p>You coul...
python|numpy|matrix|scipy
2
369,568
20,055,493
Numpy: convert an array to a triangular matrix
<p>I was looking for a built in method to convert an linear array to triangular matrix. As I failed in find one I am asking for help in implementing one.</p> <p>Imagine an array like: </p> <pre><code>In [203]: dm Out[203]: array([ 0.80487805, 0.90243902, 0.85365854, ..., 0.95121951, 0.90243902, ...
<pre><code>&gt;&gt;&gt; tri = np.zeros((67, 67)) &gt;&gt;&gt; tri[np.triu_indices(67, 1)] = dm </code></pre> <p>See <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.triu_indices.html" rel="noreferrer">doc for <code>triu_indices</code></a> for details. To get a lower-triangular matrix, use <code>np.tr...
python|numpy|linear-algebra
34
369,569
19,934,542
calculate mean using numpy ndarray
<p>The text file look like:</p> <pre><code>david weight_2005 50 david weight_2012 60 david height_2005 150 david height_2012 160 mark weight_2005 90 mark weight_2012 85 mark height_2005 160 mark height_2012 170 </code></pre> <p>How to calculate mean of weight and height for david and mark as follows:</p> <pre><code>...
<p>The <code>mean</code> function is for computing the average of an array of numbers. You will need to come up with a way to select the values of <code>c3</code> by applying a condition to <code>c2</code>.</p> <p>What would probably suit your needs better would be splitting up the data into a hierarchical structure,...
python|python-2.7|python-3.x|numpy
5
369,570
20,277,358
Sort pandas dataframe both on values of a column and index?
<p>Is it feasible to sort pandas dataframe by values of a column, but also by index?</p> <p>If you sort a pandas dataframe by values of a column, you can get the resultant dataframe sorted by the column, but unfortunately, you see the order of your dataframe's index messy within the same value of a sorted column.</p> ...
<p><strong>Pandas 0.23</strong> finally gets you there :-D</p> <p>You can now pass index names (and not only column names) as parameters to <code>sort_values</code>. So, this one-liner works:</p> <pre><code>df = df.sort_values(by = ['MyCol', 'MyIdx'], ascending = [False, True]) </code></pre> <p>And if your index is ...
python|pandas|sorting|dataframe
91
369,571
20,193,835
Parse dates when year month day and hour are in separate columns using pandas in python
<p>After reading <a href="https://stackoverflow.com/questions/11615504/parse-dates-when-yyyymmdd-and-hh-are-in-separate-columns-using-pandas-in-python">Parse dates when YYYYMMDD and HH are in separate columns using pandas in Python</a> and <a href="https://stackoverflow.com/questions/12269528/using-python-pandas-to-pa...
<p>If the regular methods dont work you can always fallback on writing your own parser. Make a function which accepts the columns from <code>parse_dates</code> and returns a <code>datetime</code> and add that functions with <code>date_parser</code>.</p> <p>So something like:</p> <pre><code>df = pd.read_csv(file, head...
python|date|csv|pandas|timestamp
11
369,572
20,036,663
Understanding NumPy's Convolve
<p>When calculating a simple moving average, <code>numpy.convolve</code> appears to do the job.</p> <p><strong>Question:</strong> How is the calculation done when you use <code>np.convolve(values, weights, 'valid')</code>? </p> <p>When the docs mentioned <code>convolution product is only given for points where the si...
<p>Convolution is a mathematical operator primarily used in signal processing. Numpy simply uses this signal processing nomenclature to define it, hence the "signal" references. An array in numpy is a signal. The convolution of two signals is defined as the integral of the first signal, <strong>reversed</strong>, sweep...
python|python-2.7|numpy|convolution|moving-average
182
369,573
19,957,192
Substituting values in a numpy masked array
<p>I'm trying to substitute some values in a <code>numpy</code> <code>masked array</code>, but my mask is being dropped:</p> <pre><code>import numpy as np a = np.ma.array([1, 2, 3, -1, 5], mask=[0, 0, 0, 1, 0]) a[a &lt; 2] = 999 </code></pre> <p>The result is:</p> <pre><code>masked_array(data = [999 2 3 999 5], mas...
<p>I think you are not doing the substitution correctly, try this:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.ma.array([1, 2, 3, -1, 5], mask=[0, 0, 0, 1, 0]) &gt;&gt;&gt; a.data[a &lt; 2] = 999 &gt;&gt;&gt; a masked_array(data = [999 2 3 -- 5], mask = [False False False True False],...
python|numpy
4
369,574
20,109,845
Iteratively concatenate pandas dataframe with multiindex
<p>I am iteratively processing a couple of "groups" and I would like to add them together to a dataframe with every group being identified by a 2nd level index.</p> <p>This:</p> <pre><code>print pd.concat([df1, df2, df3], keys=["A", "B", "C"]) </code></pre> <p>was suggested to me - but it doesn't play well with iter...
<p>Should be able just make <code>data_all</code> a list and concatenate once at the end:</p> <pre><code>data_all = [] for a in a_list: group = some.function(a, etc) group = group.set_index(['CoI'], append=True, drop=True) group = group.reorder_levels(['CoI','oldindex']) data_all.append(group) data_al...
python|loops|pandas|dataframe|multi-index
7
369,575
20,275,934
Plot Dates in MatPlotLib using a scatter data set
<p>I have a large data set. I am getting an array where I get </p> <pre><code>arDates = DataSet["dates"].Values </code></pre> <p>The array should appear like that. </p> <pre><code>arDates = [u'2013-11-27T02:02:50' u'2013-11-27T00:00:00' u'2013-11-27T00:00:00' u'2013-11-27T00:00:00'] </code></pre> <p>I am working...
<p>Maybe this is what you mean:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt arDates = pd.Series(pd.DatetimeIndex([u'2013-11-27T02:02:50', u'2013-11-25T00:00:00', u'2013-11-25T00:00:00', u'2013-11-25T00:00:00']).dayofyear) arDates.hist() plt.show() print np.histogram(arDat...
python|r|numpy|matplotlib
0
369,576
6,397,495
Unmap of NumPy memmap
<p>I can't find any documentation on how numpy handles <strong>unmapping</strong> of previously memory mapped regions: <code>munmap</code> for <code>numpy.memmap()</code> and <code>numpy.load(mmap_mode)</code>.</p> <p>My guess is it's done only at garbage collection time, is that correct?</p>
<p>Yes, it's only closed when the object is garbage-collected; <code>memmap.close</code> method does nothing.</p> <p>You can call <code>x._mmap.close()</code>, but keep in mind that any further access to the <code>x</code> object will crash python.</p>
python|numpy|mmap
16
369,577
7,011,591
Recode missing data Numpy
<p>I am reading in census data using the matplotlib cvs2rec function - works fine gives me a nice ndarray. </p> <p>But there are several columns where all the values are '"none"" with dtype |04. This is cuasing problems when I lode into Atpy "TypeError: object of NoneType has no len()". Something like '9999' or other ...
<p>Here is a solution to this problem, although if your data is a record array you should only apply this operation to your column, rather than the whole array:</p> <pre><code>import numpy as np # initialise some data with None in it a = np.array([1, 2, 3, None]) a = np.where(a == np.array(None), 9999, a) </code></pre...
python|arrays|numpy|missing-data
3
369,578
6,800,534
numpy array access
<p>I need to create a numpy array of N elements, but I want to access the array with an offset Noff, i.e. the first element should be at Noff and not at 0. In C this is simple to do with some simple pointer arithmetic, i.e. I malloc the array and then define a pointer and shift it appropriately.</p> <p>Furthermore, I ...
<p>I would be very cautious about over-riding the <code>[]</code> operator through the <code>__getitem__()</code> method. Although it will be fine with your own code, I can easily imagine that when the array gets passed to an arbitrary library function, you could get problems. </p> <p>For example, if the function expl...
python|numpy
2
369,579
6,620,471
Fitting empirical distribution to theoretical ones with Scipy (Python)?
<p><strong>INTRODUCTION</strong>: I have a list of more than 30,000 integer values ranging from 0 to 47, inclusive, e.g.<code>[0,0,0,0,..,1,1,1,1,...,2,2,2,2,...,47,47,47,...]</code> sampled from some continuous distribution. The values in the list are not necessarily in order, but order doesn't matter for this problem...
<h1>Distribution Fitting with Sum of Square Error (SSE)</h1> <p>This is an update and modification to <a href="https://stackoverflow.com/a/16651955/2087463">Saullo's answer</a>, that uses the full list of the current <a href="http://docs.scipy.org/doc/scipy/reference/stats.html" rel="noreferrer"><code>scipy.stats</code...
python|numpy|statistics|scipy|distribution
292
369,580
15,641,449
concatenate dataframes with different levels of index in pandas
<p>I am having troubles understanding how pandas multiindex work. Specifically: </p> <ol> <li>how to merge two dataframes of different index level (by row)</li> <li>how can change index level for a dataframe</li> </ol> <p>Using an example from a <a href="https://stackoverflow.com/questions/15589354/">previous questi...
<p>As @DSM pointed it out the DataFrame objects need to be in a list</p> <pre><code>pd.concat([t1, t2]) </code></pre> <p>I do have to perform calculations similar to yours. This is my preferred method</p> <pre><code>t2['Exam'] = 'tot' All Part Pass Exam ExamenYear 2007 3 2 2 tot 2008 ...
pandas|multi-index
3
369,581
12,202,845
python/numpy: problems with numpy linal.eig
<p>I just found this very strange behaviour of the numpy linalg.eig algorithm.</p> <p>If run </p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.array([[1., 0., 0., 0., 0., 0., 0., 0.], ... [0., -1., -0.5, 0., -0.5, 0., 0., 0.], ... [0., -0.5, 0., 0., 0., 0., 0., 0.], ... [0., 0., 0., 0., 0., 0., -0...
<p>All the results shown here are correct.</p> <p>Because your matrix has two 2D subspaces with eigenvalues = -1.366 and 0.366. And for the 2D subspace you can select different linear combinations of linear independent eigenvectors. </p>
python|numpy|linear-algebra
1
369,582
12,137,018
How to explicitly specify the output's string length in numpy.vectorize
<p>I am trying to use numpy.vectorize to convert some integers to strings. But, it seems the output string is always limited to a maximum of 8 characters.</p> <pre><code>In [1]: import numpy as np In [2]: str = "abcdefghijklmnopqrstuvwxyz" In [3]: def num_str(num): ...: return str[:num] ...: In [4]: np.v...
<p>It appears to be a known bug in Numpy: <a href="http://projects.scipy.org/numpy/ticket/1892" rel="nofollow">http://projects.scipy.org/numpy/ticket/1892</a></p> <p>Your workaround looks good. You might want to ask on the Numpy mailing list or comment on the bug ticket. It seems there's been no recent action toward...
python|numpy
1
369,583
12,389,033
Mask an array by value then mask the corresponding Matrix
<p>I have a numpy array y [1,2,3,4,5,6,1,2,3,4,5,6]</p> <p>Then I have a matrix X that is numpy csr format. </p> <p>1) I need to mask element 6 in y. Then, I need to mask the corresponding row in X.</p> <p>So, y.shape is 12. Should be 10. The X is 12,20. Should be 10,20.</p> <p>How do I do this in numpy</p>
<p>I don't like answering my own questions but the proper solution is this for dealing with a csr matrix:</p> <pre><code>X = X[np.where(y != 6)[0]] y = y[y != 6] </code></pre>
python|numpy
1
369,584
12,091,967
How to get one series within a multilevel index in python pandas
<p>I have a data frame 'df' which has a multilevel index ('STK_ID','RPT_Date'):</p> <pre><code> sales cogs net_pft STK_ID RPT_Date 600809 20120331 2214010000 509940000 492532000 20111231 4488150000 1077190000 780547000 20110930 3563660000 85078900...
<p>I fixed it.</p> <pre><code>df.index.get_level_values('RPT_Date') array([20120331, 20111231, 20110930, 20110630, 20110331, 20101231, 20100930, 20100630, 20100331, 20091231, 20090930, 20090630, 20090331, 20081231, 20080930, 20080630, 20080331, 20071231, 20070930, 20070630, 20070331, 20061231, 20...
python|pandas
2
369,585
12,144,887
How to concatenate data from multiple netCDF files with Python
<p>I have some netCDF files, 24 for each of the directions (<code>x</code>, <code>y</code>, <code>z</code>) and 24 with values for different times. At the final point I have to plot the data for all time steps.</p> <p>For the plotting I need to interpolate at specific point so I have to knew the nearest neighbor. My p...
<p>Numpy is generally much more convenient if you know <em>a priori</em> the shape of the arrays you'll be working with. Things like appending to arrays suffer a performance penalty. I agree with Sebastian, that the easiest way (if possible) is to create an array large enough to hold everything (worst case scenario). I...
python|arrays|numpy|append|netcdf
2
369,586
12,128,646
Multiplying polynomials with numpy.convolve return wrong result
<p>I'm trying to multiply two polynomials using the <code>numpy.convolve</code> function. I thought that this would be really easy, but I found out that it does not always return the correct product.</p> <p>The implementation of multiplication is quite simple:</p> <pre><code>def __mul__(self, other): new = ModPol...
<p>NumPy is a library that implements fast operation on arrays of <a href="http://docs.scipy.org/doc/numpy/user/basics.types.html" rel="nofollow"><em>fixed-size numeric data types</em></a>. It does not implement arbitrary precision arithmetic. So what you are seeing here is integer overflow: NumPy is representing your ...
python|numpy|polynomial-math|multiplication
4
369,587
12,424,824
How I can i conditionally change the values in a numpy array taking into account nan numbers?
<p>My array is a 2D matrix and it has numpy.nan values besides negative and positive values: </p> <pre><code>&gt;&gt;&gt; array array([[ nan, nan, nan, ..., -0.04891211, nan, nan], [ nan, nan, nan, ..., nan, nan, nan], ...
<p>The fact that you have <code>np.nan</code> in your array should not matter. Just use fancy indexing:</p> <pre><code>x[x&gt;0] = new_value_for_pos x[x&lt;0] = new_value_for_neg </code></pre> <p>If you want to replace your <code>np.nans</code>:</p> <pre><code>x[np.isnan(x)] = something_not_nan </code></pre> <p>Mor...
python|open-source|numpy|statistics|gdal
46
369,588
72,040,520
Pandas : Adding list of columns to a new columns in a dataframe
<p>A part Of my dataframe is columns of some medications like this:</p> <pre><code>Atenolol 50 mg Atorvastatin Azathioprine 50 mg 1 0 0 1 0 0 0 0 1 0 1 0 0 0 1 1 0 0 0 1 1 0 1 0 </code></pre> <p>I want to create a new column <code>Drugs</code>, that include name of used medications, ...
<p>Use:</p> <pre><code>df['Drugs'] = df.dot(df.columns + ', ').str.strip(', ') </code></pre>
python|pandas|dataframe
0
369,589
71,859,215
How to compare the column values of two Dataframs and assign the value of a third column in Python
<p>I have two different Dataframes, a long dataframe (df1) and a short dataframe (df2). Both data frames contain the columns A and B:</p> <pre><code>Data1 = {'A': [2,2,2,1,2,1,1,2], 'B': [1,2,1,2,1,1,1,2]} Data2 ={'A': [1,1,2,2],'B': [1,2,1,2],'X': [9,5,7,3]} df1 = pd.DataFrame(Data1) df2 = pd.DataFrame(Data2) print(...
<p>Just merge the two on A and B. I've added <code>how='left'</code> to join on the index of df1 (if this is removed, it still works but returns the new df sorted differently).</p> <pre><code>df1.merge(df2, on=['A', 'B'], how='left') </code></pre> <p>Output:</p> <pre><code> A B X 0 2 1 7 1 2 2 3 2 2 1 7 3 ...
python|pandas|dataframe
1
369,590
71,957,418
Is there a setting or way to have pandas warn or alert when doing operations with dataframes that are not the same size?
<p>The following snippet is an example of an operation I would like an alert or warning for. Not sure if there is some methodology or setting in pandas to avoid situations like this.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame([1,2,3,4,5,-6,-8,-9],columns=['nums']) np.sign(df) * df[df['nums'...
<p>I think I misunderstood how pandas handles situations like this. <code>np.sign(df)</code> has the full index <code>RangeIndex(start=0, stop=8, step=1)</code>, but <code>df[df['nums'] &gt; 0]</code> has a smaller index <code>Int64Index([0, 1, 2, 3, 4], dtype='int64')</code>. The indices are used to decide what to mul...
python|pandas|dataframe
0
369,591
71,978,549
How to calculate the average R square of the company data
<p><a href="https://i.stack.imgur.com/VNKpD.png" rel="nofollow noreferrer">STOCK RETURN </a></p> <p>I don't know how to compute the average r squared with individual stock return and market return</p> <pre><code>import numpy as np import pandas as pd from sklearn import datasets, linear_model from sklearn.linear_model ...
<p>Formula of R squared: <code>1-unexplained_variation/total_variation</code></p> <p><code>Unexplained variation</code> is the sum of difference for each datapoint between the prediction using the line of best fit and the actual values. You can compute the coefficients of the line of best fit with <code>numpy.polyfit()...
python|pandas|dataframe
0
369,592
72,081,111
Model weights from sess.run(() is returning the value in bytes. How can I change to value?
<p>I'm trying to extract the model weights from a saved model in a <code>.pb</code>file. However, when I run sess it returns the model weights in bytes and I cannot read it. My code follows:</p> <pre><code>constant_values = {} with tf.compat.v1.Session(graph=tf.Graph()) as sess: meta_graph = tf.compat.v1.saved_mode...
<p>Are you sure that the constant variables with model weights in your graph are named 'Const'?</p> <p>If you just copied this code from a tutorial on how to get the model weights elsewhere - as I have seen in the past - try the following:</p> <p>Instead of <code>constant_ops = [op for op in sess.graph.get_operations()...
tensorflow|protocol-buffers|tensorflow2.0|tf.keras
1
369,593
72,002,175
For loop to extract rows and ffill into another dataframe
<p>I have a list containing user ids.</p> <pre><code>userids_with_missingdata = ['1234','1236','1238'] </code></pre> <p>I also have the first dataframe (df1) containing many user_ids</p> <pre><code>user_id age weight height 1234 20 60kg 170cm 1235 21 70kg 160cm 1236 56 80kg 172cm 1...
<p>You can try <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.update.html" rel="nofollow noreferrer"><code>pandas.Series.update</code></a></p> <pre class="lang-py prettyprint-override"><code>df1.set_index('user_id')['age'].update(df2.set_index('user_id')['age']) </code></pre> <p>Notice <code>update...
python|pandas|dataframe
1
369,594
71,896,869
No module found Keras
<p>As per code , when i tried to install keras it is telling already present, next line telling No module found keras.</p> <p>code line 1:</p> <pre><code>!pip install keras </code></pre> <p>result :</p> <pre><code>Defaulting to user installation because normal site-packages is not writeable Requirement already satisfie...
<p>The module might not be on your <code>PATH</code>, which determines which modules can be accessed. To add it, run:</p> <pre><code>export PATH=&quot;/usr/local/lib/python3.8/dist-packages:$PATH&quot; </code></pre> <p>in your terminal. This command sets the <code>PATH</code> variable to the directory which <code>keras...
python|tensorflow|keras
0
369,595
71,940,846
How to calculate timestamp difference in sequence python
<p>my DF looks like this:</p> <pre><code>0 2021-01-01 01:00:00+ 00:00 1 2021-01-01 01:05:00+ 00:00 2 2021-01-01 01:10:00+ 00:00 3 2021-01-01 01:15:00+ 00:00 4 2021-01-04 06:00:00+ 00:00 5 2021-01-04 06:05:00+ 00:00 </code></pre> <p>This column is a timestamp. I want to calculate a duration of each period (w...
<p>IIUC, you could use a custom group and <code>agg</code>:</p> <pre><code># ensure datetime if string df['timestamp'] = pd.to_datetime(df['timestamp'], format='%Y-%m-%d %H:%M:%S+ 00:00') # compute a custom group for consecutive values within 5min group = df['timestamp'].diff().gt('5min').cumsum() # aggregate out = (...
python|pandas|timestamp
1
369,596
71,992,834
'method' object is not subscriptable erroor
<p>i write this code in vscode :</p> <pre><code>from fileinput import filename import imp import cv2,time,os,tensorflow as tf import numpy as np from tensorflow.python.keras.utils.data_utils import get_file np.random.seed(123) class Detector: def __init__(self) -&gt; None: pass def readClaassees(se...
<p>I think its because you forgot the brackets in this line</p> <pre><code>classScores = detections['detection_scores'][0].numpy </code></pre> <p>I think it should be:</p> <pre><code>classScores = detections['detection_scores'][0].numpy() </code></pre> <p>When you call it without the brackets you are calling a method o...
python|tensorflow
1
369,597
71,829,593
CNN model accuracy fluctuates
<p>Tensorflow/Keras</p> <p>I have developed a CNN model to classify images as circle, triangle or square. However, my accuracy values have wide fluctuations. Is it something to do with my data preprocessing?</p> <p>This is my code for data preprocessing:</p> <p>Edit: I am using this folder <a href="https://i.stack.imgu...
<p>It is easy, I am trying to generate those inputs but my work also indicates shapes-sensitive categories such as Galaxy games. Your models do not need anything special excepts matching on target responsive and layers. ( You see when training of the good response from model training )</p> <p><strong>[ Sample ]:</stron...
python|tensorflow|keras|deep-learning|conv-neural-network
0
369,598
71,897,905
How can i remove the denominator of all the Fractions
<p>I used NumPy and Fractions module to find the answers to a given system of equations. But I want to convert all the answers to integers by dividing through by the highest denominator. How do I do that when I don't even know the values.</p> <pre><code>import numpy from fractions import Fraction a=[[3,4,1], [2,3,...
<p>The minimal number that a set of numbers divides is called the <a href="https://en.wikipedia.org/wiki/Least_common_multiple" rel="nofollow noreferrer">least common multiple</a>. Python unfortunately doesn't provide this function out of the box, but we can calculate it from <code>gcd</code> (which Python <em>does</em...
python|numpy|matrix|fractions|linear-equation
1
369,599
72,063,752
PySpark: how to performs conditional calculation on each element of a long string
<p>I have a dataframe that looks like this:</p> <pre><code>+--------+-------------------------------------+-----------+ | Worker | Schedule | Overtime | +--------+-------------------------------------+-----------+ | 1 | 23344--23344--23344--23344--23344-- | 3 | +--------+-------...
<p>The shortest way (and probably the best performance) is using Spark SQL <a href="https://spark.apache.org/docs/latest/api/sql/index.html#transform" rel="nofollow noreferrer"><code>transform</code></a>, which will loop through an array of your schedule, and perform the comparison element-wise. Even though, the code w...
pyspark|apache-spark-sql|pyspark-pandas
0