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,800
61,530,950
Convert a dictionary containing arrays to a DataFrame with arrays as strings
<p>I have a dictionary that looks like this:</p> <pre><code>d = {name: 'A', 'numbers': array([2.72, 3.74, 1.75])} </code></pre> <p>And I need to create a Pandas DataFrame from this dictionary. I am currently using <code>df = pd.DataFrame.from_dict(d)</code></p> <p>However, the DataFrame looks like this:</p> <pre><c...
<p>This would do:</p> <pre><code>pd.DataFrame({k:[v] for k,v in d.items()}).astype(str) </code></pre> <p>Output:</p> <pre><code> name numbers 0 A [2.72, 3.74, 1.75] </code></pre>
python|pandas|dataframe|dictionary
1
361,801
61,588,153
LSTM - predicting on a sliding window data
<p>My training data is an overlapping sliding window of users daily data. it's <strong>shape is</strong> <code>(1470, 3, 256, 18)</code>:<br> <strong>1470</strong> batches of <strong>3</strong> days of data, each day has <strong>256</strong> samples of <strong>18</strong> features each. </p> <p>My targets <strong>sha...
<p>I think you are looking for TimeDistributed(LSTM(...)) (<a href="https://github.com/keras-team/keras/issues/2648" rel="nofollow noreferrer">source</a>)</p> <pre><code>day, num_samples, num_features = 3, 256, 18 model = Sequential() model.add(Masking(mask_value=-10., input_shape=(day, num_samples, num_features))) m...
python|tensorflow|keras|lstm
1
361,802
61,592,891
How to "reverse-map" keys of a dictionary to a row, if one in the list of values matches in the row?
<p>there is this list with among others the columns, year and criterion. There also is a dictionary of labels (key) each with a list of criteria (value). I would like to add a label each row in which the criterion matches one entry in the list of values.</p> <p>As an example:</p> <pre><code>import pandas as pd lab...
<p>The easiest way is to create an reverse dictionary and map:</p> <pre><code>reverse_label = {x:k for k,v in labels_dict.items() for x in v} df['labels'] = df['criterion'].map(reverse_label) </code></pre> <p>Output:</p> <pre><code> year criterion labels 0 2014 1 label_1 1 2014 2 label_1 ...
python|pandas|dataframe
3
361,803
61,311,334
Problem with updating running_mean and running_var in a custom Batchnorm built in Pytorch?
<p>I have been trying to implement a custom batch normalization function such that it can be extended to the Multi GPU version, in particular, the DataParallel module in Pytorch.The custom batchnorm works alright when using 1 GPU, but, when extended to 2 or more, the running mean and variance work in the forward functi...
<p>Replacing </p> <p><code>self.running_mean = (...)</code></p> <p>with</p> <p><code>self.running_mean.copy_(...)</code></p> <p>did the job.</p> <p><a href="https://discuss.pytorch.org/t/implementing-batchnorm-in-pytorch-problem-with-updating-self-running-mean-and-self-running-var/49314/11" rel="nofollow noreferre...
python-3.x|deep-learning|pytorch|batch-normalization|multi-gpu
2
361,804
61,459,831
Prevent python3 process being 'Killed' by not having enough memory
<p>I am trying to concatenate two large matrices of numbers, the first one: <code>features</code> is an <code>np.array</code> shaped <code>1238,72</code>, the other is being loaded from a <code>.json</code> file as it can be seen on the second line below, it is shaped <code>1238, 768</code>. I need to load, concatenate...
<p>Try:</p> <pre><code>bert = [json.loads(line)['features'][0]['layers'][0]['values'] for line in f] </code></pre> <p>this way you at least do not read the whole file in memory at once - that being said if the file is huge you must further process what you store in <code>bert</code></p>
python|json|pandas|optimization|memory
1
361,805
61,210,026
How do I rearrange this pandas dataframe?
<p>Right now, I have data for three poems. Each poem has 4 metrics (so columns A-D for the first poem, columns E-H for the second poem, columns I-L for the third). Each row contains scores from one person (so row 1 would contain person 1's scores for poems 1, 2 and 3, respectively, and row 2 would contain person 2's sc...
<p>Assume that the source <em>df</em> has been created as:</p> <pre><code>df = pd.DataFrame(np.arange(1,25).reshape(2, -1), columns=[ 'Metric ' + x for x in list('ABCD') ] * 3) </code></pre> <p>so it contains:</p> <pre><code> Metric A Metric B Metric C Metric D Metric A Metric B Metric C Metric D Metri...
python|python-3.x|pandas|dataframe|pandas-groupby
0
361,806
61,190,044
Python Read files and append to a dataframe
<p>I'm trying to read multiple files in a folder. I have around 100 files. I'm using the below code to read a file and append it to a data frame. There seems to be an issue with the index. After data frame is created, the columns are getting swapped. eg:</p> <blockquote> <p>File 1 gets appended in the format ID, NAME, ...
<p>Try to erase the last line since it is useless and make dfs not a list but an empty Dataframe </p> <pre><code>dfs = pd.DataFrame(data={'ID' :str(0), 'NAME':str(0), 'ADDRESS':0, 'COORDINATES':str(0)}] </code></pre> <p>Then append all the other files to it as you did and at the end you can eliminate the first observ...
python|pandas|csv|dataframe
0
361,807
61,207,344
Merging table by group in pandas
<p>I have a dataset with human genes. I want to check all possible combination of alleles. So my df:</p> <pre><code>Human Gene AllelA AllelB 1 gene1 C C 1 gene2 A T 1 gene3 G G 1 gene4 T A 2 gene1 C C 2 ...
<p>Problem are duplicates by <code>Human</code> and <code>Gene</code>, you can check them:</p> <pre><code>print (df) Human Gene AllelA AllelB 0 1 gene1 C C &lt;- added dupe row for test 1 1 gene1 C C 2 1 gene2 A T 3 1 gene3 G G 4 1 gene4 T...
python|pandas
3
361,808
61,583,071
Creating a new column based off repeating rows
<p>My goal is to create a new column that includes the total repetitions per date.</p> <p><strong>Before</strong></p> <pre><code> date 0 6/1/18 1 6/1/18 2 6/4/18 3 6/5/18 4 6/6/18 6 6/6/18 7 6/6/18 </code></pre> <p><strong>After</strong></p> <pre><code> date count 0 6/1/18 2 1 6/1/18 2 2 6/...
<p>Let us do</p> <pre><code>df['count']=df.date.groupby(df.date).transform('count') df date count 0 6/1/18 2 1 6/1/18 2 2 6/4/18 1 3 6/5/18 1 4 6/6/18 3 6 6/6/18 3 7 6/6/18 3 </code></pre>
python|pandas
3
361,809
61,604,785
How do I retrieve a value from np.arange?
<p>I have the line</p> <pre><code>a = np.arange(2.8,4,0.0001) </code></pre> <p>and later on I need to use it in a for loop as part of a function</p> <pre><code>x(v,n+1) = a(v)*x(v,n)*(1-x(v,n)) </code></pre> <p>where v and n are all index numbers for the for loop. But it says that numpy.ndarray object is not callab...
<p>Your <code>a</code> variable is a numpy.ndarray object and not a function, yet you are accessing <code>a</code> as a function. Try the correct syntax for accessing an array:</p> <p><code>a[v]</code></p> <p>instead of:</p> <p><code>a(v)</code></p>
arrays|numpy|for-loop
0
361,810
61,357,686
Buffer has wrong number of dimensions (expected 1, got 2)
<p>I need to select the first 2000 rows of a dataframe if the <code>groupby</code> count of the particular column is greater than 2000. How can this be done in python? Is the below one is the correct way of doing</p> <pre><code>X_train[ 1:2000, X_train.groupby(['value']).count() &gt; 2000]. </code></pre> <p>I am gett...
<pre><code>df = pd.DataFrame(np.random.randint(1, 10, 100).reshape((20,5))) col = 0 lower_bnd = 2 n_rows = 3 count = df.groupby([col]).size() selection = count[count &gt; lower_bnd].index dg = df.loc[df[col].isin(selection)].iloc[:n_rows] </code></pre>
python|pandas
0
361,811
61,370,733
How to get back index to dataframe as a column?
<p>I want to get back my current index variable as a column variable. Is it possible?I tried using df.reset_index() but it did not work.Please click the link to view current version of fataframe</p> <p>Ex:<a href="https://i.stack.imgur.com/h8WkY.png" rel="nofollow noreferrer">Please Click here to view the current data...
<p>you could use </p> <pre class="lang-py prettyprint-override"><code>df['new_column'] = df.index </code></pre> <p>It will copy the index as is, so if it's a datetime index then the new column will be a datetime column as well.</p>
python|pandas|dataframe|indexing
1
361,812
61,244,313
How to read large xlsx file to fast in python?
<p>Is there any option to read and get DataFrame in <strong>fast</strong> with <em>large excel</em> files in python?</p>
<p>Pandas provides a function to read excel files:</p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html</a></p> <p>I think you need to install <code>xlrd</code> sep...
python|pandas|dataframe|xlsx|large-files
0
361,813
61,530,350
Grid of plots with lines overplotted in matplotlib
<p>I have a dataframe that consists of a bunch of x,y data that I'd like to see in scatter form along with a line. The dataframe consists of data with its form repeated over multiple categories. The end result I'd like to see is some kind of grid of the plots, but I'm not totally sure how matplotlib handles multiple su...
<p>You can use either <code>sns.FacetGrid</code> or manual <code>plt.plot</code>. For example:</p> <pre><code>g = sns.FacetGrid(data=total_data, col='category', col_wrap=3) g = g.map(plt.scatter, 'x','data') g = g.map(plt.plot,'x','y', color='k'); </code></pre> <p>Gives:</p> <p><a href="https://i.stack.imgur.com/egT...
python|pandas|numpy|matplotlib
2
361,814
61,511,339
how can I remove a parentheses "( )" from an Index with Pandas?
<h2>I have an output like this:</h2> <pre><code>Vanuatu 22 10 Venezuela(Bolivarian Republic of) 32 10 Viet Nam 44 05 </code></pre> <h2>and I want something like this:</h2> <pre><code>Vanuatu 22 ...
<p>I think, this is exactly what you are looking for: </p> <pre><code>import re df['column_name'] = df['column_name'].str.replace(r'\([^)]*\)', '') </code></pre>
python|regex|pandas
0
361,815
61,543,572
Pytorch Matrix element wise multiplication
<p>Let's say I have two tensors A of shape : [32 , 512] and B of shape : [32 , 512], <br> And I want to do element-wise multiplication between the vectors of the matrix to get a new matrix of shape : [32 , 1] (first row of A with first row of B, and second row of A with second row of B and so on.. ) , current methods I...
<p>I guess this is equivalent of what you're looking for, first a matrix multiplication, then sum over each row. [associative law]</p> <pre><code>import torch a = torch.zeros(31,512) b = torch.zeros(31,512) c = torch.sum(torch.mm(a,torch.t(b)), dim=1).unsqueeze(-1) print(c.shape) </code></pre> <p>Out:</p> <pre><co...
pytorch
0
361,816
61,262,517
Pandas series returning wrong index?
<p>I'm very confused, I'm getting a <code>KeyError</code> whenever I execute this piece of code:</p> <pre><code>for k, v in df['crew_data'].items(): if v == 'xxx': df = df.drop([k]) return df </code></pre> <p>If the keys are being extracted for the same <code>for</code> loop, then why are they...
<p>I think the problem is that you're not looping over what you think you are. I think you're looking for <code>df.iterrows()</code> like so:</p> <pre><code>for k, v in df.iterrows(): if v['crew_data'] == 'xxx': df = df.drop([k]) return df </code></pre> <p>Try printing out <code>k</code> and <code...
python|python-3.x|pandas
0
361,817
61,340,777
Boundary Value Problem with Array as Coefficient
<p>First I am solving a boundary value problem, then I am reusing these results to solve another set of boundary value problems. However that means one of my coefficients in the second set of boundary value problems is an array that mismatches the dimensions when the solver attempts to do this. When I insert the first ...
<p>After the definition of <code>bc1</code> change to</p> <pre class="lang-py prettyprint-override"><code>sol1 = solve_bvp(fun1, bc1, x, y) print(sol1.message) def func2(x, y2): # Call the Magnetic Solver y = sol1.sol(x) yp = fun1(x,y) B = y[0] dB = y[1] U = -C_k*zeta*y[1] dU = -C_k*zeta*y...
numpy|differential-equations|derivative|equation-solving|boundary
1
361,818
61,276,498
Not able to extract nested table body with pandas from webpage
<p>I am trying to extract nested table from the url '<a href="http://gsa.nic.in/report/janDhan.html" rel="nofollow noreferrer">http://gsa.nic.in/report/janDhan.html</a>' using pandas with code:</p> <pre><code>import pandas as pd url ="http://gsa.nic.in/report/janDhan.html" table=pd.read_html(url)[3] print(table) table...
<p>The table is being populated by javascript, so it is not in the HTML that pandas is fetching. You can confirm this by viewing the source of the page in your browser and searching for values that are in the table, such as "PRADESH."</p> <p>The solution is to use a library such as <code>requests-html</code> or <code>...
python|pandas|web-scraping|data-wrangling
1
361,819
61,313,268
Pandas explode error - column must be scalar
<pre><code>df.explode(['X']) ValueError: column must be a scalar </code></pre> <p>Hi anyone could advice on this?</p>
<p>You can supply a list or tuple of column names, but only with pandas &gt;= 1.3.0: see <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.explode.html" rel="noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.explode.html</a></p> <blockquote> <p>New in version 1.3.0: Multi-c...
python|pandas|explode
8
361,820
61,453,983
Split Pandas Dataframe Column According To a Value
<p>I searched and I couldn't find a problem like mine. So if there is and somehow I couldn't find please let me know. So I can delete this post.</p> <p>I stuck with a problem to split pandas dataframe into different data frames (df) by a value. </p> <p>I have a dataset inside a text file and I store them as <code>pan...
<p>One idea with unique index values is replace non matched values to NaNs and backfilling them, last loop <code>groupby</code> object for list of <code>DataFrame</code>s:</p> <pre><code>g = df.index.to_series().where(df['var1'].eq('endValue')).bfill() dfs = [a for i, a in df.groupby(g, sort=False)] print (dfs) [ ...
python|pandas|numpy
3
361,821
61,524,773
How to replace with second column with missing if 0?
<p>I have a csv file which is below</p> <pre><code>ID,Name1,Name2 1,A,A 2,B,B 3,C,D 4,0,F 5,0,Z </code></pre> <p>The new table is below</p> <pre><code>ID,NewName 1,A 2,B 3,C 4,F 5,Z </code></pre> <p>Basically if <code>0</code> coming in the <code>Name1</code> has to replace with <code>Name2</code></p>
<p>You can use <code>replace</code> then do <code>bfill</code></p> <pre><code>df['Name']=df.drop('ID',1).replace({'0':np.nan}).bfill(1).iloc[:,0] df ID Name1 Name2 Name 0 1 A A A 1 2 B B B 2 3 C D C 3 4 0 F F 4 5 0 Z Z </code></pre>
pandas
0
361,822
61,582,098
Groupby for 3 columns
<p>I would like use groupby function based on 3 columns. First column has surname info for families, second column has name of individuals in that families.Third column has which animal every individual has in those families. I want to get information of person with name and surname who has cat or dog and how many of c...
<p>I think is a better task for <code>pivot_table</code></p> <pre><code>df_merged.query("Animal.isin(['Cat', 'Dog'])") .pivot_table(columns='Animal', index=['Family', 'SubFamily'], aggfunc='size') .fillna(0) .reset_index() .rename_axis(None, axis=1) # Family SubFamily Cat Dog # 0 Jackson Jason 0.0 ...
python|pandas
0
361,823
61,602,115
filter excel data with python pandas
<p><a href="https://i.stack.imgur.com/5BdFm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5BdFm.png" alt="enter image description here"></a></p> <p>I want to filter out country belonging to the tuple <strong>need</strong> and display every data in the records for countries after filter...</p> <pr...
<p>Forget the <code>for</code> loop and just use:</p> <pre><code># for i in data.index: # &lt;-- remove this filt = data[data['Recipient'].isin(need)] </code></pre>
python|pandas
2
361,824
61,513,206
Python: How to print out the cause of RuntimeWarning: invalid value encountered in greater
<p>In my simulation, when reaching such an expression of a function inside a for loop:</p> <pre><code>d1ToUse = d2Weights[:,i] &gt; 1e-9 </code></pre> <p>a warning is sometimes thrown:</p> <pre><code>RuntimeWarning: invalid value encountered in greater... </code></pre> <p>I would like to print out the value of the...
<p>You could use the <em>warnings</em> library: <a href="https://docs.python.org/3/library/warnings.html" rel="nofollow noreferrer">https://docs.python.org/3/library/warnings.html</a> <a href="https://www.geeksforgeeks.org/warnings-in-python/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/warnings-in-python...
python|numpy|spyder
1
361,825
61,489,511
Add latitude and longitude column to existing data frame
<p>I am unable to add latitude and longitude column to existing data frame. I have extracted coordinates from one of the column <strong>Restaurant_Location</strong> from my data-set using below code.</p> <pre><code>location = [x for x in rest_df['Restaurant_Location'].unique().tolist() if type(x) == str] latitude = []...
<p>Here is a pice of code that should work, I deleted some stuff as I'm not sure why, but you can still put them back if you do other things in it. <code>new_df</code> should have all the rows from your original dataframe, and added the two columns you want. I have not been able to test as I don't have your data, so th...
python|pandas|nominatim
1
361,826
61,226,942
read excel files from sub folders in a folder in python
<p>I want to read the excel files in subfolder from a list of folders. </p> <pre><code>directory_list = list() for root, dirs, files in os.walk('D:/Sectors_Week_1/', topdown=False): for name in dirs: directory_list.append(os.path.join(root, name)) for root in roots: for i in range(len(dirs)): s...
<h1>Thanks @sammywemmy for edits</h1> <p>Try module which is now in standard for paths: <code>pathlib</code></p> <p>Finding all excel files:</p> <pre class="lang-py prettyprint-override"><code>from typing import List import pathlib def find_excel_files_in(directory:pathlib.Path) -&gt; List[pathlib.Path]: files:...
python|pandas
2
361,827
61,223,241
Dividing by bigger value of substraction
<p>I have two matrices of shape <code>(43, 25520)</code>, they are called <code>m1</code> and <code>m2</code>.</p> <pre><code>if m1 &lt;= m2: distance = (m1 - m2) / m2 else: distance = (m1 - m2) / m1 </code></pre> <p>So for each index <code>i</code>, I want to subtract <code>m2[i]</code> from <code>m1[i]</cod...
<p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.maximum.html" rel="nofollow noreferrer"><code>np.maximum</code></a> returns the element-wise maximum of two matrices:</p> <pre><code>(m1 - m2) / np.maximum(m1, m2) </code></pre> <p>If you want only positive values less than one, use <a href="https...
python|numpy|calculation
5
361,828
61,331,401
Why numpy.sum on dataframe columns return inf?
<p>I have a Pandas dataframe with columns of type float64</p> <p>I try to compute apply sum function on some columns by <code>numpy.sum</code></p> <p>When I active the function <code>np.sum(x[col_name])</code> I receiving the result of 'inf'</p> <p>But when I check where is the 'inf' value by <code>np.where(np.isi...
<p>The problem appears to be that one of the numbers in your data, is bigger than the max <code>np.float64</code> accepts. If you run, <code>np.finfo(np.float64)</code>, you'll see the biggest number this dtype accepts:</p> <pre><code>Machine parameters for float64 -----------------------------------------------------...
python|pandas|numpy|dataframe
2
361,829
68,777,067
Updating QTableView on the fly when data source changes with a QSortFilterProxyModel in between
<p>I'm trying to update a QTableView when the data source (Pandas Dataframe) changes. I'm using a QAbstractTableModel as the &quot;base&quot; table model and a QSortFilterProxyModel to do some filtering.</p> <p>Somewhen during runtime the data source changes. According to that my goal is to reset the &quot;base&quot; t...
<p>The problem is not the QSortFilterProxyModel but the information is not being updated in the sourceModel, you are copying the df to the DataStore but that updates the TableModel information causing that error.</p> <pre class="lang-py prettyprint-override"><code>import sys import pandas as pd from PySide2 import QtC...
python|pandas|pyside2|qabstracttablemodel|qsortfilterproxymodel
1
361,830
68,482,554
Group by and add new column with min value between dates - pandas
<p>I have this Pandas dataframe:</p> <p><a href="https://i.stack.imgur.com/kFdEQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kFdEQ.png" alt="enter image description here" /></a></p> <p>I want a new DF to group them by ['ticked_id','time_a'] and add a new column with the min difference in time (hh...
<p>To group the data and get a column with the minimum date of the <code>time_b</code> column you can do:</p> <pre><code>df_grouped = df.groupby(['ticket_id', 'time_a'])['time_b'].min().reset_index() </code></pre> <p>I don't know the datatypes of your <code>time_a</code> and <code>time_b</code> columns but if they are ...
python|sql|pandas|dataframe|pandas-groupby
1
361,831
68,555,694
Pandas Grouping
<p>Given dataframe:</p> <pre><code>+-------+------+-------+ |Product|Amount|Country| +-------+------+-------+ | Banana| 1000| USA| |Carrots| 1500| USA| | Beans| 1600| USA| | Orange| 2000| USA| | Orange| 2000| USA| | Banana| 400| China| |Carrots| 1200| China| | Beans| 1500| China| | Orange| ...
<p>Use <code>pivot_table</code>:</p> <pre><code>&gt;&gt;&gt; df.pivot_table(index='Product', columns='Country', values='Amount', aggfunc=sum) Country Canada China Mexico USA Product Banana 2000.0 400.0 NaN 1000.0 Beans NaN 1500.0 2000.0 1600.0 Carrots 2000.0 1200.0 NaN 1500.0 Orange ...
pandas|dataframe
0
361,832
68,453,630
how to get value 50 rows before condition is true
<p>I am using this code , all other things are right but at the end condition is not true but still giving flag 1</p> <pre><code>df=pd.DataFrame({'A':[1,8.5,5.2,7,8,9,0,4,5,6],'B':[1,2,2,2,3.1,3.2,3,2,1,2]}) df['flag']=np.where((df['B']&gt;3).shift(-2),1,0) </code></pre> <p>here are result at the end B not greater than...
<p>try:</p> <p>check if the value is greater then 3 after shifting :</p> <pre><code>df['flag']=np.where((df['B'].shift(-2).gt(3)),1,0) </code></pre> <p>OR</p> <p>If you want to include shifted rows as well in your condition then use <code>fillna()</code>:</p> <pre><code>df['flag']=np.where((df['B'].shift(-2).fillna(df[...
python-3.x|pandas|numpy|pandas-groupby
1
361,833
68,636,983
Create Variable of Extracted Substring Before and After Character
<p>In a data table, I have a variable <code>'RESULT'</code> with a ton of text that looks like this:</p> <pre><code>Transfer Handoff Entered On: 07/25/2021 2:45 EDT Performed On: 07/25/2021 2:45 EDT by LAST, FIRST RN Handoff Clinician Relationship to Patient : Nurse Clinician Receiving Report : Handoff ...
<p>You can use Pandas function <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>str.extract()</code></a>, as follows:</p> <pre><code>df['RECEIVING_UNIT'] = df['RESULT'].str.extract(r'Receiving Unit\s*:(.*?)\s*Intrahospital') </code></pre...
python|pandas
2
361,834
68,841,286
Convert one dataframe's format and check if each row exits in another dataframe in Python
<p>Given a small dataset <code>df1</code> as follow:</p> <pre><code> city year quarter 0 sh 2019 q4 1 bj 2020 q3 2 bj 2020 q2 3 sh 2020 q4 4 sh 2020 q1 5 bj 2021 q1 </code></pre> <p>I would like to create date range in quarter from <code>2019-q2</code> to <code>2021-q1<...
<p>We can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>crosstab</code></a> on <code>city</code> and the string concatenation of the <code>year</code> and <code>quarter</code> columns:</p> <pre><code>new_df = pd.crosstab(df['city'], df['yea...
python-3.x|pandas|dataframe|datetime
1
361,835
68,591,135
Using Pytorch-cuda as base image for Docker
<p>I need to use Pytorch with cuda gpu access. I use FROM &quot;pytorch/pytorch:1.9.0-cuda10.2-cudnn7-runtime&quot; as my base image. Does necesssary python version also installed with this command ?</p>
<p>From the DockerHub you can see how these kinds of images are built: <a href="https://hub.docker.com/layers/pytorch/pytorch/1.9.0-cuda10.2-cudnn7-runtime/images/sha256-5dc11a9036bcb5b7950f4f8a43974057559278fa4bd87513cafd477fef9eb57a?context=explore" rel="nofollow noreferrer">https://hub.docker.com/layers/pytorch/pyto...
docker|pytorch
0
361,836
68,801,406
CSV to JSON using a custom format
<p>I am attempting to create a JSON file from a CSV using Pandas</p> <p><strong>CSV File</strong> This is just an excerpt, sorry for the long table, but I wanted to show things more clearly.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Month</th> <th>Type</th> <th>Subtype</th> <th>ItemNa...
<p>You can first create Series filled by <code>list</code>s by aggregation and then in nested dict comprehension create expected ouput:</p> <pre><code>s = df.groupby([&quot;Month&quot;, &quot;Type&quot;, &quot;SubType&quot;], sort=False)['ItemName'].agg(list) compiled = {i: {j[1]: h[j].to_dict() for j...
json|pandas|csv
2
361,837
68,485,015
Keras custom loss function returns Value Error
<p>I am using a custom loss function in <a href="https://github.com/google-research/google-research/tree/master/tft" rel="nofollow noreferrer">google TFT</a> model.</p> <pre><code>def custom_loss(y_actual,y_pred): tupl = np.shape(y_actual) flag = tf.compat.v1.math.is_nan(y_actual) y_actual = y_actual[tf....
<p>You can't have <code>if</code> statements in your loss function as it has no gradient.<br /> Try replacing it with this code. This loop serves the same function as your <code>if</code> statements</p> <pre><code>def custom_loss(y_actual,y_pred): tupl = np.shape(y_actual) flag = tf.compat.v1.math.i...
python|tensorflow|keras
1
361,838
68,599,156
Assigning keys and storing in a dictionary Python
<p>For an event of rolling a six-sided die. I need to randomly simulate the event 1000 times and plot a histogram of results for each number on the dice. I want to assign the results for each number to a key of the same value (1 for number of 1s{1:164...}).</p> <p>I need help assigning keys and storing everyting in a d...
<pre><code>dic = dict() for i in range(len(test_data)): dic[i+1] = test_data[i] </code></pre>
python|numpy|dictionary|random
0
361,839
68,565,147
Pytorch unable to export trained model as ONNX
<p>I have been training a model in the Pytorch framework using multiple convolutional layers (3x3, stride 1, padding same). The model performs well and I want to use it in Matlab for inference. For that, the ONNX format for NN exchange between frameworks seems to be the (only?) solution. The model can be exported using...
<p>Currently, <code>_convolution_mode</code> operator <a href="https://pytorch.org/docs/stable/onnx.html#supported-operators" rel="noreferrer">isn't supported</a> in pytorch. This is due to the use of <code>padding='same'</code>.</p> <p>You need to change padding to an integer value or change it to its equivalent. Cons...
python-3.x|matlab|pytorch|conv-neural-network|onnx
5
361,840
68,659,144
How to find the sum of every 4 elements in an array
<p>I have an array that will print a 10x10 random numbers from 1 to 9. I want to sum every 4 elements horizontally and vertically.</p> <p>Here is the code:</p> <pre><code>import numpy as np random_array = np.random.randint(1, 10, size=(10, 10)) print(random_array) </code></pre> <p>For example:</p> <pre><code>[[7 4 5 7...
<p>You can use <a href="https://numpy.org/doc/stable/reference/arrays.indexing.html#basic-slicing-and-indexing" rel="nofollow noreferrer">slicing</a> and <code>np.sum</code></p> <pre><code>&gt;&gt;&gt; a = np.random.randint(1,10, size=(10,10)) &gt;&gt;&gt; a array([[2, 5, 5, 6, 2, 7, 4, 4, 2, 7], [1, 4, 4, 5, 7,...
python|arrays|numpy
1
361,841
68,834,138
Combine multiple rows of different strings into one using pandas
<p>I have a dataframe with multiple rows. Is there any way in which they can be combined to form one rows? Marked with Yellow Colours. All I want to combine that into one row. Remember that I wanted to ignore the empty rows when you combine. See the output section of attached image(&quot;Problem. jpg&quot;).</p> <p><a...
<p>If you move the &quot;Drilling good ground all shift&quot; to the leftmost column so that your file looks like:</p> <pre><code>Drilling good ground all shift 2 x Gyro Surveys Mixing muds to condition the hole Driller travelled home for shift change at end of shift Equipment onsite= </code></pre> <p>then I believe y...
python|pandas|dataframe
1
361,842
68,609,530
pd.to_datetime converting the date into a wrong date
<p>I have the data in the following format of,</p> <blockquote> <p>dd-mm-yyyy</p> </blockquote> <p><img src="https://i.stack.imgur.com/Aox8p.png" alt="enter image description here" /></p> <p>After I run the following commands to get date,</p> <pre><code>df['result_date']=pd.to_datetime(df['result_date']) df['t0']=pd.t...
<p><code>pd.to_datetime</code> follows the American convention when the format is ambiguous, where month is written before date. You can specify the format explicitly to make the format unambiguous</p> <pre class="lang-py prettyprint-override"><code>In [1]: pd.to_datetime(&quot;11/02/21&quot;, format=&quot;%d/%m/%y&quo...
python|pandas|datetime
0
361,843
68,868,317
value_counts unstack with additional categories
<p>I have this DataFrame:</p> <pre><code>data = [{'name':'John', 'date':20210801, 'work':False}, {'name':'John', 'date':20210802, 'work':True}, {'name':'Lucy', 'date':20210801, 'work':False}] df = pd.DataFrame(data) df.groupby(['name'])['work'].value_counts(normalize=True).unstack(fill_value=0).stack().reset_index() </...
<p>We can use normalized <a href="https://pandas.pydata.org/docs/reference/api/pandas.crosstab.html" rel="nofollow noreferrer"><code>crosstab</code></a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a> to ensure that there are bo...
python|pandas|dataframe
2
361,844
68,860,941
Tensorflow input shape of conv3d
<p>I am having video of (x,y) height and width, I am resizing the video to height 320 and width 120 with 3 channel of RGB. Now I am merging 60 frames from a video and created depth of 60 from total 10200 frames. Now I am not sure for training model with conv3d my input shape of (170, 60, 320, 120, 3) is correct. Is thi...
<p>According to the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv3D" rel="nofollow noreferrer">Conv3D docs</a> in the latest version of tensorflow as of this post, the default shape is <em>channels_last</em>. But you can change the <code>data_format</code> parameter to be either <code>channel...
python|python-3.x|numpy|tensorflow|keras
1
361,845
68,826,431
Python read csv single specific cell
<p>Im trying to read just a single cell, in order to bring in the date to use elsewhere. Using pandas I get an error If I try to do this, generally just that the dataframe cant be read because it expects a workable dataframe and not a single cell value prior to the actual convertable dataframe far below the initial lin...
<p>Yes, pandas is not very good at files with inconsistent format (like varying number of columns). For that purpose, I recommend you should use <a href="https://docs.python.org/3/library/csv.html" rel="nofollow noreferrer">csv</a> the standard library.</p> <p>The code below should give you the desired value.</p> <pre...
python|pandas|cell
0
361,846
68,451,898
ERROR: Cannot install gluonts, mxnet, numpy and pandas because these package versions have conflicting dependencies
<p>I wanted to install certain packages:</p> <pre><code>pip install gluonts==0.8.0 mxnet~=1.7 pathlib==1.0.1 numpy==1.17.2 pandas==1.0.5 ujson==4.0.2 torch~=1.6 pytorch-lightning~=1.1 </code></pre> <p>But during installation, i got the following error:</p> <pre><code>ERROR: Cannot install gluonts==0.8.0, mxnet==1.7.0.p...
<p>You have to install numpy 1.16.6 to be compatible to mxnet 1.7. Since there are no binary (whl) files for numpy 1.16.6 for python greater than 3.7 you need a compiler to build numpy from source (a zip file). See also <a href="https://stackoverflow.com/questions/65325177/how-to-solve-numpy-error-while-installing-mxne...
python|pandas|numpy|mxnet-gluon
2
361,847
68,830,425
AttributeError: 'Model' object has no attribute '_distribution_strategy'
<p>I'm trying to train a UNet, but for some reason I get the following error:</p> <pre><code>Traceback (most recent call last): File &quot;&lt;ipython-input-54-b56497e81356&gt;&quot;, line 1, in &lt;module&gt; model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=opt.learning_rate), loss=dice_coef_loss,...
<pre><code>!pip install -q tensorflow==2.2 !pip install -q keras==2.3.1 </code></pre> <p>can definitely solve this ,, enjoy;)</p>
python|tensorflow|deep-learning|attributeerror
0
361,848
68,791,508
min-max normalization of a tensor in PyTorch
<p>I want to perform min-max normalization on a tensor in PyTorch.</p> <p>The formula to obtain min-max normalization is</p> <p><a href="https://i.stack.imgur.com/0YPfa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0YPfa.png" alt="enter image description here" /></a></p> <p>I want to perform min-ma...
<p>Having defined <code>v_min</code>, <code>v_max</code>, <code>new_min</code>, and <code>new_max</code> as:</p> <pre><code>&gt;&gt;&gt; v_min, v_max = v.min(), v.max() &gt;&gt;&gt; new_min, new_max = -.25, .25 </code></pre> <p>You can apply your formula element-wise:</p> <pre><code>&gt;&gt;&gt; v_p = (v - v_min)/(v_ma...
python|pytorch|normalization
3
361,849
68,731,086
updating plotly figure [every several seconds] in jupyter
<p>I'm new to the plotly python package and I've faced with such problem:<br /> There is a pandas dataframe that is updating in a loop and I have to plot data from it with plotly.<br /> At the beginning all <code>df.response</code> values are <code>None</code> and then it starts to fill it. Here is an example:<br /> <a...
<ul> <li>given you want to update as data arrives you need an event / interrupt handling approach</li> <li>this example uses time as the event / interupt, a <strong>dash</strong> <strong>Interval</strong></li> <li>simulates more data by concatenating additional data to dataframe then updates the <strong>figure</strong>...
python|pandas|jupyter-notebook|plotly|python-multiprocessing
1
361,850
68,819,395
Extract routes from a given data set and visualize them with networkx
<p>Given is a DataFrame with pairs of start and end locations in chronological order.</p> <p>Example:</p> <ol> <li>a-b</li> <li>g-d</li> <li>b-g</li> <li>.....</li> </ol> <p>The goal is to create a &quot;networkx&quot; map to visualize all the routes with more than 2 nodes. Like this: A --&gt; B --&gt; G and so on...<...
<p>I can propose this code</p> <pre><code>import networkx as nx import pandas as pd df = pd.DataFrame({'start': ['a', 'g', 'b', 'd', 'b'], 'end': ['b', 'd', 'g', 'a', 'e']}) G = nx.Graph() def add_path(elemnt): global G G.add_edge(elemnt.start, elemnt.end) df.apply(add_path, axis=1) nx.draw(G, with_labels = ...
python|pandas|data-visualization|networkx
0
361,851
68,764,809
Why getting only day value from date in python pyplot Need help to get full date value on xaxis even though show in pivot table
<p>Why getting only day value from date in python pyplot. Need to get full date value on xaxis even though show in pivot table</p> <p><code>DFPlot_T</code> is Dataframe with columns - <code>DateValue</code>, <code>DCID</code>, <code>AUC</code> i.e. as below</p> <pre><code> DateValue DCID AUC 151 2021-07-08 ...
<p>If <code>DateValue</code> is already in <code>datetime64[ns]</code> format, you can format x axis with:</p> <pre><code>ax.xaxis.set_major_locator(md.DayLocator(interval = 1)) ax.xaxis.set_major_formatter(md.DateFormatter('%Y-%m-%d')) plt.setp(ax.xaxis.get_majorticklabels(), rotation = 90) </code></pre> <p>The <code>...
python|pandas|dataframe|datetime|matplotlib
0
361,852
68,585,485
Unable to reshape numpy row matrix into column matrix
<p>This is a very simple exercise where I need to change my row into column, but seems like it's not that simple in python</p> <pre><code>import numpy as np rd = np.zeros(3) normal = 0 for i in range(len(rd)): rd[i]= randrange(0,10) normal += rd[i] for i in range(len(rd)): rd[i] = round(rd[i]/normal,3) pr...
<p>Use <code>x = rd.reshape((-1,3))</code>. The -1 says &quot;make this whatever is leftover after the other axes are satisfied&quot;.</p>
python|arrays|numpy|matrix
1
361,853
68,650,792
How to check torch gpu compatibility without initializing CUDA?
<p>Older GPUs don't seem to support torch in spite of recent cuda versions.</p> <p>In my case the crash has the following error:</p> <pre><code>/home/maxs/dev/mdb/venv38/lib/python3.8/site-packages/torch/cuda/__init__.py:83: UserWarning: Found GPU%d %s which is of cuda capability %d.%d. PyTorch no longer suppo...
<p>Based on the code in <code>torch.cuda.__init__</code> that was actually throwing the error the following check seems to work:</p> <pre><code>import torch from torch.cuda import device_count, get_device_capability def is_cuda_compatible(): compatible_device_count = 0 if torch.version.cuda is not None: ...
python|tensorflow|pytorch|gpu
1
361,854
68,658,182
use pandas to join two dataframes
<p>i have two dataframes:</p> <pre><code>df1: index count1 A 1 B 1 C 1 df2: index count2 B 2 C 2 D 2 </code></pre> <p>And what i want is:</p> <pre><code>index count1 count2 diff A 1 0 1 B 1 2 -1 C 1 2 -1 D 0...
<p>We can <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>join</code></a> outer, then <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer"><code>fillna</code></a> with 0 (<code>downcast='infer'</co...
python|pandas
2
361,855
68,798,894
Why get I an empty sequence from flow_from_directory tensorflow?
<p>I try to load test images for my CNN. I get the path of my test images and if I print then the length of it I see that I got successfully the images. The problem is that if I want to get the images from <code>test_data_gen</code> I get an empty sequence. This is the <a href="https://i.stack.imgur.com/R5zfy.png" rel=...
<p>In your <code>test_data_gen</code> you need to set class_mode to <code>None</code> from <code>categorical</code> to return only the images, since test directory contains only images and not class wise folder structure. Below is the changed code.</p> <pre><code>test_image_generator = ImageDataGenerator(rescale=1./255...
python|tensorflow|keras
0
361,856
68,534,261
Concatenating a list of prefetch datasets in tensorflow
<p>I have a list of prefetch datasets which I would like to concatenate into a large dataset. Is there a way to do this?</p> <pre><code>[&lt;PrefetchDataset shapes: ((32, None), (32, 50)), types: (tf.float32, tf.int32)&gt;, &lt;PrefetchDataset shapes: ((32, None), (32, 50)), types: (tf.float32, tf.int32)&gt;, &lt;Pre...
<p>Yes, you can use <code>dataset1 = dataset1.concatenate(dataset2)</code>.</p>
python|tensorflow|keras
0
361,857
68,514,705
Minimum Euclidean Distance
<p>I have two dataframes (attached image). For each of the given row in Table-1 -</p> <p><strong>Part1</strong> - I need to find the row in Table-2 which gives the minimum Euclidian distance. Output-1 is the expected answer.</p> <p><strong>Part2</strong> - I need to find the row in Table-2 which gives the minimum Eucli...
<p>The code now gives the desired output, and there's a commented out print statement for extra output.</p> <p>It's also flexible to different list lengths.</p> <p>Credit also to: <a href="https://stackoverflow.com/questions/1401712/how-can-the-euclidean-distance-be-calculated-with-numpy">How can the Euclidean distance...
python|dataframe|numpy|euclidean-distance|scipy-spatial
0
361,858
68,447,773
condense multiple rows into 1 aggregated by other columns pandas
<p>How do I select a column that is grouped by other columns and put all the values of the column in 1 row (in a list). Input:</p> <pre><code>PropID Manager Manager_email date 1 A a@aol.com 2021-02-01 1 A a@aol.com 2021-02-02 1 A a@aol.com ...
<p>try this:</p> <pre><code>df.groupby(['PropID','Manager','Manager_email'])['date'].agg(list) </code></pre>
python|pandas
4
361,859
68,761,104
Has Sklearn something like a visualization toolkit?
<p>Im using a Sklearn for my machine learning and my question is how can i see my process of my taining? If i use Tensoflow i can see my loading process with Tensorboard. But does Sklearn have something like this?</p>
<p>As pointed out in the comments, you can use matplotlib. There are plenty of tutorials of how to create a plot updating in real-time during your training.</p> <p>However, personally I found these options pretty cumbersome. I instead chose to use the PyTorch interface to tensorboard. That works like a charm and you ca...
tensorflow|scikit-learn
1
361,860
68,674,394
PyTorch: vectorising looping addition of one value from a vector to a vector
<p>I want to create a matrix that contains every combination of the sums of all elements in two large vectors using Torch, ultimately using CUDA within Torch.</p> <p>The best way to describe it is with this (inefficient) code:</p> <pre><code>import numpy as np import torch x = torch.Tensor([1.1,2.2,3.3,4.4,5.5]) x_cen...
<p>Prompted by a comment above, and looking around, I see that a similar blog post exists: <a href="https://dongkwan-kim.github.io/blogs/all-possible-combinations-of-row-wise-addition-using-pytorch/" rel="nofollow noreferrer">every combination of addition of two vectors -- but not a matrix</a></p> <p>This can be modifi...
python|pytorch
0
361,861
68,788,588
Cannot seem to be drop null valued rows from dataframe
<p>I am trying the basic Titanic competition on Kaggle and am facing the issue of not being able to drop NaN valued rows. I wanted to check what was the rate of survival for everyone for whom age is listed in fractions (data mentions this case is for when age has been estimated)</p> <pre><code>estimated_age = train_dat...
<pre><code>estimated_age.dropna(axis = 1, how='any') </code></pre> <p>should be</p> <pre><code>estimated_age.dropna(axis = 0, inplace=True, how='any') </code></pre> <p>If you want to drop <strong>rows</strong> including NaN values.</p>
pandas|dataframe
2
361,862
68,599,379
solution to tensorflow import error after import module
<pre><code>pip install tensorflow #== import it import tensorflow as tf </code></pre> <p>ERROR:</p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\C1Manager\PycharmProjects\pythonProject\dani\comp-vision\ld dataset\try.py&quot;, line 1, in &lt;module&gt; import tensorflow File &quot;C:\Users...
<p>Looks like Tensorflow not installed properly, uninstall existing Tensorflow and install new one by following instructions,</p> <p><strong>Using PIP</strong></p> <pre><code>#Install tensorflow using pip virtual env $pip install virtualenv $virtualenv tf # tf is virtual env name $source tf/bin/activate tf $ pip ins...
python|tensorflow
0
361,863
68,551,011
how to change this json to dataframe?
<pre><code>json= {'name': 'system_information', 'url': 'https://gbfs.divvybikes.com/gbfs/en/system_information.json'} {'name': 'station_information', 'url': 'https://gbfs.divvybikes.com/gbfs/en/station_information.json'} {'name': 'station_status', 'url': 'https://gbfs.divvybikes.com/gbfs/en/station_status.json'} {'name...
<p>JSON is Java Script Object Notation which is not terribly similar to the way Pandas stores data. For that reason, if you want to manipulate JSON objects in python it often helps to 'flatten' them through the use of <code>pd.json_normalize</code>. If you have a single JSON object you can simply enclose it in curly br...
python|pandas|dataframe
0
361,864
68,493,526
An alert when trying to change a value in a column in pandas
<p>I have this dataset (the Titanic dataset):</p> <pre><code>import pandas as pd import numpy as np url = 'https://raw.githubusercontent.com/chrisalbon/simulated_datasets/master/titanic.csv' df = pd.read_csv(url) </code></pre> <p>And I want to change for the column 'Sex' all the values 'male' with 'NaN'. This is the co...
<p>The recommendation from <code>pandas</code> is to do the setting like below which gets rid of the warning.</p> <pre><code>df.loc[df['Sex'].isnull(),'Sex']='male' df.head() </code></pre>
python|pandas
2
361,865
68,651,742
Loop Python List : Conditional Value Change
<p>I have a python list :</p> <pre><code>my_list = [0,0,0.5,0,0,0,0.4,0,0.6] </code></pre> <p>I want to replace all the 0 by the next higher value than 0 in the list to obtain :</p> <pre><code>my_list = [0.5,0.5,0.5,0.4,0.4,0.4,0.4,0.6,0.6] </code></pre> <p>Thanks for your help !</p>
<pre><code>my_list = [0, 0, 0.5, 0, 0, 0, -8.2, 0.4, 0, 0.6] hook = 0 for i, v in enumerate(my_list): if v &gt; 0: for j in range(hook, i): if my_list[j] == 0: my_list[j] = v hook = i + 1 print(my_list) # [0.5, 0.5, 0.5, 0.4, 0.4, 0.4, -8.2, 0.4, 0.6, 0.6] </code></pre> ...
python|pandas|list|loops|conditional-statements
0
361,866
68,528,958
How can I split a DataFrame by column index without knowing the precise index?
<p>I have a database of stock prices with the DateTime index of the trading days from 31dec2001 till 31dec2021. I have to divide the database in 6-months periods, e.g from 01 Jan 2001 to 30 Jun 2001 and so on. My idea was to use the following:</p> <pre><code>period_1 = df.loc[&quot;20010101&quot;: &quot;20010530&quot;,...
<p><code>df.index.get_loc()</code> function returns integer location, slice or boolean mask for requested label. The function works with both sorted as well as unsorted Indexes. It provides various options if the passed value is not present in the Index.</p> <p>Try <code>df.index.get_loc(your_datetime, method='nearest'...
python|pandas
0
361,867
68,731,849
Fastest way to compress a tensor in Pytorch
<p>Say I have a Torch tensor of integers in a small range <code>0,...,R</code> (e.g., R=31).</p> <p>I want to store to disk in compressed form in a way that is close to the entropy of the vector.</p> <p>The compression techniques I know (e.g., Huffman and arithmetic coding) all seem to be serial in nature.</p> <ul> <li...
<p><code>torch.save</code> will store it with pickle protocol. If you want to save space, to quantize these vectors before saving should help.</p> <p>Also, you can try zlib module:</p> <p><a href="https://github.com/jonathantompson/torchzlib" rel="nofollow noreferrer">https://github.com/jonathantompson/torchzlib</a></p...
python|pytorch|compression
0
361,868
68,797,796
Converting Object to Time in python Pandas
<p>I have a dataset that containes a column with &quot;Time&quot; values, but it's showing as object, and I want to converte them to time so I can do a for loop to see if the time is between two times.</p> <pre><code>for i in df['Time']: if i &gt;= dt.time(21,0,0) and i &lt;= dt.time(7, 30,0) or i &gt;= dt.time(3,0...
<p>You can simplify:</p> <pre><code>(21:00) &amp; (07:30) the second are (03:00) &amp; (10:00) </code></pre> <p>to:</p> <pre><code>(21:00) &amp; (10:00) </code></pre> <p>so solution is use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.between.html" rel="nofollow noreferrer"><code>Se...
python|pandas|for-loop|jupyter
1
361,869
68,559,006
PyTorch: element-wise max over all data points with the same output bin index
<p>I am using PyTorch (1.8). Is there a clever way to take an element-wise max over all data points with the same output index?</p> <p>Let's say I have a data tensor of size (N, M), and an index tensor of size (N,) containing indices [0, K). Now I want to bin the data tensor into a tensor of size (K, M) according to th...
<p>PyTorch doesn't seem to have a native implementation for this yet, but there is a repository which does exactly this. <a href="https://github.com/rusty1s/pytorch_scatter" rel="nofollow noreferrer">PyTorch Scatter</a></p> <p>What I was describing seems to correspond with scatter_max.</p> <pre><code>from torch_scatter...
pytorch|histogram|bin
2
361,870
68,683,717
tensorflow_model server does not work in colab
<p>while running the tutorial <a href="http://cognitiveai.org/2020/09/08/using-tensorflow-ranking-bert-tfr-bert-an-end-to-end-example/" rel="nofollow noreferrer">here</a>, I run</p> <pre><code>tensorflow_model_server \ --rest_api_port=8501 \ --model_name=tfrbert \ --model_base_path=&quot;/content/drive/MyDrive/ap...
<p>I saw the link of tutorial you have provided. It has considered running the <code>tensorflow_model_server</code> as a bash shell script. However you can run it in Google Colab, but you may decorate this command with some tools to get behaviour like other python regular codes.</p> <p><code>tensorflow_model_server</co...
tensorflow|server|model
1
361,871
68,603,735
Python: Extracting information from one dataframe to another (with different lengths) based on condition
<p>I have two dataframes (df1 and df2) that differ in length (25696 and 28). Nonetheless, they have two columns that share the same information (date and day_period).</p> <p>Here's a preview of the data:</p> <pre><code>df1 &gt;&gt; id timestamp col1 col2 day_period date 0 A 2021-06-09 08:...
<p>You want to join, for example using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a>:</p> <pre><code>df1.merge(df2, left_on=['date', 'day_period'], right_on=['date', 'day_period']) </code></pre> <p>output:</p> <pre><code> id ...
python|pandas|dataframe|merge|concatenation
1
361,872
68,454,485
Transform data back to original dimensions with nan values
<p>I have a pandas dataframe with datetime index, and a range column and a data column.</p> <p>The shape of the df is (4000,3).</p> <p>I take the data column out as a np.array, transforms it to a 1000 by 4 matrix and then I drop the rows I have nan in. Then let’s say I got 22 rows of nans so I got (1000-22) rows left.<...
<p>This should do what you need it to with a fair amount of efficiency:</p> <pre><code>import numpy as np import pandas as pd import random c1=np.random.choice(range(1,20),1000) c2=np.random.choice(range(1,20),1000) c3=np.random.choice(range(1,20),1000) c4=np.random.choice(range(1,20),1000) df=pd.DataFrame({'col1':c1,'...
python|pandas|numpy
0
361,873
68,558,673
Why the replace method of pandas does not work with None as value?
<p>Let's say we have a DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;a&quot;: [1,&quot;NAN&quot;,3], &quot;b&quot;: [&quot;NAN&quot;,5,&quot;NAN&quot;], &quot;c&quot;: [&quot;NAN&quot;,8,9]}) a b c 0 1 NAN NAN 1 NAN 5 8 2 3 NAN 9 </code></pre> <p>When I try to pre...
<p>As was answered <a href="https://github.com/pandas-dev/pandas/issues/19998" rel="nofollow noreferrer">here</a>:</p> <p><code>df.replace(&quot;NAN&quot;, None)</code> is equivalent to <code>df.replace(&quot;NAN&quot;, None, method='pad')</code> if you look into the source code.</p> <p>Both <code>df.replace({&quot;NAN...
python|pandas
2
361,874
68,634,311
How to return an empty value or None on pandas dataframe?
<p>SAMPLE DATA: <a href="https://docs.google.com/spreadsheets/d/1s6MzBu5lFcc-uUZ9B6CI1YR7P1fDSm4cByFwKt3ckgc/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1s6MzBu5lFcc-uUZ9B6CI1YR7P1fDSm4cByFwKt3ckgc/edit?usp=sharing</a></p> <p>I have this function that uses textacy to extract the s...
<p>I did this to solve the problem. Had to append both instances at Try and Except.</p> <pre><code>def extract_direct(text): extracted = pd.DataFrame() for i in text: try: doc = nlp(i) a = ex.direct_quotations(doc) for item in a: mined = {'speaker': item.speaker, 'cue': item.cue,...
python|pandas|dataframe|textacy
0
361,875
68,680,184
create row, column, data pandas dataframe from sparse matrix
<p>How can I create a sparse matrix in the format of COO and have the pandas dataframe not unnest to a dense layout but keep the COO format for <code>row,column,data</code>?</p> <pre><code>import numpy as np import pandas as pd from scipy.sparse import csr_matrix from scipy.sparse import coo_matrix a = np.eye(7) a_csr...
<p>The values you want to put in the dataframe are available as</p> <pre><code>a_coo.row, a_coo.col, a_coo.data </code></pre>
python|pandas|numpy|scipy|sparse-matrix
2
361,876
68,670,898
Dataframe to lists in alphabetical order - Python
<p>I have a requirement to create lists from a dataframe. For eg: I have a dataframe &quot;df&quot; containing a column called &quot;names&quot; and it has 30 random names.</p> <p>I want to create separate lists in alphabetical order like names starting from a to d will go to list1, e to g will go to list2 and so on.</...
<p>This one does 4 names per list</p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;names&quot;: ['Jon', 'Bill', 'Maria', 'Jenny', 'Jack', 'sam', 'john']}) t = sorted(df['names'].values.tolist()) split = [] for i in range(0, int(len(t) // 4) + 1): split.append([]) for i in range(0, len(t)): print(i //...
python|pandas|list|dataframe
0
361,877
68,626,923
Numpy matrix creation timing oddity
<p>My application requires a starting matrix where each column is staggered-by-1 from the previous. It will contain millions of complex numbers representing a signal, but a small example is:</p> <pre><code>array([[ 0, 1, 2, 3], [ 1, 2, 3, 4], [ 2, 3, 4, 5], [ 3, 4, 5, 6], [ 4, ...
<p>user3483203's comment, above, provides answer to the issue. If I avoid the transpose by creating the matrix with:</p> <pre><code>X = np.array([x[i:i+Np] for i in range(N)], dtype=complex) </code></pre> <p>subsequent calcs() timing is as expected. Thank you, user3483203!</p>
python|numpy|matrix
3
361,878
68,556,134
Is there a function in pandas (python) for filtering data on two conditions?
<p><a href="https://i.stack.imgur.com/ZhR5U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZhR5U.png" alt="enter image description here" /></a></p> <p>I have an excel file that looks like somewhat like the above matrix.</p> <p>There are two three columns, namely: ID, Object and AE.</p> <p>I want to ...
<p>Your question should be clearer. Is this code below gives you the result you want?</p> <pre><code>df.loc[(df['Object'].str.extract('^(V\d+)').isin(['V2', 'V3']).any(axis=1)) &amp; (df['AE'] == 'Yes')] </code></pre>
python|excel|pandas
0
361,879
68,495,481
How to map function directly over list of lists?
<p>I have built a pixel classifier for images, and for each pixel in the image, I want to define to which pre-defined color cluster it belongs. It works, but at some 5 minutes per image, I think I am doing something unpythonic that can for sure be optimized.</p> <p>How can we map the function directly over the list of ...
<p>You can use the <strong>Numba's JIT</strong> to speed up the code by a large margin. The idea is to build <code>classified_pixels</code> on the fly by iterating over the colours for each pixel. The colours are stored in a Numpy array where the <strong>index</strong> is the colour key. The whole computation can run i...
python|list|performance|numpy|optimization
10
361,880
68,677,290
How to concat output to existing dataframe?
<p>I have a typical dataframe df</p> <p>I am trying to add sklearn's output to dataframe:</p> <p>code:</p> <pre><code>rc_g_oo = RandomForestClassifier() rc_g_oo.fit(X_oo, y_oo) pred_oo_p = rc_g_oo.predict_proba(df_test) print(&quot;Predicting probability of class&quot;) pred_oo_p = rc_g_oo.predict_proba(df_test) prob...
<p>Your probability is not a comma separated list. It looks like you're intentionally outputting each value and appending it without appending after a full iteration. You need to work around that before you add it into a dictionary.</p>
python|pandas|dataframe|concatenation
0
361,881
36,624,473
pandas timedelta resample weeks fails
<h1>Actual Question</h1> <p>As in this small example shown, I try to weekly resample a pandas dataframe:</p> <pre><code>import datetime import pandas as pd df = pd.DataFrame([{ 'A' : datetime.datetime.now() - datetime.datetime.now(), 'B' : 2 },{ 'A' : datetime.datetime.now() - datetime.datetime.now(), ...
<p>I believe the difference is that pandas uses numpy's datetime64 while the python datetime class is something different. When you call </p> <pre><code>df.index = pd.to_datetime(df.index.values) </code></pre> <p>you are casting from the datetime.datetime object which you created to the numpy.datetime64 object that r...
python|pandas|resampling
0
361,882
36,451,918
Pandas: Reshape wide dataframe to multi-indexed long
<p>I have a dataset of ratings of photographs, generated by many individual raters.<br> Each rater is given several images to rate, and for each image, a rater provides several different ratings, plus a description. </p> <p>So, for example, a rater might be asked to rate 3 different photos, and provide separate ratin...
<p>You can first find columns for each category by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow"><code>str.contains</code></a> and then use not well known <code>pd.lreshape</code>. Last aggregate columns by <a href="http://pandas.pydata.org/pandas-docs/st...
python|pandas
3
361,883
36,486,008
Reshape/resize(pivot?) N-dimensional numpy array column-wise
<p>I need to reshape/resize(pivot?) [sorry I am fairly new to numpy, working with it about 6 weeks] an numpy array based on column. The source numpy array is this: </p> <pre><code>[[[-0.98261404] [-0.98261404] [-0.95991508] ..., [-0.92496699] [-0.92731224] [-0.926328 ]] [[-0.91894622] [-0.91894622] ...
<p>I believe what you want is (considering I did understood it properly):</p> <pre><code>&gt;&gt;&gt; B = np.transpose(A, (0, 2, 1)) </code></pre> <p>being <code>A</code> your data and <code>B</code> the resulting array. That will transpose/pivot the last 2 axes. Alternatively, you can write</p> <pre><code>&gt;&gt;...
python|numpy
2
361,884
36,386,713
Numpy vectorization error
<p>I'm trying to vectorize the following equation. I have it working in non-vectorized form</p> <p><a href="https://i.stack.imgur.com/RfNjx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RfNjx.png" alt="Variances"></a></p> <pre><code>print(K) print(N) print(gamma.shape) print(means.shape) print(i...
<p>Use</p> <pre><code>self.variances = np.sum(gamma * (img[:, None] - self.means) ** 2, axis=0) / N_k </code></pre> <p>instead of </p> <pre><code>self.variances = np.sum(gamma * (img - self.means) ** 2) / N_k </code></pre> <hr> <pre><code>import numpy as np N, K = 10, 20 gamma = np.random.random((N, K)) means = n...
python|numpy|vectorization
3
361,885
36,246,454
Barchart horizontal using matplotlib
<p>I have file with data <a href="https://yadi.sk/i/rOYxzv26qQans" rel="nofollow">avito_trend.csv</a> and I want to print barchart of </p> <pre><code>import pandas as pd import itertools df = pd.read_csv("avito_trend.csv", parse_dates=[2]) def f(df): dfs = [] for x in [list(x) for x in itertools.combinations...
<p>As @user308827 has already said, I would also use seaborn for that, but i would do it bit differently:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import seaborn as sns pd.set_option('display.expand_frame_repr', False) cols = ['ID', 'address', 'used_at'] df = pd.read_csv(r'D:\data\gDrive\da...
python|csv|pandas|matplotlib
1
361,886
36,561,777
How to mix numpy slices to list of indices?
<p>I have a <code>numpy.array</code>, called <code>grid</code>, with shape:</p> <pre><code>grid.shape = [N, M_1, M_2, ..., M_N] </code></pre> <p>The values of N, M_1, M_2, ..., M_N are known only after initialization.</p> <p>For this example, let's say N=3 and M_1 = 20, M_2 = 17, M_3 = 9:</p> <pre><code>grid = np.a...
<p>I think you want something like this:</p> <pre><code>In [134]: x=np.arange(24).reshape(4,3,2) In [135]: x Out[135]: array([[[ 0, 1], [ 2, 3], [ 4, 5]], [[ 6, 7], [ 8, 9], [10, 11]], [[12, 13], [14, 15], [16, 17]], [[18, 19], [20,...
python|arrays|numpy|indexing|slice
3
361,887
36,368,797
How to get ordered list of labels after fitting sklearn
<pre><code>train_index, test_index = next(iter(ShuffleSplit(821, train_size=0.2, test_size=0.80, random_state=42))) print train_index, len(train_index) print test_index, len(test_index) features_train, features_test, labels_train, labels_test = cross_validation.train_test_split(features, labels, train_size=0.33, rando...
<h2>tl;dr</h2> <ol> <li><p>Because your decision tree classifier has to be <em>trained</em> before it can predict anything. It's not a magic algorithm. It has to be shown examples of what to do before it can work out what to do on other things.</p> <p><code>cross_validation.test_train_split()</code> facilitates this ...
python|pandas|machine-learning|scikit-learn
2
361,888
36,613,747
Taking the mean by one column and then by another in pandas
<p>I have the following dataset: </p> <pre><code> data = {'VALVE_SCORE': {0: 34.1,1: 41.0,2: 49.7,3: 53.8,4: 35.8,5: 49.2,6: 38.6,7: 51.2,8: 44.8,9: 51.5,10: 41.9,11: 46.0,12: 41.9,13: 51.4,14: 35.0,15: 49.7,16: 41.5,17: 51.5,18: 45.2,19: 53.4,20: 38.1,21: 50.2,22: 25.4,23: 30.0,24: 28.1,25: 49.9,26: 27.5,27: 37.2,...
<p>Here's a possible solution. Do let me know if there is a more efficient way of doing it. </p> <pre><code>df = pd.DataFrame(data) months = list(df['MONTH'].unique()) frames = [] for p in months: df_part = df[df['MONTH'] == p] df_part_avg = df_part.groupby("DAY", as_index=False).mean() df_part_avg = df_part_a...
python|pandas
0
361,889
36,443,521
Effective reading of own images in tensorflow
<p>I've skimmed over all tensorflow tutorials in which all data sets were loaded in RAM due to their small size. However, my own data (~30 Gb of images) can not be loaded in memory, therefore I'm looking for effective ways of reading images for further processing. Could anyone provide me examples of how can I do that?<...
<p>This is what you're looking for: <a href="https://stackoverflow.com/questions/34340489/tensorflow-read-images-with-labels">Tensorflow read images with labels</a></p> <p>The exact code snippet is like this:</p> <pre><code>def read_labeled_image_list(image_list_file): """Reads a .txt file containing pathes and l...
tensorflow|deep-learning
2
361,890
36,566,822
How to hide a table in dataframe while we need it to sort?
<p>I have 3 tables combined from 2 dataframes. There are CH1, CH11, and CH12.</p> <p>I'd like to sort all the tables based on CH1, but I don't want table CH1 appears.</p> <p>Please help finding the solution.</p> <p>Here's the code:</p> <pre><code>import pandas as pd csv1=pd.read_csv('auto$0$0.csv') csv2=pd.read_cs...
<p>IIUC you can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow"><code>drop</code></a> column <code>CH1</code>. For sorting by column is better use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><c...
python|csv|pandas|dataframe
0
361,891
4,959,171
Improving memory usage in an array-wide filter to avoid block-processing
<p>I am implementing some satellite image filters, starting with one known as the Enhanced Lee filter. The images are easily up to 5000x5000 pixels and more. My current implementation is running out of memory trying to compute the filters on those large arrays (note that the moving average and moving stddev filters can...
<p>There are several (memory usage) optimizations you can make here... A few tricks to keep in mind are:</p> <ol> <li>Most numpy functions take an <code>out</code> parameter than can be used to specify the output array instead of returning a copy. E.g. <code>np.sqrt(x, x)</code> will take the square root of an array i...
python|arrays|numpy|memory|scipy
5
361,892
53,001,124
Neural net inside for loop
<p>I have smth like this</p> <pre><code>for q in range(10): # generate some samples x = Input(batch_shape=(n_batch, xx.shape[1])) x = Dense(20)(x) x = LeakyReLU(alpha=0.001)(x) y = Dense(1)(x) y = LeakyReLU(alpha=0.001)(y) model = Model(inputs=x, outputs=y) model.compile(loss='mean_squared_err...
<p>When you make a layer with keras or tensorflow, tensorflow adds a node or more to its graph, every time you add an optimizer, a loss function or an activation function it does the same thing and adds a node for them.</p> <p>When you call <code>model.fit()</code> tensorflow executes its graph starting from its root....
python|tensorflow|keras
1
361,893
53,031,577
Classify New Objects in Images Live
<p>I have a webcam, a microphone and a python GUI. The user shows the camera an object and using voice command asks "what is this object?". The webcam takes a photo of the camera frame and pushes it to a flask endpoint. I have a VGG16 model hosted in the flask app which responds with a object class based on the image f...
<ol> <li><blockquote> <p>Is VGG16 (trained initially on 2 objects using transfer learning) the best model for this type of task? Currently, it is classifying unseen objects as one of the two classes.</p> </blockquote></li> </ol> <p>Firstly the reason for "it is classifying unseen objects as one of the two class...
python|amazon-web-services|azure|tensorflow|keras
0
361,894
53,105,294
Implementing a batch dependent loss in Keras
<p>I have an autoencoder set up in Keras. I want to be able to weight the features of the input vector according to a predetermined 'precision' vector. This continuous valued vector has the same length as the input, and each element lies in the range <code>[0, 1]</code>, corresponding to the confidence in the correspon...
<p>This autoencoder can be easily implemented using the <a href="https://keras.io/getting-started/functional-api-guide/" rel="nofollow noreferrer">Keras functional API</a>. This will allow to have an additional input placeholder <code>y_prec_input</code>, which will be fed with the "precision" vector. The full source c...
python|tensorflow|keras|loss-function
1
361,895
52,943,523
Trying to return a record from from a dataframe sing a reference dataframe
<p>I have a dataframe (<code>DeptTemplate</code>) the .head() of which looks like:</p> <pre><code> Name Status Status change date Product 0 Bob CURRENT NaN Pencils 1 Steve CURRENT NaN Pens 2 Heather NEW JOINER 02/08/2018 Paper 3 Liz...
<p>You are almost there, but you are trying to slice your original <code>DataFrame</code> using a a slice of a different <code>DataFrame</code> - that won't work because they are not the same thing.</p> <p>Step 1: Set boolean masks</p> <pre><code>not_current = df['STATUS'] != 'CURRENT' no_date_change = df['Status ch...
python|pandas
1
361,896
52,922,805
Why does plotting combined Pandas data in Seaborn give "TypeError: -0.8 is not a string"?
<p>I am working through some statistics examples using Scitkit-learn (0.20.0), and trying to plot some things as I go with Seaborn (0.9.0). I keep encountering errors when I try to plot data sets I've combined using Pandas' <code>concat()</code> function.</p> <p>Here is the most minimal example I could construct:</p> ...
<p>When you construct a numpy array with a string, all other values in the array will also be treated as objects.</p> <pre><code>X = numpy.array([[-1, -1, "A"]]) print (X) array([['-1', '-1', 'A']], dtype='&lt;U11') </code></pre> <hr> <pre><code>P = numpy.array([[-0.8, -1]]) array([[-0.8, -1. ]]) ## Rem...
python|pandas|seaborn
4
361,897
52,960,707
How to suppress small elements in a tensor
<p>I have an LSTM network that outputs a decision via <code>tf.tanh</code>. Then I use a <code>tf.sign</code> to get the binary action of either 1, -1 or 0. However, I do not want the model to make a non zero action when output of <code>tf.tanh</code> is small, so I want to implement a threshold <code>T</code> before <...
<p>Here is something that works for me. The code is pretty self-explanatory if you look at the variable names. Let me know if something is unclear.</p> <pre><code>import tensorflow as tf def suppress_range(x, a, b): """Sets all the elements in the range [a, b) to 0""" assert (a &lt; b), "a must be less than b...
python|tensorflow|lstm
1
361,898
53,012,298
Comparing two columns of pandas dataframe by np.char.find gives TypeError: string operation on non-string array
<p>I wish to compare two series of strings to find if one contains the other element-wise.</p> <p>I first tried with apply, but it is slow:</p> <pre><code>cols = ['s1','s2'] list_of_series = [pd.Series(['one','sdf'],index=cols), pd.Series(['two','x y two'],index=cols)] df = pd.DataFrame(list_of_series, columns=cols) ...
<p>Using <code>find</code> from <code>numpy.core</code> and add <code>astype</code> <code>str</code> </p> <pre><code>from numpy.core.defchararray import find find(df.s2.values.astype(str),df.s1.values.astype(str))!=-1 Out[430]: array([False, True]) </code></pre>
python|pandas|numpy
8
361,899
53,003,208
How to save a Tensorflow Checkpoint file from Google Colaboratory in when using TPU mode?
<p>When I use <code>saver = tf.train.Saver()</code> and <code>save_path = saver.save(session, "checkpointsFolder/checkpoint.ckpt")</code></p> <p>I get a <code>UnimplementedError (see above for traceback): File system scheme '[local]' not implemented</code> error</p> <p>Here is the full error</p> <pre><code>---------...
<p>Another way to do this is to rewrite the model using Keras and use tf.contrib.tpu.keras_to_tpu_model(..) with tf.contrib.tpu.TPUDistributionStrategy(...). Here is small code snippet for this: </p> <pre><code>def get_model(): return keras.Sequential([ keras.layers.Dense(10, input_shape=(4,), activation=tf.nn.r...
python|tensorflow|google-colaboratory|google-cloud-tpu
3