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
354,500
63,470,659
Transforming Wide dataset to long format with multiple columns
<p>I have a dataset that looks like the following:</p> <pre><code>Name County Industry Jobs.2019 Jobs.2018 Establish.2019 Establish.2018 EPW.2019 EPW.2018 rows_0 Adams, OH Auto 1 2 3 4 5 6 row_1 Allen, OH Mfg 2 3 5 ...
<p>The answer is in your title: use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html" rel="nofollow noreferrer"><code>pd.wide_to_long</code></a>.</p> <pre><code>print (pd.wide_to_long(df, stubnames=[&quot;Jobs&quot;,&quot;Establish&quot;,&quot;EPW&quot;], ...
python|pandas|snowflake-cloud-data-platform
0
354,501
63,460,349
Compute rate of change from subset rows tagged by condition to the rest of the rows below the tagged one
<p>I have a dataframe:</p> <pre class="lang-python prettyprint-override"><code>import pandas as pd data = {'score': [1, 2, 4, 7, 11, 16, 22, 29, 37, 46], 'tag': [False, True, False, False, True, False, True, False, True, False] } df = pd.DataFrame (data, columns = ['score', 'tag']) </code></pre> <p>th...
<p>Here we need first create the <code>groupby</code> key with <code>cumsum</code> , the for each subgroup we need to <code>shift</code> the value by group</p> <pre><code>s1=df.tag.iloc[::-1].cumsum().iloc[::-1] s=df.tag.mul(df.score).groupby(s1).max().shift(-1) df['rate']=(df.score-s1.map(s))/s1.map(s) df Out[75]: ...
python|pandas|dataframe
3
354,502
63,347,149
pytorch dataset map-style vs iterable-style
<p>A map-style dataset in Pytorch has the <code>__getitem__()</code> and <code>__len__()</code> and iterable-style datasets has <code>__iter__()</code> protocol. If we use map-style, we can access the data with <code>dataset[idx]</code> which is great, however with the iterable dataset we can't.</p> <p>My question is w...
<p>I wrote a short post on how to use PyTorch datasets, and the difference between map-style and iterable-style dataset.</p> <p>In essence, you should use map-style datasets when possible. Map-style datasets give you their size ahead of time, are easier to shuffle, and allow for easy parallel loading.</p> <p>It’s a com...
pytorch
8
354,503
63,543,760
I am trying to execute a program but its give error based on wine datasets using neural networks
<p>I am trying to execute a program but its give error based on wine datasets using neural networks</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt from subprocess import check_output print(check_output([&quot;ls&quot;, &quot;../input&quot;]).decode(&quot;utf8&quot;)) </code></pr...
<p>A CalledProcessError will be raised if any non-zero exit code is returned by your called process.</p> <p>If that is okay in your python code, you can except the CalledProcessError and get any information from within its attributes especially the output attribute. (Look up this error in the <a href="https://docs.pyth...
python|neural-network|google-colaboratory|tensorflow-datasets
0
354,504
63,485,282
getting a sample from a dictionary
<p>I want to get a sample from a dictionary which holds image data. <code>Code 1</code> shows a simple example:</p> <p><strong>Code 1:</strong></p> <pre><code>import numpy as np a = dict(data_key_1=np.random.random((512, 512, 3)), data_key_2=np.random.random((512, 512, 3)), data_key_3=np.random.ran...
<p>You can't index a list with a dictionary.</p> <pre><code>for key in sample_keys: if key in a: a[key] # Now do any operation with it </code></pre> <p>Happy coding.</p>
python|dictionary|numpy-ndarray
1
354,505
63,523,810
Python pandas date_range with sampling assigned to each day separately
<p>I want to create date range between specific dates with a certain sampling within each day, but each day should start at midnight:</p> <pre><code>['2017-01-01 00:00:00', '2017-01-01 05:00:00','2017-01-01 10:00:00', '2017-01-01 15:00:00', '2017-01-01 20:00:00', '2017-01-02 00:00:00', '2017-01-02 05:00:00' ...] </code...
<p>Create hours range and then filter by modulo 5 by hours in indexing:</p> <pre><code>date1= '2017-01-01' date2= '2017-01-04' r = pd.date_range(date1,date2,freq='H') r = r[r.hour % 5 == 0] print (r) DatetimeIndex(['2017-01-01 00:00:00', '2017-01-01 05:00:00', '2017-01-01 10:00:00', '2017-01-01 15:00:0...
python|pandas|date|datetime
2
354,506
63,405,387
Creating a new column in a dataframe based on matches with another dataframe
<p>I have two dataframes:</p> <p>Dataframe 1:</p> <pre><code>ID MONTH 1 2010-01 1 2010-03 1 2010-04 2 2010-01 3 2010-01 3 2010-02 </code></pre> <p>Dataframe 2:</p> <pre><code>ID MONTH 1 2010-01 3 2010-02 </code></pre> <p>Is there a way to create a new column in Dataframe 1 based on row matches on both...
<p>Check with <code>merge</code> + <code>indicator</code>, return <code>both</code> will be <code>Yes</code>, <code>left_only</code> will be <code>No</code></p> <pre><code>s=df1.merge(df2,indicator=True,how='left') s['Match']=s.pop('_merge').map({'both':'Y','left_only':'N'}) s Out[18]: ID MONTH Match 0 1 2010...
python|pandas
3
354,507
63,496,407
How to count all the same size sequence of repeating value in a column
<p>I'm trying to transform a column that have several repeating values ​​into a dataframe that has one column for each unique value and the rows count the number of times that a same size repeating sequecence has occurs.</p> <p>Example: imagine the results of a sport team (win, draw, loss).</p> <pre><code>results = np....
<p>Do this with 2 groupbys. The first groups consecutive events. The second gets the frequency of those.</p> <pre><code>s = pd.Series(results) df = s.groupby(s.ne(s.shift()).cumsum()).agg(['size', 'first']) df.groupby([*df]).size() #size first #1 d 3 # l 3 # w 1 #2 d 1 # ...
python|pandas|pandas-groupby
2
354,508
63,407,428
Input arguments to CTC loss in TensorFlow
<p>I wanted to use CTC loss for a sequence model and decided to use Tensorflow API. But when I tried the ctc_loss function, there were 2 arguments label_length, logit_length I am unaware of.</p> <p>Can someone please give some details about what those parameters are?</p> <p>Thank you in advance.</p>
<p>Label_length is a tensor of length = <code>batch_size</code>, each of the values will denote the length of your labels.</p> <p>Logit_length is a tensor of length = <code>batch_size</code>, each of the values will denote the length of your inputs.</p>
tensorflow|neural-network|model|tensorflow2.0|loss-function
1
354,509
63,589,151
Normalize json data per level
<p>I'm struggling to normalize json files that I'm importing from coinmarketcap.com. <a href="https://drive.google.com/file/d/1ltBYT608E75L59KxVJdXMJDQ3F3Yg837/view?usp=sharinghttps://drive.google.com/file/d/1ltBYT608E75L59KxVJdXMJDQ3F3Yg837/view?usp=sharing" rel="nofollow noreferrer">Here's one of the json files</a>, ...
<ol> <li>turn <code>dict</code> into a <code>list</code> using a comprehension</li> <li>two times <code>json_normalize()</code> exploding list on first pass</li> </ol> <p>Results in data frame of 5 rows and 33 columns</p> <pre><code>import json with open(&quot;cmc_test_file.json&quot;) as f: d = json.load(f) d[&quot;d...
python|json|pandas
1
354,510
63,690,860
Pandas: How to find values that cross zero?
<p>This is my DataFrame</p> <pre><code> Date Time Value 16.02.2020 21:00:00 0.05012 16.02.2020 22:00:00 0.04285 16.02.2020 23:00:00 0.03559 17.02.2020 0:00:00 0.02833 17.02.2020 1:00:00 0.02107 17.02.2020 2:00:00 0.01380 17.02.2020 3:00:00 0.00654 17.02.2020 4:00:00 -0.00073 17...
<p>IIUC, you can try <code>np.sign</code> + <code>series.diff</code></p> <pre><code>out = df[np.sign(df['Value']).diff().fillna(0).ne(0)].copy() </code></pre>
python|pandas
4
354,511
63,348,959
How to loop through a pandas grouped time series?
<p>I have a dataframe like this:</p> <pre><code> datetime type d13C ... dayofyear week dmy 1 2018-01-05 15:22:30 air -8.88 ... 5 1 5-1-2018 2 2018-01-05 15:23:30 air -9.08 ... 5 1 5-1-2018 3 2018-01-05 15:24:30 air -10.08 ... ...
<p>Your code loops through a list of unique dates and filters the dataframe on each iteration.</p> <p>Pandas implemented this with <code>df.groupby()</code>. It can be used to loop and get each group or it can be combined with aggregations, function applications, and transformations. You can read more about it on the <...
python|pandas|time-series|pandas-groupby
2
354,512
63,531,538
Pytorch: Lower the parameters in U-net model
<p>can anyone give me some tips on how i would be able to lower the amount of parameters in the following U-net implementation. I'm having trouble with over-fitting on my training data and i would like to lower the parameters in order to see if it improves the validation data accuracy. Layers:</p> <p>First2D</p> <pre><...
<p>One way to decrease the number of parameters is to decrease the number of channels in the convolution. You wouldn't be able to change the number of model input and output channels, because they depend on the data, but you can change the number of intermediate channels.</p> <p>Remember that the output of one layer is...
python|deep-learning|pytorch|conv-neural-network
1
354,513
63,384,543
Image Classification, 3D black and white MRI data. Data Dimensionality Issues
<p>I'm trying to build a CNN that can classify 3D MRI files as being one of two classes, basically with disease or without. I've done a lot of googling and it seems like the consensus is that a 2D CNN would be best because the data is black and white and therefore has reduced dimensionality.</p> <p>I'm working on Googl...
<p>Welcome to Stack Overflow. For a 2D network, your input should have the shape <code>(batch_size, height, width, channels)</code>. You are correct in adding an extra dimension at the end of the array. That represents the grayscale color channel.</p> <p>You get the error</p> <pre><code>ValueError: Input 0 of layer seq...
python|tensorflow|keras|conv-neural-network|mri
1
354,514
63,389,282
How to implement seaborn lmplot to get a gridded plot containing each dataframe column?
<p>I have a dataset. Help to display graphs like <code>sns.lmplot</code> conveniently in the form of a 2 x 3 plot figure using seaborn or matplotlib. I try, but they are displayed in one column. And so and so I try, but it does not work. all tables contain the correlation of variables from &quot;SalePrice&quot;</p> <pr...
<ul> <li>In order to plot the data, the dataframe must be converted from a wide to long (tidy) format using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>pandas.DataFrame.stack</code></a> <ul> <li><code>SalePrice</code> must remain a col...
python|pandas|matplotlib|seaborn
0
354,515
63,367,517
how to convert object to int or float in pandas
<p>I am having the following data after I use df.info method on my loaded excel file</p> <pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 30000 entries, 1 to 30000 Data columns (total 25 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Unnamed: 0 30000 no...
<p>Let us try <code>to_numeric</code></p> <pre><code>df = pd.DataFrame({'1':['1','2'],'2':['a','b']}) df = df.apply(pd.to_numeric,errors='ignore') </code></pre> <p>Check</p> <pre><code>df.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 2 entries, 0 to 1 Data columns (total 2 columns): # Column Non-Nu...
python|pandas
3
354,516
63,569,417
Pandas Date Range Overlap Aggregation
<p>I've been trying to learn how to use Pandas, but I'm thoroughly confused about where in the API to find methods that can aggregate data conditionally based on sign across date ranges. I have a data frame like so:</p> <pre><code>Date        Change  2010-08-25    0.08 2010-08-26   -0.22 2010-08-27    0.04 2010-08-30  ...
<p>Here is one way, IIUC (comments are embedded with the code below):</p> <pre><code>from io import StringIO import pandas as pd data = '''Date Change 2010-08-25 0.08 2010-08-26 -0.22 2010-08-27 0.04 2010-08-30 -0.08 2010-08-31 -0.11 2020-08-18 0.96 2020-08-19 -1.79 2020-08-20 5.04 2020-08-...
python|pandas|dataframe
0
354,517
63,571,190
Best way to CONVERT python code(with Tensorflow) to Android APK
<p>I'm python user and very weak in Java for android APK coding.</p> <p>Now I want to my python OCR code(Package with so many *.py) to my companies APK.</p> <p>I heard tensorflow maybe converted TF-lite for APK...</p> <p>I searched kivy but it seems just a tools for android new app builder, not converting exist *.py co...
<p>If all you need is to create an OCR app and don't have the need to use a custom OCR model built with TensorFlow, I'd suggest you to just use an existing model, as they exist and are super simple to use in Android.</p> <p>I recommend you to use ML Kit's Text Recognition Package and API: <a href="https://developers.go...
python|android|tensorflow
2
354,518
63,673,211
Pandas - Count consecutive rows with column values greater than a threshold limit
<p>I have a dataframe where the speed of several persons is recorded on a specific time frame. Below is a simplified version:</p> <pre><code>df = pd.DataFrame([[&quot;Mary&quot;,0,2.3], [&quot;Mary&quot;,1,1.8], [&quot;Mary&quot;,2,3.2], [&quot;Mary&quot;,3,3.0], [&quot;Mary&quot;,4,2.6], [&quot;Mary...
<p>So here's my go:</p> <pre class="lang-py prettyprint-override"><code>df['over2'] = df['speed (m/s)']&gt;2 df['streak_id'] = (df['over2'] != df['over2'].shift(1)).cumsum() streak_groups = df.groupby(['name','over2','streak_id'])[&quot;time&quot;].agg(['min','max']).reset_index() positive_streaks = streak_groups[strea...
python|pandas|count
3
354,519
63,456,963
Other compression methods for Federated Learning
<p>I noticed that the Gradient Quantization compression method is already implemented in TFF framework. How about non-traditional compression methods where we select a sub-model by dropping some parts of the global model? I come across the &quot;Federated Dropout&quot; compression method in the paper &quot;Expanding th...
<p>Currently, there is no implementation of this idea available in the TFF code base.</p> <p>But here is an outline of how you could do it, I recommend to start from <a href="https://github.com/tensorflow/federated/tree/v0.16.1/tensorflow_federated/python/examples/simple_fedavg" rel="nofollow noreferrer"><code>examples...
tensorflow-federated
3
354,520
63,738,941
Running Tensorflow frozen_graph through opencv fail with dim denoted by -1 in function 'computeShapeByReshapeMask'
<p>I am make an AI that have to differentiate one bottle form from any other forms and run the prediction through opencv</p> <p>the learning (running the learning file) go very well but when I try to run the prediction with openCV I always get the same error</p> <p>What am I doing wrong?</p> <p>The error when launching...
<p>I had the same issue for my TensorFlow model, and was able to solve it through the following post:</p> <p><a href="https://stackoverflow.com/questions/65587336/how-to-convert-pytorch-graph-to-onnx-and-then-inference-from-opencv">How to convert PyTorch graph to ONNX and then inference from OpenCV?</a></p> <p>In funct...
python|tensorflow|opencv|keras
0
354,521
63,421,470
The implicit shape can't be a fractional number
<p>I am trying to create a label in TensorFlow. This is <a href="https://imgur.com/a/saSfA9S" rel="nofollow noreferrer">image</a> inside the code below.</p> <pre class="lang-js prettyprint-override"><code>async function main(){ const model = await mobilenet.load(); const classifier = await knnClassifier.create(...
<p>I had the same problem as yours just last night. I was wondering why it would not work with PNG images but JPG images work just fine. As it turned out, it has something to do the <a href="https://stackoverflow.com/a/60128827/14580435">number of channels</a> used when decoding the image from buffer.</p> <p>When we us...
node.js|tensorflow|tensorflow.js
2
354,522
63,479,413
Filtering a row value if it already included in the previous
<p>I am having some problems to check if an element of a list in one column match itself from another column.</p> <p>Specifically I have a dataset such this:</p> <pre><code>Student Student representatives Mary Jane [Mary Jane, Lucas] Christopher [Matt] Jonathan [Luke] Barbara [Barb...
<p>here is a working bit from this newbie - hope it helps --- thought I agree it is not the best solution...</p> <p>lets say</p> <pre class="lang-py prettyprint-override"><code>student = ['Mary Jane', 'Christopher', 'Jonathan', 'Barbara'] student_rep = [['Mary Jane', 'Lucas'], ['Matt'], ['Luke'], ['Barbara', 'Martin']]...
python|pandas
1
354,523
63,482,317
taking tuple in function argument and generate an array
<p>i need to Create a function that takes dimensions as tuples e.g.(3, 3) and a numeric value and returns a numpy array of the given dimension filled with the given value for this i have written this below code but instead of generating an array it is showing only one number , could you please guide me where i am wrong...
<p>As I mentioned in the comments, it was caused by a typo. This does sound like a good use of <code>itertools.starmap</code>:</p> <pre><code>from itertools import starmap import numpy as np func = lambda a, b: np.full(a, b) list(starmap(func, [((5, 5), 3)])) </code></pre> <pre><code>[array([[3, 3, 3, 3, 3], ...
python|arrays|numpy
1
354,524
63,569,581
Filter a list of words using Json File
<p>My Json File:</p> <pre><code>{ &quot;countries&quot;: [ &quot;Australia&quot;, &quot;France&quot;, &quot;Belgium&quot; ] } </code></pre> <p>I have a <code>index_list = ['Germany', 'USA, 'Ireland, Australia, &quot;France&quot;, Belgium, &quot;Kenya&quot;, &quot;Spain&quot;</code> I want to filter out all the co...
<p>Instead of filter you can loop through all elements and check if they exist in list from json</p> <pre><code>import json data = {&quot;countries&quot;: [&quot;Australia&quot;, &quot;France&quot;, &quot;Belgium&quot;]} index_list = [&quot;Germany&quot;, &quot;USA&quot;, &quot;Ireland&quot;, &quot;Australia&quot;, &...
python|python-3.x|pandas
1
354,525
63,647,333
How to calculate weighted average on a traingular similarity matrix
<p>I have a triangular similarity matrix like this.</p> <pre><code>[[3, 1, 2, 0], [1, 3, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]] </code></pre> <p>How do I calculate a weighted average for each row while discarding the zero elemets?</p>
<p>You could add along the second axis, and divide by the <code>sum</code> over the amount of non-zero values per row. Then with <code>where</code> in <a href="https://numpy.org/doc/stable/reference/generated/numpy.divide.html" rel="nofollow noreferrer"><code>np.divide</code></a> you can divide <em>where</em> a conditi...
python|numpy|cosine-similarity
2
354,526
63,322,930
Pandas dataframe replace blank space with "0"
<p>My dataframe look like this:</p> <pre><code> Dividends Volume Close Company Sector Year 2009 0.280000 10.35 ABC Finance 2010 0.280000 5.264694e+06 9.88 ABC Finance 2011 0.560000 5.153132e+06...
<p>I believe this is what you're looking for:</p> <pre><code>df = df.replace(&quot;&quot;, 0) </code></pre>
pandas|replace|nan|zero|fillna
1
354,527
63,429,795
Sum of only certain columns in a pandas Dataframe
<p>I have a dataframe similar to the one below. I need to add up the sum of only certain columns: Jan-16, Feb-16, Mar-16, Apr-16 and May-16. I have these columns in a list called months_list</p> <pre><code>-------------------------------------------------------------------------------------- | Id | Name ...
<p>You are using the wrong value of <code>axis</code> parameter.</p> <pre><code>`axis=0`: Sums the column values `axis=1`: Sums the row values </code></pre> <p>Assuming your df to be:</p> <pre><code>In [4]: df Out[4]: Id Name Jan-16 Feb-16 Mar-16 Apr-16 May-16 0 4674393 John Miller 0 ...
python|pandas|dataframe
4
354,528
63,473,971
TypeError: reshape(): argument 'input' (position 1) must be Tensor, not numpy.ndarray
<p>I am a high school student who doesn't having much experience in using PyTorch and LIME. I'm having a lot of trouble with my image shape. Initially my image shape was (3,224,224), however the LIME algorithm only works with images that are in this shape(...,...,3). As a result, I tried transposing the image earlier. ...
<p>You are passing NumPy array instead of <code>torch.tensor</code> in the <a href="https://pytorch.org/docs/stable/generated/torch.reshape.html#torch-reshape" rel="nofollow noreferrer"><code>torch.reshape</code></a> method. So better to convert the input to <code>torch.tensor</code> in the beginning</p> <p>therefore, ...
pytorch|lime
1
354,529
63,356,406
Names in Python dataframe which can have both values
<p>I have a dataframe like this one</p> <pre><code>df.head() NAME DATE FLAG Test1 1 April 2020 Before Test2 20 May 2020 Before Test1 28 May 2020 Before Test3 2 June 2020 After Test2 3 June 2020 After </code></pre> <p>I want to create another dataframe which has the...
<p>You' just need to do two filters; The first filter to check the <code>flag</code>, and then the second filter to remove anything that has an after flag:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd ...
python|pandas|dataframe
1
354,530
63,618,116
Panda's MERGE on customerEmail column having duplicates
<p>Aim is to detect fraud from this dataset.</p> <p>I have two dataframes with columns as:</p> <p>DF1[customerEmail, customerphone, customerdevice,customeripadd,NoOftransactions,Fraud] etc (168,11)</p> <p>DF2[customerEmail,transactionid, payment methods,orderstatus] etc (623,11)</p> <p>The customerEmail column is commo...
<p>Maybe you should consider a different value for the option &quot;how&quot;. By default, it is &quot;inner&quot; meaning deleting all rows without any match</p> <p>Maybe the option &quot;right&quot;, would help you, as then DF2 is the reference and DF1 is join to DF2.</p>
python|pandas|merge|data-science
0
354,531
63,380,568
pandas fill missing cells with similar group data
<p>I'm trying to fill missing data with data found in other fields, for example, I have a table:</p> <pre><code>Brand Model Make Toyota Corolla Japan Toyota Crescida Japan Toyota Land Cruiser Ford Escape America Ford Explorer America Ford Edge Ford Focus </code></pre> <p>I know from...
<p>You can use <code>df=df1[['Brand','Make']].groupby(['Brand']).agg(lambda x:x.value_counts().index[0]).reset_index()</code> to get the common occurences for the make column on the basis of Brand. After that you can use the following code</p> <pre><code>for index,value in enumerate(df1['Make']): if value==None: ...
python|pandas
1
354,532
63,477,121
How to predict next word using Embedding
<p>I want to predict the next word in Tensorflow. Before, I was saving one vector for each word as much as all the unique words, but this takes up a lot of memory, so I want to use embedding for this, but I'm a little confused about the dimensions of the vectors because in this method We use Integer numbers instead of ...
<p>I think everything is true except loss function. When you are using unique numbers for unique words Instead of one-hot vector for any unique words, you must use <code>sparse_categorical_crossentropy</code> instead of <code>categorical_crossentropy</code> for loss function:</p> <pre><code>model.compile(loss='sparse_c...
python|tensorflow|nlp
0
354,533
63,704,937
TensorBoard showing lots of 'nodes' from previous models
<p>I am training a model on the MNIST data and I am using tensorboard to visualise the training and validation loss.</p> <p>Here is the code for my current model I am trying:</p> <pre><code>model=tf.keras.models.Sequential() #callback=tf.keras.callbacks.EarlyStopping(monitor='accuracy', min_delta=0, patience=0, verbose...
<p>The second branch is not a graph in itself but rather it is a <strong>subgraph</strong>.<br /> Tensorflow build graphs of the operation it performs in order to speed up the execution of code. If you click on those you can see they are functions that are utilized by the batch normalization layer, not the layer itself...
python|tensorflow|keras|tensorboard
1
354,534
63,354,735
pandas timestamps comparison doesn`t work properly
<p>I have a dataframe indexed by timestamps:</p> <pre><code> A t 2020-07-27 11:00:28.575000+01:00 0 2020-07-27 11:00:43.775000+01:00 1 2020-07-27 11:00:44.175000+01:00 2 2020-07-27 11:00:44.475000+01:00 3 2020-07-27 11:00:45.575000+01:00 4 </code><...
<p>I just checked and it seems like the following works for me:</p> <pre><code>start_time = datetime.datetime(2020, 7, 27, 11, 0,) df.index[0] &gt; pd.Timestamp(start_time, tz=&quot;Europe/London&quot;) &gt;&gt;&gt; True </code></pre>
python|pandas|datetime
0
354,535
63,387,295
Python: How to read a txt file next line by splitting its column number
<p>I have some data and I am trying to read a txt file and read it line by line in excel by implementing a specific column number. For example:</p> <pre><code>0.12345 0.14251 0.12155...... 0.25541 </code></pre> <p>And say after filling up 1000th column I want to put the next data into the next line:</p> <pre><code>0.12...
<p>Here is a solution that allows you to split a string by specific number of columns. Hopefully you can adapt this code to your needs. I got the idea from here: <a href="https://stackoverflow.com/questions/1621906/is-there-a-way-to-split-a-string-by-every-nth-separator-in-python">Is there a way to split a string by ev...
python|pandas
0
354,536
63,670,330
How to convert to log base 2?
<p>How can i convert the following code to log base 2?</p> <pre><code>df[&quot;col1&quot;] = df[&quot;Target&quot;].map(lambda i: np.log(i) if i &gt; 0 else 0) </code></pre>
<p>I think you just want to use <a href="https://numpy.org/doc/stable/reference/generated/numpy.log2.html#numpy.log2" rel="nofollow noreferrer"><code>np.log2</code></a> instead of <a href="https://numpy.org/doc/stable/reference/generated/numpy.log.html#numpy.log" rel="nofollow noreferrer"><code>np.log</code></a>.</p>
python|numpy|math|logarithm
2
354,537
63,606,248
How to take returned values from a function and put them on a dataframe column
<p>This is the start and returned values of the function I used to get some values:</p> <pre><code>def gal_uvw(distance=None, lsr=None, ra=None, dec=None, pmra=None, pmdec=None, vrad=None, plx=None): return (u,v,w) </code></pre> <p>I used column values of a dataframe(df) as variables of this function, and got a li...
<p>You should be able to assign it directly from unpacked variables as long as the length of <code>u</code>, <code>v</code> and <code>w</code> are the same as your dataframe.</p> <pre><code>import pandas as pd def foo(): return (0, 9, 8, 7, 6), (0, 91, 81, 71, 61), (0, 92, 82, 72, 62) df = pd.DataFrame({'A': [1, ...
python|pandas|dataframe
1
354,538
63,559,473
How to calculate total length of process until it changes using two columns in python?
<p>Here is a snippet of data-frame which looks like this (original data frame contains 8k rows):</p> <pre><code> User State change_datetime endstate 0 100234 XIM 2016-01-19 17:03:12 Inactive 1 100234 Active 2016-01-28 17:17:15 XIM 2 100234 Active 2016-02-16 17:57:50 NaN 3 100234 ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.eq.html" rel="nofollow noreferrer"><code>Series.eq</code></a> to create a boolean mask <code>m</code> then filter the dataframe using this mask and use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Data...
python|pandas|numpy|dataframe|date
2
354,539
63,365,330
Transform datetime column
<p>I dont know how to transform data in my column 'datetime' with this format:</p> <pre><code>2020-01-01T00:00:00.000+01:00 </code></pre> <p>in to:</p> <pre><code>Jan-2020 </code></pre> <p>I've tried with this:</p> <pre><code>works_data[&quot;datetime&quot;] = pd.to_datetime(works_data[&quot;datetime&quot;], utc=True)....
<p>For a fixed UTC offset: localize the date/time column to <code>None</code> before <code>strftime</code>:</p> <pre><code>pd.to_datetime(&quot;2020-01-01T00:00:00.000+01:00&quot;).tz_localize(None).strftime('%b-%Y') Out[47]: 'Jan-2020' </code></pre> <p>See also <a href="https://stackoverflow.com/a/62656878/10197418">m...
python|python-3.x|pandas|date|datetime
1
354,540
63,693,647
Matplotlib: How to plot Time Series on top of Scatter Plot
<p>I have found solutions to similar questions, but they all produce odd results.</p> <p>I have a plot that looks like this:</p> <p><a href="https://i.stack.imgur.com/IhbuT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IhbuT.png" alt="enter image description here" /></a></p> <p>generated using this...
<p>Is your str ange line is not due to the fact you didn't sort the df before to plot it:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np dft=dft.sort_values(by=['end_date']) x = dft['pct'] u = dft['Trump Odds'] t = list(pd.to_datetime(dft['end_date'])) plt.hold(True) plt.subplot2grid((1, 1), (0, 0)...
python|pandas|matplotlib
1
354,541
63,656,333
'Reduction' parameter in tf.keras.losses
<p>According to the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/losses/Reduction" rel="nofollow noreferrer">docs</a>, the <code>Reduction</code> parameter takes on 3 values - <code>SUM_OVER_BATCH_SIZE</code>, <code>SUM</code> and <code>NONE</code>.</p> <pre><code>y_true = [[0., 2.], [0., 0.]] y_pred = ...
<p>Your assumption is correct as far as I understand.</p> <p>If you check the github [keras/losses_utils.py][1] lines 260-269 you will see that it does performs as expected. <code>SUM</code> will sum up the losses in the batch dimension, and <code>SUM_OVER_BATCH_SIZE</code> would divide <code>SUM</code> by the number o...
python|tensorflow|keras|tensorflow2.0
4
354,542
63,522,955
Understanding Memory Usage by PyTorch DataLoader Workers
<p>When running a PyTorch training program with <code>num_workers=32</code> for <code>DataLoader</code>, <code>htop</code> shows 33 python process each with 32 GB of <code>VIRT</code> and 15 GB of <code>RES</code>.</p> <p>Does this mean that the PyTorch training is using 33 processes X 15 GB = 495 GB of memory? <code>...
<blockquote> <p>Does this mean that the PyTorch training is using 33 processes X 15 GB = 495 GB of memory?</p> </blockquote> <p>Not necessary. You have a worker process (with several subprocesses - workers) and the CPU has several cores. One worker usually loads one batch. The next batch can already be loaded and ready...
python|python-3.x|ubuntu|deep-learning|pytorch
1
354,543
63,440,049
Change pandas data frame to add max column -> maximum value for each month of the year from a data frame in pandas. How can I do this?
<p>So I have a data frame structure looking like (Date, value, month, year) &lt;- the month and year are extracted from data frame. I want to get the maximum value of 'value' column in another column 'max', for each month of a year. There are more than one 'date' belonging to the same 'month' and 'year'. For example,</...
<p>Use <code>pd.Grouper</code> to group by month and <code>transform</code>:</p> <pre><code>df[&quot;Date&quot;] = pd.to_datetime(df[&quot;Date&quot;]) df[&quot;max&quot;] = df.groupby(pd.Grouper(key=&quot;Date&quot;, freq=&quot;M&quot;))[&quot;value&quot;].transform(&quot;max&quot;) # or df.groupby(df[&quot;Date&quot...
python|pandas|dataframe|date|google-colaboratory
3
354,544
63,333,108
Python - produce conditional average of variable 1 based on variable 2 with numpy?
<p>I'm trying to make some basic plots so I can better understand what is happening in my data. Currently 1 have 4 variables each with 200*387 data points. I've stored everything in a 3D array, with the 3rd dimension representing different variables associated with the data.</p> <p>Currently I have produced some scatte...
<p>Thank you for the responses. Re-reading my question I've realised that it was pretty poorly worded, so my apologies for that.</p> <p>I found my solution, it was pretty simple in the end. There was no need to use pandas and change data type from arrays to dataframes. I ended up just using the <a href="https://docs.sc...
python|python-3.x|pandas|numpy|matplotlib
-1
354,545
63,685,377
If statement comparing numpy array raised ValueError
<p>I have two arrays. Both are 1D. However, I am getting the following Value Error. Below is what I tried.</p> <pre><code>R=np.arange(30,50,1) T=np.arange(70,90,1) H=[] if (T &gt; 8) and (R&gt;10): H.append(0.5 * (T + 61. + (T - 68.) * 1.2 + R * 0.094)) else: H.append(0 * 2) </code></pre> <pre><code>ValueError...
<p>Like the above answer states, you can use all or any. The fix using any is:</p> <pre><code>if any(t &gt; value for t in T) and any(h &gt; value for h in H): H.append(0.5 * (T + 61. + (T - 68.) * 1.2 + R * 0.094)) else: H.append(0 * 2) </code></pre> <p>The python interpreter needs 1 value at a time so that it c...
python|numpy|valueerror
0
354,546
63,542,819
Pandas - Loop Control - Control the behavior of loop based on column value comparison
<p>Let's say I have a Pandas DataFrame as below:</p> <pre><code>Row | Column1 | Column2 | Column3 0 | abc | 10 | NY 1 | abc | 20 | NY 2 | abc | 15 | CA 3 | xyz | 10 | RI 4 | xyz | 30 | NV 5 | lmn | 15 | MN </code></pre> <p>Now, I want to do multiple operations on values of column2 and column3 but only when the value of...
<ol> <li>You can use <code>.shift()</code> to compare values in columns row-wise.</li> <li>You can use <code>np.where()</code> to change the data depending on conditions and operations.</li> </ol> <hr /> <p>First, let's create the condition with:</p> <p><code>condition = (df.shift()['Column1'] != df['Column1']) &amp; d...
python|pandas|loops|comparison|row
0
354,547
63,576,119
The easiest way to read an Access table with Pandas?
<p>I have an access database name DB_IMPORT_2020.accdb. It contains only one table named DB_IMPORT_2020_PM. I've been struggling a lot trying to import that table to Pandas. What I've been doing so far is:</p> <pre><code># define components of our connection string driver = '{Microsoft Access Driver (*.mdb, *.accdb)}' ...
<p>The easiest way to work with an Access database and pandas is to use the <a href="https://pypi.org/project/sqlalchemy-access/" rel="nofollow noreferrer">sqlalchemy-access</a> dialect (which I maintain).</p> <blockquote> <p>Does anyone know a simpler way to read data in a table of Access with Pandas?</p> </blockquote...
python|pandas|ms-access|pyodbc
2
354,548
63,472,480
Pandas dataframe.loc : what does "Boolean list with the same length as the row axis" mean?
<p>Pandas documentation has this <code>Boolean list with the same length as the row axis</code> example, like so:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame([[1, 2], [4, 5], [7, 8]], ... index=['cobra', 'viper', 'sidewinder'], ... columns=['max_speed', 'shield']) &gt;&gt;&gt; df max_speed shie...
<p><code>df[[False,False,True]]</code> returns the same as <code>df.loc[[False, False, True]]</code>.</p> <p><code>df[[False,False,True]]</code> is more intuitive &amp; can be interpreted as: don't return first &amp; second (ie first &amp; second <code>False</code>), return third (ie third is <code>True</code>) row.</p...
python|python-3.x|pandas|dataframe
2
354,549
63,656,687
python connectvity of mysql with csv
<p>&quot;text&quot; and &quot;imdburl&quot; columns are common in all tables<Br>but &quot;year&quot; is only present in one table when i add year it says unknown column &quot;year&quot;<Br> can anyone tell me how can i first check if this column exist in table then add its add otherwise just display N\A <Br></p> <pre>...
<p>If I understand you correctly you only have a single table that needs the year column, so assuming that <code>yeartable</code> would be the name of that table</p> <pre><code>import pymysql import pandas as pd conn=pymysql.connect(host=&quot;localhost&quot;,user=&quot;root&quot;,password=&quot;&quot;,db=&quot;bulk&qu...
python|mysql|python-3.x|pandas|csv
0
354,550
63,728,688
how do i remove <built-in function array> from the output
<p>This below is a part of my program how do I remove the from the output of this ? can it be removed?</p> <p>or is it built-in? because I intend to save it as a text file after I convert it to a 2d matrix.</p> <p>Also, I want to reshape the 1D array &quot;final&quot; as a 2D 30*5 matrix how do I do it (of course ther...
<p><code>numpy.array</code> is a function, <code>final = numpy.array</code> is assigning the function itself to the variable. Calling <code>final()</code> now does the same thing as calling <code>numpy.array()</code>.</p> <p>If you want to create an initial empty numpy array you should do something like <code>final = n...
python|arrays|numpy
2
354,551
63,390,694
Filter strings that don't follow regex pattern in python
<p>I want to filter strings from a pandas dataframe which don't follow a certain pattern. But I only get a empty Dataframe</p> <p>My Code</p> <pre><code>l = ['Dubai', 'St. Petersburg', 'Aachen', '21323', '123134', 'Klaus@facebook.com'] l = pd.DataFrame(l) pattern = re.compile(&quot;([A-Z])\w+|(\w[A-Z\u00E4-\u02AF])\w+...
<p>The <code>df.filter()</code> method filters based on the name of rows/columns, not their content; as stated in the documentation: “Note that this routine does not filter a data frame on its contents. The filter is applied to the labels of the index.”</p> <p>To do what you want you can define a function like this tha...
python|regex|pandas
0
354,552
21,462,876
Pandas Date Format Does not convert date
<p>I'm using Pandas version 0.12.0 to import a csv file with dates</p> <p>The dates are in the following format 'SEP2005'</p> <p>using pandas to read the csv file:</p> <pre><code>import pandas as pd DF = pd.read_csv('mydata.csv') mydata.head() Out[40]: Date Quantity 0 APR2002 282.0000 1 APR2002 ...
<p>You could try</p> <pre><code> pd.to_datetime(mydata.pop('Date'), format="%b%Y") </code></pre> <p>but that would expect the date to appear like <code>Apr2002</code> (note not all caps).</p> <p>You can specify a datetime format using the format string, and the format string will accept strftime arguments (defined <...
python|datetime|pandas
2
354,553
21,509,466
How to generate continuous record from incomplete data in Pandas Dataframe
<p>Ok I have a dataset regarding game outcomes that is incomplete and I want to generate a plot with either the data present or zero values for the players that have no data in that game. Furthermore I want to add the data present via a list: some players are attackers and some defenders My data is like this:</p> <p><...
<p>This is a bit messy, but certainly doable.</p> <p>First of all, you'll need to <code>reset_index()</code> on <code>df</code>, to make grouping easier. <code>Groupby</code> doesn't handle grouping on an index <em>and</em> a column at the same time gracefully (<a href="https://github.com/pydata/pandas/issues/5677" re...
python|python-3.x|pandas|dataframe|missing-data
2
354,554
21,502,851
How to find parts of elements in NumPy array
<p>I have a NumPy array with different length string elements:</p> <pre><code>array(['*,V*,UV,**,a2*,IR' , 'SB*,V*,UV,**,*,a2*,IR' , '*,V*,a2*' , ...]) </code></pre> <p>Each element is a set of abbreviations separated by comma. How to find elements (and their indices) where one of abbreviations is equal ** (double as...
<p>First off, numpy arrays aren't a good data structure for what you're doing. </p> <p>You're either going to be using a fixed-length string array (which is memory-inefficient, but can be fast) or an object array (which is inefficent for many short strings, and is generally fairly slow). Lists are a much more flexib...
python|numpy
2
354,555
21,627,926
Find all indices of maximum in Pandas DataFrame
<p>I need to find all indices where the maximum value (per row) is obtained in a Pandas DataFrame. For instance, if I have a dataFrame like this:</p> <pre><code> cat1 cat2 cat3 0 0 2 2 1 3 0 1 2 1 1 0 </code></pre> <p>then the method I am looking for would yield a result like:<...
<p>Here is the information, in a different data structure:</p> <pre><code>In [8]: df = pd.DataFrame({'cat1':[0,3,1], 'cat2':[2,0,1], 'cat3':[2,1,0]}) In [9]: df Out[9]: cat1 cat2 cat3 0 0 2 2 1 3 0 1 2 1 1 0 [3 rows x 3 columns] In [10]: rowmax = df.max(axis=1) </code></pre...
python|pandas
4
354,556
21,615,158
reshaping a data frame in pandas
<p>Is there a simple way in pandas to reshape the following data frame:</p> <pre><code>df = pd.DataFrame({'n':[1,1,2,2,1,1,2,2], 'l':['a','b','a','b','a','b','a','b'], 'v':[12,43,55,19,23,52,61,39], 'g':[0,0,0,0,1,1,1,1] }) </code></pre> <p>to...
<pre><code>In [75]: df['ln'] = df['l'] + df['n'].astype(str) In [76]: df.set_index(['g', 'ln'])['v'].unstack('ln') Out[76]: ln a1 a2 b1 b2 g 0 12 55 43 19 1 23 61 52 39 [2 rows x 4 columns] </code></pre> <p>If you need that ordering then:</p> <pre><code>In [77]: df.set_index(['g', 'l...
python|pandas|dataframe|reshape
3
354,557
21,918,267
Convert decimal range to Numpy array, with each bit being an array element
<p>I have created a small function that takes as input an integer, <code>length</code>, and returns a <code>numpy</code> <code>array</code> of the binary representation of all <code>2**length</code> integer numbers in the range <code>[0:2**length-1]</code>.</p> <pre><code>import numpy as np def get_bitstrings(length)...
<p>You can use NumPy's broadcasting and vectorized operations to do this fairly efficiently:</p> <pre><code>&gt;&gt;&gt; from numpy import arange, newaxis &gt;&gt;&gt; powers_of_two = 2**arange(4)[::-1] &gt;&gt;&gt; (arange(2**4)[:, newaxis] &amp; powers_of_two) / powers_of_two array([[0, 0, 0, 0], [0, 0, 0, 1]...
python|numpy
4
354,558
24,632,813
plot the mean of grouped dataframe
<p>i tried the following code on a multiindexed dataframe: data.header =['name', 'pH', 'salt', 'id'] for grp,val in data.df.groupby(level = data.header):</p> <pre><code> print(val['concentration']) </code></pre> <p>and i get the output:</p> <pre><code>name pH salt id sample 7.5 50 1 0.22923...
<p>Ok, this solution works:</p> <pre><code>df = data.df.groupby(level=data.header).aggregate(np.mean).copy() </code></pre> <p>and from here on i can do the desired plots etc.</p> <pre><code>for grp, val in df.groupby(level=data.header[0:-1])['concentration']: #print(val) plt.plot(val,'o') </code></pre>
python|pandas
0
354,559
24,579,942
wav file generated from numpy is not audible (complete silence)
<p>I have a numpy array that represents audio data(<code>dtype</code> is <code>np.int16</code>). Here is a plot of the audio data(me saying "one, two"): <img src="https://i.stack.imgur.com/CxmBb.png" alt="audio data"></p> <p>the sampling rate is <strong>100HZ</strong>. I saved this array into a wav file. However, the ...
<p>With a sampling frequency of 100Hz the highest audible frequency you get is 50Hz.</p> <p>The range of human hearing is from about 20 to about 20000Hz.</p> <p>For "telephone quality" you need 8000Hz and for "cd quality" you need 44100Hz (that is the standard sampling frequency for consumer audio).</p>
python|audio|numpy|scipy|wav
2
354,560
24,459,998
Pandas not detecting the datatype of a Series properly
<p>I'm running into something a bit frustrating with pandas Series. I have a DataFrame with several columns, with numeric and non-numeric data. For some reason, however, pandas thinks some of the <em>numeric</em> columns are non-numeric, and ignores them when I try to run aggregating functions like <code>.describe()</c...
<p>It might be because the <code>ND_Offset</code> column (what I call <code>A</code> below) contains a non-numeric value such as an empty string. For example,</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({'A': [0.36, ''], 'B': [111, 81]}) print(df['A'].describe()) # count 2.00 # unique ...
pandas|type-conversion|series
0
354,561
30,247,397
Break pandas DataFrame column into multiple pieces and combine with other DataFrame
<p>I have a table of phrases and I have a table of individual words that make up these phrases. I want to break my phrases up into individual words, gather and reduce information about these individual words and add as a new column in my phrase data. Is there a smart way to do this using pandas DataFrames?</p> <pre>...
<p>You could use</p> <pre><code>freq = df_onegram.set_index(['onegram'])['frequency'] sum_freq_onegrams = df_multigram['multigram'].str.split().apply( lambda x: pd.Series(x).map(freq).sum()) </code></pre> <p>which yields</p> <pre><code>In [43]: sum_freq_onegrams Out[45]: 0 60 1 25 2 15 Name: multigram,...
python|pandas
3
354,562
29,944,652
Partition pandas .diff() in multi-index level
<p>My question relates to calling .diff() within the partition of a multi index level</p> <p>In the following sample the output of the first </p> <p>df.diff() is </p> <pre><code> values Greek English alpha a NaN b 2 c 2 d 2 beta e...
<p>Just <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html#pandas.DataFrame.groupby" rel="noreferrer"><code>groupby</code></a> by <code>level=0</code> or 'Greek' if you prefer and then you can call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dif...
pandas|multi-index
21
354,563
30,258,974
Subtracting group specific value from rows in pandas
<p>In Pandas I have a data frame consisting of two groups with several samples in each group. Each group has an internal reference value that I want to subtract from all the sample values within that group. </p> <pre><code>s = u"""Group sample value group1 ref1 18.1 group1 smp1 NaN group1 smp2 ...
<p>Group your dataframe by <code>sample</code> column. Then iterate through each group and get the <code>ref</code> sample value. Then subtract with the entire column.</p> <pre><code>&gt; df = pd.read_csv(io.StringIO(s), sep='\s+') &gt; df['diff'] = 0 &gt; df_group = df.groupby('Group') &gt; for index, group in df_gro...
python|pandas|row|calc
0
354,564
30,035,052
pandas - Inconsistent behavior when applying timeseries operations to a multi-indexed DataFrame
<p>This might be a potential bug: doing grouped timeseries operations fails silently on a multi-indexed DataFrame.</p> <pre><code>import pandas as pd import pandas.io.data as web # Get some market data df = web.DataReader(['AAPL', 'GOOG'], 'yahoo', pd.Timestamp('2013'), pd.Timestamp('2014')).to_frame() df.index.names...
<p>This was indeed a bug, and has been fixed: <a href="https://github.com/pydata/pandas/issues/10063" rel="nofollow">https://github.com/pydata/pandas/issues/10063</a></p>
python|pandas
0
354,565
29,870,229
How do I push coordinates from a pandas dataframe to into a List?
<p>I have a pandas dataframe of x y coordiantes like so;</p> <pre><code>import pandas as pd coords = pd.read_csv("covariates/coords.csv") print coords.head(n=5) Coordinates x y 0 434483.347684 1873512.572689 1 433703.881013 1874208.610947 2 433087.930224 1874647.987855 3 432620.418...
<p>Use could use <code>df.values.tolist()</code> ?</p> <pre><code>In [21]: df.values.tolist() Out[21]: [[434483.34768400004, 1873512.572689], [433703.88101300003, 1874208.610947], [433087.93022399995, 1874647.987855], [432620.418522, 1875015.8017799999], [432623.66683500004, 1875078.63057]] </code></pre> <p><code...
python|pandas
1
354,566
30,132,636
Geocoding error with geopandas and geopy
<p>Per the geopandas <a href="http://geopandas.org/user.html#geopandas-functions" rel="nofollow">docs</a> I'm trying to geocode a list of strings, but I'm getting an error. </p> <p>My env</p> <pre><code>import geopandas as gdp from geopandas.geocode import geocode import geopy import sys print(sys.version) print (g...
<p>It doesn't matter whether or not it <em>uses</em> <code>MapQuest</code>; geopandas can't build that dictionary unless the name exists. geopy removed that coder in <a href="https://github.com/geopy/geopy/commit/6f406de389ef3747d902131533a879a5031f1e5a" rel="noreferrer">this commit</a>:</p> <blockquote> <p>MapQues...
python|python-3.x|geopy|geopandas
6
354,567
30,059,260
Python/Pandas: counting the number of missing/NaN in each row
<p>I've got a dataset with a big number of rows. Some of the values are NaN, like this:</p> <pre><code>In [91]: df Out[91]: 1 3 1 1 1 1 3 1 1 1 2 3 1 1 1 1 1 NaN NaN NaN 1 3 1 1 1 1 1 1 1 1 </code></pre> <p>And...
<p>You could first find if element is <code>NaN</code> or not by <code>isnull()</code> and then take row-wise <code>sum(axis=1)</code></p> <pre><code>In [195]: df.isnull().sum(axis=1) Out[195]: 0 0 1 0 2 0 3 3 4 0 5 0 dtype: int64 </code></pre> <p>And, if you want the output as list, you can</p> <p...
pandas|count|row|dataframe|nan
123
354,568
30,041,011
Meaning of the return of np.shape()
<p>I have a program in numpy utf8, which allows me to calculate the coordinates of a parabolic shot from the ground. I need to create a function which returns the coordinates (#1), create the different arrays of values to work with (#2), and finally use the function to generate the different coordinates for each pack o...
<p><code>(50L, 9L, 5L, 2L)</code> means a <code>4D</code> array.</p> <p>You can visualize as a <code>50x9</code> matrix and each cell of this matrix contains a <code>5x2</code> matrix </p>
python|numpy|physics|shapes
2
354,569
30,202,578
Aggregation of pandas groupby objects
<p>I am trying to aggregate some statistics from a groupby object on chunks of data. I have to chunk the data because there are many (18 million) rows. I want to find the number of rows in each group in each chunk, then sum them together. I can add groupby objects but when a group is not present in one term, a NaN is t...
<p>Call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.add.html#pandas.DataFrame.add" rel="nofollow"><code>add</code></a> and pass <code>fill_value=0</code> you could iteratively add whilst chunking I guess:</p> <pre><code>In [98]: df = pd.DataFrame({'X': ['A','B','C','A','B','C','B',...
python|pandas
2
354,570
30,059,350
Trouble reading CSV data into Pandas dataframe (Python/Pandas)
<p>I'm having some trouble reading some csv data into a pandas data frame. Here's what my data looks like:</p> <pre><code>C1, C2, C3, C4, C5, 5.0010254, 12, 0.37, 1.2672, 2039.5, 5.0499756, 12, 0.37, 1.2672, ...
<p>One solution is to pass the <code>skipinitialspace</code> argument, to specify that all whitespace after the delimiter should be ignored:</p> <pre><code>pd.read_csv('filename.txt', sep=",", header=1, na_values=["-999"], skipinitialspace=True) </code></pre> <p>See the docstring of <code>read_csv</code> for all poss...
python|csv|pandas
5
354,571
29,978,328
Python - Looping over raster cells, extremely slow
<p>Being not the most savvy python user, I've been trying to find a solution to speed up my code. I have 2 raster files, both have the same dimension and extent. One raster is a river, extracted from a LIDAR image, with a narrow range of elevation values, all other values in the river file are 0. So basically, with the...
<p>This is only a partial answer but should get you started.</p> <p>Use numpy to exclude (mask) all pixels of low values.</p> <pre><code>arrayRiver = arcpy.RasterToNumPyArray(river,nodata_to_value=0) # Create a any array makring pixels less than zero. mask = arrayRiver &gt; 0 arrayRiver = arrayRiver[mask] arrayLidar ...
python|numpy|raster
1
354,572
53,523,729
How to select a proper API/implementation of an LSTM cell in TensorFlow?
<p>In Tensorflow there are many different implementations of the same task under different APIs. For LSTM cell one can find many implementations, e.g.,</p> <ol> <li><a href="https://www.tensorflow.org/api_docs/python/tf/nn/rnn_cell/LSTMCell#class_lstmcell" rel="nofollow noreferrer">tf.nn.rnn_cell.LSTMCell</a></li> <li...
<p>Here <a href="https://www.tensorflow.org/guide/performance/overview#rnn_performance" rel="nofollow noreferrer">RNN Performance</a> are some recommendations for TensorFlow. A couple of important points from the doc:</p> <ul> <li>use <code>tf.contrib.cudnn_rnn()</code> on NVIDIA GPUs;</li> <li>use <code>tf.nn.dynamic...
tensorflow|keras|deep-learning|lstm|rnn
2
354,573
53,662,717
Groupby two columns ignoring order of pairs
<p>Suppose we have a dataframe that looks like this:</p> <pre><code> start stop duration 0 A B 1 1 B A 2 2 C D 2 3 D C 0 </code></pre> <p>What's the best way to construct a list of: i) start/stop pairs; ii) count of start/stop pairs; iii) avg duration of star...
<p><code>sort</code> the first two columns (you can do this in-place, or create a copy and do the same thing; I've done the former), then <code>groupby</code> and <code>agg</code>:</p> <pre><code>df[['start', 'stop']] = np.sort(df[['start', 'stop']], axis=1) (df.groupby(['start','stop']) .duration .agg(['count'...
python|pandas|dataframe|group-by|pandas-groupby
7
354,574
53,405,458
Selecting the top 50 % percentage names from the columns of a pandas dataframe
<p>I have a pandas dataframe that looks like this. The rows and the columns have the same name.</p> <pre><code>name a b c d e f g a 10 5 4 8 5 6 4 b 5 10 6 5 4 3 3 c - 4 9 3 6 5 7 d 6 9 8 6 6 8 2 e 8 5 4 4 14 9 6 f 3 3 - 4 5 14 7 g 4 5 8 9 6 7 10 </code...
<p>Sorting is flexible :)</p> <pre><code>df.sort_values('column_name',ascending=False).head(int(df.shape[0]*.5)) </code></pre> <p><strong>Update:</strong> frac argument is available only on .sample(), not in .head or .tail. df.sample(frac=.5) does give 50% but head and tail expects only int. df.head(frac=.5) fails wi...
python|python-3.x|pandas|python-2.7
9
354,575
53,782,147
Pandas: pairwise multiplication of columns based on column name
<p>I have the following DataFrame</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'ap1_X':[1,2,3,4], 'as1_X':[1,2,3,4], 'ap2_X':[2,2,2,2], 'as2_X':[3,3,3,3]}) &gt;&gt;&gt; df ap1_X as1_X ap2_X as2_X 0 1 1 2 3 1 2 2 2 3 2 3 3 2 3 3 4 4 2 ...
<p>You can do <code>groupby</code> with <code>axis=1</code> and key is the common number </p> <pre><code>df.groupby(df.columns.str[2],axis=1).prod() Out[73]: 1 2 0 1 6 1 4 6 2 9 6 3 16 6 </code></pre>
python|pandas
3
354,576
53,374,499
Get the data type of a PyTorch tensor
<p>I understand that PyTorch tensors are homogenous, ie, each of the elements are of the same type.</p> <p>How do I find out the type of the elements in a PyTorch tensor?</p>
<p>There are three kinds of things:</p> <pre><code>dtype || CPU tensor || GPU tensor torch.float32 torch.FloatTensor torch.cuda.FloatTensor </code></pre> <p>The first one you get with <code>print(t.dtype)</code> if <code>t</code> is your tensor, else you use <co...
pytorch
20
354,577
53,652,184
Array of indexes for each element alongs the first dimension in a 2D array (numpy., tensorflow)
<pre><code>indexes = np.array([[0,1,3],[1,2,4 ]]) data = np.random.rand(2,5) </code></pre> <p>Now, i would like an array of shape (2,3), where</p> <pre><code>result[0] = data[0,indexes[0]] result[1] = data[1,indexes[1]] </code></pre> <p>What would be the proper way to achieve this? A numpy way that yould generalize to ...
<p>Here are NumPy and TensorFlow solutions:</p> <pre><code>import numpy as np import tensorflow as tf def gather_index_np(data, index): data = np.asarray(data) index = np.asarray(index) # Make open grid of all but last dimension indices grid = np.ogrid[tuple(slice(s) for s in index.shape[:-1])] # ...
python|numpy|tensorflow|indexing
1
354,578
53,657,495
Pandas rolling with unsorted time series
<p>I have a CSV with 1M records. Each record is a unique site/product/date. I am trying to use the .rolling to get a moving average for each site/product across a number of dates. However, the dates are not sorted in chronological order. My question is if I use the .rolling function similar to this: </p> <pre><code>df...
<p>It really needs to be sorted. This becomes apparent if you give it an offset as the window size (for datetimes) instead of an integer. </p> <h3>Sample Data</h3> <pre><code>import pandas as pd n = 6 df = pd.DataFrame({'date': pd.date_range('2018-01-01', '2018-01-03', periods=n), 'val': range(n)})...
pandas|group-by|pandas-groupby|rolling-sum
0
354,579
53,605,031
Build a Dict of Counts based on Two Dataframe Columns
<p>I have a dataframe that looks like this:</p> <pre><code> start stop 0 1 2 1 3 4 2 2 1 3 4 3 </code></pre> <p>I'm trying to build a dictionary with key= (start, stop) pairs from my list of tuples and the value= count of their occurrence, regardless of the order. In other words, ...
<p>Use <code>collections.Counter</code>:</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; Counter(map(tuple, np.sort(df[['start','stop']], axis=1))) {(1, 2): 2, (3, 4): 2} </code></pre> <p>This does not modify your original DataFrame.</p>
python|python-3.x|pandas|dataframe
5
354,580
53,497,558
Set value in 2D Numpy array based on row sum
<p>Is this possible to accomplish with Numpy and with good performance?</p> <p>Initial 2D array:</p> <pre><code>array([[0, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 0], [1, 0, 0, 0, 0, 1]]) </code></pre> <p>If the sum of each row is less than 4, set the last item in each row to 1:</p> <pre><code>array([[0, 1, 1...
<p><s><code>numpy.where</code> can also be useful here to find the rows matching your condition</s>:</p> <pre><code>import numpy as np a = np.array([[0, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 0], [1, 0, 0, 0, 0, 1]]) a[np.sum(a,axis=1) &lt; 4, -1] = 1 a = a/a.sum(axis=1)[:,None] print(a) # Outp...
python|arrays|numpy
1
354,581
53,606,528
Pandas Groupby and create new column with custom values
<p>Folks, </p> <p>I've searched StackOverflow for my use-case but haven't been able to find anything useful. If you feel this problem is already solved, please point to the appropriate question.</p> <p>Use-case. </p> <p>I have the following data-frame.</p> <pre><code> Maturity,Periods 0.5,2 0.5,2 1....
<p>Doesn't seem like you need a <code>groupby</code> here... try this:</p> <pre><code>df['CP'] = 0 df.loc[df['Maturity'].ne(df['Maturity'].shift(-1)), 'CP'] = 1 print(df) Maturity Periods CP 0 0.5 2 0 1 0.5 2 1 2 1.0 3 0 3 1.0 3 0 4 1.0 3 ...
python|pandas|numpy|dataframe
1
354,582
53,762,851
iterating over dataframe for a pearsonr test
<p>Trying to loop through a dataframe starting at the second column to conduct a pearsonr test on the returns. The dataset is just nvidia from yahoo finance </p> <pre><code>df=pd.read_csv('NVDA.csv',dtype={'label':str}) for column in df.loc[:,0:3]: pearson_coefficient,p_value=pearsonr(column,df['Volume']) print...
<p>Consider this mini-example:</p> <pre><code>In [10]: df = pd.DataFrame(np.random.randint(10, size=(6,4))) In [11]: [col for col in df.loc[:, 0:3]] Out[11]: [0, 1, 2, 3] </code></pre> <p>Notice that loops of the form <code>for col in df</code> iterate over the <em>column labels</em>, not the column values as Series...
python|pandas|pearson-correlation
1
354,583
53,632,837
TensorFlow assign Tensor to Tensor with array indexing
<p>I would like to do something like this piece of Numpy code, just in TensorFlow:</p> <pre><code>a = np.zeros([5, 2]) idx = np.random.randint(0, 2, (5,)) row_idx = np.arange(5) a[row_idx, idx] = row_idx </code></pre> <p>meaning indexing all rows of a 2D tensor with another tensor and then assigning a tensor to that....
<p>What you are trying to do is frequently done with <a href="https://www.tensorflow.org/api_docs/python/tf/scatter_nd_update" rel="nofollow noreferrer"><code>tf.scatter_nd_update</code></a>. However, that is most times not the right way to do it, you should not need a variable, just another tensor produced from the or...
python|tensorflow
4
354,584
53,801,064
Tensorflow-lite - Getting bitmap from quantized model output
<p>We are working on semantic segmentation application in android using tensorflow-lite.The '.tflite' deeplabv3 model used has input of type (ImageTensor) uint8[1,300,300,3] and ouput of type (SemanticPredictions) uint8[300,300].We were successfully able to run the model and get the ouptut in a ByteBuffer format with...
<p>Try this code:</p> <pre><code> /** * Converts ByteBuffer with segmentation mask to the Bitmap * * @param byteBuffer Output ByteBuffer from Interpreter.run * @param imgSizeX Model output image width * @param imgSizeY Model output image height * @return Mono color Bitmap mask */ ...
android|tensorflow-lite|semantic-segmentation|deeplab
1
354,585
53,357,706
How to update weights with TensorFlow Eager Execution?
<p>So I tried TensorFlow's eager execution and my implementation of it wasn't successful. I used <code>gradient.tape</code>, and while the program runs, there is no visible update in any of the weights. I've seen some sample algorithms and tutorials using <code>optimizer.apply_gradients()</code> in order to update all ...
<p>The usage of <code>optimizer</code> seems fine, however the computation defined by <code>thanouseEyes()</code> will always return [1., 1., 1.] irrespective of the variables, thus the gradients are always 0 and thus the variables will never be updated (<code>print(thanouseEyes(init))</code> and <code>print(GRADIENTS)...
python|tensorflow|machine-learning
0
354,586
53,788,685
how to use tf.metrics.recall_at_k properly?
<p>I am a bit confused therefore I need your help and leading! </p> <p>I am having a sample dataset. I have 2 sources and 4 targets as shown in the following matrix. Each cell is representing a score from a source and a target. </p> <p><a href="https://i.stack.imgur.com/qMGW2.png" rel="nofollow noreferrer"><img src="...
<p>First, let's talk about the difference between <code>tf.metrics.recall_at_k</code> and <code>tf.metrics.recall_at_top_k</code>. </p> <p>If you look at open source code, you will find <code>precision_at_k</code> is a simple wrapper around <code>precision_at_top_k</code>. <code>precision_at_k</code> applies <code>tf....
python|tensorflow
4
354,587
53,665,458
Delete 90% of random rows by condition pandas
<p>I have a pandas dataframe and want to delete 90% of data which satisfies condition.</p> <p>The condition is very simple. If the value of the column "Parameter1" is greater than a threshold, then delete it. </p> <p>My question is how to delete 90% of them, not 90% values in a row, but random</p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="noreferrer"><code>boolean indexing</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html" rel="noreferrer"><code>sample</code></a>:</p> <pre><code>df = pd.DataFrame({ ...
python|pandas|dataframe|random|threshold
11
354,588
53,593,363
Train SqueezeNet model using MNIST dataset Pytorch
<p>I want to train SqueezeNet 1.1 model using MNIST dataset instead of ImageNet dataset. <br/>Can i have the same model as torchvision.models.squeezenet? <br/>Thanks!</p>
<p>TorchVision provides only ImageNet data pretrained model for the SqueezeNet architecture. However, you can train your own model using MNIST dataset by taking only the model (but not the pre-trained one) from <code>torchvision.models</code>.</p> <pre><code>In [10]: import torchvision as tv # get the model architect...
python|neural-network|pytorch|mnist|torchvision
2
354,589
53,660,877
Dataframe reverse for drop(column = )
<p>I'm trying to manipulate a dataframe using a cumsum function. </p> <p>My data looks like this: <a href="https://i.stack.imgur.com/40GkU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/40GkU.png" alt=""></a></p> <p>To perform my cumsum, I use</p> <pre><code>df = pd.read_excel(excel_sheet, sheet_...
<p>IIUC, then you can just set the <code>material</code> column to the index, then do your cumsum, and put it back in at the end:</p> <pre><code>df2 = df.set_index('Material').cumsum(1).reset_index() </code></pre> <p>An alternative would be to do your <code>cumsum</code> on all but the first column:</p> <pre><code>d...
python|pandas
2
354,590
53,422,873
How to unfold a dictionary of dictionaries into a pandas DataFrame for larger dictionaries?
<p>Consider the following dictionary of dictionaries in python3.x</p> <pre><code>dict1 = {4: {4:25, 5:39, 3:42}, 5:{24:94, 252:49, 25:4, 55:923}} </code></pre> <p>I would like to unfold this into a pandas DataFrame. There appear to be two options:</p> <pre><code>df1 = pd.DataFrame.from_dict(dict1, orient='columns') ...
<h3>List comprehension</h3> <p>A list comprehension should be fairly efficient:</p> <pre><code>dict1 = {4: {4:25, 5:39, 3:42}, 5: {24:94, 252:49, 25:4, 55:923}} cols = ['key', 'inner_key', 'values'] df = pd.DataFrame([[k1, k2, v2] for k1, v1 in dict1.items() for k2, v2 in v1.items()], columns=cols...
python|python-3.x|pandas|dictionary|dataframe
2
354,591
53,785,245
Grabbing an unordered index given a matching criteria
<p>I have a pandas data frame that is already filtered so the indices are not in order (i.e not from 0 - the end of my data frame). I have a column that is a 'bag of words'. This is simply a list of words. I know the word I am searching for. How can I find the index/indices that contain this word?<br /> I tried using t...
<p>A simple hack for your case, considering bag column as a string rather than a list if you need to check only contains</p> <pre><code>df['word_flag'] = df['bag'].astype(str).str.contains('your-word-here') </code></pre> <p>If you specifically need the indices</p> <pre><code>df[df['word_flag'] == 1].index </code></p...
pandas|dataframe
0
354,592
53,632,617
Replace ones in binary columns with values from another column
<p>I have a data frame that looks like this:</p> <pre><code>df = pd.DataFrame({"value": [4, 5, 3], "item1": [0, 1, 0], "item2": [1, 0, 0], "item3": [0, 0, 1]}) df value item1 item2 item3 0 4 0 1 0 1 5 1 0 0 2 3 0 0 1 </code></pre> <p>Basically what I want to d...
<p>Why not just multiply?</p> <pre><code>df.pop('value').values * df item1 item2 item3 0 0 5 0 1 4 0 0 2 0 0 3 </code></pre> <p><code>DataFrame.pop</code> has the nice effect of in-place removing and returning a column, so you can do this in a single step.</p> <hr> ...
python|pandas|dataframe
14
354,593
53,447,079
Pandas how to add the counters for matching rows between two dataframe columns
<p>I have two dataframes, where I would like to add the another counter column for matching rows between these dataframes rows.</p> <p>df1:</p> <pre><code>Id val1 val2 val3 0 ab ba sx 1 bc dc xy 2. ab ba ux </code></pre> <p>df2:</p> <pre><code>Id val1 val2 val3 0 ab ...
<p>Is not clear what you want for output, but this might help you:</p> <pre><code>dfa = df1.groupby(['val1', 'val2'], as_index = false).size().rename(columns{0,'counter'} </code></pre>
python|pandas|python-2.7|numpy|dataframe
1
354,594
53,716,439
Having trouble reading Pandas dataframe with SciLearn Kit
<p>I'm new to Python, and I am having trouble using SciLearn Kit on dataframes created using Pandas. Below is the code:</p> <pre><code>import numpy as np import pandas as pd import seaborn as sns import matplotlib as plt import json %matplotlib inline data = pd.read_json('C:/Users/Desktop/Machine Learning/yelp_academi...
<p>As mentioned by @Jarad, You have to feed a <code>list</code> or <code>series</code> to tfidf_vectorizer. Hence, the fix to your issues is</p> <pre><code>tfidf = tfidf_vectorizer.fit_transform(subset_data[records]) </code></pre>
python|pandas|scikit-learn
1
354,595
53,776,209
White Spots Appearing in Image Containing Outline
<p>I want my image to look like this.</p> <p><a href="https://i.stack.imgur.com/m3gfa.jpg" rel="nofollow noreferrer">No Spots Appearing in Purple Region</a></p> <p>However, my image looks like this, with white spots sometimes showing up in the area that is supposed to be "outlined."</p> <p><a href="https://i.stack.i...
<p>It's a bug in your <code>erosion</code> function where it does not set the white pixels to <code>255,255,255</code>. If you inspect the RGB of the eroded image you posted you will see that the first channel of the white areas has values ranging from 250 to 255, and the grayish edges are starting from <code>239,239,2...
python|python-3.x|numpy|rgb
0
354,596
53,682,566
Summing and averaging for the same days
<p>I have data which I sorted by their days in excel, what I want to do now is get the sum of the daily returns for each day. The problem here is that I have multiple entries for the days. So I might only have one Daily Return entry for 2018-12-05 but 5 entries for 2018-12-06. I would like that I only get one entry for...
<p>I think you need aggregate by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>agg</code></a> with functions <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.first.html" rel="nofollo...
python|pandas|dataframe|finance
1
354,597
53,689,758
save a split dataset in .txt format using pandas
<p>Trying to spit a dataset to <code>train</code> and <code>test</code>, and then need to save it as in <code>.txt</code> format.</p> <p>Here's the code so far , </p> <pre><code>import pandas as pd from sklearn.model_selection import train_test_split category=pd.read_csv('dataset.tsv',delimiter='\t',encoding='utf-8'...
<p>You need to write your dataframe as unicode:</p> <pre><code> test.to_csv('checkme.txt', sep='\t', encoding='utf-8') </code></pre>
python|pandas
3
354,598
53,466,252
Throttle pandas apply, when using an API call
<p>I have a large DataFrame with an address column:</p> <pre><code> data addr 0 0.617964 IN,Krishnagiri,635115 1 0.635428 IN,Chennai,600005 2 0.630125 IN,Karnal,132001 3 0.981282 IN,Jaipur,302021 4 0.715813 IN,Chennai,600005 ... </code></pre> <p>and I've written the following function to replace the ...
<p>Here is some <em>tested</em> code that may help. 1) Simple rate limiting to what the Api specifies (Nominatum appears to be 1 per second but i got success as low as 0.1 seconds). 2) Simple result caching in a dictionary, controllable by parameter for testing 3) Retry loop with multiplicative slowdown and linear spee...
python|pandas|api|geolocation|throttling
3
354,599
53,677,857
Select Row by Username with Pandas
<p>I have a Table with multiple users and the data belonging to them. <a href="https://i.stack.imgur.com/QSAMv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QSAMv.png" alt="enter image description here"></a></p> <p>Now I want to create separate tables for each user like this:</p> <p><a href="http...
<p><strong>Breaking down by</strong> <code>User</code></p> <pre><code>df.groupby('User').get_group('John') </code></pre> <p></p> <pre><code> ID User Email 0 1 John john.tomson@email.com 1 2 John john.tomson@email.com 2 3 John john.tomson@email.com </code></pre> <p>Can also be done in...
python|excel|python-3.x|pandas|python-2.7
1