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 |
|---|---|---|---|---|---|---|
376,500 | 67,369,572 | Product scoring in pandas dataframe | <p>I do have product id dataframe. I would like to find the best product by scoring each product. For each variable the more the value the better the product score except returns which means more returns less score.Also I need to assign different weight to score for the variables Shipped revenue and returns that maybe ... | <pre><code> df_product=pd.DataFrame({'ProductId':['1','2','3','4','5','6','7','8','9','10'],'ShippedUnits':
[6,8,0,4,27,3,4,14,158,96],'ShippedRevenue':[268,1705,1300,950,1700,33380,500,2200,21000,24565]
,'OrderedUnits':[23,78,95,52,60,76,68,92,34,76],'Returns':[0,0,6,0,2,5,6,5,2,13],'View':
[0,655,11,378,920,1210... | python|pandas|product|segment | 1 |
376,501 | 67,354,697 | Saving prediction_generator results in tensorflow and python | <p>Let's assume, we fitted a model in TensorFlow flow</p>
<pre><code>model.fit(
train_generator,
epochs=epochs,
verbose=1,
steps_per_epoch=steps_per_epoch,
validation_data=valid_generator,
validation_steps=val_steps_per_epoch).history
</code></pre>
<p>In the next step, we generate predictions.... | <p>Based on my understanding from the comment box, here is some possible solution for your query, let me know if it works for you or not.</p>
<blockquote>
<p>I'm wondering if it is possible to save predictions and load them from
disk for debugging subsequent code without retraining the model and
predicting the data eac... | python|tensorflow|deep-learning|tensorflow2.0|prediction | 1 |
376,502 | 67,230,437 | Extracting ID and Relevant data from a csv dataset in python | <p>Making a program for my Final Year Project.
Program takes the longitude and latitude coords from a .csv dataset and plots them on the map.
Issue I am having is there is multiple ID's and this totals 445,000+ points.</p>
<p>How would I refine it so the program can differentiate between the IDs?</p>
<pre><code> def cr... | <p>To check for a specific ID you could create a filter. For this dataframe</p>
<pre><code> long lat ID
0 10 5 test1
1 15 20 test2
</code></pre>
<p>you could do the following:</p>
<pre><code>id_filt = df_data['ID'] == 'test1'
</code></pre>
<p>This can be used to filter out every entry... | python|pandas|numpy|csv | 0 |
376,503 | 34,735,189 | error reading date time from csv using pandas | <p>I am using Pandas to read and process csv file. My csv file have date/time column that looks like:</p>
<pre><code>11:59:50:322 02 10 2015 -0400 EDT
11:11:55:051 16 10 2015 -0400 EDT
00:38:37:106 02 11 2015 -0500 EST
04:15:51:600 14 11 2015 -0500 EST
04:15:51:600 14 11 2015 -0500 EST
13:43:28:540 28 11 2015 -0500 ES... | <p>The issue you're having is likely because versions of Python before 3.2 (I think?) had a lot of trouble with time zones, so your format string might be screwing up on the %z and %Z parts. For example, in Python 2.7:</p>
<pre><code>In [187]: import datetime
In [188]: datetime.datetime.strptime('11:59:50:322 02 10 2... | python|csv|datetime|pandas | 1 |
376,504 | 34,544,210 | Numba 3x slower than numpy | <p>We have a vectorial numpy <strong>get_pos_neg_bitwise</strong> function that use a mask=[132 20 192]
and a df.shape of (500e3, 4) that we want to accelerate with numba.</p>
<pre><code>from numba import jit
import numpy as np
from time import time
def get_pos_neg_bitwise(df, mask):
"""
In [1]: print mask
... | <p>Try moving the call to <code>np.bitwise_and</code> outside of the loop since numba can't do anything to speed it up:</p>
<pre><code>@jit(nopython=True)
def numba_get_pos_neg_bitwise(df, mask):
posneg = np.zeros((df.shape[0], 2))
vandmask = np.bitwise_and(df[:, 1:], mask)
for idx in range(df.shape[0]):
... | python|numpy|numba | 11 |
376,505 | 34,762,239 | How to reverse sub arrays in numpy? | <p>In my application, I have an array like this:</p>
<pre><code>[10,20,30,
40,50,60,
70,80,90,
0.1,0.2,0.3,
0.4,0.5,0.6,
0.7,0.8,0.9,
1,2,3,
4,5,6,
7,8,9]
</code></pre>
<p>I want to reverse every 9 numbers so that my array looks like this:</p>
<pre><code>[90,80,70,
60,50,40,
30,20,10,
0.9,0.8,0.7,
0.6... | <p>Perhaps something like:</p>
<pre><code>n = a.shape[0]
a.reshape((n//9,9))[:,::-1].reshape((n,))
array([ 90. , 80. , 70. , 60. , 50. , 40. , 30. , 20. , 10. ,
0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1,
9. , 8. , 7. , 6. , 5. , 4. , 3. , 2. , 1. ])
</code></p... | python|arrays|numpy | 4 |
376,506 | 34,454,683 | Find how many weeks passed in Python Pandas | <p>I have a Pandas dataframe with a datetime column. My problem is the following:</p>
<p>I have a starting date of 04/08/2014. Since then, I count weeks in chunks of 16 weeks. So, from 04/08/2014 until 11/08/2014, it will be week 1. After 16 weeks, it will start again from week 1. I want to create a new column where i... | <p>If you need the week in a period of 16, you need the modulo, not devision. So change "/" to "%". And get int() before that.</p>
<pre><code>df['WeekChunk'] = int(((df['DateTimeColumn'] - startingweek) / pd.offsets.Day(1))/7) % 16
</code></pre>
<p>P.S. But the first week would be 0, not 1.</p> | python|datetime|pandas | 1 |
376,507 | 34,819,979 | Why does Pandas give me only one SettingWithCopyWarning? | <p>I have the following code:</p>
<pre><code>import pandas as pd
import numpy as np
mydf = pd.DataFrame({'UID':[1,2,3],
'Price':[10,20,30],
'Shipped':[2,4,6]})
grouped = mydf.groupby('UID').aggregate(np.sum)
# Call 1
mydf['Price'].loc[:] = np.round(grouped['Price'], 2)
# Call ... | <p>No SettingWithCopyWarning error</p>
<pre><code>mydf['Shipped'].values[:] = grouped['Shipped']
</code></pre> | python|pandas|warnings | 1 |
376,508 | 34,768,835 | Count of incremental duplicates over dates in Pandas | <p>I have a dataframe in the format below:</p>
<pre><code> day value
1/1/15 aa
2/1/15 bb
3/1/15 bb
3/1/15 cc
4/1/15 ee
4/1/15 ff
4/1/15 aa
</code></pre>
<p>I would like to first: group by 'day' and then count the unique values in 'value' adding up the count incremen... | <p>The following works:</p>
<pre><code>values = [l+l for l in ascii_lowercase[:8]
dates = pd.date_range(date(2016, 1, 1), date(2016, 3, 30))
df = pd.DataFrame(data=np.random.choice(values, 500), index=np.random.choice(dates, 500), columns=['value'])
df.sort_index().head(25)
value
2016-01-01 bb
2016-01-0... | python|datetime|pandas|duplicates|dataframe | 0 |
376,509 | 34,803,955 | Remove minima from inner dimension in NumPy 2D array | <p>Hello I'm new to python and vectorization.</p>
<p>Say you have a 5x3 numpy array like this:</p>
<pre><code>array([[ -1.262, -4.034, 2.422],
[ 13.849, 14.377, 4.951],
[ 3.203, 10.209, -2.865],
[ 3.618, -3.51 , -7.059],
[ -0.098, -5.012, 6.389]])
</code></pre>
<p>and you w... | <p>I would think there's a relatively straightforward function for this, but it may not be around in numpy; pandas could probably do this more easily.</p>
<p>With numpy, this is one way to do this:</p>
<pre><code>In [56]: a = np.array([[ -1.262, -4.034, 2.422],
[ 13.849, 14.377, 4.951],
[ 3.203, ... | arrays|python-3.x|numpy|vectorization | 0 |
376,510 | 34,808,668 | Find only rows that contains "NaN" in a specific column? | <p>How can i find only rows that contains "NaN" in a specific column ?</p>
<p>I tried this specific code to merge (left join) two dataFrame and find <strong>ONLY</strong> rows that contains "NaN" in "matricule"'s column. </p>
<pre><code>ln []: import pandas as pd
import datetime as dt
import numpy as np
from datetime... | <p>You can obtain a binary vector indicating whether a specific row has a <code>nan</code> in the column of interest as follows</p>
<pre><code>fltr = vehicules['matricule'].isnull()
</code></pre>
<p>You can then extract the subset of interest with</p>
<pre><code>subset = vehicules[fltr]
</code></pre> | python|numpy|pandas|jupyter|jupyter-notebook | 0 |
376,511 | 34,552,304 | Python given numpy array of weights, find indices which split array so that sum of each split is less than value | <p>I have an 1D array of weights, w and an array of capacities c of the same shape as w. I need to find the smallest array of indices such that when w is split by these indices, the cumsums of split arrays less than the corresponding capacities in c.
Given an array of weights and capacities as follows:</p>
<pre><code... | <pre><code>w = [1,2,3,1,6,6]; c = [1,3,5, 1, 6, 12]
</code></pre>
<p>The only solution to this is</p>
<pre><code>i=[2,3,4,5]
</code></pre>
<p>The greedy solution (to my understanding is to take until you cannot take) </p>
<p>It starts off with a 2 to get the [1,2] < =[1, 1+2] in c.
However, if the next split i... | python|arrays|numpy|split|indices | 1 |
376,512 | 60,170,747 | pandas get index values n positions ahead of selection | <p>I have a dataframe with a datetime index. I also have a list of specific dates which I am interested in looking at in my dataframe. I would like to get the rows 'n' positions ahead of my list of specific dates. Say for the example n=5. Here is my code:</p>
<pre><code>import pandas as pd
# generate an example ... | <p>You could use <code>flatnonzero</code> to get the indices, add <code>5</code> to them and index:</p>
<pre><code>import numpy as np
output.iloc[np.flatnonzero(output.index[:-5].isin(date_list)) + 5]
Value
Date
2002-05-16 1
2004-07-22 1
2005-03-28 1
</code></pre>
<hr>
<p>Or... | python|pandas | 4 |
376,513 | 60,014,502 | How can I convert some columns of a pandas dataframe to categorical? | <p>This is my code:</p>
<pre><code>l1 = list(train)
for i in (0,len(l1)):
if train[l1[i]].dtypes == object:
train[l1[i]] = pd.Categorical(train[l1[i]])
train.info(verbose=True)
</code></pre>
<p>But this just makes the first variable change and nothing else. The rest of the 62 object variables aren't conv... | <p>Get all object columns by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.select_dtypes.html" rel="nofollow noreferrer"><code>DataFrame.select_dtypes</code></a>, convert to dict and pass to <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.astype.... | python|pandas | 1 |
376,514 | 60,012,688 | how do I classify or regroup dataset based on time variation in python | <p>I need to assign number to values between different time hourly. How can I then add a new column to this where I can specify each cell to be grouped hourly. for instance, all the transactions within 00:00:00 to 00:59:59 to be filled with 1, transactions within 01:00:00 to 01:59:59 to be filled with 2, and so on till... | <p>You can use <a href="https://docs.microsoft.com/fr-fr/dotnet/standard/base-types/regular-expression-language-quick-reference" rel="nofollow noreferrer">regular expressions</a> and <a href="https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.Series.str.extract.html" rel="nofollow noreferrer">str.ext... | python|python-3.x|pandas|numpy|datetime | 0 |
376,515 | 60,273,966 | Replacing elements in numpy array | <pre><code>import numpy as np
a = np.array([0.75, 0.5, 0.21])
one_list = [1] * 3
L_vec = np.diag(one_list)
L_vec[1,0] = a[0]
print(L_vec)
</code></pre>
<p>Expected Result:</p>
<pre><code>[[1,0,0],[0.75,1,0],[0,0,1]]
</code></pre>
<p>Actual Result:</p>
<pre><code>[[1 0 0]
[0 1 0]
[0 0 1]]
</code></pre>
<p>this i... | <p>By default dtype for <code>np.diag</code> is <code>int</code></p>
<p>convert it into <code>float</code> so your float values from array <code>a</code> can replace older value</p>
<p><code>L_vec = L_vec.astype(float)</code></p>
<p>Use below code</p>
<pre><code>a = np.array([0.75, 0.5, 0.21])
one_list = [1]*3
L_ve... | python|python-3.x|numpy | 1 |
376,516 | 60,099,785 | TensorFlow Lite 2.0 advanced GPU using on Android with C++ | <p>I am new in TensorFlow. I built TensorFlow Lite libraries from sources. I try to use TensorFlow for face recognition. This one a part of my project. And I have to use GPU memory for input/output e.g. input data: opengl texture, output data: opengl texture. Unfortunately, this information is outdated: <a href="https:... | <p>You may look function BuildFromFlatBuffer (<a href="https://github.com/tensorflow/tensorflow/blob/6458d346470158605ecb5c5ba6ad390ae0dc6014/tensorflow/lite/delegates/gpu/common/testing/tflite_model_reader.cc" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/6458d346470158605ecb5c5ba6ad390ae0dc6... | android|c++|tensorflow2.0 | 0 |
376,517 | 59,945,409 | Calculate Date Columns in Datframe | <p><a href="https://i.stack.imgur.com/gGAsL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gGAsL.png" alt="enter image description here"></a></p>
<p>I try to calculate these columns. I need two new columns, </p>
<ul>
<li>one named "Starttime" = Date + Time </li>
<li>one named "Endtime" = Date + T... | <p>First convert <code>date</code>s and <code>time</code>s to strings by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.astype.html" rel="nofollow noreferrer"><code>Series.astype</code></a> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_dateti... | python|pandas|dataframe|datetime|timestamp | 1 |
376,518 | 59,934,963 | keras - Error when checking target with embedding layer | <p>I'm trying to run keras model as follows: </p>
<pre><code>model = Sequential()
model.add(Dense(10, activation='relu',input_shape=(286,)))
model.add(Dense(1, activation='softmax',input_shape=(324827, 286)))
</code></pre>
<p>This code works, but if I'm trying to add an embedding layer:</p>
<pre><code>model = Sequen... | <p>You don't need to provide the input_shape in the second Dense layer, and neither the first one, only on the first layer, the following layers shape will be coomputed :</p>
<pre class="lang-py prettyprint-override"><code>from tensorflow.keras.layers import Embedding, Dense
from tensorflow.keras.models import Sequent... | python|tensorflow|keras|embedding | 0 |
376,519 | 59,986,396 | Groupby and apply different function to each column with first and last | <p>I am trying to group the columns then apply different functions to each column. I referred <a href="https://stackoverflow.com/questions/58326349/apply-different-functions-to-different-columns-with-a-singe-pandas-groupby-comma">to the answer here</a> and my code is as shown below</p>
<pre><code>def f(x):
d = {}
... | <p>Better here is use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><code>GroupBy.agg</code></a>, there is possible pass columns names with aggregate methods <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cor... | python|pandas | 4 |
376,520 | 60,308,058 | How can I get rid of this error which I am getting with a code to find nearest neighbors? | <p>I have written the following function which takes data, number of peers to find, and index to find the top N nearest neighbors :</p>
<pre><code>def fit_nearest_neighbors(data, number_of_peers, index):
peer_data = FindPeers.filt_data(data)
peer_data_array = np.array(peer_data)
knn = NearestNeighbors(algo... | <p>The error message is clear. You need to reshape your data from 1D to 2D using the numpy function <code>np.reshape()</code>.</p>
<p>You can accomplish this with </p>
<pre><code>peer_data_array = np.array(peer_data).reshape(-1, 1)
</code></pre> | python|numpy|machine-learning|data-science|knn | 0 |
376,521 | 60,207,251 | Trace Operation in Python not Forming Correct Array Shape | <p>I'm looking to find the trace of matrices (using Numpy) in a function I have defined in Python. The input parameters <code>tensor</code> and <code>tensor_transpose</code> are both matrices of size (N,2,2) and are extracted from a VTK file (N is a rather large number and varies depending on the file). So both <code>A... | <p>Maybe you need to specify the axes:</p>
<pre class="lang-py prettyprint-override"><code>np.trace(A, axis1=1, axis2=2)
</code></pre> | python|arrays|numpy|matrix|vtk | 0 |
376,522 | 60,299,516 | Python count column values by other column | <p>I have the table such that: </p>
<pre><code>no Order materials status
1 1000 100 available
2 1000 200 not available
3 1001 500 Feb-20
4 1002 400 available
5 1002 300 not available
6 1002 600 available
7 1002 900 availabl... | <p>I would do a combination of <code>pivot table</code> and <code>merge</code>:</p>
<pre><code>ds_final = ds.merge(ds.pivot_table(values='Total Materials',index=['Order'],columns='status',aggfunc='count',fill_value=0).reset_index(),how='left',on='Order')
print(ds_final)
</code></pre>
<p>Output:</p>
<pre><code> no ... | python|pandas | 2 |
376,523 | 60,247,871 | Duplicate tensor name worked while it is not supposed to | <pre><code>def convolutional_block(X, f, filters, stage, block, s = 2):
conv_name_base = 'res' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + block + '_branch'
F1, F2, F3 = filters
X_shortcut = X
X = Conv2D(F1, (1, 1), strides = (s,s), name = conv_name_base + '2a', pa... | <p>Tensorflow/Keras has its own internal variable name resolution. So when you name two variables with the same name (i.e. <code>x_b</code> and <code>x_b</code>), the latter will be renamed to <code>x_b_1</code>. </p>
<p>For example, in your code, here are the variables with name <code>2b</code> in it. This is after c... | python|tensorflow|keras | 0 |
376,524 | 60,089,495 | How does the frozen model for speech recognition has been created? | <p>After following the steps train.py and freeze.py from "<a href="https://github.com/tensorflow/docs/blob/master/site/en/r1/tutorials/sequences/audio_recognition.md" rel="nofollow noreferrer">https://github.com/tensorflow/docs/blob/master/site/en/r1/tutorials/sequences/audio_recognition.md</a>", The inputs of my froze... | <p>You are following guide intended for the TensorFlow 1.x while using TensorFlow 2.1. Try using TensorFlow 1.15.</p> | python|tensorflow | 0 |
376,525 | 60,317,953 | Python pandas - Divide a column in dataframe1 with a column in dataframe2 based on another column in dataframe1 | <p>Dateframe1</p>
<pre><code>df = pd.DataFrame(SQL_Query, columns=[ X,Y . . . . Currency,Amount]
Index X Y ... Currency Amount
0 74 1 ... USD 100
1 75 1 ... EUR 5000
2 76 ... | <p>You can use a <code>map</code> to apply the transformation - </p>
<pre><code>import pandas as pd
df = pd.DataFrame({"Currency": ['USD', 'EUR', 'AUD', 'EUR'], "Amount": [100, 5000, 300, 750]})
df1 = pd.DataFrame({"Currency": ["AUD", "BGN", "BRL", "CAD", "EUR"], "FX": [1.6, 1.9, 4.5, 1.5, 1.1]})
df1 = df1.set_index(... | python|python-3.x|pandas|dataframe | 0 |
376,526 | 60,301,973 | Unfurling two columns in a Pandas dataframe into a list of lists | <p>I have two columns in a Pandas dataframe whose values logically follow one another. See the following:</p>
<pre><code>Name Includes
Account Product Account
Product Account Card Account
Card Account Plastic
Card Account Token
Token Token Vault
Account ... | <h3> #Approach1 </h3>
<p>Here's one approach, taking each row from the dataframe as a graph edge of a directed graph using <code>NetworkX</code> and looking for the <a href="https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.shortest_paths.generic.shortest_path.html#netw... | python|pandas|list|networkx | 2 |
376,527 | 60,322,381 | Hopf Bifurcation Plot | <p>I am attempting to code a bifurcation diagram to illustrate the values of f for which the Oregonator model yields oscillatory behaviour. I get the "setting an array element with a sequence" error at the solve_ivp line. I suspect it has something to do the time span but I am not sure. I should get a Hopf bifurcation,... | <p>You can not do this kind of simultaneous computation. (That is, you can, but it requires explicit coding and is still ill-advised as the step size selection may greatly vary over the range of <code>f</code> values.)</p>
<p>You should compute the solution for each of the <code>f</code> values separately, and then pl... | python|numpy|ode|nonlinear-functions|chemistry | 0 |
376,528 | 60,118,136 | Take a cell's value to indicate a column name in pandas | <p>Input</p>
<pre><code> DBN Grade 3 4 5
0 01M015 3 30 44 15
1 01M015 4 30 44 15
2 01M015 5 30 44 15
</code></pre>
<p>Desired Output</p>
<pre><code> DBN Grade 3 4 5 Enrollment
0 01M015 3 30 44 15 30
1 01M015 4 30 44 15 44
2 01M015 5 30 44 15 1... | <p>Set your index, and then use <code>lookup</code>:</p>
<pre><code>df.set_index('Grade').lookup(df['Grade'], df['Grade'])
</code></pre>
<p></p>
<pre><code>array(['30', '44', '15'], dtype=object)
</code></pre>
<hr>
<p>You might run into some issues if your data is numeric (in your sample data it is all strings), r... | python|pandas | 4 |
376,529 | 60,154,404 | Is there the equivalent of to_markdown to read data? | <p>With pandas 1.0.0 the use of <code>.to_markdown()</code> to show the content of a dataframe in this forum in <a href="https://www.markdownguide.org/" rel="noreferrer">markdown</a> is going to proliferate. Is there a convenient way to load the data back into a dataframe? Maybe an option to <code>.from_clipboard(markd... | <p>You can read markdown tables (or any structured text table) with the pandas <code>read_table</code> function:</p>
<p>Let's create a sample markdown table:</p>
<pre class="lang-py prettyprint-override"><code>pd.DataFrame({"a": [0, 1], "b":[2, 3]}).to_markdown() ... | python|pandas | 18 |
376,530 | 60,290,705 | Getting rows which contain certain value in a column per each group in Pandas | <p>was wondering if you could provide some guidance with this one- I'm still working on <a href="http://data.un.org/Data.aspx?d=EDATA&f=cmID:ES&c=2,5,6,7,8&s=_crEngNameOrderBy:asc,_enID:asc,yr:desc&v=1" rel="nofollow noreferrer">this data</a>and here's what I am trying to do:
-For each grouped 'country ... | <p>Explore and Clean the data before working on that.
few columns (ignoring Quantity footnotes) are having nan values. so lets drop those rows and proceed further. I tried this in jupyter notebook which gave dataframe of countries with quantity in year 2011 & 2016.</p>
<pre><code>cdf = df[['Country or Area', 'Comm... | python|pandas|int|data-cleaning|isnull | 0 |
376,531 | 59,911,740 | Custom loss function that skips the NaN input | <p>I am building an autoencoder, my data has NaN values in it. How do I create a custom (MSE) loss function, that does not compute loss if it encounters a NaN in the validation data? </p>
<p>Got a hint from the web:</p>
<pre><code>def nan_mse(y_actual, y_predicted):
per_instance = tf.where(tf.is_nan(y_actual),
... | <p>I guess, your loss function actually works well. The <code>nan</code> value probably comes from the predictions. Thus the condition <code>tf.is_nan(y_actual)</code> doesn't filter it out.
To filter out the prediction's <code>nan</code> you should do as follows:</p>
<pre><code>import tensorflow.compat.v1 as tf
from ... | python|tensorflow|keras|autoencoder | 4 |
376,532 | 60,138,199 | Format bar chart text to 2 decimal places | <p>I have working code as follows:</p>
<pre><code>active_parking = pd.pivot_table(parking[parking['Bldg Status'] == 'ACTIVE'],
index='Owned/Leased',
values='Total Parking Spaces',
aggfunc='mean'
... | <p>Use:</p>
<pre><code>active_parking.plot(kind='bar')
for i, number in enumerate(active_parking['Total Parking Spaces']):
plt.text(x=i-.23, y=number + 0.9, s=round(number, 2), weight='bold')
for i, number in enumerate(active_parking['% of Total']):
plt.text(x=i+.02, y=number + 0.9, s=round(number, 2), weight=... | python-3.x|pandas|matplotlib | 0 |
376,533 | 60,197,465 | Advance indexing in Pytorch to get rid of nested for-loops | <p>I have a situation for which I am using nested for-loops, but I want to know if there's a faster way of doing this using some advanced indexing in Pytorch.</p>
<p>I have a tensor named <code>t</code>:</p>
<pre><code>t = torch.randn(3,8)
print(t)
tensor([[-1.1258, -1.1524, -0.2506, -0.4339, 0.8487, 0.6920, -0.316... | <p>You can arrange the indices into 2D arrays then do the indexing in one shot like this:</p>
<pre><code>rows = [(row,)*len(index_tuple) for row, row_indices in enumerate(indexes) for index_tuple in row_indices]
columns = [index_tuple for row_indices in indexes for index_tuple in row_indices]
final_tensor = t[rows, co... | python|indexing|pytorch|numpy-ndarray | 1 |
376,534 | 60,064,762 | Does Tensorflows MirroredStrategy() split the training model? | <p>Does Tensorflows <code>MirroredStrategy()</code> split the training model across multiple GPUs? I am trying to run a 3D-UNet and I am at a limit of 224x224x224 for the volume for my training data on a single GPU. I am trying to implement <code>MirroredStrategy()</code> and <code>with tf.device():</code> to pass part... | <p>Though it's late, I hope this answer helps others in the future.</p>
<p>Note that this has been tested on TF 2.0, so it may not work for older versions.</p>
<p>Short answer to the first part of the question:</p>
<p><code>MirroredStrategy()</code> does not split the model on separate GPUs; it replicates the model on ... | python|tensorflow|keras|gpu|multi-gpu | 1 |
376,535 | 60,044,547 | Google Colab taking too long to train a GAN | <p>I followed the Generative-Adversarial Network tutorial on the TensorFlow site (linked below), it says "This may take about one minute / epoch with the default settings on Colab.". So far only two epochs have completed with each being around 750 seconds. That means it will take 10 hours to complete all 50 epochs. I t... | <p>Have you tried adjusting the 'runtime type' to GPU in the Runtime menu?</p> | python-3.x|tensorflow|machine-learning|google-colaboratory|generative-adversarial-network | -1 |
376,536 | 60,304,229 | Save model as h5 / Save model as .ckpt | <p>i have had big troubles today with saving formats while training a style-transfer neural network.</p>
<p>The task is already solved i feel, i only need to save my model and load it again. But i can't find a proper way to do it. </p>
<p>I used the following code from github to train a style-transfer network:</p>
... | <p>You can save the weights in checkpoint format using:</p>
<pre><code>model.save_weights("modelcheckpoint",save_format="tf")
</code></pre>
<p>You can read more about saving weights or models and chepoints <a href="https://www.tensorflow.org/guide/keras/save_and_serialize#weights-only_saving_using_tensorflow_checkpoi... | tensorflow|keras|conv-neural-network|dataformat|style-transfer | 1 |
376,537 | 60,175,023 | Converting a numpy ndarray to 1 dataframe column | <p>I have a text features which I convert to numeric using tfidf Vectorizer. The <code>complaint</code> text column is converted as below</p>
<pre><code>tfidf = TfidfVectorizer(sublinear_tf=True, min_df=5,ngram_range=(1, 2), stop_words='english')
complain_features = tfidf.fit_transform(df.complaint.values.astype('str'... | <p>Try:</p>
<pre><code>complain_df['Column1'] =complain_df[complain_df.columns[1:]].apply(
lambda x: ','.join(x.dropna().astype(str)),
axis=1
)
complain_df
</code></pre> | python|pandas|dataframe | 0 |
376,538 | 59,986,093 | How to compare the values of same index in multiple list and print the start time and end time if condition not satisfy? | <p>Here, i have 6 lists, all of them has same length of data. one is time which contains time from one start point to one end point and another five list contains signals. </p>
<pre><code> time = [11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,... | <p>Using numpy, you can do the following:</p>
<pre><code>import numpy as np
A = np.array(A)
B = np.array(B)
C = np.array(C)
D = np.array(D)
E = np.array(E)
time = np.array(time)
print time[(A == 0)*(B == 2)*(C == 0)*(D == 0)*(E == 1)]
</code></pre>
<p>By the way, your example is wrong. The correct result is <code>[... | python|pandas|list|numpy|dataframe | 0 |
376,539 | 59,922,447 | Generate a new dataframe with boolean column based on comparing other dataframes values | <p>I have the following 3 dataframes with shape of (8004,29) and the following schema as an example:</p>
<pre><code> id var0 var1 var2 var3 var4 ... var29
5171 10.0 2.8 0.0 5.0 1.0 ... 9.4
5171 40.9 2.5 3.4 4.5 1.3 ... 7.7
517... | <p>Here's a way to do it, we map the columns into a single dataframe to ensure the ids are mapped correctly:</p>
<pre><code># create a new data
new_df = df1.copy()
new_df['df2'] = new_df['id'].map(df2.set_index('id')['var29'])
new_df['df3'] = new_df['id'].map(df3.set_index('id')['var29'])
# use conditions
cond = (new... | python|pandas|dataframe | 1 |
376,540 | 59,954,265 | Installation errors with tensorflow 2.1.0 | <ol>
<li><code>pip3 --version</code> == <code>pip 20.0.2 from /home/nitin/anaconda3/envs/tensorflow/lib/python3.7/site-packages/pip (python 3.7)</code></li>
<li><code>python --version</code> == <code>python 3.7.6</code></li>
</ol>
<p>i created an environment with <code>conda create --name tensorflow</code>. I had tens... | <p>This is just warning from tensorflow stating that if you want to improve latency and throughput of some models you can harness the power of tensorRT. However you cannot use it because libnvinfer is not installed.
In order to install it,</p>
<pre><code>wget http://developer.download.nvidia.com/compute/machine-learni... | python|tensorflow|tensorflow2.0 | 2 |
376,541 | 60,150,530 | Python Pandas read error, What does this error mean? | <p>I want to import a <code>csv</code> file from the <a href="https://statswales.gov.wales/Catalogue/Health-and-Social-Care/Mental-Health/Psychiatric-Census/patientsinmentalhealthhospitalsandunitsinwaleswithamentalillness" rel="nofollow noreferrer">mental health website</a>.</p>
<p>I imported the correct libraries and... | <p>The error actually means that the 8th line in the file was expecting 1 field but found 13. </p>
<p>I think the error came because when you tried to export the file from the website, you also checked 'Include Title' and 'Include Metadata' buttons. Don't check these buttons and just select 'Comma separated' in Export... | python|pandas|csv | 1 |
376,542 | 60,293,398 | How to solve this obscure and excessively localised problem with pandas? | <p>I have this data frame wherein I want to give a score to each of the element in a distinct values column.</p>
<pre><code>+-------------------------------+-------------------------------+------------------------------+
| A | B | Distinct Values |
+... | <p>Because columns <code>A</code> and <code>B</code> are both lists, you can just add them together to get the total elements. Then use <code>Counter</code> in a dictionary comprehension to get the count of each letter, and divide each count by the total number of unique letters (determined by the length of the set).<... | python|pandas | 4 |
376,543 | 60,015,261 | Is there a fast alternative to scipy _norm_pdf for correlated distribution sampling? | <p>I have fit a series of SciPy continuous distributions for a Monte-Carlo simulation and am looking to take a large number of samples from these distributions. However, I would like to be able to take correlated samples, such that the <code>i</code>th sample takes the e.g., 90th percentile from each of the distributio... | <p>If you need just the normal <code>ppf</code>, it is indeed puzzling that it is so slow, but you can use <code>scipy.special.erfinv</code> instead:</p>
<pre><code>x = np.random.uniform(0,1,100)
np.allclose(special.erfinv(2*x-1)*np.sqrt(2),stats.norm().ppf(x))
# True
timeit(lambda:stats.norm().ppf(x),number=1000)
# 0... | python|numpy|scipy|distribution|montecarlo | 3 |
376,544 | 60,180,917 | Java API for loading TensorFlow models created in python | <p>I am using Java 13 (I'm not sure if that is relevant) and I'm making a blackjack game. I want to add a neural network model after training it in python to my Java application. However, on <a href="https://www.tensorflow.org/install/lang_java" rel="nofollow noreferrer">here</a> it says </p>
<blockquote>
<p>"Note: ... | <p>If you do not want to convert your model to TF Lite, you can also use the snapshots available for TensorFlow Java with 2.x support enabled, check this <a href="https://github.com/tensorflow/java" rel="nofollow noreferrer">repository</a>.</p> | java|python|tensorflow|installation|java-13 | 1 |
376,545 | 60,145,422 | Out of memory running VGG-19 on Keras and tensorflow on an 11GB GPU | <p>I am using keras + tensorflow (1.14) on (cuda-10.0). I have a RTX 2080 TI gpu. I am trying to run a VGG-19 model to train on 640*480*1 size images.
I run a code a determine the amount of memory GPU needs for running training on batch size 10.
It says the needed memory is ~6GB. Still it throws out of memory error o... | <p>You can follow below network to avoid out-of memory issue by including <code>maxpooling</code> layer after every two convolution layers.</p>
<pre><code>model = Sequential()
model.add(Conv_Base)
model.add(Conv2D(input_shape=(32,32,3),filters=64,kernel_size=(3,3),padding="same", activation="relu"))
model.add(Conv2D(f... | tensorflow|keras|gpu|conv-neural-network | 1 |
376,546 | 59,932,796 | Python: Pandas support in Pint | <p>I am trying to reproduce the example described in the Python Pint library <a href="https://pint.readthedocs.io/en/latest/pint-pandas.html" rel="nofollow noreferrer">here</a>.</p>
<p>In the section "Reading from csv" when running the following line:</p>
<pre><code>df_ = df.pint.quantify(level=-1)
</code></pre>
<p>... | <p>As @Ivan noted in the comments, you need to install <code>pint-pandas</code> package: </p>
<p><code>pip install git+https://github.com/hgrecco/pint-pandas.git</code></p>
<p><a href="https://github.com/hgrecco/pint/issues/1001#issuecomment-579210723" rel="nofollow noreferrer">Pandas has an open issue</a> regarding ... | python|pandas|pint | 1 |
376,547 | 59,933,278 | Analyse monthly sale in python | <p>I have a data set like this </p>
<pre><code> order_status created_at
0 cancelled 05/08/2018
1 cancelled 06/08/2018
2 dispatched 27/08/2018
3 dispatched 30/08/2018
4 cancelled 05/09/2018
5 dispatched 05/09/2018
6 dispatched 25/09/2018
7 cancelled 23/10/2018
8 dispatched 05/10/2018
9 ... | <p>You can use a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a>:</p>
<pre><code>df['created_at'] = pd.to_datetime(df['created_at'])
f = df.groupby(df.created_at.dt.month)['order_status'].value_counts().reset_inde... | python|pandas|matplotlib|seaborn | 1 |
376,548 | 60,132,576 | Adding a rowsum column to a large sparse matrix | <p>I have a large sparse matrix X (2 mil rows, 23k cols), and I would like to add a rowsum column on it and return a sparse matrix.</p>
<p>I have tried below </p>
<pre><code>np.hstack( (X.toarray(),X.sum(axis=1)) )
</code></pre>
<p>but it doesn't work well with large sparse matrix. </p>
<p>The thing is, when I call... | <pre><code>In [93]: from scipy import sparse
In [94]: M = sparse.random(5,7, .2, 'csr')
In [95]: M
Out[95]:
<5x7 spa... | python|numpy|scikit-learn|scipy | 2 |
376,549 | 60,103,825 | Retrieve data in Pandas | <p>I am using pandas and uproot to read data from a .root file, and I get a table like the following one:</p>
<p><a href="https://i.stack.imgur.com/92Xbg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/92Xbg.png" alt="enter image description here"></a></p>
<p>The aforementioned table is made with t... | <p>You could use the <a href="https://github.com/scikit-hep/awkward-array/" rel="nofollow noreferrer"><code>awkward.JaggedArray</code></a> interface for this (one of the dependencies of <code>uproot</code>), which allows you to have irregularly sized arrays.</p>
<p>For this you would need to slightly change the way yo... | python|pandas|physics|uproot | 2 |
376,550 | 60,177,310 | Converting MultiIndex Pandas DataFrame to Pivot | <p>Seems like this should be easy, but I cannot get it to work for the life of me.</p>
<p>I have a dataframe for stock data like below. How can I convert the below dataframe into a pivot table with the date as the rows, stock symbols as the columns, and Adj Close as the values (picture at bottom)</p>
<p>I am getting ... | <p>Try using:</p>
<pre><code>pricing['Adj Close']
</code></pre>
<p>where,</p>
<pre><code>pricing = pd.DataFrame(np.random.randint(50,75,(10,6)),
index=pd.date_range('01/2/20', periods=10, freq='D'),
columns=pd.MultiIndex.from_product([['Adj Close', 'Close', 'High'],['MSFT', 'AAPL'... | python|pandas|dataframe|pivot|pivot-table | 0 |
376,551 | 60,283,015 | Return type dependent on input type in Python | <p>The following function in Python can returns a list no matter if the input is a <code>list</code>, a <code>numpy.array</code> or a <code>pandas.Series</code>.</p>
<p>What is the pythonic way to write it so that the output type is the same as the input type?</p>
<pre><code>def foo(input):
output = []
outpu... | <p>In general, you can't do this without making a lot of assumptions about what the input <em>is</em>.</p>
<p>The first step would be to make sure that <code>output</code> is the right type, not a list.</p>
<pre><code>output = type(self)()
</code></pre>
<p>However, this assumes that whatever type your input is, you ... | python|pandas|list|numpy|polymorphism | 1 |
376,552 | 60,212,425 | Best practice (effiency) data manipulation of pandas big dataframe | <p>I'm dealing with a large datasets and I would like to ask the best way to change some entries of a pandas data frame <code>df</code></p>
<p>Here is my code:</p>
<pre><code>mask = df.P2I.values > c_th
df.loc[mask, 'P1I'] = df.P1I - c_offset
df.loc[mask, 'P3I'] = df.P3I - c_offset
df.loc[mask, 'P2I'] = df.P2I - c... | <p>You could do something like this in your case:</p>
<pre><code>df.loc[mask, ['P1I', 'P2I', 'P3I']] -= c_offset
</code></pre>
<p>You can also use different offsets for each column if you need to, like this (in terms of performance it looks to be rather similar to the first one):</p>
<pre><code>df.loc[mask, ['P1I', ... | python|pandas|numpy|indexing|data-manipulation | 1 |
376,553 | 60,288,451 | Numpy Changing Matrix dimensions | <p>I have a 28x28 pixel image as a numpy array and its shape is (28,28) using the np.array.shape function. I want the shape to be 784x1. In other words with a NxN matrix how do you convert it to a N^2x1. Using the flatten function i get almost what I'm looking for, the shape from flatten is (784,).</p> | <p>Another possible way is to use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_2d.html" rel="nofollow noreferrer">np.atleast_2d</a></p>
<pre><code>np.atleast_2d(arr.flatten())
</code></pre> | numpy|array-broadcasting | 1 |
376,554 | 59,973,453 | Is there any difference of precision in python methods to calculate euclidean distance? | <p>I am calculating euclidean distance array by array in a numpy array. I was using <code>np.linalg.norm(v1-v2)</code> to this. Since I was planning to use other distance measures I changed that to <code>scipy.spatial.distance.euclidean(v1,v2)</code> to keep a pattern in my code. </p>
<p>I noticed the last digits var... | <p>Floating point numbers are stored in computer as a fraction, with 53 bits to represent the numerator. So you cannot get a floating point answer with more than 15 significant digits of precision.
<a href="https://docs.python.org/3/tutorial/floatingpoint.html" rel="nofollow noreferrer">https://docs.python.org/3/tutori... | python|numpy|scikit-learn|scipy|euclidean-distance | 0 |
376,555 | 60,169,809 | Replace zeros with mean of non-zeros along an axis of array - Python / NumPy | <p>How can I replace 0s of the first rows by mean of the remaining rows? </p>
<pre><code>import numpy as np
from sklearn.impute import SimpleImputer
data = np.array([[0,0,0,0,3,2,4,4,0],
[4,6,8,9,3,1,1,4,0],
[4,6,8,9,3,1,1,4,0]])
print (data.shape)
imputer = SimpleImputer(missi... | <p>Just indexing should be enough for what you want:</p>
<pre><code>m = data[0] == 0
data[0, m] = data[1:,m].mean(0)
print(data)
array([[4, 6, 8, 9, 3, 2, 4, 4, 0],
[4, 6, 8, 9, 3, 1, 1, 4, 0],
[4, 6, 8, 9, 3, 1, 1, 4, 0]])
</code></pre>
<hr>
<p>To fill all zeros from the means of all other rows and ... | python|numpy | 2 |
376,556 | 59,929,165 | Understanding Pandas grouby sum() | <p>I am unable to understand how sum() works in case of groupby(). <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.sum.html#pandas.core.groupby.GroupBy.sum" rel="nofollow noreferrer">Official docs</a> say it computes sum of values but I can't see how:</p>
<pre><code>df =... | <p>Your example is quite bad but let me explain.</p>
<p>Groupby is an operation that takes the value of the column and merge all equal values together. Now we need an operation to deal with the other columns. Because with the merging the program needs to know how to deal with them. And that would be the operation sum. ... | python|pandas|pandas-groupby | 1 |
376,557 | 59,933,336 | Eigen matrix in cpp | <p>How to create a dynamic 3d matrix using the Eigen library. and how can slice the particular channel, in that channel slice some height and width?</p>
<p>example:</p>
<p>I want to create a matrix of size <code>3 * 320 * 240</code> (here channel width and height known at runtime), and then select a slice of <code>3 ... | <p>Perhaps something like this:</p>
<pre><code>#include <iostream>
#include <vector>
#include <Eigen/Dense>
using namespace Eigen;
int main()
{
int a = 320;
int b = 240;
// Create as many as you want, probably better in a loop.
MatrixXd m(a, b);
MatrixXd n(a, b);
MatrixXd o(... | c++|tensorflow|eigen|eigen3 | 0 |
376,558 | 60,235,593 | np.average of word vectors | <p>I have this dictionary that contains words as keys and their vectors as values.</p>
<pre><code>my_dict = {'new': array([ 6.77980e-02, -2.07800e-02, -1.22845e-01, 1.75853e-01, 1.49210e-02]),
'its': array([ 7.85300e-03, -8.81160e-02, 2.60125e-01, 1.77740e-02, -1.09075e-011])}
</code></pre>
<p>I would ... | <p>So that you calculate one average over all the values (rather than collect a set of nonsense average for each individual vector), try:</p>
<pre><code>np.average(list(my_dict.values()))
</code></pre>
<p>(If it doesn't return the shape you expect, try each explicit <code>axis=</code> possibility.)</p> | python|numpy | 1 |
376,559 | 60,310,736 | Read S3 Files That Meet Last Modified Window Into DataFrame | <p>I have an S3 bucket with objects where the Last Modified ranges from very old to current. I need to be able to find the files with a last modified stamp within a window, and then read those files (which are JSON) into some sort of Data Frame (pandas, spark, etc.). </p>
<p>I have attempted to gather the files, rea... | <p>Spark is a way to go on this one.</p>
<p>When talking to S3 bucket with a large number of files, we always need to keep in mind that listing all objects in a bucket is expensive since it returns 1000 object at a time and a pointer to fetch the next set. This makes it very hard to parallelise unless you know the str... | python|python-3.x|pandas|apache-spark|boto3 | 1 |
376,560 | 65,168,197 | Unable to open geojson file with geopandas, getting TypeError | <p>I'm trying to open a geojson file into geopandas but getting the following error message:</p>
<pre><code> Traceback (most recent call last):
File "C:\Users\arobe\Anaconda3\envs\test_env\lib\site-packages\geopandas\io\file.py", line 95, in read_file
gdf = GeoDataFrame.from_features(f_filt, crs=crs, column... | <p>I run your code on Linux using geopandas v0.8.1, fiona v1.8.17. All OK. The simple plot is as follows.</p>
<p><a href="https://i.stack.imgur.com/fhAz0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fhAz0.png" alt="gb-plot" /></a></p> | python|geopandas|fiona | 1 |
376,561 | 65,072,104 | Why doesn't this None filtering work with pandas? | <p>Let's say we have:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([[1, 2], [4, None], [None, 7]], dtype=object, columns=['a', 'b'])
print(df['a'])
# 0 1
# 1 4
# 2 None
</code></pre>
<p>I have read <a href="https://stackoverflow.com/questions/45512763/python-pandas-dataframe-remove-all-rows-where... | <p>I think because in pandas most time is possible change <code>None</code> with <code>NaN</code> both working with special function like <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isna.html" rel="nofollow noreferrer"><code>Series.isna</code></a>, <code>isnull</code> for oldier ver... | python|pandas|dataframe|null | 1 |
376,562 | 65,312,782 | How to compare and match data from different columns of same dataframe | <p>i am new to programming and trying to learn python. pardon me if this sounds silly. i am trying to compare two columns in a dataframe and match the values based on the first column(used as reference). when the values in first column are not available in second or third columns, then i need to enter an NaN. could any... | <p>You can do something like this</p>
<pre><code>df = pd.DataFrame([[290, 390, 160],[390, 450, 290], [160, 290, np.NaN], [450, np.NaN, 450]], columns=['A', 'B', 'C'])
lis = list(df['A'])
print(lis)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>[290, 390, 160, 450]
</code></pre>
<p>Then</p>
<pre><code>b = [i ... | python|pandas | 1 |
376,563 | 65,337,770 | Understanding for loop in pandas dataframe | <p>Hello there I was coding in pandas when I found this problem:</p>
<pre><code>for label,content in data_temp.items():
print(len(label))#Como vemos aqui nos imprime
print(len(data_temp.columns))
</code></pre>
<p>Firstly, I was trying to print the label, which is the indicator of the column, right? It outputs the... | <p>You are printing the length of the labels, not the labels themselves.</p>
<p>Try <code>print(label)</code> and <code>print(data_temp.columns)</code> that should output the labels one by one in the for loop and then the name of the columns as a list</p> | python|pandas|dataframe|data-science | 0 |
376,564 | 65,235,536 | Working with Lists as Pandas cell elements | <p>I am working with pandas dataframes where some of the columns have individual lists as cell elements. I want to conditionally select elements in each of the cell in one column and read the corresponding elements in lists with same index in the other column (and then print as another column). I am struggling how to d... | <p>List comprehension is your friend - here are zipped columns, and then in nested list comprehension filtered zipped lists:</p>
<pre><code>df['E'] = [[b for a, b in zip(x, y) if a > 3] for x, y in zip(df['C'], df['D'])]
print (df)
A B C D E
0 3.4 5.7 ... | python|pandas|list | 2 |
376,565 | 65,361,712 | AWS Lambda Function Exiting Execution Improperly | <p>I have Lambda function trying to run PoseNet from TensorflowJS. The program executed properly until it gets to</p>
<pre><code> const net = await posenet.load({
architecture: 'MobileNetV1',
inputResolution: { width: 183, height: 275 },
scale: 0.8,
})
</code></pre>
<p>after this line I have a ... | <p>detect is async so you have to <code>await detect(....)</code></p>
<p>or use then</p>
<pre><code>detect(img).then(predictions => {
console.log('Predictions: ', predictions);
});
</code></pre> | tensorflow|aws-lambda | 0 |
376,566 | 65,075,327 | How to add print OP in TensorFlow layer(GRU)? | <p>I add print OP in GRU source code, and want to debug the input of GRU , and also want to debug with some operation inside GRU, But this print nothing.
Dose tf.print don't work inside this source code of GRU.
I hope someone can give me some suggesstion.
Thank you very much!</p>
<pre class="lang-py prettyprint-overrid... | <p>Inside <code>call</code>, use this line:</p>
<pre><code>tf.py_function(func=tf.print, inp=[inputs], Tout=[])
</code></pre> | python|tensorflow|printing|operation | 0 |
376,567 | 65,394,175 | dataframe split to multiple dataframe for each rows with some condition | <p>I have a dataframe like this.</p>
<pre><code>A,B
1,2
3,4
5,6
7,8
9,10
11,12
13,14
</code></pre>
<p>I would like to split this above dataframe. The splitted dataframe should contains every three rows. The first dataframe splitted can contain from index 0 to index 2. Second contains from index 1 to index and so on.</p... | <p>Assuming you have standard <code>RangeIndex</code> indexes and borrowing a vectorized approach for a rolling window <a href="https://stackoverflow.com/questions/6811183/rolling-window-for-1d-arrays-in-numpy">from here</a>, we can get down to numpy's level and:</p>
<pre><code>def rolling_window(a, window):
shape ... | python|pandas | 1 |
376,568 | 65,174,274 | How do I group values in different rows that have the same name in Pandas? | <p>I have this Pandas DataFrame <code>df</code>:</p>
<pre><code> column1 column2
0 x a
1 x b
2 x c
3 y d
4 y e
5 y f
6 y g
7 z h
8 z i
9 z j
</code></pre>
<p>How do I group the values in <code>co... | <p>This is a pivot problem with some preprocessing work:</p>
<pre><code>(df.assign(index=df.groupby('column1').transform('cumcount'))
.pivot('index', 'column1', 'column2'))
column1 x y z
index
0 a d h
1 b e i
2 c f j
3 NaN g NaN
</code></pre>
<p... | python|pandas|dataframe | 2 |
376,569 | 65,213,769 | Merge two values and remove duplicates | <p>I want to merge the values <em>Account details</em> and <em>Account specifics</em> when accounting for which department it is in, and then remove any duplicate processes resulting from the merge. In this example, <em>Account specifics</em> in the HR department will cause a duplicate when merged with <em>Account det... | <p>I think simplest is assign same values to <code>Name</code> column and remove duplicates:</p>
<pre><code>df = df.assign(Name = 'Account details').drop_duplicates()
print (df)
Name Department Process
0 Account details HR Process1
1 Account details HR Process2
2 Account details ... | python|pandas|join|merge | 2 |
376,570 | 65,192,666 | Is there a way to concatenate the output of a pandas apply into a single multiindex? | <p>I have a dataframe with two columns where each of the two columns contains a list indices. I want to get the product of the two lists on a row by row level to create a multiindex.</p>
<p>For example, df1 below</p>
<pre><code>|---------------------|------------------|
| col_a | col_b |
|----... | <p>The easiest way is probably also the "dumbest": just take products of each row, put them all together, and feed them to <code>pd.MultiIndex.from_tuples</code>.</p>
<pre><code>import itertools
rowwise_products = df.apply(
lambda row: list(itertools.product(*row)),
axis=1
)
all_tuples = rowwise_produ... | python|pandas|apply|multi-index | 1 |
376,571 | 65,141,343 | how to split a column into comma seperated string? | <p>Here is sample dataframe and a is my column name.</p>
<pre><code>
a b x
0 1 3 a
1 2 4 a
2 1 3 b
3 2 5 b
4 2 4 c
</code></pre>
<p>need a column unique values to be seperated in this way</p>
<pre><code>required output: '1','2'
</code></pre>
<p>below is my code i'm getting like th... | <p>Try using your first approach with f-strings to make things easier.</p>
<pre><code>x2 =' ,'.join(f"'{str(i)}'" for i in x)
query = rf"""
SELECT
*
FROM
abc
WHERE
a in ({x2})
"""
</code></pre>
<p>If you try <code>print(query)</code>, it gives</p>
<pre><code>SELECT
... | python|python-3.x|pandas|dataframe | 0 |
376,572 | 65,322,276 | Custom metric in Keras using keras.losses.CategoricalCrossentropy | <p>I'm struggling to implement a custom metric in Keras (2.4.3 with the tensorflow backend) such that I can trigger an early stopping mechanic. Essentially, I want to have Keras stop training a model should there be too big a decrease in the training loss function. To do this, I am using the following code:</p>
<pre><c... | <p>Use this instead, mind the spelling:</p>
<pre><code>keras.losses.categorical_crossentropy(y_true,y_pred)
</code></pre> | python|tensorflow|keras|deep-learning | 1 |
376,573 | 65,426,110 | Pandas groupby by category | <p>I want to group by category</p>
<p>I have this DF(for ex)</p>
<pre><code>Period val2 val3
1 5546708.53 19741660.61
1 5235399.56 13022005.11
2 2294129.82 7336506.28
3 4888151.37 11870210.71
4 1463851.95 8057862.59
5 1733743.17 5131406.15
5 ... | <p>Use <code>pd.cut</code> to get the buckets:</p>
<pre><code>periods = pd.cut(df.Period, bins=[0,3,6,9])
(df.groupby(periods,as_index=False)
.agg({'Period':'min', 'val2':'sum', 'val3':'sum'})
)
</code></pre>
<p>Output:</p>
<pre><code> Period val2 val3
0 1 17964389.28 51970382.71
1 4 ... | python|python-3.x|pandas|dataframe | 2 |
376,574 | 65,178,296 | Frustrating error: Throwing KeyError when creating new columns in Pandas | <p>This is weird, I have used this code before and it worked. But now it throws me a KeyError saying:</p>
<blockquote>
<p>KeyError: "None of [Index(['0', '1'], dtype='object')] are in the
[columns]"</p>
</blockquote>
<pre><code>d = {'col1': [1, 2, 3], 'col2': [3, 4, 5]}
df = pd.DataFrame(data=d)
df[[str(c) fo... | <p>For me working well.</p>
<p>Another solution is create new DataFrame and add to original:</p>
<pre><code>df = df.join(pd.DataFrame([[5,6],[6,6], [7,7]], index=df.index, columns=['0','1']))
print (df)
col1 col2 0 1
0 1 3 5 6
1 2 4 6 6
2 3 5 7 7
</code></pre> | python|pandas|numpy | 0 |
376,575 | 65,233,188 | Generate heat-map of cyclical continuous features - 24-hour time | <p>Having a Pandas DF with hour of day, I've calculated the sin/cos time feature, <a href="https://ianlondon.github.io/blog/encoding-cyclical-features-24hour-time/" rel="nofollow noreferrer">based on this article</a>:</p>
<pre><code> counter hour sin_time cos_time
0 1 1 2.588190e-01 ... | <p>Found out that you can add weights argument to histogram2d:</p>
<pre><code>np.histogram2d(x, y, weights=w, bins=50)
</code></pre>
<p>so w is my counter column:
<a href="https://i.stack.imgur.com/CSmmQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CSmmQ.png" alt="enter image description here" />... | python|pandas|time|heatmap|scatter-plot | 0 |
376,576 | 65,300,388 | Tensorflow Taking too much time on GPU | <pre><code>import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
print("Name:", gpu.name, " Type:", gpu.device_type)
from tensorflow.python.client import device_lib
device_lib.list_local_devices()
tf.test.is_gpu_available()
</code></pre>
<p>I a... | <p>It's because Tensorflow version 2.3 doesn't support using CUDA 11, but all Ampere cards require a minimum of CUDA 11.0 and Cudnn 8.</p>
<p>Luckily TensorFlow 2.4 got released recently. It's compatible, but with a slightly lower CUDA 11.0.</p>
<p>Please update your installation to use CUDA 11.0 from the archives sect... | python|tensorflow2.0|tensorflow2.x | 2 |
376,577 | 65,188,251 | How to pivot a dataframe to collapse multiple rows into one | <p>I have a dataframe that has 4 columns: UID, Date, Type, and Value as such:</p>
<pre><code>UID Date Type Value
50 2020-12-01 3 15
50 2020-12-01 2 13
50 2020-12-01 1 50
135 2020-12-02 2 0
135 2020-12-02 1 12
50 2020-12-02 4 100
50 2020-12-02 2 25
50 2020... | <p>It is simply</p>
<pre><code>df.pivot(index = ['UID','Date'], values = 'Value', columns = 'Type').add_prefix('Type_')
</code></pre>
<p>output</p>
<pre><code> Type Type_1 Type_2 Type_3 Type_4
UID Date
50 2020-12-01 50.0 13.0 15.0 NaN
2020-12-02 40.0 25.0 15.0 100.0... | python|pandas|dataframe | 2 |
376,578 | 65,357,979 | How to delete empty sheets that have a header row from excel workbook in Python? | <p>I need to delete all empty sheets from a workbook, and these sheets have headers, so they are not completely empty. Just row 2 and on will be empty and I need to delete these sheets.</p>
<p>I currently have this:</p>
<pre><code>def DeleteEmptyColumnsAndRows(filename):
import pandas as pd
import pathlib
f... | <p>Figured it out. This is the solution to delete all sheets from a workbook where the 1st row (the header row) is the only row with any data in it:</p>
<pre><code>def DeleteEmptyColumnsAndRows(filename):
import pandas as pd
full_path = filename
df_with_header = pd.read_excel(full_path, header=None, sheet_n... | python|python-3.x|pandas|dataframe | 0 |
376,579 | 65,460,997 | Import latest file from S3 bucket to Pandas dataframe | <p><strong>SITUATION</strong></p>
<p>I have written some code in Python 3 in which I use the OS and Glob packages to find the latest csv file in a directory and convert it to a Panda dataframe.</p>
<p>Code as follows:</p>
<pre><code>import pandas as pd
from pathlib import Path
import glob
import os
# LOOK FOR ALL CSVs... | <p>To get the key of your object, you have to use <code>latest_file['Key']</code> and for pandas you should include <code>s3://</code> as a prefix:</p>
<pre><code>imported_file = pd.read_csv('s3://' + latest_file['Key'], dtype={2:'str'})
</code></pre>
<p>This will require <a href="https://s3fs.readthedocs.io/en/latest/... | python-3.x|pandas|amazon-web-services|amazon-s3|boto3 | 0 |
376,580 | 65,076,353 | How to write a list with strings and DataFrames into an .txt file | <p>i would like to write this list into a .txt file. My Problem is that i cant add the whole data of the 1801*20 matrix.</p>
<p><a href="https://i.stack.imgur.com/S841m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S841m.png" alt="list" /></a></p>
<p>i tried to convert the list into an pandas DataF... | <p>We make the assumption that you know that you have two types of elements in your list: string and pandas dataframes. So you have to identify across this only two types.</p>
<pre><code>with open('test.txt', 'w+') as fobj:
for e in Liste:
if isinstance(e, str):
fobj.write(e + '\n')
else:
... | python|pandas|list|dataframe|export-to-csv | 1 |
376,581 | 65,245,787 | What is the Problem in my Building Softmax from Scratch in Pytorch | <p>I read this <a href="https://d2l.ai/chapter_linear-networks/softmax-regression-scratch.html" rel="nofollow noreferrer">post</a> ans try to build softmax by myself. Here is the code</p>
<pre><code>import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import time
i... | <p>Change:</p>
<pre><code>def cross_entropy(y_hat, y):
return - torch.log(y_hat.gather(1, y.view(-1, 1))).sum()
</code></pre>
<p>To:</p>
<pre><code>def cross_entropy(y_hat, y):
return - torch.log(y_hat[range(len(y_hat)), y] + 1e-8).sum()
</code></pre>
<p>Outputs should be something like:</p>
<pre><code>epoch 1,... | python-3.x|pytorch|loss-function|softmax | 1 |
376,582 | 65,175,275 | Pytorch: Converting a VGG model into a sequential model, but getting different outputs | <p><strong>Background:</strong>
I'm working on an adversarial detector method which requires to access the outputs from each hidden layer.
I loaded a pretrained VGG16 from <code>torchvision.models</code>.</p>
<p>To access the output from each hidden layer, I put it into a sequential model:</p>
<pre><code>vgg16 = models... | <p>You need to call the eval mode before doing inference.</p>
<p>i.e.</p>
<pre><code>vgg16.eval()
vgg16_seq.eval()
</code></pre> | python|neural-network|computer-vision|pytorch | 1 |
376,583 | 65,142,574 | How to sum across columns after pandas groupby? | <p>I am using the <code>groupby()</code> operation on a pandas dataframe. I am then trying to sum the columns together for each row. However I keep getting an error when calling <code>sum()</code>.</p>
<p>I have attached my code below:</p>
<pre class="lang-py prettyprint-override"><code>bike_use = bike_use.groupby(['ro... | <p>I think you want double <code>sum</code> - first aggregate by <code>sum</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.sum.html" rel="nofollow noreferrer"><code>GroupBy.sum</code></a> and then sum both columns with <code>sum(axis=1)</code> by <a href="http://... | python|pandas|dataframe | 0 |
376,584 | 65,146,830 | problem with numpy ('module' object is not callable), ( fails to pass a sanity check due to a bug in the windows runtime.) | <p>I got this error trying to install another package: the current Numpy installation fails to pass a sanity check due to a bug in the windows runtime. Ive checked the problem and it seems to occur using the newest version of numpy (1.19.4). I then downgraded and it still didnt work. I then tried a lot of deinstalling,... | <p>You want <code>np.random.random(10)</code>. <code>np.random</code> is the module, <code>np.random.random</code> is the function.</p>
<p>Documentation: <a href="https://numpy.org/doc/stable/reference/random/generated/numpy.random.random.html" rel="nofollow noreferrer">https://numpy.org/doc/stable/reference/random/gen... | python|numpy|permissions|anaconda|reset | 0 |
376,585 | 65,392,679 | json_normalize: Accessing data that is both in library and array form | <p>I'm trying to extract the values for the 'Resource' in the following nested json</p>
<pre><code>{
"Statement": [
{
"Effect": "A-----------",
"Action": [
"logs:C-----------",
"logs:P-----------&q... | <p>You don't need pandas to manipulate a json.</p>
<pre><code>import pandas as pd
data = {
"Statement": [
{
"Effect": "A-----------",
"Action": [
"logs:C-----------",
"logs:P-----------"
... | pandas | 1 |
376,586 | 65,172,004 | Is it possible to close/reopen connection using pd.read_sql and chunking? | <p>Let's say I have a very large table and I want to use pd.read_sql with chunksize = 10000.</p>
<p>The way I approach it now is:</p>
<pre><code>from sqlalchemy import create_engine
import pandas as pd
engine = create_engine('dialect://user:pass@host:port/schema')
with engine.connect() as conn:
for df in pd.read_sql... | <p>Can you do something like:</p>
<pre><code>start = 0
chunk = 5000
while True:
with engine.connect() as conn:
query = f'SELECT * FROM VERY_LARGE_TABLE LIMIT {start}, {chunk}'
df = pd.read_sql(query, con=conn)
# if df is empty stop querying
if df.empty:
break
... | pandas|sqlalchemy|snowflake-cloud-data-platform | 0 |
376,587 | 65,362,162 | Apply an operation to specific columns in numpy array | <p>I would like to apply feature normalisation to a numpy array. Normally this would be trivial with python broadcasting, for example one would do something like this:</p>
<pre><code>train_mean = train.mean(axis=0)
train_std = train.std(axis=0)
train = (train - train_mean) / train_std
val = (val - train_mean) / train_... | <p>Would that be a better way?</p>
<pre><code>from sklearn import preprocessing
np.set_printoptions(suppress=True, linewidth=1000, precision=3)
np.random.seed(5)
train = np.array([np.random.uniform(low=0, high=100, size=10),
np.random.uniform(low=0, high=30, size=10),
np.random.uniform(low=0, high=70,... | python-3.x|numpy | 2 |
376,588 | 65,119,407 | Pandas: How do I search series cells for partial string match? | <p>I have a DataFrame created by importing an Excel sheet that has several columns but inconsistent text data in its rows. For example, one column labeled "Airplane 1" has a "Gross weight: 2500" in row 25 where as the column "Airplane 2" has "Gross weight: 3000" in a different r... | <pre><code>df.loc[df.column_name.str.contains("Gross weight", na=False)]
</code></pre>
<p><a href="https://stackoverflow.com/questions/28311655/ignoring-nans-with-str-contains">reference</a></p>
<p>To do this iteratively you could loop over the column names when doing this</p>
<pre><code>for name in [column_n... | python|pandas|string|series | 0 |
376,589 | 65,200,767 | pandas dataframe index remove date from datetime | <p>File dataexample_df.txt:</p>
<pre><code>2020-12-04_163024 26.15 26.37 19.40 24.57
2020-12-04_163026 26.15 26.37 19.20 24.57
2020-12-04_163028 26.05 26.37 18.78 24.57
</code></pre>
<p>I want to read it in as pandas dataframe where the index column has only the time part in format <code>'%H:%M:%S'</code>, without the ... | <p>Considering your <code>df</code> to be this:</p>
<pre><code>In [121]: df
Out[121]:
1 2 3 4
0
2020-12-04_163024 26.15 26.37 19.40 24.57
2020-12-04_163026 26.15 26.37 19.20 24.57
2020-12-04_163028 26.05 26.37 18.78 24.57
</c... | python|pandas|dataframe | 3 |
376,590 | 65,246,124 | Dataset Labeled as not found or Corrupt, but the dataset is not corrupt | <p>I have been trying to use this Github (<a href="https://github.com/AntixK/PyTorch-VAE" rel="nofollow noreferrer">https://github.com/AntixK/PyTorch-VAE</a>) and call the CelebA dataset using the config file listed. Specifically under the vae.yaml I have placed the path of the unzipped file where I have downloaded th... | <p>My pytorch version is 1.6.0.<br />
There are two issues which I have faced. The below is my solution. It is not official but it works for me. Hope the next pytorch version will update it.</p>
<ol>
<li>Issue: Dataset not found or corrupted.'</li>
</ol>
<p>When I checked file celeba.py in pytorch library. I found this... | pytorch|dataset|google-colaboratory | 0 |
376,591 | 65,201,233 | How to generate an onnx file with linear layers using Pytorch | <p>I want to create a network on the basis of the vgg16 network, but adding linear layers (Gemm) just after the conv2d layers, for normalization purpose.
After that, I want to export the network in an ONNX file.</p>
<p>The first part seems to work: I took the Pytorch code for generating the vgg16 and modified it as fol... | <p>The input data of nn.Linear here is a 4-D tensor, then torch will export it to {Transpose, MatMul, Add}. Only input is 2-D, the GEMM op will be exported.</p>
<p>You can have to look at the <a href="https://github.com/pytorch/pytorch/blob/b31f58de6fa8bbda5353b3c77d9be4914399724d/torch/nn/functional.py#L1672" rel="nof... | pytorch|onnx | 0 |
376,592 | 65,261,037 | Getting rid of extra spaces I have in different rows of a column in datafram | <p>I am trying to iterate through the rows of my column (item_2) and get rid of the extra spaces each row has by using</p>
<pre><code>" ".join(x.split())
</code></pre>
<p>But I get</p>
<blockquote>
<p>AttributeError: can't set attribute</p>
</blockquote>
<p>error when running following code.</p>
<pre><code>fo... | <p>If there's no leading/trailing whitespace, you can just use <code>.str.replace(r' +',r' ')</code></p>
<p>e.g, <code>dffirst['item_2']=dffirst['item_2'].str.replace(r' +',r' ')</code>.</p>
<p>If there is, you'll need to toss on a .strip() or use a slightly better regex.</p> | python|python-3.x|pandas|dataframe | 0 |
376,593 | 65,233,322 | REGEX IN DATAFRAME PANDAS | <p>I have a dataframe with a column like that</p>
<pre><code>COL1
PACK[5.95 $ /if game game1 + game1]
PACK[3 $ /2 products.]
</code></pre>
<p>I want create other column as following according COL1</p>
<pre><code>pack_plus pack
5,95 3
</code></pre>
<p>I am ok for pack_plus : <code>PACK\[(\d[\d.]*) ... | <p>You can use</p>
<pre class="lang-py prettyprint-override"><code>PACK\[(\d[\d.]*)\s*\$[^][+]*]
</code></pre>
<p>See the <a href="https://regex101.com/r/DU8ejJ/1" rel="nofollow noreferrer">regex demo</a>.</p>
<p><strong>Details</strong></p>
<ul>
<li><code>PACK\[</code> - <code>PACK[</code> string</li>
<li><code>(\d[\d... | regex|pandas | 1 |
376,594 | 65,235,662 | Python create a data frame by using last n rows | <p>I have a pandas df as follows:</p>
<pre><code>Value1 Value2 Label
15.1 12 0
17 5 1
19 2 1
</code></pre>
<p>I am looking to build a new df, such that each row contains thee input of the previous <code>n</code> rows. For example if <code>n=2</code> my output should be... | <p>Perhaps something like:</p>
<pre><code>n = 2
sel = [k for k in df.columns if k != 'Label']
df2 = df
for k in range(1, n + 1):
df2 = df2.join(df[sel].shift(k), rsuffix=f'.{k}')
print(df2)
Value1 Value2 Label Value1.1 Value2.1 Value1.2 Value2.2
0 15.1 12 0 NaN NaN NaN ... | python|pandas | 1 |
376,595 | 65,402,880 | Tensorflow batchsize affects precision | <p>The same input, only different batch sizes.</p>
<ul>
<li>Why the outputs are different?</li>
<li>How to avoid the difference or force the output to be the same?</li>
</ul>
<pre class="lang-py prettyprint-override"><code>from tensorflow import keras
from tensorflow.keras import layers
def create_net(n_input, n_hidde... | <p>The change in result happens only when the batch size is very less i.e 1 or 2, this is because if the batch is too small, the mean and variance for any particular batch will not be the same as compared to the larger dataset.</p>
<p>I tested with your code with a batch size of more than 2 and it all gave the same res... | python|tensorflow|keras | 0 |
376,596 | 65,073,439 | How to use Numpy vectorize to calculate columns in Pandas | <p>I have a pd Dataframe and would like to calculate one column based on two others from the same dataframe. I would like to use Numpy vectorisation for this as the dataset is large.
Here is the dataframe:</p>
<pre><code>Input Dataframe
A B
0 567 345
1 123 456
2 568 354
Output Dataframe
A B C
0 5... | <p>A list comprehension should be faster then apply or such use case:</p>
<pre><code>df['C'] = [f"{a}.{b}" for a,b in zip(df['A'],df['B'])]
</code></pre>
<hr />
<p>Outputs</p>
<pre><code> A B C
0 567 345 567.345
1 123 456 123.456
2 568 354 568.354
</code></pre> | python|pandas|numpy | 0 |
376,597 | 65,165,864 | Programming Error (sql syntax) trying to get a MySQL table with "-" in table name into Pandas dataframe | <p>Edit:</p>
<p>See answer but "-" in MySQL table names causes problems.
I tried this: <a href="https://stackoverflow.com/a/37730334/14767913">https://stackoverflow.com/a/37730334/14767913</a></p>
<p>My code:</p>
<pre><code>import pandas as pd
table_name = 'calcium-foods'
df = pd.read_sql('SELECT * FROM calci... | <p>ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-foods' at line 1")</p>
<p>Try change this line:</p>
<pre><code>sql = "SELECT * from " + table_name
</code></pre>
<p>to:</p>
<pre><code>... | python|mysql|pandas | 0 |
376,598 | 65,144,547 | keras model.fit ValueError: The outer 2 dimensions of indices.shape=[1,11,1] must match the outer 2 dimensions of updates.shape=[2] | <p>I am training a keras model with custom loss and evaluation metric. It trains without metric. But it gave following error when i try to train like:</p>
<pre><code>model.compile(optimizer= keras.optimizers.Adam(learning_rate = 1e-3), loss = inner_product, metrics=dice_index_metric)
model.fit([X_train], [y_train], ep... | <p>First, from your code</p>
<pre><code>ind = tf.argsort(y_pred,axis=-1,direction='ASCENDING',stable=False,name=None)[-2:]
</code></pre>
<p>you have forgotten that y_pred is in batch. Which means y_pred's shape is not [11,] but rather [N,11], and assuming from your error message, batch size is 1.
Therefore, the line ab... | python|tensorflow|machine-learning|keras|recommendation-engine | 0 |
376,599 | 65,327,509 | Select/Group rows from a data frame with the nearest values for a specific column(s) | <p>I have the two columns in a data frame (you can see a sample down below)
Usually in columns A & B I get 10 to 12 rows with similar values.
So for example: from index 1 to 10 and then from index 11 to 21.
I would like to group these values and get the mean and standard deviation of each group.
I found this follow... | <p>A simpler approach consist in grouping the values where the percentage change is not greater than a given threshold (let's say 0.5):</p>
<pre><code>df['Group'] = (df.A.pct_change().abs()>0.5).cumsum()
df.groupby('Group').agg(['mean', 'std'])
</code></pre>
<p>Output:</p>
<pre><code> A ... | python|pandas | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.