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
361,700
62,945,213
Trying to match values in one data frame to values in another data frame (python)
<p>I currently have a dataframe A consisting of a column (code1) of country codes such as CA, RU, US etc. I have another dataframe B that has 3 columns where the first column has all possible country codes, the second has a longitude value and the third has a latitude value. I'm trying to loop through the A, get the fi...
<p>use <code>pd.merge</code> and specify the <code>left_on</code> column to merge on as well as the <code>right_on</code> column, since the two column you want to merge have different column names. Then, <code>.drop</code> the excess column that you don't need.</p> <pre><code>A = pd.merge(A,B,how='left',left_on='code1'...
python|pandas|dataframe|country-codes
0
361,701
63,129,981
The most efficient way of finding indices of element(s) in numpy 2D array
<p>Out of huge matrix in numpy (currently <code>1000x1000</code>) only a few elements are relevant for me. Say these elements are <code>&gt;1000</code> in value and others are way lower. I need to find indices of all such elements in the most efficient way because the search will be repeated often and the matrix can be...
<p>You can try this, the filter directly included in the numpy array!</p> <pre><code>import numpy as np arr = np.array([998, 999, 1000, 1001]) filter_arr = arr &gt; 999 newarr = arr[filter_arr] print(filter_arr) print(newarr) </code></pre> <p><a href="https://www.w3schools.com/python/numpy_array_filter.asp" rel="n...
python|arrays|numpy
0
361,702
63,193,247
Pandas dataframe - create multiple columns based on multiple conditions calculations
<p>I am learning python so please excuse me if my question is too basic. Actually I need to create multiple columns on my pandas dataframe based on different conditions. I can do this in R using data.table. I am pasting below my code with sample data from R-</p> <pre><code>library(data.table) cr=4 phi=1.85 colA &lt;-...
<p>You cannot use min to directly compare 2 columns. It needs to be applied at the element level. Can you please check if this breakdown does the job..</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.uniform(0,100,size=(100, 6)), columns=list(['colA','colB','colC','colD','SALES','VALU...
python|r|pandas|numpy|data.table
1
361,703
62,917,785
Too many indices in numpy array when calculating size
<pre><code>def reg_interval_size(self, prediction, y, significance): idx = int(significance * 100 - 1) prediction = prediction[:, idx] prediction_size = prediction[:, 1] - prediction[:, 0] return prediction_size </code></pre> <p>This is the error I am getting when applying the function:</p> <p...
<p><code>idx</code> is an <code>int</code> so <code>idx[0]</code> makes no sense.</p> <p><code>prediction</code> is a 2d array so <strong>you can't</strong> access it with 3 indices like this:</p> <pre class="lang-py prettyprint-override"><code>prediction = prediction[:, :, idx] # error </code></pre> <p>I don't know wh...
python|numpy|indexing
1
361,704
63,239,374
Does anyone see any possible way to slice this? (python)
<p>I've been trying to speed up some numpy arrays in Python and I know for loops are really bad so you should slice them but I just can't see anyway to slice this. Maybe there's some smart trick? I am pretty inexperienced in this so would appreciate any help!</p> <pre><code> def propind(in1, in2): return in1...
<p>Just wanted to give the solution I got using the comments to this question. It is about 20 times faster so thank you!</p> <pre><code>tempH0s2 = [] for z in range(M): tempL = np.zeros([M,N,N]) tempL[z] = 1 tempH0s2.append(tempH0s*tempL) tempH0s3 = np.stack(tempH0s2, axis=2) ret = np.reshape(tempH0s3, (...
python|numpy|numpy-slicing
1
361,705
67,680,215
Converting non numeric columns to numeric columns
<p>My imports are:</p> <pre><code>import pandas as pd import numpy as np from pandas.api.types import is_numeric_dtype </code></pre> <p>I created a pandas dataframe (named df) that looks like this:</p> <pre><code> state initial_temp final_temp 0 Cold 48.0 88.1 1 hot 80.7 30.0...
<p>You could do</p> <pre><code>df.transform(pd.to_numeric, errors = 'ignore') </code></pre>
python|python-3.x|pandas|dataframe|numpy
1
361,706
68,010,844
Out-file a CSV-Like instead of TXT
<p>I have some piece of code that write a txt file like this:</p> <pre><code>f2.csv,val,2 f2.csv,val,5 f2.csv,new,234 f2.csv,new,432 f2.csv,old,3 f2.csv,old,437 f2.csv,val,2 f2.csv,val,9 </code></pre> <p>But I'd like to have something like this:</p> <pre><code>f2.csv,val,new,old f2.csv,2,234,3 f2.csv,5,432,437 f2.csv,2...
<p>Pandas has a built in writer:</p> <pre class="lang-py prettyprint-override"><code>df.to_csv(open(&quot;f2.csv&quot;,&quot;w&quot;), header=True) </code></pre>
python|pandas
1
361,707
67,892,894
Observing varying model performance in different machines while training an activity recognition model
<p>I am finding that my model has different performance (train and validation accuracy) on two separate machines (Laptop and PC). The code and data used are the same.</p> <p>So:</p> <ul> <li>Train and Validate on Laptop (val accuracy ~91%)</li> <li>Moved the same jupyter notebook and data to PC via (manually via Box, w...
<p>First and foremost, in order to obtain the same results you should use the same <code>tf</code> and <code>keras</code> library versions in both machines; it would be impossible to track the changes otherwise. Secondly, the GPU computation generally uses different data sizes and it impacts accuracy; you can either u...
keras|deep-learning|tensorflow2.0|activity-recognition|mobilenet
0
361,708
67,881,744
Update certain columns of dataframe with other dataframe based on condition in python
<p>I am trying to update certain columns of one dataframe with other dataframe based on condition but it is not updating. Could you please tell me what I am doing wrong?</p> <p>Example:</p> <pre><code>The below columns need to be updated- column_list = ['File Name', 'File Type', 'Published Date', 'Program Name', 'Link'...
<p>There are duplicates in <code>PDF_File_Name</code>, so for me working <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.combine_first.html" rel="nofollow noreferrer"><code>DataFrame.combine_first</code></a> for replace missing values with convert to default index by <a href="http://...
python|python-3.x|pandas|dataframe
0
361,709
67,817,583
How can I create a datframe column which counts the occurrence of each value in anopther column?
<p>I am trying to add a column to my dataframe, which will hold a value which represents the number of times a unique value has appeared in another column.</p> <p>For example , I haver the following dataframe:</p> <p>Date|Team|Goals|</p> <p>22.08.20|Team1|4|</p> <p>22.08.20|Team2|3|</p> <p>22.08.20|Team3|1|</p> <p>22.0...
<p>TRY:</p> <pre><code>df['Count'] = df.groupby('Team').cumcount().add(1) </code></pre> <p>OUTPUT:</p> <pre><code> Date Team Goals Count 0 22.08.20 Team1 4 1 1 22.08.20 Team2 3 1 2 22.08.20 Team3 1 1 3 22.09.20 Team1 4 2 4 22.09.20 Team3 5 2 </code></...
pandas|dataframe
2
361,710
67,849,179
Results mismatch between convolution algorithms in Tensorflow/CUDA
<p>I'm training a convolutional autoencoder and noticed this warning:</p> <pre><code>Tensorflow: 2.5-gpu from pip Driver: 460.80 cuda: 11.2.2 cudnn: 8.1.1 XLA: Yes Mixed precision: Yes </code></pre> <pre><code>26/27 [===========================&gt;..] - ETA: 0s - loss: 1.0554 - pre_dense_out_loss: 0.9997 - de_conv1dtra...
<p>This could be the effect of accumulation with a low precision (e.g. FP16) data type.</p> <p>Which data types are you using? And which algorithms?</p> <p>From: <a href="https://docs.nvidia.com/deeplearning/cudnn/developer-guide/index.html" rel="nofollow noreferrer">https://docs.nvidia.com/deeplearning/cudnn/developer...
tensorflow|deconvolution
0
361,711
67,795,442
how to split a mixed data column to separate int and str columns in python
<p>so I have a column which has data like mileage and data as 24.5 km 11.3 km .I want to separate integer value and string value and make 2 diff columns. how to do it.?</p> <p>I have mileage</p> <pre><code> 11.5km 21.4km </code></pre> <p>I want integer</p> <pre><code> 11.5 21.4 STR...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>df[[&quot;integer&quot;, &quot;string&quot;]] = df[&quot;mileage&quot;].str.extract(pat=r&quot;(\d+\.?\d*)(.*)&quot;) print(df) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override"><code> mileage integer string 0 11.5km 11.5 km 1 ...
python|pandas|dataframe
2
361,712
67,605,913
Python: Concatenation of elements in different matrices
<p>I have some issues in trying to concatenate strings in two different matrices between each other. Example:</p> <ul> <li>The first matrix is dat defines as follows</li> </ul> <pre><code> dat = array([['data 1:1 ', 'data 2:2 '], ['data 1:1 ', 'data 2:2 '], ['data 1:1 ', 'data 2:2 ']], dtype='&lt;U9') </c...
<p>This question contains mistakes only you can fix, such as missing brackets in the result.</p> <p>Moreover, I don't understand why use numpy instead of native Python lists or pandas in this case.</p> <hr /> <p>Not arguing with that, here is a solution</p> <pre><code>import numpy as np dat = np.array([['data 1:1 ', '...
python|string|numpy|matrix|concatenation
0
361,713
67,704,772
edit columnnames that include duplicate special characters
<p>I have some column names that include two question marks at different spaces e.g. 'how old were you? when you started university?' - i need to identify which columns have two question marks in. any tips welcome! thanks</p> <p><strong>data</strong></p> <pre><code>df = pd.DataFrame(data={'id': [1, 2, 3, 4, 5], 'how ol...
<p>One idea with list comprehension:</p> <pre><code>df = df[[c for c in df.columns if c.count(&quot;?&quot;) &lt; 2]] print (df) id how old were you when you finished university? 0 1 1 1 2 2 2 3 ...
python|pandas|duplicates|columnname|drop
4
361,714
67,913,076
How can i get the location of certain rows by using the index of a series with Pandas?
<p>I want to use the high_accidents(Pandas Series) index which is a list of cities to get the rows of the dataframe that match the df[&quot;City&quot;] value.</p> <pre><code>count_city = df[&quot;City&quot;].value_counts() high_accidents = count_city[count_city &gt;= 1000] new_df = df.loc[df[&quot;City&quot;].values ...
<p>Here df['City'].values will give your an array of cities and high_accidents.index is of pandas.index type. So the error message is shown that length must match to compare.</p> <p>To get your desired result you can modify the code as following:-</p> <pre><code>count_city = df[&quot;City&quot;].value_counts() high_ac...
python|pandas|dataframe
0
361,715
67,878,928
Gradient with respect to the parameters of a specific layer in Pytorch
<p>I am building a model in pytorch with multiple networks. For example let's consider <code>netA</code> and <code>netB</code>. In the loss function I need to work with the composition <code>netA(netB)</code>. In different parts of the optimization I need to calculate the gradient of <code>loss_func(netA(netB))</code> ...
<p>The gradients are properties of <em>tensors</em> not <em>networks</em>.<br /> Therefore, you can only <code>.detach</code> a tensor.</p> <p>You can have different optimizers for each network. This way you can compute gradients for all networks all the time, but only update weights (calling <code>step</code> of the r...
neural-network|pytorch|gradient-descent|detach
1
361,716
67,856,595
How to convert sentence to category?
<p>I'm working on NLP problem. The target column contain 5 types of sentences:</p> <pre><code>&quot;Extremely Positive&quot;, &quot;Positive&quot;, &quot;Neutral&quot;, &quot;Negative&quot;, &quot;Extremely Negative&quot; </code></pre> <p>I want to convert those sentences to number [5,4,3,2,1].</p> <p>Is there a build ...
<p>You probably want to use an Encoder from the sklearn library.</p> <p>LabelEncoder can be used to transform categorical data into integers:</p> <pre><code> from sklearn.preprocessing import LabelEncoder label_encoder = LabelEncoder() x = ['Positive', 'Neutral', 'Positive', 'Negative'] encoded = label_e...
python|tensorflow|keras
5
361,717
67,776,511
How to assign ids to sets of coordinates? -python
<p>I am working with a <code>GeoDataFrame (gdf)</code> containing a road network (Lines) that looks like the following:</p> <pre class="lang-py prettyprint-override"><code> id_road speed geometry 0 1 50.00 LINESTRING (a_lon a_lat, b_lon b_lat) 1 2 50.00 LINESTRING (b_lon b_lat, c_lon c_lat) 2 ...
<p>This is a scrappy implementation, but let me know if it helps:</p> <p>To begin you likely need some way of transforming coordinate pairs to a list of pairs from which you can index:</p> <pre><code>coordinate_pairs = df['geometry'].apply(lambda g: [g.coords[0], g.coords[-1]]) coordinates = [p for pair in coordinate_p...
python|geopandas
1
361,718
67,929,356
How to convert the table in pandas?
<p>I have the dataframe below:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame( [ ['A11', 'One', 'Person1', 'Yes'], ['A11', 'One', 'Person2', 'No'], ['B22', 'Two', 'Person3', 'Yes'], ['B22', 'Two', 'Person1', 'No'], ['B22', 'Two', 'Person4', 'No'], ...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>from string import ascii_uppercase l = ( df.groupby([&quot;Code&quot;, &quot;Name&quot;]) .agg(list) .apply(lambda x: list(zip(x[&quot;Person&quot;], x[&quot;Valid&quot;])), axis=1) ) data = [] for a in l: data.append({}) for i, (b, c) in...
python|pandas|dataframe
1
361,719
67,942,180
PyTorch - Tensors multiplication along new dimension
<p>Sorry if already asked, but I can't find the words to look for on Google.</p> <p>Let's say I have a tensor <code>t1</code> of size <code>[a,b]</code> and a tensor <code>t2</code> of size <code>[c]</code>.</p> <p>How can I output a tensor <code>t3</code> of size <code>[a,b,c]</code>, so that:</p> <pre><code>t3[0, :, ...
<p>Using <a href="https://pytorch.org/docs/stable/generated/torch.kron.html" rel="nofollow noreferrer">torch.kron</a> will give a tensor a x b*c, then using <a href="https://pytorch.org/docs/stable/tensors.html#torch.Tensor.reshape" rel="nofollow noreferrer">torch.Tensor.reshape</a> could map to a tensor a x b x c :</p...
python|pytorch
2
361,720
67,678,869
Collapse Pandas rows to elliminate NaN entries
<p>Let's consider the following DataFrame</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>A</th> <th>B</th> <th>C</th> <th>D</th> </tr> </thead> <tbody> <tr> <td>tom</td> <td>10.0</td> <td>NaN</td> <td>NaN</td> <td>NaN</td> </tr> <tr> <td>tom</td> <td>NaN</td> <td>15.0</td> <t...
<p>You can <code>.groupby</code> + <code>.transform</code> (where you &quot;move&quot; the values up). Then drop rows which contain all <code>NaN</code> values:</p> <pre class="lang-py prettyprint-override"><code>print( df.set_index(&quot;Name&quot;) .groupby(level=0) .transform(lambda x: sorted(x, key=lamb...
python|pandas|dataframe|numpy|collapse
2
361,721
67,985,204
Python: Converting a list of strings into pandas data-frame with two columns a and b, corresponding to odd and even strings respectively
<p>I have this kind of input as below. It is a list of strings, every odd string is a number starting with MR and every even string is some mixed text. I need to convert this list of strings to a pandas data-frame which strictly has two columns, but because some of the MR numbers are present several times paired with d...
<p>try:</p> <pre><code>df=pd.DataFrame(lst) #here lst is your list...Don't assign anything to list function c=df.index%2==0 #checking if the index is even bcz the values are in consicutive order out=pd.concat((df.loc[c,0].str.strip(':').reset_index(drop=True),df[~c].reset_index()),axis=1).drop('index',1) #seperating...
python|pandas
1
361,722
67,955,410
How to plot element count and add annotations
<p>I was working &quot;globalterrorism.csv&quot; and wanted to visualise terrorist attacks in each country. I did this for the same:</p> <pre><code>len(gt['country_txt'].unique()) </code></pre> <p>And I got 205 unique countries.</p> <pre><code>labels = gt.groupby([&quot;country_txt&quot;]).count()['eventid'].index x ...
<ul> <li>Using the data from <a href="https://data.world/data-society/global-terrorism-data" rel="nofollow noreferrer">data.world: Global Terrorism Data</a>. Select a file to download, and then choose the option to <strong>Download all files</strong>. Extract the files into the default folder name. <ul> <li>The total d...
python|pandas|matplotlib|bar-chart
0
361,723
67,784,745
pandas-dev installation (How to install Pandas 1.3.0)
<p>I've seen that on Pandas version 1.3.0.dev0+1779.gdcc2a8f801 there is a new implemented method (read_xml) and I would like to use it. The problem is that I have not found a way to install a development version of Pandas. i am currently using Python3 and pip and have tried from its source repository (<a href="https:/...
<p>You can use pip:</p> <pre><code>pip install git+https://github.com/pandas-dev/pandas.git </code></pre> <p>If you are using a jupyter notebook, just run:</p> <pre><code>!pip install git+https://github.com/pandas-dev/pandas.git </code></pre> <p>it will install the last version:</p> <pre><code>Collecting git+https://gi...
python|pandas
2
361,724
67,872,803
Huggingface SciBERT predict masked word not working
<p>I am trying to use the pretrained SciBERT model (<a href="https://huggingface.co/allenai/scibert_scivocab_uncased" rel="nofollow noreferrer">https://huggingface.co/allenai/scibert_scivocab_uncased</a>) from Huggingface to predict masked words in scientific/biomedical text. This produces errors, and not sure how to ...
<p>As the error message tells you, you need to use <a href="https://huggingface.co/transformers/model_doc/auto.html?highlight=automodelformaskedlm#transformers.AutoModelForMaskedLM" rel="nofollow noreferrer">AutoModelForMaskedLM</a>:</p> <pre class="lang-py prettyprint-override"><code>from transformers import pipeline,...
python|bert-language-model|huggingface-transformers
1
361,725
68,000,761
PyTorch DDP: Finding the cause of "Expected to mark a variable ready only once"
<p>I'm extending a complex model (already with <code>DistributedDataParallel</code> with <code>find_unused_parameters</code> set to <code>True</code>) in PyTorch on <code>detectron2</code>.</p> <p>I've added a new layer generating some additional output to the original network - initially, that layer was frozen (<code>...
<p>With the help of the PyTorch community, I moved forward (see the original discussion <a href="https://discuss.pytorch.org/t/finding-the-cause-of-runtimeerror-expected-to-mark-a-variable-ready-only-once/" rel="nofollow noreferrer">here</a>).</p> <p>I updated my PyTorch to 1.9.0 (was using 1.7.0 before). Now I the err...
pytorch
1
361,726
67,855,643
What is the meaning of HIGH CORRELATION in pandas profiling?
<p>I'm trying to use <code>pandas profiling</code> on titanic dateset. Under the overview section there are some features with caption &quot;<code>HIGH CORRELATION</code>&quot;</p> <ul> <li>I know what is the meaning of correlation, but the caption doesn't tell which feature is correlated to this feature ?</li> <li>So ...
<p>If you click on the <code>Warnings</code> tab it will tell what other feature the features are correlated with as seen in this <a href="https://pandas-profiling.github.io/pandas-profiling/examples/master/census/census_report.html" rel="nofollow noreferrer">example</a>. Can see the same thing in the <a href="https://...
pandas|pandas-profiling
1
361,727
67,613,525
How to select the specific class in cifar-10
<p>I would like to know how to select the specific class in cifar-10. For example, I want 7, &quot;horse&quot; class in cifar-10. And I wrote the below code. But the obtained data is not what I want because it's wrong shape.</p> <p>Please enlighten me on the specifics.</p> <pre class="lang-py prettyprint-override"><cod...
<p>For the slicing, do something like:</p> <pre><code>X_train = X_train[filter[0], ...] Y_train = Y_train[filter[0], ...] </code></pre> <p>And the shapes would be</p> <pre><code>X_train shape: (5000, 32, 32, 3), Y_train shape: (5000, 1) </code></pre>
python|numpy
0
361,728
67,945,968
How to apply TF-IDF on pandas column based on colon delimiter in text data
<p>I have a column in pandas dataframe where I capture a visitor's journey. I want to implement TF-IDF on this text column. Here is the sample data -</p> <pre><code>df = pd.DataFrame({'id': [10, 11, 12] , 'pagename': ['home:cart:checkout:buy:home','home:cart:cart:home','home:account:home']}) </code><...
<p>I think I figured it out -</p> <p>I had to use a custom tokenizer to solve this problem -</p> <p>Here is my code that works now -</p> <pre><code>def tokens(x): return x.split(':') from sklearn.feature_extraction.text import TfidfVectorizer tfidf_vect= TfidfVectorizer( tokenizer=tokens ,u...
python|pandas|tfidfvectorizer
1
361,729
67,908,812
Issues with regex to match JSON-like string with optionally missing [] brackets around lists
<p>The following string is a typical example of the format of JSON input strings that I need to convert to a pandas DataFrame. My attempted work flow is to:</p> <ol> <li>split String into List (see String below, note this represents an individual row)</li> <li>Convert each list to a dictionary</li> <li>Convert dictiona...
<p>Your string is a valid JSON without braces. Add the braces and use <code>json.loads</code> to get the JSON object.</p> <p>Next, just iterate the object, and if the current key contains a list of strings, join them:</p> <pre class="lang-py prettyprint-override"><code>import json s='&quot;PN_#&quot;:9999,&quot;Item&qu...
python|regex|pandas
1
361,730
68,008,800
Is this a valid way to filter to Unique Values?
<p>I have inherited a legacy piece of code and do not understand why this code bloc is throwing an Assertion Error, any help is really appreciated!</p> <pre><code># rename columns and filter out null values df_cipSP_PP = cipSP_PP_raw.rename(columns={'Asset/Tag Number': 'cipSP UID'}) df_cipSP_PP_select = df_cipSP_PP.loc...
<p>df['column_name'].unique()</p> <p>This will return all the unique values</p> <p>df['column_name'].unique().tolist() to have all unique values in a list</p>
python|pandas
0
361,731
67,903,185
How to fetch the data from next column in a dataframe
<p>I want to fetch the data of the column &quot;Examples&quot; with respect to column &quot; Category&quot;</p> <p><a href="https://i.stack.imgur.com/7KtCO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7KtCO.png" alt="enter image description here" /></a></p> <pre><code>Output: Fruits [Apple,Mango,O...
<p>If I understood correct, you want to unpack each list that contains a few lists in the <code>Example</code> column.</p> <p>One way is to use numpy's <code>ravel</code> function. Assuming your dataframe is <code>df</code>:</p> <pre><code>import numpy as np df[&quot;Examples&quot;] = df[&quot;Examples&quot;].apply(lam...
python|pandas|dataframe|numpy
1
361,732
67,752,969
How to predict while training?
<p>I'm working on a reinforcement learning project where the agent is a load balancer observes service request and servers' status. The agent is supposed to do some batch train after accumulating some observation/action(allocating request to service server)/reward(whether the request is well handled i.e. timely/correct...
<p>Don't know why, but importing keras separately in each process solves the issue.</p> <p>It's mentioned here. <a href="https://stackoverflow.com/questions/56344611/how-can-take-advantage-of-multiprocessing-and-multithreading-in-deep-learning-us">How can take advantage of multiprocessing and multithreading in Deep lea...
python|tensorflow|machine-learning|keras|multiprocessing
0
361,733
67,910,380
Clubbing a dataframe column values based on a specific condition and storing it in a new column
<p>Trying to club the occurrences of col1 and storing it in a new column as col1_occurences, but unable to do so, please help</p> <p>Input df:</p> <pre><code>col1 col2 sheet1 john sheet2 harry sheet3 john sheet4 mark sheet5 mark </code></pre> <p>Expected Output</p> <pre><code>col1 col2 col1_o...
<p>Try with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html#pandas-core-groupby-dataframegroupby-transform" rel="nofollow noreferrer"><code>groupby transform</code></a>:</p> <pre><code>df['col1_occurrences'] = df.groupby('col2')['col1'].transform('...
python|dataframe|pandas-groupby
1
361,734
67,891,211
Is it possible to find similarities between rows in a matrix without loop?
<p>i have a 2D numpy array. I'm trying to compute the similarities between rows and put it into a <code>similarities</code> array. Is this possible without loop? Thanks for your time!</p> <pre><code># ratings.shape = (943, 1682) arri = np.zeros(943) arri = np.where(arri == 0)[0] arrj = np.zeros(943) arrj = np.where(a...
<p>The problem is how numpy iterates through the array when indexing a two-dimentional array with two arrays.</p> <hr /> <p>First some setup:</p> <pre class="lang-py prettyprint-override"><code>import numpy; ratings = numpy.arange(1, 6) indicesX = numpy.indices((ratings.shape[0],1))[0] indicesY = numpy.indices((ratin...
python|arrays|numpy|broadcasting
0
361,735
67,850,870
Finding the smallest number not smaller than x for a rolling data of a dataframe in python
<p>Let suppose i have data in rows for a column(O) : 1,2,3,4,5,6,7,8,9,10. Its average is 5.5. I need to find the smallest number which is larger than the average 5.5 :- i.e. '6'</p> <p>Here is what I have tried soo far.</p> <p>method 1:</p> <pre><code>df[&quot;test1&quot;] = df[&quot;O&quot;].shift().rolling(min_perio...
<p>Mask the Series when it is greater than the mean, then sort, then take the first row.</p> <pre><code>import pandas as pd df = pd.DataFrame([1,2,3,4,5,6,7,8,9,10], columns=(&quot;vals&quot;,)) df[df.vals &gt; df.vals.mean()].sort_values(&quot;vals&quot;).head(1) # &gt; vals # 5 6 </code></pre>
python|pandas|dataframe|rolling-computation
4
361,736
67,902,307
How to crate new column based on time interval?
<p>I want to create a new column, based on time interval of 6hours from datetime column how can I do that?</p> <p><a href="https://i.stack.imgur.com/a65yc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a65yc.png" alt="enter image description here" /></a></p> <pre><code> C/A UNIT SCP ...
<p>pandas has <code>floor</code> function for time</p> <pre><code>df['DATETIME'].dt.floor('6H') </code></pre> <p>this column needs to be datetime type</p> <pre><code> 0 1 0 2021-06-06 00:00:00 2021-06-06 00:00:00 1 2021-06-06 01:00:00 2021-06-06 00:00:00 2 2021-06-06 02:00:00 2021-06-06 00:00:00 ...
python|pandas
1
361,737
67,824,840
How to I join two pandas DataFrames that have the same multiple columns? I don't want duplicates such as Date.a | Date.b
<p>I have two pandas DataFrames of Date | Region | District. I want to combine these two dataframes so there is not Date.a | Date.b | Region.a | District.a Region.b | District.b</p>
<p>Merge columns must be present in both dataframes</p> <pre class="lang-py prettyprint-override"><code>df = df1.merge(df2, on=[&quot;Date&quot;, &quot;Region&quot;, &quot;Disctric&quot;]) </code></pre>
python|pandas
0
361,738
67,837,710
How to solve cannot assign to function call in this Python code
<pre><code>#Start cleaning loop through all the pings for P in Pings: #All beams for current ping print(&quot;Cleansing completed&quot;, round(P/len(Pings)*100,1),&quot;%&quot;) Slice_one = df[(df.P==P)&amp;(df.Bm&gt;0)&amp;(df.Bm&lt;257)].copy() model = LinearRegression().fit(Slice_one.B...
<p>you have to use square brackets [ ], <code>Slice_one[&quot;dZ&quot;] = abs(Slice_one.Z_1 - Slice_one.Z)</code></p>
python|python-3.x|pandas|function|linear-regression
0
361,739
68,006,587
Pandas groupby and then find max value per group in another column
<p><a href="https://i.stack.imgur.com/DvGFH.png" rel="nofollow noreferrer">This is not the whole dataset, just .head(10)</a></p> <p>I want a dataframe with 3 columns: groupby user_id</p> <ol> <li><p>’user_id’</p> </li> <li><p>The ‘product_id’ that is most ordered per ‘user_id’ (max in ‘uxp_total_bought' per ‘user_id’)<...
<p>I think the following is gonna work.</p> <pre><code>test = your_dataset.groupby('product_id')['uxp_total_bought'].max() test = test.reset_index() test = your_dataset.loc[uxp.groupby(&quot;user_id&quot;)[&quot;uxp_total_bought&quot;].idxmax()] del test[&quot;uxp_total_bought&quot;] test.rename(columns = {&quot;produc...
pandas|dataframe|pandas-groupby
0
361,740
67,985,433
Pandas: Fill na with mode of a group
<p>I have a <code>df</code> with multiple columns.</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'Store':['M1','M2','M3','M1','M1','M2','M2','M3','M3'], 'Category':['A','A','A','B','B','B','C','C','C'], 'Price_Category':[np.nan,X,np.nan,np.nan,Y,Y,Z,np.nan,...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.iat.html" rel="nofollow noreferrer"><code>Series.iat</code></a> for first value of <code>Series</code> by position:</p> <pre><code>f = lambda x: x.fillna(x.mode().iat[0]) df['Price_Category'] = df.groupby('Category')['Price_Category...
python|pandas|mode|fillna
3
361,741
67,991,822
Updating Entry in Table - Python
<p>I have a table like the one below, which I used a double for loop to calculate. The problem is, I'm getting different results for rows <code>test1 vs test2</code> and <code>test2 vs test1</code> (see intersection value, rate, and percentage columns in table). They should be the same. For example, <code>test1 vs test...
<p>Create a sort key from <code>Param -a</code> and <code>Param -b</code> to match the same records and group them. You can copy the first value of the group using <code>transform</code>:</p> <pre class="lang-py prettyprint-override"><code>cols = ['Intersection.Value', 'Rate', 'Percentage'] key = df[['Param -a', 'Param...
python|pandas
0
361,742
67,917,626
group by id1 and id2 and apply a function using another dataframe and dates
<p>My problem is the following: I have a dataframe <strong>DF1</strong> of car accidents (<strong>id_accident</strong>) and PASSENGER victims (<strong>id_victim</strong>) and the date of the accident (<strong>date1</strong>).</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id_accident</th>...
<p>This looks like classic SQL question. What kind of output format do you need?</p> <p>I had to change first date if DF2 to <code>2020/20/01</code> to make pandas recognize it. Below is the complete example using <code>pd.merge</code></p> <pre><code>import pandas as pd import numpy as np from io import StringIO df1 ...
python|pandas|function|date
1
361,743
67,676,636
Why my function that creates a pandas dataframe changes the dtype to none when called
<p>I'm working on processing csv files, I was writing my code without functions and it worked, albeit some problems when trying to fillna with a string, before I did a try and except. For some reason it didn't work before creating the while loop. My question is why a dataframe object created inside of a function by rea...
<p>Well sorry guys, I figure it out by myself: I was missing the scope, sorry again for the newb stuff. I just started coding in Python a few months ago(last December) and I'm learning in the process.</p> <p>What worked for me was to add the scope Global, within the function, seriously I didn't know dataframes behaved ...
python-3.x|pandas|dataframe|function|dtype
0
361,744
67,725,175
How to access pytorch embeddings lookup table as a tensor
<p>I want to show my embeddings with the tensorboard projector. I would like to access the embeddings matrix (lookup table) of one of my layers so I can write it to the logs.</p> <p>I instantiate my layer as this:</p> <p><code>self.embeddings_user = torch.nn.Embedding(30,300)</code></p> <p>And I'm looking for the tenso...
<p>Embeddings layers have weight attributes corresponding to the lookup table. You can access it as follows.</p> <pre class="lang-py prettyprint-override"><code>vectors = self.embeddings_user.weight </code></pre> <p>So now you can visualize it with tensorboard.</p> <pre><code>import numpy as np import tensorflow as tf ...
tensorflow|machine-learning|pytorch|tensorboard
0
361,745
67,766,734
How do I reverse all lists in a pandas dataframe column?
<p>I have a dataframe with a column that is a filled with different lists. I want to reverse every list in the column.</p> <p>Example of what I want:</p> <p>I want this df:</p> <pre><code> index x_val 1 [1,2,3,4,5] 2 [2,3,4,5,6] </code></pre> <p>to become this:</p> <pre><code> index x_...
<p><strong>Two Cases:</strong></p> <h3>Case 1</h3> <p>If <code>List</code> is of <code>int type</code> forming the <code>object type</code> column <code>x_val</code></p> <pre><code>df = pd.DataFrame({ 'index':[1,2], 'x_val':[[1,2,3,4,5], [2,3,4,5,6]] }) </code></pre> <p><strong>Code</strong></p> <pre><code>df['...
python|pandas
1
361,746
67,858,524
How to append a 2d array to 3d array?
<p>I have a 3D nested list constructed like this:</p> <pre><code>[[[1,1],[2,1],[2,2],[1,2]],[[-1,-1],[-2,-1],[-2,-2],[-1,-2]]] </code></pre> <p>and I want to concat to that <code>[[0,0]]</code> to get this result:</p> <pre><code>[[[1,1],[2,1],[2,2],[1,2]],[[-1,-1],[-2,-1],[-2,-2],[-1,-2]],[[0,0]]] </code></pre> <p>I tr...
<p>The problem is that once you have a <code>numpy</code> array with shape <code>(2, 4, 2)</code>, you cannot really append another array with shape <code>(1, 1, 2)</code> unless you treat lists as objects (i.e. you are appending an element to an array of size <code>2</code> so that in the end you have an array of size...
python|list|numpy
1
361,747
67,808,562
Read multiple files from Unix folder and extract key value pair using Python
<p>Reading multiple files from Unix directory. I am trying to read multiple files stored in Unix folder and extract Key Value Pair after this bit of text &quot;input1&quot;.</p> <p>Each Files consist data in below formats:-</p> <p>input1 = {'hostname' : 'host', 'port' : '22', 'basedn' : 'CN=Users', 'bindusername' : 'ad...
<p>Here try this?</p> <pre><code>import pandas as pd dic1={'xyz':'123' , 'abc':'456','def':'765'} data = pd.DataFrame() data['Col1']=[val for val,key in dic1.items()] #=== All keys in dic1 data['Col2']=[key for val,key in dic1.items()] #=== All Values in dic1 print(data) </code></pre> <p>prints:</p> <pre><code> Col1 ...
python|python-3.x|pandas|dictionary|tuples
0
361,748
67,840,158
Numpy Array Local variable reference Python
<p>I'm getting an error with <code>npArray</code> however <code>listvals</code> works just fine. How would I be able to fix it so that the numpy array works just like <code>listvals</code>?</p> <p>Code:</p> <pre><code>import numpy as np listvals=[] npArray=np.array([]) def Run(): for n in range(5): listva...
<p>very simple, All you have to do is pass it as a function</p>
python|python-3.x|list|function|numpy
1
361,749
67,714,936
rotate diagonal of a 2d numpy array into row
<p>I have a 2d numpy array:</p> <pre><code>A = array([[1, 7, 5, 0, 5], [9, 1, 4, 6, 0], [9, 6, 1, 0, 0], [2, 5, 0, 0, 0], [1, 0, 0, 0, 0]]) </code></pre> <p>What I want to achieve is</p> <pre><code>B = array([[1, 0, 0, 0, 0], [9, 7, 0, 0, 0], [9, 1, 5, 0...
<p>This is what I could come up with:</p> <pre><code>B = np.empty_like(A) for i in range(5): pad_width = (0, 5 - len(np.diag(A[::-1], k=n)) B[i, :] = np.pad(np.diag(A[::-1], k=i-4), pad_width) </code></pre> <p>Here is the explanation:</p> <ol> <li>You can use <a href="https://numpy.org/doc/stable/reference/gene...
numpy
0
361,750
67,705,320
MACD stock indicator function using ewm() from pandas library
<p>Here is the test code for my macd function, however, the values I am getting are incorrect. I don't know if it is because my span is in days and my data is in 2 minute increments, or if it is a seperate issue. Any help would be much appreciated :)</p> <pre><code>import yfinance as yf import pandas as pd import panda...
<p>Use min_periods instead adjust code:</p> <pre><code> import pandas as pd import pandas_datareader as pdr import matplotlib.pyplot as plt df = pdr.DataReader('BTC-USD' , data_source='yahoo' , start='2020-01-01') df </code></pre> <p>Function definition:</p> <pre><code>def MACD(DF,a,b,c): df=DF.copy() ...
python|pandas|yfinance
0
361,751
67,731,499
reading columns of csv file using pandas not working
<p>I am trying to read the following .csv file, but I want to read each column of it. However, usecols is not working as it is giving the following error: <code>ValueError: Usecols do not match columns, columns expected but not found: ['sources', 'RMS']</code></p> <p>this is how I am reading it:</p> <pre><code>train=pd...
<p>If the order of the columns will always be the same, you can also use an integer-list with <code>usecols</code></p> <pre><code>df = pd.read_csv('file.csv',usecols=[0,4] #this selects just 0 and 4 </code></pre>
python|pandas|csv|file
0
361,752
31,764,579
Numpy array scaling not returning proper values
<p>I have a numpy array that I want to alter by scaling all of the columns (e.g. all the values in a column are divided by the maximum value in that column so that all values are &lt;1). </p> <p>A sample output of the array is </p> <p>[ 2. 0. 367.877 ..., -0.358 51.547 -32.633]</p> <p>[ 2. 0...
<p>IIUC, it's not that the maximum value is shared between columns, it's that you probably want to divide by the maximum <em>absolute</em> value instead, because you have elements of both signs. 1 > -100, after all, and so if you divide by the <em>maximum</em> value of a column with [1, -100], nothing would change.</p>...
python|arrays|numpy
2
361,753
31,889,441
pandas: complex grouping and nests
<p>Here is a sample data set. Assume that there are many other records and many many more customer records.</p> <pre><code> customers = ['a','a','a','a','b','b','b','c','c','c'] level = [10,15,30,49,12,15,49,9, 22, 49] cars = ['bmw','audi','vw','mercedes','bmw','bmw','audi','audi', 'bmw', 'audi'] df = pd.DataFrame(...
<p>No promises that this is the slickest way, but I think you can get where you want to go with two groupbys, and a <code>cut</code> to get the levels:</p> <pre><code>df["lev"] = pd.cut(df.levels, bins=range(0,100,10), right=False) dc = df.groupby(["customers", "lev"]).size().reset_index(name="count") dfinal = dc.grou...
pandas|grouping|nested
1
361,754
31,785,594
Python pandas: banal apply statements incredibly slow
<p>I have a pandas dataframe with ca. 250,000 rows. I am trying to create a new field as follows:</p> <pre><code>df['new_field'] = df.apply( lambda x: x.field2 if x.field1 &gt; 0 else 0, axis =1 ) </code></pre> <p>this works, but the single line above takes about 15 seconds to run!</p> <p>I optimised it this way:</p...
<p>You can use <code>np.where</code>:</p> <pre><code>df['new_field'] = np.where(df['field1'] &gt; 0, df['field2'], 0) </code></pre> <p>So the above tests your boolean condition and returns <code>df['field2']</code> when <code>True</code> else it returns <code>0</code></p> <p>or in pandas style:</p> <pre><code>df['n...
python|pandas|dataframe|numba
4
361,755
32,078,737
Create pandas dataframe manually without columns name
<p>I would like to create the following dataframe without columns names</p> <pre><code>import pandas as pd df = pd.DataFrame([0,423,2342],[12,123,1231], [1,3,5]) </code></pre> <p>I get back an error</p> <pre><code>TypeError: unhashable type: 'list' </code></pre> <p>What am I doing wrong?</p> <p>I also tried <code>...
<p>The thing is you should pass your data as a 2D array, otherwise the constructor thinks you've passed several positional arguments. </p> <pre><code>DataFrame([[0,423,2342],[12,123,1231], [1,3,5]]) </code></pre>
python|pandas|dataframe|multiple-columns|manual
4
361,756
32,027,446
Error in pandas while subtracting two values and storing them again
<pre><code>First.csv LAC Reference_Count 1000 500 2222 1000 3333 500 5555 1000 9999 1500 Second.csv LAC 10/08/15 00:00 10/08/15 01:00 1000 2000 2500 2222 3000 4000 </code></pre> <p>I have two files first.csv and second.csv,in first.csv I have two headers LAC and reference count,second.csv ...
<p>Try converting everything to float as the error is saying that you have a string that you are trying to do math with. </p> <p>Did you try:</p> <pre><code>float(value) = float(tmp) - float(val) </code></pre> <p>Let me know if the error changes after that. Post the error too.</p>
python|csv|numpy|pandas
0
361,757
31,843,008
Transforming text data in sklearn pipeline
<p>Given an array of text data, </p> <pre><code>X = np.array(['cat', 'dog', 'cow', 'cat', 'cow', 'dog']) </code></pre> <p>I would like to use an sklearn pipeline to produce output like </p> <pre><code>np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0], [0, 0, 1], [0, 1, 0]]) </code></pre> <p>My initial attempt</p...
<p>Use <code>LabelBinarizer</code>:</p> <pre><code>import numpy as np from sklearn import preprocessing X = np.array(['cat', 'dog', 'cow', 'cat', 'cow', 'dog']) ...
python|pandas|scikit-learn
3
361,758
32,002,260
statsmodel armax: Cannot add integral value to Timestamp without offset
<p>I am trying to use a simple ARMAX model to predict a time series (GDP) based on another time series (covar). I keep getting: ValueError: Cannot add integral value to Timestamp without offset.</p> <p>The GDP and covar time series are monthly data points from 201101 to 201505. I would like to predict GDP over all 12 ...
<p>According to the statsmodels documents, <code>ARMAResults.predict()</code> has four parameters, in which the third parameter <code>exog</code>, aslo known as independent variables, is not necessary to be given.</p> <p>In your case, since the prediction time interval is from Jan 2014 to Dec 2014, it is part of your ...
pandas|statsmodels
0
361,759
32,021,612
Select and Count items datetime64[ns] in Pandas
<p>I have a pd as following:</p> <pre><code>df= CreationDate 0 2008-11-04 13:21:39 1 2008-11-24 23:50:29 2 2009-05-18 07:46:48 3 2009-09-22 06:03:34 4 2009-11-07 07:28:21 5 2009-12-08 14:29:56 6 2010-01-12 06:42:00 7 2010-05-20 17:56:01 8 2010-06-05 19:27:02 9 2010-07-16 19:52:22 10 2010-07-25 ...
<p>You need to first set <code>CreationDate</code> as index and then use the slice <code>'2008-11':'2009-12'</code> to select.</p> <pre><code>print(df) CreationDate A 0 2008-11-04 13:21:39 1.7641 1 2008-11-24 23:50:29 0.4002 2 2009-05-18 07:46:48 0.9787 3 2009-09-22 06:03:34 2.2409 4 2009-11-...
python|pandas
1
361,760
31,765,123
Pandas DataFrame.merge MemoryError
<h2>Goal</h2> <p>My goal is to merge two DataFrames by their common column (gene names) so I can take a product of each gene score across each gene row. I'd then perform a <code>groupby</code> on patients and cells and sum all scores from each. The ultimate data frame should look like this:</p> <pre><code> patie...
<p>Consider two workarounds:</p> <p><strong>CSV By CHUNKS</strong></p> <p>Apparently, <a href="https://stackoverflow.com/questions/11622652/large-persistent-dataframe-in-pandas">read_csv</a> can suffer performance issues and therefore large files must load in iterated chunks.</p> <pre><code>cellsfilepath = 'C:\\Path...
python|pandas|dataframe|anaconda
5
361,761
41,543,687
TensorFlow: What is the purpose of endpoints for data parallelism when training across multiple machines?
<p>In the <code>TensorFlow-slim</code> source code, there was an endpoint indicated in the creation of its loss function:</p> <pre><code>def clone_fn(batch_queue): """Allows data parallelism by creating multiple clones of network_fn.""" images, labels = batch_queue.dequeue() logits, end_points = network_fn(image...
<p>The <code>endpoints</code> in this case just track the different outputs of the model. The <code>AuxLogits</code> one, for example, has the logits. </p>
python|machine-learning|tensorflow|deep-learning|tf-slim
2
361,762
41,504,125
How do I get the value of weight and bias from auto-encoder program
<p>I ran <a href="https://gist.github.com/tomokishii/7ddde510edb1c4273438ba0663b26fc6#file-mnist_ae1-py" rel="nofollow noreferrer">mnist_ae1.py</a>(very simple model of auto-encoder), and want to get value of <code>w_enc</code> and <code>b_enc</code>. So, I added some process as below.</p> <pre><code># Train init = tf...
<p>The second argument to <a href="https://www.tensorflow.org/api_docs/python/tf/Operation#run" rel="nofollow noreferrer">Operation.run</a> which you call in the <code>train_step.run</code> line is the session. By passing a dictionary there you confuse the runtime into treating that dictionary as a session. Try doing <...
python|python-2.7|tensorflow
0
361,763
41,552,090
How to efficiently add rows for those data points which are missing from a sequence using pandas?
<p>I have the following time series dataset of the number of sales happening for a day as a pandas data frame.</p> <pre><code>date, sales 20161224,5 20161225,2 20161227,4 20161231,8 </code></pre> <p>Now if I have to include the missing data points here(i. e. missing dates) with a constant value(zero) and want to make...
<p>You can first cast to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> column <code>date</code>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"...
python|pandas
3
361,764
41,314,967
How to combine multiple cells into a single text сell
<p>I have a dataframe like this</p> <pre><code>import pandas as pd df = pd.DataFrame({'item': [1, 1,2,2], 'user': [1,2,2,1], 'appraisal': [4,2,1,3], 'feedback' : ['good', 'bad', 'bad', 'well'] }) names = ['item', 'user', 'appraisal', 'feedba...
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer">GroupBy.agg()</a> method:</p> <pre><code>In [4]: df.groupby('item').agg({'appraisal':'mean','feedback':' '.join}) Out[4]: appraisal feedback item 1 3...
python-3.x|pandas|text
4
361,765
41,588,383
How to run Keras on multiple cores?
<p>I'm using Keras with Tensorflow backend on a cluster (creating neural networks). How can I run it in a multi-threaded way on the cluster (on several cores) or is this done automatically by Keras? For example in Java one can create several threads, each thread running on a core.</p> <p>If possible, how many cores sh...
<p>Tensorflow automatically runs the computations on as many cores as are available on a single machine. </p> <p>If you have a distributed cluster, be sure you follow the instructions at <a href="https://www.tensorflow.org/how_tos/distributed/" rel="noreferrer">https://www.tensorflow.org/how_tos/distributed/</a> to co...
python|multithreading|python-3.x|tensorflow|keras
18
361,766
41,328,122
Creating a pandas DataFrame from a list followed by an array produces error
<p>When I try creating a pandas DataFrame with a list followed by an array, I get an error:</p> <pre><code>print(DataFrame([[10,20,30],np.arange(3)])) </code></pre> <p>TypeError: Expected list, got numpy.ndarray</p> <p>But if I reverse the order of the data, then the operation succeeds:</p> <pre><code>print(DataFra...
<p>This can give you a rough idea. There are multiple checks on data argument. If data argument is a list of items then the below code will execute under the hood. The first element of list is checked. If it's a list then it proceeds into listlike block but if its ndarray it proceeds into ndarray block. The lists block...
pandas|dataframe
1
361,767
41,645,209
Select largest square chunk for data from numpy array with no data values
<p>I need to select the square section of data within an 2D numpy array with nan's as the no data value. Here is a simplified example:</p> <pre><code>import numpy as np #Fake Data data =np.reshape(np.arange(100,dtype='float64'), (10,10)) extra_cols = np.zeros((1,10), dtype=data.dtype) data = np.concatenate((data,ext...
<p>I am pretty sure I cracked it. A couple of days and too much coffee.</p> <pre><code>import numpy as np def crop_to_data(mask, im): true_points = np.argwhere(mask) top_left = true_points.min(axis=0) # take the largest points and use them as the bottom right of your crop bottom_right = true_points.m...
python|arrays|numpy|image-processing|subset
0
361,768
41,638,369
Pandas : Cannot select row from dataframe
<p>Here is my dataframe</p> <pre><code> Word 1_gram-Probability 0 ('A',) 0.001461 1 ('45',) 0.000730 </code></pre> <p>now i just want to select the row where <code>Word</code> is 45. i tried</p> <pre><code>print(simple_df.loc[simple_df['Word']=='45']) </co...
<p>It appears that you have the literal string value <code>"('45',)"</code> in the cell of your dataframe. You must select it exactly so.</p> <pre><code>simple_df.loc[simple_df['Word']=="('45',)"] </code></pre>
python-3.x|pandas|dataframe
2
361,769
41,478,086
Why ndim = 2 in this numpy array?
<pre><code>&gt;import numpy as np &gt;a = np.arange(15).reshape(3, 5) ([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]) &gt; a.shape (3, 5) &gt; a.ndim 2 /// how to calculate it for any narray </code></pre>
<p><code>ndim</code> is the same as <code>len(a.shape)</code></p> <p>in your case you have 2 dimensions, first of size 3 and second of size 5</p>
python|numpy
2
361,770
41,268,347
Pandas - Using a list of values to create a smaller frame
<p>I have a list of values that are found in a large pandas dataframe:</p> <pre><code>value_list = [1, 4, 5, 6, 54] </code></pre> <p>Example DataFrame <code>df</code> is below:</p> <pre><code> column x 0 1 3 1 4 6 2 5 8 3 6 19 4 8 21 5 12 97 6 54 102 </code></pre> <p>I woul...
<p>You might be looking for <code>isin</code> operation.</p> <pre><code>In [60]: df[df['column'].isin(value_list)] Out[60]: column x 0 1 3 1 4 6 2 5 8 3 6 19 6 54 102 </code></pre> <p>Also, you can use <code>query</code> like</p> <pre><code>In [63]: df.query('column in ...
python|pandas
3
361,771
41,230,644
Tensorflow matmul operation for rank>2 does not work
<p>I find the following on the Tensorflow documentation homepage for using the matmul operation when rank>2:</p> <p><a href="https://www.tensorflow.org/api_docs/python/math_ops/matrix_math_functions#matmul" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/math_ops/matrix_math_functions#matmul</a><...
<p>Is your TensorFlow too old? Here's what I get in version 0.12rc0</p> <pre><code>a = tf.constant(np.arange(1,13).astype(np.float32), shape=[2, 2, 3]) b = tf.constant(np.arange(13,25).astype(np.float32), shape=[2, 3, 2]) sess.run(tf.matmul(a, b)) =&gt; array([[[ 94., 100.], [ 229., 244.]], [[ 508....
python|tensorflow|rank
1
361,772
41,374,177
pandas read_html does not storing complete data
<p>I am using read_html function in pandas to extract data from some html tables . But for some reason the output gets cut after a certain size : </p> <p>example :</p> <pre><code>0 RECKITT BENCKISER INDIA PRIVATE LIMITED Vs.ST... 1 SMT. SONY AND ANOTHER Vs. STATE OF UTTARAKHA... 2 BHATIA BHAWAN DHARAM...
<p>It is getting the complete text. It was not showing the full text due to limited column width.</p> <p>Check this:</p> <pre><code>import pandas as pd pd.set_option('max_colwidth',400) df=pd.read_html('http://pastebin.com/raw/p7vfb2JG')[0] df.head() </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.c...
python|pandas|web-scraping
0
361,773
41,580,143
How do I replace the values in the second dataframe based on the values in the first dataframe
<p>I have two dataframes i.e df and df1,</p> <p><code>df</code>:</p> <pre><code>Product_name Name City Rice Chetwynd Chetwynd, British Columbia, Canada Wheat Yuma Yuma, AZ, United States Sugar Dochra Singleton, New South Wales, Australia Milk Ind...
<h1>Setup</h1> <pre><code>from io import StringIO import pandas as pd df_txt = """Product_name Name City Rice Chetwynd Chetwynd, British Columbia, Canada Wheat Yuma Yuma, AZ, United States Sugar Dochra Singleton, New South Wales, Australia Milk I...
python|pandas
2
361,774
41,271,425
pycharm ipython package not loading?
<p>I am trying to work on a ipython notebook on pycharm but I am not being able to use the packages <a href="https://i.stack.imgur.com/09pTh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/09pTh.jpg" alt="enter image description here"></a></p> <p>As you can see it says <code>pd</code> is not defined...
<p>Turns out I have to run the first cell first then the others. </p>
python|pandas|pycharm
1
361,775
41,537,320
curve fitting and parameter estimation in Python
<p>I am currently using Python to compare two different datasets (xDAT and yDAT) that are composed of 240 distance measurements taken over a certain amount of time. However, dataset xDAT is offset by a non-linear amount. This non-linear amount is equal to the width of a time-dependent, dynamic medium, which I call leve...
<p>The answer depends on what Level A is. If it is independent, your first line should be something like </p> <p><code>coefs = np.polynomial.polynomial.polyfit(numpy.arange(xDAT.size), yDAT-xDAT, 5)</code></p> <p>This will give a polyfit of an independent <code>A</code> as drawn, and then the corrected <code>x</code...
python|numpy|estimation|polynomials
0
361,776
41,492,390
How to create a new empty pandas columns with a specific dtype?
<p>I have a DataFrame <code>df</code> with columns <code>'a'</code>. How would I create a new column <code>'b'</code> which has <code>dtype=object</code>?</p> <p>I know this may be considered poor form, but at the moment I have a dataframe <code>df</code> where the column <code>'a'</code> contains arrays (each element...
<p>As each row of your column is an array, it's better to use the standard <code>NumPy</code> mathematical functions for computing their element-wise logarithms to the base 10:</p> <pre><code>df['log_a'] = df.a.apply(lambda x: np.log10(x)) </code></pre> <p><a href="https://i.stack.imgur.com/K05Ni.png" rel="nofollow n...
python|pandas
1
361,777
27,710,953
Divide each plane of cube by its median without loop
<p>I need to normalize a numpy data cube say:</p> <pre><code>cube = np.random.random(100000).reshape(10,100,100) </code></pre> <p>and then normalise each of the 10 resulting planes by the median. So, e.g. for the first plane</p> <pre><code>cube[0, :, :] /= np.median(cube[0, :, :]) </code></pre> <p>I just want to av...
<p>You can pass a list of axes to <code>np.median</code> and then expand via <code>None</code> (<code>np.newaxis</code>):</p> <pre><code>&gt;&gt;&gt; cube = np.random.random(100000).reshape(10,100,100) &gt;&gt;&gt; simple = cube / np.median(cube,axis=[1,2])[:,None,None] &gt;&gt;&gt; &gt;&gt;&gt; brute = cube.copy() &...
python|numpy
5
361,778
27,638,743
Pandas - Replace outliers with groupby mean
<p>I have a pandas dataframe which I would like to split into groups, calculate the mean and standard deviation, and then replace all outliers with the mean of the group. Outliers are defined as such if they are more than 3 standard deviations away from the group mean.</p> <pre><code>df = pandas.DataFrame({'a': ['A','...
<p>Try this:</p> <pre><code>def replace(group): mean, std = group.mean(), group.std() outliers = (group - mean).abs() &gt; 3*std group[outliers] = mean # or "group[~outliers].mean()" return group df.groupby('a').transform(replace) </code></pre> <p>Note: If you want to eliminate the 100 in your...
python|pandas
8
361,779
27,778,299
Replace the zeros in a NumPy integer array with nan
<p>I wrote a python script below:</p> <pre><code>import numpy as np arr = np.arange(6).reshape(2, 3) arr[arr==0]=['nan'] print arr </code></pre> <p>But I got this error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\Desktop\test.py", line 4, in &lt;module&gt; arr[arr==0]=['nan'] ValueError:...
<p><code>np.nan</code> has type <code>float</code>: arrays containing it must also have this datatype (or the <code>complex</code> or <code>object</code> datatype) so you may need to cast <code>arr</code> before you try to assign this value. </p> <p>The error arises because the string value <code>'nan'</code> can't be...
python|arrays|numpy|nan
52
361,780
27,621,904
Create a single-file dataset out of _many_ b/n GIFs
<p>I have many 100x100px black/white GIF images. I want to use them in Numpy to train a machine learning algorithm, but I would like to save them in a single file that is easily readable in Python/Numpy. By saying many I mean several hundred thousands, so I would like to take advantage of the images carrying only 1 bit...
<p>PyTables seems like a good option here. Something like this might work:</p> <pre><code>import numpy as np import tables as tb nfiles = 100000 #or however many files you have h5file = tb.openFile('data.h5', mode='w', title="Test Array") root = h5file.root x = h5file.createCArray(root,'x',tb.Float64Atom(),shape=(100,...
python|numpy
0
361,781
27,672,556
pandas asfreq returns NaN if exact date DNE
<p>Let's say I have financial data in a <code>pandas.Series</code>, called <code>fin_series.</code></p> <p>Here's a peek at <code>fin_series</code>.</p> <pre><code>In [565]: fin_series Out[565]: Date 2008-05-16 1000.000000 2008-05-19 1001.651747 2008-05-20 1004.137434 ... 2014-12-22 1158.085200 2014-12-2...
<p>Assuming the input is a <strike>dataframe</strike> <code>Series</code> , first do </p> <pre><code>import pandas as pd fin_series.resample("q",pd.Series.last_valid_index) </code></pre> <p>to get a series with the last non-NA index for each quarter. Then</p> <pre><code>fin_series.resample("q","last") </code></pre> ...
python|datetime|pandas
1
361,782
61,375,125
Keras tuner: mismatch between number of layers used and number of layers reported
<p>Using example from Keras Tuner website, I wrote simple tuning code</p> <pre><code>base_model = tf.keras.applications.vgg16.VGG16(input_shape=IMG_SHAPE, include_top=False, weights='imagenet') base_model.trainable = False de...
<p>Any hyperparameter seen so far will be displayed in the summary, meaning that once a trial containing three layers has been run, all subsequent summaries will contain three layer sizes. It does not mean it uses all three layers, which is indicated by by the <code>num_layers: 1</code> print for this particular trial....
python|tensorflow|keras|deep-learning|keras-tuner
1
361,783
61,339,327
How to draw a Frequency plot using the output?
<p>Using below code i listed the top 10 most frequent words with its count now i need to put it in a frequency plot .</p> <pre><code>freq6000.sort_values(by=['Word Frequency'],ascending=False).head(10) Word Frequency data 124289 experience 59135 business 33528 work 28146 science 268...
<p>Select column <code>Word Frequency</code> for <code>Series</code> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.plot.bar.html" rel="nofollow noreferrer"><code>Series.plot.bar</code></a>:</p> <pre><code>(freq6000.sort_values(by=['Word Frequency'],ascending=False) ...
python-3.x|pandas
1
361,784
61,334,090
Is it safe to always use torch.tensor or torch.FloatTensor? Or do I need to treat Ints with care?
<blockquote> <p><a href="https://pytorch.org/docs/stable/tensors.html" rel="nofollow noreferrer">https://pytorch.org/docs/stable/tensors.html</a></p> </blockquote> <p>I am trying to understand the difference between <code>tensor, FloatTensor, IntTensor</code> - and am wondering if I can just always stick to <code>te...
<p><code>CrossEntropyLoss</code> (or <code>NLLLoss</code>) expect the <code>target</code> type to be <code>Long</code>. For example, the code below raises a <code>RuntimeError</code>:</p> <pre class="lang-py prettyprint-override"><code>import torch.nn criterion = torch.nn.CrossEntropyLoss() predicted = torch.rand(1...
pytorch
1
361,785
61,292,529
Python, store the number of training and validation images obtained from ImageDataGenerator in variables for use later on
<p>I have the following python code which I run in Google Colab Notebooks which uses ImageDataGenerator to split out a development set into training and validation. </p> <pre><code>datagen = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1./255, validation_split=0.35) train_data_gen = datagen.flow_...
<p>You cannot retrieve those numbers as a result from <code>flow_from_directory()</code>.</p> <p>What you can do instead (since I presume you want to feed <code>steps_per_epoch = training_set_length // batch_size</code> and the same for <code>validation_steps</code>), you can write some arbitrary Python code to solve ...
python|tensorflow|keras
0
361,786
61,512,551
Function to get row Value of a dataframe using str Index
<p>Sample df:</p> <pre><code>Student Marks Avery 70 Joe 80 John 75 Jordan 90 </code></pre> <p>I want to use a function as below to return marks when a student name is passed. </p> <pre><code>def get_marks(student): return *something* </code></pre> <p>Expected Output: get_marks('Joe') ==> 80</...
<p>I think the following might work.</p> <pre class="lang-python prettyprint-override"><code>def get_marks(student): p = df.index[df['Student'] == student].tolist() p = p[0] return df['Marks'][p] </code></pre> <p>What I have done is I have first to get the index of row of the Student and then simply retur...
python|pandas
0
361,787
61,332,910
by changing dataframe some columns are duplicated
<p>I have dataset:</p> <pre><code>,target,text 0,0,awww thats bummer shoulda got david carr third day 1,0,upset cant update facebook texting might cry result school today also blah 2,0,dived many times ball managed save 50 rest go bounds 3,0,whole body feels itchy like fire 4,0,behaving im mad cant see 5,0,whole crew ...
<p>Create a copy and specify which column is your index when reading the CSV file:</p> <pre><code># ... df_neg = df[data_neg].copy() df_neg.to_csv("negative.csv") # For reading it df_neg = pd.read_csv("negative.csv", index_col=0) </code></pre>
python|pandas|dataframe
0
361,788
61,595,221
How to groupby values in pandas but using lists as an index?
<p>I have dataframe like and i need to groupby it based on fruit and value but i need to index it based on lists</p> <pre><code> Date ID Age Value Fruits 1.1.19 1 50 2 Apple 2.1.19 1 50 5 Mango 2.1.19 1 50 8 ...
<p>Fix your code with <code>reindex</code> </p> <pre><code>df.groupby(['Fruits', 'Date'])['Value'].mean().unstack(fill_value=0).\ reindex(columns=date_list,index=fruits_list,fill_value=0).\ round().reset_index() Out[172]: Date Fruits 1.1.19 2.1.19 3.1.19 4.1.19 5.1.19 6.1.19 0 Apple 2 ...
python|pandas|group-by
2
361,789
61,447,570
How to perform this copying operation using numpy?
<p>I've been working on a basic simulation for "diffusion monte carlo" to find the ground state energy of the hydrogen molecule. There's a critical piece of the algorithm which is slowing my code down painfully, and I'm not sure how to fix it. </p> <p>This is what the code is doing. I have a 6 by N numpy array called ...
<p>let M be an N x 1 array of the m values for each random walker.</p> <p>let X be your original 6 x N data array</p> <pre><code># np.where returns a list of indices where the condition is satisfied zeros = np.where(M == 0) # don't actually need this variable, I just did it for completeness ones = np.where(M == 1...
python|numpy|physics
2
361,790
61,532,297
Why does the optimize.curve_fit not work on smaller datasets?
<p>I have performed a piecewise linear fit for my data <code>H2O</code> and <code>CO2</code>. It works perfectly fine for a dataset of <code>288</code> data points but not for a dataset of <code>144</code> data points. My code is as following:</p> <pre><code>#Piecewiselinear fit x = np.array(H2O) y = np.array(CO2) p ,...
<p>I ended up changing the approach from the common</p> <pre><code>def piecewise_linear(x, x0, y0, k1, k2): return np.piecewise(x, [x &lt; x0], [lambda x:k1*x + y0-k1*x0, lambda x:k2*x + y0-k2*x0]) </code></pre> <p>to </p> <pre><code>my_pwlf = pwlf.PiecewiseLinFit(x, y) breaks = my_pwlf.fit(2) #if you want multi...
python|numpy|statistics|linear-regression|piecewise
0
361,791
61,489,306
Filter Pandas Dataframe by number of list entries and rearrange output by pairs
<p>I'm working with a csv file in the format like the below created by using df.groupby to filter which ids where publicly sharing which links.</p> <pre><code> url id bbc.com ['183','194','101'] cnn.com ['182', '193', '103'] google.com ['131'] </code></pre> <p>I'm now trying to turn this into a new...
<p>I guess you need to use itertools.combinations(x, k). Here is example:</p> <pre><code>import pandas as pd import numpy as np import itertools df = pd.DataFrame({ 'url': ['bbc.com', 'cnn.com', 'google.com'], 'id' : [['183','194','101'], ['182', '193', '103'], ['131'] ]}) df url id 0 ...
python|pandas|pandas-groupby
0
361,792
61,557,536
How Tensorflow & Keras go from one-hot encoded outputs to class predictions for calculating the accuracy?
<p>I'm wondering how the Accuracy metrics in TensorFlow/Keras calculates if a given input matches the expected prediction, or, in other words, how it determines the predicted number of the net.</p> <hr> <p><strong>Example 1:</strong></p> <p>Output: <code>[0, 0, 0.6]</code>, expected output: <code>[0, 0, 1]</code> </...
<p>There are several issues with your question.</p> <p>To start with, we have to clarify the exact setting; so, in <em>single-label multi-class</em> classification (i.e. a sample can belong to one and only one class) with one-hot encoded samples (and predictions), all the examples you show here are <strong>invalid</st...
python|tensorflow|machine-learning|keras
4
361,793
61,396,850
Pandas apply function to multindexed columns that takes columns (Series) as arguments
<p>I need to apply a function that takes subcolumns (aka Series) of multiindexed columns as arguments. I have come up with a solution that works, but I was curious if there was a more pythonic/proper pandas way to do this.</p> <p>Let's say we have a function that takes two series as arguments and performs some user-de...
<p>You can <code>groupby</code> over the columns axis. Your function requires a <code>Series</code> so we'll need to <code>squeeze</code> if we want to select by label.</p> <pre><code>(df.groupby(level=0, axis=1) .apply(lambda gp: user_defined_function(gp.xs('sub_col_1', level=1, axis=1).squeeze(), ...
python|pandas
2
361,794
61,562,326
Interpreting ANN results -> MSE, MAE and undisplayed epochs results
<p>Im trainning an ANN model with just a few samples (10) to predict 45 targets with 38 inputs. I cannot figure iut why the results per epoch are not being displayed, any idea? Also, the overall MAE and MSE I get is 0.5252 and 0.6234, respectively. I'm not sure how to interpretate such values as my dataset was scaled. ...
<p>You should pass verbose=2 in model.fit() to get results for every epoch. MAE and MSE values depend on your data. MSE is more sensitive to large error values, in general high MSE means you probably get large errors for few of your samples, while high MAE means you are getting smaller error values, but for many of you...
python|tensorflow|neural-network
0
361,795
61,564,786
How to set initial zoom of bokeh box chart of pandas group with a large number of categories
<p>I'm plotting covid-19 data for countries grouped by World Bank regions using pandas and Bokeh.</p> <pre><code>from bokeh.io import output_file, show from bokeh.palettes import Spectral5 from bokeh.plotting import figure from bokeh.transform import factor_cmap group = data.groupby(["region", "CountryName"]) index_...
<p>You should be able to accomplish this with the x_range parameter. In this example, the plot's x range would be the first 20 countries. You can adjust as needed. You might also have to mess around a bit to get the group_cn_list correct. It's hard to say without seeing your data. If you can post a df example for repro...
python|pandas|bokeh
0
361,796
61,389,654
Converting day count to date time
<p>I've seen many examples of the reverse (date time --> day count), but can't seem to figure out how to convert day counts to date times.</p> <p>I have a df that looks like this:</p> <pre><code>day person var 1 1 a 2 1 b 3 1 a 1 2 b 2 2 b 3 2 b 1 3 a 2 3 a 3 ...
<p>Here's a pure pandas solution:</p> <pre><code>start_date = pd.to_datetime('2019-01-01') df['date'] = pd.to_timedelta(df['day']-1, unit='D') + start_date </code></pre> <p>output:</p> <pre><code> day person var date 0 1 1 a 2019-01-01 1 2 1 b 2019-01-02 2 3 1 a 2019-01-03 3...
python|python-3.x|pandas
2
361,797
61,446,009
Python pandas - what is the proper way to NaN all zeros before first non-zero value in multiple columns?
<p>I have a <code>df</code> with columns <code>date</code>, <code>a</code>, <code>b</code> and an <code>id</code>. The <code>id</code> is grouping and the <code>date</code> values repeat when going to a new <code>id</code>. In column <code>a</code> and <code>b</code> I want to replace 0 with <code>nan</code> <em>before...
<p>use 2 masks with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.cummax.html" rel="nofollow noreferrer">cummax</a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.transform.html" rel="nofollow noreferrer">transform</a> then <code>df.where</code></p> <pre><code>m1 = d...
python|pandas
1
361,798
61,601,893
Encode folder labels stored in a numpy array in Python
<p>I'm working on a Parkinson dataset. In my dataset folder, there are two folders : <a href="https://i.stack.imgur.com/WDPZF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WDPZF.png" alt=""></a></p> <p>In two of each, there are two other folders but that's really a detail:<a href="https://i.stack....
<p>3 numbers, in case its not either :)</p> <pre><code>x = imagePath.split(os.path.sep)[-2] label = '0' if x == 'healthy' else '1' if x == 'parkinsons' else '-1' </code></pre>
python|numpy
0
361,799
61,465,541
When training a GAN, should dropout be disabled in discriminator when training is disabled?
<p>I'm doing a basic GAN implementation in keras. The training is in phases, first training the discriminator alone, then training the generator as part of a combined model (generator plus discriminator) with the training disabled for the discriminator. If the discriminator has dropout in it, it seems to me that it sho...
<p>You are right, dropout should be disabled for generator while training the discriminator or at any testing stage. And good thing is that keras does this by default <a href="https://github.com/keras-team/keras/blob/master/keras/layers/core.py#L81" rel="nofollow noreferrer">link</a>.</p> <p>So looking at your scenari...
tensorflow|keras|generative-adversarial-network
2