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
8,100
60,385,361
How to obtain value_count() of different data types of elements in a series with "Object" data type?
<p>Pandas assign dtype "object" to a series that contains mixture of numeric and non numeric data. Is it possible to obtain a value count of dtypes of all the elements in a series? </p>
<p>Yes you can </p> <pre><code>pd.Series([1,'1']).map(type).value_counts() Out[65]: &lt;class 'int'&gt; 1 &lt;class 'str'&gt; 1 </code></pre>
python|pandas|numpy
2
8,101
60,368,896
Install Pytorch GPU with pre-installed CUDA and cudnn
<p>As the title suggests, I have pre-installed CUDA and cudnn (my Tensorflow is using them). </p> <p>The version of CUDA is <strong>10.0</strong> from <code>nvcc --version</code>.</p> <p>The versiuon of cudnn is <strong>7.4</strong>. </p> <p>I am trying to install pytorch in a conda environment using <code>conda ins...
<p>So I solved this myself finally. The issue is that I didn't reboot my system after installing pytorch. After rebooting, <code>torch.cuda.is_available()</code> returns <code>True</code> as expected. </p>
installation|pytorch|conda
1
8,102
72,496,841
KNNImputer is replacing data with Nulls
<p>I was working on a project with sensitive data and stumbled upon this &quot;bug&quot; (probably something that went over my head). Recently I learned about KNNimputer from sklearn and I love its concept. <strong>However, it's replacing data with null values.</strong> I'm working on a data cleaning and modeling proje...
<p>It's probably due to a nonstandard index of your dataframe. Check the shape of the output: if I'm right, you'll have 28 more rows than before.</p> <p>The problem arises because when you re-dataframe the numpy result of <code>fit_transform</code>, you get a standard index (0...n-1). Then <code>pd.concat</code> matche...
python|pandas|scikit-learn|missing-data|knn
0
8,103
59,572,151
Pandas function issues - equation output incorrect
<p>row['conus_days']>0 or row['conus_days1']>0: return row ['conus_days']* 8 + row['conus_days1']<em>12 elif (row['Country']== 'Afghanistan' or row['Country']== 'Iraq' or row['Country']=='Somalia' or row['Country']=='Yemen') and row['oconus_days']>0 or row['oconus_days1']>0: return row [...
<p>Closing each if statement in double parenthesis allows for each if statement to run individual and accurately.</p> <p>def get_hours(row): if ((row['Country']== 'Afghanistan' or row['Country']== 'Iraq' or row['Country']=='Somalia' or row['Country']=='Yemen') and (row['conus_days']>0 or row['conus_days1']>0)): ...
pandas|function|lambda|apply
0
8,104
59,510,800
Cannot select rows out of numpy array to perform an std
<p><code>import numpy as Np</code> I need to calculate the std on the first three rows of a numPy array I made with <code>y = Np.random(100, size = (5, 3))</code>.</p> <p>The above produced the array I am working on. Note that I have since calculated the median of the array after having removed the 2 smallest values...
<p>As other people suggested the question format is not clear. Here what I tried:</p> <pre><code>import numpy as np y = np.random.randint(100, size = (5, 3)) y array([[65, 84, 56], [90, 44, 42], [51, 58, 9], [82, 1, 91], [96, 32, 24]]) </code></pre> <p>Now to compute <code>std</code> for each row: </p>...
python|arrays|numpy|row
0
8,105
40,408,471
Select data when specific columns have null value in pandas
<p>I have a dataframe where there are 2 date fields I want to filter and see rows when any one of the date field is null. </p> <pre><code>ID Date1 Date2 58844880 04/11/16 NaN 59745846 04/12/16 04/14/16 59743311 04/13/16 NaN 59745848 04/14/16 04/11/16 59598413 NaN NaN 5...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="noreferrer"><code>boolean indexing</code></a>:</p> <pre><code>mask = df['Date1'].isnull() | df['Date2'].isnull() print (df[mask]) ID Date1 Date2 0 58844880.0 04/11/16 NaN 2 59743311.0 04/13/16 ...
python|pandas
10
8,106
40,402,545
How to make a numpy array from an array of arrays?
<p>I'm experimenting in <code>ipython3</code>, where I created an array of arrays:</p> <pre><code>In [105]: counts_array Out[105]: array([array([ 17, 59, 320, ..., 1, 7, 0], dtype=uint32), array([ 30, 71, 390, ..., 12, 20, 6], dtype=uint32), array([ 7, 145, 214, ..., 4, 12, 0], dtype=u...
<p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html" rel="nofollow noreferrer"><code>np.vstack</code></a> -</p> <pre><code>np.vstack(counts_array) </code></pre> <p>Another way with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nof...
python|arrays|numpy|reshape|dimensions
4
8,107
40,366,943
Get list with element's columns from Pandas DataFrame
<p>I need to have a list containing all specific element's columns for every index. For example, this DataFrame:</p> <pre><code>&gt;&gt;&gt; df 1 2 3 4 5 2016-01-27 A B B I I 2016-03-07 A ...
<p>You may want to <code>melt</code> your data frame to long format and then calculate the corresponding list of columns for each input(value), After obtaining the Series as follows, it would be easy for you to query the result for any intended input:</p> <pre><code>import pandas as pd pd.melt(df).groupby('value').var...
python|pandas|dataframe
2
8,108
40,645,498
Create sparse RDD from scipy sparse matrix
<p>I have a large sparse matrix from scipy (300k x 100k with all binary values, mostly zeros). I would like to set the rows of this matrix to be an RDD and then do some computations on those rows - evaluate a function on each row, evaluate functions on pairs of rows, etc. </p> <p>Key thing is that it's quite sparse an...
<p>I had this issue recently--I think you can convert directly by constructing the SparseMatrix with the scipy csc_matrix attributes. (Borrowing from Yang Bryan)</p> <pre><code>import numpy as np import scipy.sparse as sps from pyspark.mllib.linalg import Matrices # create a sparse matrix row = np.array([0, 2, 2, 0,...
python|numpy|apache-spark|scipy|pyspark
5
8,109
61,922,051
Pandas dataframe - convert time series with multiple elements, to a flattened dataframe with elements as columns
<p>I have a time series dataset stored in a dataframe, with multiple elements, for example stocks with their price, p/e ratio, and p/b ratio - so I have 3 rows per ticker/date. I'm wondering if there is a way to convert this, so I have one row for each ticker/date, and the price,p/e, and p/b as columns.</p> <p>Sample ...
<p>Check below lines if help you </p> <p>import pandas as pd</p> <pre><code>dfts = pd.DataFrame({ 'date': ['2020-01-01','2020-01-01','2020-01-01', '2020-01-01','2020-01-01','2020-01-01', '2020-01-02','2020-01-02','2020-01-02', '2020-01-02','2020-01-02','2020-01-02'], 'ti...
python|pandas|dataframe
0
8,110
61,619,967
Facilities to work with datetime format in R: %Y-%m-%d %H:%M:%OS-0200
<p>I have a datetime string in a format of <code>27.04.2020 15:50:30.391-0700</code>. <code>0700</code> after dash was to denote the timezone relative to GMT. </p> <p>I found it kind of annoying in <code>R</code> as there is no known tools to work with this type of non-standard datetime format. I use R way more than p...
<p>You need to change display options to see the milliseconds. Try this one:</p> <pre><code>library(lubridate) time_string &lt;- '27.04.2020 15:50:30.391-0700' time_lubridate &lt;- dmy_hms(time_string) options(digits.secs=3) time_lubridate &gt; time_lubridate [1] "2020-04-27 22:50:30.391 UTC" </code></pre>
python|r|pandas|datetime-format
1
8,111
62,029,836
String endswith() in Python
<p>I have a pandas dataframe as below.I want to create list of columns by iterating over list called 'fields_list' and separate out lists which ends with the list in 'fields_list'</p> <pre><code>import pandas as pd import numpy as np import sys df = pd.DataFrame({'a_balance': [3,4,5,6], 'b_balance': [5,1,1,1]}) df['ah...
<p>You can sort the suffixes you're looking at, and start with the longest one. When you find a column that matches a suffix, remove it from the set of columns you need to look at: </p> <pre><code>fields_list = [ ['&lt;val&gt;','_balance'],['&lt;val_class&gt;','_agg_balance']] sorted_list = sorted(fields_list, key=...
python|pandas|ends-with
0
8,112
58,050,790
Pandas filtering by date column with mixed columns data types
<p>I've a pandas dataframe similar to the one below with mixed columns data types (strings, datatime, integers) what I wanted to do was filtering the rows to get the last record by date of the combination of Company and Model.</p> <p>I've searched among many filtering / groupby solution what I was able to get were the...
<p>use apply instead of last</p> <pre class="lang-py prettyprint-override"><code>data = {'Company': ['Mercedes', 'Fiat', 'Ferrari', 'Mercedes', 'Volkswagen'], 'Model': ['Class A', 'Punto', 'GTO', 'Class A', 'Polo'], 'User': ['Mario', 'Paolo', 'Filippo', 'Andrea', 'Giuseppe'], 'Rented on': ['201...
python|pandas
1
8,113
57,950,732
How to match rows when one row contain string from another row?
<p>My aim is to find <code>City</code> that matches row from column <code>general_text</code>, but the match must be exact.</p> <p>I was trying to use searching <code>IN</code> but it doesn't give me expected results, so I've tried to use <code>str.contain</code> but the way I try to do it shows me an error. Any hints...
<p>You can use word boundaries <code>\b\b</code> for exact match:</p> <pre><code>import re f = lambda x: bool(re.search(r'\b{}\b'.format(x['City']), x['general_text'])) </code></pre> <p>Or:</p> <pre><code>f = lambda x: bool(re.findall(r'\b{}\b'.format(x['City']), x['general_text'])) df['match'] = df.apply(f, axis ...
python|pandas|dataframe|row|contains
3
8,114
57,876,294
Remove the rows which contain double underscore in the column
<p>I have a column name called Box which contains 4000+ rows with unique variable names.Every variable in the row differentiated by the first letter and the last number present in the string in a row. for example, A_B(1),A__B(1),C__D(3),D__F(2), AA__B(1). Since, In this case, I want to remove all the rows which contain...
<pre><code>df.loc[~df['Box'].str.contains(r'_{2}')] </code></pre> <p>An example:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'A' : ['James', 'Mary', 'John', 'Patricia'], 'B' : [30, 37, 30, 35], 'C' : ['Robert', 'Jennifer', 'Michael', 'Linda'], ...
pandas|dataframe
0
8,115
57,771,481
I have a code and want a to return single value
<p>I have a data frame which has a row called items, and I have a list called topitems. Below are some ex to it </p> <pre><code>Df.head() Item Toy Car, Toy Buses, Car Bike Barbie Lorri </code></pre> <p>My list is topitems</p> <pre><code>[Toy, Bike, Car] </code></pre> <p>Now I want another column in the data frame ...
<p>You can use index <code>[0]</code> to get first element from list. Or better use <code>[:1]</code> and it will not raise error when list is empty and there is no <code>[0]</code></p> <pre><code>dff['topitems'] = dff.items.apply(lambda x: list(set(x).intersection(set(topitems)))[:1]) </code></pre> <hr> <p>Example ...
python|pandas|set|intersection
2
8,116
57,868,713
Dask not efficient on concatenating large pandas dataframes and gives Memory Error
<p>At first, I tried typical concatenation of pandas dataframe:</p> <pre><code>df=pd.concat([df,df_filtered2],axis=1,sort=False) </code></pre> <p>but it gave the error:</p> <pre><code>/home/user/.pyenv/versions/3.6.0/lib/python3.6/site-packages/pandas/compat/__init__.py:84: UserWarning: Could not import the lzma mod...
<p>This question is answered in the Dask Best Practices documentation:</p> <p><a href="https://docs.dask.org/en/latest/best-practices.html#load-data-with-dask" rel="nofollow noreferrer">https://docs.dask.org/en/latest/best-practices.html#load-data-with-dask</a></p>
python|pandas|dask
0
8,117
58,002,781
Factorize current unique values in pandas df
<p>I am assigning an integer to various groups in a <code>pandas</code> <code>df</code>. I'm currently using <code>pd.factorize</code> for this. However, I'm hoping to account for <em>current</em> values only. </p> <p>For instance, using the <code>df</code> below, a unique integer gets assigned to <code>Member</code>....
<p>Below is my solution with explanation</p> <p>Steps:</p> <ul> <li>get unique members and their counts</li> <li>create list of available area code equal to length of members, sorted in reverse order so that poping gives the minimum available id</li> <li>track assigned ids to member in "areas" dictionary</li> <li>dec...
python|pandas|dataframe
2
8,118
57,837,712
Another "ValueError: Cannot feed value of shape (30, 5) for Tensor 'Placeholder:0', which has shape '(?, 30)'"
<p>Be kind, I'm new to TensorFlow. I have found a project that trains a <strong>Policy Gradient agent</strong> to trade the stock market, trained on only the daily <strong>Close</strong> prices. And I'm interested in making it train on the <strong>Open, High, Low, and Volume</strong> features as well, so I'm attempting...
<p>you have used "self.X" as input for 1st layer, for a model number of rows (data points) can vary but number of features should be same during training and predicting because that determines the number of neurons on that layer. </p> <p>But you can reuse the code for data with different number of features to create d...
python|python-3.x|tensorflow
0
8,119
54,734,545
Indices of unique values in n-dimensional array
<p>I have a 2D Numpy array containing values from 0 to n. I want to get a list of length n, such that the i'th element of that list is an array of all the indices with value i+1 (0 is excluded).</p> <p>For example, for the input</p> <pre><code>array([[1, 0, 1], [2, 2, 0]]) </code></pre> <p>I'm expecting to get</p...
<p>Here's a vectorized approach, which works for arrays of an arbitrary amount of dimensions. The idea of this solution is to extend the functionality of the <code>return_index</code> method in <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow noreferrer"><code>np.unique</co...
python|arrays|numpy
4
8,120
28,192,810
What's the difference between ndarray.item(arg) and ndarry[arg]?
<p>I read the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.item.html" rel="nofollow">Docs</a>, but still not quite understand the difference and the use case for <code>item</code>.</p> <p>But recently I found where only <code>item</code> works:</p> <pre><code>a = np.array(100) # a has sh...
<p><code>ndarray.item</code> allows you to interpret the array with a flat index, as opposed to using <code>[]</code> notation. This allows you to do something like this:</p> <pre><code>import numpy as np a = np.arange(16).reshape((4,4)) print(a) #[[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11] # [12 13 14 15]] prin...
python|numpy
6
8,121
28,312,374
numpy where compare arrays as a whole
<p>I have an array <code>x=np.array([[0,1,2,],[0,0,0],[3,4,0],[1,2,3]])</code>, and I want to get the index where x=[0,0,0], i.e. 1. I tried <code>np.where(x==[0,0,0])</code> resulting in <code>(array([0, 1, 1, 1, 2]), array([0, 0, 1, 2, 2]))</code>. How can I get the desired answer? </p>
<p>As @transcranial solution, you can use <code>np.all()</code> to do the job. But <code>np.all()</code> is slow, so if you apply it to a large array, speed will be your concern.</p> <p>To test for a specific value or a specific range, I would do like this.</p> <pre><code>x = np.array([[0,1,2],[0,0,0],[3,4,0],[1,2,3]...
python|arrays|numpy
5
8,122
28,212,435
How to separate Monday-Friday from Saturday and Sunday Pandas?
<p>I'm working on project that has data like this (I use pandas framework with python):</p> <pre><code>days rain 0 1 2 0 3 1 1 0 6 1 2 1 1 1 2 1 3 0 4 0 5 0 </code></pre> <p>Days 0-6 is Monday-Sunday and rain 0 is ...
<p>Try this:</p> <pre><code>df['Monday-Friday'] = df['days'].isin(range(5)).astype(int) df['Saturday'] = (df['days'] == 5).astype(int) df['Sunday'] = (df['days'] == 6).astype(int) </code></pre>
python|pandas
1
8,123
73,184,171
KeyError: None of [Index([(....)])] are in the columns for a list of columns generated with df.columns
<p>I have a <code>df_a</code> that contains all columns. Then I have <code>df_b</code> that contains a subset of this dataframe. I want to select the columns that are in <code>df_b</code> from <code>df_a</code>.</p> <p>Why does the following code not work?</p> <pre><code>df_a[[df_b.columns]] </code></pre> <p>It throw...
<p>Inner <code>[]</code> is redundant, you can try</p> <pre class="lang-py prettyprint-override"><code>df_a[df_b.columns] # or df_a.reindex(columns=df_b.columns) </code></pre>
python|pandas
1
8,124
73,240,427
Extract sub String from column in Pandas
<p>Given String;- <code>&quot;\NA*(0.0001,0.,NA,0.99999983,0.02) \EVENT=_Schedule185 \WGT=_WEEKS&quot;</code></p> <p>Output = <code>EVENT=_Schedule185</code></p>
<p>If you are able to get that into a dataframe then you can use this</p> <pre><code>df = pd.DataFrame({ 'Column1' : [r&quot;\NA*(0.0001,0.,NA,0.99999983,0.02) \EVENT=_Schedule185 \WGT=_WEEKS&quot;] }) df['Column1'].apply(lambda x : x.split('\\')[2]) </code></pre> <p>However, you are doing all this on an escape ch...
python|pandas|jupyter-notebook
0
8,125
73,193,301
looping an object array with pandas
<p>I would like to find another way to loop in an array of objects for this I use pandas to generate my Excel file <code>response.text </code></p> <pre><code>{&quot;Header&quot;:{&quot;Time&quot;:&quot;2022-08-01T01:55:41-07:00&quot;,&quot;ReportName&quot;:&quot;TransactionListByCustomer&quot;,&quot;StartPeriod&quot;:&...
<p>You can try <code>pd.json_normalize</code></p> <pre class="lang-py prettyprint-override"><code>import json data = json.loads(response.text) df = (pd.json_normalize(data['Columns']['Column'], record_path='MetaData', meta='ColTitle') .drop(columns='Name') .set_index('ColTitle') .T) </code></pre> <pr...
python|python-3.x|excel|pandas
0
8,126
73,264,675
Can't import object detection imageai (python)
<p>I installed imageai,tensorflow,keras in python with pip</p> <p>i typed this code</p> <pre><code>from imageai.Detection import ObjectDetection </code></pre> <p>it shows this error</p> <pre><code>ModuleNotFoundError: No module named 'keras.layers.advanced_activations' </code></pre> <p>module versions<br /> imageai - 2...
<p>Try to update version of <strong>imageai</strong> to new versions. <a href="https://pypi.org/project/imageai/2.1.6/" rel="nofollow noreferrer">try this</a></p>
python|tensorflow|keras|imageai
1
8,127
73,200,402
How to loop through dataframe column and compare dates to current
<p>Hello I have a dataframe containing a date column I would like to loop through these dates and compare it to the current date to see if any entry is today. I tried converting the column to a list using the tolist() method but it outputted not the date but rather &quot;Timestamp('2022-08-02 00:00:00')&quot; however m...
<p>Assuming that your Dataframe is called df, here's a possible way of solving your issue: <br></p> <pre><code>df.loc[df.Date == pd.Timestamp.now().date().strftime('%Y-%m-%d')] </code></pre> <p>I think it's a straightforward solution, you filter your dataframe by &quot;Date&quot; and compare to the date part of &quot;...
python|pandas|dataframe
0
8,128
35,244,858
Count occurences of elements of a matrix fast
<p>Let <strong>M</strong> and <strong>n</strong> be <strong>d x d</strong>- and <strong>d</strong>-dimensonal numpy arrays of integers, respectively. I want to count the number of triples of the form <em>(n(i), n(j), M(i,j))</em>. As a result I want a numpy array such that each entry counts the number of occurences of ...
<p>Let :</p> <pre><code>M=np.random.randint(0,3,(10,10)) n=np.random.randint(0,3,10) </code></pre> <p>Making triples and drop i=j :</p> <pre><code>x,y=np.meshgrid(n,n) a=np.dstack((x,y,M)).reshape(-1,3) au=a[a [:,0]!=a[:,1]] # i&lt;&gt;j </code></pre> <p>The problem with unique is that it use only 1D array. a sol...
python|numpy
1
8,129
67,318,910
ValueError: Shapes (None, None) and (None, None, None, 43) are incompatible
<p>I know that there were similar threads on this forum already, but though I checked them out I can't seem to find a solution.</p> <p>I'm trying to use a VGG model for multi-classification of images. I'm following a tutorial from a book. I use the last layer from the VGG model as my input for the last sequentail layer...
<p>I actually changed my Image Generator to <code>flow_from_dataframe</code> and it worked.</p> <pre><code>train_df = train_datagen.flow_from_dataframe( traindf, y_col='ClassId', x_col='Path', directory=None, subset='training', seed=123, target_size=(150, 150), batch_size=32, class_mode='categorical')...
python|tensorflow|machine-learning|keras|deep-learning
1
8,130
67,523,633
Python: Passed two arrays as function arguments. Expecting a series but only the last value is returned
<p>I believe there are other ways of doing this but I wish to learn why I am getting the results that I am getting.</p> <p>For added context, I am trying to learn vectorization in python and I came across tutorials that show passing the arrays is quicker than say the .apply() method.</p> <p>Aim: Compare two boolean arr...
<p>You are close, but you likely want to zip the arrays together and compare element by element rather than comparing the arrays for truthiness. The reason you got &quot;Outcome 3&quot; is that:</p> <pre><code>numpy.array([...]) is True ## ---&gt; is always False </code></pre> <p>Using your code as a base, you might tr...
python|arrays|python-3.x|pandas|numpy
0
8,131
67,486,035
Tensorflow No gradients provided for any variable
<p>I'm new to Tensorflow and Machine learning in general. I'm trying to create a model to detect brain tumor through MRIs.</p> <p>I'm splitting the data using <code>validation_split</code>. After compiling the model when when I try to fitting using the <code>.fit</code> function I get this Error. After googling I have ...
<p>This is because you set the loss to <code>None</code>, no gradient is provided from the loss function back to your model. Modify</p> <pre><code>model.compile( optimizer='adam', loss=None, metrics=['accuracy'], ) </code></pre> <p>to</p> <pre><code>model.compile( optimizer='adam', loss='mse', # or ...
python|tensorflow
1
8,132
34,504,191
Python pandas combine the second row if the first row IDs are the same
<p>We are using Python 2.7</p> <p>We have a simple table below:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo polar bear'.split(), 'B': '1 1 2 3 2 2 1 3 4 5'.split()}) print(df) </code></pre> <p>It generates </p> <pre><code> A B ...
<p>You could groupby aggregate to list and join the list as below.</p> <pre><code>df Out[7]: A B 0 foo 1 1 bar 1 2 foo 2 3 bar 3 4 foo 2 5 bar 2 6 foo 1 7 foo 3 df.groupby("A")["B"].apply(list) Out[10]: A bar [1, 3, 2] foo [1, 2, 2, 1, 3] new_df = df.groupby("A")["B"].apply(list)....
python-2.7|pandas
1
8,133
34,671,012
How to create 2 column binary numpy array from string list?
<p><strong>Input:</strong></p> <p>A string list like this: </p> <pre><code>['a', 'a', 'a', 'b', 'b', 'a', 'b'] </code></pre> <p><strong>Output I want:</strong></p> <p>A numpy array like this:</p> <pre><code>array([[ 1, 0], [ 1, 0], [ 1, 0], [ 0, 1], [ 0, 1], [ 1, 0], ...
<p>Using List comprehension </p> <p><strong>Code:</strong></p> <pre><code>import numpy lst = ['a', 'a', 'a', 'b', 'b', 'a', 'b'] numpy.array([[1,0] if val =="a" else [0,1]for val in lst]) </code></pre> <p><strong>Output:</strong></p> <pre><code>array([[1, 0], [1, 0], [1, 0], [0, 1], [0, 1], [1, ...
python|arrays|numpy
4
8,134
34,805,014
Loop through a pandas dataframe with multiple groupby functions and write to excel
<p>I currently have a script that I use to produce an excel output file, using a pandas df. I run the script 5 times- only changing the columns I groupby with- and append all 5 sheets into a 'master file' manually. I'm wondering how I can loop through my script automatically with 5 different groupby functions and sim...
<p>IIUC you can add list of columns and then use for loop. Last you can add number to sheet name:</p> <pre><code>col = [['customer_account', 'CounterPartyID'], ['customer_account', 'CounterPartyID', 'symbol'], ['customer_account', 'CounterPartyID', 'Providers', 'symbol'], ['Providers', 'customer_a...
python|pandas|dataframe|xlsxwriter
2
8,135
34,676,926
Generate 1d numpy with chunks of random length
<p>I need to generate 1D array where repeated sequences of integers are separated by a random number of zeros.</p> <p>So far I am using next code for this:</p> <pre><code>from random import normalvariate regular_sequence = np.array([1,2,3,4,5], dtype=np.int) n_iter = 10 lag_mean = 10 # mean length of zeros sequence ...
<p>You can pre-compute indices where repeated <code>regular_sequence</code> elements are to be put and then set those with <code>regular_sequence</code> in a vectorized manner. For pre-computing those indices, one can use <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.cumsum.html" rel="nofoll...
python|arrays|numpy
4
8,136
60,165,547
Adding columns to dataframe that depends on a existing column and its qcut bin values
<p>I have a dataframe that looks like below. dataframe1 = </p> <pre><code>Ind ID T1 T2 T3 T4 T5 0 Q1 100 121 43 56 78 1 Q2 23 43 56 76 87 2 Q3 345 56 76 78 98 3 Q4 21 32 34 45 56 4 Q5 45 654 567 78 90 5 Q6 123 32 45 56 67 6 Q7 23 24 25 26 27 7 Q8 32 33 34 35 36 8 ...
<p>Filter column <code>T1</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code...
python|pandas|dataframe
0
8,137
60,015,596
pandas dataframe drop a row of data with same value
<p>I have a data set like below and I want to drop the row of data with same value:</p> <p><a href="https://i.stack.imgur.com/TDkPJ.png" rel="nofollow noreferrer">enter image description here</a></p> <p>I think I can check the value of all rows, if all are duplicate then drop it, or I can specify a row with specific ...
<p>Hi let me know if this works for you or not,</p> <p>Just For example I have created the data frame</p> <pre><code>import pandas as pd data1={'A':[1,2,3,43], 'B':[11,22,3,53], 'C':[21,23,3,433], 'D':[131,223,3,54]} df=pd.DataFrame(data1) df.index.names=['index'] print(df) </code></pre> <p><strong>Dat...
python|pandas
0
8,138
65,080,599
Export dataframe to excel file using xlsxwriter
<p>I have dataframes as output and I need to export to excel file. I can use pandas for the task but I need the output to be the worksheet from right to left direction. I have searched and didn't find any clue regarding using the pandas to change the direction .. I have found the package xlsxwriter do that</p> <pre><co...
<p>You can do this:</p> <pre><code>import xlsxwriter writer = pd.ExcelWriter('pandas_excel.xlsx', engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1') # Assuming you already have a `df` workbook = writer.book worksheet = writer.sheets['Sheet1'] format_right_to_left = workbook.add_format({'reading_order': 2...
python|pandas|xlsxwriter
1
8,139
65,361,279
Pandas Key error when reading from the file?
<p>I have a problem. This is my program. I use this program to find properly A and T parameters which give me properly exponential curve.</p> <pre><code>#otwieranie pliku import pandas as pd data = pd.read_csv(&quot;mgdg&quot;, sep = &quot; &quot;) #przypisanie do zmiennych t -czas, C - C t = data[&quot;czas&quot;] C ...
<p>It appears that you don't have a column named czas. One way to check your column names is to type <code>list(data)</code>. You should see a list of all of your column names. If you need to rename columns in your DataFrame, see this link: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Data...
python|pandas
1
8,140
65,123,183
GPU not recognized after building tensorflow==1.15.4 from source with CUDA 10.2
<p>For some code that I want to replicate, I need to install <code>tensorflow==1.15.4</code> with GPU support. Unfortunately, the pre-built binary is <a href="https://www.tensorflow.org/install/source#gpu" rel="nofollow noreferrer">compiled with CUDA 10.0</a>, but I have CUDA 10.2 on my system.</p> <p>Thus, I wanted to...
<p>The <a href="https://github.com/CompVis/adaptive-style-transfer#training" rel="nofollow noreferrer">code I was trying to replicate</a> had <code>CUDA_VISIBLE_DEVICES=1</code> set as environment variable. Out of inexperience with Tensorflow I also set this without understanding what I meant.</p> <p>Since I have only ...
tensorflow|build|gpu
0
8,141
49,883,048
Should I use individual vocabulary files for each tensorflow categorical column?
<p>Is there a reason to use a different vocab list for each feature column rather than giving every feature column the same "global" vocab list?</p> <p>For instance, let's say I was building a DNN with Tensorflow's DNNClassifier estimator to determine whether a cat is "awesome" or "lame".</p> <p>Each feature column i...
<p>I think you should use some individual files. According to the Tensorflow <a href="https://www.tensorflow.org/api_docs/python/tf/feature_column/categorical_column_with_vocabulary_file" rel="nofollow noreferrer">documentation</a>, in <code>categorical_column_with_vocabulary_file</code>, there are no args capable of w...
tensorflow|tensorflow-estimator
0
8,142
50,100,941
Extract values from List to Pandas DF
<p>I have a python list as below,</p> <pre><code>list_fs = ['drwxrwx--- - uname 0 2017-08-25 12:10 hdfs://filepath=2011-01-31 16%3A06%3A09.0', 'drwxrwx--- - uname 0 2017-08-29 14:12 hdfs://filepath=2011-02-28 10%3A00%3A00', 'drwxrwx--- - uname 0 2017-08-29 14:20 hdfs://filepath=2011-03-31 10%3A00%3A00', 'drwx...
<pre><code>import pandas as pd df = pd.DataFrame(list_fs) df['Timestamp_ordered'] = [re.findall('\d+-\d+-\d+ \d+:\d+',i)[0] for i in list_fs] df['FilePath'] = [re.findall('hdfs:.*', i)[0] for i in list_fs] df = df[['Timestamp_ordered', 'FilePath']].sort_values('Timestamp_ordered') </code></pre>
python|pandas|dataframe
2
8,143
49,923,145
pandas: records with lists to separate rows
<p>I have a Python Pandas DataFrame like this (UCSC schema for NCBI RefSeq):</p> <pre><code>chrom exonStart exonEnds name chr1 100,200,300 110,210,310 gen1 chr1 500,700 600,800 gen2 chr2 50,60,70,80 55,65,75,85 gen3 </code></pre> <p>and I'd like to pair values from exonStarts a...
<p>Use a <code>zip</code> and <code>split</code> within a comprehension</p> <pre><code>pd.DataFrame([ [c, s, e, n] for c, S, E, n in df.itertuples(index=False) for s, e in zip(S.split(','), E.split(',')) ], columns=df.columns) chrom exonStart exonEnds name 0 chr1 100 110 gen1 1 chr1 ...
python|pandas|numpy|dataframe|split
4
8,144
64,165,877
How to turn a list of values into column names and inputted as a variable in a pandas dataframe?
<p>I want to turn a list of values (defined as modernization_area) into column headers. For example, the modernization_area outputs: A, B, C, D and the want the function to loop through each area by generating columns A, B, C, and D. The variable would ideally replace 'modernization_area' in the last line, but python i...
<p>It is not easy to help you because your question is lacking a lot of information. I am assuming hipotheticals <code>keyword_table</code> and <code>report_table</code>. Actually, I don't know if I really got what you truly want. But I hope this piece of code could help:</p> <p>Block of assumptions:</p> <pre><code>sup...
python|pandas
0
8,145
46,796,662
Filter CSV File Program using Pandas and Python
<p>I currently have a task that involves downloading a CSV master file, removing any lines where column A - Column B &lt;= 0, and where Column C equals a given phrase. I'm looking to a create a program that will:</p> <ul> <li>Import a CSV File</li> <li>Remove all lines where Column A - Column B &lt;= 0</li> <li>Ask fo...
<p>I would just ask for input to be comma separated:</p> <pre><code>phrases = phrases.split(",") file = file[file.C.isin(phrases)] </code></pre>
python|pandas|csv|dataframe
1
8,146
46,955,022
Plot certain information from dataframe
<p>I have a data frame holding Crime information with total crime values for the past 12 months. When I plot the data frame I get a graph showing lines for every <code>crimeType</code>. </p> <p>Is there anyway I can plot a graph for each specific <code>crimeType</code> over the course of the year? </p> <p>This plots ...
<p>Perhaps select each crime type and plot each as a separate series. i.e</p> <pre><code> fig, ax = plt.subplots() for ctype in crimeMonthDf['crimeType'].unique(): ax.plot(crimeMonthDf.loc[crimeMonthDf['crimeType'] == ctype, label=ctype) plt.legend() </code></pre>
python|pandas|dataframe
0
8,147
46,655,551
changing specific columns to that of values in the list in Pandas DataFrame
<p>Fairly new to coding and python.</p> <p>My DataFrame looks like this at the moment.</p> <pre><code>Text Location .... NY, USA .... NewYork .... Austin,Texas .... Tx .... California .... Somehere on Earth </code></pre> <p>The DataFrame consists of twee...
<p>Sounds like you need a lambda function with some regular expressions.</p> <pre><code>import re states_lower = [state.lower() for state in states] df['NewLocation'] = df['Location'].map(lambda x: ' '.join([loc for loc in re.findall('\\w+',x) if loc.lower() in states])) </code></pre> <ul> <li>First, lowercase all yo...
python|pandas|dataframe
0
8,148
32,645,238
Python Bokeh: Set line color based on column in columndatasource
<p>I'm trying to produce a chart that has multiple lines, but the data I use typically comes in long form like this:</p> <pre><code>x = [0.1, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0] y0 = [i**2 for i in x] y1 = [10**i for i in x] y2 = [10**(i**2) for i in x] df = pandas.DataFrame(data=[x,y0,y1,y2]).T df.columns = ['x','y0','y1',...
<p>You can reuse the principle described in <a href="https://docs.bokeh.org/en/latest/docs/gallery/stacked_area.html" rel="nofollow noreferrer">this example</a>. It is based on "patches" but is the same for "line" (see <a href="http://docs.bokeh.org/en/latest/docs/reference/plotting.html" rel="nofollow noreferrer">http...
python|pandas|bokeh
1
8,149
32,641,460
pandas DataFrame size inconsistent with windows memory usage
<p>I am reading in a DataFrame from a hdf5 file:</p> <pre><code>import pandas as pd store = pd.HDFStore('some_file.h5') df= store['df'] store.close() </code></pre> <p>Using <code>info</code> shows:</p> <pre><code>In [11]: df.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 21423657 entries, 0 to 214236...
<p>The <code>info</code> function just calls <code>numpy.nparray.nbytes</code> which multiplies the <code>nitemsize</code>(the size of the data type, e.g. 8 bytes for int64) and array's length. The problem can come from the <code>object</code> data type.</p> <p>Numpy has rich type system: <a href="http://docs.scipy.or...
python|memory|pandas
0
8,150
38,537,399
pandas the row data transform to the column data
<p>I have a dataframe like :</p> <pre><code>user_id category view collect 1 1 a 2 3 2 1 b 5 9 3 2 a 8 6 4 3 a 7 3 5 3 b 4 2 6 3 c 3 0 7 4 e 1 4 </code></pre> <p>how to change it to a new dataframe ,each user_id can appear once,then the category with the vi...
<p>The desired result can be obtained by <a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html" rel="nofollow">pivoting <code>df</code></a>, with values from <code>user_id</code> becoming the index and values from <code>category</code> becoming a column level:</p> <pre><code>import numpy as np import pan...
python|pandas
1
8,151
38,952,853
how to convert a 1-dimensional image array to PIL image in Python
<p>My question is related to a <a href="https://www.kaggle.com/c/digit-recognizer/data" rel="nofollow">Kaggle data science competition</a>. I'm trying to read an image from a one-dimensional array containing <strong>1-bit grayscale</strong> pixel information (<strong>0 to 255)</strong> for an <strong>28x28 image</stron...
<p>You can convert a NumPy array to PIL image using <code>Image.fromarray</code>:</p> <pre><code>import numpy as np from PIL import Image arr = np.random.randint(255, size=(28*28)) img = Image.fromarray(arr.reshape(28,28), 'L') </code></pre> <p><code>L</code> mode indicates the array values represent luminance. The...
python|image|numpy|matplotlib|python-imaging-library
4
8,152
38,848,411
Apply function on each column in a pandas dataframe
<p>How I can write following function in more pandas way:</p> <pre><code> def calculate_df_columns_mean(self, df): means = {} for column in df.columns.columns.tolist(): cleaned_data = self.remove_outliers(df[column].tolist()) means[column] = np.mean(cleaned_data) ret...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>dataFrame.apply(func, axis=0)</code></a>:</p> <pre><code># axis=0 means apply to columns; axis=1 to rows df.apply(numpy.sum, axis=0) # equiv to df.sum(0) </code></pre>
python|pandas|dataframe
3
8,153
63,037,684
Applying an operation efficiently on one column that depends on another column with pandas
<p>I have a Dataframe called <code>df</code> with around 20m rows, that looks like</p> <pre><code>userId movieId rating 0 1 296 5.0 1 1 306 3.5 2 1 307 5.0 3 2 665 5.0 4 2 899 3.5 ... </code></pre> <p>and I have a Series, <code>user_bias</code></p> <pre><code>userId 1 0....
<p>Try with <code>reindex</code></p> <pre><code>df['rating'] = df['rating'] - user_bias.reindex(df['userId']).values </code></pre>
python|pandas
5
8,154
67,708,191
In Pytorch how to slice tensor across multiple dims with BoolTensor masks?
<p>I want to use BoolTensor indices to slice a multidimensional tensor in Pytorch. I expect for the indexed tensor, the parts where the indices are true are kept, while the parts where the indices are false are sliced out.</p> <p>My code is like</p> <pre><code>import torch a = torch.zeros((5, 50, 5, 50)) tr_indices = ...
<p>PyTorch inherits its advanced indexing behaviour <a href="https://stackoverflow.com/questions/42309460/boolean-masking-on-multiple-axes-with-numpy">from Numpy</a>. Slicing twice like so should achieve your desired output:</p> <pre><code>a[:, tr_indices][..., val_indices] </code></pre>
python|numpy|pytorch|advanced-indexing
1
8,155
67,671,268
Unique columns pandas
<p>I have a pandas dataframe of dimensions <code>(20000,3000)</code> and I would there are some duplicated columns but they have different headings. How would I remove those duplicates but keep the original columns in pandas</p>
<p>You can use to following to remove duplicated columns according to their values:</p> <pre><code>df=df.T.drop_duplicates().T </code></pre> <p>like below:</p> <pre><code>import pandas as pd df = pd.DataFrame( {'A': [2, 4, 8, 0], 'B': [2, 0, 0, 0], 'B_duplicated': [2, 0, 0, 0], ...
python|pandas|dataframe
1
8,156
41,599,051
Can I use an aggregate function over a specific index?
<p>Suppose I have data as follows:</p> <pre><code> Month User Visits April 101078350 16 April 101187789 10000 April 101204204 98 April 101220432 659 April 103021861 25 April 103052403 93 April 103235453 25 April 103309704 77 April 103613303 87 April 103641403 735 April...
<p>try this:</p> <pre><code>In [16]: df.groupby(level='Month').mean() Out[16]: Visits Month April 901.214286 May 2929.000000 </code></pre>
pandas
1
8,157
41,622,221
pandas: merging dataframes and replacing values
<p>I have two dataframes:</p> <pre><code> A = pd.DataFrame(data=np.array([['t1',1,'t2',2]]).reshape(2,2),columns=['a','b']) A Out[6]: a b 0 t1 1 1 t2 2 B = pd.DataFrame(data=np.array([[1,2,3],[2,5,6],[3,6,7]]).reshape(3,3),columns=['x','y','z']) B Out[8]: x y z 0 1 2 3 1 2 5 6 2 3 6 7 </c...
<pre><code>B.loc[B.x.astype(str).isin(A.b), 'x'] = A.a B x y z 0 t1 2 3 1 t2 5 6 2 3 6 7 </code></pre>
python|pandas|numpy
6
8,158
41,473,397
How to obtain information on tensorflow architecture
<p>I have been working on retraining TensorFlow Inception v3 (see <a href="https://github.com/tensorflow/models/tree/master/inception" rel="nofollow noreferrer">TensorFlow Github</a>) and was curious as to how I would obtain some general "metadata" about the model.</p> <p>For instance:</p> <ul> <li>How many hidden la...
<p>You're very much on the right track. Yes, parameters are neurons. For instance, the output of the first conv layer is 32 filters (kernels) of grid size 149^2. That's a total of 710,432 neurons/parameters for that layer alone.</p> <p>The critical part of training is back-propagation which adjusts the weights betw...
python|architecture|tensorflow
1
8,159
41,613,242
Dealing with NaNs in Pandas
<p>I have a dataframe and I want to return a subset (new copy not reference) of this dataframe to perform some operations. However I find it unable to filter on the criteria i need. </p> <p>I need these three criteria to filer : </p> <pre><code>1. df['A'] != NaN 2. df['B'] == 'X' | df['B'] == NaN 3. df['C'] == NaN </...
<p>Need special function for <code>NaN</code> - <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isnull.html" rel="nofollow noreferrer"><code>isnull</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.notnull.html" rel="nofollow noreferrer"><code>notnu...
python|pandas|numpy
4
8,160
27,592,456
Floor or ceiling of a pandas series in python?
<p>I have a pandas series <code>series</code>. If I want to get the element-wise floor or ceiling, is there a built in method or do I have to write the function and use apply? I ask because the data is big so I appreciate efficiency. Also this question has not been asked with respect to the Pandas package. </p>
<p>You can use NumPy's built in methods to do this: <code>np.ceil(series)</code> or <code>np.floor(series)</code>.</p> <p>Both return a Series object (not an array) so the index information is preserved.</p>
python|pandas|series|floor|ceil
129
8,161
27,481,349
Retrieving statistical information when 2 rows are involved
<p>I need to get some information from a data set (csv) which I have boiled down to the following simple table, </p> <pre><code>Date_Time Id passed 2013-06-23 20:13:10 112 A 2013-06-23 20:58:11 112 B 2013-06-23 21:01:10 118 A 2013-06-23 21:03:31 118 A 2013-06-...
<p>Your table is not structured in such a way that you can do this with one query. If you had a check_in_id column which would be and added column then you could do it with one query. the idea being that there would be at most two rows with the same check_in_id and they would always have the same id.</p> <p>So inste...
sql|pandas
0
8,162
61,353,437
Numpy Lognorm function, used in dataframe
<p>Suppose you have a dataframe A which looks like this:</p> <pre><code>ID sigma miu prob 1 20 0.5 0.875 2 25 0.2 0.800 3 10 0.4 0.668 4 30 0.6 0.994 </code></pre> <p>how can i use python to create another column which does this Excel equivalent calculation?</p> <pre><code>LOGNORM...
<p>This is the expected output of the scipy.stats.lognorm function, as stated in the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.lognorm.html" rel="nofollow noreferrer">documentation</a>. </p>
python|pandas|numpy|normal-distribution
2
8,163
61,330,002
Python Pandas loc keyerror
<pre><code>import pandas as pd import matplotlib.pyplot as plt eurusd = pd.read_csv("G:\Kuliah python\EURUSD_M15.csv",sep="\t") print(eurusd.loc['2020-04-03 21:15']) </code></pre> <p>it shows an error :</p> <pre><code>KeyError: '2020-04-03 21:15' </code></pre> <h2>Here is my data</h2> <p><div class="snippet" data...
<p>I'll give it a try: Set the first column as index and your .loc[] indexing works properly.</p> <pre><code>eurusd = pd.DataFrame( [['2020-04-03 21:00:00', 1.07893, 1.07936, 1.07839, 1.07868, 4380], ['2020-04-03 21:15:00', 1.07867, 1.07943, 1.07831, 1.07889, 4860], ['2020-04-03 21:30:00', 1.07888, 1.07908...
python|pandas
0
8,164
68,838,944
Same code, same library, but why my training runs slower in a new laptop compare to an old laptop
<p>Here is the background:</p> <p>I do not know much about Deep learning, and I am not the one creates the code. I follow someone's procedure and test the AI. I try the same process on 3 different laptop. I thought a laptop with better hardware would increase the training speed but ends up this is not that case.</p> <p...
<p>If you would like a particular operation to run on a device of your choice instead of what's automatically selected for you, you can use with <code>tf.device</code> to create a device context, and all the operations within that context will run on the same designated device.</p> <pre><code>import tensorflow as tf tf...
tensorflow|artificial-intelligence|hardware
0
8,165
68,585,124
Tensorflow equivalent of numpy.random.normal
<p>I am trying to add a Gaussian noise to output of each activation layer in a Keras pre-trained imagenet. I am inserting a custom layer after every activation layer. In this custom layer, I want to add a Guassian noise with stddev as a percentage of the input tensor. In numpy, if I have a stddev matrix stddev_dist, I ...
<p><strong>Possible solution to gaussian noise in between keras layers</strong></p> <pre><code>import tensorflow as tf stddev=0.02 input_layer = tf.keras.layers.InputLayer(input_shape=(128,128,3)) gaus = tf.keras.layers.GaussianNoise(stddev,name='output')(input_layer) model = tf.keras.models.Model(inputs=i...
python|numpy|tensorflow|keras|tf.keras
0
8,166
68,544,850
How to calculate point spread function (PSF) for signal data?
<p>I have chromatograph data (signal) in a pandas df and in one of the signal processing step is to perform peak sharpening as shown in fig below</p> <p><a href="https://i.stack.imgur.com/aKiRh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aKiRh.png" alt="enter image description here" /></a></p> <p...
<p>Thanks for posting your sample data.</p> <p>Start by taking the Fourier Transform of each of the four columns in turn. <code>arr</code> is your data above.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import matplotlib.pyplot as plt t=np.arange(0, arr.shape[0]) plt.figure() for icol,col in...
python|pandas|numpy|scipy|signal-processing
1
8,167
65,872,566
Using tensorflow and TFBertForNextSentencePrediction to further train bert on a specific corpus
<p>I'm trying to train <code>TFBertForNextSentencePrediction</code> on my own corpus, not from scratch, but rather taking the existing bert model with only a next sentence prediction head and further train it on a specific cuprous of text (pairs of sentences). Then I want to use the model I trained to be able to extrac...
<p>The issue resides in your 'get_keras_model()' function. You defined here that you are only interested in the first of the element of the output (i.e. logits) with:</p> <pre class="lang-py prettyprint-override"><code>X = transformer_model({'input_ids': input_ids, 'attention_mask': input_masks_ids, 'token_type_ids': t...
python|tensorflow|keras|huggingface-transformers
2
8,168
65,869,458
Tensoflow error: Could not create cudnn handle: CUDNN_STATUS_NOT_INITIALIZED
<p>My computer specification are: Windows 10 cuda 11.2 cudnn 8.0.5 Nvidia geforce GTX 3080</p> <p>I used this web(<a href="https://github.com/armaanpriyadarshan/Training-a-Custom-TensorFlow-2.x-Object-Detector" rel="nofollow noreferrer">https://github.com/armaanpriyadarshan/Training-a-Custom-TensorFlow-2.x-Object-Detec...
<p>Could you please share your tensorflow version, I believe that tensorflow&lt;=2.4 does not support cuda versions of higher than 10.1, so that might be causing the problem.</p> <p><del>If you do have the correct versions for cuda and tensorflow then i suggest you to check out <a href="https://stackoverflow.com/questi...
python|tensorflow
2
8,169
65,499,901
Error in getting accuracy using test set with PyTorch
<p>I am trying to find the accuracy of my model that I created with PyTorch, but I get an error. Originally I had a different error, which is fixed, but now I get this error.</p> <p>I use this to get my test set:</p> <pre><code>testset = torchvision.datasets.FashionMNIST(MNIST_DIR, train=False, ...
<p>I was able to figure out the issue and I needed to check the size of x.</p> <p>I added this to the for loop to fix it: <code>x = torch.flatten(x, start_dim=1, end_dim=-1)</code></p>
python|machine-learning|pytorch
0
8,170
65,581,765
Interpolate CubicSpline with Pandas
<p>I have a dataframe with ResidMat and Price, I use scipy to find the interpolate CubicSpline. I used CubicSpline and apply to find all data on my dataset. But it's not very fast, because in this case have no more data. I will have more than a hundred data and it's very slow. Do you have an idea to do that but maybe w...
<p>After looking at the profile of this code most of the time is spent in interpolating so the best thing I would suggest is going pandarallel. <a href="https://stackoverflow.com/questions/45545110/make-pandas-dataframe-apply-use-all-cores">Make Pandas DataFrame apply() use all cores?</a> has the details. My fave is ...
python|pandas|scipy|interpolation|cubic
1
8,171
65,828,791
process columns in pandas dataframe
<p>I have a dataframe <strong>df</strong>:</p> <pre><code> Col1 Col2 Col3 0 a1 NaN NaN 1 a2 b1 NaN 2 a3 b3 c1 3 a4 NaN c2 </code></pre> <p>I have tried :</p> <p><code>new_df = '[' + df + ']'</code></p> <p><code>new_df['Col4']=new_df[new_df.columns[0:]].apply(lambda x:','.join(x.dropna().astype(str)...
<p>You can add <code>[]</code> for all columns without first not missing value tested with helper <code>i</code> from <code>enumerate</code>:</p> <pre><code>def f(x): gen = (y for y in x if pd.notna(y)) return ','.join(y if i == 0 else '['+y+']' for i, y in enumerate(gen)) #f = lambda x: ','.join(y if i == 0 e...
python|pandas|dataframe
2
8,172
63,655,453
Keras. Siamese network and triplet loss
<p>I want to build a network that should be able to verificate images (e.g. human faces). As I understand, that the best solution for that is Siamese network with a triplet loss. I didn't found any ready-made implementations, so I decided to create my own.</p> <p>But I have question about Keras. For example, here's the...
<p>Yes, In triplet loss function weights should be shared across all three networks, i.e <strong>Anchor, Positive and Negetive</strong>. In Tensorflow 1.x to achieve weight sharing you can use <code>reuse=True</code> in <code>tf.layers</code>.</p> <p>But in Tensorflow 2.x since the <code>tf.layers</code> has been move...
python|tensorflow|keras|computer-vision|loss-function
3
8,173
63,717,207
how to combine (merge) different regression models
<p>I am working on training different models for different estimation of human pose problems. actually, what I need is to get different outputs from a regression model for different joints of the human body. After I did searches for this problem, I come up with this idea that I have two ways:</p> <ol> <li>training diff...
<p>You can use Functional API to achieve this. I have added a simple example you can adapt this example to more complicated models according to your usecase.</p> <p><strong>Code:</strong></p> <pre><code>import tensorflow as tf import numpy as np # Here I have generated to different data and labels containing different...
python|tensorflow|regression|pose-estimation
1
8,174
24,900,247
numpy.genfromtxt csv file with null characters
<p>I'm working on a scientific graphing script, designed to create graphs from csv files output by Agilent's Chemstation software. </p> <p>I got the script working perfectly when the files come from one version of Chemstation (The version for liquid chromatography). </p> <p>Now i'm trying to port it to work on our ...
<p>Given that your file is encoded as utf-16-le with a BOM, and all the actual unicode codepoints (except the BOM) are less than 128, you should be able to use an instance of <code>codecs.EncodedFile</code> to transcode the file from utf-16 to ascii. The following example works for me.</p> <p>Here's my test file:</p>...
python|numpy
2
8,175
30,270,820
Can't figure out a method to do this. Python, csv, pandas
<p>Ok, so I'm working on a backtest for stock data and here is where I am stumped:</p> <p>I have 150 csv files, each one contains daily stock data for the length of the stock's life. Each stock has a different starting date.</p> <pre><code>Date Close etc 2015-05-05 123.24 </code></pre> <p>I want to ch...
<p>@Alexender is right, this isn't a lot of data, and it's probably easiest to read all the files into a single <code>DataFrame</code>, but when you get to the point where your data doesn't fit into memory, you can use <a href="http://dask.pydata.org/en/latest/" rel="nofollow"><code>dask</code></a> to operate on the da...
python|csv|pandas
0
8,176
20,255,623
Update array based on other array Python
<p>I have two arrays of the same size:</p> <pre><code>import numpy as np myArray = np.array([[5,3,2,1,2], [2,5,3,3,3]]) myotherArray = np.array([[0,1,1,0,0], [0,0,1,0,0]]) </code></pre> <p>I like to multiple all values in <code>myArray</code> by 5, but only if on the same...
<p>Multiply in place:</p> <pre><code>&gt;&gt;&gt; myArray[myotherArray == 0] *= 5 &gt;&gt;&gt; myArray array([[25, 3, 2, 5, 10], [10, 25, 3, 15, 15]]) </code></pre>
python|arrays|numpy
4
8,177
20,212,830
Generate a random 3 element Numpy array of integers summing to 3
<p>I need to fill a numpy array of three elements with random integers such that the sum total of the array is three (e.g. <code>[0,1,2]</code>).</p> <p>By my reckoning there are 10 possible arrays:</p> <p>111, 012, 021, 102, 120, 201, 210, 300, 030, 003</p> <p>My ideas is to randomly generate an integer between 1 a...
<p>Here is how I did it:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a=np.array([[1,1,1],[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0],[3,0,0],[0,3,0],[0,0,3]]) &gt;&gt;&gt; a[np.random.randint(0,10)] array([1, 2, 0]) &gt;&gt;&gt; a[np.random.randint(0,10)] array([0, 1, 2]) &gt;&gt;&gt; a[np.random.r...
python|arrays|random|numpy|combinations
2
8,178
71,905,722
Keras won't broadcast-multiply the model output with a mask designed for the entire mini batch
<p>I have a data generator that produces batches of input data (<code>X</code>) and targets (<code>Y</code>), and also a mask (<code>batch_mask</code>) to be applied to the model output (the same mask applies to all the datapoint in the batch; there are different masks for different batches and the data generator takes...
<p>You can create an <code>IdentityLayer</code> which receives as an external input parameter the <code>batch_mask</code> and returns it as a tensor.</p> <pre><code>class IdentityLayer(tfk.layers.Layer): def __init__(self, my_mask, **kwargs): super(IdentityLayer, self).__init__() self.my_mask = my_m...
python|tensorflow|keras|array-broadcasting
1
8,179
72,073,417
UserWarning: Geometry is in a geographic CRS. Results from 'buffer' are likely incorrect
<p>I am create geopandas DataFrames and create a buffer to be able to do spatial joins. I set the <code>crs</code> for the DataFrame and then proceed to create buffers and encounter the warning then.</p> <pre><code>df1 = gpd.GeoDataFrame(df1, geometry=gpd.points_from_xy(df1['Long'], df1['Lat'])) # set crs for buffer ca...
<p>You may need <strong>to project the coordinate system</strong>. From geodetic coordinates (e.g. 4826) to meters (e.g. 3857) and vice-versa. The calculation of the buffer is usually done in the projected meters system because it takes a <strong>distance</strong> as an argument. The shapely doc may be useful: <a href=...
python|gis|geopandas
3
8,180
71,876,632
How to decompose multiple periodicities present in the data without specifying the period?
<p>I am trying to decompose the periodicities present in a signal into its individual components, to calculate their time-periods.</p> <p>Say the following is my sample signal:</p> <p><a href="https://i.stack.imgur.com/peC13.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/peC13.png" alt="enter image ...
<p>Have you tried more of an algorithmic approach? We could first try to identify the changes in the signal, either amplitude or frequency. Identify all threshold points where there is a major change, with some epsilon, and then do FFT on that window.</p> <p>Here was my approach:</p> <ol> <li>I found that the DWT with ...
python|numpy|signal-processing|fft|autocorrelation
3
8,181
16,952,632
Read a .csv into pandas from F: drive on Windows 7
<p>I have a .csv file on my F: drive on Windows 7 64-bit that I'd like to read into pandas and manipulate.</p> <p>None of the examples I see read from anything other than a simple file name (e.g. 'foo.csv').</p> <p>When I try this I get error messages that aren't making the problem clear to me: </p> <pre><code>impor...
<p>I cannot promise that this will work, but it's worth a shot:</p> <pre><code>import pandas as pd import os trainFile = "F:/Projects/Python/coursera/intro-to-data-science/kaggle/data/train.csv" pwd = os.getcwd() os.chdir(os.path.dirname(trainFile)) trainData = pd.read_csv(os.path.basename(trainFile)) os.chdir(pwd) ...
python|csv|pandas
13
8,182
21,929,971
Re-order numpy array based on where its associated ids are positioned in the `master_order` array
<p>I am looking for a function that makes a new array of values based on ordered_ids, when the array has a length of one million.</p> <p><strong>Input:</strong></p> <pre><code> &gt;&gt;&gt; ids=array(["WYOMING01","TEXAS01","TEXAS02",...]) &gt;&gt;&gt; values=array([12,20,30,...]) &gt;&gt;&gt; ordered_ids=a...
<p>You could try:</p> <pre><code>import numpy as np def order_array(ids, values, master_order_ids): n = len(master_order_ids) idx = np.searchsorted(master_order_ids, ids) ordered_values = np.zeros(n) ordered_values[idx &lt; n] = values[idx &lt; n] print "ordered", ordered_values return ordered...
python|numpy
1
8,183
55,555,419
Decoding prediction outputs generated by a pretrained model to human readable labels
<p>I'm trying to use a pre-trained object detection model from the <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md" rel="nofollow noreferrer">Tensorflow model zoo</a>. Basically, I've chosen <code>faster_rcnn_inception_resnet_v2_atrous_oidv4</code> traine...
<p>As described in the <a href="https://github.com/tensorflow/models/blob/82b928fe199588c62be20d4c39e69c3b5b7f649d/research/object_detection/meta_architectures/faster_rcnn_meta_arch.py#L1138" rel="nofollow noreferrer">faster_rcnn_meta_arch.py</a>, the output tensors should have following shapes:</p> <pre><code>detecti...
tensorflow|machine-learning|deep-learning|object-detection|pre-trained-model
1
8,184
55,442,366
How to fix "['Student Name'] not in index"?
<p>I'm new in Programming and I'm trying to replace the old dataframe df with a new dataframe, but when I run the code it says KeyError: "['Student Name'] not in index". How can I fix it?</p> <p>This is my code import numpy as np import matplotlib.pyplot as plt import pandas as pd</p> <p>df=pd.read_excel(r'C:\Users\T...
<p>It means that 'Student Name' is not a parameter of your dataframe, when you modify the data structure you have to execute the migration of data before calling the parameter because in the database the parameter not exist.</p>
python|pandas|anaconda|spyder
0
8,185
55,401,864
Why does my new column does net get assigned after using .sample method?
<p>So I was just answering a question and I came across something interesting:</p> <p>The dataframe looks like this:</p> <pre><code> string1 string2 0 abc def 1 ghi jkl 2 mno pqr 3 stu vwx </code></pre> <p>So when I do the following, the assigning of new columns works:</p> <pre><cod...
<p><code>pandas</code> is <code>index</code> sensitive , which means they check the <code>index</code> when <code>assign</code> it , that is when you do the <code>serise</code> assign , the whole df not change , since the <code>index</code> is not change , after <code>sort_index</code>, it still show the same order of ...
python|pandas|dataframe|sample
4
8,186
55,482,647
How to count the number of dropoffs per month for dataframe column
<p>I have a dataframe that has records from 2011 to 2018. One of the columns has the drop_off_date which is the date when the customer left the rewards program. I want to count for each month between 2011 to 2018 how many people dropped of during that month. So for the 84 month period, I want the count of people who dr...
<p>What I suggest is to work directly with the strings in the column drop_off_ym and to strip them to only keep the year and month:</p> <pre><code>df['drop_off_ym'] = df.drop_off_date.apply(lambda x: x[:-3]) </code></pre> <p>Then you apply a groupby on the new created column an then a count(): </p> <pre><code>df_co...
python|pandas
1
8,187
9,689,173
Shape recognition with numpy/scipy (perhaps watershed)
<p>My goal is to trace drawings that have a lot of separate shapes in them and to split these shapes into individual images. It is black on white. I'm quite new to numpy,opencv&amp;co - but here is my current thought: </p> <ul> <li>scan for black pixels</li> <li>black pixel found -> watershed</li> <li>find watershed b...
<p>@Hooked has already answered most of your question, but I was in the middle of writing this up when he answered, so I'll post it in the hopes that it's still useful...</p> <p>You're trying to jump through a few too many hoops. You don't need <code>watershed_ift</code>.</p> <p>You use <code>scipy.ndimage.label</co...
python|numpy|scipy|watershed
16
8,188
56,655,240
Recreate Relu function in Python
<p>I trained a neural network with TensorFlow using the relu function, then I built from scratch the neural network in python using weights from TensorFlow, but when I apply the relu function to np.dot(input,weight), the output is not the same I get from TensorFlow. For instance using:</p> <pre><code>def relu(x): re...
<p>This should be helpful for you.</p> <pre><code># Numpy relu X = np.random.rand(5, 10).astype(np.float32) W_np = np.random.rand(10, 7).astype(np.float32) np_relu = np.maximum(np.matmul(X, W_np), 0) # Tensorflow relu W_tf = tf.get_variable(initializer=tf.constant_initializer(W_np), shape=[10, 7], name="W_tf") tf_relu...
python|tensorflow
0
8,189
56,628,079
proc mean with weight python equivalent
<p>I'm converting SAS to python and came across this code where I'm not matching the exact value. SAS says to take the weighted mean of the associates columns and pwgtp columns. But tried in python value not matching.</p> <pre><code>proc means data=hhhead1 nway noprint; weight pwgtp; var associates; output out=prop...
<pre><code>def wavg(group, avg_name, weight_name): d = group[avg_name] w = group[weight_name] try: return (d * w).sum() / w.sum() except ZeroDivisionError: return d.mean() a=data1.groupby(['GroupByVar']).apply(wavg, "yourVar", "WeightVar") </code></pre> <p>This should work</p>
python|python-3.x|numpy|sas
0
8,190
56,756,118
How to duplicate a pandas dataframe to match other dataframe's length?
<p>Assume the following dataframes:</p> <p>df1:</p> <pre><code>a 10. 20. 30. 40. 50. 60. 70. 80. 90. 100. 110. 120. </code></pre> <p>df2:</p> <pre><code>b 1. 2. </code></pre> <p>df3:</p> <pre><code>b 1. 2. 3. </code></pre> <p>Knowing <code>len(df1.values) % len(df2.values) == 0</code>, I want to divide each ...
<p>Here's one way using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.resize.html" rel="nofollow noreferrer"><code>np.resize</code></a>, where the new array will be filled with copies of the original until it fits the specified length:</p> <pre><code>df1['a'] /= np.resize(df2.b.values, df1.shape[...
python|pandas|dataframe
3
8,191
25,828,478
Conditionally Replace Elements of an Array Depending on the Contents of Another Array
<p>I am trying to implement the iRPOP- learning algorithm for neural networks. I am using numpy for performance reasons. One important optimization requires conditionally zeroing out elements of an float array based on the contents of a boolean array. The equivalent python code would be:</p> <pre><code>for index, co...
<p>You could use <code>float_array[boolean_array] = 0</code>:</p> <pre><code>In [2]: boolean_array = np.array([True, False, False, True]) In [3]: float_array = np.ones(4) * 1.0 In [4]: float_array Out[4]: array([ 1., 1., 1., 1.]) In [5]: float_array[boolean_array] = 0 In [6]: float_array Out[6]: array([ 0., 1....
python|arrays|python-3.x|numpy
3
8,192
25,922,678
Not able to retrieve data in a particular columns with Python
<p>I am trying to load a huge text file of size 2GB and trying to extract data in a particular column using pandas </p> <pre><code>LOCATION_ID PRODUCT_ID PRODUCT_DESC NET_SALES SALES_DATE ------------------------------ ----------- --------------------------...
<p>That file doesn't look like a csv, given that there don't seem to be any commas, and it doesn't even seem to be a delimited file. You might have better luck treating it as a fixed-width-format file and using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_fwf.html" rel="nofollo...
python|pandas
1
8,193
26,183,175
Issue with scipy quad integration in python
<p>I'm quite new to python so I'm hoping my wording makes sense. I'm currently attempting to model a set of equations that require the product of an integration to be multiplied by a float. I'm getting a Nan output from the integration output alone and I don't know why that is my code is below:</p> <pre><code>from __f...
<p>Your value for s2 is rather large (15000.0). So, when you evaluate the <a href="http://mathworld.wolfram.com/ModifiedBesselFunctionoftheSecondKind.html" rel="nofollow">Bessel Function</a> at s2 you get zero:</p> <pre><code>&gt;&gt;&gt; sp.kv(0, 15000.0) 0.0 </code></pre> <p>So your function t1 always returns zero,...
python|numpy|scipy|integration|quad
1
8,194
26,312,174
How to check if the signs of a Series conform to a given string of signs?
<p>For example I have a Series as below,</p> <pre><code>ts = pd.Series([-1,-2.4,5,6,7, -4, -8]) </code></pre> <p>I would like to know if there is pythonic way to check the signs of <code>ts</code> against a list of signs, such as, </p> <pre><code>sign = '++++---' # returns False </code></pre> <p>while</p> <pre><co...
<p>To check the whether the elements of the Series are positive you could create a Boolean Series like this:</p> <pre><code>&gt;&gt;&gt; ts &gt;= 0 0 False 1 False 2 True 3 True 4 True 5 False 6 False dtype: bool </code></pre> <p>(I assume <code>0</code> is positive, but this technique could b...
python|pandas|series
1
8,195
67,042,495
Pandas: How to relabel the index of rows
<p>Currently I have: <a href="https://i.stack.imgur.com/iszDx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iszDx.png" alt="enter image description here" /></a></p> <p>I would like the row indices on the left of product_id to start from 0 in ascending order. Is that possible?</p>
<p>you can use 'inplace' argument.</p> <pre><code>df.reset_index(drop=True, inplace= True) </code></pre>
pandas|dataframe
2
8,196
66,788,292
How to name a pandas Series column title?
<p>I am trying to set the title for a <code>pd.Series</code>, such that when assigning it to <code>pd.Dataframe</code>s it goes along with its title.</p> <p>I searched and couldn't find anything. Best I could do was name the index, but not the data column.</p> <p>Here is what I have</p> <pre><code>import pandas as pd ...
<p>You did well, but you can directly pass it in the constructor</p> <pre><code>s = pd.Series([1, 2, 3, 4], index=[5, 6, 7, 8], name=&quot;my_amazing_name&quot;) print(s) # --------------------------------------------- 5 1 6 2 7 3 8 4 Name: my_amazing_name, dtype: int64 </code></pre> <p>If you use them to...
python|pandas
2
8,197
67,111,657
Why these Python codes fail in building a dummy variable?
<p>I have the following dataframe:</p> <pre><code>df = pd.DataFrame.from_dict({'Date': {0: '2021-01-01 00:00:00', 1: '2021-01-02 00:00:00', 2: '2021-01-03 00:00:00', 3: '2021-01-04 00:00:00', 4: '2021-01-05 00:00:00', 5: '2021-01-06 00:00:00', 6: '2021-01-07 00:00:00', 7: '2021-01-08 00:00:00', 8: '2021...
<pre><code>import pandas as pd </code></pre> <p>Use <code>to_datetime()</code> method and convert your date column from string to datetime:</p> <pre><code>df['Date']=pd.to_datetime(df['Date']) </code></pre> <p>Finally use <code>apply()</code> method:</p> <pre><code>df['comm0']=df['Date'].apply(lambda x:1 if x==pd.to_da...
python|pandas|dataframe|dummy-variable
2
8,198
67,101,676
TypeError: read_csv() got an unexpected keyword argument ‘sheetname’ when merging csv files
<p>I’m trying to merge a bunch of csv files using pandas but I am getting the above error from the code below. Each csv file has one sheet but they are named differently so I am trying to say “I want the first sheet”. I’ve tried both sheet_names and sheetnames with the same error each time. Am I missing something?</...
<p>read_csv() have no argument 'sheetname'; read_excel() have one argument 'sheet_name'. <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_excel.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.read_excel.html</a></p>
python|pandas
1
8,199
47,391,948
Pandas - Style - Background Gradient using other dataframe
<p>I like using the background_gradient as it helps me look at my dataframes in an excel way.<br> But I'm wondering if I there is a way I could map the colors to the figures in another dataframe.<br> For example, something I am keen to do is to color the dataframe using a dataframe of zscores so i can see quickly the v...
<p>I don't see a different method other than altering the <a href="https://github.com/pandas-dev/pandas/blob/29d81f3df81eb0a4d077ae1317df74d509cdc446/pandas/formats/style.py#L817" rel="noreferrer">background_gradient code</a> for transferring style from one dataframe to other i.e </p> <pre><code>import pandas as pd im...
python|pandas|matplotlib|pandas-styles
9