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
355,500
62,068,886
adding values to pandas dataframe columns based on another dataframe
<p>I have a dataframe that looks like this(df):</p> <pre><code>HOUSEID PERSONID WHY_TRP 20000017 1 1 20000017 1 1 20000017 1 1 20000017 2 1 20000017 2 3 20000231 1 11 20000231 1 11 20000231 2 ...
<p>You can get a table of the counts by doing a <code>groupby</code> on the first dataframe and unstacking <code>WHY_TRP</code>, and then you can just merge it to the second:</p> <pre><code>counts = df.groupby(["HOUSEID", "PERSONID", "WHY_TRP"]).apply(len).unstack(fill_value=0) counts.columns = counts.columns.map(lam...
python|pandas
1
355,501
62,428,232
ConvLSTM2D after a Conv2D layer in keras or tensorflow
<p>The process goes like this: <code>x(batch, time, w, h, c)</code> => <code>Reshape</code> => <code>(batch*time, w, h, c)</code> => Conv2D => Reshape => <code>(batch,time, w, h, c')</code> => ConvLstm2d => ... <br><br> The <code>tf.keras.layers.Reshape</code> can only reshape the non-batch_size portion, which I can no...
<p>You are right, <code>tf.keras</code> does not support batch dimension reshaping - if you need a layer that would do that, and still work with <code>tf.keras</code> just write a custom layer</p> <pre class="lang-py prettyprint-override"><code>class BatchAwareReshape(tf.keras.layers.Layer): def __init__(self, sha...
tensorflow|keras|tensorflow2.0
1
355,502
62,262,847
Python - Converting a year beyond 3000 is not happening using to_datetime() function
<p>I have a date in the format 30191209 in a dataframe. This needs to be converted to 3019-12-06. I used the below code, but i still face issue where the converted format returns Blank.</p> <pre><code>df['Formated Date'] = df['mat date'] df['Formated Date'] = df['Formated Date'].apply(lambda x: pd.to_datetime(str(int(...
<p>You cant do that with pandas since it exceeds the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.max.html" rel="nofollow noreferrer">max timestamp</a>. Try using a <a href="https://docs.python.org/3/library/datetime.html" rel="nofollow noreferrer">datetime</a> object:</p> <pre>...
python|pandas|datetime
0
355,503
62,360,318
Passing a list of itertools combinations to a function - map?
<p>Python Noob here, sorry. I'm playing with Anscombe's quartet to explore the idea of how "fragile" correlations are by removing individual points (replacing with the group median) and then iterating through the data to return the Pearson r and p-value, then plotting both for every item in the source vector (Anscombe'...
<p>OK, I've figured it out, so posting the code here in case this ever helps someone else. I was on the wrong track entirely. The example here passes the 3rd member of Anscombe's quartet hard-coded in as the x,y values and an n of 3 (for all combinations of 3 values) but you can obviously swap these out for whatever yo...
python|numpy|dictionary|statistics|itertools
0
355,504
62,296,537
Add call sequence number as new column to large pandas DataFrame by unique row id
<h1>Background</h1> <p>I'm not really sure how to describe the problem I'm having but I am mostly looking for help in optimizing. I have a very large dataset (100M+ records) that I need to add a column to the DataFrame with the number of attempts to the unique row (by <code>row</code> in the example). </p> <p>Each ...
<p>First we fill the new <code>call_index</code> column with <code>1</code>, then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.cumsum.html" rel="nofollow noreferrer"><code>cumsum</code></a> per row group and decrease this cumsum by 1 to make it start from 0 instead of 1:</p> <pr...
python|pandas
1
355,505
62,425,957
Generate High, Medium, Low categories from a skewed distribution
<p>I have been working on a Churn Prediction use case in Python using XGBoost. The data trained on various parameters like Age, Tenure, Last 6 months income etc gives us the prediction if an employee is likely to leave based on its employee ID. Additionally, if the user wants to the see why this ML system categorised ...
<p>EDIT: Thanks for the clarification. I have changed the answer.</p> <p>It is important to realize that you are trying to project a selection in multi-dimensional space into a 1D space. Not in every case you will be able to see a clear separation like the one you got. There are also various possibilities to do that, h...
python-3.x|pandas|xgboost|predictive
2
355,506
62,345,067
AWS Lambda running tensorflow packages exceed limit 250 MB
<p>I need to do a segmentation prediction for a tensorflow-keras model. My idea was to upload an image into an S3 bucket, and with the AWS Lambda service, trigger the process, do the prediction and save the segmented predicted mask into a new S3 bucket.</p> <p>At the beginning, I created some layers with the below lib...
<p>UPDATE: AWS Lambda now provides <a href="https://aws.amazon.com/blogs/aws/new-for-aws-lambda-container-image-support/" rel="nofollow noreferrer">container deployment support</a>, allowing for a 10GB Lambda, which would make it possible to run larger workloads on AWS Lambda, AWS Lambda <a href="https://aws.amazon.com...
python|tensorflow|deep-learning|aws-lambda
-1
355,507
62,361,446
Python dataframe get index start and end of successive values
<p>Let's say I have this dataframe : </p> <pre><code> 0 0 1 1 1 2 1 3 2 4 2 5 3 6 3 7 1 8 1 </code></pre> <p>I want to store the start and end indexes of each value (even repeated ones) in the dataframe as well as the value corresponding.</p> <p>So that I would get a result like this for example : </p> <...
<p>Given</p> <pre><code>&gt;&gt;&gt; df 0 0 1 1 1 2 1 3 2 4 2 5 3 6 3 7 1 8 1 </code></pre> <p>Solution:</p> <pre><code>starts_bool = df.diff().ne(0)[0] starts = df.index[starts_bool] ends = df.index[starts_bool.shift(-1, fill_value=True)] result = (df.loc[starts] .reset_index(drop=True) ...
python|pandas|dataframe
4
355,508
62,337,076
Pandas - Applying Function to every other row
<p>I have a data frame and what I am trying to do is essentially tabulate the score of the winning and losing team in the same spot. I have tried to put a lambda function, but have had no success with it. The data frame I currently have is the first one and I would like to create a dataset in the form of the second que...
<p>Try this:</p> <p>Input:</p> <pre><code>import pandas as pd raw_df = pd.DataFrame({"GameId": [1, 1, 2, 2], "Team": ["Spirit", "Rockets", "Lighting", "Flames"], "Home": [1, 0, 1, 0], "Score": [81, 66, 73, 82]}) print(raw_df) </code></pre> <p>Outp...
python|pandas
4
355,509
62,305,477
Tensorflow on Java: how to perform RGB to BGR operation?
<p>I need to convert my 3-D tensor containing RGB image to BGR.</p> <p>All the sources I've found on the web use python and they refer to operations that are either absent or different on java:</p> <ol> <li>reverse does not accept an index but a boolean as second input</li> <li>I've found the stack/unstack method, bu...
<p><code>Stack</code> and <code>Unstack</code> operations are actually called as they have previously been on the other platforms, that is, <code>Pack</code> and <code>Unpack</code>. *</p> <p>So, to perform the requested operation of transforming a Tensor representing an image in RGB to an image in BGR, the unstack/st...
java|tensorflow
0
355,510
62,114,645
How to build OneHot Decoder in python
<p>I have <code>encoded</code> my <strong>images(masks)</strong> with dimensions <em>(img_width x img_height x 1)</em> with <code>OneHotEncoder</code> in this way:</p> <pre><code>import numpy as np def OneHotEncoding(im,n_classes): one_hot = np.zeros((im.shape[0], im.shape[1], n_classes),dtype=np.uint8) for i, un...
<p>You have typos with commas and dots with some of your items (e.g. your first list should be <code>[0.1, 0.2, 0.5]</code> instead of <code>[0.1, 0.2, 0, 5]</code>).</p> <p>The fixed list is:</p> <pre class="lang-py prettyprint-override"><code>l = [ [[0.1,0.2,0.5],[0.2,0.4,0.7],[0.3,0.5,0.8]], [[0.3,0.6,...
python|numpy|decoding|one-hot-encoding
0
355,511
62,250,083
Tensorflow can't handle multiple input
<p>Have one model to proccess image and one model to proccess numerical values. Merged both models getting this: <a href="https://i.stack.imgur.com/JC9Eh.png" rel="nofollow noreferrer">Merged model</a></p> <p>For the image input I created a image data generator from a dataframe + pictures:</p> <pre><code>print('Impor...
<p>In the fit method you should pass list of inputs instead of a dict. Same thing for the output. Your code should look like this</p> <pre class="lang-py prettyprint-override"><code>history = model.fit( [train_generator, X_train], y_train, epochs = 2, verbose = 2) </code...
python|pandas|tensorflow|keras
0
355,512
62,166,820
How to use TimeDistributed layer for predicting sequences of dynamic length? PYTHON 3
<p>So I am trying to build an LSTM based autoencoder, which I want to use for the time series data. These are spitted up to sequences of different lengths. Input to the model has thus shape [None, None, n_features], where the first None stands for number of samples and the second for time_steps of the sequence. The seq...
<p>this function seems to do the trick</p> <pre><code>def repeat(x_inp): x, inp = x_inp x = tf.expand_dims(x, 1) x = tf.repeat(x, [tf.shape(inp)[1]], axis=1) return x </code></pre> <p>example</p> <pre><code>input_ae = Input(shape=(None, 2)) LSTM1 = LSTM(units=128, return_sequences=False)(input_ae) ...
tensorflow|keras|lstm|autoencoder|seq2seq
2
355,513
62,230,095
Python: Aggregate the rows using the column values and delete one row for each key
<p>I am trying to find a way to remove all duplicated records from my DB.</p> <p>For example, if I have this table (stored in a CSV file):</p> <pre><code>colA colB 1 102 2 101 3 101 4 105 5 102 6 101 </code></pre> <p>If we aggregate the table using a <strong>groupBy</strong> for the c...
<p>Use, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.duplicated.html" rel="nofollow noreferrer"><code>Series.duplicated</code></a> along with optional parameter <code>keep=last</code>:</p> <pre><code>m = df['colB'].duplicated(keep='last') df = df[m] </code></pre> <hr> <pre><code>...
python|pandas|dataframe|duplicates
2
355,514
62,218,113
How to perform calculation based on index?
<p>Im very new to Python, hopefully someone can help to solve this issue. Im trying to create a calculation in power bi based on my index. The reason for that is because my index resets from 1 to 250 every time one of my columns has a new value. kind of index by category. Index: Trade day (1 to 250) Catogory; [contract...
<p>It looks like you can do with <code>groupby</code>:</p> <pre><code>df['Percent_Change'] = df.groupby('Year')['Norm_Price'].pct_change().fillna(0) df['Norm_Change'] = df['Percent_Change'].add(1).groupby(df['Year']).cumprod() </code></pre> <p>Output:</p> <pre><code> Trade Day Year Norm_Price Percent_Change N...
python|pandas
0
355,515
62,395,294
With Keras model.fit, how do you set it up to save every x number of steps?
<p>I would like to save my model every x number of steps when running model.fit. </p> <p>I am looking at the documentation <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit</a></p> <p>And there doesn't seem t...
<p>This can be done using the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/ModelCheckpoint" rel="nofollow noreferrer">ModelCheckpoint callback</a>:</p> <pre><code>EPOCHS = 10 checkpoint_filepath = '/tmp/checkpoint' model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint( filepath=c...
tensorflow|keras|tensorflow2.0|tf.keras
1
355,516
62,457,245
Google Sheets API and Pandas. Inconsistent data length from the API
<p>I'm using the google sheets API to get data which I then pass to Pandas so I can easily work with the data.</p> <p>Let's say I want to get a sheet with the following data (depicted as a JSON object as tables weren't presented here well)</p> <pre><code>{ columns: ['Name', 'Age', 'Tlf.' 'Address'], data: ['Julie...
<p>Same idea, maybe simpler look:</p> <p>Get raw values</p> <pre><code>result = service.spreadsheets().values().get(spreadsheetId=spreadsheet_id, range=data_range).execute() raw_values = result.get('values', []) </code></pre> <p>Then complete while iterating</p> <pre><code>for row in raw_values: row = row + [''] * ...
python|python-3.x|pandas|google-sheets|google-sheets-api
0
355,517
62,447,232
Getting an error "list index out of range" when executing tensorflow code
<p>I am trying to execute following code developed in tensorflow for GAN, but whenever I execute it I receive index error "list index out of range"</p> <pre><code> import pandas as pd import numpy as np import tensorflow as tf import time dataset = pd.read_csv('kagglecreditcard.csv') is_Class0 = dataset['Class'] == ...
<p>At this chunk of the code:</p> <pre><code>generator_optimizer = tf.keras.optimizers.Adam(1e-4) discriminator_optimizer = tf.keras.optimizers.Adam(1e-4) noise = tf.random.normal([1,30]) generator = make_generator() discriminator = make_discriminator() gen_out = generator(noise) disc_out = discriminator(gen_out) g...
python|tensorflow|machine-learning|deep-learning|generative-adversarial-network
0
355,518
62,213,381
Getting specific word from doc file respective of uppercase/lowercase using python
<p>I want to get some word in .doc file and append them all in list.</p> <p>Doc file content : <code>"i love Audi i love audi i love AuDi "</code></p> <p>When I give audi or Audi as an input, it should read all these three different "audi" and return list containing all three different audi.</p>
<p>Try regular expression where you do findall on word and ignore case</p> <pre><code>import re doc_content = 'i love Audi i love audi i love AuDi and audis but not audits or audiences' results = re.findall(r'\baudi[s]?\b', doc_content, re.IGNORECASE) #The ? metacharacter will match only one 's' following audi to in...
python|python-3.x|pandas
2
355,519
62,140,366
How to make function?
<pre><code>plt.figure(1) plt.subplot(121) sns.distplot(df['Age']) plt.subplot(122) df['Age'].plot.box(figsize=(16,5)) plt.show() </code></pre> <p>The only changes from one plot to another is the variable name (Age, Day_Scheduled...). You could create a function that accepts the dataframe df and the variable's name as...
<p>Well... you could do just that!</p> <pre><code>def my_plotting_function(df, variable): plt.figure(1) plt.subplot(121) sns.distplot(df[variable]) plt.subplot(122) df[variable].plot.box(figsize=(16,5)) plt.show() </code></pre>
python|pandas
0
355,520
62,422,274
can i install fashion mnist on older version of tensorflow?
<p>I'm working in tensorflow 1.4.0 and I want to use fashion_mnist datasets. I know that this version does not have this datasets, but there is a way to have this?</p>
<p>I've found the solution here: <a href="https://github.com/zalandoresearch/fashion-mnist" rel="nofollow noreferrer">Fashion-MNIST</a></p> <p>You can download the data that you find in the link above and placed it in data/fashion.</p> <pre><code>from tensorflow.examples.tutorials.mnist import input_data data = input...
python|tensorflow|keras|deep-learning
0
355,521
62,408,749
How to reset Keras metrics?
<p>To do some parameter tuning, I like to loop over some training function with Keras. However, I realized that when using <code>tensorflow.keras.metrics.AUC()</code> as a metric, for every training loop, an integer gets added to the auc metric name (e.g. auc_1, auc_2, ...). So actually the keras metrics are somehow st...
<p>Your reproducible example failed in several places for me, so I changed just a few things (I'm using TF 2.1). After getting it to run, I was able to get rid of the additional metric names by specifying <code>metrics=[AUC(name='auc')]</code>. Here's the full (fixed) reproducible example:</p> <pre><code>import numpy ...
python|tensorflow|machine-learning|keras|deep-learning
6
355,522
62,228,008
Shuffling rows in pandas but orderly
<p>Let's say that I have a data frame of three columns: age, gender, and country. </p> <p>I want to randomly shuffle this data <strong>but in an ordered fashion</strong> according to gender. There are n males and m females, where n could be less than, greater than, or equal to m. The shuffling should happen in such a...
<p>First add the sequence numbers within each group:</p> <pre><code>df['Order'] = df.groupby('Gender').cumcount() </code></pre> <p>Then sort:</p> <pre><code>df.sort_values('Order') </code></pre> <p>It gives you:</p> <pre><code> Age Gender Country Order 0 10 Male US 0 3 40 Female Canada ...
python|python-3.x|pandas
2
355,523
62,432,756
How to drop column from the target data frame, but the column(s) are required for the join in merge
<p>I have two dataframe df1, df2</p> <p>df1.columns</p> <pre><code>['id','a','b'] </code></pre> <p>df2.columns</p> <pre><code>['id','ab','cd','ab_test','mn_test'] </code></pre> <p>Expected out column is <code>['id','a','b','ab_test','mn_test']</code></p> <ul> <li><p>How to get the all the columns from df1, and co...
<p>You can <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> and use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>filter</code></a> one the...
python|pandas
2
355,524
62,146,622
Why is the training accuracy fluctuating?
<p>I'm working with a video classification of 5 classes and using TimeDistributed CNN model in Google Colab platform. The training dataset contains 80 videos containing 5 frames each. The validation dataset contains 20 videos containing 5 frames each. The batch size I used is 64. So, in total, I'm working with 100 vide...
<p>You can try one or two things to stabilize the training:</p> <ol> <li><p>You can try different batch sizes of 4, 8, 16, 32, 64. You can generate different plots. Have a look at this <a href="https://machinelearningmastery.com/how-to-control-the-speed-and-stability-of-training-neural-networks-with-gradient-descent-b...
python|tensorflow|machine-learning|keras
0
355,525
62,386,613
Change elements in a python pandas dataframe slice with a numpy array
<p>Wondering if anyone can help me with this problem. I am working on a machine learning problem, I have classified the <code>df1[Age]</code> column into <code>df1[Age_group]</code>. Unfortunately there are missing data, so any <code>df[Age]</code> which is <code>NaN</code> is classified as <code>3</code>.</p> <p>Curr...
<p>As I do not see any <code>numpy.array</code> I will just make a value for those value and replace it.</p> <pre><code>import pandas as pd import numpy as np d = {'ID': [0, 1, 2, 3, 4], 'Sex': ["Male","Female","Male","Male", "Female"], 'Age':[np.nan, 23, np.nan, 6, 15] , 'Age_group':[3,2,3,0,1]} df1 = pd.DataFrame(d...
python|pandas
3
355,526
62,178,275
Increase I/O bound tensorflow training speed
<p>I am facing a problem of improving the training speed / efficiency of a Tensorflow implementation of point cloud object detection algorithm.</p> <p>The input data is a [8000, 100, 9] float32 tensor, with a size roughly 27MB per sample. On a batch size of 5, data loading becomes a bottleneck in training as most of t...
<p>Some ideas: </p> <ol> <li><p>You should use a combination of 1,2 and 3. If you save your files as <code>TFRecords</code>, you can read them in parallel, that's what they are designed for. Then, you will be able to use <code>num_parallel_calls</code> and <code>interleave</code>, because that way you don't have to wr...
python|tensorflow
3
355,527
62,169,048
Why is reindex_like(s, method='ffill') different than reindex_like(s).fillna(method='ffill')
<p>I'm trying to reindex a series with the index of another series and fill missing values.</p> <p>Demo with <code>pandas</code> version 1.0.3:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; s1 = pd.Series(['[0, 1)', '[1, 3)', '[3, 4)', '[4, 6)', '[6, inf)'], index=[0, 1, 3, 4, 6], dtype='string') &gt;&...
<p>The first option (<code>s1.reindex_like(s2).fillna(method='ffill')</code>) Does the reindexing first, leaving empty (<code>NaN</code>) values, and filling them afterwards.</p> <p>The <code>reindex_like</code> returns [1]:</p> <pre><code>s1.reindex_like(s2) 6 [6,inf) 2 NaN 5 NaN 0 [0,1) 4 ...
python|pandas
1
355,528
62,337,224
How to create a new rows from column values of pandas data frame
<p>I have dataframe like below</p> <p><strong>Input</strong></p> <pre><code>Date Country Type Zip_Incl Zip_Excl 10/4/2020 FR Regional 57_67_68 2/1/2020 GB Regional AB_DD 17/3/2021 GB Regional BT_TY TS_TN 18/3/2021 GB Re...
<p>Assuming the dtypes are all string I'd consider the following</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np df = pd.DataFrame({"Type":["Regional"]*5, "Zip_Incl":["57_67_68", "", "BT_TY", "", ""], "Zip_Excl":["","AB_DD", "TS_TN", "", ...
python|pandas|dataframe
1
355,529
62,166,642
Python for loop save only last value of area?
<p>I Used blow lines of code for contour detection and its corresponding area calculation and during printing the area all values are printed but while saving only last value got saved in CSV file</p> <pre><code>import cv2 import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import glob ...
<p>In your code, in each loop you reset the <code>df</code> dataframe.<br> Try this code:</p> <pre><code>import cv2 import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import glob import os import pandas as pd img = cv2.imread('C:\pfm\segmented/L501.jpg') image = cv2.cvtColor(img, cv2...
python|python-3.x|pandas|matplotlib
0
355,530
62,044,071
Tensorflow 2: apply one hot encoding on masks for semantic segmentation
<p>I'm trying to process my ground truth images to create one hot encoded tensors:</p> <pre><code>def one_hot(img, nclasses): result = np.zeros((img.shape[0], img.shape[1], nclasses)) img_unique = img.reshape(512*512, img.shape[2]) unique = np.unique(img_unique, axis=0) for i in range(img.shape[0]): for j ...
<p>For a purely TF2.x approach, you could also do the following</p> <pre><code>import os os.environ[&quot;TF_CPP_MIN_LOG_LEVEL&quot;] = &quot;3&quot; import tensorflow as tf @tf.function # Remove this to see the tf.print array values def get_one_hot(): label_ids = [0,5,10] mask_orig = tf.constant([[0,10], [0,10]]...
python|tensorflow
0
355,531
62,212,807
Convert Excel sheets to Pandas df's
<p>I have an excel file with one sheet name "info" as follows</p> <pre><code>Name Number S1 50 S2 100 S3 400 </code></pre> <p>This sheet give info about other sheet which I need to convert into pandas df's. but, when I read this sheet and loop to create other df's. My code is also looking for a sheet name "Name" a...
<p>Use a header row or skip the first row as mentioned in the comments. </p> <pre><code>df_info = pd.read_excel('file.xlsx', sheet_name='info', header=0) sheets = {} for sheet_name in df_info['Name']: sheets[sheet_name] = pd.read_excel('file.xlsx', sheet_name=sheet_name, header=None) </code></pre> <p><a href="htt...
python|pandas
1
355,532
62,291,535
Merging columns within a dataframe with pandas
<p>I'm trying to merge two different columns within a data frame. So if you have columns A and B, and you want A to remain the default value unless it is empty. If it is empty you want to use the value for B.</p> <p>pd.merge looks like it only works when merging data frames, not columns within an existing single data...
<p>Credit to Scott Boston for the comment on the OP:</p> <pre><code>import pandas as pd df = pd.DataFrame( { 'A': [2, None, 5, None, 7], 'B': [4, 3, None, 6, 8] } ) df.head() """ A B 0 2.0 4.0 1 NaN 3.0 2 5.0 NaN 3 NaN 6.0 4 7.0 8.0 """ df['A'] = df['A'].fillna(df['B'])...
python|pandas
1
355,533
62,144,452
Remove elements from 2d Numpy array based on a list
<p>Thank you in advance for taking a look at my post.</p> <p>I have a 2d np.array called <code>actions</code> with shape (2,x) which contains <code>int</code>s</p> <p>I have another 1d np.array <code>keys</code> with elements of the same type to the first dimension of <code>actions</code>: <code>actions[0]</code>. I...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.isin.html" rel="nofollow noreferrer"><code>np.isin</code></a>:</p> <pre class="lang-py prettyprint-override"><code>mask = np.isin(actions[0], keys, invert=True) result = actions[:, mask] </code></pre>
python|arrays|numpy|multidimensional-array|conditional-statements
2
355,534
62,380,746
python find duplicate values across multiple columns and ignore NaN
<p>I am newish to python and in I am over my head.</p> <p>I have a dataframe that looks like this:</p> <pre><code>import pandas as pd df = pd.DataFrame({'cityyear': ['chicago1990', 'detroit2000', 'detroit1999', 'chicago1999', 'detroit1990'], 'name1': ['hayden', 'charles', 'daniel', 'james', 'hayden'] ...
<p>Can you try this? First I am unstacking to find the names and only keeping the duplicate names after removing nulls. Then groupby the duplicate names and convert them into list then unlist those into columns</p> <pre><code>df = df.set_index(['cityyear']).unstack(['cityyear']).reset_index() df = df[df[0].notnull()] ...
python|pandas|duplicates|mask
0
355,535
62,179,517
Process multiple files in a tensorflow session
<pre><code>func_name(loc, id , mn): with detection_graph.as_default(): with tf.compat.v1.Session(graph=detection_graph) as sess: #tf.initialize_all_variables().run() while cap.isOpened(): ret, image_np = cap.read() print(ret) ...
<p>The following modification works for me and lets to re-use detection loop:</p> <pre><code> sess = tf.compat.v1.Session(graph=detection_graph) def dectect_func(cap): while True: # Read frame from camera ret, image_np = cap.read() # Expand dimensions since the model expects images to hav...
python|tensorflow|flask
0
355,536
62,201,496
Faster way to forward-fill and back-fill a groupby
<p>I want to <code>ffill</code> and <code>bfill</code> a specific column after a groupby. </p> <p>My solution works:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({ "A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [np.nan, 'f1', 'b1', np.nan, np.nan, 'f2', 'b2', np.nan] }) df['B'] = df.groupby('...
<p>If your data really well structured with continuous groups, then you can avoid <code>groupby</code> by using the <code>limit</code> parameter in <code>ffill</code> and <code>bfill</code> like:</p> <pre><code>print (df['B'].ffill(limit=1).bfill(limit=1)) 0 f1 1 f1 2 b1 3 b1 4 f2 5 f2 6 b2 7 b...
python|pandas|optimization
3
355,537
62,364,735
How to fix TypeError: data type not understood with a datetime object in Pandas
<p>I am working with a <code>date</code> <code>column</code> in <code>pandas</code>. I have a date column. I want to have just the year and month as a separate column. </p> <p>I achieved that by:</p> <pre><code>df1["month"] = pd.to_datetime(Table_A_df['date']).dt.to_period('M') </code></pre> <p><strong>Printing it l...
<p>It's working for the sample you shared, not sure where the issue is, are there any missing values in your month column?</p> <pre><code>df['month'] = pd.to_datetime(df['month']).dt.to_period('M') user_groups = df.groupby("customer_id")["month"] df["Cohort_month"] = user_groups.transform("min") print(df) ...
python|python-3.x|pandas|dataframe|datetime
0
355,538
62,340,872
Why does ^2/squared residual is calculating wrong answer in python?
<p>I am trying to calculate RMSE in python with <code>pandas</code> data frame but do not want to use <code>sklearn</code> library for that. I have calculated it in excel and I have found that I have messed up with calculating the <strong>squared residuals</strong>. Could anyone have any idea how to fix this? Here is t...
<p>the problem is that <code>^</code> is not the squaring operator in python, it's bitwise xor. to take <code>a</code> to the power <code>b</code>, you do <code>a**b</code></p>
python|numpy|dataframe|statistics|nan
2
355,539
51,366,217
Pandas DataFrame - count 0s in every row
<p>I have dataframe that looks like this</p> <pre><code>x = pd.DataFrame.from_dict({'A':[1,2,0,4,0,6], 'B':[0, 0, 0, 44, 48, 81], 'C':[1,0,1,0,1,0]}) </code></pre> <p>(assume it might have other columns). I want to add a column, which specifies for each row, how many 0s there are in the specific columns A,B,C.</p> <...
<p>Create a boolean dtype dataframe using <code>==</code>, then use <code>sum</code> with <code>axis=1</code>:</p> <pre><code>x['num_zeros'] = (x == 0).sum(1) </code></pre> <p>Output:</p> <pre><code> A B C num_zeros 0 1 0 1 1 1 2 0 0 2 2 0 0 1 2 3 4 44 0 1 4 ...
python|pandas|dataframe
4
355,540
51,444,850
Make cx_Freeze main.py permanently being able to use numpy module
<p>I am using the cx_Freeze script located in the Python36/Scripts folder on a regular basis to convert python files into executables and it works fine. However it seems to still not being able to convert numpy so I am trying to make it work by adding an option into the main.py which is used by the cx_Freeze script des...
<p>If I understand correctly what you like to do, you could try to add the following two lines to the file site-packages/cx_Freeze/freezer.py</p> <pre><code>@@ -127,6 +127,8 @@ class Freezer(object): self.includes = list(includes) self.excludes = list(excludes) self.packages = list(packages)...
python|numpy|cx-freeze
0
355,541
51,259,616
Python TF ObjectDetection! object_detection not found
<p>I got the well known ImportError: No module named 'object_detection' I added my **./research and my ./research/slim folders to my .~bashrc. When I run the builder/optimize_builder_test.py it works. If I run my modified detection I get the error. Here is a current screenshot from my .bashrc file <a href="https://i.st...
<p>Just a wrong placed spacebar <a href="https://i.stack.imgur.com/kqjmk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kqjmk.png" alt="enter image description here"></a></p> <p>Just a wrong placed spacebar</p>
python-3.x|tensorflow
0
355,542
51,152,088
OpenNMT issue with PyTorch: .copy_ function not clear behavior
<p>I'm working with the PyTorch version OpenNMT and I'm trying to modify the Beam Search algorithm. I'm currently stuck in the <code>beam_update</code> function (in <a href="https://github.com/OpenNMT/OpenNMT-py/blob/0d7f82eec75dc73877e8c6f9749fbadf8a8033cb/onmt/decoders/decoder.py#L406" rel="nofollow noreferrer">Open...
<p>The <code>self</code> tensor is the tensor you call <code>copy_</code> on. In your example it is <code>sent_states.data</code>.</p> <hr> <p>To answer the question raised in the comments: Why does copy not behave like assigning with <code>=</code> </p> <p><code>.copy()</code> creates a real copy to a new memory lo...
python|machine-learning|pytorch
0
355,543
51,338,028
Python pandas groupby multiple columns, creating list of strings but summing numbers
<p>Currently my dataframe looks something similar to:</p> <pre><code> ID Year Str1 Str2 Value 0 1 2014 high black 120 1 1 2015 high blue 20 2 2 2014 medium red 10 3 2 2014 medium blue 50 4 3 2015 low blue 30 5 3 2015 high ...
<p>You need check if <code>numeric</code> column, e.g. by <a href="https://stackoverflow.com/a/38185759/2901002">this solution</a>:</p> <pre><code>df = (df.groupby(['ID', 'Year'], as_index=False) .agg(lambda x: x.sum() if np.issubdtype(x.dtype, np.number) else ', '.join(x))) print (df) ID Year S...
python|pandas|pandas-groupby
3
355,544
51,163,974
how to integrate a pandas operation into sklearn pipeline
<p>I have a simple operation on pandas dataframe like this:</p> <pre><code># initialization dct = {1: 'A', 2:'B', 3: 'C'} df = pd.DataFrame({'id': [1,2,3], 'value':[7,8,9]}) # actual transformation df['newid'] = df.id.map(dct) </code></pre> <p>And I would like to put this transformation as a part of a sklearn pipelin...
<p>See below a corrected version of your code. Explanation given in the comments.</p> <pre><code>dct = {1: 'A', 2:'B', 3: 'C'} df = pd.DataFrame({'id': [1,2,3], 'value':[7,8,9]}) # define a class similar to those in the tutorials class idMapper(BaseEstimator, TransformerMixin): def __init__(self, key='id'): ...
python|pandas|class|scikit-learn|pipeline
3
355,545
51,393,369
Sum of duration between each rows with regards to 2 field in PYTHON
<p>I have a set of datas in terms of timestamp, model and mode The mode comes in 4 different mode denote as (0,2,4,8)</p> <pre><code>Index Model Timestamp Mode 1 x 2016-06-26 09:51:24.279 0 2 x 2016-06-26 09:51:26.282 0 3 x 2016-06-26 09:51:28.279 0 4 x 2016-06-26 09:51:30.2...
<p>You could use</p> <pre><code>In [42]: breaks = df['Mode'].ne(df['Mode'].shift()).cumsum() In [43]: (df.groupby(breaks)['Timestamp'].diff() / np.timedelta64(1, 's')).fillna(0) Out[43]: 0 0.000 1 2.003 2 1.997 3 2.000 4 0.000 5 2.000 6 1.999 7 0.000 8 2.000 9 2.001 10 0.000...
python|pandas|dataframe|duration
0
355,546
51,389,570
Pandas extract text notation
<p>I'm new to Pandas, using it for a class, and I can't for the life of me find a resource that shows the notation used in pandas when representing text in the extract function. For example:</p> <pre><code> movies['year'] = movies['title'].str.extract('.*\((.*)\).*', expand=True) </code></pre> <p>I know this is te...
<p><strong>In General</strong></p> <p>The string argument of the <code>.str.extract</code> is a <a href="https://www.tutorialspoint.com/python/python_reg_expressions.htm" rel="nofollow noreferrer">Regular Expression</a> (regex), which is a language used for pattern matching and feature extraction in strings. If you go...
python|pandas
0
355,547
51,556,953
How to plot time as x axis in pandas
<p>I am trying to plot a data-frame in pandas. The csv file I am using is:</p> <pre><code>Time,Total cpu%,Used mem(k),Cache mem(k),Net mem Used%,Total mem Used%,Swap mem(%),process1 cpu%,process1 mem%, 4:19:25,12.5,885324,1249960,38.38,38.38,0,6.2,34.7 4:19:28,0.4,885460,1249804,38.39,38.39,0,5.3,34.7 4:19:31,1.8,8857...
<p>It seems that your issue might be to do with the way your times are stored. If they are of <code>time</code> or <code>datetime</code> dtypes then the following should work nicely for you.</p> <p>Set Time as the index and simply call plot. Pandas sets the index as the x-axis by default.</p> <pre><code>df.Time = df....
python-3.x|pandas|plot
7
355,548
51,356,324
RDKit - Export pandas data frame with mol image
<p>I would like to know whether is it possible to export pandas dataframe with molecular image directly in excel file format?</p> <p>Thanks in advance,</p>
<p>In RDKit's PandasTools there is the funktion SaveXlsxFromFrame.</p> <p><a href="http://www.rdkit.org/Python_Docs/rdkit.Chem.PandasTools-module.html#SaveXlsxFromFrame" rel="nofollow noreferrer">http://www.rdkit.org/Python_Docs/rdkit.Chem.PandasTools-module.html#SaveXlsxFromFrame</a></p> <pre><code>import pandas as ...
pandas|rdkit
3
355,549
51,527,264
Mapping values inside pandas column
<p>I used the code below to map the 2 values inside S column to 0 but it didn't work. Any suggestion on how to solve this? N.B : I want to implement an external function inside the map.</p> <pre><code> df = pd.DataFrame({ 'Age': [30,40,50,60,70,80], 'Sex': ['F','M','M','F','M','F'], 'S' : [1,1,2,2,1,2] }) ...
<p>Use <code>eq</code> to create a boolean series and conver that boolean series to int with <code>astype</code>:</p> <pre><code>df['S'] = df['S'].eq(1).astype(int) </code></pre> <p>OR</p> <pre><code>df['S'] = (df['S'] == 1).astype(int) </code></pre> <p>Output:</p> <pre><code> Age Sex S 0 30 F 1 1 40 M...
python|pandas|dictionary|data-science
2
355,550
51,186,619
Convert list of dictionaries to dataframe with one column for keys and one for values
<p>Let's suppose I have the following list:</p> <p><code>list1 = [{'a': 1}, {'b': 2}, {'c': 3}]</code></p> <p>Which I want to convert it to a panda dataframe that have two columns: one for the keys, and one for the values.</p> <pre><code> keys values 0 'a' 1 1 'b' 2 2 'c' 3 </code></pre...
<p>Use <code>list comprehension</code> with flattening for list of tuples:</p> <pre><code>df = pd.DataFrame([(i, j) for a in list1 for i, j in a.items()], columns=['keys','values']) print (df) keys values 0 a 1 1 b 2 2 c 3 </code></pre> <p><strong>Detail</strong>:</p>...
python|list|pandas|dataframe
7
355,551
51,288,942
How to transform values from a cell into new columns in Pandas?
<p>My dataframe looks like this:</p> <pre><code>+-------+-----------------------------------------+ | Image | Bounding Boxes | +-------+-----------------------------------------+ | a.jpg | xyz 0.1 0.2 0.3 0.4 | | b.jpg | xyz 0.1 0.2 0.3 0.4 ijk 0.4 0.3 0.2 0.1 | +-------+--...
<p>You can just use <a href="https://pandas-docs.github.io/pandas-docs-travis/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>str.split(' ', expand=True)</code></a> to split on the space, and then join with the <code>Image</code> Column:</p> <pre><code>new_df = df[['Image']].join(df['Bounding B...
python|pandas|dataframe|data-science
3
355,552
51,371,070
How does pytorch broadcasting work?
<pre><code>torch.add(torch.ones(4,1), torch.randn(4)) </code></pre> <p>produces a Tensor with size: <code>torch.Size([4,4])</code>.</p> <p>Can someone provide a logic behind this?</p>
<p><a href="https://pytorch.org/docs/stable/notes/broadcasting.html#broadcasting-semantics" rel="nofollow noreferrer">PyTorch <em><code>broadcasting</code></em></a> is based on <em>numpy broadcasting</em> semantics which can be understood by reading <a href="https://numpy.org/devdocs/user/basics.broadcasting.html#gener...
python|numpy|linear-algebra|pytorch|array-broadcasting
34
355,553
51,116,473
Expand a list from one dataframe to another dataframe pandas
<p>I was hoping to get help with the following:</p> <p>I have a given df below of:</p> <pre><code>df fruit State Count apples CA 45 apples VT 54 apples MI 18 pears TX 20 pears AZ 89 plums NV 62 plums ID 10 </code></pre> <p>I took all the highest counts for each fruit ...
<p>Two step :-) without <code>groupby</code> </p> <pre><code>df2=df.sort_values('Count').drop_duplicates('fruit',keep='last') df['new']=df.fruit.map(df2.set_index('fruit').State) df Out[240]: fruit State Count new 0 apples CA 45 VT 1 apples VT 54 VT 2 apples MI 18 VT 3 pears TX ...
python|list|pandas|dataframe|expand
2
355,554
51,283,361
Pandas lambda multiple argument in return
<pre><code>import pandas as pd import numpy as np def ced(x): return x+1, x+2, x+3 df = pd.DataFrame(data=[[1,2],[10,20]], columns=['a','b']) df['x'], df['y'], df['z'] = df['a'].apply(lambda x: ced(x)) print(df) </code></pre> <p>error:</p> <blockquote> <p>line 11, in df['x'], df['y'], df['z'] = d...
<p>I suggest change function for return <code>Series</code> and subset of new columns:</p> <pre><code>def ced(x): return pd.Series([x+1, x+2, x+2]) df = pd.DataFrame(data=[[1,2],[10,20]], columns=['a','b']) df[['x','y', 'z']] = df['a'].apply(lambda x: ced(x)) print(df) a b x y z 0 1 2 2 3 ...
python|python-3.x|pandas|lambda|arguments
1
355,555
51,314,716
Groupby to find min date with conditions in Python
<p>I have like 3 columns in a data frame for example</p> <p><code>Column_A</code> has 2 categorical values like A,B </p> <p><code>Column_B</code> also has 3 categorical values like Type1, Type2, Type3 </p> <p><code>Date</code> column has values like <code>2010-06-13,2010-06-10</code></p> <p>There are about 20,00...
<p>Use boolean index with <code>loc</code> and <code>min</code>:</p> <p><code>df.loc[(df['Column_A'] == 'A') &amp; (df['Column_B'] == 'type 1'), 'Date'].min()</code></p>
python-3.x|pandas|numpy|jupyter-notebook
0
355,556
51,496,619
TensorBoard: How to write images to get a steps slider?
<p>I'm using keras in my ML project with the <code>TensorBoard</code> callback. I have an image autoencoder and I want to visualize its progress in reconstructing some images. So I sub-classed the <code>TensorBoard</code> class as such:</p> <pre><code>class Monitor(TensorBoard): def on_train_begin(self, logs=None)...
<p>The image must have the same <strong>tag</strong> (Not <strong>name</strong>, which I was doing before).</p> <pre><code>plt.figure(figsize=(5,5)) plt.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated") plt.plot(mean_predicted_values, fraction_of_positives) reliability_image = io.BytesIO() plt.savefig(reliabili...
tensorflow|keras|visualization|tensorboard|autoencoder
2
355,557
51,128,185
How to change the first occurrence of 'True' in a row to false in pandas
<p>I'm trying to change the first instance of <code>True</code> to <code>False</code> in my DataFrame dependent on row:</p> <pre><code> A B C Number 1 True True True 2 False True True 3 False False True A B C ...
<p>You can use the cumulative sum of the Boolean values (False corresponds to 0; True to 1) for each row, along with <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mask.html" rel="nofollow noreferrer"><code>DataFrame.mask()</code></a>:</p> <pre><code>&gt;&gt;&gt; condition = df.cumsum...
python|pandas|dataframe
3
355,558
51,412,920
Exception in thread Thread-5: TypeError: only integer scalar arrays can be converted to a scalar index
<p>Recently I was evaluating a tflearn model using it's model.evaluate(test_X, test_y) method with the test data and there I am getting below exception</p> <pre><code>Exception in thread Thread-5: Traceback (most recent call last): File "/Users/vishwas.abhyankar/miniconda3/lib/python3.6/threading.py", line 916, in _...
<p>This was my original method:</p> <pre><code>def evaluate(self): return self.model.evaluate(self.test_x, self.test_y) </code></pre> <blockquote> <p>here self.test_x was a list of lists like: [[0, 1, 1, 0], [1, 0, 1, 1]] and self.test_y was a list of lists like: [[0, 1], [1, 0]]</p> </blockquote> <p>Modifie...
python|pandas|numpy|tensorflow|tflearn
0
355,559
51,226,423
Pandas find common matches between 2 dataframes
<p>I have 2 dataframes and I want to find common matches based on a column (tld), once match has been found, I want to update column match as True. How to update column in destination dataframe?</p> <p><strong>Dataframe 1:</strong> source</p> <pre><code> uuid website company_name tld 0 1 ww...
<p>Using <code>isin</code> to update:</p> <pre><code>df2.loc[df2.tld.isin(df1.tld),'match']=True df2 Out[669]: id website company_name tld match 0 a www.facebook.com facebook facebook.com True 1 b www.y.com YahooInc y.com False 2 c www.g.com Google ...
python|pandas
2
355,560
51,545,231
Having trouble transforming tensor created by tf.fromPixels()
<p>What I'm trying to do is convert a tensor which was created using <code>tf.fromPixels()</code> and transform that into <code>[28, 28]</code> to then use as that as an input to get a prediction from a model trained in Python. </p> <p>What I'm having trouble with is the first layer in the model which takes an input s...
<p>After getting your image from your canvas, you need to reshape your tensor</p> <pre><code> var image = tf.fromPixels(canvas, 1); image = img.reshape([1, 28, 28]); </code></pre> <p>then you can pass the tensor to your model</p>
node.js|tensorflow|tensorflow.js
2
355,561
51,490,358
the first x label is missing using matplotlib
<p>This is my data:</p> <pre><code>a3=pd.DataFrame({'OfficeName':['a','b','c','d','e','f','g','h'], 'Ratio': [0.1,0.15,0.2,0.3,0.2,0.25,0.1,0.4]}) </code></pre> <p>and this is my code to draw a bar chart:</p> <pre><code>fig, ax = plt.subplots() ind = np.arange(a3.loc[:,'OfficeName'].nunique()) # ...
<p>There is an easier way to produce your bar chart in Pandas:</p> <pre><code>a3.set_index('OfficeName').plot.bar(width=0.35, legend=False) plt.xticks(rotation=0, ha='center') </code></pre> <p>(You still need to set the x and y axis labels and the title.)</p>
python|pandas|matplotlib|label
0
355,562
51,413,403
Python-Pandas Join two columns by adding a character
<blockquote> <p>There are three different columns, col2 and col3 need to be joined with the character "/" between the two columns and after joining column name need to be col2. please help !!!</p> </blockquote> <pre><code>col1 col2 col3 B 0.0.0.0 0 0 B 2.145.26.0 24 B 2.145.27.0 24 ...
<p>IIUC</p> <pre><code>df['col2']+='/'+df.col3.astype(str) df Out[74]: col1 col2 col3 0 B 0.0.0.00/0 0 1 B 2.145.26.0/24 24 2 B 2.145.27.0/24 24 3 B 10.0.0.08/20 20 </code></pre>
python|pandas
2
355,563
51,152,043
Creating a 3D surface plot from three 1D arrays
<p>I've got 3 arrays as shown below and I'm trying to plot a 3d surface plot (wireframe or any other) from it. I've created a scatter plot from it but not sure how to approach it from a 3D surface plot point of view. Any help would be greatly appreciated.</p> <pre><code>X = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1...
<p>As you have a regular grid, you can just use numpy to reshape your data, then use <code>ax.plot_surface</code>. In your example case, you want to reshape to a shape of <code>(9, 12)</code>:</p> <pre><code>from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np X = [0, 0, 0, 0, 0,...
python|arrays|numpy|matplotlib|plot
19
355,564
51,284,945
Pandas Resample Missing Rows
<p>I have a dataframe that I am resampling over a week period:</p> <pre><code>df = Date Game_Mode Count 0 2008-11-30 b 1 1 2009-07-03 b 1 2 2009-07-12 b 1 3 2009-07-18 b 1 4 2009-10-02 c 1 5 2009-10-21 a 1 6 2009-10-22 ...
<p>The problem is caused by</p> <pre><code>df[df['Game_Mode'] == 'a'] </code></pre> <p>If you only select the df rows where <code>Game_Mode</code> is <code>a</code> (or one of he others), then you're throwing away the start and end dates.</p> <p>What you could do is create an empty dataframe, which the same dates, b...
python|pandas|resampling
1
355,565
51,352,901
Appending the results of for loop with if statement to Pandas Dataframe in Python
<p>I'm making a script in Python for searching for the selected term (word/couple words, sentence) in a bunch of .txt files in a selected folder with printing out the names of the .txt files which contain the selected term. Currently is working pretty fine using os module:</p> <pre><code>import os dirname = '/Users/U...
<p>In the <code>code</code> below the new lines are indicated by '<code>*</code>'.</p> <p><strong>Code from question</strong></p> <pre><code>import os import pandas as pd # new line * * * import numpy as np # new line * * * dirname = '/Users/User/Documents/test/reports' search_terms = ['Pressure'] search_terms = [x...
python|pandas|file|directory|python-os
2
355,566
51,382,659
Replacing column names in a pandas dataframe based on a lookup
<p>Hi I have several dataframes with column headings that vary slightly. An example of a header of a dataframe will be:</p> <pre><code>A1 B1 C1 </code></pre> <p>In other dataframes the first row is called A2 or A3 etc. A1..., B1...C1 represent multi character words/labels and are not the literal column names. I...
<p>I think here is possible use <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#indexing-with-str" rel="nofollow noreferrer"><code>indexing with str</code></a> for replace by first letter:</p> <pre><code>df.columns = df.columns.str[0] </code></pre> <p>Another possible solution is create dictionary for ...
pandas|dataframe
1
355,567
51,325,256
calculate week over week changes in Pandas (with a groupby)?
<p>I've been able to successfully calculate the changes over week to week with my data quite fine. However, my data includes thousands of groups that I need to have sorted by. So I am looking for a faster/more efficient way to calculate these week by week changes than how I am currently implementing it.</p> <p>The way...
<p>This is the code I use for something similar:</p> <pre><code>week_freq = 'W-TUE' temp_df['Sales_change_1_week] = temp_df['Sales'].asfreq(week_freq).diff() </code></pre>
python|pandas|time-series
2
355,568
51,451,400
How to declare array in format where continuous zeros can be written as n*0 like in fortran?
<p>I have a fortran array of the type </p> <p><code>DATA ELEV \1.2,3.2,2*0.0,3.9,3*0.0\</code></p> <p>which in python would be </p> <p><code>ELEV = [1.2, 3.2, 0.0, 0.0, 3.9, 0.0, 0.0, 0.0]</code></p> <p>Notice how 2*0.0 was not 0.0 but instead 2 elements with value 0.0.</p> <p>Is there some way to use numpy or oth...
<p>Use the <a href="https://www.python.org/dev/peps/pep-0448/" rel="nofollow noreferrer">new <code>*</code> unpacking generalizations</a> and list multiplication.</p> <pre><code>&gt;&gt;&gt; [1.2, 3.2, *2*[0.0], 3.9, *3*[0.0]] [1.2, 3.2, 0.0, 0.0, 3.9, 0.0, 0.0, 0.0] </code></pre> <p>You can also multiply strings and...
python|arrays|python-3.x|numpy
3
355,569
51,420,951
np.polyfit plot with uncertainty on the y in python
<p>I have the following dataframe:</p> <pre><code>x y error_on_y 1 1.2 0.1 2 0.87 0.23 4 1.12 0.11 5 0.75 0.06 5 0.66 0.15 6 0.98 0.08 7 1.34 0.05 7 2.86 0.12 </code></pre> <p>With this frame I want to use ...
<p>When you do <code>np.polyfit(x,y,deg=1, w=1/y_err, cov=True)</code> you're calculating (among other things) the coefficients of a polynomial. To easily manipulate such coefficients you can create a polynomial object </p> <pre><code>p, mycov = np.poly1d(np.polyfit(x,y,deg=1, w=1/y_err, cov=True)) </code></pre> <p>a...
python|numpy|dataframe|statistics|polynomials
1
355,570
51,162,092
Python encoding issue with pandas read_sql
<p>So I am trying to encode two strings to utf-8 so I can use them with pandas.read_sql: </p> <pre><code>selectedTable = "ACC__AccountCodes" baseSql = "SELECT * FROM FileMaker_Fields WHERE TableName=" </code></pre> <p>Now when I encode these two things:</p> <pre><code>baseSql.encode('utf-8') selectedTable.encode('ut...
<p>You don't have to encode them as utf-8; Try passing them as normal strings to pandas <code>read_sql</code> function, it should work fine, if not, then you have a problem somewhere else... but encoding is not what you want here.</p> <p><code>Pyodbc</code> accepts unicode strings in the query as normal, so that is no...
python|python-3.x|pandas|pyodbc
2
355,571
51,451,813
Unable to create Pandas dataframe
<p>I've trouble creating a pandas dataframe. can someone explain what went wrong with the code.</p> <pre><code>column1 = ['hello'] column2 = ['world'] index = ['a','b','c'] data1 = np.linspace(0,3,1) data2 = np.arange(3) data = [data1, data2] columns = [column1, column2] df = pd.DataFrame(data = data, columns= columns...
<p>your object data1 has three elements. linespace creates 1D array, you require 2D array to represent 3 row and 2 columns.</p> <pre><code>data1 = np.linspace(0,3,1) </code></pre> <p>you should create array with 3 row and 2 columns. </p>
python|pandas
0
355,572
51,344,738
How do I pivot a pandas DataFrame and then add hierarchical columns?
<p>Can someone please help me understand the steps to convert a Python pandas DataFrame that is in record form (data set A), into one that is pivoted with nested columns (as shown in data set B)?</p> <p>For this question the underlying schema has the following rules:</p> <ul> <li>Each ProjectID appears once </li> <li...
<p>I think this is what you are looking for:</p> <pre><code>pd.DataFrame(df_A.set_index(['PM', 'ProjectID', 'Category']).sort_index().stack()).T.stack(2) Out[4]: PM Amy Bob ... Jill ProjectID 6 1 ... ...
python|pandas|data-cleaning|preprocessor|dataframe
0
355,573
51,218,869
regarding transforming PNG into JPG
<p>I have a set of <code>PNG</code> files which are of shape <code>(64,64,4)</code>, and want to feed it to a <code>tensorflow</code> model which was designed for <code>JPG</code> files, which has shape <code>(64,64,3)</code>. I plan to transform <code>PNG</code> into <code>JPG</code>, is this a good approach, what's t...
<p>One way transforming it would be using <code>opencv</code>, not sure about the side-effects, you might get a little amount of color shifting. This will take all the <code>png's</code> in the current folder and save them as <code>jpgs</code></p> <pre><code>from glob import glob ...
python|tensorflow|image-processing|computer-vision|png
0
355,574
51,357,981
What is the format of "input_shape" is keras.Sequential()?
<p>Following <a href="https://www.tensorflow.org/tutorials/keras/basic_text_classification" rel="nofollow noreferrer">this</a> tensorflow tutorial, under the <strong>Build the model</strong> section, the first layer of keras.Sequential() is given parameter <code>vocab_size=10000</code>. What does it mean?</p> <p>After...
<p>For the first part of your question:</p> <p>The example uses an embedding layer. Think of embedding layer as a lookup matrix. Each row will represent a word vector. The vocab_size is identifying the size of this matrix (or in other words number of words represented in in this matrix - which is essentially the n...
python|tensorflow|keras
2
355,575
51,420,768
How to change a value in Pandas Data Frame after adding a new column
<p>I created a DF when I have loaded the dataset. After that, I need to add a new column and assign values based on a condition. When I add it, I can not change the Value.</p> <p>P.S. I saw and test a lot of answers in SO. I have attached the picture and code:</p> <pre><code>counter = 0 for checkin in df.itertuples()...
<p>I am not sure to completly understand the question, but I think you could </p> <p>1) Change the data type of checkin_time to a datetime <code>df['checkin_time'] = pd.to_datetime(df['checkin_time'])</code></p> <p>2) Create a new column which tells the day of the week <code>df['day_of_week'] = df['checkin_time'].dt....
python|pandas|dataframe
2
355,576
51,364,121
How to stop to_csv from changing date format?
<p>I am trying to write my dataframe as is to csv. Few of the columns of the dataframe are datetime. </p> <p>I have used <code>df.column = pd.to_date(df.column)</code> to convert dates from <code>dd/mm/yyyy</code> to <code>yyyy/mm/dd</code>, which has worked successfully. </p> <p>However when I write the dataframe to...
<p>Code below saves dataframe with date column as csv. (<code>Jupyter Notebook 5.0.0, Python 3.6.6</code>)</p> <p><strong>Import libraries</strong></p> <pre><code>import pandas as pd import numpy as np import datetime as datetime </code></pre> <p><strong>Create sample dataframe</strong></p> <pre><code>x = ['01/12/2...
python-3.x|pandas|datetime|export-to-csv
3
355,577
51,395,805
Pandas to_csv skipping the first row of dataframe
<p>I have a Panda DataFrame which has <code>1646 X 26</code> shape. But when I am trying to write the fame in a csv file, the first row is getting skipped. I am getting <code>1645 X 26</code> shape in the csv file. So I looked up in the internet and I saw some solutions like using <code>header = False, header = None, h...
<p><strong>Sample</strong>:</p> <pre><code>_df = pd.DataFrame({'A':list('abcdef'), 'B':[4,5,4,5,5,4], 'C':[7,8,9,4,2,3], 'D':[1,3,5,7,1,0]}) print (_df) A B C D 0 a 4 7 1 1 b 5 8 3 2 c 4 9 5 3 d 5 4 7 4 e 5 2 1 5 f 4 3 0 </code></p...
pandas
3
355,578
51,149,865
Zero-dimensional numpy.ndarray : only element is a 2D array : how to access it?
<p>I have imported a Matlab *.mat file using scipy.io and trying to extract the 2D data from it. There are several arrays inside, and when I am trying to get them I got stuck at the last operation.</p> <p>The data looks like the image below. When I try to index it: <em>IndexError: too many indices for array</em></p> ...
<p>A search on <code>loadmat</code> should yield many SO questions that will help you pick apart this result. <code>loadmat</code> has to translate MATLAB objects into Python/numpy approximations.</p> <pre><code>data = io.loadmat(filename) </code></pre> <p>should produce a dictionary with some cover keys and various...
python|arrays|matlab|numpy
7
355,579
51,473,799
For loop alternative for multiple columns within a function (pandas)
<p>Imagine a funtion like the following:</p> <pre><code>def func(df, cols, col_ref): for c in cols: df[c] = df.apply(lambda row: row[c] * ref[(ref.SOURCE == row[col_ref])].VALUE.item() ,axis=1) return df </code></pre> <p>When calling this function, parameters are</p> <ol> <li>a dataframe with mu...
<p>I think better is use this vectorized solution - multiple by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mul.html" rel="nofollow noreferrer"><code>mul</code></a> with <code>Series</code> created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.ht...
python|pandas|function|for-loop
1
355,580
51,395,590
regex pattern to match datetime in python
<p>I have a string contains datetimes, I am trying to split the string based on the datetime occurances,</p> <pre><code>data="2018-03-14 06:08:18, he went on \n2018-03-15 06:08:18, lets play" </code></pre> <p>what I am doing,</p> <pre><code>out=re.split('^(2[0-3]|[01]?[0-9]):([0-5]?[0-9]):([0-5]?[0-9])$',data) </cod...
<p>You want to split with at least 1 whitespace followed with a date like pattern, thus, you may use</p> <pre><code>re.split(r'\s+(?=\d{2}(?:\d{2})?-\d{1,2}-\d{1,2}\b)', s) </code></pre> <p>See the <a href="https://regex101.com/r/k339Yt/2" rel="nofollow noreferrer">regex demo</a></p> <p><strong>Details</strong></p> ...
python|regex|python-3.x|pandas|datetime
4
355,581
51,372,462
Converting string/numerical data to categorical format in pandas
<p>I have a very large csv file that I have converted to a Pandas dataframe, which has string and integer/float values. I would like to change this data to categorical format in order to try and save some memory. I am basing this idea off of the documentation here: <a href="https://pandas.pydata.org/pandas-docs/versio...
<p>I think we can convert object to category data by using <code>factorize</code></p> <pre><code>objectdf=df.select_dtypes(include='object') df.loc[:,objectdf.columns]=objectdf.apply(lambda x : pd.factorize(x)[0]) df Out[452]: station date prcp tobs 0 0 0 0.08 65 1 0 1 0.00 63 ...
python|pandas|dataframe|categorical-data
0
355,582
51,304,684
Digitizing value to "floor" bin python
<p>I need to digitize some values such that the index returned is the "floor" or "ceiling" bin.</p> <p>E.g., for <code>bins = numpy.array([0.0, 0.5, 1.0, 1.5, 2.0])</code> and a value <code>0.2</code> I expect the index to be <code>0</code>, for a value <code>0.26</code> the index returned should be <code>1</code>, a...
<p>You can simply get the mid of bins and use with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html" rel="nofollow noreferrer"><code>np.digitize</code></a> -</p> <pre><code>np.digitize(value, (bins[1:] + bins[:-1])/2.0) </code></pre>
python|numpy|digitization
1
355,583
51,198,333
NumPy array built from audio file throws zero-size array error when array is neither empty nor corrupted
<p>My code is:</p> <pre><code>import numpy from scipy.io.wavfile import read audio_file_location = 'file_location' audio_file = read(audio_file_location) n = numpy.array( audio_file[1],dtype=float ) size = n.size w = 410 limit = 205 delta = n.size/410 i = 0 j = 0 a = 1 while i &lt; w: J = min(size, j+delta) ...
<p>I'll guess that this fails for sound files with only one channel, i.e. mono instead of stereo. In this case when you create the <code>n</code> array you take the first element of the channel instead of the fist channel as a whole.</p> <p>You can try something like:</p> <pre><code>if audio_file.ndims &gt; 1: au...
python|arrays|numpy|wav
1
355,584
51,315,934
Python Pivot loses last column
<p>I am opening a .csv with pandas naming it pull:</p> <pre><code> Quarter Category Value 7776 Q1-17 Autos and Transportation 6997035.2 7777 Q2-17 Autos and Transportation 7897574.5 7778 Q3-17 Autos and Transportation 6983654.1 7779 Q4-17 Autos and Transportation 7301336.9...
<p>I was able to figure it out by finding a similar post. </p> <p>Just need to add <code>order = pull['Quarter']</code> before the pivot. Then after you can fix the column order by using: <code>reshape = reshape.reindex(columns=order)</code></p>
python|pandas|dataframe|data-science
0
355,585
51,463,320
pd.to_numeric not working
<p>I am facing a weird problem with pandas.</p> <p>I donot know where I am going wrong?</p> <p><a href="https://i.stack.imgur.com/c6VY7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c6VY7.png" alt="enter image description here"></a></p> <p>But when I am creating a new df, there seems to be no pr...
<p>The fact that you can't apply <code>to_numeric</code> directly using <code>.iloc</code> appears to be a bug, but to get the same results that you're looking for (applying <code>to_numeric</code> to multiple columns at the same time), you could instead use:</p> <pre><code>df = pd.DataFrame({'a':['1','2'],'b':['3','4...
python-3.x|pandas
2
355,586
51,162,242
Finding the Location of the Duplicate for Duplicated Columns in Pandas
<p>I know I can find duplicate columns using:</p> <pre><code>df.T.duplicated() </code></pre> <p>what I'd like to know the index that a duplicate column is a duplicate of. For example, both <code>C</code> and <code>D</code> are duplicates of a <code>A</code> below:</p> <pre><code>df = pd.DataFrame([[1,0,1,1], [2,0,2...
<p>I don't know if <code>duplicated</code> have an option to give information about the first row with the same data. My idea is by using <code>groupby</code> and <code>transform</code> such as:</p> <pre><code>arr_first = (df.T.reset_index().groupby([col for col in df.T.columns])['index'] .transform(la...
python|pandas|duplicates|data-cleaning
4
355,587
51,333,061
Stochastic gradient descent in Tensorflow seems conceptually wrong
<p>I am exploring Linear Regression with Tensorflow. Here is my code from <a href="https://github.com/BinRoot/TensorFlow-Book/blob/master/ch03_regression/Concept01_linear_regression.ipynb" rel="nofollow noreferrer">this notebook</a>.</p> <pre><code>import tensorflow as tf import numpy as np learning_rate = 0.01 x_tra...
<p>I would like to answer my own question. This is not a trivial question if you think this does exactly <em>linear regression</em>. </p> <ol> <li><p>I misunderstood the performance of <em>tf.train.GradientDescentOptimizer</em>. It only run one step to minimize the loss function, not to the minium value. If so, @Umang...
python|tensorflow
0
355,588
48,290,834
python pandas index.get_loc raising KeyError despite the key being present
<p>I need to get the row number of a specific Unix timestamp, or the row number of the closest Unix timestamp if there isn't an exact match. I tried the following: </p> <pre><code>x = df.loc[df['unixTime']==1506448028].index[0] </code></pre> <p>which worked for exact matches, but I couldn't find a way to set a toler...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.idxmin.html" rel="nofollow noreferrer">Series.idxmin()</a> method:</p> <p>Demo:</p> <pre><code>In [264]: df Out[264]: unixTime lat long alt 0 1506447200 37.629079 -86.011796 216.458542 1 1506447...
python|pandas|dataframe|indexing|row
2
355,589
48,166,721
Is tensorflow embedding_lookup differentiable?
<p>Some of the tutorials I came across, described using a randomly initialized embedding matrix and then using the <code>tf.nn.embedding_lookup</code> function to obtain the embeddings for the integer sequences. I am under the impression that since the <code>embedding_matrix</code> is obtained through <code>tf.get_vari...
<p>Embedding matrix lookup is mathematically equivalent to dot product with the one-hot encoded matrix (see <a href="https://stackoverflow.com/q/47868265/712995">this question</a>), which is a smooth linear operation. </p> <p>For example, here's a lookup at the index <code>3</code>:</p> <p><a href="https://i.stack.im...
tensorflow|nlp|deep-learning|word-embedding|sequence-to-sequence
8
355,590
48,413,371
Tensorflow FailedPreconditionError: Attempting to use uninitialized value Variable
<p>I follow the instruction of 'Build a Multilayer Convolutional Network' on the official website. My code is exactly the same as the code they provide on the website. [<a href="https://www.tensorflow.org/get_started/mnist/pros]" rel="nofollow noreferrer">https://www.tensorflow.org/get_started/mnist/pros]</a></p> <p>I...
<pre><code>with tf.Session() as sess: ... print('test accuracy %g' % accuracy.eval(feed_dict={ x: mnist.test.images, y_:mnist.test.labels, keep_prob: 1.0})) </code></pre> <p>when use <code>tf.Session</code> You should put <code>print</code> method in the <code>with</code> block for setting <code>sess</...
tensorflow
0
355,591
48,202,495
Filering columns based on Row values in Pandas
<p>I can filter rows based on a column value, using a boolean series.</p> <pre><code>import pandas as pd import numpy as np from numpy.random import randn df = pd.DataFrame(randn(5,4), ['A', 'B', 'C', 'D', 'E'], ['W','X','Y','Z']) &gt;&gt;&gt; df[df['W'] &lt; 0] W X Y Z A -1.080180 -...
<p>You are really close, need <code>loc</code> with <code>:</code> for select all rows by condition:</p> <pre><code>np.random.seed(45) df = pd.DataFrame(np.random.rand(5,4), ['A', 'B', 'C', 'D', 'E'], ['W','X','Y','Z']) print (df) W X Y Z A 0.989012 0.549545 0.281447 0.077290 B 0...
python|pandas
3
355,592
48,151,497
Pandas Dataframe Faster Approach
<p>I have a section of my code which needs to take the values from one dataframe, and apply it to another. So for example lets say 1 data frame is the scores of students dataframe, and the 2nd is the combination of students dataframe. I want to go through each combination_DF, get the students scores and then sum them...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> and aggregate <code>sum</code> first and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow n...
python|pandas|dataframe
0
355,593
48,187,627
Python Loop with auto creation of data frames
<p>I am trying to create a loop which will return for each ticker, 1. a different data frame (by the name of ticker) 2. with a conversion of the time column to "normal" day 3. and it (the new time) will be used as index for that data frame.</p> <p>If I run it for each ticker it's working without problem. I apprecia...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.json.json_normalize.html" rel="nofollow noreferrer"><code>json_normalize</code></a> for <code>dinctionary of DataFrame</code>s with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofo...
python|pandas|python-requests
2
355,594
48,328,133
Find numpy array coordinates of neighboring maximum
<p>I used the accepted answer <a href="https://stackoverflow.com/questions/3986345/how-to-find-the-local-minima-of-a-smooth-multidimensional-array-in-numpy-efficie/3986876#3986876" title="How to find the local minima of a smooth multidimensional array in NumPy efficiently?">in this question</a> to obtain local maxima i...
<p>We can use pad with reflected elements to simulate the max-filter operation and get sliding windows on it with <a href="http://scikit-image.org/docs/dev/api/skimage.util.html#skimage.util.view_as_windows" rel="nofollow noreferrer"><code>scikit-image</code>'s <code>view_as_windows</code></a>, compute the flattened ar...
python|numpy|multidimensional-array
1
355,595
48,084,878
Sum values in column 3 related to unique values in column 2 and 1
<p>I'm working in Python and I have a Pandas DataFrame of Uber data from New York City. A part of the DataFrame looks like this:</p> <pre><code> Year Week_Number Total_Dispatched_Trips 2015 51 1,109 2015 5 54,380 2015 50 8,989 2015 51 1,025 ...
<p>okidoki here is it, borrowing on <a href="https://stackoverflow.com/questions/22137723/convert-number-strings-with-commas-in-pandas-dataframe-to-float">Convert number strings with commas in pandas DataFrame to float</a></p> <pre><code>import locale from locale import atof locale.setlocale(locale.LC_NUMERIC, '') df...
python|pandas|sorting|sum|grouping
1
355,596
48,114,258
TensorFlow estimator number of classes does not change
<p>I tried using tensorflow estimator for the MNIST dataset. For some reason it keep saying my <code>n_classes</code> is set to 1 even though it is at 10!</p> <pre><code>import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/"...
<p>That's a good question. <a href="https://www.tensorflow.org/api_docs/python/tf/estimator/DNNClassifier" rel="nofollow noreferrer"><code>tf.estimator.DNNClassifier</code></a> is using <a href="https://www.tensorflow.org/api_docs/python/tf/losses/sparse_softmax_cross_entropy" rel="nofollow noreferrer"><code>tf.losses....
python|tensorflow|machine-learning|deep-learning|mnist
2
355,597
48,339,893
Learning rate in tensorflow Adadelta
<p>In the original <a href="https://arxiv.org/abs/1212.5701" rel="nofollow noreferrer">paper</a>, introducing the <em>Idea 2</em> eliminates the learning rate.</p> <p>So what is the meaning of learning rate in tensorflow <a href="https://www.tensorflow.org/api_docs/python/tf/train/AdadeltaOptimizer" rel="nofollow nore...
<p>It just multiplies the variable updates (see <a href="https://github.com/tensorflow/tensorflow/blob/04b5c75aae4bdbdac7c713714a369f9b360daf70/tensorflow/core/kernels/training_ops.cc#L79" rel="nofollow noreferrer">the update op implementation</a>).</p> <p>For any "automatic learning rate" scheme, you can always scale...
python|optimization|tensorflow
1
355,598
48,435,894
Slicing from date from csv file rows
<pre><code> date LEV1 LEV2 LEV3 L2 L3 L4 2013-01-01 1:00 266.591 266.591 266.591 1000 1200 1400 2013-01-01 2:00 266.479 266.479 266.479 1000 1200 1400 2013-01-01 3:00 266.373 266.373 266.373 1000 1200 1400 2013-01-01 4:00 266.273 266.273 266.273 1000 1200 1400 2013-01-01 5:00 26...
<p>There must be various(and smarter) way to achieve your goal. But I will show you one possible example using pandas <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.html" rel="nofollow noreferrer">datetimeIndex</a>.</p> <pre><code>df['date'] = pd.to_datetime(df['date']) df = df.se...
python|pandas|matplotlib
1
355,599
48,140,133
use negative loss in tensorflow
<p>I am implementing a reinforcement agent that takes actions based on classes. so it can take action 1 or 2 or 3 or 4.</p> <p>So my question is can I use negative loss in tensorflow to stop it from outputting an action.</p> <p>Example: Let's say the agent outputs action 1 I want to very strongly dissuade it from tak...
<p>A gradient descent minimizer will typically try to find the minimum loss irrespective of the sign of the loss surface. It sounds like you either want to <strong>a)</strong> assign a large loss to encourage your model to pick something else or <strong>b)</strong> assign a fifth <em>no-action</em> category.</p>
python|tensorflow|machine-learning
3