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
373,000
63,173,744
Merge rows with pandas
<p>So I made a large csv file with information about car models, there are some rows like this:</p> <pre><code>101 | land rover 90 2.5 td 4X4 | 148 | 1 | 0.68 | 0.0068 | 0 | 35 101 | land rover 90 2.5 td 4X4 | 148 | 1 | 0.68 | 0.0068 | 9 | 0 </code></pre> <p>I want to merge these lines on the second column (name), the...
<p>Try this:</p> <pre><code>import pandas as pd df = pd.DataFrame([ [101,'land rover 90 2.5 td 4X4', 148, 1, 0.68, 0.0068, 0, 35 ], [101, 'land rover 90 2.5 td 4X4', 148, 1, 0.68, 0.0068, 9, 0], ], columns=[&quot;col1&quot;,&quot;col2&quot;,&quot;col3&quot;,&quot;col4&quot;,&...
python|pandas|csv
0
373,001
62,970,328
Python match two dataframes by numeric columns
<p>I have two dataframes, each has longitudes and latitudes. Df1 are small places with coordinates, and df2 are city names with coordinates of city centers. I would like to assign a city name to each location in df1, by finding the closest coordinates in df2.</p> <p><code>df1</code> looks like:</p> <pre><code>location ...
<p>We can do it with <code>numpy</code> broadcast and <code>argmin</code></p> <pre><code>s1=df1.lng.values s2=df1.lat.values idx=np.abs(s1-df2.citylng.values[:,None] + s2 - df2.citylat.values[:,None]).argmin(axis=0) df1['city']=df2.city.iloc[idx].values df1 location lng lat city 0 a 117 33 Z 1 b...
python|pandas|dataframe
3
373,002
63,123,001
Tensorflow JS transform 1d tensor into 2d tensor structured as square diagonal matrix
<p>Let's see an easy example, I have a tensor <code>[1,2]</code>. The position of <code>1</code> is <code>[0]</code>, the position of <code>2</code> is <code>[1]</code>. I want to transform this 1d tensor into 2d, where the position of</p> <ul> <li><code>1</code> would turn from <code>[0]</code> to <code>[0, 0]</code><...
<p>Assuming you need to transform the list of items into <a href="https://en.wikipedia.org/wiki/Diagonal_matrix#:%7E:text=In%20linear%20algebra%2C%20a%20diagonal,by%2D3%20diagonal%20matrix%20is" rel="nofollow noreferrer">square diagonal matrix</a>, you may use 2 nested <a href="https://developer.mozilla.org/en-US/docs/...
javascript|tensorflow
1
373,003
63,083,933
Why cant i run python program by clicking the .py file
<p>I am trying to run my program by clicking the .py file. I am able to do that in the simple program but not the one I am working on. In my program, I have many imports statements, is it because of that? when I click on the main.py file, the cmd black screen appears for a few seconds and closes itself.</p> <p>My progr...
<p>Reasons why You shouldn't execute *.py directly</p> <ol> <li>The window will immedietly close when the program is done</li> <li>you will not know if any error is present in the code</li> </ol> <p>You should probably use Command prompt or the terminal using this will give better clarity of errors</p> <p>If you believ...
python|pandas|selenium|cmd|web-applications
0
373,004
63,241,551
Extract data from Excel cell like phone, email, address, ID etc
<p>I have data as below in a single excel cell.</p> <pre><code>56. MEMBER ID 2100343-219 ZAHID BROTHERS MONTGOMERY BAZAR FAISALABAD TEL : 041-2646252 MOBILE : 0300-0321-9663180 FAX : E-MAIL : REP : HAJI MUHAMMAD ABID </code></pre> <p>I am looking for ideas on how to extract each detail and form a proper excel ta...
<p>Try the next function, please:</p> <pre><code>Function ExtractDataFromCell(x As String) As Variant Dim arr As Variant, arrfin(3) As String, i As Long, start As Long, length As Long Dim strMembID As String, strTel As String, strMob As String, strRep As String arr = Split(x, vbLf) For i = 0 To UBound(arr) ...
python|excel|vba|pandas
1
373,005
62,945,575
Python how to fix 'ValueError: attempt to get argmin of an empty sequence' on a Pandas groupby object
<p>''' I'm trying to create bins based on the 'Position' column on df.groupby('Chrom') object. I've been struggling for hours on the last part of my code.The purpose of the script is to retrieve the lowest pvalue (p) for each group of the groupby object. <strong>df_lowestP = data.loc[data.groupby('Bin_labels')['p'].id...
<p>Your <code>Bin_labels</code> is categorical type. It includes other bin with value NaN. Therefore, you got empty sequences. When you groupby <code>Bin_labels</code>, you lost original indices.</p> <p>To fix this, we have to save the original indices, sort the data by <code>Bin_labels</code> and <code>p</code>, gro...
python|pandas|pandas-groupby
2
373,006
62,977,383
Zsh error when trying to run tensorflow model training script
<p>I am trying to train a resnet model for CIFAR10 using the following repo in tensorflow: <a href="https://github.com/stanford-futuredata/dawn-bench-models/tree/master/tensorflow/CIFAR10/resnet" rel="nofollow noreferrer">https://github.com/stanford-futuredata/dawn-bench-models/tree/master/tensorflow/CIFAR10/resnet</a>...
<p>The answer is as simple as adding single quotes, such as <code>--train_data_path='cifar10/data_batch*'</code>, for all the filepaths.</p>
python|tensorflow|scripting|command-line-arguments|zsh
1
373,007
63,219,551
How to extract certain values from a string based on prefix in Python/pandas?
<p>I have a column in a pandas data frame where each value is a long text string of text. Somewhere in that text I may or may not have an object number with a certain prefix (&quot;IFL&quot; or &quot;IFN&quot;) that I need to extract and add as it's own column.</p> <p>Data looks like:</p> <pre><code>Description 12753, ...
<p>use a regex with <code>str.extract</code></p> <pre><code>df['object']= df['Description'].str.extract('((IFN|IFL)\d+-\d)')[0] print(df) Description object 0 12753, IFL12329-1, Supply Chain, (May) IFL12329-1 1 120873, [send], 7385876, (June), IFN1228-3 IFN1228-3 </cod...
python|pandas
0
373,008
63,141,890
Numpy/Pytorch generate mask based on varying index values
<p>I've been trying to do the following as a batch operation in <code>numpy</code> or <code>torch</code> (no looping). Is this possible?</p> <p>Suppose I have:</p> <pre><code>indices: [[3],[2]] (2x1) output: [[0,0,0,0,1], [0,0,0,1,1]] (2xfixed_num) where fixed_num is 5 here </code></pre> <p>Essentially, I want to make...
<p>Ok, so I actually assume this is some sort of HW assignment - but maybe it's not, either way it was fun to do, here's a solution for your specific example, maybe you can generalize it to any shape array:</p> <pre><code>def fill_ones(arr, idxs): x = np.where(np.arange(arr.shape[1]) &lt;= idxs[0], 0, 1) # This is ...
python|numpy|torch
0
373,009
63,001,581
Pruning using Pytorch on a complicated model
<p>So I am trying to use <a href="https://pytorch.org/docs/master/generated/torch.nn.utils.prune.global_unstructured.html" rel="nofollow noreferrer">torch.nn.utils.prune.global_unstructured</a>.</p> <p>I did it on a simple model and that worked. <code>model.cov2</code> or other layers and that works. I am trying to do ...
<p>Your modules are not names 'conv1' or 'conv2', you can see the names using the named_modules generator. From above, you have a 'conv_stem' which can be indexed as model.conv_stem[0] to access. You can iterate over modules to create a dict like:</p> <pre><code>parameters_to_prune = ( (model.conv1, 'weight'), ...
python|machine-learning|pytorch|google-colaboratory|pruning
0
373,010
63,240,702
Torch sum subsets of tensor
<p>if the tensor is of shape [20, 5] then I need to take 10 at a time and sum them, so result is [2,5].</p> <p>eg:<br /> shape[20,5] -&gt; shape[2, 5] (sum 10 at a time)<br /> shape[100, 20] -&gt; shape[10,20] (sum 10 at a time)</p> <p>Is there any faster/optimal way to do this?</p> <p>eg:<br /> <code>[[1, 1], [1, 2], ...
<p>I am not aware of any off the shelf solution for that.</p> <p>If having the average is enough you can use <code>nn.AvgPool1d</code> <a href="https://pytorch.org/docs/stable/generated/torch.nn.AvgPool1d.html#avgpool1d" rel="nofollow noreferrer">https://pytorch.org/docs/stable/generated/torch.nn.AvgPool1d.html#avgpool...
python|machine-learning|deep-learning|pytorch|tensor
2
373,011
63,094,633
How To Access Docker Container Files From Vscode?
<p>I am following this <a href="https://towardsdatascience.com/creating-your-own-object-detector-ad69dda69c85" rel="nofollow noreferrer">https://towardsdatascience.com/creating-your-own-object-detector-ad69dda69c85</a> to experiment with Tensorflow object detection. The tutorial does not use docker but I am trying to l...
<p>Broadly, there are four ways to accomplish this. I'm going to describe the simplest solutions first, and most complex last.</p> <ol> <li><p><strong>Bind mount the source files into the container.</strong> Bind mounts allow you to create a directory which is accessible on both the container and the host. Here's an ex...
python|docker|tensorflow|containers
1
373,012
63,061,669
Numba Slow Array Element Assignment to Variable
<p>This is a contrived test case but, hopefully, it can suffice to convey the point and ask the question. Inside of a Numba <code>njit</code> function, I noticed that it is very costly to assign a locally computed value to an array element. Here are two example functions:</p> <pre><code>from numba import njit import nu...
<p>As @PaulPanzer already has pointed out, your fast function does nothing once optimized - so what you see is basically the overhead of calling a numba-function.</p> <p>The interesting part is, that in order to do this optimization, numba must be replacing <code>np.sum</code> with its own <code>sum</code>-implementati...
python|numpy|numba
0
373,013
62,935,611
Why can't I assign an array as column of another array
<p>I have this numpy array</p> <pre><code>data = np.array([10.66252794 10.65999505 10.65745968 10.65492432 10.65239142 10.64985606 10.64732069 10.64478533 10.64225243 10.63971707 10.6371817 10.6346488 10.63211344 10.62957807 10.62704518 10.62450981 10.62197445 10.61944155 10.61690619 10.61437082]) </code></pre> <p>...
<p>You're trying to assign a column to an apparently empty array. You can only assign data of shape (20,) to any column in result if result is an array with mxn rows and columns, such that the number of rows, m = 20. Like:</p> <pre><code>result = np.zeros((20,5)) result[:,0] = data #Assigning to column 0 </code></pre>
python|numpy
1
373,014
63,232,537
Pandas string encoding when retrieving cell value
<p>I have the following Series:</p> <pre><code>s = pd.Series(['ANO DE LOS BÃEZ MH EE 3 201']) </code></pre> <p>When I print the series I get:</p> <pre><code>0 ANO DE LOS BÃEZ MH EE 3 201 </code></pre> <p>But when I get the cell element I get an hexadecimal value in the string:</p> <pre><code>&gt;&gt;&gt; s.iloc[0] '...
<p>Even though I am not really sure where the issue arised I Could solve it by using the <a href="https://github.com/avian2/unidecode" rel="nofollow noreferrer">unidecode</a> package.</p> <pre><code>output_string = unidecode(s.iloc[0]) </code></pre>
python-3.x|pandas|string
0
373,015
63,035,319
Weights not updating on my neural net (Pytorch)
<p>I'm completely new to neural nets, so I tried to roughly follow some tutorials to create a neural net that can just distinguish if a given binary picture contains a white circle or if it is all black. So, I generated 1000 arrays of size 10000 representing a 100x100 picture with half of them containing a white circle...
<p>Instead of <code>net.zero_grad()</code> I would recommend using <code>optimizer.zero_grad()</code> as it's more common and de facto standard. Your training loop should be:</p> <pre><code>for epoch in range(EPOCHS): for i in range(0, len(train_X), BATCH_SIZE): batch_X = train_X[i:i + BATCH_SIZE].view(-1, ...
python|machine-learning|neural-network|pytorch
3
373,016
63,067,345
I couldn't convert a object type column to string
<pre><code>Df['column'] xxx345xxxhgf447jfhf576 Djfnfjf5678 0000004444000000 Xxx88xxx888xxx8888xxx88 </code></pre> <p>8</p> <p>I tried</p> <pre><code>Df['column'].astype(str) Df['column'].astype('str') Df['column'].astype('|S') </code></pre> <p>Still it remains as object dtype</p>
<p>You need to assign it to the column after converting to <code>str</code></p> <pre><code>Df['column'] = Df['column'].astype('string') </code></pre> <pre><code>In [49]: df = pd.DataFrame({&quot;column&quot;:[&quot;xxx345xxxhgf447jfhf576&quot;, &quot;Djfnfjf5678&quot;, &quot;0000004444000000&quot;,&quot;Xxx88xxx888xxx8...
python|pandas
0
373,017
63,245,428
Read dataframe split by nan rows and reshape them into multiple dataframes in Python
<p>I have a example excel file <code>data1.xlsx</code> from <a href="https://www.dropbox.com/scl/fi/04zmd5bthe192nck4ovnc/data1.xlsx?dl=0&amp;rlkey=7btnc9279njrnsz0u9enlucf6" rel="nofollow noreferrer">here</a>, which has a <code>Sheet1</code> as follows:</p> <p><a href="https://i.stack.imgur.com/Le9Z8.png" rel="nofollo...
<p>Use:</p> <pre><code>#add header=None for default columns names df = pd.read_excel('./data1.xlsx', sheet_name = 'Sheet1', header=None) #convert columns by second row df.columns = df.iloc[1].rename(None) #create new column `city` by forward filling non missing values by second column df.insert(0, 'city', df.iloc[:, ...
python-3.x|pandas|dataframe|openpyxl
4
373,018
63,064,859
How to merge dictionaries in np.ndarray into one dictionary?
<p>Following my question on <a href="https://stackoverflow.com/questions/63062147/convert-dataframe-to-nested-dictionary-in-python/63062548?noredirect=1#comment111518087_63062548">Convert Dataframe to Nested Dictionary in Python</a>, I have been trying to convert a Pandas dataframe into a nested dictionary.</p> <p>Curr...
<pre><code>In [10]: dkl=np.array([{0.7863340563991272: 0.0002639915522703274}, ...: {0.7863340563991272: 0.0006863780359028511}], dtype=object) In [11]: dkl Out[11]: array([{0.7863340563991272...
python|numpy|dictionary|merge
1
373,019
63,087,420
Pivot pandas dataframe to long format with multiple layers
<pre><code>| | Var1 Var2 |------------|------|------|-----|------|------|-----| | | SPY | AAPL | MSFT| SPY | AAPL | MSFT | Date | | | | | | | | 2011-01-03 | 30 | 30 | 30 | 30 | 30 | 30 | | 2011-01-04...
<p>let's reproduce the dataframe 1st.</p> <p><strong>A:</strong></p> <pre><code> SPL AAPL MSFT 2011-01-03 30 30 30 2011-01-04 30 30 30 2011-01-05 30 30 30 </code></pre> <hr /> <p><strong>B:</strong></p> <pre><code> SPL AAPL MSFT 2011-01-03 30 30 30 2011-01-04 21 30 30 2011-01-05 30...
python|python-3.x|pandas|dataframe|pivot-table
2
373,020
63,203,424
how to replicate rows with group by in pandas
<p>I have following dataframe in pandas.</p> <pre><code> order_id name email date products prod_amt 123 Neil neil@gmail.com 2020-02-02 NaN nan 123 NaN NaN NaT ABC 120 123 NaN NaN ...
<p>From Comments: You want to group on <code>order_id</code> and fill missing values for all columns barring 'products' and 'prod_amt' columns.</p> <p>You can groupby+ffill based on <code>order_id</code> , then drop columns which you dont want to update, and pass this under <code>df.update</code>:</p> <pre><code>df.upd...
python|pandas
3
373,021
63,240,027
Tensorflow 2.3.0 CUDA Toolkit version 10.1 does not use GPU
<p>I had tensorflow 2.0 workig with my RTX2070 gpu. I did a windows update so I could use tf-nightly. Did not like it so uninstalled it and reinstalled tensorflow 2.3.0. Ran previous python code that ran fine with GPU previously but it did not use the GPU. Tried lots of stuff. Finally just started over. Reinstalled Ana...
<p>I found I can get tensorflow to recognize the GPU if in my working environment using conda I run conda install cudnn==7.6.4 which works with CUDA 10.1.0 resultant messages in anaconda prompt are:</p> <pre><code>Collecting package metadata (current_repodata.json): done Solving environment: failed with initial frozen...
python|tensorflow
8
373,022
63,087,756
How to get href text from 'a' tag with selenium
<p>I am trying to scrape a page.. But the link I need is in an href in an 'a' tag. how can I get it with selenium (or BS4)</p> <p>my code..</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys import pandas as pd from bs4 import BeautifulSoup import requests import pyautogui as ...
<p>From <a href="https://code.luasoftware.com/tutorials/selenium/get-href-of-element-with-selenium-python/" rel="nofollow noreferrer">https://code.luasoftware.com/tutorials/selenium/get-href-of-element-with-selenium-python/</a>:</p> <pre><code>el = driver.find_element_by_css_selector(&quot;a.link&quot;) if el: url ...
python|pandas|selenium|beautifulsoup
0
373,023
63,258,022
Non-OK-status: GpuLaunchKernel(...) status: Internal: no kernel image is available for execution on the device
<p><strong>I run my code on tensorflow 2.1.0 Anaconda with CUDA Toolkit 10.1 CUDNN 7.6.0 (Windows 10) and it returns a issue</strong></p> <pre><code>F .\tensorflow/core/kernels/random_op_gpu.h:232] Non-OK-status: GpuLaunchKernel(FillPhiloxRandomKernelLaunch&lt;Distribution&gt;, num_blocks, block_size, 0, d.stream(), ge...
<p>Looks like this is an issue with Python 3.8 and Tensorflow 2.3. I tried the tensorflow 2.3.0 with python 3.7, but it returns an error with python 3.7 because python38.dll (I don't remember exactly the error and i already delete the env), anyway i used python 3.7 on anaconda env and installed tensorflow 2.1.0 with pi...
tensorflow|nvidia|cudnn
4
373,024
63,094,688
Trying to catch a exception from another function
<p>I have created 2 dataframes and written a function to concat it and forced a nameerror by giving incorrect dataframes to concat and want to catch that exception in another function as shown below. But could not do that. Any Help is appreciated.</p> <pre><code>di1 = {'name':'xxxx', 'phone-no':'685985'} di2 = {'name':...
<p>The reason why it did not work is because you are passing the result of <code>conc(df1, df2)</code> to the <code>tryit</code> function. So the error occurs before <code>tryit</code> is called.</p> <p>To avoid this, you need to run <code>conc</code> function inside the <code>tryit</code>, and for that, you need to p...
python|pandas|dataframe
0
373,025
67,610,760
Last layer in a RNN - Dense, LSTM, GRU...?
<p>I know you can use different types of layers in an RNN architecture in Keras, depending on the type of problem you have. What I'm referring to is for example <code>layers.SimpleRNN</code>, <code>layers.LSTM</code> or <code>layers.GRU</code>.</p> <p>So let's say we have (with the functional API in Keras):</p> <pre><c...
<p>TL;DR Both are valid choices.</p> <p>Overall it depends of the kind of output you want or, more precisely, where do you want your output to come from. You can use the outputs of the LSTM layer directly, or you can use a Dense layer, with or without a <a href="https://keras.io/api/layers/recurrent_layers/time_distrib...
python|tensorflow|keras|deep-learning
1
373,026
67,813,366
How to make dataframe filter using .query method work with a variable?
<p>I'd like to use the .query method to filter a column in a dataframe by a variable but it won't work with a variable, only a string. Anybody know how to make it work with a variable? Thank you.</p> <pre><code>import pandas as pd var=&quot;A&quot; source = {'COL1': ['A','B','C'], 'COL2': ['D','E','F']} dfsource=...
<p>Use <code>@</code>:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd var = &quot;A&quot; source = {&quot;COL1&quot;: [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;], &quot;COL2&quot;: [&quot;D&quot;, &quot;E&quot;, &quot;F&quot;]} dfsource = pd.DataFrame(source) print(dfsource) df2 = dfsource...
python|pandas|dataframe
1
373,027
67,703,055
How to transform data frame in pandas with a category column and a value column
<p>I've got the following Data Frame:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Category</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>ID1</td> <td>typeA</td> <td>str1</td> </tr> <tr> <td>ID1</td> <td>typeB</td> <td>str2</td> </tr> <tr> <td>ID1</td> <td>typeB</td> <t...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>DataFrame.pivot_table</code></a> with convert values to lists:</p> <pre><code>df = df.pivot_table(index='ID', columns='Category', values='Value', aggfunc=list) print (df) Category...
python|pandas
2
373,028
67,612,169
Joining points to polygons in geopandas creating an empty dataframe even though overlapping on geoplot
<p>I have a text file where there are longitude and latitudes and the special IDs of the points I need to process. Let's assume text file looks like a bunch of lines like below:</p> <pre><code>-75.3530 41.830902 1 </code></pre> <p>I read this file as follows:</p> <pre><code>import pandas as pd point_df=pd.read_csv...
<p>Looking at the geometry of the polygon dataframe, it appears that the CRS is not actually EPSG:4326, whose coordinates should represent <a href="https://en.wikipedia.org/wiki/Decimal_degrees" rel="nofollow noreferrer">decimal degrees</a>.</p> <p>You will need to determine the correct CRS, which once found can be set...
polygon|point|geopandas
0
373,029
67,610,935
Is there a vectorized way to create a matrix in which each element is the the row-wise dot product of a matrix?
<p>Apologize for the vagueness in the title, I spend some time rephrasing but cannot get it very well.</p> <p>For example, I have a 2*3 matrix in Pytorch tensor</p> <pre><code>test = torch.tensor([[1, 10, 100], [2, 20, 200]]) </code></pre> <p>What I would like to have a final matrix that is</p> <pre...
<p>You can either do matrix multiplication:</p> <pre><code>test @ test.T </code></pre> <p>Or a <code>torch.einsum</code>:</p> <pre><code>torch.einsum('ij,kj-&gt;ik', test, test) </code></pre>
numpy|matrix|pytorch|vectorization
1
373,030
67,663,624
How to Create a new data frame column based upon GroupyBy Object?
<pre><code>df=pd.DataFrame({'Name':['a','a','b','b','b','c'], 'Score':[4,6,8,12,34,66]}) </code></pre> <p>gives df <a href="https://i.stack.imgur.com/KhZaA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KhZaA.png" alt="enter image description here" /></a></p> <p>I want to get my dataframe as follows...
<p>You can use:</p> <pre><code>df['Column'] = 'Score' + df.groupby('Name').cumcount().astype(str) (df.pivot(index='Name', columns='Column', values='Score') .reset_index() .rename_axis(columns=None) .rename(columns={&quot;Score0&quot;: &quot;Score&quot;}) ) </code></pre> <p>Output:</p> <pre><code> Name Score...
python|python-3.x|pandas|pandas-groupby
4
373,031
67,857,882
API return issue in Pandas with JSON
<p>I have a file for input parameter and request every row in the input column and get the first item back, then export as a csv file. My question is, the code works fine, but when the input para with special character like 'abc &amp; bbc'. It will return the second item from the JSON. How can I fix it to prevent such...
<h3>Fix</h3> <p>The value may be encoded, for the space/ampersand to be safe send, using <a href="https://stackoverflow.com/questions/1695183/how-to-percent-encode-url-parameters-in-python"><code>urllib</code></a> for example</p> <pre><code>from urllib.parse import quote print(quote(&quot;abc&amp;bbc&quot;)) # abc%...
python|json|pandas
1
373,032
67,760,118
Incorrect memory bandwidth when using TensorFlow
<p>I was wondering whether this memory bandwidth amount is correct. I have an NVDIA RTX 3090 and, in theory, it's bandwidth should be around 936.2 GB/s. However, when using TensorFlow, it appears significantly lower. Is there any limitation or is this how it should be? My current bus interface is PCIe x16 4.0</p> <p><a...
<p>871.81 gibibyte (GiB) ~= 936.1 gigabyte (GB)</p> <p>So the bandwidth reported by Tensorflow is about the same (0.1 GB/s difference) as the official specification of the card. I suspect the 0.1 difference is just rounding or precision loss somewhere.</p>
python|tensorflow|memory|gpu|hardware
0
373,033
67,745,140
Is there a way to find an integer offset that when added to every value in one numpy array maximizes the amount of matches it has to another array?
<p>For example say I had 2 lists:</p> <pre><code>a = np.array([1, 3, 5, 6, 8, 9]) b = np.array([103, 104, 106, 107, 108, 109]) </code></pre> <p>The value I would want to add would be ~100 to add to list <em>a</em> as an offset to match as many possible values to list <em>b</em> given the offset.</p> <p>My current solut...
<p>Equivalent to your answer without loops:</p> <pre><code>o = np.bincount(np.ravel(b[:,None] - a[None,:])).argmax() l = len(np.intersect1d(b, (a + o))) </code></pre> <pre><code>&gt;&gt;&gt; (o, l) (98, 4) </code></pre> <p><em>Updated according to comments of <a href="https://stackoverflow.com/users/15964777/alexander-...
python|arrays|numpy
1
373,034
67,659,509
How to row-normalize a feature matrix? Broadcasting error
<p>I have a feature matrix that I want to row normalize.</p> <p>This is what I have done based on min-max scaling and I am getting an error. Can anyone help me with this error.</p> <pre><code>a = np.random.randint(10, size=(4,5)) s=a.max(axis=1) - a.min(axis=1) np.amax(a,axis=1) print(s) (a - a.min(axis=1))/(a.max(axi...
<p>Try to work with transposed matrix:</p> <pre class="lang-py prettyprint-override"><code>b = a.T m = (b - b.min(axis=0)) / (b.max(axis=0) - b.min(axis=0)) m = m.T </code></pre> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; a array([[2, 3, 2, 8, 3], # min=2 -&gt; 0, max=8 -&gt; 1 [3, 3, 9, 2, 1...
python|numpy|normalization|array-broadcasting
2
373,035
67,627,298
Regex to remove 1. texts within parenthesis 2.numbers
<p>I can't seem to find the right regex for what I need. My data frame contains the following countries:</p> <pre><code>Switzerland17, Iran (Islamic Republic of), China, Hong Kong Special Administrative Region </code></pre> <p>I would like 17 to be removed from Switzerland and all text within parenthesis to be removed....
<p>You can use</p> <pre class="lang-py prettyprint-override"><code>Energy['Country'] = Energy['Country'].str.replace(r&quot;\s*\([^()]*\)|\d+&quot;, &quot;&quot;, regex=True) </code></pre> <p>See the <a href="https://regex101.com/r/tU7AUO/1" rel="nofollow noreferrer">regex demo</a>.</p> <p>If you also need to remove op...
python|regex|pandas
1
373,036
68,002,025
Nesting columns under new headers in a DataFrame
<pre><code>stocks= ['Apple','Raytheon','Amazon'] df = pd.DataFrame(data=[[10,11,12,13,5,2],[5,6,7,7,7,1]], columns=['2020-12-31','2019-12-31','2020-09-26','2019-09-28','2020-01-01','2019-01-01'], index=['cash','inventory']) </code></pre> <p>I have this list of stocks and their balance sheets in...
<p>Try scaling the <code>stocks</code> list up with <a href="https://numpy.org/doc/stable/reference/generated/numpy.repeat.html#numpy-repeat" rel="nofollow noreferrer"><code>np.repeat</code></a> then <code>zip</code> and use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.from_tupl...
python|pandas|dataframe
1
373,037
67,647,299
AttributeError: module 'torch' has no attribute 'rfft' with PyTorch
<p>I am getting an error using a code that should work according to the <a href="https://raw.githubusercontent.com/photosynthesis-team/piq/master/examples/image_metrics.py" rel="nofollow noreferrer">documentation</a>. The goal is to calculate the Feature Similarity Index Measure (FSIM) using the <code>piq</code> Python...
<p>The latest version of pytorch implements all fast fourier functions in the module torch.fft, apparently piq rely on an older version of pytorch, so if you want to run piq consider downgrading your pytorch version, for example:</p> <pre><code>pip3 install torch==1.7.1 torchvision==0.8.2 </code></pre> <p><a href="htt...
python|python-3.x|image|image-processing|pytorch
3
373,038
67,701,249
Calculate age in days from date column based availability actual date birth - else consider tentative DOB column - pandas
<p>I have df as shown below</p> <p>df:</p> <pre><code>ID Actual_DOB Tentative_DOB 1 NaN 2002-01-01 2 2020-06-23 2020-01-01 3 NaN NaN 4 2018-06-29 NaN </code></pre> <p>About df:</p> <p><code>Actual_DOB</code> - Actual date of birth,</p> <p><code>T...
<p>With your shown samples, could you please try following. Using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer"><code>fillna</code></a> along with <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html" rel="nofollow no...
python-3.x|pandas|dataframe
3
373,039
67,662,862
Number of Consecutive values in with index Numpy Python
<p>The code down below calculates the maximum number of times consecutive positive values <code>Cons_Pos_results</code>, negative values <code>Cons_Neg_results</code>, zero values <code>Cons_Zero_results</code>. I am trying to implement a piece to the code to the already existing code where it shows the indexes of wher...
<p>You can take advantage of the fact that the d array has non-zero values at the beginning and end of each found sequence. When the distance between two such non-zero values is equal to the count, you have found the desired indexes:</p> <pre><code>import numpy as np def count_consecutive(arr, sign): sign_dic = {...
python|arrays|numpy|indexing|max
0
373,040
67,816,556
How to group two items with two dates and get durations in pandas?
<p>I usually work with data look like this <code>{'id': '1', 'start_date': '2012-04-8', 'end_date': '2012-08-06'}</code> but now I have something very different. I have items of items where each two-element represents the one item</p> <pre><code> data = [ {'id': '1', 'field': 'end_tmie', 'value': '2012-08-06'},...
<p>Create DataFrame constructor first, then <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>DataFrame.pivot</code></a> with rename columns and for duration convert subtract columns with convert timedetas to days by <a href="http://pandas.py...
python|pandas|numpy
2
373,041
67,713,391
How to add space between words and punctuation in a column?
<p>I have a column (string) in a dataframe with multiple spaces between words and punctuation.<br /> I need to:</p> <ol> <li>Add space between punctuation</li> <li>Remove duplicated spaces</li> </ol> <p>Punctuation I am looking for is <code>/+-</code>.</p> <p>My dataframe:</p> <pre><code>col A 'this/is a+ string' 'this...
<p>The way I solved this is in two steps : first, add space between pontuation, then check to see if there are any continuous spaces. For first step I used a function called <code>punctuation_space</code> to pass as &quot;repl&quot; argument to <code>re.sub()</code>.</p> <pre><code>import re def punctuation_space(matc...
python|pandas|dataframe
0
373,042
67,966,217
calculating size of a given node based on an edgelist in pandas
<p>I've got a tabular dataset that is basically an edgelist and a series of nodes that represent an orgchart. The fields are name of employee, their manager's name and whether or not that employee is a manager themselves or not (1/0)</p> <p>The data (df) is as follows:</p> <pre><code>df: ID Full Name Manager Name m...
<p>Seems like a network problem:</p> <p>Here's one way to solve:</p> <ol> <li>Convert the <code>dataframe</code> to a <code>network graph</code></li> <li>Find the <code>largest network</code> in a <code>NetworkX</code> graph.</li> <li>Evaluate the <code>size</code></li> </ol> <pre><code># pip install networkx import ne...
python|pandas
0
373,043
67,631,932
How do I display only the keys of a dataframe as the xticks of a plot, in pandas?
<p>I have a dataframe with keys, formed from the concatenation of several dataFrames and I want to make a plot that has the <code>key</code> elements alone as the <code>xtickslabel</code>, but the default <strong>index</strong> numbering shows up alongside the keys, as the xtickslabel. The xticklabels are now tuples <s...
<p>Using the for statement, save the first item from each index into the list and pass it over to the parameter in <code>set_xticklabels</code>.</p> <pre class="lang-py prettyprint-override"><code># Get the first value of each tuple. indexList = [item[0] for item in alldata.index] </code></pre> <p>indexList:</p> <pre><...
python|pandas|dataframe
0
373,044
67,645,369
Python plotting from for loop
<p>How do I plot the aqr[i] values on the y-axis and the [30,60] interval on the x-axis?</p> <p>I have tried the following code:</p> <pre><code>arr = np.random.randint(100, size=1000) arq = np.zeros(31) for i in range(31): for num in arr: if num == 30+i : arq[i] += 1 plt.plot (arq[i]) ...
<p>You are trying to plot from inside the loop, I think you need to plot the data after the construction of the <code>arq</code> array:</p> <pre><code>arr = np.random.randint(100, size=1000) arq = np.zeros(31) for i in range(31): for num in arr: if num == 30+i : arq[i] += 1 plt.rcParams[&...
python|arrays|numpy|matplotlib|plot
1
373,045
67,812,297
Installing geffnet with pip
<p>I used a google colab notebook to run a certain model. It required me to install geffnet like this.</p> <pre><code>!pip -q install geffnet </code></pre> <p>How can I install geffnet locally?</p> <p><br />I tried the line below but I get an error when trying to get efficientnet_b7. <br />&quot;RuntimeError: Unknown m...
<p>Were your other python installing commands work properly? Try with a version likethis,</p> <p>pip install geffnet==0.9.0</p> <p>Still not working,try to use Pytorch instead of Colab, sometimes issue may be fixed</p>
python|pip|pytorch
1
373,046
67,778,290
How to add padded rows of 0 to a pandas dataframe?
<p>I have a df in the following form</p> <pre><code>import pandas as pd df = pd.DataFrame({'col1' : [1,1,1,2,2,3,3,4], 'col2' : ['a', 'b', 'c', 'a', 'b', 'a', 'b', 'a'], 'col3' : ['x', 'y', 'z', 'p','q','r','s','t'] }) col1 col2 col3 0 1 a x 1 1 b y 2 1 c z 3 2 a p 4 2 ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unstack.html#pandas-series-unstack" rel="noreferrer"><code>unstack</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="noreferrer"><code>reindex</code></a> + <a href=...
python|pandas
6
373,047
67,929,593
Pytorch Unable to download Dataset
<p>I am currently trying to use WikiTest103 dataset from the pytorch torchtext module. When I try to run the below code, I get the error as:</p> <pre><code>from torchtext.datasets import WikiText103 X_train= WikiText103() print(X_train.shape) </code></pre> <p>Error:</p> <pre><code>Traceback (most recent call last): F...
<p>I had the same issue, I solved it by upgrading <code>torchtext</code> to version <code>0.11.0</code> with:</p> <pre><code> pip install torchtext --upgrade </code></pre>
python|pytorch
0
373,048
67,839,089
Getting Samples of Clusters in Pandas
<p>I have a dataset in a pandas dataframe that contains a list of names and the cluster they belong to. In total there are over 1,000 different clusters. I'm looking to create 4 samples containing 100 of the clusters with no overlaps of the clusters between them. Also keep in mind that the number of names in each clust...
<p>Use <code>np.random.choice</code> with <code>replace=False</code> to select the 400 non-overlapping unique clusters and then you can <code>array_split</code> to create the groups of 100 from that. There are tons of ways to then split the data, but here I'll just map a unique ID back to the original DataFrame based o...
python|pandas|dataframe|cluster-analysis|sample
0
373,049
67,804,103
calculate a value in a row based on before and after rows in pandas
<p>I have the following dataframe:</p> <pre><code> p l w s_w v 1 1 1 1 2 1 1 2 1 2 1 1 3 0 5 1 1 4 1 5 1 1 5 1 5 2 1 1 1 1 2 1 2 0 2 2 1 3 0 3 2 1 4 0 4 2 1 5 1 5 2 1 6 1 4 </code></pre> <p>i want to have a new column where in each row if the value of s_w is 1, its value is...
<p>Idea is filtered rows with <code>1</code> and use <code>rolling sum</code> with shift values for correct align:</p> <pre><code>s = df.loc[df['s_w'].eq(1), 'v'] df['c_s'] = s.rolling(2).sum().shift().add(s.iloc[::-1].rolling(2).sum().shift()) print (df) p l w s_w v c_s 0 1 1 1 1 2 NaN 1 1 1 2...
python|python-3.x|pandas|dataframe
1
373,050
67,694,883
How to check that all gradients weights are zeros in PyTorch?
<p>I want to know how to check all PyTorch neural network gradient weights to see if they are zero or not whether to continue training or not.</p> <p>This may seem to be like <a href="https://stackoverflow.com/questions/63962561/pytorch-how-to-check-if-some-weights-are-not-changed-during-training">PyTorch: How to check...
<p>You can check the parameters are all zero like so:</p> <pre class="lang-py prettyprint-override"><code>for p in model.parameters(): if not p.all(): ... </code></pre>
python|pytorch
0
373,051
67,622,769
I'm trying to create separate bar charts for 5 categorical variables in a dataframe using pandas
<p>I have a data frame that contains 4 columns of data. Each of these columns is a character variable containing 5 different values ( i.e. column1 contains the values A,B,C,D or E . column2 contains the values EXCELLENT , VERY GOOD, GOOD, AVERAGE, and POOR. columns 3 and 4 are similar.</p> <p>I'm trying to get a se...
<p>Simply set up matplotlib subplots with number of rows and columns. Then in loop, assign each column bar plot to each <code>ax</code>:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt ... fig, axes = plt.subplots(figsize=(8,6), ncols=1, nrows=CharacterVarDF.shape[1]) for col, ax i...
python|pandas
0
373,052
67,787,156
AttributeError: Layer mnist_model_35 has no inbound nodes. Tensorflow keras subclassing API
<p>I'm doing keras subclassing with the mnist dataset. I was able to make it with <code>Sequantial</code> and <code>Functional</code> api's. But now when i call <code>model.fit()</code> on my subclass i get this error:</p> <pre class="lang-py prettyprint-override"><code>AttributeError: Layer mnist_model_35 has no inbou...
<p>You are lacking the input_shape on your first layer:</p> <pre class="lang-py prettyprint-override"><code>class MNISTModel(keras.Model): def __init__(self): super().__init__() self.flatten_layer = keras.layers.Flatten(input_shape=(28, 28)) self.dense_1 = keras.layers.Dense(64, activation='...
python|tensorflow|keras|neural-network|subclassing
1
373,053
67,683,766
Convert cardinal wind directions to degrees
<p>I have a Pandas dataframe like below with cardinal wind directions :</p> <pre><code>| X | +----------+ |N | |NE | |NNE | |SSE | |WSW | +----------+ </code></pre> <p>Question is how can I convert the wind directions to degrees and store in a dataframe/excel ?</p>
<p>Firstly create a dictionary:</p> <pre><code>d={'N':0, 'NNE':22.5,&quot;NE&quot;:45,&quot;ENE&quot;:67.5, 'E':90,'ESE':112.5, 'SE':135,'SSE':157.5, 'S':180,'SSW':202.5, 'SW':225,'WSW':247.5, 'W':270,'WNW':292.5,'NW':315,'NNW':337.5, 'N':0,'North':0,'East':90,'West':270,'South':180} </code></pre> <p>Finally use <code>...
python-3.x|pandas|dataframe
2
373,054
67,698,616
what does the function iloc do in the iris dataset?
<p>Can someone explain what the bolded portions of this code. I have read the documentation for pandas and sklearn and it is still a bit hard to wrap my mind around it. I am wanting to modify this for my own data and would like to understand this a bit more.<br/></p> <pre><code>X = df.iloc[0:100, **[0,1]**].values plt....
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.values.html" rel="nofollow noreferrer">.values</a> is only returning the values of the data frame with the axis labels removed.</p> <p>.iloc uses integer-location based indexing.</p> <p>The <a href="https://pandas.pydata.org/pandas-...
python|pandas|matplotlib|scikit-learn
1
373,055
67,778,321
Which month has the highest median for maximum_gust_speed out of all the available records
<p>Which month has the highest median for maximum_gust_speed out of all the available records. Also find the respective value</p> <p>The data set looks like below</p> <pre class="lang-none prettyprint-override"><code>Day Average temperature (°F) Average humidity (%) Average dewpoint (°F) Average barometer (in) ...
<p>You can try this way:</p> <pre><code>#Convert day column values to datetime df['Date'] = pd.to_datetime(df['Day'],format = '%d/%m/%Y') #Convert a new column month_index df['month_index'] = df['Date'].dt.month #Group the dataframe by month &amp; then find the median for max gust speed max_gust_month = df.groupby(['...
python|python-3.x|dataframe|pandas-groupby
0
373,056
68,021,168
How Can I join the points of a plot if the data is not totally complete?
<p>I'm trying to join the points of a plot with at least 70 subplots, since it is not a scatter (because I can't use it since they are not series), I've tried marker = 'o-', but doesn't work. The data is in the format %mm-%yy, there are at least 6 different months (as a date column), and not for every column (Fund name...
<p>The solution was the following:</p> <pre><code>df.interpolate().plot(subplots = True, figsize = (20,120), layout = (24,3),marker='o', legend = True) </code></pre> <p>Adding interpolate() fix the error of NaN without delating data</p>
python|pandas|join|plot|subplot
0
373,057
67,942,135
How do I separate this dataframe column by month?
<p><a href="https://i.stack.imgur.com/cPBmx.png" rel="nofollow noreferrer">A few rows of my dataframe</a></p> <p>The third column shows the time of completion of my data. Ideally, I'd want the second row to just show the date, removing the second half of the elements, but I'm not sure how to change the elements. I was ...
<p>Extracting just the date and ignoring the time from the datetime column can be done by changing the formatting of the column.</p> <pre><code>df['date'] = pd.to_datetime(df['date']).dt.date </code></pre> <p>To the second part of the question about creating a new dataframe that is filtered down to only contain rows be...
python|pandas
0
373,058
67,974,409
Pandas function which returns all subseries of a window length
<p>I know that pandas has the function <code>df.rolling()</code> where you can do operations on moving windows of subseries. However, is there a function to simply return the subseries instead of a window object in <code>df.rolling()</code>?</p> <p>For example, a series <code>[1,2,3,4,5,6,7,8,9]</code> with window leng...
<p>I'm going to write Nk03's comment in an answer here so it's more visible.</p> <p>The new numpy version 1.20.0 has a function, and I can use</p> <pre><code>np.lib.stride_tricks.sliding_window_view(ts, window_shape=m) </code></pre> <p>The API page is here: <a href="https://numpy.org/devdocs/reference/generated/numpy.l...
python|pandas
0
373,059
67,790,661
Image display issue, Neural Style Transfer
<p>I am attempting to read in my own images in python following the tensorflow <a href="https://www.tensorflow.org/tutorials/generative/style_transfer" rel="nofollow noreferrer">Neural Style Transfer</a> tutorial and when displaying them they look nothing like the original image. Can someone please explain why this is?...
<p>Normalize the image, divide the values of your input image, which usually range from 0-255, by 255 so the images are in range of 0-1</p>
python|tensorflow|opencv|matplotlib|python-imaging-library
0
373,060
67,903,102
Getting marketcap from yahoo finance
<p>I have a very long list of stocks for which I'd like to get the market cap</p> <p>say I have the following stocks stored as a list</p> <pre><code> test = ['A', 'AA', 'AA-W', 'AAAB', 'AAAG', 'AAAGY', 'AAAIF', 'AAALF', 'AAALY', 'AAAP', 'AAARF', 'AABA', 'AABB', 'AABC', 'AABNF', 'AABVF', 'AAC', 'AAC', 'AAC-U', '...
<p>Actually, your code works, albeit with errors. Simple reason - many tickers don't correspond to any known stocks. My result for your code is as follows:</p> <pre><code> A 44845838336 Name: marketCap, dtype: int64 AA 6901355520 Name: marketCap, dtype: int64 Error with: AA-W Error with: ...
python|pandas|yahoo-finance|algorithmic-trading|quantitative-finance
0
373,061
67,769,076
Perform an action from a condition for a Python Dataframe
<p><em><strong>I have the following dataframe:</strong></em></p> <pre><code>import pandas as pd import re df = pd.DataFrame ({'example': ['ACETATO MOLOCUATO']}) </code></pre> <p><strong>The condition is that if the string ends in &quot;ATO&quot; I will choose only the first three words. The way I planted it is as follo...
<p>Input data:</p> <pre><code>&gt;&gt;&gt; df example 0 W1 W2 W3 ACETATO MOLOCUATO 1 NOTHING TO DO HERE </code></pre> <p>Filter and apply:</p> <pre><code>mask = df[&quot;example&quot;].str.endswith(&quot;ATO&quot;) # condition df.loc[mask, &quot;example&quot;] = df.loc[mask, &quot;examp...
python|regex|pandas|if-statement
1
373,062
67,713,308
limit pandas .loc method output within a iloc range
<p>I am looking for a maximum value within my pandas dataframe but only within certain index range:</p> <pre><code>df.loc[df['Score'] == df['Score'].iloc[430:440].max()] </code></pre> <p>This gives me a pandas.core.frame.DataFrame type output with multiple rows. I specifically need the the index integer of the maximum ...
<p>If you just want the index:</p> <pre class="lang-py prettyprint-override"><code>i = df['Score'].iloc[430:440].idxmax() </code></pre> <p>If you want to get the row as well:</p> <pre class="lang-py prettyprint-override"><code>df.loc[i] </code></pre> <p>If you want to get the first row in the entire dataframe with that...
python|pandas
0
373,063
67,797,829
Jupyter "ImportError: Unable to import required dependencies: numpy:"
<p>I installed anaconda3 and python 3.9 Looks like anaconda3 is running with python 3.8. When i installed first my jupyter on anaconda3 was working, but i did some changes in path/pythonpath and after that i am getting error on jupyter but it works fine on visual studio. So far i have tried</p> <ol> <li>Installing and ...
<p>You can enter <code>pip uninstall pandas</code> first, Then enter <code>pip uninstall numpy</code>. These two step is to uninstall two modular. Ater that,you can enter <code>pip install pandas</code> and <code>pip install numpy</code> to reload two modular. That's how I solved the problem I just met</p>
python|numpy|jupyter-notebook
0
373,064
67,888,708
Shape rank problem with Tensorflow model as soon as I include BiLSTM layers
<p>I'm having a problem with developing a NN model with <strong>tensorflow 2.3</strong> that appears as soon as I include BiLSTM layers into the model. I've tried a custom model, but this is one from the Keras documentation page and it is also failing.</p> <ul> <li>It cannot be a problem with input shapes, as this happ...
<p>I found the problem and so I'm answering my own question.</p> <p>There is a setting in Keras that specifies the way of working with (and supossedly affecting only) image data.</p> <ul> <li><p><strong>Channels Last</strong>. Image data is represented in a three-dimensional array where the last channel represents the ...
python|tensorflow|keras|deep-learning
1
373,065
67,901,735
Groupby two columns and comparison of rows of one column
<p>I am working with groupby but i dont want to lose other columns which are not included in groupby such as i have a df:</p> <pre><code>id date name item price unit store 1 1/1/2020 abc apples 200 Fruits BigB 1 1/2/2020 abc apples 100 Fruits BigB 1 1/3/2020 abc ...
<h2>Approach</h2> <pre><code>m = df[['id','name','item']].duplicated() df['flag'] = df.eval('price &gt; price.shift() and @m').astype(int) df['start'] = df['price'].where(~m | df['flag']).ffill() </code></pre> <h2>Explanation</h2> <p>Considering the columns <code>id</code>, <code>name</code> and <code>item</code> iden...
python|pandas|dataframe|pandas-groupby
1
373,066
67,894,800
Deleting the last x amount of indexes in an Numpy Array Python
<p>How could I write a function that deletes the last X amount of indexes within a numpy array without using a for loop?</p> <pre><code>to_be_deleted_indexs= 4 A = np.array([2,3,55,6,7,3,2,5,6,7,11]) </code></pre> <p>expected output:</p> <pre><code>[2,3,55,6,7,3,2] </code></pre>
<p>You can use the <code>resize</code> method <em>as long as</em> <code>A</code> does not share memory with any other array:</p> <pre><code>A.resize(A.shape[0] - to_be_deleted_indexs) #array([ 2, 3, 55, 6, 7, 3, 2]) </code></pre>
arrays|python-3.x|numpy|indexing
0
373,067
67,828,225
What is the best data structure to represent arbitrary hierarchical data?
<p>What would the best data structure to represent/read in hierarchical data (such as a folder/file layout) that has arbitrary amounts of children? I have seen N-ary trees and tries, k/d-ary heap etc... However it seems like you need to at least know the maximum amount of children per node to have in each of these stru...
<p>To demonstrate what I mean about self-describing, here is a <em>very simple example</em> that uses <code>.visititems()</code> to recursively visit every HDF5 object in the hierarchy. Modify to reference your file in the <code>h5py.File()</code> call, and you can see the output. You will get 2 lists with group and da...
python|pandas|data-structures|hdf5|h5py
0
373,068
67,617,536
Polygon to binary mask
<p>I've made a polygon using shapely.geometry, then put it into a geopandas dataframe. I've made an array with the same size as the polygon zone</p> <p>How can I turn this polygon into a binary mask, so I can shape my array as a polygon too?</p> <p>Thanks for your time.</p>
<p>I figured it out. Not the most efficient method but it worked.</p> <p>First I make a mask on the grid, with False on data that is not in the polygon (using contains method). Second I multiply the array by that mask, then take 0 as NaNs.</p> <p>Here is an example of my code :</p> <pre><code># g is anarray with flatte...
python|pandas|geopandas|shapely
0
373,069
67,973,931
Unable to run .bat file with python code: ImportError: Unable to import required dependencies: numpy:
<p>I'm using Anaconda. I created an environment called ENGINEERING. In than environment I installed python 3.6, pandas 1.1.3, spyder 3.3.6, numpy 1.19.2, and many more. The base environment has these packages also but not necessarily the same version. Within the ENGINEERING env I created a python script in Spyder that ...
<p>You will need to upgrade/change your base Python &amp; numpy version installations to match those specified (3.6, 1.19.2). I had the same issue and same situation as OP (write/dev program in a virtual Spyder environment &quot;spyder-env&quot;, then automate .py file with WTS). I tried copying over &amp; running the ...
python|numpy|batch-file
1
373,070
67,802,878
Why do my FFT plots have these horizontal lines?
<p>I'm new to Python and signal processing, and I'm having a problem with FFT.</p> <p>I'm supposed to analyze a set of data and find the modulation frequencies from it. I wrote a basic FFT script to do this, and the output looked kinda weird. It does show the peaks like a normal FFT graph. However, for each line it has...
<p>Answer: The graph look like that because of the order of the fft calculation output: it starts with 0 Hz (more details presented here: <a href="https://numpy.org/doc/stable/reference/generated/numpy.fft.fftfreq.html" rel="nofollow noreferrer">https://numpy.org/doc/stable/reference/generated/numpy.fft.fftfreq.html</a...
python|numpy|fft|dft
2
373,071
67,694,950
Reshape pandas dataframe from column to unique index
<p>I'm trying to reshape my dataframe, in which I want the <code>Person</code> to the be index, however how do I make it so the index is unique? I don't know want duplicates in my Index.</p> <pre><code>df = pd.DataFrame({'Person':['Paul','Paul','Paul','John','John','Mia'],'Score':[24,23,54,64,89,56],'Type':['A','C','F...
<p>If you just wanna remove the duplicate values from the index use:</p> <pre><code>df = df.set_index('Person') df.index = np.where(df.index.duplicated(), '', df.index) </code></pre>
python|python-3.x|pandas
1
373,072
67,979,841
Pandas : Valid regex doesn't seem to work with str.extract on dataframe
<p>I have this csv file with data about the presidents of usa. I'm stuck where I have a column (<code>Age atstart of presidency</code>) which has both Age at start of presidency and date of start of presidency concatenated. So i came up with a regex that separates them both and i works (tested on regex101) and when tes...
<p>found the solution, as @Psidom pointed out, I copied the data from the preview window from the link i posted and pasted it in a new csv file and imported it. Ran the same code on it and it magically worked. I still do not get the cause of the issue but it is solved.</p>
python|regex|pandas|dataframe|csv
0
373,073
31,697,873
Is it possible to use variable name in imread? Basic issue in Python
<p>My problem is really quite simple.</p> <p>I have a 100 images on my computer, those images are called 1.ppm 2.ppm and so on until 100.ppm</p> <p>I want to read each image to a variable using imread, and then perform a few operations. I want to do the exact same thing to all of the images.</p> <p>My question is th...
<p>Like this:</p> <pre><code>for i in range(1,100): X=io.imread('/home/oria/Desktop/more pics/%s.ppm' %(i)) </code></pre> <p>Or, like this:</p> <pre><code>for i in range(1,100): X=io.imread('/home/oria/Desktop/more pics/'+str(i)+'.ppm') </code></pre> <p>Go ahead and read the article on <a href="https://docs...
python|loops|numpy
1
373,074
32,121,381
label size in panda plot (scatter_matrix)
<p>How can I set the label size in a pandas plot? </p> <p>In normal plot I do <code>plt.xlabel('a', size=20)</code> </p> <pre><code>In [76]: from pandas.tools.plotting import scatter_matrix In [77]: df = DataFrame(randn(1000, 4), columns=['a', 'b', 'c', 'd']) In [78]: scatter_matrix(df, alpha=0.2, figsize=(6, 6...
<p>The return of <code>scatter_matrix()</code> is a number of axis, therefore, there is no easy way to set the font size in one pass (except override it using <code>plt.rcParam</code>, such as <code>plt.rcParams['axes.labelsize'] = 20</code> for changing the label size), and it has to be set one by one, such as: <code>...
python|pandas
11
373,075
32,020,374
Export pandas DataFrame to LaTeX and apply formatters by row
<p>I want to export some DataFrames to LaTeX but these DataFrames have lots of columns, but not that many items. The solution is to display the table transposed. I know about pandas' <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.transpose.html" rel="noreferrer">transpose</a>, but I wan...
<p>I came up with this:</p> <pre><code>for key in df.columns.values: if key in formatters: df[key] = df[key].apply(formatters[key]) print df.to_latex() </code></pre> <p>This is pretty much equivalent to</p> <pre><code>print df.to_latex(formatters=formatters) </code></pre> <p>and works with transposed Da...
python|pandas|latex
2
373,076
31,908,956
Numpy conditional multiply data in array (if true multiply A, false multiply B)
<p>Say I have a large array of value 0~255. I wanted every element in this array that is higher than 100 got multiplied by 1.2, otherwise, got multiplied by 0.8.</p> <p>It sounded simple but I could not find anyway other than iterate through all the variable and multiply it one by one.</p>
<p>If <code>arr</code> is your array, then this should work:</p> <pre><code>arr[arr &gt; 100] *= 1.2 arr[arr &lt;= 100] *= 0.8 </code></pre> <p><strong>Update:</strong> As pointed out in the comments, this could have the undesired effect of the first step affecting what is done in the second step, so we should instea...
python|arrays|numpy
7
373,077
31,722,226
Length-1 Arrays and Python Scalars Via plt.text
<p>I'm trying to use plt.text to plot temperature values at their associated lat/lon points on a plot.</p> <p>After reviewing the plt.text documentation, it appears that the plotted value (third arg) has to be a number and that the number has to be a whole number, NOT a number with decimals.</p> <p>Below is the code ...
<p>I was able to achieve plotting data values only by using the following code:</p> <pre><code>for i in range(len(temp)): plt.text(x[i], y[i], temp[i], va="top", family="monospace") </code></pre> <p>Result:</p> <p><a href="https://i.stack.imgur.com/VNj7c.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur...
python|arrays|numpy|matplotlib|scipy
1
373,078
41,539,193
Pandas: apply function pairwise to a dataframe and a panel
<p>In the context of finance, suppose there is a dataframe of asset weights and a panel of daily covariance matrix: </p> <pre><code>w = pd.DataFrame({'Date':pd.to_datetime(['2016-01-01','2016-01-02','2016-01-03']),'A1':[0.3,0.1,0.1],'A2':[0.4,0.4,0.4]}).set_index(['Date']) covar = [[[0.000087,0.000017],[0.000087,0.000...
<p><strong><em>option 1</em></strong><br> rewrite <code>portVar</code></p> <p>pass entire panel to the function being applied and use <code>xs</code> to get the appropriate cross section for that particular date's weight. The date is in the <code>name</code> attribute.</p> <hr> <pre><code>def portVar(w, sigma): ...
pandas|covariance|finance|portfolio
2
373,079
41,522,264
convert R percentage equation to pandas
<p>Hello I am trying to convert this function to pandas as I am not familiar with R </p> <pre><code>sum(data_file$finished_race_date &gt;= 0, na.rm = TRUE)/sum(data_file$signup_race_date &gt;= 0, na.rm = TRUE) </code></pre> <p>I am trying to figure out what percentage of runners finished the race </p>
<p>If need divide sum of <code>True</code> values in 2 boolean masks comparing by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.notnull.html" rel="nofollow noreferrer"><code>notnull</code></a>:</p> <pre><code>100 * data_file.finished_race_date.notnull().sum()/data_file.signup_race_date.n...
python|pandas
1
373,080
41,604,484
CNN Object Localization Preprocessing?
<p>I'm trying to use a pretrained VGG16 as an object localizer in Tensorflow on ImageNet data. In their paper, the group mentions that they basically just strip off the softmax layer and either toss on a 4D/4000D fc layer for bounding box regression. I'm not trying to do anything fancy here (sliding windows, RCNN), jus...
<p>Localization is usually performed as an intersection of sliding windows where the network identifies the presence of the object you want.</p> <p>Generalizing that to multiple objects works the same.</p> <p>Segmentation is more complex. You can train your model on a pixel mask with your object filled, and you try t...
machine-learning|tensorflow|computer-vision|neural-network|conv-neural-network
0
373,081
41,325,166
plot.ly Bar plot axis labels
<p>I am trying to plot a Bar plot of a pandas df column.</p> <pre><code>df[z1z2].head() MN-SW_TO_MN-SE 562 IA-2_TO_MN-SE 345 MN-SW_TO_MN-WC 259 MN-SW_TO_MN-SW 184 ND_TO_MN-NW 163 Name: z1z2, dtype: int64 In [126]: data = [Bar(y=df['z1z2'].value_counts()[0:50])] iplot(data) </code></pre> <p>Note:...
<p>You can pass your categorical x-values directly to Plotly. In the example below the first column contains the categories (<code>x=df.iloc[:,0]</code>).</p> <pre><code>import string import pandas as pd import plotly plotly.plotly.sign_in('username', 'api_key') data = [[c, i] for i, c in enumerate(string.ascii_uppe...
python|pandas|visualization|plotly
1
373,082
41,493,177
Pandas multiply dataframes with multiindex and overlapping index levels
<p>I´m struggling with a task that should be simple, but it is not working as I thought it would. I have two numeric dataframes A and B with multiindex and columns below:</p> <pre><code>A = A B C D X 1 AX1 BX1 CX1 DX1 2 AX2 BX2 CX2 DX2 3 AX3 BX3 CX3 DX3 Y 1 AY1 BY1 CY1 DY1 ...
<h2>Proposed approach</h2> <p>We are talking about <code>broadcasting</code>, thus I would like to bring in <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="noreferrer"><code>NumPy supported broadcasting</code></a> here.</p> <p>The solution code would look something like this -</p> <pre>...
python|pandas
8
373,083
41,641,505
Read formatted data from part of a file fast (Gmsh mesh format)
<p>I maintain <a href="https://github.com/nschloe/meshio" rel="noreferrer">a little Python package</a> that converts between different formats used for mesh representation à la</p> <p><a href="https://i.stack.imgur.com/yuqfZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yuqfZ.png" alt="enter image descript...
<p>Here's a somewhat weird implementation based on NumPy:</p> <pre><code>f = open('foo.msh') f.readline() # '$MeshFormat\n' f.readline() # '2.2 0 8\n' f.readline() # '$EndMeshFormat\n' f.readline() # '$Nodes\n' n_nodes = int(f.readline()) # '8\n' nodes = numpy.fromfile(f,count=n_nodes*4, sep=" ").reshape((n_nodes,4)) ...
python|numpy|io|mesh
6
373,084
41,607,155
You must feed a value for placeholder tensor 'Placeholder' with dtype float
<p>I'm a newer to tensorflow, I really don't know how to solve the problem.</p> <p>The code is like:</p> <ol> <li><p>Feed the train with values:</p> <pre><code>sess.run(train_op, feed_dict={images: e, labels: l, keep_prob_fc2: 0.5}) </code></pre></li> <li><p>Use the value in CNN:</p> <pre><code>x = tf.placeholder(t...
<p>Some questions</p> <p>first<br> why you use <code>sess = tf.InteractiveSession()</code> and <code>with tf.Session() as sess:</code> at same time, just curious</p> <p>second what is your placeholder name <code>x</code> or <code>images</code>?<br> if name is <code>x</code>, <code>{images: x_data...}</code> won't fee...
python|tensorflow
13
373,085
41,555,612
Tensorflow imprecise timeouts
<p>I've been testing out the the timeout functionality for sess.runs (applied to a convolutional neural network), and it seems like the timeouts aren't very precise. </p> <p>For example, if I set the timeout to be 800 ms, there might be a 1-2 second delay before the timeout exception is triggered. This sort of leads m...
<p>The cancellation and timeout mechanism in TensorFlow was only designed to cancel a small number of <strong>blocking</strong> operations, in particular: <a href="https://www.tensorflow.org/api_docs/python/io_ops/queues#QueueBase.dequeue" rel="nofollow noreferrer">dequeuing</a> from an empty queue, <a href="https://ww...
tensorflow
1
373,086
41,319,868
'NoneType' error after applying .copy() to a panda dataframe
<p>I am using the Titanic dataset for a project. I first created a dataframe with </p> <pre><code>titanic_df = pd.read_csv("titanic_data.csv") </code></pre> <p>and applied a few changes (fillna and so on).</p> <p>Now I'd like to drop a few columns in that dataframe, but to avoid affecting my previous work I want to ...
<p>when you used <code>inplace=True</code> you made the change to the return value of <code>copy()</code> in place and returned <code>None</code>.</p> <p>Also note that <code>drop</code> returns a copy and therefore, the <code>copy</code> method is unnecessary.</p> <p>To fix your problem, don't use <code>inplace=True...
python|pandas|dataframe
2
373,087
41,251,068
Using regex to remove unwanted end of a string
<p>I'm struggling a little with some regex execution to remove trailing extraneous characters. I've tried a few ideas that I found here, but none are quite what I'm looking for.</p> <p>Data looks like this (only one column of data):</p> <pre><code>City1[edit] City2 (University Name) City with a Space (University N...
<p>If you always know the bracket characters that will come first you can do:</p> <p>Create data</p> <pre><code>df=pd.DataFrame({'names':['City1[edit]', 'City2 (University Name)', 'City with a Space {University Name}']}) </code></pre> <p>Then replace everything ...
python|regex|pandas
3
373,088
41,240,936
Replacing specific characters in python list
<p>I have a list named <code>university_towns.txt</code> which has a list as follows:</p> <pre><code> ['Alabama[edit]\n', 'Auburn (Auburn University)[1]\n', 'Florence (University of North Alabama)\n', 'Jacksonville (Jacksonville State University)[2]\n', 'Livingston (University of We...
<p>You may use <code>regex</code> along with <em>list comprehension</em> expression as:</p> <pre><code>import re new_list = [re.match('\w+', i).group(0) for i in my_list] # match for word ^ ^ returns first word </code></pre> <p>where <code>my_list</code> is the original <code>list</code> mentioned...
python|string|algorithm|pandas
1
373,089
41,333,216
python, apply function to dataframe indexed by id and timestamp on each feature column
<p>Hi guys i have a dataframe with 5 columns:</p> <p>ID (integer) | TIME (integer) | humidity | temperature | pressure</p> <p>ID = room<br> TIME = unixtimestamp seconds<br> humidity/temperature/pressure = sensor values</p> <p>what i need....</p> <p>i want to execute a filter (signal.lfilter) on humidity/temperature...
<p>It's not super clean, but try the following. Is this the operation you're after with the <code>signal.lfilter</code> function?</p> <p>Edit: Whoops, forgot about the time requirement. Just running <code>df.sort_values(['ID', 'TIME'], ascending=True)</code> before the operations below should do the trick.</p> <pre><...
python|pandas|multidimensional-array|filter|apply
1
373,090
41,453,083
why does get_tensor_by_name require appending a port to the tensor name
<p>I know that when getting a tensor by name that I must append an output index</p> <p>ex)</p> <pre class="lang-py prettyprint-override"><code>graph.get_tensor_by_name('example:0') </code></pre> <p>Where :0 is the output index. But why is this necessary?</p> <p><a href="https://www.tensorflow.org/api_docs/python/fr...
<p>In TensorFlow, names are given to <a href="https://www.tensorflow.org/api_docs/python/framework/core_graph_data_structures#Operation" rel="noreferrer"><code>tf.Operation</code></a> objects (which correspond to nodes in the <a href="https://www.tensorflow.org/api_docs/python/framework/core_graph_data_structures#Graph...
python|tensorflow
11
373,091
41,397,901
Python: Extracting cell values based on value in another column
<p>I need to extract strings from D column (yellow) whenever there is # in a row in F column (blue). I am a beginner and was trying Pandas and openpyxl for this task, but with no luck. Which one would be better for this?<br> I want them stored so I can access them later.<br> Also, extracting the numbers from H column...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="nofollow noreferrer"><code>read_excel</code></a> first and it seems first <code>7</code> rows has to be skipped:</p> <pre><code>df = pd.read_excel('LTE_KPIs_up.xlsx', skiprows=7) #print (df) </code></pre> <...
python|excel|pandas|indexing|openpyxl
3
373,092
41,554,540
How to set image shape in Python for Tensorflow prediction?
<p>I'm dealing with the following error:</p> <pre><code>ValueError: Cannot feed value of shape (32, 32, 3) for Tensor 'Placeholder:0', which has shape '(?, 32, 32, 3)' </code></pre> <p>The placeholder is set to: <code>x = tf.placeholder(tf.float32, (None, 32, 32, 3))</code></p> <p>And the image (when running <code>p...
<p>The placeholder <code>x</code> in your program represents a <strong>batch</strong> of 32x32 (presumably) RGB images, for which predictions will be computed in a single step. If you want to compute a prediction on a single image&mdash;i.e. an array of shape <code>(32, 32, 3)</code>&mdash;you must reshape it to have a...
python|tensorflow
1
373,093
41,386,878
Multi-dimension dynamic rnn with tensorflow
<p>In tensorflow's dynamic_rnn function, I was surprised by the output shape and I was hoping someone could help improve my understanding of the RNN cells. </p> <p>For example, if the input is defined as: </p> <pre><code>x = tf.placeholder(tf.float32, [110, seq_size, input_dim]) </code></pre> <p>where seq_size = 5 a...
<p>You can think of a sequence as a sentence and an input as a word. The sequence length is the number of words in the sentence, which is also the number of hidden nodes in LSTM; each input/word is corresponding to one hidden node, which maps the input to one output. This is why the number of output is seq_size (5).</p...
tensorflow|recurrent-neural-network
1
373,094
41,603,821
Writing a dictionary in python
<pre><code>from random import randint import threading import numpy as np def gen_write(): threading.Timer(10.0, gen_write).start() with open("pins.npy", "w") as f: f.close() data = {} for x in range(5): pin = randint(99, 9999) pins_for_file = pin ...
<p>First, instead of opening the file inside the loop, you could just open it outside the loop.<br> Second, you don't need to explicitly close the file you open with a <code>with</code> statement, that's one of the point of using <code>with</code>.<br> So the code modification I envision is the following: </p> <pre><...
python|numpy|dictionary
0
373,095
41,271,997
Finding the index of a numpy array in a list
<pre><code>import numpy as np foo = [1, "hello", np.array([[1,2,3]]) ] </code></pre> <p>I would expect</p> <pre><code>foo.index( np.array([[1,2,3]]) ) </code></pre> <p>to return </p> <pre><code>2 </code></pre> <p>but instead I get</p> <blockquote> <p>ValueError: The truth value of an array with more than one e...
<p>The reason for the error here is obviously because numpy's ndarray overrides <code>==</code> to return an array rather than a boolean.</p> <p>AFAIK, there is no simple solution here. The following will work so long as the <br><code>np.all(val == array)</code> bit works.</p> <pre><code>next((i for i, val in enumer...
python|arrays|list|numpy
14
373,096
27,814,743
How to read CSV file with of data frame with row names in Pandas
<p>I have a CSV file (<code>tmp.csv</code>) that looks like this:</p> <pre><code> x y z bar 0.55 0.55 0.0 foo 0.3 0.4 0.1 qux 0.0 0.3 5.55 </code></pre> <p>It was created with Pandas this way:</p> <pre><code> In [103]: df_dummy Out[103]: x ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_table.html"><code>index_col</code></a> parameter:</p> <pre><code>&gt;&gt;&gt; pd.io.parsers.read_csv("tmp.csv",sep="\t",index_col=0) x y z bar 0.55 0.55 0.00 foo 0.30 0.40 0.10 qux 0.00 0.30 5....
python|pandas
21
373,097
27,502,406
Convert Pandas DatetimeIndex to fractional day of year
<p>Is there an easy way to convert a <code>DatetimeIndex</code> to an array of day of years, including a fraction for the hour, minute, etc. components?</p> <p>For example, converting <code>pd.date_range("2014-01-01 00:00", periods=4, freq="12H")</code> should give me <code>[1.0, 1.5, 2.0, 2.5]</code>.</p>
<p>This requires 0.15.0 for the Timedelta functionaility. This will have full precision of your dates.</p> <pre><code>In [19]: s Out[19]: &lt;class 'pandas.tseries.index.DatetimeIndex'&gt; [2014-01-01 00:00:00, ..., 2014-01-02 12:00:00] Length: 4, Freq: 12H, Timezone: None In [21]: s-s[0] Out[21]: &lt;class 'pandas...
python|datetime|pandas
3
373,098
27,827,651
Getting indices of elements that are in another list in numpy
<p>I have two numpy arrays and I'd like to get the indices of all elements in the first array that are in the second array. For example:</p> <pre><code>import numpy as np x = np.array([0,1,1,2,3,4,5,5]) y = np.array([1,3]) # want to get np.array([1,2,4]) </code></pre> <p>If <code>y</code> were a scalar, I could just...
<p>You can <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="noreferrer"><code>numpy.where</code></a> with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html" rel="noreferrer"><code>numpy.in1d</code></a>:</p> <pre><code>&gt;&gt;&gt; np.where(np.in1d(x, y)) (a...
python|arrays|numpy
8
373,099
27,575,452
Trilinear Interpolation - Vectorising without Scipy
<p>I am looking to vectorize this piece of code but don't know where to begin. There has been another answer on this site answering a similar question to mine: <a href="https://stackoverflow.com/questions/6427276/3d-interpolation-of-numpy-arrays-without-scipy">3D interpolation of NumPy arrays without SciPy</a> , but I ...
<p>Here is some idea to remove the for loop call of <code>np.interp()</code>. </p> <p>Since <code>t_2_index</code> and <code>time</code> don't change in the loop, you can use <code>np.interp()</code> to calculate the linear mix parameter of <code>V</code>. Here is the code to confirm the idea:</p> <pre><code>y = np.s...
numpy|3d|scipy|interpolation
0