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
363,800
65,948,110
Get first occurrence indices of elements in DataFrame
<p>I have a DataFrame, df, with a <code>datetimeindex</code> that looks like this:</p> <pre><code> Cluster Date 2021-01-28 16:39:00 1 2021-01-28 16:40:00 1 2021-01-28 16:41:00 0 2021-01-28 16:42:00 2 2021-01-28 16:43:00 1 </code></pre> <p>How can I get the first occurrence indices of all Clu...
<p>You can use <code>drop_duplicates</code>:</p> <pre><code>df.drop_duplicates('Cluster').index </code></pre> <p>Output:</p> <pre><code>Index(['2021-01-28 16:39:00', '2021-01-28 16:41:00', '2021-01-28 16:42:00'], dtype='object', name='Date') </code></pre> <p>Or if you want the row number, reset index:</p> <pre><code>df...
python-3.x|pandas|dataframe
1
363,801
66,190,964
TimeSliderChoropleth map with Python Folium won't render geojson polygons individually
<p>I'm trying to render some GeoJSON polygons on a TimeSliderChoropleth map using python Folium.</p> <p>The work is being done in a Jupyter Notebook.</p> <p>The code should draw one polygon per timestep on the slider. However, it renders all three polygons for each timestep. The polygons are also not the colors or opac...
<p>It seems <code>prefer_canvas=True</code> is the cause of the problem. Removing that made it work.</p> <p><code>prefer_canvas=True</code> was suggested in some of the documentation as a speed up for maps that have a lot of objects placed in the map. Since this project does, I was attempting to use it. But, it doesn't...
python|maps|geojson|geopandas|folium
0
363,802
66,037,491
Wrong shape Dataset Tensorflow
<p>Im new to tensorflow and Im trying to feed some data with tensorflow.Dataset. Im using Cityscape dataset with 8 different classes. Here is my code:</p> <pre><code>import os import cv2 import numpy as np import tensorflow as tf H = 256 W = 256 id2cat = np.array([0,0,0,0,0,0,0, 1,1,1,1, 2,2,2,2,2,2, 3,3,3,3, 4,4, 5, ...
<p><code>Tensorflow</code> is a graph based mathematical framework that abstracts for you all of those complex vectorial or matricial operations you face, particularly in machine learning.</p> <p>What the developers though is that it would be unconfortable to specify every single time how many input vectors you need to...
python|tensorflow
1
363,803
66,088,799
How to get the first value from the pd.cut range
<p>I have a data frame as follows</p> <pre><code> COLUMN-1 6 2200 51 4699 126 5139 133 3900 240 5301 </code></pre> <p>I have a used <code>pd.cut</code> in a data frame and stored the values in a new column. The data frame now looks like this</p> <pre><code> COLUMN-1 NEW-...
<p>I suppose what you have in <code>lst</code> are the breaks to divide them. If you have n breaks, you will get n-1 labels. So in this case, you do not specify <code>300</code> inside <code>pd.cut</code>, because this means the number of breaks. You provide the breaks and use everything up to the last element of the b...
python|pandas
2
363,804
66,127,421
Get element from array based on list of indices
<pre><code>z = np.arange(15).reshape(3,5) indexx = [0,2] indexy = [1,2,3,4] zz = [] for i in indexx: for j in indexy: zz.append(z[i][j]) </code></pre> <p>Output:</p> <pre><code>zz &gt;&gt; [1, 2, 3, 4, 11, 12, 13, 14] </code></pre> <p>This essentially flattens the array but only keeping the elements that have in...
<pre><code>x = {&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;} y = {&quot;google&quot;, &quot;microsoft&quot;, &quot;apple&quot;} z = x.intersection(y) print(z) z =&gt; apples </code></pre> <p>If I understand you correctly, just use Python set. And then cast it to list.</p>
python|python-3.x|list|numpy|indexing
0
363,805
66,153,579
Create consecutive labels for boxplot
<p>I want to set the labels of a binned boxplot automatically based on the cut-intervals. The data-bins are created by applying <code>pd.cut()</code> on a data frame. The list of the <code>pd.cut</code> is specified manually (see <code>cut</code> list), but I want the histogram labels to be set automatically based on t...
<p>You could just do the following:</p> <pre><code>cut = [0,20,40,60,80,100] label = [] for i, p in enumerate(zip(cut, cut[1:])): label.append('{}-{}'.format(p[0] + 1 if p[0] != 0 else p[0], p[1])) </code></pre> <p>It will give you:</p> <pre><code>label ['0-20', '21-40', '41-60', '61-80', '81-100'] </code></pre> <...
python|pandas|cut
1
363,806
66,131,983
How can I insert rows to Pandas dataframe depending on previous and next values?
<p>I want to insert a row if the time values between the previous and next rows are high. Essentially I want to have a row for every 2 seconds. So in the below example I want to add 3 rows between 19 and 26. The time values will be 21, 23, 25 and I will later use interpolate method to fill X values for that rows.</p> <...
<p>you can use <code>append</code> a list of <code>dict</code>:</p> <pre><code>df.append([{'Time':i} for i in range(21,26,2)], ignore_index=True).sort_values('Time') </code></pre>
python|pandas|dataframe
1
363,807
66,306,737
Is there an array method for testing multiple equality values?
<p>I want to know where array a is equal to <em>any</em> of the values in array b.</p> <p>For example,</p> <pre><code>a = np.random.randint(0,16, size=(3,4)) b = np.array([2,3,9]) # like this, but for any size b: locations = np.nonzero((a==b[0]) | (a==b[1]) | (a==b[3])) </code></pre> <p>The reason is so I can change t...
<p>You can use <code>np.in1d</code> then <code>reshape</code> back to <code>a</code>'s shape so you can set the values in <code>a</code> to your special flag.</p> <pre><code>import numpy as np np.random.seed(410012) a = np.random.randint(0, 16, size=(3, 4)) #array([[ 8, 5, 5, 15], # [ 3, 13, 8, 10], # [...
numpy
1
363,808
66,078,890
Filtering rows with some NaNs in DFs
<p>I have a dataframes with many rows, and some values are NaNs.<br /> For example -</p> <pre><code>index col1 col2 col3 0 1.0 NaN 3.0 1 NaN 4.0 NaN 3 1.0 5.0 NaN </code></pre> <p><strong>I would like to filter the DF and return only the rows with 2+ values.</s...
<p>You can use <code>dropna()</code> set the threshold to be 2 <code>thresh=2</code>, and perform operation along the rows <code>axis=0</code>:</p> <pre><code>res = df.dropna(thresh=2,axis=0) res col1 col2 col3 0 1.00 NaN 3.00 2 1.00 5.00 NaN </code></pre> <p><a href="https://pandas.pydata.org/pandas-doc...
python|pandas|dataframe
2
363,809
65,973,519
How to roll n dice
<p>I have been looking on stack and spend several hours browsing to try and solve this. Task is:</p> <p>Use a For loop to perform dice experiments with increasing number of dice rolls. Perform these experiments up to a number of =1000</p> <p>I am struggling to add the number of rolls into the for loop function. What I...
<pre><code>import numpy as np N = 1000 results = np.zeros(N) for i in range(1, N+1): roll = np.random.randint(1, 7, size = i) results[i-1] = np.mean(roll) </code></pre> <p>at each iteration the mean value of all the dice rolls is stored in results</p>
python|numpy
0
363,810
66,013,059
Fill NA with another list pandas
<p>Basically, what I'm trying to do here is to fill the missing values in a dataframe column name &quot;Colors&quot; with string names/words from a separate list named &quot;lst&quot;.</p> <p>Given code does it's job in adding to the targeted row while other string names (e.g. Green..etc) still remains, which is good.<...
<p>Try to assign</p> <pre><code>df.loc[df.Colors.isnull(),'Colors'] = lst df Out[296]: Index Colors 0 0 one 1 1 Red 2 2 two 3 3 Green 4 4 three 5 5 four 6 6 Brown </code></pre>
python|pandas|dataframe
2
363,811
66,158,762
How to populate a Pandas dataframe with list elements while keeping a column same?
<p>I have a Pandas dataframe <code>df</code> which contains many rows and 2 columns like this:</p> <pre><code>| Query | Description | | -------- | -------------- | | First sentence | First description | | Second sentence | Second description | </code></pre> <p>I have created a method <code>new_...
<p>Taking a sample dataframe</p> <pre><code>df = pd.DataFrame([['hello', 'how'], ['are', 'you']], columns=['Query', 'Description']) df Query Description 0 hello how 1 are you </code></pre> <p>and taking a dummy <code>new_sentences</code> function, where you can return the new sentenc...
python|pandas|dataframe|iteration
1
363,812
66,164,513
Converting Pandas Object data type to String
<p>I can't get individual columns or my entire dataframe to convert to a string. I'm reading in data from s3 into a pandas, like such:</p> <pre><code>bucket = 'my_bucket' file_name = 'my_path/my_file.csv' s3 = boto3.client('s3') s3_obj = s3.get_object(Bucket = bucket, Key = file_name) df = pd.read_csv(s3_obj['Body']) ...
<p>Try adding dtype=str as an argument to read_csv function:</p> <pre><code>df = pd.read_csv(s3_obj['Body'], dtype=str) </code></pre> <p>If you want certain columns to be interpreted as column you can specify that in dtype as:</p> <pre><code>mydtypes = {'col1': 'str', 'col2': 'str', 'col3': 'str', 'col4': 'float'} df =...
python|pandas|string|object
0
363,813
65,966,176
What can I use instead of tf.contrib.rnn.LayerNormBasicLSTM in TensorFlow 2.x?
<p>The <code>tf.contrib.rnn.LayerNormBasicLSTM</code> is deprecated in TensorFlow 2.x. What is equivalent to this code or what can I use instead of it in TensorFlow 2.x?</p>
<p>In Tensorflow 2.x, you can use</p> <pre><code>tf.compat.v1.nn.rnn_cell.LSTMCell </code></pre> <p>For better performance, alternative is</p> <pre><code>tf.keras.layers.LSTMCell </code></pre>
python-3.x|tensorflow|tensorflow2.0
0
363,814
66,126,011
How to make a jointplot in Seaborn with multiple groups or categories?
<p>I am trying to make a jointplot in Seaborn. The goal is to have a scatter plot of all [x,z] values and to have these color-coded by [cat], and to have the distributions for these two categories. Then I also want a scatter and distribution plot of [x,alt_Z], ignoring the alt_Z values that are NaN.</p> <p>Using Python...
<p>One problem with the dataframe, is that <code>col4</code> contains integers and 'NaN'. As there don't exist NaN values for integers, pandas makes it a column of objects. Converting it to floats will create a proper float column with <code>NaN</code> as numbers.</p> <p>To create the scatter plot, two calls to <code>s...
python|pandas|seaborn|jointplot
1
363,815
65,948,018
How to convert unix epoch time to datetime with timezone in pandas
<p>I have many csv files containing Unix epoch time which needs to be converted to human readable date/time. The following Python code does the job but it is very slow.</p> <pre><code>df['dt'] = pd.to_datetime(df['epoch'], unit='s') df['dt'] = df.apply(lambda x: x['dt'].tz_localize('UTC').tz_convert('Europe/Amsterdam')...
<ul> <li>The question pertains to <code>pandas</code>, the pure python version is <a href="https://stackoverflow.com/q/3682748/7758804">Converting unix timestamp string to readable date</a></li> <li><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.tz_localize.html" rel="noreferrer"><...
python|pandas|performance|datetime|timezone
6
363,816
66,204,478
input/output/recurrent dropout layers in BiLSTM_Classifier and how they affect the model and prediction
<p>I would like to have some understanding/information on the input/output/recurrent dropout layers in BiLSTM_Classifier and how they affect the model and prediction.</p> <pre><code># Output drop out model_out_dp = Sequential() model_out_dp.add(Embedding(vocab_size, embedding_dim, input_length=maxlen,weights=[embedding...
<p>First we split 'S's and 'A's into groups per the rule -- we assign a unique `group' to each S followed by any number (including none) of As. We also number elements in each group in a sequence</p> <pre><code>df['group'] = (df['First']=='S').cumsum() df['el'] = df.groupby('group').cumcount() </code></pre> <p>Looks li...
python|tensorflow|nlp|lstm|dropout
2
363,817
66,140,509
Given a matrix A, return a vector v in a way that depends on the injective, surjective, and bijective properties of A
<p>I have a matrix A which is a bijective matrix</p> <pre><code>A= np.array([[1,2,3],[3,4,5],[4,10,6]]) </code></pre> <p>Return a vector v where the first two coordinate of v are 1 and v=Ax for some vector x. <a href="https://i.stack.imgur.com/ZHnih.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZHn...
<pre><code># A is injective v = np.array([1,1,-4]) </code></pre>
python|arrays|numpy|matrix
0
363,818
65,950,425
Fill missing values with the most common value in the grouped form
<p><a href="https://i.stack.imgur.com/aXc3U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aXc3U.png" alt="enter image description here" /></a></p> <p>Could anybody help me with fill missing values with the most common value but grouped form? .Here I want to fill missing value of cylinders columns w...
<p>I think problem is there are only <code>NaN</code>s per some (or all) groups, so error is raised. Possible solution is use custom function with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</c...
python|pandas
1
363,819
65,917,608
How to Sum by Column in Pandas DF and Remove Additional Rows
<p>I have a dataframe in the form:</p> <pre class="lang-py prettyprint-override"><code> Sales House Station Day Date Time Daypart Total Unique Key 0 CARLTON CARLTON Mon 3AUG20 1213 DAYTIME 0 CARLTON_ 3AUG20 1 CARLTON CARLTON Mon 3AUG20 2307 POSTPEAK 30 CA...
<p>Seems like you need <code>df.groupby()</code> method.</p> <p>I would try doing this in three steps:</p> <pre><code>aggregated = df.groupby(['Station', 'Date'])['Total'].sum().reset_index() # Getting sum df = df.drop_duplicates(['Station', 'Date']) # Removing duplicated rows df = df.drop(...
python|pandas|dataframe
3
363,820
66,309,055
How to do a calculation based off a T/F condition in a Pandas DataFrame
<p>So I am really not sure how I should go about this. I am working with pandas in python. I have a csv file I converted into a data frame called <code>df</code>. I have this column:</p> <pre><code>Is_High_School FALSE FALSE FALSE TRUE FALSE ... </code></pre> <p>And I have another column:</p> <pre><code>Student_Count 4...
<p>If you want do want have a dataframe with only no high school you can do this:</p> <pre><code>df = df[df['Is_High_School'] == False] </code></pre> <p>But but don't see the reason for that. You can just do:</p> <pre><code>mean_series = df.groupby(['Is_High_School']).mean() std_series = df.groupby(['Is_High_School'])....
python|pandas
0
363,821
66,211,135
Image size in DefaultPredictor of Detectron2
<p>For object detection, I'm using detectron2. I want to fix the input image size so I made my customized dataloader:</p> <pre><code>def build_train_loader(cls, cfg): dataloader = build_detection_train_loader(cfg, mapper=DatasetMapper(cfg, is_train=True, augmentations=[ T.Resize((1200, 1200)) ...
<p>You have to preprocess the images yourself or to write your own predictor that will apply the resize before calling the model.</p> <p>The <a href="https://github.com/facebookresearch/detectron2/blob/1f522c1b45b0c3192402ed5c4ae03170eed65590/detectron2/engine/defaults.py#L188" rel="nofollow noreferrer">DefaultPredicto...
pytorch|detectron
2
363,822
66,127,830
How to convert a multi-key dictionary to a pandas dataframe, where each key and value has its own column?
<p>Say I have a dictionary that looks like this</p> <pre><code>mkd = {('aab', 'ccd', 'bbd'): 3, ('aeb', 'cfd', 'bfd'): 8, ('atb', 'cttd', 'bft'): 83} </code></pre> <p>How could I mad a pandas dataframe where each key and value has its own column.</p> <p>I see there's a solution for creating a pandas df from here</p> <p...
<p>You can convert it to a series and then reset index:</p> <pre><code>pd.Series(mkd).reset_index() </code></pre> <p>Output:</p> <pre><code> level_0 level_1 level_2 0 0 aab ccd bbd 3 1 aeb cfd bfd 8 2 atb cttd bft 83 </code></pre>
python|pandas
4
363,823
65,925,371
PyTorch - Convert CIFAR dataset to `TensorDataset`
<p>I train ResNet34 on CIFAR dataset. For a certain reason, I need to convert the dataset into <code>TensorDataset</code>. My solution is based on this: <a href="https://stackoverflow.com/a/44475689/15072863">https://stackoverflow.com/a/44475689/15072863</a> with some differences (maybe they are critical, but I don't s...
<p>When using the &quot;standard&quot; dataset, each time you load an image, a random transform (flip + crop) is applied to it. As a consequence, virtually every image of every epoch is unique, seen only once. So you kind of have <code>nb_epochs * len(dataset)</code> different inputs.</p> <p>With your custom dataset, y...
python|neural-network|pytorch|dataset|dataloader
1
363,824
65,996,290
Merge mean and std in a new table pandas dataframe
<p>I have a dataframe and I´m attempting to make a new table merge the mean, std and add a symbol between then (±), the output should be like this:</p> <pre><code>TR A B C D 1 54±35 68.6±18.4 795.8±269 49.8±36.2 2 61.4±36.4 67.8±14.4 524.8±363.6 52.8±41.2...
<p>Try this:</p> <pre><code>&gt;&gt;&gt; table.astype(str) + u&quot;\u00B1&quot; + sd.astype(str) A B C D TR 1 54.0±35.0 68.6±18.4 795.8±269.0 49.8±36.2 2 61.4±36.4 67.8±14.4 524.8±363.6 52.8±41.2 3 54.0±31.9 73.6±22.8 ...
python|pandas|dataframe
0
363,825
66,106,351
Python Pandas: Creating a column in a dataframe out of three different values
<p>I need to create a column which will serve as an ID. The ID should look like this:</p> <p>ABC_7234Ij234XZ_03.02.2021</p> <p>The first part is ABC_ and constant The second part 7234Ij234XZ is stored in a column in the dataframe already as a [customer_number] which will be changing for each row The third part is _03.0...
<p>This should work:</p> <pre><code>df['my_id'] = 'ABC_' + df['customer_number'].astype(str) + '_03.02.2021' </code></pre>
python|pandas|dataframe|numpy
1
363,826
66,033,323
How to add a column to a multiindex dataframe with .loc?
<p>I have one line of code that I wrote about half a year ago. When I execute it today, I'll get an error. I think I'll updated pandas in the meantime. It's best to shown it with an example.</p> <pre><code>import pandas as pd df1 = pd.DataFrame([pd._testing.rands_array(2, 4), pd._testing.rands_array(...
<p>As I wrote this question my pandas version was 1.1.5, where this strange behaviour of my code occurs. Updating to pandas 1.2.1 solved this issue. Thank you for your comment Trenton McKinney.</p>
python|pandas
0
363,827
66,107,673
Find all matching keys and values in data frame
<p>Given a Pandas DF like the one below were the key is &quot;state county&quot; I want to find all the zip codes that are associated with each key.</p> <p>On a small scale I accomplished this using a loop but it is not efficient for the 50,000 keys I need to check. Is there a programing concept I can use to solve this...
<p>You can collect all the zips for every state and then create a new DataFrame</p> <pre class="lang-py prettyprint-override"><code>df2 = df.groupby('state county').agg({'zip': list}) df3 = pd.DataFrame(df2.zip.tolist(), index=df2.index) </code></pre> <p>You can rename the columns of the resulting DataFrame, so that th...
python|pandas
0
363,828
66,274,882
Read Excel file that is located outside the folder containing the module into Pandas DataFrame
<p>I want to read an excel file into pandas DataFrame. The module from which I want to read the file is inputs.py and the excel file (schoolsData.xlsx) that I want to read is outside the folder containing the module. I'm doing it like this in my code</p> <pre><code>def read_data_excel(path): df_file = pd.read_excel...
<p>The error could be arised because of the current working directory is different when you execute in local than when you execute after installing. Take a look to <a href="https://stackoverflow.com/questions/2860153/how-do-i-get-the-parent-directory-in-python">this</a> to generalize the path without hardcoding it.</p>
python|excel|pandas|pypi
1
363,829
66,037,255
Replicate F# map join in python
<p>Given map a and map b below, the expected result is val c in F#. I am trying to replicate this behavior in python.</p> <pre><code>let join (p:Map&lt;'a,'b&gt;) (q:Map&lt;'a,'b&gt;) = Map(Seq.concat [ (Map.toSeq p) ; (Map.toSeq q) ]) example: let a = Map([1,11;2,21;3,31;]) let b = Map([3,32; 4,41;5,51;6,61;]) ...
<p>Might not be the best solution for huge dataframes.</p> <h2>Creating dataframes</h2> <pre><code>&gt;&gt;&gt; df_a = pd.DataFrame({&quot;col1&quot;: [1,2,3], &quot;col2&quot;:[11,21,31]}) &gt;&gt;&gt; df_a col1 col2 0 1 11 1 2 21 2 3 31 &gt;&gt;&gt; df_b = pd.DataFrame({&quot;col1&quot;: [3...
python|pandas|f#
2
363,830
66,059,546
Fill in NaN values in dataframe intervals according to conditions of a column
<p>I have a dataframe with me which has an ID column and description column with START and STOP values represented by the ID's. Every START-STOP pair is denoted by an ID and it is incremented to 1 on next appearance of the pair.</p> <p><a href="https://i.stack.imgur.com/qxwtq.png" rel="nofollow noreferrer"><img src="h...
<pre class="lang-py prettyprint-override"><code># create a group-tag by every STOP cond = df.SEG_DESC == 'STOP' df['tag'] = cond.cumsum() df.loc[cond, 'tag'] = df.loc[cond, 'tag'] - 1 # for every tag-group use back fillna df['ID_START_STOP'] = df.groupby('tag')['ID_START_STOP'].bfill().astype(int) </code></pre>
python|arrays|pandas|dataframe|numpy
2
363,831
66,338,970
Cleaning text using nltk
<p>I would like to clean text column in a good and efficient way. The dataset is</p> <pre><code>pos_tweets = [('I loved that car!!', 'positive'), ('This view is amazing...', 'positive'), ('I feel very, very, great this morning :)', 'positive'), ('I am so excited about the concerts', 'positive'), ('He is...
<p>If you want to remove even NLTK defined stopwords such as i, this, is, etc, you can use the NLTK's defined stopwords. Refer to the below code and see if this satisfies your requirements or not.</p> <pre><code>import pandas as pd import numpy as np import re import nltk from nltk.corpus import stopwords stop_words = ...
python|pandas|nltk
3
363,832
66,020,574
Efficiently create 2d numpy array given 1 dimension and a constant
<p>Given an x-dataset,</p> <pre><code>x = np.array([1, 2, 3, 4, 5]) </code></pre> <p>what is the most efficient way to create the NumPy array where each x coordinate is paired with a y-coordinate of value 0? I am wondering if there is a way specifically that doesn't require any hard coding, so that x could vary in leng...
<p>As per your problem statement, the following is one way to do it.</p> <pre><code># initialize an array of zeros In [36]: res = np.zeros((2, *x.shape), dtype=x.dtype) # fill `x` as first row In [37]: res[0] = x In [38]: res Out[38]: array([[1, 2, 3, 4], [0, 0, 0, 0]]) </code></pre> <p>When we initialize the...
python|numpy|numpy-ndarray
1
363,833
66,033,370
Plot ROC curve from Cross-Validation
<p>I'm using this code to oversample the original data using SMOTE and then training a random forest model with cross validation.</p> <pre><code>y = df.target X = df.drop('target', axis=1) imba_pipeline = make_pipeline(SMOTE(random_state=27, sampling_strategy=1.0), RandomForestClassifie...
<p>First of all, I think you should run 1 cross-validation instead of a new cross-validation for every metric that you want. That is wasting resources and you are not measuring the same models for those metrics then.</p> <p>For that, see the function <code>cross_validate</code> (<a href="https://scikit-learn.org/stable...
python|pandas|machine-learning|roc
0
363,834
66,001,828
Perform a switch statement within a pandas assign
<p>I want to have a field in my data that flags the 'focus' rows for later charting them in different ways. Here's some code that works, and returns the output I'm after:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame( {'Animal': ['Falcon', 'Falcon', 'Parrot', 'Parrot', ...
<p>The <code>.assign</code> method can handle equations, per <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html</a>.</p> <p>I'd suggest that the most flexible ...
python|pandas
1
363,835
65,931,555
while importing torch- shows - [WinError 126] The specified module could not be found
<p>I have tried to install python torch by using</p> <pre><code> !pip install torch </code></pre> <p>But I got the error <strong>OSError: [WinError 126] The specified module could not be found</strong></p> <p>Then I tried with</p> <pre><code>pip install torch -f https://download.pytorch.org/whl/torch_stable.html </co...
<p>Ok the problem is that you are trying to install the cuda version of Pytorch on a non cuda enabled computer. You can find a similar problem <a href="https://discuss.pytorch.org/t/cannot-import-torch-on-jupyter-notebook/79334" rel="nofollow noreferrer">here</a>. You have to download the cpu version of pytorch like th...
python|pytorch
1
363,836
66,068,180
Tensflow Keras: TypeError: can't pickle _thread.RLock objects when using multiprocessing
<p>I have raised this issue in GitHub: <a href="https://github.com/tensorflow/tensorflow/issues/46917" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/46917</a></p> <p>I am trying to use multiprocessing threads to speedup the some of my code. In which I have to send a Keras model to each threa...
<p>@Aaron thanks for explaining the comment made by amahendrakar on GitHub. I modified the code such that the code sends the path of the model, rather than the model itself, to the child processes. Below is the working code</p> <pre><code>import tensorflow as tf from tensorflow import keras import numpy as np # from ...
python|tensorflow|keras|multiprocessing|tensorflow2.0
0
363,837
66,331,459
Numpy ndarray displays different data structure than array
<p>In my code</p> <p>I converted a dataframe to numpy array using <code>.to_numpy()</code> and <code>.values</code> function but both return a data structure like this</p> <pre><code>[[1 2] [3 4]] </code></pre> <p>I was expecting</p> <pre><code>array([[1,2], [3,4]]) </code></pre> <p>Does anyone know what is happening ?...
<p>To prove that they are the same try</p> <pre><code>import numpy as np a = np.array([[1, 2], [3, 4]]) print(a) print(list(a)) print(a.tolist()) </code></pre> <p>and you will get</p> <pre><code>[[1 2] [3 4]] [array([1, 2]), array([3, 4])] [[1, 2], [3, 4]] </code></pre> <p>to show what you have and how to move betwee...
python|pandas|numpy
0
363,838
65,978,710
Method to construct an count matrix (in integers) from a matrix of strings with pandas (Python)
<p>Could someone please help me find a way to solve my query below? I'm more so looking for the terms to search for to solve the problem but if you know a quick-and-dirty method that would also be appreciated.</p> <p>I have a matrix like the one below:</p> <pre><code> sample_1. sample_2. sample_3. ...
<p>You can use <strong><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>DataFrame.apply</code></a></strong> + <strong><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.count.html#:%7E:text=count,-Series.s...
python|pandas|dataframe|matrix
2
363,839
66,201,362
RuntimeError: Expected hidden[0] size (2, 1, 100), got (1, 1, 100)
<p>I put together a LSTM model and it works. But only as long as I set num_layers = 1. If I set it for example to 2 it gives my a long error message that tells me:</p> <p>RuntimeError: Expected hidden[0] size (2, 1, 100), got (1, 1, 100)</p> <p>I am pretty new at Python and deep learning in general, so I could need som...
<p>That is because of this line in your training loop:</p> <pre class="lang-py prettyprint-override"><code>model.hidden_cell = (torch.zeros(1, 1, model.hidden_layer_size), torch.zeros(1, 1, model.hidden_layer_size)) </code></pre> <p>Even though you correctly defined <strong>hidden_cell</strong> in ...
pytorch|lstm
0
363,840
65,956,893
How to install the "Tree Ensemble Layer" on Kaggle Notebook
<p>I would like to try the following code on Kaggle Notebook but I could not find a way to install the tf_trees.</p> <pre><code>from tensorflow import keras from tf_trees import TEL tree_layer = TEL(output_logits_dim=2, trees_num=10, depth=3) model = keras.Sequential() model.add(keras.layers.BatchNormalization()) mod...
<p>turn on internet support first and clone the google-research repo from github:</p> <pre><code>!git clone https://github.com/google-research/google-research.git </code></pre> <p>then we need the compiling and linking options for g++ so run following code snippets:</p> <pre><code>import tensorflow as tf; print(&quot;...
python|tensorflow|keras|pip|kaggle
2
363,841
66,078,233
How can I plot a stacked bar chart of median of a column in pandas dataframe?
<p>So I am a newbie learning about data visualization in pandas (python) , My task is to Create a stacked chart of median WeekHrs and CodeRevHrs for the age group 30 to 35.</p> <p>following is my code where I extracted the data applying filter on age column and below are the first five rows of my dataset</p> <pre><code...
<p>First, to filter for age (and also convert age to <code>int</code> as it makes for cleaner labels):</p> <pre class="lang-py prettyprint-override"><code>df = agework.query('30 &lt;= age &lt;= 35') df['age'] = df['age'].astype(int) </code></pre> <p>Then, you could plot a bar chart of the median of the two quantities i...
python|pandas|stacked-chart
3
363,842
66,010,821
How to plot a bar graph labels in alphabetical order in python?
<p>I have the following bar graph:</p> <p><a href="https://i.stack.imgur.com/v9aol.png" rel="nofollow noreferrer">Click here for bar graph</a></p> <p>I would like to alphabetically order the Y-axis labels (i.e, control, exclude, necrosis, other, tissue, tumor and not control, other, necrosis, exclude, tissue, tumor). H...
<p>you just need to sort index of your dataframe when you give it to <code>plt.barh()</code>, like below:</p> <pre><code>plt.barh(width=smack.values, y=smack.index.sort_values()) </code></pre>
python|pandas|bar-chart|alphabetical
1
363,843
66,249,593
Reshape Pandas dataframe (partial transpose)
<p>I have a csv similar to the following, where the column heading specifies the time (hour number):</p> <pre><code>Day,Location,1,2,3 1/1/2021,A,0.26,0.25,0.49 1/1/2021,B,0.8,0.23,0.55 1/1/2021,C,0.32,0.11,0.58 1/2/2021,A,0.67,0.72,0.49 1/2/2021,B,0.25,0.09,0.56 1/2/2021,C,0.83,0.54,0.7 </code></pre> <p>When I load it...
<p>Try:</p> <pre><code>df = pd.read_csv('VirusLevels.csv', index_col=[0,1]) df.rename_axis(columns='Time').stack().unstack('Location') # or # df.rename_axis('Time',axis='columns').stack().unstack('Location') </code></pre> <p>Output:</p> <pre><code>Location A B C Day Time ...
pandas|dataframe
1
363,844
65,916,356
Image classification Using Pytorch
<p>this is the code where I was working on Image Classification using Pytorch and I'm not able to get the accuracy right. the accuracy is exceeding 100 ,can anyone help me to find the error.</p> <pre><code> def trained_model(criterion, optimizer, epochs=5): epoch_loss = 0.0 epoch_accuracy = 0 ru...
<p>You should probably use <a href="https://pytorch.org/docs/stable/generated/torch.argmax.html" rel="nofollow noreferrer"><code>torch.argmax</code></a> to get the class predictions from your model output, instead of <code>torch.max</code>.</p> <p>Assuming you are working with indices as labels. Something like the fol...
pytorch|data-science|image-classification
0
363,845
66,202,777
Using np.where with OOP
<p>I have create an numpy array in which all the cells values are objects. I want to use np.where conditions but it is not working as I want to check the equivalent conditions for object attributes. The object class looks similar to the one below:</p> <pre><code>class Cell(): def __init__(self): self.valu...
<p>You are comparing with an object ('ABC') from <code>str</code> class with an object from <code>'__main__.Cell'</code> class. (try checking with <code>type(Cell())</code></p> <p>A fix is simply changing type with <code>np.array.astype()</code></p> <pre><code>arr = np.array([['M', Cell(),'M'], ['M', ...
python|numpy|oop
2
363,846
66,161,305
Pandas Groupby, Filter, and Insert Column
<p>I'm working with a Pandas dataframe that has a column with a unique ID code representing a client. Each ID code is repeated in several rows in the table. There is another column in the table with a boolean flag, true or false. I am trying to adjust the table so that for every ID code, if there is at least one flag s...
<ul> <li><code>groupby()</code> to get all related rows together</li> <li><code>transform()</code> to get a value for each work</li> <li>simple pandas series <code>any()</code></li> </ul> <pre><code>df = pd.DataFrame({&quot;client_id&quot;:np.random.randint(1,5,8), &quot;flag&quot;:np.random.choice([False,...
python|pandas
1
363,847
66,133,105
Stacked Bar chart of many columns grouped by the values of one column (Pandas)
<p>I have a Pandas dataframe like this</p> <pre><code>'BondInvestments' |'Cash' |'EquityInvestments'| 'MoneyMarketInvestments' | 'Cluster' 10 | 1 | 10 | 20 | 0 10 | 3 | 10 | 20 | 1 200 | 1 |...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.barh.html" rel="nofollow noreferrer"><code>DataFrame.plot.barh</code></a>:</p> <pre><code>df.set_index('Cluster').plot.barh(stacked=True) </code></pre>
python|pandas|matplotlib|data-visualization
1
363,848
66,094,445
Slow Double for loop
<p>I have a double loop that runs over a dataset comparing 1 row to the next on multiple matching conditions. When a condition is met, the matched pair is added to the list. The code works fine for small dataset but it quite slow for anything more than 5k rows.</p> <p>I would really appreciate it if anyone has any idea...
<p>create a function <code>create_cross_join</code> to create a combinations cross join dataframe with raw df.</p> <pre><code>import itertools def create_cross_join(dfn): dfn = dfn.reset_index() # create a combinations with 2 elemens # -&gt; [0,1,2,3] # -&gt; [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (...
python|python-3.x|pandas
0
363,849
65,927,313
Python: Expand 2D array to multiple 1D arrays
<p>Consider the followoing example from <a href="https://numpy.org/doc/stable/reference/generated/numpy.meshgrid.html" rel="nofollow noreferrer">np.meshgrid docs</a>:</p> <pre class="lang-py prettyprint-override"><code>nx, ny = (3, 2) x = np.linspace(0, 1, nx) y = np.linspace(0, 1, ny) xv, yv = np.meshgrid(x, y) </code...
<p>this should do it.</p> <pre><code>n_variables = 25 z = np.array([np.linspace(0, 1, 10)] * n_variables) z_grid = np.dstack(np.meshgrid(*z)) </code></pre> <p>the * operator before list, unpacks list elements. consider following:</p> <pre><code>v1 = [1,2,3] v2 = [4,5,6] list_of_v = [v1,v2] some_fucntion(v1,v2) == some_...
python|arrays|numpy|grid
0
363,850
52,506,861
How can I make all subindexes on multiindex to have same values
<p>I have a Dataframe with multiindex that looks like this:</p> <pre><code>a 1 2 3 b 2 3 </code></pre> <p>So The outer level has values a, b and the inner value is 1, 2, 3 for a and 2, 3 for b</p> <p>I want to make sure that the indexes on the inner level are the same for all indexes on the outer level (in tha...
<p>You can re-index with a <code>MultiIndex</code> made from your original dataframe indices:</p> <pre><code>df.reindex(pd.MultiIndex.from_product(df.index.levels)) </code></pre> <p>Example:</p> <pre><code>idx = pd.MultiIndex.from_arrays([['a','a','a','b','b'],[1,2,3,2,3]]) df = pd.DataFrame(np.random.random(5), in...
python|pandas|indexing
3
363,851
52,860,690
Error in manipulating dataframe within a function ('function' object has no attribute)
<p>I would like to add a columns which is the index for unique values in a certain column.</p> <p>The original dataframe is :</p> <pre><code> Team Rank Year Points 0 Riders 1 2014 876 1 Riders 2 2015 789 2 Devils 2 2014 863 3 Devils 3 2015 673 4 Kings 3 2014...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.ngroup.html" rel="nofollow noreferrer"><code>groupby.ngroup</code></a>:</p> <pre><code>df1 = df.sort_values('Year') df1['year code'] = df1.groupby('Year').ngroup() df1 = df1.reset_index(drop=True) # df.sort_values('Year...
python|pandas|function|dataframe|group-by
1
363,852
52,601,258
Allocate scatter plot into specific bins
<p>I have a <code>scatter plot</code> that gets sorted into <code>4 Bins</code>. These are separated by two <code>arcs</code> and a <code>line</code> in the middle (see figure below).</p> <p>There's a slight problem with the two <code>arcs</code>. If the <code>X-Coordiante</code> is greater than the <code>ang2</code> ...
<p>Patches have a test for containing points or not: <code>contains_point</code> and even for arrays of points:<code>contains_points</code></p> <p>Just to play with I have a code snippet for you, which you can add between the part where you're adding your patches and the <code>#Sorting the coordinates into bins</code>...
python|pandas|numpy|matplotlib|plot
2
363,853
52,640,598
Python pandas dataframe: How to count and show the number of missing value in dataframe only?
<p>I would like to ask how to count and show the number of missing value in dataframe only? I am using: <code>df.isna().sum()</code> but it will show all columns including non-missing value columns. How can I only count and show the columns with missing value with descending order value counts in dataframe?</p> <p>...
<p>In my opinion simpliest is remove <code>0</code> values by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sort_values.html" rel="nofo...
python|pandas
1
363,854
52,674,895
My Tensorflow neural network is still pretty stupid, after much remedial education
<p>I am fairly new at image classification and tensor flow and have been engaged in a little toy project for self-education. It is an image classification project that sorts photographs of cars into 16 different classes. The photographs are taken from the Kaggle Carvana competition, which had different goals and evalua...
<p>It could be that your Network is too small. You are just using two hidden layers. The number of hidden units seem quite low. Try increasing your layer number and size. </p> <p>Another idea is to use CNN layers for your classification problem, since they tend to be better for image classification then normal feed fo...
python|tensorflow|image-processing
0
363,855
52,545,145
Python panda read_csv converting data during import problem with "-" value in data
<p>I've been struggling for a while with this issue. I finally found the reason why it happens but can't find a solution yet.</p> <p>I'm importing data.csv that is scraped from different resources on the web. MOst of them are strings and need to be stripped eg "%". This works like a charm using a custom converter. </p...
<p>I suggest you do : </p> <pre><code>def convert_percentage(val): new_val = val.replace(',','').replace('%', '') try: return float(new_val) except ValueError: return new_val </code></pre> <p>You can obviously add more return depending on what you want to return. If you think the if should...
python|pandas
0
363,856
52,803,292
Pandas column to numpy arrays
<p>I have the following dataframe:</p> <pre><code> name day value time 0 MAC000002 2012-12-16 0.147 09:30:00 1 MAC000002 2012-12-16 0.110 10:00:00 2 MAC000002 2012-12-16 0.736 10:30:00 3 MAC000003 2012-12-16 0.404 09:30:00 4 MAC000003 2012-12-16 0.845 10:00:00 </c...
<p>You're probably going down the wrong track:</p> <ul> <li><code>pd.pivot_table</code> won't get you what you want here, by default it gives the <em>mean</em> by group. While you want to keep all values.</li> <li>NumPy arrays only give large benefits for fixed dimensions, e.g. same number of columns for each row. Her...
python|pandas|numpy|pandas-groupby
1
363,857
52,655,536
pandas - Pythonic way to slicing DataFrame with DateTimeIndex
<p>This question uses <code>Python-3.7</code> and <code>pandas-0.23.4</code>.</p> <p>I'm currently dealing with financial datasets that I need to <em>only</em> retrieve the data of each trading day between 08:15 to 13:45</p> <h2>Variable Setup</h2> <p>To illustrate this, I have a <code>DataFrame</code> variable with...
<p>Yes, this functionality is built in with <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.between_time.html" rel="nofollow noreferrer"><code>DataFrame.between_time</code></a></p> <pre><code>y.between_time("08:15", "13:45") </code></pre>
python|pandas|slice|datetimeindex
4
363,858
52,462,808
Tensorflow-Lite - Benchmark tool - Varying results
<p>I'm trying to use the <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/lite/tools/benchmark#on-android" rel="nofollow noreferrer">TFLite Benchmark tool</a> with mobilenet model and checking the final <code>inference time</code> in microseconds to compare different models. The issue I ...
<ol> <li><p>As the docs suggest, any value is fine, as long as you stay consistent with one across experiments. The one thing to consider is whether to use a big core or a little core (if you're a big.little architecture) and usually it's good to try both (they have varying cache sizes, etc.)</p></li> <li><p>Yes you ca...
android|performance|tensorflow|tensorflow-lite
1
363,859
52,815,779
Pandas Spread DF to Indicator DF
<p>I have a dataframe like this</p> <pre><code>import pandas as pd test = pd.DataFrame(data={"IDX": [0,0,0,1,1,2], "VAL": [27,5,13,27,24,13]}) IDX VAL 0 0 27 1 0 5 2 0 13 3 1 27 4 1 24 5 2 13 </code></pre> <p>And want to spread it so the IDX becomes the ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow noreferrer"><code>get_dummies</code></a> with <code>max</code>:</p> <pre><code>df = pd.get_dummies(test.set_index('VAL')['IDX'].sort_index()).max(level=0) print (df) 0 1 2 VAL 5 1 0 0 13 ...
python|pandas
3
363,860
52,866,449
Tensorflow RNN how to create zero state with various batch size?
<p>In this question <a href="https://stackoverflow.com/questions/39112622/how-do-i-set-tensorflow-rnn-state-when-state-is-tuple-true">How do I set TensorFlow RNN state when state_is_tuple=True?</a>: the accepted answer initialize the initial state like this:</p> <pre><code>state_placeholder = tf.placeholder(tf.float32...
<p><code>cell.zero_state</code> accepts a scalar tensor.</p> <p>Get the batch size of the place holder via <code>tf.shape</code>, then it is done: <code> B = tf.shape(state_placeholder)[0] # the batch size scalar tensor initial_state = cell.zero_state(B) </code></p>
python|tensorflow|lstm|rnn
1
363,861
52,535,214
Pandas comparing multiindex dataframes without looping
<p>I want to compare two multiindex dataframes and add another column to show the difference in values (if all index value match between the first dataframe and second dataframe) without using loops</p> <pre><code>index_a = [1,2,2,3,3,3] index_b = [0,0,1,0,1,2] index_c = [1,2,2,4,4,4] index = pd.MultiIndex.from_arrays...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.reindex_like.html" rel="nofollow noreferrer"><code>reindex_like</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a> for intersection...
python|python-3.x|pandas
3
363,862
52,790,497
pandas custom sorting multilevel index
<p>I have the following example dataset, and I'd like to sort the index columns by a custom order that is not contained within the dataframe. So far looking on SO I haven't been able to solve this. Example:</p> <pre><code>import pandas as pd data = {'s':[1,1,1,1], 'am':['cap', 'cap', 'sea', 'sea'], ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="noreferrer"><code>sort_values</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="noreferrer"><code>sort_index</code></a></p> <pre><code>df.so...
python-3.x|pandas
5
363,863
52,508,642
Importing file containing text and numerical data using Python
<p>I have a <strong>.txt</strong> file which has text data and numerical data. The first two rows of the file have essential information in text data form, while the first column (I am referring to the zeroth column as the first column) also has essential data in text form. At all other locations in the file, the data ...
<p>If I were you, I would use <code>pandas</code>, and import it using something like this:</p> <pre><code>df = pd.read_csv('dum.txt',sep='\t', header=[0,1], index_col=0) </code></pre> <p>This gives you the dataframe:</p> <pre><code>&gt;&gt;&gt; df Type T1 T2 T3 T4 T5 Tag Good Good Good Good Good ob...
python|python-2.7|pandas|numpy
4
363,864
52,875,986
Rolling Covariance on DF
<p>I have following df:</p> <pre><code> Close_x Close_y key_0 2017-10-23 NaN NaN 2017-10-24 -0.147631 0.161791 2017-10-25 0.044194 -0.466305 2017-10-26 -0.069876 0.127095 2017-10-27 0.142261 0.807302 2017-10-30 -0.178176 -0.319247 2017-10-31 0.108544 0.094446 2017...
<p>To obtain the covariance between the columns you can do:</p> <pre><code> df.rolling(21).cov() Close_x Close_y key_0 2017-10-23 Close_x NaN NaN Close_y NaN NaN 2017-10-24 Close_x NaN NaN Close_y N...
pandas
2
363,865
52,561,031
pandas: sorting and dropping rows from a grouped dataframe
<p>I have a dataframe:</p> <pre><code>import pandas as pd df = pd.read_csv('test.csv') brand rating 0 a 81 1 a 83 2 a 60 3 a 45 4 b 73 5 b 55 6 b 90 7 c 60 8 d 70 9 e 75 10 e 80 11 e 85 </code></p...
<p>You may use a <code>tuple</code> key to index the <code>MultiIndex</code> of your DataFrame:</p> <pre><code>s = df.groupby('brand').agg(['count', 'mean']) s[s[('rating', 'count')] &gt;= 3].sort_values(by=('rating', 'mean')) </code></pre> <p></p> <pre><code> rating count mean brand a 4 ...
python|pandas|pandas-groupby
1
363,866
52,679,418
pandas series sum shows extra precision
<p>I am trying to sum a simple pandas series, and i am getting extraneous results ( by way of extra precision). </p> <p>Here is the scenario:</p> <pre><code>import pandas as pd prices = [2.99, 4.45, 1.36] s = pd.Series(prices) s.sum() </code></pre> <p>shows the output:</p> <pre><code>8.8000000000000007 </code></pr...
<p>If you are okay working with DataFrame then this can be easily achieved with- </p> <pre><code>import pandas as pd prices = [2.99, 4.45, 1.36] s = pd.DataFrame(prices) with pd.option_context('display.precision', 2): print(s.sum()) </code></pre> <p>Will output- </p> <pre><code>8.81 </code></pre> <p>EDIT: Or...
python|pandas|precision|series
1
363,867
52,479,129
Retrieving value using .loc and dates
<p>I have three DataFrames. One for daily FX prices <code>d_fx</code>, one for daily NAV values <code>d</code>, and one for reference data <code>m</code>. Examples below:</p> <pre><code> EUR GBP USD date 2012-01-01 1.2961 1.5543 1.0 2012-01-02 1.2934 1.5514 1.0 2012-...
<p>Use <code>rename</code> by column <code>FUND_TOTAL_ASSETS_CRNCY</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.lookup.html" rel="nofollow noreferrer"><code>DataFrame.lookup</code></a>:</p> <pre><code>d = d.rename(index=m['FUND_TOTAL_ASSETS_CRNCY'], level=0) print (d) ...
python|python-3.x|pandas
1
363,868
52,480,839
Slow pd.to_datetime()
<p>I am reading two types of csv files that are very similar. They are about the same lenght, 20 000 lines. Each line represent parameters recorded each second. Thus, the first column is the timestamp.</p> <ul> <li>In the first file, the pattern is the following: 2018-09-24 15:38</li> <li>In the second file, the patte...
<p><code>pandas.to_datetime</code> is extremely slow (in certain instances) when it needs to parse the dates automatically. Since it seems like you know the formats, you should explicitly pass them to the <code>format</code> parameter, which will greatly improve the speed.</p> <p>Here's an example:</p> <pre><code>impor...
python|pandas|string-to-datetime
8
363,869
52,828,042
insert dataframe to the existing csv from certain row
<p>I have an existing csv file, I want to insert more rows from the top row of the csv. It looks there is no way if using pandas.to_csv, any idea?</p> <p>e.g. existing file:</p> <pre><code>Date lowprice openprice 2018-9-28 10 11 2018-9-27 12 11.5 </code></pre> <p>I want to insert this dataframe </...
<p>You can do this as follows:</p> <ul> <li>read the original data into a DataFrame</li> <li>insert the data you want to add in the correct position in the DataFrame</li> <li>write the DataFrame into a csv file</li> </ul> <p>This is the only realistic way to do this; there is no way to delete or insert contents into ...
python|pandas|csv
0
363,870
52,577,420
ValueError: shape mismatch
<p>I am trying K-means image compression, but I am getting this error </p> <pre><code>File "C:/Users/[user]/PycharmProjects/project/CompressMe.py", Line23, in &lt;module&gt; final[pixel_centroids == cluster_no] = cluster_centers[cluster_no] ValueError: shape mismatch: value array of shape (4,) could not be broadc...
<p>You hardcoded the number of png output channels to 3, which could be different to the input, when you initialize the "final" array. Correct the following lines:</p> <p><code>final = np.zeros((pixel_centroids.shape[0], img_np.shape[2]))</code></p> <p>and</p> <p><code>comp_image = final.reshape(img_np.shape[0], img...
python|numpy|k-means
1
363,871
52,827,625
Pandas - Sum of first X hours of datetime index
<p>I have a dataframe with a datetime index and 100 columns.</p> <p>I want to have a new dataframe with the same datetime index and columns, but the values would contain the sum of the first 10 hours of each day.</p> <p>So if I had an original dataframe like this:</p> <pre><code> A B C ----...
<p>You need <code>groupby</code> <code>df.index.date</code> and use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.transform.html" rel="nofollow noreferrer"><code>transfrom</code></a> with lambda function to find sum of first 10 values as:</p> <pre><code>df.loc[:,['A','B','C']] = df.g...
python|pandas|group-by
3
363,872
52,723,753
Keras model not saving correctly
<p>I am training a neural network in Keras but when new data comes and I try to retrain it, the loss in the epochs it's as high as the first time I trained my model. </p> <pre><code> checkpoint = ModelCheckpoint('my_model.h5', monitor='loss', verbose=1, save_best_only=True, mode='min') callbacks_list = [checkpoint] ...
<p><code>ModelCheckpoint</code> saves the model weighs that has had less loss in training.</p> <p>Your <code>model</code> has saved the last epoch weighs.</p> <p>If the last epoch of your model is not the one that has had less loss, the weights of the saved model (<code>new_model</code>) do not match those of the ori...
python|tensorflow|keras
1
363,873
52,664,569
Pyinstaller & pandas: Python.Runtime not found
<p>I'm trying to build an executable from a module of mine with pyinstaller but every attempt to do this ended with: </p> <pre><code>File "C:\Python 3.6.5\lib\site-packages\PyInstaller\hooks\hook-clr.py", line 37, in &lt;module&gt; raise Exception(pyruntime + ' not found') </code></pre> <p>Exception: Python.Runtime n...
<p>For me, this issue went away when I installed pythonnet: <code>pip install pythonnet</code></p>
python|pandas
4
363,874
52,559,709
Filtering dataframe in pandas based on a list of strings
<p>I have started exploring pandas recently, I am trying to import a list of fruits from sector.py and use it as a filter to produce a table of items where only fruits within the list are displayed. I am not getting the output desired is there something wrong with my codes?</p> <p>Within sector.py</p> <pre><code>Frui...
<p>Applying <code>isin</code> on a <code>GroupBy</code> object doesn't make sense. You can use Boolean indexing on the <em>index</em> of your <code>GroupBy</code> object:</p> <pre><code>Fruits = pdextract[pdextract.index.isin(sector.Fruits)] </code></pre> <p>You can also filter on a series <em>before</em> your <code>...
python|python-2.7|pandas|indexing|pandas-groupby
3
363,875
52,582,566
Python NetworkX converting Panda's ints to floats
<p>I am trying to build networkx diagrams from a pandas dataframe, with a position array for nodes when drawing. The issue that I am having is when including pandas columns as edge attributes. If the attribute column is type float, it will convert the value of node ids (int) into float types, which then causes issues ...
<p>Ok yup it really helps to read the documentation, as this issue was right there. for anyone else who wants to get around this you can just write your own to use itertuples instead of iterrows, which doesn't conserve dtype.</p> <pre><code>def pandas_to_Network(df,UpNode,DownNode,Attributes): #Create a graph ...
python|pandas|networkx
0
363,876
52,898,784
Freezing weight of neural network such that its output takes a particular value at a particular point (tensorflow)
<p>Let's say I have a neural network that looks like this</p> <pre><code>def neural_net(x): layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) layer_1 = tf.nn.sigmoid(layer_1) layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2']) layer_2 = tf.nn.sigmoid(layer_2) out_layer = t...
<p>Sure, however, the answer depends a bit on the purpose. </p> <p>The easiest solution is to just scale the output. For example by running the result through a linear regressor. While this gives the desired result it is probably not what you want.</p> <p>However, probably the better way is to integrate this addition...
python|tensorflow|machine-learning|neural-network
1
363,877
52,717,630
Training crash due to saving model: "tensorflow.GraphDef was modified concurrently during serialization"
<p>I am currently trying to train a model, and my input pipeline is constructed as of this answer <a href="https://stackoverflow.com/a/47967475/8188358">here</a>. I want to save my model after each epochs. But after training for some epochs the training crash. I have read that it is because it adds the input as a const...
<p>The problem looks like it is in the <code>_parse_function</code>. Make sure the parser is doing in the same way when you create the TFrecord file. For example if they have the same data type or so</p>
python|tensorflow|machine-learning|deep-learning|tensorflow-datasets
1
363,878
52,741,133
Delete specific values from data frame with python pandas
<p>Trying to cut the noise out of time waves, I want to delete specific but different values in the rows of a very big data frame. I could find only options of deleting whole rows or columns, but this is not what I need. one row corresponds to a measurement id (30k in total) and one column to a time step (2500 in total...
<p>To modify specific values in a row of a data frame, you can use the applymap method.</p> <p>Suppose you have a list of values you want to replace inside your data frame:</p> <pre><code>import numpy as np import pandas as pd value_to_remove=[4,6,10] arr=np.reshape(np.arange(16),(4,4)) df=pd.DataFrame(arr,columns=...
python|pandas|numpy
0
363,879
52,547,157
Pytorch 0.4.1 invalid gradient at index 0 - expected shape[] but got [1]
<p>I've been around this problem for the whole day.</p> <p><code>torch.autograd.backward(loss_seq, grad_seq)</code> will get an error.</p> <p>Output:</p> <pre><code>Traceback (most recent call last): File "train_vgg.py", line 272, in &lt;module&gt; torch.autograd.backward(loss_seq, grad_seq) File "/root/anac...
<p>I have solved this problem. Only change:</p> <p><code>grad_seq = [torch.ones(1).cuda(gpu) for _ in range(len(loss_seq))]</code></p> <p>to:</p> <p><code>grad_seq = [torch.tensor(1.0).cuda(gpu) for _ in range(len(loss_seq))]</code></p>
python|pytorch
1
363,880
52,493,708
Value not in index when subsetting dataframe
<p>I'm having trouble with a dataframe in Python.</p> <p>I would like only those columns with a particular text ("Grado en"), but I get the error: </p> <blockquote> <p>Cannot index with vector containing NA / NaN values when there are not NA's or NaN's.</p> </blockquote> <p>If I use the option <code>na=False</code...
<p>This works with pandas 0.23.3:</p> <pre><code>(df_graus .assign(title = lambda d: d.title.apply(str)) # convert title elements from bs4 to string .loc[lambda d: d.title.apply(lambda elt: "Grado en" in elt)] # filter in strings that contain "Grado en" ) </code></pre>
html|python-3.x|pandas|parsing|beautifulsoup
1
363,881
52,641,423
Fail to load frozen model in Tensorflowjs
<p>I try to load converted tensorflow model, but console shows the error as the following:</p> <p>Version:</p> <pre><code>"dependencies": { "@tensorflow-models/posenet": "0.1.2", "@tensorflow/tfjs": "0.11.4", "@tensorflow/tfjs-converter": "^0.6.1", "asyncawait": "^1.0.7", "stats.js": "^0.17.0" }...
<p>You have to pass the storage type to <code>loadFrozenModel()</code>. Which would be in your case: <code>file:///</code>.</p> <p>Another problem in you code is that the immediatly called async function doesn't return anything, so your model variable stays undefined.</p> <p>To fix both:</p> <pre><code>(async () =&g...
javascript|tensorflow.js
0
363,882
52,848,973
TensorFlow use dataset to replace function feed_dict
<p>when I learn a tensorflow project,find one line code:</p> <pre><code>cls_prob, box_pred = sess.run([output_cls_prob, output_box_pred], feed_dict={input_img: blob}) </code></pre> <p>But, this line code It took a lot of time. (use CPU need 15 seconds...┭┮﹏┭┮)</p> <p>By consulting information, I find use function 'd...
<p><code>tf.data</code> is the recommended API for tensorflow input pipelines. Here is a tutorial on <a href="https://www.tensorflow.org/guide/datasets" rel="nofollow noreferrer">tensorflow.org</a>. For your example, the section <a href="https://www.tensorflow.org/guide/datasets#decoding_image_data_and_resizing_it" rel...
python|tensorflow
1
363,883
52,619,344
Index - Match using Pandas
<p>I have the following 2 data frames:</p> <pre><code>df1 = pd.DataFrame({ 'dates': ['02-Jan','03-Jan','30-Jan'], 'currency': ['aud','gbp','eur'], 'amount': [100,330,500] }) df2 = pd.DataFrame({ 'dates': ['01-Jan','02-Jan','03-Jan','30-Jan'], 'aud': [0.72,0.73,0.74,0.71], 'gbp': [1.29,1.30,1.4...
<p>The best equivalent of INDEX MATCH is <code>DataFrame.lookup</code>:</p> <pre><code>df2 = df2.set_index('dates') df1['price'] = df2.lookup(df1['dates'], df1['currency']) </code></pre>
python|pandas|dataframe|lookup|data-munging
4
363,884
52,897,457
Numpy Matrix Memory size low compared to Numpy Array
<p>I have a .npz file which I want to load into RAM . The compressed file size is 30MB . I am doing the following operation to load the data into RAM.</p> <pre><code>import numpy as np from scipy import sparse from sys import getsizeof a = sparse.load_npz('compressed/CRS.npz').todense() getsizeof(a) # 136 type(a) # n...
<p>Your <code>a</code> matrix is a view of another array, so the underlying data is not counted towards its <code>getsizeof</code>. You can see this by checking that <code>a.base is not None</code>, or by seeing that the <code>OWNDATA</code> flag is <code>False</code> in <code>a.flags</code>.</p> <p>Your <code>b</code...
python|numpy|memory
3
363,885
52,857,702
Comma Separate Pandas DataFrame on Thousands
<p>I have a pandas dataframe with all floats. I'd like to turn these into <em>integers</em>, with thousands-separator. For example, 10000.00 would be 10,000. The dataframe only has floats with no null value.</p> <p>Currently I am looping on the dataframe's rows. Example code:</p> <pre><code>for i in range(df.shape[0]...
<p><code>.applymap()</code> can apply a function across each of the elements in a whole dataframe: </p> <pre><code>In [14]: df Out[14]: 0 1 2 3 4 0 178711.734521 118958.200494 54379.699539 72575.737361 129236.395323 1 132075.638310 37217.5049...
python|pandas|loops|dataframe
0
363,886
52,665,567
AttributeError: 'NoneType' object has no attribute 'isnull'
<p>I'm trying to remove the empty rows. But when I try to count empty lines to see if it worked, I have an error:</p> <blockquote> <p>AttributeError: 'NoneType' object has no attribute 'isnull'</p> </blockquote> <p><strong>My script:</strong> </p> <pre><code>import pandas import pandas as pd data = pd.read_csv('d...
<p>When you do an operation on a df with <code>inplace=True</code>, the variable or output of that operation is None.</p> <pre><code>data_sum_empty.dropna(how = 'all', inplace = True) data_not_empty = data_sum_empty.copy() print(data_not_empty.isnull().sum()) </code></pre> <p>Or</p> <pre><code>data_not_empty = data_...
python-3.x|pandas
4
363,887
52,761,485
How to add columns to a pandas Dataframe that has row filled with range based on a column value
<p>I created a df and then repeated rows in that df based on values in a column. For example:</p> <pre><code>df = pd.DataFrame({ 'a': [1,2,3], 'b': ['x','y','z'] }) </code></pre> <p>Then I repeated the rows based on a col value like this:</p> <pre><code>df = df.loc[df.index.repeat(df['a'])] ...
<p>First use<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>cumcount</code></a> by values of index and then create default <code>index</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset...
python|pandas
1
363,888
52,799,777
Python delete row from a DataFrame based on another DataFrame with less variables
<p>I have df1 like this:</p> <pre><code>id 1 2 3 4 5 0 1 1 0 0 0 1 1 0 1 0 0 2 1 0 0 0 1 </code></pre> <p>The I have df (less columns, less cases) with this values:</p> <pre><code>id 1 2 5 0 1 1 0 1 1 0 1 </code></pre> <p>I would like to delete from df1 the rows that share the same val...
<p>This will solve your problem:</p> <pre><code>print (pd.merge(df1,df2, indicator=True, how='outer') .query('_merge=="left_only"') .drop('_merge', axis=1)) </code></pre>
python|python-3.x|pandas|numpy|dataframe
2
363,889
52,822,382
Unable to train in Google Cloud ML
<p>I'm not being able to train in ML Engine. The training always stop around iteration 60. I have used Keras to build the model layers, but I train using <code>tf.Session</code>.</p> <p>I get this error, but no traceback.</p> <pre><code>ERROR 2018-10-15 10:31:02 -0700 master-replica-0 name: Tesla P100-PCIE...
<p>I figure out it was very very slow. So it gave me the impression the problem was on the training. I presumed was a problem with distributed training because Keras layers.</p> <p>I changed the config to use <code>complex_model_l_gpu</code> and it worked.</p>
tensorflow|google-cloud-ml
0
363,890
52,712,761
Python Pandas: getting the rows with highest value
<p><a href="https://i.stack.imgur.com/Ta61n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ta61n.png" alt="Dataframe"></a></p> <p>Hello! I have a dataframe with year (1910 ~ 2014), name, count (number of occurrence of each name) as columns. I want to create a new dataframe that shows the name with ...
<p>Vectorized way</p> <pre><code>group = df.groupby('year') df.loc[group['count'].agg('idxmax')] </code></pre>
python|pandas
1
363,891
52,564,186
Vectorized lookup another row + calculated field
<p>I have this DataFrame "dfSummary" - </p> <pre><code>exchangeBalances = [['ETHBTC','binance',10], ['LTCBTC','binance',10], ['XRPBTC','binance',10], ['ETHBTC','bitfinex',10], ['LTCBTC','bitfinex',10], ['XRPBTC','bitfinex',10]] bidOffers = [ ['ETHBTC','binance', 0.0035, 0.0351, datetime(2018, 9, 1, 8, 15)...
<p>I got it, here's my <em>real</em> code (So I am not posting everything). This will work (but not sure if this is implemented the <strong>fastest</strong> way). </p> <p>I am using <strong><em>DataFrame.apply</em></strong>. This is <strong>NOT</strong> <strong>Vectorized</strong> way, but should be a lot faster than ...
python|pandas
1
363,892
52,808,839
my data cleaning script is slow, any ideas on how to improve?
<p>I have a Data(csv format) where the first column is an epoch timestamp(strictly increasing) and the other columns are cumulative rows(just increasing or equal). Sample is as below:</p> <pre><code>df = pandas.DataFrame([[1515288240, 100, 50, 90, 70],[1515288241, 101, 60, 95, 75],[1515288242, 110, 70, 100, 80],[15152...
<p>IIUC, can use </p> <pre><code>cols = ['A', 'B', 'C', 'D'] mask_1 = df['UNIX_TS'] &gt; df['UNIX_TS'].cummax().shift().fillna(0) mask_2 = mask_2 = (df[cols] &gt;= df[cols].cummax().shift().fillna(0)).all(1) df[mask_1 &amp; mask_2] </code></pre> <p>Outputs</p> <pre><code> UNIX_TS A B C D 0 1515288240...
python|pandas|dataframe|data-science|data-cleaning
2
363,893
52,795,551
Predictions in recorded video using object detection tensorflow API
<p>I am trying to read a video file (using opencv), loop over all frames using tensorflow's object-detection API to do the predictions and bounding boxes, and writing the predicted frames (with boxes) to a new video file. I used the object_detection_tutorial.ipynb with some modifications to capture the video frames and...
<p>Actually the problem is with the model you were using. <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md</a> Basically the ...
tensorflow|object-detection|object-detection-api
0
363,894
52,455,549
TypeError: Mismatch between array dtype ('object') and format specifier ('%d %d')` when saving pandas file to text
<p>I am trying to save a line of panda values into a textfile, but I get the <code>Error: TypeError: Mismatch between array dtype ('object') and format specifier ('%d %d')</code> Can anyone explain me what that means and how to fix it? What I specifically want to do is that each time this function is called a new line...
<p>Since your data is of <code>object</code> type, you should print it using <code>fmt='%s'</code> to get the <code>str()</code> conversion of each value, rather than <code>fmt='%d'</code> which converts to integers.</p>
python|pandas|typeerror
1
363,895
52,685,239
Just create a column with all days of one month - with pandas
<p>I really try for more than 4 hour to do a simple task: Create a column in a df with pandas that represent from day one to last day of the month. For example:</p> <pre><code>index date 0 2018-08-01 1 2018-08-02 2 2018-08-03 ... ... </code></pre> <p>I'm giving up and do this in excel, save in csv to im...
<p>Ok, sure... I could not hold myself to write an answer to your question. When you say all the days in one month I directly think of: <code>how do we get the last day?</code> And the answer to that is using an offset (which is build-in in Pandas already).</p> <p>Apart from that you are instersted for what in Pandas...
python|pandas
5
363,896
52,792,692
Anaconda Python - how to reinstall NumPy
<p>I am using Anaconda 5.3.0's Python interpreter in Visual Studio Code. When I try to import <code>sklearn</code> I get an error:</p> <pre><code>Traceback (most recent call last): File "c:\Users\azzam\machinelearning.py", line 1, in &lt;module&gt; import sklearn File "C:\Anaconda3\lib\site-packages\sklearn\__...
<p>How to reinstall a package depends on the conda version.</p> <p><a href="https://docs.conda.io/projects/conda/en/latest/commands/install.html?highlight=force-reinstall" rel="noreferrer">newer versions</a> (>= 4.6):</p> <pre><code>conda install numpy --force-reinstall </code></pre> <p>older versions (&lt; 4.6):</p...
python|numpy|scikit-learn|anaconda|conda
89
363,897
52,466,844
Pandas corr() returning NaN too often
<p>I'm attempting to run what I think should be a simple correlation function on a dataframe but it is returning NaN in places where I don't believe it should. </p> <p><strong>Code:</strong></p> <pre><code># setup import pandas as pd import io csv = io.StringIO(u''' id date num A 2018-08-01 99 A 2018-08-02...
<p>The result seems to be an artefact of the data you work with. As you write, <code>NA</code>s are ignored, so it basically boils down to:</p> <pre><code>df[['B', 'C']].dropna() B C 1 100.0 100.0 6 500.0 300.0 </code></pre> <p>So, there are only two values per column left for the calculation which s...
python|pandas|dataframe|statistics|correlation
12
363,898
52,497,995
Filled 3D numpy mask
<p>I have a binary (0-1) 3D numpy array, which I plan to use for masking a 3D image. The mask at the moment consists in the area of a cylinder. The two centres of the faces are two arbitrary points, and the axis is not parallel to x, y or z. How can I fill the cylinder with a pure numpy solution?</p>
<p><strong>EDIT</strong>: <code>pymrt.geometry</code> has been removed in favor of <a href="https://pypi.org/project/raster-geometry/" rel="nofollow noreferrer"><code>raster_geometry</code></a>.</p> <hr> <p>Given that a cylinder is a convex shape, it is possible to loop through all but 1 dimension and reduce the prob...
python-2.7|numpy|geometry
2
363,899
52,744,139
create labels in a new data frame column based on partial string match of a different column
<p>First, I have looked at many SO threads on this and none seemed to work in make case. <a href="https://stackoverflow.com/questions/21702342/creating-a-new-column-based-on-if-elif-else-condition">Creating a new column based on if-elif-else condition</a> seemed to be the closest to what I am trying to do.</p> <p>In ...
<p>function in df.apply() should apply to each row of df, not for entire df.</p> <pre><code>In [37]: df = pd.DataFrame({'product':['aProcedings', 'aDVD','vcd']}) In [38]: def label_sub_cat(row): ...: if 'Procedings' in row['product']: ...: return 'Proceedings' ...: elif 'DVD' in row['product']: ...: ...
python|python-3.x|pandas
1