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
352,900
61,145,991
How to split numpy array into numpy arrays based on columns?
<p>I want to split numpy array based on columns if all values of column are zero. If sequence of columns has only 0 like first two columns of sample array, this group should discard.</p> <p>Is there any efficient solution?</p> <p>Sample input numpy array:</p> <pre><code>[[0. 0. 0. 255. 0. 255. 0. 0. ...
<p>One solution is to leverage the <code>scipy.ndimage</code> library to label columns with any non-zero elements, then split your array using those labels.</p> <p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.label.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/scipy/referenc...
python|arrays|numpy|split
2
352,901
61,137,390
Python: Dictionary to pandas dataframe
<p>I would like to change the dictionary to pandas dataframe.</p> <pre><code>data = {u'Diluted Normalized EPS': [{u'date': u'2020-01-03', u'value': u'-0.446810'}, {u'date': u'2019-10-04', u'value': u'-0.765540'}, {u'date': u'2019-06-28', u'value': u '-0.574240'}, {u'date': u'2019-03-29', u'value': u'-2.063700'}, {u'da...
<p>Use nested dictionary comprehension with <code>DataFrame</code> constructor:</p> <pre><code>d = {k:{x['date']: x['value'] for x in v} for k, v in data.items()} df = pd.DataFrame(d).rename_axis('date').reset_index() print(df) date Diluted Normalized EPS Net Income Before Extra. Items 0 2020-01-03 ...
python|pandas|dictionary
3
352,902
60,958,134
weird problem with Pytorch's mse_loss function
<pre><code>Traceback (most recent call last): File "c:/Users/levin/Desktop/programming/nn.py", line 208, in &lt;module&gt; agent.train(BATCHSIZE) File "c:/Users/levin/Desktop/programming/nn.py", line 147, in train output = F.mse_loss(prediction, target) File "C:\Users\levin\Anaconda3\lib\site-packages\tor...
<p>As stated in a comment the error due to either target of input to be <code>None</code> and is not related to the <code>size()</code> attribute.</p> <p>The problem is probably at this line:</p> <pre><code>target = torch.tensor(reward).grad_fn </code></pre> <p>Here you convert reward to a new Tensor. However, a Ten...
python|pytorch
0
352,903
60,895,313
Pandas Dataframe: New Column that uses Country if Province is empty, else use the Province
<p>The meat of what I'm trying to do can be seen at the bottom. Here's the dataset I'm using: <a href="https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv" rel="nofollow noreferrer">https://github.com/CSSEGISandData/COVID-19/blob/m...
<p>This worked:</p> <pre><code>def names_column(frame, lst): #Makes a new column called Name for i in range(len(frame)): if type(frame['Province/State'][i]) is str: lst.append(frame['Province/State'][i]) else: lst.append(frame['Country/Region'][i]) frame['Name'] = df(lst...
python|pandas|dataframe
-1
352,904
61,144,235
How to remove substring after a specific character in a list of strings in Python
<p>I have a list of string labels. i want to keep the substring of very element before the second "." and remove all characters after the second ".". I found post that show how to do this with a text string using the split function. However, the list datatype does not have a split function. The actual data type is a p...
<p>Here as a oneliner:</p> <pre><code>desired_list = [ s[:s.find(".",s.find(".")+1)] for s in current_list] </code></pre>
python|numpy|replace|split
1
352,905
60,767,757
Extract year from datetime64[ns] in Pandas but not int type
<p>Given a date columns with type <code>datetime64[ns]</code>, I want to extract <code>year</code> from them:</p> <pre><code>array(['1998-11-01T00:00:00.000000000', 'NaT', '2009-10-01T00:00:00.000000000', '2009-10-02T00:00:00.000000000', '2009-10-03T00:00:00.000000000'], dtype='datetime64[ns]') </code><...
<p>No recommend but match the expected output , since the column now have mix datatype</p> <pre><code>pd.to_datetime(df['date'], errors='coerce').dt.year.astype(object) 0 1998 1 NaN 2 2009 3 2009 4 2009 Name: date, dtype: object </code></pre>
python|pandas|datetime
2
352,906
61,155,095
Why can I use square brackets to refer to both column labels and row indices when using a pandas dataframe?
<p>I have a dataframe (<code>df</code>) with dates as index and column labels. I am able to get a slice of the dataframe by using <code>df['2008':]</code> to refer to the index, but I always assumed that you had to specify the columns first, e.g. <code>df[:]['2008':]</code>, and I just want to understand why this is th...
<p>Interesting question, let's create a simple DataFrame to do some experiments:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({'2008': [1, 3], 'column 2': [2, 4]}, index = ['2007', '2008']) df </code></pre> <pre class="lang-py prettyprint-override"><cod...
python|pandas|dataframe
0
352,907
61,089,528
tensorflow dataset from_generator() out of range error
<p>I'm trying to use <code>tf.data.Dataset.from_generator()</code> to generate training and validation data.</p> <p>I have my own data generator which does feature preparation on the fly:</p> <pre><code>def data_iterator(self, input_file_list, ...): for f in input_file_list: X, y = get_feature(f) ...
<p>I added a while True in my own generator so that it never run out and I'm not getting error any more:</p> <pre><code>def data_iterator(self, input_file_list, ...): while True; for f in input_file_list: X, y = get_feature(f) yield X, y </code></pre> <p>However, I don't know why <...
python|tensorflow|keras|generator|tensorflow-datasets
1
352,908
61,072,688
How to change python script to .exe with user defined input and output paths in python
<p>I have python script , i want to change this simple script to .exe file with user defined input and output path .</p> <p>in below script 'csv' is input folder and contain multiple txt files , </p> <pre><code>import pandas as pd import numpy as np import os for file in os.listdir('csv/'): filename = 'csv/{}'...
<p>A simple way you can do this with cx_freeze is as follows:</p> <ol> <li><p>conda install -c conda-forge cx_freeze, or pip install cx_freeze to your env with numpy and pandas</p></li> <li><p>Make a folder called dist for your new .exe </p></li> <li><p>Save the code below as csv_thing.py, or whatever you want it to b...
python-3.x|pandas|numpy|exe
0
352,909
61,053,701
How do you edit a CSV row in Python 3?
<p>Can anyone please help me fix this problem (in python 3):</p> <pre><code>def change(username, new_password): filename = 'user.csv' tempfile = NamedTemporaryFile(delete=False) with open(filename, 'rb') as csvfile, tempfile: reader = csv.DictReader(csvfile) fieldnames = ['Name', 'DOB', 'P...
<p>You are reading the file as "rb", which means that it is read in binary mode. Try setting it to just "r". Furthermore, DictWriter does not write to disk automatically, so remember to save it as well.</p>
python|python-3.x|pandas|csv
0
352,910
61,091,031
Numpy __isub__ changing global variable
<p>I've been struggling with some operations over NumPy arrays and functions in a recent script. I've finally discovered what seems to be the error: NumPy __isub__. </p> <p>Heres a example:</p> <pre class="lang-py prettyprint-override"><code>def test(apocalypse): apocalypse = apocalypse - 3 return apocalypse ...
<p>Posting an answer in case anybody needs more details than the <a href="https://stackoverflow.com/questions/61091031/numpy-isub-changing-global-variable#comment108078954_61091031">hpaulj</a> and <a href="https://stackoverflow.com/questions/61091031/numpy-isub-changing-global-variable#comment108078854_61091031">Willem...
python-3.x|numpy|namespaces
0
352,911
60,817,825
Generating data for image processing
<p>I am new to Deep learning and I am working on a hobby project related to soccer sports analytics. I want to use soccer videos and convert them on to a 2D map. I have broken down the process into smaller steps. The first step is to be able to detect players and the soccer ball. </p> <p>I am thinking of starting with...
<p>This is more likely for long-run development, but as I already wrote a similar answer so posting it here.</p> <ol> <li>First create a dataset of the players with bounding boxes (around 500-1k, then use augmentation to make a few more thousands). You can use the following tools for annotating:</li> </ol> <p><a href...
tensorflow|deep-learning|object-detection
1
352,912
61,107,067
Fit nonlinear regression pandas
<p>I have a dataset <a href="https://i.stack.imgur.com/sU58j.png" rel="nofollow noreferrer">Coronavirus cases per day with dates</a> And then I made this plot, Cases vs Days, which is a curved line. <a href="https://i.stack.imgur.com/1BLig.png" rel="nofollow noreferrer">Graph</a></p> <p>I would like to fit a curved lin...
<p>If you are looking to fit higher order polynomials, you are typically looking either for <a href="https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html" rel="nofollow noreferrer">spline fitting</a> or <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html" rel="nofollow noref...
python|pandas|machine-learning|regression|non-linear-regression
2
352,913
60,861,676
Easy way to do nd-array contraction using advanced indexing in Python
<p>I know there must be an elegant way to do this using advanced indexing, I just can't figure it out.</p> <p>Suppose I have the (2,3,4) array </p> <pre><code>x = array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23...
<pre><code>In [490]: x[y,:,np.arange(4)] Out[490]: array([[12, 16, 20], [ 1, 5, 9], [14, 18, 22], [15, 19, 23]]) </code></pre> <p>We need to transpose this. With a mix of basic and advanced indexing, the slice dimension has been...
arrays|numpy|advanced-indexing
1
352,914
60,927,196
Searching for exact whole words in Pandas Dataframe from a List
<p>I know this issue has been asked a million times but I am still having challenges with it. I have a list of exact whole words I want to search in a pandas dataframe.</p> <p>Counties_List = ['MOMBASA' ,'KWALE' ,'LAMU']</p> <pre><code>df2 = df1[df1['County/ Sub-County'].str.contains('|'.join(Counties_List))] </code>...
<p>It seems you want an exact match of the items in <code>Countries_List</code> in your <code>Countey/ Sub-County</code> column. You may use</p> <pre><code> df2 = df1[df1['County/ Sub-County'].str.contains(r'^(?:{})$'.format('|'.join(Counties_List)))] df2 = df1[df1['County/ Sub-County'].str.contains(rf'^(?:{"|".join(...
python|regex|pandas
1
352,915
60,939,262
How to merge Multi Index in pandas with different index levels?
<p>I have two pandas DataFrames :</p> <pre><code> df1 = pd.DataFrame({'user_id':['0','0','1','1','2','3','3'], 'friend_id':['1','2','3','2','4','4','5'], 'date_sent':['01-01-2020','01-01-2020','01-02-2020','01-03-2020','01-02-2020','01-03-2020','01-02-2020'], 'date_a...
<p>See comments in answers for key steps using reset_index(), renaming the column and doing another groupby. </p> <pre><code>import pandas as pd df1 = pd.DataFrame({'user_id':['0','0','1','1','2','3','3'], 'friend_id':['1','2','3','2','4','4','5'], 'date_sent':['01-01-2020','01-01...
python|pandas|dataframe|multi-index
0
352,916
60,891,956
Convert Data Frame Start/Stop times into percentage bins
<p>I want to convert a dataframe of start/end (or on/off) times into a second dataframe with percentages of total 'on time' per some arbitrary time period. In this case, that time period is an hour. I've written a very inefficient solution involving loops, and am looking for a better solution.</p> <pre><code>df1 | St...
<p>One way to deal with this, if the data is not too big, is to resample on lower frequency and groupby:</p> <pre><code>s = pd.concat([pd.Series(pd.date_range(a,b, freq='S')) for a,b in zip(df1.Start, df1.End)], ignore_index=True ) s.groupby(s.dt.floor('H')).count()/3600 ...
python|pandas|dataframe|time-series
0
352,917
60,771,377
Python Pandas CSV filter a column with its values N first char
<p>i'm using pandas csv to work with a huge csv file, basically i have a python script with some args that are filters criteria, one of them is a string that represents a serie of digits (eg: 83351828) and then export the result to a new csv file. What I want to do is to be able to filter this column by its 4 first cha...
<p>I think you need indexing with <code>str</code> for get first 4 letters, also <code>0</code> should be omitted:</p> <pre><code>chunk['Directory Number 1'].str[:4] </code></pre> <p>If values are not strings add <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.astype.html" rel="nofoll...
python|pandas|csv
3
352,918
60,933,592
Cythonize error: failed with exit status 2. numpy and pyvista
<p>I'd like to Cythonize the following code, but I receive an error.</p> <pre><code>import numpy as np cimport numpy as np import pyvista as pv from mesh_funcs import * cimport cython from libcpp cimport bool #import matplotlib.pyplot as plt #Getting mesh points from pyvista unfortunately with a for loop cdef class...
<p>Since you're running:</p> <pre><code>from libcpp cimport bool </code></pre> <p>You should change your language from the default <code>c</code> to <code>c++</code> in <code>setup.py</code>:</p> <pre class="lang-py prettyprint-override"><code>from setuptools import setup from Cython.Build import cythonize import nu...
python|numpy|cython|cythonize|pyvista
0
352,919
60,981,881
Use newly sampled validation examples with TensorFlow Keras fit when using `validation_steps`?
<p>TensorFlow's Keras <code>Model.fit</code> method has two parameters to limit the number of steps during a training epoch: <code>steps_per_epoch</code> for the number of training steps and <code>validation_steps</code> for the number of validation steps. However, a major difference between these two arguments (beside...
<p>It depends on which kind of generator you're using. </p> <p>If it's a <code>keras.utils.Sequence</code> (the standard Keras generator that you get with <code>ImageDataGenerator</code> and methods like <code>flow_from_dataframe</code>, <code>flow</code> etc.), these have a <code>len</code> property and can have thei...
python|tensorflow|keras
1
352,920
71,593,785
GeoPandas.GeoDataFrame: type "geometry" does not exist
<p>Ubuntu 20.04.3 LTS (WSL2)</p> <p>fiona 1.8.21 <br /> geopandas 0.10.2 <br /> geopandas-base 0.10.2 <br /> geopy 2.2.0 <br /> numpy 1.22.3 <br /> pandas 1.4.1 <br...
<p>Indeed my connection string was not correct. forgot to mention the database. with the adjustment of the connection string as follows:</p> <pre><code>engine = create_engine(f'postgresql://{db_user}:{db_password}@{db_host}:{db_port}/{database}') </code></pre> <p>everything works fine!</p>
python|sqlalchemy|postgis|psycopg2|geopandas
0
352,921
71,495,031
Construction of a joint dataframe under specific conditions in python
<p>From the following python dataframe:</p> <pre><code>country_ID date ID visit_ENG visit_FRA visit_ESP visit_time ENG 2022-02-04 16:30:21 3 1 0 0 0 days 01:00:00 ENG 2022-02-04 16:40:21 3 1 0 0 0 days 00:05:00 ...
<p>Are you looking for <code>pd.concat</code>:</p> <pre><code>&gt;&gt;&gt; pd.concat([visit_df, subset_avg, subset_std], axis=1).reset_index() ID visit_ENG visit_FRA visit_ESP avg_visit_ESP avg_visit_ENG std_visit_ESP std_visit_ENG 0 0 1 0 1 0 days 01:04:00 0 d...
python|pandas|dataframe
1
352,922
71,617,891
Adding new customers in a dataframe after calculating their loyalty value
<p>I have a dataset df which includes information on old customers and a list of customers that may be new or old. I would like to assign a loyalty value to new customers, i.e. those customers not evaluated yet in the dataset df. Please see below an example of what I would like to achieve. Let's say that I have a list ...
<p>Let's first build our dataframes :</p> <pre class="lang-py prettyprint-override"><code> csvfile = StringIO( &quot;&quot;&quot;Customer\tvalue cust2\t13 cust3\t14 cust6\t35 cust7\t21 cust1\t24&quot;&quot;&quot;) existing_cust_df = pd.read_csv(csvfile, sep = '\t', engine='python') csvfile = StringIO(&quot;&quot;&quot...
python|pandas
1
352,923
71,698,633
Add missing rows for each Client - Python / Pandas
<p>I have df with Weeks, Months and Years.</p> <pre><code>week = ['01/03/2022 - 01/09/2022', '01/10/2022 - 01/16/2022', '01/17/2022 - 01/23/2022', '01/24/2022 - 01/30/2022'] month = [&quot;January&quot;, &quot;January&quot;, &quot;January&quot;, &quot;January&quot;] year = [2022, 2022, 2022, 2022] myDict = {} myDict[...
<p>You could <code>pivot</code> + <code>reindex</code> + <code>fillna</code> (to get the missing data) + <code>stack</code> (to get back to the previous shape):</p> <pre><code>columns = ['Week','Month','Year'] out = (test_df.pivot(['CLient Id', 'Client Name', 'City'], columns, ['Spent']) .reindex(pd.MultiIndex.f...
python|pandas|dataframe|fillna
2
352,924
71,543,191
reorder columns in a tensor according to a dictionary
<p>I don't know how to explain it correctly, so the title might be misleading. What I want to do is to move columns from a 3d tensor <em>t1</em> to another 3d tensor <em>t2</em> according to the indices. There's a dictionary <em>td</em>, and a <em>(k,v)</em> pair in <em>td</em> means that <em>kth</em> column of <em>t1<...
<p>Assuming no repeated values then you can use</p> <pre class="lang-py prettyprint-override"><code>t2[:,:,list(td.values())] = t1[:,:,list(td.keys())] </code></pre>
python|pytorch
1
352,925
71,757,861
How to perform Constrained Optimization by Jacobian like Matlab?
<p>I have a code for doing constrained optimization in Matlab:</p> <p>this one is for objective function from deriving a function according to the constraint and the case:</p> <pre><code>function f=funcobj(X); f=[(2-3*X(1)*2+X(3)*(1-X(1))+X(4)*(5+X(1)/5)); (3-4*X(2)+3*X(3)+2*X(4)); (X(1)+3*X(2)-X(1).^2/2-5....
<p>Your <code>funcobj</code> returns a np.ndarray with shape <code>(n,1)</code> instead of <code>(n,)</code>. Note that contrary to matlab, in numpy, the former corresponds to a matrix while the latter corresponds to a vector. Next, in the line <code>jac[0, i] = (f1-f0)/h</code> you are trying to assign a np.ndarray to...
python|numpy|matlab|optimization
1
352,926
71,686,103
What is the easiest way in Pandas to find what proportion of rows have a particular label?
<p>In a table that gives the demographics of a certain population, I want to find what is the proportion of German citizens. I was wondering if there is a feature in Pandas to find out what proportion of rows have a certain label, or in this case, what proportion of rows had &quot;Germany&quot; in the &quot;native-coun...
<p>What's happening is that you're currently filtering for rows that have <code>[&quot;native-country&quot;]==&quot;Germany&quot;</code> and then running value counts on the whole resulting DataFrame. This will give you counts of 1 because each row is unique when all attributes are taken into account.</p> <p>What you s...
python|python-3.x|pandas|dataframe
0
352,927
71,746,890
pandas error on linux, but working on windows
<p>So, i ran my &quot;ml&quot; model on my local windows machine, everything runs smooth, it just takes 48 hour to fully run every process, naturally i ask the company more procesing power to cut times, they give me a linux simulation server to run my models, but for some reason pandas is giving me the next error:</p> ...
<p>Ok, took some time to figure it out, i tried more versions of pandas until it work, the version is 1.2.4 dont really have an explanation to what happen.</p>
python|pandas
0
352,928
71,676,895
Pandas: most efficient way to extract timestamp from a string
<p>I have a column that I want to convert from a string to a date time timestamp. Each row in the respective column contains data as a string in this format: &quot;01.01.2020 00:00 - 01.01.2020 00:15&quot;. I want to convert it to a date time object &quot;2020-01-01 00:00:00+00:00&quot;</p> <p>I just need the first par...
<p>IIUC, you could extract the first part and convert to datetime:</p> <pre><code>pd.to_datetime(df['Date/time before conversion'].str.extract('(\S+)', expand=False)) </code></pre>
python|pandas|datetime
1
352,929
71,609,232
Reshape DataFrame Pandas - some variables to long others to wide
<p>I need to reshape a dataframe so that some of the variables (Diag1, Diag2, Diag3) change to long wile others (Period) change to wide. Basically they need to swap places.</p> <p>I have recreated the original dataframe in the example below. I've tried using pivot and melt separately to no avail as demonstrated in the ...
<p>You could <code>melt</code>; then <code>pivot</code>:</p> <pre><code>out = (df.melt(id_vars=['ID', 'Period'], var_name='Diagnosis') .pivot(['ID','Diagnosis'], 'Period', 'value') .reset_index().rename_axis(columns=[None])) </code></pre> <p>Output:</p> <pre><code> ID Diagnosis 0 Month 3 Month 0 1...
python|pandas|dataframe|pivot-table|pandas-melt
3
352,930
71,537,789
How to get a unique id for every occurrence of an item inside a tensor of segment_ids in Tensorflow
<p>Suppose <code>x</code> contains segment ids, I want to give a unique id for every item inside every segment id. This needs to be executed in a <code>tensorflow</code> operation</p> <pre><code>x = tf.constant([1, 1, 2, 2, 3, 3, 4, 1]) </code></pre> <p>Needed output:</p> <pre><code>[0, 1, 0, 1, 0, 1, 0, 2] </code></pr...
<p>Try <code>tf.unique_with_counts</code> with <code>tf.while_loop</code>:</p> <pre><code>import tensorflow as tf x = tf.constant([1, 1, 2, 2, 3, 3, 4, 1]) unique, _, count = tf.unique_with_counts(x) i = tf.constant(0) result = tf.zeros_like(x) c = lambda i, result, unique, count: tf.less(i, tf.shape(unique)[0]) b =...
python|tensorflow
1
352,931
71,682,398
Unable to rename/replace categories in a dataframe after removing unicode u
<p>I am trying to rename the categories in a dataframe after removing the unicode u with a .replace('u','',regex) method due to the method removing the other 'u's in the text as well. I have tried using the replace, and the rename_categories method to change the categories into desired format using a dictionary to map ...
<p>Try <code>str.extract</code> before create category (if needed)</p> <pre><code>df = pd.read_excel('yelp_reviews.xlsx') df['NoiseLevel'] = df['NoiseLevel'].str.extract(&quot;(?:u')?([^']*)&quot;) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df['NoiseLevel'].unique() array(['average', 'quiet', nan, 'loud', 've...
python|pandas|categories|categorical-data
0
352,932
71,525,359
How to plot several barplots using seaborn with respect to row?
<p>Let's consider the data following:</p> <pre><code>accuracies_in = ([0.5959219858156029, 0.5736842105263158, 0.5670212765957447, 0.3]) accuracies_out = [0.5, 0.6041666666666666, 0.2, 0.4] auc_out = [0.5182608695652174, 0.6095652173913042, 0.5, 0.7] algorithm = [&quot;Logistic Regression&quot;, &quot;Decision Tree&quo...
<p>You need to convert your dataframe to <a href="https://seaborn.pydata.org/tutorial/data_structure.html#long-form-vs-wide-form-data" rel="nofollow noreferrer">long form</a>, using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html" rel="nofollow noreferrer"><code>pd.melt</code></a>.<...
python|pandas|seaborn
3
352,933
71,602,334
Why tensor board is showing "no scalar data is found"?
<p>I've copied a piece of code to create a NN and after training it logs are successfully created but when I tried to visualise it using tensorboard it is showing that no scalar data is found.</p> <p>This is code and logs are successfully created and even event files are there but it is showing</p> <pre><code>checkpoin...
<p>This could simply be an issue of order of events in Jupyter notebook. I'd recommend breaking things up a little</p> <pre><code>checkpoint_path = &quot;autoencoder.h5&quot; # For each epoch creating a checkpoint checkpoint_dir = os.path.dirname(checkpoint_path) cp_callback = tf.keras.callbacks.ModelCheckpoint(filepat...
tensorflow|jupyter-notebook|neural-network|tensorboard
0
352,934
71,590,845
Does TensorFlow Lite for Microcontrollers support Google Edge TPU?
<p>I already know that TensorFlow Lite (TFL) <a href="https://coral.ai/docs/edgetpu/models-intro/" rel="nofollow noreferrer">supports</a> the Google Edge TPU, for instance through the <a href="https://coral.ai/products/dev-board/" rel="nofollow noreferrer">Coral Dev Board</a> (Linux required).</p> <p>However I'd like t...
<p>Yes, <a href="https://coral.ai/products/dev-board-micro" rel="nofollow noreferrer">Dev board micro</a> supports TFLM models. you can run TFLM models on edgeTPU. Thanks!</p>
tensorflow|embedded|tensorflow-lite|cortex-m|google-coral
0
352,935
71,484,934
Have float64 or float32 attribute in numba jitclass
<p>How to have a numba jitclass with an argument which can be either a float64 or a float32 ? With functions, the following code works:</p> <pre class="lang-py prettyprint-override"><code>import numba import numpy as np from numba import njit from numba.experimental import jitclass @njit() def f(a): print(a.dtype...
<p>When you call <code>MyClass()</code>, Numba need to instantiate a class and because Numba only work with well-defined strongly types (this is what makes it fast and so useful), the field of the class need to be typed before the instantiation of an object. Thus, you cannot define the type of <code>MyClass</code> fiel...
python|numpy|numba
1
352,936
71,753,167
apache beam rows to tfrecord in order to GenerateStatistics
<p>I have built a pipeline that read some data, does some manipulations and create some apache beam Row objects (Steps 1 and 2 in the code below). I then would like to generate statistic and write them to file. I can leverage tensorflow data validation library for that, but tfdv GenerateStatistics expects a <code>pyarr...
<p>Unfortunately there’s no other way to do it without writing in a file. We need to do this process because Machine Learning frameworks consume training data as sequence of examples, this file formats for training ML should have easily consumable layouts with no impedance mismatch with the storage platform or programm...
apache-beam|apache-beam-io|tensorflow-transform|tensorflow-data-validation
1
352,937
71,472,804
Optimize Numpy extraction from multiband array
<p>I'm relatively new to python, so please correct me if &quot;extraction&quot; isn't the right terminology.</p> <p>My problem : I'm working on image processing/analysis using Numpy, my code works fine but very slow with high resolutions.</p> <p>this is a simplified case of what I want to do :</p> <pre><code>import num...
<p>Rewriting answer after clarification</p> <p>You should have given us an <a href="https://stackoverflow.com/help/minimal-reproducible-example">minimal reproducible example</a>, more like this</p> <pre class="lang-py prettyprint-override"><code>import numpy as np # 4M pixels with 1k segments img = np.random.randint(0,...
python|numpy|image-processing|vectorization|feature-extraction
0
352,938
71,645,813
How to iterate a VLOOKUP over multiple rows?
<p>I have the following data</p> <p>Column A | Column B | M Apple | Apple | Orange | Orange | Pear | Banana | Apple | Apple | Orange | Orange | Pear | Banana | Apple | Apple | Orange | Orange | Pear | Banana | Apple | Apple | Orange ...
<p>You need to put an 'f' in front of your string if you want to use variables between curly brackets.</p> <p>Try the code below:</p> <pre><code>from openpyxl import load_workbook wb = load_workbook(filename = 'flat_user_data.xlsx') ws = wb.active for i in ws.iter_rows(): ws[f&quot;M{i}&quot;] = f&quot;=IF(ISNA(VLO...
python|pandas|openpyxl
2
352,939
71,658,779
How how to calculate haversine cross-distance between to pandas dataframe
<p>Here's my dataset <code>B</code></p> <pre><code> index lon lat 0 0 107.071969 -6.347778 1 1 110.431361 -7.773489 2 2 111.978469 -8.065442 </code></pre> <p>and dataset <code>C</code></p> <pre><code> index lon lat 5 5 112.340919 -7.520442 6 6 107.179119 -6.291131 ...
<p>Check your output distances, what units are they? I converted mine to kilometers. You can check using an online distance calculator if you wanted. Let me know</p> <pre><code>import numpy as np import pandas as pd from sklearn.metrics.pairwise import haversine_distances pd.DataFrame(haversine_distances(np.radians(df1...
python|pandas|dataframe|haversine
2
352,940
71,654,322
Adding data to an existing excel table
<p>What I'm trying to accomplish:</p> <ul> <li>Having a user drop an excel file/files into a network folder.</li> <li>They then must run a python script that will take any files within the network folder (all of which are formatted the same) and append them to the bottom of a master excel file.</li> <li>The script will...
<pre><code>import os import glob import pandas as pd # define relative path to folder containing excel data location = &quot;T:\\Example\\Test\\&quot; # load all excel files in one list df_list = [] for file in glob.glob(os.path.join(location, &quot;*.xlsx&quot;)): df = pd.read_excel(file) df_list.append(df) ...
python|excel|pandas|dataframe|append
1
352,941
71,754,479
Setting up keras-rl2 on my M1 Macbook Pro
<p>I am working on a project on Reinforcement Learning - and completely new at this. I installed keras-rl as <code>pip install keras-rl</code>, however it caused an error as many has mentioned:</p> <blockquote> <p><code>TypeError: Keras symbolic inputs/outputs do not implement `__len__`. You may be trying to pass Keras...
<p><strong>1. To install Tensorflow on M1 Macs</strong></p> <p><a href="https://developer.apple.com/metal/tensorflow-plugin/" rel="nofollow noreferrer">https://developer.apple.com/metal/tensorflow-plugin/</a></p> <p><strong>2. To Install Keras-rl2</strong></p> <p>Open a terminal window and run these commands from:</p> ...
python|tensorflow|keras|deep-learning
2
352,942
71,467,765
Cannot use replace method on python
<p>I wanted to change my variables on spesific column with dictionary values but it does not change. I tried several ways and but it does not work. My dataset has 47k rows and my dictionary has 30 different words so I will show some.</p> <p>My dataset:</p> <p><img src="https://i.stack.imgur.com/vSEfp.png" alt="My datas...
<p>You just have to create <code>raw strings</code> (prefix <code>'r'</code>)</p> <pre><code>rolechange = {r&quot;\\Adv&quot;:&quot;Adversary&quot;, r&quot;\\Sci&quot;:&quot;Scientist&quot;, r&quot;\\Inn&quot;:&quot;Innocent&quot;, r&quot;\\Und&quot;:&quot;Undetermined&quot;} ...
python|pandas|dataframe
1
352,943
71,527,703
Iterating through rows in Pandas
<p>I am having an issue applying some maths to my dataframe</p> <p>Current df:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">name</th> <th style="text-align: center;">lastConnected</th> <th style="text-align: right;">check</th> </tr> </thead> <tbody> <tr> <td sty...
<p>IIUC, don't use <code>iterrows</code> but a vectorial function:</p> <pre><code>N = 5000 df.loc[df['lastConnected'].diff().lt(-N), 'check'] = 'No connection' </code></pre> <p>or to create the column from sratch:</p> <pre><code>N = 5000 df['check'] = np.where(df['lastConnected'].diff().lt(-N), '...
python|pandas|dataframe
2
352,944
71,562,217
How to transfer pandas .plot() to Matplotlib .errorbar()
<p>I'm looking to plot <strong>error bars</strong> on a line plot I did using pandas's <code>.plot()</code> function</p> <pre><code>scores_xgb.plot(x='size', y='MSE_mean_tot', kind='line',logx=True,title='XGBoost 5 samples, 5 fold CV') </code></pre> <p>Running this gives me the following plot:</p> <p><img src="https://...
<p>There is a property on <code>pandas.DataFrame</code> objects named <code>size</code>, and it's a number, equal to the number of cells in the DataFrame (the product of the values in <code>df.shape</code>). You're trying to access a <em>column</em> named <code>size</code>, but pandas chooses the property named <code>s...
python|pandas|matplotlib|errorbar
1
352,945
71,610,076
Read Specific Columns From Each Sheet of .xlsx File
<p>I would like to specify the columns read when reading multiple sheets of a .xlsx.</p> <p>I continue to get <code>Usecols do not match columns, columns expected but not found:</code></p> <p>I have tried something similar to the following format along with what I included far below:</p> <pre><code>usecols=['A,D:G', 'B...
<p>You can use a loop as suggested by @ScottBoston.</p> <blockquote> <p>What I don't understand is how to do this without calling 'pd.read_excel' multiple times.</p> </blockquote> <p>In this version, I use <code>pd.ExcelFile</code> to avoid to reopen 3 times the file.</p> <pre><code>sheets = { '1': {'usecols': ['or...
python|pandas|dataframe
2
352,946
71,615,883
Pandas dataframe column wise calculation
<p>I have below dataframe columns:</p> <pre><code>Index(['Location' 'Dec-2021_x', 'Jan-2022_x', 'Feb-2022_x', 'Mar-2022_x', 'Apr-2022_x', 'May-2022_x', 'Jun-2022_x', 'Jul-2022_x', 'Aug-2022_x', 'Sep-2022_x', 'Oct-2022_x', 'Nov-2022_x', 'Dec-2022_x', 'Jan-2023_x', 'Feb-2023_x', 'Mar-2023_x', 'Apr-20...
<p>Use:</p> <pre><code>#sample data np.random.seed(2022) c = ['Location', 'Dec-2021_x', 'Jan-2022_x', 'Feb-2022_x', 'Mar-2022_x', 'Apr-2022_x','sum_val', 'Dec-2021_y', 'Jan-2022_y', 'Feb-2022_y', 'Mar-2022_y', 'Apr-2022_y'] df = (pd.DataFrame(np.random.randint(10, size=(5, len(c))), columns=c) .as...
python|pandas|dataframe
1
352,947
71,536,811
Pytorch: Efficiently compute unbiased estimator of mean to the power of four
<p>Let w, x, y, z be torch tensors of shape (m, n) and we wish to compute the following unbiased estimator row-wise efficiently (without for loops), where I want to compute for every row 1, ..., m:</p> <p><img src="https://latex.codecogs.com/svg.image?%5Cwidehat%7B%5Cmu_w%20%5Cmu_x%20%5Cmu_y%20%5Cmu_z%7D%20=%20%5Cfrac%...
<p>1 This implementation seems to work if I didn't make mess with the diagonal dimensions.</p> <pre><code>import numpy as np import torch as th x = np.array([1,4,5,3]) y = np.array([5,2,4,5])[np.newaxis] z = np.array([5,7,4,5])[np.newaxis][np.newaxis] w = np.array([3,9,5,1])[np.newaxis][np.newaxis][np.newaxis] xth = ...
python|performance|pytorch|torch
0
352,948
71,621,379
Creating a for loop or function to create multiple heatmaps from a dataframe
<p>I'm relatively new to python, so I'm not that great with for/while loops or functions.</p> <p>Basically, I have a dataframe that looks like this:</p> <pre><code>temp | dewpoint | wind | precip_rate_hr | total_snow ------------------------------------------------- 31 20 3 0.2 2.1 29 ...
<p>Here is one way to create all the charts in a loop. It isn't the cleanest, as there will be repeated charts (but with the axes swapped).</p> <p>My data:</p> <pre><code>import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt snow_data = pd.DataFrame(data={&quot;temp&quot;: np.ra...
python|pandas|function|for-loop|seaborn
1
352,949
71,592,926
I need to get date patterns in one column by using regex and DataFrame
<p>Hi i have date column in DataFrame, i need to get Date patterns from that columns.For example i have below column.I need to get patterns from this.</p> <pre><code>0 01/7/2022 1 01/8/2022 2 Jan/9/2022 3 01/10/2022 4 25/11/2022 5 01/12/2022 6 21/9/2022 7 01/14/2022 8 01/...
<p>One way to do this is to create a function that tries to convert a string to date using a list of formats.</p> <pre><code>from datetime import datetime def get_date_format(text): fmt_map = {'%m/%d/%Y': 'MM/DD/YYYY', '%d/%m/%Y': 'DD/MM/YYYY', '%b/%d/%Y': 'Mon/DD/YYYY', ...
python|regex|pandas
0
352,950
71,591,133
Read numpy into pandas dataframe and back to file
<p>I have a binary file that is packed and built as repeated:</p> <pre><code>struct Record { uint32_t a; double b; } __attribute__ ((packed)); </code></pre> <p>I'm reading this binary file with python like this:</p> <pre><code>def read_file(filename): dt = np.dtype([('a', np.uint32), ('...
<p>I don't know of any good way to get pandas to make a struct dtype.</p> <pre><code>dt = np.dtype([('a', np.uint32), ('b', np.float64)]) df = read_file(...) </code></pre> <p>You're going to have to create an empty array and populate it yourself.</p> <pre><code>d = np.empty(df.shape[1], dtype=dt) d['a']...
python|c|pandas|numpy
0
352,951
71,512,037
Extract large data from iterator into DataFrame
<p>I'm extracting a large dataset (38M records) from Teradata into Python DataFrame. Here's my query:</p> <pre><code>sql = 'SELECT * from retail.consumer where unit = Texas' df = pd.read_sql(sql, conn, chunksize = 100000) ef = [] while True: try: a = next(df) ef.append(a) data = pd.DataFr...
<p>Since <code>chunksize</code> returns an iterator, simply iterate directly on that object, build your list of data frame chunks then concatenate outside the loop. Right now in each loop you are calling <code>DataFrame</code> on a <code>list</code> object that grows in the loop!</p> <pre class="lang-py prettyprint-ove...
python|sql|pandas|dataframe|iterator
0
352,952
71,640,642
How to rearrange the sample order of a torch dataloader?
<p>I have a &quot;torch.utils.data.DataLoader&quot;. I want to rearrange the order of the samples. Is it possible?</p>
<p>Yes, you can use <code>torch.utils.data.Subset</code> and specify the indices.</p> <pre><code>import numpy as np import torch from torch.utils.data import DataLoader, Subset, TensorDataset data = np.arange(5) ** 2 dataset = TensorDataset(torch.tensor(data)) # Subset with entire Dataset in rearranged order dataset...
sorting|pytorch|dataloader|pytorch-dataloader
1
352,953
71,544,483
Pandas - convert object into date format
<p>I have a date column, which is formatted as object in the following format:</p> <pre><code>May 12, 2021 Apr 1, 2019 </code></pre> <p>I would need to change the data type to date. I found a way, which carves out DD MMM YYYY into separated columns and then creates final date column afterwards. However this is obviousl...
<p>I have no idea what is problem because your code gives me error</p> <pre><code>ValueError: Unable to parse string &quot;May&quot; at position 0 </code></pre> <p>but this works for me without error</p> <pre><code>import pandas as pd data = pd.DataFrame({ 'release_date': ['May 12, 2021', 'Apr 1, 2019'] }) data['...
python|pandas|dataframe|date
0
352,954
71,492,114
What is the Fastest way to change pixel values of an RGB image using Numpy / Opencv / scikit-image
<p>Given a binary image, what is the fastest and <code>Pythonic</code> way to convert the image to <code>RGB</code> and then modify it's pixels?</p> <p>I have these two ways but they don't feel good to me</p> <pre><code>def get_mask(rgb_image_path): mask = np.array(Image.open(rgb_image_path).convert('L'), dtype = n...
<p>I suppose the most simple way is this:</p> <pre class="lang-py prettyprint-override"><code>def mask_coloring(mask): expected_color = (26, 237, 160) color_mask = np.zeros((mask.shape[0], mask.shape[1], 3), dtype=np.uint8) color_mask[mask == 255.0, :] = expected_color plt.imshow(color_mask) </code></pr...
python|numpy|opencv|image-processing|computer-vision
3
352,955
42,464,055
Plotting columns x and y of pandas dataframe with third column value determining the shape of the points
<p>I have this requirement. I have a sample data in a text file containing 3 attributes per line. Test1 score, Test2 score and pass or fail represented as 1 or 0. example:-</p> <pre><code> Score1 Score2 Result 35.00 55.00 0 45.00 34.00 0 50.00 75.00 0 80.00 80.00 1 55.00 85.00 1 67.03 66.03 0 .. .. </code></p...
<p>Use a dictionary to define the markers per result type<br> Use <code>groupby</code> to iterate through types</p> <pre><code>m = {0: 'o', 1: '+'} fig, ax = plt.subplots(1, 1) for n, g in X.groupby('Result'): g.plot.scatter( 'Score1', 'Score2', marker=m[n], ax=ax) </code></pre> <p><a href="https://i.stac...
python-3.x|pandas|dataframe|plot
2
352,956
42,275,521
Pandas: create a dictionary with a list of columns as values
<p>Given this <code>DataFrame</code>:</p> <pre><code>import pandas as pd first=[0,1,2,3,4] second=[10.2,5.7,7.4,17.1,86.11] third=['a','b','c','d','e'] fourth=['z','zz','zzz','zzzz','zzzzz'] df=pd.DataFrame({'first':first,'second':second,'third':third,'fourth':fourth}) df=df[['first','second','third','fourth']] fi...
<p>Someone else can probably chime in with a pure-pandas solution, but in a pinch I think this ought to work for you. You'd basically create the dictionary on-the-fly, indexing values in each row instead.</p> <pre><code>d = {df.loc[idx, 'first']: [df.loc[idx, 'second'], df.loc[idx, 'third']] for idx in range(df.shape[...
python|list|pandas|dictionary
3
352,957
42,495,529
How to use FuzzyWuzzy in Python to name match between two data frames?
<p>I have df1 and df2. I want to use <a href="https://github.com/seatgeek/fuzzywuzzy" rel="nofollow noreferrer">fuzzywuzzy</a> to string match column A in df1 to column A in df2, and return an ID in column B of df2 based on a certain ratio match.</p> <p>For example:</p> <p>df1 looks like this:</p> <hr> <p>Name</p> ...
<p>Firstly thanks for the question, I have never used fuzzywuzzy before... </p> <p>This is my take on your question.</p> <p>Here I am trying to match the <em>name</em> column in 2 data frames, and I will only show results which have a greater than 50 score.</p> <p>As I would then concat these results (or replace a c...
python|pandas|fuzzy-search|fuzzy-logic|fuzzywuzzy
0
352,958
42,505,488
How can I rearrange this pandas dataframe in Python
<p>How can I convert the following type of dataframe into another dataframe with columns being the entries in the Target column</p> <pre><code> Cq Target Sample Repeat 0 23.21562 NID1 Tgfb_48 4 1 23.31479 COL7A1 Tgfb_48 4 2 19.62652 COL1A2 Tgfb_48 4 3 20.99357 SERPINE1 T...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow noreferrer"><code>unstack</code></a>:</p> ...
python|pandas
1
352,959
42,387,757
Feeding timeseries data into Tensorflow for LSTM classifier training
<p>I have a dataframe of shape <code>(38307, 26)</code> with timestamp as index:</p> <p>I'm trying to implement a LSTM classifier but I'm struggling to feed it into the DataFlow</p> <p>The final arrays I'm trying to feed are of shape '(X_train = (38307, 25), y_train = (38307, 2))' </p> <p>I have added the code in ca...
<p>Unfortunately, the most important part of your code, is hidden in the RNN function. </p> <p>Some tips to help you out: I guess you are trying to build a dynamic RNN... (is that correct? ) In that case, a common mistake I see is that people confuse the time major and batch major setting of these RNNs. In other words...
python|numpy|machine-learning|tensorflow|neural-network
1
352,960
42,315,881
Tensorflow: Use softmax in training ,got result W,b value always as zero?
<p>I tried to write a tensorflow code to train samples for the first time, but I seems the weight factor W and b are always zero after every step of training. </p> <p>The training data are very simple, that are 10000 samples (x,y) when 00.3, y=1. I imported these data from a csv file. Traing data sotred in csv file sh...
<p>Jep, you could expect this problem with this weight initialisation: </p> <pre><code>#Weight W = tf.Variable(tf.zeros([1, 2])) b = tf.Variable(tf.zeros([2])) </code></pre> <p>Your weights should be initialised randomly ;)</p>
csv|tensorflow
0
352,961
42,206,413
Groupby and reshape long to wide formatted dataframe while aggregating elements as arrays
<p>Suppose I have a data frame like this: </p> <pre><code> user order value 0 1 0 90 1 1 10 80 2 1 20 70 3 2 30 60 4 2 40 50 5 2 50 40 6 3 60 30 7 3 70 20 8 3 80 10 </code></pre> <p>And now I wish to resh...
<p><strong>first output</strong>:</p> <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with <code>lambda</code> function where create <code>numpy array</code> by <a href="http://pandas.pydata.org/pandas-docs/...
python|pandas
2
352,962
42,139,624
Proper way to use iloc in Pandas
<p>I have the following dataframe df:</p> <pre><code>print(df) Food Taste 0 Apple NaN 1 Banana NaN 2 Candy NaN 3 Milk NaN 4 Bread NaN 5 Strawberry NaN </code></pre> <p>I am trying to replace values in a range of rows using iloc:</p> <pre><code>df.Taste.il...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_loc.html" rel="noreferrer"><code>Index.get_loc</code></a> for position of column <code>Taste</code>, because <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="noreferrer"><code>Da...
python|pandas|dataframe|match
10
352,963
42,275,765
Plotting a dataframe as many line-graphs
<p>I have a dataframe such as:</p> <pre><code> x y z 1 1 100 1 2 150 1 3 200 2 1 125 2 2 175 2 3 225 3 1 225 3 2 275 3 3 325 ... </code></pre> <p>I want to plot, on the same graph, $z$ as a function of $y$, for each value of $x$. So that there wi...
<p><strong><em>(option I):</em></strong> Iterate through sub-groups of the grouped object and plot on the same axes, <code>ax</code>:</p> <pre><code>ax = plt.gca() # get current axes to plot against for num, g in df.groupby('x'): g.plot(x='y', y='z', ax=ax, label="x=={}".format(num)) # plt.ylab...
python|pandas|matplotlib
1
352,964
42,549,595
pandas column values to row values
<p>I have a dataset (171 columns) and when I take it into my dataframe, it looks like this way-</p> <pre><code>ANO MNO UJ2010 DJ2010 UF2010 DF2010 UM2010 DM2010 UA2010 DA2010 ... 1 A 113 06/01/2010 129 06/02/2010 143 06/03/2010 209 05/04/2010 ... 2 B 218 06/01/2010 211 06/02/2010 244 06/...
<p>Use <a href="https://github.com/pandas-dev/pandas/blob/master/pandas/core/reshape.py#L820" rel="nofollow noreferrer"><code>pd.lreshape</code></a> as a close alternative to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow noreferrer"><code>pd.melt</code></a> after filteri...
python|pandas|numpy|jupyter-notebook|jupyter
4
352,965
42,283,688
Avoiding for loops when subsetting pandas DataFrames
<p>I have a pandas DataFrame <strong>df_R</strong> that looks like this:</p> <pre><code> Change Date SubsetCondId 0 0.000230 2015-02-13 868 1 -0.000080 2015-02-16 868 2 0.000380 2015-02-17 868 3 -0.000430 2015-02-13 679 4 0.000000 2015-02-16...
<p>Use set_index combined with pivot</p> <pre><code>df_R = df_R.set_index('Date').pivot(columns = 'SubsetCondId') </code></pre>
python|loops|pandas|numpy
0
352,966
42,393,508
Strptime returning all rows of Pandas dataframe instead of just one row
<p>I have a dataset like this:</p> <pre><code>Policy | Customer | Employee | CoveredDate | LapseDate 123 | 1234 | 1234 | 2011-06-01 | 2013-01-01 124 | 1234 | 1234 | 2016-01-01 | 2013-01-01 124 | 5678 | 5555 | 2014-01-01 | 2013-01-01 </code></pre> <p>I'm trying to iterate through ea...
<p>IIUC you want all records where wd['LapseDate'] &amp; wd['CoveredDate'] are within 5 days.</p> <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer">pd.to_datetime</a> to convert to date time formats </p> <pre><code>wd['LapseDate'] = pd.to_datetime...
python|pandas|datetime|dataframe
2
352,967
42,247,416
np.vectorize and nan - how can I make them play nice?
<p>Let's say I have</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; nv = np.array([-1, np.nan, 1]) </code></pre> <p><code>np.sin</code> will work as expected</p> <pre><code>&gt;&gt;&gt; np.sin(nv) array([-0.84147098, nan, 0.84147098]) </code></pre> <p>However if I try that with vectorize on my ...
<p>Hmm, you already wrote the answer?</p> <pre><code>def noneg(n): if n &lt; 0: return n.__class__(0) return n noneg(nv) </code></pre> <p>The problem here is the variable 0 is not concerning your input type, I think.</p>
python|numpy
0
352,968
42,193,592
Difference in matrix multiplication tensorflow vs numpy
<p>I have a case where matrix multiplication of two matrices with certain dimensions work in numpy, but doesn't work in tensorflow.</p> <pre><code>x = np.ndarray(shape=(10,20,30), dtype = float) y = np.ndarray(shape=(30,40), dtype = float) z = np.matmul(x,y) print("np shapes: %s x %s = %s" % (np.shape(x), np.shape(y),...
<p>Don't know why <code>tf.matmul</code> does not support this kind of multiplication (may be one of the core developers could provide a meaningful answer). </p> <p>But if you just want to be able to multiply tensors in this way, take a look at <a href="https://www.tensorflow.org/api_docs/python/tf/einsum" rel="nofoll...
python|numpy|matrix|tensorflow
2
352,969
42,312,367
TensorFlow naming: capitalized or not?
<p>Why does TensorFlow mix capitalized and non-capitalized naming? I don't think it make sense. Maybe it's due to some legacy code?</p> <p>Below are some examples</p> <ul> <li><code>tf.constant()</code>, <code>tf.Variable()</code></li> <li><code>tf.Session().run()</code></li> </ul>
<p>It uses pep8, functions are snake case, classes are camel case.</p>
tensorflow
3
352,970
42,447,158
Python: Writing numpy arrays with different dimensions to txt file
<p>I have two numpy arrays with dimensions (81, 5) and (3196, 7) that I need to write to a csv file. The actual desired output would look something like this:</p> <pre><code>81 #This is the len() of the first array 1 2 3 4 5 . . 81 2 3 4 5 #skip a line 3196 #len() of the second array 1 2 3...
<p>Sounds like you cobbled together an array that looks like (with space in place of None):</p> <pre><code>In [74]: data Out[74]: array([[1.0, 1.0, 1.0, 1.0, 1.0, None, None], [1.0, 1.0, 1.0, 1.0, 1.0, None, None], [1.0, 1.0, 1.0, 1.0, 1.0, None, None], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], ...
python|arrays|numpy
2
352,971
42,556,078
Combinatorics: list with alternative elements
<p>I have a python list with 1D numpy arrays as elements, which have one or more elements. Consider each of the array elements as alternatives for the respective list element.</p> <p>An example:</p> <pre><code>[array([1]),array([2]),array([2,3]),array([3]),array([4]),array([3,4,5])] </code></pre> <p>I want a two thi...
<p>Here's a NumPy based approach -</p> <pre><code>def all_combs(a): # Parte-1 num_combs = np.prod(list(map(len,a))) return np.array(np.meshgrid(*a)).reshape(-1,num_combs).T def get_minrep_combs(a): # Parte-2 out = all_combs(a) counts = (np.diff(np.sort(out,axis=1),axis=1)==0).sum(1) ret...
python|numpy|combinatorics
2
352,972
42,208,832
How to load space separate file into pandas dataframe?
<p>I want to load a space separated data into pandas dataframe. If I use <code>sep='\s+'</code>, then I get the error <code>CParserError: Error tokenizing data. C error: Expected 7 fields in line 5, saw 9</code></p> <pre><code>df = pd.read_table("data.rpt",sep='\s+',index_col=False) </code></pre> <p>I was able to ope...
<p>Add <code>delim_whitespace=True</code> as an argument.</p>
python|pandas
1
352,973
42,385,334
How to put many numpy files in one big numpy file without having memory error?
<p>I follow this question <a href="https://stackoverflow.com/questions/42160582/append-multiple-numpy-files-to-one-big-numpy-file-in-python">Append multiple numpy files to one big numpy file in python</a> in order to put many numpy files in one big file, the result is: </p> <pre><code>import matplotlib.pyplot as plt ...
<p>Try to have a look to <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.memmap.html" rel="nofollow noreferrer"><code>np.memmap</code></a>. You can instantiate<code>all_arrays</code>:</p> <pre><code>all_arrays = np.memmap("all_arrays.dat", dtype='float64', mode='w+', shape=(166601,8000)) </code></p...
python|arrays|numpy
1
352,974
42,390,530
How to format the index column of excel while using dataframe to convert xls to csv Python
<p>I am trying to convert xls to csv using python df. However I am not able to remove the \n or whatever is present in the index col of the excel.</p> <p>The input excel : </p> <p><a href="https://i.stack.imgur.com/QKYkR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QKYkR.png" alt="Input excel"><...
<p>What i suggest would be to lauch you original excel with win32 , iterate through the line where you want to disable the textWrap and use</p> <pre><code>for i in range(0,active_sheets): ws = wb.Worksheets(i+1) ws.Columns.WrapText = false </code></pre> <p>you'll need to adapt these lines to get only the firs...
python|excel|csv|pandas|dataframe
0
352,975
42,475,393
Strange behavior of Matplotlib plotting numpy.matrix types
<p>I have the result of some computations made with <code>numpy.matrix</code> types</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = Axes3D(fig) # [...] # Downsampling for plotting # type(verts): np.matrix # verts.shape: (3, 700000)...
<p>As hpaulj mentions, the issue here is that the result is 2d:</p> <pre><code>&gt;&gt;&gt; verts = np.zeros((3, 100)) &gt;&gt;&gt; verts_m = np.matrix(verts) &gt;&gt;&gt; verts[0, :].shape (100,) &gt;&gt;&gt; verts_m[0, :].shape (1, 100) </code></pre> <p>Crucially, this breaks any code that expects to be able to ite...
python|numpy|matrix|matplotlib
1
352,976
69,902,184
Python pandas how to transform defaultdict to csv format?
<p>So I have data that will appear in this format:</p> <pre><code>defaultdict(&lt;class 'list'&gt;, {'ZY20': [545, 27, 402], 'ZYV0': [2190, 5, 78], 'ZZL0': [175, 21, 90]}) </code></pre> <p>I want to take this data and parse it to look like this:</p> <pre><code>ZY20 545 27 402 ZYV0 2190 5 78 ZZL0 175 21 90 </code></pre>...
<p>You can do</p> <pre><code>out = pd.DataFrame.from_dict(d,'index') Out[23]: 0 1 2 ZY20 545 27 402 ZYV0 2190 5 78 ZZL0 175 21 90 </code></pre>
python|pandas|csv
-1
352,977
69,816,675
Pandas =right() on excel
<p>On pandas 1.3.4 and Python 3.9.</p> <p>So I'm trying to basically do a =RIGHT() function for an entire column of the column next to it. I am currently referencing <a href="https://www.datasciencemadesimple.com/extract-last-n-characters-from-right-of-the-column-in-pandas-python/" rel="nofollow noreferrer">this</a> bu...
<p>Don't let Pandas infer your data type else <code>Caller</code> will cast as an integer.<br /> Use <code>dtype=str</code> as parameter of <code>read_table</code> (or read_csv?)</p> <pre><code>df = pd.read_table('file.csv', delimiter=',', dtype=str) </code></pre>
python|pandas|dataframe
1
352,978
69,722,279
How to change string based on list in pandas
<p>I have a mapper as follows</p> <pre><code>MAPPER = { 'g': ['gm', 'gram', 'grams', 'gms'], 'ml': ['mls', 'milli-litre', 'mili-litre', 'milli litre', 'mili litre'], 'kg': ['kilo', 'kilo-gram', 'kilo gram', 'kilo grams'] } </code></pre> <p>and a pandas series as follows</p> <pre><code>Salt 500 gm Sugar Pow...
<p>First flatten nested list of dict to dictonary with words boundaries and pass to <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.replace.html" rel="nofollow noreferrer"><code>Series.replace</code></a>:</p> <pre><code>s = s.replace({rf'\b{x}\b': k for k, v in MAPPER.items() for x in ...
python|pandas
2
352,979
69,949,867
How to join two dataframes with different MultiIndex values and have one dataframe repeat?
<p>I have two data frames with different resolution MultiIndex values. The first data frame tracks <code>state</code>, <code>year</code>, and <code>hour</code> variables, while the second data frame only tracks <code>state</code> and <code>hour</code> variables. How can I join the two data frames such that the second d...
<p>Simply use:</p> <pre><code>df0.join(df1) </code></pre> <p>Because the MultiIndexes have two common levels, the join will be performed on those two and broadcasted to the third one by duplicating the rows.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; df0.join(df1).head() TOTALLOAD WIND SOLAR ...
python|python-3.x|pandas
2
352,980
69,721,934
Rename pandas Dataframe Column With Data Under it
<p>I have a dataframe like this :</p> <pre><code>df_data </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">column1</th> <th style="text-align: center;">column2</th> <th style="text-align: right;">column3</th> </tr> </thead> <tbody> <tr> <td style="text-alig...
<p>Convert first line to columns names and then filter out first line of DataFrame by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="noreferrer"><code>DataFrame.iloc</code></a>:</p> <pre><code>df.columns = df.iloc[0] df = df.iloc[1:].rename_axis(columns=None) print (...
python|pandas|dataframe
4
352,981
69,963,369
Writing the DNN output to csv file
<p>I am doing the inference stage of my trained Deep neural network. The output of my model is like that:</p> <pre><code>tensor([19]) tensor([25]) tensor([18]) </code></pre> <p>I want to save the output in raws at a CSV file to do some statistical analysis. I tried this</p> <pre><code>for data in (dataloader): z_eval ...
<p>use list to keep data and save to csv after for</p> <pre><code>pred_test =[] for data in (dataloader): z_eval = model_back(enhanced.float().to(device)) torch.cuda.empty_cache() gc.collect() pred = [torch.max(z.detach().cpu(), dim=1)[1] for z in z_eval] torch.cuda.empty_cache() gc.collect() pred_test +...
python-3.x|pandas|dataframe|export-to-csv
0
352,982
69,803,437
Find and Replace Pandas only indexing each row
<p>On Python 3.9 and Pandas 1.3.4.</p> <p>So I'm trying to get rid of &quot;(&quot;. &quot;)&quot;, and &quot;-&quot; from my csv file in column E.</p> <p><a href="https://i.stack.imgur.com/RQl0a.png" rel="nofollow noreferrer">This</a> is what the original file looks like. <a href="https://i.stack.imgur.com/GJZDT.png" ...
<p>Try using regex <a href="https://www.regular-expressions.info/charclass.html" rel="nofollow noreferrer">character class</a> <code>[()-]</code> to remove any unwanted single character.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame( {'Phone':['(555)123-1234','(555)555-1...
python|excel|pandas
1
352,983
69,767,942
Save Interpolation output from Scipy
<p>I have a problem where I need to interpolate a 3D function using e.g. SciPy, and then save the output of this interpolation for future use. That is, I don't want to have to run the interpolation procedure every time as generating the 3D function to be interpolated is computationally demanding (it is from the Biot-Sa...
<p>Why not using pickle directly ? Linked to the question : <a href="https://stackoverflow.com/questions/11218477/how-can-i-use-pickle-to-save-a-dict">How-can-i-use-pickle-to-save-a-dict</a>.</p> <p>Pickle is supposed to be able to serialize <strong>any possible type</strong> of python object. Not only numpy arrays (wi...
python|numpy|scipy|interpolation|pickle
1
352,984
69,682,642
analogy of SUMIFS in Excel function in Pandas
<p>I have a difficulty with applying Excel SUMIFS type function in Pandas. I have a table similar to one on picture. I need to find Sum of each product sold each day. But I don't need it in Summary table. I need it to be written in column next to each one as shown in red column. In excel I'm using SUMIFS function. But ...
<p>You can do this with <code>groupby</code> and its <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>transform</code> method.</a></p> <p>Creating something that looks like your dataframe, but abbreviated:</p> <pre><code>import pa...
pandas
2
352,985
69,897,911
keras input shape confusion
<p>Hi I have images with the size of 160*120 (meaning 160 is the width and 120 is the height) I want to train a network with this data set in keras and no resizing.. I think in keras instead of writing</p> <pre><code>model.add(Conv2D(....,input_shape = (160,120,1) , ....) </code></pre> <p>I should write</p> <pre><code>...
<p>From the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D" rel="nofollow noreferrer">TensorFlow docs</a>:</p> <blockquote> <p>Input shape: 4+D tensor with shape: batch_shape + (channels, rows, cols) if data_format='channels_first' or 4+D tensor with shape: batch_shape + (rows, cols, channel...
python|tensorflow|keras
0
352,986
69,832,672
Count occurrences of specific value in column based on categories of another column
<p>I have a dataset that looks like this:</p> <pre><code>Categories | Clicks 1 | 1 1 | 3 1 | 2 2 | 2 2 | 1 2 | 1 2 | 2 3 | 1 3 | 2 3 | 3 4 | 2 4 | 1 </code></pre> <p>And to make some bar...
<p>Try <code>sum</code> and <code>mean</code> on the condition <code>Clicks==1</code>. Since you're working with groups, put them in groupby:</p> <pre><code>df['Clicks'].eq(1).groupby(df['Categories']).agg(['sum','mean']) </code></pre> <p>Output:</p> <pre><code> sum mean Categories 1 ...
python|pandas|pandas-groupby
1
352,987
70,000,606
Finding Pivot Points for stock price, after grouping by symbol. Pivot Point is high for 10 values before and after point
<pre><code> Date Symbol Close Volume 1259 2021-10-29 AA 45.950 6350815.000 1260 2021-10-28 AA 46.450 10265029.000 1261 2021-10-27 AA 45.790 12864700.000 1262 2021-10-26 AA 49.442 6153100.000 1263 2021-10-25 AA 51.058 11070100.000 1264 2021-10-22 AA 49.143 7453300.000 1265 ...
<p>I was able to solve with the following code eventually and wanted to share as I didn't receive a reply. Many other solutions existed for pivot points or (support/resistance points) appending each price point to a list or just for one symbol. I had wanted to keep data frame with multiple symbols.</p> <p>First used ap...
python|pandas|dataframe|pandas-groupby|maxima
0
352,988
69,779,582
How to save specAugment warped melspectrogram as a Wav file
<p>I am trying to implement a github repo specAugment (<a href="https://github.com/DemisEom/SpecAugment" rel="nofollow noreferrer">https://github.com/DemisEom/SpecAugment</a>)</p> <p>After loading the wav file using librosa, I believe it uses numPy reshape function to reshape the melspectrogram array, get Log scale mel...
<p>from what I know, the process of converting a spectrogram back to a waveform is not a trivial task.</p> <p>Librosa does support the method as you mentioned and it's using the Griffin-Lim algorithm, which is one of the basic and most convenient if you want an instant-noodle trial. At this point I don't know what spec...
python|tensorflow|librosa|data-augmentation
0
352,989
69,686,386
Applying max min and last index within a pandas groupby function Python
<p>The code down below separates the data in months with the <code>month_changes</code>. The <code>Values</code> and <code>Val_dates</code> are correlated, <code>Val_dates</code> are supposed to be the matching dates for the Values indexes.</p> <p>So <code>[100,'2015-11-01 01:03:00'],[123, '2015-11-08 12:56:00']......<...
<p>So, given what the last functional part of your code outputs:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd ... arr = ( df.groupby(pd.Grouper(freq=&quot;MS&quot;, key=&quot;dt&quot;))[&quot;val&quot;] .apply(lambda x: x.head(1).squeeze()[: len(x)] if len(x) else [...
python|arrays|pandas|dataframe|datetime
0
352,990
69,821,151
Python-Change the RGB values under condition after performing K-Means Clustering
<p>I am performing a K-Means Clustering of color and my goal is to extract the cluster which consists of the darkest color and change the other clusters to consist of bright color, such as white.</p> <p>However, I got stuck in changing the color in other clusters. Hopes there is someone can help, thaks. Below is some s...
<p>Sorry that I misuse the <code>np.where</code> function.</p> <p>As I just want to change all the values to [255, 255, 255] except [101, 98, 88]. My condition should be the <code>value</code> but not the <code>label</code>. So below code can perform what I wish.</p> <pre><code>np.where(X_compressed != [101, 98, 88], [...
python|numpy|opencv|colors|k-means
0
352,991
69,774,689
Categorize column of strings by category name in new column
<p>I am trying to carry out what should be a pretty simple procedure in Python, but I am having trouble searching for help on this, because I don't know how to best put what I am trying to do into searchable words. I am not sure if what I am trying to do is called reclassifying or using a conditional statement or what ...
<p>You can use simple <code>np.where</code>:</p> <pre><code>df['Category'] = np.where(df['Color'].str.contains('blue|red'), 'Primary', 'Seconday') </code></pre> <p>or</p> <pre><code>df['Color'].str.contains('blue|red').map({True:'Primary',False:'Secondary'}) </code></pre>
python|pandas|dataframe
1
352,992
69,919,918
How to split dataset into two considering fixed seed to ensure reproducibility in PyTorch?
<p>I am working on one of my University assignment and there is one sub-task which says. Split the data in two (Train and Validation) while using using a fixed seed to ensure reproducibility. I have wrote some code which is working fine but I want to know whether it is the correct way or not?</p> <pre><code>torch.manua...
<p>According to PyTorch's <a href="https://pytorch.org/docs/stable/notes/randomness.html" rel="nofollow noreferrer">docs</a>:</p> <p>Completely reproducible results are <strong>not guaranteed</strong> across PyTorch <strong>releases</strong>, <strong>individual</strong> commits, or different <strong>platforms</strong>....
python|deep-learning|pytorch
1
352,993
69,858,475
When converting Dataframe to HTML is it possible to set column maximum width
<p>I'm not very good in HTML.. so maybe there is an easy fix to this by using classes... But haven't found any example on the net...</p> <p>I want to set my table column a maximum width.. It the text cell is bigger than the cell, than word breaks is performed.</p> <p>I have found an example on what I need:</p> <pre><co...
<p>Check out the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_html.html" rel="nofollow noreferrer">pandas documentation for <code>to_html</code></a>.</p> <p>There is an option to define column spacing in a list, with the width of each column as an element in the list:</p> <pre><code>df.to_h...
pandas|styles|export-to-html
1
352,994
69,772,741
making new subarrays from two arrays with numpy
<p>I am learning numpy, and I need to figure out how to create a new numpy array from two defined numpy arrays, where the new array is effectively a bunch of subarrays created from the elements of array 1 being &quot;mapped&quot; to the elements of array 2.</p> <p>What I mean is, that for:</p> <pre><code>array1 = [6,8,...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.meshgrid.html" rel="nofollow noreferrer"><code>np.meshgrid</code></a>:</p> <pre><code>import numpy as np array1 = [6, 8, 9] array2 = [1, 2, 3] def mesh(values): return np.array(np.meshgrid(*values)).T.reshape(-1, len(values)) res = mesh([ar...
python|arrays|list|numpy
1
352,995
69,973,075
Why does torch.utils.save_image overwrite saved images in my folder?
<p>I am trying an adversarial attack on 10 images and I need to save all the perturbed images in a folder. So, I used <code>torch.utils.save_image</code> in pytorch which works pretty fine. I expect all the images to be saved in the folder but instead, they are being overwritten and the last image seen is the only imag...
<p>So I figured out how to solve it myself.</p> <p>I noticed that variable <code>count</code> in <code>attack()</code> will not increase no matter how. Instead, I set <code>count = 1</code> outside <code>attack()</code> and did <code>global count</code> inside same <code>attack()</code>. This way, value of <code>count<...
python|pytorch|computer-vision
1
352,996
69,921,871
How to add rows in one column based on repeated values in another column , and finally keep the first row in python?
<p>I am very new to the python pandas module.</p> <p>Suppose I have a data frame or table as follows:</p> <pre><code> df = pd.DataFrame({ 'Column A': [12,12,12, 15, 16, 141, 141, 141, 141], 'Column B':['Apple' ,'Apple' ,'Apple' , 'Red', 'Blue', 'Yellow', 'Yellow', 'Yellow', 'Yellow'], 'Column C...
<pre><code>df.groupby(&quot;Column A&quot;, as_index=False).agg(B=(&quot;Column B&quot;, &quot;first&quot;), C=(&quot;Column C&quot;, &quot;first&quot;), D=(&quot;Column C&quot;, &quot;sum&quot;)) # Column A B C ...
python|pandas|dataframe|add|calculated-columns
4
352,997
69,850,956
Splitting a column into 2 in a csv file using python
<p>I have a .csv file with 100 rows of data displayed like this</p> <p>&quot;Jim 1234&quot;</p> <p>&quot;Sam 1235&quot;</p> <p>&quot;Mary 1236&quot;</p> <p>&quot;John 1237&quot;</p> <p>What I'm trying to achieve is splitting the numbers from the names into 2 columns in python</p> <p>edit*</p> <p>Using,</p> <p...
<p>Your data have only one column and a tab delimiter:</p> <pre><code>pd.read_csv('test.csv', quoting=1, header=None, squeeze=True) \ .str.split('\t', expand=True) \ .to_csv('result.csv', index=False, header=False) </code></pre>
python|pandas|csv
0
352,998
69,795,916
How iterate in a efficient way over Pandas dataframe with Numpy.vectorize?
<p>I'm trying to iterate over a Pandas Dataframe using each row as a parameter function. I tried this:</p> <pre><code>def vectorize_df(df, hg): print(hg + str(df['tweets_id']) + df['tokenized_text']) df = pd.DataFrame.from_records(belongs_node, columns=['tweets_id','tokenized_text']) vfunct = numpy.vectorize(vector...
<p>When you define a function to be vectorized, then:</p> <ul> <li>each column should be a <strong>separate</strong> parameter,</li> <li>you should call it passing corresponding columns,</li> <li>&quot;other&quot; parameters (not taken from the source array), should be marked as &quot;excluded&quot; parameters.</li> </...
python|pandas|numpy|performance|iterator
0
352,999
69,747,980
Can you merge elements of Pandas dataframes into tuples?
<p>If you have two Pandas dataframes in Python with identical axes, is there a function to merge the elements as tuples so that they maintain their positions? If there is a better way to combine these dataframes without duplicating the number of indices or columns, that works as well.</p> <p>Expected logic:</p> <p><img...
<p>You can do this in pure pandas:</p> <pre><code>(pd.concat([df1,df2]) .stack() .groupby(level=[0,1]) .apply(tuple) .unstack() ) </code></pre> <p>Output:</p> <pre><code> A B 0 (1, 7) (4, 10) 1 (2, 8) (5, 11) 2 (3, 9) (6, 12) </code></pre> <p>Input:</p> <pre><code>import pandas as pd d...
python|pandas
1