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
17,600
46,517,320
Tensorflow: what exactly does tf.gradients() return
<p>Quick question as I'm kind of confused here.</p> <p>Let's say we have a simple graph: </p> <pre><code>a = tf.Variable(tf.truncated_normal(shape=[200, 1], mean=0., stddev=.5)) b = tf.Variable(tf.truncated_normal(shape=[200, 100], mean=0., stddev=.5)) add = a+b add &lt;tf.Tensor 'add:0' shape=(200, 100) dtype=float...
<p>By default tf.gradients takes the gradient of the scalar you get by summing all elements of all tensors passed to tf.gradients as outputs.</p>
tensorflow|linear-algebra|derivative
1
17,601
46,224,511
unclear index error python
<p>This is my third thread in StackOverflow. I think I already learnt a LOT by reading threads here and clearing my doubts.</p> <p>I'm trying to transform an excel table, in my own python script. I've done so much, and now that I'm almost finishing the script, I'm getting an Err message that I can't really understand....
<p>Guess: <code>sense_factor = np.linspace(0.5, 2, 31)</code> has 31 elements - you ask for element 3652 and it naturally blows. <code>i</code> takes this value in final loop. Rewrite final loop as:</p> <pre><code> for k in range(len(datasource)) for m in range(12): datasource[k].pop...
python|numpy|indexing
0
17,602
46,223,725
implement an integration math equation using odeint in Python
<p>I am trying to solve the following equation in python using the scipy.odeint function.</p> <p><img src="https://i.stack.imgur.com/h4z17.png" alt="equation 1"></p> <p>Currently I am able to implement this form of the equation</p> <p><img src="https://i.stack.imgur.com/5cCOV.png" alt="equation 2"></p> <p>in python...
<p>The equation is a "coupled" ordinary differential equation (see "System of ODEs" on <a href="https://en.wikipedia.org/wiki/Ordinary_differential_equation" rel="nofollow noreferrer">Wikipedia</a>.</p> <p>The variable is a vector containing <code>y[0]</code>, <code>y[1]</code>, etc. To solve the ODE you must feed a v...
python|numpy|math|scipy|integration
1
17,603
58,488,983
PIL Image.open display image reversely rotated
<p>I'm working on predicting the number picture as below with MNIST dataset and <a href="https://www.kaggle.com/vincentman0403/pytorch-v0-3-1b-on-mnist-by-lenet/output" rel="nofollow noreferrer">LeNet Model</a> . Firstly, I show test images with <code>Image.open</code>, it displays test images in the way of reversely ...
<p><code>imshow</code> just sees an array of data. So specifying <code>origin='lower'</code> means you're telling <code>imshow</code> that the origin of your data is in the lower corner. However, image data has its origin in the upper corner so you can either remove <code>origin=</code> completely (the default is 'uppe...
python|python-imaging-library|pytorch|mnist
3
17,604
58,500,095
Keras Multilayer Perceptron train data show loss = nan
<p>I have data in data_2.csv like this.</p> <pre><code>a b c d e outcome 2 9 5 10175 3500 10000 1 3 4 23085 35000 34000 2 1 3 NaN 23283.33333 50000 .... </code></pre> <p>I try to train with MLP. Column outcome is target output. This is my code.</p> <pre><co...
<p>The prominent problem in your code is that you aren't cleaning your data. Neural Networks behave, in simple terms, by multiplying each node on each layer (that's a Dense layer). Then, imagine this: you have 32 nodes on the first layer, the largest positive number you have is about 35,000. If you multiply this 35,000...
python|tensorflow|machine-learning|keras
2
17,605
58,255,294
Pandas changing date to a shorter format
<p>G'day!</p> <p>In my limited time working with Python and Pandas one question comes up time and time again - what if my input data has date/time in a long format, how to change it to a shorter version?</p> <p>For example, the date in the input file would be:</p> <pre><code>10/10/2019 5:52:30 AM </code></pre> <p>I...
<p>Pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.floor.html" rel="nofollow noreferrer">floor</a> or <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.round.html" rel="nofollow noreferrer">round</a> functions can do the job:</p> <pre><code...
python|pandas|datetime
1
17,606
58,324,880
NN regression loss value not decreasing
<p>I'm training a NN with Pytorch to predict the expected price for the <a href="https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html" rel="nofollow noreferrer">Boston dataset</a>. The network looks like this:</p> <pre><code>from sklearn.datasets import load_boston from torch.utils.data.dataset import Datas...
<p>you are appending <code>lloss</code> once per epoch and that correct but you are appending with <code>loss</code> (using only last batch) where you should append with <code>avg_train_loss</code></p> <p>Try:</p> <pre><code>for epoch in range(EPOCHS): avg_train_loss = 0 for trainbatch in train_loader: ...
python|machine-learning|neural-network|pytorch|loss
2
17,607
69,136,446
python dataframe new column based on another column with value of conditional min of dataframe
<p>I have a dataframe called 'result' as follows:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>ddate</th> <th>sstart</th> <th>ttime</th> <th>H</th> <th>L</th> <th>C</th> <th>key</th> <th>usteps</th> <th>dsteps</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>20110427.0</td> <td>...
<p>I solved it.. it should be <code>result['dtime'] =result.apply(lambda row: result.groupby(&quot;ddate&quot;).get_group(row['ddate']).loc[(result.L &lt; row['dsteps']) , &quot;ttime&quot;].min() , axis=1)</code></p>
python|pandas|dataframe
0
17,608
68,876,431
Adding new column in pandas with an if condition using 1 = True and 0 = False
<pre><code>df = {'year': [2018, 2018, 2017, 2019], 'time': [12, 8, 10, 10], 'weekday': [4, 6, 5, 1]} df = pd.DataFrame(df) df if df['weekday'] &lt;5: df['weekend'] = df['weekday'].bool() else: df['weekend'] = df['weekday'].bool() </code></pre> <p>I want the output that looks like the image below <a href=...
<p>To answer the question, a numpy.where function will be precise</p> <pre><code># df['weekend'] = np.where(df['weekday']&gt;4, True, False) df['weekend'] = np.where(df['weekday']&gt;4, 1, 0) df.head() </code></pre>
python-3.x|pandas
1
17,609
44,503,190
Pandas: Reading TSV into DataFrame
<p>I'm using Python 2.7 and have a TSV formatted as follows (368 rows × 3 columns):</p> <pre><code>date dayOfWeek pageviews 2016 4 3920 ... </code></pre> <p>I have a Jupyter notebook saved in the same location as the TSV. I'm running this code:</p> <pre><code>import pandas as pd pd.read_table('q...
<p>How about:</p> <pre><code>pd.read_table('query_explorer.tsv',delim_whitespace=True,header=0) </code></pre>
python|pandas|csv|file-io
4
17,610
61,096,228
Loading keras model into tensorflow.js locally
<p>I want to load <code>keras</code> model which has been converted into <code>tensorflow.js</code> compatible format to perform inference. My code looks like this</p> <pre><code>import * as tf from '@tensorflow/tfjs'; import "regenerator-runtime/runtime.js"; import 'bootstrap/dist/css/bootstrap.css'; const model_pat...
<p>I had this problem too.</p> <p>Using <code>const model = await tf.loadLayersModel('directory/model.json');</code> generated the same error you had. I tried changing the import to find file <code>model2.json</code>, which didn't exist yet gave the same error (I notice there's an outstanding issue with TensorFlow.js t...
javascript|tensorflow|keras|tensorflow.js|tensorflowjs-converter
0
17,611
71,509,943
Create Tree Structure using Pandas
<p>I need to generate a new column based on the unique combinations in the data below</p> <pre><code>import pandas as pd df = pd.DataFrame({'ID': [1001, 1002, 1003, 1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1014], 'G': ['G1','G1','G1','G1', 'G2','G2','G2', 'G3','G3','G3', 'G4','G4','G4','G4'...
<p>The logic is not fully clear, but assuming you forgot the 2004 and you want to increment when there is a non-duplicate, you could do:</p> <pre><code>cols = ['G', 'F', 'SF'] # global duplicates df['ID2'] = (~df[cols].duplicated()).cumsum().add(2000) # consecutive duplicates df['ID3'] = df[cols].ne(df[cols].shift())....
pandas
2
17,612
69,957,765
pandas - datetime column subtraction datetime strptime
<p>I have a column <code>creation_date</code> in my pandas dataframe as type str that has the following format:</p> <pre><code>2020-02-06 11:35:17+00:00 </code></pre> <p>I am trying to create a new column in my dataframe titled <code>days_since_creation</code></p> <pre><code>from datetime import date today = date.toda...
<p>Just tested this out and works alright for me, apologies for the error from my comment.</p> <pre><code>df['days_since_creation'] = (pd.to_datetime(df['creation_date']).dt.date - pd.Timestamp.today().date()) </code></pre> <p>Result w just that one sample:</p> <pre><code> cr...
python|pandas
1
17,613
43,075,323
How to iterate over two dataframe columns and add values from a list based on the values in those two columns
<p>I have a dataframe with three columns like this:</p> <p>Subject{1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, ...} datetime{6/4/16 3:04:30, 6/5/16 6:02:15, ...} markers{}</p> <p>It is sorted by subject then by datetime, and the markers column is empty</p> <p>I also have a dictionary which maps subject numbers to lists of date...
<p>try this, you will have to customize the answer somewhat to meet your specific needs, but the logic is basically the same.</p> <pre><code>df = pd.DataFrame({'colA': [100,200],'colB': ['NaN','NaN']}) dict1 = {100: ['rat','cat','hat'], 200: ['hen','men','den']} df = pd.concat([df['colA'],df['colA'].map(dict1).apply(p...
python|pandas|dictionary|dataframe
0
17,614
43,249,439
Apply difference function on each adjacent row value pandas
<p>I have a df like below and want to see if timestamps are always increasing. Basically a diff in each row for timestamp column. Add diff in a third column.</p> <pre><code>A,B,Timestamp 5,58330831,1491375186654664218 5,58330832,1491375186654673017 5,58330833,1491375186654687270 5,58330834,1491375186654696695 5,583308...
<p>You can do it like this:</p> <pre><code>df['diff'] = (df['Timestamp'] - df['Timestamp'].shift(1))&gt;0 </code></pre> <p>First one will be <code>False</code> as it has no value to compare and returns <code>NaN</code>.</p>
python|pandas
1
17,615
72,446,940
Add suffixes to duplicate (column) cell values in Pandas depending on another column value (category)
<p>I have a structure like this:</p> <pre><code> Data_group Data Value Group_x A 12 Group_x A 13 Group_x B 3 Group_x C 3 Group_x C 32 Group_x C 23 Group_y A 8 Group_y A 7 Group_y B 13 Group_y C 12 Group_...
<p>You can use a single <code>groupby</code> with <strong>both Data_group/Data columns</strong>. Compute the <code>cumcount</code> as string (with brackets) and add only to groups that have more than one element (<code>transform('size').gt(1)</code>):</p> <pre><code>g = df.groupby(['Data_group', 'Data']) df.loc[g['Data...
python|python-3.x|pandas|dataframe
0
17,616
72,392,660
I got error trying to use albumentations on tensorflow data pipeline
<p>Im pretty new at deep learning and tensorflow, then when i try to use albumentations on tensorflow data pipeline, this error occurs (i use google colabs):</p> <pre><code>error: OpenCV(4.1.2) /io/opencv/modules/core/src/matrix.cpp:757: error: (-215:Assertion failed) dims &lt;= 2 &amp;&amp; step[0] &gt; 0 in function ...
<p>In the albumentations implementations with tensorflow docs it states that the dataset losses their shape after applying tf.numpy_function. You need to reset the shape of the data. You can try this bit of code.</p> <pre><code>def set_shapes(img, label, img_shape=&lt;you desired shape in 3d&gt;): img.set_shape(img...
python|tensorflow|opencv|image-augmentation|albumentations
1
17,617
72,279,871
How To use Tensoflow TFlite Models in flutter
<p>I have developed a model in python and exported it to TFLite format but I tried to integrate it into my flutter application all in vain. The plugins available at pub.dev that deal with tflite models are all deprecated and therefore cant run with flutter v2. How can I overgo this? Thanks.</p>
<h3>This worked for me!</h3> <p>Follow <a href="https://morioh.com/p/cf2128b9a231" rel="nofollow noreferrer">This great tutorial</a>. It explains step by step how to use your tflite models in your flutter apps</p>
flutter|tensorflow|tensorflow-lite
0
17,618
72,330,041
Append 2d array to 3d array
<p>I have an array of shape <code>(3, 250, 15)</code>.</p> <p>I want to append to it a 2d array of shape <code>(250,15)</code> so that I have a final shape of <code>(4,250,15)</code>. I tried with <code>dstack</code> and <code>np.stack</code> but it does not work.</p> <p>Can someone give me a suggestion ?</p>
<p>You need to add a dimension (in other words, an axis) to the 2-D array, for example:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np a = np.ones((3, 250, 15)) b = np.ones((250, 15)) c = np.vstack([a, b[None, :, :]]) </code></pre> <p>Now <code>c</code> has shape <code>(4, 250, 15)</code>.</p>...
python|arrays|numpy-ndarray
2
17,619
50,262,364
How to change entire column's timezone?
<p>I have a pandas dataframe as such:</p> <pre><code> Date Time Open High Low Close Volume OpenInt 0 2017-11-17 15:35:00 68.5300 68.7200 68.3800 68.6700 79411 0 1 2017-11-17 15:40:00 68.5956 68.6900 68.5600 68.5900 10014 0 2 2017-11-17 15:45:00 68...
<p>Assuming that <code>Date</code> and <code>Time</code> are of <code>object</code> dtype:</p> <pre><code>In [54]: df['Date'] = (pd.to_datetime(df['Date'] + ' ' + df.pop('Time')) .dt.tz_localize('Israel') .dt.tz_convert('UTC')) In [55]: df Out[55]: ...
python|pandas|dataframe|timezone
2
17,620
50,548,341
What is the purpose and utility of the subok option in numpy.zeros_like()?
<p>Using numpy's <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros_like.html" rel="nofollow noreferrer">zeros_like</a> and related functions, there is an option</p> <blockquote> <p><strong>subok:</strong> bool, optional.</p> <p><code>numpy.zeros_like(a, dtype=None, order='K', subok=True)</code><...
<blockquote> <p><strong><em>What</strong> is the <strong>purpose</strong> and <strong>utility</strong> ... ?</em></p> </blockquote> <h2>Purpose :</h2> <p>The call-signature <strong>helps</strong> either pass-through the processed instance-type, as seen here:</p> <pre><code>&gt;&gt;&gt; np.array( np.mat( '1 2; 3 4'...
python|class|numpy|subclass
4
17,621
50,457,003
numpy.concatenate float64(101,1) and float64(101,)
<p>I'm a MatLab user who recently converted to python. I am running a for loop that cuts a longer signal into individual trials, normalizes them to 100% trial and then would like to have the trials listed horizontally in a single variable. My code is</p> <pre><code>RHipFE=np.empty([101, 1]) newlength = 101 for i in ...
<p>Generally it's faster to collect arrays in a list, and use some form of concatenate once. List <code>append</code> is faster than <code>concatenate</code>:</p> <pre><code>In [51]: alist = [] In [52]: for i in range(3): ...: alist.append(np.arange(i,i+5)) ...: In [53]: alist Out[53]: [array([0, 1, ...
python|numpy|concatenation
1
17,622
50,668,651
Why scipy.distance.cdist has a big performance difference between using float32 (slower) and float64 (faster)?
<p>Why scipy.distance.cdist has a big performance difference between using float32 and float64?</p> <pre><code>from scipy.spatial import distance import numpy as np import time a_float32 = np.empty((1000000, 512), dtype=np.float32) b_float32 = np.empty((1, 512), dtype=np.float32) a_float64 = np.empty((1000000, 512), ...
<p>The underlying C code that actually does the computation is implemented using C <code>double</code> variables, which are 64 bit floating point values. When you pass in arrays of <code>np.float32</code>, the data must be copied.</p> <p>For the second part of your question: larger <code>k</code> means more work, so ...
python|performance|numpy|scipy
5
17,623
45,654,546
Uninstallation issues in python numpy
<p>I am in the process of downgrading numpy1.13 to 1.7. In order to do this, I am uninstalling the latest version so that i can install with a older version, </p> <p>I have uninstalled numpy in anaconda python using </p> <pre><code>`pip uninstall numpy` </code></pre> <p>After uninstalling, when i see the <code>conda...
<p>try this if you are using anaconda:</p> <pre><code>conda uninstall numpy conda install numpy=1.7 </code></pre> <p>or this if you are using python pip:</p> <pre><code>pip uninstall numpy pip install numpy==1.7 </code></pre>
python|numpy|anaconda
4
17,624
45,555,824
TensorFlow Estimator 1.3 no way to get predict_proba?
<p>I see the new DNN and estimator classes in 1.3 (tf.estimator.DNNClassifier) but I don't see any way to get/set predict_proba.. </p> <p>So as of now a prediction is set to true at over .5 % and false if under for the binary case I guess.. but there are numerous use cases where a lower probability to predict true, is...
<p>Per Google at GitHub: You can use tf.estimator now with e.g. predict(..., predict_keys="probabilities")</p> <p><a href="https://github.com/tensorflow/tensorflow/issues/12119#issuecomment-321098690" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/12119#issuecomment-321098690</a></p>
python|tensorflow
1
17,625
62,852,060
How to set a colour legend with the days of the week in Plotly bar chart
<p>i have a graph like this: <a href="https://i.stack.imgur.com/WWrSx.png" rel="nofollow noreferrer">https://i.stack.imgur.com/WWrSx.png</a> and i would like to have a legend with the name of the days of week, each of them with their own color so that every bar in the chart ( which represent a single day) have his resp...
<p>Here's a way to do that (with random data):</p> <pre><code>import pandas as pd import numpy as np import plotly.graph_objects as go # generate dummy data dates = pd.date_range(&quot;2020-01-01&quot;, &quot;2020-06-30&quot;, freq=&quot;1d&quot;) df = pd.DataFrame({&quot;date&quot;: dates, &quot;val&quot;: np.random...
python|pandas|plotly
3
17,626
62,861,107
module 'h5py' has no attribute 'File' when trying to save a tensorflow model
<p>So I Just made a small NN with the MNIST Digit Database and I'm trying to save it. Here is the full code:</p> <pre><code># Importing Libs import h5py import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from tensorflow import keras # ---------- PART I: Importing and cleaning Data ---------- # ...
<p>Try this.Its working fine.<br /></p> <pre><code>from tensorflow.keras.models import load_model model.save(&quot;model.h5&quot;) print(&quot;Saved model to disk&quot;) # load model model = load_model('model.h5') </code></pre>
python|tensorflow|keras|h5py
1
17,627
62,523,832
Subtracting data frames in Python returning NaN in columns
<p>I'm trying to subtract the second columns of two csv files(mycsv.csv, mycsv2.csv), while keeping the first columns of both the same. It does the latter perfectly fine as you can see below, but the prices columns (2 and 4), just give back NaN.</p> <pre><code> col2 col4 col1 MMM NaN NaN WBAI Na...
<p>I think the issue is with the initial import of the document.</p> <p>Here: data_sheet1 = pd.read_excel('C:\Users\sss\Downloads\Book1.xlsx') data_impor = data_sheet1['DDD'].tolist()</p> <p>You are only importing the first column and the rest of the data is not being saved to data_impor</p> <p>Then you pass this data ...
python|pandas|dataframe|csv
0
17,628
62,595,267
How to calculate the inverse of ndarray holding variables of type Fraction in python?
<p>I am trying to calculate the inverse of a 2d array in python that holds fractions and cannot convert it to float because I need to maintain the ratio correctly between numerator and denominator.</p> <p>A = np.array([[Fraction(1), Fraction(-0.5)], [Fraction(-4/9), Fraction(1)]])</p> <p>When I try <strong>np.linalg.in...
<p><code>Fraction</code> is a Python type but not a native numpy dtype. Said differently, for a numpy point of view, <code>Fractions</code> are (opaque) objects. If you manage to do operations over them with numpy methods, chances are that they will be automatically converted to floating point types (which are native i...
python|numpy|fractions
1
17,629
62,697,635
Python: Loop through a folder and save data from first tab of each file and save to new file on separate tabs
<p>I am trying to loop through 8 files in a specific folder and grab the data from specific column in the first tab of each. Then, I want to paste the data into a new, consolidated file with each of the data frames on their own separate tab. This is what I have so far...</p> <p>My questions:</p> <ol> <li>How do I grab ...
<p>To save to excel you need to have <strong>openpyxl</strong> installed. Then I would append each df to a list:</p> <pre><code> Filelist = glob.glob(r&quot;path\*.xlsx&quot;) list_df = [] for file in Filelist: list_df.append(pd.read_excel(file)) # the names for each sheet in the consolidated file name...
python|excel|pandas
0
17,630
54,418,859
Numpy array using expression
<p>how can I create an np array using expression y1 = x, when x array is already defined</p> <p><code>x = [1,2,5,7]</code></p> <p>from this array x , I would like to create another array y1 using the expression </p> <pre><code>y1 = x </code></pre> <p>using numpy</p>
<p>If you want a copy of the array it would be </p> <pre><code>import numpy as np y1 = np.array(x) </code></pre> <p>Currently you just assign the list from x to y1. With this you create a new numpy array with the values from x.</p>
python|numpy
1
17,631
54,444,260
LabelEncoder that keeps missing values as 'NaN'
<p>I am rying to use the label encoder in orrder to convert categorical data into numeric values.</p> <p>I needed a LabelEncoder that keeps my missing values as 'NaN' to use an Imputer afterwards. So I would like to use a mask to replace form the original data frame after labelling like this </p> <pre><code>df = pd.D...
<p>The first question is: do you wish to encode each column separately or encode them all with one encoding?</p> <p>The expression <code>df = df.astype(str).apply(LabelEncoder().fit_transform)</code> implies that you encode all the columns separately.</p> <pre><code>That case you can do the following: df = df.apply(l...
python|pandas|dataframe
11
17,632
54,471,419
IndexError: only integers, slices (`:`), ellipsis (`...`)
<p>I understand that there are a lot of answers on this topic but I have scrutinized all of them and did not find something suitable for me. I'm sure that error is childish but still can not find a solution. I want to take some element from <code>numpy.linspace</code>.</p> <pre><code> import numpy #Porosity range ph...
<p>Numpy is specialised at doing vector operations. That is taking an one or two arrays and applying an operation to all its elements. For python lists you might write:</p> <pre><code>zs = [] for x, y in zip(xs, ys): z = x + 2*y zs.append(z) print(zs) </code></pre> <p>Wheras with a numpy array you can write:...
python|numpy|indexing
0
17,633
73,741,723
create dataframe with outliers and then replace with nan
<p>I am trying to make a function to spot the columns with &quot;100&quot; in the header and replace the values in these columns with NaN depending on multiple criteria. I also want in the function the value of the column &quot;first_column&quot; corresponding to the outlier.</p> <p>For instance let's say I have a df w...
<p>IIUC, you can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><code>filter</code></a> and <a href="https://pandas.pydata.org/docs/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer">boolean indexing</a>:</p> <pre><code># get &quot;100...
python|pandas|dataframe|nan
1
17,634
73,706,211
How to group the x_axis dates in openpyxl
<p>I want to group the x_axis (Date) so that if there is a cell with 01/01/2022 &amp; another 01/01/2022 it will only show one bar with 01/01/2022, here it actualy print each row with a bar How can i do that in openpyxl please</p> <p>Thanks in advance</p> <pre><code>from openpyxl import Workbook from openpyxl.chart imp...
<p>So you want a stacked chart like this then?<br> <br></p> <pre><code>from openpyxl import Workbook from openpyxl.chart import BarChart, Reference rows = [ ('Date', 'Batch 1', 'Batch 2'), ('01/01/2022', 10, 40), ('02/01/2022', 50, ''), ('04/01/2022', 20, '') ] wb = Workbook(write_only=True) ws = wb....
python|pandas|openpyxl
0
17,635
73,785,467
pandas: How can I append rows in one data frame from another based on column values?
<p>The problem is a little hard to explain. I have one dataset &quot;Tab1&quot; that consists of 110 columns. This is the data of online experiments. The second table &quot;Tab2&quot; consist of the results of the experiments of &quot;Tab1&quot; which has 20 columns. The column &quot;exp_num&quot; is common in both of ...
<p>i think what you want is actually a concatination or pandas.concat.</p> <p>heres a full example.</p> <pre><code>import pandas as pd import numpy as np d1 = {'exp_num': ['aw23','aw23','aw23','aw23','aw23'], 'colA': [2,2,2,2,2], 'colB': [3,3,3,3,3], 'colC': [4,4,4,4,4]} df1 = pd.DataFrame(data=d1) d2 = {'exp_num': [...
python|pandas|dataframe
0
17,636
71,428,908
How to read xml tag with multiple data using pandas pd.read_xml in Python?
<p>I have following toy example code to read an xml using <code>pandas</code></p> <pre><code>xml = '''&lt;?xml version='1.0' encoding='utf-8'?&gt; &lt;data&gt; &lt;d&gt;10&lt;/d&gt; &lt;d&gt;20&lt;/d&gt; &lt;d&gt;11&lt;/d&gt; &lt;d&gt;2&lt;/d&gt; &lt;d&gt;5&lt;/d&gt; &lt;/data&gt;''' import pandas ...
<p>That's not a use case supported by <code>pd.read_xml</code>. It works best if the XPath results in a list of nodes of the form:</p> <pre class="lang-xml prettyprint-override"><code>&lt;row&gt; &lt;col1&gt;...&lt;/col1&gt; &lt;col2&gt;...&lt;/col2&gt; &lt;col3&gt;...&lt;/col3&gt; &lt;/row&gt; </code></pre> <p>Y...
python|python-3.x|pandas|xml
1
17,637
71,406,134
Scrapping Annual Reports for Companies
<p>I am extracting annual reports pdf file from the website .</p> <pre><code>import requests import pandas as pd from bs4 import BeautifulSoup url1 = &quot;https://investor.alaskaair.com/financial-information/sec-filings?field_nir_sec_form_group_target_id%5B%5D=471&amp;field_nir_sec_date_filed_value=#views-exposed-fo...
<p>Use:</p> <pre><code>table = soup.find('table', {'class':&quot;nirtable views-table views-view-table cols-5 collapse-table-wide&quot;}) trs = [x.find_all('td') for x in table.find_all('tr')] vs = [] ls = [] for tr in trs: if len(tr)&gt;0: v = 'https://investor.alaskaair.com/'+tr[1].a['href'] print...
python|pandas|dataframe|web-scraping|beautifulsoup
1
17,638
60,480,813
Making edge list from Pandas Data frame by matching row values and put into edgelist
<p>I'm new to Python and I'm trying to run a community detection algorithm using a dataset stored in a pandas dataframe, to do this I need to make an edgelist from this dataset to be put into a graph. I need this edgelist to consist of rows with matching column value. The dataset consists of 19 columns and over 2000 r...
<p>Let the data frame can be read into the following format, then</p> <pre><code> df = id col1 col2 col3 1 12 10 20 2 14 10 19 3 12 10 9 </code></pre> <p>We can create a new dataframe according to the following:</p> <pre><code> edge_list_df = pd.melt(df,i...
python|pandas|networkx
0
17,639
72,760,105
How to evaluate auto-encoder model for a single input?
<p>I have this auto-encoder model(using mnist dataset):</p> <pre><code>self.input = layers.Input(shape=(784,), name = 'input')#784 is flattened image, since 28*28 self.x = layers.Dense(h_dim, activation = 'relu', name = 'h1_enc',trainable=True)(self.input) self.x = layers.Dense(e_dim, activation = 'relu', name = 'encod...
<p>Reshaping the test data like below helped in solving the issue.</p> <pre><code># Reshaping the test data test_data= tf.reshape(test_data,(10000, 1, 784)) model.evaluate(test_data[0], test_data[0]) </code></pre> <p>Output:</p> <pre><code>1/1 [==============================] - 0s 108ms/step - loss: 0.6935 0.6934699416...
tensorflow|keras
0
17,640
72,524,008
Python - Add rows based on information in columns
<p>I want to add rows in Python based on the information in some of the columns. For example let's say this is my data</p> <pre><code>df = pd.DataFrame({ 'ID':[1,2,3], 'E Test':['Y','Y','N'], 'M Test':['Y','Y','Y'], }) </code></pre> <p><a href="https://i.stack.imgur.com/hHrN7.png" rel="nofollow noreferrer">...
<p>I use two different dates to show how they can be individually changed.</p> <pre><code>df2 = df.melt('ID', var_name='Test', value_name='Test Date') df2['Test'] = df2['Test'].str[0] df2.replace({'Y': True, 'N': np.nan}, inplace=True) df2.dropna(inplace=True) df2.loc[df2['Test'].eq('E'), 'Test Date'] = '1-Apr' df2.loc...
python|pandas
1
17,641
72,688,375
How to convert object to time
<p>How can I convert &quot;2022-03-01 1:01:42 AM&quot; to just 1:01:42?</p> <p>I tried to strip just the time out and convert to datetime format, but it keeps adding the current date to the beginning. Otherwise, it doesn't properly convert to datetime format so I can plot it later. All I want is the time in datetime f...
<p>How about using simple date format</p> <pre><code>from datetime import datetime now = datetime.now() print (now.strftime(&quot;%H:%M:%S&quot;)) </code></pre>
python|python-3.x|pandas|datetime
0
17,642
59,596,957
Iterating over rows in dataframe: Why not: "for i in workingDF.index:"?
<p>First, let me say: I know I shouldn't be iterating over a dataframe per:</p> <p><a href="https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas/55557758#55557758">How to iterate over rows - Don't!</a></p> <p><a href="https://stackoverflow.com/questions/16476924/how-to-iterat...
<p>In short, the answer is the performance benefit of using iterrows. This <a href="https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6" rel="nofollow noreferrer">post</a> could better explain the differences between the various options.</p>
python|pandas|dataframe|iteration
1
17,643
59,794,593
Create multi-index and transpose data with pandas with columns as additional index
<p>I've tried multiple things to read-in this excel file and reshape it with pandas. I've tried different functions like merge(), pivot(), melt(), reset_index() and I still can't figure it out. Can anyone point me in the right direction? This is the current table: <a href="https://i.stack.imgur.com/yeqqb.png" rel="nofo...
<p>You can <code>stack</code> and <code>unstack</code> to change <code>MultiIndex</code> between columns and rows. Simply do,</p> <pre><code>df = pd.read_excel('data.xlsx', index_col=[0,1]) new_df = df.unstack().stack(level=0) </code></pre> <p>To rename the indices simply do,</p> <pre><code>new_df.index.rename(('Med...
python|pandas
0
17,644
32,589,367
Python: make scipy use numpy.float128 instead numpy.float64?
<p>Is it possible, and if yes how to do it: How can I make scipy use by default numpy.float128. For example </p> <pre><code>&gt;&gt;&gt; from scipy.stats import norm &gt;&gt;&gt; type(norm.pdf(10, 10, 1)) &lt;class 'numpy.float64'&gt; </code></pre> <p>and I want it to be</p> <pre><code>&gt;&gt;&gt; from scipy.stats ...
<p>In general, you can't. Some of the scipy routines are wrappers of code written in C or Fortran that are only available in double precision. Even if you figure out which ones are pure python+numpy, and manage to ensure that the operations performed in the computation preserve the data type, you'll find that many of...
python|numpy|types|scipy
3
17,645
40,453,744
Pandas DataFrame - 'cannot astype a datetimelike from [datetime64[ns]] to [float64]' when using ols/linear regression
<p>I have a DataFrame as follows:</p> <pre><code> Ticker Date Close 0 ADBE 2016-02-16 78.88 1 ADBE 2016-02-17 81.85 2 ADBE 2016-02-18 80.53 3 ADBE 2016-02-19 80.87 4 ADBE 2016-02-22 83.80 5 ADBE 2016-02-23 83.07 </code></pre> <p>...and so on. The <code>Date</code> column is the...
<p>You need:</p> <pre><code>ADBE['Date'] = ADBE['Date'].values.astype(float) </code></pre> <p>and then:</p> <pre><code>ols1 = pd.ols(y=ADBE['Close'], x=ADBE['Date'], intercept=True) </code></pre>
python|pandas|dataframe|time-series|linear-regression
16
17,646
61,987,268
Key error: column not found...but its there
<p>I'm trying to group months together and then create a count column so I can graph it later. However, I keep receiving the following error </p> <blockquote> <p>KeyError: 'Column not found: Count'</p> </blockquote> <p>I don't understand why I'm receiving this error when I clearly have a column named count in the d...
<p>You are subsetting the dataframe by using only <code>df['DATE']</code>. So this subset will not have <code>Count</code> column. Hence when you apply groupby here, it gives you <code>Keyerror</code> with <code>Count</code>.</p> <p>So replace the following command:</p> <pre><code>df['DATE'].groupby(df["DATE"].dt.str...
python|pandas|pandas-groupby
2
17,647
61,737,257
How to create new columns using groupby based on logical expressions
<p>I have this CSV file</p> <p><a href="http://www.sharecsv.com/s/2503dd7fb735a773b8edfc968c6ae906/whatt2.csv" rel="nofollow noreferrer">http://www.sharecsv.com/s/2503dd7fb735a773b8edfc968c6ae906/whatt2.csv</a></p> <p>I want to create three columns, 'MT_Value','M_Value', and 'T_Data', one who has the mean of the data...
<p>You could do something like this:</p> <pre><code>(data.assign(M_Value=data.Valor.where(data.Valor!=0), T_Data=data.Valor.eq(0)) .groupby(['Year','Month']) [['Valor','M_Value','T_Data']] .mean() ) </code></pre> <p>Explanation: <code>assign</code> will create new columns with respective na...
pandas|csv|pandas-groupby
0
17,648
61,721,366
Statistical test for time series where outcome occurs - python
<p>I am enquiring about assistance regarding regression testing. I have a continuous time series that fluctuates between positive and negative integers. I also have <em>events</em> occurring throughout this time series at seemingly random time points. Essentially, when an event occurs I grab the respective integer. I t...
<p>It sounds like you are interested in determining the underlying forces that are producing a given stream of data. Such mathematical models are called Markov Models. A classic example is the study of text. </p> <p>For example, if I run a Hidden Markov Model algorithm on a paragraph of English text, then I will find ...
python|pandas|regression
2
17,649
57,788,675
loop within groupby and also change the first row for each group
<p>i need to find the first row of each group and set a value. then i need to calculate the rest rows based on values from the previous row. I know there are similar answers in stack overflow but i still can't really find the solution for it.</p> <p>Here is what I have tried so far:</p> <pre class="lang-py prettyprin...
<p>It is possible with custom function and <code>iloc</code> for select and set by positions, not by index labels:</p> <pre><code>def func(group): group.loc[group.index[0],'value']=800 pos = group.columns.get_loc('value') for i in range(1,len(group)): group.iloc[i,pos]=group.iloc[i-1,pos]*0.5 r...
python|pandas
3
17,650
57,791,185
ValueError: Error when checking target: expected conv2d_19 to have shape (None, 320, 320, 1) but got array with shape (18, 320, 320, 2)
<p>I try to train a U-Net model in keras, with regular segmentation (not multui-classe), but I get the following error:</p> <blockquote> <p>ValueError: Error when checking target: expected conv2d_19 to have shape (None, 320, 320, 1) but got array with shape (18, 320, 320, 2)</p> </blockquote> <p>I know this is rela...
<p>Assuming your labels are one-hot encoded, then you should change the output layer to:</p> <pre><code>outputs = tf.keras.layers.Conv2D(2, (1, 1), activation='softmax')(c9) </code></pre> <p>And the loss function to <code>categorical_crossentropy</code>. If you want to use your current model and loss with no modifica...
python|tensorflow|keras|conv-neural-network
0
17,651
57,953,358
pandas replace NaNs with modus of another column based on second column
<p>I have a pandas dataframe with two columns, <code>city</code> and <code>country</code>. Both <code>city</code> and <code>country</code> contain missing values. consider this data frame:</p> <pre><code>temp = pd.DataFrame({"country": ["country A", "country A", "country A", "country A", "country B","country B","count...
<p>Try <code>map</code> with dict <code>new_dict_locations</code> to create a new series <code>s</code>, and map again on <code>s</code> with <code>np.random.choice</code> to pick value from array. Finally, use <code>s</code> to <code>fillna</code></p> <pre><code>s = (temp.country.map(new_dict_locations) ...
python|pandas
5
17,652
58,030,814
apply max to each column of a dataframe
<p>I would like to replace all columns values with the max value of their respective columns. For example from this dataframe :</p> <pre><code>df0 = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 'C':[9,2,3]}) A B C 0 1 4 9 1 2 5 2 2 3 6 3 </code></pre> <p>I would like to get :</p> <pre><code> A B C 0 3 ...
<p>Check <code>assign</code></p> <pre><code>df0.assign(**df0.max()) Out[22]: A B C 0 3 6 9 1 3 6 9 2 3 6 9 </code></pre>
python|pandas|max
2
17,653
34,356,828
Tensorflow image reading empty
<p>This question is based on: <a href="https://stackoverflow.com/questions/33648322/tensorflow-image-reading-display">Tensorflow image reading &amp; display</a></p> <p>Following their code we have the following:</p> <pre><code>string = ['/home/user/test.jpg'] filepath_queue = tf.train.string_input_producer(string) se...
<p>The image will be properly loaded, but TensorFlow doesn't have enough information to infer the image's shape until the op is run. This arises because <a href="https://www.tensorflow.org/versions/master/api_docs/python/image.html#decode_jpeg" rel="noreferrer"><code>tf.image.decode_jpeg()</code></a> can produce tensor...
tensorflow
7
17,654
34,020,777
Slicing a Pandas dataframe with a period index with an array
<p>I'm trying to slice a pandas dataframe indexed by a period index with a list of strings with unexpected results.</p> <pre><code>import pandas as pd import numpy as np idx = pd.period_range(1991,1993,freq='A') df = pd.DataFrame(np.arange(9).reshape(3,3),index=idx) print df.loc[['1991','1993'],:] </code></pre> <...
<p>Pandas doesn't convert the strings into Periods for you, so you have to be more explicit. You could use:</p> <pre><code>In [38]: df.loc[[pd.Period('1991'), pd.Period('1993')], :] Out[38]: 0 1 2 1991 0 1 2 1993 6 7 8 </code></pre> <p>or </p> <pre><code>In [39]: df.loc[map(pd.Period, ['1991', '1993']...
python|pandas|slice
3
17,655
34,347,223
Python 2.7 - unable to upgrade/ install some packages after upgrading to El Capitan
<p>After I have upgraded to El Capitan, Python 2.7 is unable to install/ upgrade/ uninstall some packages, but meanwhile, it still works fine for some other packages.</p> <p>Below (the end) is the error message I have got when trying to upgrade numpy. Same error also raises when I tried to uninstall it.</p> <p>I have...
<p>The python framework you are using </p> <blockquote> <p>"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7"</p> </blockquote> <p>is the system python that comes with your mac os. You shouldn't <code>pip install</code> packages as doing so may pollute your system python and potentially cause...
macos|python-2.7|numpy|osx-elcapitan
0
17,656
34,162,549
Miminum requirements for Google tensorflow image classifier
<p>We are planning to build image classifiers using Google Tensorflow.</p> <p>I wonder what are the minimum and what are the optimum requirements to train a custom image classifier using a convolutional deep neural network?</p> <p>The questions are specifically:</p> <ul> <li>how many images per class should be provi...
<p>"how many images per class should be provided at a minimum?"</p> <p>Depends how you train.</p> <p>If training a new model from scratch, purely supervised: For a rule of thumb on the number of images, you can look at the MNIST and CIFAR tasks. These seem to work OK with about 5,000 images per class. That's if you'r...
machine-learning|computer-vision|neural-network|classification|tensorflow
7
17,657
36,904,298
How to implement multi-class hinge loss in tensorflow
<p>I want to implement multi-class hinge loss in tensorflow. The formulation is as follows:</p> <p><a href="https://i.stack.imgur.com/fGDq2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fGDq2.png" alt="multi-class hinge loss function"></a></p> <p>I find it difficult to get the second max prediction probab...
<p><code>top_k</code> has gradients, added in version 0.8 <a href="https://github.com/tensorflow/tensorflow/commit/dbc57b9068da9b823dbcc3101e599da6f65f658a" rel="nofollow">here</a></p>
neural-network|tensorflow
3
17,658
55,001,544
np.array() creates array of list-objects when given a multidimensional array, but should create 'normal' array
<p>something strange is happening when I try to transform a multidimensional list into a multidimensional array. Here an example code how it should look like and what my goal is. This example works:</p> <pre><code>array = [[1, 1], [2, 2]] array = np.array(array) print(array) </code></pre> <p>The output is as expected...
<p>As hpaulj sad, the list differ in length. Thats what confused me. I did not thought about that. Thanks for the awnser.</p>
python|arrays|numpy
0
17,659
54,891,304
Filtering a dataframe using Fuzzywuzzy keyword matches
<p>Novice Python user here. </p> <p>I have a dataframe imported from a csv file which I need to search for "Alert" and "Amber" keywords from the from_data column (searching for upper, lower or a combination of both case).</p> <p>Here are the contents of my dataframe called df:</p> <pre><code> Id_No from_data ...
<p>Use boolean indexing with <code>str.contains()</code></p> <pre><code>df[df['from_data'].str.lower().str.contains('alert|amber')] Id_No from_data 0 1 Alert g12134 CONFIRMATION CODE A27 1 1 ALERT g12134 CONFIRMATION CODE A28 3 5 g12136 CONFIRMATION CODE B02 - ...
python-3.x|pandas|dataframe|fuzzywuzzy
3
17,660
54,847,380
ImportError: cannot import name 'keras'
<p>When running this in Jupyter notebooks (python):</p> <pre class="lang-python prettyprint-override"><code>import tensorflow as tf from tensorflow import keras </code></pre> <p>I get this error:</p> <pre class="lang-python prettyprint-override"><code>ImportError: cannot import name 'keras' </code></pre> <p>I've ...
<p>I think you are using old version <code>tensorflow</code> Try to update it like</p> <pre><code>! pip install tensorflow --upgrade </code></pre>
python|tensorflow|keras
5
17,661
54,788,629
Pandas DataFrame: Operation based on leading row
<p>I have this csv file which has large amount of data. I have taken the csv as a dataframe in python. I want to compare each row with its corresponding row and if the first row has value 1 and second row has value 100 , then the program should replace 100 to 50. If there are 2 columns containing 1 above 100 , then the...
<p>Edited: Since your question has now changed, here is the new answer. You can keep track of the index of previous rows as you did, but do it in a while loop and subtract by one each time and divide by half each time the condition is still true. </p> <pre><code>for key in df: for i, value in enumerate(df[key]): ...
python|pandas|csv
1
17,662
54,738,551
Merging dataframes in pandas on 'date' only merges headers
<p>I am currently trying to merge two dataframes, by their respective date/time column. Information about each of my data sets are below:</p> <pre><code>data1.head(5) DATE AA ... AB AB2 0 2011-01-01 00:30:00 6135.998518 ... 0.0 80.331500 1 2011-01-01 01:00:00 ...
<p>The DATE column is probably of type object, then you cannot join on differently formatted dates (e.g. 2006/01/01 vs 2006-01-01). You need to change these to type datetime.</p> <pre><code>data1['DATE'] = pd.to_datetime(data1['DATE']) data2['DATE'] = pd.to_datetime(data2['DATE']) mergeddf = pd.merge(data1[['DATE','A...
python|pandas|numpy|merge
3
17,663
28,078,118
Merge Many json strings with python pandas inputs
<h2>Summary</h2> <p>I have created data objects that are comprised of (among other things), of <code>pandas</code> objects like <code>DataFrame</code>s and <code>Panel</code>s. I'm looking to serialize these objects into <code>json</code>, and speed is a primary consideration.</p> <h2>Example using a <code>pandas.Pa...
<p>In the end, the fastest way was to write a simple string <code>concat</code>-er. Here were the two best solutions, (one provided by @Skorp)) and their respective <code>%timeit</code> times in graphical form</p> <h3>Method 1. String-Merge</h3> <pre><code>def panel_to_json_string(panel): def __merge_stream(key,...
python|json|serialization|pandas|concat
1
17,664
28,256,810
dot products of rows and columns
<p>I have two matrices, a (mxn), and b (nxp). For each n, I would like to multiply the nth column of a with the nth row of b, giving me n (mxp) matrices. I would then like to 'collapse' these matrices into a single (mxp) matrix by taking the mean of each element in the matrix. Is there a reasonably efficient way (as in...
<p>The dot product does the multiplication followed by a sum, producing a (m,p) array. If you want the mean instead of sum, just divide by <code>n</code>, the number of items you are summing.</p> <pre><code>np.dot(a,b)/n </code></pre>
python|numpy|matrix
4
17,665
28,175,330
selecting a particular row from groupby object in python
<pre><code>id marks year 1 18 2013 1 25 2012 3 16 2014 2 16 2013 1 19 2013 3 25 2013 2 18 2014 </code></pre> <p>suppose now I group the above on id by python command.<br> grouped = file.groupby(file.id)</p> <p>I would like to get a new file wit...
<p>I cobbled this together using this: <a href="https://stackoverflow.com/questions/15705630/python-how-can-i-get-the-row-which-has-the-max-value-in-goups-making-groupby">Python : Getting the Row which has the max value in groups using groupby</a></p> <p>So basically we can groupby the 'id' column, then call <code>tra...
python|pandas|group-by
7
17,666
73,445,258
Train a LSTM model using multiple datasets in for loop
<p>I am in the process of training my LSTM neural networks that shall predict quintiles of stock price distributions. As I would like to train the model on not just one stock but a sample of 500 I wrote the below training loop that shall fit the model to each stock, save the model params and the load the params again w...
<p>According to this answer <a href="https://stackoverflow.com/questions/50913520/how-can-i-use-multiple-datasets-with-one-model-in-keras">How can I use multiple datasets with one model in Keras?</a></p> <p>you can repeatedly fit the same model on more datasets.</p> <p>If you want to save the model and load it at each ...
python|tensorflow|machine-learning|keras|training-data
0
17,667
73,295,316
Pickle only dumps one value in loop
<p>I am trying to pickle certain data so I have an easier time retrieving it. My code looks like this:</p> <pre><code>import pickle import networkx as nx import pandas as pd import numpy as np import load_data as load # load the graph g = load.local_data() for node in g.nodes(): # get node degree pickle.d...
<p>In the current code, you are asking python to open and write something to the pickle as you iterate over the nodes. This ends up overwriting what was already stored in the pickle file every iteration.</p> <p>What you might want to do instead is:</p> <pre class="lang-py prettyprint-override"><code>with open(&quot;./p...
python|pandas|network-programming|networkx|pickle
2
17,668
73,290,009
How to merge dataframes with others that have empty column values in python?
<p>Have tried to merge DF1 and DF2 but cannot success. Please help. I used the code DF_new = DF1.merge(DF2[[&quot;C&quot;, &quot;Z&quot;]], on=&quot;C&quot;, how=&quot;left&quot;)</p> <p><a href="https://i.stack.imgur.com/yckAI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yckAI.png" alt="enter ima...
<p>What you're trying with should work</p> <pre><code>import pandas as pd df1 = pd.DataFrame({&quot;A&quot;:[1,2,3], &quot;B&quot;:[4,5,6], &quot;C&quot;:[7,8,9]}) df2 = pd.DataFrame({&quot;C&quot;:[7,8,9]}) df2[&quot;Z&quot;] = &quot;&quot; df3 = df1.merge(right=df2[[&quot;C&quot;,&quot;Z&quot;]], on=&quot;C&quot;, ...
python|pandas|dataframe|merge
0
17,669
73,228,490
How to set specific values for the weight and bias in a neural net?
<p>I want to initialize the values of the weight and bias of the linear layers in my PyTorch neural network. Below is some code for my neural net:</p> <pre><code>class NeuralNet(nn.Module): def __init__(self, weights, bias): super(NeuralNet, self).__init__() self.wei...
<p>First, when assigning a weight value to a linear layer, the matrix size must be the same. The weight matrix size of fc1, fc2, and fc3 is 3*3, and the weight matrix size of fc4 is 1*3.</p> <p>Second, to change the weight value, use no grad to prevent the weight from changing during training.</p> <p>Third, when access...
python|machine-learning|neural-network|pytorch
0
17,670
73,361,253
Find number of islands and affected area in an image
<p>I have the following problem that I wanted to solve using opencv or scikit-image.</p> <p>Suppose I have a &quot;map&quot; in the following form: 1 is ground 0 is water</p> <pre><code>map = np.array([ [ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.], [ 0., 1., 1., 1., 0., 0.], [ 0., 0., 1., 0., 1., 0.], ...
<p><strong>Solving question no. 1 with Scikit-Image</strong>: The <a href="https://scikit-image.org/docs/stable/api/skimage.measure.html" rel="nofollow noreferrer"><code>measure</code></a> module will be your friend. Please checkout the documentation for it.</p> <pre><code>import numpy as np from skimage import measure...
python|numpy|opencv|image-processing|scikit-image
1
17,671
35,176,812
Cannot make array in using tensorflow
<p>In feeding batch_xs to x, I reshaped batch_xs, for BATCH_SIZE is 1. Here is my source. I'm not sure what is making the ValueError.</p> <pre><code>with tf.name_scope("input") as scope: x = tf.placeholder(tf.float32, shape=[1, 784]) BATCH_SIZE = 1 DROP_OUT_RATE = 0.4 EPOCH = 1 MEMORIZE = 10 accuracy_array = [] l...
<p>From the documentation <a href="https://www.tensorflow.org/versions/0.6.0/api_docs/python/client.html#Session" rel="nofollow noreferrer">here</a> :</p> <blockquote> <p>Each key in feed_dict can be one of the following types:</p> <ul> <li><p>If the key is a Tensor, the value may be a Python scalar, string, list, or n...
tensorflow
2
17,672
67,446,605
Sum values from numpy array if condition on value in another array is met
<p>I'm facing a problem with vectorizing a function so that it applies efficiently on a numpy array.</p> <p>My program entries :</p> <ul> <li>A <strong>pos_part</strong> 2D Array of <em>Nb_particles</em> lines, 3 columns (basicaly x,y,z coordinates, only z is relevant for the part that bothers me) <em>Nb_particles</em>...
<p>You can get a lot more performance by writing your first version completely in numpy. Replace pythons <code>sum</code> with <code>np.sum</code>. Instead of the <code>for i in positions</code> list comprehension, simply pass the <code>positions</code> mask you are creating anyways. Indeed, the <code>np.where</code> i...
python|numpy|numpy-ndarray
0
17,673
67,505,055
Dataframe append with multiindex
<p>I have a dataframe d1 with multiindex of col1 and col2:</p> <pre><code> col3 col4 col5 col1 col2 1 2 3 4 5 2 3 4 5 6 </code></pre> <p>And another dataframe d2 with exact same structure:</p> <pre><code> col3 col4 col5 col1 col2 20 ...
<p>Try with <code>combine_first</code></p> <pre><code>out = d2.combine_first(d1) </code></pre>
python|pandas|multi-index
3
17,674
67,501,088
How to vectorize np.dot between vectors located in arrays of vectors?
<p><strong>Variables:</strong></p> <p>x and y are arrays of N 2D vectors with shapes (N, 2).</p> <p><strong>Question:</strong></p> <p>Is there a way to perform the dot product between the vectors corresponding to the same position in the two arrays without explicitly writing the elements as in a list comprehension: <co...
<p>Try this:</p> <pre><code>N = 10 x = np.random.randn(N,2) y = np.random.randn(N,2) np.einsum(&quot;ij,ij-&gt;i&quot;, x, y) </code></pre>
python|numpy|vectorization|numpy-ndarray
5
17,675
67,462,878
Pandas: find the column value based on searching the row
<p>Assume I have a dataframe in Pandas:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(), 'B': 'one one two three two two one three'.split(), 'C': np.arange(8), 'D': np.arange(8) * 2}) </code></pre> <p>The dataf...
<p>You can filter and use <code>.loc</code>:</p> <pre><code>result = df.loc[df.C == 1, &quot;D&quot;] </code></pre> <p>alternative equivalent syntax as noted in the comments:</p> <pre><code>result = df.loc[df['C'].eq(1), 'D'] </code></pre> <p>While you can &quot;chain operations, such as <code>df[df.C == 1][&quot;D&quo...
python|pandas|dataframe
0
17,676
34,747,346
numpy array size vs. speed of concatenation
<p>I am concatenating data to a numpy array like this: </p> <pre><code>xdata_test = np.concatenate((xdata_test,additional_X)) </code></pre> <p>This is done a thousand times. The arrays have dtype <code>float32</code>, and their sizes are shown below:</p> <pre><code>xdata_test.shape : (x1,40,24,24) (x1 : [5...
<p>As far as I understand numpy, all the <code>stack</code> and <code>concatenate</code> functions are not extremely efficient. And for good reasons, because numpy tries to keep array memory contiguous for efficiency (see <a href="https://stackoverflow.com/questions/26998223/what-is-the-difference-between-contiguous-an...
python|performance|numpy
6
17,677
60,114,126
Finding mean from group by and displaying all information
<p>i have this data frame.</p> <pre><code>df1 = pd.DataFrame({'userId': [1,1,1,2,2,3,4,4], 'movieId': [500,600,700,1100,1200,600,600,1900], 'ratings': [3.5,4.5,2.0,5.0,4.0,4.5,5.0,3.5]}) df2 = pd.DataFrame({'userId':[1,1,2,3,4,5], 'movieId':[500,600,1100,80...
<p>I'll propose something different. I'll not use <code>concat</code>, instead I'll use <code>pd.merge</code></p> <p>Check this out:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'userId': [1,1,1,2,2,3,4,4], 'movieId': [500,600,700,1100,1200,600,600,1900], 'ratings': [3...
python|count|pandas-groupby|mean
1
17,678
60,118,646
Conditional operations in dataframe (if else)
<p>I have a data frame called Install_Date. I want to assign values to another data frame called age under two conditions- if value in Install_Date is null then <code>age = current year - plant construct date</code>, if value is not null then <code>age = current year - INPUT_Asset["Install_Date"]</code>,</p> <p>This ...
<pre><code>INPUT_Asset["Install_Date"] = pd.to_numeric(INPUT_Asset["Install_Date"], errors='coerce').fillna(0) INPUT_Asset["Asset_Age"] = np.where(INPUT_Asset["Install_Date"] ==0.0, this_year- Plant_Construct_Year,INPUT_Asset["Asset_Age"]) INPUT_Asset["Asset_Age"] = np.where(INPUT_Asset["Install_Date"] !=0.0, this_ye...
python|pandas|dataframe|conditional-statements
0
17,679
60,292,230
For loop to drop columns based on null values
<p>Hello I have a data frame called lc. And in the shape of the data frame is (235607,146) I was able to write a code that shows me the percentage of null values in each column(<code>np.sum(lc.isnull())/lc.shape[0]*100</code>). And now I need help in writing a for loop that drops all the columns with null values greate...
<p>You can use <code>boolean</code> indexing. Taken <code>mean</code> to check the percent of null values in each column. As <code>false</code> will be returned in case of columns that don't meet the criteria, they will not be shotlisted.</p> <pre><code>import numpy as np df.loc[:,df.isin([0,' ',np.nan,None]).mean()&l...
python|python-3.x|pandas|dataframe
1
17,680
65,197,934
numpy: Creating a binary mask for a float array without allocating intermediate arrays
<p>I have two numpy float arrays of the same shape: <code>data</code> and <code>mask</code>. I want to populate the values of <code>mask</code> based on the values in <code>data</code>. When the value of an element in <code>data</code> is equal to one of the 'acceptable values' (see below), then the corresponding item ...
<p>Perhaps using the <code>where</code> argument of the <code>np.isfinite</code> function to filter out elements equal to zero would achieve what you want? It is however slower than other options that use additional boolean arrays.</p> <pre><code>import numpy as np # Dummy data data = np.tile([0,np.inf,2,3,4,5], 10000...
python|arrays|numpy
0
17,681
65,304,285
How to shift a quadratic line?
<p>How to shift a quadratic blue line to lower position? Now the space between the curves is not the same because of a quadratic function.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() plt.rcParams[&quot;figure.figsize&quot;] = [8, 8] x = np.linspace(-1, 1, 100) y = x**2 a...
<p>Here is an approach that calculates the normals from the curve, and plots parallel lines at a given distance specified as the <code>length</code> of the normal:</p> <p><a href="https://i.stack.imgur.com/JD6ql.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JD6ql.png" alt="enter image description h...
python|python-3.x|numpy|matplotlib|geometry
1
17,682
50,074,536
Pandas bar plot to numpy array
<p>I am trying to convert a bar chart figure into a numpy array. I am doing so using the code below:</p> <pre><code>df = pd.DataFrame.from_dict(data) fig = plt.figure() fig.add_subplot(1, 1, 1) df.plot.bar() plt.savefig('curr_bar_chart.png') numpy_array = fig2data(fig) plt.close() im = data2img(numpy_array) </...
<p>That is because your <code>fig</code> is indeed empty. You can see this by <code>plt.show()</code> in place of <code>plt.savefig('curr_bar_chart.png')</code>:</p> <pre><code>df = pd.DataFrame.from_dict(data) fig = plt.figure() fig.add_subplot(1, 1, 1) df.plot.bar() plt.show() </code></pre> <p>You would end ...
python|pandas|numpy|matplotlib
1
17,683
49,901,806
Warning: Please use alternatives such as official/mnist/dataset.py from tensorflow/models
<p>I'm doing a simple tutorial using Tensorflow, I have just installed so it should be updated, first I load the mnist data using the following code:</p> <pre><code>import numpy as np import os from tensorflow.examples.tutorials.mnist import input_data os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' mnist = input_data.read_...
<p><code>tensorflow.examples.tutorials</code> is now deprecated and it is recommended to use <code>tensorflow.keras.datasets</code> as follows:</p> <pre><code>import tensorflow as tf mnist = tf.keras.datasets.mnist (X_train, y_train), (X_test, y_test) = mnist.load_data() </code></pre> <p><a href="https://www.tensorfl...
python|python-3.x|tensorflow
22
17,684
50,073,421
Efficient way to get a subset of indices in numpy
<p>I have the following indices as you would get them from <code>np.where(...)</code>:</p> <pre><code>coords = ( np.asarray([0 0 0 1 1 1 1 1 2 2 2 3 3 3 3 4 4 4 5 5 5 5 5 6 6 6]), np.asarray([2 2 8 2 2 4 4 6 2 2 6 2 2 4 6 2 2 6 2 2 4 4 6 2 2 6]), np.asarray([0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]),...
<p>Not so sure about efficiency but given you're basically comparing coordinates pairs you could use <code>scipy</code> distance functions. Something along:</p> <pre><code>from scipy.spatial.distance import cdist c = np.stack(coords).T i = np.stack(index).T d = cdist(c, i) In [113]: np.any(d == 0, axis=1).astype(in...
python|numpy
1
17,685
50,121,477
Tensorflow no module named official
<p>I am trying to use the nets from the official mnist directory of tensorflows model repository. On my windows system I receive this error:</p> <pre><code>C:\Users\ry\Desktop\NNTesting\models\official\mnist&gt;mnist_test.py Traceback (most recent call last): File "C:\Users\ry\Desktop\NNTesting\models\official\mnist...
<pre><code>pip install tf-models-official </code></pre>
python|tensorflow
23
17,686
46,948,300
pandas - filtering a dataframe by index of another dataframe, then combine the two dataframes
<p>I have two dataframes as the following:</p> <pre><code>df1 Index Fruit 1 Apple 2 Banana 3 Peach df2 Index Taste 1 Tasty 1.5 Rotten 2 Tasty 2.6 Tasty 3 Rotten 3.3 Tasty 4 Tasty </code></pre> <p>I would like to filter df2 by using the indices of the two ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.searchsorted.html" rel="nofollow noreferrer"><code>searchsorted</code></a> for indices, then select by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>iloc</code...
python|pandas
0
17,687
38,648,561
Numpy trouble vectorizing certain kind of aggregation
<p>I am having difficulty in vectorizing the below operation:</p> <pre><code># x.shape = (a,) # y.shape = (a, b) # x and y are ordered over a. # Want to combine x, y into z.shape(num_unique_x, b) # Below works and illustrates intent but is iterative z = np.zeros((num_unique_x, b)) for i in range(a): z[x[i], y[i,...
<p>Your use of <code>num_unique_x</code>, and the size of <code>z</code> suggests that this is a case where <code>x</code> and <code>y</code> have repeats, and that some of the <code>z</code> will be larger than 1. In which case we need to use <code>np.add.at</code>. But to set that up I'd have review its documentati...
python|numpy
1
17,688
63,057,525
Quantized models in Object Detection API for TF2
<p>I want to migrate my code for fine-tuning an object detection model for inference on Coral devices to TensorFlow 2, but I don't see quantized models in the <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md" rel="nofollow noreferrer">TF2 model zoo</a>.</p> ...
<p>Even for the TF1.x models, the conversions are not that straightforward which I am struggling with them at this time. I am pretty disappointed as I think Coral should have better support for tensorflow than Intel NCS USB originally as they are in the same family. However, it seems that I am wrong.</p>
tensorflow|object-detection-api|google-coral|tensorflow2.x
0
17,689
63,287,714
how to assign units to geometries and projection to polygon in python3?
<p>I created a multipolygon (shapefile) from a PNG image. The PNG image was originally a GeoTIFF. The geometries of my multipolygon are values of a normal x,y axis (with 0,0 as origin). In other words, the geometries are not lat,long. See sample:</p> <pre><code>geometry 0 POLYGON ((0.000 0.000, 0.000 310.000, 5.000 ...
<p>it says no attribute, so set <code>crs</code> at the object property like this</p> <pre><code>gdf.crs = {&quot;init&quot;:&quot;epsg:4326&quot;} </code></pre> <p>then you can project it to another by <code>to_crs()</code>, for example</p> <pre><code>gdf.to_crs(epsg=3857) </code></pre>
python|projection|geopandas
1
17,690
63,119,244
How to update Pandas in Anaconda
<p>I want to use the compare() function available in Pandas 1.1.0. I am doing an update in Anaconda to Pandas, but it just takes me to 0.25?</p>
<p>Have you tried: <code>conda install pandas=1.1.0</code>.<br /> You may need to add a channel that contains pandas 1.1.0.<br /> Conda forge contains pandas 1.0.5<br /> <code>conda config --add channels conda-forge</code></p>
python|pandas|conda
1
17,691
67,916,063
How to export an excel sheet two dataframes
<p>I need to create an excel sheet for each station_list value and write two dataframes in it</p> <pre><code>dfVentaPotencial = ventaPotencial() print(dfVentaPotencial.head) </code></pre> <pre><code>CodigoEstacion Dia 0am 1am 2am 3am 4am 5am 6am 7am 8am 9am 10am 11am 12pm 1pm 2pm 3pm 4pm 5pm 6pm 7...
<p>You have a dictionary with multiple dfs in it. You cannot export the complete dict but you can export the underlying df:</p> <pre><code>dataframe_collection[estation].to_excel(writer, sheet_name=estation) </code></pre>
python|pandas|dataframe|openpyxl|excel-writer-xlsx
0
17,692
67,726,065
How can i extract the year and month from multiple date columns in a dataframe at once? (getting an error)
<p>I have a df with four datetime columns. Some of these columns have null values in. I would like to extract the year and month from each column. For an individual column I have done this:</p> <p><code>df['year-month'] = pd.to_datetime(df['datetime']).dt.strftime('%Y-%m')</code></p> <p>However when I try to apply this...
<p>You could use Pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>apply</code></a> function to execute a function along an axis of the DataFrame.</p> <p>Original <strong>df</strong></p> <pre class="lang-py prettyprint-override"><code> 0 ...
python|pandas|datetime
0
17,693
67,813,912
Trying to append multiple items to list but getting Python TypeError: list indices must be integers or slices, not str
<p>I am trying to loop through customfield_10003 and append all the &quot;name&quot; values in each customfield_10003 for each issue in the list.</p> <p>Here is the JSON that im working on:</p> <pre><code>{ &quot;expand&quot;: &quot;operations,versionedRepresentations,editmeta,changelog,renderedFields&quot;, ...
<p>If you can better describe your desired output, then a better answer can be provided.</p> <p>This iterates through your json object and pulls the names into a list</p> <pre><code>#data = your sample json data1 = data['fields']['customfield_10003'] names_list = [d['name'] for d in data1] ['Promo Sim 3/23', 'Promo Si...
python|pandas
0
17,694
31,915,504
Modified cumulative sum of numbers in a list
<p>I want to create new list according cumulative sums of numbers in a list. Input is ideal - can be splitting to subset, sum of each subset is equal. Length of subset is not equal. Number of subset is input.</p> <p>Each subset of output represents increment integers <code>[0,1,2,3,...]</code>, which replace original ...
<p>This should solve your problem:</p> <pre><code>def changelist (l, t): subset = sum(l) / t current, total = 0, 0 for x in l: total += x if total &gt; subset: current, total = current + 1, x yield current </code></pre> <p>Examples:</p> <pre><code>&gt;&gt;&gt; list(changelist([1, 4, 5], 2)) [...
python|list|numpy|numbers|cumulative-sum
2
17,695
41,430,762
Numpy's standard deviation method giving divide by zero error
<p>I have written a function to regularise a set of features in a machine learning algorithm. It takes a rectangular 2D numpy array <code>features</code> and returns its regularised version <code>reg_features</code> (I am using the Boston housing prices data from Scikit-learn for training). The exact code:</p> <pre><c...
<p>It is the subset of the data <code>total_features[400:]</code> that results in the problem. If you look at that data, you'll see that columns <code>total_features[400:, 1]</code> and <code>total_features[400:, 3]</code> are all 0. This causes a problem in your code, because the both the mean and standard deviation ...
python|numpy
1
17,696
41,418,717
Checking if Adjacent Values are in a Numpy Matrix
<p>So, I am currently trying to figure out a more optimal solution to determine connected components in an image. Currently, I have an array with coordinates that have certain values. I want to create groups of these coordinates based on if they are touching. I am using a numpy array, and currently I have to check if e...
<p><strong>Approach #1</strong></p> <p>We could get the euclidean distances and see if any of the distances is within <code>sqrt(2)</code>, which would cover <code>up-down</code> with <code>distance = 1</code> and diagonal with <code>distance = sqrt(2)</code>. This would give us a mask, which when indexed into the gro...
python|arrays|numpy
1
17,697
61,591,324
Sum up column based on two dates in a different dataframe
<p>I'm trying to sum a column if it falls between two dates and based on a jobid. I'm using the below function but I keep zero as the sum value.</p> <pre><code>def jobrun (row): return table1[(table1.job == row['job']) &amp; \ (table1.date &gt;= row['past']) &amp; \ (table1.date &lt; row['present'])]['...
<p>I don't think you can apply <code>jobrun</code> on two dataframes, because it will give you error as <code>ValueError: Can only compare identically-labeled Series objects</code>. (as mentioned in one of the comments)</p> <p>What you might try is to perform a outer merge of <code>table1</code> and <code>row</code> b...
python|pandas|dataframe
0
17,698
68,563,827
In Python how to use Pandas to manipulate output from Prophet
<p><a href="https://i.stack.imgur.com/dK2tX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dK2tX.png" alt="enter image description here" /></a>new to Python, would appreciate any help with Pandas to manipulate output from Prophet Library ( see image ). My input Dataframe has 3 columns, Prophet only ...
<p>Cant test this without a reproducible dataset but something like this should do it.</p> <pre><code>import pandas as pd from fbprophet import Prophet df = pd.read_csv('C:\path') df.columns = ['Operator','ds','y'] df['ds'] = pd.to_datetime(df['ds']) def forecast_data(g): data = g[['ds','y']] m = Prophet() ...
python|pandas|facebook-prophet
1
17,699
68,697,032
Write Multiple API Calls to Individual JSON Files
<p>I'm trying to query an API for some data, but my queries can be very long and cause the server to not send back data (<code>414 request-uri too large</code>). As such, I am creating batches to send multiple calls with the intent of saving responses from each call as json, then read them into <code>pandas</code> down...
<p>For one, it appears as though you're writing the same response 4 times:</p> <pre><code># Write data from each batch to json file for i in range(0,num_batches): with open(os.makedir(os.path.dirname(&quot;data/output&quot;), exist_ok=True)+&quot;/output_&quot;+i+&quot;.json&quot;) as f: json.dumps(jsonRespon...
python|pandas|dataframe|python-requests
1