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,400
65,728,185
Python - Split DataFrame to make training set
<p>I have a DataFrame that looks something like this called &quot;sales_csv&quot;:</p> <pre><code> id TV radio newspaper sales invested_amount successful_campaign 0 1 230.1 37.8 69.2 22.1 15.253394 False 1 2 44.5 39.3 45.1 10.4 12.394231 ...
<p>X is all columns but sales. And y = df['sales'].copy()</p> <p>only then you split X and y with train_split</p> <p>but before that you need to labelencode your successful_campaign column - SKLEARN library have plenty of examples of above.</p>
python|pandas|dataframe|training-data
0
369,401
65,516,199
exporting html data in json format
<p>Consider this simple example</p> <pre><code>import pandas as pd import numpy as np import requests from bs4 import BeautifulSoup df = pd.DataFrame({'link' : ['https://en.wikipedia.org/wiki/World%27s_funniest_joke', 'https://en.wikipedia.org/wiki/The_Funniest_Joke_in_the_World']}) def p...
<p>Looks like pandas doesn't know how to properly handle character escaping in this instance in json. If you don't need to use pandas you can do something like:</p> <pre class="lang-py prettyprint-override"><code>import json import requests def write_json(data, path: str, indent: int = 4): with open(path, 'w') as...
python|json|pandas
1
369,402
65,753,245
Error when downloading zip file TensorFlow Keras
<p>I have been following this tutorial on machine translation by tensorflow: <a href="https://www.tensorflow.org/tutorials/text/nmt_with_attention" rel="nofollow noreferrer">Neural machine translation with attention</a></p> <p>I wanted to use the same code on a <a href="http://www.manythings.org/anki/jpn-eng.zip" rel="...
<p>From comments</p> <blockquote> <p>It seems the website <a href="http://www.manythings.org" rel="nofollow noreferrer">www.manythings.org</a> reject the request of tf.keras.utils.get_file probably due to HTTP request head info is not satisfy minimum info, you can work around it by download the file first (e.g !wget <a...
python|tensorflow|tensorflow2.0|tf.keras|machine-translation
0
369,403
65,671,626
Selecting first row of each index in multi indexing pandas DataFrame
<p>choose every first row of each index of multiindexing pandas dataframe.</p> <pre class="lang-py prettyprint-override"><code>grouped = ecommerce[[&quot;category_id&quot;, &quot;brand&quot;, &quot;price&quot;]].groupby(by=[&quot;category_id&quot;, &quot;brand&quot;]).mean() grouped_sort = grouped.sort_values(by=[&quot...
<p>The following code can help:</p> <pre class="lang-py prettyprint-override"><code>gsgb = grouped_sort.copy() gsgb = gsgb.groupby(level=0) print(type(gsgb)) gsgb.head() for cat, df in gsgb: display(df.sort_values(by=[&quot;price&quot;], ascending=False).reset_index().iloc[0]) </code></pre> <p><strong>Working:</st...
python|pandas|data-analysis
0
369,404
65,577,881
Color Specific Headers in Pandas DataFrame
<p>I want to set background color of specific headers in dataframe</p> <p>Here is the Original Dataframe:</p> <p><img src="https://i.stack.imgur.com/No5Rn.png" alt="1" /></p> <p>and here is what i want:</p> <p><img src="https://i.stack.imgur.com/HuESz.png" alt="1" /></p> <p>I have tried this code so far, but it doesn't...
<p>This should help you!</p> <pre><code>import xlwings as xw df1.to_excel(&quot;file.xlsx&quot;,index=False,header=False) wb = xw.Book(&quot;file.xlsx&quot;) # color is set with an rgb value wb.sheets['Sheet 1'].range('A').color = (169,169,169) </code></pre> <p>This basically writes to excel ad then changes the forma...
python|pandas|dataframe
0
369,405
65,546,359
How to use the "new line" command when converting a list into a dataframe?
<p>I'm converting a string into a DataFrame, but when reading as csv, and then a list, the string iterates each letter as a new row in the DataFrame. How can I code where a new row should begin?</p> <p>'overs' variable is a string:</p> <pre><code>BASKETBALL - NBA SPREAD MONEY TOTAL ... </code></pre> <p>The following c...
<p>You can use <code>pd.read_csv</code> and use <code>header=None</code> so that it won't make the first value a column:</p> <pre><code>df = pd.read_csv('overs.txt', header=None) print(df) </code></pre>
python|pandas|list|csv|iterable
1
369,406
65,686,513
How to use tf.dynamic_partition and tf.dynamic_stitch with multiple dimensions and a change in shape?
<h1>Goal</h1> <p>My goal is to perform an expensive operation on a masked subset of elements and represent the remaining elements with zero. I'll start out with an example where I use sum in place of the expensive operation:</p> <pre class="lang-py prettyprint-override"><code># shape: (3,3,2) in = [ [ [ 1, 2 ], [ 2, 3 ...
<p>I eventually found an answer after learning that you don't actually need the indices for the zero values. The intermixed zeros are implied and you just need to pad some onto the end for the final batch.</p> <p>This is messy but it works. <strong>Please feel free to offer suggestions on how this could be better.</str...
python|tensorflow|keras|tensorflow2.0|tf.keras
0
369,407
65,909,353
how to update a parameter (i.e. dropout rate or units) at each epoch within a keras model
<p>I am trying to add another parameter to Keras's implementation of deep learning architecture which changes at each or after a number of epochs.</p> <p>Assume in new architecture (CNN, RNN, etc.), a parameter 'alpha1' is added, and I want to initialize it with a value for example 16,</p> <p>Now, at the time of traini...
<p>I think to can make a list of values for N epochs, then for each epoch you multiply by the values from the list (since you can easily count which epoch you are):</p> <pre><code>alpha = alpha * somevalue[epoch_i] </code></pre>
python|tensorflow|keras|model
0
369,408
65,608,036
How do i remove a a huge number of columns in a dataframe based on their number?
<p>I have a dataframe which has 60 columns. The names of the columns are years and are named 1960.0, 1961.0......2010.0. I want to remove the columns from 1960 to 2006. This is what i have tried so far:</p> <pre><code> a = list(map(str,map(float,range(1960,2006)))) gdp = gdp.drop(a,axis=1) gdp </code></pr...
<p>I think you need to remove floats, not strings, so removed converted to strings:</p> <pre><code> a = list(map(float,range(1960,2006))) #or #a = list(range(1960,2006)) gdp = gdp.drop(a,axis=1) </code></pre> <p>Or:</p> <pre><code> gdp = gdp[:, ~gdp.columns.isin(a)] </code></pre>
pandas|dataframe
0
369,409
65,851,888
How do I calculate a "rolling" statistic on this pandas table, but with the time-window centered on the datapoint?
<p>Suppose I have the following pandas table:</p> <pre><code>import pandas as pd import math l = [['f8196bb6d34a9f44e950e30f15e1a2ab_6862', 1605148870, 51.98157826, 5.85744811], ['f8196bb6d34a9f44e950e30f15e1a2ab_6862', 1605141900, 51.98157842, 5.85744476], ['f8196bb6d34a9f44e950e30f15e1a2ab_6862', 1605145244, 51.98157...
<p>Indeed centered rolling with datetime does not seem possible. One work around is to do two <code>rolling</code> with half of the window you want and the second rolling being on the reverse data with <code>[::-1]</code>, then substract the value of the row as it has been counted twice. With the provided data, it is h...
pandas
0
369,410
65,887,411
Calculating source frequency in Python
<p>I'm new to python; I was looking for calculating the source frequency. I have files(sources are in tokens) and I want to find words that are shown in all sources to calculate. For example, the word 'beautiful' in which sources are shown, the result the word 'beautiful' is in 5 sources. I already have the python code...
<p>As mentioned you need to escape the <code>'</code> character. The way to escape it is putting <code>'\'</code>. Like <code>doen\'t</code></p> <pre class="lang-py prettyprint-override"><code>from os import listdir with open(&quot;C:/Users/elle/Desktop/Archivess/test/rez.txt&quot;, &quot;w&quot;) as f: for filena...
python|pandas|xcode|file|frequency
0
369,411
65,492,566
find index of certain value in 3 dimension array in parallel way
<p>I made a <code>zero_mask2</code> function (copied below) in the middle of my pytorch file. However, it is too slow. So, I'm looking for a better way.</p> <p>First, Let me explain the gist of the function below.</p> <h2>Input</h2> <ul> <li><p><code>all_idx_before'</code> (dimension of <code>[batch_size, number of poi...
<p>You can compare and use <code>argmax</code>:</p> <pre class="lang-py prettyprint-override"><code>tmp = all_idx_before[..., None, :] == idx[..., None] # compare along additional last dimension mask = torch.argmax(tmp, dim=-1) </code></pre>
python|numpy|indexing|pytorch
0
369,412
65,728,964
How to apply a function to a dataframe row based on a condition and values of another row?
<p>If I have a pandas dataframe such as:</p> <pre><code>a b c 1 2 3 1 2 -3 2 3 2 4 2 -1 </code></pre> <p>How do change the values of column b based on if the values in c are positive or negative, and use the values in b and a in the operation.</p> <p>I want to run something like this on each row:</...
<p>You could use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer">numpy.where</a> which is similar to <code>if/else</code> and is usually faster:</p> <pre><code> df.assign(b=np.where(df.c.ge(0), df.a - df.b, df.b - df.a)) a b c 0 1 -1 3 1 1 1 -...
python|pandas|dataframe|if-statement|iteration
0
369,413
65,741,172
Add a column according to other columns in a matrix. [python]
<p>I got a matrix of the form:</p> <pre><code> 1.0 2.0 3.0 4.0 1 0 0 0 1 2 0 0 1 0 3 1 0 0 0 4 0 1 0 0 5 1 0 0 0 6 0 0 0 0 7 1 0 0 0 </code></pre> <p>I want to add another column in the matrix where its value will ...
<p>Lets try something different. we can take sun acriss axis 1 and convert to <code>np.sign</code> then subtract that result with 1 which converts 0 to 1 and 1 to 0.</p> <pre><code>df['5.0'] = 1-np.sign(df.sum(1)) </code></pre> <p>Or with <code>df.any(axis=1)</code></p> <pre><code>df['5.0'] = 1-df.any(1) </code></pre> ...
python|pandas|dataframe|matrix|multiple-columns
2
369,414
65,581,458
Numpy: assemble three 1D arrays into 3D (but not exactly a simple coordinate grid)
<p>I have three 1D arrays, where two are the same length but the third is a different length, e.g.</p> <pre><code>A = np.array([1, 2, 3, 4]) B = np.array([10, 20, 30, 40]) C = np.array([100, 200, 300, 400, 500]) </code></pre> <p>I want to combine them into a grid as follows:</p> <pre><code>D = np.array([[[1, 10, 100], ...
<p>Let's call the lengths of <code>A</code>, <code>B</code>, <code>C</code> <code>a</code>, <code>b</code>, <code>c</code>, respectively. You are looking for an output array of shape <code>(a, c, 3)</code> (or <code>(b, c, 3)</code>). Stacking <code>A</code> and <code>B</code> correctly gives you an array of shape <cod...
python|numpy
4
369,415
65,577,371
Pandas(Python) : How to fill empty cells with previous row value with conditions
<p>For order dataset where Customer name (<strong>Name</strong>) per order are not repeated and some order does not have customer name. Example :</p> <p><a href="https://i.stack.imgur.com/e0wD3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e0wD3.png" alt="enter image description here" /></a></p> <p...
<p>You have to use groupby and then fill. If you want to apply the fill operation only on the &quot;Name&quot; column, it should look like this:</p> <pre><code>import pandas as pd import numpy as np data = {&quot;order_id&quot;: [1,1,2,3], &quot;name&quot;:[&quot;adam&quot;, np.nan, np.nan, &quot;Su&quot;],&quot;total&...
python|python-3.x|pandas
1
369,416
65,813,614
Need to speed up the operations on numpy arrays in python
<p>I am solving an integer programming model by importing Cplex as a library in Python. Let's say the optimization problem has a constraint in the following form <code>(Ax = b)</code>: <code>x0+x1+x1+x3 = 1</code></p> <p>The indices of the x variables in this constraint are 0,1,1, and 3. These are stored in a list: <co...
<p>Without going for native-code based extensions, there are probably always compromises:</p> <ul> <li><p>Numpy / Vectorization approaches miss hash-based algorithmics and imho will suffer from algorithmic-complexity drawbacks (e.g. a need to sort; need to do multiple passes ...)</p> </li> <li><p>Python-based hash-base...
python|performance|numpy|cplex|integer-programming
1
369,417
65,492,248
Machine Learning model performs worse on test data than validation data
<p>I am quite new to machine learning.</p> <p>To start things, I wanted to train a model to classify pictures of cats and dogs.</p> <p>The problem I have is that when I train my model, it gives me a (approximately) 80-85% accuracy on the training data and the validation data. The loss is quite low with about 0.4 - 0.5 ...
<p>I believe your problem results from the fact that for the validation data and the training data you have</p> <pre><code>train_batches = ImageDataGenerator(preprocessing_function=tf.keras.applications.vgg16.preprocess_input, rescale=1/255, ..... </code></pre> <p>The vgg16.preprocess_input function rescales the pixel ...
python|tensorflow
0
369,418
65,848,178
Pandas dataframe only reading first value, NaN for everything else
<p>I am attempting to read a csv with pandas and then insert into a SQL table. I am reading the data from the csv correctly when I print(data), but once I add it into the dataframe it is only reading the very first column, and is inserting NaN for every other value in the csv. Code and output below;</p> <pre><code>data...
<p>The problem is the way you're doing the <code>df</code>. You're creating the dataframe first with your <code>data</code>. Then you're trying to create another dataframe of it, using names that don't exist. To fix your problem simply do this:</p> <pre><code>&gt;&gt;&gt; col_names = ['Date','EECode','LastName','FirstN...
python|sql|pandas
3
369,419
65,854,606
pip3 cannot install .whl files on raspberry pi: File is not a zip file
<p>can anyone help me please i am trying to install tensorflow 2.3.0 on my raspberry pi 3 (Buster) i have python 3.7.3 and pip 20.3.3 when i try to install my .whl file i get the following:</p> <pre><code>~ $ sudo -H pip3 install tensorflow-2.3.0-cp37-none-linux_armv7l.whl Looking in indexes: https://pypi.org/simple, h...
<p>It turns out the wheel file was not downloaded and saved properly due to the slow internet connection. It is working now. If you want to know whether it was downloaded and saved properly or not, change the extension to .zip and open it. If it doesn't open this means that your wheel file is corrupted.</p>
python|tensorflow|pip
1
369,420
65,773,757
How do i keep my loop from repeating my random values?
<p>So i was learning how to handle probabilities and how to plot them in Python. I came across a problem where i needed to find the probability of the sum of 2 dices being &gt; 7 or odd. I know the result is around 75% but it was translating that to Python that i had a problem with. My code to solve the problem is some...
<p>Generating random values from 1 to 6 won't work. Assume that you are tossing a coin 10 times. theoretically you should get 5 heads and 5 tails. But that does not happens in real life because of sampling error. When you generate random values, there is always some sampling error.</p> <pre><code>import random import n...
python|numpy|random|probability|dice
0
369,421
65,793,451
numpy append with more than two arrays
<p>I know there are similar questions out there but i cant find the informations I'm looking for. I have a list of numpy arrays which i want to append to each other in order to form a feature matrix.</p> <p>I'm able to get the desired result like so:</p> <pre><code>a = [1,2,3] b = [4,5,6] c = [7,8,9] d = [10,11,12] new...
<p>If you have <code>value = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]</code> simply calling <code>np.array(value)</code> will do what you want.</p>
python|arrays|numpy|append|concatenation
0
369,422
65,717,962
pandas DataFrame re-order cells for each group
<p>I have a dataframe of groups of 3s like:</p> <pre><code>group value1 value2 value3 1 A1 A2 A3 1 B1 B2 B3 1 C1 C2 C3 2 D1 D2 D3 2 E1 E2 E3 2 F1 F2 F3 ... </code></pre> <p>I'd like to re-order the cells wi...
<p>Here is a proposal which uses numpy indexing with reshaping on each group.</p> <p><strong>Setup:</strong></p> <p>Lets assume your original df and the position dataframes are as below:</p> <pre><code>d = {'group': [1, 1, 1, 2, 2, 2], 'value1': ['A1', 'B1', 'C1', 'D1', 'E1', 'F1'], 'value2': ['A2', 'B2', 'C2', 'D2',...
python|pandas|dataframe|position
2
369,423
21,260,521
How to deal with this Pandas error related to dataframe.sort?
<p>A dataframe 'df' :</p> <pre><code>&gt;&gt;&gt; df = ACEV(get_SW_code('sdht', sw_cls=3))[['PB','PE','EV_EBITDA','PEG','ROIC','mg_r','opr_pft_r','net_pft_r','sales_gr','net_pft_r','Ttl_mkv']] &gt;&gt;&gt; print df PB PE EV_EBITDA PEG ROIC mg_r opr_pft_r net_pft_r sales_gr ...
<p>The error message is a little confusing with all the <code>BlockManager</code>/<code>_ref_locs</code> stuff, but it seems to be because you're selecting duplicate columns (<code>net_pft_r</code>):</p> <pre><code>df = ACEV(get_SW_code('sdht', sw_cls=3))[['PB','PE','EV_EBITDA','PEG','ROIC', 'mg_r','opr_pft_r','net_pf...
python|pandas
2
369,424
21,114,265
saving large array as csv with different fomat
<p>I have a numpy array which is of the size of 1000x1000. I want to save it as a CSV which can be done using: </p> <pre><code>numpy.savetxt('file.csv', array, delimiter = ',', fmt = '%d') </code></pre> <p>How can I save this array with only column 1 being <code>int32</code> and rest in <code>float</code>?</p>
<p>The <code>fmt</code> parameter allows that:</p> <pre class="lang-none prettyprint-override"><code>fmt : str or sequence of strs, optional A single format (%10.5f), a sequence of formats, or a multi-format string, e.g. 'Iteration %d -- %10.5f', in which case `delimiter` is ignored. For complex `X`, the l...
python|numpy
1
369,425
21,233,043
Non-sobel discrete gradients in python-Opencv or numpy
<p>I'd like to compute the discrete X and Y gradient arrays of a 2-d numpy image array according to the following masks:</p> <pre><code>import numpy as np mx = np.array([[-1, 0, 1]]) my = np.array([[-1, 0, 1]]).T </code></pre> <p>I've looked in opencv documentation and didn't find anything other than Sobel operators ...
<p>Got it, simply use <code>cv2.filter2D</code> like this:</p> <pre><code>import numpy as np import cv2 mx = np.array([[-1, 0, 1]]) my = np.array([[-1, 0, 1]]).T im = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8], [5, 6, 7, 8, ...
python|opencv|numpy
5
369,426
20,975,600
Pandas spreadsheet like tabular
<p>consider the following dataframe:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({ 'split_1':[1,2,2,2,1,2,2,2,1,1], 'split_2':[3,3,3,4,4,4,4,3,3,3], 'var_1':[1,2,4,3,2,4,2,2,1,2], 'var_2':[4,2,2,2,1,5,4,3,4,3], }) </code></pre> <p>What I want to achive is a tabular similar...
<p>This may be a tad cleaner:</p> <pre><code>In [15]: grp = df.groupby(['split_1','split_2']) In [16]: grp.agg([np.mean, np.median, np.max, np.min, np.size]).stack(0) Out[16]: mean median amax amin size split_1 split_2 1 3 var_1 1....
python|pandas
4
369,427
20,999,758
PyShp - getting Python to recognise points from a polyline
<p>I'm rather new to Python, so I suspect this problem I'm having arises from naivety, but any help would be appreciated.</p> <p>Currently I have a small coastal evolution model. Initially this randomly generates 100 points along a defined x-axis within some constraints, using NumPy. Relevant part of the code is this:...
<p>The error is because you're you're trying to make a (potentially) several thousand dimensional array with <code>Bch_Width = np.random.uniform(0, 30, BeachShp1)</code>, etc. </p> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html" rel="nofollow"><code>numpy.random.uniform</cod...
python|numpy|shapefile|polyline
2
369,428
2,716,237
Bitwise Operations on Rows of lil_matrix
<p>How can I quickly extract two rows of a scipy.sparse.lil_matrix and apply bitwise operations on them? I've tried:</p> <pre><code>np.bitwise_and(A[1,:], A[2,:]) </code></pre> <p>but NumPy seems to want an array type according to the documentation.</p>
<p>By "lil_matrix", do you mean a scipy.sparse.lil_matrix? If so, you'll have to convert your sparse array to a normal dense array to do bitwise operations on it, I believe.</p> <pre><code>a = np.asarray(A.todense()) np.bitwise_and(a[1,:], a[2,:]) </code></pre> <p>Should do the trick, I think...</p> <p>EDIT: Forgot...
python|numpy|scipy
3
369,429
63,705,192
Tensorflow Lite benchmark app explanation
<p>I'm using the <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/tools/benchmark#parameters" rel="nofollow noreferrer">Tensorflow Lite Benchmark Android application</a> to test my model on Android devices. An example of the output is the following:</p> <blockquote> <p>Average inference tim...
<p><strong>Init</strong>: The time it takes to load the model and build the interpreter object, which is the initialization step that needs to happen at the beginning (i.e., one-time cost)</p> <p><strong>Warmup</strong>: The average inference time it took for the warmup runs at the beginning, according to the <code>war...
tensorflow|benchmarking|tensorflow-lite
0
369,430
63,675,654
How can I grab the date from the top of this csv?
<p><a href="https://i.stack.imgur.com/BrnG1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BrnG1.png" alt="enter image description here" /></a></p> <p>Hi! I have this csv I'm trying to grab the date from using pandas. the date is located above the header in the picture above. I thought I could just ...
<p>To get a value at a certain cell in a dataframe, you need to use <code>iat</code> rather than <code>row</code>. Also, if you want that date, you want the 3rd column not the 3rd row.</p> <pre class="lang-py prettyprint-override"><code>datetime_df = pd.read_csv(holdings_file) print(datetime_df.iat[0,3]) </code></pre>
python|pandas
0
369,431
63,543,236
Why is the output of torch.lstsq drastically different than np.linalg.lstsq?
<p>Pytorch provides a <code>lstsq</code> function, but the result it returns drastically differs from the numpy's version. Here is an example input and both of their results:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import torch a = torch.tensor([[1., 1, 1], [2, 3, 4], ...
<p><code>torch.lstq(a, b)</code> solves <strong>minX L2∥bX−a∥</strong> while <code>np.linalg.lstsq(a, b)</code> solves <strong>minX L2∥aX−b∥</strong></p> <p>So change the order of parameters passed.</p> <p>Here's a sample:</p> <p>import numpy as np import torch</p> <pre><code>a = torch.tensor([[1., 1, 1], ...
python|numpy|pytorch|torch
2
369,432
63,485,303
"Steps per sample" in DGM-Network
<p>I am currently working with the Deep Galerkin Method and have looked at the code on the following Github account: <a href="https://github.com/adolfocorreia/DGM" rel="nofollow noreferrer">https://github.com/adolfocorreia/DGM</a>. In his application of the Merton model <a href="https://github.com/adolfocorreia/DGM/blo...
<p>The sampling_stages correspond to the number of times you want to pick new samples and the steps_per_sample is the number of times you want to send each sample into the model. That's exactly what the second loop do, it run multiple time the same sample.</p> <p>I assume that's a way to get faster result if sampling n...
python|tensorflow|deep-learning
0
369,433
63,467,441
Python dataframe manupulation
<p>I am trying` to convert the below input dataframe to the output dataframe</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd data = {'Model1': [86,23,32,13,45,12], 'Model2': [96,98,34,12,22,19], 'Model3': [56,23,44,12,32,33] } Input = pd.DataFrame(data, ...
<p>You can use <code>idxmax</code> and <code>lookup</code>:</p> <pre><code>idx = Input.idxmax(1) output = pd.DataFrame({'Best Model':idx, 'Best Acc':Input.lookup(Input.index, idx) }) </code></pre> <p>Output:</p> <pre><code> Best Model Best Acc I1 Model2 96 I2 ...
python|pandas|numpy|dataframe|sklearn-pandas
2
369,434
63,497,766
numpy vectorized operation for a large array
<p>I am trying to do some computations for a numpy array by python3.</p> <p>the array:</p> <pre><code> c0 c1 c2 c3 r0 1 5 2 7 r1 3 9 4 6 r2 8 2 1 3 </code></pre> <p>Here the &quot;cx&quot; and &quot;rx&quot; are column and row names.</p> <p>I need to compute the difference of each element by row if the eleme...
<p>Extract the values from the array first and then do subtraction:</p> <pre><code>import numpy as np a = np.array([[1, 5, 2, 7], [3, 9, 4, 6], [8, 2, 1, 3]]) cols = [0,2,1] # create the index for advanced indexing idx = np.arange(len(a)), cols # extract values vals = a[idx] # subtract array by the value...
python|arrays|numpy|vectorization
2
369,435
63,389,942
Measure the cpu usage/execution time for tesorflow in python
<p>I want to compare two tensorflow programs, my assumption is that one of program will have lower cpu usage. I am not so sure whether I should use time.clock() or time.time(). I currently uses python2.</p> <pre><code>start = time.time() for _ in range(100): sess.run(main.op) end = time.time() print((end - start)/10...
<p>You can use <a href="https://psutil.readthedocs.io/en/latest/" rel="nofollow noreferrer">psutil</a> to get the cpu usage, memory usage, disk usage etc. from python. It's really simple. Here is an example.</p> <pre><code>import psutil print(psutil.cpu_percent()) # for cpu usage print(psutil.cpu_freq()) # for cpu fre...
python|performance|tensorflow
0
369,436
63,641,982
Avoiding plotting ODEs divergent solutions ODEint
<p>I'm trying to plot a phase plane and I want it to look nice. However, some solutions of the system of equations diverge because of the initial conditions. Is there some way that I can make a try/except chain in order when the solution diverges it doesn't plot it. Here is my code:</p> <pre><code>import matplotlib.pyp...
<p>This can be solved by avoiding the wrong divergences at all, so that there is no need for exception handling.</p> <p>This is a discontinuous ODE which can lead to unusual effects like a sliding mode. One way to quickly work around that is to mollify the jump by implementing a blending zone where the vector field cha...
python|numpy|visualization|ode
0
369,437
63,681,084
how to extract rows of dataframe from user input
<pre><code>data = {'Sample':['S1', 'S1', 'S1' ,'S1' ,'S2' ,'S2' ,'S3' ,'S3', 'S4', 'Negative', 'Positive', 'Negative', 'S1', 'S1', 'S1' ,'S2' ,'S2' ,'S2' ,'S3' ,'S4', 'S4', 'Positive', 'Positive', 'Negative'], 'Location':['A1', 'A2', 'A3' ,'A4' ,'A5' ,'A6' ,'A7' ,'A8', 'A9', 'A10', 'A11', 'A12'...
<p>Just chain your conditions and use <code>to_dict(&quot;list&quot;)</code>:</p> <pre><code>print (df.loc[df[&quot;Sample&quot;].eq(&quot;Negative&quot;)&amp;df[&quot;Location&quot;].str.contains(&quot;A&quot;)].to_dict(&quot;list&quot;)) #{'Sample': ['Negative', 'Negative'], 'Location': ['A10', 'A12'], 'Repeat Numbe...
python|pandas
3
369,438
63,692,792
TF-Hub Elmo uses which word embedding to concatenate with characters in Highway layer
<p>I understand that Elmo uses CNN over characters for character embeddings. However I do not understand how the character embeddings are concatenated with word embeddings in the Highway network. In the Elmo paper most of the evaluations use Glove for word embeddings and CNN character embedding together which make sens...
<p>Concatenation happens inside the <a href="https://tfhub.dev/google/elmo/3" rel="nofollow noreferrer">https://tfhub.dev/google/elmo/3</a> model. When using <code>word_emb</code> output, one can get the embedding for each token in the input. The embedding can be used for classification or other modeling tasks similar ...
tensorflow|tensorflow-hub|elmo
1
369,439
63,449,236
Correct way of passing dataframe to ray
<p>I am trying to do the simplest thing with Ray, but no matter what I do it just never releases memory and fails.</p> <p>The usage case is simply read parquet files to DF -&gt; pass to pool of actors -&gt; make changes to DF -&gt; return DF</p> <pre><code>class Main_func: def calculate(self,data): #do some th...
<p>Does each task needs to preserve state among different files? Ray has tasks abstraction that should simplify things:</p> <pre class="lang-py prettyprint-override"><code>import ray ray.init() @ray.remote def read_and_write(path): df = pd.read_parquet(path) ... do things df.to_parquet(&quot;./temp/...&qu...
pandas|ray
1
369,440
63,647,103
merging pandas dataframes with respect to a function output
<p>Is there a convenient way to merge two dataframes with respect to the distance between rows? For the following example, I want to get the color for df1 rows from the closest df2 rows. The distance should be computed as <code>((x1-x2)**0.5+(y1-y2)**0.5)**0.5</code>.</p> <pre class="lang-py prettyprint-override"><code...
<pre><code># function to compare one row of df1 with every row of df2 # note the use of abs() here, square root of negative numbers would be complex number, # so the result of the computation would be NaN. abs() helps to avoids that def compare(x, y): df2['distance'] = (abs(x-df2['x'])**0.5 + abs(y-df2['y'])**0.5)...
python|pandas|dataframe
7
369,441
63,421,983
Python Pandas time difference from the start of every day
<p>I've got the following data frame on pandas:</p> <pre><code>d = {'col_Date_Time': ['2020-08-01 00:00:00', '2020-08-01 00:10:00', '2020-08-01 00:15:00', '2020-08-01 00:19:00', '2020-08-01 01:19:00', '...
<pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'col_Date_Time': ['2020-08-01 00:00:00', '2020-08-01 00:10:00', '2020-08-01 00:15:00', '2020-08-01 00:19:00', '2020-08-01 01:23:00', ...
python|pandas|datetime|date-difference
1
369,442
63,652,071
Looping Logistic Regression over DataFrame in Python
<p>I am stuck on where I am going wrong with this loop to perform Logistic Regression on a dataframe with 25 features.</p> <p>When I reshape it giving the error : &quot;ValueError: Expected 2D array, got 1D array instead: array=[-12.36677125 -12.91946925 -12.89317629 -13.16951215 -12.20588875 -12.44694704 -12.71370778 ...
<p>X is expected to be a 2D array while fitting the model, and y as a 1D array.</p> <p>X_train[peptide] returns a series which is a 1D array. You can either -</p> <pre><code>X_train[peptide].shape #Output = (nrows,) </code></pre> <p>You can do this -</p> <pre><code>X_train[[peptide]].shape #Output = (nrows,1) </code><...
pandas|numpy|loops|machine-learning|logistic-regression
0
369,443
63,516,579
How to unstack a df from excel table with multiple levels of duplicating columns? Set multi index?
<p>df read from an xlsx: <code>df = pd.read_excel('file.xlsx')</code> arrives like this:</p> <pre><code> Age Male Female Male.1 Female.1 0 NaN Big Small Small Big 1 1.0 2 3 2 3 2 2.0 3 4 3 4 3 3.0 4 5 4 5 df = pd.DataFrame({'Age':[np.nan, 1,2,3],...
<p>Instead of <code>.unstack()</code>, another approach would be <code>.melt()</code>.</p> <p>You can transpose the dataframe with <code>.T</code> and take everything after the first row with <code>.iloc[1:]</code>. Then, <code>.rename</code> the columns, <code>.replace</code> the <code>.1</code> with some regex, <code...
python|pandas|dataframe|indexing|multi-index
1
369,444
63,675,602
How to implement a neural network with a not-fully-connected layer as the final layer?
<p>I would like to implement a neural network with an input layer, two dense hidden layer and a non-dense output layer. A toy example is shown in the figure below. The first hidden layer has three neurons, the second two and the final four neurons but between the second and third there are only four connections.</p> <p...
<p>The final layer is actually two separate <code>Dense</code> layers, each with 2 neurons and connected to a different neuron of previous layer. Therefore, you can simply separate the neurons of second-to-last layer and pass it to two different layers:</p> <pre><code>input = keras.layers.Input(shape=(3,)) hidden1 = ke...
python|tensorflow|keras|neural-network|tf.keras
7
369,445
63,598,304
MemoryError: std::bad_alloc: rapids.ai Dask-cuDF
<p>I would like to load 5.9 GB CSV and I don't use pandas library. I have 4 GPUs. I use <a href="https://rapids.ai" rel="nofollow noreferrer">rapids.ai</a> to load this large dataset faster but every time that I tried, this error is shown to me although I have space in my other GPU memory. memory usage of GPUs at the b...
<p>The answer to the question :<a href="https://stackoverflow.com/questions/58114113/cudf-error-processing-a-large-number-of-parquet-files">CUDF error processing a large number of parquet files</a></p> <p>explains how to use dask_cudf to read large files : <a href="https://stackoverflow.com/a/58123478/13887495">https:/...
python|pandas|dask|rapids|cudf
2
369,446
63,535,462
Folium choropleth map not colouring from geopandas
<p>I have a geopandas dataframe (dfg) with the following structure</p> <pre><code>lsoa11cd object A8 float64 OBJECTID int64 LSOA11CD object LSOA11NM object LSOA11NMW object Shape__Area float64 Shape__Length float64 geometry geometry </cod...
<p>I think you are missing the <code>key_on</code> parameter in the <code>folium.Choropleth</code>, which is basically the link between your GeoJson and your pandas DataFrame.</p> <p>It uses your GeoJson keys to know where to do the join. It can be something like <code>'feature.id'</code>, but you will have to provide ...
python|geopandas|folium
1
369,447
63,647,627
Resize image and create tfexample for tensorflow 2 dataset results in error
<p>I'm using Tensorflow 2.2, and trying to convert a model into TensorRT. I am following an example, which successfully works for models that accept images as input. Unfortunately, I froze a model which accepts TF Example as input instead of image. Now, trying to create the tf dataset pipeline has become a nightmare.</...
<p>I was to able to reproduce the error you are facing using a simple bird image.</p> <p><strong>Code to recreate the error -</strong></p> <pre><code>%tensorflow_version 2.x import tensorflow as tf from keras.preprocessing.image import load_img from keras.preprocessing.image import img_to_array, array_to_img from matpl...
tensorflow2.0|tensorflow2.x
0
369,448
63,490,419
Export pytorch model parameters into separate files according to layer hierarchy
<p>Is it possible to export the trained parameters of a Pytorch model into separate binary files (float32/64, not text) under a folder hierarchy reflecting the layers defined by the model's architecture?</p> <p>I wish to examine a sizeable pretrained model without the framework overhead and also split the checkpoint in...
<p>There is no direct way to do this, but it should take only a few lines of code. For example, consider I have a model of the following structure:</p> <pre><code>class ConvBlock(nn.Module): def __init__(self, C_in, C_out, kernel, pool): super().__init__() self.conv = nn.Conv2d(C_in, C_out, kernel) ...
python|pytorch
2
369,449
63,394,042
How can I drop duplicates in pandas without dropping NaN values
<p>I have a dataframe which I query and I want to get only unique values out of a certain column.<br /> I tried to do that executing this code:</p> <pre><code> database = pd.read_csv(db_file, sep='\t') query = database.loc[database[db_specifications[0]].isin(elements)].drop_duplicates(subset=db_specification[1])...
<p>You can start by selecting all <code>NaN</code> and then drop duplicate on the rest of the dataframe.</p> <pre><code>mask = data.isna().any() data = pd.concat([data[mask], data[~mask]]) </code></pre>
python|pandas|drop-duplicates
1
369,450
63,404,656
Pytorch: How to train a network with two loss functions?
<p>I want to pretrain a network with reconstruction loss first, then finetune it by crossentropy loss. But it seems that I have to define two network in this two stage. How to achieve it?</p> <pre><code>class Net(): def __init__(self,pretrain): self.pretrain = pretrain def encoder(self,x): # do ...
<p>You can achieve this by simply defining the two-loss functions and loss.backward will be good to go. See the relevant discussion <a href="https://discuss.pytorch.org/t/how-to-combine-multiple-criterions-to-a-loss-function/348/25" rel="nofollow noreferrer">here</a></p> <pre><code>MSE = torch.nn.MSELoss() crossentropy...
python|neural-network|pytorch|pre-trained-model
1
369,451
63,575,739
How to Convert a List to numpy.datetime64 format
<p>I know that we can create a single string to <code>np.datetime64</code> format such as:</p> <pre><code>a = np.datetime64('2020-01-01') </code></pre> <p>But what if we have a list with multiple strings of dates in it?</p> <p>How are we able to apply the same <code>np.datetime64</code> to convert all the elements insi...
<p>When you have your string list, use it as a source to a <em>Numpy</em> array, passing <em>datetime64</em> as <em>dtype</em>. E.g.:</p> <pre><code>lst = ['2020-01-01', '2020-02-05', '2020-03-07' ] a = np.array(lst, dtype='datetime64') </code></pre> <p>When you execute <code>a</code> (actually print this array in a no...
python|numpy|datetime64
2
369,452
63,438,024
Using Tensorflow-Lite GPU delegate in Android's Native environment with C-API
<h3>Info</h3> <p>I'm using Tensorflow-Lite in Android's Native environment via the C-API (following <a href="https://www.tensorflow.org/lite/guide/android#use_tflite_c_api" rel="nofollow noreferrer">these instructions</a>) but runtime is significantly longer compared to the GPU delegate via the Java API (on ART).</p> <...
<p>I managed to do it as follows:</p> <h3>1. Clone and configure <code>tensorflow</code></h3> <p>Clone <code>tensorflow</code> repo from GitHub, <code>cd</code> into it and run <code>./configure</code>. There it is important to answer <code>Would you like to interactively configure ./WORKSPACE for Android builds? [y/N]...
c|android-ndk|delegates|gpu|tensorflow-lite
0
369,453
63,334,457
Pandas read xml in an excel column , and create new columns based on data
<p>I have a excel, which has data column with data in xml format.</p> <pre><code>ID Color Payload Misc 1 Green &lt;Insert&gt;&lt;emp:Emp&gt;&lt;ebo:Id&gt;001&lt;/ebo:Id&gt;&lt;ebo:Name&gt;Name 1&lt;/ebo:Name&gt;&lt;/emp:Emp&gt;&lt;/Inse...
<p>Maybe you can use find() and a loop (with index) to do it:</p> <pre><code>df['MainNode'] = df['Payload'] for i,row in df.iterrows(): df['MainNode'][i] = df['MainNode'][i][df['MainNode'][i].find('&lt;')+1 : df['MainNode'][i].find('&gt;')] df['ID'] = df['Payload'] for i,row in df.iterrows(): df['ID'][i] = df[...
xml|pandas
0
369,454
63,483,415
MatPlotLib Pcolormesh not overlaying properly
<p>I am trying to duplicate this tutorial : <a href="https://makersportal.com/blog/2019/7/8/satellite-imagery-analysis-in-python-part-i-goes-16-data-netcdf-files-and-the-basemap-toolkit" rel="nofollow noreferrer">https://makersportal.com/blog/2019/7/8/satellite-imagery-analysis-in-python-part-i-goes-16-data-netcdf-file...
<p>Actually the problem was with the data, I was trying to plot cloud data that wasn't clean, so what I did was to allot the lower values a None value so only higher values were shown</p>
python|numpy|matplotlib|data-science
0
369,455
63,569,179
Python 3.7.8 Imports an uninstalled Tensorflow Version
<p>I am currently trying to change my Tensorflow version in Python from 2.2.0 to 1.15.0, but I cannot seem to get python to import the correct module.</p> <p>First, I do:</p> <pre><code>pip uninstall tensorflow </code></pre> <p>After the uninstallation is complete, I do:</p> <pre><code>pip install tensorflow==1.15.0 </...
<p>This is common problem with python modules when the environment is messy. To help track it down, you should look at the value of the <code>PYTHONPATH</code> environment variable and the location of the imported package. That is, inside python, print this: <code>tensorflow.__file__</code></p>
python|tensorflow|deep-learning|pip|tensorflow2.0
0
369,456
63,569,144
Perlin noise problem: clearly visible lines in result
<p>I have been implementing a perlin noice generator in python. It works pretty well except for clearly visible lines in the result.</p> <p>The problem seems to be related to where i switch between gradients in X-direction.</p> <p>Here is the code:</p> <pre><code>from random import randint, seed from PIL import Image f...
<p>To answer your question, I am not certain if this is the entire issue, but I do see one error. In X, you lerp along sx from X0 to X1. But in Y, you lerp along sy from Y1 to Y0. Swapping Y1/Y0 in the topLeftDot-bottomRightDot vars should fix that. Alternatively, switch which variables are in which parts of the lerp r...
python|numpy|perlin-noise
1
369,457
63,575,343
Python, get an error when using np.dstack and can’t solve it
<p>When running the following code</p> <pre><code>mport matplotlib.pyplot as plt import numpy as np import skimage, skimage.io from skimage.color import rgb2hsv from skimage import io ic = skimage.io.imread_collection('/Users/ /remoteSensing/Image/Landsat/*.tif') img = np.dstack((ic[5],ic[4],ic[3])) </code></pre> <p>...
<p>Can you try updating your scikit-image version and installing tifffile as well? scikit-image 0.17 changed the way tiff files are read and that might fix the problem.</p> <p>Additionally, as pointed out by hpaulj, you need to pass in a list/tuple to <code>np.dstack</code>:</p> <p><code>np.dstack((ic[5], ic[4], ic[3])...
python|numpy|collections|scikit-image|imread
0
369,458
63,608,039
RecursionError: maximum recursion depth exceeded, while accessing the dataframe
<p>I am trying to put the pickle file to a dataframe. Tried <code>setrecursionlimit</code> values from 1500-5000 still get the error.</p> <p>Is there any other way to access pickle file and put it in a dataframe?</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np import sys sys.s...
<p><strong>Are you trying to read a DataFrame with columns that hold other DataFrames?</strong></p> <p>If so, and if <strong>all rows hold the same copy of the dataframe</strong>, you might consider converting the inner frame columns to actual columns in the outer frame.</p> <p>You can find the columns that hold frames...
python|pandas|dataframe|pickle
0
369,459
63,727,952
Pandas DataFrame: Removing duplicate rows based on condition in columns
<p>I have a large dataframe:</p> <pre><code>import pandas as pd df = pd.read_csv('data.csv) df.head() ID Year status 223725 1991 No 223725 1992 No 223725 1993 No 223725 1994 No 223725 1995 No </code></pre> <p>I have many unique <code>IDs</code> and I want to remove duplicate rows based on the ...
<p>I think you can do:</p> <pre><code># sort by status so that No comes before Yes df = df.sort_values('status') # pick the last row, it will either be Yes or No df = df.groupby('ID').last() </code></pre>
python|pandas|dataframe
4
369,460
63,663,238
Reading data from excel and rewriting it with a new column PYTHON
<p>I recently managed to create a program the reads data from excel, edit it and rewrite it along with new columns and it works good, but the issue is the performance if the excel file contains 1000 rows it finishes in less than 2 mins but if it contains 10-15k rows, it can take 3-4 hours and the more I have rows the m...
<p>You can remove iterating over rows by converting sheet data to a dataframe and get values as list.</p> <pre><code>from openpyxl import load_workbook from datetime import datetime,timedelta from dateutil.relativedelta import relativedelta def xls_to_dict(workbook_url): xl = pd.ExcelFile(workbook_url) work...
python|excel|pandas
1
369,461
63,502,399
Correctly saving model to .pb
<p>I used the tutorial &quot;<a href="https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/image_feature_vector.ipynb#scrollTo=9Z_ZvMk5JPFV" rel="nofollow noreferrer">Classify Flowers with Transfer Learning</a>&quot; to retrain on my own classes. Unfortunately, no example is provided on ho...
<p>This doable but can be a little fiddly, which is why tensorflow comes with a tool to do it for you.</p> <p>See: <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py" rel="nofollow noreferrer">freeze_graph.py</a></p> <p>You can either dig into how it works or simply im...
python|tensorflow
1
369,462
63,362,251
Pandas 0.25.0 cannot create cursor for read_sql - throwing error
<p>I keep getting an error with Pandas' 0.25.0 read_sql(). The code below is supposed to establish a couple connections, check if tables need to be created, and then begin extracting the result set from Oracle.</p> <p>Stack Trace</p> <pre><code>RESTART: C:\xxxx\xxxx\AppData\Local\Programs\Python\Python36\xxxx\main.py ...
<p>I found the error! The issue was in data.py. In the parameter list of data_box_extract, connection is spelled as &quot;connnection&quot;. Inside the function, &quot;connection&quot; was being used so a cursor couldn't be instantiated. Not sure why it didn't throw an error about &quot;connection&quot; not being insta...
python-3.x|pandas
0
369,463
63,701,797
Extract Partial Data from multiple excel sheets in the same workbook using pandas
<p>I have an excel Workbook with more than 200 sheets of data. Sheet names are as shown in the figure. I would like to assign each sheet to an individual variable as a data frame and later extract some required data from each sheet. Extracted information from all the sheet needs to be stored into a single excel sheet ...
<p>Not sure exactly what you are trying to do, but an easier way to traverse through the sheet names would be with a for-each loop:</p> <pre><code> for sheet in input.sheet_names: </code></pre> <p>Now you can do something for all the sheets no matter their name.</p> <p>Regarding &quot; would like to assign each sheet t...
python|excel|pandas|dataframe
1
369,464
63,630,851
How to use predict for nlp in Tensorflow-keras?
<p>I have bit of problem when predicting named entity recognition set. After i trained and tested all went good. Now i want to test on raw data like strings .</p> <p>I tried to use</p> <pre><code>model.predict(['Elon musk is good guy , he owns spacex, tesla.']) </code></pre> <p>but it throws erorr,</p> <pre><code>Unimp...
<p>I guess you want to predict words, right?</p> <p>Then you should split your words:</p> <pre><code>sentence = 'Elon musk is good guy , he owns spacex, tesla.' word_index = [[token2idx[word] for word in sentence.split(' ')]] X = pad_sequences(sequences=word_index, maxlen=7, padding='post') predicted = np.argmax(model....
python|tensorflow|keras
0
369,465
63,444,155
Pandas dataframes Python to find % distribution using a column value
<p>I have a dataframe like this, where I need to find the % of each item based on date,</p> <pre><code>Grade Count Date A+ 303 8/7/2020 B+ 35 8/7/2020 A+ 450 8/7/2017 B+ 23 8/7/2017 </code></pre> <p>I want need find the Percentage distribution of each row based on date colu...
<p>You can use 100% pandas methods, so it gets faster.</p> <pre><code>df_date_sum = df.groupby(by='Date') \ .agg({'Count': 'sum'}) \ .reset_index() \ .rename(columns={'Count': 'Total'}) df = df.merge(df_date_sum, how='left', on='Date') df['%Change'] = (df['Count']/df['Total'])*100 </code></pre>
python|pandas|dataframe|group-by
1
369,466
63,549,414
How to assign non null values in one group to all rows in the group in pandas?
<p>I have a dataframe that looks like this.</p> <pre><code>+----+-------+ | ID | Value | +----+-------+ | 1 | 23 | | 1 | NA | | 1 | NA | | 1 | NA | | 2 | 24 | | 2 | NA | | 2 | NA | +----+-------+ </code></pre> <p>For each ID value in a group, I either have one value or NA. I wanted to apply ...
<p>Check with</p> <pre><code>df.Value.fillna(df.groupby('ID').Value.transform('first'), inplace=True) </code></pre>
python|pandas|dataframe
2
369,467
63,368,363
Count the number of duplicate grouped by ID pandas
<p>I'm not sure if this is a duplicate question, but here it goes.</p> <p>Assuming I have the following table:</p> <pre><code>import pandas lst = [1,1,1,2,2,3,3,4,5] lst2 = ['A','A','B','D','E','A','A','A','E'] df = pd.DataFrame(list(zip(lst, lst2)), columns =['ID', 'val']) </code></pre> <p>will o...
<p>Let us try <code>duplicated</code></p> <pre><code>df['is_dup']=df.duplicated(subset=['ID','val'],keep=False).astype(int) df Out[21]: ID val is_dup 0 1 A 1 1 1 A 1 2 1 B 0 3 2 D 0 4 2 E 0 5 3 A 1 6 3 A 1 7 4 A 0 8 5 E 0 </c...
python|pandas
2
369,468
63,531,124
Pandas categorical series showing duplicate category names. How to find the indexes?
<p>as I run this code:</p> <pre><code>df19['tipo'] = df19['tipo'].astype('category') df19.tipo.value_counts() </code></pre> <p>I'm getting the following output:</p> <pre><code>CAS 1269 REF 667 QUE 408 CPPP 190 INH 60 COMP 25 EXC 22 REC 14 ACL 4 ...
<p>Let us try</p> <pre><code>df19['tipo'].str.strip().value_counts() </code></pre>
python|pandas|dataframe|data-science|data-cleaning
2
369,469
63,680,793
How to properly adjust code due to this futurewarning? (multidimensional indexing numpy)
<p>How to adjust the indexing in this code, so that it will work properly due to this FutureWarning?</p> <pre><code>D:/Arc/Arc_Project\Architecture\_Z07_Adjust_X_Y\backward_sequentialize.py:165: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[...
<p>For accessing the given elements just send the array of the required indices followed by the <code>,</code> to represent the other axes and return the required ones in the given axis.</p> <p><code>array[([2,5],)]</code>, that should take care of it.</p>
python|arrays|numpy|indexing|future-warning
1
369,470
63,511,327
Checking the distribution and value counts of a column based on group types in another column in Python
<p>I have a dataframe like this:</p> <pre><code> Data_Entry Type 0 1 Blue 1 10 Green 2 5 Green 3 2 Blue 4 12 Blue 5 2 Green 6 2 Red 7 50 Blue 8 32 Blue 9 76 Red 10 75 Red 11 12 Blue...
<p>Something with <code>pd.cut</code> to classify <code>values</code> and <code>groupby</code>?</p> <pre><code>df.groupby([pd.cut(df.Data_Entry, bins=np.arange(0,100,5)), 'Type']).size().unstack('Type') </code></pre> <p>Output:</p> <pre><code>Type Blue Green Red Data_Entry (0, 5] 2 ...
python|pandas
1
369,471
63,733,144
Selecting rows in pandas dataframe
<p>I would need to select rows satisfying the following conditions:</p> <ul> <li>if (X is True and Z is false) | ( X is false and Z is true) then assign to a new column True as value.</li> </ul> <p>I tried with this:</p> <pre><code>df[(df[X']==True &amp; df['Z']==False) | (df['X']==False &amp; df['Z']==True)] </code></...
<p><code>df['X']==True &amp; df['Z']==False</code> must be <code>(df['X']==True) &amp; (df['Z']==False)</code> (and everything else, respectively). In Python, operator <code>&amp;</code> has a higher precedence than <code>==</code>. Your expression is interpreted as <code>df['X']==(True &amp; df['Z'])==False</code>.</p...
python|pandas
0
369,472
63,570,089
how can i change int64 to Datetime in pandas data frame?
<p>i use for change int64 datatype to Date time type with 'to_datetime'method but the result is too weird.</p> <pre><code>df['DEATH_YMD'] = pd.to_datetime(df[&quot;DEATH_YMD&quot;], unit='s') </code></pre> <p>the result is it.</p> <blockquote> <p>PT_SBST_NO P00001 1970-01-01 00:00:00.020160515 P00002 1970-01-01 00:...
<p>You need to specify a format:</p> <pre><code>df['DEATH_YMD'] = pd.to_datetime(df[&quot;DEATH_YMD&quot;], format='%Y%m%d') </code></pre> <p>The <code>unit</code> param is used when the number is a timestamp.</p>
python|pandas
0
369,473
63,655,146
PyPDF2 give me blank pages in merged PDF
<p>I have earlier come up with this question in here: <a href="https://stackoverflow.com/questions/63622405/pypdf2-merging-pdf-pages-issue">pypdf2-merging-pdf-pages-issue</a></p> <p>Where I have now come a long way and can now create my PDF files from an Excel document via Pandas into PyPDF2.</p> <p>As well as where I ...
<p>@anon01 Thx</p> <p>And Thx/credit to Sirius3.</p> <p>It's something about the PyPDF2, how to use it and some bugs with it. So after edit the code to this it work.</p> <pre><code>import datetime #Handle date import pandas as pd #Handle data from Excel Sheet (Data analysis) from PyP...
python|pandas|pdf|pypdf2
0
369,474
63,603,245
BokehUserWarning and problem with pandas_datareader in python
<p>I am trying to plot a chart with bokeh.plotting from stock data gotten from data.DataReader using the pandas_datareader module.</p> <p>Issue one: the data retrieved is in pandas.Index and not pandas.DatetimeIndex</p> <p>Issue two: I receive a BokehWarning</p> <p>The code1:</p> <pre><code>import os from pandas_datare...
<p>I found the solution by changing the data source from Alpha Vantage to Yahoo Finance. I didn't use yahoo directly as the source from data.DataReader module because it was deprecated. Turns out that yahoo finance created a separate module called yfinance.</p> <pre><code>from pandas_datareader import data from datetim...
python|bokeh|pandas-datareader
0
369,475
63,367,506
Image translation using numpy
<p>I want to perform image translation by a certain amount (shift the image vertically and horizontally).</p> <p>The problem is that when I paste the cropped image back on the canvas, I just get back a white blank box.</p> <p>Can anyone spot the issue here?</p> <p>Many thanks</p> <pre><code>img_shape = image.shape # t...
<p>For image translation, you can make use of the somewhat obscure <code>numpy.roll</code> function. In this example I'm going to use a white canvas so it is easier to visualize.</p> <pre class="lang-py prettyprint-override"><code>image = np.full_like(original_image, 255) height, width = image.shape[:-1] shift = 100 #...
python|numpy|opencv|image-processing
2
369,476
63,426,465
Is there a way for scipy.integrate.quad to accept arrays in args?
<p>I have a function:</p> <pre><code>def xx(th, T, B): f = integrate.quad(xint, 0, np.inf, args = (th, T, B))[0] a = v(th)*f return a </code></pre> <p>where <code>xint</code> is a function of functions of <code>p, th, T, B</code>. All the preceding functions work well; <code>xx(th, T, B)</code> should then ...
<p>I never really got the usefulness of the <code>args</code> option. IMHO, the code becomes clearer if you define a function that accepts only one argument, perhaps by wrapping:</p> <pre class="lang-py prettyprint-override"><code>th = 2.0 T = 1.0 B = 3.0 def xint(x): return th * x ** B / T f, _ = integrate.quad(...
python|numpy|scipy|integrate
0
369,477
21,418,022
Choice of Dimension on Numpy Arrays
<p>I have a dataset I wish to analyze. It consists of</p> <ul> <li>measurements, total number <code>m</code>, which is roughly 2 000 000.</li> <li>each measurement contains <code>v</code> variables. (About 10 in this case)</li> </ul> <p>I can name each variable (foo, bar, etc) and choose each of them a <a href="http:...
<p>First things first: Remember that premature optimization is the root of all evil. You can always use the timeit module if you suspect something is slow. </p> <p>As for your question, I store my data such that the measurements are indexed by rows and the dimensions are indexed by columns. This way the measurements t...
python|arrays|memory|numpy|multidimensional-array
3
369,478
21,446,323
Converting a dictionary of tuples into a numpy matrix
<p>I have a very large dictionary containing tuples as keys and their values. This dictionary is supposed to represent an adjacency matrix with word co-occurrence vectors, eg 'work' appears with 'experience' 16 times and 'work' appears with 'services' 15 times. Whether or not this is the preferred storage method is ano...
<p><a href="https://stackoverflow.com/a/21325888/110026">This answer</a> may be of help. With your sample data:</p> <pre><code>&gt;&gt;&gt; frequency = {('work', 'experience'): 16, ... ('work', 'services'): 25, ... ('must', 'services'): 15, ... ('data', 'services'): 10} &gt;&g...
python|dictionary|numpy|matrix|networkx
5
369,479
21,796,353
Are there predefined functions in scipy/numpy to shift/rotate an image that use sinc-interpolation instead of spline interpolation?
<p>The question title summarizes it well I hope. I have a large batch of images which I want to register. For this purpose I need to shift/rotate the images. So far I have used scipy.ndimage.rotate and scipy.ndimage.shift for this task. However, some of the images have sharp intensity features for which the higher orde...
<p>I would suggest using the command line <code>convert</code> from <a href="http://www.imagemagick.org/script/command-line-options.php#interpolate" rel="nofollow noreferrer">imageMagik</a> you can convert the entire batch and have control of the interpolation method - available methods are:</p> <blockquote> <p>integer...
python|image-processing|numpy|scipy|image-rotation
-1
369,480
21,471,296
Condition in Pandas
<p>I have a very peculiar problem in Pandas: one condition works but the other does not. You may download the linked file to test my code. Thanks! </p> <p>I have a file (<a href="https://www.dropbox.com/s/5utmdub1ay0uerx/stars.txt" rel="nofollow">stars.txt)</a> that I read in with Pandas. I would like to create two ...
<p>This is not an error. You are seeing a summarized view of the DataFrame:</p> <pre><code>In [11]: df = pd.DataFrame([[2, 1], [3, 4]]) In [12]: df Out[12]: 0 1 0 2 1 1 3 4 In [13]: df.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 2 entries, 0 to 1 Data columns (total 2 columns): 0 2 no...
pandas
2
369,481
21,908,534
linestyle feature for plotting in python with matplotlib.pyplot
<p>I'm trying to scatter or plot 2 sets of arrays using numpy and matplotlib. Everything is ok with the code except when I try to have lines instead of dots in my plot The plot is ok when I use :</p> <pre><code>from numpy import * import matplotlib.pyplot as plt positions=open('test.txt','r') lines=positions.readline...
<p>The reason that you see no lines when you ask for a plot without setting the markers is because you are plotting each (x,y) point individually, which can have a point position, but would create a line of length zero.</p> <p>If instead of plotting each point immediately upon reading it, you put those values into an ...
python|numpy|matplotlib|plot
2
369,482
21,421,556
Join on dataframe without a key
<p>I am joining two dataframes. Each of the same size, being 287025. </p> <pre><code>dataDF = sample.join(additional_info) </code></pre> <p>The indices are identical, and the dataDF has the correct size, being 287025. However now I seem to have no access to the rows. I try <code>dataDF[1:9]</code> and it simply outpu...
<p>It sounds like the join is working, but you are seeing a summarized view.</p> <p>There are a number of display options which can do this, the most likely imo:</p> <pre><code># if there are more columns than this, you'll see a summarized view pd.options.display.max_columns = 40 # default is 20 </code></pre> <p><em...
python|pandas|dataframe|slice
2
369,483
21,637,414
Is it possible to mmap a recarray in python 2.7?
<p>I have a large global recarray totaling 30GBs of data in a programme running via qsub on a cluster with 256GBs of RAM. I am currently the only user on this cluster so there are no conflicts with the allocation of RAM. When looping over this recarray the system appears to shunt the object to the disc, not keep it hel...
<p>Instead of <a href="http://docs.python.org/2/library/mmap.html" rel="nofollow noreferrer"><code>mmap</code></a> you may want to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.memmap.html" rel="nofollow noreferrer"><code>numpy.memmap</code></a> or <a href="http://docs.scipy.org/doc/numpy/refer...
python|numpy|mmap|recarray
2
369,484
21,829,467
How to determine whether a memory page is mmaped in C
<p>I would like to know a way to determine whether a pointer belongs to a mmaped memory page.</p> <p>A <a href="https://stackoverflow.com/questions/8362747/how-can-i-detect-whether-a-specific-page-is-mapped-in-memory">post</a> on StackOverflow suggest using msync() on the pointer to determine whether it passes or not....
<p>All non-empty process address space is <code>mmap</code>ed. Either using <code>mmap</code> syscall or indirectly via <code>brk</code>/<code>sbrk</code> syscalls . </p> <p>You probably need to find another way to distinguish <code>numpy</code> arrays.</p> <p><a href="http://docs.scipy.org/doc/numpy-1.6.0/reference/...
python|c|numpy|mmap
2
369,485
21,605,143
Special Vector and Element-wise Multiplication
<p>I have 2 arrays. "A" is one of them with arbitrary length (let's assume 1000 entries for a start), where each point holds a <strong>n</strong>-dimensional vector, where each entry represents a scalar. "B" is the other one, with <strong>n</strong> entries that each hold a 3-dimensional vector. How can I do a scalar m...
<p>If you start with:</p> <pre><code>a = np.array([[1,2,3,4],[5,6,7,8]]) b = np.array([[1,0,0],[0,1,0],[0,0,1],[1,1,1]]) </code></pre> <p>Then we can add an extra axis to <code>a</code>, and repeating the array along it gives us...</p> <pre><code>&gt;&gt;&gt; a[:,:,None].repeat(3, axis=2) array([[[1, 1, 1], ...
python|arrays|numpy
3
369,486
21,621,277
How to generate difference Image?
<p>I am comparing two images. if comparison fails then I want to generate the difference image for that two. Doing in Python. Should be quickest solution.</p>
<p>Hope this helps</p> <pre><code>import ImageChops def equal(image1, image2): return ImageChops.difference(image1, image2) </code></pre> <p><a href="http://effbot.org/zone/pil-comparing-images.htm" rel="nofollow">Link found here</a></p>
python|opencv|numpy|python-imaging-library
2
369,487
21,483,469
Python - Fastest way to generate list of random colours with fixed alpha
<p>So I'm looking to generate a large list of approximately 332 million colours (tuples with 4 values - r,g,b,a) in Python, but with a fixed alpha value of 0.6. I also need to duplicate every colour in the row below it (i.e. I end up with 664 million rows - only 332 million distinct colours.</p> <p>I have tried and te...
<p>I'm a bit confused by the code you've shown. You seem to be doing things in a very round-about way, and I may be misunderstanding exactly what you want.</p> <p>However, as I understand it, you want:</p> <pre><code>import numpy as np colorarray = np.random.random_sample((332000000, 4)) colorarray[:, -1] = 0.6 col...
python|performance|random|numpy|colors
2
369,488
21,757,516
Match Trades from a CSV File in Python using Pandas
<p>So I have a CSV File with sorted trade data. It has the following columns : </p> <pre><code>Trade_Price , TimeStamp , Buy/Sell , Contract </code></pre> <p>Now I have sorted the trades so that they are in the CSV in successive rows. Now I want to pair up the trades find the net PnL by taking the difference of the ...
<p>Two grab two columns at a time you can do something like this:</p> <pre><code>import pandas as pd Trade_Price = pd.DataFrame({'A':[1,2,3,4],'B':[5,6,7,8]}) Trade_Price1 = Trade_Price.iloc[::2,:].reset_index(drop=True) Trade_Price2 = Trade_Price.iloc[1::2,:].reset_index(drop=True) print Trade_Price1 print Trade_Pri...
python|pandas|dataframe|finance|import-from-csv
0
369,489
21,916,979
numpy - selecting elements from an array with spacing
<p>I have a numpy array with a bunch of monotonically increasing values. Say,</p> <pre><code>a = [1,2,3,4,6,10,10,11,14] a_arr=np.array(a) </code></pre> <p>Also say</p> <pre><code>thresh = 4 </code></pre> <p>I want to create an array that contains the indices of a subset of <code>a_arr</code> which steps through t...
<p>Here's a vectorized solution to your approximate problem:</p> <pre><code>idx = np.cumsum(np.bincount((a-a[0])/thresh))[:-1] </code></pre> <p>This gives you all the indices except for the first zero, which is always present. Here's the explanation:</p> <ol> <li><p><code>(a-a[0])/thresh</code> does integer division...
python|arrays|numpy
1
369,490
21,822,988
What Series method replaced searchsorted?
<p>In his video, [Data analysis in Python with pandas] (<a href="http://youtu.be/w26x-z-BdWQ?t=2h14s" rel="nofollow">http://youtu.be/w26x-z-BdWQ?t=2h14s</a>), Wes McKinney presents a series method names searchsorted(), which given a value, gives back the index in which the series is crossing that value. It appears this...
<p>I believe this is due to the refactoring that occurred in Pandas 0.13.0 where Pandas Series now sub-class NDFrame rather than ndarray see <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#internal-refactoring">this</a>:</p> <pre><code>In [33]: import pandas as pd import numpy as np df = pd.DataFra...
python|pandas
7
369,491
24,918,097
Python - Matplotlib: normalize axis when plotting a Probability Density Function
<p>I'm using Python and some of its extensions to get and plot the Probability Density Function. While I manage to plot it, in its form, at least, I don't manage to succeed on scalating the axis.</p> <pre><code>import decimal import numpy as np import scipy.stats as stats import pylab as pl import matplotlib.pyplot as...
<p>the y-axis is normed in a way, that the area under the curve is one. And adding equal weights for every data point makes no sense if you normalize anyway with <code>normed=True</code>.</p> <p>first you need to shift your data to 0:</p> <pre><code> lines -= mean(lines) </code></pre> <p>then plot it.</p> <p>ythis ...
python|numpy|matplotlib|plot|statistics
3
369,492
24,807,588
Looping over a MultiIndex in pandas
<p>I have a MultiIndexed DataFrame df1, and would like to loop over it in such a way as to in each instance of the loop have a DataFrame with a regular non-hierarchical index which is the subset of df1 corresponding to the outer index entries. I.e., if i have:</p> <p><img src="https://i.stack.imgur.com/TMWyW.png" alt=...
<p>Using a modified example from <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#multiindexing-using-slicers" rel="noreferrer">here</a></p> <pre><code>In [30]: def mklbl(prefix,n): return ["%s%s" % (prefix,i) for i in range(n)] ....: In [31]: columns = MultiIndex.from_tuples([('a','foo...
python|pandas|multi-index
8
369,493
24,577,456
Trouble to impliment scipy interpolation
<p>I am trying to use the class shown <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.RegularGridInterpolator.html#scipy.interpolate.RegularGridInterpolator" rel="nofollow">here</a> to interpolate some data.</p> <p>I am having trouble getting this class to work. A minimal example is:</p>...
<p>From the docs:</p> <blockquote> <p>New in version 0.14.</p> </blockquote> <p>It's likely you have a previous version of SciPy. If you are using Ubuntu, try running <code>pip</code>:</p> <pre><code>pip install --user --upgrade scipy </code></pre> <p>You might need some additional dependencies:</p> <pre><code>s...
python|numpy|scipy|interpolation|scientific-computing
2
369,494
24,835,345
write a python code the most efficient way
<p>I am writing a code using a Python library MDAnalysis. And I have an array (502,3) of atom positions I want to get an array of bonds (vectors of position of Atom(i+1) - Atom(i)) And then I want to obtain an average tensor qab = which is essentially a np.outer(ua,ub) averaged by all atoms.</p> <p>I can rewrite thi...
<p>I've done my best below. It's pretty easy to generate your <code>bb_res</code> more efficiently, but I was unable to optimize the double <code>for</code> loop. On my computer, my method is about 26% faster. Also based on the statement of your question I believe there is a bug in your code which I pointed out in a co...
python|numpy|scipy
1
369,495
24,762,122
Read Matlab Data File into Python, Need to Export to CSV
<p>I have read a Matlab file containing a large amount of arrays as a dataset into Python storing the Matlab Dictionary under the variable name <code>mat</code> using the command:</p> <p><code>mat = loadmat('Sample Matlab Extract.mat')</code></p> <p>Is there a way I can then use Python's write to csv functionality to...
<p>The function <code>scipy.io.loadmat</code> generates a dictionary looking something like this:</p> <pre><code>{'__globals__': [], '__header__': 'MATLAB 5.0 MAT-file, Platform: MACI, Created on: Wed Sep 24 16:11:51 2014', '__version__': '1.0', 'a': array([[1, 2, 3]], dtype=uint8), 'b': array([[4, 5, 6]], dtype=ui...
python|matlab|numpy|scipy
13
369,496
30,236,481
Assign to array, adding multiple copies of index
<p>So I have this array, right?</p> <pre><code>a=np.zeros(5) </code></pre> <p>I want to add values to it at the given indices, where indices can be duplicates.</p> <p>e.g. </p> <pre><code>a[[1, 2, 2]] += [1, 2, 3] </code></pre> <p>I want this to produce <code>array([ 0., 1., 5., 0., 0.])</code>, but the answer...
<p>You need to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.at.html" rel="nofollow"><code>np.add.at</code></a> to get around the buffering issue that you encounter with <code>+=</code> (values are not accumulated at repeated indices). Specify the array, the indices, and the values to add...
python|arrays|numpy|multidimensional-array
3
369,497
30,118,305
Full-range random number in Python
<p>I'm generating a series of random floats using this line:</p> <pre><code>random.random()*(maxval-minval) + minval </code></pre> <p>I'm using it to add variable noise to a given variable, and the amount of noise added depends on a series of factors. In some cases, the noise should be so high that in practice the or...
<p>If you define a uniform random distribution over an infinite domain, the probability of any value in the domain being chosen is infinitesimal. What you're asking for doesn't make any mathematical sense.</p>
python|numpy|random|range
5
369,498
30,073,257
python image processing with numpy and scipy
<p>I'm new to python image processing</p> <p>how can I write a code to read and display an image ?</p> <p>where the image should be saved in my pc in order to be displayed ?</p>
<p>It is a very basic question. Simple google search will give codes in almost any language. If you are starting with image processing I would suggest look at <code>Open CV</code>. This library provides all the functionality you need to perform image processing</p> <p>A sample code of opencv would be</p> <pre><code>i...
python-2.7|numpy
0
369,499
30,212,079
pandas - map nested dictionary values to dataframe column
<p>I'm going a little further <a href="https://stackoverflow.com/questions/29794959/pandas-add-new-column-to-dataframe-from-dictionary">this</a> previous question about mapping dictionary values to dataframes. I have a simple dataframe df like:</p> <pre><code>U,id 111,01 112,02 112,03 113,04 113,05 113,06 114,07 </cod...
<p>I'd flatten the dict to create a new dict and then you can call <code>map</code> as before:</p> <pre><code>In [44]: max_d={} for k,v in d.items(): max_d[k] = max(v, key=v.get) max_d Out[44]: {111: 'ar', 112: 'es', 113: 'es', 114: 'es'} In [45]: df['C'] = df['U'].map(max_d) df Out[45]: U id C 0 111 ...
python|pandas
6