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
400
58,514,197
Difference between nn.MaxPool2d vs.nn.functional.max_pool2d?
<p>Whats the difference between: <code>nn.MaxPool2d(kernel_size, stride)</code> and <code>nn.functional.max_pool2d(t, kernel_size, stride)</code>?</p> <p>The first one I define in the module and the second in the forward function?</p> <p>Thanks</p>
<p>They are essentially the same. The difference is that <code>torch.nn.MaxPool2d</code> is an explicit <code>nn.Module</code> that calls through to <code>torch.nn.functional.max_pool2d()</code> it its own <code>forward()</code> method.</p> <p>You can look at the source for <code>torch.nn.MaxPool2d</code> here and see...
python|module|pytorch|forward
7
401
58,260,612
python list comprehension with if condition looping
<p>Is it possible to use list comprehension for a dataframe if I want to change one column's value based on the condition of another column's value.</p> <p>The code I'm hoping to make work would be something like this:</p> <p><code>return ['lower_level' for x in usage_time_df['anomaly'] if [y &lt; lower_outlier for y...
<p>I don't think what you want to do can be done in a list comprehension, and if it can, it will definitely not be efficient.</p> <p>Assuming a dataframe <code>usage_time_df</code> with two columns, <code>anomaly</code> and <code>device_years</code>, if I understand correctly, you want to set the value in <code>anomal...
python|pandas|python-2.7|list-comprehension
1
402
58,268,118
How to replace a column of a pandas dataframe with only words that exist in the dictionary or a text file?
<p>Hi I have a pandas dataframe and a text file that look a little like this:</p> <pre><code>df: +----------------------------------+ | Description | +----------------------------------+ | hello this is a great test $5435 | | this is an432 entry | | ... | ...
<p>Use:</p> <pre><code>with open('file.txt', encoding="utf8") as f: L = f.read().split('\n') print (L) ['hello', 'this', 'is', 'a', 'test'] f = lambda x: ' '.join(y for y in x.split() if y in set(L)) df['Description'] = df['Description'].apply(f) </code></pre> <p>For improve performance:</p> <pre><code>s = set...
python|python-3.x|pandas
1
403
58,526,171
How to use aggregate with condition in pandas?
<p>I have a dataframe. Following code works </p> <pre><code>stat = working_data.groupby(by=['url', 'bucket_id'], as_index=False).agg({'delta': 'max','id': 'count'}) </code></pre> <p>Now i need to count ids with different statuses. I have "DOWNLOADED", "NOT_DOWNLOADED" and "DOWNLOADING" fo...
<p>One way to use assign to create columns then aggregate this new column.</p> <pre><code>working_data.assign(downloaded=df['status'] == 'DOWNLOADED', not_downloaded=df['status'] == 'NOT_DOWNLOADED', downloading=df['status'] == 'DOWNLOADING')\ .groupby(by=['url', 'buc...
pandas
0
404
69,194,321
Merge two dataframe based on condition
<p>I'm trying to merge two dataframes conditionally.</p> <p>In <code>df1</code>, it has <code>duration</code>. In <code>df2</code>, it has <code>usageTime</code>. On <code>df3</code>, I want to set <code>totalTime</code> as <code>df1</code>'s <code>duration</code> value if <code>df2</code> has no <code>usageTime</code...
<p>Specify the column names when using <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>fillna</code></a> and then convert the result <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.to_frame.html" rel="nofollow noreferrer"><code>to_fram...
python|pandas|dataframe
2
405
44,595,338
How to parallelize RNN function in Pytorch with DataParallel
<p>Here's an RNN model to run character based language generation:</p> <pre><code>class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size, n_layers): super(RNN, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.output_size = outp...
<p>You can simply set the parameter dim=1, e.g.</p> <pre><code>net = torch.nn.DataParallel(RNN(n_chars, hidden_size, n_chars, n_layers), dim=1).cuda() </code></pre>
torch|recurrent-neural-network|pytorch
4
406
61,070,707
Input contains infinity of value too large for dtype "float64"
<p>So I am pretty new to python in general and I am trying to follow a tutorial to normalize and scale all of my data; however, I keep getting an error. I am using Scikit-learn with pandas. I've searched around and have tried just about everything I can think of, but I am still getting this error.</p> <p>I keep receiv...
<p>Here your problem: <code>df.replace([np.inf, -np.inf], np.nan)</code>.</p> <p>Change the code as <code>df = df.replace([np.inf, -np.inf], np.nan)</code>.</p>
python|python-3.x|pandas|scikit-learn
1
407
60,806,747
Initialize variable as np array
<p>How do I transform a list into an numpy array? Is there a function that allows you to work on a list as if it were an array?</p> <pre><code>import numpy as np container = [0,1,2,3,4] container[container &lt; 2] = 0 </code></pre> <p>Returns:</p> <pre><code>'&lt;' not supported between instances of 'list' and 'int...
<p>I am not sure if I completely understand what you are looking for, but is it maybe <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html" rel="nofollow noreferrer">numpy.asarray</a>:</p> <blockquote> <p><strong>numpy.asarray(a, dtype=None, order=None)</strong></p> <p>Convert the in...
python|arrays|list|numpy
1
408
60,923,982
The model.predict(),model.predict_classes() and model.predict_on_batch() seems to produce no result
<p>I have created a model that makes use of deep learning to classify the input data using CNN. The classification is multi-class though, actually with 5 classes. On training the model seems to be fine, i.e. it doesn't overfit or underfit. Yet, on saving and loading the model I always get the same output regardless of ...
<p>I see that when you train, you normalize your images:</p> <pre><code>X = X/255.0 </code></pre> <p>but when you test, i.e., in prediction time, you just read your image and resize but not normalize. Try:</p> <pre><code>def prepare(filepath): IMG_SIZE=100 img_array=cv2.imread(filepath) img_array = img_a...
python|tensorflow|keras|deep-learning|conv-neural-network
1
409
71,664,469
Python Pandas ValueError: cannot reindex from a duplicate axis
<p>This might be really simple but I'm trying to get a subset of values from a dataframe by selecting values where a column meets a specific value. So this:</p> <pre><code>test_df[test_df.ProductID == 18] </code></pre> <p>But I'm getting this error: *** ValueError: cannot reindex from a duplicate axis</p> <p>Which is w...
<p>If something is wrong with your index, you might reset the index with:</p> <pre><code>test_df.reset_index(level=0, inplace=True) </code></pre>
python|pandas
0
410
70,010,933
Pandas check if cell is null in any of two dataframes and if it is, make both cells nulls
<p>I have two dataframes with same shape:</p> <pre><code>&gt;&gt;&gt; df1.shape (400,1200) &gt;&gt;&gt; df2.shape (400,1200) </code></pre> <p>I would like to compare cell-by-cell and if a value is missing in one of the dataframes make the equivalent value in the other dataframe NaN as well.</p> <p>Here's a (pretty inef...
<p>This is a simple problem to solve with pandas. You can use this code:</p> <pre class="lang-py prettyprint-override"><code>df1[df2.isna()] = df2[df1.isna()] = np.nan </code></pre> <p>It first creates <em>mask</em> of <code>df2</code>, i.e., a copy of dataframe containing <strong>only</strong> <code>True</code> or <co...
python|pandas
0
411
69,940,105
In the Jupyter Notebook, using geopandas, the x- y-axis is not showing
<pre><code>import geopandas map_df = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres')) map_df.plot() </code></pre> <p>Error Traceback and Output:</p> <p><a href="https://i.stack.imgur.com/XzrVC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XzrVC.png" alt="enter image desc...
<p>The map has a transparent background where the axes are. Since the axes are black by default and your background is also black, you can't see them. But they are there :).</p> <p>You can specify the background using matplotlib.</p> <pre class="lang-py prettyprint-override"><code>import geopandas import matplotlib.pyp...
python|jupyter-notebook|geopandas
1
412
72,388,739
Python Pandas Match 2 columns from 2 files to fill values in a file
<p>Please help filling values in &quot;file1.csv&quot; (daily data) from &quot;file2.csv&quot; (weekly data).</p> <p>Below is &quot;file1.csv&quot;(daily data)::</p> <pre><code>date,value,week_num,year,fill_col_1,fill_col_2 01-01-2018,1763.95,1,2018,, 02-01-2018,1736.2,1,2018,, 03-01-2018,1741.1,1,2018,, 04-01-2018,1...
<p>Try the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">pandas.DataFrame.merge</a> func:</p> <pre><code>import pandas as pd df_daily = pd.read_csv('1.csv').iloc[:,:4] df_weekly = pd.read_csv('2.csv').iloc[:,2:] print(df_daily.merge(df_weekly,on=['week_num...
pandas|comparison|multiple-columns|python-3.9
1
413
72,224,804
how to get smallest index in dataframe after using groupby
<p>If create_date field does not correspond to period between from_date and to_date, I want to extract only the large index records using group by 'indicator' and record correspond to period between from_date to end_date.</p> <pre><code>from_date = '2022-01-01' to_date = '2022-04-10' indicator create_date 0 ...
<p>You can try</p> <pre class="lang-py prettyprint-override"><code>df['create_date'] = pd.to_datetime(df['create_date']) m = df['create_date'].between(from_date, to_date) df_ = df[~m].groupby('indicator', as_index=False).apply(lambda g: g.loc[[max(g.index)]]).droplevel(level=0) out = pd.concat([df[m], df_], axis=0).so...
python|pandas|dataframe
3
414
72,317,821
Read multiple csv files into a single dataframe and rename columns based on file of origin - Pandas
<p>I have around 100 csv files with each one containing the same three columns. There are several ways to read the files into a single dataframe, but is there a way that I could append the file name to the column names in order to keep track of the origin of the columns?</p> <p>I have now tried to import the files usin...
<p>You coud add a <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.add_prefix.html" rel="nofollow noreferrer">prefix</a> (or <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.add_suffix.html" rel="nofollow noreferrer">suffix</a>) to the column names prior to concatenating the ...
python|pandas|dataframe
1
415
72,234,738
Refactoring an algorithm to avoid inefficient slicing of a large Numpy array
<p>I have a working algorithm to analyse experimental datasets. This algorithm is made of two main functions. The first one takes a large array as one of its inputs and returns an intermediate 3D, complex-valued array that often does not fit in memory. For this reason, I use Numpy’s <code>memmap</code> to save this arr...
<p>An easy optimization is to swap the last two axes, which shouldn't change the speed of function 1 (assuming the out-of-order memory accesses from the transpose are negligible compared to disk access) but should make function 2 run faster, for the same reasons discussed in the question you linked:</p> <pre class="lan...
python|numpy|performance|optimization|memory
1
416
50,494,789
What are the inputs to GradientDescentOptimizer?
<p>I'm trying to create a minimal code snippet to understand the <code>GradientDescentOptimizer</code> class to help me to understand the tensorflow API docs in more depth. </p> <p>I would like to provide some hardcoded inputs to the <code>GradientDescentOptimizer</code>, run the <code>minimize()</code> method and ins...
<p>Your loss shouldn't be a variable (it is not a parameter of your model) but the result of an operation, e.g.</p> <pre><code>loss_data = train_data**2 </code></pre> <p>Currently your loss does not depend on <code>train_data</code> which explains why no gradient can be computed.</p>
tensorflow
2
417
50,530,544
Tensorflow not displaying the right amount of free memory
<p>I've been trying to run a neural network of mine on my GPU but for some reason upon creating the device, Tensorflow won't see the full RAM memory and instead focuses on a 2GB free memory available... </p> <pre><code>Using TensorFlow backend. 2018-05-25 11:00:56.992852: I T:\src\github\tensorflow\tensorflow\core\pla...
<p>There is nothing wrong with TF. Your graphics card has exactly 2GB of DDR3 RAM. I think you are confusing GPU RAM with your CPU RAM which might be indeed 16 GB.</p>
tensorflow|gpu|nvidia|ram
2
418
45,547,400
GAN changing input size causes error
<p>Below code takes only 32*32 input, I want to feed in 128*128 images, how to go about it. The code is from the tutorial - <a href="https://github.com/awjuliani/TF-Tutorials/blob/master/DCGAN.ipynb" rel="nofollow noreferrer">https://github.com/awjuliani/TF-Tutorials/blob/master/DCGAN.ipynb</a> </p> <p>def generator(...
<p>The generator is generating 32*32 images, and thus when we feed any other dimension in discriminator, it results in the given error. </p> <p>The solution is to generate 128*128 images from the generator, by 1. Adding more no. of layers(2 in this case) 2. Changing the input to the generator </p> <pre><code>zP =...
machine-learning|tensorflow|computer-vision|deep-learning|dcgan
0
419
45,442,797
Cannot import Tensorflow with Eclipse on Ubuntu16.04
<p>The bug happens when I try to import Tensorflow on Eclipse. Tensorflow can be imported when I directly run the python code without using IDEs (I test it and it works perfectly). I've also tested my codes on PyCharm, it's fine with Pycharm....</p> <p>I've tested the LD_LIBRARY_PATH,PATH,CUDA_HOME variables with ec...
<p>Finally, I find the solution from '<a href="https://stackoverflow.com/questions/33812902/pycharm-cannot-find-library">PyCharm cannot find library</a>' As the user 'Laizer' suggested:</p> <pre><code>The issue is that PyCharm(Here is Eclipse) was invoked from the desktop, and wasn't getting the right environment vari...
eclipse|tensorflow|ubuntu-16.04|pydev
0
420
45,548,708
Transforming excel index to pandas index
<p>To give a bit of backstory, I created and excel sheet that transforms the excel column index to pandas index. Which in essense is just a simple Vlookup, on a defined table e.g Column A=0, Column B=1. It gets the job done, however it's not as efficient as I would like it to be. </p> <p>I use these index on my functi...
<p>If you have a column of index names, such as the on in your example, you can specify that in the pd.read_excel command. Since your index column is 5, it would read like this:</p> <pre><code>df = pd.read_excel('yourfilename.xlsx', index_col=5) </code></pre>
python|pandas
1
421
62,808,580
Rearranging a column based on a list order and then mapping the list as a new column
<p>I need to map a list as a new column in a dataframe based on another column with the same values but may have different cases fro different letters:</p> <pre><code> Input DF (df_temp): Name Class ABC 1 EFG 2 HIJ 3 ABC 4 param_list: ['Ab...
<p>Using <code>join</code>:</p> <pre><code>s = pd.Series(L, name='DB_name', index=map(str.upper, L)) df_temp = df_temp.assign(k=df['Name'].str.upper()).join(s, on='k').drop('k', 1) </code></pre> <p>Result:</p> <pre><code> Name Class DB_name 0 ABC 1 AbC 1 EFG 2 EfG 2 HIJ 3 HiJ 3 ABC ...
python|pandas|list|dataframe|for-loop
0
422
62,506,543
I met an Error: line 21, in <module> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
<pre><code>import numpy as np Q = np.loadtxt(open(&quot;D:\data_homework_4\Q.csv&quot;,&quot;rb&quot;), delimiter = &quot;,&quot;, skiprows = 0) b = np.loadtxt(open(&quot;D:\data_homework_4\B.csv&quot;,&quot;rb&quot;), delimiter = &quot;,&quot;, skiprows = 0) def f(x): return 1/2 * x.T @ Q @ x + b.T @ x def gradi...
<p>As it says, in the <code>if</code> condition you are comparing between 2 arrays - both of which has multiple values and the if condition evaluates all of them but doesn't know how to collapse them into a single value of Truth - that's why it's asking you to use <code>any</code> or <code>all</code>:</p> <p>Try this f...
python|numpy
1
423
54,618,397
Counting repeating sequences Pandas
<p>I have a data scattered in a chaotic manner. </p> <pre><code>store_id period_id sales_volume 0 4186684 226 1004.60 1 5219836 226 989.00 2 4185865 226 827.45 3 4186186 226 708.40 4 4523929 226 690.75 5 41...
<p>If you only need to sort by <code>period_id</code> within each <code>store_id</code>, you can use <code>df.sort_values</code>. Using your example DataFrame as input:</p> <pre><code>df.sort_values(['store_id', 'period_id']).reset_index(drop=True) df store_id period_id sales_volume 0 41685 208 ...
python|pandas
0
424
73,569,716
Pandas group in series
<p>Given <br></p> <pre><code>df = pd.DataFrame({'group': [1, 1, 2, 1, 1], 'value':['a','b','c','d','e']}) </code></pre> <p>I need to treat <strong>a</strong> and <strong>b</strong> as one group, <strong>c</strong> as second group, <strong>d</strong> and <strong>e</strong> as third group. How to get first element from e...
<p>Try this:</p> <pre class="lang-py prettyprint-override"><code>df1 = df[df['group'].ne(df['group'].shift())] </code></pre> <p>Check <a href="https://stackoverflow.com/a/59136415/13174934">this answer</a> for more details</p>
python|pandas|series|group
0
425
73,628,386
Cannot concatenate object of type '<class 'numpy.ndarray'>'
<p>i have a problem when i try to concatenate train set and validation set. I split my dataset into train set, validation set and test set. Then i scale them with 'StandardScaler()':</p> <pre><code>X_train, X_test, t_train, t_test = train_test_split(x, t, test_size=0.20, random_state=1) X_train, X_valid, t_train, t_val...
<p><code>X_train</code>, <code>X_valid</code>, <code>t_train</code>, <code>t_valid</code> are all numpy arrays so they need to be concatenated using numpy:</p> <pre><code>X_train = np.concatenate([X_train, X_valid]) t_train = np.concatenate([t_train, t_valid]) </code></pre> <p>As suggested in the comments it is most li...
python|pandas|numpy
0
426
73,595,231
Pandas to_datetime doesn't work as hoped with format %d.%m.%Y
<p>I have a pandas dataframe with a text column containing strings in the format:</p> <pre><code>28.08.1958 29.04.1958 01.02.1958 05.03.1958 </code></pre> <p>that I want to interpret as dates. The dataframe arises from using beautifulsoup, i.e. I've not read it in from csv, so I planned to use pd.to_datetime(). There ...
<p>Try this:</p> <pre><code>import pandas as pd import io csv_data = ''' Date 28.08.1958 29.04.1958 01.02.1958 05.03.1958 ''' df = pd.read_csv(io.StringIO(csv_data)) df[&quot;Date2&quot;] = pd.to_datetime(df[&quot;Date&quot;], format='%d.%m.%Y') df.sort_values(by=&quot;Date2&quot;, ascending=True, in...
python|pandas|date|sorting
2
427
73,684,178
Pandas csv dataframe to json array
<p>I am reading a csv file and trying to convert the data into json array.But I am facing issues as &quot;only size-1 arrays can be converted to Python scalars&quot;</p> <p>The csv file contents are</p> <pre><code> 4.4.4.4 5.5.5.5 </code></pre> <p>My code is below</p> <pre><code>import numpy as np import pandas as...
<p>As other answers mentioned, just use <code>list</code>: <code>json.dumps(list(df[0]))</code></p> <p>FYI, the data shape is your problem:</p> <p><a href="https://i.stack.imgur.com/VNouL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VNouL.png" alt="enter image description here" /></a></p> <p>if yo...
python|pandas|dataframe
1
428
60,518,664
Python pandas DataFrame, sum row's value which data is Tru
<p>I am very new to pandas and even new to programming. </p> <p>I have DataFrame of [500 rows x 24 columns]</p> <p>500 rows are rank of data and 24 columns are years and months.</p> <p>What I want is </p> <ol> <li><p>select data from df</p></li> <li><p>get all data's row value by int</p></li> <li><p>sum all row val...
<p>You can use <code>np.where</code>:</p> <pre><code>rows, cols = np.where(DATAF .notna()) # rows: array([0, 1, 1, 2], dtype=int64) print((rows+1).sum()) # 8 </code></pre>
python|pandas|dataframe
1
429
60,645,104
maximum difference between two time series of different resolution
<p>I have two time series data that gives the electricity demand in one-hour resolution and five-minute resolution. I am trying to find the maximum difference between these two time series. So the one-hour resolution data has 8760 rows (hourly for an year) and the 5-minute resolution data has 104,722 rows (5-minutly fo...
<h2><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow noreferrer">Numpy's .repeat() function</a></h2> <p>You can change your hourly data into 5-minute data by using numpy's repeat function</p> <pre><code>import numpy as np np.repeat(hourly_data, 12) </code></pre>
python|pandas|time-series
1
430
60,472,670
pandas and folium not able to convert str to float
<p><a href="https://i.stack.imgur.com/8Hg9W.png" rel="nofollow noreferrer">enter image description here</a>I'm using python folium to develop a map which displays the airports in india, im using pandas to read the data from csv and assign the coordinates to <code>folium.Maker</code> location and im getting this error</...
<p>Take a look at the contents of the dataframe and you will see first row is meta-data not data. I just skipped first row using <code>loc[]</code>. For good measure I've include airport name in the marker.</p> <pre><code>df = pd.read_csv(&quot;airports.csv&quot;) map = folium.Map(location = [20.5937 ,78.9629], zoom_s...
python|python-3.x|pandas|maps|folium
0
431
60,671,971
How to reshape an Image in pytorch
<p>I have an image of shape <code>(32, 3, 32, 32)</code>. I know it's of the form <code>(batch_size, Channel, Height, Width)</code>.</p> <p>Q. How do I convert it to be <code>(32, 32, 32)</code> overriding the <code>Channel</code>?</p>
<p>If you want to convert to grayscale you could do this:</p> <p><code>image.mean(dim=1)</code></p>
python|image-processing|dataset|pytorch
0
432
72,756,016
Pandas Set row value based on another column value but do nothing on else
<p>this is my dataframe:</p> <p><a href="https://i.stack.imgur.com/meKUR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/meKUR.png" alt="enter image description here" /></a></p> <p>its got 455 rows with a secuence of a period of days in range of 4 hours each row.</p> <p>i need to replace each 'demand...
<pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np #data preparation df = pd.DataFrame() df['date'] = pd.date_range(start='2022-06-01',periods=7,freq='4h') + pd.Timedelta('3H') df['val'] = np.random.rand(7) print(df) &gt;&gt; date val 0 2022-06-01 03:00:00 0...
python|pandas|dataframe
1
433
59,614,071
values in the array change when turned to numpy array
<p>I have data stored in a pandas DataFrame that I move to a numpy array using the following code </p> <pre><code># used to be train_X = np.array(train_df.iloc[1:,3:].values.tolist()) # but was split for me to find he source of change pylist = train_df.iloc[1:,3:].values.tolist() print(pylist[0]) train_X = np.array(...
<p>As mentioned in the comments, NumPy represents the data to exponential notation. If you would like to change the way it's printed, you can do:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np np.set_printoptions(precision=2) pylist = train_df.iloc[1:,3:].values.tolist() print(pylist[0]) train...
python|pandas|numpy
1
434
59,853,054
Tensorflow Lite Object Detection with Custom AutoML Model
<p>I like to test the Object Detection Example of TFLite. </p> <p><a href="https://github.com/tensorflow/examples/tree/master/lite/examples/object_detection/android" rel="nofollow noreferrer">https://github.com/tensorflow/examples/tree/master/lite/examples/object_detection/android</a></p> <p>The example with the defa...
<p>Two probable errors on log might be:</p> <p><code>Cannot convert between a TensorFlowLite buffer with 1080000 bytes and a ByteBuffer with 270000 bytes.</code> Modify TF_OD_API_INPUT_SIZE accordingly.</p> <p><code>tflite ml google [1, 20, 4] and a Java object with shape [1, 10, 4].</code> Modify NUM_DETECTIONS acco...
android|tensorflow|machine-learning|tensorflow-lite|automl
0
435
40,515,677
Graphical Selection of Data in Python 3
<p><strong>The Problem to Solve</strong></p> <p>I have two 2D numpy arrays. One of which is an array of floats, the other is an array of strings. Each float array element is extracted from a file with a name in the corresponding string array element.</p> <p>I want to plot a 2D heatmap of the array of floats, with the...
<p>There is no easy way to do this, however it is quite doable with matplotlib. Matplotlib has two classes SpanSelector and LassoSelector that you can use.You can find some documentation <a href="http://matplotlib.org/api/widgets_api.html" rel="nofollow noreferrer">here</a>. <a href="http://matplotlib.org/examples/widg...
python|numpy|plot|interactive
1
436
18,701,569
pandas: DataFrame.mean() very slow. How can I calculate means of columns faster?
<p>I have a rather large CSV file, it contains 9917530 rows (without the header), and 54 columns. Columns are real or integer, only one contains dates. There is a few NULL values on the file, which are translated to <code>nan</code> after I load it to pandas <code>DataFrame</code>, which I do like this:</p> <pre><code...
<p>Here's a similar sized from , but without an object column</p> <pre><code>In [10]: nrows = 10000000 In [11]: df = pd.concat([DataFrame(randn(int(nrows),34),columns=[ 'f%s' % i for i in range(34) ]),DataFrame(randint(0,10,size=int(nrows*19)).reshape(int(nrows),19),columns=[ 'i%s' % i for i in range(19) ])],axis=1) ...
python|performance|pandas|dataframe
19
437
18,441,779
How to specify upper and lower limits when using numpy.random.normal
<p>I want to be able to pick values from a normal distribution that only ever fall between 0 and 1. In some cases I want to be able to basically just return a completely random distribution, and in other cases I want to return values that fall in the shape of a gaussian.</p> <p>At the moment I am using the following f...
<p>It sounds like you want a <a href="http://en.wikipedia.org/wiki/Truncated_normal_distribution" rel="noreferrer">truncated normal distribution</a>. Using scipy, you could use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.truncnorm.html" rel="noreferrer"><code>scipy.stats.truncnorm</code></...
python|numpy|random|scipy|gaussian
61
438
58,059,351
Update dataframe via for loop
<p>The code below has to update <code>test_df dataframe</code>, which is currently filled with <code>NaN</code>s.</p> <p>Each 'dig' (which is always an integer) value has corresponding 'top', 'bottom', 'left' and 'right' values, and the slices of dataframe, corresponding to respective top:bottom, left:right ranges for...
<p>The problem I see is that in <code>letters_df</code> the value in column 4 is higher than the value in column 2. That means that when you do <code>top = int(height) - int(row[2]) bottom = int(height) - int(row[4])</code> the value you will get in <code>top</code> will be bigger than the value you will get in <co...
python|pandas|dataframe
0
439
58,045,718
See all correctly and incorrectly identified images when training on the mnist dataset
<p>I'm trying to find a way to visualize which numbers in the mnist dataset a model was able to correctly identify and which ones it wasn't. What I can't seem to find is if such a visualization is possible in tensorboard or if I would need to use/create something else to achieve it.</p> <p>I'm currently working from ...
<p>It appears the what-if tool is what I was looking for, it allows you to visually sort testing data depending on whether it was <a href="https://i.stack.imgur.com/xrxiW.jpg" rel="nofollow noreferrer">correctly or incorrectly identified by the model.</a></p> <p>If you want to test it out <a href="https://pair-code.gi...
python|python-3.x|tensorflow|tensorboard
0
440
36,758,114
ValueError: setting an array element with a sequence when using feed_dict in TensorFlow
<p>I am trying to feed a Tensor containing the correct labels when I perform training.</p> <p>The correct labels for the entire training dataset are contained in one tensor which has been converted from a numpy array:</p> <pre><code>numpy_label = np.zeros((614,5),dtype=np.float32) for i in range(614): numpy_lab...
<p>The problem is that that <code>feed_dict</code> must be compatible with numpy arrays.</p> <p>Your code results in something like this</p> <p><code>np.array(&lt;tf.Tensor 'Slice_5:0' shape=(5, 5) dtype=float32&gt;, dtype=np.float32)</code></p> <p>Which fails in numpy with cryptic error above. To fix it, you need t...
python|arrays|numpy|tensorflow
2
441
37,013,115
How to read/traverse/slice Scipy sparse matrices (LIL, CSR, COO, DOK) faster?
<p>To manipulate Scipy matrices, typically, the built-in methods are used. But sometimes you need to read the matrix data to assign it to non-sparse data types. For the sake of demonstration I created a random LIL sparse matrix and converted it to a Numpy array (pure python data types would have made a better sense!) u...
<p>A similar question, but dealing setting sparse values, rather than just reading them:</p> <p><a href="https://stackoverflow.com/questions/35773101/efficient-incremental-sparse-matrix-in-python-scipy-numpy/35779647#35779647">Efficient incremental sparse matrix in python / scipy / numpy</a></p> <p>More on accessing ...
python|numpy|scipy
2
442
36,837,435
Delete column from a numpy structured array (list of tuples in the array)?
<p>I use an external library function which returns a numpy structured array.</p> <pre><code>cities_array &gt;&gt;&gt; array([ (1, [-122.46818353792992, 48.74387985436505], u'05280', u'Bellingham', u'53', u'Washington', u'5305280', u'city', u'N', -99, 52179), (2, [-109.67985528815007, 48.54381826401885], u'3505...
<p>I think that this should work:</p> <pre><code>def delete_colum(array, *args): filtered = [x for x in array.dtype.names if x not in args] return array[filtered] </code></pre> <p>Example with array:</p> <pre><code>a Out[9]: array([(1, [-122.46818353792992, 48.74387985436505])], dtype=[('ID', '&lt;...
python|arrays|python-2.7|numpy
2
443
54,934,345
Merge two numpy arrays into a list of lists of tuples
<p>I haven't been able to figure this out. Thanks for any help:</p> <p>Have:</p> <pre><code>&gt;&gt;&gt; x = np.array([[1,2],[5,6]]) &gt;&gt;&gt; x array([[1, 2], [5, 6]]) &gt;&gt;&gt; y = np.array([[3,4],[7,8]]) &gt;&gt;&gt; y array([[3, 4], [7, 8]]) </code></pre> <p>Want:</p> <pre><code>&gt;&gt;&gt;...
<p>Try this:</p> <pre><code>x_z = map(tuple,x) y_z = map(tuple,y) [list(i) for i in zip(x_z, y_z)] </code></pre> <p>Output:</p> <pre><code>[[(1, 2), (3, 4)], [(5, 6), (7, 8)]] </code></pre>
python|numpy
3
444
54,718,657
Insert dict into dataframe with loop
<p>Fetching data from API with for loop, but only last row is showing. If i put <code>print</code> statement instead of <code>d=</code>, I get all records for some reason. How to populate a <code>Dataframe</code> with all values?</p> <p>I tried with for loop and with append but keep getting wrong results</p> <pre><co...
<p>Put all your data into a list of dictionaries, then convert to a dataframe at the very end</p> <p>At the top of your code write:</p> <pre><code>all_data = [] </code></pre> <p>Then in your loop, after d = {...}, write</p> <pre><code>all_data.append(d) </code></pre> <p>Finally at the end (after the loop has finis...
python|pandas
3
445
54,703,606
Feeding vectorized data to keras
<p>I am working on using some <code>name:gender</code> data to build and train a model that could predict the gender. I am trying the basics as I read about ML and probably got many things wrong. I haven't yet learnt how to generate and feed all the features that I want the network to use in its training. At this point...
<p>A simple example:</p> <pre><code>from keras.models import Sequential from keras.layers import Dense import pandas as pd import numpy as np df = pd.DataFrame({"vectorized": [[1,0,0],[0,1,0],[0,0,1]], "gender": [1,0,1]}) # convert the inner list to numpy array # X = np.array([np.array(l) for l in...
python|arrays|pandas|keras
1
446
54,765,997
creating a numpy array in a loop
<p>I want to create a numpy array by parsing a .txt file. The .txt file consists of features of iris flowers seperated by commas. every line is has one flower example with 5 data seperated with 4 commas. first 4 number is features and the last one is the name. I parse the .txt in a loop and want to append (using numpy....
<p>While the people in the comments are right in that you are not persisting your data anywhere, your problem, I assume, is incorrect np.array construction. You should enclose all of the arguments in a list like this:</p> <pre><code>feature_table = np.array([currentline[0],currentline[3],currentline[4]]) </code></pre>...
python|arrays|numpy
2
447
73,185,812
best way to evaluate a function over each element of a dataframe or array using pandas, numpy or others
<p>I have some time series data that requires multiplying constants by variables at time t. I have come up with 3 methods to get an answer that is correct.</p> <p>The main thing I am wondering is Q1 below. I appreciate Q2 and Q3 could be subjective, but I am mostly seeing if there is a much better method I am completel...
<p><code>np.maximum</code> (note: not the same as <code>np.max</code>) gives a vectorized way of handling the <code>max</code> element of the formula:</p> <pre><code>df['ans_t'] = x * df['var1'] + (1 - x) * df['var2'] - y * np.maximum(0, df['var3'] - z) </code></pre> <p>after which <code>df['ans_t']</code> is:</p> <pre...
python|pandas|numpy
1
448
35,328,399
How to plot the rolling mean of stock data?
<p>I was able to plot the data using the below code:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt url = "http://real-chart.finance.yahoo.com/table.csv?s=YHOO&amp;a=03&amp;b=12&amp;c=2006&amp;d=01&amp;e=9&amp;f=2016&amp;g=d&amp;ignore=.csv" df = pd.read_csv(url) df.index = df[...
<p>Why don't you just use the <code>datareader</code>?</p> <pre><code>import pandas.io.data as web aapl = web.DataReader("aapl", 'yahoo', '2010-1-1')['Adj Close'] aapl.plot(title='AAPL Adj Close');pd.rolling_mean(aapl, 50).plot();pd.rolling_mean(aapl, 200).plot() </code></pre> <p><a href="https://i.stack.imgur.com/P...
python|pandas|matplotlib
3
449
30,955,004
Improve Polynomial Curve Fitting using numpy/Scipy in Python Help Needed
<p>I have two NumPy arrays time and no of get requests. I need to fit this data using a function so that i could make future predictions. These data were extracted from cassandra table which stores the details of a log file. So basically the time format is epoch-time and the training variable here is get_counts.</p> <...
<p>You could try:</p> <pre><code>time = np.array([x[1] for x in enumerate(df['epoch_time'])]) byte = np.array([x[1] for x in enumerate(df['byte_transfer'])]) fit = np.polyfit(time, byte, n) # step up n value here, # where n is the degree of the polynomial yp = np.poly1d(fit) pri...
python|numpy|matplotlib|curve-fitting|non-linear-regression
1
450
30,965,864
Joblib parallel write to "shared" numpy sparse matrix
<p>Im trying to compute number of shared neighbors for each node of a very big graph (~1m nodes). Using Joblib Im trying to run it in parallel. But Im worrying about parallel writes to sparse matrix, which supposed to keep all data. Will this piece of code produce consistent results?</p> <pre><code>vNum = 1259084 NN_M...
<p>I needed to do the same work, in my case was just ok to merge the matrixes together into one matrix which you can do this way:</p> <pre><code>from scipy.sparse import vstack matrixes = Parallel(n_jobs=-3)(delayed(nn_calc_parallel)(x) for x in documents) matrix = vstack(matrixes) </code></pre> <p>Njob-3 means all CP...
python|numpy|scipy|networkx|joblib
0
451
67,425,567
Extract values from xarray dataset using geopandas multilinestring
<p>I have a few hundred <code>geopandas</code> multilinestrings that trace along an object of interest (one line each week over a few years tracing the Gulf Stream) and I want to use those lines to extract values from a few other <code>xarray</code> datasets to know sea surface temperature, chlorophyll-a, and other var...
<p>Breaking the lines into points and then extracting the point is quite straightforward actually!</p> <pre class="lang-py prettyprint-override"><code>import geopandas as gpd import numpy as np import shapely.geometry as sg import xarray as xr # Setup an example DataArray: y = np.arange(20.0) x = np.arange(20.0) da =...
python|geopandas|python-xarray
1
452
67,547,760
Alternatives to Python beautiful soup
<p>I wrote a few lines to get data from a financial data website.</p> <p>It simply uses <code>beautiful soup</code> to parse and <code>requests</code> to get.</p> <p>Is there any other simpler or sleeker ways of getting the same result?</p> <p>I'm just after a discussion to see what others have come up with.</p> <pre><...
<p>You can try with <code>read_html()</code> method:</p> <pre><code>symbols = ('ULVR','AZN','HSBC') df=[pd.read_html('https://uk.finance.yahoo.com/quote/' + ii + '.L/history?p=' + ii + '.L') for ii in symbols] df1=df[0][0] df2=df[1][0] df3=df[2][0] </code></pre>
python|pandas|dataframe|beautifulsoup|python-requests
1
453
67,543,737
How can I groupby on one column while sorting by another over the entire dataframe
<p>I have a dataframe that looks like this:</p> <pre><code> id total 1 50 1 0 1 0 2 100 2 0 2 0 3 75 3 0 3 0 </code></pre> <p>But I need it to sort by the <strong>total</strong> in descending order, while keeping the rows grouped by <strong>id</strong>...
<h3>(1) Clarification of requirement</h3> <p>First of all, let's revisit/clarify your requirement by exploring the expected result for a more complicated data sample:</p> <pre><code> id total 0 1 100 1 1 70 2 1 68 3 1 65 4 2 100 5 2 80 6 2 50 7 3 100 8 3 75 9 3 ...
python|pandas
1
454
67,391,750
Naming objects in a python for loop for bootstrapping
<p>I have a Pandas dataframe (<code>df</code>) with columns for each of the measurements taken on the individuals. There is one row per individual:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>col_1</th> <th>col_2</th> <th>col_3</th> <th>col_4</th> </tr> </thead> <tbody> <tr> <td>1.0</td...
<p>You could use a dictionary to store each of your iterations per column and then you might (if you want to) turn into a dataframe:</p> <pre><code>bootstrapped = {} for col in df: #You don't need to specify .columns mean=[] for i in np.arange(10000): sample = np.random.choice(df[col],size=le...
python|pandas|loops
1
455
67,531,914
Choiche GPU tensorflow-directml or multi-gpu
<p>I'm training a model with tensorflow on a Windows PC, but the training is low so I'm trying to configure tensorflow to use a GPU. I installed tensorflow-directml (in a conda environment with python 3.6) because my GPU is an AMD Radeon GPU. With this simple code</p> <pre><code>import tensorflow as tf tf.test.is_gpu_a...
<p>From <a href="https://docs.microsoft.com/en-us/windows/win32/direct3d12/gpu-faq" rel="nofollow noreferrer">Microsoft</a>:</p> <pre><code>gpu_config = tf.GPUOptions() gpu_config.visible_device_list = &quot;1&quot; session = tf.Session(config=tf.ConfigProto(gpu_options=gpu_config)) </code></pre>
python|tensorflow|anaconda|amd
0
456
34,862,336
Performance of str.strip for Pandas
<p>I thought the third option was supposed to be the fastest way to strip whitespaces? Can someone give me some general rules that I should be applying when working with large data sets? I normally use .astype(str) but clearly that is not worthwhile for columns which I know are objects already.</p> <pre><code>%%timeit...
<p>Let's first look at the difference between <code>.map(str.strip)</code> and <code>.str.strip()</code> (second and third case).<br> Therefore, you need to understand what <code>str.strip()</code> does under the hood: it actually does some <code>map(str.strip)</code>, but using a custom <code>map</code> function that ...
python-3.x|pandas
14
457
60,104,102
Custom max_pool layer: ValueError: The channel dimension of the inputs should be defined. Found `None`
<p>I am working on <strong>tensorflow2</strong> and I am trying to implement Max unpool with indices to implement SegNet. </p> <p>When I run it I get the following problem. I am defining the def <code>MaxUnpool2D</code> and then calling it in the model. I suppose that the problem is given by the fact that updates and ...
<p>I have solved the problem. If someone will need here is the code for MaxUnpooling2D:</p> <pre><code>def MaxUnpooling2D(pool, ind, output_shape, batch_size, name=None): &quot;&quot;&quot; Unpooling layer after max_pool_with_argmax. Args: pool: max pooled output tensor ind: argmax indices ...
function|image-segmentation|tensorflow2.0|max-pooling
1
458
65,128,884
Change and swap values in the row and column by conditions
<p>I have a following pandas dataframe:</p> <p><a href="https://i.stack.imgur.com/WNJYd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WNJYd.png" alt="enter image description here" /></a></p> <p>and I want to check if the value in the column <code>'A start'</code> is negative. If so than swap values...
<p>This code permutates values between start and end columns if A start value is lower than zero:</p> <pre><code>for i, row in df.iterrows(): if row['A start'] &lt; 0: start_value = row['start'] end_value = row['end'] df.iloc[i, df.columns.get_loc('start')] = end_value df.iloc[i, df....
python|pandas|dataframe|conditional-statements
1
459
65,213,469
How can I convert a separate column text into row using Python/Pandas?
<p>I am teaching myself machine learning and working on some dataset which have the columns</p> <p><a href="https://i.stack.imgur.com/NHTdg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NHTdg.png" alt="dataframe image" /></a> `</p> <p>there are two sentences columns sent0 and sent1 and sol contains...
<p>This should do what you want</p> <pre><code>df = pd.DataFrame() # this should be your original df import pandas as pd data = pd.DataFrame(columns=[&quot;id&quot;, &quot;sent&quot;, &quot;sol&quot;]) for i, row in df.iterrows(): id_ = row[&quot;id&quot;] sent0 = row[&quot;sent0&quot;] sent1 = row[&quot;s...
python|pandas|dataframe|text-processing
0
460
65,430,009
I have an error while importing tensorflow
<p>I'm using Python 3.6.0 and I downloaded tensorflow using <code>pip install tensorflow</code>, I tried several times to uninstall tensorflow and install another version of tensorflow but it didn't work... Which version of tensorflow is compatible for me? (I'm using now version 1.15.0)</p> <p>This is the import error:...
<p>You need to install the C++ redist libraries C++</p> <p><a href="https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads" rel="nofollow noreferrer">c++ redist lib</a></p>
python|python-3.x|tensorflow
0
461
50,066,318
Custom Ticks and Labels for Hexbin Colorbar in Pandas/Matplotlib
<p>How do I create custom ticks and labels for a Hexbin plot's Colorbar?</p>
<p>The key to modifying the colorbar is gaining access to it, then using Locators and Formatters (in <a href="https://matplotlib.org/api/ticker_api.html" rel="nofollow noreferrer">matplotlib.ticker</a>) to modify them, finally updating the ticks after the changes have been made.</p> <pre><code>import matplotlib.pyplot...
pandas|matplotlib|plot|colorbar
2
462
50,185,275
Matplotlib x-axis disappear
<p>I'm experimenting with python's matplotlib function and having some weird result that the x-axis label disappears from the plot.</p> <p>I'm trying the following example as shown in this <a href="https://www.youtube.com/watch?v=X60m6GBq4fM" rel="nofollow noreferrer">Youtube</a>: <a href="https://i.stack.imgur.com/4z...
<p>Let's convert the Year column in the yearly_average dataframe from a str or object dtype to integer. Then, plot using pandas plot.</p> <p>MVCE:</p> <p>Working example with xaxis ticklabels where dtype 'Year' is integer</p> <pre><code>df = pd.DataFrame({'Year':[2000,2001,2002,2003,2004,2005],'Value':np.random.ran...
python|pandas|matplotlib|jupyter-notebook
0
463
64,118,921
Calculate index using base year
<p>df</p> <pre><code>fruit year price index_value Boolean index apple 1960 11 apple 1961 12 100 True apple 1962 13 apple 1963 13 100 True banana 1960 11 banana 1961 12 </code></pre> <p>How could I calculate the index column for the year after a True per fruit? The base ye...
<p>I took the liberty to adjust your input data with a row for <code>apple 1964 11</code> to match your output example. The column <code>Boolean</code> is redundant</p> <pre><code>import pandas as pd import numpy as np import io t = ''' fruit year price index_value apple 1960 11 apple 1961 12 100 ...
python|python-3.x|pandas|dataframe
1
464
64,118,458
Applying a custom aggregation function to a pandas DataFrame
<p>I have a pandas DataFrame with two float columns, <code>col_x</code> and <code>col_y</code>.</p> <p>I want to return the sum of <code>col_x * col_y</code> divided by the sum of <code>col_x</code></p> <p>Can this be done with a custom aggregate function?</p> <p>I am trying to do something like this:</p> <pre><code>im...
<p>First , you can use <code>apply</code> on <code>axis=1</code> for such problems:</p> <pre><code>df.apply(lambda x: aggregation_function(x['col_x'],x['col_y']),axis=1) </code></pre> <p>however , this will result in error in your case because the aggregate function you have is calculating <code>col_x * col_y</code> fo...
python|pandas
1
465
64,163,870
Identifying consecutive declining values in a column from a data frame
<p>I have a 278 x 2 data frame, and I want to find the rows that have 2 consecutive declining values in the second column. Here's a snippet:</p> <p><a href="https://i.stack.imgur.com/fm7Py.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fm7Py.png" alt="data frame" /></a></p> <p>I'm not sure how to ap...
<ul> <li>Use <code>shift</code> to create a temporary column with all values shifted up one row.</li> <li>Compare the two columns, <code>&quot;GDP&quot; &gt; &quot;shift&quot;</code> This gives you a new column of Boolean values.</li> <li>Look for consecutive <code>True</code> values in this Boolean column. That iden...
python|pandas
1
466
47,059,781
How to append new dataframe rows to a csv using pandas?
<p>I have a new dataframe, how to append it to an existed csv? </p> <p>I tried the following code:</p> <pre><code>f = open('test.csv', 'w') df.to_csv(f, sep='\t') f.close() </code></pre> <p>But it doesn't append anything to test.csv. The csv is big, I only want to use append, rather than read the whole csv as datafr...
<p>Try this:</p> <pre><code>df.to_csv('test.csv', sep='\t', header=None, mode='a') # NOTE: -----&gt; ^^^^^^^^ </code></pre>
pandas|csv|dataframe|append
8
467
46,732,047
TypeError for predict_proba(np.array(test))
<pre><code>model = LogisticRegression() model = model.fit(X, y) test_data = [1,2,3,4,5,6,7,8,9,10,11,12,13] test_prediction = model.predict_proba(np.array(test_data)) max = -1.0 res = 0 for i in range(test_prediction): if test_prediction[i]&gt;max: max = test_prediction[i] res = i if res==0: pri...
<p>You can also use <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.argmax.html" rel="nofollow noreferrer">numpy.argmax</a> which will directly give you the index of the largest value.</p> <pre><code>import numpy as np #test_prediction is most probably np array only pred = np.array(test_pre...
python|python-3.x|numpy|scikit-learn|typeerror
1
468
46,972,163
How to use pandas to group items by classes bounded by a difference less that 4
<p>I wonder how to create classes of items grouped by its difference &lt;=4, so 1,2,3,4,5 will be grouped into 1, 9-13 to 9 ... and then select the min/max values of the attribute y, in an efficient/easy way:</p> <p><code>items= [('x', [ 1,2,3,3,3,5,9,10,11,13]), ('y', [1,1,1,1,1,4,4,1,1,1])]</code></p> <p><code>In[...
<p>Such operations are usually done in two steps:</p> <ol> <li>Create a key to group by.</li> <li>Calculate aggregate statistics with groupby.</li> </ol> <p>I assume you have dataframe <code>df</code> defined as</p> <pre><code>df = pd.DataFrame.from_items([('x', [ 1,2,3,3,3,5,9,10,11,13]), ('y', [1,1,1,1,1,4,4,...
python|pandas
1
469
46,930,558
Keras adding extra dimension to target (Error when checking target)
<p>I have a Siamese Keras model defined with this code:</p> <pre class="lang-python prettyprint-override"><code>image1 = Input(shape=(128,128,3)) image2 = Input(shape=(128,128,3)) mobilenet = keras.applications.mobilenet.MobileNet( input_shape=(128,128,3), alpha=0.25, depth_multiplier=1, ...
<p>This is strange.</p> <p>It seems <code>y</code> is actually <code>(10,1)</code>. </p> <p>You can use <code>keepdims=True</code> in your <code>K.sum</code> to make keras expect a <code>(10,1)</code> array. </p> <hr> <p>Not sure what is the cause for that. Maybe you have old <code>Y</code> vars (perhaps upper ca...
python|numpy|tensorflow|keras
0
470
38,886,096
Adding multiple rows to pandas dataframe based on returned lambda function
<p>I have a pandas dataframe that can be represented as follows:</p> <pre><code>myDF = pd.DataFrame({'value':[5,2,4,3,6,1,4,8]}) print(myDF) value 0 5 1 2 2 4 3 3 4 6 5 1 6 4 7 8 </code></pre> <p>I can add a new column containing the returned value from a function that acts...
<p>You can create a dataframe based on the results and then concatenate it to your original dataframe. You then need to rename your columns.</p> <pre><code>df = pd.concat([myDF, pd.DataFrame([myFunc(x) for x in myDF['value']])], axis=1) df.columns = myDF.columns.tolist() + ['square', 'cubed', 'fourth'] &gt;&gt;&gt; d...
python|python-3.x|pandas|dataframe|lambda
0
471
38,924,256
Creating a Nested List in Python
<p>I'm trying to make a nested list in Python to contain information about points in a video, and I'm having a lot of trouble creating an array for the results to be saved in to. The structure of the list is simple: the top level is a reference to the frame, the next level is a reference to a marker, and the last level...
<p>This illustrates what is going on:</p> <pre><code>In [1334]: step=[[0]*3 for x in range(3)] In [1335]: step Out[1335]: [[0, 0, 0], [0, 0, 0], [0, 0, 0]] In [1336]: stack=[step]*4 In [1337]: stack Out[1337]: [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], ...
python|python-2.7|numpy
1
472
63,078,437
Unsure how to further optimise (get rid of for loop)
<p>I am working on several datasets. One dataset (geodata - 74 observations) contains Indian district names, latitude and longitude of district centres while the other (called rainfall_2009) contains information on rainfall in a geographic grid as well as grid's latitude and longitude. The aim is to link each grid to a...
<p>Can you pass pandas columns directly to <code>dist.geodesic()</code>? Calling this via the apply() statement may be slow.</p> <p>This example might be helpful (see the function <code>gcd_vec()</code> in this blog post: <a href="https://tomaugspurger.github.io/modern-4-performance" rel="nofollow noreferrer">https://...
pandas|for-loop|optimization|geopy
1
473
63,019,093
Classification metrics can't handle a mix of multiclass and continuous-multioutput targets
<p>I am running a <code>BERT</code> pretrained model on a <code>multiclass</code> dataset for text classification purposes. Since it is multiclass I cannot figure out how to generate a <code>classification report</code>. The solutions I found were <a href="https://stackoverflow.com/questions/48987959/classification-me...
<p>Well, your output layer is defined as <code>out = Dense(1, activation='sigmoid')(clf_output)</code>, which means there is a single output node followed by sigmoid activation. This is meant to train on a objective of Binary classification or regression where the output values is a real number ranging between 0 and 1...
tensorflow|scikit-learn|one-hot-encoding|multiclass-classification
1
474
63,112,253
how to get last n indices in a python dataframe?
<p>i have the following dataframe:</p> <pre><code> volume index 1 65 1 55 2 44 2 56 3 46 3 75 4 64 4 64 </code></pre> <p>when i put the code <code>df.iloc[-2:]</code> .it only shows the last two rows of my dataframe. example:</p> <pre><code> ...
<p>You can slice the index after getting the unique values, then use <code>Series.isin</code>:</p> <pre><code>df[df.index.isin(df.index.unique()[-2:])] </code></pre> <p>Or</p> <pre><code>df.loc[df.index.unique()[-2:]] </code></pre> <pre><code> volume index 3 46 3 75 4 64 4 ...
python|pandas|dataframe
5
475
67,961,979
Create For Loop To Predict Next Value Over Group (Python)
<p>I am working on a project where I need to take groups of data and predict the next value for that group using a time series model. In my data, I have a grouping variable and a numeric variable.</p> <p>Here is an example of my data:</p> <pre><code>import pandas as pd data = [ [&quot;A&quot;, 10], [&quot;B&qu...
<p>You can <code>groupby</code> first and then iterate. We can store the results in a <code>dict</code> and after the loop convert it to a DataFrame:</p> <pre><code># will hold the predictions forecasts = {} # in each turn e.g., group == &quot;A&quot;, values are [10, 18, 20, 36] for group, values in data.groupby(&quo...
python|pandas|for-loop|time-series
1
476
67,923,729
Remove all alphanumeric words from a string using pandas
<p>I have a pandas dataframe column with strings that look like</p> <blockquote> <p>'2fvRE-Ku89lkRVJ44QQFN ABACUS LABS, INC'</p> </blockquote> <p>and I want to convert it to look like</p> <blockquote> <p>'ABACUS LABS, INC'.</p> </blockquote> <p>My piece code :</p> <pre><code>list1 = data_df['Vendor'].str.split...
<p>You can use regular expressions to ensure quick and elegant solution:</p> <pre><code>df2 = df['Text'].str.findall(r'((?&lt;=\s)[a-zA-Z,]+(?=\s|$))').agg(' '.join) </code></pre> <p>Let's break it down:</p> <ol> <li><a href="https://pythex.org/?regex=((%3F%3C%3D%5Cs)%5Ba-zA-Z%2C%5D%2B(%3F%3D%5Cs%7C%24))&amp;test_strin...
python|regex|pandas
3
477
67,874,850
Extrapolate data from csv using Python
<p>I have a csv file with few rows and columns of data. Now I intend to extrapolate or interpolate new data if the input values are not matching in the csv.</p> <p>Let me describe my csv as follows.</p> <pre><code>type,depth,io,mux,enr perf,1024,32,4,103.8175 perf,1024,64,4,85.643125 perf,1024,128,4,76.5559375 perf,102...
<p>To interpolate, I'll start by loading the data</p> <pre class="lang-py prettyprint-override"><code>import pandas import numpy from io import StringIO # https://stackoverflow.com/a/43312861/1164295 myfile=&quot;&quot;&quot;type,depth,io,mux,enr perf,1024,32,4,103.8175 perf,1024,64,4,85.643125 perf,1024,128,4,76.5559...
python|pandas|csv
1
478
31,820,755
how to ignore multiple entries with same index while reading data from CSV using pandas
<p>I have a csv file that looks like this:</p> <pre><code>patient_id, age_in_years, CENSUS_REGION, URBAN_RURAL_STATUS, YEAR 11511, 7, Northeast, Urban, 2011 9882613, 73, South, Urban, 2011 32190339, 49, West, Urban, 2011 32190339, 49, West, Urban, 2011 32190339, 49, West, Urban, 2011 3...
<p>I don't believe you can ignore them as they are being read, but once they have been read you can easily drop them using <code>drop_duplicates</code>. </p> <pre><code>df = pd.read_csv(filename, index_col = 0) &gt;&gt;&gt; df.drop_duplicates() patient_id age_in_years CENSUS_REGION URBAN_RURAL_STATUS YEAR 0 ...
python|csv|pandas
1
479
31,711,686
Should stats.norm.pdf gives same result as stats.gaussian_kde in Python?
<p>I was trying to estimate PDF of 1-D using <code>gaussian_kde</code>. However, when I plot pdf using <code>stats.norm.pdf</code>, it gives me different result. Please correct me if I am wrong, I think they should give quite similar result. Here's my code. </p> <pre><code> npeaks = 9 mean = np.array([0...
<p>In the row below you make pdf calculations in every peak-point along 100 datapoints with the <code>std = 0,03</code>. So you get a matrix with array with <strong>100 elements per row</strong> then you <strong>summerize</strong> it <strong>elementwise</strong>, <strong>result:</strong> <a href="https://i.stack.imgur....
python|python-2.7|pandas|scipy|probability-density
0
480
41,442,956
Get filtered row names and save it in a list
<p>I have a dataframe like this:</p> <pre><code> Area 2016-09-02 2016-09-03 2016-09-04 2016-09-05 39.TFO 1-14 6588.67 6604.03 6567.42 6421.12 40.TFO 15-28 6843.58 6929.41 6922.24 6801.98 41.TFO 29-42 3546.59 3634.46 3770.85 3813.15 ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>split</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#indexing-with-str" rel="nofollow noreferrer">indexing-with-str</a>:</p> <pre><code>print (df['A...
python|pandas|dataframe
4
481
41,559,151
Python: How does converters work in genfromtxt() function?
<p>I am new to Python, I have a following example that I don't understand</p> <p>The following is a csv file with some data</p> <pre><code>%%writefile wood.csv item,material,number 100,oak,33 110,maple,14 120,oak,7 145,birch,3 </code></pre> <p>Then, the example tries to define a function to convert those trees name ...
<p>For the second question, according to the documentation (<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html</a>), <code>{1:convert}</code> is a dictionary whose keys are column numbe...
python|python-2.7|numpy
1
482
61,437,090
Copying data from one dataframe to another with different column names
<p>I have one dataframe:</p> <pre><code>df = pd.DataFrame([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], columns=list('ABCDE')) </code></pre> <p>I need to create another dataframe by copying data from df in this format:</p> <pre><code>df2 = pd.DataFrame([[1, 2, 0], [ 3, 4, 5], [ 6, 7, 0], [ 8, 9, 10]], columns=list('PQR')) </...
<p>reshaping ur data requires getting the first two columns and concatenating with the last three columns : </p> <pre><code>a = df.iloc[:,:2].set_axis([ent for ent,_ in enumerate(a.columns)],axis=1) a 0 1 0 1 2 1 6 7 b = df.iloc[:,2:].set_axis([ent for ent,_ in enumerate(b.columns)],axis=1) b 0 ...
python-3.x|pandas|dataframe
0
483
61,555,097
Mapping text data through huggingface tokenizer
<p>I have my encode function that looks like this:</p> <pre class="lang-py prettyprint-override"><code>from transformers import BertTokenizer, BertModel MODEL = 'bert-base-multilingual-uncased' tokenizer = BertTokenizer.from_pretrained(MODEL) def encode(texts, tokenizer=tokenizer, maxlen=10): # import pdb; pdb.s...
<p>the tokenizer of bert works on a string, a list/tuple of strings or a list/tuple of integers. So, check is your data getting converted to string or not. To apply tokenizer on whole dataset I used Dataset.map, but this runs on graph mode. So, I need to wrap it in a tf.py_function. The tf.py_function will pass regular...
tensorflow|tensorflow-datasets|huggingface-transformers
6
484
61,404,032
Getting ModuleNotFoundError only if debug mode is enabled
<p>I have a Flask server which loads <code>Tensorflow</code> models on startup in an external service module.</p> <p>The problem is if debug mode is enabled, so <code>FLASK_DEBUG = 1</code>, the app crashes because it is not able to load a certain module from Tensorflow. <code>tensorflow_core.keras</code> to be precis...
<p>Apparently there is a <a href="https://github.com/pallets/werkzeug/issues/461" rel="nofollow noreferrer">bug</a> in <code>werkzeug</code> which is used by <code>flask</code> to serve <code>flask</code> apps, when running <code>flask</code> apps in debug mode with <code>python -m</code>.</p> <p>To prevent this from ...
python|tensorflow|flask
0
485
68,450,437
UNet loss is NaN + UserWarning: Warning: converting a masked element to nan
<p>I'm training a UNet, which class looks like this:</p> <pre><code>class UNet(nn.Module): def __init__(self): super().__init__() # encoder (downsampling) # Each enc_conv/dec_conv block should look like this: # nn.Sequential( # nn.Conv2d(...), # ... (2 or 3 conv layers with relu and bat...
<p>I am not sure if this is your error, but your last Convolution layer (self.dec_conv3) has looks odd. I would only reduce to 1 channel at the very last convolution and do not perform 2 Convolutions with 1 In and 1 Out channel. Also ending with a batchnorm can only produce normalized outputs, which could be far from w...
python|neural-network|pytorch|semantic-segmentation
1
486
68,743,773
How do I map a multi-level dictionary into a DataFrame series
<p>I want to map a multi level dictionary according to two columns in a DataFrame. What I have so far is this:</p> <pre><code>df = pd.DataFrame({ 'level_1':['A','B','C','D','A','B','C','D'], 'level_2':[1,2,3,1,2,1,2,3] }) dict = { 'A':{1:0.5, 2:0.8, 3:0.4}, 'B':{1:0.4, 2:0.3, 3:0.7}, 'C':{1:0.3, ...
<p>We can try <code>MultiIndex.map</code></p> <pre><code>df['mapped'] = df.set_index(['level_1', 'level_2']).index.map(pd.DataFrame(d).unstack()) </code></pre> <hr /> <pre><code> level_1 level_2 mapped 0 A 1 0.5 1 B 2 0.3 2 C 3 0.6 3 D 1 0.5 4 ...
python|pandas|dictionary
4
487
68,696,475
Why am I getting a type error for the second pice of code while the first on worked?
<p>Code:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np #generate some fake data x = np.random.random(10)*10 y = np.random.random(10)*10 print(x) #[4.98113477 3.14756425 2.44010373 0.22081256 9.09519374 1.29612129 3.65639393 7.72182208 1.05662368 2.33318726] col = np.where(x&lt;1,'k',np.wher...
<p>The &quot;first time&quot; in your code snippet, <code>x</code> and <code>y</code> are numpy arrays, created from the calls to <code>np.random.random</code>:</p> <pre><code>col = np.where(x&lt;1,'k',np.where(y&lt;5,'b','r')) </code></pre> <p>This is not the case with <code>t</code>. As some of the comments have indi...
python|numpy|types
0
488
36,674,609
How to create a function to return an equation
<p>I am trying to create the normal random variable pdf equation.</p> <p>This function would return the final computed value of pdf for a specific x.</p> <pre><code>def normpdf(x, mu=0, sigma=1): # u = (float((x-mu) / abs(sigma))) y = exp(-(float((x-mu) / abs(sigma)))*(float((x-mu) / abs(sigma)))/2) / (sqrt(2*...
<p>Don't use the <code>float</code>-function in sympy expressions:</p> <pre><code>def normpdfeqn(x, mu=0, sigma=1): return exp(-((x-mu) / abs(sigma))**2 / 2) / (sqrt(2*pi*sigma*sigma)) x = Symbol('x') print(integrate(normpdfeqn(x), (x, -inf, inf))) </code></pre>
python|python-2.7|python-3.x|numpy|scipy
1
489
36,314,255
how to make pandas.read_sql() not convert all headers to lower case
<p>I have a function that pulls tables from our a table in our SQL server into a dataframe in Python, but it forces all the column headers to be lower case. The code is as follows:</p> <pre><code>connection = pypyodbc.connect('Driver={SQL Server};' 'Server=' + server + ';' ...
<p>I think PyPyODBC does it for you:</p> <p>Here what i found in the source code of <code>PyPyODBC</code> ver. 1.3.3 lines: 28-29:</p> <pre><code>version = '1.3.3' lowercase=True </code></pre> <p>and lines 1771-1772:</p> <pre><code> if lowercase: col_name = col_name.lower() </code></pre> <p>so y...
python|sql|pandas
12
490
36,416,725
python/pandas - converting date and hour integers to datetime
<p>I have a dataframe that has a date column and an hour column. </p> <pre><code> DATE HOUR 2015-1-1 1 2015-1-1 2 . . . . . . 2015-1-1 24 </code></pre> <p>I want to convert these columns into a datetime format somethin...
<p>You could first convert <code>df.DATE</code> to datetime column and add <code>df.HOUR</code> delta via <code>timedelta64[h]</code></p> <pre><code>In [10]: df Out[10]: DATE HOUR 0 2015-1-1 1 1 2015-1-1 2 2 2015-1-1 24 In [11]: pd.to_datetime(df.DATE) + df.HOUR.astype('timedelta64[h]') Out[11]:...
python|datetime|pandas
14
491
52,983,061
How to create a list from the dataframe?
<p>I have a dataframe with coordinates x0,y0,x1,y1. I am trying to get a list of the coordinate</p> <p>datafrme is like-</p> <pre><code> x0 y0 x1 y1 x2 y2 ... 1 179.0 77.0 186.0 93.0 165.0 91.0... 2 178.0 76.0 185.0 93.0 164.0 91.0... </code></pre> <p>desired...
<pre><code>[[[y['x0'], y['y0']], [y['x1'], y['y1']], [y['x2'], y['y2']]]for x,y in df.iterrows()] </code></pre> <p>df here will be your dataframe</p> <p>the output will look like the format you described</p> <pre><code> [ [ [179.0,77.0], [186.0,93.0], [165.0,91.0 ],... ], [ [178.0,76.0 ],[185.0,93.0 ],[164.0,...
python|pandas
1
492
52,969,708
ModuleNotFoundError: No module named 'tensorflow', even when tensorflow is installed
<p>I am trying to install tensorflow for one of my machine learning projects. However, even though I have installed it, I still get this error</p> <pre><code>ModuleNotFoundError: No module named 'tensorflow' </code></pre> <p>To help illustrate this better, I have created a <code>test.py</code> file, with the followi...
<p>I fixed it! Special thanks to the folks at the Tensorflow Talk slack who helped me, especially @akofman.</p> <p>It was a combination of 2 problems:</p> <p><strong>Problem 1</strong></p> <p>It seems that one of the reasons it was failing was due to one of tensorflow's dependencies being outdated/misinstalled/somet...
python|tensorflow|failed-installation
1
493
65,861,699
Understanding the nature of merge in pandas
<p>I want to understand the <code>pd.merge</code> work nature. I have two dataframes that have unequal length. When trying to merge them through this command</p> <pre><code>merged = pd.merge(surgical, comps[comps_ls+['mrn','Admission']], on=['mrn','Admission'], how='left') </code></pre> <p>The length was different from...
<p>The &quot;issue&quot; is with duplicated merge keys, which can cause the resulting merge to be larger than the original. For a left merge you can expect the result to be in between <code>N_rows_left</code> and <code>N_rows_left * N_rows_right</code> rows long. The lower bound is in the case that both the left and ri...
python|pandas
2
494
65,541,166
Predicting purchase probability based on prior orders?
<p>Let's assume we have the following dataframe:</p> <pre><code>merged = pd.DataFrame({'week' : [0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2], 'shopper' : [0, 0, 0, 1, 1, 0, 1, 1, 2, 0, 2, 2], 'product' : [63, 80, 91, 42, 77, 55, 77, 95, 77, 98, 202, 225], 'pr...
<p>This is not an easy task. The accuracy depends on the number of the past observations. Such a small data as you share is does not give accurate solutions. However, the code below might give you an idea. As you guess, you need to find relation between the products and should use these relations. At below, I have firs...
python|pandas|model|prediction
0
495
65,587,761
KeyError: 'accuracy'
<p>I was trying to plot train and test learning curve in keras, however, the following code produces KeyError: 'accuracy' Any help would be much appreciated. Thanks.</p> <pre><code> #plotting graphs for accuracy plt.figure(0) plt.plot(history.history['accuracy'], label='training accuracy') plt.plot(history.history['va...
<p>Try adding <code>metrics=['accuracy']</code> in model.fit() as</p> <pre><code>model.fit(#all other parameters, metrics=['accuracy']) </code></pre> <p>If you have already done so, check if you have written metrics=['acc'] instead. If so, make changes to this line in your code</p> <pre><code>plt.plot(history.history['...
python|tensorflow|plot|label
2
496
65,724,063
Optimizing Cython loop compared to Numpy
<pre><code>#cython: boundscheck=False, wraparound=False, nonecheck=False, cdivision=True, language_level=3 cpdef int query(double[::1] q, double[:,::1] data) nogil: cdef: int n = data.shape[0] int dim = data.shape[1] int best_i = -1 double best_ip = -1 double ip for i in ...
<p>The operation <code>q @ X.T</code> will be mapped to an implementation of matrix-vector-multiplication (<a href="http://www.netlib.org/lapack/explore-html/d7/d15/group__double__blas__level2_gadd421a107a488d524859b4a64c1901a9.html" rel="nofollow noreferrer"><code>dgemv</code></a>) from either OpenBlas or MKL (dependi...
python|numpy|optimization|cython
2
497
65,881,093
pandas category that includes the closest greater value
<p>I have the following dataframe:</p> <pre><code>df = pd.DataFrame({'id': ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c','c','c'], 'cumsum': [1, 3, 6, 9, 10, 4, 9, 11, 13, 5, 8, 19]}) id cumsum 0 a 1 1 a 3 2 a 6 3 a 9 4 a 10 5 b 4 6 b 9 7 b 11 8 b 13 9 c 5 10 c 8 11...
<p>You can get first value greater of equal by input by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.first.html" rel="nofollow noreferrer"><code>GroupBy.first</code></a> and filtered by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.ge....
python|pandas
1
498
65,647,762
Ensure that an array has all values encoded as 1 and -1, not 1 and 0
<p>There is a 1 dimensional <code>numpy</code> array named <code>&quot;target_y&quot;</code>. My task is to ensure that <code>&quot;target_y&quot;</code> has all values encoded as <code>1</code> and <code>-1</code>, not <code>1</code> and <code>0</code> before performing logistic regression. Once I do it, I need to ass...
<p>Checkout <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow noreferrer"><code>np.all</code></a>:</p> <p>We can do some quick boolean arithmetic to check if all the values are <code>1</code> or <code>-1</code>:</p> <pre class="lang-py prettyprint-override"><code>if np.all((target_y == 1) + (...
python|arrays|pandas|list|numpy
0
499
2,433,587
vectorize is indeterminate
<p>I'm trying to vectorize a simple function in numpy and getting inconsistent behavior. I expect my code to return 0 for values &lt; 0.5 and the unchanged value otherwise. Strangely, different runs of the script from the command line yield varying results: sometimes it works correctly, and sometimes I get all 0's. ...
<p>If this really is the problem you want to solve, then there's a much better solution:</p> <pre><code>A[A&lt;=0.5] = 0.0 </code></pre> <p>The problem with your code, however, is that if the condition passes, you are returning the <em>integer</em> 0, not the <em>float</em> 0.0. From the documentation:</p> <blockquo...
python|numpy
7