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
365,300
38,922,063
TensorFlow: LSTM on top of another LSTM
<p>There is not much to say as an introduction: I wanted to stack LSTM on another LSTM in TensorFlow, but keep being stopped by mistake I cannot quite understand, let alone solve singlehandedly. </p> <p>Here's the code:</p> <pre><code>def RNN(_X, _istate, _istate_2, _weights, _biases): _X = tf.transpose(_X, [1, ...
<p>TensorFlow's RNN code uses <a href="https://www.tensorflow.org/versions/r0.10/how_tos/variable_scope/index.html" rel="nofollow">"variable scopes"</a> to manage the creation and sharing of variables, and in this case it cannot tell whether you want to create a new set of variables for the second RNN, or reuse an old ...
machine-learning|tensorflow|deep-learning|recurrent-neural-network|lstm
2
365,301
38,754,493
Efficient data sampling with sparse timestamps on a pre-defined date range
<p>Consider a dataframe with sparse temporal data. The timestamps can be very old (e.g. years ago) or very recent.</p> <p>As an example, let's take the following dataframe:</p> <pre><code> tstamp item_id budget 2016-07-01 14:56:51.882649 0Szr8SuNbY 5000.00 2016-07-20 14:57:23.856878 0Szr8S...
<p>You can do a <code>groupby</code> on <code>'item_id'</code> and call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> on each group:</p> <pre><code># Define the new time interval. new_dates = pd.date_range('2016-07-15', '2016-07-31...
python|pandas|numpy|resampling
1
365,302
38,768,996
How to install pandas for Python 3?
<p>I try to install pandas for Python 3 by executing the following command:</p> <pre><code>sudo pip3 install pandas </code></pre> <p>As a result I get this:</p> <pre><code>Downloading/unpacking pandas Cannot fetch index base URL https://pypi.python.org/simple/ Could not find any downloads that satisfy the requir...
<p>Try this: </p> <pre><code>sudo apt-get install python3-pip sudo -H pip3 install pandas </code></pre>
python|pandas|installation|pip|python-3.4
15
365,303
38,577,170
SFrame from numpy array
<p>I would like to create an <a href="https://github.com/turi-code/SFrame" rel="nofollow noreferrer"><code>SFrame</code></a> from a <code>NumPy</code> array.</p> <p>What i want specifically is:</p> <pre><code>np.arange(16).reshape(4, 4) </code></pre> <p>=></p> <pre><code>+----+----+----+----+ | 0 | 1 | 2 | 3 |...
<p>I also has this issue, I also find multi-indexing hard in SFrame.</p> <p>may be silly fix but still workable;</p> <pre><code>from graphlab import SFrame,SArray data=np.arange(16).reshape(4, 4).T sf=SFrame(map(SArray,data) </code></pre> <p>should result in something like this</p> <pre><code>X1 X2 X3 X4 0 1...
python|numpy|pandas|dataframe|sframe
1
365,304
38,688,777
TensorFlow: Graph Optimization (GPU vs CPU Performance)
<p>This issue was originally posted on <a href="https://github.com/tensorflow/tensorflow/issues/3320" rel="noreferrer">Github #3320</a>. It would be good to start there as there is more detail on the original problem in that thread and bulky so I don't wish to re-post on StackOverflow. A summary of the issue is perfo...
<p><a href="https://i.stack.imgur.com/ssAll.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ssAll.png" alt="Results"></a>Thanks for the excellent post.</p> <p>I am experiencing a similar issue: GPU/CPU processing takes more CPU and elapsed time than CPU processing alone for two examples provided by...
tensorflow|reinforcement-learning
2
365,305
38,681,802
pandas not condition with filtering
<p>How I can implement not condition on the filtering </p> <pre><code>grouped = store_ids_with_visits.groupby(level=[0, 1, 2]) grouped.filter(lambda x: (len(x) == 1 and x['template_fk'] == exterior_template)) </code></pre> <p>I want to get all entries that not answering on the condition</p> <p>I tried doing:</p> <p...
<p>IIUC, you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html" rel="noreferrer"><code>isin</code></a> to check for bool conditions and take only the <code>NOT(~)</code> values of the grouped dataframe: </p> <pre><code> df[~df.isin(grouped.filter(lambda x: (len(x) == 1...
python|pandas|dataframe
19
365,306
38,662,011
Pandas - equivalent of str.contains() in pandas query
<p>Creating a dataframe using subsetting with below conditions</p> <pre><code>subset_df = df_eq.loc[(df_eq['place'].str.contains('Chile')) &amp; (df_eq['mag'] &gt; 7.5),['time','latitude','longitude','mag','place']] </code></pre> <p>Want to replicate the above subset using query() in Pandas.However not sure how to re...
<p>As of now I am able to do this by using the <code>engine='python'</code> argument of the <code>.query</code> method to use <code>str.contains</code> inside a query.</p> <p>This should work:</p> <pre><code>query_df = df_eq[['time', 'latitude', 'longitude', 'mag', 'place']].query( "place.str.contains('Chile') an...
python|pandas|data-analysis
8
365,307
38,746,001
Strange Python numpy array indexing behaviour
<p>I have the following array</p> <pre><code>[0. 100. 200. 300. 400. -500. -400. -300. -200. -100.] </code></pre> <p>which I'm trying to rearrange to be from smallest to largest.</p> <p>I find the turning point from pos to neg which is stored in j.</p> <p>If I print the following I get </p> <pre><code>&gt;&gt;prin...
<p>Almost everywhere through Python the behavior is <code>[)</code>, meaning the left (or start) argument is inclusive and the right (or end) argument is exclusive. Be it list slicing, string slicing, the <code>range</code> function, etc.</p> <p>It only makes sense for <code>numpy</code> to follow this convention.</p...
python|arrays|numpy
4
365,308
38,752,790
Filter 2D numpy array if array element appears more than once
<p>I would like to remove rows that share an element in a 2D array. For example:</p> <pre><code>array = [0 1] [2 3] [4 0] [0 4] filtered_array = [2 3] </code></pre> <p>edit: column position does not matter</p>
<p>Here's a vectorized approach using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a> -</p> <pre><code>def filter_rows(arr): # Detect matches along same columns for both cols samecol_mask1 = arr[:,None,0] == arr[:,0] samecol_mask2 =...
numpy|multidimensional-array
2
365,309
63,253,169
Calculating the moving average of rows of a dataframe, 12 columns at a time, starting from the left most point
<p>I have a df as such</p> <pre><code> A B C D X 1 2 3 4 Y 5 6 7 8 Z 9 10 11 12 </code></pre> <p>I need to perform a moving average on a row basis. Here is an example resultant df with a moving average 2 columns at a time:</p> <pre><code> A B C D X 1.5 2.5 3.5 ...
<p>We need reverse the order of column then do <code>rolling</code></p> <pre><code>df=df.T.iloc[::-1].rolling(2,min_periods=1).mean().iloc[::-1].T Out[348]: A B C D X 1.5 2.5 3.5 4.0 Y 5.5 6.5 7.5 8.0 Z 9.5 10.5 11.5 12.0 </code></pre>
python|pandas|dataframe
1
365,310
62,913,342
linear regression train/shape output not correct
<p>I'm trying to use linear regression to predict the amount of releases of show there will be in the upcoming years. I have a data frame where ever row is a release with column having info like release year, genre, ... I would like to use this to predict the amount of upcoming releases, so what I've done is make a new...
<p>according to <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html" rel="nofollow noreferrer">https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html</a> <br /> the return of train_test_split is in another order then you did. ...
python|database|jupyter-notebook|linear-regression|sklearn-pandas
1
365,311
62,939,849
Pandas dataframe slicing with multiple column ranges
<p>I have a pandas dataframe with many labeled columns. For example:</p> <pre><code>import numpy as np import pandas as pd cols = ['lat', 'long', 'foo', 'bar', 'year', 'month', 'day', 'hour', 'min', 'sec'] df = pd.DataFrame(np.random.random((10, 10)), columns=cols) </code></pre> <p>I would like to slice this dataframe...
<p>Slicing by multiple label ranges is more challenging and has less support, so let's try to slice on index ranges instead:</p> <pre><code>loc = df.columns.get_loc df.iloc[:, np.r_[loc('lat'):loc('long')+1, loc('year'):loc('day')+1]] lat long year month day 0 0.218559 0.418508 0.345499...
python|pandas
2
365,312
63,002,352
Where are those numbers coming from in pytorch neural networks?
<p>I'm newbie in Pytorch (python), i was just scrolling through their official tutorial and i found this simple neural network architecture. Everything is clear, but those numbers, last three fully connected layers, where are they coming from?</p> <pre class="lang-py prettyprint-override"><code>self.fc1 = nn.Linear(16 ...
<pre><code> self.fc1 = nn.Linear(16 * 6 * 6, 120) self.fc2 = nn.Linear(120, 84) # you can use any number instead of 120 play with this number and see which gives you best result. self.fc3 = nn.Linear(84, 10) </code></pre> <p>120 is number of units in <code>first layer after conv layer</code> , 84 in <code>second layer...
python-3.x|pytorch|conv-neural-network
3
365,313
62,964,122
Pandas create multiple columns based on other columns
<p>I have a huge df (720 columns) with this structure:</p> <pre><code>id A B C 1 1 0 1 2 1 0 1 3 1 1 1 </code></pre> <p>I would like to create a new df, based on calculations such as:</p> <pre><code>if A and B = 1 then v1 = 1 if A and C = 1 then v2 = 1 if A and D = 1 then v3 = 1 if A and XX = 1 then v719 = 1 id...
<p>For your question we can do , since 1 * 1 = 1</p> <pre><code>s=df.loc[:,'B':].mul(df.A,axis=0) B C 0 0 1 1 0 1 2 1 1 s.columns=np.arange(s.shape[1])+1 df=df.join(s.add_prefix('v_')) </code></pre>
python|pandas
3
365,314
63,287,004
Bokeh Select Widget to Update Plot
<p>I am trying to build a grid plot that updates based on value selected from 'Select' widget using Bokeh. The graph works but there is no interaction between the widget and the graph. I am not sure how to do this. The goal is to use the 'Select' to update dfPlot then follow the remaining steps.</p> <p>Here is what i h...
<p>Someone else will probably give you a better answer. I'll just say, I think you might be doing things completely wrong for what you are trying to do (I did the same thing when starting to work with Bokeh).</p> <p>My understanding after a bit of experience with Bokeh, as it relates to your problem, is as follows:</p...
python|pandas|bokeh
0
365,315
63,159,749
How to detect if input does not match any of the output options
<p>How would I accurately identify the results of a prediction to determine if the input was a match or if the input was completely difference to any of the training data.</p> <p>For example, if I've got a model which identifies &quot;circles&quot;, &quot;squares&quot; and other shapes but then the user inputted a &quo...
<p>In this case, softmax can still help. It is an approximation, not an exact unit-step function. You can always check the difference between the two highest terms, and threshold it to check if multiple shapes are present.</p> <p>For example, if the input contains all three shapes, the ideal output of softmax would be:...
tensorflow|tensorflow2.0|tensorflow.js
0
365,316
63,081,923
Loading pandas dataframe from a URL
<p>I tried to load a data frame from a URL</p> <pre class="lang-py prettyprint-override"><code>url = 'https://ncdc.herokuapp.com/ncdc-covid-data/epicurve-by-date?state=akwa%20ibom' df = pd.read_csv(url) </code></pre> <p>so instead of a data frame with several rows, I just got a lump of columns instead. any help will b...
<ul> <li>The URL contains <code>JSON</code>, not a <code>CSV</code>, data.</li> <li>The information of interest is in the <code>'data'</code> key</li> <li>Read the URL with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_json.html" rel="nofollow noreferrer"><code>pandas.read_json</code><...
pandas|dataframe|json-normalize
0
365,317
63,097,036
How to use Inner Join and groupby in the same python code
<p>I have the below input from excel file (<strong>Sheet1</strong> and <strong>Sheet2</strong>)</p> <p><code>Sheet1:</code></p> <p><code>Order ID | Order Date | Segment | Sales</code></p> <p><code>1001 11-11-2016 Consumer 100</code></p> <p><code>1001 11-11-2016 Consumer 200</code></p> <p><code>2001 ...
<p>Let's try this,</p> <pre><code>print( sheet1[sheet1['Order ID'].isin(sheet2['Order ID'])] .assign(Year=pd.to_datetime(sheet1['Order Date']).dt.year) .groupby(['Order ID', 'Segment', 'Year'])['Sales'].sum() .reset_index(name=&quot;Sales_Sum&quot;) ) </code></pre> <hr> <pre><code> Order I...
python|pandas|pandas-groupby|python-3.7
2
365,318
63,044,687
Replace the values of a given column in pandas with a dictionary
<p>So, I have a dataframe with the name of all the states in the USA and a few cities for each state. However, I need to change the names of the states to its two letter acronyms (ex: Nevada becomes NV and Wyoming becomes WY).</p> <p>A have a dictionary with the name of the states/territories and its respective acronym...
<p>In the dictionary the key is <code>acronym</code> and the value is the <code>state</code>. I assume that <code>State</code> column is not an acronym. You may have to inverse the dictionary such as <code>inv_map = {v: k for k, v in states.items()}</code></p>
python|pandas
1
365,319
63,102,063
sum of specific elements in normalized value count in pandas (KNN Classification)
<p>I am trying some knn-Classification and when testing the model with 30% of the original data,</p> <p>I want to calculate the percentage of correct classification within a +/-3 point range (left side in below output).</p> <p>In other words the sum of the seven floats at the bottom of the below output:</p> <pre><code>...
<p>You can lose the sort because it is un needed, but in any case you should sum by index:</p> <pre><code>df.loc[-3:0]['0'].sum() </code></pre> <p>assuming df is your dataframe and '0' is the name of the column</p>
python|pandas|scikit-learn|count|knn
0
365,320
63,087,662
How to plot a complex-valued function of a real variable in python with matplotlib
<p>I was trying to plot the function <code>((phi^n)-((-1/phi)^n))/(5^0.5)</code> as the real part in the x-axis and imaginary part in the y-axis with matplotlib and numpy, I used this code to do so</p> <pre><code>#matplotlib.pyplot for the graph import matplotlib.pyplot as plt #numpy for mathematical operations from n...
<p>To plot a complex-valued function of a real variable you have to specify that the range of the function is complex numbers so that NumPy arrays are able to store complex numbers. You can do this by adding <code>+0j</code> to the function's variable, so the code will be like this</p> <pre><code>#matplotlib.pyplot for...
python|numpy|matplotlib
0
365,321
62,945,942
How do I extract year/hour/day data from pandas Timestamp object in C++?
<p>I am working on a project with embedded Python in C++ and have run into an issue with pandas DataFrames with datetimes/Timestamps.</p> <p>When adding datetime objects to pandas, if they are within the range of Timestamp they seem to get auto-converted into a Timestamp object. For example:</p> <p><a href="https://i.s...
<p>I have figured out the way to do this, in case anyone looks for this later.</p> <p>Pandas Timestamp objects actually do extract as PyDateTime objects, so they aren't the problem. My problem was that I was extracting them as numpy ndarrays to get the column from the Pandas DataFrame first, and numpy stores the timest...
python|c++|pandas|python-datetime
0
365,322
63,156,151
How can I delete a model in Tensorflow.js?
<p>When reading the official documentation, I am aware that when handling Tensors directly one must explicitly destroy them after use to avoid memory leaks:</p> <pre><code>let mytensor = tf.tensor([1, 2, 3, 4]); tf.dispose(mytensor); </code></pre> <p>However, what can one do to dispose of a <em>model</em>? Is simply ca...
<p>A model contains layers. Each layer contains weights that can be disposed. To dispose these weights, <a href="https://js.tensorflow.org/api/latest/#tf.layers.Layer.dispose" rel="nofollow noreferrer">layer.dispose</a> can be used.</p> <pre><code>model.layers.forEach(l =&gt; l.dispose()) </code></pre>
javascript|memory-management|tensorflow.js
1
365,323
63,233,147
Docker, Python and Pandas
<p>I'm trying to deploy a Python app with docker container. I developed my app on Windows and Raspberry Pi 3B, that's why I use Python 2.7.16.</p> <p>I build my Dockerfile as :</p> <pre><code>FROM python:2.7.16 # Set workspace WORKDIR /app # Install python dependencies COPY requirements.txt . RUN pip install -r ./req...
<p>Use <code>FROM python:3.7</code> in your Dockerfile</p>
python|pandas|docker
0
365,324
63,098,108
How to replace NaN with a value which is meant to increase by 10 of previous non Non value?
<p>Suppose I have a DataFrame with some NaNs:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]]) &gt;&gt;&gt; df 0 1 2 3 1 4 NaN NaN 2 NaN NaN 9 The result should be like this which is just +10 of the previous NaN value of the column. 0 1 2 3 1 4 ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ffill.html" rel="nofollow noreferrer"><code>ffill()</code></a> to fill the <code>NaN</code>s with the previous non-NaN value, and then a simple mask to increment all by 10:</p> <pre class="lang-py prettyprint-override"><...
python|pandas
3
365,325
63,305,588
How do I import an excel file and search for specific record using python and pandas?
<p>I’m trying to import an excel file and search for a specific record</p> <p>Here’s what I have come up with so far, which keeps throwing error.</p> <p>The excel spread sheet has two columns <code>Keyword</code> and <code>Description</code>, each keyword is around 10 characters max, and description is around 150 chara...
<p>the filter syntax is like this</p> <pre class="lang-py prettyprint-override"><code>df_filtered = df[df[COLUMN]==KEYWORD] </code></pre> <p>so in your case it'd be</p> <pre><code>lookup = df1[df1['Keyword'] == &quot;as&quot;]['Description'] </code></pre> <p>or the whole code</p> <pre><code>import pandas as pd file = '...
python|excel|pandas|dataframe
1
365,326
62,963,647
Fastest way to filter and sort Numpy array?
<p>I have a large Nx2 numpy array called <code>points</code> of <code>[x, y]</code> coordinates and I want to filter it by Euclidean distance and then sort it by shortest distance. Each point in the array will be tested against another given point, call it <code>p1</code>, and I only want the <code>[x, y]</code> coordi...
<p>Try this out:</p> <pre><code>import numpy as np distances = np.linalg.norm(points - p1, axis=-1) new_points = points[distances &lt; rad] new_distances = distances[distances &lt; rad] new_distances = np.expand_dims(new_distances, axis=-1) new_points_with_new_distances = np.hstack((new_points, new_distances)) ind...
python|numpy
0
365,327
62,938,070
Different values of Numpy.var() and Pandas.var()
<p>I am learning a bit about Standard Scaler in datasets. I am noticing a strange behavior which I think might be a syntax or logical error in my code, but can anyone correct me.</p> <p>As we know that when we do <code>StandardScaler</code>, we have a <code>std</code> of 1 and <code>mean</code> of 0 as <code>Var = Stde...
<p>The problem is due to using different degrees of freedom. The scikit-learn docs state that they use the <strong>biased</strong> estimator or sample variance:</p> <blockquote> <p>We use a biased estimator for the standard deviation, equivalent to numpy.std(x, ddof=0). Note that the choice of ddof is unlikely to affec...
python|pandas|numpy|scikit-learn|statistics
1
365,328
63,226,973
Concatenate two arrays as coordinate-couples
<p>I have two numpy arrays that I need to combine in a two dimensional array: each row has to be a coordinates couple. For example, if the numpy arrays were:</p> <pre><code>[1 2 3] [a b c] </code></pre> <p>then what I'm aiming for is:</p> <pre><code>[[1 a] [1 b] [1 c] [2 a] [2 b] [2 c] [3 a] [3 b] [3 c]] </code...
<p>One way with <code>meshgrid</code></p> <pre><code>x = np.array([1,2,3]) y = np.array([4,5,6]) np.array(np.meshgrid(x, y)).T.reshape(-1, 2) </code></pre> <p>will result in</p> <pre><code>array([[1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], [3, ...
python-3.x|concatenation|numpy-ndarray
1
365,329
63,071,476
SetInterval() and async function? CPU working too hard with TF.js
<p>I have written a code for webcam classification in Tensorflow.js. By combining advice from many tutorials, it now works. However, in its current stage, it's very expensive for the system as the Tensorflow.js. predictions loop with <code>while (true)</code>. Google Chrome Helper (renderer) uses 50-60% of the CPU with...
<p>You already have a setinterval loop:</p> <pre><code>requestAnimationFrame(() =&gt; this.app()); </code></pre> <p>This works exactly like the same as:</p> <pre><code>setInterval(() =&gt; this.app(), 16.66666666667); </code></pre> <p>(well, almost exactly. It's hard to get exact millisecond value for 1/60 seconds).</p...
javascript|tensorflow.js
1
365,330
63,069,593
How to pass a DataFrame column as an argument in a function?
<p><a href="https://i.stack.imgur.com/wimFh.png" rel="nofollow noreferrer">enter image description here</a> Check the distribution of a specific value like the number of times the weather was exactly Cloudy in the given column. Feel free to check on other values. You can check it by calling the function clear with resp...
<p>Maybe just pass on the name of the column - instead of the entire column:</p> <pre><code>def clear(df, column_name, column_value): value_counts = df.loc[(df[column_name] == column_value)] # filtering dataframe return len(value_counts) </code></pre>
python|pandas|function|parameter-passing|filtering
0
365,331
63,244,911
pandas df.apply, str-methods, "If using all scalar values, you must pass an index"
<p>I have a Pandas-df that looks like this:</p> <pre><code>pods_infos = pd.read_csv(&quot;data.txt&quot;, delimiter = &quot;;&quot;, index_col = 0, header = None, names = [&quot;Position&quot;, &quot;Capacity&quot;,&quot;Capacity reversed&quot;, &quot;Storage tag&quot;, &quot;Re...
<p>The error message says that if you're passing scalar values, you have to pass an index. So you can either not use scalar values for the columns. e.g. use a list:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'A': [x], 'B': [y]}) &gt;&gt;&gt; df A B 0 2 3 </code></pre> <p>or use scalar values and pass an index...
python|pandas|apply
1
365,332
63,272,768
pandas to_sql syntax error with SQLAlchemy and Sybase
<p>I am currently struggling with to_sql function in pandas while creating and inserting data into a new table.</p> <p>Here is the code :</p> <pre><code>import pandas as pd import sqlalchemy import urllib params=urllib.parse.quote_plus(&quot;Driver=Adaptive Server Enterprise;SERVER=xxx.div.com;DATABASE=MYDB;USER=DIV;P...
<p>I am able to reproduce your issue using the internal &quot;sybase&quot; dialect in SQLAlchemy 1.3.18. That internal dialect is</p> <ul> <li>unsupported,</li> <li>soon to be officially deprecated, and</li> <li>will be removed from a future release.</li> </ul> <p>I also confirmed that the <a href="https://github.com/g...
python-3.x|pandas|sqlalchemy|sybase|sap-ase
1
365,333
62,920,233
Saving GRAYSCALE .png image with cv2.imwrite() not working
<p>I've generated images by using <code>tf.keras.preprocessing.image.ImageDataGenerator</code> and I've plotted what I've generated using <code>matplotlib</code>, here are the results:</p> <p><a href="https://i.stack.imgur.com/SAsIF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SAsIF.png" alt="ente...
<p>Most likely your pixel values from your data is in range [0.0, 1.0]. You should convert them to [0, 255] range before saving them via opencv.</p> <pre><code>cnt = 0 for image, label in zip(augmented_images, labels): cnt += 1 path = os.path.join(augmented_raw_images_train_dir,str(int(label[0])),&quot;aug_&quot;+s...
python|numpy|opencv
3
365,334
63,310,172
Expand list in pandas data frame to extra rows
<p>I have a pandas data frame that looks something like this:</p> <pre><code> EIN file_num 0 10043280 [2748, 3010, 4410] 1 10391479 [217, 829, 1753, 3131, 4376, 7428, 8048] 2 10430261 [362, 531, 3788, 4851, 5680] 3 ...
<p>You can try with <code>explode</code></p> <pre><code>df = df.explode('file_num') </code></pre>
python|pandas
2
365,335
63,043,495
Pandas lookup and return Boolean
<p>I have the below dataframe and my objective is to find whether a stock was held from one period to the next. To do this, I created two lookup codes <code>str_previous_previous_period_code</code> and <code>str_current_period_code</code> based on the concatenation of <code>ticker</code> and string conversion of <code>...
<p>I guess you can do the lookup using either :</p> <ul> <li>the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a> method of the <code>Series</code> you get with <code>df['str_current_period_code']</code> :</li> </ul> <pre class="l...
python|pandas
1
365,336
63,277,114
Setting pandas values based on range of times
<p>I would like to set all values to some value (say 999) that occur within some time period (say 1 hour) of any value over some threshold (say 7). I have had some luck with wonky non-vectorized approaches, but there must be a better, pandastic way to do it...</p> <p>An example is:</p> <p>Setting up a random data frame...
<p>Here is one approach, IIUC:</p> <pre><code>import pandas as pd import numpy as np np.random.seed(42) hr_rng = pd.date_range(start='7/1/2014 00:00:00', end='7/1/2014 10:00:00', freq='H') df = pd.DataFrame(hr_rng, columns=['date_time']) df.set_index(pd.DatetimeIndex(df...
pandas|time-series
0
365,337
62,941,853
How to Filter a DataFrame Where a Column Contains Values Stored in a List?
<pre><code>&quot;&quot;&quot;DataFrame of tweets&quot;&quot;&quot; tweet_df = pd.DataFrame(text_tweets, columns = [&quot;Date&quot;, &quot;Tweet&quot;]) &quot;&quot;&quot;Terms to search tweets&quot;&quot;&quot; TweetsCheckList = [&quot;Word&quot;, &quot;Word2&quot;,..., &quot;Word100&quot;] &quot;&quot;&quot;Empty ...
<p>You can filter the DataFrame using boolean conditions to check if any of the words are present in the column, something like this:</p> <pre><code># Setup: tweet_df = pd.DataFrame({&quot;Tweet&quot;: [&quot;Word ...&quot;, &quot;something else&quot;, &quot;blah Word2&quot;]}) TweetsCheckList = [&quot;Word&quot;, &quo...
python|pandas|dataframe
0
365,338
63,170,870
How to compare values between 2 dataframes
<p>#Hello i have 2 dataframes as per below</p> <pre><code>!pip install yahoo_earnings_calendar import pandas as pd`enter code here` from datetime import datetime from datetime import timedelta from yahoo_earnings_calendar import YahooEarningsCalendar import dateutil.parser </code></pre> <p>#setting the report date</p>...
<p>Tried using this below code,</p> <pre><code>&gt;&gt;&gt; tickers_in_snp=earnings_df[earnings_df['ticker'].isin(snp)] </code></pre> <p>This gives a dataframe of values where values of tickers present in symbol column of snp.</p> <pre><code>&gt;&gt;&gt; tickers_in_snp.head() companyshortname epsactual ... start...
python|pandas
0
365,339
63,250,668
Read dataframe split by nan rows and extract specific columns in Python
<p>I have a example excel file <code>data2.xlsx</code> from <a href="https://www.dropbox.com/scl/fi/5ngschi19ov0rbvqe638b/data2.xlsx?dl=0&amp;rlkey=k6trx5gyhtye84k8v6hqqi3iq" rel="nofollow noreferrer">here</a>, which has a <code>Sheet1</code> as follows:</p> <p><a href="https://i.stack.imgur.com/iGr3I.png" rel="nofollo...
<p>*note I use column indices when the column name is not certain</p> <p>You can split tables with</p> <pre><code>df['city'] = df.groupby(df.iloc[:, 0].isna().cumsum()).transform(first) df.dropna(subset=df.columns[0], inplace=True) df = df.loc[df[df.colmns[0]] != df.city] </code></pre> <p>Now <code>df</code> will have ...
python-3.x|pandas|dataframe|openpyxl
1
365,340
62,959,150
Find previous day in the Dataframe and assign its value to current day
<p>I have a Dataframe which has values corresponding to date. Now i need to get previous day column values and assign to the current day.</p> <p>Ex:- Current day is 10-01-2020 then previous day in the dataframe is 07-01-2020, get the values of previous day and assign to current.</p> <h2>Sample input</h2> <pre><code>Dat...
<p>Use <code>groupby</code> on <code>Date</code> and aggregate te dataframe using <code>last</code>, next use <code>reindex</code> to conform aggregated DataFrame to the index according the dates in original datafarme:</p> <pre><code>df1 = df.groupby('Date').last().shift().reindex(df['Date']).reset_index() </code></pre...
python|pandas|dataframe|group-by
1
365,341
62,920,375
Cleaning text files and importing as pandas dataframe in python
<p>I have a time-series file with a header and meteorological data, like this:</p> <p>&quot;NAME: Timeseries results</p> <p>LOC_I: 130</p> <p>LOC_J: 181</p> <p>LAT: -9.03</p> <p>LON: -35.22</p> <p>UNITS: SECONDS</p> <p>SECONDS YY MM DD hh mm ss wind_x wind_y hourly_prec rel_hum</p> <p>|BeginResults|</p> <p>0 2007 1 1 0...
<p>Try this:</p> <pre><code>import pandas as pd pd.read_csv(&quot;/path/to/file&quot;, sep=&quot; &quot;, header=6, skiprows=[0, 1, 2, 3, 4, 5, 7], engine=&quot;python&quot;, skipfooter=1) </code></pre> <p><code>sep</code> makes it split the columns using a ...
python|pandas|time-series
0
365,342
63,246,098
Keras tokenizer: Keep Numbers as "words"
<p>I am using the keras tokenizer for my text preparation. Now I have x values like <code>26.07.2020</code> or <code>27.September 1993</code>.</p> <p>I want to use the tokenizer either for adding <code>September</code> as a word to the index, but also 26, or 2020.</p> <p>I used char_level=True before, but I think the m...
<p>You can replace the <code>.</code> with whitespaces, the <code>Tokenizer</code> splits your sentence by whitespaces and then tokenize each word.</p> <p>So a simple solution would be</p> <pre><code>x.replace('.', ' ') </code></pre>
tensorflow|keras|tokenize|text-processing
0
365,343
62,909,126
Facing issues with implementing polynomial regression: AttributeError: 'PolynomialFeatures' object has no attribute 'predict'
<p>Following is the code I am trying to implement. I am trying to generate a polynomial equation to predict next values in the <code>y</code> array</p> <pre><code>import numpy as np import pandas as pd # creating a dataset with curvilinear relationship startDay = 32 y = np.array([-60,-63,-65,-64,-64,-71,-70,-74,-74...
<p>Please refer to the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PolynomialFeatures.html" rel="nofollow noreferrer">documentation</a>. <code>PolynomialFeatures</code> does not have any method like <code>predict</code>. This module is not to predict anything, it is only for data pr...
python|pandas|scikit-learn
1
365,344
62,988,385
Seaborn Plot - Wrong Dates on X Axis
<p>I have a dataframe that associates each date with multiple values. The date range is from 02-02 to 04-30.</p> <p>I have a dataframe with two columns -- 'Date' and 'Score'. The 'Date' entries are timestamps.</p> <pre><code> dem_data = {Timestamp('2020-02-02 22:27:00+0000', tz='UTC'): [0.5423], Timestamp(...
<p>I recreated a portion of your DataFrame, and just plotted every other row by setting <code>freq = int(2)</code>. I formatted the date to not display time (but you can modify it to display whatever part of the date/time you want to keep), and also adjusted the angle of the x-axis labels to be 45 degrees. An angle of ...
python|pandas|matplotlib|seaborn
1
365,345
63,200,748
Pandas DataFrame Resample to Months when DatetimeIndex is last day of year
<p>I've got a DataFrame with DatetimeIndex labeled as the last day of the year (e.j. 2020-12-31, 2021-12-31, etc). I need to resample in order to expand the dataframe into months (e.j. 2020-01-31, 2020-02-29, etc). When I use the resample function it will always start from the begining date, not the first day of that y...
<p>Transpose the dataframe from columns to rows with <code>.T</code>, get the <code>date_range</code> from the <code>.min</code> to the <code>.max</code> with a <code>freq</code> of <code>'m'</code> and transpose the dataframe back from rows to columns with <code>.T</code> again.</p> <pre><code>from datetime import ti...
python|pandas|pandas-resample
0
365,346
63,293,620
CUDA out of memory runtime error, anyway to delete pytorch "reserved memory"
<p>Like many othersm I'm getting a Runtime error of Cuda out of memory, but for some reason pytorch has reserved a large amount of it.</p> <p>RuntimeError: CUDA out of memory. Tried to allocate 2.00 MiB (GPU 0; 6.00 GiB total capacity; 4.31 GiB already allocated; 844.80 KiB free; 4.71 GiB reserved in total by PyTorch)<...
<p>From the given description it seems that the problem is not allocated memory by Pytorch so far <strong>before the execution</strong> but cuda ran out of memory while allocating the data that means the 4.31GB got already allocated (not cached) but failed to allocate the 2MB last block. Possible solution already worke...
memory|pytorch
2
365,347
63,254,984
pandas contains exact string from a list
<p>I have 2 dataframes df1 and df2.</p> <p>I would like to get all rows in df1 that has exact string match in column B of df2 This is df1:</p> <pre><code>df1={&quot;columnA&quot;:['apple,cherry','pineple,lemon','banana, pear','cherry, pear, lemon']} df1=pd.DataFrame(df1) </code></pre> <p>This is df2:</p> <pre><code>df...
<p>Without actual reproducible code it's harder to help you, but I think this should work:</p> <pre><code>words = [rf'\b{string}\b' for string in df2.columnB] df1[df1['columnA'].str.contains('|'.join(words))] </code></pre>
python|pandas
4
365,348
63,063,704
Python List Comprehension adds another dimension in Numpy Array
<p>Trying to learn list comprehensions to streamline code. However, this one below is adding an extra dimension when I print out the shape. What am I doing wrong? I thought this was a simple textbook case for list comprehension...</p> <pre><code>i = [] for item in intensities_copy: clipped = item[:, q_min_idx:q_ma...
<p>Loose the extra brackets and you will get the same shape (that is where you get extra dimension):</p> <pre><code>i2 = [item[:, q_min_idx:q_max_idx+1] for item in intensities_copy] </code></pre> <p>Note, that <code>append</code> adds the <em>whole element</em> to the list, whereas adding the <em>content</em> of eleme...
python|arrays|list|numpy|list-comprehension
1
365,349
63,159,536
How to hand duplicate duplicate values in Pandas?
<p>I have the following data frame with several duplicates.</p> <pre><code>df = pd.DataFrame( { 'ID': [4562, 4562], 'city': ['Monroe', 'Montgomery'], 2005: [144, np.NaN], 2006: [173, np.NaN], 2007: [145, np.NaN], 2008: [145, np.NaN], 2009: [np.NaN, 211]...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>pandas.Dataframe.groupby</code></a> method in combination with <a href="https://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.core.groupby.GroupBy.last.html" ...
pandas
0
365,350
62,900,811
ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (2,2) and requested shape (3,2)
<p>I have a bunch of (greyscale) images of different sizes that I resize to ensure one dimension is the same and pad the other dimension (<a href="https://stackoverflow.com/a/54591202/13112739">a la this answer</a>). Yet, I get the error <code>ValueError: operands could not be broadcast together with remapped shapes [o...
<p>Your code should work unless you are loading RGB images. So make sure that the images are in Grayscale mode</p> <p>You can load an image in grayscale mode:</p> <pre><code>image = cv2.imread('./image.tif',0) </code></pre> <p>Or simply convert it:</p> <pre><code>image = cv2.imread('./image.tif') gray = cv2.cvtColor(im...
python|numpy|opencv
1
365,351
62,972,592
Having trouble using Pandas to chain multiple statements together
<p>I am trying to filter multiple columns out of an excel spreadsheet to simplify some tasks at my work. This was the solution I thought would work the best without having to write and rewrite a file multiple times. I am pretty sure it has something to do with the variables before the bigsplit variable. I also tried wi...
<p>Seems like you want</p> <pre><code>disco2 = df[&quot;Discontinued&quot;] == 'N' close2 = df[&quot;Store Closeout&quot;] == 'N' oi2 = df[&quot;Order Indicator+&quot;] != 'S' dropship2 = df[&quot;Primary Vendor&quot;] == 'VENDOR' bigsplit = df[disco2 &amp; close2 &amp; oi2 &amp; dropship2] </code></pre> <p>Here w...
python|pandas|split
1
365,352
63,038,637
Not able to find a particular value in a column in pandas but I can find it in R
<p>Df</p> <pre><code> A 123 234 374 493 </code></pre> <p>Python</p> <pre><code>Df[Df['A']==234] </code></pre> <p>I get no value.</p> <p>R</p> <pre><code>Df[Df$A %in% c('234')] </code></pre> <p>The value is getting displayed. What is the mistake that I do in pandas. The number of rows are same in both python and R.</p>
<blockquote> <pre><code>R : %in% Pandas : isin </code></pre> </blockquote> <pre><code>Df[Df['A'].isin(['234'])] #Df[Df$A%in% c('234'),] </code></pre>
python|pandas
1
365,353
62,914,889
Using openpyxl how can i set my colorscale row by row without setting upper and lower value
<p>As the question says I'd like to apply a colour scale conditional format row by row.</p> <p>Can I set this up without setting the high and low values as my data is always different when the report is ran. Thanks</p>
<p>I was using the start_type, mid_type and end_type as 'num' If you use percentile it works like a charm. Using the below controls, i can just set a range and the code does the rest</p> <pre><code> color_scale_rule = ColorScaleRule(start_type=&quot;percentile&quot;, start_value=0, ...
python|pandas|openpyxl
0
365,354
63,296,391
PyTorch: How to append tensors into a list using loops
<p>I have the following code which outputs 2 arrays in a list:</p> <pre><code>arr1 = np.array([[1.,2,3], [4,5,6], [7,8,9]]) arr_split = np.array_split(arr1, indices_or_sections = 2, axis = 0) arr_split </code></pre> <p>Output:</p> <pre><code>[array([[1., 2., 3.], ...
<p>Better you convert it to tensor at first place and then you can use <a href="https://pytorch.org/docs/stable/tensors.html#torch.Tensor.split" rel="nofollow noreferrer"><code>torch.Tensor.split</code></a></p> <pre class="lang-py prettyprint-override"><code>arr1 = np.array([[1.,2,3], [4,5,6], [7,8,9]]) t_arr1 = torch....
python|list|pytorch|tensor
0
365,355
63,139,077
Numpy: Adding elements to array print
<p>I want to add elements to array print output. What I have done is like that(from 'Fallen Apart' my last post):</p> <pre><code>c = np.arange(9).reshape(3,3) for i, row in enumerate(c): print('G' + str(i+1) + ': ' + str(row)) </code></pre> <p>Result:</p> <pre><code>G1: [0 1 2] G2: [3 4 5] G3: [6 7 8] </code></pre>...
<p>Similar to your code:</p> <pre><code>c = np.arange(9).reshape(3,3) col_id = np.arange(c.shape[1])+1 for i, row in enumerate(c): print('G'+str(i+1)+': '+'[%s]'%' '.join([str(a)+':'+str(b) for a,b in zip(col_id,row)])) </code></pre> <p>or another equal solution:</p> <pre><code>c = np.arange(9).reshape(3,3) col_id ...
python|arrays|numpy
1
365,356
62,949,138
Read csv file by changeable columns using pandas
<p>I'm developing a software that reads a csv file and create a list for each column. After in my program I will plot this data using <code>DataTime</code> on X coordinates and <code>S1;S2;S3...</code> as Y coordinates</p> <p>My csv file:</p> <pre><code>DateTime;S1;S2;S3 2020-07-16 15:11:34.358231;677.0552427707063;787...
<ul> <li>The best thing to do is learn how pandas and matplotlib integrated to make data manipulation and plotting easier.</li> <li><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/visualization.html" rel="nofollow noreferrer">Pandas: Visualization</a></li> </ul> <pre class="lang-py prettyprint-override...
python|pandas
2
365,357
63,067,375
how to reindex python dataframe based on column grouping
<p>i am a newbie in python. please assist. I have a huge dataframe consisting of thousands of rows. an example of the df is shown below.</p> <pre><code> STATE VOLUME INDEX 1 on 10 2 on 15 3 on 10 4 off 20 5 off 30 6 on ...
<p>You can try this with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.eq.html" rel="nofollow noreferrer"><code>pd.Series.eq</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.shift.html" rel="nofollow noreferrer"><code>pd.Series.shift</...
python|pandas|indexing|rows
3
365,358
63,044,880
How could you randomly exclude/delete elements from an array that satisfy some condition?
<p>For example, if I had a 1x100 array, and it contained 90 0's, I'd like to somehow exclude 80 of those 0's chosen at random. I've been struggling with this problem for a while and I've made very little progress unfortunately.</p>
<p>Since you have a <code>numpy</code> tag:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np def solution(arr, value, size): return np.delete(arr, np.random.choice(np.flatnonzero(arr==value), size, False)) arr = np.array([0]*90 + [1]*10) np.random.shuffle(arr) print(solution(arr, 0, 80)) # ...
python|arrays|numpy|random
2
365,359
63,131,782
Where are the `tfds.load` datasets are saved?
<p>I downloaded the <code>cats vs dogs</code> dataset using the <code>tfds.load('cats_vs_dogs')</code> and I want to find where it has been saved on my computer, after reading a bit I came across someone who claims the dataset can be found at <code>~/tensorflow_datasets/cats_vs_dogs/</code> but I can't find a folder th...
<p>As per default</p> <p><a href="https://i.stack.imgur.com/1FysK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1FysK.png" alt="ex1" /></a></p> <p>as I assume TFDS_DATA_DIR has not been set, datasets will be stored under ~/tensorflow_datasets</p> <p>However, as this depends on your system and setup...
python|tensorflow|tensorflow-datasets
2
365,360
63,176,971
Filling out numpy array in parallel?
<p>I have code which looks something like this</p> <pre><code>import numpy as np A = np.zeros((10000, 10)) for i in range(10000): # Some time-consuming calculations which result in a 10 element 1D array 'a' A[i, :] = a </code></pre> <p>How can I parallelize the <code>for</code> loop, so that the array <code>...
<p>This below code creates a thread for each line of the array, not sure how efficient it is though.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import threading def thread_function(index, array): # aforementioned time-consuming calculation, resulting in 'a' a = np.ones(10) # placehol...
python|numpy|parallel-processing
1
365,361
63,101,557
strange behaviour when using numpy array for ImageTK
<p>I have three different ways to visualize a numpy array in an tkinter canvas. However, version <code>setNumpyImage</code> does not work. I cannot figure out, why this doesn't work, since all three ways are basically the same - in my opinion.</p> <pre><code>from tkinter import * from PIL import Image, ImageTk import n...
<p>Here ist the answer provided by @jizhihaoSAMA. The issue is documented <a href="http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm#:%7E:text=The%20problem%20is%20that%20the,Tk%20to%20release%20the%20image." rel="nofollow noreferrer">here</a>. Here is a copy of the text:</p> <blockquote> <p>When you add ...
python|numpy|tkinter
0
365,362
63,136,423
How can I find the intersection of two lines more efficiently? (nested for loops in Python)
<p>I need to find the intersection point of two data sets, as illustrated here:</p> <p><a href="https://i.stack.imgur.com/QS2YT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QS2YT.png" alt="Data plot" /></a></p> <p>I have used the nested loops below to achieve this, but it takes impractically long ...
<p>Can you create a new function <code>y = (Storage Modulus - Loss Modulus) vs Oscillation Stress</code>? The point of intersection is where <code>y</code> changes sign from positive to negative. The secant method should find this point in a few iterations.<br /> <a href="https://en.wikipedia.org/wiki/Secant_method" ...
python|pandas|performance|for-loop|intersection
1
365,363
63,224,601
How to generate a 1d array with very large size
<p>For instance I want to generate a 1d array with size of 1 trillion</p> <pre><code>A = np.arange(1000000000000,dtype='float') </code></pre> <p>whenever I run this code I get</p> <pre><code>Memory error </code></pre> <p>is there any other way to do this?</p>
<p>Well you seem to have a problem that your computer can simply not handle. There is simply not enough RAM memory. If you instead change the datatype to int you can clearly see the difference in storing different data types in the memory:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; A = np.arange(100000...
python|python-3.x|numpy
0
365,364
62,978,351
UnboundLocalError: local variable 'temp_var' referenced before assignmen
<p>my function is that</p> <pre><code>def func_1(df): for count1, i in enumerate(df[&quot;col1&quot;]): if df.at[count1, &quot;col3&quot;] == 1 and df.at[count1, &quot;col4&quot;] &gt; 0: tot_fun= df.at[count1, &quot;col4&quot;] for count2, j in enumerate(df[&quot;col2&quot;]): if i == j...
<p>Reaches line <code>df.at[temp_var, &quot;col4&quot;] = tot_fun</code> before <code>temp_var= count2</code> maybe insert <code>df.at[temp_var, &quot;col4&quot;] = tot_fun</code> into the if statement</p>
python|pandas|for-loop
1
365,365
67,784,280
How to create new dataframe as a subtruction result from another dataframe
<p>My df:</p> <pre><code> items $ shop_id 10CLV pen red 5.12 10CLV pencil red 6.41 10PLB pen red 7.30 10PLB pencil red 9.53 </code></pre> <p>How to create a new dataframe, where will be one column as a subtruction of two items (only two of them in each shop_id) by each shop_id ? I...
<p>You can pivoting values by add <code>items</code> to <code>MultiIndex</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unstack.html" rel="nofollow noreferrer"><code>Series.unstack</code></a>, so in next step subtract columns:</p> <pre><code>df1 = df.set_index('items', appe...
python|pandas|dataframe
1
365,366
67,932,781
pandas transform 1st mutliindex to rowindex and 2nd multiindex to columnindex
<p>So I have the following code which transforms groups a given dataframe by to columns and calculates the size of each group. This creates a DataFrame with one column and a Multiindex of two values. Afterwards I transfrom the result to put the 2nd Index as columnindex and the 1st index as rowindex.</p> <pre><code>impo...
<p>try via <code>unstack()</code>:</p> <pre><code>df_grp=df.groupby(['product', 'Changing']).size().unstack() </code></pre> <p>Finally make use of <code>columns</code> attribute:</p> <pre><code>df_grp.columns=[f'{&quot;not &quot;*col}{df_grp.columns.name}' for col in df_grp][::-1] #as suggested by @Cyttorak #rename col...
python|pandas|pandas-groupby|multi-index
2
365,367
67,742,781
How to create new rows based on columns while keeping the index constant?
<p>I have a dataframe similar to this one:</p> <p><img src="https://i.stack.imgur.com/kji62.png" alt="enter image description here" /></p> <p>And I would like to create this dataframe:</p> <p><img src="https://i.stack.imgur.com/FTmf4.png" alt="enter image description here" /></p> <p>I tried to implement this using <cod...
<p>You can use <code>pd_wide_to_long()</code> - <a href="https://pandas.pydata.org/docs/reference/api/pandas.wide_to_long.html" rel="nofollow noreferrer">link</a>:</p> <pre><code>df = pd.wide_to_long(df, stubnames='month', i=['id', 'Name', 'City'], j='month_num', sep='_').rename(columns = {'month':'mont...
python|pandas
1
365,368
67,937,651
Is it possible to get shape of a TFdataset similar to a pandas.shape()?
<p>I execute this command I get:</p> <pre><code>print(df.shape) (172717, 1521) </code></pre> <p>but if I convert the dataframe to a <code>tf</code> dataframe:</p> <pre><code> df_numpy = df.to_numpy() df_tensor = tf.ragged.constant(df_numpy) </code></pre> <p>I can see rows but not columns:</p> <pre><code>len(list(df_...
<p>Ragged tensors (<code>tf.RaggedTensor</code>), are tensors with <strong>non-uniform</strong> shapes, thus using <code>.get_shape()</code>, you only get <code>[num_of_rows, None]</code>.</p> <pre><code>df = pd.DataFrame({'Roll': [1, 2, 3, 4, 5], 'Mark': [95, 96, 98, 100, 95], }) ...
python|tensorflow|keras
3
365,369
67,823,278
how to create columns based on same date
<p>I have the dataset having columns....</p> <pre><code> created_at date time timezone \ 0 2021-06-03 09:01:59 India Standard Time 2021-06-03 09:01:59 530 1 2021-06-03 09:01:41 India Standard Time 2021-06-03 09:01:41 530 2 2021-06-03 07:32:58 India Standar...
<p>Might not be the most efficient solution, but this works.</p> <p>First, you <code>groupby</code> the date and concatenate all the tweets for one date:</p> <pre><code>df2 = df.groupby(&quot;date&quot;).apply(lambda x: x[&quot;tweet&quot;].to_list()) </code></pre> <p>Next, you split the list into individual columns:</...
python|pandas|dataframe
1
365,370
67,939,311
How do I remove all trailing characters from a dataframe that are equal to a letter 'h'
<p>I have an output generated by another script that due to a bug is using the letter <code>h</code> as a padding character. For this reason, its become difficult to clean the generated output.</p> <p>The output generated is:</p> <pre><code>k,g,h,kl,l,k,l,m,l,k,l,l,j,l,j,k,hg,hg,fg,hk,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.rstrip.html#pandas-series-str-rstrip" rel="nofollow noreferrer"><code>str.rstrip</code></a>:</p> <pre><code>df['vals'] = df['vals'].str.rstrip(',h') </code></pre> <pre class="lang-none prettyprint-override"><code> ...
python|pandas
2
365,371
67,621,261
Python Pandas group by mean() for a certain count of rows
<p>I need to group by mean() for the first 2 values of each category, how I define that. df like</p> <pre><code>category value -&gt; a 2 -&gt; a 5 a 4 a 8 -&gt; b 6 -&gt; b 3 b 1 -&gt; c 2 -&gt; c 2 c 7 </code></pre> <p>by reading only the arrowed data where the output be like</p> <pre><cod...
<p>Try <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.apply.html" rel="nofollow noreferrer"><code>apply</code></a> on each group of values and use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.head.html#pandas-series-head" rel="nofollow noreferrer"><code>head(2)</code></a> to ...
python|pandas|dataframe
1
365,372
67,918,100
How to apply if/else logic in python for an excel file? (dates)
<p><em><strong>strong text</strong></em>I got an excel file with dates, starting from 2019 till 2021. And i wanted to apply certain rules like if sales was made between 04.05.2019 and 09.05.2019 then it's a promo number 1, etc. The output is here</p> <p><a href="https://i.stack.imgur.com/YdtJv.png" rel="nofollow noref...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.between.html" rel="nofollow noreferrer"><code>Series.between</code></a> for mask and set new values by <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a...
python|excel|pandas|numpy
1
365,373
67,816,912
How can I see the model as visualized?
<p>I am trying to do some sample code of <code>GAN</code>, here comes the generator.</p> <p>I want to see the visualized model but, this is not the model.</p> <p><code>Model.summary()</code> is not the function of <a href="/questions/tagged/tensorflow" class="post-tag" title="show questions tagged &#39;tensorflow&#39;"...
<p>One possible solution (or an idea) is to wrap your <a href="/questions/tagged/tensorflow" class="post-tag" title="show questions tagged &#39;tensorflow&#39;" rel="tag">tensorflow</a> operation into the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Lambda" rel="nofollow noreferrer">Lambda layer<...
python|tensorflow|keras
1
365,374
67,837,988
Python: Parallelize nested for loop
<p>I have nested for-loop in python to create a netCDF file. The for-loop takes a pandas dataframe with time, lat, lot, and parameters and replaces the information in the netCDF file by the parameters in the correct location and time. This is taking too long since the pandas dataframe has more than 80000 rows and the n...
<p>Consider the following as pseudocode as I cannot run any test without any samples etc. I have usually parallelized my code with mpi4py and in your case, you could do in the beginning:</p> <pre><code>from mpi4py import MPI comm = MPI.COMM_WORLD size = comm.Get_size(); # let your program know how many processors you a...
python|pandas|python-multiprocessing|netcdf|xargs
1
365,375
67,985,962
LSTM Auto Encoder, use first LSTM output as the target for the decoder
<p>Having a sequence of 10 days of sensors events, and a true / false label, specifying if the sensor triggered an alert within the 10 days duration:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>sensor_id</th> <th>timestamp</th> <th>feature_1</th> <th>feature_2</th> <th>10_days_alert_lab...
<p>You can do it using <code>model.add_loss</code>. In <code>add_loss</code> we specify the loss of our interest (in our case: <code>mse</code>) and set the layers used to compute it (in our case: the LSTM output and model predictions)</p> <p>Below a dummy example:</p> <pre><code>n_sample, timesteps = 100, 9 X = np.ran...
python|tensorflow|machine-learning|keras|lstm
2
365,376
67,813,239
How do I generate pie chart labels for both value and autopct from csv using pandas?
<p>I have a simple .csv that I'd like to render PNG files of pie charts from, which from other StackOverflow questions I've gotten mostly working.</p> <p>The one change I can't figure out is how to show both values and percentages on the pie slices. There's a similar <a href="https://stackoverflow.com/a/41089685/16109...
<p>Modify the <code>absolute_value</code> function:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np sums = df.groupby(df[&quot;category&quot;])[&quot;capacity-tb&quot;].sum() pie, ax = plt.subplots(figsize=[10, 6]) def absolute_value(val): return f'{np.round(val/100.*sums.values.sum(), 0)} {rou...
pandas|dataframe|matplotlib
1
365,377
67,834,528
Scipy and Numpy upgrade generates "TypeError: Cannot cast array data from dtype('O') to dtype('float64')"
<p>I'm converting a code from Python 2.7 to Python 3.8.</p> <p>In its Python 2.7 version, I had to use downgraded versions of scipy and numpy in order to avoid a TypeError (see below). With Python 3.8, these downgraded versions of scipy and numpy are not available anymore and I get this error, which I'm unable to fix.<...
<p>At some point in running <code>scipy.integrate.odeint</code>, Numpy is told to convert an array of Python objects into an array of floats, and it's answering you that it can't do that. Your description suggests the problem has to be with <code>y_start</code>, <code>t_start</code> or (maybe, I'm not sure) the return ...
python-3.x|numpy|scipy
1
365,378
67,831,005
How to fill a np.nan column in a group based on a value in another column?
<p>I have a subset of a dataframe that I need to backfill using grouping and conditions based on another column.</p> <pre><code>data = [ [&quot;1A&quot;, &quot;aa&quot;, &quot;2020-05-09&quot;], [&quot;1A&quot;, np.nan, &quot;2020-05-09&quot;], [&quot;1A&quot;, &quot;ab&quot;, &quot;2020-05-10&quot;], [...
<p>Let us try <code>transform</code></p> <pre><code>df.value.fillna(df.groupby(['dates','product'])['value'].transform('first'),inplace=True) df product value dates 0 1A aa 2020-05-09 1 1A aa 2020-05-09 2 1A ab 2020-05-10 3 2A bb 2020-05-09 4 2A bb 2020-05-09 5 ...
python|pandas|group-by
2
365,379
67,841,257
Convert object column to array type - pandas.DataFrame
<p>Im reading a SQL query with pd.read_sql().</p> <p>One of the columns of the query has array type, but Pandas doesn't recognize this as an array, but as a string.</p> <p>How do I change de type of the column to be able to iterate over its values?</p> <p>This is the df head:</p> <pre><code> main_ID ...
<p>TRY:</p> <p>via <code>strip()</code> and <code>split()</code>:</p> <pre><code>df['related_ids']=df['related_ids'].str.strip('[]').str.split(',') </code></pre> <p><strong>OR</strong></p> <p>If you need <code>np.array()</code> then use:</p> <pre><code>df['related_ids']=df['related_ids'].str.strip('[]').str.split(',')....
python|pandas|numpy
1
365,380
67,893,732
Creating a Pandas df from two lists in python
<p>I have two python lists in following form:</p> <pre><code>A = [(1,''), (1, 'ABC'),(1,''), (1, 'DEF'),(1,''), (1, 'GHI'),(1,''), (1, 'LMO'),(1,'')] B = ['ABC', 'ghi', 'PQR'] </code></pre> <p>(Note: A is a list of list. B is normal list.)</p> <p>I want to create a pandas DF that will only contain element that are comm...
<pre><code>import pandas as pd A = [(1,''), (1, 'ABC'),(1,''), (1, 'DEF'),(1,''), (1, 'GHI'),(1,''), (1, 'LMO'),(1,'')] B = ['ABC', 'GHI', 'PQR'] A = [i[1] for i in A if i[1] in B] df = pd.DataFrame({'A':A,'B':A}) print(df) </code></pre> <p>to take care about case sensitivity and spaces try this:</p> <pre><code>impor...
python|python-3.x|pandas|list|dataframe
1
365,381
67,958,313
How to predict on a test sequence using a distilbert model?
<p>Im trying to predict on a test sequence using Ktrain with a distilbert model, my code looks like this:</p> <pre><code>trn, val, preproc = text.texts_from_array(x_train=x_train, y_train=y_train, x_test=x_test, y_test=y_test, class_nam...
<p>You can use a <code>Predictor</code> instance as shown in the <a href="https://nbviewer.jupyter.org/github/amaiya/ktrain/blob/master/tutorials/tutorial-04-text-classification.ipynb" rel="nofollow noreferrer">tutorial</a>.</p> <p>The <code>Predictor</code> simply uses the <code>preproc</code> object to transform the ...
tensorflow|nlp|multilabel-classification|distilbert|ktrain
0
365,382
67,968,674
How to save a tensor
<p>I have a dataset of 1000 items. I normalize the data before I train the model against it.</p> <p>I would now like to use the model to make predictions. However, from what I understand, I need to normalize the inputs that I will feed to the model for which I need the predictions for. In order to carry this out, I wou...
<p>I determined that we could first get the array representation of the tensor through:</p> <pre class="lang-js prettyprint-override"><code>// tensor here is the tensor variable that contains the tensor const tensorAsArray = tensor.arraySync() </code></pre> <p>and then, we save it to a file like any other string</p> <p...
tensorflow.js|danfojs
0
365,383
67,812,046
Barplot per month for all countries in python
<p>I have data showing temperature and date from different countries.</p> <pre><code>Date Temperature Units Year Month Statistics Country CODE Jan 1991 -26.2 Celsius 1991 Jan Average Canada CAN Feb 1991 -21.0 Celsius 1991 Feb ...
<pre><code>tempcountries.groupby(['Month']).plot.bar(x='Country', y='Temperature',legend=True) </code></pre> <p>If you want these in one figure, the seaborn package provides a nice interface for creating grids of graphs from categorical variables in a pandas DataFrame.</p> <pre><code>import seaborn as sns g = sns.Facet...
python|pandas|dataframe|matplotlib
0
365,384
67,612,736
In tensorflow, Do I have to set something special to ignore zero padding value when training? Or is it automatic?
<p>I want to train sequence data to Rnn base model with some zero paddings using tensorflow.</p> <p>And I want model to ignore 0 values when training.</p> <p>Do I have to set parameters to do that? or Does model automatically ignore zeros?</p> <p>Thanks,,</p>
<p>It is not automatic, You should introduce <code>Masking</code> to achieve this. It means how layers are able to know when to ignore certain timesteps in sequence inputs.</p> <p>You can introduce it in three ways</p> <ul> <li>You can add a <code>tf.keras.layers.Masking</code> layer</li> <li>You can configure a <code>...
tensorflow|recurrent-neural-network|zero-padding
1
365,385
67,879,817
Inserting from dataframe to table using psycopg2: array value must start with "{" or dimension information
<p>I want to insert data from a dataframe into a table using psycopg2, but when I try to insert, it shows a message that the array must start with &quot;{&quot; or dimension information. Here's my code:</p> <pre><code>for f in df.iterrows(): cur.execute(&quot;INSERT INTO NumCasos VALUES (%s, %s)&quot;,(df.iloc[m, 0...
<p>The first column of your table must of an array type. But you trying to insert a string, not an array of strings.</p> <p>How to fix it depends on what you are trying to do. You could change the type of that column in the table so it just holds simple strings. You could change your program so that df.iloc[m, 0] he...
python|pandas|postgresql|dataframe|psycopg2
0
365,386
67,914,281
ValueError with Training Data during DTreeViz Command
<p>I have created a DecisionTreeClassifier clf to model data, and am attempting to visualize the tree using the dtreeviz package.</p> <pre><code>clf = DecisionTreeClassifier(max_depth=3) clf.fit(X_train, y_train) </code></pre> <p>To make the data digestible by the dtreeviz function, I have transformed the X_train and y...
<p>I ran into the same problem. Make sure your classifier is also trained on the encoded labels, i.e. use</p> <pre class="lang-py prettyprint-override"><code>clf.fit(X_train, y_train_encoded) </code></pre> <p>instead of</p> <pre class="lang-py prettyprint-override"><code>clf.fit(X_train, y_train) </code></pre>
python|numpy|decision-tree|dtreeviz
0
365,387
67,623,298
python pandas replace all the float values
<p>The purpose of this code is to:</p> <ol> <li>create a dummy data set.</li> <li>Then turn it into a data frame</li> <li>Calculate the peaks and make it a column in the data frame</li> <li>Calculate the troughs and make it a column in the data frame</li> <li>Filling the “nan” values with “hold”</li> <li>Replace all th...
<p>Use <code>np.where</code> to classify it</p> <pre><code>df['minimum'] = (np.where(df['minimum'].isnull(), 'hold', 'buy')) </code></pre>
python|pandas|dataframe
3
365,388
67,610,475
How to list the most frequent combination of column that contain data
<p>Hellooo,</p> <p>I am working with geological datasets which are famously messy and disparate. What I am looking to do is: output a list of column combination with the highest number of NaN-free rows for a certain number of columns.</p> <p>e.g.</p> <pre><code>A B C D E F 2 6 3 7 7 3 4 5 6 7 5 4 3 4 x x x x 4 5 x x...
<p>It think this is what you want. Instead of returning a list of columns, this returns a list or lists of columns, to account for instances where there is a tie for the 'best' number of non-NA rows.</p> <pre><code>import pandas as pd from itertools import combinations from math import nan def best_combinations(df, n...
python|pandas|itertools
1
365,389
67,942,222
Changing Pandas Data Frame Layout
<p>I have a pandas dataframe that has four fields 'EventDate', 'DataField', 'DataValue'.</p> <p>'DataField' has three values i.e Oxygen, HeartRate, HeartRateVariability.</p> <p><a href="https://i.stack.imgur.com/Kksv3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Kksv3.png" alt="enter image descrip...
<p>Any time you want to take one attribute in your dataset and group some other attributes by it, you should think about using pandas group_by or pivot_table functionality.</p> <p>I'm personally a fan of pivot tables, so here is how do it in a pivot table:</p> <pre><code># Pivot the data pivot_table = df.pivot_table( ...
python|pandas|dataframe|data-science
1
365,390
67,732,800
Making a pivot table across multiple columns of non-numeric data
<p>The following code generates a dummy dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame( { 'user_id': [1,2,3,1,1], 'account_type': ['google','facebook','apple','facebook','google'], 'activated': ['y','pending','n','y','y'] } ) df.head() </code></pre> <p><img src="h...
<p>Try Via <code>groupby()</code>, <code>where()</code> and <code>transform()</code> method:</p> <pre><code>df['count']=(df.groupby(['user_id','account_type'])['activated'] .transform(lambda x:x.where(df['activated'].ne('n')).count())) </code></pre> <p>Finally use <code>pivot_table()</code> and <code>rename_...
python|pandas|pivot-table
2
365,391
67,788,638
Cumulative sum of a multidimensional Numpy Array with reset at 0
<p>I have a multidimensional NumPy array (16x212), and I want to calculate the cumulative sum for each of the 212 columns - however, the <strong><strong>calculation should restart at 0</strong> if there was a 0 in between.</strong></p> <p>e.g. <code>array([0, 1, -1, 1, 0, -1, 1, 0, 0, 1, 0, -1, 0, 0, 1, -1],...
<p><code>fill_zeros_with_last2d</code> is based on <a href="https://stackoverflow.com/questions/30488961/fill-zero-values-of-1d-numpy-array-with-last-non-zero-values">this answer</a>.</p> <p>The method here is to take the cumulated sum along the axes, then subtract the sum accumulated to the last zero from any later co...
python|arrays|python-3.x|numpy|multidimensional-array
0
365,392
67,741,628
apply a function over all combination of tensor rows in pytorch
<p>I want to make a function <code>f1(arg_tensor)</code> which gets a pytorch tensor as an argument.<br></p> <p>In this function I use another function: <code>f2(tensor_row_1, tensor_row_2)</code> which gets two pytorch's tensor rows as an arguments and outputs a scalar.<br></p> <p><code>f2(..)</code> should be applied...
<p>Yes, one can do it with a simple broadcasting trick:</p> <pre><code>def f1(tensor): tensor = tensor.permute(1, 0) return torch.nn.functional.kl_div( tensor.unsqueeze(dim=2), tensor.unsqueeze(dim=1), reduction=&quot;none&quot; ).mean(dim=0) def manual_f1(tensor): result = [] for row1 in ...
python|pytorch
1
365,393
67,748,675
Nested for-loop optimization while iterating over Dataframes
<p>I am fairly new to python and coding. I am looking for a way to optimize a nested for loop. The nested for loop I have written works perfectly fine, but it takes a lot of time to run. I have explained the basic idea behind my original code and what I have tried to do, below:</p> <pre><code>data = [['a', '35-44', 'ma...
<p>We can form groups over <code>age_group</code> and <code>gender</code> to obtain subsets where first two conditions hold automatically. For the third condition, we can <code>explode</code> the <code>matching_ids</code> and then check if <code>any</code> of the ids <code>isin</code> the <code>ID</code> and keep those...
python|pandas|dataframe|function|nested-loops
3
365,394
67,808,732
Converting CSV dataset to yolo format
<p>I was trying to train a dataset in yolov4 but I had some errors coming up while training about my annotations being in the wrong format.</p> <p>The dataset had its annotations in a CSV with the format</p> <pre><code>(x_min, x_max, y_min, y_max) </code></pre> <p>I checked the properties of the image and the size of e...
<p>I think you messed up calculating x and y:</p> <p>YOLO usses x_center position and y_center position (normalised, &lt;1), which is the centerof your bounding box. Plus the distance of the box along the x axes (w) and the y axes (h).</p> <p>I think that with x being the mean at our code <code>(xcen = ((df.x_min + df....
python|pandas|csv|annotations|yolo
1
365,395
67,652,946
Extracting string between multiple occurrence of same delimiter in python pandas
<p>Column &quot;Test&quot; has strings with multiple occurrence of same delimiter. Am trying to fetch the string which is within those delimiters. Can you please help.</p> <p><strong>Example:</strong></p> <pre class="lang-py prettyprint-override"><code>Test |||||CHNBAD||POC-RM0EP7-01-A </code></pre> <p>My code:</p> <pr...
<p>With your shown samples, please try following. We could use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>str.extract</code></a> function pf Pandas here. Applying <code>str.extract</code> function on <code>Test</code> column and creating new col...
python|pandas|substring
4
365,396
67,827,293
Three argument pow for arrays
<p><a href="https://docs.python.org/3/library/functions.html#pow" rel="noreferrer"><code>pow</code></a> accepts a third argument for modulo <code>pow(x, y, z)</code> that is more efficient computation than <code>x ** y % z</code>. How can you do that with arrays? What I've tried:</p> <pre><code>&gt;&gt;&gt; import num...
<p>Find the greatest n such that 2^n is not greater than your exponent. Then calculate A^{2^n} by repeatedly squaring and taking modulus for n steps. Then multiply this matrix with the matrix you obtain by recursively calling this same algorithm for <code>(your exponent - 2^n)</code>.</p> <p>I know this makes many call...
python|numpy|math|pow|modular-arithmetic
0
365,397
67,878,263
Extracting data from nested Python dictionaries
<p>I know there are some similar posts here, however I've tried each solution and none of them work for my scenario.</p> <p>I have a complicated dictionary, full of lists and other dictionaries. Which looks like this:</p> <pre><code> data = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'results': [{'id': 'i...
<p>If you switch away from generic variable names like <code>x</code>, you may find it easier to keep track of where in your structure you are looking:</p> <pre><code>for result in data['results']: id_ = result['id'] label2 = result['label2'] fields = result['fields'] # Intermediate variable (note: no loop...
python|json|pandas|loops|dictionary
2
365,398
67,655,243
Convert a pandas object into float
<p>I was trying to make a code that could read a excel file, found which line corresponds to the data I want and then save the last value of that line.</p> <p>The code I'm using is:</p> <pre><code>import pandas as ap import numpy as np #Read the Excel file excel = ap.read_excel(r'EXAMPLE') #Columns and rows selection...
<pre><code>import pandas as pd tec = np_array[found_tec_line,5] tec=pd.eval(tec) </code></pre> <p><strong>OR</strong></p> <p>Try via <code>Dataframe()</code> method and <code>apply()</code> method:</p> <pre><code>tec = np_array[found_tec_line,5] tec=pd.Dataframe(tec).apply(pd.eval).values </code></pre>
python|python-3.x|pandas|dataframe|numpy-ndarray
1
365,399
67,826,239
NumPy slicing squares in 2D array
<p>I want to create a heightfield map that consists of squares of random height. Given an array of NxN, I want that every square of size MxM, where M&lt;N, will be at the same random height, with the height sampled from a uniform distribution. For example, if we have N = 6 and M = 2, we would have:</p> <blockquote> <p>...
<p>This solution using the repeat() method should work for N/M integer.</p> <pre><code>import numpy as np N = 6 M = 2 values = np.random.random( [N//M, N//M] ) y = values.repeat( M, axis=0 ).repeat( M, axis=1 ) print(y) </code></pre>
python|arrays|numpy
1