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
13,000
50,143,092
single line Calculate a sum and print multiple columns pandas dataframe
<p>I have a dataframe written like below</p> <pre><code>df = pd.read_csv(file, skiprows=1, names=['all','my','headers','named']) </code></pre> <p>from this point, how can i apply the following forumla df['my'] - df['all'] / df['headers'] and print the name from the data below, on a single line? </p> <p>example data:...
<p>I believe <code>df.apply</code> will work here. </p> <pre><code>df['answer'] = df.apply(lambda x: x['my'] - (x['all']/x['headers']), 1) for index, row in df.itterrows: print(row['name'] + " - " + row['answer']) </code></pre> <p>Not a one liner, but might give you an idea of how to utilize df.apply.</p>
python|python-3.x|pandas|dataframe
2
13,001
63,755,940
how can I replace elements in a pandas column by a list of strings
<p>I have created a dataframe column to store hashtags, each row of this column is a list of strings like this:</p> <pre><code>df.hashtag 0 [#MondayMotivation, #BlackMamba, #RIPMamba, #c... 1 [#Periscope, #HeartGang, #SpreadLuv, #KobeRIP,... 2 [#Periscope, #HeartGang, #SpreadLuv, #KobeRIP,... 3 ...
<p>You can do the following. Add similar lines if you have more elements to be replaced.</p> <pre><code>token = ['#Covid_19', '#covid2019', '#covid19', '#covid_19', '#COVid', '#COVID__19'] l=list(df.hashtag) for i in range(len(l)): l[i]=['#COVID19' if x in token else x for x in l[i]] df.hashtag=l </code></pr...
python|pandas|dataframe
2
13,002
63,980,159
add new columns in pandas depending on other columns values
<p>Hello I would need help in order to add two new columns in a dataframe such as:</p> <pre><code>Name start1 end1 OK0100087.1_0 0 375 OK0100087.1_1 376 750 OK0100087.1_2 751 1000 OK0100088.1 0 87766 OK0100089.1 0 66778 OK0100090.1_0 0 47519 OK0100090.1_1 47520 73733 <...
<p>This is just <code>groupby().transform()</code>, given you can extract the unique name:</p> <pre><code>total = df.groupby(df.Name.str.extract('^([^\.]+)')[0])['end1'].transform('max') df['start2'] = total - df['start1'] df['end2'] = total - df['end1'] </code></pre> <p>Output:</p> <pre><code> Name start...
python|python-3.x|pandas
3
13,003
63,106,109
How to display graphs of loss and accuracy on pytorch using matplotlib
<p>I am new to pytorch, and i would like to know how to display graphs of loss and accuraccy And how exactly should i store these values,knowing that i'm applying a cnn model for image classification using CIFAR10.</p> <p>here is my current implementation :</p> <pre><code> def train(num_epochs,optimizer,criterion,mo...
<p>What you need to do is: Average the loss over all the batches and then append it to a variable after every epoch and then plot it. Implementation would be something like this:</p> <pre><code>import matplotlib.pyplot as plt def my_plot(epochs, loss): plt.plot(epochs, loss) def train(num_epochs,optimizer,cri...
python|matplotlib|pytorch|conv-neural-network
4
13,004
63,207,452
How to hist() plot each data array row of a 2d NumPy array with Matplotlib?
<p>I have a 3x10 2d ndarray that I would like to do a matplotlib hist plot. I want a hist plot of each array row in one subplot. I tried supplying the ndarray directly but discovered matplotlib would provide hist plots of each column of the ndarray, which is not what I want. How can I achieve my objective? Presently, ...
<pre><code># import needed packages import numpy as np import matplotlib.pyplot as plt </code></pre> <hr /> <h2>Create data to plot</h2> <p>Using <a href="https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it/34932520">list comprehension</a> and <a href="ht...
python|numpy|matplotlib
1
13,005
63,022,937
How can I reduce the contextily source footer at the bottom of a cartopy GeoAxes?
<p>I'm attempting to plot a contextily basemap onto one of my cartopy GeoAxes, but the problem is the source footer at the bottom is HUGE. Is there any way to decrease its size? Thanks!</p> <p>This is how I simply add it to my axes:</p> <pre><code>import contextily as ctx ax2=fig.add_subplot(gs01[:,0], projection=ccrs...
<p>You can set option <code>attribution_size</code> in <code>ctx.add_basemap</code>, for example:-</p> <pre><code>ctx.add_basemap(ax2, attribution_size=6) </code></pre>
geopandas|cartopy|contextily
2
13,006
63,065,693
Aggregating customer spend without any customer ID
<p>I have 2 columns as below. The first column is spend, and the second column is months from offer. Unfortunately there is no ID to identify each customer. In the case below, there are three customers. e.g. The first 5 rows represent customer 1, the next 3 rows are customer 2, and then final 7 rows are customer 3. Yo...
<p>In Excel, you can insert a helper column that looks at the sign and determines if the sign is different to the row above and then increments a counter number.</p> <p>Hard code a customer ID of 1 into the first row of data, then calculate the rest.</p> <pre><code>=IF(AND(SIGN(A3)=-1,SIGN(A3)&lt;&gt;SIGN(A2)),B2+1,B2)...
python|excel|pandas
2
13,007
67,818,780
What does the xticks in pd.plot really means? pd.plot(x,y,xticks)
<pre class="lang-py prettyprint-override"><code>oil_price = pd.read_csv(&quot;2018-2019.csv&quot;,usecols=[&quot;date&quot;,&quot;brent&quot;]) oil_price.info() # now the type of &quot;date&quot; is object. oil_price[&quot;date&quot;] = pd.to_datetime(oil_price[&quot;date&quot;]) # now the type of &quot;date&quo...
<pre><code># Create figure and plot space fig, ax = plt.subplots(figsize=(10, 10)) # Add x-axis and y-axis ax.bar(df.index.values, df['bret'], color='purple') # Set title and labels for axes ax.set(xlabel=&quot;Date&quot;, ylabel=&quot;bret&quot;, title=&quot;Some...
python|pandas
0
13,008
68,008,658
How can I multiply columns from different DataFrame? (python)
<p>I am trying to make new a DataFrame by myltiplying 'Wage' of df1 with respective value of df2 (male by male's value and female by female's value) of data2. I tried with grouping but I was unable to solve this.</p> <pre><code>import pandas as pd data1 = {'gender':['male', 'female', 'male', 'male'], 'Age':[20, 20...
<p>Try with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.set_index.html#pandas-dataframe-set-index" rel="nofollow noreferrer"><code>set_index</code></a> then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mul.html#pandas-series-mul" rel="nofollow noreferrer">...
python|pandas|dataframe|data-science
2
13,009
68,023,206
How to find the rolling percentage Pandas
<p>I'd like to know the win percentage of a horse using a rolling count. This is what I have at the moment</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Horse</th> <th>Another header</th> <th>Wins</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>1</td> <td>1</td> </tr> <tr> <td>A</td> <td>...
<p>You can do it like this:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame({&quot;horse&quot;: [&quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;], &quot;wins&quot;: [1, 1, 2, 0, 1, 1]}) &gt;&gt;&gt; df horse wins 0 A 1 1 A 1 2 ...
python|pandas|statistics|percentage|rolling-computation
1
13,010
61,575,593
having trouble with import tflearn
<pre><code>File "/usr/local/lib/python3.7/site-packages/tflearn/variables.py", line 7, in &lt;module&gt; from tensorflow.contrib.framework.python.ops import add_arg_scope as contrib_add_arg_scope ModuleNotFoundError: No module named 'tensorflow.contrib' </code></pre>
<p>I did some research and it looks like <code>tensorflow.contrib</code> was removed in <code>tensorflow</code> when major version was bumped from 1 to 2. Try downgrading your tensorflow to latest v1 version:</p> <pre><code>pip install -U 'tensorflow&lt;2' </code></pre>
python|tensorflow
0
13,011
68,825,585
Count rows based on year-month and sort it from oldest to newest
<p>I have a df like this:</p> <pre><code>data = {'date':['2019-01-01', '2019-01-02', '2020-01-01', '2020-02-02'], 'tweets':[&quot;aaa&quot;, &quot;bbb&quot;, &quot;ccc&quot;, &quot;ddd&quot;]} df = pandas.DataFrame(data) df['daate'] = pandas.to_datetime(df['date'], infer_datetime_format=True) </code></pre> <p...
<p>you can use groupby to count the rows</p> <pre class="lang-py prettyprint-override"><code>df['year-month'] = df['daate'].dt.strftime('%Y-%m') df.groupby('year-month').count() </code></pre> <pre><code> date tweets daate year-month 2019-01 2 2 2 2020-01 1 1 1 20...
python|pandas|dataframe|time-series
1
13,012
68,613,359
Vectorized Text as Input into RNN
<p>I have the following function which add a new column to my dataframe. I want to use the vectorized text as into my RNN, however, i am not able to reshape the column to use it as input. How can i resolve this? Thanks</p> <pre><code># vectorization max_length = 500 def vectorization(text): seq = text.split() if se...
<p><strong>Few points</strong></p> <ul> <li>Ideally you should fit <code>TfidfVectorizer</code> on full train text but not per row as you are doing</li> <li>Each row is a np array of size 500 after <code>pad_sequences</code>. So you will have to concatenate all the np arrays rows wise to create a np array of size <code...
python|numpy|recurrent-neural-network
1
13,013
68,753,099
Extracting text after specific character set from a text file using regex in python
<p>Hi I have text in the following format below from which I wanted to save name(ex:2ND ACADEMY OF NATURAL SCIENCES) and its a.k.a. names along with original name in a dictionary like the following format,</p> <p>Tried to do it using the following code not able to extract the pattern,</p> <pre><code>re.findall(r'[a-z A...
<p>You could use 2 capture groups, and split the value of group 2 on <code>(?:;\s)?a\.k\.a\.\s</code> to get the separate values.</p> <p>Using re.findall will return the capture group values</p> <pre><code>^([A-Z0-9](?:[A-Z0-9 ]*[A-Z0-9])?\b)(?: \((a\.k\.a\.[^()]+(?:\sa\.k\.a\.[^()]+)*)\))? </code></pre> <p>The pattern...
python|regex|numpy|dictionary|text
1
13,014
68,498,156
Nested dictionary in csv convert to pandas dataframe
<p>I tried to use <code>json normalize</code> in nested dictionary as showed in <a href="https://i.stack.imgur.com/n7Jty.png" rel="nofollow noreferrer">image A</a> and it show error <code>string indices must be integers</code>. Here is my code</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pypl...
<p>You may use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.from_dict.html" rel="nofollow noreferrer">DataFrame.from_dict</a></p> <p>And pay attention in the orient Parameter:</p> <blockquote> <p>orient{‘columns’, ‘index’}, default ‘columns’</p> <p>The “orientation” of the data. If the keys of...
python|json|pandas|csv|json-normalize
0
13,015
53,256,877
How to convert keras(h5) file to a tflite file?
<p>I got an keras(h5) file. I need to convert it to tflite?? I researched, First i need to go via h5 -> pb -> tflite (because h5 - tflite sometimes results in some issue)</p>
<pre><code>from tensorflow.contrib import lite converter = lite.TFLiteConverter.from_keras_model_file( 'model.h5') tfmodel = converter.convert() open ("model.tflite" , "wb") .write(tfmodel) </code></pre> <p>You can use the TFLiteConverter to directly convert .h5 files to .tflite file. <strong>This does not work on Win...
python|tensorflow|machine-learning|keras
32
13,016
52,959,146
How to convert numpy array adjacency list into numpy array adjacency matrix?
<p>I have a following table in numpy array.</p> <p><a href="https://i.stack.imgur.com/ia1oO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ia1oO.png" alt="enter image description here"></a></p> <p>Now I want to convert this into adjacency matrix whose row is source, whose column is target, and who...
<p>Your data are more or less in <code>coo</code> format, so use <code>scipy.sparse.coo_matrix</code> constructor. The resulting sparse matrix can be converted to many formats.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from scipy import sparse &...
numpy|adjacency-matrix|adjacency-list
0
13,017
53,038,113
Memory Error While Preprocessing Using Keras
<p>I am working on a project to classify dog breeds using a CNN in Keras. While preprocessing the data, I am getting this memory error: <a href="https://i.stack.imgur.com/e9TkG.png" rel="nofollow noreferrer">https://i.stack.imgur.com/e9TkG.png</a>. What should I do?</p>
<p>You should use <code>data generator</code>. </p> <p>You get this error because your machine doesn't have enough RAM to fit all the data on it. If you write the generator then you can get as much data as you need and then you can use <code>model.fit_generator()</code>. With this, you grab some amount of data, prepro...
python|tensorflow|keras|jupyter-notebook
1
13,018
53,036,910
Pandas - remove the label of the column index
<p>I have a dataframe as follows:</p> <pre><code>PLEASE_REMOVE 2013 2014 2015 THIS_IS_EASY ------------------------------- Bob 0 3 4 Mary 2 3 6 </code></pre> <p>The years (2013, 2014, 2015) are the column index labels. The names (Mary, Bob) are the row index labels.</p> ...
<h2>New answer for pandas 1.x, <a href="https://stackoverflow.com/a/61312610">submitted by Ian Logie</a></h2> <pre><code>df.columns.name = None </code></pre> <p> </p> <h3>Old Answer from Oct 2018</h3> <p>Simply delete the name of the columns:</p> <pre><code>del df.columns.name </code></pre> <p>Also, note that <code>df....
python|pandas|dataframe
30
13,019
53,313,734
Reshaping numpy array
<p>What I am trying to do is take a numpy array representing 3D image data and calculate the hessian matrix for every voxel. My input is a matrix of shape (Z,X,Y) and I can easily take a slice along z and retrieve a single original image. </p> <pre><code>gx, gy, gz = np.gradient(imgs) gxx, gxy, gxz = np.gradient(gx) ...
<p>We can use a list comprehension to get the hessians -</p> <pre><code>H_all = np.array([np.gradient(i) for i in np.gradient(imgs)]).transpose(2,3,4,0,1) </code></pre> <p>Just to give it a bit of explanation : <code>[np.gradient(i) for i in np.gradient(imgs)]</code> loops through the two levels of outputs from <code...
python|numpy|image-processing|hessian-matrix
2
13,020
53,158,713
Read Large data from database table in pandas or dask
<p>I want to read all data from a table with 10+ gb of data into a dataframe. When i try to read with <code>read_sql</code> i get memory overload error. I want to do some processing on that data and update table with new data. How i can do this efficiently. My PC have 26gb of ram but data is max 11 gb of size, still i ...
<p>See here: <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html</a></p> <p>See that <code>chunksize</code> arg? You can chunk your data so it fits into memory.</p> <p>It will return...
python|pandas|performance|bigdata|dask
2
13,021
65,803,646
pyvin: Parsing VIN number
<h1>Context</h1> <p>Same code for decoding a column with Vehicle Identification Numbers, for one of the libraries i'm getting an error.</p> <h1>Code</h1> <pre><code>import pandas as pd from vininfo import Vin # COUNTRY AND BRAND from pyvin import VIN # MODEL AND YEAR db = pd.DataFrame(&quot;VIN&quot;: [&quot;3N6PD23W...
<p>Let's break the problem in pieces. First, the <code>db</code> is a pandas.DataFrame object. The <code>db[&quot;VIN&quot;]</code> is a pandas.Series object, as you probably know. You can also verify it with</p> <pre><code>In [19]: type(db[&quot;VIN&quot;]) Out[19]: pandas.core.series.Series </code></pre> <p>Then, the...
python|pandas|parsing|lambda|vin
0
13,022
53,673,419
Cannot feed value of shape (32, 1, 3) for Tensor u'/X:0', which has shape '(?, 3)
<p>I want to create a reinforcement project, but I struggle with some problems.</p> <p>I have a class for my neural network. Consisting of one Input Layer, two Hidden Layer and one output-Layer. It is created with tflearn.</p> <pre><code>class Network(): self.inputs, self.outputs = self.createNetwork() [...] ...
<p>Your input layer is expecting a shape of (?,3) --> <code>inputs = tflearn.input_data(shape=[None, 3])</code><br> The input_shape should be <code>(None, 1, 3)</code> to match the shape of your data.</p>
python|tensorflow|shapes|tflearn
0
13,023
53,507,266
Failing to fetch Tensorflow's convolution algorithm
<p>I am printing the following the error message:</p> <pre><code>UnknownError Traceback (most recent call last) &lt;ipython-input-11-e73400b11710&gt; in &lt;module&gt;() 1 earlystopper = EarlyStopping(patience=6, verbose=1) ----&gt; 2 history = parallel_model.fit(X_train, Y_train, va...
<p>Requirement of the version of cudnn changed: <a href="https://www.tensorflow.org/install/gpu" rel="nofollow noreferrer">https://www.tensorflow.org/install/gpu</a></p> <p>cudnn version >= 7.2</p> <p>I update cudnn and it works well.</p>
python|tensorflow
1
13,024
53,575,958
Set Pandas column values to an array
<p>I have the following problem: I have a dataframe like this one:</p> <pre><code> col1 col2 col3 0 2 5 4 1 4 3 5 2 6 2 7 </code></pre> <p>Now I have an array for example a = [5,5,5] and i want to insert this array in col3 but only in specific rows (let's say 0 and 2) and...
<p>What you're attempting is not recommended.<sup>1</sup> Pandas is not designed to hold list in series. Having said this, you can define a series explicitly and assign via <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.update.html" rel="noreferrer"><code>update</code></a> or <a href="htt...
python|arrays|pandas|dataframe|series
6
13,025
53,614,874
When is the size of an ndarray not fixed?
<p>The <a href="https://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html" rel="nofollow noreferrer">numpy.ndarray documentation</a> states that:</p> <blockquote> <p>An ndarray is a (usually fixed-size) multidimensional container of items of the same type and size.</p> </blockquote> <p>I'm surprised by the adj...
<p>You are allowed to reshape the dimensions, so the memory itself is fixed-sized, but the way you shape it may be adapted (hence it may not be fixed dimensions).</p> <p>You can resize the array with <code>resize</code>, but it's basically a new array.</p>
python|numpy|multidimensional-array|numpy-ndarray
2
13,026
71,887,167
Vectorized way to find if 1 value in row from list of columns is greater than threshold
<p>I am new to using <code>np.where()</code>, so of course I tried to use my new toy for this problem. But it does not work.</p> <p>I have a dataframe.</p> <pre><code>Close M N O P 0.1 0.2 0.3 0.4 0.5 0.2 0.1 0.6 0.1 0.0 Colslist = [M,N,O,P] </code></pre> <p>I want a new column called Q with the r...
<p>The problem is that the axes don't match in your condition. The output of</p> <pre><code>df[Colslist] &gt;= (df['Close'] + 0.3) </code></pre> <p>is</p> <pre><code> M N O P 0 1 0 False False False False False False 1 False False False False False False </code></pre> <p>which...
python-3.x|pandas|numpy
1
13,027
55,251,162
Anaconda did not install packages openpyxl and xlrd
<p>After installing a new Python 3.6 environment with pandas, numpy, etc. when I tried to use the following pandas method I got the following errors:</p> <pre><code>&gt;&gt;&gt; df.to_excel(filename) ModuleNotFoundError: No module named 'openpyxl' </code></pre> <p>Similar issue occurred earlier when I used the <code>...
<p>Yes, this is intentional. If you read <a href="https://pandas.pydata.org/pandas-docs/stable/install.html#optional-dependencies" rel="nofollow noreferrer">the Optional Dependencies section of the Pandas documentation</a>, you can see that Excel I/O is included in there. </p> <p>A couple arguments I can think of for ...
python|pandas|module|conda
3
13,028
55,563,865
Tensorflow throws 'Incompatible shapes' error in Lambda layer when batch_size > 1
<p>I have a simple CNN with two inputs for text processing (code below). One input for tokens another one for weights. Both inputs are sequences of the same <code>MAX_LENGTH</code>. After passing tokens through embedding layer I'd like to multiply those embeddings by corresponding weights. So I defined new Lambda layer...
<p>When calling the lambda layer, your tensor <code>x</code> has shape <code>(batch_size, MAX_LENGTH, EMB_SIZE)</code> and <code>inp_w</code> has shape <code>(batch_size, MAX_LENGTH)</code>. Since you are taking the transpose of <code>inp_w</code> inside your custom <code>mult</code> function, you end up with the shape...
tensorflow|lambda|keras|embedding
0
13,029
55,251,132
row values on pie slices python
<p>I have the following dataset:</p> <pre><code>import matplotlib.pyplot as plotter pieLabels = 'Asia', 'Africa', 'Europe', 'North America', 'South America', 'Australia' populationShare = [5.69, 16, 9.94, 7.79, 5.68, 6.54] </code></pre> <p>To make the pie:</p> <pre><code>figureObject, axesO...
<p>Try like the following:</p> <pre><code>import matplotlib.pyplot as plotter pieLabels = ['Asia', 'Africa', 'Europe', 'North America', 'South America', 'Australia'] populationShare = [5.69, 16, 9.94, 7.79, 5.68, 6.54] figureObject, axesObject = plotter.subplots() axesObject.pie(populationShare, labe...
python|pandas
1
13,030
47,272,682
Holoviews Dynamic Map with existing Pandas dataframe
<p>I have a pandas dataframe that I read from a database, with a structure similar to </p> <pre><code>dt t1 t2 val1 val2 12 A C 12 33 13 A B 42 39 14 T C 12 09 </code></pre> <p>and I'm trying to generate a DynamicMap from the dataframe. The problem is that all examples for Dynamic Maps are for gen...
<p>You can simply omit ", df" from the argument list of gen_from_pandas, as long as you have defined df before defining that function. You'll be able to refer to it in the enclosing namespace instead.</p> <p>ETA: If you can't refer to the enclosing namespace, just make a closure:</p> <pre><code>df = pd.DataFrame(dic...
python|pandas|holoviews
0
13,031
57,041,623
Pythonic syntax for extended variable transformation (multiple lengthy method calls)
<p>Trying to seek some guidance on the best way of curating an extensive ETL process. My pipeline has a reasonably sleek extract section, and loads into a designated file in a succinct manner; but the only way I can think to do transformation steps is a series of variable assignments:</p> <pre><code>a = ['some','form'...
<p>Create a list of partially applied functions, then loop over that list.</p> <pre><code>transforms = [ lambda x: petl.addfield(x, 'NewStrField', str(x)), petl.addrownumbers, lambda x: petl.rename(x, 'row', 'ID') ] a = ['some', 'form', 'of', 'petl', 'data'] for f in transforms: a = f(a) </code></pre>...
python|pandas|petl
0
13,032
45,910,155
combine output of multiple functions into a pd.Series in python (like c() in R)
<p>I've been using <code>R</code> for data analysis and am trying to learn <code>python</code>. In R, I can create vectors with <code>c()</code>, which gives me back a "column" resulting from whatever I pass it. I often use it to concatenate sequences or repeated values. Something like this:</p> <pre><code>&gt; test &...
<p>If you start with numpy arrays, you can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow noreferrer"><code>numpy.concatenate</code></a>:</p> <pre><code>pd.np.concatenate([np.repeat([1, 2], 2), np.arange(5, 10, 2), np.random.random_sample(3)]) #array([ 1. ...
python|pandas|numpy
5
13,033
50,962,280
set value only according column name in dataframe
<pre><code> max_speed shield new 1 1 2 3 2 4 5 6 </code></pre> <p>I got this dataframe, and I want to assign a value according to some column names. like this df.loc[df['max_speed']==1, df['shield']==2, new] = 10 then I will get the new dataframe:</p> <pre><code> max_speed s...
<p>you are pretty close.</p> <pre><code>df.loc[(df.max_speed == 1) &amp; (df.shield == 2), "new"] = 10 </code></pre> <p>For further reading, see <a href="https://stackoverflow.com/questions/15315452/selecting-with-complex-criteria-from-pandas-dataframe">here</a>.</p>
python|pandas
2
13,034
50,789,492
Having trouble extracting the string value from a tensor with datatype tf.string
<p>I'm writing an NN which requires text (as a string) to be fed in as a placeholder in Tensorflow. I'm having trouble figuring out how to extract the string from the placeholder, which must hold a tensor object. I tried initializing and interactive session and then calling placeholder.eval(), but I got an error becaus...
<p>To answer your question:</p> <p><a href="https://www.tensorflow.org/api_docs/python/tf/placeholder" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/placeholder</a></p> <blockquote> <p>Inserts a placeholder for a tensor that will be always fed.</p> <p><strong>Important</strong>: This ...
python-3.x|tensorflow
0
13,035
66,560,789
evaluation not done/ export no provided when training a TF model on AI Platform
<p>I have TF a DNNRegressor to train Locally / Cloud in GCP (AI Platform).</p> <p>If the training is done locally (through the <code>gcloud</code> command below), there will be checkpoints, eval folder and export folder.</p> <pre class="lang-sh prettyprint-override"><code>gcloud ai-platform local train \ --module-n...
<p>I believe you should check this related SO question:</p> <p><a href="https://stackoverflow.com/questions/62337037/ai-platform-no-eval-folder-or-export-folder-in-outputs-when-running-tensorflow">ai-platform: No eval folder or export folder in outputs when running TensorFlow 2.1 training job using Estimatorssearchluck...
tensorflow|google-cloud-platform|gcloud
1
13,036
66,371,297
How to speed up nested for-loop logic in Python with Pandas, Numpy?
<p>I would like to check out whether the field of table <code>TestProject</code>contains the parameter from the Client-side passed, nested for loop is ugly, is there any efficient and easy way to realize it? Thanks so much for any advice.</p> <pre><code>def test(parameter_a: list, parameter_b: list) -&gt; bool: age...
<p>May be use <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow noreferrer"><code>itertools.product</code></a> and <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow noreferrer"><code>all</code></a>?</p> <pre><code>from itertools import product def tes...
python|python-3.x|pandas|numpy
4
13,037
66,609,534
Python Pandas: Compare ticks with differing intervals to hourly data
<p>I have a months worth of ticks at differing intervals in a pandas dataframe as follows</p> <pre><code> Spread Date 2021-02-01 00:01:10.718 9.0 2021-02-01 00:01:14.471 9.2 2021-02-01 00:01:24.794 5.5 2021-02-01 00:01:30.738 4.6 2021-02-01 00:01:30.938...
<p><code>pd.merge_asof</code> is your friend here:</p> <pre><code>s = pd.merge_asof(df, hourly, on='Date') # for references df['Upper'] = s['Upper'].values # we need to pass value because `merge_asof` reset the index df['matched'] = (s['Spread'] &lt;= s['Upper']).values </code></pre> <p>Output:</p> <pre><code> ...
python|pandas|date|pandas-groupby
0
13,038
66,746,205
How to fill columns based on other column values?
<p>I have a df where I want to query the postalcode to match address and city.</p> <pre><code>Postalcodestring 1181 1055 8547 </code></pre> <p>I'm using nomi.query_postal_code('n') for this. Hereby, when inputting the following the table is shown:</p> <pre><code>postal_code 1181 country_code ...
<p>You should use the <code>df.apply</code> method:</p> <pre><code>import pandas as pd import pgeocode df = pd.DataFrame({'Postalcodestring': ['1181', '1055', '8547']}) nomi = pgeocode.Nominatim('nl') df['City1'] = df['Postalcodestring'].apply(lambda code: nomi.query_postal_code(code)['place_name']) </code></pre> <p>...
python|pandas|dataframe
1
13,039
57,390,019
How can I get Keras CNN to work with the right number of dimensions?
<p>I get the error:<br> <strong>"Error when checking input: expected conv1d_41_input to have 3 dimensions, but got array with shape (1920, 5000)"</strong><br> when trying to compile a CNN model in Keras.</p> <p>My input data is 1920 samples with 5000 features.</p> <p>I have tried adding a Flatten layer before the fir...
<p>If you declare your input shape as <code>input_shape=(5000,1)</code>, then your data should have shape <code>(None, 5000,1)</code>, where the first dimension corresponds to samples, so in this case you just need to add the channels dimension with a value of one by reshaping:</p> <pre><code>X_train = X_train.reshape...
python|tensorflow|keras
1
13,040
57,693,230
How to convert time data to numeric value?
<p>I have a dataframe <code>out</code>:</p> <pre><code> dates min max wh 0 2005-09-06 07:41:18 21:59:57 14:18:39 1 2005-09-12 14:49:22 14:49:22 00:00:00 2 2005-09-19 11:08:56 11:24:05 00:15:09 3 2005-09-21 21:19:21 21:20:15 00:00:54 4 2005-09-22 19:41:52 19:41:5...
<p>One possible solution is convert timedeltas to native format, aggregate <code>mean</code> and then convert back to timedeltas:</p> <pre><code>out['dates'] = pd.to_datetime(out['dates']) out['month']= pd.PeriodIndex(out.dates, freq='M') out['wh'] = pd.to_timedelta(out['wh']).astype(np.int64) out2=pd.to_timedelta(ou...
python|pandas|datetime
3
13,041
72,914,086
How to iterate through a dataframe and find a specific part of a string and add it too a new column?
<p>I have a dataframe and there is a specific string I want to pull out and delete apart of it. The string repeats throughout the file with different endings. I want to find part of the string, delete some of it, and add the part I want to keep to several columns. I have an empty dataframe column that I want to add the...
<p>As long as you have a way of identifying the values you want to turn into the group data and a way of manipulating those values to make them what you want, then you can do something like this.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd data = [ [None, 'Group: X', None, None], [No...
python|pandas
1
13,042
73,110,331
Cannot drop index column from DataFrame when convert to html
<p>I'm trying to get rid off index column, when converting DataFrame into HTML, but even though I reset index or set <code>index=False</code> in <code>to_html</code> it is still there, however with no values.</p> <pre><code>df = df.set_index(['ID','Name','PM', 'Theme'])['Score'].unstack() df = df.reset_index() df_HTML ...
<p>Try this:</p> <pre><code>df = df.set_index(['ID','Name','PM', 'Theme'])['Score'].unstack() df = df.reset_index(drop=True).drop('Theme',axis=1) df_HTML = df.to_html(table_id = &quot;table_score&quot;, index=False, escape=False) </code></pre> <p>The error was caused because your theme columns seens to be your old inde...
python|pandas
0
13,043
73,046,541
Filter Nulls when converting pandas dataframe to dict
<p>I have this pandas dataframe.</p> <pre><code> technologies = [ (&quot;Spark&quot;, 22000,'30days',1000.0, 'Scala'), (&quot;PySpark&quot;,25000,'50days',2300.0, 'Python'), (&quot;Hadoop&quot;,23000,'55days',np.nan,np.nan) ] df = pd.DataFrame(technologies,columns = ['Courses','Fee','Duration','Discount', ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.notna.html" rel="nofollow noreferrer"><code>notna</code></a> for filtering missing values:</p> <pre><code>final_result = {k:v for k, v in result.items() if pd.notna(v)} </code></pre> <hr /> <pre><code>final_result = [{k:v for k, v in resul...
python|pandas
1
13,044
70,609,874
Fill new column in df based on many conditions in df2 and df3
<p>I have three dfs. df1 contains 46 columns. df2 and df3 contain 41 columns and contain threshold values for columns in df1 which indicate if it needs a repeat or repeat with addition. Below are simplified examples</p> <p>df1:</p> <pre><code> |Name | A | B | C |....... ------------------------------ 0|ID1 | 10 ...
<p>You're right that you want to use <code>np.select</code>, but the conditions you need to provide are Boolean Series that are the same length as <code>df1</code>. To do this, you need to compare with the rows in <code>df2</code> and <code>df3</code> as Series (so that it aligns on the columns) and then check if <code...
python|pandas|dataframe
0
13,045
51,117,661
Given a DataFrame of datetimes, plot yearly user access
<p>Given the DataFrame below, plot user access by year.</p> <p>Preferable a line graph with x-axis being years and y-axis being number of times accessed in that year.</p> <p>DataFrame:</p> <pre><code>In: print df Out: 0 2016-10-01 1 2015-11-05 2 2017-12-07 3 2016-08-09 4 2...
<p>Use:</p> <pre><code>df['date'].dt.year.value_counts().sort_index().plot.bar() </code></pre> <p><strong>Detail</strong>:</p> <pre><code>print (df['date'].dt.year.value_counts().sort_index()) 2015 3 2016 5 2017 3 Name: date, dtype: int64 </code></pre> <p><strong>Explanation</strong>:</p> <ol> <li>First c...
python|pandas
1
13,046
71,012,558
Python: append not adding to an empty list
<p>Hi sorry if this is an obvious one, looked around online and I can't seem to find what I'm doing wrong.</p> <p>I am trying to compare the contents of two lists, in two separate csv files (file A and file B). Both csv files are of x rows, but only 1 column each. File A consists of rows with sentences in each, file B ...
<p>The problem is in the if-statement <code>y in words</code>.</p> <p>Here <code>y</code> is a list. You're searching for a list inside a list of strings (not a list of lists).</p> <p>Using <code>y[0] in words</code> solve your problem.</p>
python|pandas|list|for-loop|append
2
13,047
51,571,578
How much time a image classification algo can take?
<p>I have written below code for recognizing images.</p> <pre><code># Importing the Keras libraries and packages from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense # Initialising the CNN classifier = ...
<p>The problem is the directory structure you are giving. </p> <pre><code>training_set = train_datagen.flow_from_directory('E:\\ML_R&amp;D\\training_set\\cats1', target_size = (64, 64), batch_size = 32, class_mode = 'binary') </code></pre> <p>Here the path <code>E:\\ML_R&amp;D\\training_set\\cats1</code> must contain...
python-3.x|tensorflow|machine-learning|keras|anaconda
1
13,048
51,793,364
Pandas not exporting dataframe to csv
<p>I have a script to output a whole bunch of CSVs to folder c:\Scripts\CSV. This particular script is looping through all of the dataframes and counting the usage of the top 100 words in the data set. The top 100 words and their count are added to a list, the dataframes are concatenated, and then the csv should expo...
<p>Try using <code>pathlib</code> instead:</p> <pre><code>from pathlib import PureWindowsPath directory = PureWindowsPath('c:/Scripts/CSV/') for csv_f in directory.glob('**/*.csv'): # process inputs target_path = directory / 'somename.csv' thatdata.to_csv(target_path) </code></pre>
python|pandas|dataframe|export-to-csv
0
13,049
38,018,423
tensorflow ffmpeg contrib output
<p>First, I want to say that I'm completely new to TensorFlow and machine learning in general.<br> I'm looking at the <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/ffmpeg" rel="nofollow">ffmpeg</a> contrib section and I see the example of decoding an audio file and I was wondering wha...
<p>Each of those float values in the waveform represent the <em>amplitude</em> of the corresponding audio at a discrete moment in time depending on the sample rate (in this case, every 1/16,000th of a second). If you were looking at 2 channels of audio rather than 1, you'd have another similar ndarray, thereby giving y...
python|ffmpeg|tensorflow
1
13,050
64,495,124
How to find the total length of a column value that has multiple values in different rows for another column
<p>Is there a way to find IDs that have both Apple and Strawberry, and then find the total length? and IDs that has only Apple, and IDS that has only Strawberry?</p> <p>df:</p> <pre><code> ID Fruit 0 ABC Apple &lt;-ABC has Apple and Strawberry 1 ABC Strawberry &lt...
<p>If always all values are only <code>Apple</code> or <code>Strawberry</code> in column <code>Fruit</code> you can compare sets per groups and then count <code>ID</code> by <code>sum</code> of <code>True</code>s values:</p> <pre><code>v = ['Apple','Strawberry'] out = df.groupby('ID')['Fruit'].apply(lambda x: set(x) ==...
python-3.x|pandas|numpy|dataframe|summary
3
13,051
64,308,977
Python Numpy vs Matlab : Array assignment performance
<p>I've been writing Matlab code for many years and recently I have started writing in python. Let me try to explain the problem I am facing:</p> <p>Some part of my code associates cells in a large array, let's say for the sake of the example an image of size 1080x1400, to a smaller array, a grid of size 770x700. All t...
<p>Problem solved:</p> <p>I've used numba with jit compiling and now the Python code runs in an average of 17 msec !!</p> <p>Thanks</p> <pre><code>import numpy as np import cv2 import time import numba @numba.jit(nopython=True) def Pix2Grid_MovAvg(DataMtx, OutMtx, Wx, Wy, fp_Row, fp_Col, number_of_coords): N = 1 ...
python|arrays|performance|matlab|numpy
2
13,052
47,919,045
Pandas - Rounding off timestamps to the nearest second
<p>I am struggling to round off timestamps using pandas.</p> <p>The timestamps look like this:</p> <pre><code>datetime.datetime(2017,06,25,00,31,53,993000) datetime.datetime(2017,06,25,00,32,31,224000) datetime.datetime(2017,06,25,00,33,11,223000) datetime.datetime(2017,06,25,00,33,53,876000) datetime.datetime(2017,0...
<p>You can use first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="noreferrer"><code>read_csv</code></a> with parameter <code>parse_dates</code> for create <code>datetime</code>s from column <code>date</code> and <code>time</code> and then <a href="http://pandas.pydata.org/pa...
python|python-2.7|pandas|datetime
9
13,053
47,847,423
How can i use my mnist trained model to predict an image
<p>I'm new to Tensorflow. I've done MNIST training by this example</p> <pre><code>steps = 5000 with tf.Session() as sess: sess.run(init) for i in range(steps): batch_x , batch_y = mnist.train.next_batch(50) sess.run(train,feed_dict={x:batch_x,y_true:batch_y,hold_prob:0.5}) # PRINT OU...
<p>You try to feed into your placeholder the tf-object:</p> <pre><code>images = tf.reshape(image,[-1,28,28,1]) </code></pre> <p>but you cannot do that since placeholder expects number for example <code>np.array</code>. So use <code>numpy.reshape</code> instead of <code>tf.reshape</code>. Second one you can use inside...
python|tensorflow|mnist
0
13,054
47,922,359
Multiple sequential Tensorflow operations in same Session.run() call
<p>As the title suggests, I want to run multiple Tensorflow operations in the same <code>Session.run()</code> call. Specifically, to make the problem more concrete, suppose I want to run multiple training iterations in a single call. </p> <p>The standard way of doing that with multiple <code>Session.run()</code> calls...
<p>It sounds like you could put whichever operations you'd like to run multiple times in a <a href="https://www.tensorflow.org/api_docs/python/tf/while_loop" rel="nofollow noreferrer">tf.while_loop</a>. If the operations are independent, you may have to either set <code>parallel_iterations</code> to <code>1</code> or (...
tensorflow
3
13,055
49,209,063
Fix csv files through Excel/Numbers [automatically through Python]?
<p>I'm working with some CSV files which have been created incorrectly. There are quotations and commas interconnected, and I keep getting parsing errors from pd.read_csv, even after replacing all column-separating commas with tabs.</p> <p>Nevertheless, Numbers (Apple's Excel) can read the file perfectly, and, after r...
<p>Have you tried setting <code>quoting</code> and <code>doublequote</code> in <code>pd.read_csv()</code>? It's odd to me that Pandas can't read a csv that Excel can (i usually have problems with Excel instead; the only issue i've had with Pandas is NUL characters).</p> <p>Alternatively you can also run this in VBA:</...
excel|pandas|csv|dataframe|excel-automation
1
13,056
49,054,893
convert object column into date type column using python
<p>i have a csv file. that have a column named DOB. but when i want to change the data type into date type. its gave error. here is the code</p> <p><code>b['DOB'] = pd.to_datetime(b['DOB'], format='%Y-%m-%d')</code></p>
<p>When you read csv in pandas, read it like below: <code>pd.read_csv(file_name,parse_dates=True)</code></p> <p>parse_dates=True converts data to date format if it has date.</p>
python|pandas|datetime|null
0
13,057
49,149,374
Get ascending order of numbers in array in python
<p>I have a Numpy array with some numbers and I would like to get order the items ascending order.</p> <p>For example, I have a list:</p> <p><code>[4, 25, 100, 4, 50]</code></p> <p>And I would like to use a function to get this:</p> <p><code>[1, 2, 4, 1, 3]</code></p> <p>Any ideas how to do this?</p>
<p>There is a convenient method via <code>pandas</code>:</p> <pre><code>import pandas as pd lst = [4, 25, 100, 4, 50] res = pd.factorize(lst, sort=True)[0] + 1 # [1 2 4 1 3] </code></pre>
python|numpy
1
13,058
49,199,657
numpy array concatenate with extra column to each array
<p>I try to split a numPy array in roughly equal parts and merge them together with an extra value but end up being confused how I could do this. I have a list : [0., 2.25, 4., 4., 4., 4., 4., 4., 4., 2.25], which after an np.array_split and concatenate with an extra column should end up like: [0. , 2.25, 4., 8., 4., ...
<p>Could you instead not just do </p> <pre><code>np.insert(list, [3,6,8],[8]) array([ 0. , 2.25, 4. , 8. , 4. , 4. , 4. , 8. , 4. , 4. , 8. , 4. , 2.25, 8. ]) </code></pre> <p>np.array_split produces a list of split array. So to get your desired result you would have to do </p> <pre><...
numpy
0
13,059
58,965,648
len() of unsized object (list)
<p>I am trying to modify the weights of cifar cnn and rerun inference with the modified weights. When I try to modify the weights by passing it to a function, I get the Len() of unsized object error. </p> <pre><code>f1 = h5py.File('/content/model_weights.h5', 'r+') # open the file data = np.array(f1.get('/conv1d_1...
<p>A better way to iterate through lists in a <code>for</code> loop is to do the following:</p> <pre><code>for item in mylist: print(item) </code></pre> <p>This will print each item in the list, by assigning the value of each entry to the variable defined in the <code>for</code> statement as it iterates.</p> <p>...
python|list|numpy
2
13,060
58,914,730
Python Pandas: Create dataframe from Excel file with multi (merged cell) headers
<p>I am relatively new to Python (Pandas) which I would like to use for automating Excel tasks and be more efficient at my work :)</p> <p>Currently I am sitting in front of below Excel sales report where the "year" is a merged cell. </p> <pre><code> | 2018 | ...
<p>First for <code>MultiIndex</code> in columns add parameter <code>header=[0,1]</code> and for avoid <code>MultiIndex</code> by first column add <code>index_col=[0]</code> for convert firt column to index:</p> <pre><code>df = pd.read_excel("Stackoverflow_example.xlsx", header=[0,1], index_col=[0]) </code></pre> <p>T...
python|excel|pandas|dataframe|header
1
13,061
70,360,688
Python and Pandas versions change how a number is interpreted after DataFrame read
<p>I have 2 environments:</p> <p><strong>Environment #1 (old):</strong></p> <ul> <li>Python 3.7.5</li> <li>Pandas 0.23.4</li> </ul> <p><strong>Environment #2 (new):</strong></p> <ul> <li>Python 3.8.10</li> <li>Pandas 1.3.4</li> </ul> <p>When I load the same CSV file by doing <code>pd.read_csv('name_of_my_csv_file.csv',...
<p>So, at the end it seems like an issue with representation of float objects which, in the environment #1 (old) (described in my question above) was misinterpreted. The environment #2 (new)'s values are actually correct. That means, that we will need to adjust the tests to actually match the new environment's output i...
python|pandas
0
13,062
56,242,672
Is pandas automatically adding a row and a columns in the first position?
<p>I'm using pandas to merge some csv files (the range of csv files's number is can vary). When I run the script, it seems that a column and a row are automatically added (as you can see in the picture below).</p> <p>I use pandas with python 3.7 and run a windows OS based computer. I use Excel to open the csv files.</...
<p>You'll want to set both <code>index</code> and <code>header</code> to <code>None</code>. (Not exactly intuitive in my opinion as it should have been <code>index</code> but <code>columns</code>, but what can you do.)</p> <p>To prevent having your column names repeated in the data, you need to set your column names i...
python|python-3.x|pandas|csv|concatenation
0
13,063
56,157,797
How to apply lower() to pandas columns?
<p>What's the correct way to lowercase all text-like columns in a pandas dataframe? I was trying this approach</p> <pre><code>def lowercase(col): if isinstance(col, __pandas_object_type__): return col.str.lower() df = df.apply(lowercase) </code></pre> <p>where <code>__pandas_object_type__</code> is just a...
<p>Just try each column and pass if it fails:</p> <pre><code>for col in df.columns: try: df[col] = df[col].str.lower() except AttributeError: pass </code></pre> <p>This way, you avoid the explicit type checking.</p> <p>Warning: this will take mixed-type columns that have strings in them, and ...
python|pandas
2
13,064
55,941,403
How to insert multiple rows and colums to dataframe
<p>I have a dataframe with exchange rate data. I want to insert the base currency(Norwegian Krone) for the entire daterange(from min Date to max Date) at value 1 in Units.</p> <p>Tried to merge dataframes, but no luck with my skills. The data is required for further computation for another task.</p> <pre><code> ...
<p>The trick is to obtain a range of dates that have holes in it like the source data and then to efficiently construct the repeating rows for the purpose of appending and then sorting. When constructing a dataframe, a single dictionary may be used to fill out the dataframe.</p> <pre><code>import pandas as pd import ...
pandas|dataframe
0
13,065
55,958,543
How to merge multiple dataframes with unique field names into a single dataframe?
<p>I'm trying to merge 5 dataframes into a single dataframe. Each individual dataframe has the same format, the only variation is the column name. </p> <pre><code># Input Dataframes df1 = df[['id', 'num', 'type_1', 'object_1', 'notes_1']] df2 = df[['id', 'num', 'type_2', 'object_2', 'notes_2']] df3 = df[['id', 'num', ...
<p>Thank you to @scott-boston and @alollz. I think you both are right but I was able to get it to work with Scott's suggestion. Thank you all.</p> <pre class="lang-py prettyprint-override"><code># rename columns d1 = df1a.rename(columns={'id':'id',\ 'num':'num',\ '...
python|pandas|concatenation
0
13,066
64,644,395
Copy every 2nd matrix element in Python
<p>I want to copy every 2nd matrix element in Python.</p> <p>For example:</p> <pre><code>arr1 = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]] </code></pre> <p>The desired array should be:</p> <pre><code> [2, 4] [7, 9] [12, 14] </code></pre> <p>What's the easiest way to ...
<p>Just slice the columns:</p> <pre><code>arr1_sliced = arr1[:,1::2] # if arr1 is a python list, use arr1_sliced = np.array(arr1)[:,1::2] print(arr1_sliced) # [[ 2 4] # [ 7 9] # [12 14]] </code></pre>
python|arrays|numpy
3
13,067
64,952,687
How does a (2 or 3) dimensional Fully connected layer work?
<p>I came across a Neural network which had the following configuration:(FCL = Fully connected layer)</p> <ul> <li>Input Layer - 1 dimensional with 100 units</li> <li>1st layer - 1 dimensional FCL with 512 units</li> <li>2nd layer - 3 dimensional FCL with aXbXc size</li> </ul> <p>Now as far as I know, a fully conne...
<p><code>aXbXc</code> doesn't mean that the dense layer has 3 dimensions. It is just a single number obtained by multiplying <code>a</code>, <code>b,</code> and <code>c</code> together to obtain the size of that dense layer.</p> <p>According to the provided link:</p> <pre><code>model.add(Dense(dim * dim * depth)) </cod...
tensorflow|machine-learning|keras|deep-learning
0
13,068
39,498,910
Installing tensorflow in Windows Anaconda 4.1.1 w Python 2.7
<p>I have followed the instructions in</p> <p><a href="https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html#anaconda-installation" rel="nofollow">https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html#anaconda-installation</a></p> <p>activate tensorflow changes the environment as in the in...
<p>We just announced support for TensorFlow on Windows with the 0.12 release candidate. However, due to the vagaries of <a href="https://wiki.python.org/moin/WindowsCompilers" rel="nofollow noreferrer">compiler versions on Windows</a>, we only support Python 3.5 (see below for a fuller explanation).</p> <p>At present ...
python|windows|tensorflow|anaconda
2
13,069
39,812,275
How to pivot pandas DataFrame column to create binary "value table"?
<p>I have the following pandas dataframe:</p> <pre><code>import pandas as pd df = pd.read_csv("filename.csv") df A B C D E 0 a 0.469112 -0.282863 -1.509059 cat 1 c -1.135632 1.212112 -0.173215 dog 2 e 0.119209 -1.044236 -0.861849 dog 3 f -2.104569 -0.494929...
<p>use <code>pd.concat</code>, <code>drop</code>, and <code>get_dummies</code></p> <pre><code>pd.concat([df.drop('E', 1), pd.get_dummies(df.E).mul(-1)], axis=1) </code></pre> <p><a href="https://i.stack.imgur.com/4kxQD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4kxQD.png" alt="enter image description h...
python|pandas|dataframe|binary|categorical-data
8
13,070
44,021,513
dropping columns in panda if they are NaN before a certain date
<p>I have a large dataframe that has measurements in it with different start dates. I now want to cut this down to a dataframe that only contains measurements that are older than a certain date. </p> <p>I want to turn this:</p> <pre><code> A B C D E 1950-11-01 3 NaN NaN NaN NaN 1950...
<pre><code>begin_date = pd.to_datetime('1951-01-01') </code></pre> <h1>find the columns to keep</h1> <pre><code>cols = ~df.loc[:begin_date].isnull().all() </code></pre> <p>Initially I had </p> <pre><code>cols = df.columns[~df.loc[:begin_date].isnull().all()] </code></pre> <p>but the <code>df.columns</code> is inde...
python|pandas|nan
3
13,071
40,863,658
Numpy matrix comparison to several criteria
<p>I'm working on comparing values in a numpy matrix.</p> <p>Initially I wanted to check if any of the values in the matrix m were smaller than X, so I used:</p> <pre><code>(m&lt;(X)).any() </code></pre> <p>Which worked fine, but now I would like it to ignore all 0 values in the matrix, so in essence to tell me if a...
<p>Much like <a href="https://stackoverflow.com/questions/13869173/numpy-find-elements-within-range">here</a>, you can do</p> <pre><code>np.where(np.logical_and(0&lt;a,a&lt;6)) </code></pre> <p>And it will give you two arrays, which tell you the locations in your matrix.</p> <pre><code>(array([0, 0, 1, 1, 1], dtype=...
python|numpy|matrix|string-comparison
0
13,072
53,824,326
Python - select row cell based on another cell condition
<p>I am writing some python to draw a pie chart. I am attempting to find how many goals were scored using a certain formation. The format of each row is:</p> <pre><code>date home_team away_team home_score away_score home_formation away_formation 14/06/2018 Russia Saudi Arabia 5 0 ...
<pre><code>formations = ['4-1-4-1', '4-2-3-1'] #Add as many as you'd like formation_scores = {formation: df[df['home_formation'] == formation]['home_score'].sum() for formation in formations} </code></pre>
python|pandas|data-analysis
2
13,073
38,353,567
How to fuzzy match movie titles with difflib and pandas?
<p>I have 2 lists of potentially overlapping movie titles, but possibly written in a different form.<br> They are in 2 different dataframes from pandas. So I have tried to use the <code>map()</code> function with the <code>fuzzywuzzy</code> library like so:</p> <pre><code>df1.title.map(lambda x: process.extractOne(x, ...
<p>To eliminate the possibility of low-score matches as a result of case-differences, I'd suggest applying <code>.upper()</code> or <code>.lower()</code> to the columns you're matching. After adjusting the case, you could compile a list of all titles into <code>ThisList</code> and apply the following function (relying...
python|pandas|fuzzy-search|difflib|fuzzywuzzy
2
13,074
38,476,733
Pandas.read_excel: Accessing the home directory
<p><strong>[Solution Found]</strong></p> <p>I have encountered some unexpected behavior when trying to access my home directory using <code>pandas.read_excel</code>.</p> <p>The file I want to access can be found at</p> <pre><code>/users/isys/orsheridanmeth </code></pre> <p>which is where <code>cd ~/</code> takes me...
<p>I believe <code>~</code> is expanded by the shell - in which case your code is literally trying to open a path starting with <code>~</code>. Oddly enough this doesn't work. :-)</p> <p>Try running the path through <code>os.path.expanduser()</code> first - that should work to expand the <code>~</code> variable to the...
python|pandas|path
6
13,075
66,156,740
How can I merge two data without losing date both of them
<p>all Could you please help me with merging data, I try to merge data1 and data2 by typing this code: &quot;merged3= pd.merge(left = merged2 , right = user, how='outer',on=['user_id']).fillna(0)&quot; . But the problem is month1 in data1 disapper. How can I keep month1 column after merging data1 with data2 . You can s...
<p>Month 1 is part of the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html" rel="nofollow noreferrer">multi-index</a> with <code>user_id</code>, when you merge on only the <code>user_id</code> level of the multi-index you throw away the <code>month</code>.</p> <p>To get the behaviour I thi...
python|pandas
0
13,076
66,261,729
Pytorch Lightning duplicates main script in ddp mode
<p>When I launch my main script on the cluster with ddp mode (2 GPU's), Pytorch Lightning duplicates whatever is executed in the main script, e.g. prints or other logic. I need some extended training logic, which I would like to handle myself. E.g. do something (once!) after <code>Trainer.fit()</code>. But with the dup...
<p>I have since moved on to use the native &quot;ddp&quot; with multiprocessing in PyTorch. As far as I understand, PytorchLightning (PTL) is just running your main script multiple times on multiple GPU's. This is fine if you only want to fit your model in one call of your script. However, a huge drawback in my opinion...
pytorch|multi-gpu|ddp|pytorch-lightning
5
13,077
46,272,881
Find neighbors with cuts efficiently and return index
<p>I have many points in the <code>x,y</code> plane, with length around 10000, each point <code>(x,y)</code> has an intrinsic radius <code>r</code>. This small data set is only one tiny corner of my entire data set. I have an interested point <code>(x1,y1)</code>, I want to find nearby point around <code>(x1,y1)</code>...
<p><strong>Approach #1</strong></p> <p>We could simply index into the first mask with its own mask for selecting the True places masked values from the second stage, like so -</p> <pre><code>idx[idx] = idx1 </code></pre> <p>Thus, <code>idx</code> would have the final valid masked values/ good valued places correspon...
python|numpy|indexing|nearest-neighbor
1
13,078
46,230,592
'Index' object is not callable in python
<p>I am new to python. Can someone explain what happened when I try to get index information after reading the csv file?</p> <pre><code>import pandas as pd df = pd.read_csv('olympics.csv', index_col=0, skiprows=1) for col in df.columns: if col[:2]=='01': df.rename(columns={col:'Gold'+col[4:]}, inplace=Tr...
<p>You should use "df.index", "df.index()" suggests that it is a function. "df.index" simply means that "index" is a subset of the DataFrame. You can call columns the same way (e.g. df['ID'] --> df.ID).</p> <p>Also, it is a good habit to specify the axis in "df.drop". It defaults to 0 (index), so you will get an error...
python|pandas
5
13,079
46,530,996
numpy / tensorflow vectorization of slices
<p>I'm managing a big set of positions at different times, as a sparse matrix: an array of positions (the columns) and an array of times with the same size. E.g.</p> <pre><code>matrix = numpy.random.randint(2, size = 100).astype(float).reshape(10,10) times = numpy.nonzero(matrix)[0]+1 positions = numpy.nonzero(matrix)...
<p>I tried to <em>functionalize</em> the original approach and here's what I got -</p> <pre><code>def slices2arr_org(ar, starts, ends, N): out0 = np.zeros((N),dtype=ar.dtype) for i in np.arange(n_grp): out0[starts[i]:ends[i]] = ar[i:i+1] return out0 </code></pre> <p>Now to vectorize it, we could m...
python|arrays|numpy|vectorization
1
13,080
58,585,668
Problem with ALBERT pretrained model on TF Hub
<p>I've tried to test the ALBERT model on TF Hub. I got the following error when just trying to load ALBERT from TF Hub:</p> <pre><code>python Python 3.6.8 (default, May 16 2019, 05:58:38) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36.0.1)] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&g...
<p>It looks like you answered your own question, but to make this more obvious for others:</p> <p>You need to use tensorflow &gt;= 1.14.0. The necessary op (BatchMatMulV2) was not present in older versions of TF.</p>
python|tensorflow|tensorflow-hub
1
13,081
58,293,218
Pandas Dataframe - for each row, return count of other rows with overlapping dates
<p>I've got a dataframe with projects, start dates, and end dates. For each row I would like to return the number of other projects in process when the project started. How do you nest loops when using <code>df.apply()</code>? I've tried using a for loop but my dataframe is large and it takes way too long. </p> <pre><...
<p>I suggest you take advantage of <a href="https://docs.scipy.org/doc/numpy-1.15.0/user/basics.broadcasting.html" rel="nofollow noreferrer">numpy broadcasting</a>:</p> <pre><code>ends = df.pr_start_date.values &lt; df.pr_end_date.values[:, None] starts = df.pr_start_date.values &gt; df.pr_start_date.values[:, None] d...
python|pandas|dataframe
3
13,082
58,285,940
Generate an array of bit vectors with no repeated columns
<p>I have an array of dimensions <code>[batch_size, input_dim]</code> which needs to be filled only with <code>0</code> or <code>1</code>. I need element in each column to be distinct from the rest of the columns. I have taken a approach like below:</p> <pre class="lang-py prettyprint-override"><code> train_data = np....
<h2>Why yours doesn't work</h2> <p>Yours has an issue with this line:</p> <pre><code> for _ in range(num_of_one): train_data[k][np.random.randint(0, input_dim)] = 1 </code></pre> <p>Because you select random rows to be set to 1, you could have these repeating, and it's not guaranteed that you'll have the ...
python|numpy
1
13,083
69,055,961
Tensorflow tensor cannot be converted to numpy
<p>I want to convert <code>tensorflow.python.framework.ops.Tensor</code> to NumPy.</p> <p>TensorFlow version is <code>2.4.1</code></p> <p>I tried to search some methods, but they did not work.</p> <pre><code>x = tf.reshape(tf.io.decode_raw(x, tf.float64), (3, 4096)) x = x.numpy() </code></pre> <p>Above results in <code...
<p><strong>Sample working code</strong></p> <pre><code>import tensorflow as tf x=[[&quot;1&quot;],[&quot;23&quot;]] x = tf.reshape(tf.io.decode_raw(tf.constant(x), tf.uint8, fixed_length=4), (2,4)) x = x.numpy() x </code></pre> <p><strong>Output</strong></p> <pre><code>array([[49, 0, 0, 0], [50, 51, 0, 0]],...
python|tensorflow
0
13,084
68,898,468
How to sort values in pandas based on a column that has repeating values
<p>I have the following dataframe:</p> <pre><code> name_1 name_2 Temp x1 x2 0 a b 293.35 0.0 1.0 0 a b 293.35 0.5 0.5 0 a b 293.35 1.0 0.0 0 a b 295.35 0.0 1.0 0 a b ...
<p>Simply sort on x1. You can specify a stable sorting algorithm:</p> <pre><code>df = df.sort_values(by='x1', kind='mergesort') </code></pre> <p>grouping and applying a cumcount is going nothing other than keeping the original order of the other parameters, which a stable sorting algorithm is already doing.</p> <p>cf. ...
python|pandas|dataframe|sorting
1
13,085
68,974,917
for my loss function i give the errer: ValueError: None values not supported
<p>I wrote below loss function:</p> <pre><code>def custom_loss(q_k): def loss(y_true,y_pred): loss= y_true * y_true /np.log(y_pred + q_k) return loss </code></pre> <p>and I give the error:</p> <pre><code>Cannot convert a symbolic Tensor (2nd_target:0) to a NumPy array </code></pre> <p>then according to @Dr.sno...
<p>You can not use numpy array in a loss function, since it will be executed in the graph mode.</p> <p>Instead use tensorflow methods like this:</p> <pre><code>def custom_loss(q_k): def loss(y_true,y_pred): return y_true * tf.math.log(y_pred + q_k) #tf.math.log instead of np.log # Return a function return ...
python|tensorflow|keras
3
13,086
61,119,639
Difference between `nditer` and `flat`, type of element
<p>I created subplots and I wanted to modify <code>xlim</code> for each of subplot. I wrote the following code to do that:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt fig, axs = plt.subplots(2, 3, figsize=(20, 10)) for ax in np.nditer(axs, flags=['refs_ok']): ax.set_xlim(left=0.0, right=0.5...
<p>Iterating over an array with <code>nditer</code> gives you views of the original array's cells as 0-dimensional arrays. For non-object arrays, this is almost equivalent to producing scalars, since 0-dimensional arrays usually behave like scalars, but that doesn't work for object arrays.</p> <p>Iterating over an obj...
python|python-3.x|numpy|matplotlib
1
13,087
71,616,185
How to apply a function pairwise on rows in a series?
<p>I want something like this: df.groupby(&quot;A&quot;)[&quot;B&quot;].diff()</p> <p>But instead of diff(), I want be able to compute if the two rows are different or identical, and return 1 if the current row is different from the previous, and 0 if it is identical.</p> <p>Moreover, I really would like to use a custo...
<p>Hi I think it is best if you forgo using the grouby and shift instead:</p> <pre><code>equal_index = (df == df.shift(1))[X].all(axis=1) </code></pre> <p>where X is a list of columns you want to be identic. Then you can create your own grouper by</p> <pre><code>my_grouper = (~equal_index).cumsum() </code></pre> <p>and...
python|pandas|dataframe|group-by|row
1
13,088
71,788,900
How to download a csv file in Python
<p>I am trying to download a csv file from the url</p> <p><a href="https://qubeshub.org/publications/1220/supportingdocs/1#supportingdocs" rel="nofollow noreferrer">https://qubeshub.org/publications/1220/supportingdocs/1#supportingdocs</a> .</p> <p>the file is <code>Elephant Morphometrics and Tusk Size-originaldata-386...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>import requests url = &quot;https://qubeshub.org/publications/1220/serve/1/3861?el=1&amp;download=1&quot; r = requests.get(url) filename = r.headers[&quot;Content-Disposition&quot;].split('&quot;')[1] with open(filename, &quot;wb&quot;) as f_out: print(...
python|pandas|csv
2
13,089
69,797,260
Remove star and empty line using regex
<p>I have dataframe i want remove star and all the empty line in localisation. I have to create two columns &quot;temp&quot; and &quot;word&quot;.</p> <p>&quot;temp&quot; contains all the lines after the first line break and the column &quot;word&quot; represents all the words of this list found in &quot;temp&quot;:</p...
<p>You can use</p> <pre class="lang-py prettyprint-override"><code>import re df['temp'] = df['localisation'].str.replace(r'^.*\n', '', regex=True) words = ['SECTION 11', 'CONE', 'BELLY', 'FIXED PLAN'] df['word'] = df['temp'].str.findall(fr'(?&lt;!\w)(?:{&quot;|&quot;.join([re.escape(w) for w in words])})(?!\w)').str.jo...
python|regex|pandas|dataframe
3
13,090
69,859,275
How to convert dtype from '0' to 'int64'?
<p>I started working with a dataset, which is a collection of murder reports.There is a column &quot;Perpetrator Age&quot; in which there are simple integers. But when I looked at his type, it turned out that he was <code>dtype('O')</code>.</p> <p>In order to work with this column further, I want to change its type to ...
<p>As mentioned in the comments, the first row of your df is apparently an empty space (<code>' '</code>). You can either remove it, replace it with something else, or skip it:</p> <pre class="lang-py prettyprint-override"><code>df['column_1'].iloc[1:].astype('int') </code></pre>
python|pandas
1
13,091
72,411,501
multiple nested groupby in pandas
<p>Here is my pandas dataframe:</p> <pre><code>df = pd.DataFrame({'Date': {0: '2016-10-11', 1: '2016-10-11', 2: '2016-10-11', 3: '2016-10-11', 4: '2016-10-11',5: '2016-10-12',6: '2016-10-12',7: '2016-10-12',8: '2016-10-12',9: '2016-10-12'}, 'Stock': {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H',8: 'I'...
<p><code>groupby</code> runs really fast when the aggregate function is vectorized. If you are worried about performance, try it out first to see if it's the real bottleneck in your program.</p> <p>You can create temporary data frames holding the result of each <code>groupby</code>, then successively <code>merge</code>...
pandas|pandas-groupby
5
13,092
50,462,553
How to change format of timedelta in pandas
<pre><code> import pandas as pd import datetime import numpy as np from datetime import timedelta def diff_func(row): return (row['Timestamp'] - row['previous_end']) dfMockLog = [ (1, ("2017-01-01 09:00:00"), "htt://x.org/page1.html"), (1, ("2017-01-01 09:...
<p>You are close. The way I prefer is to make a new column containing <code>time_diff</code> in seconds via <code>pd.Series.dt.seconds</code>. Then use <code>groupby.transform</code> to extract the <code>cumsum</code> by <code>user</code>:</p> <pre><code>dfMockLog['time_diff_secs'] = dfMockLog['time_diff'].dt.seconds ...
python|pandas|dataframe|series|timedelta
0
13,093
50,591,921
Search by list of indexes in pandas
<p>I'm trying the following code:</p> <pre><code>In [29]: indexes_to_search = [1, 3, 4] In [30]: df = pd.DataFrame([(1, 2, 3), (4, 5, 6), (7, 8, 9)], columns=["id", "val1", "val2"]).set_index("id") In [31]: df Out[31]: val1 val2 id 1 2 3 4 5 6 7 8 9 In [32]: df.loc[index...
<p>Need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.intersection.html" rel="nofollow noreferrer"><code>Index.intersection</code></a>:</p> <pre><code>df1 = df.loc[df.index.intersection(indexes_to_search)] print (df1) val1 val2 1 2 3 4 5 6 </code></pre> <p>Or use <cod...
python|pandas
5
13,094
50,287,085
Translate R to Python pipeline - filter, select and sort
<p>I'm cleaning up a dataset in R, and am trying to find equivalent of my below cleaning process in Python.</p> <pre><code>df = dataframe %&gt;% filter(grepl('abc', Sheet1)) %&gt;% select(product) %&gt;% arrange(nchar(product)) </code></pre> <p>I know for filtering in Pandas I can do something like df[df['va...
<p>Use:</p> <pre><code>df = pd.DataFrame({'Sheet1':['abc f','as abc','ss','abc','abcd'], 'product':['aa','sss','aaa','s','ddddd'], 'val':[7,8,9,4,2]}) print (df) Sheet1 product val 0 abc f aa 7 1 as abc sss 8 2 ss aaa 9 3 abc s 4 4 ...
python|pandas
2
13,095
50,420,359
Python Tensorflow NoneType is not Iterable
<p>Full code is <a href="https://gist.github.com/xmaayy/367259ca33f05fa5d7a12e08c2c1c11e" rel="noreferrer">here</a></p> <p>The error:</p> <pre><code> --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-i...
<p>Looks like your issue is here:</p> <pre><code>_ , loss_val = sess.run(tr_op, feed_dict=feed_dict) </code></pre> <p>You are asking tensorflow to compute the <code>tr_op</code> for you. That is one operation. E.g. one return value from <code>sess.run</code> will be produced. You are trying to extract 2 values from t...
python|tensorflow|deep-learning
16
13,096
50,559,480
Merge dummies value columns to one column (pd.get_dummies reversed)
<p>I have a Pandas DataFrame like this :</p> <pre><code>id Apple Apricot Banana Climentine Orange Pear Pineapple 01 1 1 0 0 0 0 0 02 0 0 1 1 1 1 0 03 0 0 0 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>melt</code></a>, filter <code>1</code> and last join values per groups with <code>,</code>:</p> <pre><code>df = pd.DataFrame({ 'id': ['01','02','03'], 'Apple': [1,0,0], 'Apricot...
python|pandas|numpy
5
13,097
62,524,985
How to map functions in dask
<p>I'm using Dask to manipulate a dataframe (coming from CSV file) and I'm looking for a way to improve this code using something like <code>map</code>, or <code>apply</code> functions since in large files is taking so long (I know having nested <code>for</code> and using <code>iterrows()</code> is the worst think I ca...
<p>My suggestion here is try to work with pandas and then try to translate into dask</p> <h1><code>pandas</code></h1> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np nan = np.nan df = {'name': {0: 'David', 1: 'John', 2: 'Charles', 3: nan}, 'age': {0: nan, 1: 22.0, 2: 30.0, 3: n...
python|pandas|dataframe|dask
1
13,098
62,862,501
What's the difference b/w np.random.randint() and np.random.uniform()?
<p>What's the difference b/w <code>np.random.randint()</code> and <code>np.random.uniform()</code>?</p> <p>I have gone through the numpy documentation but have not gotten a satisfactory understanding of the difference b/w them, except that the default precision of <code>np.random.uniform()</code> is much greater than t...
<p>np.random.randint() always returns integer value even when we decide to pick random numbers from a narrow spectrum -</p> <pre><code>&gt;&gt;&gt; print(np.random.randint(2,size=10)) [0 0 0 0 0 0 1 0 1 0] </code></pre> <p>At other end, np.random.uniform() always return a unique number (floating numbers) for the same r...
python|numpy
0
13,099
71,309,113
CNN model and bert with text
<p>I got error in linear function</p> <pre><code>class MixModel(nn.Module): def __init__(self,pre_trained='bert-base-uncased'): super().__init__() self.bert = AutoModel.from_pretrained('distilbert-base-uncased') self.hidden_size = self.bert.config.hidden_size self.conv = nn....
<pre><code>class MixModel(nn.Module): def __init__(self,pre_trained='bert-base-uncased'): super().__init__() self.bert = AutoModel.from_pretrained('distilbert-base-uncased') self.hidden_size = self.bert.config.hidden_size self.conv = nn.Conv1d(in_channels=768, out_channels=2...
python|pytorch|conv-neural-network|text-classification|bert-language-model
0