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 |
|---|---|---|---|---|---|---|
377,000 | 36,519,546 | Advice needed: convert objects of dataframe in pandas | <p>I have following dataframe that I try to convert it's data type.</p>
<pre><code>In [5]:
df = pd.io.json.json_normalize(data)
df.head()
Out[5]:
a b c d e f g
2014-09-10 5.38 5.45 5.35 1769 10000002 34 6651569991
2014-09-11 5.44 5.48 5... | <p>Use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="noreferrer">apply</a> function.</p>
<pre><code>In [34]: df = df.apply(lambda x: pd.to_numeric(x), axis=0)
In [36]: df.dtypes
Out[36]:
a float64
b float64
c float64
d int64
e int64
f int6... | python-3.x|pandas|multidimensional-array|dataframe|type-conversion | 5 |
377,001 | 36,440,158 | Creating a Pandas Panel with Non-Unique Index Objects | <p>I have the following data file <code>LawSchoolSample.csv</code>:</p>
<pre><code>LSAT,GPA
622,3.23
542,2.83
579,3.24
653,3.12
606,3.09
</code></pre>
<p>I'd like to create a pandas dataframe, and then resample from this dataframe <code>B</code> times to form a pandas panel. Here's my attempt (critiques welcomed):</... | <p>The long term plan is to deprecate <code>Panel</code>, see pandas documentation:</p>
<blockquote>
<p>In a future version of pandas, we will be deprecating Panel and other
>2 ndim objects. In order to provide for continuity, all NDFrame objects have gained the .to_xarray() method in order to convert to
xarray ... | python|pandas | 0 |
377,002 | 36,636,461 | How to sum column values with cross-column matching? | <p>Python Pandas question:</p>
<p>I have a table with 3 columns: From_City, To_City, Trip_Count and 4 rows:</p>
<p><code>+-----------+---------+------------+
| From_City | To_City | Trip_Count |
+-----------+---------+------------+
| Berlin | London | 2 |
| London | Berlin | 3 |
| Sydney ... | <pre><code>import pandas as pd
df = pd.DataFrame({'From_City': ['Berlin', 'London', 'Sydney', 'Tokyo'], 'To_City': ['London', 'Berlin', 'Tokyo', 'Sydney'], 'Trip_Count': [2, 3, 4, 6]})
print df.apply(lambda x: sorted(x[:2].tolist())+[x[2]], axis=1).groupby(['From_City', 'To_City']).sum()
</code></pre>
<p>result</p>
... | python|pandas | 1 |
377,003 | 36,393,247 | Pandas dateframe reshape | <p>I am playing with some date looks like below .</p>
<pre><code> song_id action_type ds
0 effb071415be51f11e845884e67c0f8c 1 14 days
1 f87ff481d85d2f95335ab602f38a7655 1 13 days
2 8a27d9a6c59628c991c154e8d93f412e 2 12 days
3 ecea5fe33e6817d09c395f2910479728 1 11 d... | <pre><code>>>> (df.groupby(['song_id', 'ds', 'action_type'])
.action_type
.sum()
.unstack(['action_type', 'ds'])
.fillna(0)
.sortlevel(level=[0, 1], axis=1))
action_type 1 2
ds ... | python|pandas|data-processing | 2 |
377,004 | 36,589,521 | How to surface plot/3d plot from dataframe? | <p>I am new to <code>pandas</code> and <code>matplotlib</code>. Couldn't able to get exact reference to plot my <code>DataFrame</code> whose schema is as follows</p>
<pre><code>schema = StructType([
StructField("x", IntegerType(), True),
StructField("y", IntegerType(), True),
StructField("z&quo... | <p><code>.plot_surface()</code> takes <code>2D</code> <code>arrays</code> as inputs, not <code>1D</code> <code>DataFrame</code> columns. This has been explained quite well <a href="https://stackoverflow.com/questions/9170838/surface-plots-in-matplotlib">here</a>, along with the below code that illustrates how one could... | python|numpy|pandas|matplotlib|dataframe | 45 |
377,005 | 36,627,268 | Python-control - step system | <p>When I create a system using the python-control package:</p>
<pre><code>import control
H = control.tf([1], [1])
</code></pre>
<p>And then want to <em>iteratively</em> simulate that system, how do I do it?</p>
<p>I know I can do this:</p>
<pre><code>T = np.arange(0, 10, 0.01)
u = np.sin(T)
y, t, x = control.lsim(... | <p>This is a great question. I am interested in this myself and asked a <a href="https://www.mathworks.com/matlabcentral/answers/513684-how-to-step-through-a-discrete-model-simulation-one-step-at-a-time?s_tid=srchtitle" rel="nofollow noreferrer">similar question</a> on the Mathworks forum a while ago and it's not curr... | python|numpy|scipy|python-control | 1 |
377,006 | 36,548,736 | TensorFlow: Unpooling | <p>Is there TensorFlow native function that does unpooling for Deconvolutional Networks ? </p>
<p>I have written this in normal python, but it is getting complicated when want to translate it to TensorFlow as it's objects does not even support item assignment at the moment, and I think this is a great inconvenience wi... | <p>I don't think there is an official unpooling layer yet which is frustrating because you have to use image resize (bilinear interpolation or nearest neighbor) which is like an average unpooling operation and it's reaaaly slow. Look at the tf api in the section 'image' and you will find it. </p>
<p>Tensorflow has a m... | tensorflow|conv-neural-network|deconvolution | 16 |
377,007 | 36,428,059 | Why does the efficiency of numpy not scale | <p>I have been comparing the relative efficiency of numpy versus Python list comprehensions in multiplying together arrays of random numbers. (Python 3.4/Spyder, Windows and Ubuntu).</p>
<p>As one would expect, for all but the smallest arrays, numpy rapidly outperforms an list comprehension, and for increasing array l... | <p>The garbage collector explains the bulk of it. The rest could be fluctuation based on other programs running on your machine.
How about turning most things off and running the bare minimum and testing it. Since you are using datetime (which is the actual time passed) it must be taking into account any processor cont... | python|arrays|numpy | 3 |
377,008 | 5,490,723 | What alternatives are there to numpy on Google App Engine? | <p>What alternatives can you recommend to numpy to use on the Google App Engine?</p>
<p>Specifically I'm interested in matrix manipulations on large matrices. </p> | <p>The Python 2.7 runtime <a href="https://developers.google.com/appengine/docs/python/tools/libraries27" rel="nofollow noreferrer">includes NumPy 1.6.1</a>.</p> | python|google-app-engine|numpy | 12 |
377,009 | 53,238,019 | How do I create a debug build of a recent Tensorflow version with CUDA Support? | <p>I tried and tried to create a debug build for a recent version of Tensorflow , using the official docker images (latest-cuda-devel-py3 -> r1.12.0) but nothing seems to work. Has someone recently created a successful debug build for Tensorflow (>= r1.11.0) and can share his approach ?</p>
<p>This is what I tried so ... | <p>Just in case someone else stumbles over this problem. I finally got it to compile, using the following command:</p>
<pre><code>bazel build --config cuda --strip=never --copt="-DNDEBUG" --copt="-march=native" --copt="-Og" --copt="-g3" --copt="-mcmodel=medium" --copt="-fPIC" //tensorflow/tools/pip_package:build_pip_... | c++|tensorflow|build|bazel|debug-symbols | 7 |
377,010 | 53,225,011 | Reshape Pandas dataframe by specific string | <p>I have a csv dataset that looks like this:</p>
<pre><code>###12345
LABEL text
LABEL text
###12213
LABEL text
LABEL text
</code></pre>
<p>I want to transform it to that shape</p>
<pre><code>12345 LABEL text
12345 LABEL text
12213 LABEL text
</code></pre>
<p>My first approach was to filter... | <p>Use:</p>
<pre><code>print (df)
label
0 ###12345
1 LABEL text
2 LABEL text
3 ###12213
4 LABEL text
5 LABEL text
</code></pre>
<hr>
<pre><code>#boolean mask
m = df['label'].str.contains("###", na=False)
#helper column with repalce non ### values to NaNs and repalce it ... | python|pandas | 0 |
377,011 | 53,225,258 | Numpy ignoring frames of TIF file when converting from PIL | <p>I have 3 diemnsional image saved as a multi page tif file. I tried reading it in using PIL(low) and it detected the correct number of frames but when I convert it to numpy it ignores the frames and only converts the single page/layer. </p>
<pre><code>from PIL import Image
import numpy as np
pil_ = Image.open(path)... | <p>There's a thread here (<a href="https://mail.python.org/pipermail/python-list/2007-May/419217.html" rel="nofollow noreferrer">https://mail.python.org/pipermail/python-list/2007-May/419217.html</a>) which suggests that you may be able to manually seek through the frames and assign each one into the 3rd dimension of y... | python|numpy|python-imaging-library | 1 |
377,012 | 53,330,074 | Unexpected result in calculating payments | <p>I have a matrix of numbers that look like this:</p>
<pre><code>[[ 0. 771.98 0. ..., 771.98 0. 1543.96]
[ 1320.83 4782.33 1320.83 ..., 1954.45 0. 1954.45]
[ 2043.61 0. 4087.22 ..., 4662.3 2907.82 1549.53]
...,
[ 427.6 0. 427.6 ..., 427.6 0. 427.6 ... | <p>You got this result because you are re-assigning your <code>payment</code> in each loop. Try change <code>payment = cf[:i+1] / cpi[i]</code> to <code>payment += cf[:i+1] / cpi[i]</code></p>
<p>As you added numpy to the tags I think an easier way would be using numpy:</p>
<pre><code>import numpy as np
a = np.arange... | python|numpy | 1 |
377,013 | 53,345,594 | Groupby first two earliest dates, then average time between first two dates - pandas | <p>I'm hoping to groupby users and find the first two uploads. I've figured out how to get the first date via minimum, but I'm having trouble getting that second upload date. Then would like to get the average time between the two upload dates for all users.</p>
<p>df:</p>
<pre><code>Date_Uploaded User_ID Display_S... | <p>Using <code>sort_values</code> + <code>head</code></p>
<pre><code>df.sort_values('Date_Uploaded').groupby('User_ID').head(2)
Out[152]:
Date_Uploaded User_ID Display_Status
6 2018-07-25 efg123 Pending
5 2018-08-01 efg123 Pending
3 2018-09-21 abc123 Pending
0 2018-10-27 abc123 ... | python|pandas | 2 |
377,014 | 52,933,379 | Calculate days between 2 datetime columns in dask dataframe | <p>I have a dask dataframe that contains two columns, which is string format, like this</p>
<pre><code>start_date end_date
2018-09-01 2018-10-01
2018-09-02 2018-09-22
...
</code></pre>
<p>I would like to calculate the number of days between the two columns. If it is a pandas dataframe, I can do:</p>
<pre><code>df... | <p><a href="http://docs.dask.org/en/latest/dataframe.html" rel="nofollow noreferrer"><code>dask.dataframe</code></a> supports a useful subset of the Pandas API, including <a href="http://docs.dask.org/en/latest/dataframe-api.html#dask.dataframe.Series.dt" rel="nofollow noreferrer"><code>Series.dt</code></a> methods. Th... | python|pandas|datetime|dataframe|dask | 3 |
377,015 | 53,189,712 | Generating binary segmentation file for lane detection in Python/Tensorflow (Tusimple Lanenet Dataset) | <p>I was using the code from <a href="https://github.com/MaybeShewill-CV/lanenet-lane-detection" rel="nofollow noreferrer">https://github.com/MaybeShewill-CV/lanenet-lane-detection</a> which using Deep Learning to detect road lane lines.</p>
<p>I successfully tested the model. Now I want to retrain the model on my own... | <p>I will just drop an answer here (Don't know if it's good to answer an old question).</p>
<pre><code>label = '0601'
labe_filename = 'label_data_%s.json' % label
clips = [json.loads(line) for line in open(labe_filename).readlines()]
for clip in clips:
lanes = clip['lanes']
filepath = clip['raw_file']
ysa... | python|opencv|tensorflow|image-processing|computer-vision | 0 |
377,016 | 53,251,860 | Best way to go towards an index in numpy, with wrap | <p>Lets say I have a 2D array below:</p>
<pre><code> [[ 0 0 0 0 0 0 ]
[ 0 0 0 0 0 0 ]
[ 0 0 0 0 0 0 ]
[ 0 0 0 0 0 2 ]
[ 0 1 0 0 0 0 ]
[ 0 0 0 0 0 0 ]]
</code></pre>
<p>I would like to get the direction from where '1' (index 4,1) is to '2' (index 3,5). Assuming directions are only up, down, left, right. Thu... | <p>Well, there is a quite simple formula for computing the distance in case of periodic boundary conditions. Below I consider only periodic b.c. on x-axis:</p>
<pre><code>import numpy as np
# periodic boundary condition for the x-axis only
def steps(start, dest, L_x):
x_start = start[1]
y_start = start[0]
... | python|arrays|numpy|matrix | 0 |
377,017 | 53,286,656 | Write python simulation output to a matrix | <p>I am trying to take the sum of four columns in a pandas dataframe (which are determined by a random number) and simulate this process 1000 times. I want this to give me 1000 rows each with different results, for each column. </p>
<p>I essentially want to say something like the following:</p>
<pre><code>for i in ra... | <p>Take the sum of four columns in a pandas dataframe (which are determined by a random number) and simulate this process 1000 times. This should give me 1000 rows each with different results, for each column. We can write:</p>
<pre><code>import os
import pandas as pd
import numpy as np
import random
from tqdm import ... | pandas|numpy | 1 |
377,018 | 53,223,103 | Pandas dataframe columns after groupby | <p>here I had solved one my problem:
<a href="https://stackoverflow.com/questions/53133174/pandas-duplicates-groupby?noredirect=1#comment93160647_53133174">Pandas duplicates groupby</a></p>
<p>Now, after using the command:</p>
<pre><code>df.groupby('Names').agg({'Column1':'sum', 'Column2':'sum','Column3':'min'})
</co... | <p>Specify parameter <code>as_index=False</code> while grouping:</p>
<pre><code>df.groupby('Names', as_index=False).agg(
{'Column1':'sum', 'Column2':'sum','Column3':'min'})
Names Column1 Column2 Column3
0 Bob 3 3 2011
1 John 4 5 2005
2 Pier 1 1 2003
<... | python|pandas|dataframe|group-by|pandas-groupby | 2 |
377,019 | 53,264,042 | Scipy ValueError: object too deep for desired array with optimize.leastsq | <p>I am trying to fit my 3D data with linear 3D function Z = a<em>x+b</em>y+c. I import the data with pandas:</p>
<pre><code>dataframe = pd.read_csv('3d_data.csv',names=['x','y','z'],header=0)
print(dataframe)
x y z
0 52.830740 7.812507 0.000000
1 44.647931 61.031381 8.827942... | <p>If you are fitting parameters to a function, you can use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html" rel="nofollow noreferrer">curve_fit</a>. Here's an implementation:</p>
<pre><code>from scipy.optimize import curve_fit
def model_calc(X, a, b, c):
x, y = X
r... | python|numpy|scipy|data-fitting|function-fitting | 1 |
377,020 | 52,906,275 | Altair: Use of color scheme with log scales | <p>I'm new to Altair and I'm trying to make a heatmap with a log scale for color, and also select a non-default color scheme (the default scheme uses very little extent, and also I want light-to-dark colors). I find that I can easily get a log scale with <code>type=log</code>, but that once I do that, the <code>scheme... | <p>I think this must have been a bug. I can't find the the issue on github where this behavior was fixed but the code you have posted appears to be working as expected now. I am running atair version <code>'3.2.0'</code>. </p>
<pre><code>import numpy as np
import pandas as pd
import altair as alt
from plotnine.data i... | python|numpy|altair | 6 |
377,021 | 53,291,987 | Filtering Max 3 count using groupby in pandas | <p>I am working with a dataframe that contains 20K rows.
I created a sample dataframe as follow to replicate the data frame.</p>
<pre><code>df = pd.DataFrame()
df ['Team'] = ['A1','A1','A1','A2','A2','A2','B1','B1','B1','B2','B2','B2']
df ['Competition'] = ['L1','L1','L1','L1','L1','L1','L2','L2','L2','L2','L2','L2']
... | <p><code>groupby</code> <em>Team</em> and <em>Competition</em> and then take the two largest values with <code>.nlargest</code>:</p>
<pre><code>df.groupby(['Team', 'Competition']).Score_count.nlargest(2).reset_index([0,1])
# Team Competition Score_count
#2 A1 L1 3
#0 A1 L1 ... | python|pandas|filter|max | 2 |
377,022 | 53,346,940 | Using np.where to find element from sub-arrays | <p>I'm trying to find all elements in array X that match element on array Y using np.where() and the condition on where() function is comparing list (a) not one element. Please see the following code:</p>
<pre><code>X = np.array([[0, 2], [2, 1], [1, 3], [5, 9], [6, 7], [4, 6]])
Y = np.array([1, 2, 3, 4, 4, 5])
a = [2,... | <p>You can use the set functions of numpy:</p>
<pre><code>X[np.where(np.isin(Y, a))]
array([[2, 1],
[1, 3],
[5, 9],
[6, 7]])
</code></pre> | python|numpy | 1 |
377,023 | 52,922,690 | Split n-dimensional array into 2D arrays along each axis | <p>So say I have an array of arbitrary dimensions (for now, we'll give it three dimensions).</p>
<pre><code>a=array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7]],
[[ 8, 9, 10, 11],
[12, 13, 14, 15]],
[[16, 17, 18, 19],
[20, 21, 22, 23]]])
</code></pre>
<p>What would be the simplest way to split this arra... | <p>Try This:</p>
<pre><code>b = []
for i in a:
b.append([item for sublist in i for item in sublist])
</code></pre>
<p>Output:</p>
<pre><code>[[0, 1, 2, 3, 4, 5, 6, 7],
[8, 9, 10, 11, 12, 13, 14, 15],
[16, 17, 18, 19, 20, 21, 22, 23]]
</code></pre> | python|arrays|numpy | 0 |
377,024 | 53,223,280 | Predicting using adanet for binary classification problem | <p>I followed the tutorial of adanet:
<a href="https://github.com/tensorflow/adanet/tree/master/adanet/examples/tutorials" rel="nofollow noreferrer">https://github.com/tensorflow/adanet/tree/master/adanet/examples/tutorials</a>
and was able to apply adanet to my own binary classification problem.</p>
<p>But how can I ... | <p>You can immediately call <a href="https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator?version=stable#predict" rel="nofollow noreferrer"><code>estimator.predict</code></a> on a new unlabeled example and get a prediction.</p> | tensorflow|predict | 1 |
377,025 | 52,995,453 | How to plot training error , validation error and prediction accuracy over training progress in tensorflow? | <p>I am running Vanilla RNN code on tensorflow in google colab. I want to plot training error, validation error and prediction accuracy over training progress without using tensorboard. I am new to tensorflow. Can anyone please guide me. Here is a part of my code </p>
<pre><code> # Model predictions
cls_pred... | <p>One such way would be to store the values in a list, then use something like <a href="https://matplotlib.org/tutorials/introductory/pyplot.html" rel="nofollow noreferrer">matplotlib</a> to plot the values</p>
<p>Example code:</p>
<pre><code>import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some nu... | python|tensorflow|matplotlib | 1 |
377,026 | 53,292,680 | Operating on histogram bins Python | <p>I am trying to find the median of values within a bin range generated by the <code>np.histrogram</code> function. How would I select the values only within the bin range and operate on those specific values? Below is an example of my data and what I am trying to do:</p>
<pre><code>x = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0... | <p>One way is with <code>pandas.cut()</code>:</p>
<pre><code>>>> import pandas as pd
>>> import numpy as np
>>> np.random.seed(444)
>>> x = np.random.randint(0, 25, size=100)
>>> _, bins = np.histogram(x)
>>> pd.Series(x).groupby(pd.cut(x, bins)).median()
(0.0, 2.... | python|numpy|histogram|median | 2 |
377,027 | 53,269,061 | pandas dataframe sum date range of another DataFrame | <p>I have two dataframes. I want to sum an "amount" column in the 2nd, for each record in the first datafame.</p>
<p>So for each </p>
<pre><code>df1.Date = sum(df2.amount WHERE df1.Date <= df2.Date AND df1.yearAgo >= df2.Date)
df1 = pd.DataFrame({'Date':['2018-10-31','2018-10-30','2018-10-29','2018-10-28'],'ye... | <p>IIUC, your expected output should have <code>4</code> in first row.</p>
<p>You can achieve this very efficiently using <code>numpy</code>'s feature of <a href="https://docs.scipy.org/doc/numpy-1.10.4/reference/generated/numpy.ufunc.outer.html" rel="nofollow noreferrer"><code>outer</code></a> comparison, since <code... | python|pandas|dataframe | 1 |
377,028 | 52,932,209 | Google BigQuery Sum return wrong result | <p>Guys im running this query on public blockchain data, to get total burned tokens. But SUM return result much less then real(run same query without sum and run sum in Pandas). it gives 8306 while pandas 328608.</p>
<p>log.data - hex number</p>
<pre><code>SELECT
SUM(SAFE_CAST(log.data as INT64)/POW(10,18))
FROM
... | <p>The problem is that some of the <code>log.data</code> values are excluded from the <code>SUM</code>, since they don't fit in the range of <code>INT64</code> and hence the <code>SAFE_CAST(log.data AS INT64)</code> returns <code>NULL</code>. As an example, <code>0x00000000000000000000000000000000000000000000000080b797... | python|pandas|google-bigquery | 4 |
377,029 | 53,090,725 | Streaming Grid Display in Jupyter Notebook | <p>I am trying to display live price updates coming from a redis pubsub channel in a grid in Jupyter. Everytime there is a price update, the message will be added at the end of the grid. In order words, a gridview widget will be tied to a Dataframe so everytime it changes, the gridview will change. The idea is to get s... | <p>Try changing the first line of <code>output_to_widget</code> to <code>output_widget.clear_output(wait = True)</code>.</p>
<p><a href="https://ipython.org/ipython-doc/3/api/generated/IPython.display.html" rel="nofollow noreferrer">https://ipython.org/ipython-doc/3/api/generated/IPython.display.html</a></p> | python|pandas|jupyter-notebook | 1 |
377,030 | 52,953,599 | Plotting multiple columns from Different Dataframe | <p>I have been trying to make a plot in python, but I am facing challenge in syntax. I have googled but I couldn't find something suitable.</p>
<p>I have three data frames. Data in first dataframe is something like attached pic. </p>
<p><a href="https://i.stack.imgur.com/yva5D.jpg" rel="nofollow noreferrer"><img src=... | <p>You could do something like this:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
# create data:
df1 = pd.DataFrame({"City Name": ["Toronto", "NYC"],
"Temp": [10, 20],
"Rainfall": [100, 232]})
df2 = pd.DataFrame({"Max Temp": [20, 25]})
df3 = pd.DataFrame... | python|pandas|python-3.6 | 0 |
377,031 | 53,147,241 | In using keras Lambda, how do I handle "TypeError: Object arrays are not currently supported"? | <p>I'm using Keras, and I want to make a layer that takes <code>[a0, a1]</code>, <code>[b0, b1, b2]</code> as inputs and gives <code>[a0*b0, a0*b1, a0*b2, a1*b0, a1*b1, a1*b2]</code> as output. I tried to use <code>Lambda</code>, but I couldn't succeed. Here's my code:</p>
<pre><code>import numpy as np
from keras.mode... | <p>Apart from the fact that you need to use Keras backend functions (i.e. <code>keras.backend.*</code>) or use backend functions directly (i.e. <code>tf.*</code> or <code>th.*</code>), I think you are making the definition of <code>mix</code> unnecessarily complicated. It can be done much simpler like this:</p>
<pre><... | python|numpy|tensorflow|keras|keras-layer | 1 |
377,032 | 53,300,965 | Pytorch Exception in Thread: ValueError: signal number 32 out of range | <p>I'm getting this error:</p>
<pre><code>Exception in Thread: ValueError: signal number 32 out of range
</code></pre>
<p>The specific tutorial that raises an issue for me is the training a classifier (<a href="https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html" rel="noreferrer">https://pytorch.org/tu... | <p>I have faced a similar issue and it got resolved when I set:</p>
<pre><code>num_workers=0
</code></pre> | python|pytorch | 11 |
377,033 | 53,161,212 | Getting percentage for each column after groupby | <p>I have a pandas dataframe with two columns <code>A</code> and <code>B</code>. The column <code>B</code> contains three categories <code>X</code>, <code>Y</code>, 'Z'. I need to check the how much percentage is a particular value for each group in A. Here is how the dataframe looks like:</p>
<pre><code> A B
AA ... | <p>You can find the row-wise sum and divide along the axis something like this:</p>
<pre><code>freq_df = df.groupby(['A'])['B'].value_counts().unstack()
pct_df = freq_df.divide(freq_df.sum(axis=1), axis=0)
</code></pre>
<p>And then to plot that you should simply be able to use</p>
<pre><code>pct_df.plot(kind="bar", ... | python|python-3.x|pandas|data-visualization | 4 |
377,034 | 52,982,056 | How to convert numpy datetime64 [ns] to python datetime? | <p>I need to convert dates from pandas frame values in the separate function:</p>
<pre><code> def myfunc(lat, lon, when):
ts = (when - np.datetime64('1970-01-01T00:00:00Z','s')) / np.timedelta64(1, 's')
date = datetime.datetime.utcfromtimestamp(ts)
print("Numpy date= ", when, " Python date= ", ... | <p>I wonder if you need all this conversion work. With the right time units a <code>datetime64</code> can produce a <code>datetime</code> object directly.</p>
<p>I'm not sure about your <code>when</code> variable, but let's assume it comes from <code>pandas</code>, and is something like a <code>DatetimeIndex</code>:<... | python|numpy | 7 |
377,035 | 52,905,360 | Summing multiple row values of various columns in Pandas | <p>I need to add row value of various columns and store it in same(or new) dataframe.
eg:
The dataframe looks something like this:</p>
<pre><code>id col1 col2 col3 col4 ... col50
1 1 12 3 44 0
1 7 0 7 2 10
1 2 3 0 4 9
3 9 0 1 ... | <p>This is a <strong>grouping aggregation</strong> by <code>id</code>. Therefore, use a <code>GroupBy</code> object:</p>
<pre><code>res = df.groupby('id', as_index=False).sum()
print(res)
id col1 col2 col3 col4 col50
0 1 10 15 10 50 19
1 3 10 1 12 1 0
</code></pre> | python|pandas|dataframe|pandas-groupby | 4 |
377,036 | 52,913,191 | How to iterate over each individual column values in multiple column dataframe? | <p>I have multiple column data frame with columns <strong>['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable']</strong>.</p>
<p>In the energy supply column, I want to convert the unit of the column to Peta from Giga. But in the process
<code>energy['Energy Supply']*= energy['Energy Supply']</code>, ... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.Series.str.isnumeric.html" rel="nofollow noreferrer"><code>str.isnumeric</code></a> to check if a string is numeric and then multiply.</p>
<pre><code>energy['Energy Supply'] = energy['Energy Supply'].apply(lambda x: int(x) * ... | python|pandas|dataframe | 2 |
377,037 | 53,196,156 | Different spectrogram between audio_ops and tf.contrib.signal | <p>I am trying to update the feature extraction pipeline of an speech command recognition model replacing the function <code>audio_ops.audio_spectrogram()</code> by <code>tf.contrib.signal.stft()</code>. I assumed that they were equivalent, but I am obtaining different spectrogram values with the same input audio. Coul... | <p>Found these helpful comments in github that discuss the differences:</p>
<p><a href="https://github.com/tensorflow/tensorflow/issues/11339#issuecomment-345741527" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/11339#issuecomment-345741527</a></p>
<p><a href="https://github.com/tensorflow... | python|tensorflow|speech-recognition | 3 |
377,038 | 53,312,259 | Rpy2 conversion of categorical data containing nulls to R factors | <p>I have a pandas dataframe with a categorical column containing NaN values, e.g.:</p>
<pre><code>g = pd.Series(["A", "B", "C", np.nan], dtype="category")
g
0 A
1 B
2 C
3 NaN
dtype: category
Categories (3, object): [A, B, C]
</code></pre>
<p>In pandas NaN is not a category but you can have NaN val... | <p>At the time of writing this is a bug with rpy2's conversion of pandas categories, that is fixed and will be included in rpy2 starting with release 2.9.5: <a href="https://bitbucket.org/rpy2/rpy2/issues/493/rpy2-conversion-of-categorical-data" rel="nofollow noreferrer">https://bitbucket.org/rpy2/rpy2/issues/493/rpy2-... | r|pandas|rpy2|categorical-data|factors | 0 |
377,039 | 53,169,808 | Exporting a pandas df to sqlite leads to duplicate datasets instead of one updated dataset | <p>I'm uploading a pandas dataframe from a csv file into a sqlite database via sqlalchmemy.
The initial filling is working just fine, but when I rerun the following code, the same data is exported again and the database contains two identical datasets.</p>
<p>How can I change the code, so that only new or changed data... | <p>This is working now, I 've added the df.to_sql code:</p>
<pre><code>import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Numeric, DateTime
from sqlalchemy.orm import sessionmaker
from datetime import datetime
i... | python|pandas|sqlite|sqlalchemy|dataset | 0 |
377,040 | 53,119,367 | filtering a dataframe on values in a list | <p>I have the below data frame :-</p>
<p><a href="https://i.stack.imgur.com/quuGH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/quuGH.png" alt="enter image description here"></a></p>
<p>I want to filter where ever there is 11 in <code>claim_status</code> </p>
<p>and for the <code>claim_ststaus_r... | <p>You can use <code>apply</code> to obtain your desired filter like:</p>
<pre><code>df[(df['claim_staus'].apply(lambda x: 11 in x)) & (df['claim_status_reason'].apply(lambda x: 'a1' in x))]
</code></pre> | python|python-2.7|pandas|dataframe | 4 |
377,041 | 53,045,867 | Extracting the hour from a time column in pandas | <p>Suppose I have the following dataset: </p>
<p><a href="https://i.stack.imgur.com/5GORt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5GORt.png" alt="enter image description here"></a></p>
<p>How would I create a new column, to be the hour of the time?</p>
<p>For example, the code below works ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="noreferrer"><code>to_datetime</code></a> to datetimes with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.hour.html" rel="noreferrer"><code>dt.hour</code></a>:</p>
<pre><code>df = pd.Dat... | python|pandas|datetime | 11 |
377,042 | 53,293,380 | pandas dataframe copy of slice warning | <p>I'm fairly new to pandas, and was getting the infamous SettingWithCopyWarning in a large piece of code. I boiled it down to the following:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([[0,3],[3,3],[3,1],[1,1]], columns=list('AB'))
df
df = df.loc[(df.A>1) & (df.B>1)]
df['B'] = 10
</code></pre>
<p>... | <p>Assuming your DataFrame as below from your question, this will avoid <code>SettingWithCopyWarning</code></p>
<p>There is <a href="https://github.com/pandas-dev/pandas/issues/11984" rel="nofollow noreferrer">github Discussion</a> and solution suggested by one of the Pandas developer Jeff :) </p>
<pre><code>df
A ... | python|pandas | 0 |
377,043 | 52,906,950 | List index is out of range - but I'm checking the length before processing | <p>Wonder if you can advise - I get the below error when processing a list of items. I should note, that this script works for 99% of items - as I've expanded the list now to 84M rows, I am now getting this issue.</p>
<p>I do this for each line</p>
<pre><code>elif len(str(x)) > 3 and str(x[len(x)-2]).rstrip() in c... | <p>Let me expand on what Corentin Limier said in comments with a specific counterexample, since you categorically deny this could be true, without actually checking your debugger:</p>
<p>based on your original question error dump:</p>
<blockquote>
<p>---> 23 elif len(str(x)) > 5 and str(x[len(x)-3]).rstrip() in... | python|python-3.x|pandas | 3 |
377,044 | 53,244,590 | Histogram per hour - matplotlib | <p>I'm analyzing public data on transport accidents in the UK.</p>
<p>My dataframe looks like this :</p>
<pre><code>Index Time
0 02:30
1 00:37
2 01:25
3 09:15
4 07:53
5 09:29
6 08:53
7 10:05
</code></pre>
<p>I'm trying to plot a histogram showing a... | <p>What you are missing is setting the format of the matplotlib x-axis format:</p>
<pre><code>df.set_index('hour', drop=False, inplace=True)
df = df['hour'].groupby(pd.Grouper(freq='60Min')).count()
ax = df.plot(kind='bar', color='b')
ticklabels = df.index.strftime('%H:%Mh')
ax.xaxis.set_major_formatter(matplotlib.tic... | python|matplotlib|histogram|pandas-groupby | 4 |
377,045 | 53,094,238 | GPU crashes when running Keras/tensorflow-gpu, specifically when clock speed goes to idle at 0 MHz | <p>I'm using Jupyter Notebook to run Keras with a Tensorflow GPU backend. I've done some testing with various dummy models while simultaneously monitoring my GPU usage using MSI Afterburner, GPU-Z, nvidia-smi and Task Manager. My GPU is a GeForce GTX 960M, which has no issues running games. The temperatures are also lo... | <p>I was finally able to figure out the issue thanks to someone from another forum. It was a driver issue. The latest drivers provided by Nvidia are causing the issue unlike the old drivers provided by my laptop manufacturer.</p>
<p>Since I was not able to run tensorflow with my old drivers and do more troubleshooting... | python|tensorflow|keras|nvidia | 0 |
377,046 | 65,776,284 | After applying pd.to_numeric on multiple columns there is no change in columns Dtype | <p>I'm wondering what I'm doing wrong while applying pd.to_numeric on multiple columns in dataframe</p>
<pre><code>df_weather = pd.read_csv ('https://raw.githubusercontent.com/MichalLeh/Edinburgh-bikes-project/main/edinburgh_weather.csv')#("J:/edinburgh_weather.csv")
</code></pre>
<p>Sample of dataframe:</p>
... | <p>You need assign back columns converted to numeric:</p>
<pre><code>cols = ['temp', 'feels', 'wind', 'gust', 'rain', 'humidity', 'cloud', 'pressure']
df_weather[cols] = df_weather[cols].apply(lambda x: pd.to_numeric(x, errors='coerce'))
</code></pre> | python|pandas|dataframe | 2 |
377,047 | 65,555,883 | Python pandas - Index lookup based on criteria | <p>I have an extract of a dataframe below:</p>
<pre><code>
IndexR ATOI_INDEX pf_52w_rolling_R atoi_52w_rolling_R
date
2012-07-27 3.576907 1.384371 -0.208960 -0.038279
2012-08-03 3.563627 1.388237 -0.1292... | <p>Let us try <code>idxmim</code> which will return the min value index</p>
<pre><code>rolling.loc[rolling['pf_52w_rolling_R'].idxmin()]
</code></pre> | python|pandas | 2 |
377,048 | 65,614,664 | Concatenate one table to another using a key | <p>I have a CSV file. <code>df</code> represents this file. I have two ids in this file. Once the <code>d_id</code> and the <code>i_id</code>. The program now runs through a certain algorithm and gives me the <code>probability</code> and the <code>d_id</code> back in an ordered row (I can also deactivate this ordered r... | <p>I think you just need to process your resulted data.</p>
<pre><code>import pandas as pd
d = {'d_id': [1, 2, 2, 3, 3, 3, 4],
'i_id': [99, 98, 98, 97, 97, 97, 96]}
df = pd.DataFrame(data=d)
d_new = {'d_id': [4, 2, 1, 3],
'probability': [0.8557, 0.83215, 0.2563, 0.14521]}
df_new = pd.DataFrame(data=d_new)
r... | python|pandas|dataframe | 1 |
377,049 | 65,873,873 | Illustrating Normal Distribution using Numpy, Matploblib 3D from MATLAB code | <p>I am trying to plot normal distribution in 3D. I have a code written in MATLAB, but I have been failed to write it in Python.</p>
<p>The completed MATLAB's code is:</p>
<pre><code>dsig = 0.25;
dx = 0.5;
mu = 0;
[X, SIGMA] = meshgrid(-10:dx:10, 1:dsig:5);
Z = exp(-(X-mu).^2./(2*SIGMA.^2))./sqrt(2*pi*SIGMA.^2);
waterf... | <pre class="lang-py prettyprint-override"><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import math
import scipy.stats as stats
mu = 0
variance = 1
sigma = math.sqrt(variance)
x = np.linspace(mu - 3*sigma, mu + 3*sigm... | python|matlab|numpy|statistics|quantitative-finance | -1 |
377,050 | 65,757,385 | Tensorfllow: load checkpoint from changed model | <p>For some reason I want to test the difference in the performance of a detector and his identical version but finetuned with some 3d convolutions.<br>
The model of the detector is google EfficientDet, the weights are finetuned on custom data. <br>
I was wondering if it was possible to load my custom weight in a model... | <p>You can load the second model, get weights of the layer and set weights of your model:</p>
<pre><code>source_model = keras.models.load_model('path/to/location')
weight = source_model.layers[0].get_weights() # <= change index here
EfficientDetModel.layers[0].set_weights(weight) # <= change index here
</code><... | python|tensorflow|deep-learning|checkpoint | 1 |
377,051 | 65,711,006 | Save to Excel during loop (Pandas DataFrame) | <p>I am running a loop that creates a large nested dictionary and in the end, saves it to an excel file using pandas.</p>
<p>How do I save to the same excel file after X iterations instead of waiting until the end? For example for every 10th iteration? Is it possible?</p>
<p>Current code (simplified):</p>
<pre class="l... | <p>As far as I know, there's no good way to stream output to a single excel sheet with pandas. You can append the data as additional sheets using the pandas.ExcelWriter, but that doesn't sound like what you want.</p>
<p>You could always just run the df.to_excel every X iterations and overwrite the existing file, but th... | python|excel|pandas | 0 |
377,052 | 65,564,030 | Pandas grouping and express as proportion | <pre><code>d = [{'name': 'tv', 'value': 10, 'amount': 35},
{'name': 'tv', 'value': 10, 'amount': 14},
{'name': 'tv', 'value': 15, 'amount': 23},
{'name': 'tv', 'value': 34, 'amount': 56},
{'name': 'radio', 'value': 90, 'amount': 35},
{'name': 'radio', 'value': 90, 'amount': 65},
{'name': '... | <p>Use custom lambda function with flatten nested lists in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer"><code>GroupBy.apply</code></a>:</p>
<pre><code>dff = df.groupby(['name', 'value']).agg('sum').reset_index()
dff['amount'] = ((df... | python|python-3.x|pandas|pandas-groupby | 2 |
377,053 | 65,553,064 | Training & Validation loss and dataset size | <p>I'm new on Neural Networks and I am doing a project that has to define a NN and train it. I've defined a NN of 2 hidden layers with 17 inputs and 17 output. The NN has 21 inputs and 3 outputs.</p>
<p>I have a data set of labels of 10 million, and a dataset of samples of another 10 million. My first issue is about th... | <p>For your first question about batch size, there is no fix rule for what value should it have. You have to try and see which one works best. When your NN starts performing badly don't go above or below that value for batch size. There is no hard rule here to follow.</p>
<p>For your second question, first of all, havi... | python|machine-learning|neural-network|pytorch | 0 |
377,054 | 65,871,648 | how to use tensorflow dataset map function correct for string column | <p>m using tensorflow datasets api</p>
<p>and i have a data with a string column that can represents a binary option</p>
<p>(something like ("yes" or "no")</p>
<p>i'm wondering if i convert it into 1 and 0 (integer value) respectively, and leave the other columns unchanged</p>
<p>my skeleton functio... | <p>You can convert a bool to int:</p>
<pre><code>y = tf.equal(features["str_col"], 'YES')
y = tf.cast(y, tf.int32)
</code></pre> | python|tensorflow|tensorflow2.0|tensorflow-datasets | 0 |
377,055 | 65,489,527 | How to select the next date in a Pandas dataframe with date index and missing dates | <p>I have a dataframe indexed on date with some dates missing (that's ok, they are non-trading data and this is stock data).</p>
<p>How do I access the next row, when I know the previous date, e.g.</p>
<pre><code>date Open
01-01-2021 501
02-01-2021 508
04-01-2021 511
05-01-2021 518
</code></pre>
<p>I would like a ... | <p>If the rows are sorted by <em>date</em>, use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.searchsorted.html" rel="nofollow noreferrer">searchsorted</a>:</p>
<pre><code>idx = df['date'].searchsorted(pd.to_datetime('02-01-2021'), side='right')
print(df.loc[idx, 'date'])
</code></pr... | python|pandas | 3 |
377,056 | 65,751,411 | Plotting scatter plot of pandas dataframe with both categorical and numerical data | <p>I am trying to plot a scatter plot of the following type of pandas dataframe:</p>
<pre><code>df = pd.DataFrame([['RH1', 1, 3], ['RH2', 0, 3], ['RH3', 2, 0], ['RH4', 1, 2], columns=['name', 'A', 'B'])
</code></pre>
<p>The final plot should have "name" column as Y axis and "A" and "B" as ... | <p>You can <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html" rel="nofollow noreferrer">melt</a> your dataframe and use the values as the column for color:</p>
<pre><code>from matplotlib import pyplot as plt
import pandas as pd
df = pd.DataFrame([['RH1', 1, 3], ['RH2', 0, 3], ['RH3',... | python|pandas|matplotlib|seaborn|scatter-plot | 1 |
377,057 | 65,753,057 | Creating new variable by aggregation in python 2 | <p>I have data on births that looks like this:</p>
<pre><code>Date Country Sex
1.1.20 USA M
1.1.20 USA M
1.1.20 Italy F
1.1.20 England M
2.1.20 Italy F
2.1.20 Italy M
3.1.20 USA F
3.1.20 USA F
</code></pre>
<p>My purpose is to get a new dataframe in which each row is a date at ... | <p>You can <code>group</code> the dataframe on columns <code>Date</code> and <code>Country</code> then aggregate column <code>Sex</code> using <code>value_counts</code> followed by <code>unstack</code> to reshape, finally <code>assign</code> the <code>Births</code> columns by summing frequency along <code>axis=1</code>... | python|pandas|group-by|aggregate | 0 |
377,058 | 65,623,468 | Unable to open file libtensorflow_io.so caused by undefined symbol | <p>I have a tensorflow 2.2 conda environment setup with python 3.8.2 on Ubuntu.</p>
<p>I ran <code>pip install tensorflow-io==0.14.0</code>.</p>
<p>When I try to</p>
<pre><code>import tensorflow-io as tfio
</code></pre>
<p>I get the erorr:</p>
<pre><code>File "/home/somedir/miniconda3/envs/env_name/lib/python3.8/s... | <p>As @Smedegaard mentioned, tensorflow_io is not on conda forge. The <a href="https://github.com/tensorflow/io/issues/1100" rel="noreferrer">answer of vlasenkoalexey on Github issues</a> to tackle this:</p>
<blockquote>
<p>Obvious workaround is to uninstall tensorflow and tensorflow-io and install them from pip: <br /... | python|tensorflow|pip|conda|undefined-symbol | 5 |
377,059 | 65,817,913 | first/count applied to groupby returns empty dataframe | <pre><code>import pandas as pd
df = pd.DataFrame( {'A': [1,1,2,3,4,5,5,6,7,7,7,8]} )
dummy = df["A"]
print(dummy)
0 1
1 1
2 2
3 3
4 4
5 5
6 5
7 6
8 7
9 7
10 7
11 8
Name: A, dtype: int64
res = df.groupby(dummy)
print(res.first())
Empty DataFrame
Columns: []
Ind... | <p>My guess is by default, <code>A</code> is set to index before applying the groupby operator (e.g. <code>first</code>). Therefore, <code>df</code> is essentially empty before the actual <code>first</code> operator is applied. If you have another column <code>B</code>:</p>
<pre><code>df = pd.DataFrame( {'A': [1,1,2,3,... | python|python-3.x|pandas | 2 |
377,060 | 65,538,234 | Write JSON file with X and Y axis | <p>I am working on a requirement to write my JSON output as <strong>[{"x": "MaxTemp", "y": "Temp3pm"}]</strong> and my current output looks like [MaxTemp, Temp3pm], so the logis here is, as per the screenshot the first word is X_axis and the second word after comma(,) is y_axis. ... | <p>you could use str.split to split text by ',' and expand into two columns, for example:</p>
<pre><code>df = df['index'].str.split(',', expand=True)
# then rename column name to x and y
df.columns = ['x', 'y']
</code></pre>
<p>then you can convert it into a dict and output as json at last</p>
<pre><code>data = df.to_... | python|json|pandas|dataframe | 0 |
377,061 | 65,597,718 | If column X contains String then find position of substring in column Y - PYTHON | <p>I'm trying to find the starting position of a string in an URL contained in column['url'] if column ['Existe'] contains "F" or "D". I'm new to Python and I'm trying to replicate a workflow from Excel in Python and after an hour of trying methods with lambda, numpy.where or numpy.select, and searc... | <h2>Avoid Looping Over Rows</h2>
<p>When manipulating data with pandas, <a href="https://stackoverflow.com/a/55557758/5075720">it is typically best to avoid looping over rows</a>. Working with logic that only operates on certain rows, it is better to begin by explicitly identifying those rows. The subset of rows where ... | python|pandas | 1 |
377,062 | 65,718,776 | Unpacking many columns of lists using apply get ValueError: If using all scalar values, you must pass an index | <p>I want to unpack multiple columns of lists into many more columns. Basically <a href="https://stackoverflow.com/questions/35491274/pandas-split-column-of-lists-into-multiple-columns">this</a> but <strong>for multiple columns</strong> of lists rather than just one, and avoiding for loops.</p>
<p>As an example I have ... | <p>If you don't mind to change <code>apply</code>to <code>explode</code> then this is one line solution. Kr.</p>
<pre><code>res=pd.concat([pd.DataFrame(tst[[x]].explode(x).values.reshape(-1,2), columns=['1' + x, '2' + x]) for x in tst.columns], 1)
print(res)
</code></pre>
<p>Which returns:</p>
<pre><code> 1A 2A 1B 2B ... | python|pandas|pandas-apply | 1 |
377,063 | 65,703,930 | Using tensordot with torch.sparse tensors | <p>Is it possible to use a similar method as "tensordot" with torch.sparse tensors?</p>
<p>I am trying to apply a 4 dimensional tensor onto a 2 dimensional tensor. This is possible using torch or numpy. However, I did not find the way to do it using torch.sparse without making the sparse tensor dense using &q... | <p>Your specific <code>tensordot</code> can be cast to a simple matrix multiplication by "squeezing" the first two and last two dimensions of <code>tensor4D</code>.</p>
<p>In short, what you want to do is</p>
<pre class="lang-py prettyprint-override"><code>raw = tensor4D.view(nb_x*nb_y, nb_x*nb_y) @ inp.flatt... | pytorch|sparse-matrix|tensor|torch|tensordot | 1 |
377,064 | 65,745,053 | Tensorflow softmax does not ignore masking value | <p>I am reviving this github <a href="https://github.com/tensorflow/tensorflow/issues/27010" rel="nofollow noreferrer">issue</a> because I believe it is valid and needs to be explained. tf.keras has a masking layer with docs that reads</p>
<blockquote>
<p>For each timestep in the input tensor (dimension #1 in the tenso... | <p>I think this is already explained well in the <a href="https://github.com/tensorflow/tensorflow/issues/27010" rel="noreferrer">Github issue</a> you have linked. Underlying problem is that irrespective of whether an array is masked or not, <code>softmax()</code> still operates on <code>0.0</code> values and returns a... | tensorflow|keras|deep-learning | 6 |
377,065 | 65,503,077 | numpy - tuple is not "(...)" in numpy? | <p>My understanding of tuple is it can be enclosed with parenthesis.</p>
<ul>
<li><a href="https://docs.python.org/3/library/stdtypes.html#tuple" rel="nofollow noreferrer">class tuple([iterable])</a></li>
</ul>
<blockquote>
<p>Tuples may be constructed in a number of ways:</p>
<p>Using a pair of parentheses to denote t... | <p>Slice notation like <code>1:2</code> is syntax, it does not create an object, so you cannot use them in a list or tuple or anything; slice <em>objects</em> on the other hand actually refer to the thing returned by <code>slice()</code> which behave the same, and that's what Numpy is referencing with "tuple of sl... | numpy|tuples|slice | 4 |
377,066 | 65,649,557 | How to transform and reshape multiple numpy arrays | <p>I have several lists of values, each list is named using 2 numbers e.g., values[1][1] , values[1][2] or values[2][1]....until values[99][99]. I need to transform each list into a numpy 1-D array then reshape each array into a 2-D array with dimensions(20,10).
I was able to do it for one list as follow but I need to ... | <p>below should do the job, storing all the shaped arrays into a list called <code>store</code></p>
<pre><code>store = []
for i in range(1,100):
for j in range(1,100):
store.append(np.reshape(np.array([values[i][j]]),(20,10)))
</code></pre> | python|arrays|numpy|jupyter|reshape | 1 |
377,067 | 65,488,924 | Pandas: Impute a given number of missing values before/after a series of available values | <p>Let's say I have a time series where I usually have data available for a certain continous span of years, but missing values before and after that span, like this:</p>
<pre><code>df = pd.DataFrame({'year': ["2000","2001","2002", "2003","2004", "2005","... | <p>Thanks to @olv1do for showing me that <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.interpolate.html" rel="nofollow noreferrer">interpolate()</a> does what I want.</p>
<p>Using interpolate and <code>.first_valid_index</code> and <code>.last_valid_index</code> allows to implemen... | python|pandas|imputation | 1 |
377,068 | 65,768,164 | Computing row-wise maximum of off-diagonal entries in a matrix | <p>It's easier to motivate the question with an example: let's say I have a matrix A</p>
<pre><code>A = np.reshape (np.arange(9,dtype = np.float), (3,3))
</code></pre>
<pre><code>>>[[0. 1. 2.]
[3. 4. 5.]
[6. 7. 8.]]
</code></pre>
<p>The row-wise maximum is <strong>(2,5,8)</strong>, found for instance by <code>... | <p>If you don't need the original data after getting the answer, this should suffice. Otherwise I'm not sure what's wrong with your approach.</p>
<pre><code>A = np.reshape (np.arange(9,dtype = np.float), (3,3))
np.fill_diagonal(A, -np.inf)
np.max(A, axis=1)
</code></pre> | python|numpy|max | 2 |
377,069 | 65,520,260 | Convert JSON to Pandas Dataframe in Python | <p>There is data in json format as below:</p>
<pre><code>dict = {"a":1,"b":2,"c":[{dic 1},{dic2},...so on]}
</code></pre>
<p>where dic 1 is defined below, like this list of dictionaries are there</p>
<pre><code>dic 1 = {"d":4,"e":{"f":6,"g":7},"... | <p>The structure of your json is complex! Make it simple!</p>
<p>Your code won't run, returns unhashable type 'dict'. To solve, simply unpack any variable you're using in the main 'dict' (that's **dic1).</p>
<p>Even with that, you end with 2 rows and 3 columns. Why? The data in key 'c' is a list of dicts, pandas inter... | python|json|python-3.x|pandas|dataframe | 3 |
377,070 | 65,609,559 | TensorFlow: No module named Pandas (I already have Pandas) | <pre class="lang-py prettyprint-override"><code>WORKSPACE_PATH = 'Tensorflow/workspace'
SCRIPTS_PATH = 'Tensorflow/scripts'
APIMODEL_PATH = 'Tensorflow/models'
ANNOTATION_PATH = WORKSPACE_PATH+'/annotations'
IMAGE_PATH = WORKSPACE_PATH+'/images'
MODEL_PATH = WORKSPACE_PATH+'/models'
PRETRAINED_MODEL_PATH = WORKSPACE_PA... | <p>Try installing pandas using conda cause conda somehow installs the package globally (base python env)</p> | python|pandas|module|pip|path | 0 |
377,071 | 65,526,429 | Python: clear a specific range of data from a column in a dataframe | <p>I have the problem that the dataframe from my import (stock prices from Yahoo) are not correct for a specific time period. I want to clear the data from 2010-01-01 until 2017-10-17 for "VAR1.DE" and replace it empty or with NaN. I have found the panda function "drop" but this will delete the hole... | <p>instead of having a for loop, you can simply do:</p>
<pre><code>df = web.DataReader(name=assets, data_source='yahoo', start=stockStartDate, end=today)['Adj Close']
</code></pre>
<p>since the return dataframe would be indexed by datetime. (i.e. <code>pd.DatetimeIndex</code>)
so you can simply do:</p>
<pre><code>df.lo... | python|pandas|numpy | 0 |
377,072 | 65,588,408 | Pandas reindex and assigning Columns to a new column | <p>I am creating a pandas dataframe and wanting to create a new column by assigning and reindexing method. The way I am doing is to pull the data which may have say 'A', 'B', 'C', D' 'E' columns
and I am wanting to create a new column say 'XX'. ( of course there are other columns in the dataframe and its a huge one, I ... | <p>Do it in one line.</p>
<p>Please filter required columns. Put the columns you need in a list. That will filter them, try find max in each row into a new column and find max in the resultant column</p>
<p>Data</p>
<pre><code> print(df)
A B C f D E
0 0 0 1 2 0 1
1 0 0 0 56 0 0
2 1 0 0 70 0 ... | python|pandas|list|indexing | 1 |
377,073 | 65,546,995 | Visualize 3D numpy.meshgrid | <p>I have used two input arrays with an output array that I have interpolated with numpy's LinearNDInterpolator and scipy's ndimage filters. I was able to easily visualize the output using a matplotlib's pcolormesh. I would like to extend this analysis to 3 input arrays using the same ndimage and interpolation function... | <p>I have found an easy way to do this exact visualization task is to use animatplot, which has its own animated pcolormesh function.
<a href="https://pypi.org/project/animatplot/" rel="nofollow noreferrer">https://pypi.org/project/animatplot/</a></p> | python|numpy|matplotlib|image-processing|visualization | 0 |
377,074 | 65,514,897 | how to transform dataframe | <p>I have the following snippet from a dataframe:</p>
<pre><code> cough fever
8 0.0 0.0
9 -1.0 1.0
24 0.0 1.0
29 0.0 -1.0
30 1.0 1.0
</code></pre>
<p>Where I need to sum up each column by each value, like:</p>
... | <p>Change the <code>concat</code></p>
<pre><code>out=pd.concat(frames ,axis=1)
</code></pre>
<p>Or simply do</p>
<pre><code>s = df.melt()
out = pd.crosstab(s.variable,s.value)
value -1.0 0.0 1.0
variable
cough 1 3 1
fever 1 1 3
</code></pre> | python|pandas|aggregate|transpose | 2 |
377,075 | 65,629,083 | Converting STR to INT on Dataframe doesn't work on the specific parts | <p>I know, this is an easy question, but I checked so many sites on the internet and couldn't find the problem that I have.</p>
<p>I have a dataframe and one column of this dataframe is for brand. I wanted to give specific numbers for these brands to make brand aggregation easier.</p>
<pre><code>import pandas as pd
la... | <p>In your code, you use a sequence of <code>f</code> as an index of rows in <code>last</code>, but <code>last</code> is sorted on <code>brand</code>, therefore the sequence of <code>f</code> is not the index of row. as a result, you put the random number in the wrong places and leave others.</p>
<p>In order to correct... | python|pandas|dataframe|anaconda|spyder | 1 |
377,076 | 65,762,748 | Pandas Seaborn FacetGrid same x labels on every plot, though different y values | <p>I'm trying to display FacetGrid with barplots so that it displays data of yellow_cards count (y) and team name (x), divided by different football leagues (other plots should show other leagues, and other team names). The data is being counted correctly but the display shows only the first league on every plot.</p>
<... | <p>If you do not need ordered bars, you can directly plot the dataframe and let seaborn do all the calculations:</p>
<pre><code>import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
#test data generation
import numpy as np
n=30
np.random.seed(123)
df_alt2 = pd.DataFrame({"index": np.aran... | python|pandas|seaborn | 1 |
377,077 | 65,907,350 | How do we change the result of groupby into dataframe? | <pre><code>df = pd.DataFrame({
"A" : [1, 2, 1, 2, 1, 2, 2, 1],
"B" : [1, 1, 2, 2, 1, 1, 1, 2],
"C": [1, 1, 1, 1, 2, 2, 2, 2]})
df
</code></pre>
<p>This is my data.</p>
<p>and I used</p>
<pre><code>gbA = df.groupby("A")
</code></pre>
<p>How can we change the result of ... | <p>If you want the original df back, use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer"><code>pandas.DataFrame.groupby.apply</code></a> with a dummy function:</p>
<pre><code>>>> gbA.apply(lambda x:x)
A B C
0 1 1 1
1 ... | python|pandas | 2 |
377,078 | 65,642,697 | pytorch runs slow when data are pre-transported to GPU | <p>I have a model written in pytorch. Since my dataset is small, I can directly load all of the data to GPU. However, I found the forward speed becomes slow if I do so. The following is a runnable example. Specifically, I have the model:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from time i... | <p>I played around with the code a little bit, and I think the problem is that you are measuring times for both cases in the same run. Here is my boiled down version of your code since your model crushed my GPU memory:</p>
<pre><code>class DGCNN(nn.Module):
def __init__(self, num_layers):
super(DGCNN, self)... | pytorch | 2 |
377,079 | 65,634,458 | train test split is not splitting correctly | <p>I am still a beginner in AI and deep learning but I wanted to test whether a neural network will be able to calculate the sum of two numbers so I generated a dataset of 5000 numbers and made test size = 0.3 so the training dataset will be equal to 3500 but what was weird that I found the model is training only on 11... | <p>The <code>110/110</code> you are seeing in your image is actually the batch count, not the sample count. So 110 batches * the default batch size of 32 gives you ~3500 training samples, which matches what you'd expect as 70% of 5000.</p>
<p>You can see by backing into it the other way that the last batch would be a p... | python|numpy|tensorflow|deep-learning | 2 |
377,080 | 65,901,247 | An easy way to calculate time intervals between dates in a column in Python | <p>Suppose I have a Pandas DataFrame like this:</p>
<pre><code> item event date
A 1 2020-03-09
B 1 2020-03-09
A 2 2020-05-01
B 2 2020-05-01
C 2 2020-05-01
A 3 2020-06-25
C 3 2020-06-25
B 4 2020-07-18
C 4 ... | <p>Very similar to @BradSolomon's answer, with two small differences:</p>
<pre class="lang-py prettyprint-override"><code>df.sort_values(['item', 'date']).groupby('item')['date'].agg(
lambda g: g.diff().mean() / pd.Timedelta(days=1))
# gives:
item
A 54.0
B 65.5
C 39.0
</code></pre>
<p>Notes:</p>
<ol>
<li>... | python|pandas|dataframe|date | 2 |
377,081 | 65,600,270 | For loop over dataframe python | <p>i have dataframe called <code>df_civic</code> with columns - <code>state ,rank, make/model, model year, thefts</code>. I want to calculate <strong>AVG</strong> and <strong>STD</strong> of <code>thefts</code> for each <code>model year</code>.</p>
<p>All years that are in dataframe are taken with: <code>years_civic = ... | <p>Pandas provides many powerful functions for aggregating your data. It's usually better to first think of these functions before using <code>for</code> loops.</p>
<p>For instance, you can use:</p>
<pre><code>import pandas as pd
import numpy as np
df_civic.groupby("Model Year").agg({"theft": [&quo... | python|pandas|dataframe|loops|for-loop | 1 |
377,082 | 65,692,575 | How to count the occurrence of a value and set that count as a new value for that value's row | <p>Title is probably confusing, but let me make it clearer.</p>
<p>Let's say I have a df like this:</p>
<pre><code>+----+------+---------------+
| Id | Name | reports_to_id |
+----+------+---------------+
| 0 | A | 10 |
| 1 | B | 10 |
| 2 | C | 11 |
| 3 | D | 12 ... | <p>Use <code>value_counts</code> to count the <code>reports_to_id</code> by values, then <code>map</code> that to <code>Id</code>:</p>
<pre><code>df['COUNT'] = df['Id'].map(df['reports_to_id'].value_counts()).fillna(0)
</code></pre>
<p>Output:</p>
<pre><code> Id Name reports_to_id COUNT
0 0 A 10 ... | python|python-3.x|pandas|dataframe | 1 |
377,083 | 65,860,326 | how to generate a list within a list delimited by a space | <p>how do i replicate the structure of result of itertools.product?</p>
<p>so as you know itertools.product gives us an object and we need to put them in a list so we can print it
.. something like this.. right?</p>
<pre><code>import itertools
import numpy as np
CN=np.asarray((itertools.product([0,1], repeat=5)))
prin... | <p>You don't have to. If you want to use <code>rfe.fit</code> function, you need to feed features and target seperately.</p>
<p>So if your df is like:</p>
<pre class="lang-py prettyprint-override"><code> a b c d target
0 5.1 3.5 1.4 0.2 1
1 4.9 3.0 1.4 0.2 1
2 4.7 3.2 1.3 0.2 ... | python|pandas|numpy|scikit-learn|dataset | 0 |
377,084 | 65,571,761 | Create a folder structure based on information from a dataframe | <p>I have this dataframe train_info with 423 different artists and filenames corresponding to images of paintings.</p>
<pre class="lang-py prettyprint-override"><code> artist filename
0 Hiroshige 53180.jpg
1 Ivan Aivazovsky 99442.jpg
2 Hiroshige 23508.jpg
3 Hieronymus Bosch ... | <p>An easy, no-sweat way, is to use explicit looping:</p>
<pre><code>import os
import shutil
srcdir = 'Paintings'
dstdir = 'train'
for name, s in df.groupby('artist')['filename']:
artistdir = os.path.join(dstdir, name)
print(f'copying {s.shape[0]} images from {srcdir} to {artistdir}')
os.makedirs(artistdi... | python|pandas|dataframe|file|data-science | 0 |
377,085 | 65,643,248 | One hot encoding from numpy | <p>I am trying to understand values output from an example python <a href="https://towardsdatascience.com/word2vec-from-scratch-with-numpy-8786ddd49e72" rel="nofollow noreferrer">tutorial</a>. The output doesent seem to be in any order that I can understand. The particular python lines are causing me trouble :</p>
<pre... | <p>The code you showed is a quick way to convert multiple label indices to one-hot-encodings.</p>
<p>Let's do it with a single index, and convert it to a one-hot-encoding vector. To keep it simple, we will stick with an encoding size of <em>10</em> (i.e. nine <code>0</code>s and one <code>0</code>):</p>
<pre><code>>... | python|numpy|one-hot-encoding | 3 |
377,086 | 65,800,234 | Passing datetime64[ns] from pandas' data frame as an argument to a function | <p>I'm trying to create an additional column in a data frame to show the number of network days (excluding custom holidays) between two dates. I'm using a function to which I'm trying to pass dates from <code>df</code>'s columns as arguments, but I can't make it work.</p>
<p>Below is my code (I'm using two made-up holi... | <p>As per my comment, use <code>.apply</code>:</p>
<pre><code>df['Working_Days'] = df.apply(lambda x: working_days(x.Start_Date, x.End_Date, public_holidays), axis=1)
</code></pre> | python|pandas|function|dataframe|datetime | 1 |
377,087 | 65,806,914 | How to replace one column values with another column values | <p>Actually I want to replace the prefix with the mean here.
How can i acheive it.
When replacing it it is replacing with NaN but not with the mean values.</p>
<p><strong>This is my code:</strong></p>
<p><a href="https://i.stack.imgur.com/I0Ldj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I0Ldj.pn... | <p>Since the second column is a multi-index column, you are basically trying to set a single column as a dataframe. You will have to refer to the exact column name to do that replacement.</p>
<pre><code>z['ID']=z['teacher_number_of_previously_posted_projects']['mean']
</code></pre> | python-3.x|pandas|replace|group-by | 1 |
377,088 | 65,503,800 | Finding mean temperature grouping every N rows | <p>I have the following dataframe with hourly temperatures at different coordinates:</p>
<pre><code>df.head
Out[63]:
time latitude longitude t2m
2018-01-01 00:00:00 72.0 -11.0 -3.957336
2018-01-01 01:00:00 72.0 -11.0 -4.165466
201... | <p>In general, it's simpler and more generalizable to use <code>pd.Grouper(freq='D')</code>.</p>
<p>From your data snippet, it's not clear whether your dataframe has an index or not. If it has, then <code>df.head()</code> (and not <code>df.head</code>, BTW) would show:</p>
<pre><code> latitude long... | python|pandas | 1 |
377,089 | 65,795,374 | GCP AI Platform: Error when creating a custom predictor model version ( trained model Pytorch model + torchvision.transform) | <p>Am currently trying to deploy a custom model to AI platform by following <strong><em><a href="https://cloud.google.com/ai-platform/prediction/docs/deploying-models#gcloud_1" rel="nofollow noreferrer">https://cloud.google.com/ai-platform/prediction/docs/deploying-models#gcloud_1</a></em></strong>. which is based on a... | <p>Got this fixed by a combination of few things. I stuck to 4gb CPU MlS1 machine and custom predictor routine (<500MB).</p>
<ul>
<li>Install the libraries using setup.py parameter but instead of parsing just the package name and it's version, add correct torch wheel (ideally <100 mb).</li>
</ul>
<pre><code>REQUI... | python|google-cloud-platform|pytorch|torchvision|google-ai-platform | 1 |
377,090 | 21,125,561 | How do I automate an environment variable dependent benchmark of BLAS in python/numpy? | <p>I need some help in figuring out how to automate a benchmark effort in python. </p>
<p>I'm testing the effects of threading on a BLAS library calls through numpy in python. In a linux environment, threading in OpenBLAS is controlled through the environment variable <code>OMP_NUM_THREADS</code>. I want to do a te... | <p>You can do something like this:</p>
<pre><code>import subprocess
os.environ['OMP_NUM_THREADS'] = '{:d}'.format(thread)
proc = subprocess.Popen(["numpy_test"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
</code></pre>
<p>Then you'll have the output of the the <code>numpy_tes... | python|multithreading|numpy|python-3.3|blas | 2 |
377,091 | 21,182,759 | Pivot data and maintain original sort order | <p>I'd like to pivot my data which results from a django queryset while maintaining the original (non-alphabetical) sort order on the index column. The pivoted data will then be used in a google visualization line chart.</p>
<p>I've hacked together my own code to do the job but it's a bit ugly and I was wondering if i... | <p>compare day unit with month unit is fuzzy, for example which is large: 30D or 1M? If this is no problem, you can use <code>reindex()</code> method to reorder the DataFrame:</p>
<pre><code>import pandas as pd
df_pivot = df.pivot(index='tenor', columns='date', values='value')
DayCounts = {"D":1, "M":365.0/12, "Y":3... | python|pandas|google-visualization | 2 |
377,092 | 21,319,929 | How to determine whether a Pandas Column contains a particular value | <p>I am trying to determine whether there is an entry in a Pandas column that has a particular value. I tried to do this with <code>if x in df['id']</code>. I thought this was working, except when I fed it a value that I knew was not in the column <code>43 in df['id']</code> it still returned <code>True</code>. When I ... | <p><code>in</code> of a Series checks whether the value is in the index:</p>
<pre><code>In [11]: s = pd.Series(list('abc'))
In [12]: s
Out[12]:
0 a
1 b
2 c
dtype: object
In [13]: 1 in s
Out[13]: True
In [14]: 'a' in s
Out[14]: False
</code></pre>
<p>One option is to see if it's in <a href="http://pandas.... | python|pandas | 313 |
377,093 | 21,399,091 | Pure python faster than numpy on element-wise operation? | <p>Can someone explain these results to me ? The pure Python seems to take less time than the
numpy expression for element-wise exponentiation.</p>
<pre><code>In [224]: ar=np.arange(1000)
%timeit a**4
100000 loops, best of 3: 5.22 µs per loop
In [225]: ar=range(1000)
%timeit [ar[i]**4 fo... | <p>The pure Python version was timed for less iterations. That doesn't mean it was faster; that means <code>timeit</code> stopped running it so it wouldn't take 60 seconds* to get results. You can see from the per-loop time that the NumPy version was 40 times faster.</p>
<p>*200 microseconds per loop * 100,000 loops *... | python|numpy | 4 |
377,094 | 21,024,066 | Annotate heatmap with value from Pandas dataframe | <p>I would like to annotate a heatmap with the values that I pass from a dataframe into the function below. I have looked at matplotlib.text but have not been able to get the values from my dataframe in a desired way in my heatmap. I have pasted in my function for generating a heatmap below, after that my dataframe and... | <p>This functionality is provided by the <a href="http://stanford.edu/~mwaskom/software/seaborn/examples/heatmap_annotation.html" rel="noreferrer">seaborn</a> package. It can produce maps like</p>
<p><a href="https://i.stack.imgur.com/CPmBQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CPmBQ.png" alt="Exam... | python|text|matplotlib|pandas|heatmap | 9 |
377,095 | 3,165,379 | how to display a numpy array with pyglet? | <p>I have a label matrix with dimension (100*100), stored as a numpy array, and I would like to display the matrix with pyglet.</p>
<p>My original idea is to use this matrix to form a new pyglet image using function pyglet.image.ImageData(). It requres a buffer of the imagedata as an input, however I have no idea how ... | <p>I think what you are looking for is <code>np.dstack</code> (or more generally, <code>np.concatenate</code>):</p>
<pre><code>label255=label*255
label3=numpy.dstack((label255,label255,label255))
</code></pre>
<p>This shows <code>dstack</code> produces the same array (<code>label3</code>) as your construction for <co... | python|numpy|pyglet | 5 |
377,096 | 63,700,984 | combine multiindex dataframe with Int64Index dataframe | <p>i have one dataframe with multiindex</p>
<p>result =</p>
<pre><code>MultiIndex([(1, 'HK_MN001'),
(2, 'HK_MN001'),
(3, 'HK_MN002'),
(4, 'HK_MN003'),
(5, 'HK_MN004'),
(6, 'HK_MN005'),
(7, 'HK_MN005'),
(8, 'HK_MN005')],
names... | <p>I think you need in both <code>DataFrames</code> create <code>MultiIndex</code>:</p>
<pre><code>photo_df = photo_df.set_index('PhotoID', drop=False)
photo_df.columns = pd.MultiIndex.from_product([photo_df.columns, ['']])
print (photo_df)
PhotoID raw_photo
... | python-3.x|pandas|dataframe|concat|multi-index | 1 |
377,097 | 63,712,804 | Combine two dataframes according to the values in one of the columns | <pre><code>dataframe1
data_a data_b data_c data_d data_e
61 0.30792 Rest 2.34857 True
183 0.93408 Rest 2.34550 True
305 1.56019 Rest 2.34215 True
427 2.18636 Rest 2.33955 True
549 2.812... | <p>Check with <code>concat</code> then <code>sort_values</code></p>
<pre><code>df3 = pd.concat([df1, df2]).sort_values('data_a')
</code></pre> | python|pandas|dataframe|data-science | 2 |
377,098 | 63,484,261 | Get a specific value from a cell | <p>Below is my df.</p>
<pre><code>import pandas as pd
df = pd.DataFrame ({
'IP':['10.140.34.210;0.0.0.0','0.0.0.0;0.0.0.0;10.0.1.87;0.0.0.0;0.0.0.0','0.0.0.0;172.31.48.174',
'10.140.67.244;0.0.0.0', '1.1.1.1','3.3.3.3'],
})
print(df)
IP
0 ... | <p>If thats the only exceptional case you need to get rid of, use <code>replace</code> with regex:</p>
<pre><code>print(df["IP"].replace(";?0\.0\.0\.0;?","", regex=True))
0 10.140.34.210
1 10.0.1.87
2 172.31.48.174
3 10.140.67.244
4 1.1.1.1
5 3.3.3.3
Name... | python-3.x|pandas | 3 |
377,099 | 63,622,985 | query reg dimension of conv2D layer in cnn | <p>I have a Conv2D layer with an input dimension of 256×226×3:</p>
<pre class="lang-py prettyprint-override"><code>self.conv1 = self.track_layer(tf.layers.Conv2D(
32, 9, 1, 'SAME',
activation=tf.nn.relu,
kernel_initializer=conv_init,
))
</code></pre>
<p>Can anyone tell me what is the dimension after passi... | <p>The output shape of this conv layer will essentially remain the same, In case you find the calculations for getting the shape of output a bit intimidating I suggest a small way of measuring it, I suggest you make a small model and give it the input size and print out the summary.</p>
<pre><code>import tensorflow as ... | tensorflow|deep-learning|conv-neural-network | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.