Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
13,500
60,743,716
Compute the count frequency of match and accuracy of grouped dataframes
<p>I have 4 dataframes and would like to compare and calculate match accuracy.</p> <pre><code>DATA_LABELS = {'DATA_LABELS': ['1', '2', '3', '3', '4', '3', '3', '1', '2', '4']} EQ_LABELS = {'EQ_LABELS': ['1', '1', '1', '1', '1', '0', '0', '0', '0', '0']} EQ_NUM = {'EQ_NUM': ['1', '1', '1', '2', '2', '1', ...
<p>Try this:</p> <pre><code>#Using your data definitions DATA_LABELS = {'DATA_LABELS': ['1', '2', '3', '3', '4', '3', '3', '1', '2', '4']} EQ_LABELS = {'EQ_LABELS': ['1', '1', '1', '1', '1', '0', '0', '0', '0', '0']} EQ_NUM = {'EQ_NUM': ['1', '1', '1', '2', '2', '1', '1', '2', '2', '2']} pred = ...
python|pandas|dataframe|classification
0
13,501
60,334,466
handling dates in pandas
<p>I am reading a csv file using pandas and csv has date columns which is mixture of string and integers and ordered in ascending order, example shown below :</p> <pre><code>Date Dec 01 2010 40513 12/1/10 12/1/10 9:00 40513 </code></pre> <p>Tried the below code to ignore values not as date ,</p> <pre><code>df['...
<p>Idea is convert datetimes to <code>Series</code> called <code>date</code>, then filter non parsed datetimes and add <code>DateOffset</code>, last use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.combine_first.html" rel="nofollow noreferrer"><code>Series.combine_first</code></a> or...
python|pandas|date|datetime
2
13,502
60,528,835
Adding n rows each time and save the result in new data frame in pandas
<p><a href="https://i.stack.imgur.com/5mO7U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5mO7U.png" alt="enter image description here"></a></p> <p>I have the above data frame I want the result to be like below where we are adding 2-2 rows and saving the result in new data frame which contains cat...
<p>You should first build an auxiliary Series with same index as <code>df</code> and alterning values 0 and 1:</p> <pre><code>x = pd.Series(0, index=df.index) x[x.index % 2 == 0] = 1 </code></pre> <p>You can then use it to group df rows by pairs:</p> <pre><code>resul = df.groupby(['item', x.cumsum()]).sum().reset_in...
python|pandas|pandas-groupby
2
13,503
60,663,224
How to take mean across row in Pandas pivot table Dataframe?
<p>I have a pandas dataframe as seen below which is a pivot table. I would like to print <strong>Africa in 2007</strong> as well as do the <strong>mean of the entire Americas row</strong>; any ideas how to do this? I have been doing combinations of stack/unstack for a while now to no avail.</p> <pre><code>year 19...
<pre><code>import pandas as pd df = pd.read_csv('dummy_data.csv') # handy to see the continent name against the value rather than '0' or '3' df.set_index('continent', inplace=True) # print mean for all rows - see how the continent name helps here print(df.mean(axis=1)) print('---') print() # print the mean for just...
python|pandas
1
13,504
72,593,881
Generating random samples from geometric distribution in python
<p>I want to generate random sample from geometric distribution using python.</p> <p>I was using the numpy.random.geometric(p=0.3, size=100) function. But I later realized that this function generates sample from geometric distribution with pmf: p*q^(x-1), x=1,2,3....</p> <p>But I want random samples from geometric dis...
<blockquote> <p>But I want random samples from geometric distribution with pmf: p*q^(x), x=0,1,2,...</p> </blockquote> <p>You can use NumPy's implementation of <code>geometric</code>, and then subtract one from the samples:</p> <pre><code>In [37]: rng = np.random.default_rng() In [38]: nsamples = 1000 In [39]: r = rn...
python|numpy|statistics|distribution
1
13,505
72,811,105
How can I search for sub-groups of dataframe that contains specific pairs of data?
<p>I have a dataset which contains orders, and items in those orders. What I want to find is which item pairs exist together in which group. For example, I want to find orders which has 6395477 and 6391546 together, in this case order 20220627-0015 and 20220627-0014 have them.</p> <pre><code>ORDER_ID ITEM_ID 202206...
<p>To do this, I created a list of the items you want to check for:</p> <pre><code>ITEM_IDS = [6395477, 6391546] </code></pre> <p>Then I filtered the dataframe using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>.loc</code></a> with <a hre...
python|pandas|group-by|itertools
0
13,506
72,550,219
How to deal with a dataframe containing columns with mixed types?
<p>I have a pandas <code>dataframe</code> (in memory) with columns containing mixed types, how do I handle it?</p>
<p>TL;DR: Copy-paste the two functions below, execute them, then run <code>df_cleaned = df.pipe(clean_mixed_dtypes)</code></p> <hr /> <p>First, you have to list the columns in which your <code>dataframe</code> has mixed types.</p> <pre class="lang-py prettyprint-override"><code>def get_mixed_columns(df_): return (...
python|pandas|types|dtype
1
13,507
40,652,453
Using Keras for real-time training and predicting
<p>I want to use Keras for a real-time training and prediction setting. In my scenario I get real-time data via MQTT that should be used to train a (LSTM) Neural Network and/or to apply them to the to get a prediction.</p> <p>I am using the Tensorflow backend with GPU support and fairly potent GPU capacity but in my s...
<p>The performance of keras should be broadly similar to the performance of raw tensorflow, so I do not recommend rewriting your model.</p> <p>Indeed modern hardware usually takes about the same time to train with a single example as it does with a batch of examples, which is why we spend so much effort batching thing...
python|neural-network|tensorflow|real-time|keras
1
13,508
40,381,181
Python Pandas Memory Error during Drop
<p>I have a df of 825468 rows. I am performing this over it.</p> <pre><code> frame = frame.drop(frame.loc[( frame['RR'].str.contains(r"^([23])[^-]*-\1[^-]*$")), 'RR'].str.replace("[23]([^-]*)-[23]([^-]*)", r"\1-\2").isin( series1.str.replace("1([^-]*)-1([^-]*)", r"\1-\2"))[lambda d: d].index)...
<p><strong>UPDATE2:</strong></p> <pre><code>In [176]: df Out[176]: RR 0 2abc-2abc 1 3abc-3abc 2 2def-2def 3 3def-3def 4 def-dfd 5 sdsd-sdsd 6 1def-1def 7 abc-abc 8 def-def In [177]: df[['d1','s','s2']] = df.RR.str.extract(r'^(?P&lt;d1&gt;\d+)(?P&lt;s1&gt;[^-]*)-\1(?P&lt;s2&gt;[^-]*)', expand=...
python|python-2.7|pandas|dataframe|filtering
1
13,509
40,571,578
Limits on Python Lists?
<p>I'm trying to assimilate a bunch of information into a usable array like this:</p> <pre><code>for (dirpath, dirnames, filenames) in walk('E:/Machin Lerning/Econ/full_set'): ndata.extend(filenames) for i in ndata: currfile = open('E:/Machin Lerning/Econ/full_set/' + str(i),'r') rawdata.append(currfile.re...
<p>Looks like <code>fdata</code> is an array, and the error is in <code>fdata[:,1,3]</code>. That tries to index <code>fdata</code> with 3 indices, the slice, 1, and 3. But if <code>fdata</code> is a 2d array, this will produce this error - <code>too many indices</code>.</p> <p>When you get 'indexing' errors, figure...
python|list|numpy
2
13,510
18,461,623
Average values in two Numpy arrays
<p>Given two ndarrays</p> <pre><code>old_set = [[0, 1], [4, 5]] new_set = [[2, 7], [0, 1]] </code></pre> <p>I'm looking to get the mean of the respective values between the two arrays so that the data ends up something like:</p> <pre><code>end_data = [[1, 4], [2, 3]] </code></pre> <p>basically it would apply someth...
<p>You can create a 3D array containing your 2D arrays to be averaged, then average along <code>axis=0</code> using <code>np.mean</code> or <code>np.average</code> (the latter allows for weighted averages):</p> <pre><code>np.mean( np.array([ old_set, new_set ]), axis=0 ) </code></pre> <p>This averaging scheme can be ...
python|arrays|numpy
167
13,511
61,977,155
Why does my Pandas DataFrame contain an empty column?
<p>Rather, why does it output an empty first column to csv when I call <code>to_csv</code>. I'm not certain if the dataframe actually contains an extra column or merely outputs one to csv. I have the code below, and when I open its output, <code>times.csv</code>, I get an "empty" first column:</p> <pre><code>,Start,En...
<p>The additional column you see is the index of the dataframe (the first line in the csv is empty here as your index has no name). You can switch it off in the output by <code>index=False</code>: </p> <pre><code>df.to_csv(r"MotionDetector\times.csv", index=False) </code></pre> <p>(there's always an index in the data...
python|python-3.x|pandas|dataframe
0
13,512
61,855,988
what is the difference between the total= df.isnull().sum(), percent1= df.count(),percent= df.isnull().count()?
<p>Can anyone tell difference between the total= df.isnull().sum(), percent1= df.count(), df.isnull().count() as Ideally df.isnull().count() should give all the count of only null values but it is giving count of all the values .Can anyone help me to understand this?</p> <p>Below is the code where i am getting output...
<p>The definition of <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.count.html" rel="nofollow noreferrer">count</a> according to the doc is:</p> <p><em>Count non-NA cells for each column or row.</em></p> <p>And using <code>isnull</code> (or <code>isna</code>) change your datafram...
pandas
2
13,513
61,856,478
Error Installing Pyarrow with Python 3.7.4
<p>I'm developing a python script to deploy an Azure Function App. For this reason I can't use another Python version to make this easier.</p> <p>In azure portal I get this error: <a href="https://i.stack.imgur.com/QM50w.png" rel="nofollow noreferrer">Azure Function app pyarrow module not found</a></p> <p>When I try ...
<p>As you use <code>conda</code> as the package manager, you should also use it to install <code>pyarrow</code> and <code>arrow-cpp</code> using it. In your above output VSCode uses <code>pip</code> for the package management. You should consider reporting this as a bug to VSCode. Your current environment is detected a...
python|numpy|azure-functions|python-3.7|pyarrow
1
13,514
61,926,275
Pandas: row operations on a column, given one reference value on a different column
<p>I am working with a database that looks like the below. For each fruit (just apple and pears below, for conciseness), we have: 1. yearly sales, 2. current sales, 3. monthly sales and 4.the standard deviation of sales. Their ordering may vary, but it's always 4 values per fruit. </p> <pre><code>dataset = {'appl...
<p>I think, there is a cleaner way to perform your both tasks, for each fruit in one go:</p> <ol> <li><p>Add 2 columns, <em>Fruit</em> and <em>Descr</em>, the result of splitting of <em>Description</em> at the first "_":</p> <pre><code>df[['Fruit', 'Descr']] = df['Description'].str.split('_', n=1, expand=True) </code...
python|pandas
1
13,515
57,923,490
Replicate indexing output from MATLAB's union in python
<p>I have a data set that has a large number of elements where each data element has a time, some metadata, and a value. There are many separate data types in the set. All information is numerically coded and stored as a numpy array. I need to sort this 1xn data stream into an array where each row is a unique time and ...
<p>You can define your own <code>union</code> function, using <code>unique</code> and some sorting. </p> <pre><code>import numpy as np def union(a, b): ua = np.unique(a) # get unique values in input a ub = np.unique(b) # get unique values in input b c = ...
python|matlab|numpy
0
13,516
57,858,127
Mask-RCNN, ValueError: could not broadcast input array from shape (70) into shape (1)
<p>I am working on a project that detects buildings on SpaceNet dataset by using Mask-RCNN. When I run this code:</p> <pre class="lang-py prettyprint-override"><code>model.train(dataset_train, dataset_val, learning_rate=config.LEARNING_RATE, epochs=1, layers='heads') </code></pre...
<p>As @Mahesh said, I debugged the variable <code>gt_class_ids</code> and realized that the shape of it was (x, 1). 'x' could be 70, 15 or whatever it is, the problem was about the <code>gt_class_ids.shape[0]</code> part. <code>gt_class_ids.shape[0]</code> gives us 'x', and x again can be any number. So I went to the</...
python-3.x|tensorflow|object-detection|mask|valueerror
1
13,517
58,050,665
Individual operations on coordinates in 2D arrays
<p>Im working on a problem with projectile motion in computational physics, and I want to perform different mathematical operations on the x and y coordinates in my array. The code Im struggling with is indexing inside a for loop.</p> <p>I've tried different forms for indexing but keep getting errors like "could not b...
<p>you need to only index the y part like this</p> <pre class="lang-py prettyprint-override"><code>v[i+1, 1] = v[i,1] - g*dt </code></pre>
python|arrays|numpy
0
13,518
58,134,184
Append two new columns to datframe using values from existing column based on conditions
<p>Say, I have a data frame which looks like. </p> <pre><code> df.head() ID col1 col2 col3 col4 type 1 146 91 Rp Rp-203 ex 1 146 314 Rp Rp-203 trans 1 603 91 Rp Rp-203 CDS 1 910 81 Rp Rp-203 CDS 1 910 81 ...
<p>Use:</p> <pre><code>#filter only ex rows by type df3 = df[df['type']=='ex'].copy() #shift values per groups from list df3['s'] = df3.groupby(['ID','col3', 'col4'])['col2'].shift() #removed NaNs rows per start and convert values to int and strings df3 = df3.dropna(subset=['s']).assign(ex_start = lambda x: x['s'].as...
python|pandas|lambda
1
13,519
57,829,570
Pandas Groupby - select row with highest value in one column if multiple rows exceed value in another
<p>This operation groups my DataFrame by two columns, then returns the row with the highest value in <code>ColumnC</code>: </p> <pre><code>df2 = df.loc[df.groupby(['columnA', 'columnB'], sort=False)['columnC'].idxmax()] </code></pre> <p>Instead, for all rows where <code>ColumnC &gt; 100</code> within each group, I wo...
<p>Usually we split the data by two part , then filter them after the condition </p> <pre><code>df=sort_values('columnD') df1 = df[df['columnC'] &gt; 100]].drop_duplicates(['columnA', 'columnB'],keep='last') df2 = df.drop_duplicates(['columnA', 'columnB'],keep='last') Yourdf=pd.concat([df1,df2]).drop_duplicates(['co...
python|pandas
0
13,520
34,232,664
projectile motion simple simulation using numpy matplotlib python
<p>I am trying to graph a projectile through time at various angles. The angles range from 25 to 60 and each initial angle should have its own line on the graph. The formula for "the total time the projectile is in the air" is the formula for t. I am not sure how this total time comes into play, because I am supposed t...
<p>First of all <em>g</em> is positive! After fixing that, let's see some equations:</p> <p><img src="https://chart.apis.google.com/chart?cht=tx&amp;chl=x=v_%7B0x%7Dt=v_%7B0%7Dcos(%5Ctheta)t%5C%5Cy=v_%7B0y%7Dt-%5Cfrac%7B1%7D%7B2%7Dgt%5E%7B2%7D=v_%7B0%7Dsin(%5Ctheta)t-%5Cfrac%7B1%7D%7B2%7Dgt%5E%7B2%7D"></p> <p>You kno...
python|numpy|matplotlib
5
13,521
36,737,707
numpy pandas not working in IDLE / work in Anaconda
<p>I am running Python 3.5.1 on Windows 10 and have Anaconda and IDLE installed. If I run any Python files, pandas and numpy seem to work in Jupyter notebooks, but not in IDLE. I have ensured that the PATH and PYTHONPATH environment variables include access to the folders where pandas and numpy are located (Lib/site-pa...
<p>I had similar problem. I uninstalled anaconda from my system completely. Steps - Delete app, delete anaconda3 folder, empty trash</p> <p>Then I reinstalled older version of it and it started working perfectly. Maybe it is some kind of bug in the newer version. </p>
numpy|pandas|anaconda|python-idle
0
13,522
55,043,158
python3 ValueError: could not convert string to float , value = float(value) is not valid
<p>I have a problem with a command of python. I want my program to read a specific line from my file, and here I haven't problem. The problem is when I have to convert the line in a float (I need of float to calculate some equation). My program is:</p> <pre><code>f=open('coeff.txt') lines=f.readlines() k1=lines[0] k...
<p>Python doesn't know how to interpret <code>'6.00*1e-34\n'</code> as a float. You will have to clean your data before you can actually use it.</p> <p>Eventually, you will want to have each line in a format like this: <code>6.00e-34</code></p> <p>Looking at it closely, it seems like the only differences are the <cod...
python|string|numpy
2
13,523
28,206,852
Parse parameter to custom kernel function of SVM in Sci-kit Learn
<p>I followed the tutorial <a href="http://scikit-learn.org/stable/auto_examples/svm/plot_custom_kernel.html" rel="nofollow">SVM with custom kernel</a> and tried to use custom kernel in SVM. For example, I implement the polynomial kernel function as follows:</p> <pre><code> def poly_kernel(x, y): degree = 3 ...
<p>The kernel function can be dynamically constructed in this case. We can use lambda get a anonymous function as a variable. </p> <p>For example:</p> <pre><code> def linear_kernel(c = 0): return lambda x, y: np.dot(x, y.T) + c </code></pre> <p>When we want to use it, we just do:</p> <pre><code> lkf =...
python|numpy|scipy|scikit-learn|svm
0
13,524
73,503,060
Fourier series columns don't appear in Deterministicprocess()
<p>I have been refreshing my time-series skills and I'm having trouble with creating Fourier series. Here is the data (if you run everything together it will give you the same plots and final table):</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt from statsmodels.tsa.deterministic import CalendarFou...
<p>I found the solution. I just had to change the <code>M</code> from</p> <pre><code>CalendarFourier(freq=&quot;M&quot;, order=4) </code></pre> <p>To <code>Y</code>:</p> <pre><code>CalendarFourier(freq=&quot;Y&quot;, order=4) </code></pre> <p>I can't understand why or how it works specifically. It seems that the functi...
python|pandas|time-series|fft|statsmodels
0
13,525
73,435,955
Create Unique IDs using other ID column
<p>I have a dataframe with the following 2 columns, the employee type, name, the column that identify the primary contract and its ID number. Like this one:</p> <pre class="lang-none prettyprint-override"><code>Name Primary row? Employee Type ID Paulo Cortez Yes Employee 100000 Paulo Cortez No Employe...
<p>Here is one way to do it. First create a groupby with cumcount for the suffix if needed. Then apply each row and take add all the parts together.</p> <pre class="lang-py prettyprint-override"><code>df['sub_ID'] = df.groupby('ID').cumcount().add(1) df['sub_ID'] = df.apply(lambda row: row['Em...
python|pandas|dataframe|dictionary|running-count
1
13,526
73,196,977
Display values of one column when using conditionals based on two other columns
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Country</th> <th>Total Cases</th> <th>Total Deaths</th> <th>Recovered</th> </tr> </thead> <tbody> <tr> <td>China</td> <td>741</td> <td>147</td> <td>987</td> </tr> <tr> <td>Sweden</td> <td>381</td> <td>021</td> <td>242</td> </tr> <tr> <td>Italy</td...
<p>import pandas as pd</p> <pre><code>df = pd.read_csv('test.csv') def check(dframe): for index, row in dframe.iterrows(): if (row['Total Cases']-row['Total Deaths'] &gt; row['Recovered']): print(row['Country']) check(df) </code></pre> <p>With <code>test.csv</code>:</p> <pre><cod...
python|pandas
0
13,527
35,161,956
How to debug shape mismatch of theano tensor?
<p>I defined a Theano tensor <code>m = T.imatrix('m')</code> and used it as an argument of a theano function <code>foo</code>. </p> <p>When I now call <code>foo(arr)</code> with a numpy array <code>arr</code> of shape (100,3), I'd expect that <code>m[:, 1]</code> would have the shape (100,). </p> <p>However, the erro...
<p>Thanks to the useful hints in the comments I was able to debug the shape mismatch. I set up another theano debug function with the same inputs and a custom output, which I could examine with the debugger, e.g.:</p> <pre><code># define a function ... inputs = T.matrix('inputs') debug_out = T.sum(fancy_expression(inp...
python|arrays|numpy|theano
2
13,528
67,310,451
How to read with lines having different number of elements
<p>I have a txt file that look like this:</p> <p>a,b,c<br /> a,b,c,d<br /> a,b<br /> a,b,c,d,e<br /> a,b,c,d</p> <p>with each line having possibly different items. I tried the:</p> <pre><code>df = pd.read_csv('text.txt', sep = ',', header = None) </code></pre> <p>but it gave me error as 'Error tokenizing data'<br /> Do...
<p>Just provide <code>names</code> for all of your columns:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd print(pd.read_csv('text.txt', header=None, names=[0, 1, 2, 3, 4])) </code></pre> <p>Output:</p> <pre><code> 0 1 2 3 4 0 a b c NaN NaN 1 a b c d NaN 2 a b Na...
python|pandas|csv
0
13,529
67,481,332
How to save the best estimator of a RandomizedSearchCV object using Tensorflow SavedModel?
<p>I am trying to save the best estimator from RandomizedSearchCV object using SavedModel format. I know that we can also save it using <code>joblib.dump</code> but I need it to be in the SavedModel format.</p> <p>Commonly, I always use:</p> <pre><code>... .. . model.fit(X,y,epochs=1000) model.save_model(&quot;MyModel&...
<p>According to the error message, you called <code>best_estimator_.saved_model(&quot;MyModel&quot;)</code> instead of <code>best_estimator_.save_model(&quot;MyModel&quot;)</code>. So that typo was probably your mistake.</p> <p>This worked for me:</p> <pre><code>model_search = RandomizedSearchCV() best_model = model_se...
python|tensorflow|keras|scikit-learn|python-3.7
1
13,530
67,240,221
pytorch: RuntimeError: CUDA out of memory. with enough GPU memory
<p>Torch Error:</p> <pre><code>RuntimeError: CUDA out of memory. Tried to allocate 392.00 MiB (GPU 0; 10.73 GiB total capacity; 9.47 GiB already allocated; 347.56 MiB free; 9.51 GiB reserved in total by PyTorch) </code></pre> <p>I checked GPU resource by nvidia-smi, showing no other running process and memory-usage: 10...
<p>I assume you've checked the GPU allocation post the error &quot;CUDA out of memory&quot;. and torch.no_grad() does'nt have anything to do with cuda memory. It depends on the problem you are defining and solving.</p> <p>Try monitoring the cuda memory using <code>watch -n1 nvidia-smi</code>and if you can post the code...
pytorch
0
13,531
60,023,462
what is the name of this graph and how to plot it?
<p>Let say i have these two list.</p> <pre><code>p=[0,0,0,0,1,1,1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4,3,3,3,3,3,5,5,5,5] q=[1,1,1,1,3,3,3,3,3,4,4,4,4,2,2,1,1,1,1,1,2,2,2,2,5,5,5,5,0,0,0,0] </code></pre> <p>I want to plot it like in this picture with the color represent the number in the list like green is 0 or yellow is ...
<p>The given graph can be created using <code>pandas</code> as a horizontal stacked bar chart. You will need to convert your dataset to a dataframe before that though.</p> <pre><code>from itertools import groupby data=[(key,len(list(group))) for key, group in groupby(p)] print(data) list1, list2 = zip(*data) df2=pd....
python|pandas
0
13,532
60,243,960
Remove a row in a dataframe with empty series
<p>I have a column in a data frame. That has an empty series in its row:</p> <pre><code>0 4.5 1 0.5 2 8 3 8 4 ...
<p>You can check if each element is an empty series and then replace all those entries.</p> <p>First, we'll create a test DataFrame.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(0, 100, (3, 3))) df[3] = [1, pd.Series([]), 5] </code></pre> <p>So, we have:</p> <pre><code...
python|pandas|dataframe
1
13,533
60,102,800
Looping through a pandas DataFrame accessing previous elements
<p>I have two DataFrames, <code>FirstColumn</code> &amp; <code>SecondColumn</code>.</p> <p>How do I create a new column, containing the correlation coeff. row by row for the two columns 5 periods back? </p> <p>For example, the 5th row would be the R2 value of the two columns 5 periods back, the 6th row would be the c...
<p>You can do:</p> <pre class="lang-py prettyprint-override"><code>df["corr"]=df.rolling(5, min_periods=1).corr()["FirstColumn"].loc[(slice(None), "SecondColumn")] </code></pre> <p>Outputs:</p> <pre class="lang-py prettyprint-override"><code> FirstColumn SecondColumn corr 0 2.0 1.0 ...
python-3.x|pandas|dataframe
2
13,534
60,121,892
Find index where change in columns occurs for large pandas dataframe
<p>I have a dataframe:</p> <pre class="lang-py prettyprint-override"><code>data = {'A': ['p1', 'p2',"p3",'p1', 'p2',"p3",'p1', 'p2',"p4"], 'time': [0,0,0,40,40,40,80,80,80] } df = pd.DataFrame (data, columns = ['A','time']) df.set_index(["time"],inplace=True) df </code></pre> <p>Output:</p> <pre><c...
<p>You can do something with this strategy:</p> <pre><code>df2 = df.groupby(['time'])['A'].unique().reset_index() time A 0 0 [p1, p2, p3] 1 40 [p1, p2, p3] 2 80 [p1, p2, p4] </code></pre> <p>now shift the previous row:</p> <pre><code>df2['B']=df2['A'].shift(1) time A B 0 0 [p1, p2...
python|pandas|dataframe
1
13,535
60,207,653
Numba: double free or corruption (!prev) Aborted (core dumped)
<p>I'm trying to speed up the following function using numba. </p> <pre><code>import numpy as np from numba import jit, prange @jit(nopython=True, parallel=True) def find_reg_numba(states): reg = [] states_sum = np.sum(states, axis=1) for i in prange(states.shape[0]): if states_sum[i] &gt; 0 a...
<p>Not sure why your code produces an error. Related error posts are:</p> <ul> <li><p><a href="https://github.com/numpy/numpy/issues/10089" rel="nofollow noreferrer">numpy double free or corruption (!prev) segmentation fault</a></p></li> <li><p><a href="https://github.com/tensorflow/tensorflow/issues/6968" rel="nofol...
python|numpy|numba
2
13,536
50,082,506
How to iterate over a 3 dimensional tensor
<p>I have a tensor say:</p> <pre><code>y_true = np.array([[[1.], [0.], [3.]], [[5.], [0.], [0.]]]) </code></pre> <p>I want to iterate over y_true accessing all indevidual values. I want to do something like following in java:</p> <pre><code>for(i=0;i&lt;y_true.length;i++){ arr2 = y_true[i]; for(j=0;j&lt;arr2...
<p>Are you looking for slicing with <code>[:,:,0]</code>?</p> <pre><code>&gt;&gt;&gt; y_true[:,:,0] array([[1., 0., 3.], [5., 0., 0.]]) </code></pre>
numpy|iteration|tensor
1
13,537
64,144,385
How to remove background from an image using TensorFlow Lite?
<p>I am creating an Android App in <strong>Kotlin</strong> in which I want to remove background from a person's portrait image in <strong>real time</strong>.</p> <p>(This code is meant to be imbedded in a video calling app whose one of the feature is to remove person's background during video calls for privacy issues.)...
<p>The project of TF Lite works fine and you get the generated mask from input image... Then you have to use something different to achieve the desired result. Just check out <a href="https://developer.android.com/reference/android/graphics/PorterDuff.Mode?authuser=1" rel="nofollow noreferrer">PorterDuff.Mode</a>!</p> ...
android|tensorflow|kotlin|computer-vision|tensorflow-lite
0
13,538
64,046,765
Replace only specific values in df column based on specific value in another column
<p>I have the following datframe:</p> <pre><code>&gt;&gt;&gt; name ID geom geometry_error 0 Lily 1234 POLYGON ((5.351418786 7.471461148, 5.352018786... overlap 1 Pil 3248 POLYGON ((7.351657486 9.341445548, 1.346718786... overlap 2 Poli 9734 - ...
<p>Use this, nice and simple. <code>np.where</code> is doing the test for you.</p> <p>Code:</p> <pre><code>import numpy as np # ... df['geometry_error'] = np.where(df['geom'] == '-', 'no geometry generated', df['geometry_error']) </code></pre> <p>Outp...
python|pandas|if-statement|replace
1
13,539
46,998,290
Writing a basic XOR neural network program
<p>I am trying to write a neural network that recognizes the xor function from scratch. The full code is <a href="https://pastebin.com/Xm6hWsfR" rel="nofollow noreferrer">here</a> (in python 3).</p> <p>I am currently getting the error :</p> <pre><code>ValueError: No gradients provided for any variable, check your gr...
<p>The error is caused by the use of <code>tf.round</code> when you define <code>A2</code> (<a href="https://github.com/tensorflow/tensorflow/issues/5888" rel="nofollow noreferrer">known issue</a>, by the way). </p> <p>In this particular task, the solution is simply not to use <code>tf.round</code> at all. Remember th...
python-3.x|machine-learning|tensorflow|neural-network|xor
0
13,540
46,750,798
Best method to import multiple related excel files having multiple sheets in Pandas Dataframe
<p>I have 20 excel files, each represent a year, each one of them have 10 sheets of different (but related to each other) data for that year.</p> <p>How to properly import them all in pandas dataframe for purpose of Data analysis for the whole period?</p> <p>To illustrate more, for example: Should I use a Dict for ea...
<p>This should work with ExcelFile and concat. Update based on comment:</p> <pre><code>import pandas as pd location1 = r'Location1.xlsx' location2 = r'Location2.xlsx' locations = [location1, location2] frames = [] for loc in locations: file = pd.ExcelFile(loc) df = file.parse('Sheet1') df['source'] = l...
python|pandas|dataframe
0
13,541
32,616,261
Filtering pandas dataframe rows by contains str
<p>I have a python pandas dataframe <code>df</code> with a lot of rows. From those rows, I want to slice out and only use the rows that contain the word 'ball' in the 'body' column. To do that, I can do:</p> <p><code>df[df['body'].str.contains('ball')]</code></p> <p>The issue is, I want it to be case insensitive, m...
<p>You could either use <code>.str</code> again to get access to the string methods, or (better, IMHO) use <code>case=False</code> to guarantee case insensitivity:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({"body": ["ball", "red BALL", "round sphere"]}) &gt;&gt;&gt; df[df["body"].str.contains("ball")] body 0 b...
python|string|pandas
58
13,542
32,871,228
ternary expression dependent on two columns
<p>Say we have a data set similar to:</p> <pre><code>DF = pd.DataFrame({'Time':[1,2,3,4,5,6,7,8,9,10],'Value': [1,3,5,5,6,8,9,5,6,7]}) </code></pre> <p>giving:</p> <pre><code> Time Value 0 1 1 1 2 3 2 3 5 3 4 5 4 5 6 5 6 8 6 7 9 7 8 4 8 9...
<p>I find it easy to use numpy.where in these situations:</p> <pre><code>import numpy as np DF['Value'] = np.where((DF.Time &gt; 5) &amp; (DF.Value &gt; 5),0,DF.Value) </code></pre> <p>*To add to this answer, in case there are more conditions that you want to satisfy you can add them to the above code like:</p> <pre...
python|pandas
5
13,543
63,158,883
Python Group by Bucketing
<p>I am trying to rank the following df based on the Sharpe grouped by Year/Month. For instance , in January 2018, I would like to look at the Sharpe’s for Stock 1,2,3 with the values of 0.4,0.3 and 0.6 respectively and rank them between the scale of 1 (low score) – 5(highest score). My criteria would be if the if Shar...
<p>Looked at your requirement rather than specific approach. Key point <code>apply()</code> on a <code>groupby()</code> gives a dataframe so <code>lambda</code> function needs to operate on a dataframe which is subset of data defined by <code>groupby()</code></p> <ol> <li>generate a larger test dataset</li> <li><code>...
python|pandas
0
13,544
67,668,232
Getting same runtime for cpu and gpu on Google Colab
<p>So I've been experiencing with Colab in order to conduct my deep learning project for my Bachelor's. When I run the provided example on colab to test the comparison speed between cpu and gpu it works fine, however when I try with my own code, I get the same run time for both. The task that I was conducting was simpl...
<p>Tensorflow device setting won't affect non-Tensorflow operations.</p> <p>That said, Tensorflow has now it's own <a href="https://www.tensorflow.org/guide/tf_numpy#device_placement" rel="nofollow noreferrer">numpy API</a> that can use the device that is set up for Tensorflow in e.g. <code>with tf.device('/device:GPU:...
python|tensorflow|google-colaboratory
0
13,545
67,853,961
python reorder a column and the dataframe in a desired order
<p>I have a data frame with repeating string values. I want to reorder in a desired order.</p> <p>My code:</p> <pre><code>df = name 0 Fix 1 1Ax 2 2Ax 3 2Ax 4 1Ax 5 Fix df.sort_values(by=['name'],ignore_index=True,ascending=False)) print(df) df = name 0 Fix 1 Fix 2 2Ax ...
<p>Currently you are sorting in reverse alphabetical order: so 'F' comes before '2' which comes before '1'. Changing <code>ascending</code> to True will place 'Fix' at the bottom.</p> <p>It's a bit of a hack, but you could pull out the rows where the first character is number of sort them separately...</p> <pre class="...
python|pandas|dataframe|sorting
1
13,546
67,976,604
Open/ read rw2 image with color using python?
<p>Can someone open this raw file with color? It is an image and I tried everything with numpy, rawpy, fastrawviewer etc. It is almost 3 days I try to open with color but I failed.</p> <pre><code>import numpy as np import cv2 fd = open('img.rw2', 'rb') ROWS = 2000 COLS = 2000 f = np.fromfile(fd, dtype=np.uint8,count=RO...
<p>If your image was 2000x2000 RGB it would be 12,000,000 bytes, but it is 16,000,000. So try reading it as RGBA, rather than RGB.</p> <pre><code>im = np.fromfile('img.raw', dtype=np.uint8).reshape((2000,2000,4)) </code></pre> <p>[![enter image description here][1]][1]</p> <p>If the image was saved as RGBA, you will ne...
python|numpy
1
13,547
67,789,639
What do the arguments for TFRecordOptions actually mean (wrt tf.io.TFRecordWriter)?
<p>I export some fairly large Pandas dataframes to Tensorflow's serialized format. And I do it often and it's really slow. Which is probably because I have to serialize the individual examples idk. Also, I compress the files with the &quot;GZIP&quot; option.</p> <p>I have found some options for the TFRecordWriter in th...
<p>Some description is given in <a href="https://github.com/tensorflow/tensorflow/blob/a4dfb8d1a71385bd6d122e4f27f86dcebb96712d/tensorflow/python/lib/io/tf_record.py#L65" rel="nofollow noreferrer">tf_record.py</a>. That will point to the zlib library which gives some more complete information.</p> <p>Sadly, the text i...
python|tensorflow|tfrecord
0
13,548
67,796,669
Is there an easy way to establish a hierarchy between entities using only 2 ID fields?
<p>I have a table with 2 fields like so:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Account_ID</th> <th>Parent_ID</th> </tr> </thead> <tbody> <tr> <td>x</td> <td>y</td> </tr> <tr> <td>x1</td> <td>y</td> </tr> <tr> <td>x2</td> <td>y</td> </tr> <tr> <td>y</td> <td>z</td> </tr> <tr> <td>y...
<p>This does the trick. Advantageously it only relies on pandas and a small function.</p> <pre class="lang-py prettyprint-override"><code>def add_hierarchy(df, s, tier): df['Hierarchy'] = df['Account_ID'] for i in range(tier): next_tier = s.apply(lambda x: df[df['Account_ID'] == x].iloc[0]) df['...
python|python-3.x|pandas|dataframe
1
13,549
31,887,463
Passing a dataframe as an an argument in apply with pandas
<p>I'm trying to use <code>.apply()</code> with a dataframe as one of the arguments:</p> <pre><code>df.apply(func, axis=1, args=(df)) </code></pre> <p>When I do, I get the following error:</p> <pre><code>ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). </c...
<p>Ok, the problem here is the combination of <code>func</code> and <code>apply</code>. The <code>apply</code> method of a dataframe applies the given function to each COLUMN in the data frame and returns the result. So the function you pass to <code>apply</code> should expect a pandas Series or an array as input, not ...
python|numpy|pandas
0
13,550
31,917,249
Pandas Pivot Tables- Unexpected keyword 'cols'
<p>I'm trying to make a pivot table using pd.pivot_table. </p> <pre><code>df1=df.pivot('Partner','Year','Value') </code></pre> <p>works no problem and produces a table </p> <pre><code>Year 2011 2012 2013 2014 Partner ...
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="noreferrer">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html</a></p> <p>Check this documentation of pandas pivot table function. There is no parameter named cols. There used to be 'cols' in olde...
python|pandas|dataframe|pivot-table|keyword-argument
8
13,551
41,311,735
role of [:] in numpy
<p>What is the role of <code>[:]</code> in this program:</p> <pre><code>import numpy as np l=np.array([[0,0,0,0], [4,5,6,7], [7,8,9,8]]) out[:]=np.nanstd(l, axis=0) print(out) </code></pre> <p>If I write the third line of the code just like this (i.e., without <code>[:]</code>):</p> <pre><cod...
<p>A <code>Jupyter/ipython</code> session maintains an <code>Out</code> dictionary that contains history. But <code>Out[:]</code> would give an error.</p> <p>In a fresh session, this produces an error:</p> <pre><code>In [731]: out[:]=np.array([1,2,3]) .... NameError: name 'out' is not defined </code></pre> <p>But i...
python|numpy
1
13,552
27,659,235
Adding multiple constraints to scipy minimize, autogenerate constraint dictionary list?
<p>Is there a way to autogenerate a dictionary list of multiple constraints in scipy.minimize? When I use the following code (where the list constraint is a list of sage multivariate polynomials over the same ring)</p> <pre><code>cons = [{'type': 'eq', 'fun': lambda s: ((constraint[0])(*s))}, {'type': 'eq', 'f...
<p>The problem is in your loop. The <code>lambda</code> operator performs what is called a <strong>lazy</strong> evaluation. At the end of your loop, the lambda the cons is performing the function on the last value of <code>ii</code>, instead of on each index.</p> <p>To perform a <strong>strict</strong> evaluation, yo...
python|numpy|scipy|sage
5
13,553
61,509,971
Python DataFrame using a small section from a large text file
<p>Here is my code so far:</p> <pre><code>import pandas as pd with open("input.txt") as f: data = f.readlines() for line in data: data = {'col1': [line[':']], 'col2': [line[':']], 'col3': [line[':']], 'col4': [line[':']]} df = pd.DataFrame(data) print(df) </code></pre> <p>The problem ...
<p>You are getting a single-row dataframe because the dataframe constructor is in the loop that goes over every line of the file.</p> <pre><code>for line in data: data = ... df = pd.DataFrame(data) </code></pre> <p>It isn't clear what your end goal is here, but I would look at the various options for <code>pa...
python|pandas|file|dataframe|text
0
13,554
61,335,816
Using beautifulsoup to extract information within pre, turning it into a table to csv
<p>I am trying to extract the text from the below site shown within the code. </p> <p>While I can print the list fine, I can't seem to turn it into a pandas dataframe, and print it out as a csv.</p> <p>This is a site that only has the pre info. </p> <p>Please let me know if there is way to do this. </p> <pre><code>...
<p>Not the most robust, but you can iterate line by line to parse the data you need:</p> <pre><code>import requests import pandas as pd from io import StringIO #url list for the new stations url1="https://www.kyoshin.bosai.go.jp/cgi-bin/kyoshin/db/sitedat.cgi?1+NIG010+knet" tt1="C:/temp/" page = requests.get(url1...
pandas|csv|web-scraping|beautifulsoup|pre
0
13,555
61,408,755
How do I predict on more than one batch from a Tensorflow Dataset, using .predict_on_batch?
<p>As the question says, I can only predict from my model with model.predict_on_batch(). Keras tries to concatenate everything together if I use model.predict() and that doesn't work.<br> For my application (a sequence to sequence model) it is faster to do grouping on the fly. But even if I had done it in Pandas and th...
<p>You can iterate over the dataset, like so, remembering what is "x" and what is "y" in typical notation:</p> <pre><code>for item in ds: xi, yi = item pi = model.predict_on_batch(xi) print(xi["group"].shape, pi.shape) </code></pre> <p>Of course, this predicts on each element individually. Otherwise you'd...
python|tensorflow|keras|tensorflow-datasets|seq2seq
1
13,556
68,632,004
Error when try adding a column to a dataframe
<p>I am trying first to slice a some columns from original dataframe and then add the additional column 'INDEX' to the last column.</p> <pre><code> df = df.iloc[:, np.r_[10:17]] #col 0~6 df['INDEX'] = df.index #col 7 </code></pre> <p>I have the error message of second line saying 'A value is trying to be set o...
<p>I would do</p> <pre><code>df.loc[:,'INDEX'] = df.index </code></pre>
python|pandas|dataframe
0
13,557
68,592,172
How to use rgb value to add color in pandas.scatter_matrix?
<p>I want to add color in <code>pd.scatter_matrix</code>, the rgb value like that,</p> <pre><code> val_rgb = [[127 80 34] [130 89 34] [170 133 75] ...] </code></pre> <p>I once use them in scatter3D them like that,</p> <pre><code>for i in range(0, len(df)): ax1.scatter3D( df[i,0], ...
<p>You can specify a color using RGB format using a tuple of float values between 0 and 1. Thus simply divide the RGB values by 255:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np import pandas as pd N = 500 data = pd.DataFrame(np.random.randn(N, 4), columns=['A'...
python-3.x|pandas|matplotlib|seaborn|data-visualization
1
13,558
68,856,373
pandas.errors.ParserError: Error tokenizing data with data which made no mistake before
<p>I am trying to solve <code>pandas.errors.ParserError: Error tokenizing data</code> problem.</p> <p>I have two types of data.</p> <p>I use a same code but it does not work with a type of data as I attach below. (It works well with another)</p> <pre><code>(msnoise) [sujan@node01 MSNoise_test2]$ msnoise plot dvv Traceb...
<p>I find the solution. The reason was the environment variable. I add python path there for solving <code>no module</code> problem which occurred before <code>parsererror</code>. But it was not the solution for the <code>no module</code> problem but to edit bashrc. Anyway, when I delete the python path in the environm...
python|pandas|tokenize
0
13,559
68,576,189
Converting dataframe to json
<p>i want to transform following dataframe</p> <pre><code>| id | date | score | | --- | ------------ | ----- | | 1 | 2021-01-01 | 1 | | 1 | 2021-01-02 | 2 | | 1 | 2021-01-03 | 3 | </code></pre> <p>into json of following format</p> <p><code>[{id: 1}, {date: 2021-01-01, score: 1}, {date: ...
<p>There is a native <code>to_json()</code> method to the pandas <code>DataFrame</code>: The orient parameter will help you out with the output format.</p> <pre><code>df.to_json(filepath, orient='records') </code></pre> <p>This should do it:</p> <pre><code>import pandas as pd df = pd.DataFrame([{'id': 1, 'date': '2021-...
python|pandas|dataframe
2
13,560
68,765,906
Combine images using numpy.concatenate
<p>I want to combine 5 png figures into one png or jpg file using the code in <a href="https://stackoverflow.com/a/55387451/3084842">this answer</a>. I want the final figure to look like:</p> <p><a href="https://i.stack.imgur.com/YD6FO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YD6FO.png" alt="e...
<p>Concatenate is an array manipulation. It combines multiple arrays into a single array. Each image can be seen as a array with the shape height x width x num_channels (not that height and width are swapped).</p> <p>If I take 3 gray scale image 200 by 100 pixels I have 3 arrays of 100 x 200 x 1. If I Concatenate them ...
python|image|numpy|python-imaging-library
0
13,561
53,281,433
How to check if panda dataframe group have same data
<p>I have a pandas dataframe as below</p> <pre><code>id name Base field1 field2 field3 1 AA Y Yes Consumer Not Applicable 1 BB N Yes Consumer Not Applicable 2 CC Y Yes Consumer Not Applicable 2 DD N Yes Not Appl...
<p>You may get what you want with the code (assuming that <code>df</code> has index named <code>id</code>):</p> <pre><code>def handler(df): for col in ['field1', 'field2', 'field3']: if df.loc[:, col].nunique() &gt; 1: return 'error in {} for id {}'.format(col, df.index[0]) else: re...
python-3.x|pandas|dataframe|pandas-groupby
0
13,562
65,505,697
Pandas dataframe not properly sorted
<p>I have several excel data files, each one referring to a different timing (i.e. 0h, 24h, 48h, ...), and the columns with the data of interest are named: 'Product' and 'Value'. I have concatenated those files by using the following:</p> <pre><code>result = pd.concat([pd.read_excel(file) for file in filenames], keys=t...
<p><em>Can someone shed a light on this?</em></p> <p>Default sorting algorithm of <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer">sort_values</a> is not stable, therefore order of elements with equal <code>Product</code> might be different...
python|pandas|dataframe|sorting
1
13,563
63,508,675
What does Default MaxPoolingOp only supports NHWC on device type CPU [[{{node maxpool4/MaxPool}}]] mean?
<p>I'm attempting to write the squeezenet CNN found in matlab inside python. In my attempt of doing so I got an error. I found the inspiration for this code on github and will link the person as well to make sure they get the credit they deserve. <a href="https://github.com/chasingbob/squeezenet-keras" rel="nofollow no...
<p>Posting answer here for the benefit of the community.</p> <p>Upgrading the Tensorflow version to <strong>2.3</strong> solved the issue.</p> <p>You can use the below line to upgrade the Tensorflow version.</p> <pre><code>pip install --user --upgrade tensorflow </code></pre> <p>Additionally, you can also try with belo...
python|tensorflow|scikit-learn|conv-neural-network
2
13,564
63,689,072
Issues with TensorFlow and Keras in-term of Keras optimizer
<p>currently I am learning the basics of chatbot programming and have little or none experience with TensorFlow and Keras. while coding my program I came upon an error message : <strong>AttributeError: module 'keras.optimizers' has no attribute 'TFOptimizer'</strong> Version : Tensorflow 2.1.0 : keras 2.3.1 : Python 3....
<p><code>keras</code> and <code>tensorflow.keras</code> are two different implementations of the Keras API and as such should not be mixed. <a href="https://twitter.com/fchollet/status/1174018651449544704?s=19" rel="nofollow noreferrer">According to the creator of the Keras API</a>, users should prefer the <code>tensor...
python|tensorflow|machine-learning|keras|deep-learning
1
13,565
63,431,758
While performing a diff function how to only perform when the data is not zero or not to consider the first and last value after a zero
<p><a href="https://i.stack.imgur.com/jk8ij.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jk8ij.jpg" alt="enter image description here" /></a>I have a data frame X which will always have zeros to start with and ends with zeroes so I am performing the .diff() function on the sun column to get the di...
<h3>If no zeroes in valid data range:</h3> <pre><code>df.loc[~df['sun'].eq(0), 'sun'].diff().fillna(0).reindex(df.index, fill_value=0) </code></pre> <p>Output:</p> <pre><code>2020-07-20 03:05:00 0.0 2020-07-20 03:10:00 0.0 2020-07-20 03:15:00 0.0 2020-07-20 03:20:00 0.0 2020-07-20 03:25:00 0.0 2020-...
python|pandas|dataframe|diff
1
13,566
63,320,577
Getting the Euclidean distance of X and Y in Python
<p>I'm fairly new to python so I hope somebody can help me. we have two arrays X and Y</p> <pre><code>X=np.array([[ 5.43840675, -1.05259078, -0.21793506, 8.56686818, -2.58056957, -0.07310339, -0.31181501, 0.02696586], [ 5.72318296, -0.99665473, -0.14540062, 8.32051008, -3.36201189, -0.04897565...
<p>based on the <a href="https://en.wikipedia.org/wiki/Euclidean_distance" rel="nofollow noreferrer">Euclidean distance</a> formula:</p> <pre><code>import math x = [ 5.72318296, -0.99665473, -0.14540062, 8.32051008, -3.36201189, -0.04897565, -0.34271698, -0.0339766 ] y = [ 5.72318296, -0.99665473, -0.14540062, 8.3205...
python|numpy
1
13,567
63,326,544
concat two df by two equal columns pandas python
<p>i got two df with two similar columns but different names , and i want to concat them by the similar columns</p> <p>that is my df</p> <pre><code>data={&quot;col1&quot;:[&quot;A&quot;,&quot;B&quot;,&quot;D&quot;,&quot;f&quot;], &quot;col2&quot;:[4,2,4,6], &quot;col3&quot;:[7,6,9,11], &quot;col4&quot;:[14,11,22,8], &q...
<pre><code>df1.merge(df2, left_on='col1', right_on='col5').drop('col5', axis=1) </code></pre>
python|pandas|dataframe|merge|concat
1
13,568
24,601,424
add different data at the end of different lines in a file
<p>I have a txt file with the following structure:</p> <p><img src="https://i.stack.imgur.com/OtJxI.png" alt="original.txt file"></p> <p>and I want to add to the end of each long line, the data (after the comma) of the short lines above them, without the description (STN_NO, STN_ID, INST_HT), like that:</p> <p><img ...
<p>Let's assume this simplified version of the file in your image:</p> <pre><code>STN_NO, 41943043 STN_ID, KAST INST_HT, 1.01500; Line 1 Line 2 Line 3 STN_NO, 41943062 STN_ID, S2 INST_HT, 0.75; Line 4 Line 5 Line 6 STN_NO, 123456 STN_ID, XXX INST_HT, 0.99; Line 7 Line 8 Line 9 </code></pre> <p>You can use a regex to ...
csv|python-3.x|numpy|append
1
13,569
30,090,151
how to collapse/compress/reduce string columns in pandas
<p>Essentially, what I am trying to do is join Table_A to Table_B using a key to do a lookup in Table_B to pull column records for names present in Table_A. </p> <p>Table_B can be thought of as the master name table that stores various attributes about a name. Table_A represents incoming data with information about a ...
<p>You can drop duplicates based on columns <code>raw_name_left</code> and also remove the <code>raw_name_right</code> column using <code>drop</code></p> <pre><code>In [99]: df_new.drop_duplicates('raw_name_left').drop('raw_name_right', 1) Out[99]: raw_name_left real_name stats1 stats2 stat...
python|pandas|group-by
2
13,570
29,886,466
Distribution-type graphs (histogram/kde) with weighted data
<p>In a nutshell, what is my best option for a distribution-type graphs (histogram or kde) when my data is weighted?</p> <pre><code>df = pd.DataFrame({ 'x':[1,2,3,4], 'wt':[7,5,3,1] }) df.x.plot(kind='hist',weights=df.wt.values) </code></pre> <p>That works fine but seaborn won't accept a weights kwarg, i.e.</p> <pr...
<p>You have to understand that seaborn uses the very matplotlib plotting functions that also pandas uses.</p> <p>As the <a href="http://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.distplot.html" rel="noreferrer">documentation</a> states, <code>sns.distplot</code> does not accept a <code>weights</code> arg...
python|pandas|matplotlib|bokeh|seaborn
7
13,571
53,596,289
Length of values does not match length of index (Kaggle Submission)
<p>I am trying to merge a scored dataset into the original field name and I get the error: Length of values does not match length of index</p> <p>Does anyone know what this one means? </p> <p>here is my Kaggle URL for this Kernel: <a href="https://www.kaggle.com/jrichie/nyc-taxi-fare-eda-and-random-forest-model" rel=...
<p>You can find the answer <a href="https://stackoverflow.com/questions/42382263/valueerror-length-of-values-does-not-match-length-of-index-pandas-dataframe-u">here</a> (pretty common question)</p> <p>Based on your kernel, it looks like your <code>rf_predict</code> array has 9824 rows whereas your <code>submission</co...
python|pandas
0
13,572
53,448,202
Square array from linear array python
<p>I would like to get a square matrix <code>B</code> from a linear vector <code>A</code> such that <code>B = A * transpose(A)</code>. <code>A</code> is a numpy array and <code>np.shape(A)</code> returns <code>(10,)</code>. I would like <code>B</code> to be a <code>(10,10)</code> array. I tried <code>B = np.matmut(A, A...
<p>you can do this using <code>outer</code>:</p> <pre><code>import numpy as np vector = np.arange(10) np.outer(vector, vector) </code></pre>
python|arrays|numpy|matrix|vector
3
13,573
53,691,438
Find all sets of 4 coplanar points in an array of 3D points using Numpy
<p>Say that I have a list of <code>n</code> 3D points stored in a Numpy array of shape <code>(3, n)</code>. I want to find all of the sets of 4 points in that list such that the 4 points are coplanar. How can I do that?</p> <p>For example, given an array of <code>points</code> containing the 8 vertices (in no particul...
<p>The following might not be a very <em>fast</em> solution, but it works and makes mathematical/geometrical sense.<br> But first - please note that your example has <strong>12</strong> subsets of 4 coplanar points, not 8, due to having "diagonal" planes going through your cube. That can be formalized but should be cle...
python|arrays|numpy|scipy|computational-geometry
1
13,574
15,833,190
Sympy: generate figure with multiple subplots
<p>I'm using sympy and matplotlib, and wish to generate a figure with multiple plots, similarly to how it's done using pylab.subplot when using numpy. This should be trivial, or so I thought...</p> <p>To my surprise I didn't find a simple way to do it. Either (a) evaluate a SymPy expression at multiple points and get ...
<p>It depends on the version of SymPy that you are using.</p> <p>In the latest version (0.7.2) you already have a plotting module that is guaranteed to be able to plot <em>anything</em> and that can use as a backend matplotlib.</p> <p>In older versions you have the option to use <code>lambdify</code> which is a hacki...
python|numpy|matplotlib|sympy
6
13,575
12,268,526
Non distinct prime factors of larger numbers
<p>I wrote and use this function to produce prime factors of a number:</p> <pre><code>import numpy as np from math import sqrt def primesfrom3to(n): """ Returns a array of primes, p &lt; n """ assert n&gt;=2 sieve = np.ones(n/2, dtype=np.bool) for i in xrange(3,int(n**0.5)+1,2): if sieve[i/2]:...
<p>The traditional way to do this is to divide out each prime factor in turn and then recurse on your factorisation method. This will in general be faster than sieving for all of the primes, because you only care about the (few) primes that actually divide your number.</p> <p>Of course, there are many, many better pri...
python|math|numpy
8
13,576
72,059,034
How to set multiple conditions using an iteration for python
<p>I am looking for a gradient pattern on my dataframe as follows:</p> <pre><code>df.loc[( (df['A'].shift(-0).lt(1.7)) &amp; (df['A'].shift(-1).lt(1.7)) &amp; (df['A'].shift(-2).lt(1.7)) &amp; (df['A'].shift(-3).lt(1.7)) &amp; (df['A'].shift(-4).lt(1.7)) &amp; (df['A'].sh...
<p>You can try use <code>reduce</code> on list</p> <pre class="lang-py prettyprint-override"><code>from functools import reduce m = reduce((lambda df1, df2: df1&amp;df2), [df['A'].shift(-s).lt(v) for s, v in parameters]) </code></pre> <pre><code>print(df.loc[m]) A 358 1.4375 359 1.4375 360 1.5000 361 1....
python|pandas|iteration|multiple-conditions|pandas-loc
0
13,577
72,138,311
When using read_sql_query in pandas, how to write the SQL across multiple lines?
<p>my question is pretty much what it sounds like: Is it possible to write my SQL across multiple lines for ease of reading when using the read_sql_query method please? For example, to make this:</p> <pre><code>v_df = pd.read_sql_query( sql = &quot;SELECT EVENT_INVITE, COUNT(ACCOUNT_NUMBER) AS CUSTOMERS FROM CS.SM_...
<p>python multiline string is your best bet here. So in your case:</p> <pre><code>v_df = pd.read_sql_query( sql = &quot;&quot;&quot; SELECT EVENT_INVITE, COUNT(ACCOUNT_NUMBER) AS CUSTOMERS FROM CS.SM_MAR22_FINAL GROUP BY EVENT_INVITE ORDER BY EVENT_INVITE ;&quot;...
python|pandas
1
13,578
72,097,015
How to duplicate each row having only one column different than the previous row pandas data frame?
<p><img src="https://i.stack.imgur.com/3nDlQ.png" alt="enter image description here" /></p> <p>I have a big data and I want to duplicate each row just below the original column by changing just one column value</p> <p>I want to copy the previous row value in place of &quot;same&quot; and I want to change the last colum...
<p>Assuming this input:</p> <pre><code>A B C D E F 45 20 A1 46 20 A2 45 20 B2 46 20 B1 46 20 A2 47 20 A1 46 20 B1 47 20 B2 </code></pre> <p>and the fact that you want to duplicate rows while getting the values of C for column F:</p> <pre><code>out = (pd.concat([df, df.assign(F=df['C'])]) .sort_...
pandas|dataframe
0
13,579
22,340,808
Plotting a Discriminant Function for Normal Densities via Matplotlib
<p>I want to plot the general discriminant function for normal densities for some random data. I have no idea how I would go about it via matplotlib, I hope anyone could help me a little bit.</p> <p>The equation would be:</p> <p><img src="https://i.stack.imgur.com/IaWNR.png" alt="enter image description here"> <img s...
<p>Here is the code:</p> <pre><code>import pylab as pl import numpy as np D = 2 M1 = np.array([0.0, 0.0]) M2 = np.array([1.0, 1.0]) C1 = np.array([[2.0, 0.4], [0.4, 1.0]]) C2 = np.array([[1.0, 0.6], [0.6, 2.0]]) X, Y = np.mgrid[-2:2:100j, -2:2:100j] points = np.c_[X.ravel(), Y.ravel()] invC = np.linalg.inv(C1) v ...
python|numpy|matplotlib|classification
1
13,580
17,713,050
Display a georeferenced DEM surface in 3D matplotlib
<p>I want to use a DEM file to generate a simulated terrain surface using matplotlib. But I do not know how to georeference the raster coordinates to a given CRS. Nor do I know how to express the georeferenced raster in a format suitable for use in a 3D matplotlib plot, for example as a numpy array. </p> <p>Here is...
<p>You can use the normal <code>plot_surface</code> method from matplotlib. Because it needs a X and Y array, its already plotted with the right coordinates. I always find it hard to make nice looking 3D plots, so the visual aspects can certainly be improved. :)</p> <pre><code>import gdal from mpl_toolkits.mplot3d imp...
python|numpy|matplotlib|gdal|osgeo
3
13,581
55,208,723
Parsing output from scraped webpage using pandas and bs4: way to make output more readable?
<p>I wanted to scrape <a href="http://yadamp.unisa.it/showItem.aspx?yadampid=18" rel="nofollow noreferrer">this</a> page.</p> <p>I wrote this code:</p> <pre><code>import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("http://yadamp.unisa.it/showItem.aspx?yadampid=18") soup = BeautifulS...
<p>You can use pandas <code>read_html()</code> to get the table and then navigate the table using pandas <code>DataFrame()</code>, see the code below!</p> <pre><code>url = 'http://yadamp.unisa.it/showItem.aspx?yadampid=18' table = pd.read_html(url, attrs={ 'class': 'table table-responsive'}, header=0) print(pd.Dat...
python|pandas|beautifulsoup|python-requests
1
13,582
55,424,897
Optimal method for tensor assignment on a "sparse" tensor for Keras
<p>I'm trying to create a multi-dimensional array of size <code>n</code> (where <code>n</code> is a part of symbolic shape tensor). This array shall have <code>0</code> in every region but few where it will be a variable <code>b_class</code>.</p> <p>Here's a simple <code>Numpy</code> implementation of this, but in thi...
<p>Yes, there is. You could use <a href="https://www.tensorflow.org/api_docs/python/tf/scatter_nd" rel="nofollow noreferrer">tf.scatter_nd</a> to apply the sparse updates. Here's an example:</p> <pre><code>import tensorflow as tf n = tf.constant([100]) index_tensor = tf.constant([[10], [99], [50], [70]]) updates = tf...
python|tensorflow|keras
0
13,583
55,327,282
Pandas row to list (only the values)
<p>I want to take the values from a specific pandas row and save them to a list, but I don't get only the values. What I am doing wrong? For example i want only the first row</p> <p>thanks</p> <pre><code>list = [] n = 10 for i in range(n): x = dtest.iloc[[0],i] list.append(x) </code></pre> <pre><code>list [...
<p>You could use the built-in method <code>tolist</code>. Try:</p> <pre><code>dtest.iloc[0].tolist() </code></pre>
python|pandas
0
13,584
55,390,492
RuntimeError: b'no arguments in initialization list'
<p>I'm trying to solve my issue in my own but I couldn't, I'm trying to run this code in every format you can imagine and in ArcGIS pro software it's the same I can't find this error message in any other issue. From similar issues, it seems some data files could be missing?</p> <pre><code>import geopandas as gpd impor...
<p>to make sure this is pyproj error rather than geopandas.</p> <pre><code>import pyproj pyproj.Proj("+init=epsg:4326") </code></pre> <p>if the above runtime error is the same, we can be sure this error is due to pyproj.</p> <p>just <code>conda remove pyproj</code> and install it with pip.</p> <pre><code>pip instal...
python|machine-learning|arcpy|geopandas|pyproj
24
13,585
26,089,670
Unable to apply methods on timestamps using Series built-ins
<p>On the following series:</p> <pre><code>0 1411161507178 1 1411138436009 2 1411123732180 3 1411167606146 4 1411124780140 5 1411159331327 6 1411131745474 7 1411151831454 8 1411152487758 9 1411137160544 Name: my_series, dtype: int64 </code></pre> <p>This command (convert to timestamp, lo...
<p>As Jeff's answer mentions, <code>tz_localize()</code> and <code>tz_convert()</code> act on the index, not the data. This was a huge surprise to me too.</p> <p>Since Jeff's answer was written, Pandas 0.15 added a new <code>Series.dt</code> accessor that helps your use case. You can now do this:</p> <pre><code>pd....
python|numpy|pandas|timestamp
89
13,586
66,863,467
Argument of type 'Timestamp' is not iterable?
<p>in my code I've generated a range of dates using <code>pd.date_range</code> in an effort to compare it to a column of dates read in from excel using pandas. The generated range of dates is refered to as &quot;all_dates&quot;.</p> <pre><code>all_dates=pd.date_range(start='1998-12-31', end='2020-06-23') for i, da...
<p>I think you are trying to create a NaN row if the date does not exist in the excel file.</p> <p>Here's a way to do it. You can use the <a href="https://pandas.pydata.org/docs/user_guide/merging.html#brief-primer-on-merge-methods-relational-algebra" rel="nofollow noreferrer"><code>df.merge</code></a> option.</p> <p>I...
python|pandas
2
13,587
66,855,359
How do I find percentage difference from the first row and subsequent rows in pandas?
<p>So I have a dataframe with certain values and I want to find the percentage difference from year 2020 for the subsequent time periods.</p> <p>My dataframe is something like this:</p> <pre><code>Years A B C D E 2020 801.566522 769.2986786 830.8725406 830.87254...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.squeeze.html" rel="nofollow noreferrer"><code>df.squeeze</code></a> with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>df.iloc</code></a>:</p> <pre><code>In [877]: df.iloc[:,...
python|python-3.x|pandas|dataframe
2
13,588
66,921,599
Is it possible to create a model in Keras Functional API without an input layer?
<p>I would like to create a model consisting of 2 convolutional, one flatten, and one dense layer in Keras. This would be a model with shared weights, so without any predefined input layer.</p> <p>It is possible to do using the sequential way:</p> <pre><code>model = tf.keras.models.Sequential() model.add(tf.keras.layer...
<p>The keras sequential api is designed to be easier to use, and as a result is less flexible than the functional api. The benefit of this is that an input 'layer' shape can be inferred automatically by whatever shape of the data you pass to it. The downside is that this easier to use model is simplified, and so you ca...
python|tensorflow|keras|functional-api
2
13,589
47,398,081
How do I map df column values to hex color in one go?
<p>I have a pandas dataframe with two columns. One of the columns values needs to be mapped to colors in hex. Another graphing process takes over from there.</p> <p>This is what I have tried so far. Part of the toy code is taken from <a href="https://stackoverflow.com/questions/28752727/map-values-to-colors-in-matpl...
<p>You may use <a href="https://matplotlib.org/api/_as_gen/matplotlib.colors.to_hex.html#matplotlib.colors.to_hex" rel="nofollow noreferrer"><code>matplotlib.colors.to_hex()</code></a> to convert a color to hexadecimal representation.</p> <pre><code>import pandas as pd import matplotlib import matplotlib.pyplot as plt...
python-3.x|pandas|matplotlib|colors
6
13,590
47,159,554
Sum unique values by group with pandas
<p>I got a dataframe like this:</p> <pre><code>data = { 'YEAR' : [2018,2018,2017,2018,2018,2018], 'SEASON': ['SPRING', 'SPRING', 'WINTER', 'SPRING', 'SPRING', 'SPRING'], 'CODE': ['A', 'A', 'A', 'B', 'C', 'D'], 'BUDGET': [500,200,300,4000,700,0], 'QUANTITY': [1000,1000,1000,2000,300,4000]...
<p>Based on your comments, a slightly more involved procedure is required to get your result. The solution for <code>QUANTITY</code> is very similar to how it is in jezrael's answer with <code>apply</code>, so thanks to him.</p> <pre><code>df BUDGET CODE QUANTITY SEASON YEAR 0 500 A 1000 SPRING 20...
python|pandas|dataframe|group-by|pandas-groupby
15
13,591
68,196,183
string.split() giving memory error in pandas dataframe
<p>I am trying to split string but getting memory error. Is there any way to solve this or alternative solution for this?</p> <p>I am getting error below code -</p> <pre><code>content_str = str(content_str).split('\n') df1 = pd.DataFrame(content_str) df1 = df1[0].str.split(',', expand=True) </code></pre> <p>Error-</p> ...
<p>Since you are splitting a huge string using a df column, then deleting the df, looks like you only need the count of commas for each row. So get the count, which is simple, rather than splitting the df -- which could generate a huge amount of columns and therefore cause your memory error.</p> <pre><code>row1list = ...
python|python-3.x|pandas|dataframe|out-of-memory
0
13,592
68,304,283
Why does pandas.DatetimeTZDtype compare equal to numpy.dtype("O")? Is this expected?
<p>I was surprised to find that <code>pandas.DatetimeTZDtype</code> compares equal to <code>numpy.dtype(&quot;O&quot;)</code>:</p> <pre><code>&gt;&gt;&gt; numpy.dtype(&quot;O&quot;) == pandas.DatetimeTZDtype True </code></pre> <p>I ran into this in a unit test, where a test was unexpectedly passing.</p> <p>Is this equa...
<p>Checking the docs:</p> <pre><code>pd.DatetimeTZDtype( unit: Union[str, ForwardRef('DatetimeTZDtype')] = 'ns', tz=None, ) Docstring: An ExtensionDtype for timezone-aware datetime data. **This is not an actual numpy dtype**, but a duck type. </code></pre> <p>and the class inheritance is entirely differen...
python|pandas|numpy
2
13,593
68,422,078
Simple python question about data visualization
<p>I want a bar plot that shows the number of all diseases in 2000 for Albania.</p> <p><a href="https://i.stack.imgur.com/LPtzy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LPtzy.png" alt="Image of data" /></a></p> <p>I tried this, but I could not get what I want.</p> <pre><code>fig, ax = plt.subp...
<p>Let's first set up a dummy example:</p> <pre><code>import numpy as np import pandas as pd import itertools np.random.seed(0) df = pd.DataFrame({('Country_%s' % c, y): {'disease_%d' % (i+1): np.random.randint(100) for i in range(4)} for c,y in itertools....
python|pandas|plot|seaborn|visualization
0
13,594
68,409,093
Using Python how to take input from an Excel file , define a function and generate ouput in a new sheet of that Excel file?
<p>Please help me understand how to approach this problem, I'm a beginner in Python.<br/></p> <p>I have this specific task where I have to import data from an excel file (.xlsx) and take the column 'Count' to perform normalization in Python.<br/></p> <p><strong>Then under Numpy library define a function in Python to pe...
<p>I assumed your excel file is in csv format, if not, you can open and save your file in csv.</p> <pre><code>import numpy as np #Opening data just with numpy lib from numpy import genfromtxt data = genfromtxt('Sample data.csv', delimiter=';') #Defining normalize function def normalize(x,MA,MI): return ((x - MI)/(...
python|numpy
1
13,595
59,367,111
Legacy code does not work with new large csv file
<p>I have legacy code writing for pandas.</p> <p>Now the new data become very large (in CSV format), and it is hard to read_csv with the new files (the file sizes ~ 7,8GB and will be larger in the future).</p> <p>Could you suggest me the best way to not change the legacy code but still working with large CSV files? I...
<p>Have you tried reading the file in chunks? And defining the column dtypes beforehand might help boost the performance</p> <pre class="lang-py prettyprint-override"><code>chunksize = 1000000 chunks = pd.read_csv(filepath, dtype=dtypes, chunksize=chunksize) df = pd.concat((chunk for chunk in chunks), ignore_index=Tru...
pandas|large-files
1
13,596
59,284,226
Tensorflow TypeError: expected bytes, Descriptor found
<p>I've been following this tutorial for recognising an object using machine learning:</p> <p><a href="https://www.youtube.com/watch?v=Rgpfk6eYxJA" rel="nofollow noreferrer">https://www.youtube.com/watch?v=Rgpfk6eYxJA</a></p> <p>I've followed all the instructions on what to install and how, including those in this re...
<p>I've followed a different tutorial, however came across the same errors. In case anyone is still wondering, I've fixed it by updating the tensorflow version from 1.5 originally to 1.15 </p> <pre><code>pip install --ignore-installed --upgrade tensorflow-gpu==1.15.0 </code></pre> <p>This is the official issue where...
tensorflow|machine-learning|anaconda
0
13,597
59,403,694
Python for the Comparison of excel column elements and print the matched elements in separate column
<p>I have developed the following code and fetched the matched output using a for loop.I need to print these output elements in separate column using python.</p> <p>excel file name - Sample_data.xlsx first column - WBS_CODE second column - PROJECT_CODE</p> <p>first column and second column are matched and then printe...
<p>I have found a way to export the output and print them in a separate column in excel sheet. Below is the solution,</p> <pre><code>import pandas as pd from openpyxl import load_workbook # Reading the Excel file columns A = pd.read_excel("D:\python_work\Sample_data.xlsx", sheet_name='4Dec') code = A['PROJECT_CODE']...
excel|python-3.x|pandas
0
13,598
13,854,476
pandas' transform doesn't work sorting groupby output
<p>Another pandas question.</p> <p>Reading Wes Mckinney's excellent book about Data Analysis and Pandas, I encountered the following thing that I thought should work:</p> <p>Suppose I have some info about tips.</p> <pre><code>In [119]: tips.head() Out[119]: total_bill tip sex smoker day time size ...
<p><code>transform</code> is not that well documented, but it seems that the way it works is that what the transform function is passed is not the entire group as a dataframe, but a single column of a single group. I don't think it's really meant for what you're trying to do, and your solution with <code>apply</code> ...
python|aggregate|pandas
62
13,599
44,973,484
Efficient way to run a function over the columns of a pandas Dataframe?
<p>I want to run a function over the columns of a Pandas Dataframe. Corpus is a pd.Dataframe </p> <pre><code>import pandas as pd import numpy as np from scipy.spatial.distance import cosine corpus = pd.DataFrame([[3,1,1,1,1,60],[2,2,0,2,0,20], [0,2,1,1,0,0], [0,0,2,1,0,1],[0,0,0,0,1,0]],index=["stark","groß","schwa...
<p>You could use <a href="https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow noreferrer"><code>scipy.spatial.distance.cdist's</code></a> <code>'cosine'</code> functionality for a vectorized soliution, like so -</p> <pre><code>from scipy.spatial.distance import ...
python|pandas|numpy|dataframe|vectorization
2