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
4,500
69,164,245
Filter out rows based on condition
<p>I have a dataframe:</p> <pre><code> | from id | from group | to id | to group | | 1 | A | 3 | B | | 4 | B | 4 | X | | 5 | F | 5 | J | | 2 | B | 3 | A | </code></pre> <p>Looking at the 'fro...
<p>Supposing that you're using <code>pandas</code> try something like:</p> <pre><code>df.loc[~((df['from group'].isin(['A','B'])) &amp; (df['to group'].isin(['A','B'])))] </code></pre> <p>The <code>~</code> in front of the first parenthesis will define a negation of the coming filter</p>
python|pandas|numpy
-1
4,501
69,260,384
Get column name where value match with multiple condition python
<p>Looking for a solution to my problem an entire day and cannot find the answer. I'm trying to follow the example of this topic: <a href="https://stackoverflow.com/questions/14734695/get-column-name-where-value-is-something-in-pandas-dataframe">Get column name where value is something in pandas dataframe</a> to make a...
<p>You can use boolean mask:</p> <pre><code>problems = ['acne', 'wrinkles', 'darkspot'] m1 = df1[problems].isin([3, 4]) # main condition m2 = df1[problems].eq(2) # fallback condition mask = m1 | (m1.loc[~m1.any(axis=1)] | m2) df1['problem'] = mask.mul(problems).apply(lambda x: [i for i in x if i], axis=1) </...
python|pandas|dataframe|extract|columnname
1
4,502
69,283,272
Excel file gets corrupted after bulking data with panda
<p>Ok so apparently this is a very simple task, but for some reason it's giving me trouble.</p> <p>Here's the code:</p> <pre><code> marcacoes = pd.read_excel(file_loc, sheet_name=&quot;MONITORAMENTO&quot;, index_col=None, na_values=['NA'], usecols =&quot;AN&quot;) x=0 while x &lt; len(statusclientes): ...
<p>You could try using openpyxl, as such:</p> <pre><code>from openpyxl import load_workbook book = load_workbook(file_loc) writer = pd.ExcelWriter(file_loc, engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) marcacoes.to_excel(writer, sheet_name='MONITORAMENTO', start...
python|excel|pandas|openpyxl|xlsm
1
4,503
60,882,887
How to fill null values in a column conditionally in pandas
<p>I have the following dataframe :</p> <pre><code>time label 2020-03-03 08:35:03.585 ok 2020-03-03 08:05:01.288 ok 2020-03-03 11:50:01.944 faulty 2020-03-03 08:45:04.540 ok 2020-03-12 10:30:02.227 None 2020-03-12 11:10:02.385 None 2020-03-05 11:15:03.526 None 2020-03-10 10:55:01.084 faulty 2020-03-...
<p>In your solution is necessary filter missing rows for both sides for same length of assigned array to <code>label</code> column:</p> <pre><code>m = df["label"].isna() df.loc[m, 'label'] = np.where(df.loc[m, 'time'] &lt; '2020-03-10', 'ok' ,'no label') print (df) time label 0 2020-03-03 08:3...
python|python-3.x|pandas|dataframe
0
4,504
71,621,643
how use some function to avoid writing for loops?
<p>I have a data frame like this:</p> <pre><code>2pair counts 'A','B','C','D' 5 'A','B','K','D' 3 'A','B','P','R' 2 'O','Y','C','D' 1 'O','Y','CL','lD' 4 </code></pre> <p>I want to make a nested list, based on the first 2 elements. the first element is t...
<p>Here's one way using <code>str.split</code> to split the strings in <code>2pair</code> column; then use <code>groupby.apply</code> + <code>to_dict</code> to create the lists:</p> <pre><code>df[['head', 'tail']] = [[(*x[:2],), x[2:]] for x in df['2pair'].str.split(',')] out = [[[*k]] + v for k,v in (df.groupby('head'...
python|pandas|list|dataframe
2
4,505
71,600,264
Pandas parallel URL downloads with pd.read_html
<p>I know I can download a csv file from a web page by doing:</p> <pre><code>import pandas as pd import numpy as np from io import StringIO URL = &quot;http://www.something.com&quot; data = pd.read_html(URL)[0].to_csv(index=False, header=True) file = pd.read_csv(StringIO(data), sep=',') </code></pre> <p>Now I woul...
<p>You could try like this:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd URLS = [ &quot;https://en.wikipedia.org/wiki/Periodic_table#Presentation_forms&quot;, &quot;https://en.wikipedia.org/wiki/Planet#Planetary_attributes&quot;, ] df = pd.DataFrame(URLS, columns=[&quot;URL&quot;]) ...
html|pandas|web-scraping
1
4,506
71,495,713
Sampling a dataframe according to some rules: balancing a multilabel dataset
<p>I have a dataframe like this:</p> <pre><code>df = pd.DataFrame({'id':[10,20,30,40],'text':['some text','another text','random stuff', 'my cat is a god'], 'A':[0,0,1,1], 'B':[1,1,0,0], 'C':[0,0,0,1], 'D':[1,0,1,0]}...
<p>The exact output you expect is unclear, but assuming you want to get 1 random row per letter with 1 you could reshape (while dropping the 0s) and use <code>GroupBy.sample</code>:</p> <pre><code>(df .set_index(['id', 'text']) .replace(0, float('nan')) .stack() .groupby(level=-1).sample(n=1) .reset_index() ) </co...
python-3.x|pandas|multilabel-classification
1
4,507
42,530,216
How to access weight variables in Keras layers in tensor form for clip_by_weight?
<p>I'm implementing WGAN and need to clip weight variables.</p> <p>I'm currently using <em>Tensorflow</em> with <em>Keras</em> as high-level API. Thus building layers with Keras to avoid manually creation and initialization of variables.</p> <p>The problem is WGAN need to clip weight varibales, This can be done using...
<p>You can use constraints(<a href="https://keras.io/constraints/" rel="nofollow noreferrer">here</a>) class to implement new constraints on parameters. </p> <p>Here is how you can easily implement clip on weights and use it in your model.</p> <pre><code>from keras.constraints import Constraint from keras import back...
python|tensorflow|deep-learning|keras
4
4,508
69,667,513
How to plot timeline in a single bar?
<p>I am trying to plot a timeline chart but they are stacking over each other.</p> <pre><code>import pandas as pd import plotly.express as pex d1 = dict(Start= '2021-10-10 02:00:00', Finish = '2021-10-10 09:00:00', Task = 'Sleep') d2 = dict(Start= '2021-10-10 09:00:00', Finish = '2021-10-10 09:30:00', Task = 'EAT') d3...
<p>According to the <a href="https://plotly.com/python-api-reference/generated/plotly.express.timeline.html" rel="nofollow noreferrer">documentation</a>, you can use the <code>y</code> parameter and provide an array_like object of size equal to the number of rows in <code>df</code> and all elements equal.</p> <p>So, on...
python|pandas|graph|plotly|gantt-chart
2
4,509
69,736,701
Comparing embeddings of a siamese network
<p>I have created a Siamese network using tensorflow 2.4.</p> <pre><code>def create_encoder_siamese(pairs, cfg): # Based on https://keras.io/examples/vision/siamese_network/ # and https://keras.io/examples/vision/siamese_contrastive/ def euclidean_distance(vects): x, y = vects sum_square = tf.math.reduce_sum(t...
<p>Regarding the error, the Model 'inputs' take a tensor or a list of tensors and not a list of sizes:</p> <pre><code>tower_1 = tf.keras.layers.Input(EMBEDDING_SIZE) tower_2 = tf.keras.layers.Input(EMBEDDING_SIZE) # Compute distance between embeddings distance_layer = tf.keras.layers.Lambda(euclidean_distance)([tower...
python|tensorflow|siamese-network
1
4,510
69,881,567
pandas subtract rows in dataframe according to a few columns
<p>I have the following dataframe</p> <pre><code>data = [ {'col1': 11, 'col2': 111, 'col3': 1111}, {'col1': 22, 'col2': 222, 'col3': 2222}, {'col1': 33, 'col2': 333, 'col3': 3333}, {'col1': 44, 'col2': 444, 'col3': 4444} ] </code></pre> <p>and the following list:</p> <pre><code>lst = [(11, 111), (22, 222), (99, 999...
<p>If need test by pairs is possible compare <code>MultiIndex</code> created by both columns in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.isin.html" rel="nofollow noreferrer"><code>Index.isin</code></a> with inverted mask by <code>~</code> in <a href="http://pandas.pydata.org/panda...
python|pandas
2
4,511
43,288,542
Max in a sliding window in NumPy array
<p>I want to create an array which holds all the <code>max()</code>es of a window moving through a given numpy array. I'm sorry if this sounds confusing. I'll give an example. Input:</p> <pre><code>[ 6,4,8,7,1,4,3,5,7,2,4,6,2,1,3,5,6,3,4,7,1,9,4,3,2 ] </code></pre> <p>My output with a window width of 5 shall be th...
<p>Pandas has a rolling method for both Series and DataFrames, and that could be of use here:</p> <pre><code>import pandas as pd lst = [6,4,8,7,1,4,3,5,7,8,4,6,2,1,3,5,6,3,4,7,1,9,4,3,2] lst1 = pd.Series(lst).rolling(5).max().dropna().tolist() # [8.0, 8.0, 8.0, 7.0, 7.0, 8.0, 8.0, 8.0, 8.0, 8.0, 6.0, 6.0, 6.0, 6.0, ...
python|performance|numpy|scipy|max
14
4,512
50,537,015
Setting Dataframe Value based on idx Series
<p>Given the Dataframe <code>df</code>:</p> <pre><code>A B C 0.10 0.83 0.07 0.40 0.30 0.30 0.70 0.17 0.13 0.72 0.04 0.24 0.15 0.07 0.78 </code></pre> <p>And the Series <code>s</code>:</p> <pre><code>A 3 B 0 C 4 dtype: int64 </code></pre> <p>Is there a w...
<p>There are a couple of ways you can do this. Both require converting your data to <code>object</code> type in order to assign strings to previously <code>float</code> series.</p> <h2>Option 1: numpy</h2> <p>This requires you to input coordinates via an integer array or, as here, a list of tuples.</p> <pre><code>im...
python|pandas|indexing
1
4,513
50,300,983
Involuntary conversion of int64 to float64 in pandas
<p>Never mind the below--I see the cause of the problem. The shift of course produces a N/A.</p> <p>I want to prevent a type conversion that occurs when concatenating a dataframe to itself horizontally. I have a dataframe where all columns are int64 (and the index is a datetime64[ns]):</p> <pre><code>df.dtypes Out[...
<p>This occurs because <code>df.shift(-1)</code> has one element which is <code>NaN</code>, which is a <code>float</code>. Such a series will automatically be upcasted to <code>float</code>. Here is a minimal example:</p> <pre><code>df = pd.DataFrame({'op': [1, 2, 3]}) df = pd.concat([df, df.shift(-1).add_suffix('_nex...
python|pandas|dataframe
2
4,514
45,358,766
Using a function to calculate the frequency of columns in a dataframe (pandas)
<p>For the following data set:</p> <pre><code>Index ADR EF INF SS 1 1 1 0 0 2 1 0 1 1 3 0 1 0 0 4 0 0 1 1 5 1 0 1 1 </code></pre> <p>I am going to calculate the frequency for each column. This is my code: </p> <pr...
<p>Assuming you want to calculate the frequency of all columns, rather than selectively, I don't recommend a custom function.</p> <p>Try using <code>df.apply</code>, passing <code>pd.value_counts</code>:</p> <pre><code>In [1048]: df.apply(pd.value_counts, axis=0) Out[1048]: ADR EF INF SS 0 2 3 2 2 1 ...
python|pandas|dataframe
3
4,515
62,751,221
Error Loading Tensorflow Frozen Inference Graph to OpenCV DNN
<p>I have trained an object detection model using Tensorflow API, following an example based on this Google Colaboratory notebook by Roboflow. <a href="https://colab.research.google.com/drive/1wTMIrJhYsQdq_u7ROOkf0Lu_fsX5Mu8a" rel="noreferrer">https://colab.research.google.com/drive/1wTMIrJhYsQdq_u7ROOkf0Lu_fsX5Mu8a</a...
<p><strong>Solved after adding an additional input node in my own generated pbtxt file</strong></p> <p>Someone suggested that OpenCV Version 4.11 which i was using is outdated. I updated to 4.30, still not working, however it now lets me to use FusedBatchNormV3 which is very important in the future.</p> <p>Now, after t...
python|tensorflow|opencv|google-colaboratory|roboflow
2
4,516
62,605,041
Change from .apply() to a function that uses list comprehension to compare one dataframe with a column of lists to values in another dataframe
<p>Simply put, I want to change the following code into a funtion that doesn't use <code>apply</code> or <code>progress_apply</code>, so that the performance doesn't take 4+ hours to execute on 20 million+ rows.</p> <pre><code>d2['B'] = d2['C'].progress_apply(lambda x: [z for y in d1['B'] for z in y if x.startswith(z)]...
<p>Let's try, using <code>explode</code> and regex with <code>extract</code>:</p> <pre><code>d1e = d1['B'].explode() regstr = '('+'|'.join(sorted(d1e)[::-1])+')' d2['B'] = d2['C'].astype('str').str.extract(regstr) </code></pre> <p>Output:</p> <pre><code> C B 0 8420513 8420 1 8421513 8421 2 8426513 842...
python|pandas|function|lambda|list-comprehension
3
4,517
62,848,600
Python skimage image with one value for color definition
<p>I just started working with <code>skimage</code> and I am using it in python.3.6 with the <code>skimage-version: 0.17.2</code><br /> And I started using the example form: <a href="https://scikit-image.org/docs/stable/user_guide/numpy_images.html" rel="nofollow noreferrer">https://scikit-image.org/docs/stable/user_gu...
<p>The color is defined by a single value because it's not RGB, it's greyscale. So the image shape is <code>(512, 512)</code>, and not <code>(512, 512, 3)</code>. As a result, if you pick a single <em>white</em> point it will be <code>[255]</code> and not <code>[255, 255, 255]</code>.</p> <p>If you're confused because ...
python|python-3.x|image|numpy|scikit-image
1
4,518
73,791,775
ValueError: Output of generator should be a tuple `(x, y, sample_weight)` or `(x, y)`. Found: [[[[0.08627451 0.10980393 0.10980393]
<p>I am a new learner in tensorflow, when I try to do the transfer learning. I meet an error of Value error. Does anyone know where the bug is? This code is related to the transfer learning of VGG16. Basically I just created my own MLP layers and do the fine-tuning</p> <pre><code>import os from tensorflow.keras.models ...
<p>The output of VGG16 is of shape <code>(batch_size, height, width, channels)</code>. So before you use a <code>Dense</code> layer, you should apply a <code>Flatten</code> layer. Try this:</p> <pre><code>model2=Sequential() model2.add(Flatten()) model2.add(Dense(128, activation='relu')) model2.add(Dropout(0.5)) model2...
python|tensorflow|keras|transfer-learning
0
4,519
71,399,160
AttributeError: module 'numpy.random' has no attribute 'BitGenerator' in python 3.8.10
<p>I'm trying to import the xarray module into python 3.8.10 but I get this error:</p> <p><code> AttributeError: module 'numpy.random' has no attribute 'BitGenerator'</code></p> <p>In order to allow you to reproduce the error: First of all, I created a new environment with conda and by importing at the same time the mo...
<p>I solved mine with <code>pip install --upgrade numpy</code></p>
python-3.x|numpy|attributeerror|python-module|python-xarray
2
4,520
71,438,100
Pandas, Python - Assembling a Data Frame with multiple lists from loop
<p>Using loop to collect target data into lists from JSON file. These lists are organized as columns and their values are organized; thus, no manipulation/reorganization is required. Only attaching them horizontally.</p> <pre><code>#Selecting Data into List i=1 target = f'{pathway}\calls_{i}.json' with open(target,'r')...
<p>The problem is that you are overwriting the <code>number</code> variable in the loop, so is no longer available at the end of each iteration, I add a solution adding the column Index in each iteration.</p> <pre><code># create an empty dataframe df = pd.DataFrame() #Selecting Data into List i=1 target = f'{pathway}\...
python|python-3.x|pandas|dataframe
1
4,521
52,142,344
Creating a placeholder having a shape that is a function of another shape
<p>Suppose that we have a tensorflow placeholder as follows:</p> <pre><code>x = tf.placeholder(tf.float32, (2, 2, 3 ..., 1)) </code></pre> <p>I would like to create another tensor <code>y</code> whose shape is the as <code>x</code> except the first and second dimensions, which are three times those of <code>x</code>....
<p>What about this ?</p> <pre><code>x = tf.placeholder(tf.float32, (2, 2, 3 , 1)) shape = x.get_shape().as_list() shape[0] = shape[0] * 3 shape[1] = shape[1] * 3 y = tf.placeholder(tf.float32, shape=shape) shape = y.get_shape().as_list() print(shape) </code></pre> <blockquote> <p>[6, 6, 3, 1]</p> </blockquote>
python|tensorflow|placeholder
2
4,522
52,340,101
Tensor.name is meaningless in eager execution
<p>I was doing some exercise in tensorflow in google colab and trying something under eager execution. When I was practicing on the <code>tf.case</code> by running the code below:</p> <pre><code>x = tf.random_normal([]) y = tf.random_normal([]) op = tf.case({tf.less(x,y):tf.add(x,y), tf.greater(x,y):tf.subtract(x,y)}...
<p>This seems like a bug in eager execution, which you should feel encouraged to <a href="https://github.com/tensorflow/tensorflow/issues" rel="nofollow noreferrer">report</a>.</p> <p>That said, using <code>tf.case</code> to express what it does only makes sense when constructing graphs. Enabling eager execution allow...
python|tensorflow
2
4,523
60,754,633
Why getting values of model parameters and reassigning of new values takes longer and longer in TensorFlow?
<p>I have a Python function that takes TensorFlow session, symbolic variables (tensors representing parameters of the model, gradients of the model parameters). I call this function in a loop and each subsequent call takes longer and longer. So, I wonder what might be the reason for that.</p> <p>Here is the code of th...
<p>It seems that you are missing the point on how tensorflow 1.* is used. I'm not going into details here since you could find plenty of resources on the internet. I think <a href="http://download.tensorflow.org/paper/whitepaper2015.pdf" rel="nofollow noreferrer">this paper</a> would be enough to understand the concept...
python|tensorflow
1
4,524
60,503,194
Dropping index column of mutiple excel files in python
<p>I have multiple excel sheets that have identical column names. When I was saving the files from previous computations I forgot to set ‘Date’ as index and now all of them (40) have index columns with numbers from 1-200. If I load these into python they get an additional index column again resulting in 2 unnamed colum...
<p>dfs = [pd.read_csv(file).set_index('Date')[['value']] for file in glob.glob("/your/path/to/folder/*.csv")]</p>
python|pandas|dataframe|datetimeindex
0
4,525
60,399,734
Indexing in two dimensional PyTorch Tensor using another Tensor
<p>Suppose that tensor A is defined as:</p> <pre><code> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 </code></pre> <p>I'm trying to extract a flat array out of this matrix by using another tensor as indices. For example, if the second tensor is defined as:</p> <pre><code>0 1 2 3 </code></pre> <p>I want the result...
<p><strong>1st Approach: using <code>torch.gather</code></strong></p> <pre><code>torch.gather(A, 1, B.unsqueeze_(dim=1)) </code></pre> <p>if you want one-dimensional vector, you can add squeeze to the end:</p> <pre><code>torch.gather(A, 1, B.unsqueeze_(dim=1)).squeeze_() </code></pre> <p><strong>2nd Approach: using lis...
python|pytorch
1
4,526
72,698,869
pandas - get difference to previous n-th rows
<p>Assume I have the following data frame in pandas, with accumulated values over time for all ids:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>date</th> <th>value</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>01.01.1999</td> <td>2</td> </tr> <tr> <td>2</td> <td>01.01.1999...
<p>IIUC, you want to groupby and <code>diff</code></p> <pre class="lang-py prettyprint-override"><code>df['value'] = df.groupby('id')['value'].diff().fillna(df['value']) </code></pre> <pre><code>print(df) id date value 0 1 01.01.1999 2.0 1 2 01.01.1999 3.0 2 3 01.01.1999 5.0 3 1 03.01.1...
python-3.x|pandas
0
4,527
72,536,408
How to drop columns from a pandas DataFrame that have elements containing a string?
<p>This is not about dropping columns whose name contains a string.</p> <p>I have a dataframe with 1600 columns. Several hundred are garbage. Most of the garbage columns contain a phrase such as <code>invalid value encountered in double_scalars (XYZ)</code> where `XYZ' is a filler name for the column name.</p> <p>I wou...
<p>You can use <code>df.select_dtypes(include=[float,bool]</code>) or <code>df.select_dtypes(exclude=['object'])</code></p> <p>Link to docs <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.select_dtypes.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.s...
python-3.x|pandas|dataframe
2
4,528
72,712,449
SageMaker Pipeline - Processing step for ImageClassification model
<p>I'm trying to solve ImageClassification task. I have prepared a code to train, evaluate and deploy tensorflow model in SageMaker Notebook. I'm new with SageMaker and SageMaker Pipeline too. Currently, I'm trying to split my code and create SageMaker pipeline to solve Image Classification task. In reference to AWS do...
<p>So, <code>ImageGenerator</code> and <code>flow_from_directory</code> I continue use inside of Training step. Processing step I skip at all, just use Training, Evaluating and Register model.</p>
tensorflow|keras|amazon-sagemaker|image-preprocessing
0
4,529
72,580,594
ModuleNotFoundError: No module named 'yaml' when trying to fit sagemaker tensorflow estimator locally
<p>I am trying to follow <a href="https://gitlab.com/juliensimon/aim410/-/tree/master" rel="nofollow noreferrer">this</a> tutorial for connecting aws to a jupyter notebook for local development (I am running jupyter inside of vscode which I don't think matters but just noting it in case).</p> <p>I have <a href="https:/...
<p>You are just missing the pyyaml module</p> <p>Install it by:</p> <pre><code>pip install pyyaml </code></pre>
python|docker|tensorflow|amazon-sagemaker
1
4,530
59,863,058
How to avoid the bottleneck to GPU in case of CNN ( Conv Neural Net )?
<p>I am using Keras ( with tensorflow ) to implement CNN, doing image classification. My GPU usage isn't crossing %1 , reasons I have found that it is due to delay in loading data into memory hence low GPU utilisation. But I am not getting how to implement it using keras.</p> <p>Can anyone help me with code snippet ...
<p>There is a lot to do here.</p> <p>Firstly, you'll need a generator. It will give the data batch per batch. You can either write your own generator or leave keras to do it, use <a href="https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly" rel="nofollow noreferrer">this tutorial</a> in the first...
tensorflow|machine-learning|keras
1
4,531
59,476,863
Reindexing Multiindex dataframe
<p>I have Multiindex dataframe and I want to reindex it. However, I get 'duplicate axis error'.</p> <pre><code>Product Date col1 A September 2019 5 October 2019 7 B September 2019 2 October 2019 4 </code></pre> <p>How can I achieve output like this?</p>...
<p>Let <code>df1</code> be your first data frame with non-zero values. The approach is to create another data frame <code>df</code> with zero values and merge both data frames to obtain the result.</p> <pre><code>dates = ['{month}-2019'.format(month=month) for month in range(1,9)]*2 length = int(len(dates)/2) products...
pandas|multi-index|reindex
0
4,532
59,627,166
Update value in a cell based on summation of other cells matching other grouping variables
<p>I have dataframe like this -</p> <pre><code> Alpha Title Jan Feb Mar Apr 0 a T1 63 66 65 53 1 b T2 35 88 81 42 2 b T3 0 23 51 95 3 c T2 83 70 77 57 4 c T3 0 81 15 59 </code></pre> <p>I want to update the value in column <code>Jan</code> where <code>T...
<p>Use:</p> <pre><code>#create Series for match by conditions and columns names df1 = df.set_index('Alpha') s = df1.loc[df1['Title'].eq('T2'), ['Jan','Feb','Mar']].sum(1) #another condition m = df['Title'].eq('T3') #replace by mask df.loc[m, 'Jan'] = df.loc[m, 'Alpha'].map(s) print (df) Alpha Title Jan Feb Mar ...
python|pandas
4
4,533
61,630,255
Resetting index to flat after pivot_table in pandas
<p>I have the following dataframe <code>df</code></p> <pre><code> Datum HH DayPrecipitation 9377 2016-01-26 18 3 9378 2016-01-26 19 4 9379 2016-01-26 20 11 9380 2016-01-26 21 23 9381 2016-01-26 22 12 </code></pre> <p>Which I converted to wide format using </p> <pre><code>df.piv...
<p>You can remove <code>[]</code> in <code>['DayPrecipitation']</code> for avoid <code>MultiIndex in columns</code>, then set new columns names by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_axis.html" rel="nofollow noreferrer"><code>DataFrame.set_axis</code></a> and last con...
python|pandas|pivot-table
1
4,534
58,156,797
Replacing bad date values in python pandas
<p>I have a dataframe in pandas which mostly contain correct date values but it also contain bad date values. How can check for those bad date fields and replace it with today's date.</p> <p>My dataframe will look like</p> <pre><code>Date 12/12/2018 12/11/2018 #REF 12/1/205 12/1/205 N/A Unknown 6/12/2018 6/3/2018 </c...
<p>We can using <code>to_datetime</code></p> <pre><code>pd.to_datetime(df.Date,errors='coerce').fillna(pd.to_datetime('today')).dt.date Out[484]: 0 2018-12-12 1 2018-12-11 2 2019-09-29 3 2019-09-29 4 2019-09-29 5 2019-09-29 6 2019-09-29 7 2018-06-12 8 2018-06-03 Name: Date, dtype: object #d...
python-3.x|pandas
1
4,535
54,955,859
Pandas/Dataframe: How to assign default value when condition fails while taking single cell value from data frame using python?
<p>Let consider the below code:</p> <pre><code>import pandas as pd df = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8]], columns=["A", "B"]) x=0 print(df) x=df.loc[df['A'] == 3, 'B', ''].iloc[0] print(x) </code></pre> <p>while printing the x I get 4 as the output.Its fine. If the condition get fails as per the belo...
<p>you can have a look at try and except for exception handling, Use:</p> <pre><code>import pandas as pd df = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8]], columns=["A", "B"]) x=0 print(df) try: x=df.loc[df['A'] == 3, 'B', ''].iloc[0] print(x) except Exception as e: print(e) print(x) </code></pre>...
python-3.x|pandas|dataframe
2
4,536
54,695,828
Transforming a Nested Dict in a dataframe?
<p>I have been trying to parse the nested dict in data frame. I made this df from dict, but couldn't figure out this nested one.</p> <p>df</p> <pre><code> First second third 0 1 2 {nested dict} </code></pre> <p>nested dict:</p> <pre><code> {'fourth': '4', 'fifth': '5', 'sixt...
<p>I can't quit tell the format of the nested dict in the "third" column, but here is what I recommend using <a href="https://stackoverflow.com/questions/29681906/python-pandas-dataframe-from-series-of-dict">Python: Pandas dataframe from Series of dict</a> as a starting point. Here is a dict and dataframe which are rep...
python|pandas|dataframe
1
4,537
54,998,898
Passing Genrator function to TF-Hub Universal sentence Encoder from pandas dataframe
<p>I have a pandas dataframe in which one column contains text body of an Email, I am trying to encode it using this <a href="https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/semantic_similarity_with_tf_hub_universal_encoder.ipynb" rel="nofollow noreferrer">tutorial</a>. I have managed...
<p>I had a similar issue and is very similar to "<a href="https://stackoverflow.com/questions/56488857/strongly-increasing-memory-consumption-when-using-elmo-from-tensorflow-hub/56493291#56493291">Strongly increasing memory consumption when using ELMo from Tensorflow-Hub</a>". I got a great answer from <a href="https:/...
python|pandas|tensorflow|generator
0
4,538
54,817,230
Can re.search() skip past integer objects?
<p>Question is pretty self-explanatory. I have a column in a pandas dataframe that contains both int and str objects. When I attempt to search it with re.search() it can't run because (I believe) some of the columns contain integer and it doesn't know what to do.</p> <p>Is there some type of a way to fix this? I do no...
<p>Best thing to do would be to use pandas inbuilt <code>pandas.Series.str.match</code> <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.match.html#pandas-series-str-match" rel="nofollow noreferrer">Docs</a>. It automatically "skips" int values by casting them all to string.</p> <p...
python|regex|pandas
0
4,539
49,393,659
tf.Data: what are stragglers in parallel interleaving?
<p><a href="https://www.tensorflow.org/versions/master/api_docs/python/tf/data/Dataset#interleave" rel="noreferrer"><code>interleave</code></a> is a <code>tf.Data.Dataset</code> method that can be used to interleave together elements from multiple datasets. <a href="https://www.tensorflow.org/api_docs/python/tf/contrib...
<p>A straggler is a function which takes longer than normal to produce its output. This can be due to congestion on the network, or weird combination of randomness.</p> <p><code>interleave</code> does all the processing in a sequential manner, on a single thread. In the following schema, let <code>___</code> denote <e...
python|tensorflow|tensorflow-datasets
10
4,540
49,569,708
How to determine highest occurrence of categorical labels across multiple columns per row
<p>I am trying to determine the label name with the highest occurrence across multiple columns and set the another pandas columns with that label.</p> <p>For examples, given this dataframe:</p> <pre><code> Class_1 Class_2 Class_3 0 versicolor setosa setosa 1 virginica versicolor virginica 2 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>value_counts</code></a> for return first index by most common value per rows with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofoll...
python|pandas
2
4,541
49,626,554
How to binary encode tow mixed features?
<p>I have a dataset looking like this one:</p> <pre><code>import pandas as pd pd.DataFrame({"A": [2, 2, 1, 0, 5, 3, 0, 4, 5], "B": [1, 0, 0, 0, 1, 1, 1, 0, 0]}) A B 0 2 1 1 2 0 2 1 0 3 0 0 4 5 1 5 3 1 6 0 1 7 4 0 </code></pre> <p>(I know that A is between 0 and 5; B is only 0 or 1)</p> <p>I wou...
<p>Given that the number of distinct values for column A and B is <code>n_A</code> and <code>n_B</code> respectively, and all values are represented as the zero-based integers, you can use the following transform function. </p> <pre><code>def transform(self, x): indices = x.B * n_A + x.A columns = ["A%d_B%d" %...
python|scikit-learn|sklearn-pandas
1
4,542
49,363,850
Approximation of vector-valued multivariate function with arbitrary in- and output dimensions in Numpy/Scipy
<p>Starting point is a m-dimensional vector-valued function </p> <p><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=f(x)%3D(f_1(x)%2C...%2Cf_m(x))%20" alt="eq">,</p> <p>where the input is also a n-dimensional vector:</p> <p><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=x%3D(x_1%2C...%2Cx_n)...
<p>I think you have to roll your own approximation for that. The idea is simple: sample the function at some reasonable points (at least as many as there are monomials in the Taylor approximation, but preferably more), and fit the coefficients with <code>np.linalg.lstsq</code>. The actual fit is one line, the rest is p...
numpy|scipy|interpolation|taylor-series|function-approximation
1
4,543
49,673,005
Any way for a faster Python For Loop
<p>Can anyone please let me know if the below for loop can be adjusted to be faster. the below for loop runs on a spreadsheet of almost 200k rows and it takes around 22 hours to compute. Any help would be appreciated.</p> <p>So my initial spreadsheet have the 2 columns highlighted in green. </p> <p>My code job is to ...
<p>Yeah reduce down to minimal complexity then optimize as @jpp commented. </p> <p>Take a look at this also, great way to get things like this done at speed with Python. <a href="http://chriskiehl.com/article/parallelism-in-one-line/" rel="nofollow noreferrer">http://chriskiehl.com/article/parallelism-in-one-line/</a>...
python|pandas|for-loop|dataframe
1
4,544
73,341,288
Replace a column with binned values and return a new DataFrame
<p>I have a DataFrame <code>df</code> that has an <code>Age</code> column with continuous variables. I would like to create a new DataFrame <code>new_df</code>, replacing the original continuous variables with categorical variables that I created from binning.</p> <p>Is there a way to do this?</p> <p><strong>DataFrame ...
<p>You can try add <code>include_lowest</code> argument to make <code>0</code> included to <code>Toddler</code> label</p> <pre class="lang-py prettyprint-override"><code>out = df.join(pd.cut(df.pop('Age'), bins=[0,3,17,25,64,99], labels=['Toddler', 'Child', 'Young Adult', 'Adul...
python|pandas|dataframe|binning
1
4,545
67,205,712
Sorting two separate xarray DataArrays based on one of those arrays only in a dask-friendly way
<p>Say I have a two DataArrays, <code>A</code> and <code>B</code>, both with dimensions time, x, z. I want to sort all values of <code>A</code> only in x and z. So that at each individual time I will have a DataArray with sorted values. Simultaneously, I also want to sort <code>B</code> but based on the values of <code...
<p>I think I have something working that seems to be fully parallel. Only works when the time dimension is chunked with size one:</p> <pre class="lang-py prettyprint-override"><code>import xarray as xr import numpy as np def zipsort3(da_a, da_b, unsorted_dim=&quot;time&quot;): &quot;&quot;&quot; Only works if...
python|arrays|numpy|dask|python-xarray
0
4,546
60,000,899
Is Python runtime needed to use Tensorflow.js Node?
<p>As mentioned in the node version installation instructions, is Python runtime needed to use Tensorflow.js Node? I can install whatever is required but not sure if our production servers have it.</p>
<p>It depends of what you want to do. </p> <p>If you already have a tensorflow model written in python that you would like to deploy for inference in nodejs, </p> <ul> <li><p>you can use the tensorflow.js converter. In this case you will need a python runtime</p></li> <li><p>since the version 1.3 of tfjs-node, it is ...
tensorflow.js
1
4,547
60,226,735
How to count overlapping datetime intervals in Pandas?
<p>I have a following DataFrame with two datetime columns:</p> <pre><code> start end 0 01.01.2018 00:47 01.01.2018 00:54 1 01.01.2018 00:52 01.01.2018 01:03 2 01.01.2018 00:55 01.01.2018 00:59 3 01.01.2018 00:57 01.01.2018 01:16 4 01.01.2018 01:00 01.01.2018 01:12 5 01.01.20...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumsum.html" rel="noreferrer"><code>Series.cumsum</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="noreferrer"><code>Series.map</code></a> (or <a href="https://pandas....
python|pandas|datetime|count
6
4,548
60,158,162
Convolution 3D image with 2D filter
<p>I have a single image of shape <code>img.shape = (500, 439, 3)</code></p> <p>The convolution function is</p> <pre><code>def convolution(image, kernel, stride=1, pad=0): n_h, n_w, _ = image.shape f = kernel.shape[0] kernel = np.repeat(kernel[None,:], 3, axis=0) n_H = int(((n_h + (2*pad) - f) / stri...
<p>np.multiply is doing an elementwise multiplication. However, your arguments do not have matching dimensions. You could transpose your kernel or image with this to ensure it can work: </p> <pre><code>kernel = kernel.transpose() </code></pre> <p>You could do this prior to your <code>np.multiply</code> call. </p>
python|numpy|convolution
2
4,549
65,453,509
Make a attendace student report using pandas
<p>I have some <code>csv</code> table from google form for attendance report. The data looks like this</p> <pre><code>df1= pd.read_csv(&quot;12-9-2020.csv&quot;) df1 Name StudentID Robert C 102 Jessica Myla 103 Nana D 105 df2= pd.read_csv(&quot;12-10-2020.csv&quot;) df2 Name ...
<p>Here is a solution for two dataframes:</p> <pre><code>df1.set_index('StudentID', inplace=True) df1.loc[:, '12-9-2020.csv'] = 1 df2.set_index('StudentID', inplace=True) df2.loc[:, '12-10-2020.csv'] = 1 df1 = df1.join(df2, how='outer', rsuffix='_') df1['Name'] = df1['Name'].combine_first(df1['Name_']) df1.drop('Name_...
python|pandas|dataframe
2
4,550
65,157,759
Filling missing values with increasing values in pandas
<p>I have a dataframe, which contains tool <em>id</em> and <em>time</em>.</p> <p>For the last date I have tool <em>counter</em> values, and I need to fill up missing <em>counter</em> values in the dataframe by substracting <em>1</em> from the <em>counter</em> for each time the <em>id</em> has been used at a particular ...
<p>You can <code>groupby</code> the dataframe <code>df_sort</code> on <code>id</code> then forward fill the <code>counter</code> values per group using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.ffill.html" rel="nofollow noreferrer"><code>ffill</code></a> an...
python|pandas|dataframe
2
4,551
49,950,186
Can I change drop out rate when use the call method in tf.nn.rnn_cell.MultiRNNCell
<p>Here is how I define the MultiRNNCell:</p> <pre><code> n_lstm_cells = [tf.contrib.rnn.DropoutWrapper(tf.contrib.rnn.LSTMCell(hs), output_keep_prob=1-dropout_ph, variational_recurrent=True, ...
<p>I solved it by creating another MutilRNNCell with shared(reuse) weights in certain <code>tf.variable_scope</code>. And when use the call method, we need to specific the <code>tf.variable_scope</code> to <code>’[YOUR SCOPE]/rnn/mutil_rnn_cell’</code>.</p>
python|tensorflow|rnn
1
4,552
50,050,617
Assign Unique Numeric Group IDs to Groups in Pandas
<p>I've consistently run into this issue of having to assign a unique ID to each group in a data set. I've used this when zero padding for RNN's, generating graphs, and many other occasions. </p> <p>This can usually be done by concatenating the values in each <code>pd.groupby</code> column. However, it is often the ca...
<p>You just need <code>ngroup</code> data from seeiespi (or <code>pd.factorize</code>)</p> <pre><code>df.groupby('C').ngroup() Out[322]: 0 0 1 0 2 2 3 1 4 1 5 1 6 1 7 2 8 2 dtype: int64 </code></pre> <p>More Option</p> <pre><code>pd.factorize(df.C)[0] Out[323]: array([0, 0, 1, 2, 2, 2, 2,...
python|pandas|pandas-groupby
29
4,553
50,071,518
What is the proper way of selecting date ranges in Pandas multi-indexes?
<p><strong>What is the proper way of selecting date ranges in Pandas multi-indexes?</strong></p> <p>I've got a multi-index dataframe, that looks like the following:</p> <p><a href="https://i.stack.imgur.com/tECvB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tECvB.png" alt="enter image descriptio...
<p>Using data from previous question:</p> <pre><code>d = {'Col1': {(Timestamp('2015-05-14 00:00:00'), '10'): 81.370003, (Timestamp('2015-05-14 00:00:00'), '11'): 80.41999799999999, (Timestamp('2015-05-14 00:00:00'), 'C3'): 80.879997, (Timestamp('2015-05-19 00:00:00'), '3'): 80.629997, (Timestamp('2015-05-19 00...
python|pandas|datetime|time-series|multi-index
2
4,554
50,106,021
Adding a column of repeating values to dataframe
<p>I have some quarter level data for finance deals, so a pretty big dataset. I now want to add the following values to a new column repeated over and over:</p> <pre><code>[-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12] </code></pre> <p>The column should then look something like this:</p> <pre>...
<p>Try this:</p> <pre><code>N = len(df) df['A'] = pd.Series(np.tile(lst, N//len(lst))).iloc[:N] </code></pre>
python|pandas|dataframe
3
4,555
46,761,348
Change the value of `row`
<pre><code>def multiple_dfs(item, sheets, *args): """ Put multiple dataframes into one xlsx sheet """ writer, row = args[:2] response = send_request(item).content df = pd.read_csv(io.StringIO(response.decode('utf-8'))) df.to_excel(writer, sheets, startrow=row, index=False) row += len(...
<p>You can't change argument values like that.</p> <pre><code> ... ... return len(df.index) + 2 ... ... row = multiple_dfs(item, key, writer, row) </code></pre>
python|pandas
0
4,556
67,885,893
Mixture of Multi-Level columns & Regular Columns
<p>It is straightforward to create Pandas dataframes with Multi-level columns like so:</p> <pre><code>import numpy as np import pandas as pd dat = np.random.randn(5, 4) header = pd.MultiIndex.from_product([['Truck','Car'], ['Speed','Position']], ...
<p>Always need <code>MultiIndex</code>, there is possible use empty string for some level like:</p> <pre><code>df2[('', 'Age')] = np.random.randn(5) print (df2) Truck Car Speed Position Speed Position Age 0 1.224236 -0.545658 0.906748 -0.982617 -0.654448 1 -...
python|pandas
1
4,557
67,883,437
Get weekdays as column based on index
<p>I tried this code to get the following output:</p> <pre><code>idx = pd.date_range(&quot;2021-06-08&quot;, periods=3, freq=&quot;D&quot;) ts = pd.Series(['Tuesday', 'Wednesday', 'Thursday'], index=idx) ts 2021-06-08 Tuesday 2021-06-09 Wednesday 2021-06-10 Thursday Freq: D, dtype: object </code></pre> <p>...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.day_name.html" rel="nofollow noreferrer"><code>DatetimeIndex.day_name</code></a>:</p> <pre><code>idx = pd.date_range(&quot;2021-06-08&quot;, periods=3, freq=&quot;D&quot;) ts = pd.Series(idx.day_name(), index=idx) print (ts) ...
python|pandas
1
4,558
61,537,558
Pytorch:1.2.0 - AttributeError: 'Conv2d' object has no attribute 'weight'
<p>I am trying to initialise the following weights the following way:</p> <pre><code>def _initialize_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) eli...
<p>I think the attribute you're looking for is <code>weights</code>, not <code>weight</code>. (<em>Plural form instead of singular)</em> You can visit this link for more information. <a href="https://faroit.com/keras-docs/1.2.2/layers/convolutional/#convolution2d" rel="nofollow noreferrer">https://faroit.com/keras-docs...
initialization|pytorch
0
4,559
61,408,653
How can I show data related to a max value from a dataset with pandas?
<p>I have this dataframe where I have more than one column and I want to know additional data to the maximum value of one column</p> <p>For example, given the following code, show the country where the number is the highest per year per causes What I did was:</p> <pre><code>var=data.groupby(["Year","Causes"])["number...
<p>There's probably a more efficient way but if I've understood what you'd like to achieve and your data structure then this works:</p> <pre><code>var=data.groupby(["Year","Causes"])["number"].max() var = pd.DataFrame(var) new = var.merge(data, how='inner').drop_duplicates() new </code></pre>
python|pandas|pandas-groupby
0
4,560
61,209,145
Transform schedule to comprehensive report with Python
<p>I'm trying to turn a schedule with the following format into a report format. </p> <p>Currently the data is stored as follows:</p> <pre><code>Person Name Jun 1 Jun 2 Jun 3 Jun 4 Jun 5 Jun 6 Jun 7 Jun 8 Jun 9 Jun 10 ... John Smith X X X X O O O ...
<p>This will need the <code>cumsum</code> create the subgroup then we stack , <code>groupby</code> with <code>agg</code> </p> <pre><code>df=df.set_index('PersonName') s1=df.eq('O').cumsum(1).stack().reset_index() s=s1[df.stack().ne('O').values].groupby(['PersonName',0])['level_1'].agg(['first','last']).reset_index(l...
python|pandas|dataframe|for-loop
2
4,561
61,529,235
How to run tflite model not on image classification swift
<p>I have seen several tutorials on how to run a tflite model for image classification, but don’t know how to do it for any other application... For example, I have a model that takes in audio data in the form of a (16000, 1) array. How can I pass this array into the tflite model?</p>
<p><code>TensorFlow Lite</code> provides all the tools we need to convert and run <code>TensorFlow models</code> on mobile, embedded, and IoT devices. </p> <p>To use a <code>model</code> with <code>TensorFlow Lite</code>, we must convert a full <code>TensorFlow model</code> into the <code>TensorFlow Lite</code> format...
swift|xcode|tensorflow|audio|tensorflow-lite
0
4,562
68,477,081
With Pandas, how do I use to_sql to insert a cell with lists into a Postgresql database?
<p>I'm stuck on how to insert a column that contains lists into a Postgresql database. I know it is theoretically possible, because there are datatypes like BIGINT[] that exist, whereas it doesn't exist with other SQL variants.</p> <p>Here is my code:</p> <pre><code>import datetime import json import pandas as pd impor...
<p>You cannot insert list in a SQL Database Cell as it breaks the normalization parameters.</p> <p>What you can do instead is:</p> <ol> <li>Convert your list to a json string object (or XML)</li> <li>Create a new table that has the elements in individual cells and refers to original table.</li> </ol> <p>For example: If...
python|pandas|postgresql
0
4,563
53,035,762
Creating new column based on value in another column
<p>I'm trying to create new feature columns based on values in a different column. So I have a column with comments, and if they contain a url address, I want to output 1 to the new column, or else output 0, so it would be a binary feature creation.</p> <pre><code>Text ...
<p>I think you can do this much more efficiently without <code>apply</code>, simply by using the boolean value resulting from <code>str.contains('http')</code>, and casting it to <code>int</code>:</p> <pre><code>data['contains_url'] = data['Text'].str.contains('http').astype(int) </code></pre>
python|python-3.x|pandas|numpy
1
4,564
65,850,595
Remove rows in a csv file based on the format of column value
<p>I have a csv file which contains three columns - computer_name, software_code, software_update_date. The file contains computers that I don't need in my final report. I only need the data for computers whose name starts with 40- , 46- or 98-. Here is the sample file:</p> <pre><code>computer_name software_code so...
<p>You can try this,</p> <pre><code># String to be searched in start of string search = (&quot;40-&quot;, &quot;46-&quot;, &quot;98-&quot;) # boolean series returned with False at place of NaN series = df[&quot;computer_name&quot;].str.startswith(search, na = False) # displaying filtered dataframe df[series]...
python|pandas
0
4,565
63,341,708
How to filter columns containing dates in format yyyyMmm?
<p>I am working on a data that looks like that:</p> <pre><code> unit coicop geotime 2020M07 ... 1996M04 1996M03 1996M02 1996M01 122 IA5 CP5261 AAT NaN ... 84.43 84.60 84.52 84.85 7630 IA5 CP5261 AAT NaN ... 62.60 62.72 62.66 62.91 23690 IA6 CP5261 AAT...
<p>You can convert all columns without first 3 to datetimes:</p> <pre><code>df = df.set_index(['unit','coicop','geotime']) df.columns = pd.to_datetime(df.columns, format='%YM%m') print (df) 2020-07-01 1996-04-01 1996-03-01 1996-02-01 \ unit coicop geotime ...
python|pandas
1
4,566
53,750,143
Flip tensorflow values
<p>I have a tensor which contains only 1s and 0s, like the following:</p> <pre><code>[0.0, 1.0, 1.0, 0.0, 1.0, 1.0] </code></pre> <p>What is the fastest method to "flip the bits" and output</p> <pre><code>[1.0, 0.0, 0.0, 1.0, 0.0, 0.0] </code></pre>
<p><code>1.0-x</code> should do the trick in your case.</p>
tensorflow|bit|logical-operators|flip
2
4,567
53,409,647
Combining different columns with overlapping index in pandas
<p>I have a pandas Dataframe which looks like this:</p> <pre><code> ABC_1 ABC_2 ABC_3 ABC_4 x y z k NaN y NaN k x NaN z NaN x NaN z k ... ... ... ... </code></pre> <p>This is just one column <code>ABC</code> which has been split into many columns. Sim...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow noreferrer"><code>unstack</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dropna.html" rel="nofollow noreferrer"><code>dropna</code></a> and for remove MultiInd...
python|python-3.x|pandas|dataframe|data-analysis
3
4,568
53,571,236
'DNN' object has no attribute 'fit_generator' in ImageDataGenerator() - keras - python
<p>Following code is developed for identify 5 image classes using keras and python with tensorflow backend. I have used imageDataGenerator but when I run this, it's started to train and after a while, following error occured.</p> <p>How can I solve this?</p> <blockquote> <p>Training Step: 127 | total loss: 0.01171...
<p>Your model object is an instance of the <code>tflearn.DNN</code> class, which simply does not have a <code>fit_generator</code> method. This method is only available for keras objects. Maybe you could define your architecture in keras and you would be able to use your data generators.</p>
python|tensorflow|machine-learning|keras
2
4,569
71,928,602
Difference between using a ML docker image and running pip install in Dockerfile
<p>I see there are many available Docker images for popular ML frameworks such as <a href="https://hub.docker.com/r/pytorch/pytorch" rel="nofollow noreferrer">PyTorch</a> and <a href="https://hub.docker.com/r/tensorflow/tensorflow/" rel="nofollow noreferrer">Tensorflow</a>.</p> <p>What is the difference between using t...
<p>There is no difference, using a pre-built image saves you from misconfiguring the docker environment or the missing dependencies and ensuring a safer execution (the whole point of docker I say). Your approach is fine in case you want to have a full control on the image being built.</p>
python|docker|machine-learning|deep-learning|pytorch
0
4,570
55,508,210
Grouping and Summing in Pandas
<p>I have a dataframe with two columns. The first column contains <code>years</code> and the second column contain <code>value</code>. I want to group a certain year and change it to one name for that group and add all the corresponding values.</p> <p>For example, below is the small dataset</p> <pre><code>years va...
<p>Use integer division, multiple <code>10</code>, cast to string and add <code>s</code> and use this Series for aggregating <code>sum</code>:</p> <pre><code>y = ((df['years'] // 10) * 10).astype(str) + 's' df = df.groupby(y)['value'].sum().reset_index() print (df) years value 0 1950s 6 1 1960s 14 2 1...
python|pandas|dataframe
3
4,571
67,020,577
AttributeError: module 'xlwings' has no attribute 'load'
<p>I am on Windows 10, Python 3.8.5, xlwings-0.23.0</p> <p>I am trying to load a selected range of cells in Excel into Pandas DataFrame. I am following documentation on: <a href="https://docs.xlwings.org/en/stable/api.html#xlwings.load" rel="nofollow noreferrer">https://docs.xlwings.org/en/stable/api.html#xlwings.load<...
<p>Case resolved with the following solution:</p> <p>Open Excel file and select a target tab.</p> <pre><code>wb = xw.Book(strMyExcelFile) wb.sheets[strMyTab].activate() </code></pre> <p>Critical issue #1: Need to define the range of selected cells to use downstream.</p> <p>Select a starting cell, C5 in this case, and a...
excel|pandas|xlwings
0
4,572
66,904,053
How do I select the first item independent of the number of dimensions?
<p>I have a multidimensional <code>numpy.array</code> called <code>my_imgs</code>. I want to store the array as an image. The dimensions of the array are not constant. At the moment I have four or five dimensions; later I will add more dimensions. For all diemensions from the 4th diemension on, I always want to select ...
<p>The slice that numpy uses to specify 'the entire dimension', <code>:</code>, is equal to <code>slice(None)</code>.</p> <p>This means you can do</p> <pre><code>import numpy as np arr_5d = np.zeros((10, ) * 5) arr_6d = np.zeros((10, ) * 6) def my_slicer(arr, i=0): indexer = (i, slice(None), slice(None)) + (0,)...
python|numpy
1
4,573
66,799,192
Numpy matrix with values equal to offset from central row/column
<p>For given odd value <code>a</code>, I want to generate two matrices, where values represent the offset from central row/column in x or y direction. Example for <code>a=5</code>:</p> <pre><code> | -2 -1 0 1 2 | | -2 -2 -2 -2 -2 | | -2 -1 0 1 2 | | -1 -1 -1 -1 -1 | X = | -2 -1 0 1 2 | Y = | 0 ...
<p><code>np.arange</code> and <code>np.repeat</code> will do:</p> <pre><code>a = 5 limits = -(a//2), a//2 + 1 col = np.c_[np.arange(*limits)] Y = np.repeat(col, repeats=a, axis=1) X = Y.T </code></pre>
python|numpy|numpy-ndarray
1
4,574
66,991,234
Python image_dataset_loader Module Instances are inconsistent
<p>I want to import an image dataset into Numpy arrays with images and labels. I am trying to use the <code>image_dataset_loader</code> to do this and have wrote this so far:</p> <pre><code>import image_dataset_loader (x_train, y_train), (x_test, y_test) = image_dataset_loader.load('./data', ['train', 'test']) </code>...
<p>Check the color of your images. Chances are that some of your images may be grayscale.</p>
arrays|python-3.x|image|numpy|artificial-intelligence
0
4,575
47,128,212
Is it possible to have dynamic batchsize in keras?
<p>Keras codes I have looked or wrote have fixed batchsize during training (i.e. 32, 64, 128 ...). I am wondering if it is possible to have dynamic batchsize. (For example, 104 in the first iteration, 82 in the next iteration, 95 in next, and so on.) </p> <p>I am currently using tensorflow backend.</p>
<p>It is possible if you train on a loop vs training with fit. an example</p> <pre><code>from random import shuffle dataSlices = [(0,104),(104,186),(186,218)] for epochs in range(0,10): shuffle(dataSlices) for i in dataSlices: x,y = X[i[0]:i[1],:],Y[i[0]:i[1],:] model.fit(x,y,epochs=1,bat...
tensorflow|deep-learning|keras
4
4,576
68,112,182
Replace the string in pandas dataframe
<p>I have the following dataframe (df):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>shape</th> <th>data</th> </tr> </thead> <tbody> <tr> <td>POINT</td> <td>POINT (4495 33442)</td> </tr> <tr> <td>POLYGON</td> <td>POLYGON ((6324 32691, 6326 32691, 6330 32691, 6333 32693, 6332 32696, 6329 ...
<p>This function will format the polygon strings correctly:</p> <pre><code>def format_polygon(s): return [tuple([float(i) for i in x.split(&quot; &quot;)]) for x in s[10:-2].split(&quot;, &quot;)] </code></pre> <p>and this code will format the point strings correctly:</p> <pre><code>def format_point(s): return ...
python|pandas|replace|python-re|parentheses
0
4,577
68,397,820
List of lists to array conversion. Mixed strings and floats
<p>I have an array (150,40) that looks like:</p> <pre><code>list_of_lists= ['name_1' 0.0123 'name_2' 0.1234 ... 'name_40' 0.213241 Name: 2015-03-26 16:02:42.117000, dtype: float64, and so on, 149 more ] </code></pre> <p>I have two questions:</p> <p>The 40 names are all the same for all 150 lists, how can I ...
<p>In regards the first question, one way you could do this, strictly using only <code>numpy</code> would be to create a new <code>numpy</code> structured array and create a set of two for each loops (<code>for x in list</code>), the top level to loop over array then the nested one to loop over each array element, appe...
python|arrays|list|numpy
0
4,578
68,073,270
Pandas: full outer join with filled-in blanks
<p>I have the following df:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Product</th> <th>Region</th> <th>MTD PnL</th> <th>FYTD PnL</th> </tr> </thead> <tbody> <tr> <td>21/6/1</td> <td>Coke</td> <td>Northeast</td> <td>$300</td> <td>$15,000</td> </tr> <tr> <td>21/6/1</td> <t...
<p>Use <code>.reindex</code> with the product of all the unique values for the other levels -- that way the values for the basis are filled in. <code>.reindex</code> also supports a <code>fill_value</code> for non-Index columns.</p> <pre><code>import pandas as pd idx = pd.MultiIndex.from_product([df1.Date.unique(), df1...
python|pandas|dataframe|join
0
4,579
59,119,925
Exclude column from being read using pd.ExcelFile().parse()
<p>I would like to exclude certain columns from being read when using pd.ExcelFile('my.xls').parse()</p> <p>Excel file I am trying to parse has too many columns to list them all in usecols argument since I only need to get rid off a single column that is causing trouble.</p> <p>Is there like a simple way to ~ invert ...
<p>We can usually do </p> <pre><code>head = list(pd.read_csv('your.xls', nrows = 1)) df = pd.read_excel('your.xls', usecols = [col for col in head if col != 'the one drop'])) </code></pre> <p>However , why not read whole file then <code>drop</code> it </p> <pre><code>df = pd.read_excel('your.xls').drop('the col dro...
python|pandas|python-3.7
2
4,580
46,004,393
Convolutional layer output size
<p>I'm currently trying to get into deep learning and I have a minor problem in understanding concerning CNNs. </p> <p>According to <a href="http://cs231n.github.io/convolutional-networks" rel="nofollow noreferrer">CS231n</a>, the common formula for computing the output size of a conv. layer is <code>W'=(W−F+2P)/S+1</...
<p>Here for the conv layer by default they used <code>SAME</code> padding. <code>P=floor(F/2)</code> for <code>SAME</code> padding. So <code>(28- 5 + 2*2)/1 +1 = 28</code> </p>
tensorflow|deep-learning
2
4,581
45,768,126
When we do supervised classification with NN, why do we train for cross-entropy and not for classification error?
<p>The standard supervised classification setup: we have a bunch of samples, each with the correct label out of <code>N</code> labels. We build a NN with N outputs, transform those to probabilities with softmax, and the loss is the mean <code>cross-entropy</code> between each NN output and the corresponding true label,...
<p>Policy gradient <strong>is</strong> using cross entropy (or KL divergence, as Ishant pointed out). For supervised learning tf.gather is really just implementational trick, nothing else. For RL on the other hand it is a must because you do not know "what would happen" if you would execute other action. Consequently y...
tensorflow|neural-network|gradient-descent|reinforcement-learning
1
4,582
45,742,265
Matrix m1 multiplied by tf.inverse(m1) does not yield identity matrix
<p>Using TensorFlow in python, I have the following code:</p> <pre><code>sess = tf.InteractiveSession() # so I can eval() t1 = tf.convert_to_tensor([[1,4,5],[34,5,1],[53,1,4]],dtype=tensorflow.float32) t1.eval() OUTPUT&gt;&gt; array([[ 1., 4., 5.], [ 34., 5., 1.], [ 53., 1., 4.]], dtype=floa...
<p>Here <code>t1*t1_inverse</code> is element-wise multiplication, you need to use <code>tf.matmul</code></p> <pre><code>idenity_mat = tf.matmul(t1, t1_inverse) sess.run(identity_mat) # Results: array([[ 1.00000000e+00, 5.96046448e-08, 0.00000000e+00], [ 0.00000000e+00, 1.00000000e+00, -...
python|tensorflow|matrix-multiplication|matrix-inverse
1
4,583
45,866,555
Pycharm not displaying wide Dataframe in Jupyter Notebook
<p>In Pycharm, I'm using a Jupyter notebook, but when the pandas dataframe I'm working with gets wider than the width of the cell it doesn't display the dataframe anymore. Instead there's just a horizontal line across the output cell. I've tried setting the max columns, width, and every other pandas display option and ...
<p>This is a PyCharm bug and it still has not been resolved in the latest (2017.3) version. </p> <p>Only 1D dataframes are shown as expected, multidimensional dataframes are shown as a horizontal line. </p> <p>You can vote this issue in IntelliJ's issue tracker: <a href="https://youtrack.jetbrains.com/issue/PY-25931"...
python|pandas|ipython|pycharm|jupyter
1
4,584
46,144,951
Sci-kit-learn Normalization removes column headers
<p>I have a pandas data frame with 22 columns, where the index is datetime. </p> <p>I am trying to normalize this data using the following code:</p> <pre><code>from sklearn.preprocessing import MinMaxScaler # Normalization scaler = MinMaxScaler(copy = False) normal_data = scaler.fit_transform(all_data2) </code></pre...
<p>Try <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.scale.html" rel="nofollow noreferrer"><code>sklearn.preprocessing.scale</code></a>. No need for the class-based scaler here.</p> <blockquote> <p>Standardize a dataset along any axis. Center to the mean and component wise scale ...
python|pandas|numpy|scikit-learn
1
4,585
66,680,988
Cumulative Sum of Grouped Strings in Pandas
<p>I have a pandas data frame that I want to group by two columns and then return the cumulative sum of a third column of strings as a list within one of these groups.</p> <p>Example:</p> <pre><code>Year Bucket Name 2000 1 A 2001 1 B 2003 1 C 2000 2 B 2002 2 C </code></pre> <p>...
<p>My Dr. Frankenstein Answer</p> <pre><code>dat = [] rng = range(df.Year.min(), df.Year.max() + 1) for b, d in df.groupby('Bucket'): for y in rng: dat.append([y, b, [*d.Name[d.Year &lt;= y]]]) pd.DataFrame(dat, columns=[*df]) Year Bucket Name 0 2000 1 [A] 1 2001 1 ...
python|pandas|cumsum
3
4,586
66,649,154
pandas read_excel adds fractional seconds that don't appear in original xlsx file
<p>I am reading an excel spreadsheet into pandas as:</p> <p><code>input_df: pd.DataFrame = pd.read_excel(data_filename, engine='openpyxl')</code></p> <p>Here's a screenshot of the beginning of the excel file:</p> <p><a href="https://i.stack.imgur.com/GYKTB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur....
<p>OK. This was my fault. It turns out that there is a fractional part to the timestamps. Google sheets needed to be configured to show that fractional part. In summary, it appears that there is agreement between the xlsx file and the pandas dataframe.</p>
python|excel|pandas|dataframe
0
4,587
66,385,270
Getting groups by group index
<p>I want to access the group by group index. My dataframe is as given below</p> <pre><code>import pandas as pd from io import StringIO import numpy as np data = &quot;&quot;&quot; id,name 100,A 100,B 100,C 100,D 100,pp; 212,E 212,F 212,ds 212,G 212, dsds 212, sas 300,Endüstrisi` &quot;&quot;&quot; df = pd.read_csv(S...
<p>You need pass value of <code>id</code>:</p> <pre><code>dfg=df.groupby('id',sort=False) a = dfg.get_group(100) print (a) id name 0 100 A 1 100 B 2 100 C 3 100 D 4 100 pp; </code></pre> <hr /> <pre><code>dfg=df.groupby('id',sort=False) a = dfg.get_group(df.loc[0, 'id']) print (a) id name 0 ...
pandas|group-by|python-3.8
1
4,588
66,413,040
Converting a naive datetime column to a new timezone Pandas Dataframe
<p>I have the following dataframe, named 'ORDdataM', with a DateTimeIndex column 'date', and a price point column 'ORDprice'. The date column has no timezone associated with it (and is naive) but is actually in 'Australia/ACT'. I want to convert it into 'America/New_York' time.</p> <pre><code> ORDpri...
<p>Your <code>date</code> is index not a column, try:</p> <pre><code>df.index = df.index.tz_localize('Australia/ACT').tz_convert('America/New_York') df # ORDprice #date #2021-02-23 02:09:00-05:00 24.01 #2021-02-23 02:14:00-05:00 23.91 #2021-02-23 02:19:0...
python|pandas|datetime|timezone|datetimeindex
4
4,589
66,681,835
Pandas: Remove rows except the first new occurrence of a value
<p>I have a dataframe</p> <pre><code>x y a 1 b 1 c 1 d 0 e 0 f 0 g 1 h 1 i 0 j 0 </code></pre> <p>I want to remove the rows with 0 except every first new occurence of 0 after 1, so the resultant dataframe should be</p> <pre><code>x y a 1 b 1 c 1 d 0 g 1 h 1 i 0 </code></pre> <p>Is it possible to do it without creating ...
<p>Check consecutive similarity using shift()</p> <pre><code> df[df.y.ne(0)|(df.y.eq(0)&amp;df.y.shift(1).ne(0))] x y 0 a 1 1 b 1 2 c 1 3 d 0 6 g 1 7 h 1 8 i 0 </code></pre>
python|pandas|dataframe|numpy
2
4,590
72,996,734
Create columns from another column which is a list of items
<p>Let's say that I have a <code>DataFrame</code> with column <code>A</code> which is a list of strings of the form &quot;Type:Value&quot; where <code>Type</code> can have 5 different values and <code>Value</code> can be anything. What I would like to do is to create new 5 columns (each having appropriate <code>Type</c...
<p>One Solution. This can be done on loop as well. But since the number of columns were small, the code is less automated.</p> <pre><code> df = pd.DataFrame({&quot;A&quot;: [[&quot;Type1:Value1&quot;, &quot;Type2:Value2&quot;, &quot;Type1:Value3&quot;]]}) df[['x','y','z']] = df.A[0] df['type1'] = df.x....
python-3.x|pandas
0
4,591
70,631,234
creating series_route from multiple chunks of string in list
<p>I am working on a route building code and have half a million record which taking around 3-4 hrs to get executed.</p> <p>For creating dataframe:</p> <pre><code># initialize list of lists data = [[['1027', '(K)', 'TRIM']], [[SJCL, (K), EJ00, (K), ZQFC, (K), 'DYWH']] # Create the pandas DataFrame df = pd.DataFrame(d...
<p>Use <code>explode</code> to flatten your dataframe:</p> <pre><code>sr1 = df['route'].explode() sr2 = pd.Series(np.where(sr1.str[0] == '(', sr1.shift() + sr1, sr1), index=sr1.index) df['route'] = sr2[sr1.eq(sr2).shift(-1, fill_value=True)].groupby(level=0).apply(list) print(df) # Output: 0 [102...
python|pandas
1
4,592
70,396,644
VCF file is missing mandatory header line ("#CHROM...")
<p>I am getting an error when I am going to read a VCF file using <strong>scikit-allel</strong> library inside a docker image and os ubuntu 18.04. It shows that</p> <p>raise RuntimeError('VCF file is missing mandatory header line (&quot;#CHROM...&quot;)') RuntimeError: VCF file is missing mandatory header line (&quot;#...
<p>You need to add a line like this in the first:</p> <p><code>#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT NA00001 NA00002 NA00003 </code></p> <p>but it's not static for all of the files, you have to make a <code>Header</code> like above for your file. (I suggest try this header first and if it's got error t...
pandas|numpy|scikit-learn|python-3.6|vcftools
0
4,593
51,496,017
Pandas >0.20 indexing with labels and position for a writing operation
<p>Since ix operator is deprecated since 0.20 version, how should I update this line?</p> <pre><code>df_final.ix[int(len(df_final)/2):, 'type'] = 1 </code></pre> <p>I tried this:</p> <pre><code>df_final['type'][int(len(df_final)/2):] </code></pre> <p>and works well for reading operations (not the most efficient bec...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_loc.html" rel="nofollow noreferrer"><code>Index.get_loc</code></a> for position of column <code>type</code>:</p> <pre><code>df_final = pd.DataFrame({ 'A': ['a','a','a','a','b','b','b'], 'type': list(range(7)) }) print (df_fi...
python|pandas
0
4,594
51,215,569
Optimizing shuffle buffer size in tensorflow dataset api
<p>I'm trying to use the <code>dataset</code> api to load data and find that I'm spending a majority of the time loading data into the shuffle buffer. How might I optimize this pipeline in order to minimize the amount of time spent populating the shuffle buffer.</p> <pre><code>(tf.data.Dataset.list_files(path) .shu...
<p>Since I have at most thousands of images, my solution to this problem was to have a separate tfrecord file per image. That way individual images could be shuffled without having to load them into memory first. This drastically reduced the buffering that needed to occur.</p>
python|tensorflow|tensorflow-datasets
2
4,595
51,402,943
Tensorflow Saver restores all variables no matter which ones I specified
<p>I'm trying to save and restore a subset of variables from Tensorflow graph, so that everything I don't need is discarded and their weights don't take memory. The common advice to pass list or dict of desired variables to <code>tf.train.Saver</code> doesn't work: the saver restores all the variables no matter what. <...
<p>This is what you want to do. Please examine the code carefully.</p> <h3>To save the selected variables</h3> <pre><code>import tensorflow as tf tf.reset_default_graph() # ============================================================================= # to save # =====================================================...
python|tensorflow
1
4,596
51,753,964
How to simultaneously sort columns in pandas dataframe
<p>Suppose that I want to sort a data frame in Pandas and my data frame looks like this</p> <pre><code> First Name Last Name Street Address Type 0 Joe Smith 123 Main St. Property Address 1 Gregory Stanton 124 Main St. X Old Property Address 2 Phill Allen ...
<p>You can sort by multiple columns. Just put both columns in the list.</p> <pre><code>duplicates = duplicates.sort_values(['Last Name', 'Address Type'], ascending = True) </code></pre>
python|pandas|sorting|for-loop|columnsorting
0
4,597
51,874,054
Python data frame manipulation
<p>maybe my question is too simple and sorry for this :</p> <p>I have the following sample data frame (My actual data frame has many rows and columns):</p> <pre><code>Months =("JAN","FEB","MAR","APR","MAY","JUN") df = pd.DataFrame(np.random.randn(2, 6), columns=Months).round(1) </code></pre> <p><code>df</code></p>...
<p>Dont use loops, because slow, if exist vectorized solution:</p> <pre><code>df1 = df.sub(df.shift(3, axis=1)).iloc[:, 3:] print (df1) APR MAY JUN 0 -0.6 -0.4 -0.9 1 0.0 0.3 -1.7 </code></pre> <p><strong>Details</strong>:</p> <p>First <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Data...
python|pandas
1
4,598
36,195,904
Combine two rows with the same class using Pandas
<p>Here is my question. </p> <pre><code> ## data for example Name type Value1 Value2 Value3 Value4 A unemp 1.733275e+09 2.067889e+09 3.279421e+09 3.223396e+09 B unemp 1.413758e+09 2.004171e+09 2.383106e+09 2.540857e+09 C unemp 1.2...
<p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow"><code>merge</code></a> the result with a column-subset of the original DataFrame:</p> <pre><code>&gt;&gt;&gt; pd.merge( f_test.groupby('Name').sum().reset_index(), f_test[['Name', 'type']].drop...
python|pandas
2
4,599
37,533,921
Google Appengine application written in Java with access to Python+Numpy+Scipy?
<p>I have a rather big appengine application completely written in Java. I would need to obtain results from functions completely written in python (if possible 3.x) with numpy and similar packages. </p> <p>What is the best way to do it?</p>
<p>I'm thinking in two options.</p> <ol> <li>You can write an app-engine's python module (now called <a href="https://cloud.google.com/appengine/docs/java/an-overview-of-app-engine#services_the_building_blocks_of_app_engine" rel="nofollow">services</a>) using default or <a href="https://cloud.google.com/appengine/docs...
java|python|google-app-engine|numpy|scipy
1