Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
361,300
35,211,305
Pandas DataFrame creates new row for index using groupby and sum
<p>After using the groupby and sum operations as follows:</p> <pre><code>companyGrouped = dailyStocks.groupby(['SYMBOL']) sumByCompany = companyGrouped.sum() </code></pre> <p>I end up with a new row for the group by and sum key, this is undesirable as I later want to merge this with another dataframe using <code>[SYM...
<p>Solved with <code>df.reset_index(level=0, inplace=True)</code></p> <p><a href="https://stackoverflow.com/questions/20461165/how-to-convert-pandas-index-in-a-dataframe-to-a-column%22SO%20Question%22">enter link description here</a></p>
python|pandas|group-by|sum|dataframe
0
361,301
35,001,169
Numpy binary matrix - get rows and columns of True elements
<p>I have a binary numpy 2D array, say,</p> <pre><code>import numpy as np arr = np.array([ # Col 0 Col 1 Col 2 [False, False, True], # Row 0 [True, False, False], # Row 1 [True, True, False], # Row 2 ]) </code></pre> <p>I want the row and column of each <code>True</code> element in the matrix:</p>...
<p>You are looking for <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.argwhere.html"><code>np.argwhere</code></a> -</p> <pre><code>np.argwhere(arr) </code></pre> <p>Sample run -</p> <pre><code>In [220]: arr Out[220]: array([[False, False, True], [ True, False, False], [ Tru...
python|arrays|numpy|matrix|vectorization
7
361,302
35,220,309
mosaic plot with percentage and count values as labels in pandas DF
<p>I have pandas dataframe like this:</p> <pre><code> LEVEL_1 LEVEL_2 Freq Percentage 0 HIGH HIGH 8842 17.684 1 AVERAGE LOW 2802 5.604 2 LOW LOW 22198 44.396 3 AVERAGE AVERAGE 6804 13.608 4 LOW AVERAGE 2030 ...
<p>Here's a start. Note I had to add a row of zeros to the DataFrame for the labeling. You can make the labeling nicer by string formatting in the <code>lambda</code> function. You'll also want to reorder the headers.</p> <pre><code>import pandas as pd from statsmodels.graphics.mosaicplot import mosaic import io d = i...
python|pandas|plot|mosaic
4
361,303
35,144,364
python calculate min/max, std for a time series
<p>my dataset is like,</p> <p>date time product value1 value2 value3</p> <p>2015-10-01 09:00:00.000 P1 1 2 3 </p> <p>2015-10-01 10:00:00.000 P1 2 3 4 </p> <p>2015-10-01 11:00:00.000 P1 5 6 7</p> <p>2015-10-01 ...
<p>It seems that your <code>date</code> and <code>time</code> are two columns of strings. If that's the case, I would create a timestamp column and then filter. Finally, you can <code>groupby</code> product and then aggregate. (Assuming your data is in a pandas dataframe <code>df</code>. <code>np</code> is numpy)</p> ...
python|pandas
0
361,304
34,992,672
Change point detection in python
<p>I have a pandas DataFrame where one column contains the following elements:</p> <pre><code>[2,2.5,3,2,2.6,10,10.3,10,10.1,10.3,10], </code></pre> <p>is there a python function that can detect the sudden change from 2.6 to 10 from that list? I have read a little bit and <a href="https://cran.r-project.org/web/pack...
<p>IIUC you could use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.Series.pct_change.html" rel="noreferrer"><code>pct_change</code></a> for that to find differencies between neighbours and then compare with your limit (whatever it'll be):</p> <pre><code>s = pd.Series([2,2.5,3,2,2.6,10...
python|python-2.7|pandas
11
361,305
35,331,154
set two columns as the index in a pandas dataframe for time series analysis
<p>In the case of weather or stock market data, temperatures and stock prices are both measured at multiple stations or stock tickers for any given date.</p> <p>Therefore what is the most effective way to set an index which contains two fields?</p> <p>For weather: the weather_station and then Date</p> <p>For Stock D...
<p>As mentioned by Anton you need to use MultiIndex as follows:</p> <pre class="lang-py prettyprint-override"><code>stock_df.index = pd.MultiIndex.from_arrays(stock_df[['code', 'date']].values.T, names=['idx1', 'idx2']) weather_df.index = pd.MultiIndex.from_arrays(weather_df[['station', 'date']].values.T, names=['idx...
python|pandas|indexing|time-series
7
361,306
35,186,965
Asserting that pandas dataframe has a datetime index through decorator
<p>How can I add a decorator stating that the incoming pandas dataframe argument to a function has a datetime index?</p> <p>I have looked at the packages engarde and validada, but not found anything yet. I could do this check inside the function, but would prefer a decorator.</p>
<p>As @PadraicCunningham writes, it is not too hard to create one using <a href="https://docs.python.org/2/library/functools.html" rel="noreferrer"><code>functools.wraps</code></a>:</p> <pre><code>import functools def assert_index_datetime(f): @functools.wraps(f) def wrapper(df): assert df.index.dtype...
python|pandas|decorator|datetimeindex
5
361,307
35,134,683
How to groupby or exclude based on value counts?
<p>I have a df where the groupby looks like this</p> <pre><code> +----------------+----------------+-------------+ | Team | Method | Count | +----------------+----------------+-------------+ | Team 1 | Manual | 14 | | Team 2 | Automated | ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.apply.html" rel="nofollow"><code>apply</code></a> for all values <code>Manual</c...
python|pandas|count
1
361,308
35,277,898
TensorFlow for binary classification
<p>I am trying to adapt <a href="https://www.tensorflow.org/versions/0.6.0/how_tos/summaries_and_tensorboard/index.html" rel="noreferrer">this MNIST example</a> to binary classification.</p> <p>But when changing my <code>NLABELS</code> from <code>NLABELS=2</code> to <code>NLABELS=1</code>, the loss function always ret...
<p>The original MNIST example uses a <a href="https://en.wikipedia.org/wiki/One-hot" rel="noreferrer">one-hot encoding</a> to represent the labels in the data: this means that if there are <code>NLABELS = 10</code> classes (as in MNIST), the target output is <code>[1 0 0 0 0 0 0 0 0 0]</code> for class 0, <code>[0 1 0 ...
python|neural-network|tensorflow
42
361,309
34,877,523
In TensorFlow, what is tf.identity used for?
<p>I've seen <code>tf.identity</code> used in a few places, such as the official CIFAR-10 tutorial and the batch-normalization implementation on stackoverflow, but I don't see why it's necessary.</p> <p>What's it used for? Can anyone give a use case or two?</p> <p>One proposed answer is that it can be used for transf...
<p>After some stumbling I think I've noticed a single use case that fits all the examples I've seen. If there are other use cases, please elaborate with an example.</p> <p>Use case:</p> <p>Suppose you'd like to run an operator every time a particular Variable is evaluated. For example, say you'd like to add one to <c...
python|tensorflow
67
361,310
35,288,052
Convertin string of list to list of floats [pandas]
<p>when importing in pandas the data looks like that:</p> <pre><code>&gt;&gt;&gt; BOM.PriceQty['substrate'] '[200.0, 300.0, 500.0]' </code></pre> <p>how do I convert it to list of floats? tried convert_objact:</p> <pre><code>&gt;&gt;&gt; BOM.PriceQty['substrate'].convert_object(convert_numeric=True) </code></pre> <...
<p>This would nicely convert a string representing a list of floats to an actual list of floats:</p> <pre><code>s = '[200.0, 300.0, 500.0]' l = [float(x.strip(' []')) for x in s.split(',')] </code></pre> <p>The <code>strip</code> function removes any <code>' '</code>, <code>'['</code>, and <code>']'</code> characters...
python-3.x|pandas
5
361,311
35,005,569
Behavior of ufuncs and mathematical operators differ for subclassed MaskedArray
<p>I am attempting to subclass <code>numpy.ma.MaskedArray</code>, but keep running into an issue where directly using mathematical operators on my subclass behaves differently than directly using the analogous ufunc. When using the ufunc directly (e.g. <code>np.subtract(arr1, arr2)</code>), __array_prepare__, __array_...
<p>This appears to be a legitimate bug that was implemented in the Numpy v1.10.0 release and that is not fixed as of the v1.10.4 release. <a href="https://github.com/numpy/numpy/issues/7122" rel="nofollow">I have submitted this as an issue to the Numpy project.</a></p>
python|numpy
0
361,312
34,903,082
Data-frame Object has no Attribute
<p>I am trying to call Dataframe columns for analysis using Pandas. I uploaded a CSV file, however every time It gives me this error <code>AttributeError: 'DataFrame' object has no attribute 'X' </code> How can I make every column available for analysis and why does this always happen. </p> <p><code>proportion_women_s...
<p>You get the error because your column names are case-sensitive, typically you can check what your columns really are by using <code>df.columns.tolist()</code> as you're concerned about this you can lower case the columns after loading by using:</p> <pre><code>df.columns = df.columns.str.lower() </code></pre> <p>Ex...
python|csv|pandas
2
361,313
30,826,224
How to get complex64 output from numpy.fft?
<p>I have the following code:</p> <pre><code>Ga=rfft2(A) </code></pre> <p><code>A</code> is type <code>float32</code>, but <code>Ga</code> comes out as <code>complex128</code> effectively doubling my data. How can I get out <code>complex64</code> data? Certainly this isn't the default functionality for <code>fftw</c...
<p>Well, it seems that the type is defined quite deep in the C code. <a href="https://github.com/numpy/numpy/blob/master/numpy/fft/fftpack_litemodule.c" rel="nofollow">fftpack_litemodule.c</a> uses <code>NPY_CDOUBLE</code> as the array type and that is basically your <code>complex128</code>. The only solution that I se...
python|numpy|fft
2
361,314
30,951,141
Numpy set range where less than
<pre><code>def updatemap(depthmap, p1, p2, value): maps = depthmap[0:580,p1[0]:p2[0]] maps[maps &lt; value] = value depthmap[0:580,p1[0]:p2[0]] = maps </code></pre> <p>This is the current way I do it. But it requires I make a copy of the range, then set the range where the value is less than, then copy it ...
<p>Assuming <code>depthmap</code> is a NumPy array, this part:</p> <pre><code>maps = depthmap[0:580,p1[0]:p2[0]] </code></pre> <p>doesn't actually make a copy. Unlike with lists and tuples, NumPy slicing creates a view of the original array. Thus, the next line:</p> <pre><code>maps[maps &lt; value] = value </code></...
numpy
2
361,315
30,897,069
Memory Issue for Array Conversion
<p>If we convert a large array containing <code>0</code> and <code>1</code> as <code>boolean</code> to another array containing <code>0</code> and <code>1</code> as <code>float</code>, the size of array would be almost 10 times larger. What is the best way (if any) to handle this issue in python (Numpy) if we need this...
<p>You probably don't have to do the conversion. If you are performing some calculation with your bool array and another float array, the conversion will be handled during the operation:</p> <pre><code>import numpy as np y = np.array([False, True, True, False], dtype=bool) x = np.array([2.5, 3.14, 2.7, 8.9], dtype=fl...
python|memory|numpy
6
361,316
30,847,339
What's the fastest way to compare datetime in pandas?
<p>I have two big csv files with different number of rows which I am importing as follows:</p> <pre><code>tdata = pd.read_csv(tfilepath, sep=',', parse_dates=['date_1']) print(tdata.iloc[:, [0,3]]) TBA date_1 0 0 2010-01-04 1 9 2010-01-05 2 0 2010-01-06 3 8 2010-01-07 4 ...
<p>If you call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html#pandas.DataFrame.set_index" rel="nofollow"><code>set_index</code></a> on <code>pdata</code> to <code>date_2</code> then you can pass this as the param to <a href="http://pandas.pydata.org/pandas-docs/stable/gen...
python|python-3.x|numpy|pandas|datetime64
3
361,317
31,200,747
python,pandas do group wise value_count()
<p>I have a dataframe like this:</p> <pre><code>a b 1 2 1 3 2 4 2 4 3 3 </code></pre> <p>I want to group by 'a' and for every group I want to do values_count() of 'b'. What I want to get is something like:</p> <pre><code>for a = 1: b[2:1,3:1] for a = 2: b[4:2] for a = 3: b[3:1] </code></pre> <p>is...
<pre><code>df Out[20]: a b 0 1 2 1 1 3 2 2 4 3 2 4 4 3 3 df.groupby(['a']).apply(lambda group: group.b.value_counts()) Out[21]: a 1 3 1 2 1 2 4 2 3 3 1 dtype: int64 </code></pre>
python|python-2.7|pandas
1
361,318
30,881,489
Data type using Pandas
<p>If I ftp into a database and use pandas.read_sql to read in a huge file, what data type would the variable set equal to this be? And, if applicable, what kind of format would it be in? What object type is a pandas data frame?</p>
<p><strong>Variable = ?</strong></p> <p>The variable set would be equal to a <code>pandas.core.frame.DataFrame</code> object. </p> <p><strong>Format?</strong></p> <p>The <code>pandas.core.frame.DataFrame</code> format is a collection of numpy ndarrays, dicts, series, arrays or list-like structures that make up a 2 d...
python|pandas
1
361,319
30,797,657
What could cause a Value Error in this short image matching function in Python (using numpy)?
<p>I need a Python program I am working on to be able to find an exact, pixel for pixel match of a small image inside a larger one. I have been using the following function, which is a slightly modified version of some code given in an answer to a question about how to do such image matching right here on Stack Overfl...
<p>The docs for <code>logical_and</code> specify <code>logical_and(x1, x2[, out])</code>. It expects 2 or 3 arguments. You need to use <code>logical_and.reduce</code> if you want to compare anything other than 2 arrays.</p> <p>For example:</p> <pre><code> In [703]: A=np.ones((4,3),np.bool) In [704]: np.logic...
python|image-processing|numpy
1
361,320
31,191,192
Not able to install Python with OpenCV on windows x64 system
<p>I am trying to install python on my system but facing some issues.</p> <p>I have installed OpenCV 3.0.0 for Windows x64 bit system and now i am trying to install python 2.7.5 on my system and i also have installed numpy 1.7.1. </p> <p>Then i copied 'cv2.pyd' from my OpenCV folder to python folder, now in order to...
<p>Here's a complete way of installing OpenCV with Python </p> <ol> <li>Download: Python-2.7.11 from <a href="https://www.python.org/downloads" rel="nofollow">https://www.python.org/downloads</a> numpy-1.8.0-win32-superpack-python2.7.exe from <a href="https://sourceforge.net/projects/numpy/files/NumPy/1.8.0/" rel="nof...
python|python-2.7|opencv|numpy|opencv3.0
1
361,321
30,924,140
ValueError: invalid literal for float(): when inserted substring from "2015-05-21T18:11:55" into dataframe
<p>I have a key value pair in a JSON-derived dictionary that looks like this:</p> <pre><code>u'local_start_time': u'2015-05-21T18:11:55.000Z' </code></pre> <p>When I try to insert a portion of this string into a dataframe I get this error:</p> <pre><code> File "fix_runs_prepare.py", line 63, in &lt;module&gt; d...
<p>The problem is <code>pandas.dataframe</code> treats datatype of all cells as <code>object</code> and even try to <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.html" rel="nofollow">infer</a> the datatype if you don't specify it explicitly. </p> <p>To avoid that, explicitly set the data...
python|pandas|dataframe
0
361,322
31,131,614
Ploting datetime data from pandas datetime
<p>I read csv file with panda. On source file i have column with date and time and some outher columns ( financial OHLC ). When i was reading csv file i was using some parse option ( combine columns on parse like this <a href="http://pandas.pydata.org/pandas-docs/stable/io.html?highlight=read%20csv#specifying-date-colu...
<p>I don't have all your data but essentially you need to use <code>DateFormatter</code> to format your x-ticks:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.dates as dates fig, ax = plt.subplots() date_time=df.icol(0) date_close=df.icol(6) plt.plot_date(x=date_time,y=date_close,fmt="r-") plt.xlabe...
python-3.x|pandas|matplotlib
1
361,323
30,782,011
How to call more than one function in python
<p>for some reason when I call all four functions at once I get an error with the newly named dataframes. specifically the empty dataframes that I want to fill. Have no idea why. I've tried to move all empty dataframes outside the function and that didn't work. Any help appreciated. </p> <p>The first function works (F...
<p>You have a basic syntax error in your function <code>def TCD_extract1_to_9(filepath)</code> you declare <code>new_dfb = pd.DataFrame()</code> but you then use <code>new_df[colname] = selected_data</code>.</p> <p>In your last function <code>def TCD_extract9_to_96(filepath)</code> you declare <code>new_dfc = pd.DataF...
python|pandas|dataframe
3
361,324
67,435,464
Create feature based on consecutive rows in various independent sections of dataframe
<p>I could not think of a better way to word the question, kindly edit if you have something better.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>date</th> <th>country</th> <th>total_cases</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>denmark</td> <td>2</td> </tr> <tr> <td>2</td> <td>d...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.shift.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.shift</code></a>:</p> <pre><code>df['new_cases'] = df['total_cases'] - df.groupby('country')['total_cases'].shift(1) </code></pre> <p>Or <a href="ht...
python|pandas|dataframe
1
361,325
67,244,126
DataFrame row-to-column conversion optimization
<p>I have a <code>DataFrame</code> that needs to be converted. Convert the <code>a, b, c, and d</code> columns of each year from <code>rows</code> to <code>columns</code>. <code>df</code> is the data before conversion and <code>df1</code> is the data after conversion. Which statements can be optimized? My code is as fo...
<p>You can do this with a <code>pivot</code>:</p> <pre><code>result = df.pivot(index=&quot;code&quot;, values = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;], columns = &quot;year&quot;) # flatten and rename your columns if necessary: result.columns = result.columns.to_flat_index().map(lambda x: &quot;&q...
python|pandas|dataframe
1
361,326
67,548,394
Getting row values by column name
<p>I have the following data frame:</p> <pre><code> &gt;&gt;&gt; data = {'seasons': ['season_2', 'season_3', 'season_4', 'season_5', 'season_6', 'season_7', 'season_1']} &gt;&gt;&gt; df = pd.DataFrame(data) &gt;&gt;&gt; df['season_1'] = 1 &gt;&gt;&gt; df['season_2'] = 2 &gt;&gt;&gt; df['season_3'] = 3 &gt;&gt;&gt;...
<p>TRY:</p> <pre><code>df = df.assign(season_values = df.apply(lambda x: x[x['seasons']],1)) # df['season_values'] = df.apply(lambda x: x[x['seasons']],1) </code></pre> <p>Another option via <code>melt</code>:</p> <pre><code>melt = df.melt(['seasons'], ignore_index=False) df['season_value'] = melt.loc[melt['seasons'] =...
python-3.x|pandas|dataframe
2
361,327
67,253,343
Adding multiple different headers to df in python
<p>I have to read in multiple files and store these files as df in memory, since there are no headers in my csv file, I need to add multiple headers to each df manually. <strong>Each file has different headers.</strong></p> <p>What I did is using the if-elif statements, which works but very redundant. Does anyone have ...
<p>Use a dictionary mapping filenames to headers.</p> <pre><code>headers = {&quot;20210101&quot;: [&quot;Name&quot;,&quot;Age&quot;,&quot;City&quot;], ...} df = pd.read_csv(file_name, names=headers[file_name], ...) </code></pre>
python|pandas|dataframe
2
361,328
67,529,976
Change h:mm:ss to hh:mm:ss
<p>i am working with python and i have a df as:</p> <pre><code>time 00:01:24 00:22:44 00:12:32 00:02:56 </code></pre> <p>and i want to change it as</p> <pre><code>time 01:24:00 22:44:00 12:32:00 02:56:00 </code></pre> <p>i first removed 00: from the column by using:</p> <pre><code>df['time'] = df['time'].str.strip('00:...
<pre><code>df['time'] = pd.to_datetime(df.time, format=&quot;%S:%H:%M&quot;).dt.time df </code></pre> <p><strong>Output</strong></p> <pre><code> time 0 01:24:00 1 22:44:00 2 12:32:00 3 02:56:00 </code></pre>
python|pandas|datetime|type-conversion
3
361,329
67,367,511
How can I parse pandas datetime values which are in an inconsitent date format into a uniform date format?
<p>I have datetime values in a dataframe which have different formats i.e some are in the form <code>yyyy-mm-dd</code> and some are in the form <code>yyyy-dd-mm</code>. I want to convert all of them into one format <code>yyyy-mm-dd</code>. The problem only exists for months and dates upto 12 i.e <code>2021-03-09</code>...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> with <code>format</code> and <code>errors='coerce'</code> parameter, so if no match there is missing value and set new column by compare <code>Tuesday</code>s in <a h...
python|pandas|datetime
2
361,330
67,393,596
Creating new columns by adding groups of columns
<p>I have a dataframe</p> <pre><code>df = pd.DataFrame({ 'BU': ['Total', 'Total', 'Total', 'CRS', 'CRS', 'CRS'], 'Line_Item': ['Revenues','EBT', 'Expenses', 'Revenues', 'EBT', 'Expenses'], 'Small Business Loans &lt; $100K 2020 ($000)': [100, 120, 0, 200, 190, 210], 'Small Business Loans &lt; $100K 201...
<p><strong>Update:</strong> For the Small Business Loans, try a <code>regex</code> filter:</p> <pre class="lang-py prettyprint-override"><code>s = '\$(000)' years = range(2018, 2021) df.assign(**{ f'SBL {y} {s}': df.filter(regex=fr'Small Business Loans.*{y}.*{s}').sum(1) for y in years }) </code></pre> <p>To c...
python|pandas|multiple-columns
3
361,331
67,529,618
Expand counted row value into separate rows, adding distinct ID in python
<p>I have a dataset that has several rows and columns, however within the column labeled, 'number', I wish to remove the aggregation and separate this into its own unique count. I also wish to add a column that gives this count a unique id.</p> <p><strong>Data</strong></p> <pre><code>location name type number ...
<p>Idea is split values for repeat only of <code>number</code> is greater like <code>1</code>, then add rows with <code>number=0,1</code> and sorting for original ordering:</p> <pre><code>m = df1['number'].gt(1) df2 = df1[m] df = (pd.concat([df2.reindex(df2.index.repeat(df2['number'])).assign(number=1), ...
python|pandas|numpy
1
361,332
67,252,743
How do I check if all elements fall in one group?
<p>I have different product groups, let's say toys, clothes and food. When I get a series (or list) of products I want to know if they all fall in one group or if I have products from a few groups.</p> <p>Let's make an example:</p> <pre><code>toys=['Car', 'Teddy Bear', 'Doll'] food=['Banana', 'Cola', 'Bread', 'Milk'] <...
<p>This is essentially a set operation. You can convert the <code>toys</code> and <code>food</code> to sets and then use <code>set.intersection</code>. For example:</p> <pre><code>toys = [&quot;Car&quot;, &quot;Teddy Bear&quot;, &quot;Doll&quot;] food = [&quot;Banana&quot;, &quot;Cola&quot;, &quot;Bread&quot;, &quot;Mi...
python|pandas|list
2
361,333
67,418,010
How to input maximum value of two equations into pandas dataframe column?
<p>I am trying to input into new column of dataframe maximum result of two equations based on different columns. Unfortunately I am having below error. How should I change the code to make it work (I would like to stay with pandas library in this case)?</p> <div class="s-table-container"> <table class="s-table"> <thead...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.maximum.html" rel="nofollow noreferrer"><code>numpy.maximum</code></a>:</p> <pre><code>s = df['Prc1'] - df['Prc2'] df['Price'] = np.maximum((s / df['Prc1']).abs(), (s / df['Prc2']).abs()) </code></pre> <p>Another idea with divide from right side by ...
python|pandas
1
361,334
67,213,190
How can I reshape the (1006,19) result of keras regressor predictions into a (1006,1) numpy array?
<p>I'm trying to create a stock prediction model in botch PyTorch and Keras. I have already followed some tutorials online and modified to fit my data and it works fine.</p> <p>Now I'm translating that code into a compatible Keras model. I've already created the model and did the predictions but the problem is that the...
<p>Set the <code>return_sequences</code> to <code>False</code> for the last <code>LSTM</code> layer. You need to do as follows:</p> <pre><code>.... .... regression.add(LSTM(units=50,kernel_initializer='glorot_uniform', return_sequences=False)) regression.add(Dropout(0.2)) regression.add(Dense(units...
python|tensorflow|machine-learning|keras|pytorch
1
361,335
67,589,990
How to convert Python Dataframe utc time column to epoch timestamp?
<p>I have a df with time column in ISO Format</p> <pre><code>df = pd.DataFrame({'time':['2021-05-01T16:08:59.094953+00:00','2021-05-01T16:08:56.675183+00:00','2021-05-01T16:08:56.675183+00:00']}) </code></pre> <p><a href="https://i.stack.imgur.com/miNbR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com...
<p>TRY this approach</p> <pre><code>pd.to_datetime(df.time).astype(int) / 10**9 </code></pre>
python-3.x|pandas|dataframe|datetime
0
361,336
67,257,891
Pandas get three most common values for every column in groupby
<p>I have a table like this:</p> <pre><code> colour number letter 0 red one a 1 red two b 2 red two c 3 blue two a 4 blue two b 5 green one a 6 green two b 7 green three c </code></pre> <p>Which I made by doing:</p> <pre><code>df = pd.DataFrame([ ('red', 'one', 'a'), ('red...
<p>Try:</p> <pre><code>def fn(x): return pd.Series( (x.value_counts().index[:3].tolist() + [np.nan, np.nan])[:3], index=range(1, 4), ) out = pd.concat( [ df.groupby(&quot;colour&quot;)[col].apply(fn).unstack(level=0).ffill() for col in df.loc[:, &quot;number&quot;:] ], ...
python|pandas
1
361,337
67,292,315
Is there a way to extract a solid box slice of an arbitrary multidimensional Python array given two sets of corner index coordinates?
<p>Suppose I have <code>a = np.arange(16).reshape(4,4)</code>, which is</p> <pre><code>array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) </code></pre> <p>And want to slice <code>a</code> as I could with <code>a[0:3,1:4]</code>, which results in</p> <pre><code>array([[ ...
<p>I am not sure about a numpy way of doing this but you can use <code>slice</code> and <code>zip</code> to do this.</p> <pre><code>import numpy as np def box_slice(arr, start, stop): return arr[tuple(slice(*i) for i in zip(start, stop))] a = np.arange(16).reshape(4, 4) print(box_slice(a, [0, 1], [3, 4])) a = np...
python|multidimensional-array|numpy-slicing|array-indexing
1
361,338
67,186,335
aggregate irregular data to monthly averages weighing for days in months,using python
<p>I am struggling to average my data into monthly mean taking into account that the data can represent two months (and years), and there are empty periods. Thus a need to weigh the samples accordantly, i.e. a sample with 2 days in one month and 5 in the next should have 2/7 and 5/7 weight, respectively. I have tried t...
<p>From a software design prospective, it looks like you need to do some data cleaning before trying to interact with the data.</p> <p><a href="https://i.stack.imgur.com/YHVpi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YHVpi.png" alt="Data Science Cycle" /></a></p> <p>You need to define what you...
python|pandas|weighted-average
0
361,339
67,573,950
Visualizing values in a normalized plot
<p>I have some data that I would like to plot, visualizing in a normalized chart. Dataset:</p> <pre><code> Gini var1 0.000223 var2 0.000047 var3 0.000933 var4 0.000081 var5 0.000014 df.sort_values(by='Gini', ascending=False).plot(kind='bar') </code></pre> <p>I have tried w...
<p>If you're having a single column and plotting only the <code>&quot;Gini&quot;</code> column, you can select that column and normalize it before plotting it like:</p> <pre class="lang-py prettyprint-override"><code>((df['Gini']-df['Gini'].min())/(df['Gini'].max()-df['Gini'].min())).sort_values().plot(kind='bar') </co...
python|pandas|matplotlib|visualization
2
361,340
67,461,425
What is the relation between a learning rate scheduler and an optimizer?
<p>If I have a model:</p> <pre><code>import torch import torch.nn as nn import torch.optim as optim class net_x(nn.Module): def __init__(self): super(net_x, self).__init__() self.fc1=nn.Linear(2, 20) self.fc2=nn.Linear(20, 20) self.out=nn.Linear(20, 4) ...
<p><strong>TL;DR:</strong> The LR scheduler contains the optimizer as a member and alters its parameters learning rates explicitly.</p> <hr /> <p>As mentioned in <a href="https://pytorch.org/docs/stable/optim.html" rel="noreferrer">PyTorch Official Documentations</a>, the learning rate scheduler receives the optimizer ...
python|pytorch
5
361,341
67,393,754
(Selenium, Python) Concatenate URL + CSV data, then open each URL in a new tab
<p>I wish to read a list of strings from a CSV file and concatenate the string with a URL, then open this complete URL list individually in each tab. So far I am able to do either or. I can read the data from the CSV file and open the data in each tab, or concatenate the URL + data and have it loop through the same tab...
<pre><code>for url in urls: driver.execute_script('window.open(&quot;{}&quot;, &quot;_blank&quot;,);'.format(link + str(url))) driver.close() </code></pre> <p>got it as soon as i post the question, I need a duck it seems</p>
python|pandas|selenium|csv|selenium-webdriver
0
361,342
67,403,280
How to impute specific row value by adding values of 2 different row values of same column in python
<p>I have a DataFrame shown below:</p> <pre><code> df = {'col1': {0: 'v1', 1: 'v2', 2: 'v3', 3: 'v4'}, 'col2': {0: np.nan, 1: 13, 2: 76, 3: 2}, 'col3': {0: np.nan, 1: 91, 2: 3, 3: 33}, 'col4': {0: np.nan, 1: 9, 2: 47, 3: 62}} </code></pre> <p>I want to replace all &quot;nan&quot; values assoc...
<p>Try with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html#pandas-dataframe-loc" rel="nofollow noreferrer">loc</a></p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd df = pd.DataFrame({'col1': {0: 'v1', 1: 'v2', 2: 'v3', 3: 'v4'}, ...
python|pandas|dataframe|data-manipulation|data-wrangling
0
361,343
67,236,923
comparing pandas list in column with external list
<p>Given a sample dataframe column:</p> <pre><code>colA colB 1 [20,40,50,60] 2 [20,70,80] 3 [10,90,100] </code></pre> <p>and given this list <code>test_lst = [20, 45, 35]</code></p> <p>I am trying to develop a way to filter my dataframe to only show rows in which at lea...
<p>You can use <code>set.intersection</code>:</p> <pre><code>test_lst = [20, 45, 35] print(df[df.colB.apply(lambda x: set(x).intersection(test_lst)).astype(bool)]) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override"><code> colA colB 0 1 [20, 40, 50, 60] 1 2 [20, 70, 80]...
python|pandas
6
361,344
67,336,267
What is the fastest way to get modification date of a list of files in a directory using Python?
<p>I have a folder in a directory with a large amount of csv files (500+). I only need the csv files with a modification date after a certain date. Eventually I will pd.concat these files into a single pandas dataframe.</p> <p>What is the fastest way to get an overview of the relevant files?</p> <p>My current solution ...
<p>Try to evaluate the modification time before initializing dataframe -</p> <pre><code>import glob result= [] for file in glob.glob(Path + '*.csv'): temp = { 'files': file, 'Modification_Time': datetime.date.fromtimestamp( os.path.getmtime(file) ), } result.append(temp...
python|pandas|time
2
361,345
67,196,226
Remove rows from tensor by matching
<p>I'm trying to do some operation like if there is tensor in pytorch</p> <pre><code>a = torch.tensor([[1,0] ,[0,1] ,[2,0] ,[3,2]]) b = torch.tensor([[0,1] ,[2,0]]) </code></pre> <p>I want to remove the rows [0,1], [2,0] which are the rows of <co...
<p>You <em>could</em> do it if the tensor shapes were broadcastable.</p> <p>For a tensor <code>a</code> of shape <code>(?, d)</code> and a tensor <code>b</code> of shape <code>(d,)</code>, you could write something like:</p> <p><code>cmp = a.eq(b).all(dim=1).logical_not()</code>, i.e. compare each <code>d</code>-dimens...
python|pytorch|tensor
0
361,346
67,596,697
Unable to move R analyses output back to Python (rpy2)
<p>I am attempting to pass some data from python to R and then retun the results to a python but can't seem to get it to work.</p> <p>I am successful in passing my data to R and running my custom function on the data and even get the output. Where I am stuck is getting the statistical output back into python as a dataf...
<p>The problem was in</p> <pre><code>return(list(&quot;params&quot; = summary(fit), &quot;r2&quot; = cor(predict(fit), df$y)^2)) </code></pre> <p>The first item in the list &quot;params&quot; was a summary table from R. While this printed in python as the data I wanted it was a single object that could not be subdivide...
python|r|pandas|rpy2
0
361,347
67,485,983
subset pandas df columns with partial string match OR match before "?" using lists of names
<p>I hope someone might help me.</p> <p>I have a dataframe that inculdes columns with <strong>similar</strong> names (see example data)</p> <p>I have 3 additional lists of column names which include the original names of the columns (i.e. the string occurring before the question mark (see lists of column names)</p> <p>...
<p>You can form a dynamic regex for each df lists:</p> <pre><code>df_lists = [df1_lst, df2_lst, df3_lst] result = [df.filter(regex=fr&quot;\b({'|'.join(names)})\??&quot;) for names in df_lists] </code></pre> <p>e.g., for the first list, the <a href="https://regex101.com/r/xi7DK3/1" rel="nofollow noreferrer">regex</a> ...
python|pandas|list|subset|partial-matches
1
361,348
67,442,107
Pandas: Expand/Explode Dataframe Horizontally
<p>This may be a duplicate, but I can't find the required answer. So, here's the question:</p> <p>Suppose, I have got a dataframe like this:</p> <pre><code>d1 = {'col1': [[1],[2,3]], 'col2' : [[3],[21,1]]} df1 = pd.DataFrame(d1) </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> ...
<pre class="lang-py prettyprint-override"><code>x = pd.concat( [df1[c].apply(pd.Series).add_prefix(c + &quot;_&quot;) for c in df1], axis=1 ) print(x) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override"><code> col1_0 col1_1 col2_0 col2_1 0 1.0 NaN 3.0 NaN 1 2.0 3.0 ...
python|python-3.x|pandas|dataframe|pandas-groupby
4
361,349
67,524,250
Encountering strange issue in python numpy.mean function when using vectorise
<p>I am writing a function and passing a nested list to it. The goal is to find the mean of the each nested list. For eg. if the below is the input</p> <pre><code>[[1914.05004882812], [1930.65002441406, 1934.5]] </code></pre> <p>I want the output to be like the below, mean of each individual list.</p> <pre><code>[1914....
<p>If you need a list as output, I think <code>map</code> will work:</p> <pre><code>def map_f(x): return list(map(np.mean,x)) </code></pre> <p>Try:</p> <pre><code>map_f([[1914.05004882812], [1930.65002441406, 1934.5]]) [1350.3250122070299, 1358.9500122070299] map_f([[1349.15002441406, 1351.5], [1358.90002441406, 1...
python|numpy|vectorization|google-colaboratory
1
361,350
67,232,549
How did langid.py create the model binary as strings in code?
<p><a href="https://github.com/saffsd/langid.py" rel="nofollow noreferrer">Langid.py</a> is a popular language detection library.</p> <p>Inside the library's <a href="https://raw.githubusercontent.com/saffsd/langid.py/master/langid/langid.py" rel="nofollow noreferrer"><code>langid.py</code> file</a>, there's a peculiar...
<p>You can sort of reverse engineer the serialization process by simply looking at how they decode it.</p> <p>It is apparent that the operations <code>b64decode</code> -&gt; <code>decompress</code> -&gt; <code>loads</code> are happening. Furthermore, the object that is pickle loaded clearly seems to be a list of lists,...
python|numpy|scikit-learn|nlp|binary
1
361,351
67,371,125
How to drop a index row from multiindex dataframe in python
<p><strong>DataFrame :df</strong></p> <pre><code>None | A B col1 col1 col2 col2 X | v1 v2 v1 v2 --------------------------------------- 0 | e1 f1 12 &quot;def&quot; 65 &quot;pqr&quot; 1 | e1 f2 23 &quot;def&quot; 20 &quot;pqr&quot; 2 | e1 f3 0 &quot;de...
<p>Answer -</p> <pre><code>df.droplevel(&quot;X&quot;,axis=1) </code></pre>
python|pandas|dataframe|multi-index
0
361,352
67,542,305
Python | NumPy - Poor performance for algorithm that sums y values with same x value
<p>I'm trying to develop an algorithm that sums every y values with the same x values. The following works fine for small datasets, but once the number of rows crosses into the tens of thousands the use of a for loop to sum over all of the unique x values is very slow. Is there another way to do this that does not invo...
<p>Maybe use pandas groupby to group the same values and then take the sum of those?</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import pandas as pd data = np.array([[1, 2], [1, 3], [1, 5], [2, 2], [2, 4], [3, 1], [3, 8], [3, 9]]) x= data[:,0] x = np.unique(x) y = [] df = pd.DataFrame(data) df.gr...
python|numpy
0
361,353
67,357,722
Difference between NumPy.dot() and ‘*’ in Python
<p>Normally: <code>a * b == np.multiply(a, b)</code> but in this case :</p> <pre><code>a=np.matrix(([1,2,3],[1,2,3],[1,2,3])) b = np.array(([1,2,3])) print( a.dot(b)) print(np.multiply(a,b)) print(a * b) </code></pre> <p>I have a problem:</p> <pre><code>[[14 14 14]] [[1 4 9] [1 4 9] [1 4 9]] Traceback (most recent ca...
<h3>You should replace np.matrix by np.array to get the same result!</h3> <pre><code>a = np.array(([1,2,3],[1,2,3],[1,2,3])) b = np.array(([1,2,3])) print( a.dot(b)) print(np.multiply(a,b)) print(a * b) </code></pre> <h3>Additional Information</h3> <p><strong>1. element-wise product</strong>: <code>a*b</code> or <stron...
python|numpy|matrix
0
361,354
67,236,710
Split time (HHMMSS) into three different columns
<pre><code>Column A 22:55:12 </code></pre> <p>Column A is currently in (Object), Sample to convert it into Datetime format</p> <pre><code>Expected Output: Hour Minute Seconds 22 55 12 </code></pre> <p><a href="https://i.stack.imgur.com/qhyM8.png" rel="nofollow noreferrer">Sample</a></p>
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.split.html#pandas-series-str-split" rel="nofollow noreferrer">pandas.Series.str.split</a> with the expand flag set to True.</p> <p>Then assign the new columns back to your DF.</p> <pre class="lang-py prettyprint-override"><code>impor...
python|pandas
1
361,355
67,392,558
Python Pandas merge two data frames on two keys and get totals
<p>I have two dfs</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>F1_ID</th> <th>F2_ID</th> <th>Event_ID</th> <th>Date</th> </tr> </thead> <tbody> <tr> <td>a1</td> <td>b2</td> <td>ab4</td> <td>5/12/21</td> </tr> <tr> <td>a2</td> <td>b3</td> <td>ab5</td> <td>5/12/21</td> </tr> <tr> <td>b2</t...
<p>Simply use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html" rel="nofollow noreferrer">pandas.DataFrame.append()</a></p> <pre class="lang-py prettyprint-override"><code>df2 = df2.append(df1, ignore_index=True) </code></pre> <pre><code>print(df2) F1_ID Event_Name F2_...
python|pandas
1
361,356
67,424,189
Pandas Sequebtial Count of members within a group and the sum
<p>If I want to have a sequential count within a group I can do something like</p> <pre><code>df['GID'] = df.groupby(['G_COL1','G_COL2]).cumcount() </code></pre> <p>I cannot however figure out how to generate a column that contains the total number of values within the group. So if the group had three members df['GID']...
<pre><code>df[&quot;count_zeros&quot;] = pd.DataFrame((df[&quot;GID&quot;]==0)).cumsum() df[&quot;COUNT&quot;] = df.groupby(&quot;count_zeros&quot;).transform(lambda x: len(x))[&quot;GID&quot;] </code></pre> <p>I think the above gives what you want. The GID column starts from zero whenever a new group starts taking pla...
pandas|dataframe|group-by
1
361,357
67,367,856
Create a new column in df based on multiple NaN checks
<p>I am trying to create a derived column based on multiple NaN checks.</p> <p>Df</p> <pre><code>A|B|C NaN|23|dfs NaN|NaN|dsdfs 1223|3423|234234 NaN|NaN|NaN </code></pre> <p>Df with derived field D - if A and B and C is not empty or NaN, concatenate the values in A,B,C</p> <pre><code>A|B|C|D NaN|23|dfs|&quot;&quot; NaN...
<p>You can try this.</p> <pre><code># df = df.convert_dtypes() uncomment this to convert dtypes of all the columns to suitable data-types. ( df.assign(D=np.where( df.isna().any(axis=1), &quot;&quot;, df.astype(str).apply(''.join, axis=1) # or df.astype(str).sum(axis=1) ) ) ) </code>...
python|pandas|dataframe|null
1
361,358
67,252,385
How can I group a pandas dataframe by time with a minimal amount of rows for each group?
<p>I have a dataframe that looks like this;</p> <pre><code> created_at value1 value2 value3 2021-04-25 11:38:33 1 1 5 2021-04-25 11:38:47 4 3 6 2021-04-25 11:39:36 1 1 8 2021-04-25 11:39:47 6 5 5 2021-04-25 11:...
<p>One-liner:</p> <pre class="lang-py prettyprint-override"><code>df.groupby( [pd.Grouper(key='created_at', freq='2Min')] ).agg( lambda x: x.mean() if len(x) &gt; 20 else None # get None if there are not at least 20 rows in the group ).dropna( how='all', axis=0 # remove all the rows with all na values ) <...
python|pandas
2
361,359
67,338,129
I want a correct way to Install OSMnx on my fresh Linux
<p>I have been installing and using OSMnx on my windows+ anaconda system. But, due to on and on issues on windows I have switched to Linux which is totally fresh. I need a correct way to install OSMnx on Linux using <code>pip</code> . I can't install anaconda due to an issue with size.</p> <p>I tried finding .whl files...
<blockquote> <p>I can't install anaconda due to an issue with size.</p> </blockquote> <p>If a size issue is your only problem with anaconda, then you could use miniconda instead, as this will be far easier than installing with pip.</p> <blockquote> <p>I need a correct way to install OSMnx on Linux using pip .</p> </blo...
python|linux-kernel|geopandas|osmnx
0
361,360
67,236,830
add a datetime element between two other datetime elements
<p>I have a df with a bit low sampling rate. I want to interpolate the NaN values in value column. My problem is the 'ts' column. My samples are not evenly spaced, and I have trouble trying to use timedelta to create the 'ts' value between the samplings.</p> <p>Example, df.head(4):</p> <pre><code> 'ts' ...
<p>The error is as simple as passing the correct arguments to the constructor. The docs <a href="https://numpy.org/doc/stable/reference/arrays.datetime.html#datetime-units" rel="nofollow noreferrer">https://numpy.org/doc/stable/reference/arrays.datetime.html#datetime-units</a> specify &quot;The length of the span is th...
python|pandas|datetime
0
361,361
67,558,535
How to use list comprehensions for dataframe with two or more variables in python?
<p>I've dataframe <code>df</code> from excel</p> <p>Is this possible in any way:</p> <pre><code>df[&quot;A&quot;] = [foo(b, c) for (b, c) in (df[&quot;B&quot;], df[&quot;C&quot;])] </code></pre> <p>need to pass variables in function from different columns of dataframe</p> <p>thx</p>
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>df.apply()</code></a> on <code>axis=1</code> (for column index) to get the corresponding values of <code>df[&quot;B&quot;]</code> and <code>df[&quot;C&quot;])</code> for each r...
python|pandas|list|dataframe|list-comprehension
2
361,362
67,425,731
How to number each consecutive night in a pandas dataframe using python
<p>In Python 3x I have some filled lists and I have put these in a pandas dataframe with 'ID' and 'Time' as columns:</p> <pre><code>import pandas as pd df = pd.DataFrame({'ID': ID, 'UTCTime': UTCTime}) print(df) ID UTCTime 3 4 2021-04-03 21:56:53 4 5 2021-04-03 21:56:55 5 6 2021-04-03 21:56:57...
<p>Use <code>shift</code> to find date change and use <code>cumsum</code> to create nightID.</p> <pre><code>import pandas as pd df = pd.DataFrame({'ID': range(8), 'UTCTime': pd.to_datetime(['2021-04-03 14:56:53', '2021-04-03 18:00:00', ...
python|pandas|indexing
0
361,363
67,519,676
Iterate through Python dictionary in customer order - Per row instead of per key
<p>Let's say the following situation: I have a dictionary with 3 keys. Every key is a pd dataframe with 5 rows.</p> <p>I am currently iterating through the complete dictionary using:</p> <pre><code>for key in dict1: for i in range(len(dict1[key])): do_something </code></pre> <p><strong>So the way this iter...
<p>It doesn't need smart way. You have to use <code>for</code>-loops in different order - first <code>range</code>, next <code>keys</code>. That's all.</p> <pre><code>for i in range(len(dict1['key1'])): for key in dict1: print(dict1[key].iloc[i,0]) </code></pre> <hr /> <p>Minimal working code</p> <pre><code...
python|pandas|loops|dictionary|iteration
2
361,364
67,377,407
Calculate Average True Range directly with Dataframe
<p>I wonder if there is a simple and direct way to calculate <a href="https://www.investopedia.com/terms/a/atr.asp" rel="nofollow noreferrer">ATR</a> from DataFrame object. I am stuck in the max() part. This is what I am trying to do:</p> <pre><code>df['atr']=max( (df['High']-df['Low']), (df['High']-df['Close'].shift()...
<p>Following your approach:</p> <pre><code>np.max( ((df['High']-df['Low']).values, np.abs(df['High']-df['Close'].shift()), np.abs(df['Low']-df['Close'].shift())) , axis=0) </code></pre> <p>A function can be this (no pandas copy warning):</p> <pre><code>def ATR(data: pd.DataFrame, window=14, use_nan=True) -&gt; pd.Serie...
pandas
0
361,365
67,261,035
convert column to date time in pandas(Data Cleaning)
<p>i have a column which is of format h:m:s:ms dd/mm/yy(but not consistent) <a href="https://i.stack.imgur.com/MWbxw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MWbxw.png" alt="col3 date field" /></a> Unique values of the column are <a href="https://i.stack.imgur.com/7aBCO.png" rel="nofollow nore...
<p>First is necessary remove trailing spaces with <code>\t</code> values, replace possible <code>\t</code> to spaces and split with join formats in swapped ordering.</p> <pre><code>#https://raw.githubusercontent.com/sprabhala-cpu/Machine-Learning/main/datetime.txt df = pd.DataFrame({'col3':a}) s = df['col3'].str.strip...
python|pandas|data-cleaning
0
361,366
67,197,448
How to extract multiple rows from tensor at the same time?
<p>TL;DR: TensorFlow tensor is of shape <code>(50, 50, 6)</code>, want these indices (:, :, (0, 2, 3)). How to extract them?</p> <p>Here is an example array I am working with:</p> <pre><code>import numpy as np a = np.random.randint(0,10, (50, 50, 6)) </code></pre> <p>I want to extract the the first, third, and fourth ...
<p>If you want the 0,2 and 3rd element of the last axis in the tensor, you can use tf.gather as follows: tf.gather(t,indices=[0, 2, 3],axis=-1))</p>
python|arrays|numpy|tensorflow
1
361,367
67,381,454
Loop through all the values (string) in one column and append the values in another column if not unique-Text processing
<p>I would like to find a solution for the following problem:</p> <pre><code>import pandas as pd rows = {'Id': ['xb01','nt02','tw02','dt92','tw03','we04','er04','ew06','re07','ti92'], 'DatasetName': ['first label','second label','third label','fourth label','third label','third label','third label','fourth la...
<p>Let's try an <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.aggregate.html#pandas-core-groupby-dataframegroupby-aggregate" rel="nofollow noreferrer"><code>agg</code></a> with <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.SeriesGroupBy.unique.htm...
python|pandas|dataframe|nlp
1
361,368
67,532,334
How to apply Filer in header row with pandas
<p>Let say I have dataframe like this:</p> <pre><code> col1 col2 col3 0 A A_1 pass 1 A A_2 pass 2 A A_1 fail 3 A A_1 fail 4 A A_1 pass 5 A A_2 fail </code></pre> <p>I want to save this dataf...
<p>Try this:</p> <pre><code>import pandas as pd from openpyxl import load_workbook path = r'D:\temp\you.xlsx' df.to_excel(path,index=False) wb = load_workbook(path) ws = wb.active ws.auto_filter.ref = ws.dimensions wb.save(path) wb.close() </code></pre>
python|python-3.x|excel|pandas|dataframe
1
361,369
67,219,284
Python - Calculating ranks related to a dataframe column that includes blank cells
<p>I have a Panda dataframe and want to produce an extra column that holds the ranks of an original column in the pd. However, the column has empty cells. The ranks for those empty cells should be empty as well.</p> <p>When I use</p> <pre><code>df['RRanked'] = df['R'].rank(ascending=1,na_option='keep') </code></pre> ...
<p>Well, I solved it in a not so &quot;clean&quot; way. I managed to replace all those cells by NaN. Then I used the kind answer by Yefet: df['R'].apply(lambda x: pd.NA if x in [&quot;NaN&quot;] else x).rank(ascending=1). Later, I just replace the NaNs in the Ranks by &quot;&quot;. That works.</p>
python|pandas|dataframe|rank
0
361,370
67,214,578
Why pandas Dataframe.to_csv has a different output as Series.to_csv?
<p>I need a one-line CSV with data split by a <code>,</code>. My problem is when I try to iterate over my Dataframe using apply, I get a <code>Series</code> object and the <code>to_csv</code> method gives me one <code>str</code> split into lines, setting <code>None</code> as <code>&quot;&quot;</code> and without any <...
<p>Well, I researched a lot, and my output is different because it is the expected behavior. I found a PR in the Pandas repository where some contributor adds a snippet with <code>Series.to_csv</code> and has the same output I have (<a href="https://github.com/pandas-dev/pandas/pull/21896#issuecomment-405003819" rel="n...
python|python-3.x|pandas|dataframe|csv
1
361,371
34,844,423
Index lookup for calculation
<p>This is a follow-up of the following question: <a href="https://stackoverflow.com/questions/34735915/pandas-dataframe-window-function">Pandas DataFrame Window Function</a></p> <pre><code> analysis first_pass fruit order second_pass test units highest \ 0 full 12.1 apple 2 20.1 ...
<p>You could use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.sign.html" rel="nofollow"><code>np.sign()</code></a>:</p> <pre><code>second_pass = df.groupby(['test', 'analysis']).apply(lambda x: {fruit: int(np.sign(x.loc[x.fruit==fruit, 'second_pass'].iloc[0] - x.loc[x.fruit==fruit, 'first_...
python|numpy|pandas
0
361,372
34,796,896
Pandas: How to groupby and get a count of uniques in a given column?
<p>I have a DataFrame that has three columns:</p> <pre><code>id order ordernumber 1 app 1 1 pip 2 1 org 3 2 app 1 3 app 1 3 org 3 </code></pre> <p>The "order" column only has 3 unique values (app, pip and org). I would like to get...
<p>You can use <code>pivot_table</code> to get the counts:</p> <pre><code>&gt;&gt;&gt; df2 = df.pivot_table(index='id', columns='order', aggfunc='size', fill_value=0) &gt;&gt;&gt; df2 order app org pip id 1 1 1 1 2 1 0 0 3 1 1 0 </code></pre> <p>Then you can add the 'total' c...
python|pandas|dataframe|pivot-table
2
361,373
34,781,192
TensorFlow. Changes in code in CIFAR10 example are not reflected when I run cifar10_train.py
<p>For example, I wanted to change the distortions in distorted_inputs. I commented out the random crops and the random flips. After doing so, I saved the file, and ran cifar10_train.py. I then ran TensorBoard, and viewed the images in the image visualizer. I realized that they are still flipped and cropped. This is so...
<p>I found the problem. Changing the lines at the top of each .py file, such as:</p> <pre><code>from tensorflow.models.image.cifar10 import cifar10 </code></pre> <p>to</p> <pre><code>import cifar10 </code></pre> <p>did the trick. I'm not too sure myself on why it works, but it's probably because doing such an impor...
tensorflow
3
361,374
34,516,729
Quickest way to calculate the average growth rate across columns of a numpy array
<p>Given an array such as:</p> <pre><code>import numpy as np a = np.array([[1,2,3,4,5],[6,7,8,9,10]]) </code></pre> <p>What's the quickest way to calculate the growth rates of each row so that my results would be <code>0.52083333333333326</code>, and <code>0.13640873015873009</code> respectively. </p> <p>I tried usi...
<pre><code>In [262]: a = np.array([[1,2,3,4,5],[6,7,8,9,10]]).astype(float) In [263]: np.nanmean((a[:, 1:]/a[:, :-1]), axis=1) - 1 Out[263]: array([ 0.52083333, 0.13640873]) </code></pre>
python|arrays|numpy
4
361,375
34,550,514
How to efficiently generate a special co-author network in python pandas?
<p>I'm trying to generate a network graph of individual authors given a table of articles. The table I start with is of articles with a single column for the "lead author" and a single column for "co-author". Since each article can have up to 5 authors, article rows may repeat as such: </p> <pre><code>| paper_ID | pro...
<p>With <code>df</code> as your first <code>DataFrame</code>, you should be able to:</p> <pre><code>nodes = pd.concat([df.loc[:, ['lead_id', 'is_published']].rename(columns={'lead_id': 'author_id'}, df.loc[:, ['co_lead_id', 'is_published']].rename(columns={'co_lead_id': 'author_id'}]).drop_duplicates() </code></pre> ...
python|networking|pandas|graph
1
361,376
34,666,001
Why is it not possible to access other variables from inside the apply function in Python?
<p>Why would the following code not affect the <code>Output</code> DataFrame? (This example is not interesting in itself - it is a convoluted way of 'copying' a DataFrame.)</p> <pre><code>def getRow(row): Output.append(row) Output = pd.DataFrame() Input = pd.read_csv('Input.csv') Input.apply(getRow) </code></pre...
<h2>What happens</h2> <p><code>DataFrame.append()</code> returns a new dataframe. It does not modify <code>Output</code> but rather creates a new one every time.</p> <blockquote> <pre><code> DataFrame.append(self, other, ignore_index=False, verify_integrity=False) </code></pre> <p>Append rows of <code>other</c...
python|pandas
5
361,377
34,537,027
how does one make lines thicker in pandas subplots
<p>I am using pandas to plot 3 subplots in a single figure. The code below accomplishes this. However, I am having trouble making the data lines in the subplots thicker. Anybody know how to do this? </p> <pre><code>## setup 3 dataframes t_index=pd.date_range('1/1/2000', periods=10); df_1 = DataFrame(np.random.randn(10...
<p>Specify a line width (<code>lw</code>) parameter:</p> <pre><code>df_3.plot(ax=target3, lw=4) </code></pre> <p><a href="https://i.stack.imgur.com/TUeBF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TUeBF.png" alt="enter image description here"></a></p>
python|pandas|matplotlib
16
361,378
34,539,290
Python numpy fill masked elements in matrix according to order in another matrix
<p>I'm trying to do a Uniform Order Crossover for a genetic algorithm. In that, I have two 2D arrays p1 and p2 and a 2D bit array, b. p1, p2 and b are of the same shape. I mask elements in p1 corresponding to 1s in b and elements in p2 corresponding to 0s in b. From these, I need to generate 2 matrices c1 and c2 such t...
<p>I can't exactly make sense of what exactly you're asking, because either you have made a typo in your question or I'm just completely missing the point here.</p> <p>So, first we have a mask for p1</p> <pre><code>mp1 = [[1, _, 3, _, 5], [1, _, _, 2, _]] </code></pre> <p>where the <code>_</code> values shoul...
python|arrays|numpy|matrix
0
361,379
34,518,141
Python/Scikit-learn - How to actually predict?
<p>I have the following DataFrame, which I call main_frame:</p> <pre><code> Value Value 1lag 2lag 3lag 4lag Date 2005-04-01 0.824427 0.892308 1.000000 0.000000 0.000000 0.000000 2005-05-01 0.778626 0....
<p>You are passing the wrong argument into the predict function. Try this:</p> <pre><code>prediction=model.predict(predictor) print prediction </code></pre> <p>Note that the model has been trained using the "predictor" variable. So you can only predict data that have the exact same amount of columns as the "predictor...
python|pandas|scikit-learn
2
361,380
34,698,864
Count frequencies of x, y coordinates, display in 2D and plot
<p>I am trying to plot the frequency of how often viral biological sequences combination of isolation year differences and nucleotide differences occurs. I am trying to find an elegant way to do it have having trouble. </p> <p>So I have an alignment and I compare each sequence against each other to get an integer valu...
<p>I'm heavily borrowing the table construction of <a href="https://stackoverflow.com/a/10195347/2243104">this post</a>.</p> <p>The difference here is in constructing the array data. By initialising an array with zeros, for every coordinate (i, j), you increment that array element by one, to represent the incremented ...
python|pandas|plot
1
361,381
34,797,323
Pandas Can't use Apply on Transposed DataFrame
<p>I have a simple function:</p> <pre><code>def f(returns): base = (1 + returns.sum()) / (1 + returns).prod() base = pd.Series([base] * len(returns)) exp = returns.abs() / returns.abs().sum() return (1 + returns) * base.pow(exp) - 1.0 </code></pre> <p>and a DataFrame:</p> <pre><code>df = pd.DataFrame([[...
<p>As EdChum says, the problem is pandas is trying to align the index of the Series you create inside <code>f</code> with the index of the DataFrame. This coincidentally works in your first example because you don't specify an index in the <code>Series</code> call, so it uses the default <code>0, 1, 2</code>, which ha...
python|pandas
2
361,382
60,240,602
Conversion between Cartesian vs. Polar Coordinates. Hoping the result is positive
<p>I have several points that I need to covert them from Cartesian to Polar Coordinates. But for some points, the results I got were negative values.</p> <p>For example, the origin or the center of the system is (50,50), and the point I want to covert is (10, 43). The angle I got from my code is -170.07375449, but I w...
<p>If you need to convert [-180; 180] angle to [0; 360] you can use this code:</p> <pre><code>def convert_angle(angle): return (angle + 360) % 360 </code></pre>
python|numpy
1
361,383
60,037,586
Run Mask RCNN code and stuck at "Converting sparse IndexedSlices to a dense Tensor of unknown shape"
<p>I'm new to Python and Tensorflow <br> Running Mask RCNN code from <a href="https://www.analyticsvidhya.com/blog/2018/07/building-mask-r-cnn-model-detecting-damage-cars-python/" rel="nofollow noreferrer">this tutorial</a> and got stuck at <br> "<strong>Converting sparse IndexedSlices to a dense Tensor of unknown shap...
<p>its not "stuck", its in training. Epoch 1/10 means its currently on the first epoch and there are 100 steps in an epoch, the speed of each epoch can vary according to different specifics in the code. For example </p> <ul> <li>Are you using a GPU? If no then mask-rcnn training will be extremely slow.</li> <li>What i...
python|tensorflow|faster-rcnn
0
361,384
59,952,078
Matplotlib side by side bar plot
<p>I am trying to plot the following dataframe using matplotlib:</p> <pre><code>df = pd.DataFrame({'X': ["A", "A", "B", "B"], 'Z': ["a", "b", "a", "b"], 'Y': [5, 1, 10, 5]}) df X Z Y 0 A a 5 1 A b 1 2 B a 10 3 B b 5 </code></pre> <p>What I want is two bar plots where the bars are next...
<p>If you want to have the bars side by side you can use the <a href="https://seaborn.pydata.org/" rel="nofollow noreferrer">seaborn</a> library:</p> <pre><code>import seaborn as sns sns.barplot(data=df, x='Y', hue='Z', y='X') </code></pre> <p><a href="https://i.stack.imgur.com/os7KH.png" rel="nofollow noreferrer"><i...
python|pandas|matplotlib
4
361,385
59,937,062
Specific conditions for string replacement?
<p>I was wondering if it were possible to iterate over a pandas column and replace strings if a particular condition was met. Essentialy I have a dataframe column with 100s of strings all in the general format GCA_XXXXX.X_MMXXXX.X, although some are in the XXXX_MMXXXX.X format, and I need to remove one of that dashes ...
<p>Maybe try something like this:</p> <p><code>df['column'] = df['column'].astype(str).replace('_MM','|MM') df['column'] = df['column'].astype(str).replace('GCA_','GCA') </code></p>
python-3.x|pandas
0
361,386
60,215,245
Using a pandas method on multilevel index without the level argument
<p>I've been looking through Pandas documentation on multilevel indexing, and I'm getting stuck on one problem:</p> <p>If I have a multi level index, and want to apply operations on a particular level of the index, I'm not sure how I would do this if the method doesn't have the <code>level</code> argument. </p> <p>H...
<p>You can use a groupby operation on the level of interest for methods that don't have the level built in:</p> <pre><code>series.groupby(level=0)['Value'].diff() </code></pre> <p>For your df would return:</p> <pre><code>&gt;&gt;&gt; series.groupby(level=0)['Value'].diff() Item Date A 2020-01-01 NaN ...
python|pandas
1
361,387
60,053,147
Taking the min value of N last days
<p>I have this data frame:</p> <pre><code>ID Date X 123_Var 456_Var 789_Var A 16-07-19 3 777 250 810 A 17-07-19 9 637 121 529 A 20-07-19 2 295 272 490 A 21-07-19 3 778 600 544 A 22-07-19 6 741 792 907 A 25-07-19 6 ...
<p>Use similar solution like @Chris with custom lambda function in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer"><code>GroupBy.apply</code></a> and last join to original by <a href="http://pandas.pydata.org/pandas-docs/stable/referen...
python|pandas|numpy
2
361,388
59,979,763
Can't get done Conv1D with tf.keras
<p>I'm having te following model and the dataset contains 186093 time-series where each time-series is the length of 48</p> <p>Tensorflow version 2.x</p> <pre><code>model = tf.keras.models.Sequential([ tf.keras.layers.Conv1D(30, 4, activation=tf.nn.selu, input_shape=(train_data.shape[1], train_data.shape[0])), ...
<p>The problem in simply the shape of your data.</p> <p>First things first, I'm assuming <code>train_data.shape[0]</code> gives 186093. This is the number of discrete samples. It is not the number of features in a single sample.</p> <p>So change <code>input_shape=(train_data.shape[1], train_data.shape[0])</code> to <...
python|tensorflow|conv-neural-network|tf.keras
1
361,389
60,169,905
How can I differentiate between values in lower end of colorbar spectrum? (sns heatmap)
<p>I have a sns clustermap outlined below. </p> <pre><code>fig = plt.figure(figsize=(14,10)) sns.clustermap(df2,cmap='icefire', center=18, fmt=".3f", linewidths=0.05, annot=True) </code></pre> <p>But I have some really small values (e.g. 0.6) that are just above 0 and that are all getting coloured the same way. I pla...
<p>Depending on the significance of the data and their distribution, you could work with a logarithmic or a diverging norm. The parameters could be like this:</p> <pre class="lang-py prettyprint-override"><code>mport numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.colors as mcolors im...
python|pandas|seaborn|heatmap
0
361,390
60,005,900
initial_sparsity parameter in sparsity.PolynomialDecay() TensorFlow 2.0 magnitude-based weight pruning
<p>I was trying the tutorial <a href="https://www.tensorflow.org/model_optimization/guide/pruning/pruning_with_keras#train_a_pruned_mnist" rel="noreferrer">TensorFlow 2.0 Magnitude-based weight pruning with Keras</a> and came across the parameter <em>initial_sparsity</em></p> <pre><code>import tensorflow_model_optimiz...
<p>So I also found the Tensorflow documentation on weight pruning to be quite <em>sparse</em>, so I spent some quality time with the debugger to figure out how everything works. <br><br></p> <h1>How Pruning Schedules Work</h1> <p>At the most basic level, the Pruning Schedule is simply a function that takes the step a...
python|tensorflow|neural-network
9
361,391
60,140,400
Pandas Group-By and Calculate Ratio of Two Columns
<p>I'm trying to use Pandas and groupby to calculate the ratio of two columns. In the example below I want to calculate the ratio of staff <strong>Status</strong> per <strong>Department</strong> (Number of Status in Department/Total Number of Employees per Department). For example the <strong>Sales</strong> department ...
<p>Try (with the original <code>df</code>):</p> <pre class="lang-py prettyprint-override"><code>df.groupby("Department")["Status"].value_counts(normalize=True).mul(100) </code></pre> <p>Outputs:</p> <pre class="lang-py prettyprint-override"><code>Department Status Finance Contractor 100.000000 Marketing Co...
python-3.x|pandas|pandas-groupby
4
361,392
59,913,069
Image deconvolution with a CNN
<p>I have an input tensor of <code>shape (C,H,W)</code>, where <code>H=W</code> and <code>C=W^2</code>. This tensor contains non-linearly transformed information for an image of <code>shape (1,H,W)</code> squeezed to <code>(H,W)</code>. The exact form of the transformation is not important (plus, there is no closed-f...
<p>There's no problem with applying a ReLU layer near the beginning, as long as you apply a weighted linear layer first. If the net learns that it needs the values there, it can apply a negative weight to preserve the information (roughly speaking).</p> <p>In fact, a useful thing to do in some networks is to normalize...
python|deep-learning|pytorch|conv-neural-network
2
361,393
59,905,927
python pandas - creating a column after matching keys with another data frame
<p>I have two data frames. for the sake of simpleness, I will provide two dummy data frames here.</p> <pre><code>A = pd.DataFrame({'id':[1,2,3], 'name':['a','b','c']}) B = pd.DataFrame({'id':[1,1,1,3,2,3,1]}) </code></pre> <p>Now, I want to create a column on the data frame B with the names that match the ids. In thi...
<p><code>pd.merge</code> or <code>.map</code> we use your id column as the key and return all matching values on your target dataframe.</p> <pre><code>df = pd.merge(B,A,on='id',how='left') #or B['name'] = B['id'].map(A.set_index('id')['name']) </code></pre> <hr> <pre><code>print(df) id name 0 1 a 1 1 ...
python|pandas|dataframe|lookup
2
361,394
60,325,093
Pandas forward and backward fill on distinct indices
<p>I have the following dataframe df:</p> <pre><code> length timestamp width name testschip-1 NaN 2019-08-01 00:00:00 NaN testschip-1 NaN 2019-08-01 00:00:09 NaN testschip-1 2 2019-08-01 00:00:20 NaN testschip-1 2 2019-08-01...
<p>Use:</p> <pre><code>df.index = df.index.str.lstrip('testschip-').astype(int) #alternative #df.index = df.index.str[10:].astype(int) #df.index = df.index.str.split('-').str[-1].astype(int) df.groupby(level = 0).apply(lambda x: x.bfill().ffill()) </code></pre> <p><strong>Output</strong></p> <pre><code> length ...
python-3.x|pandas|fill
2
361,395
59,987,700
How to add names to layers of Keras sequential model
<p>I use Keras in Tensorflow 2.0 to create a sequential model:</p> <pre><code>def create_model(): model = keras.Sequential([ keras.layers.Flatten(input_shape=(28,28), name="bla"), keras.layers.Dense(128, kernel_regularizer=keras.regularizers.l2(REGULARIZE), activation="relu",), keras.layers...
<p>You're doing it the right way, straight from my jupyter :</p> <pre class="lang-py prettyprint-override"><code>from tensorflow import keras model = keras.Sequential([ keras.layers.Flatten(input_shape=(28,28), name="bla"), keras.layers.Dense(128, activation="relu",), keras.layers.Dropout(0.5), keras....
keras|tensorflow2.0
1
361,396
60,026,028
How do I create a tensorflow gpu docker container with data-science library support?
<p>I have managed to create and run a tensorflow container with gpu support, and managed to run simple python scripts that only use tensorflow. But I would like to be able to use other librarys such as openCV, PIL, etc.. </p> <p>I've seen tutorials for setting up 'datascience' containers, but none with GPU acceleratio...
<p>A minimal Dockerfile that builds upon <code>tensorflow/tensorflow:latest-gpu</code> and installs some custom debian and python packages on top of it could look like so:</p> <pre><code> # Install custom debian packages you need # e.g. python 3 pip RUN apt update &amp;&amp; apt install -y -q python3-pip # Install cu...
python|docker|tensorflow
0
361,397
60,100,733
Pandas Memory Error when creating new columns with apply() custom function
<h1>Function to compute mean log(1+TPM) of 2 replicates</h1> <pre><code>def average_TPM(a,b): log_a = np.log(1+a) log_b = np.log(1+b) if log_a &gt; 0.1 and log_b &gt; 0.1: avg = np.mean([log_a,log_b]) else: avg = np.nan return avg </code></pre> <h1>Applying the function to df to cr...
<p>Not sure why you have memory error, but you can vectorize your problem:</p> <pre><code>#dummy variable np.random.seed = 2 df = pd.DataFrame(np.random.random(8*4).reshape(8,-1), columns=['a1','a2','b1','b2']) print (df) a1 a2 b1 b2 0 0.416493 0.964483 0.089547 0.218952 1 0.655331 ...
python|pandas|memory-management|vectorization|apply
1
361,398
60,163,503
How to Load Weka data set from pandas dataframe in python
<p>Currently I am setting the pandas dataframe into a csv and loading it as weka dataset from CSV loader . Is there a mechanism to to directly load pandas dataframe into weka dataset without creating a intermediate CSV file in between </p> <pre><code>learn_df = pd.DataFrame.from_records([s.to_dict() for s in learnList...
<p>@Manish You can either convert the pandas dataframe into a list or a numpy matrix and then use the weka methods create_instances_from_lists() and create_instances_from_matrices().</p> <p>For more details you can look into the weka examples at <a href="http://fracpete.github.io/python-weka-wrapper/examples.html" rel=...
python|pandas|weka
3
361,399
60,283,116
GroupBy and Change the values of one columns
<p><a href="https://i.stack.imgur.com/DhasS.png" rel="nofollow noreferrer">dataframe</a></p> <p>Hi dear coders, I need help from you as I don't know how to deal with it. As you can see on my dataframe i have a column description and a column title. I want for a same description , my title to be all the same. I want to...
<p>Here's a solution with some dummy data using <code>pandas.DataFrame.transform</code>:</p> <pre><code>import pandas as pd df = pd.DataFrame({'title': ['t1', 't2', 't3', 't4', 't5'], 'description': ['d1', 'd1', 'd1', 'd2', 'd2']}) description title 0 d1 t1 1 d1 t2 2 ...
python|pandas
2