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
359,100
72,976,604
Performance of numpy all/any vs testing a single element
<p>I create an array that does not contain a single zero (let's ignore that it does, with zero probability, as <code>np.random.rand()</code> samples [0,1) uniformly). I want to check whether all values are equal to zero (for some other purpose the arrays may contain all zeros). Below are some timings.</p> <p>Surprising...
<p>When you write <code>a == 0</code>, numpy creates a new array of type boolean, compares each element in <code>a</code> with 0 and stores the result in the array. This allocation, initialization, and subsequent deallocation is the reason for the high cost.</p> <p>Note that you don't need the explicit <code>a == 0</co...
python|numpy|performance|any
4
359,101
73,096,762
Pad spaces to header row to same as column width Pandas Dataframe
<p>I have converted csv file to psv file, how can I add spaces using Pandas Dataframe to individual header rows to fix the width of each column.(Widths for columns are 16,56,56,42,6,3 respectively) My table now looks like this I want pad spaces to the header row in the top and also to the row number column on the left ...
<p>From <a href="https://stackoverflow.com/a/72780739/15239951">my answer</a>, you can use <code>to_markdown</code>:</p> <pre><code>widths = [16, 56, 56, 42, 6, 3] df.columns = [c.strip().ljust(w) for c, w in zip(df.columns, widths[1:])] df.index.name = ''.ljust(widths[0]) out = df.astype(str).to_markdown(tablefmt='pip...
python|pandas|dataframe
1
359,102
73,090,413
Keras symbolic inputs/outputs do not implement __len__ Error
<p>I want to build an AI to solve an optimization problem in a given environment, but I get the following error</p> <pre><code>--------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-352-765c5782fe72&gt; in...
<p>You do not need to specifically install the <code>Keras</code> package separately. You can import <code>Keras</code> from <code>TensorFlow</code>. Also, please provide the right alias while importing <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Input" rel="nofollow noreferrer">Input</a> as below. <...
python|tensorflow|machine-learning|keras|deep-learning
1
359,103
72,999,404
How to prevent Python/pandas from treating ids like numbers
<p>I have a data set in a csv with some id's that are very long numbers like this:</p> <pre><code>963839330864351104 426545668232740352 811862613586429056 </code></pre> <p>when I read the csv and convert my dataset into a dataframe, pandas incorrectly thinks it is a number and converts them to scientific notifation so ...
<p>Since you mentioned you're loading from csv, you can simply inform <code>pandas</code> you want to treat that column as a string:</p> <pre class="lang-py prettyprint-override"><code>from io import StringIO from pandas import read_csv data = StringIO(''' id1,id2 963839330864351104,963839330864351104 4265456682327403...
python|pandas|google-colaboratory
5
359,104
73,138,287
Plot group bar chart plotly python
<p>I am trying to make a grouped bar chart in plotly python. But I have not been able to get it to work. It has drawn me the general groups (API1, API2, API3) but it draws me the accumulated bars and I want differentiated bars for each of the S1, S2 and S3</p> <div class="s-table-container"> <table class="s-table"> <th...
<pre><code>df.reset_index(inplace=True) df.rename(columns={'index': 'group'}, inplace=True) df ## group API1 API2 API3 0 s1 41 56 48 1 s2 40 50 45 2 s3 15 24 8 </code></pre> <pre><code>df_plot = df.melt(value_vars=df.columns, id_vars='group') df_plot ### group variable value...
python|pandas|plotly
1
359,105
73,012,338
selectKBest with chi2 throws ValueError: could not convert string to float: 'Self_emp_not_inc' for categorical columns in classification problem
<p>I am trying to select the best categorical features for a classification problem with <code>chi2</code> and <code>selectKBest</code>. Here, I've sorted out the categorical columns: <a href="https://i.stack.imgur.com/3NC0w.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3NC0w.png" alt="categorical-...
<p>Encode features would do the job. For example</p> <pre class="lang-py prettyprint-override"><code>from sklearn.preprocessing import OneHotEncoder from sklearn.feature_selection import chi2, SelectKBest from sklearn.pipeline import make_pipeline X, y = df_cat_kbest.iloc[:, :-1], df_cat_kbest.iloc[:, -1] selector = ...
python|pandas|scikit-learn
1
359,106
73,145,394
How can I take the unique rows of a Huggingface Dataset?
<p>Huggingface Datasets have a <code>unique</code> method, which produces a list of unique vals for a particular column. This method is very fast.</p> <p>I'd like to do something similar, with two differences:</p> <ol> <li><p>I need not just the first column (<code>id</code>) but also another column (<code>answer</cod...
<p>As far as I know/understand from the current <a href="https://huggingface.co/docs/datasets/process" rel="nofollow noreferrer">documentation</a>, there is no way to do this unless you iterate twice from the dataset (without converting to pandas) and without using intermediate variables. I also read that other develop...
python|dataset|huggingface-datasets
1
359,107
73,084,813
TypeError: 'in <string>' requires string as left operand, not Series
<p>Why am I getting this error in the very basic Python script? What does the error mean?</p> <p>Error:</p> <pre><code> 7 def get_speciality_ids(indication): ----&gt; 8 return motif_df.loc[motif_df['motif'] in indication, 'id_speciality'].to_list() 9 10 new_df = drug_df.copy() TypeError: 'in &lt;s...
<p>When you use the <code>in</code> operator like this:</p> <pre><code>x in y </code></pre> <p>if <code>y</code> is a string, <code>x</code> must also be a string.</p> <p>So that means in your example:</p> <pre><code>motif_df['motif'] in indication </code></pre> <p><code>indication</code> is a string, but <code>motif_d...
python|pandas
1
359,108
73,044,883
How to make pandas groupby().count() sum values rather than rows?
<p>I am aware that size() is the one that count rows, and count() <em>should</em> be counting values. However, that isn't happening. When I compare the .count() vs .size(), I get the same result, when they should be greatly different. My code:</p> <pre><code>import pandas as pd df = pd.read_csv(&quot;TEST1.csv&quot;,s...
<p>I think what you want to use is <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.sum.html" rel="nofollow noreferrer">GroupBy.sum</a></p>
python|pandas|dataframe|group-by
0
359,109
72,997,201
how to drop nan values from pandas dataframe
<p>Sample data:</p> <pre><code> WN TOW Azimuth Elevation S4_SIG1 S4_SIG2 TEC 0 2138 432060 289 38 0.087 0.075 16.083 1 2138 432060 37 5 0.175 nan 22.237 2 2138 432060 42 39 0.058 nan 11.188 3 2138 432060 283 6 ...
<pre><code>#change to type float df3 ['WN'] = df3['WN'].astype(float) df3 ['TOW'] = df3['TOW'].astype(float) df3 ['Azimuth'] = df3['Azimuth'].astype(float) df3 ['Elevation'] = df3['Elevation'].astype(float) df3 ['S4_SIG1'] = df3['S4_SIG1'].astype(float) df3 ['S4_SIG2'] = df3['S4_SIG2'].astype(float) df3 ['TEC'] = df3['...
python|pandas|dataframe|jupyter-notebook
0
359,110
72,948,577
How to generate a csv file with pandas fro given start/end dates & interval?
<p>I'm very new to coding and stack overflow, so my apologies if my code is clunky. I'm adjusting some code from Tim Supinie (<a href="https://github.com/tsupinie/vad-plotter" rel="nofollow noreferrer">https://github.com/tsupinie/vad-plotter</a>) to run through a given time frame and plot hodographs for these times. I'...
<p>First, you need to filter the data that only have loop_time value.</p> <p>Then you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> from <code>Pandas</code></p> <p>You can set the <code>loop_time</code> c...
python|pandas|loops|csv
0
359,111
72,866,930
Efficient way of calculating amount of concurrent calls by one user to a distinct phone number using python pandas?
<p>I have a large dataframe of user calls to different phone numbers</p> <pre><code>calls = { 'user': ['a', 'b', 'b', 'b', 'c', 'c'], 'number': ['+1 11', '+2 22', '+2 22', '+1 11', '+4 44', '+1 11'], 'start_time': ['00:00:00', '00:02:00', '00:03:00', '00:00:00', '00:00:00', '00:00:00'], 'end_time': ['00...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;start_time&quot;] = pd.to_datetime(df[&quot;start_time&quot;]) df[&quot;end_time&quot;] = pd.to_datetime(df[&quot;end_time&quot;]) def fn(x): x[&quot;tmp1&quot;] = x.apply( lambda y: pd.date_range(y[&quot;start_time&quot;], y[&quot;end_ti...
python|python-3.x|pandas|dataframe|group-by
1
359,112
72,961,695
Find "most used items" per "level" in big csv file with Pandas
<p>I have a rather big csv file and I want to find out which items are used the most at a certain player level.</p> <p>So one column I'm looking at has all the player levels (from 1 to 30) another column has all the item names (e.g. knife_1, knife_2, etc.) and yet another column lists backpacks (backback_1, backpack_2,...
<p>Try the following:</p> <pre><code>data = &quot;&quot;&quot;\ index playerLevel playerKnife playerBackpack 0 1 knife_1 backpack_1 1 2 knife_2 backpack_1 2 3 knife_1 backpack_2 3 1 knife_2 backpack_1 4 2 knife_3 backpack_2 5 ...
python|pandas
1
359,113
72,885,552
Pandas - Group / Aggregate rows based on duplication AND the existence of an opposite
<p>I have a Dataframe that sometimes contains 2 rows for what is, in reality, one entry. The way to identify these is:</p> <ol> <li>Columns: Not, Strike, Cents, SD, ED are identical</li> <li>Column ExecutionTimestamp is going to be within a short period of time (&lt;2.5min)</li> <li>For a (+) in Structure, there exists...
<p>This should allow you to get your expected results.</p> <pre><code>df = df.groupby(['A', 'B', 'D', 'E']).agg({'C' : 'sum', 'ExecutionTimestamp' : 'last'}).reset_index() df['F'] = '(=)' df[['A', 'B', 'C', 'D', 'E', 'F', 'ExecutionTimestamp']] </code></pre> <p>I was sure what you meant by the &quot;keep either timesta...
python|pandas
1
359,114
72,988,374
python string eval string got error in dict
<pre><code>In [33]: def select_func(df): ...: df=df.copy() ...: rules=[&quot;df['Age']&lt;60&quot;] ...: s={ f&quot;n{i}&quot; :eval(r) for i,r in enumerate(rules) } ...: return df In [34]: select_func(df=df1) --------------------------------------------------------------------------- N...
<h2>The minimal example</h2> <p>The minimal example of your problem is:</p> <pre><code>m1=1 def outer_fun(m): commands = [&quot;m&quot;] s = {i: eval(r) for i, r in enumerate(commands)} outer_fun(m1) </code></pre> <p>Which gives:</p> <pre><code>Traceback (most recent call last): File &quot;/tmp/pycharm_proj...
python|pandas
1
359,115
73,153,190
NumPy: Get indices of elements of array after insertion in sorted array
<p>Consider the code</p> <pre><code>import numpy as np v = np.linspace(0, 9, 10) w = np.array([3.5, 4.5]) idx = np.searchsorted(v, w) v = np.insert(v, idx, w) print(idx, v[idx]) </code></pre> <p>which outputs</p> <pre><code>[4 5] array([3.5, 4. ]) </code></pre> <p>The variable <code>idx</code> contains the indices of...
<p>Perhaps the most elegant solution is</p> <pre><code>idx_new = idx + np.argsort(np.argsort(idx)) </code></pre> <p>but probably not the fastest</p>
python|numpy
2
359,116
10,395,691
Numpy cannot be accessed in sub directories
<p>I have used import numpy as np in my program and when I try to execute np.zeroes to create a numpy array then it does not recognize the module zeroes in the program. This happens when I execute in the subdirectory where the python program is. If I copy it root folder and execute, then it shows the results.</p> <p>C...
<blockquote> <p>then it does not recognize the module zeroes in the program</p> </blockquote> <p>Make sure you don't have a file called <code>numpy.py</code> in your subdirectory. If you do, it would shadow the "real" <code>numpy</code> module and cause the symptoms you describe.</p>
python|numpy
1
359,117
10,278,004
How to order this computation for numerical stability?
<p>I'm trying to compute a vector, whose sum is 1 and whose elements are defined as such:</p> <pre><code>v[i] = exp(tmp[i])/exp(tmp).sum() </code></pre> <p>The problem is that the value in the exponential may be large (between -10^2 and 10^2), making the exponential to evaluate to inf or 0.</p> <p>I tried some varia...
<pre><code>&gt;&gt;&gt; tmp = np.array([-10**10, 10**10]) &gt;&gt;&gt; tmp_max = tmp.max() &gt;&gt;&gt; log_D = log(sum(exp(tmp - tmp_max))) + tmp_max &gt;&gt;&gt; log_v = tmp - log_D &gt;&gt;&gt; v = np.exp(log_v) &gt;&gt;&gt; v array([ 0., 1.]) </code></pre> <p>Or use <a href="http://docs.scipy.org/doc/scipy/refere...
python|numpy|numerical|exponential|stability
4
359,118
10,738,412
Recommended setup involving Scitools, NumPy, and SciPy
<p>I have a book called "Scientific Programming with Python (2009)", in which example code makes heavy use of SciTools. I use Python 3.2 64 (thinking about having a parallel install / development environment of 2.7; more on this later), to which SciTools has not yet been ported.</p> <p>Has Scitools been superceded fo...
<p>Scipy/Numpy is the defacto standard for scientific/numerical computing with python. The vast majority of packages are built on top of them (including Scitools). In many ways it looks like Scitools is just a connivence wrapper around Numpy/Scipy/Matplotlib.</p> <p>As far as Python 3 support, Numpy and Scipy are ther...
numpy|python-3.x|scipy|scientific-computing
13
359,119
10,831,417
Extracting diagonal blocks from a numpy array
<p>I am searching for a neat way to extract the diagonal blocks of size 2x2 that lie along the main diagonal of a (2N)x(2N) numpy array (that is, there will be N such blocks). This generalises numpy.diag, which returns elements along the main diagonal, that one might think of as 1x1 blocks (though of course numpy doesn...
<p>You can also do it with views. This is probably faster than the indexing approach.</p> <pre><code>import numpy as np import scipy.linalg a1 = np.array([[1,1,1],[1,1,1],[1,1,1]]) a2 = np.array([[2,2,2],[2,2,2],[2,2,2]]) a3 = np.array([[3,3,3],[3,3,3],[3,3,3]]) b = scipy.linalg.block_diag(a1, a2, a3) b[1,4] = 4 b[1...
python|numpy|scipy
4
359,120
10,760,364
"Zebra Tables" in IPython Notebook?
<p>I'm building some interactive workflows in IPython using the fantastic Notebook for interactive analysis and Pandas.</p> <p>Some of the tables I'm displaying would be much easier to read with a little bit of formatting. I'd really like something like "zebra tables" where every other row is shaded. I <a href="http:/...
<p>You can run arbitrary javascript (with jQuery) either in markdown cells inside <code>&lt;script&gt;</code> tags, or via IPython's <code>IPython.core.display.Javascript</code> class. With these, you can manipulate (or ruin) the document to your heart's content, including adding stylesheets.</p> <p>For instance, the...
python|pandas|ipython|ipython-notebook|jupyter
13
359,121
10,443,295
Combine 3 separate numpy arrays to an RGB image in Python
<p>So I have a set of data which I am able to convert to form separate numpy arrays of R, G, B bands. Now I need to combine them to form an RGB image. </p> <p>I tried 'Image' to do the job but it requires 'mode' to be attributed. </p> <p>I tried to do a trick. I would use Image.fromarray() to take the array to image ...
<pre><code>rgb = np.dstack((r,g,b)) # stacks 3 h x w arrays -&gt; h x w x 3 </code></pre> <p>To also convert floats 0 .. 1 to uint8 s,</p> <pre><code>rgb_uint8 = (np.dstack((r,g,b)) * 255.999) .astype(np.uint8) # right, Janna, not 256 </code></pre>
python|image|image-processing|numpy
92
359,122
3,551,242
Numpy index slice without losing dimension information
<p>I'm using numpy and want to index a row without losing the dimension information.</p> <pre><code>import numpy as np X = np.zeros((100,10)) X.shape # &gt;&gt; (100, 10) xslice = X[10,:] xslice.shape # &gt;&gt; (10,) </code></pre> <p>In this example xslice is now 1 dimension, but I want it to be (1,10). I...
<p>Another solution is to do</p> <pre><code>X[[10],:] </code></pre> <p>or </p> <pre><code>I = array([10]) X[I,:] </code></pre> <p>The dimensionality of an array is preserved when indexing is performed by a list (or an array) of indexes. This is nice because it leaves you with the choice between keeping the dimensio...
python|numpy
114
359,123
3,488,934
SimpleJSON and NumPy array
<p>What is the most efficient way of serializing a numpy array using simplejson?</p>
<p>In order to keep dtype and dimension try this:</p> <pre><code>import base64 import json import numpy as np class NumpyEncoder(json.JSONEncoder): def default(self, obj): """If input object is an ndarray it will be converted into a dict holding dtype, shape and the data, base64 encoded. ...
python|json|numpy|simplejson
80
359,124
70,672,108
Airflow s3Hook - read files in s3 with pandas read_csv
<p>I'm trying to read some files with pandas using the <code>s3Hook</code> to get the keys. I'm able to get the keys, however I'm not sure how to get pandas to find the files, when I run the below I get:</p> <blockquote> <p>No such file or directory:</p> </blockquote> <p>Here is my code:</p> <pre><code>def transform_pa...
<p>The format you are looking for is the following:</p> <pre><code>filepath = f&quot;s3://{bucket_name}/{key}&quot; </code></pre> <p>So in your specific case, something like:</p> <pre><code>for file in keys: filepath = f&quot;s3://s3_bucket/{file}&quot; df = pd.read_csv(filepath, sep='\t', skiprows=1, header=No...
python|pandas|amazon-s3|airflow
1
359,125
70,433,310
How to make python ignore a blank cell and continue downloading images from the next cell
<p>when iterating through the cell if a blank cell comes up, and error pops up and stop download. is there any exception or steps to ignore a blank cell?</p> <pre><code>for j in u.iteritems(): file_name = str(i)+&quot;.jpeg&quot; res = requests.get(u[0], stream = True) if res.status_co...
<p>try adding a try: ..., except: continue block (or try:..., except: pass block) something like this:</p> <pre><code>for j in u.iteritems(): try: file_name = str(j)+&quot;.jpeg&quot; res = requests.get(u[0], stream = True) if res.status_code == 200: with open(file_name,'wb') as f: ...
pandas|python-requests|shutil
0
359,126
70,536,282
Go through every row in a dataframe, search for this values in a second dataframe, if it matches, get a value from df1 and another value from df2
<p>I have two dataframes:</p> <ol> <li><p>Researchers: a list of all researcher and their id_number</p> </li> <li><p>Samples: a list of samples and all researchers related to it, there may be several researchers in the same cell.</p> </li> </ol> <p>I want to go through every row in the researcher table and check if the...
<p>You have a few data cleaning job to do such as 'Moore' in lowercase, 'Haffer' with first name initials in one case and none in the other, etc. After normalizing your two dataframes, you can <code>split</code> and <code>explode</code> <code>collections</code> and use <code>merge</code>:</p> <pre><code>samples['collec...
python|pandas|dataframe|loops
0
359,127
70,556,905
how to compare current and last element iterated from numpy without loop
<p>In 2d array get the last column and compare current value with its last iterated value and if the difference is == 1 then get row indexes of both of them . I able to do it using for loop but it gets slow when array grows as there are multiple conditions next after getting indexes</p> <pre><code>x=np.array ([[79, 50,...
<p>I don't think there is a way of doing this in python that doesn't use a loop (or a function that utilizes a loop). But I would suggest something like this, it worked quite well for me:</p> <pre><code>import numpy as np x = np.array([[79, 50, 18, 55, 35], [46, 71, 46, 95, 80], [97, 37, 71, 2, 79],[80, 96, 60, 85, 7...
python|numpy
0
359,128
70,680,062
Calculate the number of definite months in a period
<p>The start year, start month, end year, and end month are the inputs (like May'2022 to June'2024). If I need to calculate how many definite months are included in this period (like how many January, March, or December are in this period), how can I achieve this using Python?</p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html" rel="nofollow noreferrer"><code>date_range</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.month_name.html" rel="nofollow noreferrer"><code>DatetimeIndex.month_name</...
python|pandas
1
359,129
70,395,179
Using two dataframes how can I compare a lookup value as a substring in the column in another dataframe to create a new column if the match exists
<p>I'm attempting to use two dataframes, one as a lookup table to find a substring match on the value in my datasets dataframes column. After I find the value, I'd like to create a new column with that value and iterate through the entire column and remove the matched substring from the initial column and loop through...
<ol> <li>Use <code>str.extractall</code> to get all matches</li> <li><code>unstack</code> to convert to individual columns</li> </ol> <pre><code>output = df2['Ingredient_Name'].str.extractall(f&quot;({'|'.join(df1['Ingredient_Name'])})&quot;).unstack() #formatting output = output.droplevel(0,1).rename_axis(None, axis=...
python|pandas|dataframe
1
359,130
70,665,035
Delete DataFrame if condition is true - Pandas
<p>I'm sorry if this is obvious (I feels like it should be). I am downloading stock data using a for loop to create a set of dataframes labeled with the ticker name. I wish to not download stocks that return less than x rows in the downloaded data.</p> <p>I currently have this that is not working?</p> <pre><code>with ...
<pre><code>with open('Tickers/25_tickers.csv') as f: lines = f.read().splitlines() for Symbol in lines: print(Symbol) vars()[Symbol] = pd.DataFrame() vars()[Symbol] = yf.download(Symbol, start, end, interval= '1d') i = vars()[Symbol].shape[0] #try to remove empty and low row df....
python|pandas|dataframe
1
359,131
70,729,290
Search and filter in Python Pandas
<pre><code>tune = input(&quot;Type your tune parameters ?&quot;) </code></pre> <p><a href="https://i.stack.imgur.com/qNWCN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qNWCN.png" alt="enter image description here" /></a></p> <p>Hi there</p> <p>I'm wondering if I can plot &quot;High&quot; on a line...
<pre><code>dataset : tune,drs Low,31 Low-medium,42 Ultra Low,52 Medium,48 MediumHard,9 MediumSoft,26 MediumCSS,28 HightCSS,59 HightCSS,59 Avavee,34 Hight,22 Hight,49 </code></pre> <hr /> <pre><code>import pandas as pd df = pd.read_csv(&quot;ExportCSV.csv&quot;, usecols=[&quot;tune&quot;,&quot;drs&quot;]) print(&quot;...
python-3.x|pandas|dataframe
-1
359,132
70,633,104
Reorganize index and column DataFrame Pandas
<p>I'm supposed to create a palindrome checker and convert them into dataFrame.</p> <p>The code:</p> <pre><code>import pandas as pd # TODO: Check if the number is palindrome or not and convert them into DataFrame n = [1,0,1] g = n == n[::-1] a = pd.DataFrame(n) a['Is Palindrome'] = g a.transpose() </code></pre> <p>T...
<p>I think you just need to add the <code>Is Palindrome</code> column all the way at the end:</p> <pre><code>import pandas as pd n = [3,0,3] g = n == n[::-1] a = pd.DataFrame(n) a = a.transpose() a['Is Palindrome'] = g </code></pre>
python|pandas
1
359,133
70,514,404
Input() IF ELSE Control statement in Python
<p>I have a dataset where, whenever a date value is input, specific date columns will shift.</p> <p><strong>Data</strong></p> <pre><code>location type mig1 de mig2 re ny aa 8/1/2021 10/1/2021 1/1/2022 2/1/2022 ny aa 8/1/2021 10/1/2021 1/1/2022 2/1...
<p>IIUC:</p> <pre><code>input = datetime(2022, 8, 1) conditions = {'mig1':5, 'de':3, 're':1} def apply_this(x): if x.name == 'mig2': return [input]*len(x) else: return [input - pd.DateOffset(months=conditions[x.name])]*len(x) date_cols =['mig1', 'de', 're', 'mig2'] df.loc[df['type'] == 'aa', da...
python|pandas|numpy|if-statement|input
1
359,134
70,639,896
Pandas - Groupby and Standardize
<p>I have tried to tackle this for quite some time, but haven't been able to get a pythonic way around it by using the built-in <code>groupby</code> and <code>transform</code> methods from pandas.</p> <p>The goal is to group the data by columns <code>ex_date</code> and <code>id</code>, then within the groups identified...
<p>You can mask the non matching values and fill per group using <code>groupby</code>+<code>transform</code> to get the reference. Then simply divide your data with the reference.</p> <pre><code>ref = df['ref_value_1'].where(df['calc_date'].eq(df['ex_date'])).groupby(df['id']).transform('first') df['standardized_val']...
python|pandas|dataframe
0
359,135
70,649,970
Pandas groups into the numpy arrays including the group info
<p>I have a dataframe like this,</p> <pre><code> df = pd.DataFrame({ 'id': ['A','A','A','B','B','C','C','C','C'], 'groupId': [11,35,46,11,26,25,39,50,55], 'type': [1,1,1,1,1,2,2,2,2], }) </code></pre> <p>I want to turn the groups into the list of numpy arrays includi...
<p>Use <code>x.name</code> for <code>type</code> value and add to <code>np.array</code>:</p> <pre><code>a = df.groupby(['id','type'])['groupId'].apply(lambda x: np.array([x.name[1], *x])).tolist() print (a) [array([ 1, 11, 35, 46], dtype=int64), array([ 1, 11, 26], dtype=int64), array([ 2, 25, 39, 50, 55], dtype=int6...
python|pandas
3
359,136
70,648,371
How to convert a date to Quarter
<p>I am trying to convert a date to <code>Year-Quarter</code> format. Below is my code</p> <pre><code>import pandas as pd import datetime as datetime pd.PeriodIndex(datetime.date(2020, 6, 15), freq='Q-MAR').strftime('Q%q') </code></pre> <p>Which this I am getting below error:</p> <pre><code>Traceback (most recent call...
<p>If working with scalar need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/pandas.Period.html" rel="nofollow noreferrer"><code>Period</code></a>:</p> <pre><code>print (pd.Period(datetime.date(2020, 6, 15), freq='Q-MAR').strftime('Q%q')) Q1 print (pd.Period(datetime.date(2020, 6, 15), freq='Q-MAR')....
python|pandas|datetime
0
359,137
70,462,970
How to use argmin() and find minimum value from array
<p>I'm new to python so the code may not be the best. I'm trying to find the minimum Total Cost (TotalC) and the corresponding m,k and xM values that go with this minimum cost. I'm not sure how to do this. I have tried using min(TotalC) however this gives an error within the loop or outside the loop only returns the va...
<p><code>argmin()</code> returns the index of a minimum value. If You are looking for the minimum itself, try using <code>.min()</code>. There is also a possibility that 0 is the lowest value in Your array so bear that in mind</p>
python|numpy|min
0
359,138
70,723,588
filter rows in a pandas dataframe from substrings (keys) in a list and also add new column "key" to dataframe containing the substring matched (key)
<p>Iam new to python. The below code filter rows in a dataframe df based on substrings (keys) in a list and add a new column say 'Key&quot; containing the substring (all of them). The dataframe contains name of student, age, sport. The sport page contains all sports played by him. the list array contains two sports n...
<p>While it might be possible in this case to just use substrings, a more robust approach would be to make a new DataFrame that maps each Name to each associated Sport, and select the desired Names from there.</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; name_to_sport = ( df[['Name']] .join(...
python|pandas|dataframe|contains|string-matching
1
359,139
70,734,265
Pandas pivot table function values into wrong rows
<p>I'm making a pivot table from a CSV (cl_total_data.csv) file using pandas pd.pivot_table() and need find a fix to values in the wrong rows.</p> <p>[Original CSV File]</p> <p><img src="https://i.stack.imgur.com/DIopx.png" alt="1" /></p> <p>The error occurs when the year has 53 weeks(i.e. 53 values) instead of 52, the...
<blockquote> <p>I can't figure out what I'm coding wrong in the pivot table function that causes this misplacement of values. Is there a better way to code it?</p> </blockquote> <p>The problem here lies in the definition of the <a href="https://en.wikipedia.org/wiki/ISO_week_date" rel="nofollow noreferrer">ISO week num...
python|pandas|csv|charts|data-analysis
1
359,140
70,602,469
My S3 bucket has more than 100k parquet files. What is the best way to programmatically merge all the parquet files and make one big parquet
<p>The parquet files are being dumped every minute into the S3 bucket. I have 6 months data which has more than 100k small parquet files. All of them have the same schema. Now I am writing a program to merge all these files. Tried appending one dataframe to another using pandas but obviously that does not seem to be th...
<p>I have done this in the past by using <strong>Amazon Athena</strong> to query all the files and then save the result in a new table, with the data being stored in a new location.</p> <p>I start by creating a table that points to the existing data. You can either do this manually or use an <strong>AWS Glue crawler</s...
pandas|dataframe|apache-spark|amazon-s3|parquet
2
359,141
70,571,567
How to extend a list inside a pandas dataframe
<p>I have a pandas data frame, and each element of one of its columns is a list. Then I have a list with the same amount of elements as rows in the pandas data frame; I want to extend the list inside pandas with this new list.</p> <p>So, for example, if this is the data frame.</p> <pre class="lang-py prettyprint-overri...
<pre><code>df = pd.DataFrame({'my_column':[[1, 2], [3, 4]]}) lst = [[5, 6], [7, 8, 9]] </code></pre> <p>One way:</p> <pre><code>df['my_column'] += pd.Series(lst) </code></pre> <p>Another way: You can <code>zip</code> the column values with list values and use list comprehension:</p> <pre><code>df['my_column'] = [l1 + ...
python|pandas|list
2
359,142
70,521,522
How to find the column number for a specific value and the CSV file at that location
<p>I'm trying to split a csv file at a specific row with a specific value, but i cannot figure out how to do it. The csv file is a data export from a program we use and it consist of two different parts. The file looks like this and the second part is always started with '[Faces]'.</p> <pre><code>[Name] Plane 1750 [Da...
<p>Try to consume lines until we meet <code>[Faces]</code> line:</p> <pre><code>with open('data.txt') as fp: while fp.readline().strip() != '[Faces]': pass df = pd.read_csv(fp, header=None, skipinitialspace=True) with open('faces.csv') as fp: fp.write('[Faces]\n') df.to_csv(fp, index=False) </c...
python|pandas|numpy
2
359,143
70,731,102
How to correct wrong data type in Excel raw data file when reading it in to Pandas data frame
<p>I've imported data from multiple Excel files and some of the values are formatted incorrectly in the raw data files. For example, when I import the data, my table looks like this:</p> <pre><code> Date Income 2010-01:05 00:00:00 3500 Unknown Unknown 2010-02:10 ...
<p>To convert the dates use:</p> <pre><code>from datetime import datetime import xlrd date=42988 print(xlrd.xldate_as_datetime(date, 0).date()) </code></pre>
python-3.x|pandas
0
359,144
70,625,575
Bigger batch size improves training by too much
<p>I am writing a classifier that takes a surname and predicts a language it belongs to. I found that small batch sizes (256 and less) perform poorly compared to big batch sizes (2048 and more). Could someone give me some insight on why this is happening and how to fix it? Thank you.</p> <p>Training code:</p> <pre><cod...
<p>It looks like there issue is how the loss is calculated.</p> <p><code>train_loss += loss</code> line accumulates the loss. When batch size is higher, there will be fewer steps to do. The code normalizes this by dividing by the length of train data, <code>train_loss /= len(train_data)</code>, but should probably take...
pytorch|lstm|recurrent-neural-network|batchsize
1
359,145
70,665,911
Why is it not possible to store DD-MM-YYYY format in date format?
<p>I'm trying to convert date type information in the &quot;YYYY-MM-DD&quot; format to &quot;DD-MM-YYYY&quot; but I wanted to keep the date type, but I'm not able to tell you why? Or am I doing something wrong?</p> <pre><code>import moment df = pd.DataFrame({&quot;Date&quot;: [&quot;2022-12-10&quot;, &quot;2022-12-11&...
<p>Following the format of the solutions you have tried, a correct way to do it (not the most efficient) is:</p> <pre><code>import datetime df[&quot;Date&quot;] = [datetime.datetime.strptime(s, '%Y-%m-%d').strftime('%d-%m-%Y') for s in df[&quot;Date&quot;]] </code></pre> <p>If you need more efficiency in the solution,...
python|python-3.x|pandas
3
359,146
70,524,428
Cannot install Tensorflow 2.4.1 as a dependency for OpenVino
<p>When going through the process of installing OpenVino as documented <a href="https://docs.openvino.ai/latest/openvino_docs_install_guides_installing_openvino_macos.html" rel="nofollow noreferrer">here</a>, I'm running:</p> <pre><code>sudo ./install_prerequisites.sh </code></pre> <p>and getting</p> <pre><code>ERROR: ...
<p>I've already <a href="https://stackoverflow.com/a/70501550/7976758">shown</a> you how to debug such problems. Well, let's see.</p> <p>The list of available packages for <a href="https://pypi.org/project/tensorflow/2.4.1/#files" rel="nofollow noreferrer">tensorflow 2.4.1</a> includes wheels for Python 3.6-3.8. No 3.9...
tensorflow|pip|openvino
1
359,147
70,504,121
find numpy rows that are the same
<p>I have a numpy array</p> <p>How can I find which of them are the same and how many times appear in the matrix? thanks dummy example:</p> <pre><code>A=np.array([[0, 1, 0, 1],[0, 0, 0, 0],[0, 1, 1, 1],[0, 0, 0, 0]]) </code></pre>
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.unique.html" rel="nofollow noreferrer"><code>numpy.unique</code></a> with <code>axis=0</code> and <code>return_counts=True</code>:</p> <pre><code>np.unique(A, axis=0, return_counts=True) </code></pre> <p>Output:</p> <pre><code>(array([[0, 0,...
numpy|rows
1
359,148
70,612,364
numpy warning with django 4 - 'numpy.float64'> type is zero
<p>I just updated numpy and I get the following warning with Django. How can I fix it?</p> <blockquote> <p>/usr/local/lib/python3.9/site-packages/numpy/core/getlimits.py:89: UserWarning: The value of the smallest subnormal for &lt;class 'numpy.float64'&gt; type is zero.</p> </blockquote>
<p>In my case this was some kind of compatability issue between a custom compiled version of opencv and numpy 1.22. The workaround to stop the warnings was the do the following.</p> <pre><code>import numpy as np np.finfo(np.dtype(&quot;float32&quot;)) np.finfo(np.dtype(&quot;float64&quot;)) import cv2 </code></pre> <p...
python|django|numpy
3
359,149
70,431,847
'DataFrame' object has no attribute 'value' to plot a chart
<p>I need to plot a chart but it raises the following error:</p> <pre><code> --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_6816/1118115357.py in &lt;module&gt; 5 plt.show() ...
<p>Try:</p> <pre><code>plot_df(df, x=df.index, y=df['Sales'], title='Mecerdez Car Sales in the US from 2015 to 2020.') </code></pre>
python|pandas
0
359,150
70,668,130
ERROR:root:Internal Python error in the inspect module. Below is the traceback from this internal error
<p>I want to calculate the following CNN.</p> <p>I launched the Jupyter notebook via Anaconda. The calculation should be done via the GPU.</p> <p>Unfortunately, I got the following error message. Any Ideas regarding my issue?</p> <pre><code> history = model.fit( train_generator, steps_per_epoch= len(...
<p>There is a problem with installed TensorFlow version and other existing modules version mismatch in your system.</p> <p>Please reinstall the upgraded TensorFlow version and restart the kernel in the existing conda environment.</p> <pre><code>!pip install --upgrade tensorflow </code></pre> <p>Also, please avoid using...
python|tensorflow|jupyter-notebook|gpu
0
359,151
70,701,009
Run tensorflow model before training, otherweise it won't train?
<p>I found a very interesting thing today when running a tensorflow code:</p> <pre><code>import matplotlib from matplotlib import pyplot as plt import tensorflow as tf matplotlib.rcParams['figure.figsize'] = [9, 6] x = tf.linspace(-2., 2., 201) def f(x): y = x**2 + 2*x - 5 return y y = f(x) + tf.random.normal(shap...
<p>Before you can train your model, you must build it and compile it.</p> <p>Building the model creates all variables of the model depending on the <code>input_shape</code> of your training data.</p> <p>Compiling the model sets the optimizer and loss function you would like to use during training.</p> <p>When you call ...
python|tensorflow|machine-learning|keras
-1
359,152
70,661,279
Sentiment Analysis: Fitting a model result in value error (shapes incompatible?)
<p>I am doing a sentiment analysis on a set of reviews --&gt; predicting the rating (0-5) based on the text review. I have completed text pre-processing and tokenizing. I am using a pre-trained word vector embeddings (googlenews) and created the embedding_matrix.</p> <p>I have built the model thus far:</p> <pre><code>#...
<p>You are currently having a sparse tensor for your y-values:</p> <pre><code>y_train = to_categorical(y_train,6) </code></pre> <p>This sould have the shape <code>[1000,6]</code> which you can check with <code>y_train.shape()</code>.</p> <p>One thing that should be working is simply changing the size of your output lay...
python|tensorflow|keras|deep-learning|sentiment-analysis
0
359,153
70,556,990
How to load first 2 channel of a 3 channel image in pytorch?
<p>I have a datasets of 3 channel images, but I want to use the first 2 channel of each image as input to Resnet34. Is there anyway I can just load the first 2 channel of each imgage?</p>
<p>You have two problems:</p> <ol> <li>Images on disk have 3 channels, and you need to remove one when you load them using your <code>Dataset</code>.</li> <li>Your network (<code>ResNet-18</code>) expects inputs with 3 channels - now it will get only two. (This might trigger an error like <a href="https://stackoverflow...
python|pytorch|computer-vision|conv-neural-network|resnet
0
359,154
70,703,154
Size of array of returned function does not match
<p>I am trying to solve the problem below using python, first time using this language so bear with me please.</p> <p>I keep getting this error and am unsure of the problem, I have looked at other posts as well but with no success.</p> <p>I am trying to find the solution to <code>di/dt=beta-s*i-gamma*i</code></p> <p>wh...
<p>I am not sure what your ODEs are exactly describing but the problem seems to be that you have three states but only one ODE that you use in your function <code>F()</code> and it describes only a single state. The number of states and equations should match if each produces a single state. Similarly I am not sure why...
python|numpy
1
359,155
70,596,324
Pandas-InnerJoin- Multiplication of Rows
<p>I have two sets of data, with one common column. Some rows have repetitions so I created a similar small example.</p> <p>Here are my dataframes:</p> <pre><code>#Dataframe1 import pandas as pd data = [['tom', 10], ['tom', 11], ['nick', 15], ['juli', 14]] df = pd.DataFrame(data, columns = ['Name', 'Age']) #Datafr...
<p>Create a temporary key for duplicate name in order, such that the first Tom in df joins to the first Tom in df2 and 2nd Tom joins to 2nd Tom in df2, etc.</p> <pre><code>df = df.assign(name_key = df.groupby('Name').cumcount()) df2 = df2.assign(name_key = df.groupby('Name').cumcount()) df.merge(df2, how='inner', on=[...
python|pandas|inner-join
1
359,156
70,589,100
Pandas : How can I create new column using previous rows from existing column and newly created column?
<p>From excel, I have used this formula to create new column ( column 'D' )</p> <p><code>IF(OR(A2&lt;&gt;A1,AND(B2&lt;&gt;&quot;000&quot;,B1=&quot;000&quot;)),D1+1,0)</code></p> <p>I have referred data from previous row of existing column A and B as condition to create value in current row of column D and also I have r...
<p><a href="https://stackoverflow.com/questions/64568951/python-pandas-dataframe-calculating-new-row-value-based-on-previous-row-value-wi">Python Pandas Dataframe calculating new row value based on previous row value within same column</a></p> <p>Sorry I just found this link it can help me. This code is my solution.</p...
python|pandas
1
359,157
70,631,490
how can i make np.argmin code without numpy?
<p>I've been given the challenge to code np.argmin without numpy .</p> <p>I've been thinking hard for about a day.. I have no idea whether I should use a for statement,</p> <p>an if statement, a while statement, or another function..</p> <hr /> <h2>First question!</h2> <p>First, I thought about how to express it with a...
<pre><code>def argmin(a): return min(range(len(a)), key=lambda x : a[x]) def argmax(a): return max(range(len(a)), key=lambda x : a[x]) </code></pre> <p>This code is for 1D list.</p>
python|numpy
1
359,158
70,443,444
Comparing 2D boolean arrays
<p>I am working on a problem where I need to compare 1 particular array to hundreds of thousands of others and return a list of results showing how similar they are to each other, I read up that numpy was probably the best library to go about working with arrays (if there's anything better please let me know:) so I scr...
<p>There are a number of efficient tricks for doing this in numpy. None of them require explicit loops or appending to a list.</p> <p>First, make the list into an array:</p> <pre><code>list_of_arrays = np.random.randint(0, 2, (100000, 30, 30), dtype=bool) </code></pre> <p>Notice how much simpler (and faster) that is. N...
python|arrays|numpy
1
359,159
70,571,949
Simple Linear Regression not converging
<p>In my attempt to dig deeper in the math behind machine learning models, I'm implementing a Ordinary Least Square algorithm in Python, using vectorization. My references are:</p> <ul> <li><a href="https://github.com/paulaceccon/courses/blob/main/machine_learning_specialization/supervisioned_regression/2_multiple_regr...
<p>Your code seems actually to work fine; except for learning rate, really! Just reduce it from <code>0.01</code> to e.g. <code>0.0001</code> and everything works fine (well, I would also reduce tolerance to something much much smaller, like <code>1e-5</code>, to make sure it actually converges to the right solution).<...
python|numpy|linear-regression
1
359,160
70,475,625
Cannot convert tf.keras.preprocessing.image_dataset_from_directory to np.array
<p>I am trying to create a image classification model using CNN. For that I am reading the data using the <code>tf.keras.preprocessing.image_dataset_from_directory</code> function.</p> <p>This is the code:</p> <pre><code>train_ds = tf.keras.preprocessing.image_dataset_from_directory(data_dir_train,seed=123,validation_s...
<p>When using <a href="https://www.tensorflow.org/api_docs/python/tf/keras/utils/image_dataset_from_directory" rel="nofollow noreferrer">image_dataset_from_directory</a>:</p> <blockquote> <p>... image_dataset_from_directory(main_directory, labels='inferred') will return a <em>tf.data.Dataset</em> that <em>yields</em> b...
python|numpy|tensorflow|keras|conv-neural-network
0
359,161
70,403,895
best way to extract the first-name and last-name from sentence python (Persian text)
<p>I have over <strong>20,000</strong> first and last name and I want to check the sentence if in that sentence is any <code>first-name</code> or <code>last-name</code> of my <code>dataset</code>, this is my <code>dataset</code></p> <pre><code>l-name f-name میلاد جورابلو علی احمدی امیر احمدی </code></pre> <p...
<p>If you would like to approach this in a naive way you could consider regex, however this is based on the assumption that all first and last names are capitalised.</p> <pre><code>sentence = 'I am going out with John Williams today' name = re.search(r&quot;[A-Z]{1}[a-z]+ [A-Z]{1}[a-z]+&quot;, sentence).group() print(n...
python|pandas|dataframe|dataset
0
359,162
70,678,834
Is there a way in Pandas to fill down the previous value with condition?
<p>I have a table as below and want to fill down the Stage of the same category based on the condition <code>if Stage = &quot;Delivered&quot; then fill down &quot;Delivered&quot; to all the next rows else if Stage = &quot;Paid&quot; then fill down &quot;Paid&quot; to all the next rows </code></p> <div class="s-table-co...
<p>You can use <code>mask</code> and <code>combine_first</code>:</p> <p>Assuming your dataframe is already sorted by <code>Date</code> column.</p> <pre><code>df['Stage'] = df['Stage'].mask(~df['Stage'].isin(['Paid', 'Delivered'])) \ .groupby(df['Category']).ffill() \ .c...
python|pandas|dataframe
1
359,163
70,659,778
Pandas - Delete multiple columns based on column position
<p>I have a dataframe with an index, and with 19 columns that don't have column names. I want to keep the 3rd, 4th, 5th and 7th columns and drop the rest. I've tried this that is dropping the columns and leaving the 4 I need, but is there a cleaner way?</p> <pre><code>ds_drop1 = df.drop(df.columns[[0, 1]], axis = 1, in...
<p>In your case doing <code>numpy.r_</code> with <code>iloc</code>(Adding <code>copy</code> for prevent the future copy warning)</p> <pre><code>#import numpy as np out = df.iloc[:,np.r_[3:6,7]].copy() </code></pre>
pandas
1
359,164
70,551,922
Converting for loop to numpy calculation for pandas dataframes
<p>So I have a python script that compares two dataframes and works to find any rows that are not in both dataframes. It currently iterates through a for loop which is slow.</p> <p>I want to improve the speed of the process, and know that iteration is the problem. However, I haven't been having much luck using various ...
<p>It's still a unclear what you want without providing examples of each dataframe. But if you want to test unique IDs in differently named columns in two different dataframes, try an approach like this.</p> <p>Find the IDs that exist in the second dataframe</p> <pre><code>test_ids = df2['cola_id'].unique().tolist() </...
python|pandas|numpy
0
359,165
70,680,109
Access Pandas Dataframe based on current (now) minute
<p>I have a Dataframe with one row per minute. I need to access the row corresponding to the current minute</p> <pre><code> value 2022-01-12 11:27:24+01:00 a 2022-01-12 11:28:41+01:00 b 2022-01-12 11:29:36+01:00 c 2022-01-12 11:30:11+01:00 d 2022-01-12 11:31:03+01:00 e 2022-...
<p>How to select row(s) based on the current minute? Make sure to set the condition correctly (as intended), e.g. by flooring the current time to the minute (clip to minute resolution). Ex:</p> <pre><code>import pandas as pd import numpy as np tz = 'Europe/Rome' now = pd.Timestamp.now(tz) print(now) # 2022-01-12 12:11...
python|pandas|datetime|utc
2
359,166
70,605,178
Finding intersection between two dataframes iteratively
<p>I have the following two dataframes and would like to find their intersection.</p> <pre><code>df1 = pd.DataFrame({&quot;0&quot;: [1524, 8788, 9899, 27172], &quot;1&quot;: [1333, 4476, 78783, 90832], &quot;2&quot;: [2021, 2022, 34522, 38479]}) print(df1) 0 1 2 0...
<p>Given</p> <p><code>df1</code>:</p> <pre><code> 0 1 2 0 1524 1333 2021 1 8788 4476 2022 2 9899 78783 34522 3 27172 90832 38479 </code></pre> <p>and <code>df2</code>:</p> <pre><code> 0 0 [1123, 2021, 1333, 6636] 1 [1245, 2022, 4477, 0] 2 [1524...
python|pandas|list|dataframe|intersection
2
359,167
70,720,387
operating on array with condition
<p>Consider the following code,</p> <pre><code>import numpy as np xx = np.asarray([1,0,1]) def ff(x): return np.sin(x)/x # this throws an error because of division by zero # C:\Users\User\AppData\Local\Temp/ipykernel_2272/525615690.py:4: # RuntimeWarning: invalid value encountered in true_divide # return np.sin...
<p>For conditional operations as you describe numpy has the <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer">numpy where</a> function.</p> <p>You can do</p> <pre><code>np.where(x==0, 1, np.sin(x)/x) </code></pre>
python-3.x|numpy
1
359,168
70,669,161
Add a moving formula to excel using python
<p>I have a df that looks like this:</p> <pre><code> 2021-12-06 2021-12-13 2021-12-20 2021-12-27 A 10 20 30 40 B 20 50 40 90 C 30 </code></pre> <p>To replicate :</p> <pre><code>df = pd.DataFrame(index = ['A','B','C'], columns = pd.t...
<p>I ended up using <code>openpyxl</code> as <a href="https://stackoverflow.com/users/4238408/quang-hoang">Quang Hoang</a> suggested.</p> <pre><code>wb = openpyxl.load_workbook(filename = 'file.xlsx') ws = wb['sheet_name'] for cell in ws[1]: try: if '2021-12-31' &lt;= pd.to_datetime(cell.value): ...
python|excel|pandas
0
359,169
70,432,925
sql: select list of columns
<p>I want to pass an str or list argument and want that sql knows how to treat it. Example of <code>list_col='date1, date2, date3, date4'</code> and at the end i want to have dataframe date1, date2, date3, id</p> <pre><code>query = &quot;&quot;&quot; SELECT {list_col} AT TIME ZONE 'Europe/Paris' as {list_col}, {tab...
<p>As already noted this is not doable in a way you suggested because both <code>AT TIME ZONE</code> and <code>AS</code> clauses should appear along with each column. I would suggest doing something like this.</p> <pre><code>query = &quot;&quot;&quot; SELECT {date_cols_as_tz}, {table}.{id} FROM {table} ORD...
python|sql|pandas
1
359,170
42,635,162
How to identify a specific occurrence across two rows and calculate the count
<p>Let's say I have these 2 <code>pandas</code> dataframes:</p> <pre><code>id | userid | type 1 | 20 | a 2 | 20 | a 3 | 20 | b 4 | 21 | a 5 | 21 | b 6 | 21 | a 7 | 21 | b 8 | 21 | b </code></pre> <p>I want to obtain the number of times 'b follows a' for each user, and obta...
<p>You can use <code>shift()</code> to check if <code>a</code> is followed by <code>b</code> with vectorized <code>&amp;</code> and then count the trues with a <code>sum</code>:</p> <pre><code>df.groupby('userid').type.apply(lambda x: ((x == "a") &amp; (x.shift(-1) == "b")).sum()).reset_index() #userid type #0 20 ...
python|pandas|dataframe
2
359,171
42,890,999
Merging two dataframes with a list inside one of the columns
<p>I am trying to merge multiple dataframes to find users that are in groups they arent supposed to be. </p> <p>DF1</p> <pre><code> AccountType Name SID disabled compname localaccount lockout passwordchangeable passwprdexpires passwordrequired status ...
<p>IIUC you can do it this way:</p> <pre><code>In [49]: d1 = df1[['Name','compname']] ...: d2 = df2[['groupname','GroupSID','members','status']] ...: ...: lst_col = 'members' ...: ...: pd.DataFrame({ ...: col:np.repeat(d2[col].values, d2[lst_col].str.len()) ...: for col in d2.colu...
python|python-3.x|pandas
1
359,172
42,744,241
Is it possible to have a function that gets any data frame and any column as its inputs using Pandas in Python?
<p>Imagine we have a dataframe like this:</p> <pre><code> my_df&gt;&gt; column_1 column_2 column_3 column_4 0 0.276162 0.552951 0.866023 0.571535 1 0.112933 0.549487 0.626958 0.988705 2 0.916932 0.561641 0.220696 0.545019 </code></pre> <p>Can I have a function that can get any dataframe like this ...
<p>Actually you don't even need such a function - you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.eval.html" rel="nofollow noreferrer">DataFrame.eval()</a> function:</p> <p>Data:</p> <pre><code>In [6]: df Out[6]: column_1 column_2 column_3 column_4 0 0.276162 0.552951 0.8660...
python|pandas
1
359,173
42,624,956
Replace variable names in column
<p>I have a column with names and I want to group into three different names shown in the column name Group</p> <pre><code>Col1 Group Gbx stage PS - 1st Gbx PS stage - 1st Gbx 2nd - 2nd 2nd Gbx - 2nd Gbx Iss - 2nd stage Gbx PS - 1st Gbx 3rd Hss - 3rd HSS Gbx - 3rd Gbx HSS - 3rd </code...
<p>I think you can use double <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>str.contains</co...
regex|pandas|lambda
0
359,174
42,613,942
Gradients are zeros
<p>I try to learn a network but always get a zeros gradient. I am really confused about it and I don't have any ideas whit it happens.</p> <p>I have an input data in format <em>(batch_size, 120, 10, 3)</em> and after six layer <em>(conv1 - pool1 - conv2 - pool2 -fc1 - fc2)</em> I expect output of size 1x1 (0 or 1). Al...
<p>Your learning rate is really small consider increasing it to 0.01 and then decreasing it over time.</p>
python|tensorflow|gradient-descent
0
359,175
42,720,528
Getting Started with TensorFlow documentation
<p>I am not sure if this is the right place to raise this. I was following <a href="https://www.tensorflow.org/get_started/get_started" rel="nofollow noreferrer">https://www.tensorflow.org/get_started/get_started</a> and came across the following sample code:</p> <pre><code>W = tf.Variable([.3], tf.float32) b = tf.Va...
<p>In this code snippet, 'x' is the input and 'y' serves the purpose of label as you seem to already understand.</p> <p>'W' and 'b' are variables that the program should 'learn' such that when x=[1,2,3,4], y ends up as [0,-1,-2,-3].</p> <p>The values of 'W' and 'b' you see are the initial values. Not included in this...
tensorflow
0
359,176
42,715,147
Compress a TensorFlow model
<p>Is there a ready-to-use tool that can <a href="https://arxiv.org/pdf/1510.00149v5.pdf" rel="noreferrer">compress</a> the trained TensorFlow weights ?</p> <p>This kind of tools exists for Caffe models (<a href="https://github.com/yuanyuanli85/CaffeModelCompression" rel="noreferrer">link</a>)</p>
<p>You can at least <a href="https://www.tensorflow.org/performance/quantization" rel="nofollow noreferrer">quantize the network</a> with tensorflow. You'll find <a href="https://www.tensorflow.org/mobile/optimizing" rel="nofollow noreferrer">here</a> other tools to reduce the graph size to put it on mobile.</p>
tensorflow
0
359,177
42,684,808
Pandas dataframe update column
<p>I have the following pandas dataframes:</p> <pre><code>&gt;&gt;&gt; df1 Col1 Col2 Col3 0 A a 2017-02-28 1 B b 2017-02-28 2 C c 2017-03-08 3 D d 2017-02-28 &gt;&gt;&gt; df2 Col1 Col2 Col3 0 B b 2017-03-05 1 C c 2017-03-05 2 D d 2017-03-05 </code></pre> <p>a...
<p>It looks like you are used to using R. The syntax to select a column in Pandas is either <code>df.Col1</code> or <code>df['Col1']</code>. </p> <p>You can concatenate the two dataframe, sort by <code>Col3</code>, then drop the duplicates of the combination of <code>['Col1','Col2']</code>. You need to convert <cod...
python|pandas|dataframe
0
359,178
42,751,825
Pandas new dataframe by rolling the rows
<p>I'm trying to create a new pandas dataframe by rolling the row values in a window. i.e </p> <pre><code>A R N D C Q -1 -2 -3 -3 -1 -2 -1 -2 -3 -3 -1 -2 -1 -2 -3 -3 -1 -2 -1 -2 -3 -3 -1 -2 </code></pre> <p>to something like this:</p> <pre><code>A1 R1 N1 D1 C1 Q1 A2 R2 N2 D2 C...
<p>You can use numpy indexing to accomplish this:</p> <pre><code>In [1]: import pandas as pd ...: import numpy as np ...: import string ...: In [2]: abc = list(string.ascii_letters.upper()) ...: df = pd.DataFrame(dict(a=abc, b=abc[::-1])) ...: df.head() ...: Out[2]: a b 0 A Z 1 B Y 2 C X...
python|pandas|dataframe
1
359,179
42,806,690
Is it possible to have an alias for a Tensorflow node?
<p>I have a complex net for which I have created a very simple class for inferencing the model once it is serialised into a frozen graph file.</p> <p>The thing is that in this file I need to load the variable with his namespace which may end up depending on how I have structured the model. In my case ends up like this...
<p>You can use <code>tf.identity</code> for the output.</p> <pre><code>output_node = sess.graph.get_tensor_by_name("create_model/mymodelname/output_node:0") tf.identity(output_node, name="output_node") </code></pre> <p>will create a new passthrough op that has the name "output_node" and will get its value from the no...
variables|namespaces|tensorflow|alias|serving
3
359,180
42,868,443
List of lists of lists to pandas dataframe
<p>I have a list of lists of lists. The outer-most list is of length 20 (separate categories). The middle lists are of variable length (list of timestamps). The inner lists are of length 5 (splitting each timestamp). For example:</p> <pre><code>sTimestamps[0][:5][:] = [['Tue', 'Feb', '7', '10:06:30', '2017'], ['Tue...
<pre><code>sTimeStamps = [ [['Tue', 'Feb', '7', '10:06:30', '2017'], ['Tue', 'Feb', '7', '10:07:06', '2017'], ['Tue', 'Feb', '7', '10:07:40', '2017'], ['Tue', 'Feb', '7', '10:12:36', '2017'], ['Tue', 'Feb', '7', '10:13:24', '2017']], [['Tue', 'Feb', '7', '10:06:30', '2017'], ['Tue', 'Fe...
python-3.x|pandas|dataframe|nested-lists
7
359,181
42,729,986
Installing Pandas on MacOs. Permission Error
<p>I am trying to pip install pandas on a mac. I have python 3.6 installed. </p> <p>When I pip install in the terminal I get the following error:</p> <pre><code>Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main stat...
<p>You might have already noticed, Mac come with a built in Python, python 2.7. If you read your traceback: <code>/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py</code> it's pointing to the 2.7 dir. this dir is in the Library folder so you don't have permission to install to it. </p> <p>But yo...
python|macos|python-3.x|pandas|pip
0
359,182
42,935,973
I am getting error with im.show()
<p>I am trying to save a gray scale image (256,256,1) and show it in the output. </p> <pre><code>im = data.astype(np.uint8) print im.shape im = np.transpose(im, (2,1,0)) print im.shape im.show() </code></pre> <p>However, I am getting the following error:</p> <pre><code>(256, 256, 1) Traceback (most recent call last...
<p>Note that <code>im.show()</code> does not exist, but it might just be a typo in the question. The real problem is the following:</p> <p>Matplotlib's <code>pyplot.imshow</code> can plot images of dimension <code>(N,M)</code> (grayscale) or <code>(N,M,3)</code> (rgb color). Your image is <code>(N,M,1)</code>; we the...
python|python-2.7|python-3.x|numpy|matplotlib
5
359,183
42,913,814
ValueError when reading in fixed width file using pd.read_fwf - number of expected fields not matching number seen
<p>My current code contains the following:</p> <pre><code>columns=[(0,4), (4,8), (8,9), (9,10), (20,22), (23,24)] header=['var1','var2','var3','var4','var5','var6'] file=pd.read_fwf('file_name.gz', compression='gzip', colspec=columns, names=header) </code></pre> <p>When I run I get the following : ValueError: Expec...
<p>as @StephenRauch stated in his comment (while I was sluggishly compiling this answer)</p> <pre><code>from io import StringIO import pandas as pd txt = """02011602160108 26 312870000""" columns=[(0,4), (4,8), (8,9), (9,10), (20,22), (23,24)] header=['var1','var2','var3','var4','var5','var6'] pd.read_fwf(StringIO(...
python|pandas
1
359,184
42,904,715
Is there a better way to compute the average of a row in a pandas DataFrame?
<p>I have a DataFrame with <strong>"n"</strong> rows and <strong>"m"</strong> columns and I want the average of the <strong>first</strong> row and <strong>m-1</strong> columns.</p> <pre><code> c1 c2 c3 . . . . . . . cm r1 r2 r3 . . . . rn </code></pre> <p>I am currently summing the entire...
<p>I believe something like </p> <pre><code>df[df.columns[:-1]].mean(axis=1) </code></pre> <p>will do the trick, given you have this flat dataframe structure.</p> <p>Here, <code>df.columns[:-1]</code> returns an Index pointing to all the columns except the last one.</p> <p><em>UPD</em> Pardon, that will give you al...
python|pandas
2
359,185
43,004,040
I am trying to fill all NaN values in rows with number data types to zero in pandas
<p>I have a DateFrame with a mixture of string, and float rows. The float rows are all still whole numbers and were only changed to floats because their were missing values. I want to fill in all the NaN rows that are numbers with zero while leaving the NaN in columns that are strings. Here is what I have currently....
<p>Use either <code>DF.combine_first</code> (does not act <code>inplace</code>):</p> <pre><code>df.combine_first(df.select_dtypes(include=[np.number]).fillna(0)) </code></pre> <p>or <code>DF.update</code> (modifies <code>inplace</code>):</p> <pre><code>df.update(df.select_dtypes(include=[np.number]).fillna(0)) </cod...
python|pandas|missing-data
5
359,186
42,727,990
Speed up to_sql() when writing Pandas DataFrame to Oracle database using SqlAlchemy and cx_Oracle
<p>Using pandas dataframe's to_sql method, I can write a small number of rows to a table in oracle database pretty easily:</p> <pre><code>from sqlalchemy import create_engine import cx_Oracle dsn_tns = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=&lt;host&gt;)(PORT=1521))\ (CONNECT_DATA=(SERVER=DEDICATED)(SERVICE...
<p>Pandas + SQLAlchemy per default save all <code>object</code> (string) columns as <strong>CLOB</strong> in Oracle DB, which makes insertion <strong>extremely</strong> slow.</p> <p>Here are some tests:</p> <pre><code>import pandas as pd import cx_Oracle from sqlalchemy import types, create_engine ##################...
oracle|performance|pandas|dataframe|sqlalchemy
44
359,187
42,818,819
What is the difference between tensorflow conv2d_transpose and conv2d_backprop_filter?
<p>Can someone please explain in simple terms and examples on how these work after performing the conv2d forward pass.</p> <p>Let me add to this question - What is the difference between conv2d_backprop_filter and tf.nn.conv2d_backprop_input?</p>
<p>For an explanation of conv2d_transpose I would look at other stack overflow questions such as this one: <a href="https://stackoverflow.com/questions/39373230/what-does-tensorflows-conv2d-transpose-operation-do">conv2d_transpose</a></p> <p>As for conv2d_backprop_filter: this is what is computed during backpropagatio...
tensorflow|convolution|backpropagation|deconvolution
1
359,188
42,887,980
pandas.read_csv gives FileNotFound error inside a loop
<p><code>pandas.read_csv</code> is working properly when used as a single statement. But it is giving <code>FileNotFoundError</code> when it is being used inside a loop even though the file exists.</p> <pre><code>for filename in os.listdir("./Datasets/pollution"): print(filename) # To check which file is under pro...
<p><code>os.listdir("./Datasets/pollution")</code> returns a list of files without a path and according to the path <code>"./Datasets/pollution"</code> you are parsing CSV files NOT from the current directory <code>"."</code>, so changing it to <code>glob.glob('./Datasets/pollution/*.csv')</code> should work, because <...
pandas|python-3.6
2
359,189
42,609,382
Replace a value within for loop with the value of the cell of the following row of a data frame
<pre><code>result = [] EB = 0.0 i=int() for i in df['A']: EB = max(EB + i , 0) result.append(EB) df['D'] = result </code></pre> <p>The input df is:</p> <pre><code> A | B | C -0,20 | 0,40 | 0,50 0,54 | 0,20 | 0,80 -0,18 | 0,80 | -4,00 *0,00 | 0,00 | 0,00* 0,10 | 0,90 | 0,60 </code></pre> ...
<p>Try this:</p> <pre><code>result = [] EB = 0.0 for t in df.assign(S=df.sum(1), next_B=df.B.shift(-1)).itertuples(): if t.S == 0: EB = t.next_B else: EB = max(EB + t.A, 0) result.append(EB) df['D'] = result </code></pre> <p>Result:</p> <pre><code>In [238]: df Out[238]: A B C ...
python|pandas|dataframe
0
359,190
42,928,438
Are Topic Distributions of Documents in LDA Space Probabilistic?
<p>I know that the creation of LDA models is probabilistic, and that two models trained under the same parameters on the same corpus will not necessarily be identical. However, I'm wondering if the topic distribution of a document fed into an LDA model is also probabilistic. </p> <p>I have an LDA model as presented he...
<p>Try setting <code>random_state</code> to the same state when you train a LDA model.</p> <pre><code>lda = models.LdaMulticore(corpus=corpus, id2word=dictionary, num_topics=numTopics, passes=10, random_state=0) </code></pre> <p>When LDA initializes, and during inference, it uses randomized matrices that introduces n...
python|numpy|gensim|lda
0
359,191
42,867,239
How to know the figure reference of a chart done in python with pandas?
<p>I need to iterate over several figures done with matplotlib. Only one of the figures is done "directly" with Pandas Visualization. In the code below will show an example with just 2 figures, one done with matplotlib API and one done directly with Pandas. </p> <pre><code>import numpy as np import pandas as pd impo...
<p>You can use <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.gcf" rel="nofollow noreferrer"><code>plt.gcf()</code></a> to get the current figure after plotting with Pandas:</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt dates = pd.date_range('20000101', ...
python|pandas|matplotlib
3
359,192
42,788,982
Find the time that 90% of tickets are processed in?
<p>My boss wants metrics on our ticket processing system, and one of the metrics he wants is "the 90% time" which he defines as the time it takes 90% of the tickets to be processed. I guess he's considering that 10% are anomalous can be ignored. I would like this to at least approach some statistical validity. So I've ...
<p>Percentiles are a statistically perfectly valid approach. They are used to provide robust descriptions of the data. For example the 50% percentile is the median, and box-plots typically show the 25%, 50%, and 75% percentiles to give an idea of the range covered by data.</p> <p>The 90% percentile can be seen as a ra...
python|numpy|statistics
2
359,193
42,947,297
Tuple key Dictionary to Table/Graph 3-dimensional
<p>I have a dictionary like this:</p> <pre><code>dict = {(100,22,123):'55%',(110,24,123):'58%'} </code></pre> <p>Where, for example, the elements of the tuple are (x,y,z) and the value is the error rate of something... I want to print that dictionary but I'm not very clear how to do it or in what format to do it (whi...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html" rel="nofollow noreferrer"><code>Series</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>reset_index</code></a>, last only set...
python|pandas|dictionary|plot|graph
0
359,194
42,776,511
Change rows order pandas data frame
<p>I have the following data frame in <code>pandas</code> in <code>python3</code>:</p> <pre><code> +------------------------------+ | total_sum | percent_of_total | +--------------+------------------------------+ | Group | | | +--------------+------------...
<p>Per <a href="https://stackoverflow.com/users/1865106/ssc">SSC</a> in the comments:</p> <hr> <p>Try using <code>.reindex</code>:</p> <pre><code>.reindex(['11-', 'Just 12', 'Some College', 'Bachelor+']) </code></pre> <p>The <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.htm...
python|pandas|sorting|jupyter-notebook
10
359,195
42,941,000
What's the best Pandas apply / loop method in this case?
<p>I'm transforming some applicant transactional data, and I need to create a new flag column (labeled as "DESIRED FLAG" in my example). However, I can't figure out the right looping/apply method as there can be so many different variations in the logic below. </p> <p>In a perfect world, the sequential applicant proce...
<p>I think the following code solves your problem</p> <pre><code>import pandas as pd data = {'Employee ID': ["100","100", "100", "100","100","100","100","100","100","100","200", "200", "200","200","200","200","200","300","300", "300", "300","300","300","300"], 'Completed On Date': ["2009-01-01","2010-01-01","...
python|python-3.x|loops|pandas
2
359,196
42,644,079
How to include the counts for each character while removing the duplicates using itertools.groupby
<p>I have the following code:</p> <pre><code>df= pd.DataFrame(data=all_r_1.to_dataframe().groupby(['user_id'])['type'].sum()).reset_index() userid | type 20 | aab 21 | ababb </code></pre> <p>To remove the duplicates from the strings in the <code>type</code> column, I have this code:</p> <pre><code>df['type'...
<p><code>itertools.groupby</code> stores the actual groups so you can access this as follows:</p> <pre><code>df['type'] = df['type'].apply(lambda x: ''.join('{}{}'.format(ch,len(list(group))) for ch, group in itertools.groupby(x))) </code></pre>
python|string|pandas|itertools
1
359,197
42,714,660
How to use python-colormath's Delta E function with pandas Series
<p>I am using python-colormath in order to calculate the color difference delta E 2000 between a list of Lab colors. </p> <p>I have two pandas dataframe (df1 and df2), in each dataframe I recorded the Lab values.</p> <p>here is my code: </p> <pre><code>L1 = df1.L a1 = df1.a b1 = df1.b L2 = df2.L a2 = df2.a b2 = df2...
<p>It seems that <code>python-colormath</code> does not support the use of anything that can't be converted to a <code>float</code> as input to its <code>LabColor</code> objects.</p> <p>If you want to keep using <code>python-colormath</code> you could loop over the series objects instead of using the function directly...
python|pandas|colors
0
359,198
42,931,068
Pandas.read_csv() MemoryError
<p>I have a 1gb csv file. The file has about 10000000(10 Mil) rows. I need to iterate through the rows to get the max of a few selected rows(based on a condition). The issue is reading the csv file.</p> <p>I use the Pandas package for Python. The read_csv() function throws the MemoryError while reading the csv file. ...
<p>Pandas read_csv() has a low memory flag.</p> <pre><code>tp = pd.read_csv('capture2.csv',low_memory=True, ...) </code></pre> <p>The low_memory flag is only available if you use the C parser</p> <blockquote> <p>engine : {‘c’, ‘python’}, optional</p> <p>Parser engine to use. The C engine is faster while the python eng...
python|csv|pandas|numpy|large-files
1
359,199
42,793,027
"Quantize" Tensorflow Graph to float16
<p>How do you convert a Tensorflow graph from using <code>float32</code> to <code>float16</code>? Currently there are graph optimizations for quantization and conversion to eight bit ints. </p> <p>Trying to load <code>float32</code> weights into a <code>float16</code> graph fails with:</p> <pre><code>DataLossError (s...
<p>I think my solution is definitely not the best and not the one which is the most straight forward, but as nobody else posted anything:</p> <p>What I did was training the network with full precision and saved them in a checkpoint. Then I built a copy of the network setting all variables desired to a dtype of tf.floa...
tensorflow
8