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
2,800
67,268,152
Pytorch: create a mask that is larger than the n-th quantile of each 2D tensor in a batch
<p>I have a <code>torch.Tensor</code> of shape <code>(2, 2, 2)</code> (can be bigger), where the values are normalized within range <code>[0, 1]</code>.</p> <p>Now I am given a positive integer <code>K</code>, which tells me that I need to create a mask where for each 2D tensor inside the batch, values are 1 if it is l...
<pre><code>t = torch.tensor([[[1., 3.], [2., 4.]], [[5., 7.], [9., 8.]]]) t_flat = torch.reshape(t, (t.shape[0], -1)) quants = torch.quantile(t_flat, 1/K, dim=1) quants = torch..reshape(quants, (quants.shape[0], 1, 1)) res = torch.where(t &gt; val, 1, 0) </code></pre> <p>and after this res is...
python|pytorch
1
2,801
34,643,500
iterate through all dataframe columns
<p>I want to compare all rows of 2 given dataframes</p> <p>how can i optimize the following code to dynamically iterate through all columns of the given pandas dataframe?</p> <pre class="lang-python prettyprint-override"><code>df1,df2 = pd.read_csv(...) for index2, row2 in df2.iterrows(): for index1, row1 in df1...
<p>IIUC you need to check whether whole row of one dataframe is equal to another one. You could compare for equality two dataframes then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.all.html?highlight=all#pandas.DataFrame.all" rel="nofollow"><code>all</code></a> method for that wi...
python|pandas|dataframe
2
2,802
60,130,278
How to find all text values in dataframe and put them into list?
<p>I have dataframe which contains both numbers and string values. I am struggling to find an elegant way to extract all strings into list in order to further replace them with NAN. Could you please help me?</p> <p>Actually i dont understand what is the best way to iterate through all values of pandas dataframe, The o...
<p>You can iterate through a column like this:</p> <pre><code>import numpy as np df['column'] = df['column'].apply(lambda x: np.nan if isinstance(x, str) else x) </code></pre> <p>Three things are happening here:</p> <ul> <li>.apply() function lets you apply a function to a dataframe or its column</li> <li>lambda let...
python|pandas
1
2,803
59,905,738
Looping over dataframe and selecting rows based on substring in Pandas
<p>I have a dataframe with 5 columns, one of which is 'TABLE_NAME'. That column has values such as:</p> <pre><code>A_value1 B_value1 B_value2 A_value150 </code></pre> <p>I want to print those that start with 'A_' only. </p> <p>I tried this but its returning the following:</p> <pre><code>ValueError: The truth valu...
<p>You can use str.startswith:</p> <pre><code>df.loc[df.TABLE_NAME.str.startswith('A_')] </code></pre> <p>If you want to use your for loop, you can do:</p> <pre><code>value = 'A_' for index, row in df.iterrows(): if row['TABLE_NAME'].startswith(value): print('y') else: print('n') </code></pre...
python|string|pandas
1
2,804
49,847,771
How to iterate over an dataframe object list?
<p>I have a dataset with a lot of <code>int</code>, <code>float</code> and <code>object</code> variables. I've used the code bellow to extract only the name of the <code>object</code> variables into a <code>list</code>.</p> <pre><code>objects = df.dtypes[df.dtypes == "object"].index objects = list(objects) </code></pr...
<p>I finally find an answer. The code bellow do what I was trying to do. It plots two boxplots against variable <code>Y</code>, one at a time.</p> <pre><code>objects = ['A', 'B'] for obj in objects: plt.figure(figsize=(15,8)) sns.boxplot(df[obj], df.Y) </code></pre>
python|pandas|dataframe|matplotlib
0
2,805
50,217,764
In Python, how to sort a dataframe containing accents?
<p>I use sort_values to sort a dataframe. The dataframe contains UTF-8 characters with accents. Here is an example:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame ( [ ['i'],['e'],['a'],['é'] ] ) &gt;&gt;&gt; df.sort_values(by=[0]) 0 2 a 1 e 0 i 3 é </code></pre> <p>As you can see, the "é" with an accent is at t...
<p>This is one way. The simplest solution, as suggested by @JonClements:</p> <pre><code>df = df.iloc[df[0].str.normalize('NFKD').argsort()] </code></pre> <p>An alternative, long-winded solution, normalization code <a href="https://stackoverflow.com/a/37926512/9209546">courtesy of @EdChum</a>:</p> <pre><code>df = pd....
python|string|pandas|sorting|dataframe
3
2,806
63,767,469
Pandas GroupBy and Sum python
<p>Hello everyone Im trying to group data by Date and then sum the second column, but I not getting the information as i need</p> <p>This is my data:</p> <pre><code>|Day |Messages|Codes | |----------|--------|-------| |2020-08-25|647 |34234 | |2020-08-25|6,396 |3425645| |2020-08-25|16,615 |64564 | |2020...
<p>This might get you close to what you need:</p> <p><code>read.groupby(['Day','Messages','ShortCode']).size().reset_index().set_index(['Day','Messages'])</code></p>
python|pandas|dataframe
0
2,807
64,166,439
How to retain the colors of a PNG image when converting back from an array
<p>Whenever I convert a PNG image to a np.array and then convert it back to a PNG I lose all the colors of the image. I would like to be able to retain the colors of the original PNG when I am converting it back from a np.array.</p> <p>Original PNG Image</p> <p><a href="https://i.stack.imgur.com/gsmur.png" rel="nofollo...
<p>Your image is using single channel color using palette. Try the code below. Also you can check more about this subject at <a href="https://stackoverflow.com/questions/52307290/what-is-the-difference-between-images-in-p-and-l-mode-in-pil">What is the difference between images in &#39;P&#39; and &#39;L&#39; mode in PI...
python|numpy|python-imaging-library|png|color-palette
2
2,808
64,002,589
Import numpy from macOS Terminal running python launches but not from python script
<p>My goal is to be able to run NumPy through simple scripts. Being new at this, simple is not so simple. From the Terminal running python, NumPy works just fine. However, I can not import it from a script. The numpy sample runs from python with the following result.</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&...
<p>You write:</p> <blockquote> <p>As stated before my goal is to begin NumPy at the python prompt &gt;&gt;&gt; without using another import statement. This shell script works fine. It calls the python scripts.</p> </blockquote> <p>This is actually not a good goal. You should try to get out of the habit of running pytho...
python|macos|numpy|terminal
0
2,809
46,669,135
Launch a model when the session is close - Tensorflow
<p>I build a neural network with two hidden layer. When I launch the session i save the session by :</p> <pre><code>saver.save(sess, "model.ckpt") </code></pre> <p>If I remain in the same session and I launch this code:</p> <pre><code>restorer=tf.train.Saver() with tf.Session() as sess: restorer.restore(sess,"./...
<p>You can't run the model outside of <code>tf.Session</code>. The quote from <a href="https://www.tensorflow.org/api_docs/python/tf/Session" rel="nofollow noreferrer">the documentation</a>:</p> <blockquote> <p>A Session object encapsulates the environment in which Operation objects are executed, and Tensor objects ...
python-3.x|tensorflow|neural-network|save
1
2,810
46,802,122
Obtaining Indexes for maximum points in a 2D numpy array
<p>I know this seems to be somewhat of a common question, but none of the answers currently seem to help my situation. I have a 2D numpy array which stores a spectrogram of a song. I want to identify the peaks using numpy's where function (I know people have other solutions for peak finding, but that's not what I'm loo...
<p>To answer this question for others who are curious about the answer, it was an issue with how they are indexed vs matplotlib. Kind of like when you study matrices and they list the height and then the length. It is similar here. Therefore the code:</p> <pre><code>peaksx, peaksy = numpy.where(arr2D &gt; (arr2Dcoefva...
python|arrays|numpy|multidimensional-array|spectrogram
0
2,811
38,858,177
Pandas - Sort by group membership numbers
<p>When faced with large numbers of groups, any graph you might make is apt to be useless due to having too many lines and an unreadable legend. In these cases, being able to find the groups that have the most and least information in them is very useful. However, while <code>x.size()</code> tells you the group members...
<p>You can use <code>transform</code> to get the counts and sort on that column:</p> <pre><code>df = pd.DataFrame({'A': list('aabababc'), 'B': np.arange(8)}) df Out: A B 0 a 0 1 a 1 2 b 2 3 a 3 4 b 4 5 a 5 6 b 6 7 c 7 </code></pre> <hr> <pre><code>df['counts'] = df.groupby('A').transform('count'...
python|pandas
3
2,812
63,239,708
Aggregate time series data to make a scatter plot
<p>I want to make time series scatter plot for my time series data, where my data has categorical columns which needs to be aggregated by group to make plotting data first, then make scatter plot either using <code>seaborn</code> or <code>matplotlib</code>. My data is product sales prices time series data, I want to se...
<h2>Updated with <code>threshold</code></h2> <h3>Option 1</h3> <ul> <li>This option was implemented after seeing the results of <strong>Option 1</strong>. <ul> <li>There is a lot of unexplained information in the plots and they do not clearly present the data</li> </ul> </li> <li>To clearly present the data, each plot ...
python|pandas|matplotlib|time-series|seaborn
7
2,813
62,987,940
how to write into excel with the header follow exactly the dictionary keys?
<p>I do have a list of 20000++ dictionaries with 59 keys and values. I need to export the dictionary into excel. Below is my script using pandas to write into excel but the problem is the header did not follow the correct position of the key in dictionary. Below is just some part of the list.</p> <pre><code>new_d=[{'fi...
<p>You can force pandas excel writer to keep the order of the columns the way you want by giving <code>columns=[list of columns]</code> <code>ccf_df.to_excel(writer,sheet_name='CCF', columns=[list of columns])</code></p>
python|excel|pandas|dictionary
1
2,814
63,169,314
Group datafrime by time slots in Pandas python
<p>i'm working with a dataset that comes from the data sent by underground sensors stations, which provide an estimate of the flow of the cars going through them. My data are grouped by hour for each sensor on the same period of time, this is how the df looks like:</p> <p><a href="https://i.stack.imgur.com/YbfsW.png" r...
<p>create the bins and group by them:</p> <pre><code>df = pd.read_csv('readings_by_hour.csv') df['time'] = pd.to_datetime(df['time']) df['time_bins'] = df['time'].dt.floor('6h') df.groupby(['station_id', 'time_bins'])['flow'].mean() </code></pre>
python|pandas|datetime
1
2,815
63,080,812
sum for id'sin python
<p>I have below dataframe called &quot;df&quot; and calculating the last amount sum by unique id called</p> <pre><code>import pandas as pd from dateutil import parser from datetime import datetime, timedelta df= {'Date':['2019-01-11 10:23:45','2019-01-09 10:23:45', '2019-01-11 10:27:45', '2019-01-11 10:25:...
<p><code>pivot_table</code> could be useful here.</p> <pre><code>df.sort_values(by='Date', inplace=True) newdf = pd.pivot_table(df, columns='Fruit id', index='Date', aggfunc=np.sum, values='Amount').rolling('30min', closed='left').sum().sort_index() newdf['Fruit id'] = df['Fruit id'].values df['count_ncc_amt'] = newdf....
python|pandas
1
2,816
63,284,825
LSTM model is giving me 99% R-squared even if my training data set is 5% of the overall set
<p>I'm using a LSTM model to perform time series forecasting. I have a weird issue where my R-squared is basically always 99% even if my training data set is 5% of my total data set! I plot the graph between the predicted values and the test data and it looks almost identical. How is this even possible?</p> <p>My data ...
<p>Mathematically, The <a href="https://en.wikipedia.org/wiki/Coefficient_of_determination" rel="nofollow noreferrer">R-Squared</a>'s purpose is to give you an estimation on the fraction of your model's variance that is explained by your model's independent features.</p> <p>The formula goes as follows: [1 - (SSres / SS...
python|tensorflow|machine-learning|keras|lstm
0
2,817
67,916,079
Tensorflow ImportError: cannot import name 'model_lib_v2' from 'object_detection'
<p>Today I was working on a sign language detector using deep learning by <code>Tensorflow</code></p> <p>And by following the tutorial named <a href="https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/training.html" rel="nofollow noreferrer">Training Custom Object Detector</a> but as soon as I g...
<p>Your error looks like this, <code>ImportError: cannot import name 'model_lib_v2' from 'object_detection' (C:\Python\379\lib\site-packages\object_detection\__init__.py)</code>.</p> <p>Clearly, python is unable to find <strong>model_lib_v2.py</strong> at &quot;C:\Python\379\lib\site-packages\object_detection&quot; sin...
python|python-3.x|deep-learning|tensorflow2.0
3
2,818
31,760,427
Save result of multiplication to existing array
<p>Consider the following code:</p> <pre><code>a = numpy.array([1,2,3,4]) b = numpy.array([5,6,7,8]) # here a new array (b*2) will be created and name 'a' will be assigned to it a = b * 2 </code></pre> <p>So, can numpy write the result of <code>b*2</code> directly to memory already allocated for <code>a</code>, with...
<p>Yes this is possible - you need to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.multiply.html#numpy.multiply" rel="nofollow"><code>np.multiply</code></a> with its <a href="http://docs.scipy.org/doc/numpy/reference/ufuncs.html#optional-keyword-arguments" rel="nofollow"><code>out</code></a> p...
python|arrays|numpy|multiplication
3
2,819
32,053,203
Ewma in pandas but over rolling weekly data.
<p>I'm trying to calculate the ewma in pandas on a "rolling weekly" way. For example lets say today is tuesday. Then today´s ewma would be calculated using only tuesdays data. (This tuesday, the previous tuesday, the one before and so on). Now tomorrow we would have to do the same thing but with wednesdays and so fort...
<p>There's probably multiple ways to do this, but the way I'd do it is with a reduce.</p> <p>Your resampled EWMA calls can be done with this list comprehension to give a list of DataFrames: </p> <pre><code>ewmas = [pd.ewma(df[['PX_LAST']].resample(w), span=10) for w in lista4] </code></pre> <p>and then we want to ma...
python|pandas
1
2,820
31,715,082
How to drop rows which has elements equal to a specific value
<p>I have a file which looks like</p> <pre><code>1618246950 0.000 0.000 0.003 0.000 0.000 0.000 0 0 -1 -1 -1 -1 -1 -1 -1 -1 9 0 1618387251 0.000 0.000 0.000 0.000 0.021 0.012 0 0 -1 -1 -1 -1 -1 -1 -1 -1 0 0 1618436689 0.000 0.000 0.000 0.000 0.000 0.000 ...
<p>How about this:</p> <pre><code>df=df[-df.applymap(lambda x: x==-1).any(axis=1)] </code></pre>
pandas
2
2,821
41,453,892
Python Pandas: Function doesn't work when used with apply()
<p>The following function:</p> <pre><code>def func(x): for k in x['slices']: for j in k: print(x['low'].iloc[j]) </code></pre> <p>applied in the following manner works:</p> <pre><code>func(test) </code></pre> <p>but as follow doesn't:</p> <pre><code>test.apply(func, axis=1) </code></pre> ...
<p>define your function this way</p> <pre><code>def fun(slices): return [df.low.loc[s].tolist() for s in slices] </code></pre> <p>And apply over the slices column</p> <pre><code>df['slices_low'] = df.slices.apply(fun) df </code></pre> <p><a href="https://i.stack.imgur.com/hAGXG.png" rel="nofollow noreferrer"><...
python|pandas
2
2,822
61,264,739
How can I alternate tf.Session.run in TensorFlow2.0?
<p>Hi I've started learning machine learning by TensorFlow. I've learned codes below and realized that these doesn't work anymore.</p> <pre><code>sess = tf.Session() print(sess.run(hello)) print(sess.run([a, b, c])) sess.close </code></pre> <p>It would be grateful someone can help me how to change these codes work....
<p>In Tensorflow 2.0, You can use <code>tf.compat.v1.Session()</code> instead of <code>tf.session()</code></p> <p>Please refer code in TF 1.X in below</p> <pre><code>%tensorflow_version 1.x import tensorflow as tf print(tf.__version__) with tf.Session() as sess: output = tf.constant(""Hello, World"") print(ses...
tensorflow
1
2,823
61,400,852
Find matching rows in a numpy matrix of 3
<p>Given a cube of mxmxm, I need to know the rows, in the 6 faces that the smallest value in their row is greater than a given n.</p>
<p>To obtain the various faces:</p> <pre><code>faces = np.array([ x[ 0, :, :], x[-1, :, :], x[ :, 0, :], x[ :, -1, :], x[ :, :, 0], x[ :, :, -1], ]) </code></pre> <p>Now collapse the last dimension axis:</p> <pre><code># No information on orientation provided by OP so always pick ax...
python-3.x|numpy|cube
-1
2,824
61,208,808
How to use pandas DataFrames with sklearn?
<p>The goal of my project is to predict the accuracy level of some textual descriptions.</p> <p>I made the vectors with FASTTEXT.</p> <p>TSV output:</p> <pre><code>0 1:0.0033524514 2:-0.021896651 3:0.05087798 4:0.0072637126 ... 1 1:0.003118149 2:-0.015105667 3:0.040879637 4:0.000539902 ... </code></pre> <p>Resour...
<p>Like mentioned in the comments below your question your features and your label are persumably strings. However, sklearn requires them to be numeric (sklearn is normally used with numpy arrays). If this is the case you have to convert the elements of your dataframe from strings to numeric values. </p> <p>Looking at...
python|pandas|scikit-learn
1
2,825
68,605,678
How to color bars based on a separate pandas column
<p>I need to plot a barchat and to apply a color according to the &quot;Attribute&quot; column of my dataframe</p> <p><a href="https://i.stack.imgur.com/VBDqr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VBDqr.png" alt="enter image description here" /></a></p> <p>x axis = Shares<br /> y axis = Pri...
<ul> <li>There are two easy ways to plot the bars with separate colors for <code>'Attribute'</code> <ol> <li>Transform the dataframe with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>.pivot</code></a> and then plot with <a href="https://pandas.pydata...
python|pandas|matplotlib|seaborn|bar-chart
1
2,826
68,761,888
Compare and match values from two df and multiple columns
<p>I've got two dataframes with data about popular stores and districts where they are located. Each store is kind of a chain and may have more than one district location id (for example &quot;Store1&quot; has several stores in different places).</p> <p>First df has info about top-5 most popular stores and district ids...
<p>You can <code>stack</code> first dataframe, then convert it to float type, <code>map</code> the column from second dataframe, then <code>unstack</code> and finally <code>add_prefix</code>:</p> <pre class="lang-py prettyprint-override"><code>df1.stack().astype(float).map(df2['district_name']).unstack().add_prefix('di...
python|pandas|dataframe
1
2,827
68,781,636
Finding a vector that is orthogonal to n columns of a matrix
<p>Given a matrix <code>B</code> with shape <code>(M, N)</code>, where <code>M &gt; N</code>. How to find a vector <code>v</code> (with shape of <code>M</code>) that is perpendicular to all columns in <code>B</code>.</p> <p>I tried using Numpy <code>numpy.linalg.lstsq</code> method to solve : <code>Bx = 0</code>. <code...
<p>You can use sympy library, like</p> <pre><code>from sympy import Matrix B = [[2, 3, 5], [-4, 2, 3], [0, 0, 0]] V = A.nullspace()[0] </code></pre> <p>or to find whole nullspace</p> <pre><code>N = A.nullspace() </code></pre>
python-3.x|numpy|linear-algebra
0
2,828
65,509,486
Return boolean from cv2.inRange() if color is present in mask
<p>I am making a mask using cv2.inRange(), which accepts an image, a lower bound, and an upper bound. The mask is working, but I want to return something like True/False or print('color present') if the color between the ranges is present. Here is some sample code:</p> <pre><code> from cv2 import cv2 import nump...
<p>Since you picked the color you can count Non Zero pixels in the mask result. Or use the relative area of this pixels.</p> <p>Here is a full code and example.</p> <p>Source image from <a href="https://commons.wikimedia.org/wiki/File:RGB_color_model.svg" rel="nofollow noreferrer">wikipedia</a>. I get 500px PNG image f...
python|numpy|opencv|computer-vision
1
2,829
65,728,814
return missing rows by searching by ID in two different dataframes
<p>I have the following two dataframes.</p> <p>current_df:</p> <pre><code>speacial_id name count date 123 al 4 01-01-2020 456 james 4 01-01-2021 789 joe 5 01-02-2021 111 will 2 01-09-2020 222 hal 1 02-10-2009 </code></pre> <p>previous...
<p>Im pretty sure <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>pandas.DataFrame.merge</code></a> is what you need:</p> <pre><code>current_df.merge(previous_df, how = &quot;outer&quot;) </code></pre>
python|python-3.x|pandas|dataframe|series
0
2,830
65,647,979
Keras, Sequential Neural Network Model
<p>Here is the code for the Keras Model, which gives typeError</p> <pre><code> model=keras.Sequential() model.add(Dense(128, input_shape=(len(train_x[0]),), activation='relu')) model.add(Dropout(0,5)) model.add(Dense(64, activation='relu')) model.add(Dropout(0,5)) model.add(Dense(len(train_y[...
<p>@Andrey is correct. There are other minor things, but thats the reason for the error.</p> <p>Here is the fixed code -</p> <pre><code>from tensorflow import keras from tensorflow.keras.layers import Dense, Dropout from tensorflow.keras.optimizers import SGD import numpy as np train_x = np.random.random((100,8)) tra...
tensorflow|keras|typeerror|sequential
0
2,831
20,901,968
numpy.rint not working as expected
<p>I am trying to find the cause of this result:</p> <pre><code>import numpy result1 = numpy.rint(1.5) result2 = numpy.rint(6.5) print result </code></pre> <p>The output:</p> <pre><code>result1-&gt; 2 result2-&gt; 6 </code></pre> <p>This is odd: <em>result1</em> is correct but I <em>result2</em> is not (It has to b...
<p>From <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.around.html#numpy.around" rel="nofollow">numpy's documentation on <code>numpy.around</code>, equivalent to <code>numpy.round</code></a>, which supposedly also is relevant for <code>numpy.rint</code>:</p> <blockquote> <p>For values exactly hal...
python|math|numpy|scipy
7
2,832
63,515,549
What is df.values[:,1:]?
<pre><code>from sklearn.preprocessing import StandardScaler X = df.values[:,1:] X = np.nan_to_num(X) Clus_dataSet = StandardScaler().fit_transform(X) Clus_dataSet </code></pre> <p><strong>Does anyone understand what is the meaning of this context?</strong></p> <p><a href="https://i.stack.imgur.com/ymqFR.png" rel="nofo...
<ul> <li><p><code>df</code> is a DataFrame with several columns and apparently the target values are on the first column.</p> </li> <li><p><code>df.values</code> returns a numpy array with the underlying data of the DataFrame, without any index or columns names.</p> </li> <li><p><code>[:, 1:]</code> is a slice of that ...
python|dataframe|sklearn-pandas
4
2,833
63,342,230
read csv without row enumeration column and sorting with custom key
<p>I have a TSV file which I want to read, sort by a specific column and write it back.<br /> Two problems I ran into are:</p> <ul> <li>providing a custom key results an error (which I will show the backtrace at the end of the post)</li> <li>without providing a custom key, the sorting is done. but when I write the data...
<p>according to docs key func should get and give a Series (BTW, pd.read_csv does not need with open), so try this:</p> <pre><code>import re import pandas as pd def natural_sort_key(S, _nsre=re.compile('([0-9]+)')): return pd.Series([[int(text) if text.isdigit() else text.lower() for text in _nsre.split(s)] for s ...
python|pandas|csv
1
2,834
24,581,931
How can I convert a vector containing entries [[[int int]] ...] into a vector containing entries [[int int] ...] in python/numpy?
<p>I have data in a numpy vector that looks like this:</p> <pre><code> [[[1119 15]] [[1125 27]] [[1129 43]] [[1131 62]] [[1131 87]] [[1141 234]] ...] </code></pre> <p>These are supposed to be a set of points that I can use to represent a curve, but instead each point [int, int] seems to be enca...
<p>Look at the shape of this array. It probably is <code>(n, 1, 2)</code>. </p> <p><code>reshape</code> it to <code>(n,2)</code>. <code>x.reshape(-1,2)</code> is a handy shortcut, saving you the work of determining <code>n</code>. <code>squeeze</code> also gits rid of the singular dimension.</p>
python|opencv|numpy
3
2,835
24,743,753
Test if an array is broadcastable to a shape?
<p>What is the best way to test whether an array can be broadcast to a given shape?</p> <p>The "pythonic" approach of <code>try</code>ing doesn't work for my case, because the intent is to have lazy evaluation of the operation.</p> <p>I'm asking how to implement <code>is_broadcastable</code> below:</p> <pre><code>&g...
<p>I really think you guys are over thinking this, why not just keep it simple?</p> <pre><code>def is_broadcastable(shp1, shp2): for a, b in zip(shp1[::-1], shp2[::-1]): if a == 1 or b == 1 or a == b: pass else: return False return True </code></pre>
python|arrays|numpy|multidimensional-array
9
2,836
24,488,927
Variable amount of dimensions in slice
<p>I have a multidimensional array called <code>resultsten</code>, with the following shape </p> <pre><code>print np.shape(resultsten) (3, 3, 6, 10, 1, 9) </code></pre> <p>In some occasions, I use a part of this array in a program called <code>cleanup</code>, which then further tears this array apart into <code>x</co...
<p>I would use a list of slice objects:</p> <pre><code>import numpy as np A = np.arange(2*3*4*5).reshape(2,3,4,5) #[:] &lt;-&gt; [slice(None,None, None)] sliceList = [slice(None, None, None)]*(len(A.shape)-1) a,b,c,d,e = [A[sliceList+[i]] for i in range(A.shape[-1])] </code></pre> <p>Output:</p> <pre><code>&gt;&gt...
python|arrays|numpy
0
2,837
30,004,737
Create a "wrapped" ndarray from a given array
<p>I'm trying to create a 2D array from an array by using a rolled given array as the rows of the 2D array of a specified row dimension. For example:</p> <pre><code>r = np.array([1,2,3,4]) </code></pre> <p>want a matrix of 3 rows (using r) as</p> <pre><code>[[2,3,4,1], [1,2,3,4], [4,1,2,3]] </code></pre> <p>I thi...
<p>If using <a href="http://docs.scipy.org/doc/scipy/reference/" rel="nofollow">scipy</a> is an option, you can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.circulant.html" rel="nofollow"><code>scipy.linalg.circulant</code></a>. You will still have to tweak the argument to <code>circul...
python|arrays|numpy
2
2,838
53,788,828
How to predict a label in MultiClass classification model in pytorch?
<p>I am currently working on my mini-project, where I predict movie genres based on their posters. So in the dataset that I have, each movie can have from 1 to 3 genres, therefore each instance can belong to multiple classes. I have total of 15 classes(15 genres). So now I am facing with the problem of how to do predi...
<ol> <li>You're right, you're looking to perform binary classification (is poster X a drama movie or not? Is it an action movie or not?) for each poster-genre pair. <code>BinaryCrossEntropy(WithLogits)</code> is the way to go.</li> <li>Regarding the best metric to evaluate your resulting algorithm, it's up to you, what...
conv-neural-network|pytorch|multilabel-classification|multiclass-classification
1
2,839
53,723,217
Is there a version of TensorFlow not compiled for AVX instructions?
<p>I'm trying to get TensorFlow up on my Chromebook, not the best place, I know, but I just want to get a feel for it. I haven't done much work in the Python dev environment, or in any dev environment for that matter, so bear with me. After figuring out pip, I installed TensorFlow and tried to import it, receiving this...
<p>A best practices approach suggested by <a href="https://stackoverflow.com/users/224132/peter-cordes">peter-cordes</a> is to see what gcc is going to make of your 'what capabilities your cpu has' by issuing the following:</p> <pre><code>gcc -O3 -fverbose-asm -march=native -xc /dev/null -S -o- | less </code></pre> <...
python|tensorflow|avx
5
2,840
15,806,414
Storing multidimensional arrays in pandas DataFrame columns
<p>I'm hoping to use pandas as the main Trace (series of points in parameter space from MCMC) object. </p> <p>I have a list of dicts of string->array which I would like to store in pandas. The keys in the dicts are always the same, and for each key the shape of the numpy array is always the same, but the shape may be ...
<p>The relatively-new library <em>xray</em>[1] has <code>Dataset</code> and <code>DataArray</code> structures that do exactly what you ask.</p> <p>Here it is my take on your problem, written as an <em>IPython</em> session:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import xray &gt;&gt;&gt; ## Prepar...
python|pandas
12
2,841
72,047,477
Neural network to predict air flow from coordinate and fan speed
<p>I'm trying to get a neural network to predict air velocity in a container. The input to the neural network is a coordinate (x, y) and the fan speed (in percentage) and from which is should approximate the velocities (u, v) at that point. The grid looks like <a href="https://i.stack.imgur.com/B4qpQ.png" rel="nofollow...
<p>On thing that might help in general is to set up your CFD model grid so that you have a much higher grid density in the areas where you have meaningful results, and a sparser grid where you expect the results to be close to zero. Having most of your data (all those 0s) provide no useful information to the ML model w...
python|tensorflow|neural-network
0
2,842
71,865,761
Why the rank function is not working when I set axis=1?
<p>I have this code:</p> <pre><code>y=pd.DataFrame({'num':[10,12,13,11,14]}) out = (y.join(y['num'].quantile([0.25,0.5,0.75,1]) .set_axis([f'{i}Q' for i in range(1,5)], axis=0) .to_frame().T .pipe(lambda x: x.loc[x.index.repeat(len(y))]) .reset_index(drop=True)) .assign(...
<p>Building on what you already have here:</p> <pre><code>y = y.join(y['num'].quantile([0.25,0.5,0.75,1]) .set_axis([f'{i}Q' for i in range(1,5)], axis=0) .to_frame().T .pipe(lambda x: x.loc[x.index.repeat(len(y))]) .reset_index(drop=True)) </code></pre> <p>we could add the <cod...
python|python-3.x|pandas|dataframe|jupyter-notebook
1
2,843
72,059,571
how can I create a single box plot?
<p>dataset: <a href="https://github.com/rashida048/Datasets/blob/master/StudentsPerformance.csv" rel="nofollow noreferrer">https://github.com/rashida048/Datasets/blob/master/StudentsPerformance.csv</a></p> <pre><code>from bokeh.models import Range1d #used to set x and y limits #p.y_range=Range1d(120, 230) def box_plot...
<p>I am not sute if this it is the best to implement this both in one function, but if this is your goal, one solution can be, to add a few <code>if-else</code> conditions.</p> <p>Here is a description of the changes:</p> <p>First give <code>label</code> a default.</p> <pre><code># old # def box_plot(df, vals, label, y...
python|pandas|bokeh|boxplot
1
2,844
19,096,047
Can not install pandas on windows 64 bit
<p>Trying to install pandas on a new windows 64 system. I did so using:</p> <pre><code>pip install pandas </code></pre> <p>the installtion aborts with error when trying to install pytz (from pandas):</p> <blockquote> <p>Could not find a version that satisfies the requirement pytz (from pandas)</p> </blockquote> <...
<p>If you're running CPython you can try to install it using the windows binaries available here: <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pandas" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#pandas</a></p> <p>You can find several binaries, for different Python version and x64/win32. It also ha...
python|windows|pandas|pip
0
2,845
22,233,094
Create a Pandas DataFrame from series without duplicating their names?
<p>Is it possible to create a DataFrame from a list of series without duplicating their names?</p> <p>Ex, creating the same DataFrame as:</p> <pre><code>&gt;&gt;&gt; pd.DataFrame({ "foo": data["foo"], "bar": other_data["bar"] }) </code></pre> <p>But without without needing to explicitly name the columns?</p>
<p>Try <code>pandas.concat</code> which takes a list of items to combine as its argument:</p> <pre><code>df1 = pd.DataFrame(np.random.randn(100, 4), columns=list('abcd')) df2 = pd.DataFrame(np.random.randn(100, 3), columns=list('xyz')) df3 = pd.concat([df1['a'], df2['y']], axis=1) </code></pre> <p>Note that you need...
python|pandas
3
2,846
55,230,516
tensorflow more metrics with custom estimator
<p>I created custom estimator that used <code>binary_classification_head()</code> under the hood. All works good but the problem is with visible metrics. I'm using logging with level <code>tf.logging.set_verbosity(tf.logging.INFO)</code> and tensorboard but I only see loss value. I added this code but it helps nothing....
<p>You need to place relevant metrics function inside your <code>model_fn</code>.</p> <p>For example:</p> <pre><code>tf.summary.image('input_image', input_image, max_outputs) for v in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES): tf.summary.histogram(v.name, v) </code></pre> <p>Metrics that include <...
tensorflow|metrics|tensorboard|tensorflow-estimator
0
2,847
55,419,362
ModuleNotFoundError: No module named 'mport pandas as pd\r'
<blockquote> <p>ModuleNotFoundError: No module named 'mport pandas as pd\r'</p> </blockquote> <p>but not getting any line in the source code 'mport pandas as pd/r'</p> <p>This is code part nothing here like mport not even in the other file that is imported in the code.</p> <pre><code>{ import cv2 import numpy as ...
<blockquote> <pre><code> File "recom.py", line 11, in &lt;module&gt; data = pd.read_pickle('pickles/dataclean.py') //dataclean.py {import pandas as pd </code></pre> </blockquote> <p>You are trying to load a Python file as a pickle. Python and pickle are two completely different formats, so this is never gonna w...
python|pandas|machine-learning
1
2,848
9,924,135
fast Cartesian to Polar to Cartesian in Python
<p>I want to transform in Python 2d arrays/images to polar, process then, and subsequently transform them back to cartesian. The following is the result from ImajeJ <a href="http://rsbweb.nih.gov/ij/plugins/polar-transformer.html" rel="noreferrer">Polar Transformer</a> plugin (used on the concentric circles of the samp...
<p>Latest versions of opencv supports a function cv2.linearPolar. This may be another solution that does not involve the use of opencv:</p> <pre><code>def polar2cart(r, theta, center): x = r * np.cos(theta) + center[0] y = r * np.sin(theta) + center[1] return x, y def img2polar(img, center, final_radiu...
python|image-processing|opencv|numpy
5
2,849
56,821,137
How to format an If Statements with multiple conditionals inside a function
<p>I'm working on creating a function that will evaluate two conditions from a dataframe and pass a series of prearranged return values given the inputs back to the dataframe should it encounter a NaN. The first condition I'd like to have is a check to see if the value of one column is a NaN (obviously) and then check ...
<p>The solution to your problem can be addressed as mentioned below if you really wanted to go with the custom function and apply.</p> <pre><code>import pandas as pd import numpy as np import math frame = {'key' : [1,2,3,4,5], 'height' : [70, 68, 74, 67, 72], 'age' : [29,45,'N/A',51,34]} frame = pd.DataFrame...
pandas|if-statement|conditional-statements
0
2,850
56,605,509
Pandas substring using another column as the index
<p>I'm trying to use one column containing the start index to subselect a string column.</p> <pre><code>df = pd.DataFrame({'string': ['abcdef', 'bcdefg'], 'start_index': [3, 5]}) expected = pd.Series(['def', 'g']) </code></pre> <p>I know that you can substring with the following</p> <pre><code>df['string'].str[3:] <...
<p>Using for loop with <code>zip</code> of two columns , why we are using for loop here, you can check the <a href="https://stackoverflow.com/questions/54028199/for-loops-with-pandas-when-should-i-care">link</a> </p> <pre><code>[x[y:] for x , y in zip(df.string,df.start_index) ] Out[328]: ['def', 'g'] </code></pre>
python|string|pandas|substring
1
2,851
56,739,059
PySpark - map with lambda function
<p>I'm facing an issue when mixing python map and lambda functions on a Spark environment.</p> <p>Given df1, my source dataframe:</p> <pre><code>Animals | Food | Home ---------------------------------- Monkey | Banana | Jungle Dog | Meat | Garden Cat | Fish | House Elephant ...
<p>Here is one possible solution, in which the <code>Content</code> column will be an array of <code>StructType</code> with two named fields: <code>Content</code> and <code>count</code>.</p> <pre class="lang-python prettyprint-override"><code>from pyspark.sql.functions import col, collect_list, desc, lit, struct from ...
python|pandas|apache-spark|lambda|pyspark
3
2,852
56,533,560
pandas dataframe with list elements: split, pad
<p>I have a pandas dataframe (NROWS x 1) where each row is a list , such as</p> <pre><code> y 0 [[aa, bb], 0000001] 1 [[uz, mk], 0000011] </code></pre> <p>I want to flatten the list and split into (in this case three) columns like so:</p> <pre><code> 1 2 3 0 aa bb 0000001 1 uz mk 0000011 </code><...
<h3>Setup</h3> <pre><code>df = pd.DataFrame(dict(y=[ [['aa', 'bb'], '0000001'], [['uz', 'mk'], '0000011'], [['mk'], '0000111'] ])) df y 0 [[aa, bb], 0000001] 1 [[uz, mk], 0000011] 2 [[mk], 0000111] </code></pre> <hr> <h3><code>flatten</code></h3> <p>From <a href="https://st...
python|pandas
4
2,853
26,363,156
Can I classify elements of a df.column and create a column with the output without iteration (Python-Pandas-Np)?
<p>Given this dataframe,</p> <pre><code>A = pd.DataFrame([[1, 5, 2], [2, 4, 4], [3, 3, 1], [4, 2, 2], [5, 1, 4]], columns=['A', 'B', 'C'], index=[1, 2, 3, 4, 5]) </code></pre> <p>I would like to classify the elements of column 'A' according to their size, and create a new column with the output like this...
<p>You can use <code>loc</code> as a boolean mask to assign just to the rows that meet the criteria, even for such a small df it is faster, for a larger df it will be significantly faster:</p> <pre><code>In [60]: %%timeit A['Size'] = "" for index, row in A.iterrows(): if row['A'] &gt;= 4: A.loc[index, 'S...
python|numpy|pandas|iteration
1
2,854
67,083,987
Lemmatize df column
<p>I am trying to lemmatize content in a df but the function I wrote isn't working. Prior to trying to lemmatize the data in the column looked like this.</p> <p><a href="https://i.stack.imgur.com/hCfCP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hCfCP.png" alt="enter image description here" /></a...
<p>You are lemmatizing each char instead of word. Your function should look like this instead:</p> <pre><code>def lemmatize_text(text): lemmatizer = WordNetLemmatizer() return ' '.join([lemmatizer.lemmatize(w) for w in text.split(' ')]) </code></pre>
python-3.x|pandas|nltk|stemming|lemmatization
1
2,855
67,117,157
Is there a way to made the name of a dataframe a variable that is defined by the user?
<p>The user would enter in the date. I would then like the name of the dataframe to be table_date. I get the following error when I try running the code. SyntaxError: cannot assign to f-string expression</p> <pre><code>date = &quot;199101&quot; data = {'Start Date': ['1', '2', '3'], 'End Date': ['2', '3','33'...
<p>To answer your question:</p> <pre><code>&gt;&gt;&gt; globals()[&quot;table_&quot;f&quot;{date}&quot;] = pd.DataFrame(...) </code></pre> <p>create the variable <code>table_199101</code> in global namespace but I must advise you this is really not a good practice!</p>
pandas|string|dataframe|variables
0
2,856
66,886,064
How to use Raise a value error when calculating derivatives using numpy
<p>``I need to Write a function which calculates the following math equation and round your answer to 2 decimal places: z = π*e<strong>x</strong>2/4y.</p> <p>There are the following contstraints: The input variables x and y are single values (that is, not a list/array). If a division by zero occurs, raise a ValueError....
<p>First thing, I believe that the division by 0, will only happen if y = 0, as b = 4*y, and b can be only 0 if y = 0, thus, you should change the if statement for b == 0.</p> <p>Anoter thing, that if statement should be before calculating the z value, because you want to raise the Error before any computations has bee...
python|numpy|jupyter
0
2,857
67,138,037
"TextInputSequence must be str” error on Hugging Face Transformers
<p>I’m very new to HuggingFace, I’ve come around this error “<strong>TextInputSequence must be str</strong>” on a notebook which is helping me a lot to do some practice on various hugging face models. <strong>The boilerplate code on the notebook is throwing this error (I guess) due to some changes in huggingface’s API<...
<p>This is an issue with data , the data consists of None type or other data type except string</p>
deep-learning|nlp|pytorch|huggingface-transformers|huggingface-tokenizers
1
2,858
67,110,549
pybind11 - Identify and remove memory leak in C++ wrapper
<p>I have a simple C++ function that I've attempted to wrap with <code>pybind11</code> (the <code>ehvi3d_sliceupdate</code> function from the <a href="https://moda.liacs.nl/index.php?page=code" rel="nofollow noreferrer">KMAC library</a>). It's deep in a loop and gets called a few hundred thousand to a million times in ...
<p>It turns out removing the use of <code>new</code> where possible (and adding a <code>delete</code> where it wasn't) plus replacing all the raw pointers with <code>make_shared</code> and <code>shared_ptr</code> in the base library and the wrapper actually fixed the issue. It seems using these over raw pointers will a...
python|c++|numpy|pybind11
2
2,859
67,107,199
Is there a function can choose data from a specified csv file if there are conflicts while combining two csv files?
<p>I have two csv files, and I want to combine these two csv files into one csv file. Assume that the two csv files are A.csv and B.csv, I have already known that there are some conflicts in them. For example, there are two columns, ID and name, in A.csv ID &quot;12345&quot; has name &quot;Jack&quot;, in B.csv ID &quot...
<p>If you want to keep one DataFrame value over the other, then <a href="https://pandas.pydata.org/docs/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concatenate</code></a> them and keep the first duplicate in the output. This means the preferred values should be in the first argument to the sequenc...
python|pandas|csv
0
2,860
66,928,773
How to find the relative time between two datetime columns?
<p>I have two columns of format:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">A</th> <th style="text-align: center;">B</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">31-12-2010:10.06</td> <td style="text-align: center;">05-01-2011:15.12</td> ...
<p>You are getting the error because you are trying to operate a negative sign(subtraction) on two objects of <code>str</code> data type. You need to convert them first to datetime object then only you can do mathematical operations.</p> <p>You can try this as well, you can run along with my example given:</p> <pre><co...
python|python-3.x|pandas|datetime
1
2,861
47,387,555
Numpy equivalent of Tensorflow's embedding_lookup function
<p>What would be a NumPy equivalent code to Tensorflow's <code>embedding_lookup</code> function?</p> <p>In particular, what would be the NumPy equivalent of the last line of the following code block?</p> <pre><code>words = tf.placeholder(tf.int64, name='words') ... embedding = tf.nn.embedding_lookup(embedding_params,...
<p><img src="https://www.tensorflow.org/images/Gather.png" alt="tf.gather"></p> <p><a href="https://www.tensorflow.org/versions/master/api_docs/python/tf/nn/embedding_lookup" rel="nofollow noreferrer">tf.nn.embedding_lookup</a> works basically like <a href="https://www.tensorflow.org/api_docs/python/tf/gather" rel="no...
python|numpy|tensorflow
0
2,862
47,272,763
Effective scraping from web into (pandas) DataFrame that preserves the intended format
<p>Goal: Scraping a page and convert it to DataFrame preserving the intended format (python 3).</p> <p>The data seems to be in csv format and is located here: '<a href="https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data" rel="nofollow noreferrer">https://archive.ics.uci.edu/ml/machine-lea...
<pre><code>In [33]: url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data' In [34]: df = pd.read_fwf(url, header=None) In [35]: df Out[35]: 0 1 2 3 4 5 6 7 8 0 18.0 8 307.0 130.0 3504.0 12.0 70 1 "chevrolet chevell...
python-3.x|pandas|web-scraping|beautifulsoup
1
2,863
47,439,234
Merge dataframes without duplicating rows in python pandas
<p>I'd like to combine two dataframes using their similar column 'A':</p> <pre><code>&gt;&gt;&gt; df1 A B 0 I 1 1 I 2 2 II 3 &gt;&gt;&gt; df2 A C 0 I 4 1 II 5 2 III 6 </code></pre> <p>To do so I tried using:</p> <blockquote> <p>merged = pd.merge(df1, df2, on='A', how='outer')</p> <...
<p>Let us create a new variable g, by <code>cumcount</code></p> <pre><code>df1['g']=df1.groupby('A').cumcount() df2['g']=df2.groupby('A').cumcount() df1.merge(df2,how='outer').drop('g',1) Out[62]: A B C 0 I 1.0 4.0 1 I 2.0 NaN 2 II 3.0 5.0 3 III NaN 6.0 </code></pre>
python|pandas|dataframe|merge
8
2,864
47,458,521
Divide matrix into square 2x2 submatrices - maxpooling fprop
<p>I'm trying to implement fprop for MaxPooling layer in Conv Networks with no overlapping and pooling regions 2x2. To do so, I need to split my input matrix into matrices of size 2x2 so that I can extract the maximum. I am then creating a mask which I can use later on in <code>bprop</code>. To carry out the splitting ...
<p>This is implemented as <a href="http://scikit-image.org/docs/dev/api/skimage.util.html#skimage.util.view_as_blocks" rel="nofollow noreferrer"><code>view_as_blocks</code></a> in <code>skimage.util</code>:</p> <pre><code>blocks = skimage.util.view_as_blocks(a,(2,2)) maxs = blocks.max((2,3)) </code></pre>
python|numpy|matrix|machine-learning|deep-learning
2
2,865
68,263,681
How do I remove unknown, extra, data values from large file?
<p>I am working on an Python, TensorFlow, image classification model, and in my training images, I have 12,611 images, but in my training labels, I have 12,613. (each image has a number as the title, and this number corresponds to the same number in a CSV file with the accompanying information for that image).</p> <p>F...
<p>Well its very straightforward, you can try something like this (As I dont kno exactly how and where you have saved your images, you might have to update the code to meet your use case) :</p> <pre class="lang-py prettyprint-override"><code>dir_path = r'/path/to/folder/of/images' csv_path = r'/path/to/csv/file' images...
python|image|csv|tensorflow|image-classification
0
2,866
68,276,507
Find a subset of columns based on another dataframe?
<p>I'm collecting heart rate data across time for multiple subjects. Different events occur during the course of the data collection, so the start of each event is recorded elsewhere. Each event would have started at at a slightly different time for each subject. I would like to bridge the information between the two d...
<p>I was able to put together a function that I think works for this, but assumes that columns don't change orders or more get added. If there would be changes to the df shape, this would need to be updated for that.</p> <p>First, I merged together your <code>example_g_table</code> and <code>example_s_table</code> to g...
python|pandas
1
2,867
68,231,586
numpy roots() returns false roots
<p>I'm trying to use numpy to find the roots of some polynomials, but I am getting some erroneous results:</p> <pre><code>&gt;&gt; poly = np.polynomial.Polynomial([4.383930e+00, 2.277144e+14, -7.008406e+25, -4.258004e+16]) &gt;&gt; roots = poly.roots() &gt;&gt; roots array([-1.64593692e+09, -1.91391398e-14, 3.26830022...
<p>The root appears real:</p> <pre><code>x = np.linspace(-2e9, 1000, 10000) plt.plot(x, poly(x)) </code></pre> <p><a href="https://i.stack.imgur.com/6K2ss.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6K2ss.png" alt="enter image description here" /></a></p> <p>The problem is that the scale of the d...
python|numpy|optimization|linear-algebra
2
2,868
59,226,174
PANDAS - converting a column with lists as values to dummy variables
<p>I'm working with a dataset of airbnb listings. one of the columns is called amenisities, and contains all of the amenisities that listing has to offer. several examples:</p> <pre><code>[Internet, Wifi, Paid parking off premises] [Internet, Wifi, Kitchen] [Wifi, Smoking allowed, Heating] </code></pre> <p>I would ...
<p>I believe you need <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MultiLabelBinarizer.html" rel="nofollow noreferrer"><code>MultiLabelBinarizer</code></a> what working nice if large <code>DataFrame</code>:</p> <pre><code>print (df) amenisities 0 [...
python|pandas|data-processing
2
2,869
59,361,779
Keras model returning AttributeError: 'str' object has no attribute 'ndim'
<p>I am trying to build a simple Keras model but am getting an AttributeError for some unkown reason. All of the datatypes I am feeding to the model are float64. Code is as follows:</p> <p>Defining features and target:</p> <p><code>X = rated_df[["content_found", "domain_found","title_found", "url_found", "CPC","Comp...
<p>The problem is that you are defining <code>y</code> to be a string.</p> <p>You likely want</p> <pre><code>y = df["Position"] </code></pre>
python|pandas|keras
2
2,870
59,163,503
How to efficiently restrict tensorflow model output?
<p>I have a model, e.g. </p> <pre><code>model = keras.Sequential([ keras.layers.Reshape(target_shape=(10,10,1),input_shape=(100,)), keras.layers.Convolution2DTranspose(1, 3, activation='relu') ]) </code></pre> <p>After it's trained, I would only like to do compute a subset of the outputs, e.g. </p> <pre><cod...
<p>You can do the following,</p> <p>This is your first model. Note that I removed the <code>Reshape</code> layer and directly specified the <code>input_shape</code> for the <code>Convolution2DTranspose</code> layer.</p> <pre><code>model = models.Sequential([ layers.Convolution2DTranspose(1, 3, activation='rel...
tensorflow|keras|sparse-matrix
0
2,871
14,008,307
Use Boost-Python to calculate derivative of function defined in python
<p>I want to write a Boost-Python program to take a symbolic python function from user and evaluate its derivative in my program.</p> <p>For example the User provide a python file (Function.py) which defines a function like F = sin(x)*cos(x).</p> <p>Then I want to have access to F'(x) (derivative of F(x)) using symbo...
<p>Here is some code that should help you get started.</p> <p>main.cpp:</p> <pre><code>#include &lt;boost/python.hpp&gt; #include &lt;iostream&gt; using namespace boost::python; int main(void) { Py_Initialize(); object main_module = import("__main__"); object main_namespace = main_module.attr("__dict__...
c++|python|numpy|boost-python|sympy
4
2,872
44,931,689
How to disable printing reports after each epoch in Keras?
<p>After each epoch I have printout like below:</p> <pre><code>Train on 102 samples, validate on 26 samples Epoch 1/1 Epoch 00000: val_acc did not improve 102/102 [==============================] - 3s - loss: 0.4934 - acc: 0.8997 - val_loss: 0.4984 - val_acc: 0.9231 </code></pre> <p>I am not using built-in epochs, so...
<p>Set <code>verbose=0</code> to the fit method of your model.</p>
python|tensorflow|keras
53
2,873
57,020,855
How to make a pandas column out of filenames?
<p>I have N images. I want to create pandas dataframe, and put all the filenames of images in these colums.How to do it? I need a column with header "filename". a.jpg b.jpg</p>
<p>Make an array, where you append filenames.</p> <pre><code>array = [] </code></pre> <p>Then save these filenames into pandas.DataFrame as:</p> <pre><code>df = pd.DataFrame(array, index=False, columns=["filenames"]) </code></pre>
python|pandas|glob
0
2,874
45,889,276
Does SavedModelBundle loader support GCS path as export directory
<p>Currently I am using a saved_model file stored on my local disk to read an inference graph and use it in servers. Unfortunately giving a GCS path doesn't work for SavedModelBundle.load api.</p> <p>Tried providing GCS path for the file but did not work.</p> <p>Is this even supported, if not how can i achieve this u...
<p>A <a href="https://github.com/tensorflow/serving/commit/f8cc9fd0d36ab6830340875d26aa7870369afe9e#diff-bf0c841686ee859a4e04283ff50ea0ac" rel="nofollow noreferrer">recent commit</a> inadvertently broke the ability to load files from GCS. This has been <a href="https://github.com/tensorflow/serving/commit/c6ace3fed3a0e...
machine-learning|tensorflow|google-cloud-platform|google-cloud-storage|tensorflow-serving
2
2,875
23,111,990
Pandas DataFrame stored list as string: How to convert back to list
<p>I have an <em>n</em>-by-<em>m</em> Pandas DataFrame <code>df</code> defined as follows. (I know this is not the best way to do it. It makes sense for what I'm trying to do in my actual code, but that would be TMI for this post so just take my word that this approach works in my particular scenario.)</p> <pre><code>...
<p>As you pointed out, this can commonly happen when saving and loading pandas DataFrames as <code>.csv</code> files, which is a text format.</p> <p>In your case this happened because list objects have a string representation, allowing them to be stored as <code>.csv</code> files. Loading the <code>.csv</code> will th...
python|string|list|pandas|dataframe
126
2,876
35,368,645
pandas - change df.index from float64 to unicode or string
<p>I want to change a dataframes' index (rows) from float64 to string or unicode. </p> <p>I thought this would work but apparently not:</p> <pre><code>#check type type(df.index) 'pandas.core.index.Float64Index' #change type to unicode if not isinstance(df.index, unicode): df.index = df.index.astype(unicode) </co...
<p>You can do it that way:</p> <pre><code># for Python 2 df.index = df.index.map(unicode) # for Python 3 (the unicode type does not exist and is replaced by str) df.index = df.index.map(str) </code></pre> <p>As for why you would proceed differently from when you'd convert from int to float, that's a peculiarity of ...
python|pandas|indexing|dataframe|rows
128
2,877
28,853,687
cython: create ndarray object without allocating memory for data
<p>In cython, how do I create an ndarray object with defined properties without allocating memory for its contents?</p> <p>My problem is that I want to call a function that requires a ndarray but my data is in a pure c array. Due to some restrictions I cannot switch to using an ndarray directly.</p> <p>Code-segement ...
<p>Efficiency aside, does this sort of assignment compile?</p> <p><code>np.empty</code> does not zero fill. <code>np.zeros</code> does that, and even that is done 'on the fly'. </p> <p><a href="https://stackoverflow.com/q/27464039">Why the performance difference between numpy.zeros and numpy.zeros_like?</a> explores...
numpy|cython
3
2,878
50,930,849
Python pandas dataframe with duplicate values
<p>I am looking to index the following pandas dataframe with the following sample values. The dataframe has a lot of duplicates.</p> <pre><code>ID AccountName 83 CHRISTIAN UNIVERSITY 83 CHRISTIAN UNIVERSITY 83 CHRISTIAN UNIVERSITY 83 CHRISTIAN UNIVERSITY 104 UNIVERSITY 104 UNIVERSITY 1...
<p>Assuming that you want an increasing index for each new ID, I'd do:</p> <pre><code>In [43]: df["number"] = df.ID.rank(method='dense').astype(int) In [44]: df Out[44]: ID AccountName number 0 83 CHRISTIAN UNIVERSITY 1 1 83 CHRISTIAN UNIVERSITY 1 2 83 CHRISTIAN UNIVERSITY ...
python|pandas|dataframe
4
2,879
50,692,749
How to multiply two columns with different two csv file and return result in first csv file using Pandas
<p>I have two CSV files where first csv file contains Price column and second csv contains quantity i tried to multiply this two columns and save result in new columns with first csv</p> <p>First.csv</p> <pre><code>Code Description Unit Price 110101 STATIONARY BICYCLE INDOOR USE ...
<p>Use <code>map</code></p> <pre><code>First.assign( Total=First.Price * First.Code.map(dict(zip(Second.Code, Second.Quantity)))) </code></pre>
python|pandas|csv|multiple-columns|multiplication
0
2,880
50,690,865
Overfitting Issue On a variation of ZF-net
<p>I am training a CNN on imagenet-2012 dataset, but the model keeps overfitting(Valiation Error rate: top1: 49%, top5: 25%, Training Error rate: top1:25%, top5: 8%. trained on GTX1080ti after 600k training steps (about 5 days)). the architecture is based on ZF-net but adds batch norm:</p> <pre><code> x_input = fe...
<p>the thing is when I evaluate the model I just resize the image to 224*224, it is different from the training data processing(crop image to 224*224), so the probability distribution of validation set is kind of different from the training set(different manifolds), and originally I thought it is not a big deal and the...
python|tensorflow|machine-learning|deep-learning
0
2,881
66,354,570
Sort image as NP array
<p>I'm trying to sort an image by luminosity using NumPy, which I'm new to. I've managed to create a random image and sort it.</p> <pre><code>def create_image(output, width, height, arr): array = np.zeros([height, width, 3], dtype=np.uint8) numOfSwatches = len(arr) swatchWidth = int(width/ numOfSwatches) for...
<p>Have not ever used PIL, but the following approach hopefully works (I'm not sure as I can't reproduce your exact examples), and of course there might be more efficient ways to do so. I'm using your functions, having changed the <code>math.sqrt</code> function to <code>np.sqrt</code> in the <code>lum</code> function ...
python|numpy|colors|python-imaging-library
1
2,882
66,558,347
Binarization using pd.cut
<p>I am a newbie to the world of ML. I am trying to learn to preprocess.</p> <p>I have an outcome data that has four types of inputs: 0,1,2,3,4</p> <p>0 corresponds to no disease while 1 to 4 corresponds to different types of diseases.</p> <p>I wish to binarize them into two: 0 for &quot;no disease&quot; and those 1-4 ...
<p>Your condition is binary so you can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>np.where</code></a> from <code>numpy</code>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; df Type 0 2 1 2 2 3 3 0 4 2 .. .....
python|pandas
0
2,883
66,683,077
Python function that evaluates each row by a list
<p>I am using Python to clean address data and standardize abbreviations, etc. so that it can be compared against other address data. I finally have 2 dataframes in Pandas. I would like to compare each row in the first df, named <code>df</code>, against a list created from another list of addresses in a df of similar s...
<p>EDIT based on <em>tdy</em> comment as my original answer didn't have the value for False option in where statement.</p> <p>Try sth like this:</p> <pre><code>df[&quot;isFound&quot;] = np.where(df['concat'].isin(second_df[&quot;concat&quot;]), &quot;found&quot;, &quot;notfound&quot;) </code></pre> <p>Should be exactly...
python|pandas
0
2,884
66,427,448
Tkinter canvas image bug
<p>I am rewriting my application in oop style and ran into an unexpected problem. The palette image is distorted. This has never happened before.</p> <p><a href="https://i.stack.imgur.com/fCzPN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fCzPN.jpg" alt="enter image description here" /></a></p> <p...
<p>The problem might be with the array conversion or something, it is recommended to load and use images using <code>PIL</code> itself, so its much easier. As a work around for you, you can use <code>cv2.imwrite()</code> and save the image and then use that path and open the new image up using <code>PIL</code>. Somethi...
python|numpy|opencv|tkinter|tkinter-canvas
1
2,885
16,223,483
Forced conversion of non-numeric numpy arrays with NAN replacement
<p>Consider the array</p> <p><code>x = np.array(['1', '2', 'a'])</code></p> <p>Tying to convert to a float array raises an exception</p> <pre><code>x.astype(np.float) ValueError: could not convert string to float: a </code></pre> <p>Does numpy provide any efficient way to coerce this into a numeric array, replacing...
<p>You can convert an array of strings into an array of floats (with NaNs) using <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.genfromtxt.html" rel="nofollow noreferrer"><code>np.genfromtxt</code></a>:</p> <pre><code>In [83]: np.set_printoptions(precision=3, suppress=True) In [84]: np.gen...
python|numpy|type-conversion|nan|coercion
15
2,886
16,099,488
Elementwise multiplication of several arrays in Python Numpy
<p>Coding some Quantum Mechanics routines, I have discovered a curious behavior of Python's NumPy. When I use NumPy's multiply with more than two arrays, I get faulty results. In the code below, i have to write:</p> <pre><code>f = np.multiply(rowH,colH) A[row][col]=np.sum(np.multiply(f,w)) </code></pre> <p>which prod...
<p>Your fault is in not reading <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.multiply.html" rel="noreferrer">the documentation</a>:</p> <blockquote> <p><code>numpy.multiply(x1, x2[, out])</code></p> </blockquote> <p><code>multiply</code> takes exactly two input arrays. The optional third argu...
python|numpy|multiplication
17
2,887
57,311,750
Create a dataframe with duplicate entries
<p>I do a sql query, and I then with <code>data = pd.read_sql(query, connection)</code> I have the following table,</p> <pre><code> ID ITEM TYPE_USER Count 711757 item1 type1 1 711757 item2 type1 1 711757 item3 type1 1 711794 item1 type2 1 711794 ...
<pre><code>pd.pivot_table(df, index=['ID','TYPE_USER'], columns='ITEM', values='Count').fillna(0).reset_index() </code></pre> <p>result</p> <pre><code>ITEM ID TYPE_USER item1 item2 item3 0 711541 type3 0.0 1.0 0.0 1 711757 type1 1.0 1.0 1.0 2 711794 type2 1.0 ...
python|pandas|dataframe
2
2,888
57,438,215
Is there a way to set all my GPUs to NOT be XLA so I can train with multiple gpus rather than just one?
<p>I would like to train keras models using multiple GPUs. My understanding is that you cannot currently train multiple gpus using XLA. The issue is I can't figure out how to turn off XLA. Every GPU is listed as an xla gpu.</p> <p>For reference, I am using 3 RTX2070s on the latest Ubuntu desktop. nvidia-smi does indee...
<p>I faced this problem either.</p> <p>Sometimes I fixed it by reinstalling the tensorflow-gpu package.</p> <pre><code>pip uninstall tensorflow-gpu pip install tensorflow-gpu </code></pre> <p>However, sometimes these commands didn't work. So I tried the following ones and it works surprisingly.</p> <pre><code>conda ins...
tensorflow|keras|gpu|nvidia
0
2,889
43,531,329
Group by timestamp a single CSV file - Pandas
<p>i have a almost endless horizontal csv where the variables are spreaded across the header and i have many repeated timestamps which results in a scenario like this:</p> <pre><code>+------------+------------+------------+------------+ | Timestamp | Variable1 | Variable2 | .... | +------------+------------+-...
<p>You can groupby timestamp and combine the values </p> <pre><code>df.groupby('Timestamp')['Variable1', 'Variable2'].apply(lambda x: x.sum()).reset_index() </code></pre> <p>You get</p> <pre><code> Timestamp Variable1 Variable2 0 2017/02/12 20 5 1 2017/02/13 20 2 2 2017/02/14 30 ...
python-3.x|pandas
4
2,890
43,832,311
How to plot by category over time
<p>I have two columns, categorical and year, that I am trying to plot. I am trying to take the sum total of each categorical per year to create a multi-class time series plot.</p> <pre><code>ax = data[data.categorical=="cat1"]["categorical"].plot(label='cat1') data[data.categorical=="cat2"]["categorical"].plot(ax=ax, ...
<p>I'm hesitant to call this a "solution", as it's basically just a summary of basic Pandas functionality, which is explained in the same documentation where you found the time series plot you've placed in your post. But seeing as there's some confusion around <code>groupby</code> and plotting, a demo may help clear t...
python|pandas|matplotlib
5
2,891
73,056,640
Drop row with bad data in a Pandas DataFrame
<p>I have at least one row with potentially bad data. I'd like to identify rows with bad data and entirely drop the row. Here's a pattern I have observed in a fairly large dataframe - <code>50k x 200</code></p> <pre><code>import pandas as pd df = pd.DataFrame({ 'name': ['12 x st', '0.5555', 'y'], ...
<p>If the valid values are only going to be letter characters, you could do something as simple as this filter, which checks if all of the characters in each value are alphabetic.</p> <pre class="lang-py prettyprint-override"><code>df = df[df['name'].str.isalpha()] </code></pre> <pre><code> name val col z 2 ...
python|pandas
1
2,892
73,012,710
How iterate over a df to know the most frequent item in each month
<p>I have the following Pandas DF:</p> <pre><code>visit_date|house_id ----------+--------- 2017-12-27|892815605 2018-01-03|892807836 2018-01-03|892815815 2018-01-03|892812970 2018-01-03|892803143 2018-01-03|892815463 2018-01-03|892816168 2018-01-03|892814475 2018-01-03|892813594 2018-01-03|892813557 2018-01-03|89280983...
<p>Adopted from a <a href="https://stackoverflow.com/questions/35364601/group-by-and-find-top-n-value-counts-pandas">similar answer</a></p> <pre><code>df = pd.DataFrame({'visit_date': ['2017-12-27', '2018-01-03', '2018-01-03', '2018-01-03', '2018-01-03', '2018-01-03', '2018-01-03', '2018-01-03', '2018-01-03', ...
python|pandas|loops
1
2,893
72,950,881
Running an external function within Pandas Dataframe to speed up processing loops
<p>Good Day Peeps,</p> <p>I currently have 2 data frames, &quot;Locations&quot; and &quot;Pokestops&quot;, both containing a list of coordinates. The goal with these 2 data frames, is to cluster points from &quot;Pokestops&quot; that are within 70m of the points in &quot;Locations&quot;.</p> <p>I have created a &quot;B...
<p>The Apply function Might be helpful. The Apply function applies the specified function to every cell of the Dataset (Of course you can control the parameters). Check this documentation (<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer">https://...
python|arrays|pandas|dataframe|for-loop
0
2,894
73,091,127
Use list items as column seperators pd.read_fwf
<p>I have text files containing tables which I want to put into a dataframe. Per file the column headers are the same, but the width is different depending on the content (because they contain names of different lengths for example).</p> <p>So far I managed to get the index of the first character of the header, so I kn...
<p>So what you can do is standardize the spacing with regex.</p> <pre><code>import re string = &quot;something something something more&quot; results = re.sub(&quot;(\W+)&quot;, &quot;|&quot;, string) results </code></pre> <p>That returns</p> <pre><code>'something|something|something|more' </code></pre> <p>If you ...
python|pandas|dataframe|text|read.fwf
1
2,895
70,404,478
Get column index of max value in pandas row
<p>I want to find not just the max value in a dataframe row, but also the specific column that has that value. If there are multiple columns with the value, then either returning the list of all columns, or just one, are both fine.</p> <p>In this case, I'm specifically concerned with doing this for a single given row, ...
<p>Assume that the source DataFrame contains:</p> <pre><code> A B 0 1 4 1 7 5 2 3 6 3 9 8 </code></pre> <p>Then, to find the column name holding the max value in <strong>each</strong> row (not only row <em>0</em>), run:</p> <pre><code>result = df.apply('idxmax', axis=1) </code></pre> <p>The result is:</p> <p...
python|pandas|dataframe
1
2,896
70,472,524
Finding The Row Of A Pandas Dataframe When Searching With A Variable In a Column PROBLEM
<p>I have a csv file that i imported to pandas df. Lets say it is something like this</p> <pre><code># A B C D # 0 foo one 0 0 # 1 bar one 1 2 # 2 foo two 2 4 # 3 bar three 3 6 # 4 foo two 4 8 # 5 bar two 5 10 # 6 foo one 6 12 # 7 foo three 7 14 </code></pre...
<p>You mean like this?:</p> <pre><code>df = pd.DataFrame([ (&quot;foo&quot;,&quot;one&quot;,0,0), (&quot;bar&quot;,&quot;one&quot;,1,2), (&quot;foo&quot;,&quot;two&quot;,2,4), (&quot;bar&quot;,&quot;three&quot;,3,6), (&quot;foo&quot;,&quot;two&quot;,4,8), (&quot;bar&quot;,&quot;two&quot;,5,10), ...
python|pandas|dataframe
1
2,897
70,683,832
Get one elements inside <tb> with Python
<p>im new to Python and im trying to make a web scraper to get the name and the ip of Minecraft server.</p> <p>The problem is that I was able to get the value of the but for example the ip of the server is in a div inside de Im using pandas and lxml.html</p> <p>example:</p> <pre><code>&lt;tr&gt; &lt;td class=...
<p>If I understand you correctly, this should get you what you're looking for:</p> <pre><code>servers = [] cols = [&quot;Name&quot;, &quot;ip&quot;] for s in doc.xpath(&quot;//td[@class='server-name']&quot;): s_ip = s.xpath(&quot;.//div[@class='server-ip input-group']//span[@class='form-control text-justify']/text(...
python|html|pandas|web-scraping
1
2,898
42,816,124
What is the relationship between steps and epochs in TensorFlow?
<p>I am going through TensorFlow <a href="https://www.tensorflow.org/get_started/get_started" rel="nofollow noreferrer">get started tutorial</a>. In the <code>tf.contrib.learn</code> example, these are two lines of code:</p> <pre><code>input_fn = tf.contrib.learn.io.numpy_input_fn({"x":x}, y, batch_size=4, num_epochs=...
<p><strong>TL;DR</strong>: An epoch is when your model goes through your whole training data once. A step is when your model trains on a single batch (or a single sample if you send samples one by one). Training for 5 epochs on a 1000 samples 10 samples per batch will take 500 steps.</p> <p>The <code>contrib.learn.io<...
tensorflow
44
2,899
27,127,539
numpy loading file error
<p>I tried to load <em>.npy</em> file created by <em>numpy</em>:</p> <pre><code>import numpy as np F = np.load('file.npy') </code></pre> <p>And <em>numpy</em> raises this error:</p> <blockquote> <p>C:\Miniconda3\lib\site-packages\numpy\lib\npyio.py in load(file, mmap_mode)</p> <pre><code>379 N = len(fo...
<p>You are using a file object that does not support the <code>seek</code> method. Note that the <code>file</code> parameter of <code>numpy.load</code> <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.load.html" rel="nofollow">must support the <code>seek</code> method</a>. My guess is that you are per...
python|numpy
2