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 |
|---|---|---|---|---|---|---|
1,100 | 46,740,584 | Python dataframe exploded list column into multiple rows | <p>I have a dataframe like this:</p>
<pre><code> desc id info
[a,b,c] 2 type
[u,v,w] 18 tail
</code></pre>
<p>Three columns: desc,id,info and desc is a list.I want this:</p>
<pre><code> des id info
a 2 type
b 2 type
... | <p>Here is one way</p>
<pre><code>df.set_index(['id', 'info']).desc.apply(pd.Series).stack()\
.reset_index(name = 'desc').drop('level_2', axis = 1)
id info desc
0 2 type a
1 2 type b
2 2 type c
3 18 tail u
4 18 tail v
5 18 tail w
</code></pre> | python|pandas|dataframe | 5 |
1,101 | 62,961,194 | How does BertForSequenceClassification classify on the CLS vector? | <p><strong>Background:</strong></p>
<p>Following along with this <a href="https://stackoverflow.com/questions/60876394/does-bertforsequenceclassification-classify-on-the-cls-vector">question</a> when using bert to classify sequences the model uses the "[CLS]" token representing the classification task. Accord... | <blockquote>
<p>Is the CLS token a regular token which has its own embedding vector that "learns" the sentence level representation?</p>
</blockquote>
<p>Yes:</p>
<pre class="lang-py prettyprint-override"><code>from transformers import BertTokenizer, BertModel
tokenizer = BertTokenizer.from_pretrained('bert-... | python|transformer-model|huggingface-transformers|bert-language-model | 6 |
1,102 | 63,025,291 | Align dataframe by row dates | <p>The df below has a series of columns that starts with a date column followed by value columns.</p>
<p>I would like to align all rows on the same data. The problem: not all columns have the same dates (some dates are missing) - see highlights in yellow. How can I realign this df so that all series are aligned to th... | <p>This is code to split sub-df and after then join these.</p>
<pre><code>import pandas as pd
df = pd.read_csv('test.csv')
# split df into sub-df
df1 = df[['DATE','Y','Y1D', 'Y5D', 'Y20D']].rename(columns={'DATE' : 'NEWDATE'})
df2 = df[['DATE_CITI', 'CITI_INDEX','DATE_GLOBAL' , 'GLOBALINDEX']].rename(columns={'DATE... | pandas | 0 |
1,103 | 67,989,995 | Python write function saves dataframe.__repr__ output but truncated? | <p>I have a dataframe output as a result of running some code, like so</p>
<pre><code>df = pd.DataFrame({
"i": self.direct_hit_i,
"domain name": self.domain_list,
"j": self.direct_hit_j,
"domain name 2": self.domain_list2,
"domain name cleaned": self... | <p>Try the syntax:</p>
<pre><code>with open('./filename.txt', 'w') as fo:
fo.write(f'{df!r}')
</code></pre>
<p>Another way of doing this export to csv would be to use a too like <a href="https://trymito.io/so" rel="nofollow noreferrer">Mito</a>, which full disclosure I'm the author of. It should allow you to export ... | pandas|database|dataframe | 0 |
1,104 | 67,701,440 | Pandas conditional rolling counter between 2 columns of boolean values | <p>thanks in advance for helping a python newbie like me.</p>
<p>I would like to achieve the following results in the column "count" without using a stupid slow for loop.</p>
<p>I am sure it is possible to vectorize that. Any suggestions ?</p>
<p>Thanks again !</p>
<pre><code> A B count
... | <p>You can try:</p>
<pre><code>df['count'] = (df.groupby(df.A.cumsum())['B'].cumsum() + df.groupby(df.B.cumsum())['A'].cumsum())
</code></pre>
<p>OUTPUT:</p>
<pre><code> A B count
0 False False 0
1 True False 1
2 False False 1
3 True False 2
4 False True 1
5 Fal... | python|pandas|count|rolling-computation | 1 |
1,105 | 67,727,890 | RNN LSTM valueError while training | <p>Hi there recently I've been working on a RNN LSTM project and I have e 2D data set like</p>
<pre><code>x = [[x1,x2,x3...,x18],[x1,x2,x3...,x18],...]
y = [[y1,y2,y3],[y1,y2,y3],...]
X.shape => (295,5,18)
Y.shape => (295,3)
</code></pre>
<p>and I convert it to a 3D dataset by code below</p>
<pre><code>X_train =... | <p>Change:</p>
<pre><code>input_shape=(X_train.shape[0],X_train.shape[1],X_train.shape[2])
</code></pre>
<p>to</p>
<pre><code>input_shape=(X_train.shape[1],X_train.shape[2])
</code></pre>
<p>Basically <code>keras</code> is designed to take any number of examples in a single batch, so it automatically puts <code>None</c... | python|numpy|keras|deep-learning|lstm | 1 |
1,106 | 67,798,892 | torch.inverse returns identity matrices. Bug resolved by print input before calculation (But why?) | <p>torch.inverse() only returns identity matrices. (see <em>unnormal output</em> below). It occur repeatly after the first iteration.</p>
<p>If I try to print anything of <code>pose_pre</code> first, the problem would disapear. (see <em>normal output</em> below)</p>
<p>Here is a part of the code:</p>
<pre class="lang-p... | <p>This problem happens when you use cuda version of tensor. If you do matrix inverse operation under cuda, it will always return an identity matrix. Detach to cpu would solve the problem.</p> | python|multithreading|printing|pytorch | 0 |
1,107 | 67,822,953 | GCP: IA ML serving with autoscaling to zero | <p>I wanted to try the ML serving AI platform from GCP, but i want the node to scale only if there is a call to prediction.</p>
<p>I see in the <a href="https://cloud.google.com/ai-platform/prediction/docs/deploying-models" rel="nofollow noreferrer">documentation here</a>:</p>
<blockquote>
<p>If you select "Auto s... | <p>I tried to reproduce your case and found the same thing, I was not able to set the <code>Minimum number of nodes</code> to 0.</p>
<p>This seems to be an outdated documentation issue. There is an ongoing <a href="https://issuetracker.google.com/issues/147141612" rel="nofollow noreferrer">Feature Request</a> that expl... | tensorflow|google-cloud-platform|google-ai-platform | 1 |
1,108 | 61,331,091 | Replace zeroes in array with different values for different halves of the array | <p>I have an array of floats whose size is not known in advance. There are zero values in it and other floats.
I want to replace its zeroes with a certain value only for part of the array, let's say for the first third of the array, with another value for the second third, and another value for the last third.</p>
<p>... | <p>You can use mask to get the desired indices first and then assign them any value at once without loop:</p>
<pre><code>mask = np.where(my_array==0)[0]
my_array[mask[mask<my_array.size//3]] = first_value
my_array[mask[np.logical_and(mask>=my_array.size//3, mask<2*my_array.size//3)]] = second_value
my_array[m... | python|arrays|numpy|list-comprehension | 1 |
1,109 | 61,305,853 | Grouping pandas series based on condition | <p>I have a Pandas df with one column the following values.</p>
<pre><code> Data
0 A
1 A
2 B
3 A
4 A
5 A
6 B
7 A
8 A
9 B
</code></pre>
<p>I want to try and group these values as such, for each encounter of Value B, i want the the group value to be changed as fo... | <p>You can try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumsum.html" rel="noreferrer"><code>cumsum</code></a> after comparing if the series <code>equals</code> <code>B</code> and then <code>shift</code> 1 place to include B in the group:</p>
<pre><code>df['Data'].eq('B').shift(... | python|pandas|dataframe|grouping | 6 |
1,110 | 61,277,879 | Convert Stacked DataFrame of Years and Months to DataFrame with Datetime Indices | <p>I am reading a csv file of the number of employees in the US by year and month (in thousands). It starts out like this:</p>
<pre><code>Year,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
1961,45119,44969,45051,44997,45119,45289,45400,45535,45591,45716,45931,46035
1962,46040,46309,46375,46679,46668,46644,46720,4677... | <p>After the <code>stack</code> create the DateTimeIndex from the current index</p>
<pre><code>from datetime import datetime
dt_index = pd.to_datetime([datetime(year=year, month=month, day=1)
for year, month in df.index.values])
df.index = dt_index
df.head(3)
# 1961-01-01 45119
# 1961-02-01 ... | python|python-3.x|pandas|dataframe | 2 |
1,111 | 61,213,685 | How to randomly shuffle blocks in numpy 3D array on particular axis | <p>I have a 3D numpy array and I want to shuffle it block wise in a particular axis while keeping the data in that block in it's original state. For instance I have an np array of shape (50, 140, 23) and I want to shuffle by making blocks of (50, 1, 23) on axis=1. So 140 blocks will be created and blocks should be shuf... | <p>You can use a random permutation:</p>
<pre><code>A = sum(np.ogrid[0:0:50j,:140,0:0:23j])
rng = np.random.default_rng()
Ashuff = A[:,rng.permutation(140),:]
</code></pre> | python|arrays|numpy|shuffle | 3 |
1,112 | 61,464,888 | TensorFlow Error: ValueError("Shapes %s and %s are incompatible" % (self, other)) | <p>I'm trying to classify images of PCBs into two categories (<code>defected</code> and <code>undefected</code>) using <code>categorical cross-entropy</code> as the loss function. The code for the same is as below:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import tensorflow
from tensorflow.ker... | <p>Seems your y_train data have shape (None,1) while your network is expecting (None,2). There are two options to solve this:</p>
<p>1) Change your model output to 1 unit and change loss to binary crossentropy</p>
<p>or</p>
<p>2) Change your y_train data to categorical. See <a href="https://www.tensorflow.org/api_do... | python|tensorflow|machine-learning|keras|deep-learning | 1 |
1,113 | 68,540,419 | reshape Pandas dataframe by appending column to column | <p>i do have a Pandas df like (df1):</p>
<pre><code> 0 1 2 3 4 5
0 a b c d e f
1 1 4 7 10 13 16
2 2 5 8 11 14 17
3 3 6 9 12 15 18
</code></pre>
<p>and i want to generate an Dataframe like (df2):</p>
<pre><code> 0 1 2
0 a b c
1 1 4 7
2 2 5 7
3 3 6 9
4 d e f
5 10 13 1... | <p>Use <code>np.vstack</code> and <code>np.hsplit</code>:</p>
<pre><code>>>> pd.DataFrame(np.vstack(np.hsplit(df, df.shape[1] / 3)))
0 1 2
0 a b c
1 1 4 7
2 2 5 8
3 3 6 9
4 d e f
5 10 13 16
6 11 14 17
7 12 15 18
</code></pre>
<p>Another example:</p>
<pre><code>>... | python|python-3.x|pandas|dataframe | 1 |
1,114 | 53,194,704 | Keras loss function understanding | <p>In order to understand some callbacks of Keras better, I want to artificially create a <code>nan</code> loss.</p>
<p>This is the function</p>
<pre><code>def soft_dice_loss(y_true, y_pred):
from keras import backend as K
if K.eval(K.random_normal((1, 1), mean=2, stddev=2))[0][0] // 1 == 2.0:
# return nan
... | <p>Your first conditional statement is only evaluated once the loss function is defined (i.e. called; that is why Keras stops right at the start). Instead, you could use <a href="https://keras.io/backend/#switch" rel="nofollow noreferrer">keras.backend.switch</a> to integrate your conditional into the graph's logic. Yo... | python|tensorflow|keras|nan|loss | 1 |
1,115 | 53,201,829 | How should we take the sum of values in a column after grouping by a different column in pandas dataframe | <p>I am trying to plot a graph for to analyze if there's any relation between the available_days of a property and number of reviews for it. I have a dataset which has different unique property listings, available_days for each property, number of reviews for each property. I am trying to plot by grouping the data by '... | <p>Do you mean something like this?</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
"availability": [1, 2, 2, 3, 3, 3, 4, 4, 4, 4],
"num_reviews": [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
})
# Count number of reviews per unique value for "availibility"
df["reviews_by_availability"] = df.groupby("availability")[... | python|pandas|matplotlib|data-analysis | 0 |
1,116 | 53,234,329 | How to do an R style aggregate in Python Pandas? | <p>I need to do an aggregate (at least that what you would call it in R) over the mtcars data set that I have uploaded into python. The end goal is to get the average mpg for each value of cyl in the data set (There are three values for cyl, 4,6,8). Here is the R code for what I want to do</p>
<p>mean_each_gear <- ... | <p>You want pandas groupby()!</p>
<pre><code>import pandas as pd
my_dataframe = pd.read_csv('my_input_data.csv') //insert your data here
pd.groupby(['col1'])['col2'].mean()
</code></pre>
<p>where 'col1' is the column you want to group by and 'col2' is the column whose mean you want to obtain. Also see here:</p>
<p>... | python|r|pandas|aggregate | 0 |
1,117 | 52,939,673 | Pandas and DateTime TypeError: cannot compare a TimedeltaIndex with type float | <p>I have a pandas DataFrame Series time differences that looks like::</p>
<pre><code> print(delta_t)
1 0 days 00:00:59
3 0 days 00:04:22
6 0 days 00:00:56
8 0 days 00:01:21
19 0 days 00:01:09
22 0 days 00:00:36
...
</code></pre>
<p>(the full DataFrame had a bunch of NaNs whi... | <p>Assuming your Series is in <code>timedelta</code> format, you can skip the <code>np.where</code>, and index using something like this, where you compare your actual values to other timedeltas, using the appropriate units:</p>
<pre><code>delta_t_lt1day = delta_t[delta_t < pd.Timedelta(1,'D')]
delta_t_lt1hour = d... | python|pandas|datetime|series | 5 |
1,118 | 65,512,677 | How can i use 2 numpy arrays as dataset for denoising autoencoder, and further split them into train and test sets | <p>I have 2 numpy arrays, one with clean data [4000 x [1000][25]] (4000 1000x25 arrays) and one with noisy data (same size as clean) to be used for a de-noising auto-encoder problem.</p>
<p>I want to be able to either map them and then store them into a tensorflow data set, or any other way which allows me to do this</... | <p>assume you have your clean data in an array clean_data and your noisy data in an array noisy_data. Then use train_test_split from sklearn to split the data into a training set
and a test as follows</p>
<pre><code>from sklearn.model_selection import train_test_split
train_size=.7 # set this to the percentage you wan... | python|numpy|tensorflow|keras|autoencoder | 0 |
1,119 | 65,525,313 | Merge two dataframes on string columns with values containing wilcards as for like in SQL - Python | <p>I want to merge 2 dataframes on string columns with values containing wildcards as we can do with like in SQL.</p>
<p>Example :</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'A': ["He eat an apple in his office.", "There are many apples on the tree."], 'B': [1, 2]})
df2 = pd.DataFrame({... | <p>This can be done by using apply to search for df2's patterns in each row of df1. This will require runtime proportional to <code>O(n*m)</code>, where n is the number of rows in df1, and m is the number of rows in df2. This is not very efficient, but that's fine for small dataframes.</p>
<p>Once we identify the match... | python|regex|pandas|merge|wildcard | 0 |
1,120 | 65,797,918 | How to find the closest value on the left | <p>I have a function and I have detected the peaks of this function. I took the half of the height of each peak, now I want to find the intersection point, on the left only, between the function and the line that passes by the half of the height of the peak.</p>
<p>Please, note that in the picture below, the line does ... | <p>The following code use the function <code>find_roots</code> from <a href="https://stackoverflow.com/questions/46909373/how-to-find-the-exact-intersection-of-a-curve-as-np-array-with-y-0">How to find the exact intersection of a curve with y==0?</a>. This function searches the exact interpolated x-value corresponding ... | python|python-3.x|numpy|matplotlib|numpy-ndarray | 1 |
1,121 | 65,641,499 | How to parse a string calculation in a pandas dataframe column | <p>I am trying to parse a string calculation which is a column within a dataframe, if the calculation is static I can use the eval function. However this doesnt appear to work when you give it a column name.</p>
<pre><code>import pandas as pd
calcs = {'a': [1,1],
'b': [1,1],
'c': [1,1],
'cal... | <p>You can <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>df.apply</code></a>, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.eval.html#pandas.DataFrame.eval" rel="nofollow noreferrer"><code>df.eval</... | python|python-3.x|pandas|dataframe|eval | 1 |
1,122 | 65,836,299 | LOOP univariate rolling window regression on entire DF Python | <p>I have a dataframe of 24 variables (24 columns x 4580 rows) from 2008 to 2020.</p>
<p>My independant variable is the first one in the DF and the dependant variables are the 23 others.</p>
<p>I've done a test for one rolling window regression, it works well, here is my code :</p>
<pre><code>import statsmodels.api as... | <p>Can you throw it all in a loop and store the results in some other object like a dict?</p>
<p>Potential solution:</p>
<pre><code>data = {}
for column in list(df.columns)[2:]: # iterate over columns 2 to 24
x = sm.add_constant(df[column])
y = df[['CADUSD']] ## This never changes from CADUSD, right?
rols... | python|pandas|list|dataframe|regression | 1 |
1,123 | 63,531,557 | Convert time to categorical variable | <pre><code>df
Time | Day_of_the_Week
16:24:18 | Sat
17:00:01 | Sun
03:48:12 | Mon
</code></pre>
<p>Expected Output:</p>
<pre><code>df
Time | Day_of_the_Week | Time_Category
16:24:18 | Sat | Afternoon
17:00:01 | Sun | Evening
03:48:12 | Mon | Midnight
</co... | <p>We can try <code>pd.cut</code></p>
<pre><code>s = pd.cut(df.Time, pd.to_timedelta(['04:00:00','12:00:00','17:00:00','23:59:59']),
labels=['Morning','Afternoon','Evening']).astype(str).replace('nan','Midnight')
Out[43]:
0 Afternoon
1 Evening
2 Midnight
Name: Time, dtype: object
df['Time_categor... | python|python-3.x|regex|pandas|datetime | 1 |
1,124 | 63,558,757 | % Increase value in number record | <p>my dataset</p>
<pre><code>name date record
A 2018-09-18 95
A 2018-10-11 104
A 2018-10-30 230
A 2018-11-23 124
B 2020-01-24 95
B 2020-02-11 167
B 2020-03-07 78
</code></pre>
<p>As you can see, there are several ... | <p>Use:</p>
<pre><code>#get percento change per groups
s = df.groupby("name")["record"].pct_change()
#get row with maximal percent change
df1 = df.loc[s.groupby(df['name']).idxmax()].add_suffix('_increase')
#get row with previous maximal percent change
df2 = (df.loc[s.groupby(df['name'])
.a... | python|pandas|numpy|compare | 2 |
1,125 | 63,731,947 | Aggregate quantity based on string and additional column using pandas | <p>I have a data set that contains data that looks like this:</p>
<pre><code>Month, Year, Quantity Sold, Product Name
11, 2017, 13, "Creatine Powder Supplement - 500g"
11, 2017, 10, "Gummies 1 bag"
11, 2017, 12, "Creatine Powder Supplement - 1000g"
11, 2017, 15, "Creatine Powder Suppl... | <p>Here is a Python solution. It writes <em>error</em> lines to an output file and writes good lines to the terminal.</p>
<pre><code>from collections import defaultdict
import re
d = defaultdict(int)
with open('f0.txt', 'r') as f, open('err.txt', 'w') as fout:
fout.write(f.readline()) # print header to err.txt
... | python|pandas | 1 |
1,126 | 63,365,169 | Prediction retracing warning message while creating LOOCV in CNN keras/tensorflow2.0 | <p>I am trying to write a custom for loop in order to execute a LOOCV using tensorflow 2.0 and Keras API. I am testing a CNN regression where each value is represented by 12 molecular images.</p>
<p>My dataset consists of 504 images from 42 molecules and it looks like this:</p>
<pre><code> file value ... | <p>My code was loading the model and the running predict and I had a similar message as warning.</p>
<p>WARNING:tensorflow:11 out of the last 11 calls to <function Model.make_predict_function..predict_function at 0x000001A789F8F288> triggered tf.function retracing. Tracing is expensive and the excessive number of... | python|tensorflow|image-processing|keras|conv-neural-network | 2 |
1,127 | 72,014,261 | Pandas -- create ranks for diffrent records that similar except one column | <p>I want to fetch 1 record from duplicate rows in Df except one column. example :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>index</th>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>abc</td>
<td>efg</td>
<td>hij</td>
<td>op</td>
</... | <p>Use:</p>
<pre><code>df['rank'] = df.groupby(df.columns.difference(['col4']).tolist()).cumcount().add(1)
</code></pre> | python|pandas|dataframe|group-by|rank | 0 |
1,128 | 72,046,920 | Bokeh callback function doesnt update scatterplot colors based on clusters | <p>My intial plot works great and shows the colors of the intial 3 clusters. However, when I select a new k value with the silder widget, the new clusters are all colored grey.</p>
<pre><code>import numpy as np
import pandas as pd
import random
from typing import List, Tuple
from bokeh.models import ColumnDataSource, ... | <p>This seemed to work in my callback function</p>
<pre><code>def callback(attr, old, new):
# recompute the clustering and update the colors of the data points based on the result
k = slider_k.value_throttled
init = select_init.value
clustering_new, counter_new = k_means(data_np,k,500,init)
sou... | python|numpy|cluster-analysis|bokeh|k-means | 0 |
1,129 | 55,472,095 | AttributeError: module 'resource' has no attribute 'getpagesize' | <p>I am trying to use Tensorflow Object Detection API and I follow the steps mentioned in the given link -</p>
<p><a href="https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/install.html#tf-models-install" rel="nofollow noreferrer">https://tensorflow-object-detection-api-tutorial.readthedocs.io/... | <p>Got a similar error. My project contained modules (folders)</p>
<ul>
<li>model</li>
<li>resource (replaced with resources)</li>
<li>service</li>
</ul>
<p>So I changed the name of the resource module to resources (change name to any appropriate module name)</p> | python-3.x|tensorflow|jupyter-notebook|object-detection | 1 |
1,130 | 55,250,161 | Identifying stops from telemetric data using Pandas | <p>I have telemetric (latitude, longitude, time, mileage) from a large number of vehicles. Each pandas dataframe has one vehicle's travel over time and I would like to identify when the vehicle stops.</p>
<p>I have used pandas groupby to identify if the vehicle is moving between rows (accounting for some drift).</p>
... | <p>Look at the output of <code>df.groupby('DAY')['LAT'].diff()</code>. Many values are negative, so you need to take the absolute value before you check if they are less than your cutoff value:</p>
<pre><code>df['Stopped2'] = (df.groupby('DAY')['LAT'].diff().abs() <= 0.0001) & (df.groupby('DAY')['LNG'].diff().a... | python|python-3.x|pandas|pandas-groupby | 0 |
1,131 | 66,792,507 | Pandas how to shift column by datetime into datetime not in index | <p>I want to shift a pandas column by an amount of time, and reindex the dataframe to accommodate this shift.
Take the following dataframe:</p>
<pre><code>df = pd.DataFrame({"Col1": [10, 20, 15, 30, 45],
"Col2": [13, 23, 18, 33, 48],
"Col3": [17, 27, 2... | <p>BENY's answer works, but I found to be slow with my very large dataframe. As such, I did the following and it worked for me and was much quicker:</p>
<pre><code>dt_index2 = pd.date_range(df.index[0], df.index[-1], freq="15min")
df = df.reindex(dt_index2)
df["Col1"] = df["Col1"].shift(15... | python|pandas|dataframe|datetime | 1 |
1,132 | 47,129,156 | Tensorflow - How to use tf.gather() to deliver part of the first layer's inputs to one of the next layer's filter | <p>Let's say I have this setup:</p>
<pre><code>conv1 = tf.layers.conv2d(
inputs=input_layer,
filters=4,
kernel_size=[14, 14],
padding="valid",
activation=tf.nn.relu
)
conv2 = tf.layers.conv2d(
inputs=conv1,
filters=16,
kernel_size=[5, 5],
padding="valid",
activation=tf.nn.r... | <p>tf.gather() makes slices only along one axis, so for your case tf.gather_nd() would work better. So it should be as following:</p>
<pre><code># make a placeholder for indices of the outputs you will pick,
# or make it constant if they won't change
indices = tf.placeholder(tf.int32,[None,4])
conv1 = tf.layers.con... | python|tensorflow | 0 |
1,133 | 47,314,000 | divide values of column based on some other column | <p>I have a pandas data frame as can be seen below: </p>
<pre><code>index ID Val
1 BBID_2041 1
2 BBID_2041 1
3 BBID_2041 3
4 BBID_2041 1
5 BBID_2041 2
6 BBID_2041 1
7 BBID_2041 1
8 BBID_20410 1
9 BBID_204... | <p>By using <code>transform</code></p>
<pre><code>df['New']=df.groupby('ID').Val.transform(lambda x : x/len(x))
df
Out[814]:
index ID Val New
0 1 BBID_2041 1 0.142857
1 2 BBID_2041 1 0.142857
2 3 BBID_2041 3 0.428571
3 4 BBID_2041 1 0.142857
4 ... | python|pandas|dataframe|grouping | 2 |
1,134 | 47,290,682 | Index datatime in a dateframe from a list of datetimes | <p>First of all, I did this function that returns one date frame but I wanna use in a list of dates and then concatenate them in one data frame with the index being the date time stamp that is in the list</p>
<pre><code>lista = [datetime.datetime(2017, 11, 11, 0, 0), datetime.datetime(2017, 11, 12, 0, 0), datetime.dat... | <p>Not positive what you're going for, but maybe something like this:</p>
<pre><code>def create_df(dl):
idx = []
cols = {
'00_04': [],
'04_08': [],
'08_12': [],
'12_16': [],
'20_24': [],
}
for date in dl:
col['00_04'].append(int( df_output.loc[ (df_outpu... | python|pandas|time | 1 |
1,135 | 47,424,766 | How Can I choose count the data in one column based on other column? | <p>I have two dataframe as below:</p>
<pre><code>df1 = DataFrame({'a': np.random.randint(10, size=2)})
df2 = DataFrame({'a': np.random.randint(10, size=100)})
</code></pre>
<p>There is two numbers in df1, and I want to count the two numbers' amount in df2. The answer is in the right of df1['a'].</p>
<p>I use for in... | <pre><code>df2.a.value_counts().reindex(df1.a)
Out[369]:
a
4 11
5 5
Name: a, dtype: int64
</code></pre>
<p>Add <code>sum</code></p>
<pre><code>df2.a.value_counts().reindex(df1.a).sum()
Out[370]: 16
</code></pre> | python|pandas|numpy | 2 |
1,136 | 47,328,224 | Error using data augmentation options in the Object Detection API | <p>I am trying to use the data_augmentation_options in the .config files to train a network, specifically a ssd_mobilenet_v1, but when I activate the option random_adjust_brightness, I get the error message pasted below very quickly (I activate the option after the step 110000).</p>
<p>I tried reducing the default val... | <p>Often, getting <code>LossTensor is inf or nan. : Tensor had NaN values</code> is due to an error in the bounding boxes / annotations (Source: <a href="https://github.com/tensorflow/models/issues/1881" rel="nofollow noreferrer">https://github.com/tensorflow/models/issues/1881</a>).</p>
<p>I know that the Bosch Small... | tensorflow|object-detection|object-detection-api | 1 |
1,137 | 47,145,683 | Error reading images with pandas (+pyTorch,scikit) | <p>I'm trying to read images to work with a CNN, but I'm getting a pandas error while trying to load the images.
This is some of the code (omitted imports and irrelevant nn class for clarity):</p>
<pre><code>file_name = "annotation.csv"
image_files = pd.read_csv(file_name)
class SimpsonsDataset(Dataset):
def __i... | <p>Your variable <code>image_files</code> is a pandas DataFrame, since it holds the return value of <code>pd.read_csv()</code>, which returns a DataFrame. Try deleting the line</p>
<pre><code>image_files = pd.read_csv(file_name)
</code></pre>
<p>and changing the last line to this:</p>
<pre><code>simpsons = SimpsonsD... | python|pandas|scikit-image|pytorch | 1 |
1,138 | 47,518,450 | Error tokenizing data with Pandas from a tsv file | <p>I have got dataset named <code>train.tsv.7z</code> and <code>test.tsv.7z</code>. I unzip them in my Mac with unarchiver (double click) so I have the <code>train.tsv</code> and <code>test.tsv</code> now.</p>
<p>Then I am reading those files with pandas using </p>
<pre><code>PATH='data/projData/'
tables = pd.read_ta... | <p>It doesn't work this way.</p>
<p>You have to specify a single file (not a directory):</p>
<pre><code>train = pd.read_csv('data/projData/train.tsv', sep='\t')
</code></pre> | python|pandas | 1 |
1,139 | 47,212,051 | Create new pandas dataframe and add values stored in an array of tuples | <p>I have an array of tuples like:</p>
<pre><code>myArr=Ttest_indResult(statistic=array([ -5.27693006, 0., 0., 0.15105006,]),
pvalue=array([ 2.31902785e-06, 1.00000000e+00, 1.00000000e+00,
8.80460569e-01,)]))
</code></pre>
<p>I want to add the values <code>myArr[1][0],myArr[1][1],myArr[1][2] and myAr... | <p><code>myArr</code> is not exactly a <code>tuple</code> but rather a <a href="https://docs.python.org/3/library/collections.html#collections.namedtuple" rel="nofollow noreferrer"><code>namedtuple</code></a> (see <a href="https://github.com/scipy/scipy/blob/80c2d3be7064a71906fef937e633af57921ec996/scipy/stats/mstats_b... | python|pandas | 1 |
1,140 | 68,358,634 | Referening chunked Dataframe - Pandas | <p>I have broken a large dataframe into small chunks. I am now trying to pass the data from these chunks into a loop but I am not sure how to call each of these chunked dataframes.</p>
<p>I have broken the Dataframe into 4 chunks as shown below. But I am not sure how to call each of these chunked Dataframe and pass the... | <ul>
<li>you describe a <strong>bigdf</strong> that is <em>chunked</em> into a list of data frames. I have simulated this</li>
<li>if you want a <strong>list comprehension</strong> of rows in subset of data frame <strong>list</strong> it's a simple case of effectively looping over both lists</li>
</ul>
<pre><code>impo... | pandas | 0 |
1,141 | 68,212,970 | Python Dataframe fill nan from multiple columns | <p>I have a data frame with 3 columns. I want to fill <code>nan</code> in the first column with the second column. If there is also <code>nan</code> in the second, go to the third column.</p>
<p>My code:</p>
<pre><code>xdf = pd.DataFrame({'A':[10,20,np.nan,np.nan],'B':[15,np.nan,30,np.nan],'C':[np.nan,np.nan,35,40]})
... | <p>Try via <code>bfill()</code>:</p>
<pre><code>xdf['A']=xdf.bfill(1)['A']
</code></pre>
<p>output of <code>df</code>:</p>
<pre><code> A B C
0 10.0 15.0 NaN
1 20.0 NaN NaN
2 30.0 30.0 35.0
3 40.0 NaN 40.0
</code></pre>
<p><strong>Update:</strong></p>
<p>if there were add... | python|pandas|dataframe|numpy|fillna | 3 |
1,142 | 68,231,398 | Create and Fill Duplicate Dataframe Values with Lists | <p>I am trying to find a way to arrange a dataframe given a path that leads to several numbers that are read from files in that path.</p>
<p>I have a dataframe that has a JobID and the path associated with that job that looks as follows:</p>
<pre><code>JobID Path
43402866 /global/162940/mill/scanfiles0001
... | <p>You could try like this:</p>
<pre class="lang-py prettyprint-override"><code># Initial dataframe
df = pd.DataFrame(
{
"JobID": ["43402866", "43408681"],
"Path": [
"/global/162940/mill/scanfiles0001",
"/global/162940/mi... | python|pandas|dataframe | 0 |
1,143 | 68,127,203 | compare the two rows string for same id and get the unique string values in pandas | <p>Input:</p>
<pre><code>df1 = pd.DataFrame([[101, 'DC1', ' AHT - QA + + AHT - Required Disclosures + payment'],
[101, 'EM5', ' AHT - QA + AHT - Required Disclosures + + Off + STAR.ist'],
[102, 'RA6', '+ AHT - QA + Recap Warning - Yes +'],
[103, 'DC1', 'Greeting + Navig... | <p>You can try:</p>
<pre><code>df1['unique_task_done']=df1['Task_done'].mask(df1['Task_done'].duplicated(keep=False),'same task')
mask=df1['unique_task_done'].str.count(' + ')
</code></pre>
<p>Finally:</p>
<pre><code>df1.loc[mask.ge(2),'unique_task_done']=df1.loc[mask.ge(2),'unique_task_done'].str.split('+').str[mask... | python-3.x|pandas | 0 |
1,144 | 59,133,420 | Concatenated data from pandas_datareader | <p>I am trying to create a dataframe which columns from 2 different datarame.</p>
<pre><code>import pandas as pd
import numpy as np
from statsmodels import api as sm
import pandas_datareader.data as web
import datetime
start = datetime.datetime(2016,12,2)
end = datetime.datetime.today()
df = web.get_data_yahoo(['F'], ... | <p>Add parameter <code>axis=1</code> for concanecate by columns in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a>:</p>
<pre><code>df3 = pd.concat([df['Adj Close'], df1['Adj Close']], axis=1)
</code></pre>
<p>But I think your sol... | python-3.x|pandas|pandas-datareader | 1 |
1,145 | 56,871,477 | Pandas creating and filling new columns based on other columns | <p>I have a pandas dataframe with Time and values columns. I am trying to create two new columns 'START_TIME" and 'END_TIME'. It is medication related data and it is stored poorly in the database so I am trying to transform the table.
In this case, the medication for a patient started at 2018-11-07 23:59:32 with a dos... | <p>IIUC create the condition by using <code>diff</code>, then the value equal to -1 and 1 will be the end and start point </p>
<pre><code>s=df.Values.eq(0).astype(int).diff().fillna(-1)
df.loc[s==-1,'START_TIME']=df.Time
df.loc[s==1,'END_TIME']=df.Time
df
Out[334]:
Time Values START_TIME ... | python-3.x|pandas|dataframe | 2 |
1,146 | 57,237,671 | Tensorflow & Keras can't load .ckpt save | <p>So I am using the ModelCheckpoint callback to save the best epoch of a model I am training. It saves with no errors, but when I try to load it, I get the error:</p>
<pre><code>2019-07-27 22:58:04.713951: W tensorflow/core/util/tensor_slice_reader.cc:95] Could not open C:\Users\Riley\PycharmProjects\myNN\cp.ckpt: Da... | <p>TLDR; you are saving whole model, while trying to load only weights, that's not how it works.</p>
<h2>Explanation</h2>
<p>Your model's <code>fit</code>:</p>
<pre><code>model.fit(
train_images,
train_labels,
epochs=100,
callbacks=[
keras.callbacks.ModelCheckpoint(
"cp.ckpt", mon... | python|tensorflow|machine-learning|keras|computer-vision | 6 |
1,147 | 66,755,165 | RuntimeError:shape ‘[4, 98304]’ is invalid for input of size 113216 | <p>I am learning to train a basic nn model for image classification, the error happened when I was trying to feed in image data into the model. I understand that I should input correct size of image data. My image data is 128*256 with 3 channels,4 classes, and the batch size is 4. What I don't understand is where does ... | <h2>Shapes</h2>
<ul>
<li><code>Conv2d</code> changes width and height of image without <code>padding</code>. Rule of thumb (if you want to keep the same image size with <code>stride=1</code> (default)): <code>padding = kernel_size // 2</code></li>
<li>You are changing number of channels, while your <code>linear</code> ... | image|pytorch|conv-neural-network | 1 |
1,148 | 66,655,525 | Error in merging pandas data frame columns | <p>I'm trying to merge three columns from the same data frame into one.</p>
<p>Here my data frame <code>selected_vals</code></p>
<pre><code> label_1 label_2 label_3
0 NaN NaN NaN
1 ('__label__Religione_e_Magia',) NaN ... | <p>You can apply function to each row and keep only desired value (where column is not NaN)</p>
<pre class="lang-py prettyprint-override"><code>selected_vals['selected_vals'] = selected_vals.apply(lambda row: row[row[pd.notnull(row)].index.item()], axis=1)
</code></pre> | python|pandas|dataframe | 0 |
1,149 | 66,402,155 | Merge two DataFrames with overlapping MultiIndex columns | <p>I'm trying to find a simple way to merge two MultiIndex dataframes together in a way that adds new columns and merges existing. For example if I had two data frames</p>
<pre><code>d1_columns = pd.MultiIndex.from_product([["A", "B",], ["1", "2"]])
d1_index = pd.date_range("... | <p>It seems you want</p>
<pre><code>df = d1.combine_first(d2)
</code></pre>
<p>or</p>
<pre><code>df = d2.combine_first(d1)
</code></pre>
<p>depending on which frame's values shall be preferred.</p> | pandas|merge|multi-index | 1 |
1,150 | 66,517,341 | Pandas count, sum, average specific range/ value for each row | <p>i have big data, i want to count, sum, average for each row only between specific range.</p>
<pre><code>df = pd.DataFrame({'id0':[10.3,20,30,50,108,110],'id1':[100.5,0,300,570,400,140], 'id2':[-2.6,-3,5,12,44,53], 'id3':[-100.1,4,6,22,12,42]})
</code></pre>
<blockquote>
<pre><code> id0 id1 id2 id3
0 10... | <p>You can apply the conditions with AND between them, and then <code>sum</code> along the row (axis 1):</p>
<pre><code>((df >= 10) & (df <= 100)).sum(axis=1)
</code></pre>
<p>Output:</p>
<pre><code>0 1
1 1
2 1
3 3
4 2
5 2
dtype: int64
</code></pre>
<hr />
<p>For sum and mean, you can apply ... | python|pandas|pandas-groupby|isin | 1 |
1,151 | 72,836,451 | Sort values in array by keys in another dictionary (python) | <p>Let's suppose I have an array that looks like this:</p>
<pre><code>x=['Other', 'Physical Training', 'Math', 'English', 'Physics', 'Literature']
</code></pre>
<p>I need to sort it (not alphabetically) by keys in dictionary:</p>
<pre><code> y={'Math':0,
'Physics':1,
'Chemistry':2,
'Biology':3,
'English... | <p>if <code>x</code> is a list, to sort inplace:</p>
<pre><code>x.sort(key=y.get)
#['Math', 'Physics', 'English', 'Literature', 'Physical Training', 'Other']
</code></pre>
<p>to sort without changing <code>x</code> itself:</p>
<pre><code>x_sorted = sorted(x, key=y.get)
</code></pre>
<p>if <code>x</code> is an array, co... | python|pandas|numpy | 2 |
1,152 | 73,055,157 | What does "ImportError: cannot import name randbits" mean? | <p>The first cell of my jupyter notebook contains the libraries I want to import. For some reason when I run it receive the <code>ImportError: cannot import name randbits</code>. I have never seen this import error before and have already tried restarting the kernel and confirmed that all libraries were installed cor... | <p>I have been having the same issue all day. Finally figured out what solved my problem. Somehow anaconda3/Lib/secrets.py got overwritten. Numpy relies on files in this directory called random.py and secrets.py so if you have files with those names numpy will not load.</p>
<p>-I renamed my incorrect secrets.py file</p... | python|python-3.x|numpy|import|importerror | 5 |
1,153 | 70,601,746 | How to operate a function over multiple columns (Pandas/Python)? | <p>Let's consider IBM HR Attrition Dataset from Kaggle (<a href="https://www.kaggle.com/pavansubhasht/ibm-hr-analytics-attrition-dataset" rel="nofollow noreferrer">https://www.kaggle.com/pavansubhasht/ibm-hr-analytics-attrition-dataset</a>). How do I rapdly gets the variable with the highest Shapiro p-value?</p>
<p>In ... | <p>I hope this helps! I'm sure there are a lot better ways, but it was fun trying :)</p>
<pre><code>import pandas as pd
from scipy import stats
</code></pre>
<pre><code>df = pd.read_csv('path.csv')
</code></pre>
<pre><code># make a new dataframe newdf with only the columns containing numeric data
numerics = ['int16', ... | python|pandas|scipy|statistics | 0 |
1,154 | 70,466,211 | groupby on column which contain bytearray object using Pandas Dataframe | <p>I have pandas dataframe and want to do groupby on Customer ID</p>
<pre><code> df['rank_col'] = df.groupby('PSEUDO_CUSTOMER_ID')['DB_CREATED_DT'].rank(method='first')
</code></pre>
<p>now the problem is pseudo_customer_ID which look like this</p>
<pre><code> [138, 76, 16, 9, 86, 71, 5, 85, 117, 237, 97, 212, 13, 157... | <p>Convert your <code>bytearray</code> with the <code>bytes</code> function to allow grouping (and get hashable type):</p>
<p>Demo:</p>
<pre><code>df['PSEUDO_CUSTOMER_ID_BYTES'] = df['PSEUDO_CUSTOMER_ID'].apply(bytes)
print(df)
# Output:
PSEUDO_CUSTOMER_ID PS... | python|arrays|pandas|pandas-groupby | 1 |
1,155 | 51,433,372 | Tensorflow estimator.DNNClassifier not repeating results | <p>Each time I run the following code I get a different 'Loss for final step' when training my model. The subsequent evaluation accuracy also changes. I have checked that the input data from train_test_split is constant.I have set the value of tf.random_seed, turned off shuffling and set the value of num_threads. I am ... | <p>Here is some code that TensorFlow sent me to solve the problem. Rather than use tf.set_random_seed, with estimators you use tf.estimator.RunConfig. </p>
<pre><code>import tensorflow as tf
tf.reset_default_graph()
config = tf.estimator.RunConfig(tf_random_seed=234)
input1_col = tf.feature_column.numeric_column('inp... | python|repeat|tensorflow-estimator | 0 |
1,156 | 51,311,062 | Can't import apply_transform from keras.preprocessing.image | <p>I have been having issues importing <code>apply_transform</code> from <code>keras.preprocessing.image</code>. As far as I know the name has not changed according to Keras documentation. Anyone has any idea what might be the issue. I can, from the same library, import <code>ImageDataGenerator</code> for instance.</p>... | <p><code>apply_transform</code> <a href="https://github.com/keras-team/keras/commit/08c873669f39b37743014db99fcd2d308f8ea5ea#diff-93850fa46a789f2e5905894ad0e7bee4L239" rel="nofollow noreferrer">has been removed</a> from <code>image</code> module and <a href="https://github.com/keras-team/keras-preprocessing/blob/f16eb5... | python|python-3.x|tensorflow|keras|anaconda | 5 |
1,157 | 51,679,840 | Pandas DataFrame initialized with a nested dict fail if only specify row index | <p>I try to specify row index of a DataFrame initialized with a nexted dict.</p>
<pre><code>pop={'Nevada': {2001: 2.4, 2002: 2.9}, 'Ohio': {2000: 1.5, 2001: 1.7, 2002: 3.6}}
pandas.DataFrame(pop, index=[2000,2001,2002])
AttributeError: 'list' object has no attribute 'astype'
</code></pre>
<p>However, if I also speci... | <p>I reproduced this problem in Python 3.7.1 with pandas 0.23.4.</p>
<p>The aim of this code section is used for clarifying that the order of index can be assigned artificially.</p>
<pre><code>pd.DataFrame(pop, index = pd.Series([2001, 2000, 2002]))
</code></pre>
<p>should work.</p> | python|pandas|dataframe | 2 |
1,158 | 37,214,884 | How do I choose an optimizer for my tensorflow model? | <p>Tensorflow seems to have a large collection of optimizers, is there any high level guideline (or review paper) on which one is best adapted to specific classes of loss functions ?</p> | <p>It depends on your datasets and NN models, but generally, I would start with Adam. Figure 2 in this paper (<a href="http://arxiv.org/abs/1412.6980" rel="noreferrer">http://arxiv.org/abs/1412.6980</a>) shows Adam works well.</p>
<p><a href="https://i.stack.imgur.com/cWsLk.png" rel="noreferrer"><img src="https://i.st... | tensorflow | 16 |
1,159 | 8,108,649 | Change elements in 2d ndarray into arrays | <p>In numpy, I have a 2d array like:</p>
<pre><code>[
[1 2 3 4 5]
[2 3 1 4 5]
.....
[3 5 2 3 5]
]
</code></pre>
<p>I want to replace each element in this array into a 1d array, e.g.</p>
<pre><code>1 -> [0 0 0 0 1]
2 -> [0 0 0 1 0]
</code></pre>
<p>etc.</p>
<p>This will convert elements into arrays, and t... | <p>Suppose this is your 2d array:</p>
<pre><code>x=np.random.randint(1,3,size=(3,2))
print(x)
# [[2 2]
# [1 2]
# [2 1]]
</code></pre>
<p>Create the array:</p>
<pre><code>y=np.array([[0,0,0,0,0],[0,0,0,0,1],[0,0,0,1,0]])
</code></pre>
<p>You can look upon this array as a mapping:</p>
<pre><code>0 --> [0,0,0,0... | python|numpy | 4 |
1,160 | 37,697,934 | How to remove % symbol for particular column in dataframeusing python pandas? | <p>My data frame have following data:</p>
<pre><code>company,standard,returns
aaa,b1,10%
bbb,b2,20%
</code></pre>
<p>I have to remove <code>%</code> from <code>returns</code> column.</p> | <p>First remove last value of each string by <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#indexing-with-str" rel="noreferrer">indexing with str</a> and then cast to <code>int</code> or <code>float</code>:</p>
<pre><code>#if int values
print (df['returns'].str[:-1].astype(int))
#if flaot values
print... | python|python-2.7|pandas|dataframe | 7 |
1,161 | 31,437,402 | Remove column from Pandas multiindex | <p>I have a dataframe such as:</p>
<pre><code> Year Value
Country Element Item ItemCode
Afghanistan Production Wheat and products 2511 1961 2279
1962 2279
... | <p>Try this.</p>
<p><code>df.reset_index(level='ItemCode')</code></p> | python|pandas | 3 |
1,162 | 31,385,478 | Adding new rows to an array dynamcally | <p>I want to initialize an empty list and keep on adding new rows to it. For example.
myarray=[]
now at each iteration I want to add new row which I compute during iteration. For example</p>
<pre><code>for i in range(5):
calc=[i,i+1,i+4,i+5]
</code></pre>
<p>After calc I want to add this row to myarray. Therfore... | <p>It looks like you need a multi dimensional array</p>
<pre><code>calc = [[0, 1, 4, 5]]
for i in range(1, 5):
calc.append([i, i+1, i+4, i+5])
</code></pre>
<p>Will yield you the following array</p>
<pre><code>calc = [[0, 1, 4, 5], [1, 2, 5, 6], [2, 3, 6, 7], [3, 4, 7, 8], [4, 5, 8, 9]]
</code></pre>
<p>To acce... | python|arrays|numpy | 1 |
1,163 | 64,276,836 | Splitting a column with list of tuples into a seperate columns | <p>I'm working on a dataframe which has a shopping_cart column in the following format:
the first element of the tuple is the item ordered, and the second element is the quantity ordered for such item: for example:[('Candle Inferno', 1), ('iAssist Line', 2)] implies 'Candle Inferno' was bought once and 'iAssist Line' w... | <pre><code>def pretty_printer(l):
header = "|".join(["item_%d\tquantity_%d" % (index+1, index+1) for index, _ in numerate(l)])
items = "|".join(["%s\t%d" % (i[0], i[1]) for i in l])
print(header)
print(items)
l1 = [('Candle Inferno', 1), ('iAssist Line', 2)]... | python|regex|pandas|dataframe | 0 |
1,164 | 64,547,861 | How to split string and get only one word in python | <p>I have a string similar like this:</p>
<pre><code>HELLO TEST PACKAGE PARIS1 PROJECT
</code></pre>
<p>I got this string from selecting row and column:</p>
<pre><code>project_name = df[col_pro].values[row_pro]
</code></pre>
<p>and I want to get the "PARIS" only to be in a new column which is 'location_id'</p... | <p>I would use Named groups.
Say you have <code>df</code>;</p>
<pre><code> text
0 HELLO TEST PACKAGE PARIS1 PROJECT
</code></pre>
<p>Using Named Groups</p>
<pre><code>df.text.str.extract(r'(?P<location_id>PARIS)')
</code></pre> | python|pandas | 1 |
1,165 | 64,569,141 | How to sum with Null Values in group by statement using agg function in python | <p>I have a dataframe which looks like:</p>
<pre><code>A B C
a 100 200
a NA 100
a 200 NA
a 100 100
b 200 200
b 100 200
b 200 100
b 200 100
</code></pre>
<p>I use the aggregate function on column B and column C as:</p>
<pre><code>ag=data.groupby(['A']).agg({'B':'s... | <p>Maybe you already though about this but is not possible in your problem, but you can replace the NA values by 0 in the dataframe before this operation. If you don´t want to change the original dataframe you can transform it in a copy.</p>
<pre><code>ag=data.replace(np.nan,0).groupby(['A']).agg({'B':'sum','C':'sum'})... | python-3.x|pandas|aggregate | 0 |
1,166 | 47,986,269 | Preprocess the input data slow down the input pipeline when using Tensorflow Dataset API to read TFRecords file | <p>I am using Tensorflow Dataset API to read TFRecords files, but the GPU usage is still low (10%). I reckon the cause is that I preprocess the data before they are fed into the <code>sess.run()</code>. Here is my code below.<br>
1. Create a dataset from 3 separate files. </p>
<pre><code>tf.reset_default_graph()
# T... | <p>Can you share the code of <code>_data_generate</code> function?
I can't see what it does.</p>
<p>As you pointed out performance is likely lost because of RAM <-> GPU
memory swap and mixing tensorflow ops with pythonic ones.</p>
<p>Instead of running iterator <code>data_iter</code> yourself by <code>sess.run()... | python|performance|tensorflow|tfrecord | 1 |
1,167 | 47,741,873 | Unable to install Numpy on AWS EC2 Python 3.6 | <p>I have an Amazon EC2 instance running Amazon Linux and a virtual environment with python 3.6.</p>
<p>I can't seem to install Numpy :</p>
<pre><code>(testenv) [ec2-user@ip-xxx-xx-xx-xx venv]$ pip3 install numpy
Collecting numpy
Using cached numpy-1.13.3-cp36-cp36m-manylinux1_x86_64.whl
Installing collected packag... | <p>I got same problem and found a solution that worked for me on that website : <a href="https://samsblogofthings.wordpress.com/2016/07/17/installing-numpy-on-your-amazon-ec2-instance-for-a-particular-python-version/" rel="nofollow noreferrer">https://samsblogofthings.wordpress.com/2016/07/17/installing-numpy-on-your-a... | python|numpy|amazon-ec2 | 1 |
1,168 | 47,861,085 | using recently created attributes in pandas dataframe to create new attribute | <p>I'm looking for the equivalent of R's mutate, which allows you to reference defined variables immediately after creating them <em>within the same mutate call</em>. </p>
<pre><code>new_df <- old_df %>%
mutate(new_col = ifelse(something, 0, 1),
newer_col = ifelse(new_col == 0, 'yay', 'nay'))
</co... | <p>Using dict in <code>assign</code> </p>
<pre><code>df.assign(**{'less_than_6' :lambda x : np.where(x['numbers'] < 6, 100, 0)}).assign(**{'pass_fail':lambda x : np.where(x['less_than_6'] == 100, 'pass', 'fail')})
Out[202]:
names numbers less_than_6 ... | python|r|pandas|dataframe|dplyr | 2 |
1,169 | 47,971,809 | Pandas Map creating NaNs | <p>My intention is to replace labels. I found out about using a dictionary and map it to the dataframe. To that end, I first extracted the necessary fields and created a dictionary which I then fed to the map function. </p>
<p>My programme is as follows:</p>
<pre><code>factor_name = 'Help in household'
df = pd.read_c... | <p>Try this:</p>
<pre><code>In [140]: df['Help in household'] \
.astype(str) \
.map(labels.loc[labels['Column']=='Help in household',['Level','Rename']]
.set_index('Level')['Rename'])
Out[140]:
0 Every day
1 Once a week
2 Every day
3 Every day
4 ... | python|pandas|csv | 1 |
1,170 | 47,873,380 | Recursive integration with array - Stefan Boltzmann law | <p>I'm trying to plot Stefan Boltzmann law via integrating Planck law. When I set one temperature, say T=3000, the code produces its integration well. However, when I make T as array like np.array([310,3000,5800,15000]), the code gives me errors. Attached image is a plot that I am trying to reproduce. Anyone who have i... | <p>You would need to do the integration for each temperature separately. </p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import quad
h = 6.626e-34
c = 2.9979e+8
k = 1.38e-23
temps=np.linspace(300,15000)
def integrand(wav,T):
return (2.0*3.14*h*c**2)/ ( ((wav*1e3*1e-9)**5)... | numpy|matplotlib|scipy | 1 |
1,171 | 49,074,599 | Writing a nested list into CSV (Python) | <p>I have a list that looks like this:</p>
<pre><code>hello = [(('case', 'iphone'), 91524), (('adapter', 'iphone'), 12233), (('battery', 'smartphone'), 88884)]
</code></pre>
<p>And I am simply trying to write it to a csv file, looking like this:</p>
<pre><code>keyword 1 keyword 2 frequency
case ... | <p>Pandas is convenient for this:</p>
<pre><code>import pandas as pd
hello = [(('case', 'iphone'), 91524), (('adapter', 'iphone'), 12233), (('battery', 'smartphone'), 88884)]
df = pd.DataFrame([[i[0][0], i[0][1], i[1]] for i in hello],
columns=['keyword 1', 'keyword 2', 'frequency'])
# keyword 1... | python|list|pandas|csv | 4 |
1,172 | 49,018,263 | map with named function vs identical lambda function providing different responses, pandas | <p>I am trying to apply a simple function to extract the month from a string column in a pandas dataframe, where the string is of the form m/d/yyyy.</p>
<p>The dataframe is called data, the date column is called transaction date, and my new proposed month column I wish to call transaction month.</p>
<p>The below work... | <p>You can extract the month via <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.month.html" rel="nofollow noreferrer"><code>pd.Series.dt.month</code></a>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'date': ['8/2/2018']})
df['date'] = pd.to_datetime(df['date'])
df['month']... | python|pandas | 0 |
1,173 | 70,064,642 | Setting the index for a pandas dataframe Python | <p>The code below creates a bunch of data tables form the dictionary below. I am trying to add <code>Values</code> as the index parameter for all the data tables but they all the table values turn into <code>nan</code>. How will I be able to change it so that the Indexes <code>0 to 2</code> are replaced with <code>Firs... | <p>Consider using the next code instead:</p>
<pre><code>for k,v in df_dic.items():
#print(f"{k}\n{v}\n")
v.index = pd.Index(Values)
v.style.set_caption(k).set_table_styles([{
'selector': 'caption',
'props': [
('color', 'red'),
('font-size', '16px'),
... | python|pandas|database|function|dictionary | 0 |
1,174 | 70,144,451 | compare column value with another value in a dataframe (weather data forecast) | <p>I need to compare my column value (113 839 values) with the mean-value(rainfall) of a category (Location)(44 values). If it is higher than my mean value it should be replaced by the mean value. My foreach does not work:</p>
<pre><code>df_rainfall = pd.DataFrame(weather_train_data_total.groupby(['Location'])['Rainfal... | <p>Without data, it's always tricky to help but you can try to adapt this:</p>
<pre><code># calculate and assign the average value for each group
df["mean_val"] = df.groupby("Location")["Rainfall"].transform("mean")
# identify rows in which the value is above the average
relevan... | python|pandas|dataframe|numpy|foreach | 0 |
1,175 | 70,168,752 | could not convert string to float: '2,550,000,000' | <p>I'm trying to fit a module to my dataframe but im getting <code>could not convert string to float: '2,550,000,000'</code> error. please take a look at my codes below:</p>
<pre><code>import tensorflow as tf
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.compose import make_column_transformer
from sk... | <p>You can specify the thousands separator when you read the file like this:</p>
<pre><code>houseprice = pd.read_csv('houseprice.csv', thousands=',')
</code></pre> | python|pandas | 3 |
1,176 | 70,320,221 | Read the data from a text file and reshape the data in python using pandas | <p>I need to convert the following text file into csv format using Python pandas.
I have a dataset in the following format. It is a text file and doesn't have header.</p>
<p><a href="https://i.stack.imgur.com/sz3o9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sz3o9.png" alt="Input text file" /></a... | <p>This code will do exactly what you want, in a simpler (and faster) way:</p>
<pre><code>with open('your_file.txt') as f:
text = f.read().strip()
lines = [[('InputFile.txt', line_no + 1, col_no + 1, cell) for col_no, cell in enumerate(re.split('\t', l.strip())) if cell != ''] for line_no, l in enumerate(re.split(... | python|pandas|text-files | 0 |
1,177 | 56,141,648 | AttributeError: module 'numpy' has no attribute 'testing' when importing sklearn library | <p>I've imported numpy together with sklearn library but I got an Error
<code>AttributeError: module 'numpy' has no attribute 'testing'</code></p>
<p>If I removed sklearn library from my code, it could run well. </p>
<p>the code is just like this:</p>
<pre><code>import numpy as np
from kumparanian import ds
from sk... | <p>Run an additional import code, example:</p>
<pre><code>import numpy.testing as npt
npt.assert_array_almost_equal(answer1, answer2)
</code></pre> | python|numpy|scikit-learn | 0 |
1,178 | 55,680,603 | pandas filter on DatetimeIndex by excluding date range | <p>I currently have a <code>pandas.DataFrame</code> which has a <code>pandas.DatetimeIndex</code> and a set of values.</p>
<p>I would like to <strong>exclude</strong> all the dates in a given <code>pandas.date_range</code> from this <code>pandas.DataFrame</code>.</p>
<p>Example code:</p>
<pre><code>dates = pd.date_r... | <p>Use <code>isin()</code>:</p>
<pre><code>df.loc[~df.index.isin(exclusion_dates)]
val
2012-02-01 100
2012-03-01 100 <-- April excluded
2012-05-01 100
2012-06-01 100
2012-07-01 100
2012-08-01 100
2012-09-01 100
2012-10-01 100
2012-11-01 100
2012-12-01 100
2013-01-01 100
2013-02-01 100
201... | python|pandas|dataframe | 3 |
1,179 | 65,033,492 | Apply multiple functions to GroupBy object in a specific order | <p>I have a dataframe <code>df</code> with at column <code>date</code> which consists of date.</p>
<p>If I want to calculate the maximum difference between the dates within each group, is that doable (without having to re-group and without using <code>.apply</code>)? If I do</p>
<pre class="lang-py prettyprint-override... | <blockquote>
<p>is that doable (without having to re-group and without using .apply)</p>
</blockquote>
<p>I think generally not, if only 2 values per groups or some another patterns of data there should be alternatives.</p>
<pre><code>#if always 2 values per id in order
df1 = df.groupby("id")['date'].agg(['mi... | python|pandas|pandas-groupby | 2 |
1,180 | 64,690,655 | Plus one in calculating area of rectangle | <pre><code>areas = (end_x - start_x + 1) * (end_y - start_y + 1)
</code></pre>
<p>Above is what use in calculating area of rectangle for non-max-suppression in two different links below, why there is a need for plus one?</p>
<p><a href="https://github.com/amusi/Non-Maximum-Suppression/blob/master/nms.py" rel="nofollow ... | <p>I guess that plus one is just used to get the exact area.
For example,
width begin in pixel 2, end in pixel 4. The exact width is 3 (pixel 2, 3, 4).
A 3 equals to 4 - 2 + 1.</p>
<p>But in my opion, it's not essential to care about that. Just make sure you cal every area in the same standard.</p> | python|numpy|tensorflow|tensorflow2.0|non-maximum-suppression | 1 |
1,181 | 64,731,513 | How to make X number of random sets of 3 from pandas column? | <p>I have a dataframe column that looks like this (roughly 200 rows):</p>
<pre><code>col1
a
b
c
d
e
f
</code></pre>
<p>I want to create a new dataframe with one column and 15 sets of 3 random combinations of the items in the pandas column. for example:</p>
<p>new_df</p>
<pre><code>combinations:
(a,b,c)
(a,c,d)
(a,d,c)
... | <p>While not quite as elegant as the previous answers, If you truly want to create a random sampling of values, not just the first you could also do something along the lines of the following:</p>
<pre><code>def newFrame(df: pd.DataFrame, srccol: int, cmbs: int, rows: int) -> pd.DataFrame:
il = df[srccol].values... | python-3.x|pandas | 1 |
1,182 | 65,029,458 | Insert a row in a specific cell using pandas? | <p>Is there a way to start inserting rows from a specific cell using pandas? I attach an example for better understanding, The red mark is where I want to insert the row:</p>
<pre><code>header header header header header header
DATA DATA xxxxxx empty empty empty
DA... | <p>I'm going off the example table above, starting with a csv without the column of 'x's.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.read_csv('example.csv')
new_col = ['xxxx']*len(df)
df['header_insert'] = new_col
</code></pre>
<p>This will insert a new column in the right most pos... | python|pandas|csv | 0 |
1,183 | 40,023,026 | Pandas Split 9GB CSV into 2 5GB CSVs | <p>I have a 9GB CSV and need to split it into 2 5GB CSVs.
I started out doing this:</p>
<pre><code>for i, chunk in enumerate(pd.read_csv('csv_big_file2.csv',chunksize=100000)):
chunk.drop('Unnamed: 0',axis=1,inplace=True)
chunk.to_csv('chunk{}.csv'.format(i),index=False)
</code></pre>
<p>What I need to do is ... | <p>Solution is a little messy. But this should split the data based on the ~6 billion row threshold you mentioned. </p>
<pre><code>import pandas as pd
from __future__ import division
numrows = 6250000000 #number of rows threshold to be 5 GB
count = 0 #keep track of chunks
chunkrows = 100000 #read 100k rows at a tim... | python|python-3.x|csv|pandas | 3 |
1,184 | 39,611,122 | Python cv2 TypeError: src is not a numpy array, neither a scalar | <p>The following code gives the error: ""TypeError: src is not a numpy array, neither a scalar"" by using cv2.The image is defined as Grey level image with photoimage. The image is displayed correctly and I don't understand why it doesn't work.</p>
<pre><code> #Photoimage
self.imgTk=ImageTk.PhotoImage(img)
... | <p>For opencv You need to pass the image as numpy array</p>
<p>In your function def find_balls(self): do the following</p>
<p>Add a line immediately inside the function</p>
<pre><code>def find_balls(self):
#Add this Line
temp_image = cv2.imread(self.imgTk)
#This will read the image and convert it to a n... | python|arrays|numpy | 0 |
1,185 | 39,439,054 | How do I get the index of a column by name? | <p>Given a <code>DataFrame</code></p>
<pre><code>>>> df
x y z
0 1 a 7
1 2 b 5
2 3 c 7
</code></pre>
<p>I would like to find the index of the column by name, e.g., <code>x</code> -> 0, <code>z</code> -> 2, &c.</p>
<p>I can do</p>
<pre><code>>>> list(df.columns).index('y')
1
</code... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_loc.html" rel="nofollow"><code>Index.get_loc</code></a>:</p>
<pre><code>print (df.columns.get_loc('z'))
2
</code></pre>
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.se... | python|python-2.7|pandas | 1 |
1,186 | 39,581,300 | Python ImageIO Gif Set Delay Between Frames | <p>I am using ImageIO: <a href="https://imageio.readthedocs.io/en/latest/userapi.html" rel="noreferrer">https://imageio.readthedocs.io/en/latest/userapi.html</a> , and I want to know how to set delay between frames in a gif.</p>
<p>Here are the relevant parts of my code.</p>
<pre><code>import imageio
. . .
imageio.... | <p>Found it using <code>imageio.help("GIF")</code> you would pass in something like</p>
<p><code>imageio.mimsave(args.output + '.gif', ARR_ARR, fps=$FRAMESPERSECOND)</code></p>
<p>And that seems to work.</p> | python|image|numpy|gif | 7 |
1,187 | 39,710,903 | pd.read_html() imports a list rather than a dataframe | <p>I used <code>pd.read_html()</code> to import a table from a webpage but instead of structuring the data as a dataframe Python imported it as a list. How can I import the data as a dataframe? Thank you!</p>
<p>The code is the following:</p>
<pre><code>import pandas as pd
import html5lib
url = 'http://www.fdic.g... | <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html" rel="noreferrer"><code>.read_html()</code></a> produces a <em>list of dataframes</em> (there could be multiple tables in an HTML source), get the desired one by index. In your case, there is a single dataframe:</p>
<pre><code>dfs ... | python|html|pandas | 20 |
1,188 | 39,819,090 | For loop to evaluate accuracy doesn't execute | <p>So I've the following numpy arrays.</p>
<ul>
<li>X validation set, X_val: (47151, 32, 32, 1)</li>
<li>y validation set (labels), y_val_dummy: (47151, 5, 10) </li>
<li>y validation prediction set, y_pred: (47151, 5, 10)</li>
</ul>
<p>When I run the code, it seems to take forever. Can someone suggest why? I believe... | <p>You're main problem is that you're generating a massive number of very large lists for no real reason</p>
<pre><code>for i in range(X_val.shape[0]):
# this line generates a 47151 x 5 x 10 array every time
pred_list_i = [y_pred_array[i] for y_pred in y_pred_array]
</code></pre>
<p>What's happening... | python|numpy | 0 |
1,189 | 44,110,138 | Python: numpy and scipy minimize: setting an array element with a sequence minimize | <p>I'm trying to minimize the function, but get an </p>
<blockquote>
<p><strong>ValueError: setting an array element with a sequence.</strong></p>
</blockquote>
<p>in the following code:</p>
<pre><code>import numpy as np
from scipy import optimize as opt
def f(x):
return np.sin(x / 5.) * np.exp(x / 10.) + 5 *... | <p>Check the dimensions of both x inside the function <code>f()</code> and its returning value during the mininization, when you find the problem probably the function <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html" rel="nofollow noreferrer">flatten()</a> will help.</p> | python|arrays|numpy|scipy|minimize | 0 |
1,190 | 69,482,493 | How can i implement the __getitem__ method in PyTorch for the sinus | <p>I am starting with PyTorch and i am trying to create a Network that is predicting the sinus of x. I tried to create a DataSet like this:</p>
<pre><code> class SinusDataset(Dataset):
def __init__(self, size: int = 1000):
self.size = size
def __len__(self):
return self.size
def __getite... | <p>You could initialize your input and labels on init and save those in <em>list</em>s. Then, in your <code>__getitem__</code> function, pick instances from those two using the provided <code>idx</code> integer. Something like:</p>
<pre><code>class SinusDataset(Dataset):
def __init__(self, size: int = 1000):
... | python|pytorch | 3 |
1,191 | 69,323,196 | Environment issues with running Anaconda Python in VS Code | <p>I am trying to learn Python and debug code for the first time in VS Code (latest edition). I have anaconda running and the code I have runs fine by itself but now I need to know how to update the code and debug it for the first time.</p>
<p>I keep getting the following error related to NumPy:</p>
<blockquote>
<p>Ex... | <p>You should launch VS Code from Anaconda Navigator so that the environment is initialized.</p> | python|numpy|visual-studio-code|anaconda|python-3.7 | 0 |
1,192 | 38,319,646 | TensorFlow and preparing data for MS COCO | <p>I can't quite figure out how to prepare the data to use with the MS COCO dataset. I'm currently saving all of the data in <code>TFRecord</code>s. For each record, I need to save the jpeg data as well as all of the annotations. For each image, there can be up to ~20 annotations and for each of those annotations, ther... | <p>You might be better off either (1) putting all annotations as the same feature or (2) always putting all features in all examples, but leaving empty values for the absent ones.</p> | python|json|tensorflow | 0 |
1,193 | 38,337,918 | Plot pie chart and table of pandas dataframe | <p>I have to plot pie-chart and a table side by side using matplotlib.</p>
<p>For drawing the pie-chart, I use the below code:</p>
<pre><code>import matplotlib.pyplot as plt
df1.EventLogs.value_counts(sort=False).plot.pie()
plt.show()
</code></pre>
<p>For drawing a table, I use the below code:</p>
<pre><code>%%char... | <p>Look at the code:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
from pandas.tools.plotting import table
# sample data
raw_data = {'officer_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
'jan_arrests': [4, 24, 31, 2, 3],
'feb_arrests': [25, 94, 57, 62, 70],
'march_arr... | python|pandas|matplotlib | 44 |
1,194 | 38,494,300 | Flatten/ravel/collapse 3-dimensional xr.DataArray (Xarray) into 2 dimensions along an axis? | <p>I have a dataset where I'm storing replicates for different classes/subtypes (not sure what to call it) and then attributes for each one. Essentially, there are 5 subtype/classes, 4 replicates for each subtype/class, and 100 attributes that are measured. </p>
<p><strong>Is there a method like <code>np.ravel</code>... | <p>Yes, this is exactly what the <code>.stack</code> is for:</p>
<pre><code>In [33]: stacked = DA_data.stack(desired=['subtype', 'replicates'])
In [34]: stacked
Out[34]:
<xarray.DataArray (attributes: 100, desired: 20)>
array([[ 0.54020268, 0.14914837, 0.83398895, ..., 0.25986503,
0.62520466, 0.086... | python|arrays|pandas|multidimensional-array|python-xarray | 5 |
1,195 | 66,324,928 | In a series with mixed data types, how to transform occasional lists and dicts into strings? | <p>I'm trying to clean up a json file with all my own Telegram messages from a certain chat where I receive notifications from a bot. Although the messages are pretty clean in the application, in the json file they get a bit messy. For example, the one-line Telegram message below...</p>
<pre><code>Xparty P-Q D-21-01-30... | <p>This should do the trick:</p>
<pre><code>import json
df['messages'] = df['messages'].apply(lambda x: json.dumps(x))
</code></pre> | json|python-3.x|pandas | 1 |
1,196 | 66,234,450 | Sorting an array along its last dimension, and undoing the sorting | <p>In my current project, I have a D-dimensional array. For the sake of exposition, we can assume D=2, but the code should work with arbitrarily high dimensions. I need to run some operations on this matrix when it is sorted according to its last dimension, and subsequently reverse the sorting on the matrix.</p>
<p>The... | <p>So yes, after following <a href="https://stackoverflow.com/users/3874623/mark-m">Mark M</a>'s suggestion, and reading up on some other StackOverflow answers continuing from there, the answer seems to be as follows:</p>
<pre><code>import numpy as np
# Create the initial random matrix
D = 2
matrix ... | python|arrays|python-3.x|numpy|sorting | 0 |
1,197 | 52,870,248 | How to remove columns where Multiindex levels equal NaN (no value) from a dataframe | <p>I am trying to remove columns from a dataframe with Multiindex, as for some of the columns my levels equal <code>NaN</code> (null). I tried to use dropna() but it works only for rows I assume:
<a href="https://i.stack.imgur.com/nRpvg.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nRpvg.jpg" alt="... | <p>Try to reset the index and re-indexing again like this:</p>
<pre><code>old_idx = df.index.names
my_new_df = df.reset_index().dropna().set_index(old_idx)
</code></pre>
<p>That's should be able to solve it, hope it helps somehow.</p> | python|pandas | 2 |
1,198 | 58,255,759 | 80 Gb file - Creating a data frame that submits data based upon a list of counties | <p>I am working with an 80 Gb data set in Python. The data has 30 columns and ~180,000,000 rows. </p>
<p>I am using the chunk size parameter in <code>pd.read_csv</code> to read the data in chunks where I then iterate through the data to create a dictionary of the counties with their associated frequency.</p>
<p>This ... | <h1>The idea</h1>
<p>I was not sure whether you have data for different <strong>counties</strong> (e.g. in UK or USA)
or <strong>countries</strong> (in the world), so I decided to have data concerning <strong>countries</strong>.</p>
<p>The idea is to:</p>
<ul>
<li>Group data from each chunk by country.</li>
<li>Gene... | python|pandas|dataframe|bigdata | 1 |
1,199 | 58,247,405 | Using static rnn getting TypeError: Cannot convert value None to a TensorFlow DType | <p>First some of my code:</p>
<pre><code>...
fc_1 = layers.Dense(256, activation='relu')(drop_reshape)
bi_LSTM_2 = layers.Lambda(buildGruLayer)(fc_1)
...
def buildGruLayer(inputs):
gru_cells = []
gru_cells.append(tf.contrib.rnn.GRUCell(256))
gru_cells.append(tf.contrib.rnn.GRUCell(128))
gru_layers = tf.keras.lay... | <p>If anyone still needs a solution to this. Its because you need to specify the dtype for the GRUCell, e.g tf.float32</p>
<p>Its default is None which in the documentation defaults to the first dimension of your input data (i.e batch dimension, which in tensorflow is a ? or None)</p>
<p>Check the dtype argument from... | tensorflow|keras|tf.keras | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.