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
362,800
73,129,024
How to select a web form option based on a value from a column in a dataframe using Selenium
<p>Please I have a Selenium script that I use to autofill data into a web form. One of the fields called <strong>location</strong> is a selection field. I would like to match the value in a column to the index of the web form before selecting it. For example, I want to select index 9 on the webform based on a column va...
<p>The solution that worked is not different from what was done with the <strong>remarks_field</strong> variable.</p> <p>Here is how I formatted the <strong>location_field</strong> variable with the Select class.</p> <pre><code>location_field = Select(driver.find_element(By.XPATH, f&quot;//*[@id='WGItem09_voyage_log-{i...
python|pandas|dataframe|selenium|selenium-webdriver
0
362,801
72,944,455
Print Elements from Data Frame
<p>I have the following code:</p> <pre><code>import pandas as pd import numpy as np df = {'sport' : ['football', 'hockey', 'baseball', 'basketball', 'nan'], 'league': ['NFL', 'NHL', 'MLB', 'NBA', 'NaN'], 'number': [1,2,3,4,'']} df = pd.DataFrame(df) df def printlinesindf(datafrm): print('This is my favrotie sport...
<p>If you want to use apply you can do something like this:</p> <pre><code>def printlinesindf(row): print('This is my favrotie sport:', row[0], 'and this is my favorite league: ',row[1], 'and this is my ranking: ', row[2]) df.apply(lambda row: printlinesindf(row), axis=1) </code></pre> <p>However, this is not ...
python|arrays|pandas|dataframe
1
362,802
72,958,024
Flatten JSON in Dataframe Column
<p>I have data in a dataframe as seen below (BEFORE)</p> <p>I am trying to parse/flatten the JSON in the <strong>site_Activity</strong> column , but I am having no luck.</p> <p>I have tried some of the methods below as a proof I have tried to solve this on my own.</p> <p>I have provided a DESIRED AFTER section to highl...
<p>You can:</p> <ul> <li>use <code>.apply(json.loads)</code> to transform the json column into a list/dict column;</li> <li>use <code>df.explode</code> to transform the list o dicts into a Series of dicts;</li> <li>use <code>.apply(pd.Series)</code> to 'explode' de Series of dicts into a DataFrame;</li> <li>use <code>p...
python|json|pandas|dataframe
0
362,803
73,171,916
Merge Two Dataframes by Index without loosing data on empty rows
<p>say I want to merge two dataframes on a matching index using pandas, but one of the df's is missing some indexes, how could I do this without losing any data? E.g.</p> <pre><code> price 21-02-2022 2 22-02-2022 1 23-02-2022 3 sales 22-02-2022 2 </code></pre> <p>should output:</p> <...
<p>What you describe is called an <strong>outer join</strong>, which you can achieve as follows:</p> <pre><code>df1.join(df2, how='outer').fillna(0) </code></pre> <p>Notably, you must <code>fillna</code> as pandas, by default, will put in <code>NaN</code> values for non-matching rows.</p>
python|pandas|dataframe
1
362,804
72,984,990
Getting None of [] are in the [columns] error when using isin function
<p>I would like to get a subset of indices in a pandas data frame using a certain column. However, when I use list of values as my subset, I receive an error which seems like a very common error faced by other users. I've tried different solutions proposed in the previos posts, but none of them helped me.</p> <pre><cod...
<p>The grouping for when you check if df's C col is in your list is done improperly</p> <p>It should be of the format df[condition]</p> <pre class="lang-py prettyprint-override"><code>#change the last line print(df[df['C'].isin(my_subset)]) </code></pre> <p>output</p> <pre><code> A B C 2 3 3 3-3 3 4 5 4-5 <...
python|pandas|dataframe|numpy
0
362,805
73,027,927
Overwrite portion of dataframe
<p>I'm starting to lose my mind a bit. I have:</p> <pre><code>df = pd.DataFrame(bunch_of_stuff) df2 = df.loc[bunch_of_conditions].copy() def transform_df2(df2): df2['new_col'] = [rand()]*len(df2) df2['existing_column_1'] = [list of new values] return df2 df2 = transform_df2(df2) </code></pre> <p>I know w...
<p>You have the right method with <code>pd.concat</code>. However you can optimize a little bit by using a boolean mask to avoid to recompute the index difference:</p> <pre><code>m = bunch_of_conditions df2 = df[m].copy() df = pd.concat([df[~m], df2]).sort_index() </code></pre> <p>Why do you want to make a copy of your...
python|pandas
1
362,806
72,955,118
Recover the time shift from nympy.correlate result in Python
<p>This is not a duplicate question since <a href="https://stackoverflow.com/a/52367241/11748994">other answers</a> only explain how to plot the cross-correlation function and do not explain how you can get the time difference. Given a sin signal and shifted version, we should be able to get the time delay between them...
<p>@Sepide. It seems to me as if you are trying to maximise the correlation between the signal <code>y</code> and a shifted version of <code>y_shifted</code>. This might be accomplished using <code>np.correlate()</code> but it seems nontrivial indeed to recover the time shifts in the signals. In the solution below I ma...
python|numpy|cross-correlation
1
362,807
73,056,632
Looking for the lowest value in pandas row
<p>I try to look the highest and lowest column</p> <p>My Input</p> <pre><code> id Place A Place B Place C 1 67 87 76 </code></pre> <p>My Output</p> <pre><code> id Place A Place B Place C Highest Lowest 1 67 87 76 Place B Place A </code></pre> <pre...
<p>The error happens because you are reassigning the result of the <code>idxmax</code> to the same dataframe, so at the time you compute <code>idxmin</code> the dataframe contains an extra column <code>Highest</code> which is a string and cannot be compared to the other numbers. The solutions is just to assign to a dif...
python|pandas
2
362,808
73,035,687
Pandas: Give (string + numbered) name to unknown number of added columns
<p>I have this example CSV file:</p> <pre><code>Name,Dimensions,Color Chair,!12:88:33!!9:10:50!!40:23:11!,Red Table,!9:10:50!!40:23:11!,Brown Couch,!40:23:11!!12:88:33!,Blue </code></pre> <p>I read it into a dataframe, then split <code>Dimensions</code> by <code>!</code> and take the first value of each <code>!..:..:.....
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pop.html" rel="nofollow noreferrer"><code>DataFrame.pop</code></a> for use and drop column <code>Dimensions</code>, add <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.add_prefix.html" rel="nof...
python|pandas
1
362,809
72,981,035
sklearn random forest plot interpretation
<p>can you please help me to understand the plot below. what is Gini? what the meaning that the values of the Glucose are [66,72]? what the diffrent betweeen the colors (blue,white,pink)?</p> <p>data based on diabetes.csv (google it)</p> <pre class="lang-py prettyprint-override"><code> from matplotlib import pypl...
<p>From <a href="https://scikit-learn.org/stable/auto_examples/tree/plot_iris_dtc.html" rel="nofollow noreferrer">this example</a>:</p> <blockquote> <p>For each pair of features, the decision tree learns decision boundaries made of combinations of simple thresholding rules inferred from the training samples.</p> </bloc...
scikit-learn|random-forest|sklearn-pandas
1
362,810
73,033,021
Pytorch fine tuned CNN model giving always the same prediction in training and validation data
<p>I decided to move from TensorFlow to Pytorch and I am with some issues in understanding how it works. I tried to follow <a href="https://pytorch.org/tutorials/beginner/finetuning_torchvision_models_tutorial.html" rel="nofollow noreferrer">This Tutorial</a> which has a very simple example of Feature Extraction from I...
<p>Be careful, <code>img_to_test</code> is in the <code>HWC</code> format. You are reshaping the image when you should be transposing its axes from <code>HWC</code> to <code>CHW</code>. You may want to replace the following:</p> <pre><code>&gt;&gt;&gt; test_x = img_to_test.reshape(1, 3, 224, 224) </code></pre> <p>With ...
python|machine-learning|pytorch|conv-neural-network|imagenet
1
362,811
72,839,553
Need to insert rows for missing dates for individuals in pandas dataframe
<p>I have a data set containing donor information for several years, and I need to insert rows where a donor has skipped a year. There are several thousand records in the actual dataframe, but a sample looks like this</p> <pre><code>import pandas as pd df = pd.DataFrame([['A','2011',10], ['A','2012',10],['A','2013',10]...
<p>You can <code>.groupby()</code> using <code>donor_id</code> column and on each group apply custom function.</p> <p>In this function you'll merge actual group with new <code>pd.Series</code> made from <code>range(&lt;min year of this group&gt;, &lt;max year of this group&gt;+1)</code>.</p> <p>Afterwards, the missing ...
python|pandas|dataframe|pandas-groupby
2
362,812
72,876,298
Combine two Tensorflow Datasets with heterogeneous data
<p>I have data with different dtypes and I would like to build a windowed dataset. Previously, I asked <a href="https://stackoverflow.com/q/72821373/8973620">this question</a> where I dealt with homogeneous data. If I have a dataframe with different dtypes I need to use a dictionary and the accepted solution that uses ...
<p>You can do this with bit of a hack. It's gets a bit messy when you try to <code>zip()</code> data in different structures (e.g. a dict of arrays (<code>x</code>) and a plain array (<code>y</code>)). I'm not sure if it's possible (I got weird errors). So I'm collating both <code>x</code> and <code>y</code> to a singl...
python|tensorflow|deep-learning|tensorflow-datasets
1
362,813
72,953,255
Why doesn't my plot display date and time correctly?
<p>I am attempting to create a plot with Temperature on the Y axis, and date and time on the X Axis. My data appears to plot correctly, however the date and time does not. My date and time data is in column 0 of my csv, Labeled in the format m/d/Y H:M:S, example: 6/13/2022 2:36:00 PM. Instead of this expected format T...
<p>I have updated your code to what I hope is what you need. Some of the key changes are:</p> <ol> <li>The date format read from CSV needs to be converted to datetime using pd.to_datetime()</li> <li>The CrtlTC should be just a list of all column names, except Time</li> <li>Date formatter added, which you can use to con...
python|pandas|matplotlib|plot|time
0
362,814
73,071,719
Drop duplicated rows where all column are same except one in pandas
<p>I have seen similar questions but nothing answer mine. For example, I have a pandas data frame where the columns are 'A', 'B', 'C', 'D' and 'E'. First, I want to keep the rows if any of the 'A', 'B', 'C' and 'D' columns has different value. Also, if all the columns except 'E' is same, then I would like to keep the ...
<pre><code>df = pd.DataFrame(np.random.randint(1,3,size=(10, 5)), columns=list('ABCDE')) df Out[3]: A B C D E 0 2 2 1 2 2 1 1 2 1 2 2 2 2 1 2 1 2 3 1 2 1 1 1 4 1 2 1 2 2 5 1 2 2 1 1 6 2 2 2 2 2 7 1 1 1 2 2 8 2 1 1 2 2 9 1 1 1 2 1 # sort by column 'E', largest ...
python|pandas|dataframe|duplicates
0
362,815
73,004,011
How to add a number to the end of numpy array with left-shift
<p>I have an numpy array with (1,4) shape of zeros. I want to add numbers in the end of the array and the array element shift to the left. I expect the below results:</p> <pre><code>at the beginning: zeros=[0,0,0] first iteration (add 1): [0,0,1] second iteration (add 2): [0,1,2] third iteration (add 3): [1,2,3] forth...
<p>First of all, we define a function to shift each element to the left:</p> <pre><code>def shift_all_to_the_left(array): for index, element in enumerate(array): if index == len(array)-1: continue array[index] = array[index+1] return array </code></pre> <p>After that, we apply the fu...
python|arrays|numpy
0
362,816
73,140,801
how to get rid of strings in each list of each row in pandas
<p>Say I have a string column in pandas in which each row is made of a list of strings</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Class</th> <th style="text-align: center;">Student</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">One</td> <td sty...
<p>Check Below code. Seems like you are not defining what you need to split at, hence things are automatically getting split a char level.</p> <pre><code>import pandas as pd df = pd.DataFrame({'Class':['One','Two'],'Student':['[Adam, Kanye, Alice Stocks, Joseph Matthew]', '[Justin Bieber, Selena Gomez]'], ...
python|pandas|dataframe
1
362,817
72,923,612
Return only the differences from 2 dataframe tables
<p>I have 2 identically formatted Dataframes (DF1 and DF2). DF1 is a search from the last 30 days, and DF2 is today only. I want to compare the two and only produce a new data frame (DF3) with the Data from DF2 that isnt on DF1. Everything tried so far either merges or concats the tables and i'm left with a table of AL...
<p>You do not provide details of your data nor what to do with the duplicated values. But in principle comprehension could be used as below; this will replace duplicated values with NaN.</p> <pre><code>df3 =df2[df2 != df1] </code></pre>
python|pandas|dataframe
0
362,818
72,863,266
How do I limit the rate of a scraper?
<p>So I am trying to create a table by scraping hundreds of similar pages at a time and then saving them into the same Excel table, with something like this:</p> <pre><code>#let urls be a list of hundreds of different URLs def save_table(urls): &lt;define columns and parameters of the dataframe to be saved, df&gt; ...
<p>Python official documentation is the best place to go: <a href="https://docs.python.org/3/library/time.html#time.sleep" rel="nofollow noreferrer">https://docs.python.org/3/library/time.html#time.sleep</a></p> <p>Here an example using 5 seconds. But you can customize it according to what you need and the restrictions...
python|pandas|dataframe|pandas.excelwriter
1
362,819
72,973,946
What is the difference between model([states, actions]) and model.predict([states, actions])?
<p>I have seen code with <code>model([states, moves])</code> and with <code>model.predict([states, moves])</code>. I think both of them are Q-learning. But when I exchange <code>model([states, moves])</code> with <code>model.predict([states, moves])</code> it takes a mad amount of time. Both give values back.</p> <p>PS...
<p>Most of your question can be answered from this <a href="https://stackoverflow.com/questions/60837962/confusion-about-keras-model-call-vs-call-vs-predict-methods">StackOverflow question</a>. The answers there go over the minute differences between <code>model()</code> and <code>model.predict</code>.</p> <p>As regard...
tensorflow|keras
2
362,820
72,973,867
How to join two columns of a pandas dataframe containing null values?
<p>I have the dataframe pandas:</p> <pre><code> import numpy as np import pandas as pd df = pd.DataFrame({'ID': [1,2,3,4,5], 'column_1': [10.6, 10.4, np.NaN, np.NaN, np.NaN], 'column_2': [np.NaN, np.NaN, 30, 40, 50] }) pri...
<pre><code>import numpy as np import pandas as pd df = pd.DataFrame({ 'ID': [1,2,3,4,5], 'column_1': [10.6, 10.4, np.NaN, np.NaN, np.NaN], 'column_2': [np.NaN, np.NaN, 30, 40, 50] }) df['column_1'] = df['column_1'].astype(float) df['column_2'] = df['column_2'].astype(float) df['new_column'] = df['column_...
python|pandas|dataframe
0
362,821
72,867,650
AttributeError: 'Pandas' object has no attribute 'to_dict'
<p>I am trying to convert a tuple of a Pandas DataFrame into a dictionary because I need the dict to call an API later. I have an entire Dataframe, from which I iterate a for loop to get all data inside it. Here is the code</p> <pre><code>df = ....Dataframe definition and retriving for item in df.itertuple...
<pre><code>df.to_dict() </code></pre> <p>is a method that you call and by different arguments you can get:</p> <p>‘list’ : dict like {column -&gt; [values]}</p> <p>‘series’ : dict like {column -&gt; Series(values)}</p> <p>‘split’ : dict like {‘index’ -&gt; [index], ‘columns’ -&gt; [columns], ‘data’ -&gt; [values]}</p> ...
python|pandas
1
362,822
72,874,737
How to make a checkerboard in Pytorch?
<p>I see that a simple checkerboard pattern can be created <a href="https://stackoverflow.com/a/51715491/5349476">fairly concisely with numpy</a> Does anyone know if a checkerboard where each square may contain multiple values could be created? E.g.:</p> <pre><code>1 1 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 0 0 1 1 0 0 </code...
<p>Although there is no equivalent of <a href="https://numpy.org/doc/stable/reference/generated/numpy.indices.html" rel="nofollow noreferrer">np.indices</a> in PyTorch, you can still find a workaround using a combination of <a href="https://pytorch.org/docs/stable/generated/torch.arange.html" rel="nofollow noreferrer">...
pytorch
0
362,823
73,001,733
Append rows to a dask dataframe using apply function on another dask dataframe
<p>I want to run the following operation using dask.</p> <pre><code>df1 = pd.DataFrame() def foo(row): global df1 df1.append(row) def main(): global df1 df2.apply(foo , axis = 1) </code></pre> <p>When I run the following operation without Dask , it runs perfectly fine, but when I convert both of my da...
<p>The result of <code>.apply</code> method should be assigned to a new <code>dask</code> DataFrame:</p> <pre class="lang-py prettyprint-override"><code>df2 = df2.apply(foo , axis = 1, meta = df2) </code></pre> <p>However, it's likely that this is not efficient when working with data at scale. What is more efficient wi...
python|pandas|dataframe|dask|dask-distributed
0
362,824
72,915,550
How to speed up currency conversion while getting historical exchange rates
<p>I need some help thinking through this:</p> <p>I have a dataset with 61K records of services. Each service gets renewed on a specific date, each service also has a cost and that cost amount is billed in one of 10 different currencies.</p> <p>what I need to do on each service record is to convert each service cost to...
<p>So if I understand this correctly what this package does is provide a daily fixed rate between two currencies (so one direction is the inverse of the other direction).</p> <p>And what makes things so slow is very clearly the calls to the packages methods. For me around ~4 seconds per call.</p> <p>And you always are ...
python|pandas|dataframe|google-colaboratory
2
362,825
73,176,108
Standadise Numpy Array
<p>I am trying to standardize a numpy array. I seem to be doing something wrong as the value of some elements of the output array is incorrect. I'd appreciate any help. Please find the code below: PYTHON CODE:</p> <pre><code>from numpy import loadtxt import numpy as np import math class matrix(object): &quot;&quo...
<p>If what you want to do is just to scale the matrix you dont have to do it in a for loop. You can do like this because Numpy is vectorized by default.</p> <pre><code>a = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) scaled_a = (a - a.min(axis=1))/(a.max(axis=1) - a.min(axis=1)) </code></pre>
python|arrays|numpy
2
362,826
73,081,123
Create new columns by multiplying all columns by one specific column
<p>I have the following df:</p> <pre><code>pd.DataFrame({'Jugador': {0: 'F. Thauvin', 1: 'C. Rodríguez', 2: 'M. Meza', 3: 'F. Gorriarán', 4: 'V. Guzmán'}, '90s': {0: 22.0, 1: 28.0, 2: 40.0, 3: 39.0, 4: 35.0}, 'Duelos/90': {0: 26.02, 1: 15.31, 2: 24.72, 3: 18.59, 4: 19.82}, 'Acciones defensivas realizadas/90': {0: 4.25,...
<p>IIUC, you can use:</p> <pre><code>new_df = df.join(df.filter(like='/90').mul(90) .rename(columns=lambda x: x.replace('/90', '')) ) </code></pre>
python-3.x|pandas|dataframe
2
362,827
73,065,101
Reading .pyth filetype in PyTorch
<p>There is pretrained model in a repository that its file type is .pyth. I searched the web to find out about this file type and which language is able to read that but I could not find anything. Since I am working with PyTorch, is it possible to read such file in PyTorch? Moreover, normally how it is possible to rea...
<p>The file extension can literally be anything, it doesn't change the file contents. If you run <code>torch.load(&quot;file.pyth&quot;)</code> it will load a weight dictionary. You can find this in the code in the repo you included. They save the model using this code:</p> <pre><code>path_to_checkpoint = get_path_to_c...
python|deep-learning|pytorch|pre-trained-model
1
362,828
73,084,391
Converting year-month to next year-quarter
<p>I have below date expressed as yearmon '<code>202112'</code></p> <p>I want to convert this to yearqtr and report the next quarter. Therefore from above string I want to get <code>2022Q1</code></p> <p>I unsuccessfully tried below</p> <pre><code>import pandas as pd pd.PeriodIndex(pd.to_datetime('202112') ,freq='Q') </...
<pre><code>import pandas as pd df = pd.DataFrame({&quot;Date&quot;: ['202112']}) # dummy data df['next_quarter'] = pd.PeriodIndex(pd.to_datetime(df['Date'], format='%Y%m'), freq='Q') + 1 print(df) </code></pre> <p>Output:</p> <pre><code> Date next_quarter 0 202112 2022Q1 </code></pre> <p>Note that column Date m...
python-3.x|pandas|datetime
2
362,829
72,956,964
How Merge multi dataframes Pandas in Python
<pre><code>FinalDf = pd.merge(HRTrainingData,HRDataSet1,HRDataSet2,HRDataSet3, on='EmployeeNumber', how='outer') </code></pre> <p><strong>TypeError: merge() got multiple values for argument 'on'</strong></p> <p>I have only entered one 'on' argument, so I'm not sure what is going on here, but I am unable to merge these ...
<p>You can write like below:</p> <pre><code>pd.merge(df3, pd.merge(df1,df2, on='EmployeeNumber', how='outer'), on='EmployeeNumber',how='outer') </code></pre> <p>Or with <code>functools.reduce</code>:</p> <pre><code>import functools functools.reduce(lambda x,y : pd.merge(x,y, on=...
python|pandas|dataframe|merge
2
362,830
73,145,096
how to apply function to a list element within a list of lists?
<p>I have a list of lists. Here is an example of 2 of the lists inside a list:</p> <pre><code>global_tp_old = [[2, 1, 0.8333595991134644],[2, 1, 0.8530714511871338]] </code></pre> <p>I want to access a dataframe index where the index is specified in the first element of the above list in a list. At the moment I have tr...
<p>List comprehension might be useful to apply a function <code>fun</code> to the first element of each list in a list of lists (<code>LoL</code>).</p> <pre><code>LoL = [[61, 1, 0.8333595991134644],[44, 1, 0.8530714511871338]] newL = [fun(l_loc[0]) for l_loc in LoL] </code></pre> <p>No need to use a Pandas DataFrame....
python|pandas|list|numpy
2
362,831
72,934,719
Save lists as rows of a dataframe
<p>I am new to pandas. I hope this is not too easy :). I have tried to solve this problem without success.</p> <p>I am using beatifulsoup to scrape a website. My variable gets the result I am looking for.</p> <pre><code>var = [sd.get_text() for sd in x.select(&quot;li&quot;)] </code></pre> <p>The variable contains this...
<p>Convert your variable to a list of lists and pass it to a DataFrame constructor -</p> <pre class="lang-py prettyprint-override"><code>myvar = [[A, B, C, D, E, F, G, H], [I, J, K, L, M, M, N, O, P], [Q, R, S, T, U, V, W, X]] df = pd.DataFrame(myvar, columns=columns) </code></pre>
python|pandas|dataframe|beautifulsoup
2
362,832
72,937,781
Python: Colorize a row by clicking a button
<p>I'm trying to colorize a specific row in the output when I click on the &quot;Sortiert&quot; button&quot;. Is there any quick way to include this into my code? Another option would be that clicking the button deletes the entire row. I haven't found a solution for tkinter for now, maybe somebody has an idea or has ha...
<p>You can simply use a list to store those <code>Text</code> boxes in a row and pass this list to a function associated to the button of the corresponding row. Then you can go through the list inside the function to change the background color of those <code>Text</code> boxes:</p> <pre class="lang-py prettyprint-overr...
python|pandas|tkinter
0
362,833
73,106,139
Fastest way to repeatedly find indices of K largest values in an iteratively partially updated array
<p>In a complex-valued array <code>a</code> with <code>nsel = ~750000</code> elements, I repeatedly (<code>&gt;~10^6</code> iterations) update <code>nchange &lt; ~1000</code> elements. After each iteration, in the absolute-squared, real-valued array <code>b</code>, I need to find the indices of the <code>K</code> large...
<p>I tried to implement a <strong>Cython solution based on C++ containers</strong> (for 64-bit float values). The good news is that it is faster than a naive <code>np.argpartition</code>. The bad news is that it is quite complex and not much faster: <strong>3~4 times faster</strong>.</p> <p>One main issue is that Cytho...
python|arrays|numpy|performance|max
1
362,834
73,111,080
pandas to pivot or melt data
<p>I have a data frame looks like this:</p> <pre><code>{'year1_ID': [Id1, Id2], 'year1_Name':['Name1', 'Name2'], 'year1_Info': ['Info1','Info2'],'year1_AddInfo':['AddInfo1','AddInfo2'], 'year2_ID': [Id3, Id4], 'year2_Name':['Name3', 'Name4'], 'year2_Info': ['Info3','Info4'],'year2_AddInfo':['AddInfo3','AddInfo4'], 'ye...
<p>Here's an easy way:</p> <pre><code>df = pd.DataFrame(data) df.columns = df.columns.str.split('_', expand=True) df.stack(0).sort_index(level=1) </code></pre> <p>Output:</p> <pre><code> AddInfo ID Info Name 0 year1 AddInfo1 Id1 Info1 Name1 1 year1 AddInfo2 Id2 Info2 Name2 0 year2 AddInfo3 Id3 ...
python|pandas
1
362,835
10,766,009
flip order of ndarray in cython for opencv - OpenCV Error
<p>Apologies for the length of the post...</p> <p>I am using cython to wrap some cpp code for image processing. </p> <p>On return of my processed image which is in 32-bit ARGB mode - i.e. a 32-bit uint where <code>r = (buff[0] &gt;&gt; 16) &amp; 0xFF; g = (buff[0] &gt;&gt; 8) &amp; 0xFF; g = buff[0] &amp; 0xFF</code...
<p>It fails because of bug in OpenCV: <a href="http://code.opencv.org/issues/1393" rel="nofollow">http://code.opencv.org/issues/1393</a></p> <p>You should be able to workaround this issue by multiplying flipped matrix by 1:</p> <pre><code>original = original * 1 </code></pre>
python|opencv|numpy|cython
1
362,836
10,319,448
Large on disk array for numpy
<p>I have a sparse array that seems to be too large to handel effectively in memory (2000x2500000, float). I can form it into a sparse lil_array (scipy) but if I try output a column or row compressed sparse array (A.tocsc(), A.tocsr()) my machine runs out of memory (and there's also a serious mismatch between the data...
<p>I often use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.memmap.html" rel="nofollow">memory-mapped <code>numpy</code> arrays</a> to process multi-gigabyte numerical matrices. I find them to work really well for my purposes. Obviously, if the size of the data exceeds the amount of RAM, one has t...
python|arrays|numpy|sparse-matrix
2
362,837
3,522,946
Using Numpy arrays as lookup tables
<p>I have a 2D array of Numpy data read from a .csv file. Each row represents a data point with the final column containing a a 'key' which corresponds uniquely to 'key' in another Numpy array - the 'lookup table' as it were.</p> <p>What is the best (most Numpythonic) way to match up the lines in the first table with ...
<p>Some example data:</p> <pre><code>import numpy as np lookup = np.array([[ 1. , 3.14 , 4.14 ], [ 2. , 2.71818, 3.7 ], [ 3. , 42. , 43. ]]) a = np.array([[ 1, 11], [ 1, 12], [ 2, 21], [ 3, 31]]) <...
python|numpy
10
362,838
70,625,534
How to update rows in an "Excel-file Column" with the contents of a pandas data frame col
<p>EDIT_01: I just noticed my way does not work properly as it removes the &quot;Horse&quot; field from the saved excel file. EDIT_02: I have a work-round but I'm sure there must be a better way. Work-round by deleting the &quot;Odds&quot; column in df1 then merge df1 with df_odd then save df1. This still moves the ...
<p>Thanks for the input - it seems like my Work-round is the easiest solution (by deleting the &quot;Odds&quot; column in <code>df1</code> then merge <code>df1</code> with <code>df_odd</code> then save df1).</p> <p>So I will close this thread. Thanks again</p>
python|pandas
0
362,839
70,404,042
Slicing arrays inside pd dataframe cells
<p>I have a dataframe looking like this:</p> <pre><code> spectrum concentration 0 [-0.7966700525900023, 1.051812899165725, -3.22... 97.21 1 [4.2516158928053756, 4.311297642065483, 0.5998... 9.16 2 [2.6277027502790133, 7.421702513385412, -7.280... ...
<p>I would normally use <code>.map()</code> for this, e.g.,</p> <pre><code>df.spectrum.map(lambda x: x[70:920]) </code></pre>
python|arrays|pandas|dataframe|numpy-slicing
0
362,840
70,477,243
How to reduce repeated elements in a Pandas dataframe with Python
<p>I'm working with a dataframe that looks like this:</p> <pre><code>A B C D E F G H ctg.s1.000000F_arrow CDS gene 21215 22825 0 + . DAFEIOHN_00017 ctg.s1.000000F_arrow CDS gene 21215 22825 0 + . DAFEIOHN_00017 ctg.s1.000000F_arrow CDS...
<p>We can use a <code>groupby</code> and count the element like so :</p> <pre class="lang-py prettyprint-override"><code>df.groupby('H').count() </code></pre>
python|pandas|dataframe
1
362,841
70,580,391
How to invert volume of matrices in numpy?
<p>Please assume a vector of invertible matrices:</p> <pre><code>import numpy as np a = np.arange(120).reshape((2, 2, 5, 6)) </code></pre> <p>I want to invert the matrices over their defined axes:</p> <pre><code>b = np.linalg.inv(a, axis1=0, axis2=1) </code></pre> <p>but this does not seems supported.</p> <p>How to a...
<p><code>inv</code> docs specifies its array input as:</p> <pre><code>a : (..., M, M) array_like Matrix to be inverted. </code></pre> <p>You have a</p> <pre><code>a = np.arange(120).reshape((2, 2, 5, 6)) (M,M,...) </code></pre> <p>The dimensions are in the wrong order - change them!</p> <pre><code>In [44]: a = np.a...
python|numpy|linear-algebra
2
362,842
70,547,395
discord.py wait and analyze input using imported file
<p>I'm making a bot that takes in the user input (which is a stock symbol) and then provides information on that specific stock. Thing is, I'm not really sure how to use the <code>client.wait_input()</code> in my case. Here's my code for the bot:</p> <pre class="lang-py prettyprint-override"><code># bot.py import os im...
<p>The <code>companySymbol</code> variable already stores the user's input, so you can modify the <code>stocks_input()</code> function to take input.</p> <pre class="lang-py prettyprint-override"><code>def stocks_input(userinput): if userinput.isupper(): symbol = (df[df['Symbol'] == userinput]) retu...
python|pandas|discord.py
1
362,843
70,595,954
Converting a JSON Dictionary (currently a String) to a Pandas Dataframe
<p>I am using Python's request library to retrieve data from a web API. When viewing my data using <code>requests.text</code>, it returns a string of a large JSON object, e.g.,</p> <pre><code>'{&quot;Pennsylvania&quot;: {&quot;Sales&quot;: [{&quot;date&quot;:&quot;2021-12-01&quot;, &quot;id&quot;: &quot;Metric67&quot;,...
<p><code>r.text</code> returns json as text.</p> <p>You can use <code>r.json</code> to get json as dictionary from requests:</p> <pre class="lang-py prettyprint-override"><code>import requests r=requests.get(YOUR_URL) res=r.json() </code></pre>
json|python-3.x|pandas|python-requests|type-conversion
1
362,844
70,537,645
Handling duplicates in a Pandas dataframe
<p>I'm pulling cryptocurrency data from binance API and storing it in an database, its working, but how do I work around duplicates in the database? If I run the for loop a second time, it raises</p> <blockquote> <p>ValueError: Table &quot;'BTCUSDT' already exists.&quot;</p> </blockquote> <p>How do stop it from creatin...
<p>Have you tried the pandas &quot;drop_duplicates&quot; method?</p> <p><code>frame.drop_duplicates()</code> should take care of this.</p>
python|pandas
3
362,845
70,629,633
Count all values in a 2D matrix greater than a value for a 3D array
<p>Given a 3D <code>arr</code></p> <pre><code>np.random.seed(0) arr=np.random.rand(4,3,3) </code></pre> <p>The <code>arr</code> is a below</p> <pre><code>0.54881,0.71519,0.60276 0.54488,0.42365,0.64589 0.43759,0.89177,0.96366 0.38344,0.79173,0.52889 0.56804,0.92560,0.07104 0.08713,0.02022,0.83262 0.77816,0.87001,0.9...
<p>You can sum over multiple axes.</p> <pre class="lang-py prettyprint-override"><code>(arr &gt; 0.7).sum(axis=(1, 2)) array([3, 3, 5, 2]) </code></pre>
python|numpy
2
362,846
70,551,621
big data in pytorch, help for tuning steps
<p>I've previously splitted my bigdata:</p> <pre><code># X_train.shape : 4M samples x 2K features # X_test.shape : 2M samples x 2K features </code></pre> <p>I've prepared the dataloaders</p> <pre><code>target = torch.tensor(y_train.to_numpy()) features = torch.tensor(X_train.values) train = data_utils.TensorDataset(fea...
<ol> <li><p>To shorten the training process by simply stopping the training for loop after a certain number like so.</p> <pre><code>for local_batch, local_labels in train_loader: cont+=1 if cont== number_u_want_to_stop: break #Breaks out of the for Loop and continues with the rest. </code></pre> </li> <li>...
python|pytorch|bigdata|dataloader
2
362,847
70,423,602
Simplest solution to convert a 1D tensor to a 5x5 tensor
<p>What would be the simplest solution to a convert the tensor:</p> <pre class="lang-py prettyprint-override"><code>tensor = tf.constant([4.0]) </code></pre> <p>to a 5x5 tensor, where the main diagonal and the antidiagonal have the scalar 4.0, but the rest of the tensor has the value 0.0 as shown below:</p> <pre><code>...
<p>Here's one way you could do this:</p> <pre class="lang-py prettyprint-override"><code> def diag_antidiag(shape): &quot;&quot;&quot;Create an diag and anti-diagonal tensor of ones given `shape` Examples -------- &gt;&gt;&gt; diag_antidiag(5) (&lt;tf.Tensor: shape=(5, 5), dtype=int32, numpy= ...
python|tensorflow
2
362,848
70,519,263
Keras on Apple M1
<p>I am running following command on my Apple M1 system.</p> <p><strong>----------Code Start----------------------</strong></p> <pre><code>from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, BatchNormalization model = Sequential() model.add(Conv2D(32...
<p>You need to do some changes in both these lines below as you said it is category 2 <code>binary_class model</code> (0,1).</p> <pre><code>model.add(Dense(1, activation='sigmoid')) # 1 because you have cat and dog classes(0,1) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) </code>...
python|tensorflow|keras|apple-m1
0
362,849
70,623,472
converting dictionary to pandas dataframe in python
<p>I'm querying a API and pulling data that i need out of it. I then want to convert this to a pandas dataframe but not sure on best way to do it. I've got something that works but is very convoluted. The sample data below is a dictionary but this would really come from a API but it gets the point across.</p> <pre><...
<p>I may be missing something here but is just this what you're after?</p> <pre><code>df2 = pd.DataFrame([invoice_header]) </code></pre> <p>Looks the same as <code>df</code> to me</p>
pandas|dataframe|invoice
1
362,850
70,416,616
Rolling sum based on all previous dates NOT previous rows sorted by date
<p>Given the following dataframe:</p> <pre><code>+------------+--------+ | Date | Amount | +------------+--------+ | 01/05/2019 | 15 | | 27/05/2019 | 20 | | 27/05/2019 | 15 | | 25/06/2019 | 10 | | 29/06/2019 | 25 | | 01/07/2019 | 50 | +------------+--------+ </code></pre> <p>I need to get ...
<p>You can do</p> <pre><code>df['new'] = df.Date.map(df.groupby('Date').Amount.sum().rolling(&quot;28d&quot;, closed=&quot;left&quot;).sum()) df Date Amount new 0 2019-05-01 15 NaN 1 2019-05-27 20 15.0 2 2019-05-27 15 15.0 3 2019-06-15 10 35.0 4 2019-06-29 25 10.0 5 2019-07-01 ...
python|pandas
2
362,851
70,482,421
How to create the column words as row and give each word weight and file number in pandas
<p>I have a large amount of data in a file that I viewed in the Pandas library. The file has three important columns, a column containing words represented by numbers, a column containing the file numbers in which each word appeared, and a column containing a weight for each word. There are repeated words that have app...
<p>Not sure if this is what you're looking for. Let me know: Example dataframe:</p> <pre><code>df = pd.DataFrame([[1, 'word_a', 100], [1, 'word_b', 200], [1, 'word_c', 300], [2, 'word_d', 400], [2, 'word_e', 500], [3, 'word_f...
python|pandas|dataframe|numpy|matrix
1
362,852
70,539,091
Python Reformat Dataframe
<p>I am trying to iterate through the dataframe and if the row's value <code>Age</code> column is empty, it will move the value in <code>Name</code> column to the <code>Location</code> column of the previous row. Is there a quick way to do this?</p> <p><strong>As-Is</strong></p> <p><a href="https://i.stack.imgur.com/CS...
<p>You can use <code>numpy</code>:</p> <pre><code>arr = df.to_numpy() arr[::2, -1] = arr[1::2,0] df = pd.DataFrame(arr[::2], columns=df.columns) </code></pre> <p>Output:</p> <pre><code> Name Age Location 0 Amber 21 North 1 Max 23 South 2 Jackson 38 East </code></pre>
python|pandas|tabula
1
362,853
70,723,817
How to unmelt a completely melted table
<p>I have this dataframe <code>df</code> which I have melted and then using pd.pivot_table I am able to get the table structure back at least looking at the rows it seems so - but the indexes become <code>MultiIndex</code> type - is there a way to change to back to <code>RangeIndex</code> as it was in the original <cod...
<p>As @mozway said your code does not work, some steps must be missing</p> <p>But to go from d to df you can use <code>unstack</code>. You need a unique index for this to work hence this is where <code>'count'</code> column comes in</p> <pre><code>(d.assign(count = np.arange(len(d))%6) .set_index(['count','Column']...
python|pandas|dataframe|pivot-table
0
362,854
70,535,245
Is there a way to wrap every single entry of an numpy.ndarray into a separate array?
<p>I'm facing some problems getting an array into the right shape to use it as an input into a convolutional neural net:</p> <p>My array has the shape <code>(100,64,64)</code>, but I'd need it to be <code>(100,64,64,1)</code>. I realize it looks a bit odd, but I basically want to pack every single entry into a separate...
<p>You can pass an <a href="https://docs.python.org/3/library/constants.html?highlight=ellipsis#Ellipsis" rel="nofollow noreferrer">Ellipsis</a> plus <code>None</code> to the arrays indexer:</p> <pre><code>&gt;&gt;&gt; a array([[0, 1, 0], [1, 1, 1], [0, 0, 1]]) &gt;&gt;&gt; a[..., None] array([[[0], ...
python|arrays|numpy|multidimensional-array
2
362,855
70,386,188
cannot parse datetime in pandas dataframe
<p>Column Name: dateAdded</p> <p>format: 2017-03-03T16:56:05Z</p> <p>I am trying this code</p> <pre><code>df = pd.read_csv ('amazon.csv') df['dateAdded'] = pd.to_datetime(df['dateAdded'], format= '%Y-%d-%mT%H:%M:%S%Z') </code></pre> <p>Error:</p> <blockquote> <p><strong>time data '2017-03-03T16:56:05Z' does not ma...
<p><code>Z</code>, or <code>Military Time</code> is not supported in <code>Datetime</code>. The solution is to either remove the <code>Z</code> or replace it with <code>+00:00</code>. Your code becomes:</p> <pre><code>df['dateAdded'] = pd.to_datetime(df['dateAdded'].rsplit('Z', 1)[0], format= '%Y-%d-%mT%H:%M:%S') ...
python|pandas|dataframe
0
362,856
70,581,385
How do I reindex a MultiIndex with additional Rows for only one Index Level?
<p>I have the following dataframe:</p> <pre><code> volume month source brand 2020-01-01 SA BA 5 2020-02-01 SA BA 10 2020-02-01 SA BB 5 2020-01-01 SB BC 5 2020-02-01 SB BC 10 </code></pre> <p>I want ...
<p>I've often found MultiIndexes to be more trouble than they're worth, so here is a 'straight' or at least more traditional/relational alternative to your index_fill_missing function.</p> <p><strong>Note</strong>: requires Pandas &gt;= 1.2 for the .merge(.., how='cross')</p> <p>Starting from the dataframe in your rece...
python|pandas|dataframe|multi-index
1
362,857
70,487,940
Finding Lowest Common Multiple using numpy (for more than two inputs)
<p>So I would like to find the lowest common multiple of 4 or more numbers in python. Now I understand that in numpy, you can just use np.lcm but the function is only restricted to two inputs.</p> <pre><code>import numpy as np result = np.lcm(12, 8) # calculating the lcm of 12 and 8 print(result) 24 </code></pre> <p>T...
<p>You'd use <code>np.lcm.reduce()</code>, and pass it an array of numbers:</p> <pre><code>&gt;&gt;&gt; np.lcm.reduce([1, 2, 3, 4]) 12 </code></pre>
python|numpy|lcm
2
362,858
70,491,794
Dynamically store the API data
<p>I have to extract data from API's and return the report with the required info. For eg:</p> <pre><code>request_data = {'url1 : https://abcd.com','url2 : https://dfgh.com','url3 : https://hjkl.com',column : (name,Ecode,salary,status)} x1 = '{ &quot;name&quot;:&quot;John&quot;, &quot;age&quot;:30, &quot;city&quot;:&...
<p>You could start by creating an empty dataframe called cumulative_df in which you could collect the responses of the different API calls.</p> <p>Then, loop through the list of URLs; within the loop, for each URL:</p> <ol> <li>Make the API call (e.g., by using the requests library).</li> <li>Convert the JSON response ...
python|json|pandas|api
2
362,859
70,446,378
Column stored as List; how can I split as COLUMNS in pandas python?
<p>assume &quot;Tags&quot; column as stores as below; How can I split into multiple columns or set into one list?</p> <p>desired as &quot; To be combined as List and filter-out duplication</p> <pre><code>&quot;Tags&quot; ['Saudi', 'law', 'Saudi Arabia', 'rules'] ['Hindi', 'Tamil', 'imposition', 'cbse', 'neet', 'Tamil N...
<p>If need list without duplicates use set comprehension with <code>set</code> if performance is important:</p> <pre><code>L = list(set(y for x in df['Tags'] for y in x)) </code></pre> <p>If possible there are <code>list</code>s saved like strings use:</p> <pre><code>import ast L = list(set(y for x in df['Tags'].dropn...
python|python-3.x|pandas|dataframe
0
362,860
70,498,338
Extract all values from div but individually
<pre><code>import requests from bs4 import BeautifulSoup, element Stock_Symbol=input(&quot;Enter the symbol of the stock\n&quot;) Stock_URL=&quot;https://ticker.finology.in/company/&quot;+Stock_Symbol response=requests.get(Stock_URL) soup=BeautifulSoup(response.text, 'html.parser') Current_Price = soup.find(&quot;div...
<p><strong>Note:</strong> <em>Question and expected output is not that clear, so answer is just pointing in a direction.</em></p> <p>There are several ways to select the values / elements more specific - One option could be to select it by the name of the metric with selector <code>:-soup-contains()</code></p> <pre><co...
python|pandas|web-scraping|beautifulsoup|python-requests
0
362,861
70,627,421
How to retain node ordering when converting graph from networkx to pytorch geometric?
<p><strong>Question</strong>: How to retain the node ordering/labels when converting a graph from <code>networkx</code> to pytorch geometric?</p> <p><strong>Code</strong>: (to be run in Google Colab)</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import networkx as nx import torc...
<p>It seems this issue was resolved in the comments (the solution proposed by @Sparky05 is to use <code>copy=True</code>, which is the default for <code>nx.relabel_nodes</code>), but below is the explanation for why the node order is changed.</p> <p>When <code>copy=False</code> is passed, <code>nx.relabel_nodes</code> ...
python|python-3.x|pytorch|networkx|pytorch-geometric
3
362,862
70,721,182
How to install additional dependencies in Tensorman
<p>I am on popos 20.04 LTS and I want to use <a href="https://support.system76.com/articles/tensorman/" rel="nofollow noreferrer">Tensorman</a> for tenserflow/python. I'm new into docker and I want to install additional dependencies for example using default Image I can run jupyter notebook using these commands -</p> <...
<p>There are two ways to install dependencies.</p> <ol> <li>Create a custom image, install dependencies and save it.</li> <li>Use the <code>--root</code> tag to gain root access to the container, install dependencies and use them.</li> </ol> <h1>Build your own custom image</h1> <p>If you are working on a project and wa...
python|docker|tensorflow|machine-learning|deep-learning
0
362,863
70,497,103
Need to split a column but only removing the character
<p>Good morning. Below the first 20 rows of my df and my code.</p> <p>When I try to split by the '&lt;' to remove the strong tag from the link, <code>split</code> only removes the character, <code>split('&lt;')[0]</code> returns a KeyError.</p> <p>Any ideas how to get this to work?</p> <p>First desired link:</p> <p><a ...
<p>Filter you datframe to get the rows with the <code>&lt;strong&gt;</code> tags. Then just us BeautifulSoup to parse the html. Use it in lambda function:</p> <pre><code>from bs4 import BeautifulSoup import pandas as pd df = pd.DataFrame( [ ['&lt;a class=&quot;back&quot; href=&quot;http://africa.espn.com/college-s...
python|pandas
2
362,864
70,544,786
how to write this romove_stopwords faster python?
<p>I have a function <code>remove_stopwords</code> like this. How do I make it run faster?</p> <pre><code>temp.reverse() def drop_stopwords(text): for x in temp: elif len(x.split()) &gt; 1: text_list = text.split() for y in range(len(text_list)-len(x.split())): ...
<p>Your function does a lot of the same thing over and over, particularly repeated <code>split</code> and <code>join</code> of the same <code>text</code>. Doing a single <code>split</code>, operating on the list, and then doing a single <code>join</code> at the end might be faster, and would definitely lead to simpler...
python|pandas|stop-words
1
362,865
70,659,219
Randomly picking a positions of a given value in the matrix and switching it to another given value
<p>I have a given matrix</p> <p><code>M= np.array([[7, 7, 7, 7, 7, 7, 7],[7, 1, 1, 8, 1, 1, 7],[7, 1, 1, 1, 1, 1, 7],[7, 7, 7, 7, 7, 7, 7]]) </code></p> <p>I'm trying to randomly pick <code>k</code> values that are equal to <code>1</code> in the matrix and transform them to <code>5</code>.</p> <p>So, let's say that <co...
<p>The recommended <a href="https://numpy.org/doc/stable/reference/random/generated/numpy.random.Generator.choice.html" rel="nofollow noreferrer">random generator api</a> does support what you are looking for.</p> <pre><code>import numpy as np M = np.array([[7, 7, 7, 7, 7, 7, 7],[7, 1, 1, 8, 1, 1, 7],[7, 1, 1, 1, 1, 1...
python|numpy
2
362,866
70,557,342
Counting the filtered values in Pandas Python
<pre><code>col1 col2 col3 0 14 37 10 29 49 20 30 40 </code></pre> <p>I want to know the number of filtered values only on single column.Such as how many numbers are greater than 45 in column 3. I tried</p> <pre><code>a = df[&quot;col3&quot;] &lt;= 45 a.sum() </code></pre> <p>But the out was 0. ...
<p>A simple way to do it would be:</p> <pre><code>len(df[df['col3'] &lt;= 45]) </code></pre>
python|pandas
0
362,867
70,608,948
Efficient element-wise matching of two arrays in python
<p>I am working on a matching problem. I have two arrays <code>A</code> and <code>B</code> of the same size (assume 1000x1000). For each element <code>a_ij</code> in <code>A</code> (<code>i</code> and <code>j</code> are the row and column indices, respectively), I need to find the closest element <code>b_i?</code> in t...
<p><strong>The algorithm is clearly inefficient</strong> (all methods): checking all items of <code>rowB</code> to find the one that is the closest is expensive and results in <em>several billions of floating-point operations</em>. Not to mention Numpy creates an expensive unnecessary <em>temporary array</em> for each ...
python|arrays|numpy|performance|mapping
1
362,868
70,637,745
pandas dataframe with string index containing row 'nan' gets converted to NaN when saved to and read from hd5
<p>I have a simple dataframe with a string index:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame(dict(x=['a','nan', 'NA', 'na', 'NaN'], y=[1,2,3,4,5])).set_index('x') &gt;&gt;&gt; df y x a 1 nan 2 NA 3 na 4 NaN 5 </code></pre> <p>It properly sets the index as strings.</p> <pre><...
<p>I think that's an issue with read_hdf module.I could be wrong.</p> <p>but one work around is to not set x as index when you save it as hd5 but after you read it back from hdf,set the index to x:</p> <pre><code>import pandas as pd df = pd.DataFrame(dict(x=['a', 'nan', 'NA', 'na', 'NaN'], y=[1,...
python|pandas|dataframe|indexing|hdf
1
362,869
70,545,677
Custom Loss Function Error: ValueError: No gradients provided for any variable
<p>I am using a binary crossentropy model with non binary Y values &amp; a sigmoid activation layer.</p> <p>I have created my first custom loss function but when I execute it I get the error &quot;ValueError: No gradients provided for any variable: [....]&quot;</p> <p>This is my loss function. It is used for cryptocurr...
<p>I found the correct differentiable code for the loss function i wanted to use.</p> <pre><code>def loss(y_true, y_pred): y_true_onehot = tf.where( tf.greater(y_true, 0.0), 1.0, 0.0 ) loss_values = keras.losses.BinaryCrossentropy()(y_true_onehot, y_pred) mask = tf.where( ...
python|tensorflow|keras|deep-learning
0
362,870
70,527,591
I am getting this error while installing torch package
<p>C:\Users\Utkarsh&gt;pip install torch ERROR: Could not find a version that satisfies the requirement torch (from versions: none) ERROR: No matching distribution found for torch</p> <p>I am getting the above error! I have installed python v3.10</p> <p>I have also tried to install torch from whl file but there also I ...
<p>ypu need to install <code>pytorch</code></p> <pre><code>pip install pytorch </code></pre> <p><a href="https://pytorch.org/" rel="nofollow noreferrer">https://pytorch.org/</a></p>
python|pip|pytorch|torch
0
362,871
70,713,523
Pandas Dataframe - running through two columns 'Father' and 'Son' to rebuild end-to-end links step by step
<p>I have a long dataframe I need to transform to get a wide one. The long one is :</p> <pre><code>df = pd.DataFrame({ 'key' : ['E', 'E', 'E', 'E', 'J', 'J', 'J', 'J'], 'father' : ['A', 'D', 'C', 'B', 'F', 'H', 'G', 'I'], 'son' : ['B', 'E', 'D', 'C', 'G', 'I', 'H', 'J'] }) df </code></pre> <p>First thing to...
<p>Assign the new key with <code>cumcount</code> then we can do <code>pivot</code></p> <pre><code>out = df.assign(c = df.groupby('key').cumcount().add(1).astype(str)).pivot('key','c').sort_index(level=1,axis=1) out.columns = out.columns.map('_'.join) out Out[34]: father_1 son_1 father_2 son_2 father_3 son_3 father...
pandas|dataframe|pandas-groupby
1
362,872
70,463,683
How to get the top 5 percentile values in pandas series for each class?
<p>I was solving a <a href="https://platform.stratascratch.com/coding/10303-top-percentile-fraud?python=" rel="nofollow noreferrer">practice question</a> where I wanted to get the top 5 percentile of frauds for each state. I was able to solve it in SQL but the pandas gives a different answer for me than SQL.</p> <p>Ful...
<p>Thanks to Emma, I got the partial solution. I could not get the ranks like 1,2,3,...,100 but the resultant table is at least same from the output of SQL. I am still learning how to use the pandas.</p> <p>Logic:</p> <ul> <li>To get the top 5 percentile, we can use quantile values &gt;= 0.95 as shown below:</li> </ul>...
python|sql|pandas|postgresql
0
362,873
70,606,320
multiprocessing.pool cannot be accelerated in tf.data
<p>I want to use <code>multiprocessing.pool</code> in <code>tf.data</code> to speed up my augmentation function. But the result is slower than normal for loop.</p> <p>multiprocessing.pool cost about: 72s</p> <p>normal for loop cost about: 57s</p> <p>My environment: <code>python3.6</code>, <code>tensorflow-gpu2.4.0</cod...
<p>TensorFlow Dataset API is already equipped with built in multiprocessing. Just use <code>num_parallel_calls</code> parameter in <code>map</code> and <code>prefetch</code> feature without any pythonic multiprocessing tools. Besides, pass only TensorFlow style functions to <code>map</code> that can be converted to gr...
python|tensorflow|multiprocessing|tensorflow-datasets
0
362,874
70,525,434
How to select, map and count data from JSON API with Python?
<p>I am new to Python and am struggling to find the right method for the following:</p> <p>I have 2 API responses, one is a list of devices, the other one is a list of organizations. Each device is linked to an organization with an Organization ID.</p> <pre><code>organizations = [ { '...
<p>This code will achieve you goal:</p> <pre><code>organizations = [ { 'name': 'Aperture Science Inc.', 'description': 'Just a corporation!', 'id': 1 }, { 'name': 'Software Development Inc', 'description': &quot;Making the world's next best app!&quot;, 'id': 2 ...
python|pandas|dataframe
1
362,875
70,426,574
calculate percent change in pandas dataframe, subject to conditions
<p>I have a dataframe that looks like:</p> <pre><code>df = pd.DataFrame({'name': ['Portrait of Dr. Gachet', 'Salvator Mundi','Interchange'], 'sold_price': [1000.0, 5000.0, 2500.0, 6000.0, 8000.0, 16000.0, 20000.0, 9000.0, 40000.0], 'serialized_trx': [1, 1, 1, 2, 2, 2, 3, 3, 3]} </code></pre> <p>The data shows the <em>s...
<p>Try this:</p> <pre><code>df['pct_change'] = df.groupby('name')['sold_price'].pct_change().mul(100).fillna(0).round(2) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df name sold_price serialized_trx pct_change 0 Portrait of Dr. Gachet 1000.0 1 0.00 1 ...
python|pandas|dataframe|vectorization
0
362,876
42,905,276
How to remove space lines between my numpy list's file?
<p><a href="https://stackoverflow.com/questions/42901619/how-to-create-a-file-list-of-my-files-included-in-the-same-folder/42901967?noredirect=1#comment72906712_42901967">How to create a file list of my files included in the same folder?</a> I have posted in this question that I need to put all mye file names from the ...
<p>Take a look at <a href="https://docs.python.org/2/library/os.html#os.linesep" rel="nofollow noreferrer">os.linesep()</a> method that you're calling...</p> <p>As stated in the docs:</p> <blockquote> <p>Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single ...
python|numpy
1
362,877
42,750,287
how to group by and count in pandas
<p>I have following dataframe in pandas.</p> <pre><code> ID Names Class ABC [James,Jack,Bob] A DES [Michel,Sara] B ERT [Jack,Mike] A </code></pre> <p>I want to count names in each class</p> <p>Desired output</p> <pre><code> Class ...
<p>I think you can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow noreferrer"><code>numpy.repeat</code></a> for repeat values by legths by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.len.html" rel="nofollow noreferrer"><code>str.le...
pandas
1
362,878
42,933,884
python pandas datetime index resample
<p>I have a dataframe edf, where I transform DATESENT into my datetimeindex and then I want to pivot it by week.</p> <pre><code>edf = pd.read_csv('C:\Users\j~\raw.csv', parse_dates=[6]) edf2 = edf[['DATESENT','Sales','Traffic]].copy() edf2['DATESENT']=pd.to_datetime(edf2['DATESENT'],format='%m/%d/%Y') edf2 = edf2.set_...
<pre><code>df = pd.DataFrame({'Date':pd.date_range(start='2014-01-01', end='2014-01-31', step=1),'sales':np.random.randint(31),'traffic':np.random.randint(31)}) df = df.set_index('Date') #Change the week start day to Monday. df.resample('W-MON').agg(['sum']) </code></pre> <p>or</p> <pre><code>#Change the week start ...
python|pandas|datetime
1
362,879
42,862,390
Box plot of one column grouped by another in pandas/matplotlib
<p>Let's say I have a data frame like this:</p> <pre><code>species,weight lion,130 lion,190 giraffe,803 lion,150 giraffe,1200 hippo,1300 giraffe,1000 hippo,1800 giraffe,1100 lion,160 </code></pre> <p>There are different numbers of animals per species (less, sorry - fewer - hippos, for example). I would like to make a...
<pre><code>import matplotlib.pyplot as plt import numpy as np # fake up some data spread = np.random.rand(50) * 100 center = np.ones(25) * 50 flier_high = np.random.rand(10) * 100 + 100 flier_low = np.random.rand(10) * -100 data = np.concatenate((spread, center, flier_high, flier_low), 0) # basic plot plt.boxplot(dat...
python|pandas|matplotlib|boxplot
-1
362,880
42,671,334
Applying function to column in grouped pandas dataframe and returning output as a new column
<p>I have some weather dataset consisting of multiple columns:</p> <p><em>StationID, altitude, datetime, longitude, latitude, rainfall</em></p> <p>I have multiple stations, which are identified by their respective IDs. The rainfall column has accumulated rainfall amounts. For example, for station X in 10 days, I coul...
<p>I think you need:</p> <pre><code>print (df.groupby('station')['rainfall'].apply(intensity)) </code></pre> <p>But better is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.diff.html" rel="nofollow noreferrer"><code>diff</code></a> with replace <code>NaN</code> to ...
python|pandas
1
362,881
42,838,855
Python stacked to unstacked format
<p>or also known as long to wide format.</p> <p>I have the following:</p> <pre><code>ID1 ID2 POS1 POS2 TYPE TYPEVAL --- --- ---- ---- ---- ------- A 001 1 5 COLOR RED A 001 1 5 WEIGHT 50KG A 001 1 5 HEIGHT 160CM A 002 ...
<p>You can set the index with all but the <code>'TYPEVAL'</code> column then <code>unstack</code></p> <pre><code>df.set_index( df.columns.difference(['TYPEVAL']).tolist() ).TYPEVAL.unstack('TYPE').reset_index().rename_axis(None, axis=1) </code></pre> <p><a href="https://i.stack.imgur.com/9ntXU.png" rel="nofollow ...
python|database|pandas
3
362,882
42,596,805
I can't find seq2seq module in tensoflow repository
<p>I am reading tensorflow tutorial on seq2seq models. It has mentioned the location of the source code in t***ensorflow/tensorflow/python/ops/seq2seq.py***. But after I go there (<a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/python/ops" rel="nofollow noreferrer">https://github.com/tensorflow...
<p>The code <code>seq2seq.py</code> was moved to <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py</a> on commit <a...
tensorflow|bots|lstm
1
362,883
42,673,221
Matmul with different rank
<p>I have 3 tensor<br> <code>X</code> shape <code>(1, c, h, w)</code>, assume <code>(1, 20, 40, 50)</code><br> <code>Fx</code> shape <code>(num, w, N)</code>, assume <code>(1000, 50, 10)</code><br> <code>Fy</code> shape <code>(num, N, h)</code>, assume <code>(1000, 10, 40)</code> </p> <p>What I want to do is <code>...
<p>A case for the <a href="https://www.tensorflow.org/versions/master/api_docs/python/math_ops/reduction#einsum" rel="nofollow noreferrer">mythical <code>einsum</code></a>, I guess:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; X = np.random.rand(1, 20, 40, 50) &gt;&gt;&gt; Fx = np.random.rand(100, 50, 1...
python|tensorflow|vectorization
2
362,884
42,894,308
Can't train a model from scratch using tensorflow-slim
<p>I just followed slim tutorial for image classification library and made imagenet TFRecord,too. </p> <p>In <a href="https://github.com/tensorflow/models/tree/master/slim#training-a-model-from-scratch" rel="nofollow noreferrer">training-a-model-from-scracth</a>, followed below code :</p> <pre><code>TRAIN_DIR=/home/y...
<p>Add <code>--num_clones=n</code> can use mutli-gpu, if not, it use one gpu as default.</p> <p>Clean the TRAIN_DIR is useful to me, maybe it help</p>
tensorflow
0
362,885
42,613,183
Pandas group by unique counts as new column
<p>I want to add a new column <code>col</code> in my pandas data frame which will be calculated as:</p> <pre><code>select count(distinct ITEM) as col from base_data where STOCK &gt; 0 group by DEPT, CLAS, DATE; </code></pre> <p>For which I am doing </p> <pre><code>assort_size = base_data[(base_data['STOCK'] &gt; 0)...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> first, then <code>groupby</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.nunique.html" rel="nofoll...
python|pandas
2
362,886
42,860,617
Evaluating Tensorflow operation is very slow in a loop
<p>I'm trying to learn tensorflow by coding up some simple problems: I was trying to find the value of pi using a direct sampling Monte Carlo method.</p> <p>The run time is much longer than I thought it would be when using a <code>for loop</code> to do this. I've seen other posts about similar things and I've tried to...
<p>The slow in speed has got to do with some communication overhead between Python and Tensorflow in <code>sess.run</code>, which is executed multiple times inside your loop. I would suggest using <code>tf.while_loop</code> to execute the computations within Tensorflow. That would be a better comparison over <code>nump...
python|tensorflow|montecarlo
2
362,887
42,680,508
Pandas mean of rows following a matching condition
<p>Lets say I have a Pandas dataframe that looks like this:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({"time": [100,200,300,400,100,200,300,np.nan], "correct": [1,1,0,1,1,0,0,0]}) </code></pre> <p>Printed:</p> <pre><code> correct time 0 1 100.0 1 1...
<p>you can use <a href="https://pandas-docs.github.io/pandas-docs-travis/generated/pandas.Series.shift.html" rel="noreferrer">shift()</a> method:</p> <pre><code>In [55]: df.loc[df.correct.shift() == 0, 'time'].mean() Out[55]: 350.0 </code></pre> <p>Explanation:</p> <pre><code>In [53]: df.correct.shift() Out[53]: 0 ...
python|pandas|dataframe|mean
5
362,888
42,953,068
LLDB breakpoint "TF_NewSession" is not triggered when I debug tensorflow using LLDB
<p>I'd like to learning the C++ source code of tensorflow using lldb debuging as follow.</p> <p>In one terminal:</p> <pre><code>&gt;&gt;&gt;import tensorflow as tf &gt;&gt;&gt;import os &gt;&gt;&gt;os.getpid() 42677 </code></pre> <p>In the other terminal:</p> <pre><code>$lldb -p 42677 Process 42677 stopped * thread...
<p>There is a simple explanation for this: currently (TensorFlow 1.0.1 and earlier) the Python API never calls <code>TF_NewSession()</code>. Instead it <a href="https://github.com/tensorflow/tensorflow/blob/ef56133461079f28b61b5a83a62685051408aadb/tensorflow/python/client/session.py#L562" rel="nofollow noreferrer">call...
c++|tensorflow|lldb
0
362,889
42,866,174
Cosine Similarity
<p>I was reading and came across this formula: </p> <p><a href="https://i.stack.imgur.com/ehC5H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ehC5H.png" alt="enter image description here"></a></p> <p>The formula is for cosine similarity. I thought this looked interesting and I created a numpy arr...
<p>Here's a possible implementation of the adjusted cosine similarity:</p> <pre><code>import numpy as np from scipy.spatial.distance import pdist, squareform M = np.asarray([[2, 3, 4, 1, 0], [0, 0, 0, 0, 5], [5, 4, 3, 0, 0], [1, 1, 1, 1, 1]]) M_u = M.mean(axis=1) it...
python|numpy|scikit-learn|similarity|cosine-similarity
3
362,890
42,701,570
adding rows to empty dataframe with columns
<p>I am using Pandas and want to add rows to an empty DataFrame with columns already established.</p> <p>So far my code looks like this...</p> <pre><code>def addRows(cereals,lines): for i in np.arange(1,len(lines)): dt = parseLine(lines[i]) dt = pd.Series(dt) print(dt) # YOUR CODE GOES...
<p>There are two probably reasons your code is not operating as intended:</p> <ul> <li><p><code>cereals.append(dt, ignore_index = True)</code> is not doing what you think it is. You're trying to append a series, not a DataFrame there.</p></li> <li><p><code>cereals.append(dt, ignore_index = True)</code> does not modify...
python|pandas
1
362,891
43,025,382
Error in Tensorflow Inception V3 geting while pool_3 layer output
<p>I am trying to get the pool_3 layer output of the tensorflow inception v3. My input is ndarray of shape (64,64,3) but I get following error</p> <pre><code>with tf.Session() as sess: pool_3_tensor = sess.graph.get_tensor_by_name('pool_3:0') feat1 = sess.run(pool_3_tensor,{'DecodeJpeg/contents:0': image}) ...
<p>change </p> <pre><code>feat1 = sess.run(pool_3_tensor,{'DecodeJpeg/contents:0': image}) </code></pre> <p>into</p> <pre><code>feat1 = sess.run(pool_3_tensor,{'DecodeJpeg/contents:0': image.tostring()}) </code></pre> <p>and have a try</p> <p><code>'DecodeJpeg/contents:0'</code> is a scalar string tensor from whi...
python|python-3.x|tensorflow
0
362,892
42,683,097
Launching Tensorboard - NameError: name 'tensorboard' is not defined
<p>I'm attempting to launch tensorboard and view a graph I created.</p> <pre><code>import tensorflow as tf logPath = "C:\\path\\to\\log" -- can also be /path/to/log sess = tf.Session() file_writer = tf.summary.FileWriter(logPath, sess.graph) </code></pre> <p>This code runs fine and creates a event file in the prope...
<p>Have you tried adding to the top of your script:</p> <pre><code>from keras.callbacks import TensorBoard </code></pre>
python|tensorflow|tensorboard
6
362,893
42,625,161
Get value from list in pandas
<p>I have a panda data frame (Python 2.11) containing the time as text in one column (format hh:mm:ss). I want to get the hours (minustes or seconds) only. For that I create a list </p> <pre><code>df.Time.str.split(":") </code></pre> <p>This way I get a list e.g. <code>[10,23,00]</code>. How can I access the first (s...
<p>I think you need parameter <code>expand=True</code> - then output is 3 columns of <code>df</code>:</p> <pre><code>df.Time.str.split(":", expand=True) </code></pre> <p>Sample:</p> <pre><code>df = pd.DataFrame({'Time':['10:23:00', '11:23:00']}) print (df) Time 0 10:23:00 1 11:23:00 df[['hour','minute','s...
python|list|pandas
5
362,894
42,589,835
Adding a pandas.DataFrame to Existing Excel File
<p>I have a web scraper which creates an excel file for this month's scrapes. I want to add today's scrape and every scrape for that month into that file as a new sheet every time it is run. My issue, however, has been that it only overwrites the existing sheet with a new sheet instead of adding it as a separate new sh...
<h3>Update:</h3> <p>This functionality has been added to <a href="http://pandas.pydata.org/pandas-docs/version/0.24/whatsnew/v0.24.0.html#other-enhancements" rel="nofollow noreferrer">pandas 0.24.0</a>:</p> <blockquote> <p>ExcelWriter now accepts <code>mode</code> as a keyword argument, enabling append to existing work...
python|excel|python-3.x|pandas|openpyxl
4
362,895
42,980,011
Working on 50 million rows in pandas (python)
<p>I am working on a dataframe of 50 million rows in pandas. I need to run through a column and extract specific parts of the text. The column has string values defined in 4 or 5 patterns. I need to extract the text and replace the original string. I am using the apply function and regex for this. This takes me close t...
<p>here are the docs:</p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html" rel="nofollow noreferrer">http://pandas.pydata.org/pandas-docs/stable/indexing.html</a></p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/text.html#extracting-substrings" rel="nofollow noreferrer">http://pandas....
python|pandas
1
362,896
42,771,237
Adding missing days of week and time of day in the pandas dataframe
<p>I have a pandas dataframe that looks like this:<a href="https://i.stack.imgur.com/hSGSk.jpg" rel="nofollow noreferrer">Dataframe</a></p> <p>Time of Day has levels: Early Morning, Morning, Afternoon, Evening, Late Night</p> <p>The objective is to make the data uniform by adding missing days of week and time of day ...
<p>Here is one way to solve your problem. This is a class which inherits from <code>datetime.datetime</code> and provides some methods for working with your strings to convert to and from a <code>datetime</code>. The advantage of having a datetime, is that you can then use <code>pandas</code> various methods associat...
python|python-2.7|pandas|datetime
1
362,897
42,592,547
Pandas KeyError when working on split data frame
<p>I want to perform some operations on a pandas data frame that is split into chunks. After splitting the data frame, I then try to iterate over the chunks, but after the first iterations runs well, I get an error (see below). I have gone through some questions like these: <a href="https://stackoverflow.com/questions/...
<p>You can first floor divide index values and then use <code>list comprehension</code> - loop by <code>unique</code> values and select by <code>loc</code>, last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>reset_index</code></a> for r...
python|pandas
1
362,898
42,843,352
Is there a way to save the preprocessing objects in scikit-learn?
<p>I am building a neural net with the purpose of make predictions on new data in the future. I first preprocess the training data using sklearn.preprocessing, then train the model, then make some predictions, then close the program. In the future, when new data comes in I have to use the same preprocessing scales to t...
<p>I think besides pickle, you can also use <code>joblib</code> to do this. As stated in Scikit-learn's manual <a href="https://scikit-learn.org/stable/modules/model_persistence.html" rel="nofollow noreferrer">3.4. Model persistence</a></p> <blockquote> <p>In the specific case of scikit-learn, it may be better to us...
machine-learning|tensorflow|scikit-learn|preprocessor|sklearn-pandas
3
362,899
42,830,872
Tesorflow: matrix initialize
<p>I get a matrix <strong>A</strong> with the shape <strong>[ M</strong> x <strong>N</strong> x <strong>L1 ]</strong> and another matrix B with shape <strong>[ M</strong> x <strong>L2 ]</strong>, <strong>L1</strong> and <strong>L2</strong> have the same dimension size but with different values. The M in A and B are cor...
<p>I figured out today morning. One possible way is: </p> <p>As M&amp;N are None dim in tensorflow, <strong>A: [None, None, L], B: [None, L]</strong>, so I used tf.transpose()</p> <p>what we should do is :</p> <p><strong>1, swift dimensions:</strong> </p> <p>tf.transpose(<strong>A,[1,0,2]</strong>): <strong>[ M x N...
matrix|tensorflow
0