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
21,100
69,360,048
AttributeError: 'ReLU' object has no attribute 'dim'
<p>I am building a GAN, and my discriminator function is defined as</p> <pre><code>class Discriminator(nn.Module): def __init__(self): super(Discriminator, self).__init__() self.fc1 = nn.Linear(50*15, 32) self.fc2 = nn.Linear(32, 32) self.fc3 = nn.Linear(32, 1) def forward(self, x): x = x.flat...
<p><em>nn.ReLU(</em>) creates an nn.Module which you can add e.g. to an nn.Sequential model. <em>nn.functional.relu</em> on the other side is just the functional API call to the relu function, so that you can add it e.g. in your <em>forward</em> method yourself. (from <a href="https://discuss.pytorch.org/t/whats-the-di...
python|pytorch|generative-adversarial-network
4
21,101
69,353,135
Building a new Pandas DataFrame based on dates from another DataFrame
<p>My title is not great because I'm having trouble articulating my question. Basically, I have a DateFrame with transactional data consisting of a few DateTime columns and a value column. I need to apply filters to the dates and sum the resulting values in a new DataFrame.</p> <p>Here is a simplified version of my Dat...
<p>I kept digging and found a solution to my question with a lot of help from this <a href="https://stackoverflow.com/questions/62923267/pandas-sumif-equivalent-for-two-dataframes">answer from kait</a></p> <pre><code>def usr(x): mask = df['Sched Week'] &lt;= x['Sched Week'] mask &amp;= df['Ship Week'] &gt; x['S...
python|pandas|dataframe
1
21,102
69,618,513
Get max value() of result of aggregate function by column name
<p>Lets say I have this data</p> <pre><code>import pandas as pd data = { 'country':['USA', 'China', 'Japan', 'Germany', 'UK', 'India', 'USA', 'India'] ,'foo':[1, 2, 3, 4, 5, 6, 7, 8] ,'bar':[11, 22, 33, 44, 55, 66, 77, 88] } df = pd.DataFrame(data) </code></pre> <p>With <code>df.groupby('country').agg(['c...
<p>Try:</p> <pre><code># find the rows with a maximum either in foo or bar mask = (counts == counts.values.max(0)).any(1) res = counts[mask] print(res) </code></pre> <p><strong>Output</strong></p> <pre><code> foo bar count count country India 2 2 USA 2 ...
python|pandas|dataframe
1
21,103
54,107,108
Python convert the day of year to month on an axis
<p>I have a time series that I would like to plot year on year. I want the data to be daily, but the axis to show each month as "Jan", "Feb" etc.</p> <p>At the moment I can get the daily data, BUT the axis is 1-366 (the day of the year).</p> <p>Or I can get the monthly axis as 1, 2, 3 etc (by changing the index to df...
<p>This can be done using the <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.xticks.html" rel="nofollow noreferrer">xticks function</a>. Simply add the following code before <code>plt.show()</code>:</p> <pre><code>plt.xticks(np.linspace(0,365,13)[:-1], ('Jan', 'Feb' ... 'Nov', 'Dec')) </code></pre> <p>...
python|pandas|datetime|matplotlib
5
21,104
38,127,209
How to use groupby to concatenate strings in python pandas?
<p>I currently have dataframe at the top. Is there a way to use a groupby function to get another dataframe to group the data and concatenate the words into the format like further below using python pandas?</p> <p>Thanks</p> <p>[<img src="https://i.stack.imgur.com/ffFpH.png" alt="enter image description [1]"></p>
<p>You can apply <code>join</code> on your column after <code>groupby</code>:</p> <pre><code>df.groupby('index')['words'].apply(','.join) </code></pre> <p>Example:</p> <pre><code>In [326]: df = pd.DataFrame({'id':['a','a','b','c','c'], 'words':['asd','rtr','s','rrtttt','dsfd']}) df Out[326]: id words 0 a a...
python|pandas|pandas-groupby
28
21,105
38,060,450
numpy: fromfile for gzipped file
<p>I am using <code>numpy.fromfile</code> to construct an array which I can pass to the <code>pandas.DataFrame</code> constructor</p> <pre><code>import numpy as np import pandas as pd def read_best_file(file, **kwargs): ''' Loads best price data into a dataframe ''' names = [ 'time', 'bid_size', 'bi...
<p>I have had success reading arrays of raw binary data from gzipped files by feeding the read() results through numpy.frombuffer(). This code works in Python 3.7.3, and perhaps in earlier versions also.</p> <pre><code># Example: read short integers (signed) from gzipped raw binary file import gzip import numpy as n...
python|numpy
5
21,106
66,147,071
How to read xlsx blob into pandas from Azure function in python
<p>I am reading in .xslx data from a blob in an azure function. My code looks something like this:</p> <pre><code>def main(techdatablob: func.InputStream, crmdatablob: func.InputStream, outputblob: func.Out[func.InputStream]): # Load in the tech and crm data crm_data = pd.read_excel(crmdatablob.read().decode('...
<p>Please refer to my code, it seems that you don't need to add <code>decode('ISO-8859-1')</code>:</p> <pre class="lang-py prettyprint-override"><code>import logging import pandas as pd import azure.functions as func def main(techdatablob: func.InputStream, crmdatablob: func.InputStream, outputblob: func.Out[func.Inp...
python|pandas|azure|azure-functions|blob
4
21,107
66,200,140
How can I create lag variable for a particular variable for each ID
<p>I wanna create a lag variable named <code>lag_ins</code></p> <p>Which look likes:</p> <pre><code>year ID emissions ins lag_ins 2010 1 10 0 Nan 2011 1 20 1 0 2012 1 30 1 1 2010 2 10 1 Nan 2011 2 20 0 1 2...
<p>You can just do <code>groupby.shift</code>:</p> <pre><code>df['lag_ins'] = df.groupby('ID').ins.shift() df # year ID emissions ins lag_ins #0 2010 1 10 0 NaN #1 2011 1 20 1 0.0 #2 2012 1 30 1 1.0 #3 2010 2 10 1 NaN #4 2011 2 ...
python|pandas
0
21,108
66,230,457
Python: how to remove values from array
<p>I have this array in my code however I need to remove the rows that contain zeros (in this case the third row and the fourth). I have tried some options but all without success, can someone suggest something for me to solve this problem?</p> <p>I leave below the array:</p> <pre><code>print(AA) array([[2.40258090e+01...
<h3>Value Based:</h3> <p>To filter an array by value, boolean masking can be used as:</p> <pre><code>a[(a[:,0] != 0) &amp; (a[:,1] != 0)] </code></pre> <p>This filters array <code>a</code> to keep only rows where values in columns <code>0</code> <em>and</em> <code>1</code> are not zero; using the bitwise <code>&amp;</c...
python|arrays|numpy|numpy-ndarray
2
21,109
66,037,389
Tensorflow: How to define custom metrics for LSTM stock prediction model
<p>I'm trying to make a stock price prediction model using lstm. It is very rare that the predicted price and the actual stock price match exactly, so I tried to calculate the accuracy by dividing the number of predictions that came within a certain range(ex. 3%) by a total number of predictions.</p> <p>I thought accur...
<h3>Disclaimer</h3> <p>First of all, never mix <code>pytorch</code> and <code>tensroflow</code>, it's good for your hardware, your program and also your health, to use just one of those.</p> <h3>Hacky Solution</h3> <p>You can use <code>tf.shape(y_pred)</code> and extract the dimension you are looking for (should be the...
python|tensorflow
2
21,110
66,103,551
Reshape pandas dataframe which has dict as values
<p>I have a pandas dataframe which has dict as values. I would like to transform this dataframe into the format in expected result.</p> <p><img src="https://i.stack.imgur.com/DXRbm.png" alt="image of the df i have" /></p> <p>and i want to split the columns into each keys of the dict. For example for the first columns '...
<p>Is the column value in the format of type <code>string</code> ? If it is then you can try this. I tried this on a dataframe and it worked. Iterate over each column values convert them from <code>str</code> to <code>dict</code> then iterate over those values create a new column with key value and assign the value to ...
python|pandas|dictionary|reshape
1
21,111
52,728,493
numpy - vectorize functions: apply_over_axes / apply_along_axis
<p>I want to calculate the determinant of m<em>m subarrays of a m</em>m*n dimensional arrays, and would like to do this in a fast/more elegant way. The brute-force approach works:</p> <pre><code>import numpy as n array=n.array([[[0.,1.,2.,3.],[2,1,1,0]],[[0.5, 0.5,2,2],[0.5,1,0,2]]]) detarray=n.zeros(4) for i in rang...
<p>Utilizing the <a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.transpose.html" rel="nofollow noreferrer">transpose semantics of NumPy</a> for 3D arrays, you can simply pass the transposed array to <a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.linalg.det.html" re...
python|numpy|array-broadcasting
2
21,112
52,483,935
Titanic Machine Learning Problem using Logistic Regression
<p>I'm an aspiring data scientist. I stumbled across the titanic data set. I tried to use logistic regression for the problem. However I get stuck while trying to fit the logistic regression model on the training set. Here is my code below:</p> <pre><code>#importing the libraries import numpy as np import matplotlib.p...
<p>You need to cast label outcome <code>Y.Survived</code> to <code>float</code>. The following code just runs:</p> <pre><code>Titanic_train = pd.read_csv('train.csv').values Titanic_test = pd.read_csv('test.csv').values columns = ['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch', 'Ticket', ...
python|pandas|numpy|machine-learning|scikit-learn
1
21,113
52,748,464
Python/Pandas - Cumulative Sum with Interest
<p>Attempting to do some forecasting in pandas. I have a revenue schedule of monthly payments coming in and want to do a cumulative sum of the total - this I can esily do with <code>.cumsum()</code>. <strong>However I would like to add a 5%pa Interest/Growth factor.</strong></p> <p>Example df:</p> <pre><code>Month ...
<p>Here's a quick try:</p> <pre><code>def interest(data, rate): #turn yearly to monthly rate monthly = rate/12.0 #hole output out = np.zeros_like(data, dtype = float) #initial deposit out[0] = data[0] for i in range(1, len(data)): #t+1 = t*(1+monthly) + deposit out[i] = out[...
python|pandas|numpy
0
21,114
46,255,730
Advanced python/pandas pivoting and filtering?
<p>I have a dataset with information on clients, on which products they spend money and how much money they spend. i.e.</p> <ul> <li>client_name: string</li> <li>product: [A,B,C]</li> <li>profit: float</li> </ul> <p>looking kinda like this:</p> <pre><code> Clients Products Profit 0 client 1 A 100 1 cl...
<p>Since you have the sum you can get the clients who have profit more than 300 and convert them to list. Reset the index after finding the percent of profit from products to select client and products. </p> <p>Later you can do boolean indexing based on the list we got earlier whose profit is greater than 50 and produ...
python|pandas
1
21,115
58,303,497
Count unique slices in a ndarray
<p>I have a 3D integer tensor <code>X</code> with <code>X.shape=(m, n, k)</code> </p> <p>I'd like to treat <code>X</code> as a <code>(m, n)</code> matrix with entries that are <code>k</code> sized integer vectors and count how many such unique entries are in each row. So for example</p> <pre><code>&gt;&gt;&gt; X arra...
<pre><code>unique_list = [] for sublist in X: tmp_unique_list = [] for element in sublist: if element not in tmp_unique_list: tmp_unique_list.append(element) unique_list.append(tmp_unique_list) </code></pre> <p>Output:</p> <pre><code>&gt; unique list [[[0, 1, 2], [1, 2, 3]], [[3, 4,...
python|numpy
0
21,116
58,326,502
How to plot a stacked bar using the groupby data from the dataframe in python?
<p>I am reading huge csv file using pandas module.</p> <p><code>filename = pd.read_csv(filepath)</code></p> <p>Converted to Dataframe,</p> <p><code>df = pd.DataFrame(filename, index=None)</code></p> <p>From the csv file, I am concerned with the three columns of name country, year, and value. I have groupby the cou...
<p>from what i understand you should try something like :</p> <p><code>df.groupby(['country', 'Year']).value.sum().unstack().plot(kind='bar', stacked=True)</code></p>
pandas|python-2.7|matplotlib|visualization|stacked-chart
1
21,117
68,955,129
pandas numpy : setting an array element with a sequence while math operation
<p>I have a df named df4,you can get it buy following code:</p> <pre><code>df4s = &quot;&quot;&quot; contract RB BeginDate ValIssueDate EndDate Valindex0 48 46 47 49 50 2 A00118 46 19850100 19880901 99999999 50 1 2 3 7 7 3 A00118 47 19000100 19880901 19831231 47 1 2 ...
<p>Reconstructing your dataframe (thanks for using the <code>StringIO</code> approach)</p> <pre><code>In [82]: df4['RB'].values Out[82]: array([46, 47, 47, 48, 48, 48, 50, 50, 50]) In [83]: test(46) Out[83]: array([42, 42, 42, 42, 42, 42, 42, 42, 42]) In [84]: test(50) Out[84]: 1 In [85]: [test(i) for i in df4['RB'].va...
python|pandas|dataframe|numpy|numpy-ndarray
1
21,118
71,765,975
How can I fix this problem of automated differentiation with Tensorflow?
<p>I need to compute the gradient wrt a loss for the variables of a defined neural network, the loss is computed correctly but the gradients are None. The code is the following:</p> <pre class="lang-py prettyprint-override"><code>variables = self.model.trainable_variables for var in variables: print(&quot;{}&quot;.f...
<p>Direct indexing <code>y[actions[t]]</code> is not differentiable, so your loss tensor is disconnected from the graph.</p> <p>You can rewrite your code to produce the loss for all elements, but use an input binary <code>mask</code> to select only one element. This way your final loss is connected to all inputs (<code...
python|tensorflow|automatic-differentiation
1
21,119
42,358,829
Is there a way to color values in a dataframe if the belong to a certain range (Python-Pandas)
<p>I have a data frame with values from 0 to 10. I would like to color the value 1 and 5 with red rather than black. Is that possible to do it in python DataFrame? I am using Jupyter notebook. </p>
<p>You can change the <code>style</code> of cells - </p> <pre><code>df = pd.DataFrame({'v1': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}) dft = df.style.applymap(lambda x: 'color: red' if x &gt;= 1 and x &lt;=5 else 'color: black') dft </code></pre> <p>You can find more information about applying styles here - <a href="http:...
python-3.x|pandas|jupyter-notebook
3
21,120
42,451,387
Converting my column to 2 decimal places
<p>I have a dataset:</p> <pre><code>df = pd.read_excel('/Users/Adeel/Desktop/ECON628-01-omerqureshi84/datasets/main-data.xlsx') </code></pre> <p>It has columns with names such as "lerate" which is the log of the exchange rates for countries. It's in 5 decimal places and and I'm trying to convert it to 2 decimal place...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.round.html" rel="noreferrer"><code>round</code></a>:</p> <pre><code>df.lerate = df.lerate.round(2) </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame(np.random.random([3, 3]), co...
python|pandas|decimal
9
21,121
69,927,810
Use np.fromfile to read data with specific behavior
<p>For example, let's say I have a file with the following binary data:</p> <pre><code>0x01 0x02 0x03 0x04 </code></pre> <p>I want to create a custom dtype <code>my_type</code> that will behave as following:</p> <pre><code>&gt;&gt; np.fromfile(..., dtype=my_type, count=2) np.array([3, 7]) </code></pre> <p>I.e. the cust...
<p>Rather than creating a new data type I would instead use <code>np.loadtxt</code> with a converter:</p> <pre><code># Example input: s = io.StringIO('0x01 0x02 0x03 0x04') # Read the file x = np.loadtxt(s,delimiter=' ',converters={0:lambda s: int(s,16)}) # Sum the result 2 by 2. x = x[::2]+x[1::2] </code></pre> <p>And...
python|numpy
1
21,122
69,918,785
How to get values using pd.shift
<p><a href="https://i.stack.imgur.com/LIDvQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LIDvQ.png" alt="enter image description here" /></a></p> <p>I am trying to populate values in the column <code>motooutstandingbalance</code> by subtracting the previous row <code>actualmotordeductionfortheweek...
<p>This works:</p> <pre><code>start_value = 468300.0 df['motooutstandingbalance'] = (-df['actualmotordeductionfortheweek'][::-1]).append(pd.Series([start_value], index=[-1]))[::-1].cumsum().reset_index(drop=True) </code></pre> <p>Basically what I'm doing is I'm—</p> <ol> <li>Taking the <code>actualmotordeductionforthew...
python|pandas|numpy
0
21,123
69,689,289
Python Numpy how to change the data types inside an array
<p>I am trying to calculate information from an array that contains integers, however when I do a calculation the results are foat's. How do I change the ndarry to accept 0.xxx numbers as a input. Currently I am only getting 0's. Here is the code I have been trying to get working:</p> <pre><code> ham_fields = np...
<pre><code>ham_fields = np.array([], dtype=float) ham_fields = data[data[:, 0] == 0] ham_sum = np.delete((ham_fields.sum(0)),0) </code></pre> <p>This line assigns a new array object to <code>ham_fields</code>. The first assignment did nothing for you. In Python variables are not declared at the start.</p> <p>If <...
python|arrays|numpy
2
21,124
43,152,312
Plot a row in Panda/Python
<p>I know it can look basic but I didnt find anything about it... </p> <p>In panda I have a dataframe with one row only. the index is a date and the columns are the date, the data are regular figures... </p> <p>I want to plot all the row... any idea? </p> <pre><code> 2017-03-23 2017-03-22 2017-03-21 20...
<p>You have to select a row by it index and then plot:</p> <pre><code>row = df.iloc[0] row.plot() </code></pre> <p><a href="https://i.stack.imgur.com/cOH0Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cOH0Q.png" alt="enter image description here"></a></p>
python|pandas|plot|row
4
21,125
72,413,410
Transform xyz data into surface for Plotly
<p>I have a text file with xyz data called <code>elevation.txt</code>.</p> <pre><code>29.6615067663688 -98.3933654143067 -0.772875302700243 29.6615067663688 -98.3933757636723 -0.71250410914962 29.6615065076668 -98.3933654143067 -0.757068728178126 29.6615032793597 -98.3933757636723 -0.761051993140882...
<p>The <code>Surface</code> class expects the points to be spaced linearly across both <code>x</code> and <code>y</code> (like those that would be created by <code>np.linspace</code>, examples <a href="https://plotly.com/python/3d-surface-plots/" rel="nofollow noreferrer">here</a>). It appears that your data is a set o...
numpy|plotly
0
21,126
72,296,017
The streamlit does not refresh the dataframe on the localhost
<p>I am New in pandas and streamlit , What I am trying is to filter such a dataframe using streamlit selectbox but unfortunately everything is going well except that when changing the filter value it does not reflect on the shown table</p> <p><a href="https://i.stack.imgur.com/V4Ad4.jpg" rel="nofollow noreferrer"><img ...
<p>Here is a sample code with example data.</p> <h3>Code</h3> <pre><code>import streamlit as st import pandas as pd data = { 'Name': ['a', 'b', 'c'], 'halka': [1, 2, 3] } st.set_page_config(page_title='makraa reports',layout='wide') folderDF = pd.DataFrame(data) # make filteration # st.sidebar.header(&qu...
python|pandas|streamlit
0
21,127
72,376,495
Optimizing the creation of a non-numeric matrix with NumPy
<p>As I was trying to find a way to optimize the creation and printing of a huge 2D matrix, I decided to try out NumPy. But, unfortunately for me, using this library on the contrary makes the situation worse. My goal is to create a matrix that will be filled with strings with its index. Something like this (where <code...
<p>Running an <code>ipython</code> session and using its <code>timeit</code>, I don't get such large differences:</p> <p>Making the list:</p> <pre><code>In [13]: timeit [[f&quot;{y}, {x}&quot; for y in range(N)] for x in range(N)] 492 ms ± 3.28 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) </code></pre> <p>Maki...
python|numpy|matrix
0
21,128
50,533,797
Get indices of N maximum values in a numpy array without sorting them?
<p>My question is very similar to this one: <a href="https://stackoverflow.com/questions/6910641/how-to-get-indices-of-n-maximum-values-in-a-numpy-array">How to get indices of N maximum values in a numpy array?</a></p> <p>But I would like to get the indices in the same order I find them. </p> <p>Let's take the exampl...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argpartition.html" rel="nofollow noreferrer"><code>numpy.argpartition()</code></a>:</p> <pre><code>k = 3 np.argpartition(arr, len(arr) - k)[-k:] </code></pre> <p>Adjust <code>k</code> index to whatever you need.</p> <p>NOTE: returned indices ...
python|numpy
4
21,129
45,447,621
Create a unique indicator two join two datasets in pandas/python
<p>How can I combine four columns in a dataframe in pandas/python to create a unique indicator and do a left join?</p> <p>Is this even the best way to do what I am trying to accomplish?</p> <pre><code>example: make a unique indicator (col5) then setup a join with another dataframe using the same logic col1 col2 ...
<p>This problem is the same whether its 4 columns or 2. You don't need to create a unique combined key. You just need to <code>merge</code> on multiple columns.</p> <p>Consider the two dataframes <code>d1</code> and <code>d2</code>. They share two columns in common.</p> <pre><code>d1 = pd.DataFrame([ [0, 0, 'a...
python|pandas
0
21,130
45,536,724
Move from Matlab to Python numpy
<p>I am new to python so by gentle with me , I try to convert code from Matlab to numpy python , I am working with matrix .</p> <p>I have some basic question (that I didn't found the answers in Google):</p> <p>What is the equivalent for the ' tag for example : H' , H= H*H'</p> <p>What is the equivalent for the / (mr...
<ul> <li><p><a href="https://se.mathworks.com/help/matlab/ref/transpose.html" rel="nofollow noreferrer"><code>'</code> (transpose)</a> means the <em>conjugate</em> transpose of a matrix. For real matrices, it is given by <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html" rel="nofollow n...
python|matlab|numpy
4
21,131
62,622,748
why is function not applying to dataframe? Series object has no attribute called query (Pandas)
<p>I have a dataframe user and calls where common column is user_id. I need to drop values in user dataframe where churn is not null and remove those user_id rows in calls.</p> <pre><code>users = user_id,first_name,last_name,age,city,reg_date,plan,churn_date 1000,Anamaria,Bauer,45,&quot;Atlanta-Sandy Springs-Roswell, G...
<p>When you running <code>calls.apply(some_action, axis=1)</code>, it would call function <code>some_action</code> to all rows of your dataframe <code>calls</code>.</p> <p>So you should either change your <code>new</code> function to work with <code>pd.Series</code> of rows, either filter users using anohter techniques...
python|pandas|numpy|dataframe|data-science
1
21,132
62,651,236
Comparing strings in two columns to produce new column
<p>I have a dataframe with two columns: &quot;names&quot; (~10 characters per entry) and &quot;articles&quot; (~20,000 characters per entry).</p> <pre><code> Names | Articles ---------------------------------------------------------------------------------------------- | ['Craig Johnson'] ...
<p>You can <code>explode</code> the column <code>Names</code>, create a mask with <code>zip</code> and finally <code>agg</code> the results back together:</p> <pre><code>df = pd.DataFrame({&quot;Names&quot;:[['Craig Johnson'],['Jim Billy', 'Bob Cob'],['Darth Vader']], &quot;Articles&quot;:[&quot;In t...
python|arrays|python-3.x|pandas|list
1
21,133
62,736,306
can't launch tensorboard from mac terminal
<p><strong>problem: I can't run &quot;tensorboard --logdir=summaries&quot; in my terminal because I get this error</strong></p> <ul> <li>system: macbook pro running Catalina</li> <li>environment: running pyenv with python3 as global</li> <li>package: I have tensorflow 2.2.0 installed via pip</li> <li>I have setuptools ...
<p>As it turns out I was not using Pyenv correctly. Once I used &quot;pyenv global system&quot; then I was able to update the pip packages correctly and the right setuptools was installed and TensorBoard ran as expected</p>
python|tensorflow|tensorboard
0
21,134
62,541,820
Restoring a multiband Image shape after passing through a Keras Flat layer
<p>I have an image containing 6 different bands.</p> <p>I have pre-processed the image to make it ready for the model as follows:</p> <pre><code>ds1, image = raster.read(imagePath, bands='all') </code></pre> <p>then I reshaped it with pyrsgis</p> <pre><code>image = changeDimension(image) </code></pre> <p>Finally, I spl...
<p>If anyone had the same issue, this was the solution</p> <pre><code>predicted = model.predict(featuresHyderabad) predictedArr = np.zeros(shape = ( nBands, imageHeight, imageWidth )) for i in range(nBands): prediction = np.reshape(predicted[:,i], (imageHeight, imageWidth)) predictedArr[i] = prediction raster.expo...
python|tensorflow|machine-learning|image-processing|keras
0
21,135
54,561,728
Define parameter in pyomo from pandas DataFrame
<p>First time pyomo user here.</p> <p>I have a function that defines a model</p> <pre><code>def define_problem(SET_gen, SET_time, SET_buses, demand): model = pyo.ConcreteModel() #Define sets model.SET_GEN = pyo.Set(initialize = SET_gen) #Set of generators model.SET_TIME = py...
<p>You seem to have this one covered, so I'm just providing a couple of suggestions:</p> <p>It's going to make your life much easier to just call the columns 1,2 etc. and call the <em>axis</em> <code>bus</code>, instead of calling each columns <code>"Bus1"</code> etc.</p> <pre class="lang-py prettyprint-override"><co...
python|python-3.x|pandas|optimization|pyomo
3
21,136
54,344,222
Plot two pandas dataframes in one scatter plot
<p>I have two dataframes with the same index and columns like:</p> <pre><code>import pandas as pd dfGDPgrowth = pd.DataFrame({'France':[2%, 1.8%, 3%], 'Germany':[3%, 2%, 2.5%]}, index = [2007, 2006, 2005]) dfpopulation = pd.DataFrame({'France':[100, 105, 112], 'Germany':[70, 73, 77]}, index = [2007, 2006, 2005]) </cod...
<p>Are you looking for something like this</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt dfGDPgrowth = pd.DataFrame({'France':[2, 1.8, 3], 'Germany':[3, 2, 2.5]}, index = [2007, 2006, 2005]) dfpopulation = pd.DataFrame({'France':[100, 105, 112], 'Germany':[70, 73, 77]}, index = [2007, 2006, 2005]...
python|pandas|dataframe|matplotlib
3
21,137
54,585,798
Using the items in the list as the name for empty pandas data frame
<p>I have a list as below </p> <p>list = ['df1','df2','df3']</p> <p>I want to create empty dataframes with these list items and I have tried the below</p> <pre><code>for i in list: str(i) = pd.DataFrame() </code></pre> <p>I would like to get 3 pandas dataframe created </p> <pre><code>df1 df2 df3 </code></pre> ...
<p>Use the <code>exec</code> function:</p> <pre><code>l = ['df1','df2','df3'] for x in l: exec('%s = pd.DataFrame()' %x) </code></pre>
python|pandas|list|dataframe
1
21,138
73,772,896
'Worksheet' object has no attribute 'set_column'
<p>I am trying to auto adjust the length of every header in my dataframe while converting it to an excel file like the following:</p> <pre><code>from pandas import ExcelWriter for k,v in final_1.items(): v.to_excel(writer, sheet_name=k, index=False) for column in v: column_length = ma...
<p>Pandas can use either openpyxl or xlsxwriter as &quot;engines&quot; for creating xlsx files with <code>to_excel()</code>.</p> <p>The <code>set_column()</code> method is a xlsxwriter method but the error message about the missing method/attribute indicates that pandas isn't using it, probably because it isn't install...
python|pandas|xlsxwriter
1
21,139
73,681,308
Creating network flow from Pandas DataFrame
<p>I have the following data frame for critical path problem:</p> <pre><code>Activity = ['A','B','C','D','E','F','G'] Predecessor = [None, None, None, 'A', 'C', 'A', ['B','D','E']] Durations = [2,6,4,3,5,4,2] df = pd.DataFrame(zip(Activity, Predecessor, Durations), columns = ['Activity','Predecessor','Du...
<p>The output you expect is not fully clear, but you can use <code>networkx</code> to create and handle your graph.</p> <p>Here is the graph:</p> <p><a href="https://i.stack.imgur.com/xiRfA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xiRfA.png" alt="enter image description here" /></a></p> <pre><...
python|pandas|algorithm|data-structures|network-flow
1
21,140
73,739,461
splitting array into 3 arrays
<p><strong>Note</strong>: please edit the title to be more reflective of the question; I could not come up with a way to phrase it.</p> <p>I have very large array; here is some sample data:</p> <pre><code>array([ 0.2952941 -0.22235294j, -0.4027451 +0.2090196j , -0.19882353+0.2717647j , 0.17764705-0.1282353j , ...
<p>If you know the shape of the array is a multiple of 3, you can reshape it into rows of 3 and transpose. This will give you the rows you want, which you can unpack if you choose to.</p> <pre><code>import numpy as np a = np.array([ 0.2952941 -0.22235294j, -0.4027451 +0.2090196j , -0.19882353+0.2717647j...
python|numpy
0
21,141
71,179,411
Fill in missing values for missing dates in dataframe
<p>I have the following dataframe:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame( { 'status': ['open', 'closed', 'open', 'closed', 'open', 'closed', 'open', 'closed'], 'month': ['January 2020', 'January 2020', 'February 2020', 'February 2020', 'April 2020', 'April 2020', 'Aug...
<p>You could pivot the dataframe, and then reindex with the desired months.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({'status': ['open', 'closed', 'open', 'closed', 'open', 'closed', 'open', 'closed'], 'month': ['January 2020', 'January 2020', 'Februa...
python|pandas|seaborn
2
21,142
71,330,615
Can you have more than two responses to np.where
<p>I have the following np.where statement</p> <pre><code>df['DCC'] = np.where((df['RxDate'] - df['ABdat']).dt.days &gt; 0, 0, df['DCC'] </code></pre> <p>If the difference between ABdat and RxDate &gt; 0 then it assigns 0 to DCC if not DCC remains as it was.</p> <p>If the difference between ABdat and RxDate &gt; 0 I ...
<p>I would do something like this:</p> <pre><code>mask = (df['RxDate'] - df['ABdat']).dt.days &gt; 0 df.loc[mask, ['DCC', 'AbcCode']] = [0,1] </code></pre>
python|pandas
1
21,143
71,381,577
Reading csv file row-by-row in pandas
<p>I have large piece of data that is problematic to load entirely to memory so I have decided to read it row-by-row, picking desired data, making transformations etc. and then clearing variables and pick another row.</p> <p>It works fine while I am using csv.reader.</p> <pre><code> source_file = open(path_to_source...
<p>the <code>csv</code> module also provides the <code>DictReader</code> method.</p> <pre><code>reader = csv.DictReader(csv_file) print(reader.fieldnames) </code></pre> <p>by default, columns names are inferred from the first row, alternatively you can specify what they should be by passing a sequence with the <code>fi...
python|pandas|csv
2
21,144
71,347,237
How to multiply all the elements in the pandas dataframe with int16 in python
<p>The pandas dataframe has seven columns with 100 rows.It is converted into numpy nd array using <code>arr = df.to_numpy()</code>.Now, I have to multiply each element with 2^15 to convert each value into int16 equivalent.The ndarray is given here with only 9 rows.</p> <pre><code>dtype: object [[ 0. 0. 0. 0...
<pre><code>df = pd.DataFrame(columns =['1Hz','2Hz', '3Hz', '4Hz', '5Hz', '6Hz', '7Hz']) df['1Hz']=(2**15) *pd.Series(get_values_for_frequency(1)) df['2Hz']=(2**15) *pd.Series(get_values_for_frequency(2)) df['3Hz']=(2**15) *pd.Series(get_values_for_frequency(3)) df['4Hz']=(2**15) *pd.Series(get_values_for_frequency(4)) ...
python|python-3.x|numpy|types|numpy-ndarray
1
21,145
60,351,094
Graph Is Empty..Python 2.7
<p>Please I need to rectify this, as it started recently for some days now. My grapgh shows empty, even though everything seems to be Ohk. When I print X, its 'NaN that displays. Here is the code: </p> <pre><code>import pandas as pd from pandas import DataFrame import matplotlib.pyplot as plt pd.set_option('display.m...
<p>It should be:</p> <pre><code>import pandas as pd from pandas import DataFrame import matplotlib.pyplot as plt pd.set_option('display.max_columns',10000) pd.set_option('display.width', 2000) pd.set_option('display.max_rows', 100000) pd.set_option('max_seq_items',1000) data=pd.read_csv('cost-revenue.csv') print dat...
python|pandas|dataframe|matplotlib|pycharm
0
21,146
60,616,925
Python numpy array of functions
<p>I've been looking for ways to avoid long "for" loops as I'll be dealing with mesh operations and was wondering if there was a way to make an array of functions. Something like the following would be nice.</p> <pre><code>x=np.array([1,2,3,4,5]) funcs=np.array([func1,func2,func3,func4],dtype=function) output=funcs(x...
<p>You can just create a list of functions and then use a list comprehension for evaluating them:</p> <pre><code>x = np.arange(5) + 1 funcs = [np.min, np.mean, np.std] output = [f(x) for f in funcs] </code></pre> <p>If you really think that <code>funcs(x)</code> reads nicer in your code, you can create a custom class...
python|numpy
3
21,147
59,531,137
Can i convert each unique Id of dataframe in list?
<p>I have dataframe something like this </p> <pre><code>| ID | M001 | M002 | M003 | M004 | |------|------|------|------|------| | E001 | 3 | 4 | 3 | 2 | | E002 | 4 | 5 | 5 | 3 | | E003 | 4 | 3 | 5 | 4 | </code></pre> <p>And I want output in list but something like this for each ...
<p>Something like that:</p> <pre><code>new_df = df.apply(lambda x: list(zip(df.columns, x)), axis=1) </code></pre> <p>Output:</p> <pre><code>ID E001 [(M001, 3), (M001, 4), (M001, 3), (M001, 2)] E002 [(M002, 4), (M002, 5), (M002, 5), (M002, 3)] E003 [(M003, 4), (M003, 3), (M003, 5), (M003, 4)] dtype: object ...
python|pandas|list
0
21,148
32,389,276
How to expand lists nested in DataFrame columns to their own columns
<p>I've just started working with the Pandas library for Python, and I've hit upon a problem that I can't work out.</p> <pre><code>dictionary = {key:list} series = pd.Series(dictionary) dataframe = pd.DataFrame(series) print(dataframe) </code></pre> <p>So the output is:</p> <pre><code> 0 key list key list key lis...
<p>You can directly create the DataFrame from the dictionary, but when creating that, the <code>keys</code> would become the column and <code>0</code>/<code>1</code> , etc would become the indices, if you want it the other way round - <code>keys</code> as indices and <code>0</code>/<code>1</code> , etc as columns - you...
python|list|pandas|dataframe
1
21,149
40,654,881
How to print current variables gradients values with vars names in TensorFlow?
<p>I want to print current variables gradients values together with names for all variables.</p> <p>I am using the following code:</p> <pre><code>import tensorflow as tf import numpy as np x_data = np.random.rand(100).astype(np.float32) y_data = x_data * 0.1 + 0.3 W = tf.Variable(tf.random_uniform([1], -1.0, 1.0), ...
<p>As you noted, <code>compute_gradients</code> returns list of pairs (gradient, value). To print the value of the gradient, you need to <code>run</code> it inside a session. The names of variables, on the other hand, are static, so you just need to do:</p> <pre><code>for step in range(201): sess.run(train) ...
tensorflow
5
21,150
40,493,759
Regular expression for na_values using pandas.read_csv
<p>I want to read a file like this using <code>pandas.read_csv</code> </p> <pre><code>1891, 91920, 7, 628,249, 59,51.0, 0.026, 0.028, NaN, NaN, NaN, NaN, NaN, 0.156, 0.071, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 21,500, 21,43.8, 0.005, 0.619, NaN,45.6, 0.048, 0.053, NaN, ...
<p>Try this:</p> <pre><code>df = pd.read_csv(engine='python', index_col=None, sep=',\s*', header=None) </code></pre> <p>The parsing engine is set to <code>python</code> to avoid a warning you get when you use regex as a separator.</p>
python|regex|pandas|nan
-1
21,151
40,668,180
python-Pandas df.sum() across multiple columns unexpected arg 'axis' error
<p>here I have a pandas Dataframe df like:</p> <pre><code> A B C 0 1 2 3 1 1 2 3 3 1 2 3 </code></pre> <p>Then I have a list</p> <pre><code>x=['B','C'] </code></pre> <p>I want to get the sum of each number of each row under B &amp; C columns. So I write like:</p> <pre><code>df[...
<p>It's hard to diagnose w/o a continuous example that demonstrate the error.</p> <p>If I start out with:</p> <pre><code>import numpy import pandas df = pandas.DataFrame( numpy.arange(9).reshape(3, 3), index=['a', 'b', 'c'], columns=['X', 'Y', 'Z'] ) print(df) </code></pre> <p>Which gives:</p> <pre><cod...
python|pandas|dataframe|typeerror
1
21,152
18,291,713
How to conditionally select items from a pandas Series
<p>I am using a Pandas Series which consists of lists of numbers, with words as the index:</p> <pre><code>$10 [1, 0, 1, 1, 1, 1, 1] $100 [0, 0, 0] $15 [1] $19 [0, 0] $1? [1, 1] $20 ...
<p>You should avoid using <code>list</code>s in <code>Series</code> objects, but you can do what you're asking like this:</p> <p><strong>EDIT:</strong> Usage</p> <pre><code># DON'T use `eval` in production I'm just using it for convenience here In [7]: s = read_clipboard(sep=r'\s{2,}', index_col=0, header=None, squee...
python|list|pandas|conditional|list-comprehension
3
21,153
18,326,524
Pass tuple as input argument for scipy.optimize.curve_fit
<p>I have the following code:</p> <pre><code>import numpy as np from scipy.optimize import curve_fit def func(x, p): return p[0] + p[1] + x popt, pcov = curve_fit(func, np.arange(10), np.arange(10), p0=(0, 0)) </code></pre> <p>It will raise <strong>TypeError: func() takes exactly 2 arguments (3 given)</strong>. ...
<p>Not sure if this is cleaner, but at least it is easier now to add more parameters to the fitting function. Maybe one could even make an even better solution out of this.</p> <pre><code>import numpy as np from scipy.optimize import curve_fit def func(x, p): return p[0] + p[1] * x def func2(*args): return func...
python|numpy|scipy|curve-fitting
8
21,154
61,868,760
Categorical Scatter Plot with Plotly
<p>I am trying to draw a scatter plot with numerical x-values that are discrete. The problem is that <code>Plotly</code> interprets the values as continuous and the resulting dots are not evenly spaced. In <code>Seaborn</code> I could solve this problem by converting the x-values to <code>str</code>, but this doesn't w...
<p>IIUC, in the <code>update_layout</code>, you can specify the <code>xaxis_type</code> to be <code>category</code> like:</p> <pre><code>fig = px.scatter( test_df, x=test_df.index, #no need of str here y=test_df, ) fig.update_layout(showlegend=False, xaxis_type='category') #add this </c...
python|pandas|plotly-express
5
21,155
61,967,512
Get from pandas datetime variable day and month
<p>I have daily data of 40 years in a pandas dataframe with columns[Index = Date, Data] and I would like to extract the data from each month with cumalative sum of the data contained in days in the order showed in the code below, that means I have to repeat that code 12 times (thats for each month). </p> <p>I would li...
<p>Here is a way that could get you started - your function appears to return a tuple of data, but what you pasted looks different, so you will still need to work on the exact format you need.</p> <pre><code># create mock data index=pd.DatetimeIndex(start='1/1/1962',end='1/1/1966',freq='D') data=pd.DataFrame(data={'...
python|pandas|python-datetime
0
21,156
61,957,293
Tensorflow Data Validation does not identify anomalies in numerical features
<p>I've been testing Tensorflow Data Validation (version 0.22.0) to use in my current ML pipelines and I noticed it does not get any anomaly in numerical features. For instance, </p> <pre><code>&gt; import pandas as pd &gt; import pyarrow &gt; import tensorflow as tf &gt; import apache_beam as beam &gt; import ap...
<p>We need use jensen_shannon_divergence skew comparator for Numerical Features and infinity_norm for Categorical Features</p> <p>tfdv.get_feature(schema_updated,'SALES').skew_comparator.jensen_shannon_divergence.threshold = 0.001</p> <p>skew_anomalies = tfdv.validate_statistics(statistics=new_dataset_stats, schema=sch...
python-3.x|tensorflow-data-validation
1
21,157
58,127,963
Compare 2 Dataframe and Find the Matching Rows
<p>I have a master Dataframe as:</p> <pre><code>Time Frq Seq 12:46:17 4200.0 30700.0 12:49:29 4160.0 30690.0 12:46:18 3060.0 30700.0 12:46:18 3060.0 30700.0 12:46:19 3060.0 30700.0 12:46:20 3060.0 30700.0 12:46:20 4240.0 30700.0 12:46:19 4220.0 30700.0 12:46...
<p>First remove duplicated in <code>master</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer"><code>DataFrame.drop_duplicates</code></a> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataF...
python|python-3.x|pandas
1
21,158
57,912,193
How to get a mapping of ids to their respective cluster?
<p>I did a clustering analysis using DBSCAN with random data for now. However, at the end I would like to the a mapping like this:</p> <pre><code>[Cluster, Total_users] [A,10] [B,6] [C,60] </code></pre> <p>The starting point is this code I have but at the end, the output is missing this list. Does somebody know what ...
<p>You could use </p> <pre class="lang-py prettyprint-override"><code>from collections import Counter, defaultdict print(Counter(model.labels_)) </code></pre> <p>The out put will be like</p> <pre><code>Counter({1: 5, 0: 2, -1: 2}) </code></pre> <p>where, </p> <p>label 0 has 2 elements<br> label 1 has 5 elements ...
python-3.x|pandas|cluster-analysis
0
21,159
58,033,350
Python `assert` function ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
<p>I am trying to write an <code>assert</code> function in Python to test whether the output of my function is a particular array of values. </p> <p>Using <code>assert simulate(15,0,3) == np.array([15.,15.,15.,15.])</code>, I get the following error:</p> <blockquote> <p><code>ValueError: The truth value of an array...
<p>the <code>assert</code> function doesn't work well when working with numpy. Use <code>allclose()</code> instead.</p> <p>this should work</p> <pre><code>print(np.allclose(simulate(15,0,3), np.array([15,15,15,15]))) </code></pre>
python|arrays|numpy|assert
0
21,160
58,116,575
Renaming Column Header with date
<p>I want to extract the date from the columns which have dates in it and keep them as a column header of those specific columns from which they were extracted. Also, all the previous column headers will be the first row. The Column headers where dates are present I wanted to extract those specific dates and keep them ...
<p>If I understood you correctly, you can do in this way:</p> <pre><code>import re from datetime import datetime for col in df.columns: try: match = re.search(r'\d{4}-\d{2}-\d{2}', col) date = datetime.strptime(match.group(), '%Y-%m-%d').date() except AttributeError: continue df.re...
python|pandas|dataframe
3
21,161
57,826,104
Calculating the angle between two 3D vectors
<p>I am trying to calculate the angle between two 3D vectors in python and for some reason I am getting two different answers depending on how I plug it into my code and was wondering if someone could look over it and see my mistakes.</p> <p>Lets just assume by vectors are numpy arrays [1, 2, 3] and [2 ,3, 4] for the ...
<p>I think the problem is in the maths rather than the code. Try <code>vectorA = [1, 0, 0]</code> and <code>vectorB = [0, 1, 0]</code> -> angle of 90°.</p> <p>I get <code>vector = [1, -1, 1] / sqrt(3)</code> -> angle of <code>acos(1 / sqrt(3))</code>.</p>
python|numpy|vector
0
21,162
57,951,650
Most efficient way to encode presence of elements of a list in another list
<p>Suppose I have a <strong>sorted</strong> main list like this: <code>main = ["a", "b", "cd", "e"]</code></p> <p>And a bunch of other lists like <code>l1 = ["a", "cd"]</code> and <code>l2 = ["b", "cd"]</code>. It's also guaranteed that all elements of the individual lists like <code>l1</code> and <code>l2</code> also...
<p>Here's one with <code>np.searchsorted</code> -</p> <pre><code>def isin_many(main, L): # main is the array or list where presence is to be detected # L is list of lists whose presence is to be detected main_ar = np.asarray(main) La = np.concatenate(L) sidx = np.argsort(main_ar) idx = sidx[np...
python|arrays|performance|numpy
2
21,163
34,220,521
how to extract pandas series element and compare it with rows in dataframe's column
<p>I have a following dataframe..</p> <pre><code> coupon_type dish_id dish_name dish_price dish_quantity 0 Rs 20 off 012 Sandwich 65 2 1 Rs 20 off 013 Chicken 125 3 2 Rs 20 off 013 Chicken 125 3 3 Rs 20 off ...
<p>Essentially you are looking to do a lookup for that we can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html#pandas.Series.map" rel="nofollow"><code>map</code></a> on the boolean series so the following will add a boolean flag:</p> <pre><code>df_final['Flag'] = df_final['dish...
python|pandas|series
2
21,164
34,402,378
Rounding error from array -> string -> array conversion
<p>I am trying to create an array by horizontally concatenating data in 4 columns, like so:</p> <pre><code>col1=numpy.arange(191.25,196.275,.001)[:, numpy.newaxis] nrows=col1.shape[0] col2=numpy.zeros((nrows,1),dtype=numpy.int) col3=numpy.zeros((nrows,1),dtype=numpy.int) col4=numpy.ones((nrows,1),dtype=numpy.int) a=...
<p>There fundamentally isn't really a solution to this. Generally speaking, a finite decimal string and a finite binary representation have no exact equivalents. Rounding errors will be accrued in such conversions, and rather than testing for exact equivalency, constructs like np.allclose will have to be used.</p>
python|arrays|string|numpy|rounding-error
0
21,165
36,963,502
Can't plot value counts for pie chart
<p>I wrote a function to plot the distribution of values for variables in a pie chart, as shown below. <a href="https://i.stack.imgur.com/AIDA3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AIDA3.png" alt="Pie chart I need to get"></a></p> <pre><code>def draw_piecharts(df, variables, n_rows, n_cols): ...
<p>While <code>value_counts</code> is a Series method, it's easily applied to the Series inside DataFrames by using <code>DataFrame.apply</code>. In your case. for example,</p> <pre><code>df[variables].apply(pd.value_counts).plot(kind='pie', layout=(n_rows,n_cols), subplots=True) </code></pre> <p>(assuming <code>pand...
python|pandas|dataframe|pie-chart|subplot
14
21,166
37,142,927
Cant install Numpy+MKL
<ol> <li><p>I have win10, x64, i7-3770K</p> <ol start="2"> <li>I downloaded numpy-1.11.0+mkl-cp35-cp35m-win_amd64.whl from the <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a></li> <li>I have python 3.5 installed from the official cite</li> <li>i hav...
<p>I have met the same problem as yours. It's pretty simple. </p> <p>The .whl file is Packaged by zip. So I check the file of *.whl and found it has a wrong size. A problem occurred when downloading the file. </p> <p>So try to download it again!</p>
python|python-3.x|numpy
1
21,167
28,100,714
Integrating differential with time-dependent arguments
<p>I've been trying to get an actual (start data value + Integral(0-t) result) value from a differential equation. The arguments of the equation are all time dependent. Below is an example of such an equation:</p> <pre><code>dx/dt = a + sin(b) + ln(c) + 5*x </code></pre> <p>I've tried integrating the equation with <...
<p>If performance is not of utmost importance you can just calculate the integral using an implementation of Euler forward. </p> <pre><code>steps = 10; tMin = 0; tMax = 5; dt = (tMax-tMin)/steps timeValues = [dt*i for i in range(steps)] aValues = [aFunc(t) for t in timeValues] bValues = [bFunc(t) for t in timeValues] ...
python|math|numpy|scipy|time-series
0
21,168
73,367,874
import pandas in visual studio(2022)
<p>My Environment in VS 2022 is Python 3.8 (same as the Python version installed on my system), I installed the pandas package using pip install pandas, and it said successfully installed. But when I import pandas I get the &quot;import pandas could not be resolved from source&quot; report. any help will be appreciated...
<p>Version mismatches problem:</p> <p>First you need to make sure that the python3 interpreter version from terminal version is the same with your python version selection in VSCode.</p> <ol> <li>Open terminal</li> <li>Type 'python3'; you'll see your python version (Eg. version x)</li> <li>Open your IDE VSCode</li> <li...
python|python-3.x|pandas|visual-studio
0
21,169
73,471,929
How to use OneCycleLR?
<p>I want to train on CIFAR-10, suppose for 200 epochs. This is my optimizer: <code>optimizer = optim.Adam([x for x in model.parameters() if x.requires_grad], lr=0.001)</code> I want to use OneCycleLR as scheduler. Now, according to the documentation, these are the parameters of OneCycleLR:</p> <pre><code>torch.optim.l...
<p>The documentation says that you should give <code>total_steps</code> or both <code>epochs &amp; steps_per_epoch</code> as arguments. The simple relation between them is <code>total_steps = epochs * steps_per_epoch</code>.</p> <p>And <code>total_steps</code> is the total number of steps in the cycle. <code>OneCycle</...
optimization|deep-learning|neural-network|pytorch|learning-rate
0
21,170
73,403,775
How to Filter 2 parameters with scatterplot and pandas dataframe
<p>I need to separate some data that I got. I'm using pandas DataFrame in order to do this.</p> <p>Here is the code before my problem:</p> <pre><code>import pandas as pd from sklearn.datasets import load_iris import matplotlib.pyplot as plt import seaborn as sns from sklearn.svm import LinearSVC from sklearn.metrics im...
<p>The system has somewhere shown to you that the class parameters are <code>b'Basmati'</code>, <code>b'Arborio'</code>, <code>b'Jasmine'</code>, <code>b'Ipsala'</code> and <code>b'Karacadag'</code>. However, this does not mean that the parameters are actually these characters inside a string. These are the <a href="ht...
python|pandas|scatter-plot
0
21,171
73,474,786
Creating repeating values using numpy.repeat
<p>I am Python newbie and trying to replicate an R script of the following form in Python.</p> <pre><code># set value for k k &lt;- 3 # script 1 R cnt &lt;- c(1,-1, rep(0,k-2)) print(cnt) 1 -1 0 # script 2 R for (i in 2:(k-1)) { cnt &lt;- c(cnt, c(rep(0,(i-1)),1,-1,rep(0,(k-i-1)))) } print(cnt) 1 -1 0 0 1...
<p>Your <code>repeat</code> makes an array.</p> <p>If we try to make a new array with integers and an array, we get:</p> <pre><code>In [23]: np.array([1,2,np.array([3,4])]) &lt;ipython-input-23-77cecd77c763&gt;:1: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of l...
arrays|python-3.x|numpy|repeat
1
21,172
73,389,438
how to print the value stored in a variable inside a class
<p>I want to print the data sored in self.datafame but it's not working inside the class and function and outside the class it gives me an error self is not defined. Anyone who know how to print it.</p> <pre><code>class CustomDataSet(Dataset): def __init__(self, csv_file, root_dir, transform): self.root_dir = root_...
<p>in your example you have</p> <pre><code> Traceback (most recent call last) Input In [33], in &lt;cell line: 19&gt;() 16 tensor_image = self.transform(image) 17 return tensor_image ---&gt; 19 print(self.dataframe) </code></pre> <p>As your error, which from what I'm seeing you are printing...
python|pandas|numpy
2
21,173
31,126,179
Compute separate correlations, grouped by column value
<p>Given 2 pandas dataframes,</p> <pre><code>A = pd.DataFrame({'one':['a','a','a','b','b','b'], 'two':[1,2,3,3,2,1]}) B = pd.DataFrame({'one':['a','a','a','b','b','b'], 'two':[4,3,2,2,3,4]}) </code></pre> <p>A</p> <pre><code> one two 0 a 1 1 a 2 2 a 3 3 b 3 4 b 2 5 b 1 </code></pre> <p>B<...
<p>One approach to iterate over the two groups would be:</p> <pre><code>x, y = A.groupby('one'), B.groupby('one') res = {i[0]:i[1].two.corr(y.get_group(i[0]).two) for i in x} pd.DataFrame(res.items()) # 0 1 #0 a -1 #1 b -1 </code></pre>
python|pandas
1
21,174
30,993,145
How can I copy a multidimensional h5py dataset to a flat 1D Python list without making any intermediate copies?
<h1>The question</h1> <p>How can I copy the data from an <code>N x N x N x...</code> h5py dataset over to a 1D standard Python list without making an intermediate copy of the data?</p> <p>I can think of a few different ways to do this with an intermediate copy. For example:</p> <pre class="lang-py prettyprint-overri...
<p>For numpy arrays I would suggest using ndarray.flat but h5py Datasets don't have a flat/flatten attribute.</p> <p>You could create a generator which brings chunks into memory as numpy arrays and then yields values from the flattened values. This could then be converted into a list. For instance to simply chunk al...
python|numpy|protocol-buffers|hdf5|h5py
1
21,175
30,964,409
Extract indices of a 2D binary array
<p>I have a numpy array (data) consisting of 0 and 1.</p> <pre><code>import numpy as np data = np.array([[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0], [1, 1, **1**, 1, 1, 0], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1]]) </c...
<p>Alternatively to <code>binary_erosion</code>, you could use the <code>scipy.ndimage.generic_filter</code> to achieve this,</p> <pre><code>from scipy.ndimage import generic_filter generic_filter(data, np.all, size=(5,5), mode='constant', cval=0).astype(np.bool) </code></pre> <p>However you would obtain the same res...
python|numpy|scipy|scikit-learn|scikit-image
2
21,176
67,223,868
pandas get first element of contigous values to perform sessionization i.e. obtain the sesion start event
<p>How can I find the first element of one of the sessions (for each group) which starts a new series of continuous values?</p> <pre><code>import pandas as pd df = pd.DataFrame({'group':[1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,], 'value':[ 1,2,3,4,5,10,11, 15, 16,17,18,19,20, # 13 21, 22,23,2...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.diff.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.diff</code></a> with compare not equal <code>1</code> and filter in <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boo...
python|pandas
1
21,177
67,397,331
Get cumulative sum and mean for specifc columns in pandas dataframe
<p>I have a dataframe:</p> <pre><code># create example df df = pd.DataFrame(index=[1,2,3,4,5,6]) df['ID'] = [1,1,1,2,2,2] df['election_date'] = pd.date_range(&quot;01/01/2010&quot;, periods=6, freq=&quot;M&quot;) df['stock_price'] = [1,2,3,4,5,6] # sort values df.sort_values(['election_date'], inplace=True, ascending=...
<p>We can <code>sort</code> the dataframe on <code>election_date</code> and create a sequeantial counter using <code>groupby</code> and <code>cumcount</code>, then divide this <code>counter</code> by the cumulative sum per <code>ID</code> to get the cumulative mean</p> <pre><code>df = df.sort_values('election_date') gr...
pandas|dataframe|count|sum|aggregate
4
21,178
34,735,623
SQLite3 with Python and Pandas slows down when adding lots of data
<p>I am trying to use Pandas' df.to_sql and SQlite3 in python to put about 2GB of data with about 16million rows in a database. My strategy has been to chunk the original CSV into smaller dataframes, perform some operations on them, and then throw them into an SQL database.</p> <p>As I run this code, it starts out fas...
<p>Solution: set <code>df.to_sql</code> argument to <code>index = False</code></p> <p>So I know this answer will no longer be relevant to the author, but I stumbled across it because I had exactly the same problem and wanted to share my answer.</p> <p>I was trying to load ~900 .csv files into an sql database one by one...
python|database|pandas|sqlite
2
21,179
60,104,689
finding the position of an element within a numpy array in python
<p>I want to ask a question about finding the position of an element within an array in Python's numpy package. </p> <p>I am using Jupyter Notebook for Python 3 and have the following code illustrated below:</p> <pre><code>concentration_list = array([172.95, 173.97, 208.95]) </code></pre> <p>and I want to write a bl...
<p>You can go through the <code>where</code> function from the <code>numpy</code> library</p> <pre><code>import numpy as np concentration_list = np.array([172.95, 173.97, 208.95]) number = 172.95 print(np.where(concentration_list == number)[0]) Output : [0] </code></pre>
python|numpy
2
21,180
59,972,650
I have a figure with 2 axes, how do I make them have the same scale in y axis in matplotlib?
<p>This is the code. The two axes have two different scales. (ax1 has both negative and positive values and ax2 has only negative values). The graph should be such a way that ax1 would have one line(the positive points) on top of the x-axis and the other line (with negative x-ticks) under the x-axis. Same for ax2.</p> ...
<p>To specify the same y-axis limits for both figures, you can use <code>set_ylim</code>:</p> <pre><code>ymin, ymax = 0, 100 # Change these to whatever values you require ax1.set_ylim(ymin, ymax) ax2.set_ylim(ymin, ymax) </code></pre> <p>You could also use the minimum and maximum of the default y-limits generated by...
python|pandas|numpy|matplotlib|graph
1
21,181
60,134,193
How do split columns of csv file after importing in jupetyr notebook?
<p>I have imported the csv file onto jupetyr notebook, but i am unable to visualize properly </p>
<p>Use pandas library and read your data as a DataFrame:</p> <pre><code>import pandas as pd dataframe = pd.read_csv('\filepath') </code></pre> <p>Then you visualize your columns as:</p> <pre><code>dataframe.columns </code></pre> <p>or you can visualize a snapshot of your data like this:</p> <pre><code>dataframe.he...
python|pandas|csv
0
21,182
65,094,838
pandas multiple independent indexes(not multi index)
<p>I have few large pandas <code>data frames</code> in python and would like to improve the speed of join operations by adding <code>index</code>. In the similar lines of adding index to a <code>database table</code>.</p> <p>What i see when searched is only <code>multi-index</code> options. which it looks like a <code>...
<p>Well, As you looked, You can use multilevel index in df but if you want independent indexes on specific column, you can apply a trick by setting and resetting index as before joining operation.</p>
python|pandas
0
21,183
49,941,717
Tensorflow Create Dataset from csv and mapping
<p>I try to create a Dataset for Tensorflow from a CSV file that I created with pandas. </p> <p>The csv file looks like this:</p> <pre><code>feature1 feature2 filepath label 0.25 0.35 test1.jpg A 0.33 0.15 test2.jpg B </code></pre> <p>I read the dataframe lik...
<p>The mapping function should return all features and the label. For example:</p> <pre><code>def mappingfunction(feature,label): print(feature['Filename']) image = tf.read_file(feature['Filename']) image = tf.image.decode_image(image) features['image'] = image return features, label </code></pre> ...
python|dictionary|tensorflow|dataset
0
21,184
50,213,967
numpy slicing and indexing different results
<p>In numpy subarrays obtained through any of slicing, masking or fancy indexing operations are just views to the original array, which can be demonstrated as follows:</p> <pre><code>$ python3 Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" ...
<p>It's not a bug. As far as you pass a slice object to Numpy array the returned sub array is a view of the original items which means that even slice assignment or single item assignments will change the original array. But in other cases the returned result is not a view. It's, in fact, a shallow view (copy) of the c...
python|numpy|sub-array
2
21,185
46,688,733
python script converting .dat to json
<p>I have .dat file that I want to use in my script which draws scatter graph with data input from that .dat file. I have been manually converting .dat files to .csv for this purpose but I find it not satisfactory. This is what I am using currently.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt im...
<p>try using the numpy read feature</p> <pre><code>import numpy as np yourArray = np.fromfile('YourData.dat',dtype=dtype) yourArray = np.loadtxt('YourData.dat') </code></pre> <p>loadtxt is more flexible than fromfile</p>
python|json|numpy|matplotlib|graph
0
21,186
46,851,600
Open .h5 file in Python
<p>I am trying to read a h5 file in Python.</p> <p>The file can be found in <a href="https://github.com/yhilpisch/py4fi/tree/master/ipython/source" rel="noreferrer">this link</a> and it is called 'vstoxx_data_31032014.h5'. The code I am trying to run is from the book Python for Finance, by Yves Hilpisch and goes like ...
<p>In order to open a HDF5 file with the <code>h5py</code> module you can use <code>h5py.File(filename)</code>. The documentation can be found <a href="http://docs.h5py.org/en/latest/" rel="noreferrer">here</a>.</p> <pre><code>import h5py filename = "vstoxx_data_31032014.h5" h5 = h5py.File(filename,'r') futures_dat...
python|pandas|h5py
11
21,187
62,957,536
For loop in numpy 3d arrays
<p>I want to take a basic 3d array like this:</p> <pre><code>b = np.arange(1,101).reshape(4,5,5) b </code></pre> <p>Then I want to take the first index, and work down like a stairs.</p> <pre><code>b1 = [b[0:,0,0],b[0:,1,1],b[0:,2,2],b[0:,3,3],b[0:,4,4]] b1 = np.asarray(b1) b1 = np.transpose(b1) b1 </code></pre> <p>The ...
<p>You may use list comprehension:</p> <pre><code>b1 = [b[0:,i,i] for i in range(5)] b1 = np.asarray(b1) b1 = np.transpose(b1) </code></pre>
python|arrays|numpy|numpy-slicing
0
21,188
63,155,829
Compare two dataframes with different size and create a new column in Pandas
<p>I've a large dataframe as shown below:</p> <pre><code>df1: Date Code ab-ret 0 1997-07-02 11 NaN 1 1997-07-04 11 NaN 2 1997-07-07 11 NaN 3 1997-07-08 11 NaN 4 1997-07-10 11 NaN ... ... ... ... 377395 2017-12-22 5757 -0.046651 377396 2017-12-2...
<p>It is a <code>merge</code> operation, use the parameter <code>indicator=True</code> to get a column named '_merge' close to the column 'Match' you want to create. Then just need to convert this column to False/True like in your expected output and <code>drop</code> the _merge column.</p> <pre><code>df1 = (df1.merge(...
python|pandas|numpy|dataframe
1
21,189
62,907,693
pandas date time function on multiple columns timezones
<p>I have a dataframe z2 with columns utc_time and timezone. I want to make a new column that takes the UTC epoch time and returns date time based on the timezone in column timezone. I am also using the function timezone from pytz. I want to apply this function below to the whole data frame (a few million long) in reas...
<p>Since you only have 4 timezones, you should be fine with looping those. You can use <code>.loc</code> to select the according rows and localize. Ex:</p> <pre><code>import pandas as pd # example df: df = pd.DataFrame({'UTCtime': ['2020-03-01T12:00:00', '2020-07-01T12:00:00'], 'Timezone': ['US/Pacif...
python|pandas|datetime
0
21,190
63,208,223
Python pandas creating an uneven multiindex
<p>I have the following code,</p> <pre><code>IDX_VALS_BANKNOTER_PATRIMONY = [['PATRIMONY'],['GOLD']] IDX_VALS_BANKNOTER_ASSETS = [['ASSETS'],['DEPOSITS', 'ADVANCES']] IDX_VALS_BANKNOTER_LIABILITIES = [['LIABILITIES'], ['CLIENTS', 'SUPPLIERS']] IDX_BANKNOTER_PATRIMONY = pd.MultiIndex.from_product(IDX_VALS_BANKNOTER_PAT...
<p>code:</p> <pre><code>import pandas as pd IDX_VALS_BANKNOTER_PATRIMONY = [['PATRIMONY'],['GOLD'], ['']] IDX_VALS_BANKNOTER_ASSETS = [['ASSETS'],['DEPOSITS', 'ADVANCES'], ['']] IDX_BANKNOTER_PATRIMONY = pd.MultiIndex.from_product(IDX_VALS_BANKNOTER_PATRIMONY) IDX_BANKNOTER_ASSETS = pd.MultiIndex.from_product(IDX_VAL...
python|pandas|dataframe
2
21,191
67,825,452
Extract data after a special character in python
<p>I have a dataset where I would like to extract anything that is after the underscore</p> <p>Data</p> <pre><code>id type a h_bu a zz_db b v_ssc c i_db-nd c i_db-nd </code></pre> <p>Desired</p> <pre><code>id type alias a h_bu bu a zz_db db b v_ssc ssc c i_db-nd db c i_db-nd db </code></...
<p>Using Regex.</p> <p><strong>Ex:</strong></p> <pre><code>df['alias'] = df['type'].str.extract(r&quot;(?&lt;=_)([\w]+)&quot;) # OR r&quot;(?&lt;=_)([a-z]+)&quot; print(df) </code></pre> <p><strong>Output:</strong></p> <pre><code> id type alias 0 a h_bu bu 1 a zz_db db 2 b v_ssc ssc 3 c i_db...
python|pandas|numpy
1
21,192
67,850,463
Printing a data frame in Pandas and Python
<p>I am new to pandas and trying to solve a problem of a basic code to form a data frame. I wrote two rows the data frame to try, but it is not working. I do not know the problem is about the continuation of the dictionaries and the list on the new line or something else. Do I need to use backslash when moving to the n...
<p>Your problem is syntax error with the ‘defense’ key element. There is a missing apostrophe.</p> <pre><code>data = [{'#':1, 'Name': 'BS', 'Type 1': 'grass', 'type 2': 'poison', 'Total': 318, 'HP': 45, 'Attack': 49, 'Defense': 49, 'Sp. Atk': 65, 'Sp. Def': 65, 'Speed': 45, 'Generation': 1, 'Legendary':'false...
python|pandas
3
21,193
67,619,828
Numpy splitting into array based on division
<p>I want to have something that could split an 1-D array :</p> <p><code>np.array([600, 400, 300, 600, 100, 0, 2160])</code></p> <p>into a 2-D array based on a value, e.g. 500 such that the resulting array should look like</p> <pre><code>500 | 100 | 0 | 0 | 0 400 | 0 | 0 | 0 | 0 300 | 0 | 0 | 0 | ...
<p>It's a min/max problem not division.</p> <pre><code>import numpy as np arr = np.array([600, 400, 300, 600, 100, 0, 2160 ]) res = np.zeros( (7, 6), dtype = np.int64) res[:] = arr[:,None] res -= np.arange( 0, 3000, 500 ) # Subtract successive 500s from arr. res = np.clip( res, 0, 500 ) # Clip results to lie &gt...
python|arrays|numpy
6
21,194
67,670,614
How to convert column values to multiple rows for a csv in python
<pre><code>check_NUMBER,2021-12-01,2022-01-01,2022-02-01 1000M,24,17,22 1000M,24,83,55 </code></pre> <p>This is my example data. I want to convert it into:</p> <pre><code>check_NUMBER,dates,values 1000M,2021-12-01,24 1000M,2021-12-01,17 1000M,2021-12-01,22 1000M,2022-02-01,24 1000M,2022-02-01,83 1000M,2022-02-01,55 </c...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.melt.html" rel="nofollow noreferrer">df.melt</a></p> <p><strong>Code</strong></p> <pre><code>df.melt(id_vars='check_NUMBER', var_name='dates', value_name='values') </code></pre> <p><strong>Output</strong></p> <pre><code>check_NUMBER dates values 0...
python|python-3.x|pandas|dataframe|numpy
2
21,195
31,690,076
Creating large Pandas DataFrames: preallocation vs append vs concat
<p>I am confused by the performance in Pandas when building a large dataframe chunk by chunk. In Numpy, we (almost) always see better performance by preallocating a large empty array and then filling in the values. As I understand it, this is due to Numpy grabbing all the memory it needs at once instead of having to re...
<p>Your benchmark is actually too small to show the real difference. Appending, copies EACH time, so you are actually doing copying a size N memory space N*(N-1) times. This is horribly inefficient as the size of your dataframe grows. This certainly might not matter in a very small frame. But if you have any real size ...
python|pandas
34
21,196
31,855,010
Create pandas dataFrame from two other using append
<p>I am preparing a dataframe from two other dataframes so I later can use to_csv to export the results into csv file ,but the resulting dataframe is empty despite that the input row of datatype <code>&lt;class 'pandas.core.series.Series'&gt;</code> isn't empty, here is how I am doing that: </p> <pre><code>def writeCS...
<p><code>pandas.DataFrame.append(other)</code> "Appends rows of <code>other</code> to the end of this frame, <strong>returning a new object</strong>."</p> <p>In other words, it does not change the object at hand. You are calling <code>append</code> and dropping the result on the bit floor. If you want to append to the...
python|pandas
1
21,197
41,325,955
python - pandas: count identical values per row
<p>I have a dataframe such as follow:</p> <pre><code> investing.com ft bloomberg 19 API Weekly Distillates Stocks NaN NaN 20 API Weekly Gasoline Stock ...
<p>The count method does exactly this. Use it with axis=1 to add a column.</p> <pre><code>df.count(axis=1) </code></pre>
python|pandas
3
21,198
61,226,553
How to multiply rows of list by another list?
<p>I have two lists (<code>l1</code>, <code>l2</code>) with arbitrary dimensions, say <code>l1.shape = (3,2)</code> and <code>l2.shape = (2,2,2)</code>. </p> <pre><code>l1 = np.array([[1, 10], [2, 20], [3, 30]]) l2 = np.array([[[1, 2], [3, 4]], [[5, 6],...
<p>Try the following,</p> <pre><code>(l1[:,:,None,None]*l2.T).swapaxes(1,3) </code></pre> <p>This should give you the desired output</p>
numpy|multidimensional-array|matrix-multiplication
0
21,199
61,440,229
Car Detection(Mask R CNN), How can I find the direction that car is moving?
<p>I trained a model (Mask R-CNN) that uses instance segmentation and detects cars. Now I want to find the direction that the car is moving. The example from my model is here: <a href="https://i.stack.imgur.com/zbxsL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zbxsL.jpg" alt="enter image descript...
<p>A lot of work has been done on feature descriptors which would allow you to determine the direction of the cars. One such approach that I recently came across is <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjegcShuIbyAhVjkWoFHQU9Cyk...
python|tensorflow|image-processing|keras|computer-vision
1