Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
357,300
59,625,063
Seaborn plots appending legends when plotting multiple plots in the same script
<p>I am new to Seaborn. When plotting multiple plots in the same script, the first plot is correct, but for the rest, the legends are appended which skew the plots.</p> <p><strong>My code</strong></p> <pre><code>sns.set() cmap = sns.cubehelix_palette(rot=-.2, as_cmap=True) ax = sns.scatterplot(x="Clicks", y="Impressi...
<p>I am not certain if this will fix your problem. But in general I have a strong preference for using the explicit object oriented approach whenever creating more than one plot in matplotlib/seaborn (matplotlib is the underlying library, seaborn is just wrapping it to make certain applications quicker). This means get...
python|pandas|seaborn
1
357,301
59,723,055
How can I print the phrase as the randomly generated numbers?
<p>Code:</p> <pre><code>import string, random import pandas as pd #User Input title = input("Please Enter A Title For This Puzzle: ") if len(title) == 0: print("String is empty") quit() phrase = input("Please Enter A Phrase To Be Encoded: ") if len(phrase) == 0: print("String is empty") quit() #Numb...
<p>If I understand you correctly, is it something like this you were looking for?</p> <p>flip the nums position</p> <pre><code>code = dict(zip(string.ascii_lowercase, nums)) code.update({" ":0}) HELLO = [code[item] for item in "hello"] </code></pre>
python|pandas
2
357,302
59,569,396
What does [] mean when it replaces values in a dataframe?
<p>Following the creation of a pivot table, I've had a number of [] values appear. I'm not sure why this has happened but I'm trying to figure out why / whether I can safely remove?</p> <p>The dataframe column types were:</p> <pre><code>zone float64 logtime_round datetime64[ns] varname ...
<p>You have duplicated values for <code>2017-05-01 06:20:00</code> for each zone and varname that is what is causing the list results. </p> <p>To get a clear view, try</p> <pre><code>df.pivot_table(index='logtime_round', columns=['varname', 'zone'], values='value', aggfunc=lambda x: x.to_list()) </code></pre> <p>res...
python|pandas|pivot-table
1
357,303
59,901,859
Pandas - count things of one column by a condition of other
<p>I have a DataFrame <code>d</code> of games played of the game Go. The important columns for these are the player name, and if they won or not that particular game. How can I make a new DataFrame with a column that is Player name (without repeating names), the total games they played and the total number they won. Ex...
<p>Few ways (feel free to add more)</p> <h1>1</h1> <pre><code>df2.groupby(['Nombres','col2'])['col2'].count().to_frame() col2 Nombres col2 pepe Lost 1 Win 2 tito Lost 1 </code></pre> <h1>2</h1> <pre><code>pd.crosstab(df2.Nombres,df2.col2,df2.col2,aggfunc='count').filln...
python|pandas
3
357,304
59,867,388
Pandas if any n of m conditions are met
<p>Example.</p> <p>Let's say I have dataframe with several columns and I want to select rows that match all 4 conditions, I would write:</p> <pre><code>condition = (df['A'] &lt; 10) &amp; (df['B'] &lt; 10) &amp; (df['C'] &lt; 10) &amp; (df['D'] &lt; 10) df.loc[condition] </code></pre> <p>Contrary to that if I want t...
<p>Since <code>True == 1</code> and <code>False == 0</code> you can find rows that satisfy atleast N conditions by checking the sum. Series have most of the basic comparisons as attributes so you could make a single condition list with a variety of checks and then use <code>getattr</code> to make it tidy.</p> <pre><co...
python|pandas
5
357,305
59,714,392
Convert value of dictionary in a Dataframe to columns. Also add extra columns using the other values
<p>I have a data frame which initially looks like this</p> <pre><code>date some_info 2020-01-01 [{'a': 1, 'hour': -1, 'data': 2}, {'a': 2, 'ho... 2020-01-02 [{'a': 1, 'hour': -1, 'data': 2}, {'a': 2, 'ho... 2020-01-03 [{'a': 1, 'hour': -1, 'data': 2}, {'a': 2, 'ho... ...... </code></pre> <p>where some_info ...
<p>Sample data:</p> <pre><code>date,some_info 2020-01-01,"[{""a"" : 1, ""hour"" : -1, ""data"":2},{""a"" : 2, ""hour"" : 1, ""data"":2},{""a"" : 3, ""hour"" : 4, ""data"":2},{""a"" : 4, ""hour"" : 6, ""data"":2}]" 2020-01-02,"[{""a"" : 1, ""hour"" : -1, ""data"":4},{""a"" : 2, ""hour"" : 1, ""data"":9},{""a"" : 3, ""h...
python|pandas|numpy
0
357,306
59,746,713
I meet a problem which is "RuntimeError: Input and hidden tensors are not at the same device, found input tensor at cuda:0 and hidden tensor at cpu"
<p>I guess the hidden tensor is the tenor which I need to initialize in the beginning of RNN. So I set the h0 and c0 by .cuda(), but that is not useful. Following is my code.Please, who can give me a hand?</p> <pre><code>class LSTM_net(nn.Module): def __init__(self, Embedding, vocab, label, batch): super(LSTM_net,...
<p>initially I thought you did the error of not putting .cuda() before wrapping it in the variable like it is described here: <a href="https://discuss.pytorch.org/t/tensor-cuda-vs-variable-cuda/12549" rel="nofollow noreferrer">https://discuss.pytorch.org/t/tensor-cuda-vs-variable-cuda/12549</a></p> <p>However, you have...
pytorch|lstm|recurrent-neural-network
0
357,307
59,620,279
How to append the list in Python for certain index?
<p>I have a list like this;</p> <pre><code>list1 = [1, 1, 1, 1, 1, 1, 1, 1, 1] # list of 9 elements </code></pre> <p>I want to have another <code>list2</code> like this..</p> <pre><code>list2 = [1, 2, 2, 2, 2, 2, 2, 2, 2, 1] # list of 10 elements </code></pre> <p><code>list2</code> is formed by keeping <code>0th</c...
<p>An alternate way to achieve your desired result is to effectively shift <code>list1</code> by prepending a list with one entry of 0 to it, and then add it to itself (extended by an entry of 0 to match lengths), by using <a href="https://docs.python.org/3.3/library/functions.html#zip" rel="nofollow noreferrer"><code>...
python|python-3.x|list|numpy
4
357,308
59,488,092
fillna doens't fill null values
<p>I like to fill the null values in a column with a formel based on other columns:</p> <pre><code>data['datacqtr'].fillna(data['datadate'].dt.year.apply(str) + str('Q')+data['datadate'].dt.quarter.astype(str)) </code></pre> <p>Can you see where the problem is with my Code? Because there are some nulll values after t...
<p><code>fillna()</code> is a <strong>method</strong> on a dataframe -- you pass arguments to it. In the snippet above it looks like you are assigning something to it instead. It would help to get a sample of the dataframe you're working with and what your expected result is.</p>
python|pandas|null|fillna
1
357,309
59,652,882
Comparing lists in two columns row-wise efficiently
<p>When having a Pandas DataFrame like this: </p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np df = pd.DataFrame({'today': [['a', 'b', 'c'], ['a', 'b'], ['b']], 'yesterday': [['a', 'b'], ['a'], ['a']]}) </code></pre> <pre class="lang-py prettyprint-overrid...
<p>Not sure about performance, but at the lack of a better solution this might apply:</p> <pre><code>temp = df[['today', 'yesterday']].applymap(set) removals = temp.diff(periods=1, axis=1).dropna(axis=1) additions = temp.diff(periods=-1, axis=1).dropna(axis=1) </code></pre> <p>Removals:</p> <pre><code> yesterday 0...
python|pandas|numpy|dataframe
15
357,310
59,840,555
argument of type 'float' is not iterable - TypeError
<p>I am simply applying some filter on data-frame and calculation 1st Quartile, but it shows me error like "TypeError: argument of type 'float' is not iterable". many sources says that it is because of NAN value in your data frame but i can not ignor that row.</p> <pre><code># Import pandas import pandas as pd import...
<p>I resolved the error by just converting row['storepartyname'] into string dynamically like str(row['storepartyname'])</p> <p><strong>Final working code</strong></p> <pre><code>outstanding_df['Flag'] = "" Distributors = ['agency','dist','distributor','pharma','agencies'] for index, row in outstanding_df.iterrows()...
python|pandas
1
357,311
59,809,321
apt-get install python3-numpy doesn't install numpy on python3, but installed on python2.7
<p>I'm trying to install numpy for python3, and I used <code>sudo apt-get install python3-numpy</code> to install numpy as I use Jetson tx2.</p> <p>Although the installation is successful, but numpy is installed on python2.7 not python3. How can I solve it?</p>
<p>Actually when you flash your Jetson TX2 with Jetpack (version), numpy package is present for <em>Python2</em> by default and not for <em>Python3</em>.<br> In order to install <em>numpy</em> for <em>Python3</em> Please follow the steps given below:-<br> 1. Check if you have pip3 installed for <em>Python3</em>. If no...
python|python-3.x|numpy|nvidia-jetson
1
357,312
59,520,777
Identify pairs of matching records using Pandas for further analysis
<p>I conduct a multiple choice survey at the start and end of the semester and I would like to analyze whether students answers to questions change significantly from begin to end.</p> <p>There will be students who answer the first one and don't the second one and vice versa, for numerous reasons. I want to drop those...
<p>starting with your initial data frame, </p> <p>first, we convert your date into a proper datetime.</p> <pre><code>df['date'] = pd.to_datetime(df['date']) </code></pre> <p>then we create two variables, the first ensures there are more than 2 counts of an email per person, the 2nd that they fall into months 1 &amp;...
pandas
1
357,313
59,587,036
Why tensorflow.one_hot is not sparse?
<p>Take the following example:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf indices = [0, 1, 2] depth = 3 tf.one_hot(indices, depth) </code></pre> <p>which outputs:</p> <pre><code>&lt;tf.Tensor: id=9, shape=(3, 3), dtype=float32, numpy= array([[1., 0., 0.], [0., 1., 0.], ...
<p>Quite likely because if you think of the output of a typical neural net for classification, it is a dense vector of likelihoods. In order for the optimization algorithm to modify the weights of the neural net, the error vector must be calculated. The error(or really, the squared error) is the sum of the outputs - tr...
python|tensorflow|linear-algebra|tensorflow2.0
1
357,314
59,726,670
How to convert float value to date9 format in pandas
<p>Basically i am sas developer. As of now i am doing sas2python migrations. Before reading to pandas dataframe i have two columns ie,</p> <pre><code>DATE NAME 01JAN1988 VARUN 11JAN1999 THARUN </code></pre> <p>After reading to pandas dataframe the <code>DATE</code> columns is automatically read as <c...
<p>you can use apply function to convert the values into date objects and datetime module to covert them:</p> <pre><code>df['DATE'] = df['DATE'].apply(lambda x: datetime.datetime.strptime(x,'%d%b%Y').date()) </code></pre> <p>Output:</p> <pre><code> DATE NAME 0 1988-01-01 VARUN 1 1999-01-11 THARUN <...
python|pandas|pandas-groupby|pandasql
0
357,315
59,554,749
time difference between datetime.time
<p>Lets say I have a dataframe:</p> <pre><code>1027 2019-01-01 07:17:00 479 2019-01-01 07:10:00 480 2019-01-01 06:10:00 </code></pre> <p>and I have a variable:</p> <pre><code>x=datetime.time(8,0) </code></pre> <p>How I can get the difference (in minutes) between each row and <code>x</code>? </p> <p>I've tr...
<p><code>time</code> doesn't support subtractions, use <code>datetime</code> instead</p> <pre><code>In [14]: x = datetime(2019, 1, 1, 8, 00, 00) In [15]: y = datetime(2019, 1, 1, 7, 17, 00) In [16]: x Out[16]: datetime.datetime(2019, 1, 1, 8, 0) In [17]: y Out[17]: datetime.datetime(2019, 1, 1, 7, 17) In [18]: x -...
python|pandas|dataframe|datetime|timestamp
1
357,316
59,503,250
Python3 Pandas Filter by Columns with Unknown Column Names
<p>Working with a data set comparing rosters with different dates. It goes through a pivot and we don't know the dates of when the rosters are pulled but the resulting data set is structured like this:</p> <pre><code>colA ColB colC colD Date:yymmdd Date:yymmdd Date:yymmdd Bob aa aa aa ...
<p>Below snippet will give you one Dataframe containing True and False as cell values of df.</p> <pre><code>df.iloc[:, 4:].eq(x) </code></pre> <p>If you want to have only those rows where x is there, then you can <code>any()</code> clause. like the way @jpp has shown in his answer.</p> <p>In your case, it will be <c...
python|python-3.x|pandas|filter
2
357,317
59,753,325
Merge dataframes by closest coordinates
<p>Imagine we have 2 dataframes with coordinates ['X','Y']:</p> <p>df1 :</p> <pre><code> X Y House № 2531 2016 175 2219 2196 11 2901 3426 201 6901 4431 46 7891 1126 89 </code></pre> <p>df2 :</p> <pre><code> X ...
<p>No silver bullet, but a way to do this is to turn the Y values in categories using <code>pd.cut</code>. Using this method, it will place the values in different bins. You need to tune the bins manually, for example set it at 20.</p> <p>Load the data:</p> <pre><code>df1 = pd.DataFrame({'X':[2531, 2219, 2901, 6901,...
python|pandas|fuzzy-comparison
0
357,318
32,316,978
numpy array multiplication slower than for loop with vector multiplication?
<p>I have come across the following issue when multiplying numpy arrays. In the example below (which is slightly simplified from the real version I am dealing with), I start with a nearly empty array <code>A</code> and a full array <code>C</code>. I then use a recursive algorithm to fill in <code>A</code>.</p> <p>Be...
<p>First of all, you can easily replace:</p> <pre><code>n_array = np.arange(0,c-1) temp_vec= C[c-n_array] * A[n_array] A[c] += temp_vec.sum(axis=0) </code></pre> <p>with:</p> <pre><code>A[c] += (C[c:1:-1] * A[:c-1]).sum(0) </code></pre> <p>This is much faster because indexing with an array is much slower than slic...
python|arrays|performance|numpy|cython
7
357,319
32,368,078
How do I calculate a rolling mean with custom weights in pandas?
<p>The Pandas documentation <a href="http://pandas.pydata.org/pandas-docs/stable/computation.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/computation.html</a> has an example of how to calculate moving averages:</p> <pre><code>ser = pd.Series(np.random.randn(10), index=pd.date_range('1/1/2000', peri...
<p>I'm not Math expert, but <em>stahlous</em> explain what you need <a href="https://github.com/pydata/pandas/pull/8238#issuecomment-56139375" rel="nofollow">here</a>. </p> <p>I try test it:</p> <pre><code>import pandas as pd ser = pd.Series([1,1,1], index=pd.date_range('1/1/2000', periods=3)) print ser rm1 = pd.ro...
python|pandas|moving-average
2
357,320
32,242,992
Confusing datetime objects in pandas
<p>I face some confusion with the way <code>pandas</code> is handling time-related objects.</p> <p>If I do </p> <pre><code>x = pd.datetime.fromtimestamp(1440502703064/1000.) # or x = pd.datetime(1234,5,6) </code></pre> <p>then <code>type(x)</code> returns <code>datetime.datetime</code> in either of the cases. Howeve...
<p>I'm not 100% sure, since I haven't studied the underlying code, but the conversion from <code>datetime.datetime</code> happens the moment the value is "incorporated" into a <code>DataFrame</code>.</p> <p>Outside a <code>DataFrame</code>, pandas will try to do the smart thing and return something sensible when using...
python|datetime|numpy|pandas
1
357,321
32,348,116
Pandas and moving average
<p>I have data:</p> <pre><code>date count 2015-09-01 5 2015-09-02 4 2015-09-03 8 2015-09-04 8 2015-09-05 3 2015-09-06 5 2015-09-07 9 2015-09-08 7 2015-09-09 5 2015-09-10 7 ... </code></pre> <p>I need to get <strong>moving average</strong> over the last 5 days.</p> <p>How can I do it on python and pa...
<p>IIUC you want <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.rolling_mean.html#pandas.rolling_mean" rel="nofollow"><code>rolling_mean</code></a>:</p> <pre><code>In [136]: df.set_index('date', inplace=True) pd.rolling_mean(df['count'], window=5) Out[136]: date 2015-09-01 NaN 2015-09-02 ...
python|pandas|data-analysis
4
357,322
32,319,726
Time between events (pandas)
<p>I want to find the time elapsed between 2 events A and B. More specifically, whenever event A occurs, I want to know how long it takes before the next occurence of event B. </p> <p>Take a look at this example:</p> <pre><code>import pandas as pd import numpy as np np.random.seed(5) strings=list('AB') data=[strings...
<p>You could use <code>searchsorted</code> to find the indices where the start dates would be inserted into an array of end dates while maintaining the end dates in sorted order. This array of indices tells you which end date to associate with each start date.</p> <pre><code>import pandas as pd import numpy as np np....
python|pandas|time-series
5
357,323
32,574,863
increment float32 by smallest possible amount (using numpy currently)
<p>Trying to increment a single-precision floating point number by the smallest possible amount. I see there is a nextafter function, but I can't get that to work for single precision numbers. Any suggestions?</p>
<p>Seems to work fine:</p> <pre><code>&gt;&gt;&gt; x = np.float32(1.) &gt;&gt;&gt; y = np.nextafter(x, np.float32(2.)) &gt;&gt;&gt; y 1.0000001 &gt;&gt;&gt; type(y) numpy.float32 </code></pre>
python|numpy
7
357,324
32,569,188
SciPy SVD vs. Numpy SVD
<p>Both SciPy and Numpy have built in functions for singular value decomposition (SVD). The commands are basically <code>scipy.linalg.svd</code> and <code>numpy.linalg.svd</code>. What is the difference between these two? Is any of them better than the other one?</p>
<p>From the <a href="https://www.scipy.org/scipylib/faq.html#why-both-numpy-linalg-and-scipy-linalg-what-s-the-difference" rel="noreferrer">FAQ page</a>, it says <code>scipy.linalg</code> submodule provides a more complete wrapper for the Fortran LAPACK library whereas <code>numpy.linalg</code> tries to be able to buil...
python|numpy|scipy|svd
7
357,325
32,317,479
Slice pandas dataframe into equal lengths of 34
<p>I have a pandas data frame that looks like the below:</p> <pre><code> page hour count 0 3899549 399593 1530 1 3899549 399594 1610 2 3899549 399595 1592 3 3899549 399596 1220 4 3899549 399597 1729 5 3899549 399598 224 6 3899549 399599 481 </code></pre> <p>The full data set is available...
<p>I think your description is still confusing.</p> <p>It's a little tricky to get it all right</p> <pre><code>import pandas as pd cols = ['instance', 'page', 'hour', 'count'] data = [ (0, 3899549, 399593, 1530), (1, 3899549, 399594, 1610), (2, 3899549, 399595, 1592), (3, 3899549, 399596, 1220), ...
python|pandas
2
357,326
32,154,475
einsum and distance calculations
<p>I have searched for a solution to determine distances using einsum for numpy arrays that are not equal in their number of rows, but equal in columns. I have tried various combinations but the only way I can do it successful is using the following code. I am obviously missing something and the literature and numero...
<p>If I understood the question correctly, the for-loop code that you have posted looks generic to me when considering 2D arrays only. Now, if you are looking to have a generic vectorized solution with a single call to <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow norefer...
python|arrays|numpy|euclidean-distance
10
357,327
40,336,740
How do I compute the convolution input shape/size?
<p><strong>If I have the output shape, filter shape, strides and padding,</strong> </p> <p>filter shape: <code>[kernel_height, kernel_width, output_depth, input_depth]</code></p> <p>output shape: <code>[batch, height, width, depth]</code></p> <p><code>strides=[1,1,1,1]</code></p> <p><code>padding='VALID'</code></p>...
<p>It's <code>batch, height + kernel_height - 1, width + kernel_width - 1, input_depth</code></p> <p><code>batch</code> at the beginning is somewhat obvious, so is <code>input_depth</code> at the end. To understand <code>height + kernel_height - 1</code>, consider how kernel is applied. If you input image was say 10 b...
neural-network|tensorflow|deep-learning|caffe|conv-neural-network
1
357,328
40,424,835
Select maximum in array according to condition
<p>I have a numpy array <code>[6,5,4,3,2,1,0,1]</code> to define a metric, and I have selected some indices from this array according to a condition. The array indices are <code>[1,2]</code>. Now I want to select the element among the selected indices that has corresponding maximum value in metric array.</p> <p>The...
<p>I think you want:</p> <pre><code>import numpy as np x = np.array([6,5,4,3,2,1,0,1]) idx = np.array([1,2]) y = idx[ np.argmax(x[idx]) ] </code></pre>
python|numpy
2
357,329
40,724,135
Plot a time series grouped by id
<p>I want to plot a time series grouped by id. So that time is my x-value and 'value' is my y-value. How can I plot x and y grouped by 'id' 1? </p> <pre><code>id time value 1 1 0.3 1 2 0.6 1 3 0.9 2 1 0.1 2 2 0.3 2 3 0.6 3 1 0.2 3 2 0.4 3 3 0.5 </code>...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="noreferrer"><code>pivot</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.bar.html" rel="noreferrer"><code>DataFrame.plot.bar</code></a> or only <a h...
python|pandas|matplotlib
8
357,330
40,667,874
Visualize conv2d filter for TensorBoard image_summary
<p>I want to visualize the filter weights of my CNN. They are of size <code>height</code>x<code>width</code>x<code>input</code>x<code>output</code>.</p> <p>However, TensorBoard requires the image_summary to be a Tensor of shape <code>batches</code>x<code>height</code>x<code>width</code>x<code>channels</code>. </p> <p...
<p>A normal image batch has shape <code>[batch, height, width, 3]</code> so you can make Tensorboard show a batch of colored images for the first convolution layer by transposing the filters to <code>[output, height, width, 3]</code>. This answer has the code: <a href="https://stackoverflow.com/questions/35759220/how-t...
python|numpy|tensorflow|tensorboard
1
357,331
40,595,967
Fast way to check if a numpy array is binary (contains only 0 and 1)
<p>Given a numpy array, how can I figure it out if it contains only 0 and 1 quickly? Is there any implemented method?</p>
<p>Few approaches -</p> <pre><code>((a==0) | (a==1)).all() ~((a!=0) &amp; (a!=1)).any() np.count_nonzero((a!=0) &amp; (a!=1))==0 a.size == np.count_nonzero((a==0) | (a==1)) </code></pre> <p>Runtime test -</p> <pre><code>In [313]: a = np.random.randint(0,2,(3000,3000)) # Only 0s and 1s In [314]: %timeit ((a==0) | (a...
python|numpy
15
357,332
40,448,039
Tensorflow: get_shape() for use in reshape()
<p>I have some tensor-flow code that involves some reshaping of tensors:</p> <pre><code># sigma has shape (15000,20,2) sigma_shape = sigma.get_shape() # We want to reshape it to (300000,2) sigma = tf.reshape(sigma, [-1, sigma_shape[-1]]) # (300000,2) # Because we have to do this operation Sigma = matrix_with_upper_v...
<p>You can extract the <code>value</code> of a <code>Dimension</code> object. Thus</p> <pre><code> sigma_shape[-1].value </code></pre> <p>Is an <code>int</code> value that you can use in you <code>tf.reshape</code> calls</p>
tensorflow
0
357,333
40,433,398
Placing n rows of pandas a dataframe into their own dataframe
<p>I have a large dataframe with many rows and columuns.</p> <p>An example of the structure is:</p> <pre><code>a = np.random.rand(6,3) df = pd.DataFrame(a) </code></pre> <p>I'd like to split the DataFrame into seperate data frames each consisting of 3 rows.</p>
<p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html" rel="nofollow noreferrer">numpy.split()</a> method:</p> <pre><code>In [8]: df = pd.DataFrame(np.random.rand(9, 3)) In [9]: df Out[9]: 0 1 2 0 0.899366 0.991035 0.775607 1 0.487495 0.250279 0....
python-3.x|pandas
2
357,334
40,539,783
How can I use `pivot` to track wins and loses?
<p>Suppose I have some team data as a dataframe <code>df</code>.</p> <pre><code>home_team home_score away_team away_score A 3 C 1 B 1 A 0 C 3 B 2 </code></pre> <p>I'd like to a dataframe indicating how many times...
<p>This will create a new dataframe with just the winners and loosers. It can be pivoted to created what you are looking for.</p> <p>I made some additional data to fill in some of the pivot table values</p> <pre><code>import pandas as pd data = {'home_team':['A','B','C','A','B','C','A','B','C'], 'home_scor...
python|pandas
4
357,335
40,640,458
Find Null Values in Rows using GroupBy
<p>I want to summarize the the data, but I want to group the data first to get the NULL counts. I can figure out how to summarize the data the way I want, but I can't seem to figure out how to translate this using a groupby function first.</p> <p>Can anyone point me to the proper syntax?</p> <p>Thank you</p> <pre><...
<p>I figured it out. </p> <pre><code>group.get_group("&lt;GROUPNAME&gt;").isnull().sum() </code></pre> <p>Which results in:</p> <pre><code>BLAH 1 COUNT 2 MEASURE 1 dtype: int64 </code></pre> <p>Thanks all</p>
python|python-2.7|pandas
-2
357,336
40,711,900
replacing empty strings with NaN in Pandas
<p>I have a pandas dataframe (that was created by importing a csv file). I want to replace blank values with NaN. Some of these blank values are empty and some contain a (variable number) of spaces <code>''</code>, <code>' '</code>, <code>' '</code>, etc.</p> <p>Using the suggestion from <a href="https://stackoverf...
<p>Indicate it has to start with blank and end with blanks with ^ and $ :</p> <pre><code>df.replace(r'^\s*$', np.nan, regex=True, inplace = True) </code></pre>
python|pandas|replace
18
357,337
40,646,458
list comprehension in pandas
<p>I'm giving a toy example but it will help me understand what's going on for something else I'm trying to do. Let's say I want a new column in a dataframe 'optimal_fruit' that is apples * orange - bananas.</p> <p>I can do something like this to get it. </p> <pre><code>df2['optimal_fruit'] = df2['apples'] * df2['ora...
<p>Essentially your list comprehension statement is a set of 3 nested loops. In code:</p> <pre><code>l = [] for x in df2['apples']: for y in df2['oranges']: for z in df2['bananas']: l.extend([x * y - z]) </code></pre> <p>The length of your resultant list will be 3 times the length of your Data...
python|pandas|list-comprehension
23
357,338
40,544,982
wide vs long format when saving data in pandas hdf5
<p>pandas data frame are in general represented in long ( a lot of rows) or wide (a lot of columns) format. </p> <p>I'm wondering which format is faster to read and occupies less memory when saved as hdf file (<code>df.to_hdf</code>). </p> <p>Is there a general rule or some cases where one of the format should be pr...
<p>IMO long format is much more preferable as you will have much less metadata overhead (information about column names, dtypes, etc.).</p> <p>In term of memory usage they are going to be more or less the same:</p> <pre><code>In [22]: long = pd.DataFrame(np.random.randint(0, 10**6, (10**4, 4))) In [23]: wide = pd.Da...
pandas|dataframe|hdf|wide-column-store
0
357,339
40,398,232
List of dictionaries from numpy array without for loop
<p>Is there a way to vectorize an operation that takes several numpy arrays and puts them into a list of dictionaries?</p> <p>Here's a simplified example. The real scenario might involve more arrays and more dictionary keys.</p> <pre><code>import numpy as np x = np.arange(10) y = np.arange(10, 20) z = np.arange(100,...
<p>With your small example, I'm having trouble getting anything faster than the combination of list and dictionary comprehensions</p> <pre><code>In [105]: timeit [{'x':i, 'y':j, 'z':k} for i,j,k in zip(x,y,z)] 100000 loops, best of 3: 15.5 µs per loop In [106]: timeit [{'key':{'x':i, 'y':j, 'z':k}} for i,j,k in zip(x,...
python|performance|numpy|vectorization
3
357,340
18,726,497
how to update existing data frame in pandas?
<p>Given these two data frames:</p> <pre><code>&gt;&gt;&gt; df1 = pd.DataFrame({'c1':['a','a','b','b'], 'c2':['x','y','x','y'], 'val':0}) &gt;&gt;&gt; df1 c1 c2 val 0 a x 0 1 a y 0 2 b x 0 3 b y 0 &gt;&gt;&gt; df2 = pd.DataFrame({'c1':['a','a','b'], 'c2':['x','y','y'], 'val':[12,31,14]}) &gt;&g...
<p>Yes, take a look at <a href="http://pandas.pydata.org/pandas-docs/dev/merging.html#merging-together-values-within-series-or-dataframe-columns" rel="noreferrer">combine_first</a> or <a href="http://pandas.pydata.org/pandas-docs/dev/merging.html#merging-together-values-within-series-or-dataframe-columns" rel="noreferr...
python|pandas|dataframe
8
357,341
18,572,083
Extend and forward fill numpy array
<p>I'd like to duplicate each line of an array N times. Is there a quick way to do so?</p> <p>Example (N=3):</p> <pre><code># INPUT a=np.arange(9).reshape(3,3) array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) # OUTPUT array([[0, 1, 2], [0, 1, 2], [0, 1, 2], [3, 4, 5], [3, 4, 5], ...
<p>This is a job for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow"><code>np.repeat</code></a>:</p> <pre><code>np.repeat(a,3,axis=0) array([[0, 1, 2], [0, 1, 2], [0, 1, 2], [3, 4, 5], [3, 4, 5], [3, 4, 5], [6, 7, 8], [6, 7...
python|arrays|numpy
3
357,342
18,697,644
IPython + Pandas Can't plot data from .csv
<p>Im importing a csv with Pandas in IPython. When displaying the DataFrame it looks like:</p> <pre> 2013 2012 2011 2010 2009 2008 2007 2006 2005 Jan 11,875 10,989 10,852 11,762 13,850 14,269 14,075 9,222 - Feb 10,206 10,501 15,713 11,785 13,886 14,289 12,635 13,149 - ...
<p>Thanks for all the suggestions! It pointed me in the right direction. I managed to fix the issue with</p> <pre><code>df = df.replace(',', '', regex=True) df = df.replace('-', 'NaN', regex=True).astype('float') df.plot() </code></pre>
python-3.x|pandas|ipython-notebook
3
357,343
18,672,584
Identify elements of a dataframe satisfying a condition
<p>Suppose I have the following dataframe:</p> <pre><code>df = pd.DataFrame({'A':[1,2,3,400], 'B':[100,2,3,4]}) </code></pre> <p>And I want to find the locations (by index and column) of every element larger than 50, i.e. a correct output would be:</p> <pre><code>[(3,'A'), (0,'B')] </code></pre> <p>What would be th...
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow">stack</a> here and then use a boolean mask (for those values over 50):</p> <pre><code>In [11]: s = df.stack() In [12]: s Out[12]: 0 A 1 B 100 1 A 2 B 2 2 A 3 B...
pandas
3
357,344
61,841,672
No matching distribution found for torch==1.5.0+cpu on Heroku
<p>I am trying to deploy my Django app which uses a machine learning model. And the machine learning model requires pytorch to execute. When i am trying to deploy it is giving me this error<br></p> <pre><code>ERROR: Could not find a version that satisfies the requirement torch==1.5.0+cpu (from -r /tmp/build_4518392d43...
<p>PyTorch does not distribute the CPU only versions over PyPI. They are only available through their custom registry.</p> <p>If you select the CPU only version on <a href="https://pytorch.org/get-started/locally/" rel="noreferrer">PyTorch - Get Started Locally</a> you get the following instructions:</p> <pre class="...
python|django|heroku|pytorch|torch
17
357,345
61,902,892
Add data in a row (from another file) if that row consists of a particular string(city)
<p>I have two csv files and I want to add number of confirmed cases in front of the state in another csv file. Also this had to match with the date as well.</p> <pre><code> #updated.csv address Date time Albany,us 1/30/2020 Atlanta, US 1/30/2020 </code></pre> <p>2nd file </p> <pre><code...
<p>You should show some more information in your question. It is hard to guess what you want to achieve. I assume you should extract the State from the <code>covid.csv</code> in a new column and use group by that new column to calculate the number of Confirmed deaths per state. Join the <code>updated.csv</code> datafra...
python-3.x|pandas|csv|dataframe
0
357,346
61,816,158
How to divide the dataset when it is distributed
<p>Now I want to divide a dataset into two parts: the train set and validation set. I know that on a single GPU I can do this using a sampler:</p> <pre><code>indices = list(range(len(train_data))) train_loader = torch.utils.data.DataLoader( train_data, batch_size=args.batch_size, sampler=torch.utils.data.s...
<p>You can split <code>torch.utils.data.Dataset</code> before creating <code>torch.utils.data.DataLoader</code>.</p> <p>Simply use <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.random_split" rel="nofollow noreferrer">torch.utils.data.random_split</a> like this:</p> <pre><code>train, validation =...
python|pytorch|distributed
2
357,347
62,023,292
Calculate the empirical distribution of a sequence in NumPy?
<p>Suppose <code>A</code> is a (NumPy) length-<code>M</code> array of integers in 0, 1, ..., <code>N-1</code>, I would like to calculate an array of length <code>N</code>, <code>c</code>, such that <code>c[i] = sum(A == i)</code>. A <code>for</code>-based solution is obvious, but is there a faster solution?</p> <p>I ...
<p>I think I found a solution. </p> <pre><code>N = 10 # just an example M = 10000 A = np.random.randint(0, N, size=M) # for-based solution c1 = [sum(A == i) for i in range(N)] # using numpy unique c2 = np.zeros(N, dtype=int) val, count = np.unique(A, return_counts=True) c2[val] = count assert all(c2 == c1) </cod...
python|numpy
0
357,348
61,631,826
How to have all the contain matches of a string column?
<p>Let's take this small dataframe :</p> <pre><code>df = pd.DataFrame(dict(Name=['abc','abcd','bc'])) Name 0 abc 1 abcd 2 bc </code></pre> <p>I would like to create a new dataframe :<br> - Having its index and column names equal to the values of column Name<br> - Whose values are equal to true or false if th...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>Series.str.contains</code></a> in list comprehension, create masks and join together by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="n...
python|string|pandas|dataframe|contains
3
357,349
61,690,689
Bert pre-trained model giving random output each time
<p>I was trying to add an additional layer after huggingface bert transformer, so I used <code>BertForSequenceClassification</code> inside my <code>nn.Module</code> Network. But, I see the model is giving me random outputs when compared to loading the model directly.</p> <p>Model 1:</p> <pre><code>from transformers i...
<p>The reason is due to the random initialization of the classifier layer of Bert. If you print your model, you'll see</p> <pre><code> (pooler): BertPooler( (dense): Linear(in_features=768, out_features=768, bias=True) (activation): Tanh() ) ) (dropout): Dropout(p=0.1, inplace=False) (classifi...
python-3.x|pytorch|huggingface-transformers|bert-language-model
5
357,350
61,689,702
Deleting sub array from a larger multi dimensional array without changing the dimensions
<p>Having arrays a, and b I would like to get the array c which excludes a from b.</p> <pre><code>a=np.array([8,14]) [ 8 14] b=np.array([[3,2],[8,10],[8,14],[17,65]]) [[ 3 2] [ 8 10] [ 8 14] [17 65]] </code></pre> <p>The desired c is :</p> <pre><code>print(c) [[ 3 2] [ 8 10] [17 65]] </code></pre> <p>nump...
<p>try this:</p> <pre><code>c = b[np.any(b != a, axis=(1))] print(c) </code></pre>
python|numpy|numpy-ndarray
1
357,351
61,807,858
Subtracting values based on a relationship table
<p>I want to develop some code that will calculate the value of the target location (down gradient) by using a relationship table of targets and sources. The general formula is (value = down gradient - up gradient) or, given my relationship table, (value = target - all contributing source locations).</p> <p>Operationa...
<p>Well, I think I found one way to accomplish what I wanted to. I am sure there is a more efficient way, but this seems to work for me at the moment. I am still open to suggestions if there is a more elegant/efficient solution out there.</p> <pre><code>import pandas as pd import networkx as nx import numpy as np ...
python|pandas|dataframe|math|networkx
0
357,352
61,766,655
Fill Column using a for loop from multiple dictionaries
<p>I have multiple dictionaries and I'm trying to append them into one dataframe.</p> <pre><code>import pandas as pd dict1 = {'A': '1', 'B': [{'att1': 'value1', 'att2': 'value2'}]} dict2 = {'A': '2', 'B': [{'att1': 'value3', 'att2': 'value4'}]} df = pd.DataFrame() dict = [dict1, dict2] df['A'] = [] for i in range(0, 2...
<p>u can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html" rel="nofollow noreferrer">json normalize</a>:</p> <pre><code>from pandas import json_normalize def normalize(mapping): return json_normalize(mapping, 'B', 'A') pd.concat((normalize(dict1),normalize(dict2))...
python|pandas|dictionary|for-loop|append
1
357,353
61,673,931
Iris-Data - regplot out of dataframe -> choosing color
<p>Problem:My dataframe contains of the Iris-Dataset and looks like this:</p> <p><a href="https://i.stack.imgur.com/l8LqY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l8LqY.png" alt="enter image description here"></a></p> <p>It has 50 entries of 3 species each, making 150 in total. Now I want to...
<p>You can specify the colors following <a href="https://python-graph-gallery.com/45-control-color-of-each-marker-seaborn/" rel="nofollow noreferrer">this link</a>. Since they are fixed, then a easier solution without plotting twice:</p> <pre><code>colors = {'Iris-setosa': 'red', 'Iris-versicolor': 'blue', 'Iris-virgi...
python|pandas|plot|seaborn
1
357,354
62,001,813
Pandas condition-based row elimination in DataFrame
<p>I have a DataFrame in with information stored in a column until an unknown row number. After this row number, the column only stores NaN values. However, throughout the column some random NaN values appear as well. I want a cumulation to check how many NaN values are repeated to determine the the last row storing in...
<p>To achieve this you could look at the shift function in Pandas, then shift twice and check if all three values are <code>NaN</code></p> <p>Try this:</p> <pre><code># Find the rows where itself and the two subsequent rows are null in the bananas column All_three_null = Fruits[‘banana’].isna() &amp; Fruits[‘banana’]...
excel|pandas|dataframe
1
357,355
61,998,379
Pandas to_csv should suppress exponential
<p>I have a dataframe of datatype object and while writing to CSV,it's getting converted to exponential and I want to retain the value as it is.I tried everything like</p> <pre><code>pd.set_option('display.precision',12) </code></pre> <p>works only if I print the column ..But when I write it to csv,its getting conver...
<p>What you set is a display precision, i.e. what is displayed on the screen. For writing to file with <code>to_csv</code> use <code>float_format</code> option:</p> <pre><code>df.to_csv('your.csv', sep=',', float_format='%f') </code></pre> <p>Example:</p> <pre><code>import pandas as pd import numpy as np X = np.ra...
pandas|python-2.7
1
357,356
61,687,925
CuDNN crash in TF 2.x after many epochs of training
<p>I'm currently becoming more and more desperate concerning my tensorflow project. It took many hours installing tensorflow until I figured out that PyCharm, Python 3.7 and TF 2.x are somehow not compatible. Now it is running, but I get a really unspecific CuDNN error after many epochs of training. Do you know if my c...
<p><strong>For those who come after me:</strong></p> <p>I played a lot around with different versions. I even tried to get CUDA 10.2 to work by symlinking the new dlls with the old names. But even this did not fix the bug.</p> <p><strong>I finally managed to get it to work, by removing all NVidia stuff (including dri...
python|tensorflow|pycharm|cudnn
2
357,357
61,874,527
Unnest a records column in a pandas dataframe
<p>I am wondering if there is a <code>pandas</code> way (in-built, or generally better) to unnest a column of records (where records are <code>List[dict]</code>) into a <code>DataFrame</code>.</p> <p>Sample data:</p> <pre><code>import pandas as pd expected = pd.DataFrame({ 'A': [1, 1, 2], 'asset_id': ["aaa"...
<p>IIUC <code>explode</code> <code>pd.Series</code> and <code>set_index</code></p> <pre><code>df1 = df.set_index('A')['B'].explode().apply(pd.Series).reset_index() A asset_id another_prop 0 1 aaa 2 1 1 AAA 4 2 2 bbb 3 </code></pre> <p>or as @anky so kindly po...
python|pandas|dataframe
3
357,358
61,923,552
Use posenet from tensorflow.js in electron
<p>I am trying to use the posenet MobileNetV1 network in an electron app. I want to be able to read image from file system (it does not matter if it is a png or jpg), and run it through the network.</p> <p>What have I done so far:</p> <p>I am using the following modules:</p> <pre><code>import * as posenet from '@ten...
<p>electron has two separated contexts; one that can be considered as a server side context called the main context and the renderer context in which the browser and its scripts are called. Though the question is not precise enough, it is trying to execute posenet in the main context of electron which can be compared a...
javascript|electron|tensorflow.js|pose-estimation
1
357,359
61,777,441
List of sift descriptors to an NxN matrix
<p>I have a lot of sift descriptor from a dense-sift algorithm. Its an Array of N SIFT descriptor. One descriptor looks like this one:</p> <pre><code>[14.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 16.0, 0.0, ...] </code></pre> <p>y Goal is to transform the descriptors to an NxN Matrix so i can use them...
<p>You can use <code>stack</code> and <code>reshape</code> and specify the desired axis like the following:</p> <pre><code>import numpy as np arr1 = np.ones((1, 128)) arr1 = arr1.reshape((4,4,8)) arr2 = np.ones((1, 128)) arr2 = arr2.reshape((4,4,8)) print(np.stack((arr1, arr2), axis=3).shape) # (4, 4, 8, 2) </code...
python|numpy|sift
0
357,360
61,627,557
pandas pivot table with parameter "columns" but no value for each category of the column
<p>I'd like to apply the pd.pivot_table() to get the number of each categorical value for column 'categories'.</p> <p>Here, the basic info of the dataset is as following:</p> <pre><code>df.info() Data columns (total 3 columns): location 2270 non-null object time ...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>GroupBy.size</code></a> function for count and also <code>values</code> parameter should be omit:</p> <pre><code>table=pd.pivot_table(df, in...
python|pandas|pivot
1
357,361
61,623,582
Efficiently transforming data in pandas
<p>What would be the best way to approach this problem using pandas and python? </p> <p>I currently have a pandas data-frame in a relatively awkward format, for example:</p> <pre><code> Country Indicator 2000 2010 0 Afghanistan foo 1 2.5 1 Afghanistan bar 3 4.5 2 ...
<p>This transformation is called "pivoting", or sometimes "casting" or "unmelting". It's so common that <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer">it's covered by specific functions in the api.</a>:</p> <pre><code>df_years = df.pivot(index...
python|pandas|dataframe
3
357,362
61,691,534
How to write a transformer in sklearn pipeline with multiple dataframe column inputs
<p>My dataframe looks like </p> <pre><code>+---------------------+-------------+---------+---------+---------+---------+ | Date | pre_close | open | high | low | close | |---------------------+-------------+---------+---------+---------+---------+ | 1992-04-27 00:00:00 | 0.93152 | 0....
<p>I think you can simply use pandas apply:</p> <pre><code>df["num"] = df.apply(lambda x: np.max([x['high']-x['high'], np.abs(x['pre_close']-x['high']), np.abs(x['pre_close']-x['low'])]), axis=1) </code></pre>
python|pandas|scikit-learn|pipeline|sklearn-pandas
0
357,363
61,959,012
Create a pandas dataframe column depending if a value is null or not
<p>I have Data science-related project about a course students took in 2016. I have a column which shows at what dates did the students upgrade their course. If the course has not been upgraded the value is Null. What I want is to create a new data frame consisting of only this upgraded column consisting of "yes" or "n...
<p>You can achieve this with the <code>isna</code> method and <a href="https://numpy.org/doc/1.18/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> (think of it as <code>numpy.if_then_else</code>).</p> <pre><code>&gt;&gt;&gt; pd.DataFrame(np.where(registration.isna(), 'No', '...
python|pandas|data-science
3
357,364
62,008,485
Load a .tab file with different delimiters in header and body
<p>I'm having trouble reading a .tab file into Python 3.7 and am hoping someone might be able to help. The problem is that column names in the header and the actual data use different delimiters:</p> <pre><code>Example of part of column row: | ID | DESIGNATION | GLON | GLAT | ...
<p>You can read headers and data with two calls to read_csv. First we read the data skipping the header row and then we read just the header and assign these column labels to the dataframe we read in the first step:</p> <pre><code>s="""| ID | DESIGNATION | GLON | GLAT | ...
python|python-3.x|pandas
0
357,365
61,877,437
Dynamically count number of business days excluding holiday calendar in Python
<p>I want to calculate the number of business days between two dates and create a new pandas dataframe column with those days. I also have a holiday calendar and I want to exclude dates in the holiday calendar while making my calculation. </p> <p>I looked around and I saw the numpy busday_count function as a useful to...
<p>This should work:</p> <pre><code>import pandas as pd import numpy as np import holidays df = {'start' : ['2019-01-02', '2019-02-01'], 'end' : ['2020-01-04', '2020-03-05']} df = pd.DataFrame(df) holidays_country = holidays.CountryHoliday('UK') def f(x): return np.busday_count(x[0],x[1],holidays=holidays...
python|pandas|numpy|dataframe|time-series
0
357,366
62,041,850
Looping over Pandas' groupby output when grouping by multiple columns and missing data
<p>Grouping by multiple columns with missing data:</p> <pre><code>data = [['Falcon', 'Captive', 390], ['Falcon', None, 350], ['Parrot', 'Captive', 30], ['Parrot', 'Wild', 20]] df = pd.DataFrame(data, columns = ['Animal', 'Type', 'Max Speed']) </code></pre> <p>I understand how missing data are dealt with when ...
<p>In the post concerning <em>groupby columns with NaN (missing) values</em> there is a sentence: <em>NA groups in GroupBy are automatically excluded</em>.</p> <p>Apparently, in case of grouping by <strong>multiple</strong> columns, the same occurs if <strong>any level</strong> of grouping key contains <em>NaN</em>.</...
python|pandas|pandas-groupby
1
357,367
61,894,619
Pandas sample() with conditions
<p>I have this dataframe (shortened) :</p> <pre><code>+-------+------------+--------+----------+-------+------+ | index | id_product | margin | supplier | price | seen | +-------+------------+--------+----------+-------+------+ | 0 | 100000000 | 92.00 | 14 | 0.56 | 2 | | 1 | 100000230 | 72.21 | 2...
<blockquote> <ul> <li>the 3 rows selected should have 3 ecom_id different : (14,27,13) is good, (14,27,14) is not.</li> </ul> </blockquote> <p>Setting <code>replace=False</code> in <code>pd.sample</code> should achieve this if <code>ecom_id</code> is unique.</p> <blockquote> <ul> <li>rows with lower seen sh...
python|python-3.x|pandas|dataframe
2
357,368
61,967,963
ModuleNotFoundError: No module named 'tensoflow'
<pre><code>%matplotlib inline import tensoflow as tf import matplotlib.pyplot as plt from rnn.lstm_recurrent_model import LSTMRecurrentModel from rnn.lstm_solver import LSTMSolver from rnn.data_util import load_word_based_text_input </code></pre> <p><strong>But I got error like below</strong></p> <p>ModuleNotFoundE...
<p>it should be </p> <pre><code>import tensorflow as tf </code></pre> <p>You have mistakenly written</p> <pre><code>import tensoflow as tf </code></pre> <p>Typing mistake.</p>
tensorflow|keras|recurrent-neural-network
1
357,369
61,715,369
ImportError: No module named 'numpy.testing.nosetester'
<p>I am facing an issue when I run 'from sklearn.model_selection import train_test_split' in jupyter notebook. I tried to upgrade/reinstall numpy, scipy and pandas but still cannot fix the problem. Please help. Thanks in advance.</p>
<p>Upgrade numpy/scipy.</p> <p>( Possible duplicate: <a href="https://stackoverflow.com/questions/59474533/modulenotfounderror-no-module-named-numpy-testing-nosetester">ModuleNotFoundError: No module named &#39;numpy.testing.nosetester&#39;</a> )</p> <p>Using Python3:</p> <pre><code>pip3 install numpy==1.16.4 </code...
tensorflow
3
357,370
61,932,120
Keras shape error when given input from the front end
<p>I am trying to build a chatbot using keras and bag of words model. But when i am trying to input the answer from the front end , this is the error that i get :- </p> <pre><code>ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 69 but received input...
<p>You have to define correctly the input and output shapes of your model</p> <pre><code>import tensorflow import numpy as np training = np.random.uniform(0,1, (24, 69)) output = np.random.randint(0,2, (24, 13)) model = tensorflow.keras.Sequential([ tensorflow.keras.layers.Dense(8,input_shape=(training.shape...
python-3.x|tensorflow|machine-learning|keras
0
357,371
62,038,762
Group categories based on values from df.groupby
<p>I'd like to group again my grouped data from df.groupby. On my data frame, I grouped my languages column by counting its row occurrences. Below is my code:</p> <p><code>grouped = df_covid_qua.groupby('LANG')['ID'].count()</code></p> <p><code>grouped</code> data works as expected. Below is its output:</p> <pre><co...
<p>Use:</p> <pre><code>s = df_covid_qua.groupby('LANG')['ID'].count() #first sort output s = s.sort_values(ascending=False) #specify how many last unique values is replaced N = 4 #remove duplicates and get last smallest values with swap order of values v = s.drop_duplicates().nsmallest(N).iloc[::-1] #generate LANG ...
python|pandas|dataframe
0
357,372
62,013,503
Count number of occurences of a particular value in each column in pandas dataframe
<p>I have generated a pandas dataframe using below code where an example sequence column is like '0-0-0-1-0-0-2-0-0-0-0' I split the sequence string into different columns</p> <pre><code>df = DataFrame(data, columns = ['id', 'sequence']) print(df.sequence.str.split("-", expand=True)) </code></pre> <p>0 1 2 3 ...
<p>Have you tried this?</p> <pre><code>df.rename(columns={"A": "NewName", "B": "NewName"}) </code></pre>
python|pandas|dataframe|count|pandas-groupby
0
357,373
61,948,244
Efficient sparse matrix column change
<p>I'm implementing an efficient PageRank algorithm so I'm using sparse matrices. I'm close, but there's one problem. I have a matrix where I want the sum of each column to be one. This is easy to implement, but the problem occurs when I get a matrix with a zero column. </p> <p>In this case, I want to set each element...
<p>You can't add new nonzero values without reallocating and copying the underlying data structure. If you expect these zero columns to be very common (> 25% of the data) you should handle them in some other way, or you're better off with a dense array.</p> <p>Otherwise try this:</p> <pre><code>import scipy.sparse M...
python-3.x|algorithm|numpy|scipy|sparse-matrix
1
357,374
61,915,125
How to find N maximum product subarrays of M elements of a Numpy array?
<p>I have a Numpy array, and I need to find the N maximum product subarrays of M elements. For example, I have the array <code>p = [0.1, 0.2, 0.8, 0.5, 0.7, 0.9, 0.3, 0.5]</code> and I want to find the 5 highest product subarrays of 3 elements. Is there a "fast" way to do that?</p>
<p>Here is another quick way to do it:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np p = [0.1, 0.2, 0.8, 0.5, 0.7, 0.9, 0.3, 0.5] n = 5 m = 3 # Cumulative product (starting with 1) pc = np.cumprod(np.r_[1, p]) # Cumulative product of each window w = pc[m:] / pc[:-m] # Indices of the first el...
python|numpy|numpy-ndarray|sub-array
1
357,375
61,807,663
How to identify columns that contain only NULL values?
<p>I have a CSV file with 400+ columns. Many of them have no records. I am using the following to display <em>all</em> columns and to show a count of records per column: </p> <pre><code>pd.set_option('display.max_columns', None) df.isna().sum() </code></pre> <p>The result set is only showing the first 5 and the last ...
<p>As @Amitai Irron pointed out in his comment, it'll only show you the edges of the frame, however, you can change Jupyter options for that print to set the rows/columns diplay max to none which will show you all of the datatframe:</p> <pre><code>with pd.option_context('display.max_rows', None, 'display.max_columns',...
python|pandas|null|jupyter-notebook
0
357,376
61,977,216
Python Pandas: Find the total sales value of the category 'Office Supplies' after combining the dataframes
<p>How do we find sales for Office Supplies Category?</p> <p><a href="https://i.stack.imgur.com/OOtCI.jpg" rel="nofollow noreferrer">enter image description here</a></p>
<p>Assuming (and I'm having to assume a lot) that you want to find the total of the column 'Sales_x' for all lines where the category is 'Office Supplies', then it's the following. </p> <pre><code>df3[df3['Category'] == 'Office Supplies']['Sales_x'].sum() </code></pre> <p>Hopefully even if my assumption is wrong, thi...
python|pandas
0
357,377
61,978,795
pandas DataFrame (easy?) manipulation
<pre><code>pd.DataFrame({'id': ['id1', 'id1', 'id2', 'id2'], 'value': ['1', '2', '10', '20'], 'index': ['day1', 'day2', 'day1', 'day2']}) </code></pre> <p>how can I transform this data correctly (and concisely) with pandas that it results in:</p> <pre><code> | id1 | id2 da...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer">pandas pivot</a>. It reshapes datframe based on the input conditions</p> <pre><code> pd.pivot_table(df, index=['index'], columns=['id'],values='value').reset_index() </code></pre> <p>Just ...
python|pandas
0
357,378
61,617,612
Getting duplicated rows of large excel file with Pandas
<p>I have an excel file with a minimum of 600,00 lines (the size varies). I want to get all duplicates of a particular column with Pandas.</p> <p>This is what I have tried so far:</p> <pre><code>use_cols = ['ID', 'AMOUNT'] df = pd.DataFrame() for chunk in pd.read_csv("INPUT.csv", usecols=use_cols, chunksize=10000):...
<p>I have tried duplicated and I get the rows which are duplicated, That is to say, the first one I do not take into account because it would be unique if the others weren't</p> <p><a href="https://i.stack.imgur.com/5OyNU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5OyNU.png" alt="enter image de...
python|pandas
0
357,379
61,788,993
stack a 2d array into an existing 3d array in numpy
<p>I start by initializing: </p> <pre><code>3dArray = np.zeros(shape=(0,250,2)) </code></pre> <p>Within a loop, I go through a file and pick out sections of data, resulting in multiple 2D arrays of size (250,2). </p> <p>For each of these sections, I'm trying to stack these 2d arrays into the 3d array, so that the 0t...
<pre class="lang-py prettyprint-override"><code>3DArray = np.vstack((3DArray,new2Darray.reshape(1,250,2))) </code></pre> <p>Side Note: Python doesn't allow variable names to start with numbers.</p>
python|arrays|numpy
1
357,380
61,934,896
Heatmap is not showing missing value
<p>I am working to find-out the missing value of dataframe(that is train).I used pandas .isnull and it give me correct boolean output for missing value in 'Age','Cabin' and 'Embarked' columns.But when i used sns.heatmap ,it is not showing missing value for 'Embarked'.What I am doing wrong? please help me.Below are the ...
<p>I solved this by resizing fiqure:</p> <pre><code>plt.figure(figsize=(12,8)) sns.heatmap(train.isnull(),cbar=False) </code></pre> <p>Thanks Stupidwolf for suggesting me. <a href="https://i.stack.imgur.com/3T3LQ.jpg" rel="nofollow noreferrer">solved</a></p>
python-3.x|pandas|matplotlib|plot|seaborn
3
357,381
61,796,503
Update column value of the csv file using Python
<p>My question is: Once the customer selects the hotel, ask him the give feedback for the same and update the rating.csv file as per the data received.And how i update that given feed back to these file.</p> <p>This is what I tried so far:</p> <pre><code>h_id=str(input("Enter Hotel_Id:")) with open("rating.csv", "r")...
<p>I would do it in this way:</p> <pre><code>import pandas as pd #read the hotels table hotels = pd.read_csv("rating.csv") h_id=str(input("Enter Hotel_Id:")) f_back=float(input("Please Give Feedback of Hotel you selected outoff 5:")) hotels.loc[hotels.Hotel == h_id,"no_of_feedback" ] = hotels.loc[hotels.Hotel == h_...
python-3.x|pandas|csv|data-science|computer-science
1
357,382
61,891,795
Reshaping Pandas dataframe based on repeating values in a column
<p>Very new to Pandas and probably been answered somewhere but I can't seem to find exactly what I'm looking for. Assuming my dataset has this type of structure</p> <pre><code>Animal | Age | Color | Length Cat 1 Brown 50cm Cat 2 White 60cm Cat 3 Brown 55cm Dog...
<p>Create <code>MultiIndex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>GroupBy.cumcount</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofo...
python|pandas
2
357,383
61,680,655
Performance drop using PCA with LSTM
<p>I've been following this tutorials on tensorflow on Timeseries forecasting using LSTM: <a href="https://www.tensorflow.org/tutorials/structured_data/time_series?_sm_byp=iVVPDS34q1N5fqcV" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/structured_data/time_series?_sm_byp=iVVPDS34q1N5fqcV</a></p> <p>My...
<p>The modified code below works fine, I had to move the scaling before the PCA.</p> <pre><code>from sklearn.decomposition import PCA features = df.drop(["Date Time"], axis = 1) features.index = df['Date Time'] data_mean = features[:TRAIN_SPLIT].mean(axis=0) data_std = features[:TRAIN_SPLIT].std(axis=0) features = (...
tensorflow|lstm
0
357,384
61,884,380
Best practices to benchmark deep models on CPU (and not GPU) in PyTorch?
<p>I am little uncertain about how to measure execution time of deep models on CPU in PyTorch ONLY FOR INFERENCE. I list here some of them but they maybe inaccurate. Please correct them if required and mention more if required. I am running on PyTorch version 1.3.1 and Intel Xeon with 64GB RAM, 3.5GHz processor and 8 c...
<blockquote> <ol> <li>Should we use time.time()?</li> </ol> </blockquote> <p>Yes, it's fine for CPU</p> <blockquote> <ol start="2"> <li>Should we use volatile?</li> </ol> </blockquote> <p>As you said it's deprecated. Since <code>0.4.0</code> <code>torch.Tensor</code> was merged with <code>torch.Variable<...
python|pytorch
5
357,385
61,988,485
pandas - comparing two columns of different dataframes with multiple strings
<p>I'm pretty new to pandas and got an assignment asking me to compare &amp; match two columns of 2 different .csv files. dtypes are strings</p> <p>1st df<br> Name | Subjects <br> Student1 | Biology, Math, German<br> Student2 | Sport, Biology, English<br> Student3 | Chemistry, Math, Biology<br></p> <p>2nd df<br>...
<p>Since you said you didn't want a solution, but a push in the right direction, here is how I would approach the problem:</p> <ol> <li>Read both datasets as lists. Let's call the dataframes student and teacher.</li> </ol> <p>e.g. </p> <pre><code>students = """Name | Subjects Student1 | Biology, Math, German Student...
python|pandas|dataframe
0
357,386
61,957,155
How to create star markers using matplotlib?
<p>'</p> <pre><code>pitchLength = 120 pitchWidth = 75 createPitch(pitchLength,pitchWidth,'meters','white') ax = plt.subplot() for index,col in rf_pass.iterrows(): x_start = col['location'][0] y_start = col['location'][1] x_end = col['pass.end_location'][0] y_end = col['pass.end_location'][1] if col...
<p>If the problem is just about creating different markers, adding <code>marker=&quot;*&quot;</code> creates a star marker.</p> <p>for example</p> <pre><code>plt.scatter(x,y) #creates normal plot with circle marker plt.scatter(x,y, marker=&quot;*&quot;) #creates plot with star marker </code></pre> <p>I hope it works ...
python|pandas|matplotlib
0
357,387
61,928,675
keras transferlearning predict classes working and predict not working
<p>I am using transfer learning and building on top of the "inception_v3" model. Training seems to go well, i get a val_accuracy of 0.9526. I can also do predict_class after to get the predicted label for new samples - that also seems quite good. However, for some reason when i try to use the predict function, it alwa...
<p>After help from Yoskutik the code now looks like the following and has improved, but I still don't understand why I get the results that I do (see code below).</p> <p>In the final epoch i get this output</p> <pre><code>Epoch 5/5 414/414 [==============================] - ETA: 0s - loss: 0.1207 - accuracy: 0.9587 E...
python|tensorflow|machine-learning|keras|computer-vision
0
357,388
61,895,050
np.arange or np.arage ? Error:module 'numpy' has no attribute 'arage' when using plot_confusion_matrix
<p>I just ran into this error. Is it something wrong with my <code>NumPy</code> package? If so, is there any way to fix this? Thank you!!</p> <pre><code>import numpy as np from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_compare,pred) np.set_printoptions(precision=2) #Normalize the confusion matrix ...
<p>I'm pretty sure this was supposed to be <a href="https://numpy.org/doc/1.18/reference/generated/numpy.arange.html" rel="nofollow noreferrer"><code>np.arange()</code></a>.</p> <p>Could you tell me if you wrote that <code>plot_confusion_matrix(cm, names, title, cmap)</code> function? If yes, just change <code>tick_ma...
python|numpy
0
357,389
58,097,871
Select values from one columns based on values from another column - python
<p>I have a large dataframe <code>df1</code> that looks like this: </p> <pre><code>DeviceID Location 1 Internal 1 External 2 Internal 2 Internal 3 Internal 3 External 3 Internal 4 Internal 4 Interna...
<p>You can <code>groupby</code>, <code>transform</code> with the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.SeriesGroupBy.nunique.html" rel="nofollow noreferrer"><code>nunique</code></a> to see which gorups contain two different values and use the result to perform boolean i...
python|pandas
1
357,390
58,171,156
Pull a variable out of multiple functions
<p>I have 4 functions where I manipulate a dataframe to create a new version of it. I need to pull out the last version of the adjusted dataframe out of each function to use them elsewhere. Keep in mind that df_1 is not the returned dataframe but rather an intermediate variable. So running the functions wouldn't return...
<p>The best is that if you work with methods local scope and you don't use any global scope. Pass the dataframe you want to modify as a parameter and return the modified version. That way your code becomes more modular, easy to test and to follow. That way you can write:</p> <pre><code>df1 = function_1(df) df2 = funct...
python|pandas
0
357,391
57,794,657
update values in dataframe
<p>I have a dataframe in which the second column is an array. I have an another dataframe which has 2 columns, from which the value has to be updated in the first dataframe.</p> <p>I already tried using update, explode, map, assign method.</p> <pre><code>df = pd.DataFrame({'Account': ['A1','A2','A3']}) groups = np.a...
<p><strong><em>Setup</em></strong></p> <pre><code>m = key_values.set_index('Group')['ID'] </code></pre> <hr> <p><strong><em>Option 1</em></strong><br> <code>explode</code> + <code>map</code></p> <pre><code>f = df.explode('Group') res = f['Group'].map(m).groupby(level=0).agg(list) </code></pre> <p></p> <pre><code...
numpy
0
357,392
57,828,416
How to use GradientTape with AutoGraph in Tensorflow 2?
<p>I can not figure out how to run GradientTape code on AutoGraph in Tensorflow 2.</p> <p>I want to run GradientTape code on TPU. I wanted to start by testing it on CPU. TPU code would run much faster using AutoGraph. I tried watching the input variable and I tried passing in the argument into the function that contai...
<p>It doesn't "fail", it's just that <code>print</code>, if used in the context of a <code>tf.function</code> (i.e. in graph mode) will print the symbolic tensors, and these do not have a value. Try this instead:</p> <pre><code>@tf.function def compute_me(): x = tf.constant(3.0) with tf.GradientTape() as g: ...
python-3.x|tensorflow
1
357,393
57,797,012
I am getting a Open cv error when working with object detection
<pre class="lang-py prettyprint-override"><code>import cv2 import numpy as np from random import shuffle from tqdm import tqdm import os TRAIN_DIR=r'C:\Users\Valued Customer\Desktop\Object detection\train' TEST_DIR=r'C:\Users\Valued Customer\Desktop\Object detection\test' IMG_SIZE=300 LR=1e-3 MODEL_NAME = 'dogsvscats-...
<p>I got this error today because my path of images was not right.U can try to show one image to see whether you read the image successfully.</p>
python|numpy|opencv|object-detection
1
357,394
58,036,681
Integrating the loss of a keras model into a tensorflow graph
<p>If I define this simple Keras model</p> <pre><code>import tensorflow as tf from tensorflow import keras import numpy as np l1 = keras.layers.Input(shape=(32)) l2 = keras.layers.Dense(10)(l1) model = keras.Model(inputs=l1, outputs=l2) model.compile(loss='mse', optimizer='adam') </code></pre> <p>Let's say I have t...
<p>Since you want to "evaluate" and not use it in some further graph calculations, you can simply use a callback:</p> <pre><code>from keras.callbacks import LambdaCallback def getLoss(epoch, logs): print(logs['loss']) #or val_loss (print the keys of logs if in doubt) callback = LambdaCallback(on_epoch_end = getL...
python|python-3.x|tensorflow|keras
0
357,395
58,151,957
Generate Python dictionary from combination of lists
<p>I've tried to solve my issue but I could not. </p> <p>I have three Python lists: </p> <pre><code>atr = ['a','b','c'] m = ['h','i','j'] func = ['x','y','z'] </code></pre> <p>My problem is to generate a Python dictionary based on the combination of those three lists: </p> <p>The desired output: </p> <pre><code>py...
<p>You can use <code>itertools.product</code>:</p> <pre><code>import itertools atr = ['a','b','c'] m = ['h','i','j'] func = ['x','y','z'] prod = list(itertools.product(func, m)) result = {i:prod for i in atr} </code></pre> <p>Output:</p> <pre><code>{'a': [('x', 'h'), ('x', 'i'), ('x', 'j'), ('y', 'h'), ('y', 'i'), (...
python|pandas|list|dictionary|combinations
7
357,396
57,771,825
How is the IoU calculated for multiple bounding box predictions in Tensorflow Object Detection API?
<p>How is the IoU metric calculated for multiple bounding box predictions in Tensorflow Object Detection API ?</p>
<p>Not sure exactly how TensorFlow does it but here is one way that I recently got it to work since I didn't find a good solution online. I used numpy matrices to get the IoU, &amp; other metrics (TP, FP, TN, FN) for multi-object detection.</p> <p>Lets say for this example that your image is 6x6.</p> <pre><code>import...
tensorflow|object-detection
1
357,397
57,972,482
Implementing MSE loss
<p>I'm new to deep learning and I want to implement an autoencoder. I'm using <strong>keras</strong> and <strong>mse loss function</strong>. But when I use MSE function that I implemented althogh the output of my function and keras.losses.mse are approximately the same but the result is significantly worse.</p> <p>Duo...
<p>I believe you are missing summing of the diffs.</p> <p>try:</p> <pre><code>def custom_loss(im1, im2): im11 = im1[:, :, 0] im12 = im1[:, :, 1] im13 = im1[:, :, 2] im21 = im2[:,:,0] im22 = im2[:,:,1] im23 = im2[:,:,2] diff1 = (im11 - im21)**2 diff2 = (im12 - im22)**2 diff3 = (im13...
python|tensorflow|machine-learning|keras|deep-learning
0
357,398
58,136,174
Extract Tables from an Iframe - Anbima Using python + selenium
<p>Sup, I'm trying to extract some data tables from an website (<a href="https://www.anbima.com.br/pt_br/informar/curvas-de-juros-fechamento.htm" rel="nofollow noreferrer">https://www.anbima.com.br/pt_br/informar/curvas-de-juros-fechamento.htm</a>), but as we can see the data is inside an Iframe. It took me a while, si...
<p>Try replacing your <code>driver.switch_to.frame(0)</code> line with this:</p> <pre><code># Get the iframe element - note, may need to use more specialized selector here iframe = driver.find_elements_by_tag_name('iframe') driver.switch_to.frame(iframe) </code></pre> <p>That will get your driver into the frame cont...
python|pandas|selenium|iframe
0
357,399
58,077,391
How to convert nan to NULL in database table using Pandas
<p>In my CSV some columns are empty but when I'm inserting CSV data so in the place of the empty column nun is coming but I want NULL in the table</p> <pre><code>file = request.FILES['csvfile'] df = pd.DataFrame(data, columns=['company’]) if not df.loc[i]['company'] == 'NaN': company = df.loc[i]['company'] else: ...
<p>I had a similar issue. The below worked for me:</p> <p>df.astype(object).replace(np.nan, None)</p>
python|django|pandas
3