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
357,600
30,960,734
Compute difference between rows in pandas dataframe
<p>I'd like to compute the difference between two categories in a dataframe. For example, in the following case, I want to compute the differences between male and female on each job. However, there are some jobs done by only male or female. What is an efficient way to do it? Thanks.</p> <pre><code>import pandas as pd...
<p>You could do a pivot such that the male and female pay for the same job are on the same row. Then you can visually compare, or run other row-based code.</p> <pre><code>import pandas as pd df = pd.DataFrame({'job': ['a', 'a', 'b', 'b', 'c'], 'gender':['M', 'F', 'M', 'F', 'M'], 'income':[300, 200, 450, 400, 350]}) ...
python|pandas
2
357,601
30,915,228
Zero out portion of multidim numpy array
<p>I have an numpy array with dimensions (200, 200, 3). It is an RGB image. </p> <p>I also have the (xmin,ymin,xmax,ymax) coordinates of a region of this image that I would like to set to zero. This region should be zero in all three channels.</p> <p>I can of course solve this with a loop, but that would be wasteful....
<p>Use array slicing. If <code>xmin</code>, <code>xmax</code>, <code>ymin</code> and <code>ymax</code> are the indices of area of the array you want to set to zero, then:</p> <pre><code>a[xmin:xmax,ymin:ymax,:] = 0. </code></pre>
python-2.7|image-processing|numpy
1
357,602
30,969,221
Calculate days before next third Friday in a month for a Dataframe
<p>I have a time series in pandas Dataframe which looks like following:</p> <pre><code>time A B 2012-06-11 09:25:00.005001 2572.4 2.589 2012-06-11 09:30:00.005004 2573.2 2.592 2012-06-11 09:31:00.005000 2572.6 2.592 2012-06-11 09:32:00.004996 2572.2 2....
<p>You could use the <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.apply.html" rel="nofollow"><code>Series.apply</code></a> function together with the <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html" rel="nofollow"><code>WeekOfMonth</code> offset class</a> and its rollfo...
python|pandas|dataframe
1
357,603
30,857,626
Calculating distances between unique Python array regions?
<p>I have a raster with a set of unique ID patches/regions which I've converted into a two-dimensional Python numpy array. I would like to <strong>calculate pairwise Euclidean distances between all regions</strong> to obtain the minimum distance separating the nearest edges of each raster patch. As the array was origin...
<p>Distances between labeled regions of an image can be calculated with the following code,</p> <pre><code>import itertools from scipy.spatial.distance import cdist # making sure that IDs are integer example_array = np.asarray(example_array, dtype=np.int) # we assume that IDs start from 1, so we have n-1 unique IDs ...
python|arrays|numpy|scipy|distance
2
357,604
30,964,093
Big data visualization for multiple sampled data points from a large log
<p>I have a log file which I need to plot in python with different data points as a multi line plot with a line for each unique point , the problem is that in some samples some points would be missing and new points would be added in another, as shown is an example with each line denoting a sample of n points where n i...
<p>Getting the data into pandas:</p> <pre><code>import pandas as pd df = pd.DataFrame(columns = ['timestamp','name','value']) with open(logfilepath) as f: for line in f.readlines(): timestamp = line.split(',')[0] #the data part of each line can be evaluated directly as a Python list data = eval(li...
python|pandas|plot|statistics|scikit-learn
1
357,605
30,861,956
Python 2.7 Anaconda Pandas error(Ubuntu 14.04)
<p>I'm doing a data science course on udemy using python 2.7, running Anaconda. My OS is Ubuntu 14.04.</p> <p>I'm getting the following error running with the pandas module:</p> <p><code>Traceback (most recent call last): File "/home/flyveren/PycharmProjects/Udemy/15_DataFrames.py", line 13, in &lt;module&gt; n...
<p>So, the solution was essentially to create a virtual environment and install the needed packages independently. Some issues with dependencies on my system, I believe. </p>
python|python-2.7|ubuntu|pandas
1
357,606
67,189,378
How to convert to API response with multiple levels to dataframe in python
<p>I have response from API call as shown below</p> <pre><code>(data = json.loads(response.text) {'items': [{'start': '2021-03-21T00:00:00.000', 'end': '2021-03-31T00:00:00.000', 'location': {'code': None, 'position': {'lat': 47.464699, 'lon': 8.54917}, 'country_code': None}, 'source': 'geoeditor', ...
<p>You can try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html" rel="nofollow noreferrer"><code>json_normalize</code></a> in loop with append for list of <code>DataFrame</code>s and then join them by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas...
python|json|python-3.x|pandas|dataframe
2
357,607
67,514,983
pandas special chars converted to weird chars when saving
<p>I have a series of texts:</p> <pre><code>s = [&quot;t1&quot; , &quot;t1&quot;, &quot;it wasn’t that simple&quot;] </code></pre> <p>When saving as csv:</p> <pre><code>s.to_csv(&quot;s.csv&quot;) </code></pre> <p>And then open it in excel, the char <code>'</code> changed to the following:</p> <pre><code>&quot;it wasn‚...
<p>Use <code>encoding='utf-16'</code></p> <p><strong>Ex:</strong></p> <pre><code>s = [&quot;t1&quot; , &quot;t1&quot;, &quot;it wasn’t that simple&quot;] s = pd.Series(s) s.to_csv(filename, encoding='utf-16', index=False) </code></pre>
pandas|macos|dataframe|csv|export-to-csv
0
357,608
67,556,393
appying a function to dataframe's index
<p>I need to make a function that receives a number <code>X</code> and then divides two specific columns in the <code>X</code> row. Then I need to make a whole column (using my function and apply) that shows the quotient of the two columns. How can I apply a function to a DataFrame index and make it a column ? Here's m...
<p>If I understand your question correctly, you want to make a <code>ratio</code> column based on two other columns, you can simply do this and it will create a new column without the need to iterate over all rows:</p> <pre><code>df2['ratio'] = df2['Sepal.Length'] / df2['Sepal.Width'] </code></pre> <p>And if you still ...
python|pandas|dataframe
1
357,609
67,531,452
How to use 're.serach' in pandas-dataframe for including"[" or "]"
<pre><code>import pandas as pd import re df = pd.DataFrame([['a[]'],['a[] foo'],['a[] foo \n bar']],columns = ['a']) txt = 'a[] foo \n bar' def Function(x): if re.search(x, txt): return 'Match' else: return 'Nomatch' df['match'] = df['a'].apply(Function) </code></pre> <p>df Table is below</p...
<p>You must escape the special characters:</p> <pre><code>import pandas as pd import re df = pd.DataFrame([['a\[]'],['a\[] foo'],['a\[] foo \n bar']],columns = ['a']) txt = 'a[] foo \n bar' def Function(x): if re.search(x, txt): return 'Match' else: return 'Nomatch' df['match'] = df['a'].app...
pandas|python-re
0
357,610
67,266,104
Using tensors as indexes in a network
<p>My network has multiple inputs where one of those inputs is an index that is used in the network to index into other tensors.</p> <p>I am having issues using the tensor as an index.</p> <pre><code>class MemoryLayer(tf.keras.layers.Layer): def __init__(self, memory_size, k, **kwargs): super().__init__(kwargs) ...
<p>By default, input to layers are <code>tf.float32</code>. However, to index a tensor, you need integers. You can either cast the inputs of your layer to integers, or you can specify that the input of that layer should be of the integer type.</p> <h3>With casting</h3> <pre><code>cluster = tf.cast(input[1], dtype=tf.in...
tensorflow|machine-learning|keras
1
357,611
67,235,367
Creating a dataframe from an excel file
<p>I have made a data frame from an excel file using python:</p> <pre><code> df = pd.read_excel(excel_file_path_from_db, engine='openpyxl', sheet_name='Sheet1', skiprows=1) </code></pre> <p>What i am now trying to do is to set a new dataframe as the last 12 columns of my the sheet 1 in the excel file.</p> <p>I know th...
<p>Rather than relying explicitly on <code>openpyxl</code>, you can select the last 12 columns directly in <code>pandas</code> using <code>iloc</code> on the dataframe you've already loaded:</p> <pre><code>new_df = df.iloc[:, -12:] </code></pre> <p>The <code>:</code> says &quot;take all rows&quot; and the <code>-12:</c...
python|pandas|openpyxl
0
357,612
67,267,383
Update PostgresSQL column with computed data from the same table
<p>I need to update values in a PostgreSQL table based on information from the same table.</p> <p>For example the table look like this</p> <p><strong>Before Update</strong>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>index</th> <th>shop_id</th> <th>tire_type</th> <th>count</th> </tr> <...
<p>You can use window functions:</p> <pre><code>select t.*, count(*) over (partition by tire_type, shop_id) from t; </code></pre> <p>If you need to update the value, then you can use aggregation in an <code>update</code> statement:</p> <pre><code>update t set count = tt.cnt from (select tire_type, shop_i...
python|sql|pandas|postgresql
1
357,613
67,537,494
How does slice notation work in the context of this matplotlib plot?
<p>Please could someone help me understand this notation I found in a matplotlib plot? I believe that it is slice notation but can't get my head around it.</p> <pre><code>plt.plot(self.input_indices, inputs[n, :, plot_col_index], label='Inputs', marker='.', zorder=-10) </code></pre> <p>Specifically I don't understand <...
<p>It looks like <code>inputs</code> is a 3D tensor, which you can visualise as 3 individual 2D arrays.</p> <p>The slice <code>inputs[n, :, plot_col_index] </code> first selects <code>n</code>, one of the 3 2D arrays. Then from that 2D array, by indexing <code>[:, col_index]</code> you are selecting all the rows for a ...
python|tensorflow|matplotlib|syntax
0
357,614
67,419,889
Pandas df manipulation - breaking data into 2 columns
<p>I have an example data frame with 2 indicating columns (example below, product and version - where version numbers can only be 1 or 2) and a 3rd column with actual data.</p> <pre><code>product version data a 1 8000 a 2 1000 b 1 4...
<p>You can pivot the table using pandas function <code>.pivot</code></p> <pre><code>&gt;&gt;&gt; result = df.pivot(index='product', columns='version', values='data').reset_index() &gt;&gt;&gt; result version product 1 2 0 a 8000 1000 1 b 4000 2000 2 c 9000 1000 3 ...
python|pandas|dataframe
5
357,615
67,209,301
Making Pandas dataframe to display aggregate values based on date
<p>Hello a Python newbie here.</p> <p>I have a dataframe that shows the product and how much they sold on each date <a href="https://i.stack.imgur.com/eyVYM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eyVYM.png" alt="enter image description here" /></a></p> <p>I need to change this dataframe to s...
<p>If <code>product</code> is column use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.cumsum.html" rel="nofollow ...
python|pandas|dataframe|datetime|crosstab
1
357,616
67,324,586
Descending Sort of repeated pattern of Pandas DF
<pre class="lang-py prettyprint-override"><code>I have this data frame import pandas as pd ques=pd.DataFrame(data) data={'sort_code': {0: 1, 1: 2, 2: 3, 3: 1, 4: 2, 5: 3}, 'text': {0: 'MCQ option3', 1: 'MCQ option 2', 2: 'MCQ option1 ', 3: 'MCQ option3', 4: 'MCQ option2', 5: 'MCQ option1'}} ques=pd.DataFrame(data) </...
<p>WE can try <code>cumcount</code></p> <pre><code>ques['key'] = ques.groupby('sort_code').cumcount() ques = ques.sort_values(['key','sort_code'],ascending=[True,False]).drop('key',1) ques sort_code text 2 3 MCQ option1 1 2 MCQ option 2 0 1 MCQ option3 5 3 MCQ opti...
python|pandas
1
357,617
67,401,788
Why I can't add a figure to separate sheet in Excel Workbook?
<p>I need to save data and corresponding figure in separate excel sheets.</p> <pre><code>writer = pd.ExcelWriter('Fiber Forecast.xlsx', engine = 'xlsxwriter') fiber_forecast_future.to_excel(writer,sheet_name='Future', index=True) worksheet = writer.sheets['New Sheet'] worksheet.insert_image('C2','India Fiber Price.png'...
<p>You can use</p> <pre><code>writer.book.add_worksheet(&quot;New Sheet&quot;) </code></pre> <p>instead. There is more information regarding this method and the workbook object here: <a href="https://xlsxwriter.readthedocs.io/workbook.html" rel="nofollow noreferrer">https://xlsxwriter.readthedocs.io/workbook.html</a><...
python|pandas|pandas.excelwriter
1
357,618
67,509,301
Exploding rows with identical nested keys in pandas
<p>I have data in a column that looks like this in a pandas dataframe:</p> <pre><code>'Column name': [{'Name': Dan Smith, 'Attribute1': 4, 'Attribute2': 10, 'Attribute3': 6}, {'Name': Bob Smith, 'Attribute1': 4, 'Attribute2': 10, 'Attribute3': 6}], [{'Name': Shelly Smith, 'Attribute1': 4, 'Attribute2'...
<pre><code>def tolist(x): if isinstance(x, dict): return [x] else: return x df['Column name'] = df['Column name'].apply(literal_eval).apply(tolist) df = df.explode('Column name') </code></pre> <hr /> <h2>Explanation</h2> <p>To use explode, every row must be a sequence type (<code>list</code> fo...
python|pandas|dataframe|parsing|explode
1
357,619
67,259,231
Use multiple aliases for a module depending on whether another module exists or not
<p>I am currently doing some work where <code>cupy</code> is involved. Overall, it makes my code run faster, since it is running everything on my GPU. Now, if a user does not have <code>cupy</code> installed, but he does have <code>numpy</code>, I would like to make the necessary adjustment. Currently, I am importing t...
<p>To have another alias for a numpy import, why not just assign it?</p> <pre><code>import numpy as np cp = np # then just use it normally, x = cp.arange(10) </code></pre>
python-3.x|numpy|python-import
2
357,620
67,497,954
Generate combinations with specified order with itertools.combinations
<p>I used <code>itertools.combinations</code> to generate combinations for a dataframe's index. I'd like the combinations in specified order --&gt; <code>(High - Mid - Low)</code></p> <p>Example</p> <pre><code>from itertools import combinations d = {'levels':['High', 'High', 'Mid', 'Low', 'Low', 'Low', 'Mid'], 'convert...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFrame.reindex</code></a> first, but first and second values in list are swapped:</p> <pre><code>order = ['High','Mid','Low'] a = list(combinations(df_.reindex(order).index, 2)) pr...
pandas|itertools
1
357,621
67,207,734
Concat two Pandas DataFrame column with different length of index
<p>How do I add a merge columns of Pandas dataframe to another dataframe while the new columns of data has less rows? Specifically I need to new column of data to be filled with NaN at the first few rows in the merged DataFrame instead of the last few rows. Please refer to the picture. Thanks.</p> <p><a href="https://i...
<p>Use:</p> <pre><code>df1 = pd.DataFrame({ 'A':list('abcdef'), 'B':[4,5,4,5,5,4], }) df2 = pd.DataFrame({ 'SMA':list('rty') }) df3 = df1.join(df2.set_index(df1.index[-len(df2):])) </code></pre> <p>Or:</p> <pre><code>df3 = pd.concat([df1, df2.set_index(df1.index[-len(df2):])], axis=1) print (d...
python|pandas
1
357,622
67,262,452
Why does Keras sequential model return multiple predictions per test sample?
<p>I don't work with Keras or TF very often so just trying to understand how it works. For example, this is a bit confusing: we generate some points of sine plot and trying to predict the remainder:</p> <pre><code>import numpy as np from tensorflow.keras import layers from tensorflow.keras.models import Sequential a =...
<p>It's because, in your model, you have <strong>20</strong> relu activated features in your last layer. That gave <strong>20</strong> features of a single instance in the inference time. All you need to do (as you requested) is to use a layer with <strong>1</strong> unit, place it as the last layer, and probably no ac...
python|tensorflow|keras
2
357,623
67,389,953
Mapping dictionary with multiple key values to data frame
<p>I have a dictionary which has multiple key values.</p> <pre class="lang-py prettyprint-override"><code>d = {(0, 0, 'Shift 2 (2000 FT)'): 0.0, (0, 0, 'Shift 1 (0800 FT)'): 0.0, (0, 1, 'Shift 2 (2000 FT)'): 0.0, (0, 1, 'Shift 1 (0800 FT)'): 0.0, (0, 2, 'Shift 2 (2000 FT)'): 0.0, (0, 2, 'Shift 1 (0800 FT)'): 0.0} </cod...
<p>You can read in the dict then turn the Index into a MultiIndex and reshape.</p> <pre><code>import pandas as pd df = pd.DataFrame.from_dict(d, orient='index') df.index = pd.MultiIndex.from_tuples(df.index) df = (df[0].unstack(-1) .rename_axis(index=['Week', 'Day']) .reset_index()) </code></pre...
python|pandas
5
357,624
67,244,416
How to increment duplicate time axis
<p>I have a <code>pd.DataFrame</code> which has duplicate time in its index.</p> <p>Example:</p> <pre><code>from datetime import datetime import pandas as pd time_index = [ datetime(2017, 1, 1, 0, 4, 1, 80000), datetime(2017, 1, 1, 0, 4, 1, 80000), datetime(2017, 1, 1, 0, 4, 1, 80000), datetime(2017, 1, 1, 0,...
<p>You can groupby and cumcount and then add milliseconds:</p> <pre><code>t = df_i_have.groupby(level=0).cumcount() df_i_have.index += pd.to_timedelta(t,unit='ms') </code></pre> <hr /> <pre><code>print(df_i_have) A 2017-01-01 00:04:01.080 1 2017-01-01 00:04:01.081 2 2017-01-01 00:04:01.082 ...
python|pandas|dataframe|running-count
3
357,625
67,248,513
Pandas groupby using an equation in agg function
<p>Hello I am trying to get this dataframe to groupby employment but then I want to find the infection rate for each employment type.</p> <p>The infection rate should be easy where it is the infected people / total people but I cannot figure out that part in a single line.</p> <p>I have this</p> <pre><code>infect_df = ...
<p>suppose your dataframe has two columns like this</p> <pre><code>data = StringIO(''' A,0 B,0 A,0 B,1 A,1 A,1 C,1 B,1 C,0 C,0 A,0 B,1 ''') df = pd.read_csv(data,names=['employment','infected']) </code></pre> <p>you can count the rate of infected == 1 by</p> <pre><code>df.groupby(['employment'])['infected'].apply(lambd...
python|pandas
1
357,626
67,541,525
Filtering tensors element in Tensorflow
<p>What's the equivalent operation in Tensorflow for this? For example, I have a <code>x = np.array([-12,4,6,8,100])</code>. I want to do as simple as this: <code>x = x[x&gt;5]</code>, but I can't find any TF operation for this. Thanks!</p>
<p>In <code>TF</code> you can do something like this to achieve similar results.</p> <pre><code>import numpy as np import tensorflow as tf x = np.array([-12,4,6,8,100]) y = tf.gather(x, tf.where(x &gt; 5)) y.numpy().reshape(-1) array([ 6, 8, 100]) </code></pre> <p><strong>Details</strong></p> <p>The <a href="http...
python|tensorflow
1
357,627
67,262,565
Creating a model which weights are the sum of weights of 2 different neural networks
<p>I am doing an experiment of transfer learning. I trained 2 CNNs that have exactly the same structure, one for MNIST and one for SVHN. I obtained the parameters (weights and bias) of the 2 models. Now, I want to combine (sum, or other operations) these weights. A thing like this:</p> <pre><code>modelMNIST.parameters...
<p>You need to update the <code>.data</code> attribute of the parameter. <code>Parameter</code> is not FloatTensor and hence the error.</p> <p>Since the two networks are identical you can use the below code to update the weights.</p> <pre><code>for param1, param2 in zip(modelMNIST.parameters(), modelSVHN.parameters()):...
neural-network|pytorch|conv-neural-network|mnist|transfer-learning
1
357,628
67,304,376
TensorFlow.js train using multiple inputs one output
<p>I´m currently trying to write a system that can classify specific number sequence to action. Trying to build it with tensorflow.js has worked fine so far, but now i´m running into some issues.</p> <p>I´m trying train the model using an input like</p> <pre><code>[ [0,1,2,3,4,5,6,7,8,9], [0,1,2,3,4,5,6,7,8,9],...
<p>Found out that if I just flat down the array of data, it should work out aswell</p>
javascript|tensorflow|machine-learning|artificial-intelligence|tensorflow.js
0
357,629
67,262,143
how to encoding several column (but not all column) in dataframe python using pandas
<p>I want to build a naive bayes model using two dataframes (test dataframe, train dataframe)</p> <p>The dataframe contains 13 columns, but I just want to encode the dataframe from <code>str</code> to <code>int</code> value in just 5-6 columns. How can I do that with one code so that 6 columns can directly be encoded, ...
<p>You can loop through the columns and fit_transform</p> <pre><code>cols = ['col1', 'col2', 'col3', 'col4', 'col5', 'col6'] for col in cols: le = LabelEncoder() df[col] = le.fit_transform(df[col].astype('str')) df </code></pre> <p>Ideally you want to use same trasnfomer for both train and test dataset<br...
python|pandas|dataframe|scikit-learn|sklearn-pandas
1
357,630
67,502,828
Tensorflow Serving Compiling Failure For CPU AVX AVX2
<p>I use the method in the tfx official document to compile the tfx devel in docker file. The OS is MacOS, intel CPU.</p> <p>here is the docker build code for it</p> <pre><code>#!/bin/bash USER=$1 TAG=$2 TF_SERVING_VERSION_GIT_BRANCH=&quot;2.4.1&quot; git clone --branch=&quot;${TF_SERVING_VERSION_GIT_BRANCH}&quot; h...
<p>These instruction sets are not available on all machines, especially with older processors.</p> <p>If you'd like to apply generally recommended optimizations, including utilizing platform-specific instruction sets for your processor, you can add <em><strong>--config=nativeopt</strong></em> to Bazel build commands wh...
tensorflow-serving|tfx
0
357,631
67,343,682
Summing observations from column in pandas
<p>Suppose I have a big Dataframe DS_df w/ column names year, dealamount and CCS among others. For every year, from 1985 until 2020, I need a separate panda series i.e. sum_2019. I need to sum the dealamount, if CCS does occur multiple times (if it occurs only once, it should just be added to the series) and the year m...
<p>Do you want this?</p> <pre><code>df.dealamount = df.dealamount.str.replace(',','').astype(int) new_df = df.groupby(['year','CCS']).agg({'dealamount': sum}) </code></pre> <p>Output -</p> <pre><code> dealamount year CCS 2009 Albania_Turkey 258328000 2013 Albania...
python|pandas|dataframe|multiple-columns|series
1
357,632
67,421,904
Use PyTorch to speed up linear least squares optimization with bounds?
<p>I'm using <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.lsq_linear.html" rel="nofollow noreferrer">scipy.optimize.lsq_linear</a> to run some linear least squares optimizations and all is well, but a little slow. My A matrix is typically about 100 x 10,000 in size and sparse (sparsity ...
<p>Not easily, no.</p> <p>I'd try to profile lsq_linear on your problem to see if it's pure python overhead (which can probably be trimmed some) or linear algebra. In the latter case, I'd start with vendoring the lsq_linear code and swapping relevant linear algebra routines. YMMV though.</p>
optimization|scipy|pytorch|torch|scipy-optimize
1
357,633
67,293,988
Python NumPy array of objects where each object is a different size NumPy array
<p>I want to create a numpy array of objects, where objects are the other numpy arrays have different or exact dimensions. The purpose is to have advanced indexing while working with an array of arrays where nested arrays might have different sizes.</p> <p>If all the nested arrays have different dimensions then all is ...
<pre><code>import numpy as np a = np.array([np.array([0, 1, 2], dtype=int), np.array([3, 4], dtype=int)], dtype=object) print(a[0].dtype, a[1].dtype) </code></pre>
python|arrays|numpy
0
357,634
67,554,605
What does an LSTM do when it gets 2 or more numeric features?
<p>Based on the spec that an LSTM works by receiving this input (samples, time-steps, features)</p> <p>What does it do by default (no custom code) when it gets , let's say, 2 numeric features? Does it considers the two numbers as combination of the sequence?<br /> Tries to arithmetically combining them?</p>
<p>We can start by understanding the dimensions of the LSTM input -</p> <p><strong>sample</strong> - one training example for a LSTM is a sequence - number of samples is essentially number of sequences <br> <strong>time-steps</strong> - each sequence is represented by a fixed number of time steps(padding is done accord...
tensorflow|machine-learning|keras|lstm
1
357,635
67,293,426
trouble when running tansorflow project
<p>I was trying to run main.py of <a href="https://github.com/LucaAngioloni/ProteinSecondaryStructure-CNN" rel="nofollow noreferrer">this project</a> on my m1 macbook and got this output:</p> <pre><code>Collecting Dataset... Time elapsed getting Dataset: 25.09 s Using CullPDB Filtered dataset Hyper Parameters Learn...
<p>The problem is I did not use proper version of TensorFlow. I finally got an answer by following <a href="https://www.cyberlight.xyz/passage/tensorflow-apple-m1" rel="nofollow noreferrer">this page</a>, which tells me to install apple version Tensorflow and use conda environment, it solves the problem.</p>
python|tensorflow|apple-m1
0
357,636
67,261,726
Instance mismatch while plotting
<p>I am trying to plot using seaborn</p> <pre><code> data=pd.read_csv('MyCSV') data['Date']= pd.to_datetime(data['Date']) start_date ='2016-04-18' end_date ='2016-04-21' fig, ax = plt.subplots(figsize=(16,9)) ax.plot(data.loc[start_date:end_date,'Date'].index, data.loc[start_date:end_date,&quot;Price&quot;], lab...
<pre><code>data['Date']= pd.to_datetime(data['Date']) data = data.set_index('Date') start_date =datetime.strptime('2016-04-18', '%Y-%m-%d') end_date =datetime.strptime('2016-04-21', '%Y-%m-%d') fig, ax = plt.subplots(figsize=(16,9)) ax.plot(data.loc[start_date:end_date].index, data.loc[start_date:end_date, &quot;Pri...
python|pandas|matplotlib
-1
357,637
67,299,935
Can we pass a column instead of a variable to access nth item of a list?
<p>My data contains multiple columns, on which I have done a group by and given row numbers based on the group by. I'm using python here The column 'Text' is a list of strings. The entire 'Text' was initially 1 string, which is split into a list with ; as the delimiter. Rownumber are integers. What I want to do here is...
<p>As i see, Delimeter should be &quot;,&quot; not &quot;;&quot;. Since &quot;Text&quot; is a single string then first remove square brackets uisng <code>replace()</code> then split it by ',' and then extract the element using index in &quot;Row_num&quot;</p> <pre><code>df =pd.DataFrame({&quot;Row_num&quot;: [0,1,2,3,0...
python|pandas|list|pointers
0
357,638
67,269,564
Pandas How to replace values based on Conditions for Several Values
<p>I have a Dataframe with several column and below is first 3 columns in that dataframe:</p> <pre><code>data_df = pd.DataFrame({'id':['era','bb','cs','jd','ek','gtf','okg','huf','mji','loj','djjf','wloe','rfm','cok'], 'doc':[1050 ,580,170,8, 7, 220, 45155,305,458,201,48,78,256,358], ...
<p>Create a dict for mapping -</p> <pre><code>dict1 = dict(zip(range(1, 11), range(10,0,-1))) data_df['dif'] = data_df['dif'].map(dict1) </code></pre>
python|pandas|dataframe
2
357,639
67,315,911
How to create function to pass lat long in api call for get weather data
<p>I try to get the data from pyOWM package using city name but in some cases because of city typo error not getting data &amp; it breaks the process.</p> <p>I want to get the weather data using lat-long but don't know how to set function for it.</p> <pre><code>Df1: ----- User City State ...
<p>Catch the error if a city is not found, parse the lat/lon from the dataframe. Use that lat/lon to create a bounding box and use <code>weather_at_places_in_bbox</code> to get a list of observations in that area.</p> <pre><code>import time from tqdm.notebook import tqdm import pyowm from pyowm.utils import config from...
python|pandas|dataframe|openweathermap
0
357,640
67,525,474
how to retrieve feature in xml file that is embedded in a tag using beautiful soup
<p>i am trying to parse through a series of XML files and use beautiful soup to get certain values that are embedded in tags using beautiful soup using these functions:</p> <pre><code>case_feature_keys = ['year', 'offenceCategory', 'offenceSubcategory'] person_feature_keys = ['gender', 'age', 'occupation', 'given'] out...
<p>To get occupation and person type you can use this example:</p> <pre class="lang-py prettyprint-override"><code>from bs4 import BeautifulSoup html_data = &quot;&quot;&quot; &lt;persName id=&quot;t18100221-1-person52&quot;&gt; GEORGE ROSS &lt;interp inst=&quot;...
xml|pandas|beautifulsoup|getattr
0
357,641
67,387,883
Neural segmentation network gives different output based on test batch size
<p>I have implemented and trained a neural segmentation model on (224, 224) images. However, during testing, the model returns slightly different results based on the shape of the test batch.</p> <p>The following images are results obtained during testing on my pre-trained model.</p> <p><a href="https://i.stack.imgur.c...
<p>This behavior was coming from the batch normalization layers that were in my model. I use <code>training=true</code> during my calls to the model.</p> <p>As a result, batch normalization normalizes the batches based on their norm, and that norm changes based on batch size.</p> <p>Therefore, this is normal behavior!<...
python|tensorflow|output|vision
0
357,642
67,552,960
Attribute error applying a transform across a list of columns in a pandas dataframe
<p>Hi I have a dataframe and a list of columns I want to perform a loop over:</p> <pre><code>#list of the 4 columns i want to perform function on columnnames= ['a','b','c','d'] #Function for col in columnnames: df[f&quot;{col}_new&quot;] = df.groupby('Name')[col].transform(lambda x: x.rolling(20).apply(ewma).shif...
<p>Turns out my error was that I had some columns with the same name!</p>
python|pandas
0
357,643
67,498,662
How to get that result without for loop (python)
<p>I have a list of tuples(<code>rule</code>) and a pandas dataframe(<code>proof_path</code>) .</p> <p><strong>Inputs</strong></p> <p>rule :</p> <pre><code> [('#1', 'X', 'Y'), ('#2', 'X', 'Z'), ('#3', 'Z', 'Y')] </code></pre> <p>proof_path :</p> <pre><code> p1 X Y p2 Z p3 0...
<p>This is as close as you can get to avoiding the loops. But this code uses implicit loops: list comprehension and <code>zip</code>.</p> <pre><code>proof_path[[r[0].replace('#','p') for r in rule]]\ .apply(lambda x: list(zip([r[0] for r in rule], x))).values.tolist() #[[('#1', 'nationality'), ('#1', 'placeO...
python|pandas|dataframe
0
357,644
67,185,741
Why resizing dataset images before CNN since it stretches them?
<p>I initialize my dataset using the following function (simplified):</p> <pre><code>WIDTH = ... HEIGHT = ... def load_data(dataset_path): images = [] labels = [] for all_images: image = cv2.imread(pimage_path) image = cv2.resize(image, (WIDTH, HEIGHT)) #??? labels.add(corresponding...
<p>You aren't limited to stretching the image, perhaps you could either crop the image or add a bufferzone with a consistent color, although if you can afford to crop the images that'd be more convenient but still you can just fill the rest of the space with a fixed color, the model would not care less.</p>
tensorflow|keras|conv-neural-network
0
357,645
67,241,148
How to create a new column that is a calculation of other columns
<p>I would like to create a column that is the sum of columns A + B / C * 100, in order to get a column that is a percentage, yet when I run the code:</p> <pre><code># Create new column that displays the % of the population that has a long-term health issue. for i, row in health_issues.iterrows(): health_issues.lo...
<p>You don't have to iterate through rows to do this:</p> <pre class="lang-py prettyprint-override"><code>health_issues[&quot;PC_LTHP&quot;] = (health_issues[&quot;LTHP_littl&quot;] + row[&quot;LTHP_lot&quot;]) / row[&quot;residents&quot;] * 100 </code></pre>
python|geopandas
0
357,646
67,462,923
Eliminating csv file rows if specific string is not present
<p>I am trying to compile a database of medical school interview questions and scraped a lot of data onto a csv file. Column 0 contains the school name, and Column 1 contains the entry.</p> <p>Some of the entries to the CSV are comments about medical schools rather than self-reported interview questions. Is there any w...
<p>You could use <code>contains</code> to return only the rows that contain the specified words.</p> <pre class="lang-py prettyprint-override"><code>modified_df = modified_df[modified_df['Question'].str.contains('\?|Explain|Define|Tell me')] </code></pre>
python|pandas|csv
1
357,647
67,517,315
How to retrieve rows from DataFrame based on their first appearance
<p>I generated a dataset that shows the similarity between users in a graph based on their neighbors. Based on a dataset that shows the trust relations between users in a social network, I'm aiming to build a new dataset that contains the most similar users to my &quot;trustor&quot; user (e.g. the 3 most similar ones) ...
<p>If user is being your column truster you can use a <code>groupby</code> and get the first 3 appearances.</p> <pre><code>arr = {'truster':{0:1642,1:1642,2:1642,3:1642,4:1642,5:2,6:2,7:2,8:2,9:2},'trustee':{0:1570,1:524,2:1039,3:1545,4:1360,5:1388,6:658,7:1078,8:1336,9:1157},'value':{0:'0,08',1:'0,0533333',2:'0,04',3:...
python|pandas|dataframe|jupyter-notebook
0
357,648
67,286,838
pdf mcq to pandas dataframe?
<p>Is there any way to convert text like this from a pdf into a pandas dataframe? text:</p> <ol> <li>The theory of comparative cost advantage theory was Introduced by----- a) Alfred Marshall b) David Ricardo c) Taussig d) Heberler</li> <li>The Ricardo’s comparative cost theory is based on which of the following assumpt...
<ul> <li>Row by row is delimited by newline</li> <li>column by column by a regular expression split</li> </ul> <pre><code>rawtxt = &quot;&quot;&quot;The theory of comparative cost advantage theory was Introduced by----- a) Alfred Marshall b) David Ricardo c) Taussig d) Heberler The Ricardo’s comparative cost theory is ...
python|pandas|dataframe
2
357,649
67,402,139
I can see the table but cannot extract using BS4
<p>I have been trying to extract a table from <a href="https://www.zacks.com/stock/research/MMM/earnings-announcements" rel="nofollow noreferrer">https://www.zacks.com/stock/research/MMM/earnings-announcements</a>. I did my best I couldn't extract the table. There is a similar post <a href="https://stackoverflow.com/qu...
<p>The data is embedded inside the page in Javascript. You can use this example how to load it:</p> <pre class="lang-py prettyprint-override"><code>import re import json import requests from bs4 import BeautifulSoup headers = { &quot;User-Agent&quot;: &quot;Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:88.0) Gecko/2...
python|pandas|beautifulsoup
2
357,650
67,475,044
python panda help from text file to custom format
<p>I am looking for help in python where I can convert the following into columns.</p> <p>Data in text file:</p> <pre class="lang-none prettyprint-override"><code>---- [ Job Information : 2926 ] ---- Name : Run26 User : abc Account : xyz Partition : q_24hrs Nodes ...
<p>You can use this example how to parse the text file using <code>re</code> module:</p> <pre class="lang-py prettyprint-override"><code>import re with open(&quot;your_file.txt&quot;, &quot;r&quot;) as f_in: data = f_in.read() job_ids = re.findall(r&quot;Job Information : (\d+)&quot;, data) names = re.findall(r&q...
python|pandas|text|utc
3
357,651
67,259,338
How to locate and count the number of words in a column
<p>So want to count the occurrences of contaminants but some cases has more than one contaminants so when I use the value_counts it counts them as one. For example &quot;Gasoline, Diesel = 8&quot; How would I count the them as separate without doing it manually.</p> <p>And would it be possible to create a function tha...
<p>Assuming the contaminants are always separated by commas in your data, you can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>pandas.Series.str.split()</code></a> to get them into lists. Then you can get them into distinct rows with <a href="ht...
python|pandas|matplotlib
1
357,652
67,576,304
Copying 3 columns values from DF2 into DF1 based on matching rows in a different column
<p>I have two dataset with columns names as below.</p> <p>DF1:</p> <p>Record Type , FNAME , MNAME , LNAME , ID , etc.</p> <p>DF2:</p> <p>ID, PREFIX , FNAME , MNAME , LNAME , etc.</p> <p>If ID field in DF2 found a match in DF1, then copy matching values in 3 columns(FNAME , MNAME , LNAME) from DF2 to DF1.</p> <p>thank ...
<p>You can do that using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">pd.merge()</a>:</p> <pre><code>new_df = pd.merge(DF1, DF2[['ID', 'FNAME' , 'MNAME' , 'LNAME']], on = 'ID', how = 'left') </code></pre>
python|pandas|jupyter-notebook
0
357,653
67,255,646
What to do with negative value in a dataFrame
<p>Suupose i have a dataframe with different columns. And some column contains the negative value, like amount column containing some negative number which is not possible because the amount can't be negative so how to handle that negative number in the columns.</p>
<p>I assume you want to set all negative values in your column &quot;amount&quot; to 0 (or some other value). You can apply a lambda function to your column to replace negative values by 0, and keep positive values unchanged:</p> <pre><code>df['amount'] = df['amount'].apply(lambda x: 0 if x &lt; 0 else x) </code></pre>
python|pandas|machine-learning|data-science
1
357,654
67,333,524
ValueError: could not convert string to float: 'what' (Sklearn), How to use the labelencoder?
<p>I have two training sets input and output set</p> <pre><code>X = df['First Word'] y = df['Answers'] </code></pre> <p>When I tried:</p> <pre><code>from sklearn.tree import DecisionTreeClassifier model = DecisionTreeClassifier() model.fit(X,y) predictions = model.predict(['how']) </code></pre> <p>I got the error:</p...
<p>All ML models need input in the form of numbers so you need to encode the input data either label encoder or one-hot encoding as per your need.</p> <p>you can encode your dataframe using the below code</p> <pre><code> from sklearn import preprocessing le = preprocessing.LabelEncoder() X = le.fit_transform(X) </cod...
python|pandas|scikit-learn|decision-tree|sklearn-pandas
2
357,655
67,483,263
Reproduce simple pandas plot
<p>I have a situation with my data. I like the behaviour of .plot() over a data frame. But sometimes it doesn't work, because the frequency of the time index is not an integer.</p> <p>But reproducing the plot in matplotlib is OK. Just ugly.</p> <p>The part that bother me the most is the settings of the x axis. The tick...
<p>You can use some matplotlib date utilities:</p> <ul> <li><a href="https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.FigureBase.autofmt_xdate" rel="nofollow noreferrer"><strong><code>Figure.autofmt_xdate()</code></strong></a> to unrotate and center the date labels</li> <li><a href="https://matplotli...
python|pandas|matplotlib
1
357,656
67,507,482
How to find the survival ratio in each gender in each PClass?
<p>I was able to find ratio on the basis of pclass or sex but i am not able to find the ratio of survival of each gender in each Pclass</p> <pre><code>df1[['Sex', 'Survived']].groupby(['Sex'], as_index=False).mean().sort_values(by='Survived', ascending=False) df1[['Pclass', 'Survived']].groupby(['Pclass'], as_index=Fa...
<p>You can use pandas pivot_table for this:</p> <pre class="lang-py prettyprint-override"><code>df.pivot_table('Survived', index='Sex', columns='Pclass') </code></pre> <p>If you want to see the counts instead, you can use:</p> <pre class="lang-py prettyprint-override"><code>df.pivot_table('Survived', index='Sex', colum...
python|pandas
0
357,657
67,423,189
Can't import tensorflow 2.x with spyder (any version): Tensorflow_core.estimator problem
<p>I have different conda environments for different tensorflow and pytorch versions. They all work without issues when calling python on the terminal.</p> <p>I can also use them with Spyder, either with an individual Spyder installation in each conda environment, or using the &quot;modular approach&quot; described her...
<p>SOLVED: There was a version mismatch between tensorflow-gpu and tensorflow-estimator</p> <p>When installing tensorflow-gpu=2.x , for some reason, a mismatching tensorflow-estimator version was being downloaded. For tensorflow-gpu=2.1, tensorflow-estimator=2.4 was being downloaded. Downgrading this to tensorflow-esti...
python|tensorflow|anaconda|spyder
2
357,658
67,523,914
How to detect a tie in a numpy array when using argmax
<p>If I have an array like below, how can I detect that there is a tie of at least 3 or more values when using <code>np.argmax()</code>?</p> <pre><code>examp = np.array([[4, 0, 1, 4, 4], [5, 5, 1, 5, 5], [1, 2, 2, 4, 1], [4, 6, 1, 2, 4], [1, 4, 3, ...
<p>One way for finding the n-th maximum is <a href="https://numpy.org/doc/stable/reference/generated/numpy.partition.html" rel="nofollow noreferrer"><code>np.partition</code></a> (or <a href="https://numpy.org/doc/stable/reference/generated/numpy.argpartition.html" rel="nofollow noreferrer"><code>np.argpartition</code>...
python|numpy|sorting|argmax
1
357,659
67,492,303
How to store information from a loop function?
<p>Could you please help me store the 'name' and 'gender' into a new pandas.DataFrame from the following loop's outcome?</p> <p>Here's my loop function:</p> <pre><code>def predict_gender_combined(name_input): d_2=GenderDetector() g_2=d_2.get_gender(name_input) g_3= Genderize().get([name_input]) print(f'{g_2}\n...
<p>This is what dictionary comprehensions are for.</p> <pre class="lang-py prettyprint-override"><code># This := syntax is an &quot;assignment expression&quot; that is available in Python 3.8+ result = {&quot;name&quot;: predicted[0][&quot;name&quot;], &quot;gender&quot;: predicted[0][&quot;gender&quot;] for predicted ...
python|pandas|dataframe|loops
0
357,660
34,479,872
Why is Tensorflow 100x slower than convnetjs in this simple NN example?
<p>I've been working with convnetjs for 1 year and now I want to move on to more powerful and fast libraries. I thought Tensorflow would be orders of magnitude faster than a JS library, so I wrote a simple neural network for both libraries and did some tests. It is a 3-5-5-1 neural network, trained on one single exampl...
<p>There could be many reasons why:</p> <ul> <li><p>The data input is so small that most of the time is spent in just conversion between python and the C++ core, while the JS is just one language. </p></li> <li><p>You are using only one core in Tensorflow while the JS could potentially leverage more than one</p></li> ...
javascript|performance|optimization|neural-network|tensorflow
15
357,661
34,868,837
Shortest way to iterate over 3 pandas dataframe columns
<p>What is the shortest way to do the following?</p> <pre><code>i = 0 for Year, Month, Day in zip(test_data['Year'], test_data['Month'], test_data['Day']): ans = dt.date(Year, Month, Day) test_data.loc[i,'Day1'] = ans.strftime("%A") i += 1 </code></pre>
<p>You can <code>apply</code> over the rows, which avoids having to <code>zip</code> and keep track of which row you're up to:</p> <pre><code>df = pd.DataFrame({'Year': [2015, 2016], 'Month': [12, 1], 'Day': [28, 3]}) df Out[3]: Day Month Year 0 28 12 2015 1 3 1 2016 df['Day1'] = df.apply( ...
python|pandas|dataframe
2
357,662
34,646,262
How to call a function with parameters as matrix?
<p>I am trying to call <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.multivariate_normal.html" rel="nofollow"><code>scipy.stats.multivariate_normal</code></a> with four different parameters for mu and sigma. And then for each generated probability density function I need to call that p...
<p>Based on your description of what you are trying to compute, you don't need <code>multivariate_normal</code>. You are calling the PDF method with a set of scalar values for a distribution with a scalar mu and sigma. So you can use the <code>pdf()</code> method of <a href="http://docs.scipy.org/doc/scipy/reference/...
python|numpy|scipy|probability|probability-density
1
357,663
60,188,642
Pandas Apply Function To Groupby Sub DataFrames
<p>Is there a way to apply function to sub-dataframes and not just to columns or rows of the main data? </p> <p>For example, if I have<br> <code>df = pd.DataFrame({'ID': [1,2,2,3,3], 'Valid':[0, 0, 0, 1, 1], 'Value':[10, 5, 10, 0, 10]})</code> </p> <p><a href="https://i.stack.imgur.com/PTz81.png" rel="nofollow ...
<p>I think you need convert column to boolean if necessary and also add column name for filter column for <code>sum</code>:</p> <pre><code>def calc(subDf): output = subDf.loc[subDf['Valid'].astype(bool), 'Value'].sum() return output df = df.groupby('ID').apply(calc).reset_index(name='Value') print (df) I...
pandas|pandas-groupby|apply
0
357,664
60,016,616
Why does Series.min(skipna=True) throws an error caused by na value?
<p>I work with timestamps (having mixed DST values). Tried in Pandas 1.0.0:</p> <pre><code>s = pd.Series( [pd.Timestamp('2020-02-01 11:35:44+01'), np.nan, # same result with pd.Timestamp('nat') pd.Timestamp('2019-04-13 12:10:20+02')]) </code></pre> <p>Asking for min() or max() fails:</p> <pre><code>s.min...
<p>I think problem here is pandas working with Series with different timezones like objects, so <code>max</code> and <code>min</code> here failed.</p> <pre><code>s = pd.Series( [pd.Timestamp('2020-02-01 11:35:44+01'), np.nan, # same result with pd.Timestamp('nat') pd.Timestamp('2019-04-13 12:10:20+02')]) p...
pandas|timestamp|aggregate
3
357,665
60,303,481
Python | Pandas DataFrame: Advanced Slicing/GroupBy
<p>I have been struggling with a pandas quest for a while now and maybe someone can shed some new light into this problem :)</p> <p>Consider de following pandas dataframe, <strong>df</strong>:</p> <pre><code>Year Month Task TaskID TaskClass TaskClassID SomeValue 2019 11 A 1 X 10 6.58 2019 ...
<p>Why not use drop duplicates?</p> <p>More here: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html</a></p> <p>Assume a dataframe like so:...
python|pandas|dataframe|object-slicing
0
357,666
60,166,450
How to slice a pandas dataframe with multiple timeframes?
<p>I have two variables "start" and "end", which consist of multiple timeframes and I want to use them to slice a dataframe. How can I achieve this with python?</p> <p>(I only found solutions with two timeframes or solutions where the timeframes had to be put in as strings and not as variable)</p> <p>variable start:<...
<p>you can use loc to index your data <code>df30m.loc[(df30m.Timestamp &lt;= d0) &amp; (df30m.Timestamp &gt;= d1)] </code></p> <p>You can set the index to the Timestamp column and then index as well</p> <p><code>df.set_index('Timestamp', inplace=True) df[d1:d0]</code></p>
python|pandas|dataframe
0
357,667
59,973,334
How to plot boxplot or violin plot with Seaborn using a multi-dimensional numpy array as input?
<p>I've got a 2D numpy array with dimensions (500, 10) that I'd like to plot as a Seaborn violinplot or boxplot where there is a box for each of the 10 columns. What is the cleanest way to pass this to Seaborn without doing a bunch of tedious manipulation to get it into a Pandas Dataframe first? I'm confident that I ca...
<p>Your solution is correct, <code>boxplot()</code> expects a list of vectors, so you have to somehow transform your matrix into that.</p> <p>You can simplify the way you write your code however: <code>sns.boxplot(data=[d for d in the_array.T])</code></p> <p>full code:</p> <pre><code># create a dummy matrix 500x10 t...
python|numpy|seaborn
4
357,668
60,077,515
TFF: TensorSliceDataset
<p>In the Federated learning context, I try to simulate a code with TFF so the type of my dataset is 'DatasetV1Adapter' (tf.data.Dataset) instead the dataset of emnist in the tutorial <a href="https://www.tensorflow.org/federated/tutorials/federated_learning_for_image_classification" rel="nofollow noreferrer">ImageClas...
<p>It sounds like you are running with Tensorflow 1.X--<code>DatasetV1Adapter</code> is simply a wrapper for TF 2.x <code>Dataset</code> in the <code>tf.compat.v1.data.Dataset</code> API.</p> <p>Try running <code>tf.compat.v1.enable_v2_behavior()</code> immediately after <code>import tensorflow as tf</code>, or simply...
dataset|tensorflow2.0|tensorflow-federated
0
357,669
60,024,754
Apply formula based on condition in certain column
<p>I have a DataFrame that looks like that:</p> <pre><code>df1=pd.DataFrame([[1,0.10],[1,0.15],[3,0.16],[3,0.11],[3,0.12],[1,0.14],[2,0.17], [2,0.19],[1,0.10]], columns=["a","b"]) </code></pre> <p>result is:</p> <pre><code> a b 0 1 0.10 1 1 0.15 2 3 0.16 3 3 0.11 4 3 0.12 5...
<p>Use custom function with consecutive groups by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.shift.html" rel="nofollow noreferrer"><code>Series.shift</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumsum.html" rel="nofollow noreferr...
python|pandas
1
357,670
60,311,307
How does one reset the dataloader in pytorch?
<p>I was trying to reset the dataloader manually but was unable. I tried everything here <a href="https://discuss.pytorch.org/t/how-could-i-reset-dataloader-or-count-data-batch-with-iter-instead-of-epoch/22902/4" rel="noreferrer">https://discuss.pytorch.org/t/how-could-i-reset-dataloader-or-count-data-batch-with-iter-i...
<p>To <em>reset</em> a DataLoader then just <em>enumerate</em> the loader again. Each call to <code>enumerate(loader)</code> starts from the beginning.</p> <p>To not <em>break</em> transformers that use random values, then <em>reset</em> the random seed each time the DataLoader is initialized.</p> <pre class="lang-py...
pytorch
10
357,671
60,091,241
Import Tensorflow packages failed
<p>I'm trying to run the below code in a jupyter notebook and I get the following errors. I checked I have the latest version of tensorflow and all its packages with pip list and they seem to be there. I also enabled jupyter extensions. </p> <p>Not sure what causes this and any help would be much appreciated. Thanks</...
<p>try installing the compatible cuda and cudnn for the TensorFlow that you have installed. check this link: <a href="https://www.tensorflow.org/install/source_windows" rel="nofollow noreferrer">https://www.tensorflow.org/install/source_windows</a></p>
tensorflow|installation
0
357,672
60,107,680
Choropleth map from Shape file in Holoviews
<p>I have a shape file with a column named geometry containing MULTIPOLYGONs.</p> <pre><code>postcode name geometry 0 2003.0 A MULTIPOLYGON Z (((1048559.000 7841160.000 0.00... 1 1438.0 B MULTIPOLYGON Z (((-29156.720 6885495.170 0.000... </code></pre> <p>While it is straight forward to draw a map in m...
<p>If you install <a href="https://hvplot.holoviz.org/" rel="nofollow noreferrer">hvPlot</a>, you should be able to plot shape columns directly from GeoPandas using HoloViews, as described at <a href="https://hvplot.holoviz.org/user_guide/Geographic_Data.html" rel="nofollow noreferrer">https://hvplot.holoviz.org/user_g...
geopandas|holoviews
2
357,673
60,073,362
Is it possible to include scipy.stat function in pandas aggregate function?
<pre><code>import pandas as pd import numpy as np import scipy.stats as st num = np.random.randint(20,100, size=10) df = pd.DataFrame(num, columns=["Weight"]) df.agg([np.sum, np.std, st.sem]) </code></pre> <blockquote> <p>i am getting following error.</p> <p>RuntimeWarning: Degrees of freedom &lt;= 0 for sli...
<p>I believe you want to do as below</p> <p>df.agg(['sum','std','sem'])</p>
python|pandas|numpy|scipy
0
357,674
59,960,825
1 dimenstional convolution error in using tensorflow
<p>I am studying 1d convolution using tensorflow. </p> <p>Code:</p> <pre><code>import numpy as np import tensorflow as tf \#####raw data, input length is 24, and feature_len is 6 batch = np.ceil((np.random.rand(24, 6)*10))-5 \#####filter for convoltion, filter width is 3, filter input dim is 6, output dim is ...
<p>It's expecting your input tensor to be "Rank 4" meaning it has 4 dimensions, but you've technically given a 2d array.</p> <p>Technically, Conv1d uses Conv2d as you noticed, according to this API documentation: <a href="https://www.tensorflow.org/api_docs/python/tf/nn/conv1d" rel="nofollow noreferrer">conv1d api doc...
tensorflow|convolution
1
357,675
59,922,405
xarray.DataArray.diff vs. pandas.DataFrame.diff output is different
<p>I have been trying to migrate some of my higher dimensional data from pandas to xarray with the deprecation of pandas panels. I would like to use the diff function in xarray but it's parameters and output are not the same as pandas.</p> <p>The pandas version: "DataFrame.diff(self, periods=1, axis=0)" allows me to ...
<p><code>n</code> in <code>da.diff</code> is 'The number of times values are differenced'.</p> <p>So if <code>n = 2</code>, it's second-order difference in xarray. while <code>df.diff</code> is always first order.</p>
python|pandas|python-xarray
0
357,676
60,094,332
How to use the same layer/model twice in one model in Keras?
<p>I am trying to make a combined model which passes two different images through a sub-model (an encoder) one at a time and then contacenates the two results and feeds them to a final sub-model, which makes a decision based on these two latent representations. I want to use the same encoder for both images to reduce t...
<p>Let's assume you have a model built using the following function:</p> <pre><code>def make_encoder(h, w, c): inp = Input((h, w, c)) x = SomeLayer()(inp) x = SomeLayer()(x) .... out = OutLayer()(x) return Model(inputs=[inp], outputs=[out]) </code></pre> <p>Now, to make a combined model, you n...
python|tensorflow|keras|deep-learning
4
357,677
60,080,285
Pandas Dataframe Styles are not working with Jupyter Notebook
<p>I have a dataframe which is constructed using a list and other dataframe that i read from excel file. What I want to do is, I just have to apply the background color to first row of a dataframe which I would export in to an excel. The below code doing the job correclty as expected.(There is issue with the data)</p> ...
<p>You need to export to excel the styled dataframe and not the unstyled dataframe and so you either need to chain your styling and sending to Excel together, similar to shown in the documentation <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html?highlight=styler#Export-to-Excel" rel="nofollow...
python|r|excel|pandas|dataframe
4
357,678
60,314,939
pandas group by day or week or month
<p>I'm a pandas beginner.</p> <p>I have the following data:</p> <pre><code>a = [ {"content": '1', "time": '2020-01-01'}, {"content": '4', "time": '2020-01-01'}, {"content": '2', "time": '2020-01-02'}, {"content": '3', "time": '2020-02-01'}, {"content": '4', "time": '2020-02-02'}, {"content": '5', "tim...
<p>First convert list of dictionaries to <code>DataFrame</code>, then get <code>YY-MM</code> format of datetimes:</p> <pre><code>df = pd.DataFrame(a) g = pd.to_datetime(df['time']).dt.strftime('%Y-%m') </code></pre> <p>And in dict comprehension create dictionary of lists:</p> <pre><code>d1 = {k: v.to_dict('r') for k...
python-3.x|pandas
3
357,679
60,098,161
Matching ID's to a varied set of names
<p>I have a dataset containing a list of company names, and a respective ID for them. There are multiple instances of each company, with some appearing differently. There is at least one instance of each company name that has an ID, but not all of them due to inconsistencies in the spellings. All of the companies are g...
<p>Here's one way to do it using <code>pandas</code>:</p> <pre><code>import pandas as pd import numpy as np import re from collections import OrderedDict # a function that splits a string into text and number def my_splitter(s): return filter(None, re.split(r'(\d+)', s)) #reading the data as a dataframe from the f...
python|pandas|matching|fuzzy
1
357,680
60,116,193
Python: How to compare columns with text entries and with each other
<p>I'm a total python noob just started with scripting. I have a dataframe of three samples and for each sample I have a list of Peptide sequences, like:</p> <pre><code>d = {'Sample 1': ['QSFLEVSYYPMAGYIKEDSIM', 'MLPIQTRIAS', 'AAVACTVLRCLAAEQQTSRSVDEAY'], 'Sample 2': ['QSFLEVSYYPTEIRQMGM', 'AEAARLVLAARIKGDAM', 'AAVACT...
<p>Did you try this?</p> <pre><code>from matplotlib_venn import venn3 venn3([set(v) for v in d.values()], set_labels=d.keys()) </code></pre>
python|pandas|numpy|venn-diagram
0
357,681
60,157,191
Finding and deleting sub-strings in dataframe column Python
<p>I would like to find all the rows in a column that contains a unique ID as a string which starts with digits and symbols. After they have been identified, I would like to delete the first 9 characters for those unique rows, only. So far I have: </p> <pre><code>if '.20_P' in df['ID']: df['ID']= df['ID']str.slic...
<p>You could also use a regular expression to find your substring. </p> <p>The regular expression here works as follows: Find a substring <code>()</code> consisting of multiple occurrences (<code>+</code>) of digits (<code>\d</code>) or (<code>[]</code>) non whitespace characters (<code>\w</code>). This might (<code>*...
python|pandas|dataframe|substring|slice
1
357,682
59,971,324
Pytorch dataloader for sentences
<p>I have collected a small dataset for binary text classification and my goal is to train a model with the method proposed by <a href="https://arxiv.org/pdf/1408.5882.pdf" rel="nofollow noreferrer">Convolutional Neural Networks for Sentence Classification</a></p> <p>I started my implementation by using the <code>torc...
<p>As you correctly suspected, this is mostly a problem of different tensor shapes. Luckily, PyTorch offers you several solutions of varying simplicity to achieve what you desire (batch sizes >= 1 for text samples):</p> <ul> <li>The highest-level solution is probably <a href="https://github.com/pytorch/text" rel="nofo...
python|deep-learning|nlp|pytorch|text-classification
1
357,683
59,972,179
Can I use pandas to create a biased sample?
<p>My code uses a column called booking status that is 1 for yes and 0 for no (there are multiple other columns that information will be pulled from dependant on the booking status) - there are lots more no than yes so I would like to take a sample with all the yes and the same amount of no.</p> <p>When I use </p> <p...
<p>If our entire dataset looks like this:</p> <pre><code>print(df) c1 c2 0 1 1 1 0 2 2 0 3 3 0 4 4 0 5 5 0 6 6 0 7 7 1 8 8 0 9 9 0 10 </code></pre> <p>We may decide to sample from it using the <a ...
pandas|sample
1
357,684
60,197,206
Select rows with specific values in columns and include rows with NaN in pandas dataframe
<p>I have a <code>DataFrame</code> <code>df</code> that looks something like this:</p> <pre><code>df a b c 0 0.557894 -0.196294 -0.020490 1 1.138774 -0.699224 NaN 2 NaN 2.384483 0.554292 3 -0.069319 NaN 1.162941 4 1.040089 -0.271777 NaN 5 -0.337374 NaN -0.771888 6...
<p>You should use the | (or) operator.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'a': [0.557894,1.138774,np.nan,-0.069319,1.040089,-0.337374,-1.813278,np.nan,0.737413,-2.345448], 'b': [-0.196294,-0.699224,2.384483,np.nan,-0.271777,np.nan,-1.564666,np.nan,np.nan,2.4436...
python|pandas
1
357,685
60,163,466
extracting date using regex from the cell in pandas dataframe
<p>I have a following dataframe</p> <pre><code>column 1 Description Extracted Data date January 15,2020 is important day </code></pre> <p>I want to get following result</p> <pre><code>column 1 Description Extracted Data date January 15,2020 is import...
<p>Use multi dot <code>.*</code> and digits.</p> <pre><code>import pandas as pd df = pd.DataFrame({'column 1': ['date'], 'Description': ['January 15,2020 is important day']}) df['Extracted Data'] = df['Description'].str.extract(r'(.*,\d{4})') </code></pre> <p><b>Output:</b></p> <pre><code> column 1 ...
python|regex|pandas
1
357,686
60,140,988
Numpy Vectorization: add row above to current row on ndarray
<p>I would like to add the values in the above row to the row below using vectorization. For example, if I had the ndarray,</p> <pre><code>[[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]] </code></pre> <p>Then after one iteration through this method, it would result in</p> <pre><code>[[0, 0, 0, 0], [1, 1...
<p>You can use indexing directly:</p> <pre><code>b = np.zeros_like(a) b[0] = a[0] b[1:] = a[1:] + a[:-1] &gt;&gt;&gt; b array([[0, 0, 0, 0], [1, 1, 1, 1], [3, 3, 3, 3], [5, 5, 5, 5]]) </code></pre> <p>An alternative:</p> <pre><code>b = a.copy() b[1:] += a[:-1] </code></pre> <p>Or:</p> <pre><co...
numpy|vectorization|numpy-ndarray
2
357,687
60,328,035
Pandas Dataframe Error 'StringArray requires a sequence of strings or pandas.NA'
<p>I've been reading from an excel sheet for the past month with no problems using Pandas.</p> <p>Recently though I made a change to my date formats (which have now been switched back to their original formats mm/dd/yyyy).</p> <p>All of sudden Pandas throws an error now when I try to read my .xlsm</p> <p>Below is th...
<p>According to the documentation <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html" rel="noreferrer">Pandas doc</a>:</p> <p>The new <code>df.astype()</code> method can work both with <code>str</code> and <code>"string"</code></p> <p>The difference is: with the <code>"string"</code> it will t...
python|arrays|string|pandas|dataframe
15
357,688
60,158,700
Apply function over a Pandas DataFrame
<p>I am working on Pandas and I am struggling to create a new column with information from an API over the rows of my dataframe.</p> <p>The "location" column I want to iterate is a Series of dictionaries like this:</p> <pre><code>{'type': 'Point', 'coordinates': [-0.1394759, 51.5170385]} </code></pre> <p>My function...
<p>Your function is expecting a data frame, but you are passing a value to it. I think your function should be:</p> <pre><code>def starbucks(val): API_key = os.getenv('API_KEY') lat = list(val)[1]["coordinates"][1] lon = list(val)[1]["coordinates"][0] base_url = "https://maps.googleapis.com/maps/api/pl...
python|pandas|dataframe|apply
0
357,689
59,917,425
Get the least sales in pandas dataframe
<p>Datarame</p> <pre><code>Fresh Milk Grocery Channel 20 50 80 Hotel 40 10 30 Restaurant 100 90 20 Cafe 120 150 80 Hotel 450 910 30 Restaurant 10 90 20 Cafe 205 50 80 Hotel 403 10 30 Restaurant 10 90 20 Cafe </code></pre> <...
<p>You first need to combine all the items into one column:</p> <pre><code>df['sum_of_items'] = df.sum(axis=1) </code></pre> <p>Then you can use a simple groupby:</p> <pre><code>df.groupby('Channel')['sum_of_items'].sum() </code></pre> <p>The result is:</p> <pre><code>Channel Cafe 450 Hotel 835 ...
python-3.x|pandas
3
357,690
60,053,710
SQLAlchemy and filtering with numpy datatypes
<p>The SQLAlchemy .filter() function doesn't seem to be able to work with numpy datatypes. If I use a np.int32 in the filter argument the desired result is not achieved. Instead, I need to cast my np.int32 to int to make a query work as expected.</p> <p>In the following example I query values from the database, do som...
<p>I spent a few hours running into the same underlying issue from a different angle (the <code>where()</code> clause). Although the above question was eventually edited with a mention of the <code>TypeDecorator</code> class as a solution, I wanted to implement that solution here (using sqlalchemy's Core API instead o...
python|numpy|sqlalchemy
1
357,691
60,129,742
Pandas Loc with condition statement
<p>I am using loc on pandas data frame which has an index on indicator columns. In the above picture, you can see that after applying loc with the condition I am getting a boolean list. Is there any way I can get the values instead of boolean. Thanks</p> <p><a href="https://i.stack.imgur.com/a7Sic.jpg" rel="nofollow n...
<p>Try this:</p> <pre><code>data.loc['Meal, Inexpensive Restaurant', data.loc['Meal, Inexpensive Restaurant']&gt;400] </code></pre> <p>the first <code>'Meal, Inexpensive Restaurant'</code> means that you want this row, and the <code>data.loc['Meal, Inexpensive Restaurant']&gt;400</code> is your boolean vector</p>
python|pandas|dataframe
0
357,692
59,951,397
ValueError: This sheet is too large! Your sheet size is: 1220054, 3 Max sheet size is: 1048576, 16384
<p>I am trying to convert a <code>.txt</code> file to an excel file and I encountered the below error:</p> <pre><code>Traceback (most recent call last): File &quot;C:/Users/haroo501/PycharmProjects/MyLiveRobo/convert_txt_csv.py&quot;, line 13, in &lt;module&gt; dataf_umts_txt_df.to_excel('umtsrelation_mnm.xlsx', ...
<p>You can try converting it to csv instead of excel which when opened in excel gives almost the same use except that you cannot use formulas or multiple sheets. The second option is dividing the data frame into two parts or as many you feel comfortable and then push all of them to sql</p>
python|excel|pandas
6
357,693
59,921,242
Accessing the last character of a specific element in python
<p>I am currently building something like a flash card programme to help me learn both french and python at the same time using pandas and numpy.</p> <p>I have a csv with 3 columns which i convert to a dataframe (verbs). My code randomly selects a row (selection) and gives a word in french, then the user has to input ...
<p>In Python (and in general), strings are treated as arrays. So to access the last entry in a string, you only need to type [-1]. [0]. In addition, to access a single character, you just need a single digit i.e. [-1], and not a list which is what you've tried to do [-1:].</p> <p>E.g. </p> <p>given:</p> <p><code>x =...
python-3.x|string|pandas|dataframe|slice
0
357,694
60,153,802
Group together matched pairs across multiple columns Python
<p>Thank you for reading.</p> <p>I have a dataframe which looks like this:</p> <pre><code>Col_A Col_B Col_C Col_D Col_E 1 2 null null null 1 null 3 null null null 2 3 null null null 2 null 4 null 1 null null null 5 </code></pre> ...
<p>As @YOBEN_S and @QuangHoang suggests, you can use networkx library and <a href="https://en.wikipedia.org/wiki/Component_(graph_theory)" rel="nofollow noreferrer">Graph Theory connnected components</a> like this.</p> <p>Given df, </p> <pre><code>df = pd.DataFrame({'Col_A': {0: 1.0, 1: 1.0, 2: np.nan, 3: np.nan, 4: ...
python|pandas|dataframe|cluster-computing
2
357,695
60,137,572
Issues installing PyTorch 1.4 - "No matching distribution found for torch===1.4.0"
<p>Used the install guide on <code>pytorch.org</code> on how to install it and the command I'm using is</p> <pre><code>pip install torch===1.4.0 torchvision===0.5.0 -f https://download.pytorch.org/whl/torch_stable.html </code></pre> <p>But it's coming up with this error;</p> <blockquote> <p>ERROR: Could not find a vers...
<p>Looks like this issue is related to virtual environment. Did you try recommended installation line in another/new one virtual environment? If it doesn't help the possible solution might be installing package using direct link to PyTorch and TorchVision builds for your system:</p> <pre class="lang-sh prettyprint-ove...
python|python-3.x|pip|installation|pytorch
29
357,696
60,108,214
Getting Error :-ValueError: format number 1 of "b'Feb 1978, 2, 1975 Total time of visit (in minutes):\n'" is not recognized
<p>I am trying to convert a df into datatime using formula below:</p> <pre><code>output_final_date['Date'] = pd.to_datetime(output_final_date[['Year','Month','Day']].astype(str),format='%Y%m%d%') </code></pre> <p>But I am getting the error:</p> <blockquote> <p>ValueError: format number 1 of "b'Feb 1978, 2, 1975 T...
<p>I think <code>.astype</code> and <code>format</code> should be removed and added <code>errors='coerce'</code> for convert problematic non datetimes values to missing values, <code>NaT</code>:</p> <pre><code>output_final_date['Date'] = pd.to_datetime(output_final_date[['Year','Month','Day']], errors='coerce') </code...
python-3.x|pandas|dataframe
0
357,697
59,907,296
How to use tf.nn.sampled_softmax_loss with Tensorflow Keras?
<p>I've been looking around a way to use sampled softmax <code>tf.nn.sampled_softmax_loss()</code> for one of my models. I couldn't find any post that could help me on how to implement it.</p> <p>If anyone has implemented it with Keras architecture, would you please let me know how to use it with keras?</p> <p>Right ...
<p>sampled_softmax_loss() computes and returns the sampled softmax training loss.</p> <p>This is a faster way to train a softmax classifier over a huge number of classes.</p> <p>This operation is for training only. It is generally an underestimate of the full softmax loss.</p> <p>A common use case is to use this met...
python|python-3.x|tensorflow|keras
1
357,698
59,995,003
Pandas how to split one column in two using separator
<p>I have a dataframe in which one column corresponds to credit card numbers in this form:</p> <p>123456******1234</p> <p>I want to create two new columns: 'First' and 'Last' using the sep "******"</p> <p>I have tried:</p> <pre><code>df[['First','Last']] = df['credit_card'].str.split("******",expand=True) </code></...
<p>The delimiter is being treated as a regular expression, and <code>*</code> has special meaning in regexp, so it needs to be escaped to match literally. You can write</p> <pre><code>df[['First','Last']] = df['credit_card'].str.split(r"\*{6}",expand=True) </code></pre> <p><code>{6}</code> means to repeat the pattern...
python|pandas|split
4
357,699
60,107,790
Python Numpy Get Green Mask even if pixel values aren't all 0 in other channel
<p>The code below basically gets the color green from an image:</p> <pre><code>green_mask = np.all(label==[0,255,0], axis=-1) </code></pre> <p>But how do I change that line so I can still get mask even if, say the first channel contains pixels greater than 0 BUT still less than 255?</p> <p>So, I want something like ...
<p>What I ended up doing was:</p> <pre><code>green_mask = (label[:,:,0]&lt;255) &amp; (label[:,:,1]==255) &amp; (label[:,:,0]&lt;255) </code></pre>
python|numpy
1