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 |
|---|---|---|---|---|---|---|
14,800 | 70,952,500 | Multiply a column with a row | <p>I have a data frame like this</p>
<pre><code>Name Oil Cream Sales
A 0 900 43
B 12 0 76
C 0 9 48
D 3 0 33
E 12 98 91
Cur Sales 0.1 0.9 998
</code></pre>
<p>Now when... | <p>Select all columns and indices without columns <code>Sales</code> and index <code>Cur Sales</code>, comapre by <code>1</code> and multiple by column and by row:</p>
<pre><code>c = df.columns.drop(['Sales'])
i = df.index.drop(['Cur Sales'])
df.loc[i, c] = df.loc[i, c].eq(0).mul(df['Sales'], axis=0).mul(df.loc['Cur S... | python|pandas|dataframe | 0 |
14,801 | 70,859,462 | python - List of Lists into pandas dataframe including name of columns | <p>I would like to transfer a list of lists into a dataframe with columns based on the lists in the list.
This is still easy.</p>
<pre><code>list = [[....],[....],[...]]
df = pd.DataFrame(list)
df = df.transpose()
</code></pre>
<p>The problem is: I would like to give the columns a column-name based on entries I have in... | <p>Use <code>zip</code> with <code>dict</code> for dictionary of lists and pass to <code>DataFrame</code>:</p>
<pre><code>L= [[1,2,3,5],[4,8,9,8],[1,2,5,3]]
list_two = list('ABC')
df = pd.DataFrame(dict(zip(list_two, L)))
print (df)
A B C
0 1 4 1
1 2 8 2
2 3 9 5
3 5 8 3
</code></pre>
<p>Or if pass <c... | pandas|list | 0 |
14,802 | 70,867,023 | select first occurrence where column value is greater than x for each A(key) | dataframe | <p>What I have</p>
<pre><code> A B C D E
0 foo 0 1.2 1 2
1 foo 1 1.3 2 4
2 foo 2 2.1 4 5
3 foo 3 3.1 3 5
4 nan 0 0 0 0
5 bar 0 4.1 4 6
6 bar 1 1.2 5 8
7 bar 2 1.4 6 9
8 bar 3 5.0 7 9
9 nan 0 0 0 0
10 baz 0 4.1 5 0
11 baz 1 1.2 5 3
12 baz 2 1.4 6... | <p>You can first slice the rows that match the condition on D, then <code>groupby</code> A and get the <code>first</code> element of each group:</p>
<pre><code>df[df['D'].ge(4)].groupby('A', sort=False).first()
</code></pre>
<p>output:</p>
<pre><code> B C D E
A
foo 2 2.1 4 5
bar 0 4.1 4 ... | python|pandas|dataframe | 2 |
14,803 | 51,754,676 | Need to determine if group contains only one catagory in pandas dataframe | <p>I currently have the following DataFrame with an id and a column called "childOrParent".
A group cannot have children without Parents.</p>
<pre><code>+----+---------------+
| id | childOrParent |
+----+---------------+
| 1 | Parent |
| 1 | child |
| 2 | Parent |
| 3 | child |
| 3 ... | <p>Using <code>groupby</code> with <code>filter</code> + <code>all</code></p>
<pre><code>df.groupby('id').filter(lambda x : (x['childOrParent']=='child').all())
Out[383]:
id childOrParent
3 3 child
4 3 child
5 3 child
df.groupby('id').filter(lambda x : (x['childOrParent']=='child').al... | python|pandas | 2 |
14,804 | 41,707,385 | TypeError: 'Tensor' object does not support item assignment | <pre><code>output = tf.zeros(shape=[2, len(wss), 3, 2*d])
for i, atten_embed in enumerate(atten_embeds):
for j, ws in enumerate(wss):
conv_layer = conv_layers_A[j]
conv = conv_layer(atten_embed)
new_shape = (reduce(lambda x,y:x*y, conv.get_shape()[:-1]).value,num_filters)
conv = K.re... | <pre><code>output = []
for i, atten_embed in enumerate(atten_embeds):
for j, ws in enumerate(wss):
conv_layer = conv_layers_A[j]
conv = conv_layer(atten_embed)
new_shape = (reduce(lambda x,y:x*y, conv.get_shape()[:-1]).value,num_filters)
conv = K.reshape(conv, new_shape)
for ... | tensorflow|keras | 1 |
14,805 | 64,491,090 | Python Pandas data_range | <p>I'm trying to get every month between a given date range using data_range function in pandas. However, if I set the end the date to be the last date of a month, it's returning an extra month for me. How can I fix this?</p>
<pre><code>[In]: pd.date_range(*(pd.to_datetime(['01/01/2020', '03/30/2020']) + pd.offsets.Mon... | <p>Use <code>pd.offsets.MonthEnd(0)</code> instead, that will solve your problem:</p>
<pre><code>pd.date_range(*(pd.to_datetime(['01/01/2020', '03/31/2020']) + pd.offsets.MonthEnd(0)), freq='M')
DatetimeIndex(['2020-01-31', '2020-02-29', '2020-03-31'], dtype='datetime64[ns]', freq='M')
</code></pre>
<p>The cleaner sol... | python|pandas|date | 0 |
14,806 | 64,354,377 | Multiplying 2D and 1D arrays NumPy | <p>I'm somewhat new to python and numpy, so maybe some of you can help me here.</p>
<p>I have a 1D numpy array called z, and some 2D matrices called X0 , Y0, and SLM.</p>
<p>I want to create a 3D array (a stack of 2D matrices), by doing this operation, trying to avoid a for loop:</p>
<pre><code>for index in range(len(z... | <p>Good question, what you're looking for is <code>np.tensordot</code>, see example below:</p>
<pre><code>import numpy as np
x0 = np.floor(np.random.rand(3, 3)*10)
y0 = np.floor(np.random.rand(3, 3)*10)
z = np.array([1, 2, 3])
SLM = 1
array = SLM*np.exp(np.tensordot(z, x0+y0, axes=0))
</code></pre> | python|arrays|performance|numpy|product | 0 |
14,807 | 64,441,531 | how to split a dataframe based on the unique channel name for graph plotting | <p>I have been trying to split a dataframe based on a unique channel name and then plot a graph across different weeks for progress demonstration using Colab.</p>
<p>Here is my attempt:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
#read and append all the worksheets into a single dataframe... | <p>After changing the data type, you could make a pivot table with 'channel' as columns, 'Week' as the index.</p>
<pre><code>subchannel_df = data.pivot_table('Time of alarms', index = 'Week', column='Channel', aggfunc='sum')
</code></pre>
<p>then if you would like to either put all channel together in one bar plot,</p>... | python|pandas|dataframe|data-analysis | 0 |
14,808 | 64,551,140 | keras prioritizes metrics or loss? | <p>I'm struggling with understanding how keras model works.</p>
<p>When we train model, we give metrics(like ['accuracy']) and loss function(like cross-entropy) as arguments.
What I want to know is which is the goal for model to optimize.
After fitting, leant model maximize accuracy? or minimize loss?</p> | <p>The model optimizes the loss; Metrics are only there for your information and reporting results.
<a href="https://en.wikipedia.org/wiki/Loss_function" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Loss_function</a></p>
<p>Note that metrics are optional, but you must provide a loss function to do training.<... | tensorflow|keras|neural-network | 2 |
14,809 | 64,472,414 | How to handle returned errors from applying isbnlib.meta with pandas | <p>I'm using <code>isbnlib.meta</code> which pulls metadata (book title, author, year publisher, etc.) when you enter in an isbn. I have a dataframe with 482,000 isbns (column title: isbn13). When I run the function, I'll get an error like <code>NotValidISBNError</code> which stops the code in it's tracks. What I want ... | <ul>
<li>The current implementation for extracting isbn meta data, is incredibly slow and inefficient.
<ul>
<li>As stated, there are 482,000 unique isbn values, for which the data is being downloaded multiple times (e.g. once for each column, as the code is currently written)</li>
</ul>
</li>
<li>It will be better to d... | python|pandas|error-handling|json-normalize|isbnlib | 2 |
14,810 | 47,959,217 | Sort 2D NumPy array by one of the columns | <p>I though this would be super easy but I am struggling a little. I have a data structure as follows</p>
<pre><code>array([[ 5. , 3.40166205],
[ 10. , 2.72778882],
[ 15. , 2.31881804],
[ 20. , 2.50643777],
[ 1. , 3.94076063],
[ 2. , 3.80598599],
... | <p>This is a common numpy idiom. You can use <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.argsort.html" rel="nofollow noreferrer"><code>argsort</code></a> (on the first column) + numpy indexing here - </p>
<pre><code>x[x[:, 0].argsort()]
array([[ 1. , 3.94076063],
[ 2. ... | python|arrays|sorting|numpy | 2 |
14,811 | 48,978,004 | python - Create sparse tiles in numpy | <p>I looked through the numpy documentation, but I don't know the exact terminology of the thing I want to do. I want to do the following:</p>
<pre><code>a=np.array([[0,1,2],
[3,4,5],
[6,7,8],
[,9,10,11]])
b=np.sparse_tiles(a,(1,2),dtype=a.dtype)
b
array([[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,1,0,0,2],
[0,0,0,0,0,0,0,0,0],
... | <p>You can use <code>np.kron</code>:</p>
<pre><code>>>> np.kron(a, [[0,0,0],[0,0,1]])
array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 1, 0, 0, 2],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 3, 0, 0, 4, 0, 0, 5],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0],... | python|numpy | 2 |
14,812 | 49,340,081 | One_Hot Encode and Tensorflow (Explain behind the scenes ) | <p>I am new to deep learning world and tensorflow. Tensorflow is so complicated for me right now.</p>
<p>I was following a tutorial on TF Layers API and I got this issue with one hot encode. Here is my code </p>
<pre><code>import pandas as pd
from sklearn.datasets import load_wine
from sklearn.model_selection import ... | <p>Your network is making a class prediction on 3 classes, class A, B, and C. </p>
<p>In defining a neural network to transform your 13 inputs to a representation that you can use to distinguish between these 3 classes you have a few choices.</p>
<p>You could output 1 number. Let's define a single-value output <1 ... | tensorflow|scikit-learn|deep-learning|tensorflow-datasets|one-hot-encoding | 1 |
14,813 | 48,984,869 | How to conditionally separate a cell value and add to a column using pandas | <p>For example</p>
<p><strong>testing.csv:</strong></p>
<pre><code>First Name Last Name Profile URL
Ashleigh Phelps https://www.linkedin.com/in/ashleighephelps
Jonathan https://www.linkedin.com/in/jonathantsegal
Camilla Innes https://www.linkedin.com/in/camilla-innes-61213628 ... | <p>Well this big lines do the job:</p>
<pre><code>df.loc[(df['Last Name']=='')&(df['First Name'].apply(lambda x: len(x.split()))>1), 'Last Name'] = df.loc[df['First Name'].apply(lambda x: len(x.split()))>1, 'First Name'].apply(lambda x: x.split()[1])
df.loc[(df['First Name'].apply(lambda x: len(x.split()))&... | python|pandas|dataframe | 1 |
14,814 | 58,987,897 | How to do groupby concat sum of only positives numbers in pandas dataframe | <p>I have dataframe like as show where I need create a new data frame by grouping the input dataframe by document number and concat all the descriptions(column name:Text)with space delimiter and sum up the positive amounts as a new column.</p>
<p><strong>Input dataframe</strong></p>
<pre><code> df
Doc Number Te... | <p>Use <code>pandas.DataFrame.groupby.agg</code>:</p>
<pre><code>new_df = df.groupby('Doc Number', as_index=False).agg({'Text': ' '.join, 'Amount': lambda x: sum(i for i in x if i > 0)})
print(new_df)
</code></pre>
<p>Output:</p>
<pre><code> Doc Number Amount Text
0 122 50 DB1 DB2... | python|pandas|dataframe|pandas-groupby|group-concat | 2 |
14,815 | 59,023,883 | How to drop Pandas DataFrame rows with condition to keep specific column value | <p>I know similar questions have been asked before, but they didn't quite seem to help with my issue so I decided to ask a new question.</p>
<p>What I have are three separate DataFrames - let's call them <code>a</code>, <code>b</code>, and <code>c</code> - that are merged into one large dataframe. In each of these thr... | <p>we can use <code>sample</code> before we combine with <code>c</code></p>
<pre><code>a_b=pd.concat([a,b]).sample(n=len(a)+len(b))
new=pd.concat([a_b,c]).drop_duplicates(['value', 'target'], keep='last')
new
Out[11]:
unit value target
1 2 24 'd'
4 0 32 'q'
3 9 89 'p'
1 2 ... | python|pandas | 0 |
14,816 | 70,117,813 | Run Keras.NET models in different threads in C# | <p>Since <code>Keras.Models.Sequential</code> takes a little bit of time to get ready for utilization, that makes a program with a user interface to freeze for a moment, and obviously would annoy the user.<br>
Therefore, I am trying to create models, fit and predict data in a different thread in the background, then re... | <p>I just found a way of making that.<br>
After a little bit of research and trials, I found that C# Tensorflow tools as "Keras.Models.Sequential" and "Numpy" must run on the same thread. Therefore, I just have to create only one thread in the background, which deals with tensorflow stuff, and make ... | c#|multithreading|numpy|keras|access-violation | 0 |
14,817 | 70,361,956 | Determine in how many categories users are logged per time window unit | <p>I have a log of users and in which category it is logged. Users can be logged in multiple categories. I would like to determine which users are logged in multiple categories. The log is kinda long so preferably it would be sorted on users on top that have been logged in most categories.</p>
<div class="s-table-conta... | <p>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> by column <code>user</code>:</p>
<pre><code>df1 = (df.groupby('user', as_index=False)
.agg(categories=('category', ','.join), counts=('category'... | python|pandas|database | 1 |
14,818 | 70,222,802 | how to change the data type from string to bytes, keeping the contents of the string unchanged? | <p>How can you convert string to bytes? And it's not about decode/encode, I have just bytes in the string, I just need to convert the format of the string to bytes.</p>
<p>The point is that I want to write the array numpy in the image metadata. In order to save both the shape of the array and its contents I use the pic... | <p>It would be good if you show some code.</p>
<p><a href="https://docs.python.org/3/library/pickle.html#pickle.dumps" rel="nofollow noreferrer"><code>pickle.dumps</code></a> returns a <a href="https://docs.python.org/3/library/stdtypes.html#binary-sequence-types-bytes-bytearray-memoryview" rel="nofollow noreferrer"><c... | numpy|pickle | 0 |
14,819 | 70,213,109 | ValueError: Shapes (None, 5) and (None, 15, 5) are incompatible | <p>I want to implement a Hierarchical attention mechanism for document classification presented by Yang. But I want to replace LSTM with Transformer.</p>
<p>I used Apoorv Nandan's text classification with Transformer:
<a href="https://keras.io/examples/nlp/text_classification_with_transformer/" rel="nofollow noreferrer... | <p>When I had a similar error, I found that a Flatten() layer helped, I had incompatible shapes of (None, x, y) and (None, y).</p>
<p>If you try to provide a flatten layer for the part that gives you the (None, 15, 5), then it should output something like (None, 75).</p>
<p>The flatten layer merely removes dimensions, ... | python|tensorflow|keras|self-attention | 0 |
14,820 | 70,082,416 | Python: Appending 2D arrays from meshgrid | <p>I'm plotting two surface plots in python obtained from <code>np.meshgrid</code>, which I want to append to create only one surface plot. For instance:</p>
<pre><code>fig = plt.figure(figsize=(8,4))
ax = fig.add_subplot(projection='3d')
# First surface:
x1 = np.linspace(0,1,100)
y1 = np.linspace(0,1,100)
X1,Y1 = np.... | <p>I would simply fill only one Z array, for example:</p>
<pre><code>fig = plt.figure(figsize=(8,4))
ax = fig.add_subplot(projection='3d')
x = np.linspace(0,1,100)
y = np.linspace(0,2,100)
X, Y = np.meshgrid(x, y)
Z = np.empty_like(Y)
Z[Y < 1] = 2 * Y[Y < 1]
Z[Y >= 1] = 10 * Y[Y >= 1] - 8 # different slope... | python|arrays|numpy|matplotlib|multidimensional-array | 1 |
14,821 | 56,385,211 | Your session crashed after using all available RAM in Google Colab | <p>I am trying to get this to run in google colab <a href="https://github.com/oawiles/X2Face/blob/master/UnwrapMosaic/Face2Face_UnwrapMosaic.ipynb" rel="nofollow noreferrer">https://github.com/oawiles/X2Face/blob/master/UnwrapMosaic/Face2Face_UnwrapMosaic.ipynb</a>, </p>
<p>I was able to get it to run and display resu... | <p>Try to change settings,</p>
<p><strong>Go to</strong> run-time->change run-time type->hardware accelerator->select option GPU or TPU</p>
<p>I think this might help.</p> | python-2.7|pytorch|google-colaboratory|torchvision | 1 |
14,822 | 56,387,591 | Lasso Regression: The continuous heavy step function | <p>From many documents, I have learned the recipe of Ridge regression that is:</p>
<pre><code>loss_Ridge = loss_function + lambda x L2 norm of slope
</code></pre>
<p>and the recipe of Lasso regression that is: </p>
<pre><code>loss_Lasso = loss_function + lambda x L1 norm of slope
</code></pre>
<p>When I have read t... | <p>From the link that you provided,</p>
<pre><code>if regression_type == 'LASSO':
# Declare Lasso loss function
# Lasso Loss = L2_Loss + heavyside_step,
# Where heavyside_step ~ 0 if A < constant, otherwise ~ 99
lasso_param = tf.constant(0.9)
heavyside_step = tf.truediv(1., tf.add(1., tf.exp(tf.... | python|tensorflow|machine-learning|lasso-regression | 1 |
14,823 | 56,302,582 | How to do column string concatenation including space separator in Pandas dataframe? | <p>I am a Pandas DataFrame as follows:</p>
<pre><code>df = pd.DataFrame({
'id': [1,2 ,3],
'txt1': ['Hello there1', 'Hello there2', 'Hello there3'],
'txt2': ['Hello there4', 'Hello there5', 'Hello there6'],
'txt3': ['Hello there7', 'Hello there8', 'Hello there9']
})
df
id txt1 txt2 ... | <p>You can also add separator between columns:</p>
<pre class="lang-py prettyprint-override"><code>df['alltext'] = df['txt1'] + ' ' + df['txt2'] + ' ' + df['txt3']
</code></pre>
<p>Or filter by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html" rel="nofollow noreferrer"><c... | python|pandas | 7 |
14,824 | 55,880,098 | How to find mean of n previous rows in a column in pandas based on date criteria? | <p>I have a dataset that looks like this:</p>
<pre><code>value1 value2 value3 date
17 21 22 2005-04-01 12:05:00
19 20 24 2005-04-01 12:06:00
16 26 23 2005-04-01 12:07:00
</code></pre>
<p>I need to transform it somehow, so the values of each row with date ending with .05:00 (5th minute... | <p>This will create a rolling mean on 60 minutes windows (makes sure, that <code>date</code> column is <code>datetime64[ns]</code> dtype, if not, convert it beforehand), then you can select the necessary rows with <code>.loc[]</code>:</p>
<pre><code>df.rolling('H', on='date').mean().loc[lambda x: x['date'].dt.minute =... | python|pandas | 0 |
14,825 | 64,721,878 | Can we strictly reproduce Alexnet network architecture with Tensorflow? | <p>I want to strictly reproduce the <a href="https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf" rel="nofollow noreferrer">Alexnet</a> neural network with Tensorflow 2:</p>
<p><a href="https://i.stack.imgur.com/YbJw9.png" rel="nofollow noreferrer"><img src="https://i.s... | <p>It is not very complicated if you use Functional API. Here I only demonstrate how to split it in two, or in many as you like</p>
<pre class="lang-py prettyprint-override"><code>inp = tf.keras.Input(input_shape=shape)
x1 = Layers.Conv2D(filters_1, kernel_size_1)(inp)
x2 = Layers.Conv2D(filters_2, kernel_size_2)(inp)
... | python|tensorflow|distributed-computing|imagenet | 0 |
14,826 | 64,625,175 | Preprocessing test images using opencv for prediction | <p>I am working on a dataset of gray images that are saved under RGB format. I trained VGG16 on this dataset, and preprocessed them this way:</p>
<pre><code>train_data_gen = ImageDataGenerator(rescale=1./255,rotation_range = 20,
width_shift_range = 0.2,
... | <p>The error was in the interpolation parameter of resize function. It should be <code>cv2.INTER_NEAREST</code> instead of <code>cv2.INTER_AREA</code>.</p> | tensorflow|opencv|keras|conv-neural-network|vgg-net | 1 |
14,827 | 64,619,912 | How do I concatenate two tensorflow tensors of the same size in one dimension but different size in the other? | <p>I'm trying to carry out one-hot encoding with the tensorflow API. To do so you need to specify the number of distinct values up front so I've had to iterate through each variable and count the distinct values in each case. This leaves me with a one-hot encoded tensor for each variable that I want to join back togeth... | <p>Axis should be 1 instead of 0:</p>
<pre><code>import tensorflow as tf
x = tf.random.uniform([100, 100])
y = tf.random.uniform([100, 2])
z = tf.concat((x, y), 1)
</code></pre> | tensorflow|concatenation|one-hot-encoding | 2 |
14,828 | 64,988,086 | how to melt the column with group by in python | <p>I have data with 4 columns . I want to perform group by with melt.</p>
<pre><code>data:
col1 col2 col3 col4
de1 do1 2020-11-24 vt1
de1 do1 2020-11-24 vt2
de1 do2 2020-11-24 vt1
de1 do2 2020-11-24 vt2
</code></pre>
<p>I want to get output like below:</p>
<pre>... | <p>Will it not be easier to do a pivot_table?</p>
<pre><code>import pandas as pd
data={'col1':['de1','de1','de1','de1'],
'col2':['do1','do1','do2','do2'],
'col3':['2020-11-24','2020-11-24','2020-11-24','2020-11-24'],
'col4':['vt1','vt2','vt1','vt2']}
df=pd.DataFrame(data)
pivot=pd.pivot_table(df... | python|pandas-groupby|melt | 1 |
14,829 | 64,683,018 | Error: "not found in axis" when droping list of index values | <p>I am trying to drop two days every year from a dataframe with hourly values from 6am-8pm for dates from the 15.07 to 20.10. Therefore, I created a list with all the dates that should be dropped like this:</p>
<pre><code>
for i in range(0,6):
Year = 1999 + i
drop_list.append(str(Year)+'-07-15')
drop_list.... | <p>If you want to drop from a datetime index, you need to pass datetimes.</p>
<p>E.g.</p>
<pre><code>>>> s = pd.Series([1,2,3], index=pd.to_datetime(['2020-01-01', '2020-01-02', '2020-01-03']))
>>> s
2020-01-01 1
2020-01-02 2
2020-01-03 3
dtype: int64
>>> s.drop(pd.to_datetime(['20... | pandas | 0 |
14,830 | 40,279,723 | Rolling Mean in Pandas | <p>I have this initial DataFrame in Pandas</p>
<pre><code> A B C D E
0 23 2015 1 14937 16.25
1 23 2015 1 19054 7.50
2 23 2015 2 149... | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html" rel="nofollow"><code>rolling</code></a> (need at least <a href="... | python|pandas|dataframe|group-by|mean | 2 |
14,831 | 39,959,925 | Amending datetime format while parsing from csv read - pandas | <p>I am reading a csv file (SimResults_Daily.csv) into pandas, that is structured as follows:</p>
<pre><code>#, Job_ID, Date/Time, value1, value2,
0, ID1, 05/01 24:00:00, 5, 6
1, ID2, 05/02 24:00:00, 6, 15
2, ID3, 05/03 24:00:00, 20, 21
</code></pre>
<p>etc.
As the datetime format cannot be read by pandas pa... | <p>You can use:</p>
<pre><code>import pandas as pd
import io
temp=u"""#,Job_ID,Date/Time,value1,value2,
0,ID1,05/01 24:00:00,5,6
1,ID2,05/02 24:00:00,6,15
2,ID3,05/03 24:00:00,20,21"""
dateparse = lambda x: pd.datetime.strptime(x.replace('24:','00:'), '%m/%d %H:%M:%S')
#after testing replace io.StringIO(temp) to f... | python|date|csv|parsing|pandas | 2 |
14,832 | 44,076,945 | Choosing initial values for variables and parameters for optimizers in tensorflow | <p>How do people typically choose initial values for their variables and parameters? Do we just tinker till it works?</p>
<p>I was following the Getting Started tutorial for tensorflow, and was able to train the linear model in it. However, I noticed that the starting values for the variables W, b were reasonably clos... | <p>Some of the famous initializers for Convolutional Neural Networks:</p>
<p><strong>Glorot Normal</strong>: Also called Xavier. Normal distribution centered on 0 with stddev = sqrt(2 / (fan_in + fan_out)) where fan_in is the number of input units in the weight tensor and fan_out is the number of output units in the w... | tensorflow | 0 |
14,833 | 69,526,671 | Casting types of all columns starting with Pandas | <p>I have a df and several columns starting with <code>'comps'</code> and I want to cast their types to float.</p>
<p>I tried</p>
<pre><code>df = df.convert_dtypes() - Not Ok
df = df.columns.startswith('comps').astype(float) - Failed
</code></pre>
<p>Is there a fast way to do it?</p>
<p>Thanks</p> | <p>Get all columns starting by <code>comps</code> and casting to floats:</p>
<pre><code>d = dict.fromkeys(df.columns[df.columns.str.startswith('comps')], 'float')
d = dict.fromkeys(df.filter(regex='^comps').columns, 'float')
df = df.astype(d)
print (df)
</code></pre>
<p>Or:</p>
<pre><code>m = df.columns.str.startswith... | pandas | 1 |
14,834 | 40,863,006 | What is the parameter "state_is_tuple" in TensorFlow used for? | <p>I'm trying to figure out the structure of tensorflow code (r0.11) and have problems understanding the "state_is_tuple" parameter used in RNNs (currently looking at LSTMs).</p>
<p>In this post <a href="https://stackoverflow.com/questions/39112622/how-do-i-set-tensorflow-rnn-state-when-state-is-tuple-true">How do I s... | <p>This is a change to an earlier implementation of the rnn_cell-class in which state was a concatenation of the hidden neurons and the cell state. In I think Release 0.11 this was changed to a preferred version of (hidden neurons, cell state), thus as a tuple.</p>
<p>In the future the old concatenation way will be de... | python|parameters|tensorflow|recurrent-neural-network|lstm | 8 |
14,835 | 40,803,478 | Multiprocessing with class functions and class attributes | <p>I have a pandas Dataframe, that has millions of rows and I have to do row-wise operations. Since I have a Multicore CPU, I would like to speed up that process using Multiprocessing. The way I would like to do this is to just split up the dataframe in equally sized dataframes and process each of them within a separat... | <p>It should be possible as long as all elements in your class (that you pass to the sub-processes) is picklable. That is the only thing you have to make sure. If there are any elements in your class that are not, then you cannot pass it to a Pool. Even if you only pass <code>self.x</code>, everything else like <code>s... | oop|pandas|multiprocessing|python-3.5 | 0 |
14,836 | 53,983,072 | Arrange bar chart in ascending / descending order | <p>I have a random forest feature importance procedure. All the feature importance parameters have been generated for each variable. I have also plotted it on a horizontal bar graph. </p>
<p>Now I would like to sort the bars into ascending / descending order. How do I do it? </p>
<p>My code is as follow:</p>
<pre><c... | <p>You could do something like this!
Feed <code>allVarlist</code> with your feature names. </p>
<pre><code>plt.figure(figsize=(14,16))
df=pd.DataFrame({'allvarlist':range(5),'importances':np.random.randint(50,size=5)})
df.sort_values('importances',inplace=True)
df.plot(kind='barh',y='importances',x='allvarlist',color=... | python|scikit-learn|visualization|sklearn-pandas | 2 |
14,837 | 54,071,973 | Extract value of pandas dataframe with differents index columns according to the rows | <p>I have this dataframe with <strong>1 000 000 rows</strong> and 1<strong>00 columns</strong>.</p>
<pre><code> 0 1 2 3 4 5 6 ...
0 2.645751 2.828427 3.000000 3.000000 3.000000 3.000000 3.000000
1 2.645751 2.828427 2.828427 3.000000 3.000000 3.0... | <p>You can simply use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a>:</p>
<pre><code>finalListofList = df.loc[0,list_idx[0][0]].values
# array([3. , 3. , 3.31662479])
</code></pre>
<p>Note that the extra... | python|pandas|list | 2 |
14,838 | 54,056,316 | Pandas value error when converting JSON into an excel | <p>JSON File:-</p>
<pre><code> {"customer_name":"james",
"customer_id":41
}
</code></pre>
<p>my Python code below gives the error message :-</p>
<pre><code> " ValueError: If using all scalar values, you must pass an index "
</code></pre>
<p>Please let me know what is the issue in the below code.</p>
<pre><cod... | <p>You can try:</p>
<pre><code>pandas.read_json("p1.json", typ = 'series')
</code></pre>
<p>It creates pd.Series</p> | python|json|python-3.x|pandas | 2 |
14,839 | 66,332,241 | Pandas check if dataframe column contains value from list (different lengths) | <p>I have the following DataFrame <code>df1</code>:</p>
<pre><code> A
0 E2
1 27
2 99
3 NaN
4 20
5 14
</code></pre>
<p>And the following list:</p>
<pre><code>list1 = [14, 61, 27, 82, 79, 75, 44, 10, 'E2','E9']
</code></pre>
<p>I want to add/append a new column called 'B' to <code>df1</code> that checks whether the valu... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code></a>, only necessary match numeric with numbers types for correct working:</p>
<pre><code>df['B'] = df['A'].isin(list1)
</code></pre>
<p>If numeric are stored like strings... | python|pandas|list|dataframe | 2 |
14,840 | 52,693,136 | more pythonic way - pandas dataframe manipulation | <p>Say I have a dataframe called <code>vals</code> as follows:</p>
<p><strong>id</strong>..........<strong>date</strong>..........<strong>min_date</strong>..........<strong>max_date</strong></p>
<p>1..........2016/01/01..........2017/01/01..........2018/07/01
2..........2017/02/02..........2017/01/01..........2017/04... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.between.html" rel="nofollow noreferrer"><code>pd.Series.between</code></a>:</p>
<pre><code>vals['within_range'] = vals['date'].between(vals['min_date'], vals['max_date'])
</code></pre> | python|pandas|performance|dataframe|series | 3 |
14,841 | 52,687,216 | How can I give an index value to a specific date in python? | <p>I want to assign indicess to the dates in python with respect to a fixed date. For e.g., an index of 1 to 20130101, index of 2 to 20130102 and so on upto 20181231. These dates are in a python dataframe. The indices could be overwritten on the dates in the dataframe. Could someone please suggest how to do this?</p> | <p>You can subtract <code>date</code> objects. That gives a timedelta that's easily converted to the number of days. From your explanation this sounds exactly like what you're looking for:</p>
<pre><code>>>> (datetime.date(2013, 1, 2)-datetime.date(2013, 1, 1)).days
1
>>> (datetime.date(2013, 1, 31)-... | python|pandas|datetime|series | 2 |
14,842 | 52,845,785 | load_model and Lamda layer in Keras | <p>How to load model that have lambda layer?</p>
<p>Here is the code to reproduce behaviour:</p>
<pre><code>MEAN_LANDMARKS = np.load('data/mean_shape_68.npy')
def add_mean_landmarks(x):
mean_landmarks = np.array(MEAN_LANDMARKS, np.float32)
mean_landmarks = mean_landmarks.flatten()
mean_landmarks_tf = tf.... | <p>You need to pass <code>custom_objects</code> argument to <code>load_model</code> function:</p>
<pre><code>model = load_model('model_file_name.h5', custom_objects={'MEAN_LANDMARKS': MEAN_LANDMARKS})
</code></pre>
<p>Look for more info in Keras docs: <a href="https://keras.io/getting-started/faq/#handling-custom-lay... | python|tensorflow|keras|deep-learning|keras-layer | 3 |
14,843 | 58,216,460 | How can I multiply words with numbers in a DataFrame? | <p>I have a DataFrame like this: </p>
<pre><code>print(df.words[0])
[('replacement', 1), ('shaver', 2)]
print(df.words[1])
[('filter', 2), ('purifier', 1), ('please', 2)]
</code></pre>
<p>I want to create a new column, called "all_words". The column, should represent the real strings, instead of numbers. </p>
<pre>... | <p>You will need to <code>apply</code> a function to join the tuples to a single string.</p>
<pre><code>df['all_words'] = df.words.apply(lambda x: ', '.join(', '.join([y[0]] * y[1]) for y in x))
</code></pre> | python|string|pandas | 3 |
14,844 | 69,104,443 | merge dataframes based on column A OR B | <p>I need to merge two dataframes, but the merge can be made on either two columns of the right-hand dataframe.</p>
<pre><code>df_1 = pd.DataFrame({'col' : ['a', 'b', 'c']})
df_2 = pd.DataFrame({'col_a' : ['a', 'b', np.nan], 'col_b' : ['z', np.nan, 'c']})
df_1.merge(df_2, how = 'left', left_on = 'col', right_on = 'col_... | <p>You could perform both merges and use <code>combine_first</code> to fuse the two merges:</p>
<pre><code>(df_1.merge(df_2, left_on='col', right_on='col_a', how='left')
.combine_first(df_1.merge(df_2, left_on='col', right_on='col_b', how='left'))
)
</code></pre>
<p>output:</p>
<pre><code> col col_a col_b
0 a ... | python|pandas|merge | 0 |
14,845 | 44,779,421 | group and filter pandas dataframe | <pre><code>OID,TYPE,ResponseType
100,mod,ok
100,mod,ok
101,mod,ok
101,mod,ok
101,mod,ok
101,mod,ok
101,mod,no
102,mod,ok
102,mod,ok2
103,mod,ok
103,mod,no2
</code></pre>
<p>I want to remove all OIDs that ever had no or no2 as their response.</p>
<p>I tried:</p>
<pre><code>dfnew = df.groupby('OID').filter(lambda x: (... | <p>You need add one <code>(</code> and <code>~</code> for invert booelan mask - but it is really slow:</p>
<pre><code>dfnew = df.groupby('OID').filter(lambda x: ~((x['ResponseType']=='no') |
(x['ResponseType']=='no2')).any() )
#her... | python|pandas|dataframe|filter | 2 |
14,846 | 60,985,567 | How to delete certain values in a column after Boolean indexing? | <p>I have a <code>df</code> as follows:</p>
<pre><code>dates values
2020-03-29 00:30:00 86.824
2020-03-29 00:45:00 86.923
2020-03-29 01:00:00 87.222
2020-03-29 01:15:00 87.52
2020-03-29 01:30:00 87.918
2020-03-29 01:45:00 88.415
2020-03-29 02:00:00 89.012
2020-03-29 02:15:00 89.807
2020-03-29 02:30:00 90.504
2020-03... | <p>Try</p>
<pre><code>df.loc[mask, 'dates'] = pd.NaT
df['dates'] = df['dates'].sort_values(ascending=True).tolist()
</code></pre> | python|python-3.x|pandas|dataframe | 1 |
14,847 | 61,041,144 | Adding a new row with additional value in only one column | <p>I have a DataFrame as follows:</p>
<pre><code>Name | Year | Score | Time
Bob 2000 5 8
Jan 2000 6 6
Bob 2001 4 7
Jan 2001 8 8
Carl 2001 2 4
Bob 2002 5 7
Jan 2002 6 9
Carl 2002 7 4
</code></pre>
<p>As you can see, Carl has no entry for <co... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html" rel="nofollow noreferrer"><code>DataFrame.unstack</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code... | python|pandas|dataframe | 3 |
14,848 | 60,991,965 | Insert Data and conditions on timestamp - Pandas Python | <p>The column Flag correspond to the appearance of an alarm with its begin and the end with the timestamp column corresponding.</p>
<p>Rule: Each begin and the following end <strong>must be in the same date</strong> !</p>
<p>I have this piece of dataframe : </p>
<pre><code> Flag Timestamp
1 be... | <p>You can try the following:</p>
<ul>
<li><p>Group the dataframe by 2 rows. This <a href="https://stackoverflow.com/a/57055020/10041823">discussion</a> explains how.</p></li>
<li><p>For each group: we check the dates are the same day.</p>
<ul>
<li>The length on a groupby let us know</li>
<li>If the two dates are the... | python|pandas|loops|datetime|timestamp | 0 |
14,849 | 71,470,672 | Split a cell in two rows by delimiter | <p>I have this data</p>
<pre><code>df = pd.DataFrame(data={'var1':['A','B','C', 'D'], 'var2':['something','something#else','something#else','something']})
var1 var2
0 A something
1 B something#else
2 C something#else
3 D something
</code></pre>
<p>I need to split the cells by '#' in tw... | <p>IIUC, you could do:</p>
<pre><code>(df
.assign(var2=df['var2'].str.split('#'))
.explode('var2')
.assign(var1=lambda d: d['var1'].mask(d['var1'].duplicated(keep=False),
d['var1']+'.'+d.groupby('var1').cumcount().add(1).astype(str)))
)
</code></pre>
<p>Alternative syntax:</p>
... | python|pandas | 1 |
14,850 | 71,579,983 | How can I import several Excel sheets into separate pandas dataframes? | <p>I've reviewed this post: <a href="https://stackoverflow.com/questions/58563546/pandas-save-multiple-sheets-into-separate-dataframe">Pandas: Save multiple sheets into separate dataframes</a>, however it doesn't seem to address my problem.</p>
<p>So this creates a dictionary with sheet names as keys, and dataframes as... | <p>To create dynamically variables, you have to use <code>globals()</code> or <code>locals()</code> (which is strongly discouraged). The <code>dict</code> version is better.</p>
<pre><code>sheets = pd.read_excel('Data Series.xlsx',sheet_name=None)
for sheet, dataframe in sheets.items():
globals()[f'df_{sheet}'] = da... | python|pandas | 0 |
14,851 | 71,729,997 | Numpyic way to take the first N rows and columns out of every M rows and columns from a square matrix | <p>I have a 20 x 20 square matrix. I want to take the first 2 rows and columns out of every 5 rows and columns, which means the output should be a 8 x 8 square matrix. This can be done in 2 consecutive steps as follows:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
m = 5
n = 2
A = np.arange(... | <p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.ix_.html" rel="nofollow noreferrer"><code>np.ix_</code></a> to retain the elements whose row / column indices are less than 2 modulo 5:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
m = 5
n = 2
A = np.arange(400).re... | python|arrays|python-3.x|numpy|indexing | 3 |
14,852 | 42,375,276 | Tensorflow autoencoder: How to get representative output? | <h1>Setup</h1>
<p>I build an autoencoder with Tensorflow for images. My images are around 30 Pixels in length and width. I am using 5 layers:</p>
<ol>
<li>Input layer</li>
<li>Encoder layer with 256 neurons with linear functions. (This layer is supposed to function sort of as a preprocessing PCA.)</li>
<li>Encoder la... | <p>Your network is clearly not training</p>
<ul>
<li>Your Autoenconder Layers are not symmetric </li>
<li>Don't use sigmoid, use ReLU</li>
<li>Use a better initialization technique (the specific distribution depends on the activation function)</li>
<li>Share the weight of the Encoder and Decoder layers </li>
</ul> | python|machine-learning|tensorflow|computer-vision|autoencoder | 0 |
14,853 | 42,549,546 | reading textfile returning empty variable in tensorflow | <p>I have a text file which has 110 rows and 1024 columns of float values. I am trying to load the textfile and it doesnt read any thing. </p>
<pre><code>filename = '300_faults.txt'
filename_queue = tf.train.string_input_producer([filename])
reader = tf.TextLineReader()
_,a = reader.read(filename_queue)
#x = np.loadtx... | <p>Firstly - <code>tf.shape(a) == []</code> doesn't mean that variable is empty. All scalars and strings have shape <code>[]</code>. </p>
<p><a href="https://www.tensorflow.org/programmers_guide/dims_types" rel="nofollow noreferrer">https://www.tensorflow.org/programmers_guide/dims_types</a></p>
<p>May be you can che... | text|tensorflow|readfile | 0 |
14,854 | 42,236,808 | Unpack Set in Dataframe Value and Duplicate into Row | <p>There is a pandas dataframe with a column of sets that maybe of any length:</p>
<pre><code>n = np.nan
stack1 = pd.DataFrame.from_dict(
{'letter1': ['a','b','c','y'],
'letter2': [ 'o','p', 'q', 'y'],
'overlap': [ {'v'},{'c'}, {'c'}, {'v', 'c'}]
})
stack1.reset_index(inplace=True, drop... | <p>Try this:</p>
<pre><code>In [32]: col_to_unpack = 'overlap'
In [33]: df = stack1.copy()
In [34]: pd.DataFrame({
...: col:np.repeat(df[col].values, df[col_to_unpack].str.len())
...: for col in df.columns.difference([col_to_unpack])
...: }).assign(**{col_to_unpack:np.concatenate(df[col_to_unpa... | python|pandas | 1 |
14,855 | 69,950,493 | How to align 2 columns in a pandas dataframe | <p>I'm trying to align the 2 columns in my dataframe such that wherever the 2nd column has the same value as the first column it will be same value on the same row as the first column. Wherever there is no match to the 1st column, I would like the 2nd column to have a default "0" value placed in. I have some ... | <p>Here you go:</p>
<pre class="lang-py prettyprint-override"><code>df["col2"] = df.col1.where(df.col1.isin(df.col2), 0)
</code></pre>
<p>Output:</p>
<pre class="lang-py prettyprint-override"><code>In [5]: df["col2"] = df.col1.where(df.col1.isin(df.col2), 0)
In [6]: df
Out[6]:
col1 col2
0 ... | python|pandas|dataframe | 2 |
14,856 | 43,265,098 | Plot implicit surface from arrays in matplotlib | <p>Suppose I have four one-dimensional numpy arrays, <code>x</code>, <code>y</code>, <code>z</code>, and <code>value</code>. The point <code>(x[i],y[i],z[i])</code> is part of the surface if and only if <code>value[i]=0</code>. Is there a way to plot this surface in matplotlib?</p> | <p>you can apply boolean indexing on numpy arrays x,y,z like shown below.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x = np.random.random(10)
y = np.random.random(10)
z = np.random.random(10)
value = np.random.randint(2,size=10)
fig = plt.figure()
ax = f... | python|numpy|matplotlib | 1 |
14,857 | 72,175,044 | Converting daily OHLC price data to monthly with pandas | <p>I'm trying to convert a daily OHLC price of a stock to monthly with the following code:</p>
<pre class="lang-py prettyprint-override"><code>def daily_to_monthly_for_one_stock(path):
df = pd.read_csv(path)
logic = {'<Open>' : 'first',
'<High>' : 'max',
'<Low>' : '... | <p>IIUC, add <code>'DTYYYYMMDD': 'first'</code> to your <code>logic</code> dict.</p>
<p>Example:</p>
<pre><code>>>> df
DTYYYYMMDD Open High
0 2010-08-02 10 11
1 2010-08-03 13 14
2 2010-08-04 15 16
>>> logic
{'DTYYYYMMDD': 'first', 'Open': 'first', 'High': 'max'}
>>> df... | python|pandas | 1 |
14,858 | 72,256,648 | more efficient column filling along rows in pandas dataframe | <p>I am building a matrix of 1 and -1 based on the words in an existing column. It is for a basic neural network. the data is setup as follows:</p>
<pre><code>data_table data_table_final
index word_list index word_list cat hat mouse house run in... | <p>Scikit-learn has a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html" rel="nofollow noreferrer"><code>CountVectorizer</code></a> class that you can use for this purpose. By default, it returns the counts for each non stop-word as integers, but you can eas... | python|pandas | 1 |
14,859 | 72,190,471 | find intersection between list and multiple lists from dataframe | <p>I am labeling data based on dict. the dict looks like <code>{"tpoic1":["item1","item2"...],"tpoic2":["item1",....]....}</code>. I am reading this dict as dataframe with columns representing topics and list data. In my dataset I have a column named hashtags which in ... | <p>If you <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html?msclkid=0a82a5bcd08511ec95eae203578f88e9" rel="nofollow noreferrer">explode</a> your dataframe first:</p>
<pre><code>clusters_df = clusters_df.explode("data", ignore_index=True)
</code></pre>
<p>You can... | python|pandas|dataframe | 0 |
14,860 | 50,561,577 | Mapping column value based on another column in python | <p>I am trying to change column value depends from the other column along its row then merge it to an existing excel file using the <code>ADSL</code> column as my key.</p>
<p>I have a Data like this:</p>
<pre><code>ADSL Status Result
2/134 WO No Server Answer
1/239 WO Faulty
2/94 FA ... | <p>I believe need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a> by <code>Series</code>:</p>
<pre><code>df2['Status'] = df2['Status'].map(df1.set_index('Result')['Status'])
</code></pre>
<p>If some values are not match is possible ... | python|pandas|openpyxl|xlsxwriter | 1 |
14,861 | 62,714,354 | Emailing Pandas df resulting into poor formating | <p>I wish to email a pandas df as html to a group. Below is my code. This code works but, the formatting is very poor. Is there any method/function to beautify the output?</p>
<pre><code>import smtplib
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart impo... | <p>You can directly export the dataframe to html:</p>
<pre><code>pd.DataFrame({
'a': np.random.random(3),
'b': np.random.random(3),
'c': np.random.random(3),
}).to_html()
</code></pre>
<p>this produces:</p>
<pre><code><table border="1" class="dataframe">
<thead>
<tr ... | python|pandas | 1 |
14,862 | 54,593,864 | asyncio + asyncpg + pandas: obtain pandas.df with async selects from db - ERROR | <p>Edited my code - NOW it WORKS
I'm trying to obtain some date from my Postgres db through asyncpg connection pool asynchronously.
Basically my db contain about 100 different tables (per city) and i'm trying to gather all the data in one frame as fast as it possible.</p>
<pre><code> import pandas as pd
import ... | <p><code>asyncio.gather</code> accepts coroutines as individual arguments, and you are sending it a list of tasks. You have to use the <code>*</code> operator to call <code>gather</code> correctly:</p>
<pre><code> tasks = await asyncio.gather(*tasks)
</code></pre> | python|pandas|python-asyncio|asyncpg | 1 |
14,863 | 54,253,104 | How to load model and weights using tensorflow.js in browser saved on Node.js? | <p>Source: <a href="https://js.tensorflow.org/tutorials/model-save-load.html" rel="nofollow noreferrer">Save / load model docs</a></p>
<p>I have trained multiple models on nodeJS side and saved them to using "file://"</p>
<p>So I have 1 JSON file, and 1 binary file with weights</p>
<p>But to load this model on brows... | <p>The weight files are loaded automatically by using the same path as the model file.
With your example the model file has url as following:
<a href="http://model-server.domain/download/model.json" rel="noreferrer">http://model-server.domain/download/model.json</a></p>
<p>The loader will load the weight files from fo... | tensorflow|neural-network|tensorflow.js | 5 |
14,864 | 54,439,966 | How to update dataframe value in multiprocessing | <p>I want to update pandas </p>
<p>Hello, I want to compare the speeds of single-core and multicore in pandas dataframe calculations.
The following cases are given, The column'c' in the 'i'th-row is the average of the values of 'a' from 'i-9'-row to 'i'th-row.</p>
<pre><code>from multiprocessing import Process, Va... | <p>You may look at <a href="https://github.com/jmcarpenter2/swifter" rel="nofollow noreferrer">swifter</a> as well, iit applies functions using multiprocessing <strong>IF it helps in faster code execution</strong>.</p>
<p><strong>In your case it is a terrible idea</strong>, 10 is a really small amount of data so distr... | python|pandas|multiprocessing | 0 |
14,865 | 52,426,807 | Python Pandas String matching from different columns | <p>I have a excel-1(Raw Data) and excel-2(reference Document)</p>
<p>In excel-1 the "Comments" should be matched against excel-2 "Comments" column.If the string in excel-1 "comments" column contains any of the substring in excel-2 "comments" column,the Primary reason and Secondary reason from excel-2 should be populat... | <p>for value in df['Comments']:</p>
<pre><code>string = re.sub(r'[?|$|.|!|,|;]',r'',value)
for index,value in df1.iterrows():
substring = df1.Comment[index]
if substring in string:
df['Primary Reason']= df1['Primary Reason'][index]
df['Secondary Reason']=df1['Secondary Reason'][index]
</co... | python|excel|string|pandas | 0 |
14,866 | 60,451,053 | Pandas search replace using two datasets | <p>I have a situation where I need to search replace values using two datasets basis on the first column or pandas default index.
My df1 :</p>
<pre><code> id1 id2 id3 id4
0 1 2 3 4
1 3 4 5 6
</code></pre>
<p>My df2</p>
<pre><code> id_df2
0 500
1 1000
2 2000
3 3000
4 4000
5 ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer"><code>DataFrame.replace</code></a> by <code>Series</code> created be select:</p>
<pre><code>df = df1.replace(df2['id_df2'])
print (df)
id1 id2 id3 id4
0 1000 2000 3000 4000
1... | python-3.x|pandas|replace|match | 2 |
14,867 | 60,574,858 | Python: counting frequency for two columns with the same possible values | <p>I have two columns with <em>two possible values (0 or 1)</em>. One column is the <em>predicted value</em> and the other is the <em>real value</em>. Something like this.</p>
<pre><code>ID Predicted Real
1 1 1
2 1 0
3 0 0
4 0 1
5 1 0
6 1 0
</code></p... | <p>You can apply <code>pd.value_counts</code> to the dataframe (assuming ID is the index and not a column, if not set ID as index first)</p>
<pre><code>out = df.apply(pd.value_counts).rename_axis('Value').reset_index()
</code></pre>
<hr>
<pre><code> Value Predicted Real
0 0 2 4
1 1 ... | python|pandas|pandas-groupby|frequency | 0 |
14,868 | 60,568,604 | How to shape input array appropriately for ML | <p>I apologize in advance if this question seems silly but I am trying to understand a <a href="https://machinelearningmastery.com/how-to-develop-lstm-models-for-time-series-forecasting/" rel="nofollow noreferrer">machinelearningmastery blog</a> about LSTM type ML algorithms, more specifically on how the input data get... | <p>The problem is mentioned in the error in this case. The problem is that you are trying to reshape the array to a specific shape but it is not possible. The array <strong>X</strong> has 2499 elements and 2499 cannot be reshaped to a (357,2,2,1) shape. The product of the numbers in the shape is the number of elements ... | python|tensorflow|machine-learning|keras|lstm | 0 |
14,869 | 72,575,010 | python pandas normalization | <p>I have a csv file where one field should be normalized over two records:</p>
<pre><code> +-----+---------+
| id | field |
+-----+---------+
| 1 | A-a,B-b |
| 2 | C-c |
+-----+---------+
</code></pre>
<p>so some records are comma separated with two tuples
to become different records<... | <pre><code>df.field = df.field.str.split(',')
df1 = df.explode('field')
df1[['field_1', 'field_2']] = df1.field.str.split('-', expand = True)
df1
id field field_1 field_2
0 1 A-a A a
0 1 B-b B b
1 2 C-c C c
</code></pre> | python|pandas|dataframe|database-normalization | 0 |
14,870 | 72,584,830 | Trying to open .bson file and read to pandas df but getting 'bson.errors.InvalidBSON: objsize too large' first time using .bson | <p>#This is my code</p>
<pre><code>import pandas as pd
import bson
FILE="users_(1).bson"
with open(FILE,'rb') as f:
data = bson.decode_all(f.read())
main_df=pd.DataFrame(data)
main_df.describe()
</code></pre>
<p>#This is my .bson file</p>
<pre><code>[{'_id': ObjectId('999f24f260f653401b'),
'isV2': ... | <p>If the main goal here is to read the data into a pandas DataFrame you could indeed format the data to json and use <a href="https://dfproj.readthedocs.io/en/latest/api/bson/json_util.html" rel="nofollow noreferrer"><code>bson.json_util.loads</code></a>:</p>
<pre><code>import pandas as pd
from bson.json_util import l... | python|pandas|bson | 0 |
14,871 | 72,655,669 | tensorflow hub example throws an error when Float16 is enabled | <p>I am trying to load a model from Tensorflowhub using example code. It works perfect with the FP32. As soon as I add the tf.keras.mixed_precision.set_global_policy('mixed_float16') to enable mixed float, it raises an error. Looks like the dimension issue but then it works perfect with FP32. Here is the reproducible c... | <p>It is about target 'dtype' when float16 is enabled as the variable rules it trying to use the float16 then you just need to specify float32 as the model input required. I like to include channel numbers as the image properties when switching colors to transforming. Some functions work without channels number but for... | tensorflow|computer-vision|tensorflow-lite|tensorflow-hub | 1 |
14,872 | 72,493,464 | Vectorizing addition | <p>Let's say I have two numpy arrays <code>a[n,3]</code> and <code>b[m,3]</code></p>
<p>How do I calculate <code>c[n,m,3]</code> , without resorting to a <code>for</code> loop, such as:</p>
<p><code>c[i,j,:] = a[i,:] + b[j,:]</code></p> | <p>Try this:</p>
<pre class="lang-py prettyprint-override"><code>c = a[:, None, :] + b[None, :, :]
</code></pre> | python|numpy | 1 |
14,873 | 59,557,263 | Efficient way to reference one table from another | <p>I have the following two data frames:</p>
<pre><code>import numpy as np
import pandas as pd
df1 = pd.DataFrame({'name': np.repeat(['Brandon', 'Erica'], [3, 4]),
'date': ['2019-01', '2019-02', '2019-03', '2018-01', '2018-02', '2018-03', '2018-04'],
'value': [1,2,3,4,5,6,7]})
... | <p>I think the following would do what you're describing. It makes the assumption that the dates are sorted in ascending order within each <code>name</code> group, like in your example. You could enforce this with a sort, if it's not the case. As it avoids an explicit loop through the rows, it should be much faster at ... | python|pandas|dataframe | 1 |
14,874 | 59,893,471 | Correct way to iterate over a dataframe using multiple conditionals | <p>I have a dataset of football matches as a Pandas dataframe in the form below:</p>
<pre><code> Home Away Result HG AG
0 Liverpool Norwich City Liverpool 4 1
1 West Ham Man City Man City 0 5
2 AFC Bournemouth Sheffield United Draw 1 1
3 Bu... | <p>You can naturally get a formula per team, something like this:</p>
<pre><code>team_list = list(set(list(df.Home)+list(df.Away)))
d = {i:list(df.loc[(df.Home==i)|(df.Away==i),'Result'].map({i:'W','Draw':'D'}).fillna('L'))
for i in team_list}
</code></pre>
<p>Basically for each unique team name, we're getting... | python|pandas|dataframe | 3 |
14,875 | 58,143,637 | Tensorflow 2.0 can't use GPU, something wrong in cuDNN? :Failed to get convolution algorithm. This is probably because cuDNN failed to initialize | <p>I am trying to understand and debug my code. I try to predict with a CNN model developed under tf2.0/tf.keras on GPU, but get those error messages.
could someone help me to fix it?</p>
<p>here is my environmental configuration</p>
<pre><code>enviroments:
python 3.6.8
tensorflow-gpu 2.0.0-rc0
nvidia 418.x
CUDA 10.0... | <p>You have to check that you have the right version of CUDA + CUDNN + TensorFlow (also ensure that you have all installed).</p>
<p>A couple of examples of running configurations are presented below(<strong>UPDATE</strong> FOR <strong>LATEST</strong> VERSIONS OF <strong>TENSORFLOW</strong>)</p>
<ol>
<li><p>Cuda <code>1... | tensorflow|tensorflow2.0|nvidia|tensorflow2.x | 13 |
14,876 | 57,951,210 | How to insert today's date in SQL select statement using python? | <p>I'm trying to send today variable into SQL but it is not working.</p>
<pre><code>import datetime from date
today = date.today()
stmt = "select agent_email from customer_interaction_fact where to_date(DT) >= + today + ORDER BY CONVERSATION_CREATED_TIME DESC"
</code></pre> | <p>You don't have to compute today's date in Python. Just use the PostgreSQL function <a href="https://www.postgresql.org/docs/8.1/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT" rel="nofollow noreferrer"><code>CURRENT_DATE</code></a>:</p>
<pre><code>stmt = "SELECT ... WHERE TO_DATE(DT) >= CURRENT_DATE ..."
</c... | python|sql|pandas|postgresql | 4 |
14,877 | 57,834,128 | The input dimension of the LSTM layer in Keras | <p>I'm trying keras.layers.LSTM.
The following code works.</p>
<pre><code>#!/usr/bin/python3
import tensorflow as tf
import numpy as np
from tensorflow import keras
data = np.array([1, 2, 3]).reshape((1, 3, 1))
x = keras.layers.Input(shape=(3, 1))
y = keras.layers.LSTM(10)(x)
model = keras.Model(inputs=x, outputs=y... | <p>Check out the documentation for <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Input" rel="nofollow noreferrer">tf.keras.Input</a>. The syntax is as-</p>
<pre><code>tf.keras.Input(
shape=None,
batch_size=None,
name=None,
dtype=None,
sparse=False,
tensor=None,
**kwargs
)
</c... | tensorflow|keras|rank|dimension | 1 |
14,878 | 54,904,908 | How does LSTM convert character embedding vectors to sentence vector for sentence classification? | <p>I want to build a LSTM model for sentence classification using character embeddings. </p>
<p>I know how to do it using word embeddings where the model can learn the embeddings from word indexes but not sure how to do it with character embeddings.</p>
<p><strong>for word embeddings:</strong></p>
<pre><code>sentenc... | <p>It's exactly the same. No difference at all. </p>
<p>Transform the sentences into vectors of indices and go fit.</p>
<p><strong>Important things</strong>:</p>
<p>Don't make sentences starting with 0, your <code>vectors</code> should be:</p>
<pre><code>vectors = [[1,2,3,4,0,0,0,0,0]
[5,6,7,5,8,0,0,0,0]]... | python|tensorflow|keras|lstm | 2 |
14,879 | 54,984,421 | Two different type date compare, Python 3.6 | <p>I want to compare below two dates,</p>
<pre><code>publicationDate contains Timestamp('2018-05-25 00:00:00')
Type: pandas._libs.tslibs.timestamps.Timestamp
</code></pre>
<p>publicationDate getting from API Ressult:</p>
<pre><code>publicationDate = pd.to_datetime(Json_Data_1['publicationDate'])
datetime.date.toda... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.to_pydatetime.html#pandas.Timestamp.to_pydatetime" rel="nofollow noreferrer">to_pydatetime()</a> in order to convert Timestamp to python datetime</p> | python|python-3.x|pandas|datetime|dataframe | 2 |
14,880 | 55,132,135 | Calculating portfolio's value in time with pandas | <p>So I want to calculate (in a very simplified manner) how much would $10000 invested in a certain portfolio be worth in 20 years time. I have calculated the portfolio's return rates over the years, but I have trouble actually calculating that 'value in time' in pandas.</p>
<p>My dataframe looks like this:</p>
<pre>... | <p>It sounds like you want to calculate the value of an investment as it grows over time. Assuming the returns is the year-over-year return rate, try this:</p>
<pre><code>df['amount']=(df['Returns']+1).cumprod()*10000
</code></pre>
<p>The numbers I get match up for the first few rows but diverge after that. I'm not sur... | python|pandas | 2 |
14,881 | 49,532,511 | How to get the dates between two dates | <p>I have a start date and end date . I need to get all the dates in between these two dates. One more condition is it should return the dates based on split ways, ie it can be week basis, day basis, hour basis,Month basis</p>
<p>I have checked the pandas date_range function but its returning only the ending of all t... | <p>Here is a numpy solution using "business" day filtering with a custom <code>weekmask</code>:</p>
<pre><code>>>> all_days = np.arange('1970-02-05', '1970-05-08', dtype='M8[D]')
>>> week_start_end = all_days[np.is_busday(all_days, weekmask='Mon Sun')]
>>> week_start_end
array(['1970-02-08',... | python|python-3.x|pandas | 2 |
14,882 | 49,374,607 | How to plot graph in complicated pandas groupby? | <p>I have a DataFrame about rows-transaction like:</p>
<pre><code> Month Category Quantity
3 A 1
3 A 1
3 B 1
4 A 1
4 B 1
4 B 1
</code></pre>
<p>I used g... | <p>You'd want to <code>unstack</code> and then call <code>pd.DataFrame.plot</code>:</p>
<pre><code>df.groupby(['Month','Category'])['Quantity'].count().unstack().plot()
plt.show()
</code></pre>
<p>You get a graph with two lines, one per <code>Category</code>.</p> | python|pandas|matplotlib | 2 |
14,883 | 49,713,998 | Formatting String Digits in Python Pandas | <p>I have a pandas DataFrame which has 3 digits (string) such as '001' , '010' and '121'. I would like to replace any 1 digit and any 2 digit strings such as '001' , and '010' with just '1' and '10'.</p>
<p>How can I do this? I tried using the apply method (see below) but nothing changes.</p>
<p><code>df.ZIPCOUNTY_CA... | <p>Or use <code>str.replace</code> to remove leading zeros:</p>
<pre><code>df_ZIPCOUNTY_CA['county code']
#0 010
#1 001
#2 121
#Name: county code, dtype: object
df_ZIPCOUNTY_CA['county code'].str.replace('^0+', '')
#0 10
#1 1
#2 121
#Name: county code, dtype: object
</code></pre>
<p><code>^0+<... | python|python-3.x|pandas|dataframe | 3 |
14,884 | 49,345,578 | How to decide threshold value in SelectFromModel() for selecting features? | <p>I am using random forest classifier for feature selection. I have 70 features in all and I want to select the most important features out of 70. Below code shows the classifier displaying the features from most significant to least significant.</p>
<p>Code: </p>
<pre><code>feat_labels = data.columns[1:]
clf = Rand... | <p>I would try the following approach:</p>
<ol>
<li>start with a low threshold, for example: <code>1e-4</code></li>
<li>reduce your features using <code>SelectFromModel</code> fit & transform</li>
<li>compute metrics (accuracy, etc.) for your estimator (<code>RandomForestClassifier</code> in your case) for selecte... | python|pandas|numpy|machine-learning|scikit-learn | 4 |
14,885 | 73,362,355 | How do I apply conditional processing based on a prior row value per group | <p>I have a table like the below:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>account</th>
<th>month</th>
<th>bad</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>1</td>
<td></td>
</tr>
<tr>
<td>a</td>
<td>2</td>
<td>y</td>
</tr>
<tr>
<td>a</td>
<td>3</td>
<td></td>
</tr>
<tr>
<td>a</td>... | <p>A possible solution, based on the idea of propagating last valid observation forward to next valid (<a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.ffill.html" rel="nofollow noreferrer"><code>pandas.DataFrame.ffill</code></a>):</p>
<pre><code>df['been_bad'] = df.groupby('account')['bad'].ffill... | python|pandas|group-by|conditional-statements | 2 |
14,886 | 73,243,196 | filter dataframe where a value stays under a threshold for specified amount of time | <p>I have a time series dataset which is described as follows:</p>
<pre><code>timestamp,y
2019-08-01 00:00:00,772.0
2019-08-01 00:15:00,648.0
2019-08-01 00:30:00,652.0
2019-08-01 00:45:00,572.0
2019-08-01 01:00:00,604.0
2019-08-01 01:15:00,644.0
2019-08-01 01:30:00,544.0
...
</code></pre>
<p>What I am doing at the mome... | <p>Let's make your data worth looking at:</p>
<pre><code>df.loc[7] = ['2019-08-01 5:30:00', 900]
df.loc[8] = ['2019-08-01 8:30:00', 500]
df.loc[9] = ['2019-08-01 12:30:00', 900]
df.timestamp = pd.to_datetime(df.timestamp)
df = df.set_index('timestamp')
df = df.resample('15T').interpolate()
print(df)
# Output:
... | python|pandas | 1 |
14,887 | 67,243,218 | Accessing PyTorch modules - ResNet18 | <p>I am using a ResNet-18 coded as follows:</p>
<pre><code>class ResidualBlock(nn.Module):
'''
Residual Block within a ResNet CNN model
'''
def __init__(self, input_channels, num_channels,
use_1x1_conv = False, strides = 1):
# super(ResidualBlock, self).__init__()
super... | <p>this will work</p>
<pre><code>import torch.nn.utils.prune as prune
prune.random_unstructured(list(model.children())[0][0] , name = 'weight', amount = 0.3) # first conv layer
</code></pre> | python|deep-learning|neural-network|pytorch | 1 |
14,888 | 60,112,582 | How to divide a pandas dataframe into several dataframes by month and year | <p>I have a dataframe with different columns (like price, id, product and date) and I need to divide this dataframe into several dataframes based on the current date of the system (current_date = np.datetime64(date.today())).</p>
<p>For example, if today is 2020-02-07 I want to divide my main dataframe into three diff... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.tseries.offsets.DateOffset.html" rel="nofollow noreferrer"><code>offsets.DateOffset</code></a> for last 1mont and 3month datetimes, filter by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-ind... | python|pandas|python-2.7|dataframe | 1 |
14,889 | 60,142,710 | Plot a DataFrame based on grouped by column in Python | <p>Based on the code below, I'm trying to assign some columns to my DataFrame which has been grouped by month of the date and works well : </p>
<pre><code>all_together = (df_clean.groupby(df_clean['ContractDate'].dt.strftime('%B'))
.agg({'Amount': [np.sum, np.mean, np.min, np.max]})
... | <p>When you apply groupby function on a DataFrame, it makes the groupby column as index(ContractDate in your case). So you need to reset the index first to make it as a column.</p>
<pre><code>df = pd.DataFrame({'month':['jan','feb','jan','feb'],'v2':[23,56,12,59]})
t = df.groupby('month').agg('sum')
</code></pre>
<p>... | python|pandas|matplotlib|plot | 1 |
14,890 | 65,080,401 | Understanding indexes and column names in pandas | <p>I am trying to understand how to handle indexes and series and vice versa when using apply. Here is a much simplified example of my problem.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'name':["alice","bob","charlene","alice","bob","charlene",&q... | <p>I think everything can be done with <code>agg</code></p>
<p><code>df.groupby(pd.Grouper(key='date', freq='1D')).agg({'name': 'value_counts'}).rename(columns={'name': 'count'}).reset_index()</code></p>
<pre><code> date name count
0 2020-01-01 bob 3
1 2020-01-01 alice 2
2 2020-01-01 c... | python|pandas | 2 |
14,891 | 65,348,906 | How to merge dataframes on one column while aligning the other columns in common | <p>Consider two DataFrames:</p>
<pre><code>>>> df1 = pd.DataFrame({'key': [1, 2, 3, 4, 5],
'bar': ['w','x','y','z','h'],
'foo': ['A', 'B', 'C', 'D','E']})
>>> df2 = pd.DataFrame({'key': [1, 2, 3, 8, 9, 10],
'foo': [np.nan, np.nan, np.nan, 'I'... | <p>Let's try <code>concat</code> and <code>groupby</code>:</p>
<pre><code>(pd.concat((df1, df2.query('key>8')))
.groupby('key',as_index=False).first()
)
</code></pre>
<p>Output:</p>
<pre><code> key foo bar
0 1 A w
1 2 B x
2 3 C y
3 4 D z
4 5 E h
5 9 J NaN
6 10 ... | python|pandas|dataframe | 2 |
14,892 | 65,223,255 | Error intsalling tensorflow via pip install | <p>WARNING: Failed to write executable - trying to use .deleteme logic
ERROR: Could not install packages due to an EnvironmentError: [WinError 2] The system cannot find the file specified: 'c:\python38\Scripts\chardetect.exe' -> 'c:\python38\Scripts\chardetect.exe.deleteme'</p>
<p>I was trying to install Tensorflow ... | <p>According to <a href="https://www.codegrepper.com/" rel="nofollow noreferrer">https://www.codegrepper.com/</a> you can use these two:</p>
<p>In Windows</p>
<pre><code>python -m pip install -U pip --user
</code></pre>
<p>In Linux</p>
<pre><code>pip install -U pip --user
</code></pre> | tensorflow|installation|pip | 1 |
14,893 | 65,119,152 | Download .txt file and extract file name | <p>I am trying to download the file in Python from the url <a href="https://marketdata.theocc.com/position-limits?reportType=change" rel="nofollow noreferrer">https://marketdata.theocc.com/position-limits?reportType=change</a>.</p>
<p>I am able to convert it to DataFrame just by using:</p>
<pre><code>df = pd.read_csv('... | <p>if you are using the <code>requests</code> library, the information about the file is in the response header (a dictionary):</p>
<pre class="lang-py prettyprint-override"><code>response = requests.get('https://marketdata.theocc.com/position-limits?reportType=change')
print(response.headers['content-disposition'])
</... | python|pandas|download|python-requests | 2 |
14,894 | 50,020,744 | Python Delete rows of matrices with bool index like matlab | <p>I have the following problem.</p>
<p>Considering I have 9 x 9 sparse identity matrix <code>var</code> and a 3x3 boolean matrix <code>bol</code>, where the position (2,2) has the value False.</p>
<p>In matlab I can delete rows like this</p>
<pre><code> var1 = speye(9);
bol=false(3,3);
bol(3:3,1:3)=1;
... | <p>This reads a lot like someone coming from matlab to python. There are ways of pythonizing it.</p>
<pre><code>import numpy as np
from scipy import sparse
var1 = sparse.eye(9).tocsc()
# we can make our truth matrix much faster
bol = np.ones((3, 3), dtype='bool')
bol[1, 1] = False
</code></pre>
<p>In matlab to dele... | python|matlab|numpy | 1 |
14,895 | 63,785,086 | How to pad a legend in matplotlib | <p>I have the following code that uses <code>GeoPandas</code> to visualize columns on a shape file</p>
<pre><code>cols = ['UrbanPop','Murder','Assault','Rape']
for i in cols:
fig, ax = plt.subplots(figsize=(12,12))
merged.plot(column=i,
ax=ax,
legend=True,
legend_kwds={'label... | <p>What's the version of your <code>geopandas</code>? For <code>0.8.1</code>, you can simply pass a <code>pad</code> arg in <code>legend_kwds</code>.</p>
<pre class="lang-py prettyprint-override"><code>import geopandas as gpd
import matplotlib.pyplot as plt
gdf = gpd.read_file(gpd.datasets.get_path('naturalearth_lowre... | python|pandas|matplotlib|geopandas | 2 |
14,896 | 63,146,831 | What is the analytic interpretation for Tensorflow custom gradient? | <p>In the official <a href="https://www.tensorflow.org/api_docs/python/tf/custom_gradient" rel="nofollow noreferrer">tf.custom_gradient</a> documentation it shows how to define custom gradients for <code>log(1 + exp(x))</code></p>
<pre class="lang-py prettyprint-override"><code>@tf.custom_gradient
def log1pexp(x):
e ... | <p>The extra <code>dy</code> you are looking at is the value of activation itself. Because the optimizer equation if you look at requires you multiply the gradient with the output value. Hence, this is why that has been done.</p> | python|tensorflow|tensorflow2.0|gradient-descent | 0 |
14,897 | 67,995,888 | Pandas: List of maximum values of difference from previous rows in new column | <p>I want to add a new column 'BEST' to this dataframe, which contains a list of the names of the columns which meet these criteria:</p>
<ul>
<li>Subtract from the current value in each column the value in the row that is 2 rows back</li>
<li>The column that has the highest result of this subtraction will be listed in ... | <p>First use <code>shift</code> and <code>subtract</code> to get the diff, then replace the maximum values with the column name and drop the others.</p>
<pre><code>df['BEST'] = (
df.subtract(df.shift(2))
.apply(lambda x: [df.columns[i] for i,e in enumerate(x) if e==max(x)], axis=1)
)
A B C BEST
0 1... | python|pandas|dataframe | 3 |
14,898 | 67,712,531 | found many NaN values after combining two dataframe with the same number of rows | <p>I want to combine two dataframes:</p>
<p>df1:</p>
<pre><code> money house points day hour min sec
0 -0.099322 -0.023973 -0.830284 -0.078535 -0.479580 -0.590838 -1.519931
1 -0.100334 -0.023973 -0.391713 -0.078535 0.742059 0.680058 -1.230736
2 ... | <p>Both dataframes may not have same index number so you can use</p>
<pre><code>pd.concat([df1, df2], axis = 1, ignore_index=True)
</code></pre> | python|pandas|dataframe|concatenation | 0 |
14,899 | 61,497,115 | Add a parameter to eval function that is applied to pd.df | <p>I have a program like below, it works fine when each function has only one parameter.</p>
<pre><code>import pandas as pd
df = pd.DataFrame([1])
df.columns = ['number']
def add_one(x):
return x+1
def add_two(x):
return x+2
class Functions:
add_one = "add_one"
add_two = "add_two"
def main(df, fun... | <p>You can pass your arguments separately to the <code>.apply</code> function using the <code>args</code> <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.apply.html" rel="nofollow noreferrer">parameter</a> as shown below</p>
<pre><code>import pandas as pd
df = pd.DataFrame([1])
df.co... | python|pandas|dataframe|apply|eval | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.