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
375,600
69,861,033
Tensorflow object detection "Use fn_output_signature instead" warning
<p>I am following this tutorial to train my own models. <a href="https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/" rel="nofollow noreferrer">https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/</a></p> <p>I followed all the steps exactly as described in this tutorial but ...
<ul> <li>For version TF_2.6.0</li> <li>in file &quot;piplile.config&quot;</li> <li>var batch_size = 8 -&gt; 1-4 (using RAM)</li> </ul>
python|tensorflow|object-detection|tensorflow-datasets|object-detection-api
0
375,601
69,886,693
From multiple values per rows of a pandas dataframe: get two columns with every realation of the values (to analyse the network with Networkx)
<p>I have a dataframe with names of persons in it. The persons work thogether on the same item.</p> <pre><code>item names a moriz, jon, cate b jon, lenard c cate, martin, leo, jil </code></pre> <ul> <li>I like to prepare the names for a network-visualisation. I need to split the name-cells up in in ...
<p>You could do something like this (<code>df</code> your dataframe):</p> <pre><code>import pandas as pd from itertools import combinations df = pd.DataFrame( { 'item': ['a', 'b', 'c'], 'names': ['moriz, jon, cate', 'jon, lenard', 'cate, martin, leo, jil'] } ) df.names = df.names.str.split(&qu...
python|pandas|dataframe|networkx
1
375,602
69,844,273
Broadcast across pandas MultiIndex level even if index values happen to agree
<p>This one has me stumped. I have two <code>pd.Series</code> <code>s</code> and <code>t</code> as follows:</p> <pre><code>Common Level s Foo a 1 b 2 Name: s, dtype: int64 </code></pre> <pre><code>Common Level t Foo A 10 B 20 Name: t, dtype: int64 </code></p...
<p>The method that is called to normalise indexes of Series and DataFrames for broadcasting is <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.align.html" rel="nofollow noreferrer"><code>align</code></a>. This method is called internally to get the new indexes, we can see this with:</p> <pre><code>l...
pandas|multi-index|array-broadcasting
1
375,603
69,989,219
Store values into keys with scrapy
<p>I want to extract information from a website like price and store that as values in a dictionary. However, I'm trying to learn scrapy so I'd like to know how to achieve this with it.</p> <p>Here's how it would look like with <code>requests</code> and <code>BeautifulSoup</code></p> <pre><code>import numpy as np impor...
<p>I set the custom_settings to write to 'cards_info.json' with json format.</p> <p>Inside parse I go through each card on the page (see xpath) and get the card's title and price, then I yield them. Scrapy will write them into 'cards_info.json'.</p> <pre class="lang-py prettyprint-override"><code>import scrapy from scr...
python|pandas|web-scraping|scrapy
1
375,604
69,965,208
Numpy where condition when met must modify the original value, if not original value must remain
<p>I have the following dataframe:</p> <pre><code>Policy_id Value A xyz B abc A pqr C lmn </code></pre> <p>And I want to use <code>np.where()</code> such that whenever the <code>policy_id</code> is equal to <code>A</code> the corresponding value must be appen...
<p>Try</p> <pre><code>df['new'] = np.where(df['Policy_id'].eq('A'),df['Value']+'*',df['Value']) </code></pre>
python|pandas|dataframe|numpy
0
375,605
69,759,141
How to reshape 3d numpy table?
<p>I have a 3d numpy table with shape=(2,3,4) like below:</p> <pre><code>a = np.array([[[1., 2., 3., 4.], [1., 2., 3., 4.], [1., 2., 3., 4.]], [[5., 6., 7., 8.], [5., 6., 7., 8.], [5., 6., 7., 8.]]]) </code></pre> <p>And want to reshape this in a way where the columns in each dim...
<p>Here you go:</p> <pre><code>res = a.T.reshape((-1,2)) </code></pre> <p>Output:</p> <pre><code>array([[1., 5.], [1., 5.], [1., 5.], [2., 6.], [2., 6.], [2., 6.], [3., 7.], [3., 7.], [3., 7.], [4., 8.], [4., 8.], [4., 8.]]) </code></pre>
python|numpy
4
375,606
69,848,969
How to build NumPy from source linked to Apple Accelerate framework?
<p>It is my understanding that NumPy dropped support for using the Accelerate BLAS and LAPACK at version 1.20.0. According to the release notes for NumPy 1.21.1, these bugs have been resolved and building NumPy from source using the Accelerate framework on MacOS &gt;= 11.3 is now possible again: <a href="https://numpy....
<p>No it doesn't have to be that complicated. I used these two commands and was able to install numpy with Apple Accelerate on Mac M1.</p> <pre><code>pip install cython pybind11 pip install --no-binary :all: --no-use-pep517 numpy </code></pre> <p>Reference: <a href="https://stackoverflow.com/questions/65745683/how-to-i...
python|numpy|build|apple-m1|accelerate-framework
2
375,607
69,779,690
Unable to install TensorFlow with miniconda on macOS Monterey
<p>I tried to install tensorflow following this issue: <a href="https://github.com/apple/tensorflow_macos/issues/153" rel="nofollow noreferrer">https://github.com/apple/tensorflow_macos/issues/153</a></p> <p>Although for M1 Monterey the wheel is not working and showing the following error.</p> <pre><code>pip install --...
<p>Please follow below steps to Install TensorFlow successfully</p> <ol> <li><p>Download and install <a href="https://www.anaconda.com/products/individual" rel="nofollow noreferrer">Anaconda</a> or the smaller <a href="https://docs.conda.io/en/latest/miniconda.html" rel="nofollow noreferrer">Miniconda</a>.</p> </li> <l...
macos|tensorflow|miniconda|macos-monterey
0
375,608
69,880,250
Get first list element in apply function Pandas
<p>I have a function <code>preprocess_names</code> that splits an input variable:</p> <pre><code>def preprocess_names(name): #SOME PREPROCESSING return name.split('') </code></pre> <p>Also, I have a Pandas DataFrame <code>df</code> to which I want to apply this function. In my case, the <code>preprocess_names</...
<p>Do you want:</p> <pre><code>df['runs'] = df['name'].apply(preprocess_names).str[0] </code></pre>
python|pandas|dataframe|apply
1
375,609
69,823,422
Create 1 row dataframe from dictionary, with three columns and attach variable to first column
<p>I have a dictionary with a set of data as follows:</p> <pre><code>fruit_dict = {'apples': 12.0, 'pears': 14.0, 'oranges': 5.0, 'lemons': 2.0} </code></pre> <p>I would like to create a dataframe of these items with the title of each fruit as a column as well as having one DATE column, like so (capitalised column titl...
<p>First merge dictionaries for <code>Date</code> column and then pass to <code>list</code> in <code>DataFrame</code> constructor:</p> <pre><code>d = {**{'date': today}, **fruit_dict} fruit_price = pd.DataFrame([d]).rename(columns=lambda x: x.upper()) </code></pre>
python|pandas|dataframe|dictionary
2
375,610
69,990,800
Why is TensorFlow model reporting incorrect high confidence level for predictions?
<p>I wrote this function that takes in an image and generates a prediction. The level of confidence for the prediction that the function reports is greater than 100% many times. Sometimes the prediction is correct and reports a high level of confidence. Sometimes it is incorrect and still reports a high level of confid...
<p>If you want your output to be between 0 and 1, you should use either a <code>'sigmoid'</code> or <code>'softmax'</code> activation in your last layer:</p> <pre><code>outputs = tf.keras.layers.Dense(3, activation='softmax')(x) </code></pre> <p>Careful, however, because softmax output can't really be interpreted as pr...
python|tensorflow|machine-learning|keras
1
375,611
69,972,526
Fastest way to load_model for inference in Tensorflow Keras
<p>I’m trying to quickly load a model from disk to make predictions in a REST API. The <em>tf.keras.models.load_model</em> method takes ~1s to load so it’s too slow for what I’m trying to do. Compile flag is set to false.</p> <p>What is the fastest way to load a model from disk for inference only in Tensorflow/Keras?</...
<p>Doink! I had a bit of a brain fart moment just there so in case you have it too, here is a solution that does the job.</p> <p>Just load the model when you start the server so all request can use the model.</p>
tensorflow|keras|tensorflow2.0
0
375,612
69,784,678
Loading model from saved checkpoints in keras
<p>I am using original DCGAN MNIST code (keras) for my project . My task is to generate an array and then I'll calculate some observables from that . I am saving model after each epochs so that I can find for which epoch I am getting best observables. I have used 50 Epochs so I have 50 saved checkpoints . Now I want to...
<p>You can use <code>tf.train.CheckpointManager</code> to load your latest checkpoint or whatever checkpoint you like and then generate some images with your <code>generator</code> model based on random noise:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf checkpoint_dir = &quot;./training...
python|tensorflow|keras|generative-adversarial-network|dcgan
1
375,613
69,975,400
Pytorch CNN: Expected input to have 1 channel but got 60000 channels instead
<p>While implementing a NN for Fashion MNIST dataset, I'm getting the following error:</p> <pre><code>RuntimeError: Given groups=1, weight of size [6, 1, 5, 5], expected input[1, 60000, 28, 28] to have 1 channels, but got 60000 channels instead </code></pre> <p>I'm inferring that 60000 is the length of my entire datase...
<p>You input is shaped <code>(1, 60000, 28, 28)</code>, while it should be shaped <code>(60000, 1, 28, 28)</code>. You can fix this by transposing the first two axes:</p> <pre><code>&gt;&gt;&gt; x.transpose(0, 1) </code></pre>
python|neural-network|pytorch|conv-neural-network|mnist
2
375,614
69,774,038
Error: index 9 is out of bounds for axis 0 with size 9
<p>I am attempting to make a Lagrange interpolation function however after construction I get the error <em>index 9 is out of bounds for axis 0 with size 9</em>. Why am a receiving this error and how can I fix it to perform my interpolation?</p> <pre><code> import numpy as np b = np.arange(3,12) y = np.arange(9) from ...
<p>Because the first index is a zero you can only go to the index 8 and 9 is then out of bounds. Your 9 indices are 0, 1, 2, 3, 4, 5, 6, 7, 8.<br /> So you should not loop through d + 1. Use only d.</p>
python|function|numpy|interpolation
2
375,615
69,982,638
Count cumulative true Value
<p>I have the following column with <code>True</code> and <code>False</code> boolean values. I want create a new column performing a cumulative sum on the <code>True</code> values and if the value is <code>False</code> reset the count, like this:</p> <pre><code> bool count 0 False 0 1 True 1 2 True ...
<p>Yes, this can be done, using a series of steps:</p> <pre><code>df['count'] = df.groupby(df['bool'].astype(int).diff().ne(0).cumsum())['bool'].cumsum() </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df bool count 0 False 0 1 True 1 2 True 2 3 True 3 4 False 0 5 True ...
python|pandas|dataframe|boolean|pandas-groupby
1
375,616
69,747,667
Subset df on specific timestamps and previous seconds - python
<p>I've got a df containing timestamps and separate values. The timestamps are recorded in ms (10 rows per second). I want to subset specific timepoints <em>plus</em> the previous rows within that second.</p> <p>Using below, the timestamps have been returned. I then subtract a second of each and concat back to original...
<p>One way is to build a list of dates, and do an outer merge with the original <code>df</code> :</p> <pre class="lang-py prettyprint-override"><code>prev = df.Time - pd.Timedelta('900ms') # build new dates new_values = pd.concat(pd.date_range(start, end, periods=10, ...
python|pandas|datetime|timedelta
2
375,617
69,816,464
Pandas pivoting/stacking/reshaping from string in rows
<p>Accepted answer from Sammy as it did solve the original post. Editing to include further complexity when using the solutions, some of the values themselves has spaces in them and so the regex breaks these as well. Including example change in key1=value 11.</p> <p>This data seem designed to be analytics unfriendly.</...
<p>You could do the entire transformation with python, which should be faster and easier. Given an input Series <code>s</code>:</p> <pre class="lang-py prettyprint-override"><code>import re pd.DataFrame([dict(e.split('=') for e in re.split(&quot;[\s,]&quot;, ent)) for ent in s]) key1 key2 key3 0 ...
pandas
1
375,618
69,888,535
How to move files from a dataframe into separate folders?
<p>I am working with a covid dataset right now and I have loaded all the images into a dataframe.I have labelled covid positive images as 1 and normal images as zero.I want to separate the data into two folders namely 1 (<em>1 shall contain covid positive images</em>) and 0(<em>0 folder should contain normal images</em...
<p>Just go through the dataframe element by element and save to a folder based on the flag:</p> <pre><code>for file, flag in zip(df['filename'], df['categories']): if flag == 0: #save file to first directory elif flag == 1: #save file to second directory </code></pre>
python|pandas|dataframe
0
375,619
69,706,273
replace substrings in pandas columns while skipping rows with value: None
<p>I stole this from here <a href="https://stackoverflow.com/questions/57200908/remove-replace-columns-values-based-on-another-columns-using-pandas?noredirect=1&amp;lq=1">Remove/replace columns values based on another columns using pandas</a></p> <pre><code>[a.replace(b,'') for a,b in zip(df1['asker'], df1['party']) if...
<p>Use:</p> <pre><code>[a.replace(b,'') if (a != None) and (b != None) else a for a,b in zip(df1['asker'], df1['party'])] </code></pre> <p>If need test <code>NaN</code>s or <code>None</code>s use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.notna.html" rel...
python|pandas|list-comprehension|nonetype
1
375,620
69,893,417
Group by in Pandas based on a condition
<p>I have a dataframe</p> <pre><code>|phone_number|call_date|answered| attempt| |123 | 13thJune| 1 | 1 | |234 | 15thJune| 0 | 1 | |234 | 15thJune| 0 | 2 | </code></pre> <p>I want to perform a groupby and take out the max date of answered. i.e If the call is not answered which is 0 , then max date o...
<p>Use:</p> <pre><code>df = df.groupby('phone_number').apply(lambda x: x[x['answered']!=0]['call_date'].max()).reset_index().rename(columns={0: 'max_call_date'}) print(df) </code></pre> <p><code>Output:</code></p> <pre><code> phone_number max_call_date 0 123 13thJune 1 234 NaN </cod...
python|pandas
2
375,621
69,859,586
How to get mean of selected rows with another column's values in pandas
<p>I have a dataframe like this:</p> <p><a href="https://i.stack.imgur.com/MFNJw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MFNJw.png" alt="enter image description here" /></a></p> <p>I want to take the mean of WFR between 2009-2015 for each NAME and put it for all the years of each NAME. any id...
<p>Use <code>groupby_mean</code> after filter years then map the mean for each name:</p> <pre><code>tmp = df.loc[df['YEAR'].between(2009, 2015)].groupby('NAME')['WFR'].mean() df['MEAN'] = df['NAME'].map(tmp) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df NAME YEAR WFR MEAN 0 A 2017 20 NaN 1 B ...
python|pandas|dataframe
4
375,622
70,001,458
I want to filter column with a character
<p>I want to filter the column NAME with just one letter &quot;o&quot;.<br /> DataFrame:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">NAME</th> <th style="text-align: left;">HOBBY</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">John</td> <td style...
<p>You can use .contains to filter only the rows where name contains a lower case 'o'.</p> <p>Using the below df:</p> <pre><code>df = pd.DataFrame({'NAME' : ['John', 'Kelly'], 'HOBBY' : ['football', 'chess']}) </code></pre> <p>Then you can use .loc and .contains to filter on desired rows:</p> <pre><c...
python|pandas
1
375,623
70,012,098
Tensorflow Object Detection API taking forever to install in a Google Colab and failing
<p>I am trying to install the Tensorflow Object Detection API on a Google Colab and the part that installs the API, shown below, takes a very long time to execute (in excess of one hour) and eventually fails to install.</p> <pre><code># Install the Object Detection API %%bash cd models/research/ protoc object_detection...
<p>I have solved this problem with</p> <pre><code>pip install --upgrade pip </code></pre> <p>Please refer to <a href="https://github.com/tensorflow/models/issues/10375" rel="nofollow noreferrer">this issue</a>.</p>
tensorflow|google-colaboratory|object-detection|object-detection-api
3
375,624
69,976,510
Pandas: Assign value based on value in another row
<p>I have the 3 columns data frame: page_number, line_number, text.</p> <p>I want to create another column prev_text which contains text from previous page, the same line number eg:</p> <p>For page 3, line 10 I want to have value from page 2, line 10 if such page &amp; line exist.</p> <p>At the moment I build 2 dimensi...
<p>Here's one approach:</p> <pre><code>import pandas as pd df = pd.DataFrame({'page_num': [1, 1, 1, 1, 2, 2, 3, 3, 3, 4], 'line_num': [1, 2, 3, 4, 1, 2, 1, 2, 3, 1], 'text': ['apple', 'banana', 'car', 'dog', 'egg', 'fire', 'goat', ...
python|pandas
0
375,625
69,917,766
Can't Plot Loss and Accuracy After training datasets
<p>I already training my dataset with this code before</p> <pre><code>def train_model(model, criterion, optimizer, scheduler, num_epochs): since = time.time() #device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 for epoch in range(num...
<p>I finally fixed the problem. I couldn't plot the result before because I was not putting the result into the tensorboard. Now I can plot the result.</p>
python|pytorch
0
375,626
69,848,362
Degree Centrality and Clustering Coefficient in Adjacent matrix
<p>Based on a dataset extracted from this link: <a href="https://cosmosimfrazza.myfreesites.net/cosmic-web-and-brain-network-datasets" rel="nofollow noreferrer">Brain and Cosmic Web samples</a>, I'm trying to do some Complex Network analysis.</p> <hr /> <p>The paper <a href="https://www.frontiersin.org/articles/10.3389...
<p>This is not really a programming question, but I will try to answer it. The webpage with the data sources states that the adjacent matrix files for brain samples give distances between connected nodes expressed in pixels of the images used to reconstruct the networks. The paper then explains that to get the real adj...
python|pandas|cluster-analysis|adjacency-matrix|node-centrality
6
375,627
69,935,174
Iterate over duplicate partitions/groups of a Pandas DataFrame
<p>I have a df like this</p> <pre><code>id val1 val2 val3 0 1 1 2 1 1 NaN 2 2 1 4 2 3 1 4 2 4 2 1 1 5 3 NaN 3 6 3 7 3 7 3 7 3 </code></pre> <p>then</p> <pre><code>temp_df = df.loc[df.duplicated(subset=['val1','val3'], keep=False)] </code></pre> <p>gives me thi...
<p><strong>Update</strong></p> <p>Use <code>groupby_apply</code>:</p> <pre><code>df['val2'] = df.groupby(['val1', 'val3'])['val2'] \ .apply(lambda x: x.fillna(x.mode().squeeze())) print(df) # Output: id val1 val2 val3 0 0 1 1.0 2 1 1 1 4.0 2 2 2 1 4.0 2 3 3 ...
pandas|dataframe|duplicates|pandas-groupby
1
375,628
69,979,709
Read in .dat file with headers throughout
<p>I'm trying to read in a .dat file but it's comprised of chunks of non-columnular data with headers throughout.</p> <p><a href="https://i.stack.imgur.com/QkOSz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QkOSz.png" alt="data opened in Excel" /></a></p> <p>I've tried reading it in in pandas:</p>...
<p>I developed a work-around. I needed the Displacement data pairs, as well as some data that was all divisible evenly by 100.</p> <p>To get to the Displacement data, I first pretended 'Cyclic Acquisition' was a valid column name, coerced errors on the values forced to be numeric and forced the values included to be ju...
python|pandas
0
375,629
69,881,484
Python Pandas : find n in a sorted multindex dataframe and return [0:n+1] for each level 1 index
<p>I am having some issues with what I thought a simple filtering task. We have a data that have roughly this shape :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>name</th> <th>item</th> <th>cumsum</th> </tr> </thead> <tbody> <tr> <td>name1</td> <td>item 1</td> <td>0.05</td> </tr> <tr> ...
<p>Use <code>|</code> for bitwise <code>OR</code> by mask shifted per groups by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.shift.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.shift</code></a>:</p> <pre><code>m = (df['cumsum'] &lt; 0.2) df = df[m | m....
python|pandas|filtering|multi-index
1
375,630
69,822,282
add a new column in multi index from the others
<pre><code>In [151]: df Out[151]: first bar baz second one two one two A 1 2 3 4 B 5 6 7 8 </code></pre> <p>My question is simple: from this df, how to create a new columns three which the...
<p>One way to do this is:</p> <pre><code>df1 = df.join(df.sum(level=0, axis=1)) </code></pre> <p>which returns:</p> <pre><code>(bar, one) (bar, two) (baz, one) (baz, two) bar baz 0 1 2 3 4 3 7 1 5 6 7 8 11 15 </code></pre> <p...
python|pandas|multi-index
0
375,631
69,805,233
I have a DataFrame and need to perform calculations between columns. Can my function do_something be vectorised?
<p>I have a DataFrame and need to perform calculations between columns. Can my function <code>do_something </code>be vectorised ?</p> <p>Column <code>['1min', '2min', '5min', '15min', '30min', '1hour', '2hour', '4hour', '1day', '2day', '7day',]</code> need to be compared with price and the value of the previous column ...
<p>IIUC, it looks like you want to get the <code>idxmin</code> and <code>min</code> masked with False if the first value is not greater than price.</p> <p>You can use numpy to get both operations at once:</p> <pre><code>m = np.argmin(df[list1].values, axis=1) (pd.DataFrame({'min_bar': np.take(list1, m), ...
python|pandas|dataframe|vectorization
2
375,632
69,829,423
How do I save a N x M array/list using Pandas?
<p>I have a <code>N x M</code> numpy array / list. I want to save this matrix into a <code>.csv</code> file using Pandas. Unfortunately I don't know <strong>a priori</strong> the values of M and N which can be <em>large</em>. I am interested in Pandas because I find it manageable in terms of data columns access.</p> <p...
<p>Following the comment of Quang Hoang, there are 2 possibilities:</p> <ol> <li><code>pd.DataFrame(A).to_csv('yourfile.csv')</code>.</li> <li><code>np.save(&quot;yourfile.npy&quot;,A)</code> and then <code>A = np.load(&quot;yourfile.npy&quot;)</code>.</li> </ol>
python|pandas|dataframe|csv|save
0
375,633
69,733,845
how can i display json array to python dataframe
<p>I have a json file.</p> <pre><code>[ { 'orderId': 1811, 'deliveryId': '000001811-1634732661563000', 'shippingBook': '[{&quot;qtyOrdered&quot;:1,&quot;bookNoList&quot;:[&quot;B8303-V05&quot;,&quot;B8304-V05&quot;,&quot;B8305-V05&quot;,&quot;B8306-V05&quot;,&quot;B8307-V05&quot;],&quot;cour...
<p>You have string in <code>'shippingBook'</code> which may need <code>json.loads()</code> to convert it to Python's list with dictionaries.</p> <p>And you could use normal <code>for</code>-loops to convert all data to normal list with expected data - and later convert it to <code>DataFrame</code></p> <pre><code>import...
python|json|pandas
1
375,634
69,759,004
could not broadcast input array from shape (3,1) into shape (3,)
<p>I have the following python code for QR factorization. At line of <code>Q[:,i] = u / norm</code> , I get the error mentioned in the title. Can anyone help, please?</p> <ul> <li><code>Q</code> is has the shape (3,3),</li> <li><code>u</code> is expected to has the shape (3,1)</li> <li><code>norm</code> is a scalar</li...
<p>The use of <a href="https://numpy.org/doc/stable/reference/generated/numpy.matrix.html" rel="nofollow noreferrer"><code>numpy.matrix</code> is discouraged</a>, and using <code>numpy.array</code> also fixes this issue:</p> <pre><code>def main(): # input is an square matrix A A = np.array([[1,2,3],[4,5,6],[1,2...
python|arrays|numpy
0
375,635
69,866,910
How to convert a pandas dataframe to NumPy array
<p>How can I convert a pandas dataframe (21 x 31) into a numpy array?</p> <p>For example:</p> <p>array_1 (n_1, n_2, n_3, ... , n31) <br> array_2 (n_1, n_2, n_3, ... , n31)<br> ...<br> array_21(n_1, n_2, n_3, ... , n31)<br></p> <p>I tried the following code snippet:</p> <pre><code>np.array(df) </code></pre> <p>.. and ge...
<p>It seems that you want to convert the DataFrame into a 1D array (<strong>this should be clear in the post</strong>).</p> <p>First, convert the DataFrame to a 2D numpy array using <code>DataFrame.to_numpy</code> (using <code>DataFrame.values</code> is discouraged) and then use <code>ndarray.ravel</code> or <code>ndar...
python|arrays|pandas|numpy
2
375,636
69,872,543
How to plot a stacked bar with annotations for multiple groups
<p>In the histogram a gap appears between 2 bars.. anyone knows why?</p> <p>I get this error:</p> <p>The number of FixedLocator locations (11), usually from a call to set_ticks, does not match the number of ticklabels (10).</p> <p>The csv file is just 2 columns, one with the name of the country and the other with the t...
<ul> <li>This is easier to implement as a stacked bar plot, as such, reshape the dataframe with <a href="https://pandas.pydata.org/docs/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>pandas.crosstab</code></a> and plot using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plo...
python|pandas|matplotlib|bar-chart
1
375,637
69,806,603
NumPy converting mixed data types in 2D arrays via astype
<p>I have been working on the <a href="https://www.ncdc.noaa.gov/ibtracs/index.php?name=ib-v4-access" rel="nofollow noreferrer">IBTrACS dataset</a> lately and would like to convert it to a 2D numpy array with the correct data types. I went through some filtering and selected the subset of data that I need, which is a 2...
<p>To illustrate my last comment:</p> <pre><code>In [9]: arr = np.array([[1,2,'word'],[3,4,'other']]) In [10]: arr Out[10]: array([['1', '2', 'word'], ['3', '4', 'other']], dtype='&lt;U21') In [11]: arr.astype('i,i,U10') Traceback (most recent call last): File &quot;&lt;ipython-input-11-3800d012c681&gt;&quot;...
python|numpy
1
375,638
43,098,706
TFLearn/Tensorflow: Proper way to save an encoder extracted from an autoencoder
<p>This issue was originally posted on the tflearn github repo, but I haven't had any luck there: <a href="https://github.com/tflearn/tflearn/issues/682" rel="nofollow noreferrer">https://github.com/tflearn/tflearn/issues/682</a></p> <p>I'm trying to save an encoder model that represents the middle layer from an autoe...
<p>In tensorflow you don't save into a .tfl file.</p> <pre><code>saver = tf.train.Saver() </code></pre> <p>and then save into a .cpkt</p> <p>Check this tutorial on saving: <a href="https://www.tensorflow.org/programmers_guide/saved_model" rel="nofollow noreferrer">https://www.tensorflow.org/programmers_guide/saved_...
python|tensorflow|deep-learning|tflearn
0
375,639
43,380,484
TensorFlow: Linear Regression with multiple inputs returns NaNs
<p>This is my first attemp at TensorFlow: I am building a <strong>Linear Regression</strong> model with <strong>multiple inputs</strong>.</p> <p>The problem is that <strong>the result is always NaN</strong>, and I suspect that it is because I am a complete noob with matrix operations using numpy and tensorflow (matlab...
<p>You need to add <code>keep_dims=True</code> inside your definition of <code>linear_model</code>. That is,</p> <pre><code>linear_model = tf.reduce_sum(x * w + b, axis=1, name='out',keep_dims=True) </code></pre> <p>The reason is that otherwise the result is "flattened", and you cannot subtract <code>y</code> from it...
python|numpy|tensorflow
1
375,640
43,232,352
Create simple bar chart from data frame with many columns
<p>I would like to create a simple bar chart from a pandas data frame that looks like this:</p> <p>A a1 a2 a3 a4 a5 a6...</p> <p>B b1 b2 b3 b4 b5 b6...</p> <p>C c1 c2 c3 c4 c5 c6...</p> <p>The values are float numbers and there are over 2000 columns The chart should have 3 bars in total with A,B,C on the x axis....
<p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow noreferrer"><code>sum</code></a> first and then plot by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.plot.bar.html" rel="nofollow noreferrer"><code>Series.plot.bar</code></a...
python|pandas|matplotlib|bar-chart
3
375,641
43,125,962
Pandas column contents as index
<p>I am trying to set a new pandas column using an existing pandas columns as set of indices to separate list, but I keep getting the following error:</p> <pre><code>TypeError: list indices must be integers or slices, not Series </code></pre> <p>See code below:</p> <pre><code>import pandas as pd monthvalues=[1,4,9,...
<p>It's because <code>df['month']</code> returns a Pandas Series, not a list as I suspect you expect (although it still wouldn't work if it were a list).</p> <p>I'm not sure if there's a neater way, but try this:</p> <pre><code>df['value'] = [monthvalues[x] for x in df['month']-1] </code></pre>
python|pandas
1
375,642
43,211,668
Check if a row in a pandas dataframe exists in other dataframes and assign points depending on which dataframes it also belongs to
<p>In <a href="https://stackoverflow.com/questions/38855204/check-if-a-row-in-one-data-frame-exist-in-another-data-frame">this</a> question this problem is solved partially to check if a row in a dataframe exists in another one.</p> <p>What I have is many dataframes df1, df2, df3, df4 etc. which are subsets of a large...
<p>Apply the exact methodology of the other question you are pointing at to get one additional boolean column per dataframe. You will end up with n extra columns being Exist_in_df1, Exist_in_df2, ..., Exist_in_dfn</p> <p>Now you have a simple boolean matrix to work with against which you can apply your simple rating l...
python|pandas|dataframe
0
375,643
43,302,821
Python: splitting trajectories into steps
<p>I have trajectories created from moves between clusters such as these:</p> <pre><code>user_id,trajectory 11011,[[[86], [110], [110]] 2139671,[[89], [125]] 3945641,[[36], [73], [110], [110]] 10024312,[[123], [27], [97], [97], [97], [110]] 14270422,[[0], [110], [174]] 14283758,[[110], [184]] 14317445,[[50], [88]] 143...
<p>My solution uses the magic of pandas' <code>.apply()</code> function. I believe this should work (I tested this on your sample data). Notice that I also added an extra data points on the end for the case when there is only a single move, and when there is no move.</p> <pre><code># Python3.5 import pandas as pd #...
python|pandas|graph|networkx
2
375,644
43,370,069
Converting xy co ords of Geotiff to numpy array positions in python
<p>I have geotiff file which I have read into an numpy array as described in the link below:</p> <p><a href="https://stackoverflow.com/questions/7569553/working-with-tiffs-import-export-in-python-using-numpy">Working with TIFFs (import, export) in Python using numpy</a></p> <p>The size of the Geotiff array that I hav...
<p>You need to use the geotransform, from an opened GDAL dataset you can get it with:</p> <p><code>gt = ds.GetGeoTransform()</code></p> <p>From the GDAL documentation:</p> <blockquote> <p>The affine transform consists of six coefficients returned by GDALDataset::GetGeoTransform() which map pixel/line coordinates into g...
python|arrays|numpy|gdal|geotiff
0
375,645
43,196,046
Plotting dictionary values into multi_line / timeseries Bokeh chart
<p><em>Note from maintainers: This question is about the obsolete <code>bokeh.charts</code> API removed years ago. For information on plotting with modern Boheh, including timseries, see:</em></p> <p><a href="https://docs.bokeh.org/en/latest/docs/user_guide/plotting.html" rel="nofollow noreferrer">https://docs.bokeh.o...
<p><em>Note from maintainers: This question is about the obsolete <code>bokeh.charts</code> API removed years ago. For information on plotting with modern Boheh, including timseries, see:</em></p> <p><a href="https://docs.bokeh.org/en/latest/docs/user_guide/plotting.html" rel="nofollow noreferrer">https://docs.bokeh.or...
python|python-3.x|pandas|dictionary|bokeh
0
375,646
43,257,217
Why is being indent's wrong causes wrong function?
<p>I cannot understand why this error happen. First,I wrote </p> <pre><code>import urllib.request from bs4 import BeautifulSoup import time import os def download_image(url,name): path = "./scrape_image/" imagename = str(name) + ".jpg" if not os.path.exists(path): os.makedirs(path) print...
<p>Because in the first example you're only getting the image if your condition passes:</p> <pre><code>if not os.path.exists(path): </code></pre> <p>And that condition will only pass <em>once</em> because you immediately create the path:</p> <pre><code>os.makedirs(path) </code></pre> <p>For every other iteration of...
python-3.x|tensorflow
0
375,647
43,130,439
pandas: replace NaN with the last non-NaN value in column
<p>I have an excel file which lists basketball teams and the players on each team. The first row for a new team states the team name in column 0 and a player on that team in column 1. The next row simply has a player on that team in column 1 (nothing in column 0 as the team is implied from the last stated team). This i...
<p>You can do this using the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="noreferrer"><code>fillna()</code></a> method on the dataframe. The <code>method='ffill'</code> tells it to fill forward with the last valid value.</p> <pre><code>df.fillna(method='ffill') </co...
python|excel|pandas|missing-data
16
375,648
43,147,267
Python Pandas: selecting rows based on criteria
<p>I have a pandas DataFrame in the following format:</p> <pre><code>df.head() y y_pred 599 0 0 787 9 9 47 2 2 1237 1 1 1069 6 6 </code></pre> <p>I want to find the rows / index numbers - where y != y_pred.</p> <p>I am trying to do it through <code>Select</code> but am not abl...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="nofollow noreferrer"><code>query</code></a>:</p> <pre><code>df = df.query('y != y_pred').index </code></pre> <p>Sample:</p> <pre><code>print (df) y y_pred 599 0 1 &lt;-values changed for match 787 ...
python|pandas
5
375,649
43,254,828
Extrapolating with a single data point
<p>Is there an function for extrapolating in numpy? </p> <p>I tried using the interp but of course that interpolates between the range of my values and not outside the range of values.</p> <p>So for example i have my x-values between 1 and 8, inclusive, and for each x-value, i have its corresponding y-value and I wan...
<p>scipy.interpolate.interp1d allows extrapolation.</p> <pre><code>import numpy as np from scipy import interpolate x = np.arange(1,8,1) y = np.array((10,20,30,40,50,60,70)) interpolate.interp1d(x, y, fill_value='extrapolate') </code></pre> <p>hope this answers your question</p>
python|numpy|extrapolation
0
375,650
43,432,466
Run TensorFlow on Macbook Pro 2016 with OpenCL?
<p>My laptop is Macbook Pro 2016 with graphic card Radeon Pro 460. Is there anyway that I can leverage my GPU to speed up tensorflow?</p> <p>I understand that CUDA is for NVIDIA card, and CUDA version of TF doesn't work. Is there any other tool that I can use GPU to run TF such as OpenCL?</p> <blockquote> <p>Update...
<p>Presumably, you've read: <a href="https://www.tensorflow.org/install/install_mac" rel="nofollow noreferrer">https://www.tensorflow.org/install/install_mac</a></p> <p>You cannot "trick your computer" and the suggestion that you might is perhaps contributing to your downvotes. </p> <p>If you want to learn more about...
cuda|tensorflow|opencl
3
375,651
43,415,876
How to write a custom aggregation function for strings?
<p>I have a Dataframe of millions of records, i'm trying to make the whole dataframe to be grouped by one column 'napciente', that is done. But there are 63 columns which i need to aggregate as string based on a specific match, for example, if the Series contain "SI" and any other strings i want to return that "SI" as ...
<p>You can use <code>apply</code> directly on the <code>groupby</code> object, then in the custom function, just return <code>pd.Series</code> in order for pandas to refer to it as columns:</p> <pre><code>def agg_func(group): """group is actually a dataframe containing only the relevant rows""" result = {} ...
python|string|python-3.x|pandas|anaconda
1
375,652
43,237,656
Extract Pattern in Pandas Dataframe
<p>I am extracting a pattern from the column of the dataframe. Some has the Word 'Oscar' and some has the Word 'Oscars'. How to extract in the panda dataframe . Below is the extract line code. This gives error.</p> <pre><code> df['Oscar_Awards_Won'] = df['Awards'].str.extract('Won (\d+) (Oscar[s]?)', expand=True).fi...
<p>Is this what is needed?</p> <pre><code>import pandas as pd df = pd.DataFrame({'a': [1,2,3,4], 'b': ['is Oscar','asd','Oscars','not an Oscars q']}) df['c'] = ['Won 3 Oscars. Another 234 wins &amp; 312 nominations.', 'Won 7 Oscars. Another 215 wins &amp; 169 nominations.', 'Won 11 Oscar. Another 174 wins &amp; 113 n...
python|pandas|numpy|dataframe
0
375,653
43,190,850
Python Seaborn Plot ValueError
<p>I have a pandas dataframe <code>df</code> and am trying to use the seaborn library to create a violin plot.</p> <pre><code> rank sentiment category 0 1 0.657413 m 1 2 0.895769 m 2 3 -0.435457 m 3 4 -0.717959 m 4 5 0.869688 m </code></pre> <p>This i...
<pre><code>sns.violinplot(x="rank", y="sentiment", hue="category", data=df) </code></pre>
python|pandas|seaborn
4
375,654
43,388,387
Searching for String Value in Pandas
<p>I am trying to search values in a Pandas dataframe.</p> <p>This is how my DF looks like:</p> <pre><code> 0 1 2 \ 0 NaN NaN NaN 1 CITI Pass-T... ...
<p>I'll give it a go, you can check if column is not empty like this:</p> <pre><code>for col in df: if not df[col].empty: print col print df[df[col].str.contains("A-1", na=False)] </code></pre>
python|pandas
1
375,655
43,085,422
Retrieve file from database using python
<p>I have a column <code>FileContent</code> (datatype <code>image</code>) in the database which store pdf, zip and docx file. </p> <p>The <code>FileContent</code> column has the following value in database: <code>0x2550444...</code></p> <p>I read the SQL table into DF using python and the values in column <code>FileC...
<p>Everything is fine. What you see is different representations of the same content.</p> <p>0x255044... is the hexadecimal representation of the first bytes. If you look up in an ASCII table,</p> <ul> <li>0x25 = '%'</li> <li>0x50 = 'P'</li> <li>0x44 = 'D'</li> </ul> <p>and so on. The other text is what the .pdf loo...
python|python-2.7|pandas|pdf|dataframe
3
375,656
43,310,962
Tensorflow installation problems in Windows
<p>I went through the official documentation to install tensorflow from <a href="https://www.tensorflow.org/install/install_windows" rel="nofollow noreferrer">https://www.tensorflow.org/install/install_windows</a> but I always get this error.</p> <pre><code>tensorflow-1.0.1-cp35-cp35m-win_amd64.whl is not a supported ...
<p>As you are using </p> <blockquote> <blockquote> <p>pip install tensorflow-1.0.1-cp35-cp35m-win_amd64.whl</p> </blockquote> </blockquote> <p>make sure of the following </p> <p>You have python version 3.5 64 bit installed.</p> <blockquote> <blockquote> <p>python --version</p> </blockquote> </blockq...
python|tensorflow|pip
0
375,657
43,142,475
How to convert n rows of xlsx to csv in Python while preserving date values
<p>I am trying to convert an xlsx file to one CSV file containing the header and another CSV file containing the actual data. I have the following requirements:</p> <ol> <li>Header does not start at first row but at row <code>start_line</code>.</li> <li>Dates should not be considered as floats but in some string forma...
<p>As long as all of your data is below your header row then following should work. Assuming the header row is at row <code>n</code> (indexing beginning at 0 not 1 like excel).</p> <pre><code>df = pd.read_excel('filepath', header=n) df.head(0).to_csv('header.csv', index=False) df.to_csv('output.csv', header=None, inde...
excel|python-2.7|csv|pandas|xlrd
1
375,658
43,241,733
Fastest way to go through a long list of arrays
<p>I have a data set from electrophysiological recordings in a hdf5 file in the form of what is really close to numpy arrays from my understanding and what I am trying to do is access it in the most efficient and fast way.</p> <p><strong>Let me explain:</strong> The dataset is a list of arrays (2D-array?); each array ...
<p>If my guess that <code>t_stamp</code> is a 1d array of varying length, you could collect all elements >400 with:</p> <pre><code>list_value = [] for t_stamp in (dset_data): list_value.append(t_stamp[t_stamp&gt;400]) # list_value.extend() </code></pre> <p>Use <code>append</code> if you want to collect the va...
python|numpy|h5py
1
375,659
43,045,426
Linear Regression overfitting
<p>I'm pursuing course 2 on this coursera course on linear regression (<a href="https://www.coursera.org/specializations/machine-learning" rel="nofollow noreferrer">https://www.coursera.org/specializations/machine-learning</a>)</p> <p>I've solved the training using graphlab but wanted to try out sklearn for the experi...
<p>I wouldn't even call this overfit. I'd say you aren't doing what you think you should be doing. In particular, you forgot to add a column of 1's to your design matrix, X. For example:</p> <pre><code># generate some univariate data x = np.arange(100) y = 2*x + x*np.random.normal(0,1,100) df = pd.DataFrame([x,y]).T d...
pandas|scikit-learn
3
375,660
72,476,599
How do I use MLRun to train a model with Hyperparameters?
<p>I am interested in Hyperparamter Tuning with MLRun. Does MLRun include functionality similar to Tensorflow Hparams.</p>
<p>MLRun supports iterative tasks for automatic and distributed execution with variable parameters (hyperparams). Iterative tasks can be distributed across multiple containers for parallel execution.</p> <p>MLRun iterations can be viewed as a child runs under the main task/run. Each child run gets a set of parameters t...
python|tensorflow|mlops
0
375,661
72,332,332
Maximum Value in pandas dataframe in specific column from index to index
<p>ich have a pandas dataframe pd_data and want to find the maximum value from an index to another index in one specific column.</p> <p>The dataframe looks like this:</p> <pre><code> Open High Low Close Volume 0 1.21223 1.21246 1.21215 1.21227 132.32 1 1.21223 1.21...
<p>You can try</p> <pre class="lang-py prettyprint-override"><code>out = df.loc[1:4, 'High'].max() # or out = df['High'].iloc[1:4].max() </code></pre> <pre><code>print(out) 1.21226 </code></pre>
pandas|max
0
375,662
72,353,629
How better perform Pearson R from 2 arrays of dimensions (m, n) and (n), returning an array of (m) size? [Python, NumPy, SciPy]
<p>I'm trying to improve a simple algorithm to obtaining the Pearson correlation coefficient from two arrays, <strong>X(m, n)</strong> and <strong>Y(n)</strong>, returning me another array <strong>R</strong> of dimension <strong>(m)</strong>.<br /> In the case, I want to know the behavior each row of <strong>X</strong>...
<p><code>pearsonr</code> only supports 1D array internally. Moreover, it computes the p-values which is not used here. Thus, it would be more efficient not to compute it if possible. Additionally, the code also recompute the <code>y</code> vector every time and it does not efficiently make use of vectorized Numpy opera...
python|numpy|scipy
1
375,663
72,482,224
Apply if else condition in specific pandas column by location
<p>I am trying to apply a condition to a pandas column by location and am not quite sure how. Here is some sample data:</p> <pre><code> data = {'Pop': [728375, 733355, 695395, 734658, 732811, 789396, 727761, 751967], 'Pop2': [728375, 733355, 695395, 734658, 732811, 789396, 727761, 751967]} PopDF = pd.DataFrame(da...
<p>Instead of selected the first N rows and subtracting them, subtract the entire column and only assign the first 6 values of it:</p> <pre><code>df.loc[:remainder, 'Pop2'] = df['Pop2'] - 1 </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df Pop Pop2 0 728375 728374 1 733355 733354 2 695395 695394 3 ...
python|pandas
1
375,664
72,233,338
Stack the same row in each layer of a 3D numpy array
<p>Hi is there a way to efficiently stack the same row in each layer of a 3D numpy array? I have an array like this:</p> <pre><code> a = np.array([[[&quot;a111&quot;,&quot;a112&quot;,&quot;a113&quot;], [&quot;b&quot;,&quot;b&quot;,&quot;b&quot;], [&quot;c&quot;,&quot;c&quot;,&quot;c&quot...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.swapaxes.html" rel="nofollow noreferrer"><code>swapaxes</code></a>:</p> <pre><code>a.swapaxes(0,1) </code></pre> <p>output:</p> <pre><code>array([[['a111', 'a112', 'a113'], ['a211', 'a212', 'a213'], ['a311', 'a312', 'a313'], ...
arrays|python-3.x|numpy
1
375,665
72,401,746
Drop the duplicate where boolean column = False
<p>In the following example, I have been trying to drop the duplicate that is == false. I mean when id and year match with more than 1 row (subset =[id, year])</p> <pre><code>df = pd.DataFrame({'id': ['1', '1', '1', '2', '2', '3', '4', '4'], 'Year': [2000, 2000, 2003, 2004, 2004, 2002, 2001, 2003], ...
<p>&quot;<em>I have been trying to drop the duplicate that is == false. I mean when id and year match with more than 1 row (subset =[id, year])</em>&quot; -&gt; so you need to group by <strong>both ID and Year</strong> (and use the correct column as boolean source):</p> <pre><code>df.loc[df['Boolean'].eq('false').group...
python|pandas|dataframe
2
375,666
72,460,821
Python Pandas - Find and replace across two dataframes
<p>I searched a lot but I can't solve my problem - maybe someone can give me a hint:</p> <p>I have two Panda Dataframes, df1 and df2, with these columns:</p> <pre><code>EAN PRODUCT-NAME OLD-DESCRIPTION PURCHASE-PRICE SALES-PRICE EAN NEW-PRODUCT-NAME NEW-DESCRIPTION </code></pre> <p>I want to locate a product in df1 by...
<p>EAN column is not common between both tables. df1 is way bigger.</p> <p>I thought about something like this, but this is not elegant at all...</p> <pre><code>for x in df1.index: for y in df2.index: if df1.loc[x, &quot;EAN&quot;] == df2.loc[y, &quot;EAN&quot;]: print (&quot;Found!&quot;) d...
python|pandas|dataframe
1
375,667
72,462,160
How to aggregate DataFrame to stay rows with the highest date and add new column in Python Pandas?
<p>I have DataFrame in Python Pandas like below (&quot;date_col&quot; is in &quot;datetime64&quot; format):</p> <pre><code>ID | date_col | purchase ----|------------|------- 111 | 2019-01-05 | apple 111 | 2019-05-22 | onion 222 | 2020-11-04 | banana 333 | 2020-04-19 | orange </code></pre> <p>I need to aggregate abov...
<p>Assuming the dataframe is sorted on <code>date_col</code> column, you can use <code>groupby</code>:</p> <pre><code>g = df.groupby('ID', as_index=False) g.last().merge(g.size()) </code></pre> <hr /> <pre><code> ID date_col purchase size 0 111 2019-05-22 onion 2 1 222 2020-11-04 banana 1 2 333...
python|pandas|aggregate|aggregate-functions
1
375,668
72,284,278
use python variable to read specific rows from access table using sqlalchemy
<p>I have an access table called &quot;Cell_list&quot; with a key column called &quot;Cell_#&quot;. I want to read the table into a dataframe, but only the rows that match indices which are specified in a python list &quot;cell_numbers&quot;. I tried several variations on:</p> <pre><code> import pyodbc import pand...
<p>Consider best practice of parameterization which is supported in <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_sql.html" rel="nofollow noreferrer"><strong><code>pandas.read_sql</code></strong></a>:</p> <pre class="lang-py prettyprint-override"><code># PREPARED STATEMENT, NO DATA query = ( 'SE...
python|pandas|ms-access|pyodbc
1
375,669
72,321,672
Jupyter notebook crashes when trying to create a df
<p>I'm trying to create a data frame where the rows are the result of vectorization of a list of stories and the columns are the words in those stories.</p> <p>the end goal is to predict gender of the writer of each story</p> <pre><code>vec = CountVectorizer() X_train = vec.fit_transform(df_train[&quot;story&quot;].tol...
<p>The <code>X_train.toarray()</code> method changes the type of the spare matrix (containing only the non null entries) outputed by your <strong>CountVectorizer</strong> to a dense one (full of zeros), which can be hundred of times bigger. Your error is most likely a memory error.</p> <p>I would suggest you only print...
python|pandas|dataframe|jupyter-notebook
0
375,670
72,376,168
Converting date to Monday date of each week
<p>I have a <code>df</code>:</p> <pre><code>date 2021-06-28 2021-06-29 2021-06-30 2021-07-02 2021-07-04 2021-07-07 2021-08-06 2021-08-07 </code></pre> <p>I am trying to convert this to week, I know I can use <code>df.date.dt.isocalendar().week</code> but this returns the week number with the default start date, whereas...
<p>You can convert to 'W-SUN' <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.to_period.html" rel="nofollow noreferrer">period</a> and get the first day:</p> <pre><code>df['date'] = pd.to_datetime(df['date']) df['Monday'] = df['date'].dt.to_period('W-SUN').dt.start_time </code></pre> <p><em>NB. ...
python|pandas|date
1
375,671
72,142,699
Get records that are a time interval away from a given date and specific conditions on a pandas DataFrame
<p>Let it be the following Python Panda DataFrame:</p> <pre><code>| ID | date | direction | country_ID | |-----------|-------------------------|---------------|------------| | 0 | 2022-04-01 10:00:01 | IN | UK | | unknown | 2022-04-01 10:00:03 | IN ...
<p>You can use a mask to split the dataframe in two and <a href="https://pandas.pydata.org/docs/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer"><code>pandas.merge_asof</code></a> to find the matches by group and within 2 seconds:</p> <pre><code>df['date'] = pd.to_datetime(df['date']) mask = df['ID'].eq...
python|pandas|dataframe|datetime
1
375,672
72,327,467
Python to list vs explode
<pre><code>Set.Categories.str.split(',').tolist() Set.Categories.str.split(',')).explode('Categories') </code></pre> <p>what is the difference between tolist and explode in pandas?</p>
<p>Those are completely different functions.</p> <p>The first one returns (here, nested) python lists:</p> <pre><code>df = pd.DataFrame({'Categories': ['a,b','c,d','e']}) df['Categories'].str.split(',').tolist() [['a', 'b'], ['c', 'd'], ['e']] </code></pre> <p>The second one expands the rows of the Series to have one ...
python|pandas|matplotlib
1
375,673
72,140,543
How to create a dummy only if a column has non-zero values for certain dates but zero for other dates
<p>Let's say, I want to identify traders who only traded during bull runs but did not trade (zero values) during downturns or stable periods. Let's say we have two bull runs, <code>2018Q4</code>, <code>2021Q4</code>. Below, <code>D</code> starts trading only from <code>2021Q4</code> (the second bull run period) but I w...
<p>You can test if both values not equal <code>0</code> and test both quarters, compare (thanks mozway for improvement) and last aggregate <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.all.html" rel="nofollow noreferrer"><code>GroupBy.all</code></a> for test if all <code...
python|pandas|dataframe
2
375,674
72,314,802
Tensor split to dynamic length tensors based on continuous mask values in tensorflow?
<p>I'm trying to figure out how to split my tensor of sequential data into multiple parts based on partitioning continuous masks with value of binary number '1'.</p> <p>I've read the official documentation. Howerver I can't find any function that can handle this easy. Any helpful ways for this in python?</p> <p>I have ...
<p>I recently discovered a method to do it in a very clean way in <a href="https://stackoverflow.com/a/72258918/2246849">this answer</a> by @AloneTogether:</p> <pre><code>import tensorflow as tf data_tensor = tf.constant([3,5,6,2,6,1,3,9,5]) mask_tensor = tf.constant([0,1,1,1,0,0,1,1,0]) # Index where the mask change...
python|tensorflow
2
375,675
72,268,307
How to replace string on pandas dataframe before certain characters
<p>Here's my dataset</p> <pre><code>Id Text 1 Animation_and_Cartoon - Comics and Anime/Cartoon_and_anime 2 Animation_and_Cartoon - Comics and Anime/Manga_and_anime </code></pre> <p>Expected output is all <code>_</code> before <code>-</code> is replaced by ' ', but after <code>-</code> is not</p> <pre><code>Id Tex...
<p>You can use:</p> <pre><code>df['Text'] = df['Text'].str.replace( r'^([^-]+)', lambda m: m.group().replace('_and_',' and '), regex=True) </code></pre> <p>Output:</p> <pre><code> Id Text 0 1 Animation and Cartoon - Comic...
python|python-3.x|regex|pandas
-1
375,676
72,476,560
How can I find out maximum percentage change for n years?
<p>Problem statement: display the <strong>maximum percentage change</strong> and the <strong>year</strong> that it occurred. The array looks like this:</p> <pre><code>import numpy as np array = np.array([[2010,2011,2012,2013,2014,2015,2016,2017,2018,2019], [1996,2165,2342,2511,2829,3052,3299,3523,3741...
<p>Is that what you're looking for ?</p> <pre><code>import numpy as np array = np.array([[2010,2011,2012,2013,2014,2015,2016,2017,2018,2019], [1996,2165,2342,2511,2829,3052,3299,3523,3741,3864]]) values = array[1] perc_change = [round((values[i]-values[i-1])*100/values[i-1], 2) for i in range(1, len(...
python|arrays|numpy|compare|shift
1
375,677
72,297,267
RNN network: ValueError: Expected input batch_size (96) to match target batch_size (32)
<p>I am implementing a simple recurrent neural network architecture for CIFAR10 image classification. I have also changed the batch size 512 to 1536 but it didn't work out. The input_size and sequence length is 32.</p> <pre><code>import torch import torch.nn as nn import torchvision import torchvision.transforms as tra...
<p>You've resized your images incorrectly, they are RGB images and so you need to include the channel information:</p> <pre><code>images = images.view(-1, 32, 3*32).cuda() </code></pre> <p>This is why your batch is 3x what you expect because it was putting each channel as an element of your batch.</p>
pytorch|recurrent-neural-network
0
375,678
72,410,286
How to clean data which has columns of 'Object' Data type
<p>So recently again I was playing with NFL dataset and trying to do data cleaning assignment. While performing this activity, I came up with data which is of 'Object' datatype. Now the thing is I did some data exploration and what I came up with is that the columns has lot of unique values. What I am looking for is to...
<p>Null-like values can be replaced with <code>pd.DataFrame.fillna()</code> or <code>pd.Series.fillna()</code>.</p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.f...
python|pandas|numpy|machine-learning|data-cleaning
2
375,679
72,363,556
Pandas Pivot Table - Adding Subtotals to Multiindex Table
<p>I have a table of data structured as it follows:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Card</th> <th>Payment ID</th> <th>Amount</th> </tr> </thead> <tbody> <tr> <td>John Doe</td> <td>t077</td> <td>7312637</td> <td>54</td> </tr> <tr> <td>John Doe</td> <td>t077</td>...
<p>Pivot table is a good approach, try:</p> <pre><code>table = pd.pivot_table( df, values=['Amount'], index=['Name', 'Card'], aggfunc=['count', 'sum'], ) # Adds subtotals, and sorts: pd.concat([ d.append(d.sum().rename((k, 'Total'))) for k, d in table.groupby(level=0) ]).sort_index(ascending=[...
python|pandas|pivot-table
0
375,680
72,338,772
How to fix Value error "Length of Values (1) doesn match length of index (15)"
<p>Workflow =&gt;</p> <ul> <li>Read CSV file and get <em>Unit Price</em> column data</li> <li>Convert column data price and create a new column as name 'Fabric'</li> <li>save the output as xlsx</li> </ul> <p>Sample:</p> <pre><code>Unit Price ---------- 330 350 380 I want to convert this data Fabric ------ Card Combe...
<p>That's easy dude...</p> <pre><code>your_df[&quot;Fabric&quot;] = your_df[&quot;Unit Price&quot;].apply(lambda x: str(x).replace(&quot;330&quot;, &quot;Card&quot;)) # do this for every conversion your_df.to_csv(&quot;filename.csv&quot;) </code></pre> <p>The above code can be saved as a CSV file that could be viewed...
python|pandas|valueerror
1
375,681
72,200,942
how do you fill row values of a column groupby with the max value of the grouped data
<p>I am trying to fill the values of a column in grouped data with the maximum value of the grouped data.</p> <p>The following is a sample of the data</p> <pre><code> df1 = [[52, '1', '0'], [52, '1', '1'], [52, '1', '0'], [52, '2', '0'], [53, '2', '0'], [52, '2', '0']] df = pd.DataFrame(df1, colu...
<p>You can use a group by in combination with a transform &quot;max.&quot; I'm not sure if you would simply want to replace the 'fail' column or if you would want to make a new column but this should get you the expected results.</p> <pre><code>df['fail'] = df.groupby(['Cow', 'Lact'])['fail'].transform(max) </code></pr...
python|pandas|pandas-groupby
2
375,682
72,441,972
How to convert Pandas DataFrame to Julia DataFrame.jl
<p>I have not been able to find a way to convert my 30,000 x 1,000 Pandas.jl String DataFrame into a DataFrames.jl DataFrame. I have attempted previous stackoverflow solutions but they have not worked. I would like to know what the best way is to convert the dataframe. Thanks for your help.</p>
<p>Preparing data:</p> <pre><code>julia&gt; import Pandas julia&gt; import DataFrames julia&gt; df_df1 = DataFrames.DataFrame(string.(rand(1:10, 10, 5)), :auto) 10×5 DataFrame Row │ x1 x2 x3 x4 x5 │ String String String String String ─────┼──────────────────────────────────────── 1 │ ...
pandas|dataframe|julia|pycall|pycall.jl
4
375,683
72,360,428
tf.GradientTape giving None gradient while writing custom training loop
<p>I'm trying to write a custom training loop. Here is a sample code of what I'm trying to do. I have two training parameter and one parameter is updating another parameter. See the code below:</p> <pre><code>x1 = tf.Variable(1.0, dtype=float) x2 = tf.Variable(1.0, dtype=float) with tf.GradientTape() as tape: n = ...
<p>Check the <a href="https://www.tensorflow.org/guide/autodiff#getting_a_gradient_of_none" rel="nofollow noreferrer">docs</a> regarding a gradient of <code>None</code>. To get the gradients for <code>x1</code>, you have to track <code>x</code> with <code>tape.watch(x)</code>:</p> <pre><code>x1 = tf.Variable(1.0, dtype...
python|tensorflow|gradient-descent|gradienttape
2
375,684
72,363,741
pytorch dataloader - RuntimeError: stack expects each tensor to be equal size, but got [157] at entry 0 and [154] at entry 1
<p>I am a beginner with pytorch. I am trying to do an aspect based sentiment analysis. I am facing the error mentioned in the subject. My code is as follows: I request help to resolve this error. Thanks in advance. I will share the entire code and the error stack. <code>!pip install transformers</code></p> <pre><code>i...
<p>Quick answer: you need to implement your own <code>collate_fn</code> function when creating a <code>DataLoader</code>. See <a href="https://discuss.pytorch.org/t/dataloader-gives-stack-expects-each-tensor-to-be-equal-size-due-to-different-image-has-different-objects-number/91941/7" rel="nofollow noreferrer">the disc...
pytorch|sentiment-analysis|pytorch-dataloader
1
375,685
72,263,932
pandas how to explode from two cells element-wise
<p>I have a dataframe:</p> <pre><code>df = A B C 1 [2,3] [4,5] </code></pre> <p>And I want to explode it element-wise based on [B,C] to get:</p> <pre><code>df = A B C 1 2 4 1 3 5 </code></pre> <p>What is the best way to do so? B and C are always at the same length.</p> <p>Thanks</p>
<p>Try, in pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html?highlight=explode" rel="nofollow noreferrer">1.3.2</a>:</p> <pre><code>df.explode(['B', 'C']) </code></pre> <p>Output:</p> <pre><code> A B C 0 1 2 4 0 1 3 5 </code></pre>
pandas|dataframe|data-science|data-munging|pandas-explode
1
375,686
72,370,869
Issues with generating the following block matrix using horizontal stacking and vertical stacking
<p>I am trying to generate the following block matrix consisting of submatrices <code>A</code> and <code>B</code>, and <code>N</code> is a positive integer. So far, my code is as follows:</p> <pre><code>C_lower = B for j in range(0,N): for i in range(0,N-j): col = np.linalg.matrix_power(A,i) @ B C =...
<p>Here's the answer to your first question. There are a number of issues in your code. This is a better way of achieving what you want:</p> <pre><code>C = np.zeros((N, N, A.shape[0], B.shape[1])) for i in range(N): for j in range(i + 1): C[i, j] = np.linalg.matrix_power(A, i - j) @ B </code></pre> <p>Simil...
python|numpy
1
375,687
72,218,279
How to get the min and the max index where a pandas column has the same value
<p>I have the following pandas dataframe</p> <pre><code>foo = pd.DataFrame({'step': [1,2,3,4,5,6,7,8], 'val': [1,1,1,0,0,1,0,1]}) </code></pre> <p>I would like to get the 1st and last <code>step</code> for each of the sequence of <code>1</code>s in the <code>val</code> column. Explanation:</p> <ul> <li><p>The first seq...
<p>IIUC, you can use a <code>groupby</code> aggregation, flatten using numpy and convert to list:</p> <pre><code># compute groups of consecutive numbers group = foo['val'].ne(foo['val'].shift()).cumsum() out = (foo .loc[foo['val'].eq(1), 'step'] # keep step only where vale is 1 .groupby(group).agg(['first', ...
python|pandas
2
375,688
72,357,955
reuse function with multiple string values pandas
<p>I'm hoping to streamline a function that only return columns based on a single string value. Using below, I have two distinct colours in a df. I want to pass each colour to a function. But I only want the output to include columns relating to that colour.</p> <p>If I have numerous colours and multiple outputs within...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.copy.html" rel="nofollow noreferrer"><code>DataFrame.copy</code></a>...
python|pandas
1
375,689
72,352,546
separating values ​between rows with pandas
<p>I want to separate values in &quot;alpha&quot; column like this</p> <p>Start:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>alpha</th> <th>beta</th> <th>gamma</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>1</td> <td>0</td> </tr> <tr> <td>A</td> <td>1</td> <td>1</td> </tr> <tr> <td>B<...
<p>You can try</p> <pre class="lang-py prettyprint-override"><code>out = (df.groupby('alpha') .apply(lambda g: pd.concat([g, pd.DataFrame([['X', 'X', 'X']], columns=df.columns)])) .reset_index(drop=True)[:-1]) </code></pre> <pre><code>print(out) alpha beta gamma 0 A 1 0 1 A 1 1 2 ...
python|pandas|dataframe
3
375,690
72,469,363
Replace only "," by "." in a String Python
<p>i'm using a dataset that contains a column &quot;Streams&quot; dtype: object and i just need to replace &quot;,&quot; by &quot;.&quot; to later use pandas.to_numeric() and convert String by float64. Is there a way to replace only the characters and keep the numbers?</p> <p>Example: 48,633,449 to 48.633.449</p> <p>Co...
<p>You are throwing away your <code>replace</code> since you are not assigning it to anything. Unless you explicitly use <code>inplace=True</code> arguments, Pandas methods do not change the current instance of an object (Series, Dataframes).</p> <p>You can provide the result of <code>replace</code> as the argument to ...
python|pandas|replace|dataset
1
375,691
72,305,984
Do LSTMs remember previous windows or is the hidden state reset?
<p>I am training an LSTM to forecast the next value of a timeseries. Let's say I have training data with the given shape (2345, 95) and a total of 15 files with this data, this means that I have 2345 window with 50% overlap between them (the timeseries was divided into windows). Each window has 95 timesteps. If I use t...
<p>What you are describing is called &quot;Back Propagation Through Time&quot;, you can google that for tutorials that describe the process.</p> <p>Your concern is justified in one respect and unjustified in another respect.</p> <p>The LSTM is capable of learning across multiple training iterations (e.g. multiple 15 st...
python|tensorflow|keras|lstm
1
375,692
72,348,873
Reading all the XML files to make dataframe
<p>I asked the question about reading the xml data to pandas dataframe</p> <p><a href="https://stackoverflow.com/questions/72252937/nlp-using-xlm-dataset/72336520#72336520">NLP using XLM dataset</a></p> <p>I got the following answer</p> <pre><code>medlinecitation = pd.read_xml(&quot;Taxonomy_NLP/public_dat/trainset/178...
<p>Your code seems to be loading two different elements from the same XML file. You can create a function to do this which returns the new dataframe:</p> <pre><code>def read_gct(path): medlinecitation = pd.read_xml(path, xpath=&quot;.//medlinecitation&quot;) .dropna(axis=1) abstract = pd.read_...
python|pandas|xml|dataframe
1
375,693
72,486,821
Summarization with Huggingface: How to generate one word at a time?
<p>I am using a DistilBART for abstractive summarization. The method <a href="https://huggingface.co/docs/transformers/v4.19.2/en/main_classes/text_generation#transformers.generation_utils.GenerationMixin.generate" rel="nofollow noreferrer"><code>generate()</code></a> is very straightforward to use. However, it returns...
<p>For future reference, <strong>here is how it can be done</strong> (<em>note:</em> this is specific to encoder-decoder models, like BART):</p> <p><strong>1. Initialization</strong></p> <pre class="lang-py prettyprint-override"><code>import torch from transformers import AutoTokenizer, AutoModelForSeq2SeqLM # Load mo...
huggingface-transformers|summarization|huggingface
0
375,694
72,295,381
Pandas dataframe Group by Time Interval and then ID with sum of Counts
<p>I'm trying to group a dataset by time first and then group by ID using pandas, while summing the counts. My data looks something along the lines of this:</p> <pre><code>id,selected time,count 1,5/16/2022 3:58:06 PM,1 1,5/16/2022 3:55:10 PM,1 2,5/16/2022 3:52:01 PM,2 3,5/16/2022 3:19:33 PM,1 3,5/16/2022 3:15:04 PM,1 ...
<p>first, a new columns is created where minute and seconds were made to zero, by flooring the hour. Then the Pivot_table gives the required result</p> <pre><code>df['selected_time_2'] = df['selected time'].astype('datetime64').dt.floor('h').dt.strftime('%m/%d/%YY %I:%M:%S %p') df.pivot_table(index='id',columns='selec...
python|pandas
0
375,695
72,276,265
'numpy.float64' object is not callable with numpy and pandas with custom function
<p>I have code of the form:</p> <pre><code>import pandas as pd import numpy as np def StrdErr(vec): return np.std(vec)/np.sqrt(len(vec)) df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['a', 'b', 'c']) for idx_q in range(0, df2.shape[0]): StrdErr = StrdErr(np.array(df2.loc[idx_q, :])) </c...
<p>This looks like a very complicated way to compute:</p> <pre><code>df2.std(1, ddof=0).div(np.sqrt(df2.shape[1])) </code></pre> <p>output:</p> <pre><code>0 0.471405 1 0.471405 2 0.471405 dtype: float64 </code></pre> <h5>even if it is inefficient, to fix your loop use:</h5> <pre><code>out = [] for idx_q in ran...
python|pandas|numpy|vector
2
375,696
72,304,677
Cleaning data using pandas and excel
<p>I have a massive data frame which I exported as an excel file to fix up spelling by removing duplicates and creating a column with all words corrected. Now I want to reimport the corrected data and replace the old values with the new ones so in the data frame every instance of 'Ne York' would become 'New York'. Here...
<p>You can load the new excel file as dataframe as follows.</p> <pre><code>import pandas as pd df = pd.read_excel(r'Path/Filename.xlsx') print(df) </code></pre> <p>if you want to replace the location column in the old dataframe with Final column, you can do: <code>df_old['Location'] = df['Final']</code></p>
pandas|dataframe|data-cleaning|data-wrangling
0
375,697
72,231,902
Reversing row values in a panda
<p>i'm having a mind wipe, i cannot for the life of me figure out a simple way of reversing this input to the output, any help would be appreciated.</p> <p>input:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>level1</th> <th>level2</th> <th>level3</th> <th>level4</th> </tr> </thead> <tbod...
<p>Here is one way, using reindexing:</p> <pre><code>(df .apply(lambda s: s.dropna()[::-1].reset_index(drop=True), axis=1) .reindex(columns=range(df.shape[1])) .set_axis(df.columns, axis=1) ) </code></pre> <p>output:</p> <pre><code> level1 level2 level3 level4 0 1.0 2.0 4.0 NaN 1 1.0 2.0...
python|pandas|dataframe
1
375,698
72,375,060
ValueError: Expected 2D array, got 1D array instead/ Signal Processing
<p>Can someone help to fix this error: I am a beginner and finding it difficult to figure out how to fix it.</p> <p>This is the error I am getting : ValueError: Expected 2D array, got 1D array instead: array=[ 282 561 837 ... 649442 649701 649957]. Reshape your data either using array.reshape(-1, 1) if your dat...
<p>As sklearn docs says in: <a href="https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.NearestNeighbors.html#sklearn.neighbors.NearestNeighbors.fit" rel="nofollow noreferrer">https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.NearestNeighbors.html#sklearn.neighbors.NearestNeighbors.fi...
python|arrays|numpy|pytorch|valueerror
0
375,699
72,328,963
Combining two indexes in a Pandas Dataframe
<p><a href="https://i.stack.imgur.com/1bEtb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1bEtb.png" alt="enter image description here" /></a></p> <p>I have the above dataframe and i would like to combine the two indexes so that only 1 remains and it is the addition of the indexes.</p>
<p>Get the 2 lines in the dataset and apply the logic below:</p> <pre class="lang-py prettyprint-override"><code>list1 = [1,0,1,0,1] list2 = [0,2,0,2,0] list3 = [x or y for x, y in zip(list1, list2)] print(list3) </code></pre> <p>Output: <code>[1, 2, 1, 2, 1]</code></p>
python|pandas
0