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
376,400
73,324,303
Vlookup using python when data given in range
<p>I have two excel files, I want to perform vlookup and find difference of costs using python or even excel.</p> <p>My files look like this</p> <p><strong>source_data.xlsx</strong> contains contains distance covered and their price, example distance range from 1 to 100 should be charged 4800 and distance range from 10...
<p>Since it is a categorical bins problem, I suggest utilizing <code>cut()</code> and find the corresponding value.</p> <pre><code>import pandas as pd # create bins bh = df_source['DISTANCE'].apply(lambda x: x.split('-')).apply(pd.Series).astype(int).values[:,0] bt = df_source['DISTANCE'].apply(lambda x: x.split('-'))....
python|excel|pandas
1
376,401
73,381,308
Calculate a Python Array Using For Loops from Data in 2 Dataframes?
<p>I am trying to make or fill a 2-d array using a numpy function called &quot;np.random.normal(average, standard deviation, size)&quot; with the given inputs. My inputs originate from two different dfs that contain the average and standard deviation respectively and they are shown below. This is dfa:</p> <pre><code> ...
<p>The problem comes from the fact that <code>rout</code> is not reinitialized after being appended.</p> <p>With the dataframes you provided:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd dfa = pd.DataFrame({'month': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6,...
arrays|pandas|loops
0
376,402
73,329,568
NLP data processing between `BucketIterator` and `build_vocab_from_iterator`
<p>I am using AG News Dataset to train model for using text classification.</p> <p>The part using <code>TabularDataset</code> to generate dataset from <code>csv</code> file.</p> <pre><code>import torchtext import torch from torchtext.legacy.data import Field, TabularDataset, BucketIterator, Iterator import spacy def ...
<p>After all, the solution which I just post can train the model.</p> <p>And it had better to use stopwords from library to has better accuracy.</p>
python|machine-learning|nlp|pytorch|vocabulary
0
376,403
73,248,121
Identify the discontinuity and mark it as incremental event in pandas
<p>Given a dataframe, I need to increment the event_id when a discontinuity observed in the column. Here for the given data below, if the difference between the current data and the previous data is &gt;5 then the succeeding column has to be mark with next event_id.</p> <pre><code>id, data, event_id, aa, 2, ...
<p>if i understand well your problem you need to increase the <code>event_id</code> every time the difference is more than 5. In this case the solution is in your code you just need to change this</p> <blockquote> <p><code>df['diff_flag']=np.where((df['data']-df['pre_data'])&lt;5,1,0)</code></p> </blockquote> <p>to thi...
python|pandas
0
376,404
73,492,505
Follium map : my European locations are plotted in Africa
<p>I would like to use Folium map to plot markers. My locations are in France. I have latitude and longitude information. So I create POINT geometry in order to implement them in Folium map.</p> <pre><code>df = pd.read_csv('./data/addresses_geocoded.csv', sep = ';', encoding = 'latin-1') geometry = [Point(xy) for xy in...
<p>The most typical CRS is EPSG:4326 which you have used. Have used a CSV that contains cities in the world and select 100 French cities. If I use longitude as latitude and latitude as longitude (erroneously transpose them) then the cities appear in Africa! As demonstrated by red markers in <strong>folium</strong> m...
geometry|geopandas|folium|shapely|epsg
1
376,405
73,505,612
I am trying to assign a value to a cell in a dataframe using iloc and it is not working. It is simply staying its original value
<p>Trying to change 174.0 to NaN. Am I missing something obvious? Finding the index of the value in the overall dataframe is too complicated, so I narrowed it down to Well L15. Is this not allowd?</p> <pre><code>input: df[df['Well']=='L15'].iloc[4,6] output: 174.0 input: df[df['Well']=='L15'].iloc[4,6] = np.nan inpu...
<p>The <a href="https://pandas.pydata.org/docs/user_guide/indexing.html?highlight=chained#why-does-assignment-fail-when-using-chained-indexing" rel="nofollow noreferrer">docs</a> say:</p> <blockquote> <p>Outside of simple cases, it’s very hard to predict whether it will return a view or a copy (it depends on the memory...
python|pandas|dataframe|indexing
0
376,406
73,437,721
Create a def function to filter categories in a dataframe
<p>I´m trying to apply the following rules (picture attached) into the following dataframe (code attached).</p> <p><a href="https://i.stack.imgur.com/SxLEN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SxLEN.png" alt="enter image description here" /></a></p> <pre><code>data = pd.DataFrame({'col1': ...
<p>Use <code>groupby</code> and <code>cut</code>:</p> <pre><code>bins = {'SMALL': [100, 515, 533, ... ,999], 'MEDIUM': [100, 525, 543, ... ,999], 'HIGH': [100, 544, 562, ... ,999], 'SELECT': [100, 564, 585, ... ,999] } labels = ['object 1', 'object 2', 'object 3', ..., 'object 13'] dat...
python|pandas|numpy|function|lambda
1
376,407
73,226,161
How can I best convert an API JSON object to a single row for SQL server?
<p>I have a script setup to pull a JSON from an API and I need to convert objects into different columns for a single row layout for a SQL server. See the example below for the body raw layout of an example object:</p> <pre><code>&quot;answers&quot;: { &quot;agent_star_rating&quot;: { &quot;question_id&quot;: 145...
<p>I would do something like this:</p> <pre class="lang-py prettyprint-override"><code># values that you always capture row = ['value1', 'value2', ...] gottem_attrs = {'question_id': '' , 'question_text': '', 'comment': '', 'selected_options': ''} # find and save the valu...
python|sql|pandas|formatting
1
376,408
73,272,371
Change Column Values in a Dataframe column using Pandas
<p>The data type of the column is object. but, i still map it to string using <code>astype(str)</code>. even used <code>temp['Injury Severity'].str.strip()</code> to remove spaces from column values.</p> <p><a href="https://i.stack.imgur.com/PEO7R.png" rel="nofollow noreferrer">enter image description here</a></p> <p>I...
<p><img src="https://i.stack.imgur.com/jFYk7.png" alt="1" /></p> <p>I think it is solved. It seems that the values were having leading and trailing spaces in the name of values.Thanks alot for the help everyone !!</p>
pandas|replace|jupyter-notebook|slice
1
376,409
73,506,997
Is there a way of storing the original data lines in a pandas dataframe
<p>I am using the <code>read_csv</code> method from pandas.</p> <p>Say I am reading:</p> <pre><code>A,&quot;B&quot;,C </code></pre> <p>With column names 1, 2, 3</p> <p>I will get a dataframe of 3 columns, with the columns having values:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>1</th>...
<p>The answer heavily depends on the data in a csv-file. If you are sure that there's no separator in quoted items, then we can avoid unquoting with <code>quoting=csv.QUOTE_NONE</code> parameter:</p> <pre><code># create dummy file data = 'A,&quot;B&quot;,C' with open('test.csv', 'w') as f: f.write(data) # read the...
python|pandas|dataframe
0
376,410
73,279,382
How to return value if a number is withing a specified range in pandas
<p>I want to return a value (1,2,3,4 or 5) based on the range a number falls in. I want to define a function and apply the function to a column in a DataFrame using <code>.apply()</code>.</p> <p>In the code below, <code>amount</code> is a hypothetical column in a DataFrame. However, I get the error <code>SyntaxError: i...
<p>For this particular case, you are mapping discrete fixed-width integer ranges to a number. This can be solved using a linear transform. The offset in this case is 0.</p> <pre><code>amount = pd.Series([20, 25, 65, 80]) out = amount.divide(20).astype(int) out # returns: 0 1 1 1 2 3 3 4 dtype: int32 </code></p...
python|pandas
4
376,411
73,371,174
Pytorch, Pandas, Numpy different result on Windows and Linux
<p>We are working on an AI project which amongst others calculates the position of a human body lying in a bed. External supporters provided us a code package which does this job and calculates the deviation between the real position of the body (detected by a camera) and the predicted position.</p> <p>That code packag...
<p>If you want more consistency in your environment solves, then add specificity to your YAML. I would recommend specifying every package that is important to you <strong>up through minor version</strong>. That is <a href="https://stackoverflow.com/a/64594513/570918">what is recommended</a> for Conda YAMLs amongst the ...
python|pandas|numpy|pytorch|conda
1
376,412
73,179,912
I keep getting error with my code. I want tselect rows for AR, AL, CA,
<p>1 to 5 of 5 entriesFilter</p> <p>I keep getting error with my code. I want tselect rows for AR, AL, CA, . Then, utilize stacked bar plot, to stack vote percentages for Trump, Clinton, Johnson, and Others. Please see 'pct_clinton', 'pct_trump', 'pct_johnson', 'pct_other' columns. Make sure that your x tick labels are...
<p>You can try:</p> <pre><code># Restrict the list of states STATES = ['Arizona', 'Arkansas', 'California'] ax = df[df['state'].isin(STATES)].plot(x='state', kind='bar', rot=45, xlabel='States') plt.tight_layout() plt.show() </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/1VjAp.png" rel="nofollow no...
python|pandas|matplotlib|plot
0
376,413
73,358,227
What's the .egg folder in pycharm?
<p>I am using pycharm/<code>python 3.8</code>. I am working on a branch let's call it: <code>Working_branch1</code>. I have some tests that I need to run, usually when I run them they test the version of my code: <code>code.py</code> located <code>\directory_name\code.py</code>. However since few days, every time I run...
<p><code>site-packages</code> is where Python stores installed packages for a given environment. The tests are running on the version installed in your environment, which means you probably installed it at some point. Your options are either to uninstall it, or to reinstall the updated version.</p>
python|pandas|pycharm
0
376,414
73,455,383
What does a disparity map in OpenCV tell?
<p>What does the map returned by <code>stereo.compute()</code> indicate?</p> <p>The definition of disparity is the distance between two comparable pixels in the left and right images. However, by running the following code, I obtained a map with the same size as the input photos with values ranging from <code>-16</code...
<p>As per its <a href="https://docs.opencv.org/4.5.2/d2/d6e/classcv_1_1StereoMatcher.html#a03f7087df1b2c618462eb98898841345" rel="nofollow noreferrer">documentation</a>, <code>stereo.compute()</code> computes <em>16-bit fixed-point disparity map (where each disparity value has 4 fractional bits), whereas other algorith...
python|numpy|opencv|disparity-mapping
1
376,415
73,315,559
How to compare multi column values with other multi column value of same dataframe?
<p>I want to match <code>a1</code> <code>a2</code> from the row whose <code>a3</code> is missing with the entire column of <code>b1 b2 b3</code> where ever <code>a1 a2</code> matches with any two <code>b's</code> value we will grab the 3rd <code>b</code> value i.e in row 2 <code>a1=84</code> and <code>a2=5</code> which...
<p>You can get all permutations of <code>b</code> columns, left join with original DataFrame filtered only rows with missing values in <code>a3</code> for <code>a3_</code> column wich match <code>a1, a2</code> in list. Then join list to one Series, remove possible duplicates in index and replace missing values of <code...
python|python-3.x|pandas|dataframe|csv
2
376,416
73,303,134
The size of tensor a (20) must match the size of tensor b (25) at non-singleton dimension 1 for pad_sequence() in pytorch
<p>My Code :</p> <pre><code> import torch.nn.utils.rnn as r a = torch.ones([1, 20]) b = torch.ones([1, 25]) c = r.pad_sequence([a, b], batch_first=True, padding_value=0) </code></pre> <p>The Traceback of this code is :</p> <pre><code>RuntimeError: The size of tensor a (20) must match the size of tensor b (23) ...
<p>In your example you have two sequences of length/duration of 20 and 25 samples, respectively. Both sequences have 1-dim element per time step.</p> <p>PyTorch expects the element dim to be the last dim, therefore you need:</p> <pre class="lang-py prettyprint-override"><code>c = r.pad_sequence([a.T, b.T], batch_first=...
python|pytorch|recurrent-neural-network|tensor
0
376,417
73,448,658
Uncorrelated random variables python
<p>I am trying to create a random vector whose components are uncorrelated standard normal variables with zero mean and unit variance. I am using the function</p> <p>Are these random variables uncorrelated? Because when I am trying to find covariance coefficient:</p> <pre><code>import numpy as np print(np.random.normal...
<p>Those are <a href="https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables" rel="nofollow noreferrer">independent and identically distributed</a> variates drawn from a <a href="https://en.wikipedia.org/wiki/Continuous_uniform_distribution#Standard_uniform" rel="nofollow noreferrer">sta...
python|numpy|random|covariance|variance
3
376,418
73,513,856
Pandas: Map DF with multiple columns to another
<p>I am trying to figure out an efficient way to map <code>df2</code> to <code>df1</code>. What makes this a bit trickier, is the <em>key</em> can sometimes be a tuple of 2+ <code>keys</code>.</p> <p>Keys (the a, b, c's) are indeed strings.</p> <pre><code>df1 = pd.DataFrame(data={'Index':[1,2,3,4,5,6,7,8],'key':['a','...
<p>Since you are talking about data types, I think you are trying to join/merge in (a,b,c) variables and getting the error:</p> <blockquote> <p>TypeError: Unhashable Type: 'List'</p> </blockquote> <p>If I'm right, you should build a dictionary {index:value}, with index = integers and value = tuples of objects. Then, re...
python|pandas
0
376,419
73,329,541
mapping bad matches to other dataframe
<p>I've got a pandas df where I've already matched the name to the ID, but there are some IDs that don't have a name. For those, I want to go back to the mapping file and search the 'alternative_ID_list' column and see if there is a match with a corresponding name.</p> <pre><code>current df name ID 0 joe ...
<p>First split column <code>alternative_ID_list</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>DataFrame.explode</code></a>, convert to integer and filter by <code>bad_matches</code> for possible match by original DataFrame b...
python|pandas|dataframe
0
376,420
73,328,881
Dataframe(pandas) append not working in a loop
<p>I am trying to append the DataFrame into existing DataFrame using loop. Currently, <code>new_data</code> has 4 values each column. I want to go through loop and add new data which is <code>df2</code> with the 3 values each column every time loop iterates.</p> <pre><code> new_data = df = pd.DataFrame({&quot;a&quot;:[...
<p>You need to:</p> <pre><code>df1 = df1.append(df2) </code></pre> <p>And even better, don't use append which will be deprecated soon and use <code>concat</code> instead:</p> <pre><code>df1 = pd.concat([df1, df2]) </code></pre>
python|pandas|dataframe
0
376,421
73,308,464
Including a lag specification in a pandas merge based on datetime column
<p>I am merging a column from one dataframe with a larger one based on date column. With this code: <code>df_final = pd.merge(df_final, pmms_df, how='left', on='PredictionDate')</code></p> <p><code>pmms_df</code> looks like this:</p> <pre class="lang-py prettyprint-override"><code> PredictionDate U.S. 30 yr FRM...
<p>Solution <a href="https://stackoverflow.com/a/73312099/15975987">here</a>.</p> <p>Needed to do the lag first, then merge, instead of doing it simultaneously.</p>
python|pandas|dataframe|datetime|merge
0
376,422
73,407,268
Create a dummy column based on a different column
<p>I have panel data and want to create a column &quot;active trader&quot; for each ID for each period, if the ID has at least traded once per quarter consecutively</p> <p>current df</p> <pre><code>ID date trading A 2020Q1 4 A 2020Q2 5 A 2020Q3 0 A 2020Q4 2 A 2021Q1 1...
<p>You could try as follows:</p> <pre><code>import pandas as pd import numpy as np data = {'ID': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C'], 'date': ['2020Q1','2020Q2','2020Q3','2020Q4','2021Q1','2019Q1','2019Q2','2019Q3','2021Q1','2021Q2','2021Q3','2021Q4'], 'trading': [4, 5, 0, 2...
python|pandas
5
376,423
73,257,965
Merge two functions such that the arguments are merged and the output is merged
<p>I have a two functions as follows:</p> <pre><code>def eq_2(x): A, P, E, EA = x return np.array([E*A, EA, EA, E*P]) def eq_3(x): A, P, E, EA = x return np.array([E**2, E, E, E]) </code></pre> <p>Subsequently I make a list and save it as '<code>v</code>':</p> ...
<p>I the length of the input is always 8, I think you could split the input into two parts, feed it to the two functions, and concatenate the outputs.</p> <pre><code>import numpy as np def eq_2(x): A, P, E, EA = x return np.array([E*A, EA, EA, E*P]) def eq_3(x): A, P, E, EA = ...
python|numpy
0
376,424
73,332,346
How to make create a triangle of "1"?
<p>I want to create this from multiple arrays, best using NumPy:</p> <pre><code>1 0 0 0 0 0 1 1 0 0 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 1 1 1 0 1 1 1 1 1 1 </code></pre> <p>However, I prefer if a library is used to create this, how do I go about doing this?</p> <p>Note: NumPy can be used to create the array as well.</p> <p...
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.tril.html" rel="nofollow noreferrer"><code>np.tril</code></a>:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; np.tril(np.ones((6, 6), dtype=int)) array([[1, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, ...
python|arrays|numpy
2
376,425
73,244,807
related to pandas data frame
<p>CODE :-</p> <pre><code>from datetime import date from datetime import timedelta from nsepy import get_history import pandas as pd end1 =date.today() start1 = end1 - timedelta(days=10) exp_date1 = date(2022,8,25) exp_date2 = date(2022,9,29) stock = ['RELIANCE','HDFCBANK','INFY','ICICIBANK','HDFC','TCS','KOTAKBANK',...
<p>A few lines of code are sufficient to check the condition and add the stock's symbol.</p> <pre class="lang-py prettyprint-override"><code># ... your code before the loop target_stocks = [] for stock in stock: # ... your code in the loop print(df) # check condition cond_loc = ((df.loc[df....
python|excel|pandas|numpy
0
376,426
34,889,599
Pandas df sum rows based on index column
<p>I have a Pandas df (See below), I want to sum the values based on the index column. My index column contains string values. See the example below, here I am trying to add Moving, Playing and Using Phone together as "Active Time" and sum their corresponding values, while keep the other index values as these are alrea...
<p>I am sure that there must be a simpler way of doing this, but here is one possible solution. </p> <pre><code># Filters for active and inactive rows active_row_names = ['Moving','Playing','Using Phone'] active_filter = [row in active_row_names for row in df.index] inactive_filter = [not row for row in active_filter]...
python|pandas|indexing|dataframe
3
376,427
35,032,135
how to add hour to pandas dataframe column
<p>I have a pandas dataframe time column like following.</p> <pre><code> segments_data['time'] Out[1585]: 0 04:50:00 1 04:50:00 2 05:00:00 3 05:12:00 4 06:04:00 5 06:44:00 6 06:44:00 7 06:47:00 8 06:47:00 9 06:47:00 </code></pre> <p>I want to add 5 hours a...
<p>as of '0.25.3' this is as simple as </p> <pre><code>df[column] = df[column] + pd.Timedelta(hours=1) </code></pre>
python|pandas|datetime|dataframe
14
376,428
34,980,659
select rows in pandas DataFrame using comparisons against two columns
<p>I have a pandas dataframe:</p> <pre><code>df = pd.DataFrame({'one' : [1, 2, 3, 4] ,'two' : [5, 6, 7, 8]}) one two 0 1 5 1 2 6 2 3 7 3 4 8 </code></pre> <p>Column "one" and column "two" together comprise (x,y) coordinates </p> <p>Lets say I have a list of coordinates: <code>c = [(1,5),...
<p>This approaching using <code>pd.merge</code> should perform better than the iterative solutions.</p> <pre><code>import pandas as pd df = pd.DataFrame({"one" : [1, 2, 3, 4] ,"two" : [5, 6, 7, 8]}) c = [(1, 5), (2, 6), (20, 5)] df2 = pd.DataFrame(c, columns=["one", "two"]) pd.merge(df, df2, on=["one", "two"], how="...
python|pandas
1
376,429
34,929,717
Get list of column names for columns that contain negative values
<p>This is a simple question but I have found "slicing" <code>DataFrames</code> in <code>Pandas</code> frustrating, coming from <code>R</code>. </p> <p>I have a <code>DataFrame</code> <code>df</code> below with 7 columns:</p> <pre><code>df Out[77]: fld1 fld2 fld3 fld4 fld5 fld6 fld7 0 8 8 -1 ...
<p>You can select them by building an appropriate Series and then using it to index into <code>df</code>:</p> <pre><code>&gt;&gt;&gt; df &lt; 0 fld1 fld2 fld3 fld4 fld5 fld6 fld7 0 False False True False False False False 1 False False False False False True False 2 False False False...
python|python-2.7|pandas
7
376,430
35,281,237
I have a gaussian function with two independent discrete variables. How do I create a matrix of all possible values?
<p>Basically I have this:</p> <pre><code>from scip.stats import norm import pandas as pd r = pd.Series([1, 2, 3]) k = pd.Series([0.2, 0.3, 0.4, 0.5]) x = 2 mean = x + k variance = k # I'm feeding the gaussian function two vectors. # I'd like to get a matrix back of all possible combinations. Quickly. values = nor...
<p>You can apply the <code>pdf</code> to each element of <code>r</code> and automatically put the results in a matrix using:</p> <pre><code>r.apply(lambda x: pd.Series(norm.pdf(x, mean, variance), index=k)) </code></pre> <p>If you return a <code>Series</code> from <code>apply</code> then the results are automatically...
python|numpy|pandas|scipy
2
376,431
34,983,707
extract the first occurrence in numpy array following the nan
<p>I have the following array:</p> <pre><code>[1,1,1,1,1,1,nan,nan,nan,1,1,1,2,2,2,3,3] </code></pre> <p>I want to extract the first occurrence of <code>1</code> in this array following the nan's. I tried this:</p> <pre><code>numpy.argmax(arr &gt; numpy.nan) </code></pre>
<p><code>np.where(np.isnan(foo))[0][-1] + 1</code></p> <p>After the <code>np.where</code>, 0 returns the indices of the elements containing NaN. Then -1 gives you the last NaN index. Then add one to that to find the index of the element after the last NaN.</p> <p>In your example array, it produces an index of 9</p> ...
python|numpy|pandas
5
376,432
35,031,976
Rolling window or occurrences for 2D matrix in Numpy per row?
<p>Looking for occurrences of a pattern on each row of a matrix, I found that there was not clear solution to do it on python for very big matrix having a good performance.</p> <p>I have a matrix similar to</p> <pre><code>matrix = np.array([[0,1,1,0,1,0], [0,1,1,0,1,0]]) print 'matrix: ', mat...
<p>You are using the wrong axis of the numpy array. You should change the axis in np.all from 1 to 2. Using the following code:</p> <pre><code>a = rolling_window(matrix, 2) print np.all(rolling_window(matrix, 2) == [0,1], axis=2) </code></pre> <p>you get:</p> <pre><code>&gt;&gt;&gt;[[ True False False True False] ...
python|numpy|matrix|window|find-occurrences
1
376,433
35,323,023
State Normalization of RNNs
<p>Perhaps a question better posed to Computer Science or Cross Validated?</p> <hr> <p>I'm beginning some work with LSTM on sequences of arbitrary length and one problem I'm experiencing and that I haven't seen addressed, is that my network seems to have developed a couple parameters that grow linearly (perhaps as a ...
<p>Idea #1: Gradient clipping is often applied in RNNs. Here is an example of implementation: <a href="https://stackoverflow.com/questions/36498127/how-to-effectively-apply-gradient-clipping-in-tensor-flow">How to effectively apply gradient clipping in tensor flow?</a></p> <p>Idea #2: Using <a href="https://arxiv.org/...
python-2.7|neural-network|tensorflow|lstm|recurrent-neural-network
0
376,434
34,904,791
Python: Embed pandas plot in Tkinter GUI
<p>I'm writing an application using pandas DataFrames in Python 2.7. I need to plot columns of my DataFrames to a Tkinter window. I know that I can plot pandas DataFrames columns using the built-in plot method on the DataFrame or Series (that is just a wrapper of the matplotlib plot function), like so:</p> <pre><code>...
<p><code>pandas</code> uses <code>matplotlib</code> for plotting. Most <code>pandas</code> plotting functionality takes an <code>ax</code> kwarg that specifies the axes object that will be used. There are a few <code>pandas</code> functions that can't be used this way, and will always create their own figure/axes usin...
python|pandas|matplotlib|tkinter|embed
4
376,435
35,234,680
Weighted smoothing of a 1D array - Python
<p>I am quite new to Python and I have an array of some parameter detections, some of the values were detected incorrectly and (like 4555555):</p> <pre><code>array = [1, 20, 55, 33, 4555555, 1] </code></pre> <p>And I want to somehow smooth it. Right now I'm doing that with a weighted mean:</p> <pre><code>def smoothi...
<p>For weighted smoothing purposes, you are basically looking to perform <a href="https://en.wikipedia.org/wiki/Convolution" rel="noreferrer"><code>convolution</code></a>. For our case, since we are dealing with 1D arrays, we can simply use NumPy's 1D convolution function : <a href="http://docs.scipy.org/doc/numpy-1.10...
python|numpy|smoothing
5
376,436
35,076,837
Pandas Groupby - naming aggregate output column
<p>I have a <code>pandas</code> <code>groupby</code> command which looks like this:</p> <pre><code>df.groupby(['year', 'month'], as_index=False).agg({'users':sum}) </code></pre> <p>Is there a way I can name the <code>agg</code> output something other than 'users' during the groupby command? For example, what if I wa...
<p>I like @Alexander answer, but there is also <code>add_prefix</code>:</p> <pre><code>df.groupby(['year','month']).agg({'users':sum}).add_prefix('total_') </code></pre>
python|pandas
4
376,437
35,222,827
How to separate pandas elements that contain lists
<p>Here is a sample of the data.</p> <pre><code>data['nxt'].head() ​ Out[47]: market_cap_by_available_supply price_btc price_usd volume_usd 0 [1386136000000, 15091900] [1386136000000, 1.3982e-05] [1386136000000, 0.0150919] [1386136000000, 0.0] 1 [1386222394000, 14936300] [1386222394000, 1.31922e-05] [...
<p>Regarding your first question, you can use the map function:</p> <pre><code># Just renaming for readability cap_by_supply = data['nxt']['market_cap_by_available_supply'] # Exploding the market_cap_by_available_supply array into 2 columns data['nxt']['timestamp'] = cap_by_supply.map(lambda r: r[0]) data['nxt']['cap...
python|pandas
0
376,438
35,093,496
problems in "pandas datetime convert to num"
<p>I use pandas to read a csv file to do some analysis. But the returned type is pandas.core.series.Series, which can not be converted to num using the command matplotlib.dates.date2num. Below is my code:</p> <pre><code>import pandas as pd import numpy as np from bokeh.plotting import figure, output_file, show import ...
<p>Use <code>x.astype(datetime)</code> to convert to <code>datetime</code>.</p> <pre><code>from datetime import datetime x = mdates.date2num(x.astype(datetime)) z4 = np.polyfit(x, y, 6) p4 = np.poly1d(z4) xx = np.linspace(x.min(), x.max(), 100) dd = mdates.num2date(xx) plt.plot(dd,p4(xx)) </code></pre>
python|datetime|numpy|pandas|matplotlib
4
376,439
34,898,917
How to raise arrays with negative values to fractional power in Python?
<p>I have an array with negative values that has to be raised to fractional power in Python. I need to obtain the real part of the complex number array generated by the operation.</p> <p><strong>MWE</strong></p> <pre><code>from __future__ import division import numpy as np a = -10 b = 2.5 n = 0.88 x = np.arange(5, 11...
<p>The issue is that NumPy does not promote float or integer dtypes to complex dtypes for this calculation. </p> <p>You have a float array base and a float exponent, so NumPy tries to compute the results using the "<em>put two float dtype objects in, get a float dtype object out</em>" loop. Negative values trigger a w...
python|arrays|numpy|complex-numbers
2
376,440
35,145,472
How to modify a pandas DataFrame in a function so that changes are seen by the caller?
<p>I find myself doing repetitive tasks to various <code>[pandas][1]</code> DataFrames, so I made a function to do the processing. How do I modify <code>df</code> in the function <code>process_df(df)</code> so that the caller sees all changes (without assigning a return value)? </p> <p>A simplified version of the code...
<p>Indexing a <code>DataFrame</code> using <code>ix</code>, <code>loc</code>, <code>iloc</code>, etc. returns a view of the underlying data (it is a read operation). In order to modify the contents of the frame you will need to use in-place transforms. For example,</p> <pre><code>def process_df(df): # drop all col...
python|pandas
7
376,441
35,230,524
Seaborn FacetGrid barplots and hue
<p>I have a DataFrame with the following structure:</p> <pre><code>interval segment variable value 4 02:00:00 Night weekdays 154.866667 5 02:30:00 Night weekdays 100.666667 6 03:00:00 Night weekdays 75.400000 7 03:30:00 Night weekdays 56.533333 8 04:00:00 Nig...
<p>Because <code>interval</code> is nested within the <code>x</code> variable (<code>segment</code>), you need to tell <code>barplot</code> about all of the possible levels of the <code>x</code> variable, so that they are not drawn on top of each other:</p> <pre><code>times = df.interval.unique() g = sns.FacetGrid(df,...
python|pandas|seaborn
23
376,442
31,051,593
Pandas: Filter rows by | (OR) – not mutually inclusive
<p>I'm looking for a way to filter <code>pandas</code> rows via alternatives in a string. I have many different terms I would like to search for, so it would be easier to put them in a few variables rather than list them every time I need to access them.</p> <p>I currently do:</p> <pre><code>df = df[df["A"].str.conta...
<p>You needed to add an additional <code>'|'</code> to join your terms:</p> <pre><code>In [227]: df = pd.DataFrame({'A':['bull', 'bear', 'short', 'null', 'LONG']}) df Out[227]: A 0 bull 1 bear 2 short 3 null 4 LONG In [228]: bull = "BULL|LONG" bear = "BEAR|SHORT" leverage = bull + '|' + bear df =...
python|python-2.7|pandas
1
376,443
31,018,622
Pandas quantile function for dates?
<p>I have a dataframe of donation amounts and dates. I would like to see how long it took a certain proportion of the donations to come in (at what point did we have 25% of donations?, 75% ?). It looked like the Pandas quantile function would do what I want. However it seems to only want numbers, not dates. Is there ...
<p>Like Evert say, you can convert it temporarily to int 64 compute and convert back to datetime</p> <pre><code>YOUR_DATAFRAME.YOUR_DATE.astype('int64').quantile([.25,.5,.75]).astype('datetime64[ns]') </code></pre>
python|pandas
6
376,444
31,021,235
Convert pandas dataframe to list of tuples
<p>I have a sample dataframe as follows</p> <pre><code>&gt;&gt;&gt; df a b 0 1 2 1 3 4 </code></pre> <p>I want to convert this to a list of tuples. I tried using <code>itertuples()</code> for the same</p> <pre><code>&gt;&gt;&gt; list(df.T.itertuples()) [('a', 1, 3), ('b', 2, 4)] </code></pre> <p>But, I want...
<p>You can zip the column names with the values as lists:</p> <pre><code>In [127]: list(zip(df.columns,df.T.values.tolist())) Out[127]: [('a', [1, 3]), ('b', [2, 4])] </code></pre>
python|numpy|pandas|dataframe
8
376,445
30,997,206
Python Replacing every imaginary value in array by random
<p>I got an </p> <pre><code>array([[ 0.01454911+0.j, 0.01392502+0.00095922j, 0.00343284+0.00036535j, 0.00094982+0.0019255j , 0.00204887+0.0039264j , 0.00112154+0.00133549j, 0.00060697+0.j], [ 0.02179418+0.j, 0.01010125-0.00062646j, 0.00086327+0.00495717j, 0.00204473-0.00584213j, ...
<pre><code>n_epochs = 2 n_freqs = 7 # form giving parameters for the array data2 = np.zeros((n_epochs, n_freqs), dtype=complex) for i in range(0,n_epochs): data2[i] = np.real(data[i]) + np.random.vonmises(mu, kappa) * complex(0,1) </code></pre> <p>It gives my whole <code>n_epoch</code> the same imaginary value. ...
python|arrays|numpy|complex-numbers|replaceall
0
376,446
30,784,064
Trouble with pandas to_csv function
<p>the data that i'm working with has a tab delimiter. My issue is that when i try to put it to a csv / text file (with pandas), it displays the results like this</p> <pre><code>Symbol Description OM0S.SI sally 3LLS.SI walley </code></pre> <p>I am trying to achieve a result of this (seperated by a tab)</p> <pre><co...
<p>If you're always adding only one i row each time (which, probably, wouldn't be the most pythonic way to solve that), you should sent to pandas list of lists instead, like this:</p> <pre><code>nd = df.values[i] test = pd.DataFrame(data=[nd], index=None, columns=None) test.to_csv('SGX[Defunct]' + '.txt', mode='a', se...
python|pandas
0
376,447
31,082,904
Downscaling part of image in Python
<p>I am trying to downscaling part of image start from (x,y) coordinate and have a width and height of 500 to be resized to 40x40. By doing so, I am averaging the surrounding pixel into one. (the simplest way I could find) But result is weird.</p> <p>The original image is a 512x512 png</p> <p>Original Image:</p> <p>...
<p>There are several problems with your code. Let's tackle the issues one at a time:</p> <h1>Issue #1 - <code>(x,y)</code> are useless in your <code>shrink</code> definition</h1> <p>I see where you're going with <code>(x,y)</code>. You're using this to traverse over each of the larger blocks, summing all of the pix...
python|image-processing|numpy|resize|python-imaging-library
2
376,448
67,226,537
Pandas Plot Bar Fixed Range Missing Values
<p>I'm plotting a bar chart with data that I have in a pandas.DataFrame. My code is as follows</p> <pre><code>import pandas as pd import matplotlib.pyplot as plot from datetime import datetime start_year = 2000 date_range = [ i + start_year for i in range(datetime.today().year - start_year)] data = pd.DataFrame([ ...
<p>You can prepare your dataframe so that it has all years you want. <strong>right</strong> <code>merge()</code> to a dataframe that has all required years</p> <pre><code>data = pd.DataFrame([ [2015, 100], [2016, 110], [2017, 105], [2018, 109], [2019, 110], [2020, 116], [2021, 113] ], columns=[&quot;year&quot;, &q...
python-3.x|pandas|matplotlib|bar-chart
0
376,449
67,561,709
Colab: Cannot run any cell after changing the runtime to local
<p>I'm new to Tensorflow and I just started using Google Colab a week ago, and I want to run it locally so that it can use my own CPU to avoid <a href="https://research.google.com/colaboratory/faq.html#resource-limits" rel="nofollow noreferrer">Colab Resource Restrictions</a>, so I followed the <a href="https://researc...
<p>Since you mentioned you are new to colab, just double checking the basics - did you try <a href="https://i.stack.imgur.com/jQYVT.png" rel="nofollow noreferrer">Connect Button</a> (in top right area of colab) and choosing &quot;Connect to Local Run time&quot;?</p> <p>Also note that sometimes large datasets cause out ...
tensorflow|jupyter-notebook|google-colaboratory|tensorflow2.0|tf.keras
0
376,450
67,275,865
Querying a list object from API and returning it into dataframe - issues with format
<p>I have the below script that returns data in a list format per quote of (i). I set up an empty list, and then query with the API function get_kline_data, and pass each output into my klines_list with the .extend function</p> <pre class="lang-py prettyprint-override"><code>klines_list = [] a = [&quot;REQ-ETH&quot;,&q...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html" rel="nofollow noreferrer"><code>pandas.DataFrame()</code></a> can accept a dict. It will construct the dict key as column header, dict value as column values.</p> <pre class="lang-py prettyprint-override"><code>import pandas a...
python|pandas|list|dataframe|append
1
376,451
67,470,057
Get an element from column and if equal to something put it in another column in python
<p>Lets say I have a dataframe like this:</p> <pre><code> full_path 0 C:\Users\User\Desktop\Test1\1.txt 1 C:\Users\User\Desktop\ABC\1.txt 2 C:\Users\User\Desktop\Test2\1.txt 3 C:\Users\User\Desktop\Test1\1.txt 4 C:\Users\User\Desktop\ABCD\1.txt 5 C:\Users\User\Desktop\Test2\...
<p>You can use Numpy where:</p> <pre><code>import numpy as np df['folder'] = np.where(df['full_path'].str.contains('Test'), df['full_path'].str.rsplit('\\').str[4], np.nan ) </code></pre> <p>Output:</p> <pre><code> full_p...
python|python-3.x|pandas|list|dataframe
1
376,452
67,464,023
I wrote a KMeans class but the results look strange, what am I doing wrong?
<p>I was following along with Joel Grus' &quot;Data Science from Scratch&quot; and using it wrote my own KMeans code (swapping Joel's functions for numpy ones etc.). The code below converges and finds centroids, but they are almost always in the center of the feature space. Upon further investigation, it looks like the...
<p>You know, sometimes you just need to post on here to end up answering your own question while you write it!</p> <p>Anyway, the reason it was breaking on the second iteration was that the list comprehensions needed to be converted into numpy arrays to be able to use the np.argmin() in classify() and to properly count...
python|numpy|k-means
0
376,453
67,391,645
CannedClassifier at Tensorflow Lattice with more than 2 classes
<p>could someone helps me with tensorflow lattice? here's my problem: I want to classify one label with 18 features. if I use a label with two classes (e.g. 0 and 1) everything is fine. but my label has 30 classes and I get an error-message, that only one label is allowed (I use only one label and if I use the same str...
<p>Tensorflow lattice is not the best tool for classification problems. It's most commonly used for regression problems where you want to enforce monothonicity constraints. That's probably the reason why it does not allow more than one label.</p> <p>It would be helpful if you could explain why you want to use tensorflo...
tensorflow|classification|lattice
0
376,454
67,318,704
How to sort numpy arrays of a list based on the averages of columns
<p>I have a list of numpy arrays and want to firstly sort each array and then sort whole the array in my list. The first step is clear for me. It is my data:</p> <pre><code>unsorted=[np.array([[2.5, 6., 5.1],\ [3.5, 7., 0.1],\ [2.5, 7., 0.],\ [3.5, 6., 0.1]]),...
<p>From your <code>sorted_arr</code>, you can do:</p> <pre><code>sorted(sorted_arr, key=lambda x: tuple(x[:,:2].mean(0))) </code></pre>
python|arrays|numpy|sorting
1
376,455
67,198,159
Not showing the total number of size in each bar in its graph in Python?
<p>I have a problem about showing the numbers above each bar in its graph.</p> <p>Here is my dafaframe which is shown below.</p> <pre><code>ID SEX count 6 Secret Identity Male Characters 1751 3 Public Identity Male Characters 1662 1 Public Identity Female Characters 765 4 Secret Identity Female Characters ...
<p>Kindly check it and assign value to 0 is <code>p.get_height()</code> is NaN.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np def show_values_on_bars(axs, h_v=&quot;v&quot;, space= 0.4): def _show_on_single_plot(ax): if h_v == &quot;v&quot;: for p in ax.patches: ...
python|pandas|axes
1
376,456
67,439,268
Comparing and getting the indexes of 2 arrays
<p>What would be a numpy function that goes through array <code>a</code> and then output the indexes where values of array <code>b</code> is allocated.</p> <p>Code:</p> <pre><code>a = np.array([&quot;BTCUSD&quot;, &quot;ETHUSDC&quot;, &quot;BBB&quot;, &quot;ETHUSD&quot;, &quot;cow&quot;, &quot;head&quot;]) b= np.array...
<pre><code>[list(a).index(i) for i in a if i in b] </code></pre>
arrays|python-3.x|string|numpy|indexing
0
376,457
67,209,056
dockerized flask app does not import pandas
<p>i'm developing a flaskapp that has pandas in it! it work fine when i run it in localhost but when i dockerize it and try to run the container i get this log:</p> <blockquote> <p>Traceback (most recent call last): File &quot;C:\testapi\app.py&quot;, line 4, in import pandas as pd ModuleNotFoundError: No module named...
<p>Put this in your dockerfile:<br /> <code>RUN pip install pandas</code></p> <p>You should consider using a <code>requirements.txt</code> file for dependencies.<br /> Copy the <code>requirements.txt</code> to your container and install the requirements:<br /> <code>RUN pip install -r requirements.txt</code></p>
python|pandas
1
376,458
67,328,216
join 2 data sets and compare in python
<p>Can someone please help with the following using python code?</p> <ul> <li>I have 2 csv data sets each with a million records</li> <li>Both files have the same column names and total of 200 (100 in each)</li> <li>the 2 files are month over month transactions. So, many records may overlap, however, some columns can h...
<p>First you can keep track of your original columns into a list.</p> <pre class="lang-py prettyprint-override"><code>cols = df1.columns.tolist() </code></pre> <p>Then set <code>ID</code> column as index, and properly rename your two dataframe's column headers. Concat the two dataframes along columns.</p> <pre class="l...
python|pandas|dataframe|join
0
376,459
67,566,170
Sum columns based off conditionals - pandas
<p>I'm aiming to sum specific columns in a df where a condition is met. Where <code>Group</code> == <code>Group_A</code>, I want to sum <code>A_4','B_4</code>. However, where <code>Group</code> == <code>Group_B</code>, I want to pass the sum of <code>A_1','B_1</code> to the same column. I need to pass the function at t...
<p>Another option, save the sum to series, and then update the dataframe:</p> <pre><code>Sum1 = df.loc[df['Group'] == df['Group_A'],['A_4','B_4']].sum(axis=1) Sum2 = df.loc[df['Group'] == df['Group_B'],['A_1','B_1']].sum(axis=1) df['Sum']=Sum1.append(Sum2) </code></pre> <p>as mentioned in comments, if you want to subtr...
python|pandas
1
376,460
67,340,358
find index based on data from two numpy arrays
<p>I have huge numpy matrix. Let us say</p> <pre><code>A['a1'] = [1,2,3,6] A['a3']= [3,4,3,7] A['a4']= [4,6,8,7] B['b2'] = [2,2,2,4] A['a1'] A['a3'] A['a4'] B['b2'] 1 3 4 2 2 4 6 2 3 3 8 2 6 7 7 4 </code></pre> ...
<p>You could use a set object <strong>{...}</strong> combined with its method <em><strong>intersection</strong></em></p> <pre class="lang-py prettyprint-override"><code>import numpy as np A, B = {}, {} # Optional : to avoid bug in this chunk of code A['a1'] = [1,2,3,6] A['a3']= [3,4,3,7] A['a4']= [4,6,8,7] B['b2'] = ...
python|numpy
1
376,461
67,249,082
Hyperparameter Tuning with Keras Tuner RandomSearch Error
<p>I am using keras tuner to optimize hyperparameters: hidden layers, neurons, activation function, and learning rate. I have time series regression problem with 31 inputs, 32 outputs with N number of data samples.</p> <p>My original X_train shape is (N,31) and Y_train shape is (N,32). I transform it to work for keras ...
<p>LSTM layers expects a 3D tensor input with the shape [batch, timesteps, feature]. Since you are using number of layers are a tuning parameter along with LSTM layers, when the number of LSTM layers is 2 and above, the LSTM layers after the first LSTM layer will also expect a 3D tensor as input which means that you wi...
python|tensorflow|keras|deep-learning|keras-tuner
0
376,462
67,354,192
Numpy double-slice assignment with integer indexing followed by boolean indexing
<p>I already know that Numpy &quot;double-slice&quot; with fancy indexing creates copies instead of views, and the solution seems to be to convert them to one single slice (e.g. <a href="https://stackoverflow.com/questions/34764141/cannot-assign-values-to-a-double-slice-using-numpy">This question</a>). However, I am fa...
<p>Ok apparently I am making things complicated. No need to combine the indexing. The following code solves the problem elegantly:</p> <pre><code>b = a[..., idx_y, idx_x] b[mask] = 1 a[..., idx_y, idx_x] = b print(a[..., idx_y, idx_x][mask]) # all 1s </code></pre>
python|numpy|slice
1
376,463
67,516,148
How to reshape an ndarray to fir prediction model?
<p>I need to read two images, convert them to size 150x150 and add them to an array that needs to be reshaped into a shape of (2, 150, 150, 3) in order to fit a keras model. Im having trouble understanding how numpy's reshape method works and how do i need to make use of it.</p> <p>My code:</p> <pre><code>import cv2 im...
<p>The function 'numpy.append' does not work inplace as I think you expect it to. Instead, you can do smth like:</p> <pre><code>mport cv2 import numpy as np def loadAndReshape(image_list, path): targetImage = cv2.imread(path) targetImage = cv2.cvtColor(targetImage, cv2.COLOR_BGR2RGB) targetImage = cv2.resi...
python|numpy|keras|cv2
0
376,464
67,449,430
Concise way to concatenate consecutive rows in pandas
<p>I would like to take a dataframe and concatenate consecutive rows for comparison.</p> <p>e.g. Take</p> <pre><code>xyt = pd.DataFrame(np.concatenate((np.random.randn(3,2), np.arange(3).reshape((3, 1))), axis=1), columns=['x','y','t']) </code></pre> <p>Which looks something like:</p> <pre><code> x y ...
<p>Let's try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer">concat</a> on axis=1 with the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shift.html#pandas-dataframe-shift" rel="nofollow noreferrer">shifted</a> frame...
pandas
1
376,465
67,470,504
Group the same column value in the dataframe and add the sum of the same values as a new column
<p>I have a pandas <code>DataFrame</code> like following.</p> <pre><code>df = pd.DataFrame({ 'Column1': ['A', 'B', 'C', 'A', 'B', 'A', 'C', 'A', 'B', 'B'], 'Column2': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'Column3': ['X','Y','Z','X', 'X', 'Z','X','Y','Z','X']}) </code></pre> <p>I want to group by co...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>DataFrame.pivot_table</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.insert.html" rel="nofollow noreferrer"><code>DataFrame.in...
python|pandas|dataframe|pandas-groupby
2
376,466
67,498,283
Dataframe bar plot not consistent x axis with plt.plot
<pre><code>df = pd.DataFrame({&quot;segments&quot;: [2, 2, 2, 5, 3, 3, 3, 4, 4], &quot;values&quot;: [1, 2, 3, 4, 5, 6, 7, 8, 9]}) df.groupby(&quot;segments&quot;).size().plot(kind=&quot;bar&quot;) plt.plot([3, 3], [0, 5]) </code></pre> <p>Let's say I have a dataframe with columns segments and values. I want to plot b...
<p>When overlapping graphs with the pandas plotting function, write the code to plot them consecutively. Also, in this case, the x-axis is a categorical variable, so set use_index to false.</p> <pre><code>df.groupby(&quot;segments&quot;).size().plot(kind=&quot;bar&quot;) df.groupby(&quot;segments&quot;).size().plot(kin...
python|pandas|matplotlib
0
376,467
67,576,058
Pandas: How to put labels on timestamp based on pre-designated time interval?
<p>I have a dataframe that looks like this:</p> <pre><code>+---------------------+--------+ | time | score | +---------------------+--------+ | 2021-01-01 08:01:00 | xx | +---------------------+--------+ | 2021-01-01 15:01:00 | xx | +---------------------+--------+ | 2021-01-02 23:45:00 | xx ...
<p>You can shift the time with <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/timedeltas.html" rel="nofollow noreferrer"><code>pd.Timedelta</code></a> and then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html?highlight=cut#pandas.cut" rel="nofollow noreferrer"><code>...
python|pandas|date|datetime
0
376,468
67,588,381
Rolling correlation that includes all previous values in pandas
<p>I want to compute the correlation between two time series columns. I know that I can do this to get a singular r value:</p> <pre><code>df['a'].corr(df['b']) </code></pre> <p>However, I want to get the r value of the correlation between all previous and current values. I know pandas has prebuilt <code>rolling</code> ...
<p>Try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.window.expanding.Expanding.corr.html#pandas-core-window-expanding-expanding-corr" rel="nofollow noreferrer">expanding corr</a>:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'a': {0: 1, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: ...
python|pandas
1
376,469
67,404,862
Implementing Backprop for custom loss functions
<p>I have a neural network <code>Network</code> that has a vector output. Instead of using a typical loss function, I would like to implement my own loss function that is a method in some class. This looks something like:</p> <pre><code>class whatever: def __init__(self, network, optimizer): self.network ...
<p>As long as all your steps starting from the input till the loss function involve differentiable operations on PyTorch's tensors, you need not do anything extra. PyTorch builds a computational graph that keeps track of each operation, its inputs, and gradients. So, calling <code>loss.backward()</code> on your custom ...
python|machine-learning|neural-network|pytorch|backpropagation
1
376,470
67,299,116
How to create a dictionary for a 10,000 dataframe records and then access each dictionary record to make some calculations?
<p>I have a panda dataframe that has 10,000 records. The dataframe consists of 0 and 1 and looks like this:</p> <pre><code>C1 C2 C3 C4 0 0 1 1 0 1 0 0 1 0 1 1 </code></pre> <p>My aim is to make each record as a dictionary which I assign a value for the dictionary for each column (each column has the same v...
<p>If you don't need the intermediate dicts, you can do some multiplications and sums:</p> <pre class="lang-py prettyprint-override"><code>values = [10, 11, 15, 13] zeros = df.eq(0).mul(values).sum(axis=1) ones = df.eq(1).mul(values).sum(axis=1) df['New_column'] = ones.gt(zeros).astype(int) # C1 C2 C3 C4 New_c...
python-3.x|pandas|dataframe|dictionary
2
376,471
67,568,149
How do I separate the dictionary list into separate columns?
<p>I have a list of dictionary in my dataframe column of vary length:</p> <pre><code>categories 1) [ { &quot;S&quot; : &quot;Vibes&quot; }, { &quot;S&quot; : &quot;Themed&quot; }, { &quot;S&quot; : &quot;Experiences&quot; }, { &quot;S&quot; : &quot;Girls Night&quot; }] 2) [ { &quot;S&quot; : &quot;Vibes&quot; }] ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html?highlight=explode#pandas.DataFrame.explode" rel="nofollow noreferrer"><code>.explode()</code></a> to expand the list of dict in column <code>categories</code> into separate rows, then create the categories n...
python|pandas|list|dataframe|dictionary
1
376,472
67,493,974
How to use tensor shape parameters for something useful?
<p>I'm trying to use the shape of an incoming tensor to form the output, sort of like this:</p> <pre><code>import tensorflow.keras.backend as K def myFunc(x): sz = tf.shape(x)[1] # .. other stuff z = K.repeat_elements(y, sz, axis=1) </code></pre> <p>This results in <code>TypeError: Tensor object cannot be int...
<p>If you know are that the dimension of <code>x</code> is known in advance, you can use <code>x.shape[1]</code> instead of <code>tf.shape(x)[1]</code>, which will return an integer.</p> <p>But I would advise to use <a href="https://www.tensorflow.org/api_docs/python/tf/repeat" rel="nofollow noreferrer"><code>tf.repeat...
tensorflow|keras
1
376,473
67,380,305
Installing but OSMnx in new Environment: Fiona Error-- module 'fiona' has no attribute '_loading'
<p>I am installing OSMnx in a new environment following the steps from Geoffboeing's site: <a href="https://geoffboeing.com/2017/02/python-getting-started/" rel="nofollow noreferrer">https://geoffboeing.com/2017/02/python-getting-started/</a></p> <p>After activating the environment and importing the OSMnx module, it gi...
<p>If you want to install OSMnx, just follow its current documented <a href="https://osmnx.readthedocs.io/en/stable/#installation" rel="nofollow noreferrer">installation instructions</a>. Blog posts can fall out-of-date over the years.</p>
python|python-3.x|geopandas|osmnx|fiona
0
376,474
67,591,193
About tf.gradients is not supported when eager execution is enabled in R
<p>I am trying to implement the Grad-cam in R. And I met this error:</p> <pre><code>Error in py_call_impl(callable, dots$args, dots$keywords) : RuntimeError: tf.gradients is not supported when eager execution is enabled. Use tf.GradientTape instead. </code></pre> <p>I found some solutions online but they all use python...
<p>This can help</p> <pre><code>tf$compat$v1$disable_eager_execution() </code></pre>
r|tensorflow|keras
0
376,475
67,368,886
pandas: add week dates with dataframe
<p>I have a df like, which has such rows:</p> <pre><code> p_id m_id x_id g_id u_id 0 2 NaN 1408 7 121 1 3 1259 117 23 315 2 3 1259 221 9 718 3 3 1259 397 76 367 </code></pre> <p>and two datetime objects:</p> <p>start_date:<...
<h3>Generate <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html" rel="noreferrer"><code>date_range</code></a> and cross <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge.html" rel="noreferrer"><code>merge</code></a></h3> <ol> <li>In pandas version &...
python|python-3.x|pandas|date
5
376,476
67,254,060
why is my visualization of cnn image features in tensorboard t-sne RANDOM?
<p>I have a Convolutional neural network (VGG16) that performs well on a classifying task on 26 image classes. Now I want to visualize the data distribution with t-SNE on tensorboard. I removed the last layer of the CNN, therefore the output is the 4096 features. Because the classification works fine (~90% val_accuracy...
<p>After weeks I stopped trying it with tensorboard. I reduced the number of features in the output layer to 256, 128, 64 and I previously reduced the features with PCA and Truncated SDV but nothing changed.</p> <p>Now I use sklearn.manifold.TSNE and visualize the output with plotly. This is also easy, works fine and I...
python|tensorflow|keras|conv-neural-network|tensorboard
0
376,477
67,333,907
Subtract sum of two rows from another row based on condition in Pandas
<p>I have a <strong>dataframe</strong> with three columns- <code>Col1</code>, <code>Col2</code> and <code>Col3</code></p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Col1</th> <th>Col2</th> <th>Col3</th> </tr> </thead> <tbody> <tr> <td>x</td> <td>a</td> <td>10</td> </tr> <tr> <td>x</td> <td...
<p>We can select the subset of rows where the <code>Col2</code> values is either <code>a</code> or <code>b</code>, then group these rows by <code>Col1</code> and transform using <code>sum</code> to calculate the transformed sum <code>a + b</code> per group, finally subtract the transformed sum from <code>Col3</code> wh...
python|pandas|dataframe
2
376,478
67,245,347
how to get the first 3 elements of a string?
<p>I have a column in pandas which is postal codes. like this : <code>V6N 3S1</code> how I can make a new column with the first 3 element of each postal code? for an example <code>V6N</code> in my example?</p>
<p>use pandas string method -</p> <pre><code>df['postal_codes'].str[:3] </code></pre>
pandas|text
1
376,479
67,360,858
Numpy subarray affect the original 2d array
<p>I created this <code>2D array</code> with <code>numpy</code>:</p> <pre><code>&gt;&gt;&gt;import numpy as np &gt;&gt;&gt;np.random.seed(0) &gt;&gt;&gt;x2 = np.random.randint(10, size=(3, 4)) &gt;&gt;&gt;print(x2) [[5 0 3 3] [7 9 3 5] [2 4 7 6]] </code></pre> <p>Then I created another subarray from <code>x2</code><...
<p>Slices in numpy create a <em>view</em> unlike Python lists. Use <code>.copy()</code> to explicitly create a copy:</p> <pre><code>x2_sub = x2[:2, :2].copy() </code></pre>
python|arrays|numpy
2
376,480
67,549,738
Transformation of the 3d numpy array
<p>I have 3d array and I need to set to zero its right part. For each 2d slice (n, :, :) of the array the index of the column should be taken from vector b. This index defines separating point - the left and right parts, as shown in the figure below.</p> <p><a href="https://i.stack.imgur.com/gx8qK.jpg" rel="nofollow no...
<p>Here's a version without loops.</p> <pre><code>In [232]: A = np.arange(1,49).reshape(3,4,4) In [233]: b = np.array([2,3,1]) In [234]: d = np.array([50,100,150]) In [235]: I,J = np.nonzero(b[:,None]&lt;=np.arange(4)) In [236]: A[I,:,J]=0 In [237]: A[np.arange(3),:,b-1] *= d[:,None] In [238]: A Out[238]: array([[[ ...
python|arrays|numpy
2
376,481
67,279,958
Returning indices from pytorch Dataset: Function to alter __getitem__ results in metaclass conflict
<p>I have multiple classes (for different datasets) that inherit from pytorch's Dataset class. They have a general structure, like so:</p> <pre><code>from torch.utils.data import Dataset class SomeDataset(Dataset): def __init__(self, data, labels): super(SomeDataset, self).__init__() self.data = d...
<p>Just do this:</p> <pre><code>def return_indices(dataset_class): def __getitem__(self, index): return {'index':1, **dataset_class.__getitem__(self, index)} metacls = type(dataset_class) return metacls(dataset_class.__name__, (dataset_class, ), {'__getitem__': __getitem__}) </code></pre> <p>Wh...
python|python-3.x|pytorch|metaclass
0
376,482
67,294,320
How to split a numpy array into arrays with specific number of elements
<p>I know that np.array_split allows us to split a NumPy array, but the number of elements in the split arrays only depends on the number of split chunks. The following example shows what I get and what I wish to get (the size of my_array is 35):</p> <pre><code>my_array = [1 1 1 1 1 0 0 0 1 1 0 1 1 1 0 1 0 1 0 0 0 0 1 ...
<p>You are close:</p> <pre><code>my_array = np.arange(35) N = 8 </code></pre> <pre><code>&gt;&gt;&gt; np.array_split(my_array, range(N, len(my_array), N)) [array([0, 1, 2, 3, 4, 5, 6, 7]), array([ 8, 9, 10, 11, 12, 13, 14, 15]), array([16, 17, 18, 19, 20, 21, 22, 23]), array([24, 25, 26, 27, 28, 29, 30, 31]), arra...
python|arrays|numpy
1
376,483
67,513,640
Create a new dataframe by removing the outliers from the column
<p>I am working on removing outlier tutorial but it quite confused me when this loop not working properly:</p> <pre class="lang-py prettyprint-override"><code>target = df['ConvertedComp'] mean = target.mean() sd = target.std() for x in target: z_score = (x-mean)/sd if np.abs(z_score) &gt; 3: selected_df...
<p>You can try the following code to select rows where z_score calculated from <code>ConvertedComp</code> column is less than or equal to 3.</p> <pre class="lang-py prettyprint-override"><code>mask = df['ConvertedComp'].sub(df['ConvertedComp'].mean()).div(df['ConvertedComp'].std()).abs().le(3) df = df[mask] </code></p...
python|pandas|dataframe|outliers
0
376,484
67,237,732
Effecient Way to Access an Element of a PyTorch Tensor?
<p>I want to extract only the first element of a very large pytorch tensor. I've seen posts talking about options like <code>my_tensor.numpy()[0]</code> or <code>my_tensor.detach().numpy()[0]</code> if I'm using requires_grad. This seems really inefficient just to access one element, especially if my tensor is big. Is ...
<p>If you have a 1d tensor, you can access the first element with :</p> <pre><code>my_tensor[0].item() </code></pre> <p>If your tensor is higher dimensional, you will need to index it like:</p> <pre><code>my_3dtensor[0,0,0].item() </code></pre>
python|pytorch|tensor
0
376,485
67,236,791
Asking advice on EEG classification using Keras
<p>I have a dataset on EEG, with this shape:</p> <pre><code>(11,1158, 200) </code></pre> <p>Where</p> <pre><code>11 is the number of EEG channel 1158 is the number of each task 200 is the time interval of each task </code></pre> <p>for example, if you plot a task, you'll get (Note that the data is normalized):</p> <p><...
<p>As your data is essentially a time-series classification problem my instinct is to start with something LSTM based.</p> <p>Sadly my second insight is related to data size. Your feature space is 200x11=2200 and sample size is 1158. I tend think of using deep learning if sample size &gt;5 * feature size but really t...
python|tensorflow|machine-learning|keras|neuroscience
0
376,486
67,423,937
Vectorize a function with a condition
<p>I would like to vectorize a function with a condition, meaning to calculate its values with array arithmetic. <code>np.vectorize</code> handles vectorization, but it does not work with array arithmetic, so it is not a complete solution</p> <p>An answer was given as the solution in the question &quot;<a href="https:/...
<p>The statement <code>np.where(x &lt; 1.1, 1, np.arcsin(1 / x))</code> is equivalent to</p> <pre><code>mask = x &lt; 1.1 a = 1 b = np.arcsin(1 / x) np.where(mask, a, b) </code></pre> <p>Notice that you're calling <code>np.arcsin</code> on all the elements of <code>x</code>, regardless of whether <code>1 / x &lt;= 1</c...
numpy|conditional-statements|vectorization
2
376,487
67,199,019
How to add 91 to all the values in a column of a pandas data frame?
<p>Consider my data frame as like this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>S.no</th> <th>Phone Number</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>9955290232</td> </tr> <tr> <td>2</td> <td>8752837492</td> </tr> <tr> <td>3</td> <td>9342832245</td> </tr> <tr> <td>4</td> <td>919...
<p>Simplest would be comvert to string, add <code>91</code> to the beginning and slice to last 12 digits:</p> <pre><code>df['New Phone Number'] = df['Phone Number'].astype(str).radd(&quot;91&quot;).str[-12:] </code></pre>
python|pandas|dataframe|numpy
7
376,488
67,471,592
Deleting rows based on time interval in pandas
<p>I have a dataframe with datetime timestamps (every 1 minute). I'd like to increase the time interval between rows to 5 minutes. Basically keep rows 0, 5, 10 etc and remove the rest. How would I do that?</p> <pre><code>Date Value 17/08/2017 04:00:00 0 17/08/2017 04:01:00 1 17/08/20...
<p>Firstly convert your date column to datetime dtype by using <code>to_datetime()</code> method(If its already of datetime then ignore this step):</p> <pre><code>df['Date']=pd.to_datetime(df['Date']) </code></pre> <p>Finally You can do this by boolean masking:</p> <pre><code>newdf=df[df['Date'].dt.minute%5==0] </code>...
python|pandas|sorting|datetime
2
376,489
67,395,873
Tensorflow-text: NotFoundError: _text_similarity_metric_ops.so not found
<pre><code>import tensorflow-text </code></pre> <p>Actually i'm trying to run on Windows 10 (Pro), version 1909. Attempts to run on <strong>Python 3.8.5, 3.6.13, and 3.7</strong> brought no result - i've got the same error.</p> <p>Using Jupiter Notebook, conda (4.10.1)</p> <p><strong>Version of Tensorflow - 2.1.0</stro...
<p><em>So, this problem was solved easy by myself!</em></p> <p>All you have to do is:</p> <ol> <li><p><em>Setup conda enviroment, in Anaconda Then in Anaconda cmd run conda activate &lt;your_enviroment_name&gt;</em></p> </li> <li><p><code>pip install tensorflow==2.4.1</code>, <code>pip install tensorflow-text==2.4.1</c...
python|tensorflow
1
376,490
67,442,911
Altair doesn't display charts when running a script from terminal?
<p>I am following this tutorial example on my Mac Pro Big Sur.</p> <pre><code>https://altair-viz.github.io/gallery/simple_bar_chart.html </code></pre> <p>vtest.py is below:</p> <pre><code>import altair as alt import pandas as pd source = pd.DataFrame({ 'a': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], 'b': [...
<p>If you want to show an Altair plot by running a script from terminal, you can use the <code>.show()</code> method to open it in your default browser:</p> <pre><code>alt.Chart(source).mark_bar().encode( x='a', y='b' ).show() </code></pre> <p>The docs include a section with <a href="https://altair-viz.github.i...
python|pandas|visualization|altair
1
376,491
67,583,402
how to replace values on a dataframe using pandas and streamlit in python?
<p>i have a python script that read dataframe using pandas and display its content using streamlit.</p> <p>What i want is to replace <strong>current value</strong> with a <strong>new value</strong> based on the user input.</p> <p>Where user <strong>select the required column</strong> and than enter the <strong>current...
<p>Your code works for <strong>text</strong> columns (<code>location</code> and <code>category</code>). It doesn't work for the <strong>numeric</strong> <code>source_number</code> column as you're trying to replace one <strong>string</strong> by another.</p> <p>For numeric columns you'll need to use <code>number_input<...
python|pandas|replace|streamlit
0
376,492
67,191,434
Parse a log line and store in `Pandas.DataFrame`
<p>Suppose i have a <code>Pandas.DataFrame</code>:</p> <pre><code>log_df = pd.DataFrame(columns=['type', 'ts', 'process', 'subprocess', 'num', 'message']) </code></pre> <p>and a log file which contains lines in the following format:</p> <pre><code>ERROR:2021-04-19 08:43:10,562:trigger_manager.py:SpawnProcess-2:29:Strea...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>.str.extract()</code></a> to extract the log file contents as follows:</p> <p>For testing purpose, I created one line of data of your sample log file in the series <code>log_file</code>. ...
python|python-3.x|regex|pandas
2
376,493
67,387,433
Python csv to json using pandas - csv columns to nested json
<p><strong>Python 3.8.5 with Pandas 1.1.3</strong></p> <p>I have a csv file with columns: name, city, state, and zipcode. I need to convert to json with the city, state, and zipcode column values inside an object called residence.</p> <p>For example:</p> <p>CSV file</p> <pre><code>Name City State Zipcode Jo...
<p>IIUC try creating the nested object row-wise first, then creating the JSON:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd csv_file = pd.read_csv(&quot;data.csv&quot;, sep=&quot;,&quot;, header=0, index_col=False) # Create Nested dict (Object) csv_file['Residence'] =...
python|pandas
1
376,494
67,360,987
BERT model bug encountered during training
<p>So, I made a custom dataset consisting of reviews form several E-learning sites. What I am trying to do is build a model that can recognize emotions based on text and for training I am using the dataset I've made via scraping. While working on BERT, I encountered this error</p> <p><code>normalize() argument 2 must b...
<p>It sounds like you may have a float value in your <code>data['Text']</code> column somehow.</p> <p>You can try something like this to shed more light on what's happening:</p> <pre class="lang-py prettyprint-override"><code>for i, s in enumerate(data['Text']): if not isinstance(s, str): print('Text in row %s is ...
python|pandas|numpy|tensorflow|bert-language-model
1
376,495
67,263,575
Pandas dataframe: how to permute rows and create new groups of combinations
<p>I have the following pandas dataframe df with 10 rows and 4 columns that attributes 3 categorical variables:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(np.random.choice([&quot;dog&quot;, &quot;cat&quot;, &quot;mice&quot;], size=(10, 4))) </code></pre> <p>I would to know all permutations po...
<p>I hope I've understood your question right. This example will create Series where index is the combination and values are size of this combination:</p> <pre><code>from collections import Counter from itertools import permutations print( df.assign( items=df.apply( lambda x: [ ...
python|pandas|pandas-groupby|itertools
1
376,496
67,191,190
Create new columns and calculate values based on condition with date in Python
<p>I need to create a new column as Billing and Non-Billing based on the Date column.</p> <p>Condition for Column 1 : If the Start Date is <code>NULL</code> OR <code>BLANK</code> (OR) if its Start Date is in 'Future Date' (OR) if its Starts Date is in 'Past Date' (OR) if its End Date is in Past Date then I should crea...
<p>I don't understand the conditions very well as there seem to be some inconsistencies but I believe this will help you getting started:</p> <pre><code>import pandas as pd import numpy as np import datetime df['Total'] = df.sum(axis=1) df['Available']=168 df['Amount']=df['Total']/df['Available']*100 df['Billing']=np...
python|pandas|numpy|pandas.excelwriter
0
376,497
67,229,256
Extract the position of one date in a dataframe
<p>I'm looking for a way to cut my dataframe at one precise date, so I thought about enter this date in my code, and then, extract the position of where it is and then just slice my dataframe with that position as the end of the df.</p> <p>Here is my code :</p> <pre class="lang-py prettyprint-override"><code>import pan...
<p>You can easily slice your data based on a certain date if you parse the column that contains the date information to datetime datatype. Ex:</p> <pre><code>import pandas as pd df = pd.read_csv(filename, sep=';', decimal=',') # to datetime df['dte_1981'] = pd.to_datetime(df['dte_1981'], dayfirst=True) # now you can...
python|pandas|date|datetime
2
376,498
67,484,547
How do I train the DeepSORT tracker for custom class?
<p>I want to detect and count the number of vines in a vineyard using Deep Learning and Computer Vision techniques. I am using the YOLOv4 object detector and training on the <a href="https://www.github.com/AlexeyAB/darknet" rel="nofollow noreferrer">darknet</a> framework. I have been able to integrate the SORT tracker ...
<p>Yes, you can use the same classes for DeepSORT. SORT works in 2 stages, and DeepSORT adds a 3rd stage. First stage is detection, which is handled by YOLOv3, next is track association, which is handled by Kalman Filter and IOU. DeepSORT implements the 3rd stage, a Siamese network to compare the appearance features be...
python|tensorflow|computer-vision|object-detection
2
376,499
67,343,548
Break out of the 'nested loop' when condition is met, and then continue the loop of the parent loop
<p>I have a nested loop, but I only need the first condition of the child loop. So I need the child loop to stop when it meets the condition, and restart the loop for the index of the parent loop. The example should clarify. I have first few rows of the dataframe:</p> <pre><code> M# Date Time Day Team Team...
<p>You can move the loop into a <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><strong><code>DataFrame.apply()</code></strong></a>.</p> <p>Find the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.first_valid_index.html" rel="nofollow n...
python|pandas|loops|break
1