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
7,400
47,317,141
pytorch, AttributeError: module 'torch' has no attribute 'Tensor'
<p>I'm working with <strong>Python 3.5.1</strong> on a computer having <strong>CentOS Linux 7.3.1611</strong> (Core) operating system.</p> <p>I'm trying to use <strong>PyTorch</strong> and I'm getting started with <a href="https://github.com/mila-udem/welcome_tutorials/blob/master/pytorch/1.%20The%20Torch%20Tensor%20L...
<p>The Python binary that you are running does not have <code>torch</code> installed. It <em>does</em> have a directory named <code>torch</code> on the module search path, and it is treated as a <a href="https://www.python.org/dev/peps/pep-0420/" rel="nofollow noreferrer">namespace package</a>:</p> <pre><code>$ pwd /s...
python|python-3.5|centos7|torch|pytorch
14
7,401
68,173,262
Pandas: How to get column names except those that matches a given list
<p>Assume I have a df:</p> <pre><code>df = pd.DataFrame({'day': range(1, 4), 'apple': range(5, 8), 'orange': range(7, 10), 'pear': range(9, 12), 'purchase': [1, 1, 1], 'cost': [50, 55, 60]}) day apple orange pear purchase...
<p>Use:</p> <pre><code>cols = df.columns.difference(['day', 'purchase', 'cost'], sort=False) </code></pre> <p>Or:</p> <pre><code>cols = df.columns[~df.columns.isin(['day', 'purchase', 'cost'])] df = df[cols] </code></pre>
python|pandas
2
7,402
68,134,127
Pandas is either not finding a specific row of data or is detecting it as an empty data frame
<p>I have a big chunk of data that needs to be ordered read and then merged using pandas, my problem is that I noticed that pandas was returning &quot;empty dataframe&quot; on specific rows.</p> <pre><code>info = pd.read_excel(&quot;01. US Books.xlsx&quot;) book3 = load_workbook(&quot;01. US Books.xlsx&quot;,data_only=...
<p>The problem is your filter:</p> <pre><code>desc = info[info[&quot;IDshorttext&quot;].isin([str(u)])] </code></pre> <p>Your Dataframe contains strings and integers. However, you always cast them as strings to compare them. Hence you are saying &quot;give me the line that contains '6068871', a string.&quot; But there ...
python|pandas|dataframe
0
7,403
68,358,218
Pandas - merging start/end time ranges with short gaps
<p>Say I have a series of start and end times for a given event:</p> <pre><code>np.random.seed(1) df = pd.DataFrame(np.random.randint(1,5,30).cumsum().reshape(-1, 2), columns = [&quot;start&quot;, &quot;end&quot;]) start end 0 2 6 1 7 8 2 12 14 3 18 20 4 24 25 5 26 28...
<p>You can subtract shifted values, compare by <code>N</code> for mask, create groups by cumulative sum and pass to <code>groupby</code> for aggregate <code>max</code> and <code>min</code>:</p> <pre><code>N = 1 g = df['start'].sub(df['end'].shift()) df = df.groupby(g.gt(N).cumsum()).agg({'start':'min', 'end':'max'}) p...
python|pandas
8
7,404
68,354,088
Using python trying to clean and load file, to CSV but empty fields keep displaying double quotes. I would like empty fields to be empty strings
<p>My data displays &quot;&quot; in place of empty fields when I convert the file to a CSV. I would like for it to be an empty string using pandas dataframe.</p> <p>What it looks like</p> <pre><code>10/10/2020 10/10/2020 10/10/2020 &quot;&quot; &quot;&quot; </code></pre> <p>What I want it to look like<...
<p>Assuming your existing dataframe has the following setup:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd data = {'a_column': ['10/10/2020', '10/10/2020', '10/10/2020', '', '']} df = pd.DataFrame(data) # Replace empty strings with np.NaN df.replace('', np.NaN, inplace=Tru...
python|sql|pandas|dataframe
1
7,405
68,049,751
how do i get the # of the row of a dataframe, not the value of the index?
<p>i have a dataframe that looks like this:</p> <pre><code>Open High ... Dividends Stock Splits Date ... 2021-01-04 118.759295 119.907541 ... 0.194 0 2021-01-05 118.299996 120.137196 ... 0.000 0 2021-01-06 118.509...
<p>You can get the range index by doing a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>reset_index()</code></a>, as follows:</p> <pre><code>df = df.reset_index() </code></pre> <p><strong>Result:</strong></p> <p>The required row nu...
python|pandas
1
7,406
59,176,278
Apply a function over different dataframes
<p>I am trying to turn all my column headers to lower cases simultaneously over multiple dataframes. </p> <p>Something close like this:</p> <ol> <li><p><a href="https://stackoverflow.com/questions/38243556/how-to-apply-function-to-multiple-pandas-dataframe">How to apply function to multiple pandas dataframe</a></p></...
<p>Try:</p> <pre><code>df_list = [df1, df2, df3] for df in df_list: df.columns = df.columns.str.lower() </code></pre>
python|pandas|function|dataframe
2
7,407
59,317,346
Why am I Getting Different results from timestamp (datetime.datetime vs. pandas.Series datetime64)?
<p>I have a pandas DataFrame including a column of timestamps (e.g. <code>1382452859</code>). Now I want to convert this column to ordinary date and time (e.g. <code>2013-10-22 18:10:59</code>). I have tried two different approaches but I don't know why I get different answers:</p> <pre><code># my DataFrame's head df....
<p>I think best is use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> here with parameter <code>unit=s</code>:</p> <pre><code>df['Timestamp'] = pd.to_datetime(df['Timestamp'], unit='s') print (df) Timestamp ...
python|pandas|dataframe|datetime|timestamp
1
7,408
59,444,849
Create a function to calculate an equation from a dataframe in pandas
<p>I have a dataframe as shown below</p> <pre><code>Inspector_ID Sector Waste Fire Traffic 1 A 7 2 1 1 B 0 0 0 1 C 18 2 0 2 A 1 6 3 2...
<p>You could look into something along the lines of:</p> <pre><code>newData = [] inspector_ids = df['Inspector_ID'].unique().tolist() for id in inspector id: current_data = df.loc[df['Inspector_id'] == id] #With the data of the current inspector you get the desired values waste_val = 'I1W' fire_val = ...
pandas|numpy|pandas-groupby|array-broadcasting
1
7,409
45,082,576
"No Module name matrix_factorization_utilities" found
<p>I am a beginner in Machine Learning. I am getting this error in my machine learning recommendation model "<strong>No Module name matrix_factorization_utilities" found</strong><a href="https://i.stack.imgur.com/1260J.png" rel="nofollow noreferrer">Screen Shot of error</a>. I am using Python 3 and Pycharm. Library nu...
<p>Looks like you don't have scipy</p> <p>Windows:</p> <pre><code>python -m pip install scipy </code></pre> <p>Linux:</p> <pre><code>pip install scipy </code></pre>
python|numpy|machine-learning
0
7,410
45,199,864
dataframe logical_and works fine with equals and don't work with not equals
<p>Please help me understand why the "<em>not equal</em>" condition doesn't work properly.</p> <pre><code>&gt;&gt;&gt;d = {'a' : [1, 2, 3, 3, 1, 4], &gt;&gt;&gt; 'b' : [4, 3, 2, 1, 2, 2]} &gt;&gt;&gt;df = pd.DataFrame(d) a b 0 1 4 1 2 3 2 3 2 3 3 1 4 1 2 5 4 2 </code></pre> <p>We get...
<p>I think you should understand <a href="https://en.wikipedia.org/wiki/De_Morgan%27s_laws" rel="nofollow noreferrer"><strong><em>De Morgan's Laws</em></strong></a>:</p> <blockquote> <pre><code>not (A or B) == (not A) <b>and</b> (not B)</code></pre> <pre><code>not (A and B) == (not A) <b>or</b> (not B)</code></pre> <...
python|pandas|numpy|logical-and
9
7,411
57,074,442
Split list into columns in pandas
<p>I have a dataframe like this</p> <pre><code>df = (pd.DataFrame({'ID': ['ID1', 'ID2', 'ID3'], 'Values': [['AB', 'BC'], np.NaN, ['AB', 'CD']]})) df ID Values 0 ID1 [AB, BC] 1 ID2 NaN 2 ID3 [AB, CD] </code></pre> <p>I want to split the item inside list into column such that</p> <p...
<p>Pandas functions working with missing values nice, so use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.join.html" rel="nofollow noreferrer"><code>Series.str.join</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.get_dummies.ht...
python|pandas|dataframe|sklearn-pandas
4
7,412
45,725,500
How to handle custom named index when copying a dataframe using pd.read_clipboard?
<p>Given this data frame from some other question:</p> <pre><code> Constraint Name TotalSP Onpeak Offpeak Constraint_ID 77127 aaaaaaaaaaaaaaaaaa -2174.5 -2027.21 -147.29 98333 bbbbbbbbbbbbbbbbbb -1180.62 -1180.62 0 1049 cccccccccccccccccc -1036.53 -886.77 ...
<p><code>read_clipboard</code> by default uses whitespace to separate the columns. The problem you see is because of the whitespace in the first column. If you specify two or more spaces as the separator, based on the table format it will figure out the index column itself:</p> <pre><code>df = pd.read_clipboard(sep='\...
python|pandas|dataframe|clipboard
5
7,413
45,841,624
Filtering a LARGE delimited file with AWK
<p>I am working with a large (20+ GB) delimited text file I would like to process in python. My current workflow, which was devised with smaller files in mind, includes a sorting step, in pandas. Reading 20+ GB into memory isn't a great idea obviously. Chunking the file isn't really applicable either since I actually n...
<p>I open-sourced a tool for tab delimited files that improves on the speed of awk for the filtering step. The tool is <a href="https://ebay.github.io/tsv-utils/docs/tool_reference/tsv-select.html" rel="nofollow noreferrer">tsv-select</a>, it's part of eBay's <a href="https://github.com/eBay/tsv-utils" rel="nofollow no...
python|pandas|sorting|awk|command-line
2
7,414
28,595,701
pandas equivalent of R's cbind (concatenate/stack vectors vertically)
<p>suppose I have two dataframes: </p> <pre><code>import pandas .... .... test1 = pandas.DataFrame([1,2,3,4,5]) .... .... test2 = pandas.DataFrame([4,2,1,3,7]) .... </code></pre> <p>I tried <code>test1.append(test2)</code> but it is the equivalent of R's <code>rbind</code>.</p> <p>How can I combine the two as two co...
<pre><code>test3 = pd.concat([test1, test2], axis=1) test3.columns = ['a','b'] </code></pre> <p>(But see the detailed answer by @feng-mai, below)</p>
python-3.x|pandas|concat|cbind
74
7,415
50,804,227
Iterating through 2 variables to create a flag
<p>I have a df that looks generally like this:</p> <pre><code>Year ID Loc 2014 56 01x 2015 56 01x 2016 56 07b 2014 23 04k 2016 23 75b 2017 56 75q 2015 23 04k 2016 12 23q 2014 12 23q 2015 12 23q </code></pre> <p>I'm trying to create a flag for Loc changes. So for each ID if Loc is the same as the previous year the fla...
<p>You can use <code>shift</code> to make the comparisons. First, you'll need to sort the <code>DataFrame</code> and then <code>shift</code> will allow you to determine if the <code>ID</code> and <code>Loc</code> are the same as the previous year, without needing a <code>groupby</code>. </p> <pre><code>import pandas a...
python|python-3.x|pandas
1
7,416
20,571,995
pandas read_csv does not capture final (unnamed) column into dataframe
<p>I am trying to read a csv file in the following format</p> <pre><code>myHeader myJunk myDate A, B, C, D , b, c, d dataA, dataB, dataC, dataD, EXTRA_INFO_STRING dataA, dataB, dataC, dataD, EXTRA_INFO_STRING dataA, dataB, dataC, dataD, EXTRA_INFO_STRING </code></pre> <p>When I create my data frame using</p> <pre><c...
<p>How about:</p> <pre><code>df = pd.read_csv(StringIO(s), skiprows=5, header = None, index_col = False) df.columns = list("ABCDE") </code></pre> <p>Sometimes if you have problem with read_csv numeric conversions you could add dtype=object into read_csv call and deal with conversions later on your own using DataFrame...
python|csv|pandas|dataframe
0
7,417
33,400,176
Pandas dataframe to_html cell alignment
<p>I have a Pandas data frame that look like this:</p> <pre><code> X Y Z abc 0.2 -1.5 efg 0.8 -1.4 </code></pre> <p>I would like to use the to_html() method to generate a HTML out of this, but I would like to have column X to be left aligned, column Y and Z right aligned. In addition, I ...
<p>I've been working on the same right justification issue. It seems like it's a known issue (see @TomAugspurger's comment above). I used your solution for displaying negative numbers with parentheses and was able to get the right justification to work. However, there's a catch. You need to have leading and trailin...
python|html|pandas|formatting|conditional
1
7,418
33,105,830
How to compare column values of pandas groupby object and summarize them in a new column row
<p>I have the following problem: I want to create a column in a dataframe summarizing all values in a row. Then I want to compare the rows of that column to create a single row containg all the values from all columns, but so that each value is only present a single time. As example: I have the following data frame</p>...
<p>A method by which you can do this would be to apply a function on the grouped DataFrame.</p> <p>This function would first convert the series (for each group) to a list, and then in the list split each string using <code>,</code> and then chain the complete list into a single list using <a href="https://docs.python....
python|pandas|group-by
2
7,419
33,506,042
OpenBLAS error when importing numpy: `pthread_creat error in blas_thread_init function`
<p>All of a sudden, I cannot import numpy:</p> <pre><code>import numpy as np OpenBLAS: pthread_creat error in blas_thread_init function. Error code:1 </code></pre> <p>I'm running numpy from <code>Anaconda 1.10.1-py27_0</code> but I had the same issue on <code>1.9.3-py27_0</code></p> <p>Any clues?</p> <p>Edit:Trying...
<p>I had a similar problem with anaconda. I solved it by updating numpy, scipy and openblas</p>
python|numpy|anaconda|openblas
2
7,420
9,216,455
Is it possible to use blitz++ indexing and blitz functions in scipy.weave.inline
<p>The scipy document gives examples of Blitz++ style operations when using <code>weave.blitz()</code> and C style indexing when using <code>weave.inline()</code>. Does <code>weave.inline()</code> also support Blitz++ style indexing and reductions. That will be very convenient. If <code>weave.inline()</code> does indee...
<p>Here is an example, set the type_converter = weave.converters.blitz when calling weave.inline()</p> <pre><code># -*- coding: utf-8 -*- import scipy.weave as weave import numpy as np import time def my_sum(a): n=int(len(a)) code=""" int i; double counter; counter =0; for(i=0;i&lt;n;i++){ ...
numpy|blitz++
1
7,421
9,141,732
How does numpy.histogram() work?
<p>While reading up on numpy, I encountered the function <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html"><code>numpy.histogram()</code></a>.</p> <p>What is it for and <strong>how does it work?</strong> In the docs they mention <strong>bins</strong>: What are they?</p> <p>Some googli...
<p>A bin is range that represents the width of a single bar of the histogram along the X-axis. You could also call this the interval. (Wikipedia defines them more formally as "disjoint categories".)</p> <p>The Numpy <code>histogram</code> function doesn't draw the histogram, but it computes the occurrences of input da...
python|numpy|histogram
192
7,422
5,721,831
Python: Making numpy default to float32
<p>Is there any clean way of setting numpy to use float32 values instead of float64 globally?</p>
<p>Not that I am aware of. You either need to specify the dtype explicitly when you call the constructor for any array, or cast an array to float32 (use the ndarray.astype method) before passing it to your GPU code (I take it this is what the question pertains to?). If it is the GPU case you are really worried about, I...
python|numpy|numbers
13
7,423
66,740,962
Pytorch add hyperparameters for 3x3,32 conv2d layer and 2x2 maxpool layer
<p>I am trying to create a conv2d layer below using pytorch. The hyperparameters are given in the image below. I am unsure how to implement the hyperparameters (3x3,32) for the first conv2d layer. I want to know how to use this using <code>torch.nn.Conv2d</code>. Thank you very much.</p> <p><a href="https://i.stack.img...
<p>The conv2d hyper-parameters (<code>3</code>x<code>3</code>, <code>32</code>) represents <code>kernel_size=(3, 3)</code> and number of output channels=32.<br /> Therefore, this is how you define the first conv layer in your diagram:</p> <pre class="lang-py prettyprint-override"><code>conv3x3_32 = nn.Conv2d(in_channle...
deep-learning|pytorch|conv-neural-network|hyperparameters
0
7,424
66,530,497
How to read data from multiple csv files and write into same sheet of single Excel Sheet in Python
<p>I want append multiple csv files data into same sheet of single excel sheet with one empty row between data.</p> <p>1.csv</p> <pre><code>ID Currency Val1 Val2 Month 101 INR 57007037.32 1292025.24 2021-03 102 INR 49171143.9 1303785.98 2021-02 </code></pre> <p>2.csv</p> <pre><code>ID Currency...
<p>1.csv:</p> <pre><code>ID;Currency;Val1;Val2;Month 101;INR;57007037.32;1292025.24;2021-03 102;INR;49171143.9;1303785.98;2021-02 </code></pre> <p>2.csv:</p> <pre><code>ID;Currency;Val1;Val3;Month;Year 103;INR;67733998.9;1370086.78;2020-12;2020 104;INR;48838409.39;1203648.32;2020-11;2020 </code></pre> <p>3.csv</p> <pre...
python|pandas
1
7,425
66,522,526
TensorFlow issue when running code with GPU (CUDA-11.0) on Ubuntu 20.4 LTS
<p><strong>Could not load dynamic library 'libcusparse.so.11'; dlerror: libcusparse.so.11: cannot open shared object file: No such file or directory</strong></p> <p>Can someone help me solve the above problem?</p> <p>When I try to execute the following code:</p> <pre><code>import tensorflow as tf if __name__ == '__main...
<p>Was able to fix the problem by simply re-installing Ubuntu and using &quot;one-liner&quot; from <a href="https://lambdalabs.com/lambda-stack-deep-learning-software" rel="nofollow noreferrer">Lambda-Stack</a>.</p> <pre><code>LAMBDA_REPO=$(mktemp) &amp;&amp; \ wget -O${LAMBDA_REPO} https://lambdalabs.com/static/misc/l...
python|tensorflow|cuda
3
7,426
66,355,499
cannot import name 'theano_backend' from 'keras.backend'
<p>I am trying to run the following:</p> <pre><code>from keras.backend import theano_backend </code></pre> <p>But I get this error:</p> <pre><code>Traceback (most recent call last): File &quot;&lt;ipython-input-64-39e623866e51&gt;&quot;, line 1, in &lt;module&gt; from keras.backend import theano_backend ImportE...
<p>The latest Keras versions are just a wrapper on top of tf.keras, they are not the multi-backend keras you are expecting.</p> <p>For this code to work, you should downgrade Keras to a version that is still multi-backend, like 2.2.x versions. I think 2.3.x still have multiple backends too, but versions 2.4 are TensorF...
python|tensorflow|keras|theano
0
7,427
16,302,763
How to read unstructured ASCII data in numpy?
<p>I need to read unstructured ASCII data into numpy arrays. As an example, a file could look like this:</p> <pre><code>August 2005 OMI/MLS Tropo O3 Column (Dobson Units) X 10 Longitudes: 288 bins centered on 179.375W to 179.375E (1.25 degree steps) Latitudes: 120 bins centered on -59.5S to 59.5N (1.00 degree steps...
<p>A bit of a hack, but it doesn't read it <em>"by hand"</em>. </p> <pre><code>nrows = 2 ncols = 25 nlines = 12 lastline = 13 a = np.genfromtxt('tmp.txt', skip_header=3, delimiter=[4]+[3,]*(ncols-1), comments='l', dtype=int) a = a.reshape(nrows...
numpy|ascii
1
7,428
57,619,798
How to apply IF, else, else if condition in Pandas DataFrame
<p>I have a column in my pandas DataFrame with country names. I want to apply different filters on the column using if-else conditions and have to add a new column on that DataFrame with those conditions. </p> <p> Current DataFrame:-</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" dat...
<p>Not sure exactly what you are trying to achieve, but I guess it is something along the lines of:</p> <pre><code>df=pd.DataFrame({'country':['Sweden','Spain','China','Japan'], 'continent':[None] * 4}) country continent 0 Sweden None 1 Spain None 2 China None 3 Japan None df.loc[(df.c...
python-3.x|pandas|numpy|dataframe|if-statement
3
7,429
24,412,510
Transpose pandas dataframe
<p>How do I convert a list of lists to a panda dataframe?</p> <p>it is not in the form of coloumns but instead in the form of rows.</p> <pre><code>#!/usr/bin/env python from random import randrange import pandas data = [[[randrange(0,100) for j in range(0, 12)] for y in range(0, 12)] for x in range(0, 5)] print dat...
<p>This is what I came up with</p> <pre><code>data = [[[randrange(0,100) for j in range(0, 12)] for y in range(0, 12)] for x in range(0, 5)] print data df = pandas.DataFrame(data[0], columns=['B','P','F','I','FP','BP','2','M','3','1','I','L']) print df df1 = df.transpose() df1.columns = ['B','P','F','I','FP','BP','2',...
python|pandas|dataframe
6
7,430
43,758,709
How to convert NumPy ndarray to C++ vector with Boost.Python and back?
<p>I am working on a project where I need to convert an <code>ndarray</code> in Python to a <code>vector</code> in C++ and then return a processed <code>vector</code> from C++ back to Python in an <code>ndarray</code>. I am using <strong>Boost.Python</strong> with its <strong>NumPy extension</strong>. My problem specif...
<p>I will consider the title of your question to give a more generalized answer to whoever finds this post.</p> <p>You have a <code>boost::python::numpy::ndarray</code> called <code>input</code> that contains <code>doubles</code> and you want to convert it a <code>std::vector&lt;double&gt;</code> called <code>v</code>...
python|c++|numpy|vector|boost
6
7,431
43,870,169
Tensorflow log-likelihood for two probability vectors which might contain zeros
<p>Suppose I have two tensors, <code>p1</code> and <code>p2</code> in tensorflow of the same shape which contain probilities, some of which might be zero or one. Is their and elegant way of calculating the log-likelihood pointwise: <code>p1*log(p2) + (1-p1)*log(1-p2)</code>?</p> <p>Implementing it naively using the t...
<p>As an initial hack (there most be a better solution) I add an epsilon inside the <code>log</code>:</p> <pre><code>eps = 1e-10 p1*tf.log(p2+eps) + (1-p1)*tf.log(1-p2+eps) </code></pre> <p>which prevents a <code>log(0)</code>.</p>
python|tensorflow|log-likelihood
1
7,432
43,567,551
Tensorflow seed not working with LSTM model
<p><strong>tf.set_random_seed() is not working and opt seed not found.</strong> <br> For many parameters in the LSTM, it seems no opt seed found in the tf.nn.rnn_cell.BasicLSTMCell. Thus, for every time it produces different results. How to set the seed to produce the same results for running several times?</p> <pre><...
<p>I believe this should work "as expected" in the <a href="https://github.com/tensorflow/tensorflow/#installation" rel="nofollow noreferrer">tensorflow nightly builds</a>. Please try this with a TF nightly build and report back:</p> <p>Oh, also call <code>tf.set_random_seed</code> <em>before</em> creating any ops.</...
tensorflow
0
7,433
73,133,352
How to compute partial derivatives of a component of a vector-valued function?
<p>Let’s say I have a function Psi with a 4-dimensional vector output, that takes a 3-dimensional vector u as input. I would like to compute the gradient of the first three components of Psi w.r.t. the respective three components of u:</p> <pre><code>import torch u = torch.tensor([1.,2.,3.], requires_grad=True) psi =...
<p>The reason why is because <code>u[0]</code> is actually a copy so the one used on the following line:</p> <pre><code>psi[0] = 2*u[0] </code></pre> <p>is different to the one used here</p> <pre><code>grad_Psi_0 = torch.autograd.grad(psi[0], u[0]) </code></pre> <p>which means they are not linked in the computation gra...
pytorch|autograd
1
7,434
73,021,403
Pandas str.extract() to limit number of alphanumeric characters
<p>I have a pandas dataframe of descriptions like this:</p> <pre><code>df['description'] 22CI003294 PARCEL 32 22CI400040 NORFOLK ESTATES 12CI400952 &amp; 13CI403261 22CI400628 GARDEN ACRES 9CI00208 FERNHAVEN SEC 22CI400675 CECIL AVE SUB 22CI400721 124.69' SS BOLLING AVE SS </code></pre> <p>I want to extract the firs...
<p>Your way to limit the character length is not correct, see why at <a href="https://stackoverflow.com/a/32477224/3832970">Restricting character length in a regular expression</a>.</p> <p>You can use</p> <pre class="lang-py prettyprint-override"><code>df['results'] = df['description'].str.extract(r'^(\d[^\W_]{5,})') <...
python|pandas|regex
0
7,435
10,686,924
numpy array to scipy.sparse matrix
<p>Given an arbitrary numpy array (<code>ndarray</code>), is there a function or a short way to convert it to a <code>scipy.sparse</code> matrix? </p> <p>I'd like something that works like:</p> <pre><code>A = numpy.array([0,1,0],[0,0,0],[1,0,0]) S = to_sparse(A, type="csr_matrix") </code></pre>
<p>I usually do something like</p> <pre><code>&gt;&gt;&gt; import numpy, scipy.sparse &gt;&gt;&gt; A = numpy.array([[0,1,0],[0,0,0],[1,0,0]]) &gt;&gt;&gt; Asp = scipy.sparse.csr_matrix(A) &gt;&gt;&gt; Asp &lt;3x3 sparse matrix of type '&lt;type 'numpy.int64'&gt;' with 2 stored elements in Compressed Sparse Row for...
numpy|python-3.x|scipy|sparse-matrix
9
7,436
70,721,757
When one of my column in dataframe is nested list, how should i transform it to multi-dimensional np.array?
<p>I have the following data frame.</p> <pre><code>test = { &quot;a&quot;: [[[1,2],[3,4]],[[1,2],[3,4]]], &quot;b&quot;: [[[1,2],[3,6]],[[1,2],[3,4]]] } df = pd.DataFrame(test) df </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>a</th> <th>b</th> </tr> </thead> <...
<p>The following code works:</p> <pre><code>np.array(list(df['a'])) </code></pre>
python|arrays|pandas|numpy
1
7,437
70,422,213
Load multiple files to multiple arrays with for loop and pandas?
<p>I have an unknown number of txt files and each file contains two columns for numbers. I am trying to make a python script that loads whatever it finds in that directory and create numpy 1D arrays for each column automatically. Here's my attempt in which I don't know how to update the names of the arrays and how to p...
<p>IIUC use:</p> <pre><code>for i, myfile in enumerate(myfiles, 1): df = pd.read_csv(myfile, delimiter = &quot;\t&quot;) df.columns = [f&quot;x{i}&quot;, f&quot;y{i}&quot;] </code></pre> <hr /> <pre><code>for i, myfile in enumerate(myfiles, 1): df = pd.read_csv(myfile, delimiter = &quot;\t&quot;, names=[f&q...
python|pandas|numpy
0
7,438
70,440,606
Why does Tensorflow Function perform retracing for different integer inputs to the function?
<p>I am following the Tensorflow guide on Functions <a href="https://www.tensorflow.org/guide/intro_to_graphs" rel="nofollow noreferrer">here</a>, and based on my understanding, TF will trace and create one graph for each call to a function with a distinct input signature (i.e. data type, and shape of input). However, ...
<p>The numbers 2 and 3 are treated as different integer values and that is why you are seeing &quot;Tracing!&quot; twice. The behavior you are referring to: &quot;TF will trace and create one graph for each call to a function with a distinct input signature (i.e. data type, and shape of input)&quot; applies to tensors ...
python|tensorflow|tensorflow2.0|tensor
2
7,439
70,433,591
removing similar data after grouping and sorting python
<p>I have this data:</p> <pre><code>lat = [79.211, 79.212, 79.214, 79.444, 79.454, 79.455, 82.111, 82.122, 82.343, 82.231, 79.211, 79.444] lon = [0.232, 0.232, 0.233, 0.233, 0.322, 0.323, 0.321, 0.321, 0.321, 0.411, 0.232, 0.233] val = [2.113, 2.421, 2.1354, 1.3212, 1.452, 2.3553, 0.522, 0.521, 0.5421, ...
<p>You could sort the dataframe, like this:</p> <pre class="lang-py prettyprint-override"><code>grouped = df.groupby([&quot;lat&quot;, &quot;lon&quot;]) val_max = grouped[&quot;value&quot;].max() df_1 = pd.DataFrame(val_max) df_1 = ( df_1.sort_values(&quot;value&quot;, ascending=False).reset_index().sort_values([&q...
python|pandas|dataframe|numpy
0
7,440
42,669,216
create csv headers from log file python
<p>My log file contains some info in every row like below</p> <pre><code>Info1:NewOrder|key:123 |Info3:10|Info5:abc Info3:10|Info1:OldOrder| key:456| Info6:xyz Info1:NewOrder|key:007 </code></pre> <p>I want to change it to a csv like below (if i give key,Info1,Info3 as required headers)</p> <pre><code>key,Info1.Info...
<p>The bulk of it is just using useful string methods like strip and split, plus list comprehensions.</p> <pre><code>import csv string = """Info1=NewOrder|key=123 |Info3=10|Info5=abc Info3=10|Info1=OldOrder| key=456| Info6=xyz Info1=NewOrder|key=007""" requested_columns = ["key", "Info1", "Info3"] def wrangle(strin...
python|pandas|csv
0
7,441
42,873,166
Multi-class classification using keras
<p>I am developing a neural network in order to classify with classes pre-calculated with k-means.</p> <p>Dataset looks like:</p> <pre><code>50,12500,2,1,5 50,8500,2,1,15 50,6000,2,1,9 50,8500,2,1,15 </code></pre> <p>Where resulting row is the last row. Here is the code on Python with <strong>Keras</strong> I am try...
<p>If you want the class instead of the probability you could call numpy argmax at your predictions. </p> <p>Or use the convenient call predict_classes instead of predict</p> <pre><code>result = model.predict_classes(numpy.array(X[0]).reshape((1,4))) </code></pre> <p>As for your result, you could try running a few e...
python|machine-learning|tensorflow|keras
2
7,442
42,591,439
Keeping zeros in data with sklearn
<p>I have a csv dataset that I'm trying to use with sklearn. The goal is to predict future webtraffic. However, my dataset contains zeros on days that there were no visitors and I'd like to keep that value. There are more days with zero visitors then there are with visitors (it's a tiny tiny site). Here's a look at the...
<p>In this line of your code:</p> <pre><code>df['y'] = np.log(df['y']) </code></pre> <p>you are taking logarithm of 0 when your df['y'] is zero, which results in warnings and NaNs in your resulting dataset, because logarithm of 0 is not defined.</p> <p>sklearn itself does NOT interpret zero values as NaNs unless you...
machine-learning|scikit-learn|sklearn-pandas
1
7,443
42,928,344
convert list of pandas dictionaries sharing the same key in a unique dictionary
<p>I have a list of dictionaries:</p> <pre><code>dict_list = [{'A': [1,2], 'B': [3,4], 'C': [5,6]}, {'A': [7,8], 'B': [9,10], 'C': [11,12]}] </code></pre> <p>Which keys are 'A','B','C' (key names are just an example) for all the dictionaries (here 2...
<p>You can use <em>dictionary comprehension</em> for that:</p> <pre><code><b>import numpy as np</b> dict_list2 = {k:np.array([<b>d[k]</b> for d in dict_list]) for <b>k in dict_list[0]</b>}</code></pre> <p>We make the assumption that <code>dict_list</code> <strong>contains at least one dictionary</strong>, and that a...
python|pandas|dictionary
0
7,444
26,965,916
How to do a distributed matrix multiplication in numpy / ipython.parallel?
<p>I saw a <a href="http://nbviewer.ipython.org/github/jakevdp/2013_fall_ASTR599/blob/master/notebooks/21_IPythonParallel.ipynb" rel="nofollow noreferrer">tutorial</a> on how to do a distributed calculation:</p> <pre><code>def parallel_dot(dview, A, B): dview.scatter('A', A) dview['B'] = B dview.execute('C...
<p>that's hardly a worthy load. First you're doing vector multiplication, not true matrix to matrix multiplication. Try say, oh 10000x10000 matrices. If you have multiple cores I think you might begin to see some differences.</p>
python|numpy|ipython|ipython-parallel
1
7,445
27,084,056
How to copy unique keys and values from another dictionary in Python
<p>I have a dataframe <code>df</code> with transactions where the values in the column <code>Col</code> can be repeated. I use Counter <code>dictionary1</code> to count the frequency for each <code>Col</code> value, then I would like to run a for loop on a subset of the data and obtain a value <code>pit</code>. I want ...
<p>Since you're using <code>pandas</code>, I should point out that the problem you're facing is common enough that there's a built-in way to do it. We call collecting "similar" data into groups and then performing operations on them a <code>groupby</code> operation. It's probably wortwhile reading the tutorial sectio...
python|dictionary|pandas|defaultdict
2
7,446
14,909,459
Using numpy.linalg.svd on a 12 x 12 matrix using python
<p>I want to perform an SVD on a 12*12 matrix. The <code>numpy.linalg.svd</code> works fine. But when I try to get the 12*12 matrix A back by performing u*s*v , i dont get it back. </p> <pre><code>import cv2 import numpy as np import scipy as sp from scipy import linalg, matrix a_matrix=np.zeros((12,12)) with ope...
<p>Except from saving some code and time by using built in functions like <code>numpy.diag</code>, your problem seems to be the <code>*</code> operator. In numpy you have to use <code>numpy.dot</code> for matrix multiplication. See the code below for a working example...</p> <pre><code>In [16]: import numpy as np In ...
python|numpy|camera|svd
3
7,447
26,741,204
Pandas Pivot Table alphabetically sorts categorical data (incorrectly) when adding columns parameter
<p>I ran into trouble with the Pandas pivot function. I am trying to pivot sales data by month and year. The dataset is as follows:</p> <pre><code>Customer - Sales - Month Name - Year a - 100 - january - 2013 a - 120 - january - 2014 b - 220 - january - 2013 </code></pre> <...
<p>You're right after <code>pivot_table</code> it will reindex the 'Month' and thus sort alphabetically. Luckily you can always convert your <code>dataset['Month']</code> to <code>pandas.datetime</code> and convert it back to string after <code>pivot_table</code>'s reindex.</p> <p>Not the best solution, but this shoul...
python|pandas
0
7,448
39,248,380
unable to plot two columns from DataFrame after using pandas.read_csv
<p>I'm trying to plot two columns that have been read in using pandas.read_csv, the code:-</p> <pre><code>from pandas import read_csv from matplotlib import pyplot data = read_csv('Stats.csv', sep=',') #data = data.astype(float) data.plot(x = 1, y = 2) pyplot.show() </code></pre> <p>the csv file snippet:-</p> <pre...
<p>Your input csv is without headers which doesn't help clarity (see Murali's comment). But I think the problem stems from the nature of column that contains a4,a2.</p> <p>This column can be used for the x axis but not for y axis (non-numeric data on an x axis appears to be just read in order). Hence the count offset....
python|csv|pandas
0
7,449
19,514,315
How can I fit a cosine function?
<p>I wrote a python function to get the parameters of the following cosine function: <img src="https://i.stack.imgur.com/1St1m.png" alt="enter image description here"></p> <pre><code>param = Parameters() param.add( 'amp', value = amp_guess, min = 0.1 * amp_guess, max = amp_guess ) param.add( 'off', value = off_gu...
<p>My experience tells me that it's <em>always</em> good to depend as little as possible on toolboxes. For your particular case, the model is simple and doing it manually is pretty straightforward. </p> <p>Assuming that you have the following model: </p> <pre><code>y = B + A*cos(w*x + phi) </code></pre> <p>and that ...
matlab|optimization|numpy|curve-fitting
5
7,450
19,825,964
plot pandas data frame but most columns have zeros
<p>I am new to pandas and ipython I just setup everything and currently playing around. I have following data frame: </p> <pre><code> Field 10 20 30 40 50 60 70 80 90 95 0 A 0 0 0 0 0 0 0 0 1 3 1 B 0 0 0 0 0 0 0 1 4 14 2 C 0 0 0...
<p>It depends a bit on how you want to handle the zero values, but here is an approach:</p> <pre><code>df = pd.DataFrame({'a': [0,0,0,0,70,0,0,90,0,0,80,0,0], 'b': [0,0,0,50,0,60,0,90,0,80,0,0,0]}) fig, axs = plt.subplots(1,2,figsize=(10,4)) # plot the original, for comparison df.plot(ax=axs[0...
matplotlib|pandas|ipython
4
7,451
33,640,471
Find same data in two DataFrames of different shapes
<p>I have two Pandas DataFrames that I would like to compare. For example</p> <pre><code> a b c A na na na B na 1 1 C na 1 na </code></pre> <p>and</p> <pre><code> a b c A 1 na 1 B na na na C na 1 na D na 1 na </code></pre> <p>I want to find the index-c...
<p>If you pass the <code>keys</code> parameter to <code>concat</code>, the columns of the resulting dataframe will be comprised of a multi-index which keeps track of the original dataframes:</p> <pre><code>In [1]: c=pd.concat([df,df2],axis=1,keys=['df1','df2']) c Out[1]: df1 df2 a b c ...
python|pandas
5
7,452
22,768,418
numpy.where() with 3 or more conditions
<p>I have a dataframe with multiple columns. </p> <pre><code> AC BC CC DC MyColumn </code></pre> <p>A</p> <p>B</p> <p>C</p> <p>D</p> <p>I would like to set a new column "MyColumn" where if BC, CC, and DC are less than AC, you take the max of the three for that row. If only CC and DC are less...
<p>You can use the lt method along with where:</p> <pre><code>In [11]: df = pd.DataFrame(np.random.randn(5, 4), columns=list('ABCD')) In [12]: df Out[12]: A B C D 0 1.587878 -2.189620 0.631958 -0.432253 1 -1.636721 0.568846 -0.033618 -0.648406 2 1.567512 1.089788 0.489559 1.67...
python|numpy|pandas|where
6
7,453
62,189,194
Efficient calculation across dictionary consisting of thousands of correlation matrizes
<p>Based on a large dataset of daily observations from 20 assets, I created a dictionary which comprises (rolling) correlation matrices. I am using the date index as a key for the dictionary.</p> <p>What I want to do now (in an efficient manner) is to compare all correlation matrizes within the dictionary and save the...
<p>You can look at <code>itertools</code> and then insert your code to compute the correlation within a function (<code>compute_corr</code>) called in the single for loop:</p> <pre><code>import itertools for key_1, key_2 in itertools.combinations(dict_corr, 2): correlation = compute_corr(key_1, key_2, dict_corr) ...
python|pandas|numpy|scipy|hierarchical-clustering
1
7,454
62,048,441
using gather on argmax is different than taking max
<p>I'm trying to learn to train a double-DQN algorithm on tensorflow and it doesn't work. to make sure everything is fine I wanted to test something. I wanted to make sure that using tf.gather on the argmax is exactly the same as taking the max: let's say I have a network called target_network:</p> <p>first let's take...
<p>Found out what went wrong. chosen action is of shape (n, 1) so I thought that using gather on a variable that's (n, 4) I'll get a result of shape (n, 1). turns out this isn't true. I needed to turn chosen_action to be a variable of shape (n, 2)- instead of [action1, action2, action3...] I needed it to be [[1, action...
tensorflow|deep-learning|tensorflow2.0|reinforcement-learning
1
7,455
62,111,426
How to solve this Import error for pandas?
<p>I get this error when I try to import <em>pandas</em> after installing it using pip install and I'm using <em>IntelliJ</em></p> <blockquote> <pre class="lang-sh prettyprint-override"><code>C:\Users\Start\venv\Pyhon3.7\Scripts\python.exe D:/PYTHON/HelloWorld/HelloWorld.py Traceback (most recent call last): File ...
<p>If you are using Pycharm</p> <ol> <li>Go to settings.</li> <li>Go to Project: (Project-name)</li> <li>Go to Project Interpreter and all the modules you have downloaded. Maybe pandas was not installed correctly</li> </ol> <p>Please check if the python version you are using is also 64 bit. If not then that could be ...
python|pandas|intellij-idea
0
7,456
62,434,811
Json_Normalize, targeting nested columns within a specific column?
<p>I'm working with an API trying to currently pull data out of it. The challenge I'm having is that the majority of the columns are straight forward and not nested, with the exception of a CustomFields column which has all the various custom fields used located in a list per record.</p> <p>Using json_normalize is the...
<p>Try this, You have square brackets in your JSON, that's why you see those [ ] :</p> <pre><code>d = [{'EmailAddress': 'an_email@gmail.com', 'Name': 'Al Smith', 'Date': '2020-05-26 14:58:00', 'State': 'Active', 'CustomFields': [{'Key': '[Location]', 'Value': 'HJGO'}, {'Key': '[location_id]', 'Value': '34566'}, {'Key'...
python|json|pandas
1
7,457
62,194,765
Python 3.8 numpy array subtraction
<p>Update: <code>u_n = u[n,:].copy()</code> fixed the issue. Thanks, everyone for their valuable suggestions. The answer suggesting the fix is marked.</p> <hr> <p>I have a code that generates two arrays:</p> <pre><code>u_n = [0.00000000e+00 -3.55754723e-04 -5.83161988e-04 -7.28203241e-04 -8.20386731e-04 -8.78649151...
<p>Try to change line</p> <pre><code>u_n = u[n,:] </code></pre> <p>to</p> <pre><code>u_n = u[n,:].copy() </code></pre> <p>Slicing creates a view, so modifying the view modifies the original array as well and vice versa. As both arrays points to the same data the difference is a bunch of zeros. The problem can be so...
python|numpy|floating-point
0
7,458
51,479,140
Convert numpy.array object to PIL image object
<p>I have been trying to convert a numpy array to PIL image using Image.fromarray but it shows the following error. </p> <blockquote> <p>Traceback (most recent call last): File "C:\Users\Shri1008 Saurav Das\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\Image.py", line 2428, in fromarray ...
<p>The problem is the shape of your data. Pillow's <code>fromarray</code> function can only do a MxNx3 array (RGB image), or an MxN array (grayscale). To make the grayscale image work, you have to turn you MxNx1 array into a MxN array. You can do this by using the <code>np.reshape()</code> function. This will flatten o...
python|numpy|python-imaging-library
4
7,459
48,238,227
How to slice matrices from a 2D matrix along column (vertically) and create a 3D in tensorflow?
<p>I have a tensor , which is an intermediate result produced during a set of operation . It is a 2D matrix ( tensor ) , I want to reshape it into 3d but in a specific way . How could I do that .</p> <p>This is an example. The shape of K = [ 10 , 12 ]. I want to convert it into ( 3 x 10 x 4 ) matrix , Here my batch_si...
<p>We can use tf.split for this . This can be achieved by</p> <pre><code>tf.stack(tf.split(k, batch_size , axis=1)) #### Note here batch_size=3 </code></pre>
python|matrix|tensorflow|deep-learning
0
7,460
48,029,692
TypeError: unsupported operand type(s) for *: 'NoneType' and 'float' help FOR "nonlin np.dot"
<pre><code>import numpy as np def nonlin(x, deriv=False): if(deriv==True): return(x*(1-x)) return 1/(1+np.exp (-x)) x = np.array([[0,0,1], [0,1,1], [1,0,1], [1,1,1]]) y = np.array([[0], [1], [1], [0]]) #seed np.random.seed(1) #weights/synapses syn0 = 2*np.random.random((3,4)) - 1 syn1 = 2*np...
<p>It is good to see people still using <a href="https://www.youtube.com/channel/UCWN3xxRkmTPmbKwht9FuE5A" rel="nofollow noreferrer">Siraj Raval</a> tutorials to practice on Neural Networks.</p> <p>Anyways, your error is raised when the function <strong>nonlin</strong> doesn't return anything and thus L1 becomes <stro...
python|numpy|neural-network|nonlinear-functions
0
7,461
48,570,140
Difference between SparseTensor and SparseTensorValue
<p>What is the difference between SparseTensor and SparseTensorValue? Is there anything I should keep in mind if I want to build the sparse tensor based on fed indices and values? I could only find a few toy examples.</p>
<p>It depends on where you define your Sparse Tensor.</p> <p>If you would like to define the tensor outside the graph, e.g. define the sparse tensor for later data feed, use SparseTensorValue. In contrast, if the sparse tensor is defined in graph, use SparseTensor</p> <p>Sample code for tf.SparseTensorValue:</p> <pr...
tensorflow|machine-learning
2
7,462
48,554,588
Pandas left outer join
<p>I'm working with python pandas now. Here is a problem I'm experiencing. There's a dataset called master, and its length comes with like this:</p> <pre><code>print(len(master)) 120000 </code></pre> <p>And then I try to left-outer-join this with another dataset called click:</p> <pre><code>master_active=pd.merge(ma...
<p>Your merge only guarantees the result will have <code>len(master.index)</code> as a <em>minimum</em> number of rows. As @Wen mentioned, you will have more rows if <code>click</code> has more than one match on joining columns.</p> <p>This example should clarify the behaviour:</p> <pre><code>df1 = pd.DataFrame([['a'...
python|pandas|merge|left-join
1
7,463
48,752,888
pandas merge intervals by range
<p>I have a pandas dataframe that looks as the following one:</p> <pre><code> chrom start end probability read 0 chr1 1 10 0.99 read1 1 chr1 5 25 0.99 read2 2 chr1 15 25 0.99 read2 3 chr1 30 40 0.75 read4 </code></pre> <p>What I wanna do is to me...
<p>As suggested by @root, the accepted answer fails to generalize to similar cases. e.g. if we add an extra row with range 2-3 to the example in the question:</p> <pre><code>df = pd.DataFrame({'chrom': ['chr1','chr1','chr1','chr1','chr1'], 'start': [1, 2, 5, 15, 30], 'end': [10, 3, 20, 25, 40], 'probabili...
python|pandas|bioinformatics
4
7,464
48,513,337
Python version on windows
<p>I am trying to "Training on the Oxford-IIIT Pets Dataset on Google Cloud" <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/running_pets.md" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/running_pets.md</a> And I'm r...
<blockquote> <p>ImportError: No module named matplotlib.pyplot</p> </blockquote> <p>Looks like you need to install matplotlib</p> <p>And the code isn't running in windows given that Python is being executed from <code>/root/.local/...</code></p>
python|tensorflow|google-cloud-platform
0
7,465
70,883,463
Replace zeroes with nan in either data frame or array based on another element in the row
<p>I have a dataset which can be in a numpy array, or a dataframe, here is a sample of it in a dataframe:</p> <pre><code> totalsum totalmean raindiffsum raindiffmean name bin 0 0 NaN 0 NaN openguage 2021-11-01 00:00:00 1 0 NaN 0 N...
<p>You can use <code>.loc</code> to do this. <code>df['totalmean'].isna()</code> returns a mask (just a Series) where each value is true if that item in <code>totalmean</code> is NaN, false otherwise.</p> <pre><code>df.loc[df['totalmean'].isna(), 'totalsum'] = np.nan </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt;...
pandas|numpy
3
7,466
70,976,707
ONNX with custom ops from TensorFlow in Java
<p>in order to make use of Machine Learning in Java, I'm trying to train a model in TensorFlow, save it as ONNX file and then use the file for inference in Java. While this works fine with simple models, it's getting more complicated using pre-processing layers, as they seem to depend on custom operators.</p> <p><a hre...
<p>The solution you propose in your update is correct, you need to compile the ONNX Runtime extension package from source to get the dll/so/dylib, and then you can load that into ONNX Runtime in Java using the session options. The Python whl doesn't distribute the binary in a format that can be loaded outside of Python...
java|tensorflow|onnx|onnxruntime|tf2onnx
2
7,467
71,000,354
Impulse response with initial conditions on python using filter/filtic
<p>I am trying to get impulse response using filter/filtic at rest and initial conditions.</p> <pre><code> import numpy as np import matplotlib.pyplot as plt from scipy import signal n = np.arange(0,8,1) h = np.array([1,0,0,0,0,0,0,0]) #unit impulse signal a = np.array([1,1/2,1/4]) b = np.array([1,2,1/4]) #a &amp;...
<p>When trying to obtain the filter response with initial condition you're using <code>lfiltic</code> two times in a row. You need to use the response from the first <code>lfiltic</code> (<code>z1</code>) in the <code>lfilter</code> command, similarly with what you've done in the first block, but now passing <code>z1</...
python|numpy|matplotlib|scipy
0
7,468
70,926,148
Extract pattern from a column based on another column's value
<p>given two columns of a pandas dataframe:</p> <pre><code>import pandas as pd df = {'word': ['replay','replayed','playable','thinker','think','thoughtful', 'ex)mple'], 'root': ['play','play','play','think','think','think', 'ex)mple']} df = pd.DataFrame(df, columns= ['word','root']) </code></pre> <p>I'd like to e...
<p>You can use a regex with <code>str.extract</code> in a <code>groupby</code>+<code>apply</code>:</p> <pre><code>import re df['match'] = (df.groupby('root')['word'] .apply(lambda g: g.str.extract(f'^(.*{re.escape(g.name)})')) ) </code></pre> <p>Or, if you expect few repeated &quot;root&...
python|pandas|extract
1
7,469
51,605,300
To replace internet acronyms in a dataframe using dictionary
<p>I'm working on a text mining project where I'm trying to replace abbreviations, slang words and internet acronyms present in text (In a dataframe column) using a manually prepared dictionary. </p> <p>The problem I'm facing is the code stops with the first word of the text in the dataframe column and does not replac...
<p>You can try as following with using <code>lambda</code> and <code>join</code> along with <code>split</code>:</p> <pre><code>import pandas as pd abbr_dict = {"abt":"about", "b/c":"because"} df = pd.DataFrame({'text': ['However, industry experts are divided abt whether a Bitcoin ETF is necessary or not.']}) df['ne...
python|pandas|text-mining
2
7,470
51,564,922
Pandas Improving Efficiency
<p>I have a pandas dataframe with approximately 3 million rows. I want to partially aggregate the last column in seperate spots based on another variable. </p> <p>My solution was to separate the dataframe rows into a list of new dataframes based on that variable, aggregate the dataframes, and then join them again into...
<p>This function does the same, and is 10 times faster. </p> <pre><code>test.groupby(["year", "month"], as_index=False).agg({"day_count":sum}).rename(columns={"day_count":"month_count"}) </code></pre>
python|performance|pandas
3
7,471
51,616,996
Python Pandas: Merge Columns of Data Frame with column name into one column
<p>I have the data in the following format in my Data Frame:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('ABCD')) &gt;&gt;&gt; df A B C D 0 0.578095 -1.985742 -0.269517 -0.180319 1 -0.618431 -0.937284 0.556290 -1.416877 2 1.695109 0....
<p>Drop the columns and create a new one with <code>agg</code>:</p> <pre><code>df2 = df.drop(['C', 'D'], axis=1).assign(New_Column= df[['C', 'D']].agg(pd.Series.to_dict, axis=1)) </code></pre> <p></p> <pre><code>df2 A B New_Column 0 -0.645719 -0.757112 {...
python|json|pandas|dataframe|snowflake-cloud-data-platform
5
7,472
42,012,337
Deconvolution with Metal Performance Shaders
<p>Turns out there is no such operation as <code>deconvolution</code> in <code>MPS</code>. The closest analogue in <code>tensorflow</code> is <code>conv2d_transpose</code>. </p> <p>Is it possible to sort of plug-in custom operations between <code>MPS</code> default operations?</p>
<p>You can write your own Metal compute kernels and execute those in between the MPS operations.</p> <p>For example:</p> <pre><code>let commandBuffer = commandQueue.makeCommandBuffer() . . . // Do something with an MPSCNN layer: layer1.encode(commandBuffer: commandBuffer, sourceImage: img1, destinationImage: img2) ...
tensorflow|metal|metal-performance-shaders
5
7,473
41,803,853
Extracting specific elements from a tensor in tensorflow
<p>I'm using tensorflow on python I have a data tensor of shape [?, 5, 37], and a idx tensor of shape [?, 5]</p> <p>I'd like to extract elements from data and get an output of shape [?, 5] such that:</p> <pre><code>output[i][j] = data[i][j][idx[i, j]] for all i in range(?) and j in range(5) </code></pre> <p>It looks...
<p>I managed to do it with <code>gather_nd</code> as shown below</p> <pre><code>nRows = tf.shape(length_label)[0] # ==&gt; ? nCols = tf.constant(MAX_LENGTH_INPUT + 1, dtype=tf.int32) # ==&gt; 5 m1 = tf.reshape(tf.tile(tf.range(nCols), [nRows]), shape=[nRows, nCols]) m2 = tf.trans...
python|tensorflow
2
7,474
64,246,466
How to fill a tensor of values based on tensor of indices in tensorflow?
<p>I need to extract values from tensor based on the indices tensor.</p> <p>My code is as follows:</p> <pre><code>arr = tf.constant([10, 11, 12]) # array of values inds = tf.constant([0, 1, 2]) # indices res = tf.map_fn(fn=lambda t: arr[t], elems=inds) </code></pre> <p>It works slowly. Is there more efficient way ?</...
<p>You can use tf.gather method</p> <pre><code> arr = tf.constant([10, 11, 12]) # array of values inds = tf.constant([0, 2]) r = tf.gather(arr , inds)#&lt;tf.Tensor: shape=(2,), dtype=int32, numpy=array([10, 12])&gt; </code></pre> <p>If you have a multi-dimensional tensor, The tf.gather has an &quot;axis&quot; p...
python|tensorflow
2
7,475
64,433,828
Need help rewriting Python expression into a function
<p>I have a dataframe formatted like this in pandas.</p> <pre><code>School ID Column 1 Column 2 Column 3 School 1 8100 8200 School 2 9999 School 3 9300 9500 School 4 7700 7800 School 5 8999 .... </code...
<p>You can try this :</p> <pre><code>def find(num) : d1=df.loc[df['Column 2']==num] if len(d1)&gt;0 : return d1[['School ID','Column 2']] else : return df.loc[(num&gt;= df['Column 2']) &amp; (num&lt;= df['Column 3'])][['School ID','Column 2','Column 3']] </code></pre>
python|pandas
0
7,476
64,320,883
The size of tensor a (707) must match the size of tensor b (512) at non-singleton dimension 1
<p>I am trying to do text classification using pretrained BERT model. I trained the model on my dataset, and in the phase of testing; I know that BERT can only take to 512 tokens, so I wrote if condition to check the length of the test senetence in my dataframe. If it is longer than 512 I split the sentence into sequen...
<p>This is because, BERT uses word-piece tokenization. So, when some of the words are not in the vocabulary, it splits the words to it's word pieces. For example: if the word <code>playing</code> is not in the vocabulary, it can split down to <code>play, ##ing</code>. This increases the amount of tokens in a given sent...
python|tensorflow|pytorch|tokenize|bert-language-model
6
7,477
64,522,751
Poor accuracy of CNN model with Keras
<p>I need advice. I got a very poor result(10% accuracy) when building a CNN model with Keras when only using a subset of CIFAR10 dataset (only use 10000 data, 1000 per class). How can I increase the accuracy? I try to change/increase the epoch, but the result is still the same. Here is my CNN architecture :</p> <pre><...
<p>First of all, the problem is the loss. Your dataset is a <strong>multi-class problem</strong>, not a binary and not multi-label one</p> <p>As stated <a href="https://stackoverflow.com/questions/42081257/why-binary-crossentropy-and-categorical-crossentropy-give-different-performances">here</a>:</p> <blockquote> <p>Th...
python|tensorflow|machine-learning|keras|conv-neural-network
1
7,478
64,324,153
precision score (numpy.float64' object is not callable)
<p><strong>I don't know how to fix this problem, can anyone explain me?</strong></p> <p>Im truying to get best precision_score in loop, by changing the parameter of DecisionTreeClassifier</p> <pre><code>import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import precision_score fr...
<p>Your last lines in the cycle:</p> <pre><code>precision_score = precision_score(y_test,preds,average='micro') temp_scores = pd.DataFrame({'depth':[depth], 'test_score':[test_score], 'train_score':[train_score], 'precision_score:':[...
python|pandas|scikit-learn|decision-tree
1
7,479
64,593,792
How to make Intel GPU available for processing through pytorch?
<p>I'm using a laptop which has Intel Corporation HD Graphics 520. Does anyone know how to it set up for Deep Learning, specifically Pytorch? I have seen if you have Nvidia graphics I can install cuda but what to do when you have intel GPU?</p>
<p>PyTorch doesn't support anything other than NVIDIA CUDA and lately AMD Rocm. Intels support for Pytorch that were given in the other answers is exclusive to xeon line of processors and its not that scalable either with regards to GPUs.<br /> Intel's <code>oneAPI</code> formerly known ad <code>oneDNN</code> however, ...
deep-learning|pytorch|gpu|intel
9
7,480
47,888,392
is it possible to use np arrays as indices in h5py datasets?
<p>I need to merge a number of datasets, each contained in a separate file, into another dataset belonging to a final file. The order of the data in the partial dataset is not preserved when they get copied in the final one - the data in the partial datasets is 'mapped' into the final one through indices. I created two...
<p>So you are doing fancy-indexing for both the read and write:</p> <p><a href="http://docs.h5py.org/en/latest/high/dataset.html#fancy-indexing" rel="nofollow noreferrer">http://docs.h5py.org/en/latest/high/dataset.html#fancy-indexing</a></p> <p>It warns that it can be slow with long lists.</p> <p>I can see where re...
numpy|h5py
1
7,481
47,812,635
Indexing Python array and skipping
<p>I have a matrix for which I want to do the following in Matlab syntax:</p> <pre><code>M = [M1(1:3:20,1:3:20) M1(21:40,21:40) M1(41:3:70,41:3:70)]; </code></pre> <p>So, I want to skip every 3th element for the first 20 element and again skip every 3th element for 41-70 elements, while those in the middle stay the s...
<p>The Python syntax is very similar, but please note that the step size goes at the end of the slicing syntax:</p> <pre><code>import numpy as np M1 = np.ones((100, 100)) M = [M1[1:20:3,1:20:3], M1[21:40,21:40], M1[41:70:3,41:70:3]] </code></pre>
python|arrays|matlab|numpy|indexing
1
7,482
49,281,663
Assign group averages to each row in python/pandas
<p>I have a dataframe and I am looking to calculate the mean based on store and all stores. I created code to calculate the mean but I am looking for a way that is more efficient. </p> <p>DF</p> <pre><code>Cashier# Store# Sales Refunds 001 001 100 1 002 001 150 2 ...
<p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="noreferrer"><code>GroupBy.transform</code></a> for new column filled by aggregate values with <code>mean</code>:</p> <pre><code>df['Sales_StoreAvg'] = df.groupby('Store#')['Sales'].transform(...
python|pandas|group-by|mean|pandas-groupby
8
7,483
49,086,356
How to replace dataframe column with separate dict values - python
<p>My <code>user_artist_plays</code> dataframe below shows a user column, but for statistical computation I must replace these mixed characters with <code>int</code> only IDs. </p> <pre><code> users artist plays 0 00001411dc427966b17297bf4d69e7e193135d89 sting 12763 1 ...
<p>It seems you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a>:</p> <pre><code>user_artist_plays['users'] = user_artist_plays['users'].map(user_dict) </code></pre> <p>Or <a href="http://pandas.pydata.org/pandas-docs/stable/gen...
python|pandas|dataframe|dictionary-comprehension
3
7,484
58,664,297
Pandas dataframe to sparse matrix based on group assignment (1 if in group, 0 if not in group)
<p>I have a Pandas dataframe that looks like this:</p> <pre><code> user community abc A abc A abc B def A def A def B def C ghi A ghi D ... </code></pre> <p>Based on the <code>user</code> column and the <code>community<...
<p>I will do <code>dot</code></p> <pre><code>df=df.drop_duplicates() s=pd.crosstab(df.community,df.user) s.dot(s.T.gt(0)) Out[330]: community A B C D community A 3 2 1 1 B 2 2 1 0 C 1 1 1 0 D 1 0 0 1 </code></pre>
python|pandas
3
7,485
58,932,102
How do groupby with part of column name, dcast and revalue at the same time in pandas dataframe
<p>I have the following <code>dataframe</code></p> <pre><code> import numpy as np import pandas as pd df = pd.DataFrame({'x_d_a_b_1to3': [np.NaN, 'yes', 'yes', 'no'], 'x_d_a_b_lessthanhalf': ['no', 'no', 'no', np.NaN], 'y_k_d_e_lessthanhalf': ['no', 'yes', 'no', np.NaN], ...
<p>I really don't understand your logic for the output, could you please expand the explanation for each case?</p> <p>Essentially, you are defining a 2 variable function that returns one value. </p> <p>This is applied to each row.</p> <p>I modified your input like this </p> <pre><code>df = df.replace(to_replace={'y...
python|python-3.x|pandas
1
7,486
59,034,464
Round values of a python dataframe column according to authorized values
<p>I have this dataframe :</p> <pre><code>df = pd.DataFrame({'id':[1,2,3,4], 'score':[0.35,3.4,5.5,8]}) df id score 0 1 0.35 1 2 3.4 2 3 5.5 3 4 8 </code></pre> <p>and this list :</p> <pre><code>L = list(range(1,7)) L [1, 2, 3, 4, 5, 6] </code></pre> <p>I would like to round the values of df.sco...
<p>Numpy solution is better if large DataFrame and performance is important:</p> <pre><code>L = list(range(1,7)) a = np.array(L) df['score'] = a[np.argmin(np.abs(df['score'].values - a[:, None]), axis=0)] print (df) id score 0 1 1 1 2 3 2 3 5 3 4 6 </code></pre> <p>How it working:</p...
python|pandas|list|dataframe|rounding
2
7,487
59,040,238
Efficient expanding OLS in pandas
<p>I would like to explore the solutions of performing expanding OLS in pandas (or other libraries that accept DataFrame/Series friendly) efficiently.</p> <ol> <li>Assumming the dataset is large, I am NOT interested in any solutions with a for-loop;</li> <li>I am looking for solutions about expanding rather than rolli...
<p>One option is to use the <code>RecursiveLS</code> (recursive least squares) model from Statsmodels:</p> <pre><code># Simulate some data rs = np.random.RandomState(seed=12345) nobs = 100000 beta = [10., -0.2] sigma2 = 2.5 exog = sm.add_constant(rs.uniform(size=nobs)) eps = rs.normal(scale=sigma2**0.5, size=nobs) e...
python|pandas|linear-regression|statsmodels
2
7,488
59,007,950
How to get a particular layer output of a pretrained VGG16 in pytorch
<p>I am very new to pytorch and I am trying to get the output of the pretrained model VGG16 feature vector in 1*4096 format which is returned by the layers just before the final layer. I found that there are similar features available in keras. Is there any direct command in pytorch for the same?</p> <p>The code I am ...
<p>Part of the network responsible for creating <code>features</code> is named... <code>features</code> (not only in VGG, it's like that for most of the pretrained networks inside <code>torchvision</code>).</p> <p>Just use this field and pass your image like this:</p> <pre><code>import torch import torchvision imag...
python|computer-vision|pytorch|vgg-net
2
7,489
58,776,217
What is the algebraic expression for PyTorch's ConvTranspose2d's output shape?
<p>When using PyTorch's ConvTranspose2d as such:</p> <pre><code>w = 5 # input width h = 5 # output height nn.ConvTranspose2d(in_channels, out_channels, kernel_size=k, stride=s, padding=p) </code></pre> <p>What is the formula for the dimensions of the output in each channel? I tried a few examples and cannot derive th...
<p>The formula to calculate <code>ConvTranspose2d</code> output sizes is mentioned on the <a href="https://pytorch.org/docs/stable/nn.html#convtranspose2d" rel="nofollow noreferrer">documentation</a> page:</p> <blockquote> <p>H_out ​= (H_in​−1)*stride[0] − 2×padding[0] + dilation[0]×(kernel_size[0]−1) + output_padding[...
python|conv-neural-network|pytorch
2
7,490
70,303,725
Splitting the total time (in seconds) and fill the rows of a column value in 1 second frame
<p>I have an dataframe look like (start_time and stop_time are in seconds followed by milliseconds)</p> <p><a href="https://i.stack.imgur.com/WJKNx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WJKNx.png" alt="enter image description here" /></a></p> <p>And my Expected output to be like.,</p> <p><a...
<pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df2 = pd.DataFrame({ &gt;&gt;&gt; &quot;Labels&quot; : df.apply(lambda x:[x.Labels]*(round(x.stop_time)-round(x.start_time)), axis=1).explode(), ... &quot;start_time&quot; : df.apply(lambda x:range(round(x.start_time), round(x.stop_time)), axis=1).ex...
python|pandas|dataframe|time
1
7,491
70,271,926
How to create top worst sales product?
<p>My idea is merge all product to each day in year to Sales Data. Because I don't have the new product launch date data, so basing on the first order containing the product, I will remove the previous ones. I don't known how to coding it right. Here is the simple data I created:</p> <pre><code>import pandas as pd data...
<p>IIUC, group by <code>product_code</code> then find rows with valid <code>po</code> and compute cumulative sum. Finally remove, all rows where cumsum equals 0.</p> <p>Suppose the following dataframe. I slightly modified yours to have another valid value for 'C'</p> <pre><code>&gt;&gt;&gt; df order_date po produc...
python|pandas|dataframe
1
7,492
70,197,026
Unpack numpy array objects, from shape (3,2)(2) to shape (3,2,2)
<p>I have a numpy array of shape (3,2), where each cell is a numpy array of shape 2 (object):</p> <pre><code>df = pd.DataFrame({'A':[np.array([4,4]),np.array([5,5]),np.array([6,6])], 'B':[np.array([4,5]),np.array([5,6]),np.array([6,7])]}) df.head() A B 0 [4, 4] [4, 5] 1 [5, 5] [5, 6] 2 [6, 6] [6, 7...
<p>IIUC, you might want:</p> <pre><code>import numpy as np np.c_[df.values.tolist()] </code></pre> <p>output:</p> <pre><code>array([[[4, 4], [4, 5]], [[5, 5], [5, 6]], [[6, 6], [6, 7]]]) </code></pre>
python|arrays|numpy
0
7,493
70,351,939
Converting an xlsx file to a dictionary in Python pandas
<p>I am trying to import a dataframe from an xlsx file to Python and then convert this dataframe to a dictionary. This is how my Excel file looks like:</p> <pre><code> A B 1 a b 2 c d </code></pre> <p>where A and B are names of columns and 1 and 2 are names of rows.</p> <p>I want to convert the data frame to a dictio...
<p>This does what is requested:</p> <pre><code>import pandas as pd d = pd.read_excel(‘.\inflation.xlsx’, sheet_name = ‘Sheet2’,index_col=0,header=None).transpose().to_dict('records')[0] print(d) </code></pre> <p>Output:</p> <pre><code>{'a': 'b', 'c': 'd'} </code></pre> <p>The <a href="https://pandas.pydata.org/pandas-...
python|excel|pandas|dataframe|dictionary
1
7,494
70,069,055
Cannot find reference 'TextVectorization' in '__init__.py'
<p>I'm using Pycharm 2021.2.3 with tensorflow 2.6.2 on ubuntu 18.04.6</p> <p>When testing the Text classification tutorial from <a href="https://www.tensorflow.org/text/guide/word_embeddings" rel="nofollow noreferrer">https://www.tensorflow.org/text/guide/word_embeddings</a></p> <p>In this line :</p> <p><code>from tens...
<p>TextVectorization is found under <code>tensorflow.keras.layers.experimental.preprocessing</code>, not <code>tensorflow.keras.layers</code></p>
python|tensorflow|keras|pycharm|tensorflow2.0
0
7,495
70,118,333
Read data from a pandas Dataframe and create a tree and represent it as a dictionary
<p>Suppose I have a dataframe</p> <pre><code>df1 = pd.DataFrame({'parent id': [0,0,2,2,2,2,2,2,3,3,4,4,4], 'id' : [1,2,3,4,11,12,13,16,14,15,41,42,43]}) </code></pre> <p>I want to use this data to create a tree and then represent the tree as a dictionary like this:</p> <pre><code>tree = {0: [1, {2:...
<p>The order in the of the object/numbers in the list isn't exactly like yours, but I'm guessing that doesn't matter.</p> <pre class="lang-py prettyprint-override"><code>items = df[~df['id'].isin(df['parent id'])].groupby('parent id').apply(lambda x: {x['parent id'].iloc[0]: x['id'].tolist()}) df[df['id'].isin(df['pare...
python|pandas
1
7,496
56,069,319
How to fix "ValueError: Operands could not be broadcast together with shapes (2592,) (4,)" in Tensorflow?
<p>I am currently designing a NoisyNet layer, as proposed here: <a href="https://arxiv.org/abs/1706.10295" rel="nofollow noreferrer">"Noisy Networks for Exploration"</a>, in Tensorflow and get the dimensionality error as indicated in the title, while the dimensions of the two tensors to be multiplied element-wise in li...
<p>As stated in the <a href="https://keras.io/layers/writing-your-own-keras-layers/" rel="nofollow noreferrer">custom layer document</a>, you need to implement <code>compute_output_shape(input_shape)</code> method:</p> <blockquote> <p><code>compute_output_shape(input_shape)</code>: in case your layer modifies the ...
python|python-3.x|tensorflow|valueerror
2
7,497
56,162,774
Where to find the loss functions for manual fitting in tensorflow2.0?
<p>I am trying to resolve this error:</p> <pre><code> AttributeError: module 'tensorflow.python.keras.api._v2.keras.losses' has no attribute 'sparse_softmax_cross_entropy' </code></pre> <p>For context, I'm using <code>tensorflow2.0</code> on windows with <code>python3.6</code>. I am trying to do some quick catego...
<p>Solved, I couldn't find the documentation for 2.0 but here it is:</p> <p><a href="https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/losses/SparseCategoricalCrossentropy" rel="nofollow noreferrer">https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/losses/SparseCategoricalCrossentropy</a></p>
tensorflow|anaconda|python-3.7|tensorflow2.0
0
7,498
55,696,971
Neural Network after first epoch generates NaN values as output, loss
<p>I am trying to set neural network with few layers which will solve simple regression problem which should be f(x) = 0,1x or f(x) = 10x </p> <p>All the code is showed below (generation of data and neural network)</p> <ul> <li>4 fully connected layers with ReLu</li> <li>loss function RMSE</li> <li>learning Gradient...
<p>You need to normalize your data because your gradients, and as a result <code>cost</code>, are exploding. Try to run this code:</p> <pre class="lang-py prettyprint-override"><code>learning_rate = 0.00000001 x_batch = learningTestData[:10] y_batch = outputData[:10] with tf.Session() as sess: # Initializing the v...
python|tensorflow|neural-network|nan
2
7,499
55,690,327
Is there a way to conditionally index 3D-numpy array?
<p>Having an array A with the shape <code>(2,6, 60)</code>, is it possible to index it based on a binary array B of shape <code>(6,)</code>?</p> <p>The 6 and 60 is quite arbitrary, they are simply the 2D data I wish to access.</p> <p>The underlying thing I am trying to do is to calculate two variants of the 2D data (...
<p>You can generate a range of the indices you want to iterate over, in your case from 0 to 5:</p> <pre><code>count = A.shape[1] indices = np.arange(count) # np.arange(6) for your particular case &gt;&gt;&gt; print(indices) array([0, 1, 2, 3, 4, 5]) </code></pre> <p>And then you can use that to do your advanced in...
python|arrays|numpy|indexing
1