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
16,200
68,212,306
torchaudio "RuntimeError: Error loading audio file: failed to open file" for wav file
<p>I was following this <a href="https://towardsdatascience.com/audio-deep-learning-made-simple-sound-classification-step-by-step-cebc936bbe5" rel="nofollow noreferrer">tutorial</a></p> <p>However, when I ran the code under &quot;Training&quot;, it gave me the following error.</p> <pre><code>RuntimeError: Error loading...
<p>It was a silly trouble... i was missing <code>/audio</code> in the path...</p> <p>I did not realize this was the case because the file it gave me error at always changed.</p>
python|pytorch
1
16,201
59,326,903
Adding total row to pandas DataFrame groupby
<p>I am aware of <a href="https://stackoverflow.com/questions/51712739/pandas-groupby-an-overall-total-row">this link</a> but I didn't manage to solve my problem.</p> <p>I have this below DataFrame from <code>pandas.DataFrame.groupby().sum()</code>:</p> <pre><code> ...
<p>You can use:</p> <pre><code>m=df.groupby(['Level','Company','Item'])['Value'].sum().unstack() m.assign(total=m.sum(1)).stack().to_frame('Value') </code></pre> <hr> <pre><code> Value Level Company Item 1 X a 100.0 b 200.0 total 300.0 ...
python|python-3.x|pandas|group-by|pivot-table
5
16,202
14,188,807
Numpy: Beginner nditer
<p>I am trying to learn <a href="http://docs.scipy.org/doc/numpy-dev/reference/arrays.nditer.html" rel="nofollow noreferrer">nditer</a> for possible use in speeding up my application. Here, i try to make a facetious reshape program that will take a size 20 array and reshape it to a 5x4 array:</p> <pre><code>myArray = ...
<p>It really helps to break things down by printing out what's going on along the way.</p> <p>First, let's replace your whole loop with this:</p> <pre><code>i = 0 while not it.finished: i += 1 print i </code></pre> <p>It'll print 20, not 5. That's because you're doing a 5x4 iteration, not 5x1.</p> <p>So, why is...
python|numpy|iteration
13
16,203
44,937,573
What are use cases for *not* resetting a groupby index in pandas
<p>When working with <code>groupby</code> on a pandas <code>DataFrame</code> instance, I have never <em>not</em> used either <code>as_index=False</code> or <code>reset_index()</code>. I cannot actually think of any reason why I <em>wouldn't</em> do so. Because my behavior is not the pandas default (indeed, because the ...
<p>When you perform a <code>groupby/agg</code> operation, it is natural to think of the result as a mapping from the groupby keys to the aggregated scalar values. If we were using plain Python, a dict would be the natural data structure to hold such a mapping from keys to values. Since we are using Pandas, a Series is ...
python|pandas
3
16,204
56,999,223
NumPy: Understanding values in colour matrix
<p>I have an image which I have read and converted into a numpy array. I have then extracted each colour channel (R,G,B) of the image into three separate arrays:</p> <pre><code>import cv2 import numpy as np from sklearn.cluster import MeanShift, estimate_bandwidth from sklearn.datasets.samples_generator import make_bl...
<p>Yes they represent intensity, each value is an a 8-bit value from 0 to 255. If a value is 0 the red pixel is completely off and 255 is completely on. Usually people just use the image an array (well, opencv list them in the order blue green red). The image array holds a rgb value at every pixel (try printing image)....
python|numpy|opencv|computer-vision
0
16,205
56,944,961
Unable to use numpy.isin function in xarray DataArray
<p>I have a xarray DataArray called <code>da_temp</code>. It has dimensions <code>time</code>, <code>latitude</code> and <code>longitude</code>.</p> <p>The <code>time</code> dimension is a hourly data which has coordinates spanning from 2009-01-01T00:00:00 to 2009-12-31T23:00:00.</p> <pre><code>&lt;xarray.DataArray '...
<p>The issue is that <code>np.isin</code> returns a NumPy array (i.e. without labeled dimensions), so xarray cannot automatically figure out how to broadcast it appropriately within <code>where</code>.</p> <p>I recommend using xarray's built-in <a href="http://xarray.pydata.org/en/stable/generated/xarray.DataArray.isi...
python|numpy|python-xarray
0
16,206
35,435,996
Efficient Pandas Dataframe insert
<p>I'm trying to add float values like <code>[[(1,0.44),(2,0.5),(3,0.1)],[(2,0.63),(1,0.85),(3,0.11)],[...]]</code> to a Pandas dataframe which looks like a matrix build from the first value of the tuples</p> <p>df = <code>1 2 3 1 0.44 0.5 0.1 2 0.85 0.63 0.11 3 ... ... ...</c...
<p>Use list comprehensions to first sort and extract your data. Then create your dataframe from the sorted and cleaned data.</p> <pre><code>data = [[(1, 0.44), (2, 0.50), (3, 0.10)], [(2, 0.63), (1, 0.85), (3, 0.11)]] # First, sort each row. _ = [row.sort() for row in data] # Then extract the second element...
python|performance|pandas
2
16,207
35,662,392
Memory error with AdaBoosClassifier
<p>I define <code>AdaBoostClassifier</code> as follows:</p> <pre><code>adaboost = AdaBoostClassifier(base_estimator=ensemble.RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=20, max_features=300, max_leaf_nodes=None, ...
<p>Your system is trying to allocate more memory than you have available.</p> <p>This is somewhat expected as you are using AdaBoost with a very complex base learner: a Random Forest of 580 trees. Use less complex base model like a low-depth decision tree. </p> <p>From the <a href="http://scikit-learn.org/stable/modu...
python|scikit-learn|sklearn-pandas
0
16,208
35,424,567
Python Pandas: Add column based on other column
<p>I'm new to pandas and pretty confused about it especially compared to lists and using list comprehensions.</p> <p>I have a dataframe with 4 columns. I want to create a 5th column "c" based on 4th column "m". I can get the value for "c" by applying my function for each row in column "m".</p> <p>If "m" was a list an...
<p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="noreferrer"><code>assign</code></a> - sample from <code>doc</code>:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'A': range(1, 11), 'B': np.random.randn(10)}) print df A ...
python|pandas
8
16,209
35,765,658
My data input is 5 GB of numpy arrays, yet running through a function takes 20 GB. Why?
<p>The code is too complicated to paste here, but I have a numpy array shaped <code>(800, 800, 1300)</code>, or 1300 matrices shaped <code>(800, 800)</code>. This is 5GB. </p> <p>I pass this array into a function, whereby the function </p> <ol> <li><p>multiplies each "matrix" in the above array by a float in a <code>...
<p>It sounds like this could be a type issue, i.e. you converted the values in the matrices to a different type. Perhaps you stored the original matrix with values as int16 or a single, and after multiplying it with a float, it's stored as a matrix of double values (which require 2 times more space in memory).</p> <p...
python|arrays|python-3.x|numpy|matrix
0
16,210
11,892,491
specifying missing values to pdist in scipy
<p>how can missing values be specified when calling <code>pdist</code> in scipy? i.e. the function described here:</p> <p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html<...
<p>The best way is to fill your X array with np.nan for the points to be excluded. For example, assuming a 2D case with a X a (10,2) array:</p> <pre><code>import numpy as np X = np.random.rand(10, 2) </code></pre> <p>Let's assume you want to exclude X[7] from the calculation:</p> <pre><code>X[7] = np.nan my_dist = p...
python|numpy|matplotlib|scipy
2
16,211
28,392,857
Automating a logical aggregation mapping function in python
<p>I have one column named brand_name as:</p> <pre><code>Hum Iriga Hum Erel Methox Erel neuro Erel </code></pre> <p>Now I want to do logical aggregation such that Hum Iriga is same as Hum and Erel Methox and Erel neuro are same as Erel. One way is to define a mapping function like:</p> <pre><code>Mapping={ 'EREL Me...
<p>The answer by <code>falsetru</code> is good, but there are also vectorized string functions in python which will likely be faster (and are generally nice to avoid having to <code>lambda</code> every time you want to do something similar.</p> <pre><code>df = pd.DataFrame({'brand_names': ['Hum Iriga', ...
python|pandas|mapping
1
16,212
28,543,491
pandas data frame: get maxima of a column after grouping by another coumn
<p>I try to get maximum of B for each of the A's. C and D are there, because my dataset is more than just the 2 columns I want to sort and get the maximas of.</p> <pre><code>import pandas import numpy df = pandas.DataFrame({'A': [10, 10, 20, 20, 30, 20, 10, 20], 'B': [1001, 1002, 2002, 2003, 3001, 2003, 1...
<p>You need to <code>groupby</code> the 'A' column, then select 'B' column and call <code>max()</code> on the column:</p> <pre><code>In [42]: df.groupby('A')['B'].max() Out[42]: A 10 1002 20 2003 30 3001 Name: B, dtype: int64 </code></pre> <p>You can perform multiple functions on separate columns at once, s...
python|python-2.7|pandas
2
16,213
28,786,354
Python numpy.ndarray compare
<p>How can I compare array elements in a <code>numpy.ndarray</code>?</p> <p>My <code>ndarray</code> is like this </p> <pre><code>array([[ 781, 94], [ 781, 656], [1367, 94], [1367, 656]]) </code></pre> <p>Required Output: </p> <pre><code>array([781, 94, 656, 1367]) </code></pre>
<p>It seems like you want unique values in your array</p> <pre><code>In [16]: arr = np.array([[ 781, 94], [ 781, 656], [1367, 94], [1367, 656]]) In [17]: np.unique(arr) Out[17]: array([ 94, 656, 781, 1367]) </code></pre>
python|numpy|multidimensional-array|compare
1
16,214
50,831,061
Add new columns to a pandas df after filtering
<p>I have a df that contains information about various places.</p> <pre><code>import pandas as pd d = ({ 'C' : ['08:00:00','XX','08:10:00','XX','08:41:42','XX','08:50:00','XX', '09:00:00', 'XX','09:15:00','XX','09:21:00','XX','09:30:00','XX','09:40:00','XX'], 'D' : ['Home','','Home','','Away','','Home','','Aw...
<p>I believe need custom function with groupby by <code>D</code> and <code>F</code> columns with replace duplicated values by <code>mask</code>:</p> <pre><code>def f(g): Stop = g.loc[df['B'] == 'Stop', 'C'] Start = g.loc[df['B'] == 'Start', 'C'] Res = g.loc[df['B'] == 'Res', 'C'] g['Start_diff'] = Star...
python|pandas|dataframe|group-by|unique
0
16,215
51,101,432
timedelta to string type in pandas dataframe
<p>I have a dataframe <code>df</code> and its first column is <code>timedelta64</code></p> <pre><code>df.info(): &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 686 entries, 0 to 685 Data columns (total 6 columns): 0 686 non-null timedelta64[ns] 1 686 non-null object 2 686 non-null object 3 686 no...
<p>It is possible by:</p> <pre><code>df['duration1'] = df['duration'].astype(str).str[-18:-10] </code></pre> <p>But solution is not general, if input is <code>3 days 05:01:11</code> it remove <code>3 days</code> too.</p> <p>So solution working only for timedeltas less as one day correctly.</p> <p>More general solut...
python|pandas|timedelta
8
16,216
51,006,163
Pandas: How to detect the peak points (outliers) in a dataframe?
<p>I am having a pandas dataframe with several of speed values which is continuously moving values, but its a sensor data, so we often get the errors in the middle at some points the moving average seems to be not helping also, so what methods can I use to remove these outliers or peak points from the data?</p> <p>Exam...
<p>I really think z-score using <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.zscore.html" rel="nofollow noreferrer">scipy.stats.zscore()</a> is the way to go here. Have a look at the related issue in <a href="https://stackoverflow.com/questions/50904088/deleting-the-same-outliers-in-two-tim...
python|python-3.x|pandas|outliers
3
16,217
20,491,459
Efficient correlation calculation between large number of records
<p>I am reading a book (<a href="http://guidetodatamining.com/" rel="nofollow">A Programmer's Guide to Data Mining</a>) which has the following data attached to it <a href="http://guidetodatamining.com/guide/ch2/BX-Dump.zip" rel="nofollow">BX-Dump</a>, having 100k users' rating, each having some books rated. I'd like t...
<p>Be careful with benchmark such as this. Pandas might be using lazy loading, i.e. it may return but not actually have read the data yet. In which case the measured wall time would be worthless. Try performing some simple operation on all the data to ensure it has really been read.</p> <p>As for correlation: your inp...
python|pandas|data-mining|correlation
3
16,218
33,183,297
How to combine date and elapsed time into one datetime column in Python
<p>I am trying to combine a date column and total elapsed time column into one datetime column.</p> <p>I have a pandas dataframe that looks as follows:</p> <pre><code>calendarid actualdeparturetime actualtriptime 2014-01-01 360.066667 26.716667 2014-01-01 384.0500...
<p>Use <code>astype("timedelta64[m]")</code></p> <pre><code>In [608]: df['calendarid'] + df['actualdeparturetime'].astype("timedelta64[m]") Out[608]: 0 2014-01-01 06:00:00 1 2014-01-01 06:24:00 2 2014-01-01 06:46:00 3 2014-01-01 07:04:00 4 2014-01-01 07:24:00 dtype: datetime64[ns] </code></pre>
python|datetime|pandas|timedelta
1
16,219
9,470,760
Linear combination of unevaluated functions
<p>I am building a class for constructing a certain type of approximating function (mathematical function). This approximating function will be a linear combination of a given number of basis functions, which I store in a list, and it will return a scalar. A method of the class needs to update my approximating function...
<p>A quick way to combine the function basis with the coefficients is a python dictionary:</p> <pre><code> f = lambda x : x+1 g = lambda x : 2*x d = { f : 7, g : 3 } print(d) d[f]=8 print(d) def app (d,x): return np.sum([ v * k(x) for k,v in d.items() ] ) print(app(d,0)) </code></pre> <p>This prints:</p> <pr...
python|numpy
2
16,220
66,369,896
How to fill out missing entries with zeroes (completely missing, not NaN) in a dataset using pandas and numpy?
<p>I have a dataset with a 1-second timestep in the form of a CSV with the following format:</p> <pre><code>2021-02-07 11:00:30, 64.8 2021-02-07 11:00:31, 64.8 2021-02-07 11:00:35, 50.3 .. .. </code></pre> <p>and so on and so forth. The problem is, it only has entries for when the value at that time is larger ...
<p>If the dates in your df are not your <code>index</code>, then you have to set them as your index.</p> <p>To set as index:</p> <pre><code>df = df.set_index('Datecolumn') </code></pre> <p>After that try this:</p> <pre><code>df.asfreq(freq='1S', fill_value=0) </code></pre>
python|pandas|dataframe|numpy|datetime
0
16,221
66,656,120
SageMaker TF 2.3 distributed training
<p>Using SageMaker v2.29.2 and Tensorflow v2.3.2 I'm trying to implement distributed training as explained in the following blogpost:</p> <p><a href="https://docs.aws.amazon.com/sagemaker/latest/dg/model-parallel-customize-training-script-tf.html#model-parallel-customize-training-script-tf-23" rel="nofollow noreferrer"...
<p>smdistributed is only available on the SageMaker containers. It is supported for specific TensorFlow versions and you must add:</p> <pre><code>distribution={'smdistributed': { 'dataparallel': { 'enabled': True } }} </code></pre> <p>On the estimator code in order to ena...
python|tensorflow|amazon-sagemaker
0
16,222
66,420,493
Python ValueError: diag requires an array of at least two dimensions
<p>I am trying to take a diagonal matrix but unfortunately, I am getting an error. My code is:</p> <pre><code>import numpy as np a = np.array([1, 2, 3, 2, 1 ,2]) b = np.diagonal((a)*(a).T) </code></pre>
<p>Try</p> <pre><code>import numpy as np a = np.array([1, 2, 3, 2, 1 ,2])[np.newaxis] b = np.diagonal((a)*(a).T) </code></pre> <p>Refer: <a href="https://stackoverflow.com/questions/5954603/transposing-a-1d-numpy-array">Transposing a 1D NumPy array</a></p>
python|numpy
0
16,223
66,479,862
Calculating mean and standard deviation in pandas dataframe
<p>I have the following dataframe:</p> <pre><code> COD CHM DATE 0 5713 0.0 2020-07-16 1 5713 1.0 2020-08-11 2 5713 2.0 2020-06-20 3 5713 3.0 2020-06-19 4 5713 4.0 2020-06-01 ... ... ... ... 2135283 73306036 0.0 2020-09-30 2135284 73306055 12.0 2020-09...
<p>If I understand correctly, you're simply requiring this:</p> <pre><code>df.groupby(&quot;COD&quot;)[&quot;CHM&quot;].agg(&quot;std&quot;) </code></pre> <p>As a general principle, there's almost always a &quot;pythonic&quot; way to do these things that's fewer lines and easy to understand!</p>
python|pandas|jupyter-notebook|mean|standard-deviation
0
16,224
16,371,292
pandas dataframe groupby like mysql, yet into new column
<pre><code>df = pd.DataFrame({'A':[11,11,22,22],'mask':[0,0,0,1],'values':np.arange(10,30,5)}) df A mask values 0 11 0 10 1 11 0 15 2 22 0 20 3 22 1 25 </code></pre> <p>Now how can I group by A, and keep the column names in tact, and yet put a custom function into Z:</p> <pre><code>d...
<p>If you want the original columns in your result, you can first calculate the grouped and aggregated dataframe (but you will have to aggregate in some way your original columns. I took the first occuring as an example):</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'A':[11,11,22,22],'mask':[0,0,0,1],'values':np.ara...
python|group-by|pandas|dataframe
2
16,225
16,486,252
Is it possible to use argsort in descending order?
<p>Consider the following code:</p> <pre><code>avgDists = np.array([1, 8, 6, 9, 4]) ids = avgDists.argsort()[:n] </code></pre> <p>This gives me indices of the <code>n</code> smallest elements. Is it possible to use this same <code>argsort</code> in descending order to get the indices of <code>n</code> highest element...
<p>If you negate an array, the lowest elements become the highest elements and vice-versa. Therefore, the indices of the <code>n</code> highest elements are:</p> <pre><code>(-avgDists).argsort()[:n] </code></pre> <p>Another way to reason about this, as mentioned in the <a href="https://stackoverflow.com/questions/16...
python|numpy
319
16,226
57,579,579
Replace values in pandas dataframe based on other dataframe
<p>I have two dataframes, one in the form of:</p> <pre><code># X Y 1 2 0.0 2 5 0.0 3 10 0.0 4 15 0.0 5 17 0.0 6 21 0.0 </code></pre> <p>and one in the form of:</p> <pre><code>A B C 1 4 2 2 5 3 3 6 4 </code></pre> <p>I want to replace all the ABC values fr...
<p>IIUC <code>replace</code></p> <pre><code>df1.replace(df.set_index('#').X) Out[382]: A B C 0 2 15 5 1 5 17 10 2 10 21 15 </code></pre>
python|pandas|dataframe
3
16,227
57,631,668
Most efficient way to append rows to a Dataframe with unequal columns
<p>I am trying to append a row (df_row) with every iteration to a parent dataframe (df_all). The parent dataframe has all the possible column values and every iteration produces a row with a unique set of columns which are a subset of the all possible columns. It looks something like this:</p> <p><code>df_all</code></...
<p>Notice that you can build a DataFrame from a list of Series or dicts:</p> <pre><code>In [46]: pd.DataFrame([pd.Series({'A':1,'B':2}), pd.Series({'A':2,'C':3})]) Out[186]: A B C 0 1.0 2.0 NaN 1 2.0 NaN 3.0 In [187]: pd.DataFrame([{'A':1,'B':2}, {'A':2,'C':3}]) Out[187]: A B C 0 1 2.0 ...
python|pandas|dataframe
3
16,228
57,572,126
Why I am getting error "Duplicate names are not allowed"?
<pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np u_cols = ['user_id', 'age', 'sex', 'occupation', 'zip_code'] users = pd.read_csv('ml-100k/u.user', sep='|', names=u_cols, encoding='latin-1') r_cols = ['user_id','movie_id','rating', 'unix_timestamp'] ratings = pd.read_csv('ml-100k/...
<p>we can able to resolve issue like this, no need of version change.</p> <pre><code>X_train = pd.read_csv('../UCI_HAR_Dataset/train/X_train.txt', delim_whitespace=True, header=None, encoding='latin-1') X_train.columns = features </code></pre>
python|python-3.x|pandas
1
16,229
57,500,582
Unable to figure out inplace operation in the pytorch code?
<p>I have the following implementation in PyTorch for learning using LSTM:</p> <p><a href="https://gist.github.com/rahulbhadani/f1d64042cc5a80280755cac262aa48aa" rel="nofollow noreferrer">https://gist.github.com/rahulbhadani/f1d64042cc5a80280755cac262aa48aa</a></p> <p>However, the code is experiencing in-place operat...
<p>I think the issue is with the following line: </p> <pre><code>global_loss_list.append(global_loss.detach_()) </code></pre> <p>The convention in PyTorch for in-place operations is using <code>_</code> at the end of the function name (as in <code>detach_</code>). I believe you shouldn't be detaching in-place. In oth...
python|machine-learning|pytorch|lstm|recurrent-neural-network
1
16,230
57,511,329
ValueError: Error when checking target: expected conv2d_37 to have shape (57, 57, 16) but got array with shape (120, 120, 3)
<p>my training variable shape is (264, 120, 120, 3) trying to give numpy array of images as input </p> <pre><code>model = Sequential() model.add(Conv2D(8, (3, 3), activation='relu', strides=2,input_shape=(image_height,image_width,channels))) model.add(Conv2D(16, (3, 3), activation='relu')) model.summary() model.comp...
<p>This error was because of mismatch in shape between model output and training data. </p> <p>Please refer sample code in below </p> <pre><code>#Import Dependencies import keras from keras.models import Model, Sequential from keras.layers import Conv2D, Flatten, Dense # Model Building model = Sequential() model....
python-3.x|tensorflow|keras|conv-neural-network
0
16,231
43,844,510
Is Session.run(fetches) guaranteed to execute its "fetches" arguments in-order?
<p>Is <code>Session.run(fetches, feed_dict)</code> guaranteed to execute its <code>fetches</code> arguments in-order?</p> <p>The documentation doesn't seem to mention it.</p> <p>For example, if you run</p> <pre><code>sess.run([accuracy, train_op], feed_dict=feed_dict) </code></pre> <p>the order of execution matters...
<p>No. By default, Tensorflow is free to evaluate operators in any order. Because of concurrency, that order may even change between runs. This is usually a good thing because it means that Tensorflow may make optimal use of the available hardware. It can be problematic if your code mutates state such as Variables.</p>...
python|machine-learning|tensorflow
10
16,232
43,845,783
Python - count distinct rows from a dataframe
<p>I have a dataframe in the following format:</p> <pre><code>UserId, CurrentUserLocationId, RegisteredUserLocationId, RestorauntId </code></pre> <p>I wish to count the amount of unique appearances of the key <code>(UserId, CurrentUserLocationId, RegisteredUserLocationId)</code></p> <p>For example, if the pair <code...
<pre><code>DataFrame.drop_duplicates() DataFrame.count </code></pre> <p>If necessary duplicate the dataframe before dropping duplicates and when making the duplicate dataframe only call in the columns you want to be unique combinations.</p>
python|database|pandas|numpy|anaconda
2
16,233
43,652,054
Subset columns with NaN values in Pandas
<p>Searched and tried several answers here on SO, but they are all for returning rows with NaN's. I'd like to return only the columns with NaN values. For example the following df. How can I select columns 'A' and 'LG'?</p> <pre><code>df = pd.DataFrame( {'H': ['a','b', 'c'], 'A': [np.nan,'d', 'e'], ...
<p>I think you need first replace strings <code>NaN</code> to <code>np.nan</code> in sample:</p> <pre><code>df = pd.DataFrame( {'H': ['a','b', 'c'], 'A': [np.nan,'d', 'e'], 'LG':['AR1', 'RO1', np.nan], }) </code></pre> <p>Then check by <a href="http://pandas.pydata.org/pandas-docs/s...
python|pandas
4
16,234
43,548,122
pandas operation on several files and merge
<p>I need to perform pandas df operations on multiple files, </p> <pre><code>df1 = pd.read_csv("~/pathtofile/sample1.csv") some_df=pd.read_csv("~/pathtofile/metainfo.csv") df1.sort_values('col2') df1 = df1[df1.col5 != 'N'] df1['new_col'] = df1['col3'] - df1['col2'] + 1 f = lambda row: '{col1}:{col2}-{col3}({col4})'.fo...
<p>Well I just quickly put this together for the aforementioned code. I would suggest learning how to write scripts and generalize things. I didn't clean up the code or take out redundancies, I will leave that up to you. This should work from the command line if the code you posted works.</p> <pre><code>import sys imp...
python|pandas
1
16,235
73,040,498
How to check if values in column are NOT null and then output a specific value to another column using a function in pandas
<p>I am currently writing a function in pandas to try to check rows in a column to see if they are not null. If they are not null, I want something to be outputed to a new column and for this case it would be 'Financing'. Basically if a row has a value for loan funded date, I want the phrase Financing to be printed to ...
<p>Instead of iterating over the rows you can use:</p> <p><strong>Edit</strong>: Just read the last part about 'Cash/Credit' when both are null.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'Loan Funded Date': [1, np.nan, np.nan], 'Claim Approved Date': [np.nan, 1, np.nan]}) df['Payment Typ...
python|pandas|dataframe|function
0
16,236
73,159,250
How to find the distance between a point x,y and the diagonales?
<p>I need to find the distance of O and N with the diagonales (with a 90° angle/ the shortest). I found a formula online, but why in this case, it does not return the good distance ? And if possible, how to normalize the result (e.g. O is at20% of the diagonale?)</p> <pre><code>import numpy as np import math O = (1,3)...
<pre><code> d = abs((a * x1 + b * y1 + c)) / (math.sqrt(a * a + b * b)) </code></pre> <p>Your computation is wrong because a, b and c refer to the coefficients of the equation of the line <strong>ax+by+c=0</strong></p> <pre><code>import numpy as np O = (1,3) N = (3,2) M, L, I, H = (-1,-2), (3, -2), (3, 2), (-1, 2) ...
image|numpy|math|geometry
1
16,237
72,874,936
How to split a row into two rows in python based on delimiter in Python
<p>I have the following input file in csv</p> <pre><code>A,B,C,D 1,2,|3|4|5|6|7|8,9 11,12,|13|14|15|16|17|18,19 </code></pre> <p>How do I split column C right in the middle into two new rows with additional column E where the first half of the split get &quot;0&quot; in Column E and the second half get &quot;1&quot; in...
<p>Here's how to do it without Pandas:</p> <pre class="lang-py prettyprint-override"><code>import csv with open(&quot;input.csv&quot;, newline=&quot;&quot;) as f_in, open(&quot;output.csv&quot;, &quot;w&quot;, newline=&quot;&quot;) as f_out: reader = csv.reader(f_in) header = next(reader) # read header h...
python|pandas|dataframe|csv
3
16,238
72,939,670
Increase GPU load Mac M1 Tensorflow
<p>I'm new to tensorflow and using the GPU on my M1 Mac. Running my code, I observed a max GPU load of about 45%. Is there a way to increase this up to about 100%?</p> <p><a href="https://i.stack.imgur.com/0URfC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0URfC.png" alt="enter image description h...
<p>Your GPU appears to be underutilized because it can't perform faster than you instruct it to.</p> <p>Typically you can increase the GPU load by increasing the batch dimension -- all else being equal.</p> <p>For instance, if the batch dimension is 1 with utilization at 45%, if you change the batch dimension to 2 it s...
python|tensorflow|gpu|apple-m1|metal
1
16,239
73,015,062
How can I multiply matrices of matrices elementwise using numpy (and not for loops)?
<p>I have some 4-dimensional numpy arrays for which the easiest visualisation is a matrix of arbitrary size (not necessarily square) in which each element is a 2x2 square matrix. I would like to standard matrix multiply (@) the 2x2 matrices of the large matrices elementwise (producing another matrix of the same dimensi...
<p>As Homer512 stated in a comment, <code>np.matmul</code>, aka the <code>@</code> operator, will handle this scenario (see the <a href="https://numpy.org/doc/stable/reference/generated/numpy.matmul.html#numpy.matmul" rel="nofollow noreferrer">numpy docs</a>). You will need to make sure your 2 x 2 matrices are in the l...
python|numpy|matrix|4d
0
16,240
70,537,488
cannot import name '_registerMatType' from 'cv2.cv2'
<p>I got below error message when I run <code>model_main_tf2.py</code> on Object Detection API:</p> <pre><code>Traceback (most recent call last): File &quot;/content/models/research/object_detection/model_main_tf2.py&quot;, line 32, in &lt;module&gt; from object_detection import model_lib_v2 File &quot;/usr/loc...
<p>The same thing occurred to me yesterday when I used Colab. A possible reason may be that the version of opencv-python(4.1.2.30) does not match opencv-python-headless(4.5.5.62). Or the latest version 4.5.5 may have something wrong...</p> <p>I uninstalled opencv-python-headless==4.5.5.62 and installed 4.1.2.30 and it ...
python|tensorflow|object-detection-api
71
16,241
70,707,423
Fill na by applying condition on another column
<p>There is a df which contains two columns. First column has monthly values but the second one only contains quarterly values. I want to fill the NA values of second column by the same percentage change on the first column. For example, the original df looks like this:</p> <pre><code> ColA ColB 2019-12-3...
<p>You could simply compute a ratio, ffill it, and use combine_first to update missing values:</p> <pre><code>ratio = (df['ColB'] / df['ColA']).ffill() df['ColB'] = df['ColB'].combine_first(df['ColA'] * ratio) </code></pre> <p>It is enough to get the expected result:</p> <pre><code> ColA ColB 2019-12-31 1...
python|pandas|fillna
1
16,242
70,700,015
Nested for loops to calculate max. temperature from a csv
<p>I'm starting a class on advanced data structures and I'm struggling to answer the problems shown in the image below.The NYC_temperature.csv has hourly temperatures and you have to calculate it by day to then show what was the warmest 30-day period</p> <p><a href="https://i.stack.imgur.com/z6MDS.png" rel="nofollow no...
<pre><code>for i in range(len(data)-24*30-1): temp = 0 for j in range(i, i+30): temp += data[j] maxtemp = max(temp, maxtemp) </code></pre>
numpy|nested-loops|cumsum
0
16,243
70,460,646
One to many comparison of data in two different DFs
<p>I have two Dataframes</p> <pre><code> df1 df2 fname lname age fname lname Position 0 Jack Lee 45 0 Jack Ray 25 1 Joy Kay 34 1 Chris Kay 34 2 Jeff Kim 54 2 ...
<p>Using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>pd.merge()</code></a> with <code>indicator=True</code> will return a clear comparison between the two dataframes based on the columns 'fname' and 'lname':</p> <pre><code>df = pd.merge(df2, ...
python|pandas
0
16,244
42,741,009
How to retain the index position back to the ouput when/after running pandas iterrorws?
<p>In the following pandas dataframe:</p> <pre><code>d1 = pd.read_csv('to_count.mcve.txt', sep='\t') d1 = d1.set_index(['pos'], append=True) M1 M2 F1 F2 pos 0 23 A,B,A,C,D A,C,B A D 1 24 A,B,B,C,B A,B,A B B 2 28 C,B,C,D,E B,C E C </...
<p>You can replace the two lines above your for loop with the below lines. This will create empty DataFrames with the index having the same names as the index of <code>d1</code>.</p> <pre><code>hapX_count = pd.DataFrame(index=d1.index[0:0]) hapY_count = pd.DataFrame(index=d1.index[0:0]) </code></pre>
python|pandas|indexing|dataframe
1
16,245
25,059,936
Normalization of several time-series of different lengths and scale
<p>Say I have several random time-series in numpy, e.g.:</p> <pre><code>my_time_series = dict() for L in range(20,50,10): scaling = np.random.randint(100) my_time_series[L] = scaling * np.random.rand(L) + scaling * np.random.rand(L) </code></pre> <p>I would like to <strong>normalize</strong> them <strong>in sca...
<pre><code>y_normed = {k: (data-np.mean(data))/np.std(data) for k, data in my_time_series.items()} maxlength = max(my_time_series) x_interped = {k: np.interp(np.linspace(0, 1, maxlength), np.linspace(0, 1, k), data) for k, data in y_normed.items()} [plot(data) f...
python|numpy|matplotlib|scipy
7
16,246
30,653,986
Pandas: How do I assign multiple values based on different combinations of column content?
<p>I would like to create a new column with a numerical value based on the following conditions:</p> <p>a. if color=blue &amp; pet=dog, points=10</p> <p>b. if color=blue &amp; pet=cat, points=8</p> <p>c. if pet=snake &amp; gender=female, points=7</p> <p>d. if pet=mouse &amp; gender=male, points = 6</p> <p>All rows...
<p>Rather than doing a very long one-liner, I think 4 separate assignments which are masked using <code>loc</code> would be more readable:</p> <pre><code>In [4]: df.loc[(df['color']=='blue') &amp; (df['pet']=='dog'), 'points'] = 10 df.loc[(df['color']=='blue') &amp; (df['pet']=='cat'), 'points'] = 8 df.loc[(df['pet']=...
python|pandas
3
16,247
30,452,578
Python: count the matrix values according to the threshold
<p>Help me, please) I have a numpy array 160x160 What i need is to count an amount of indexes whose value is between value a and b. What i tried: A - my matrix</p> <pre><code>for i in A: for j in A[i]: if A[i,j] &lt; 0.1 and A[i,j]&gt; 0: m=collections.Counter(don't know what to write here) </code>...
<p>Here's an example extension for the comment</p> <p>Let <code>arr</code> be random array</p> <pre><code>In [33]: arr = np.random.rand(160,160) </code></pre> <p>Get the number of elements which are <code>&gt;0 &amp; &lt;0.1</code></p> <pre><code>In [34]: ((arr&gt;0) &amp; (arr&lt;0.1)).sum() Out[34]: 2649 </code>...
python|sorting|numpy
1
16,248
26,807,177
Overlapping polygons in Python PIL
<p>Instead of overwriting the overlapping regions of multiple polygons by the value of the last polygon drawn, I would like to draw the mean value of these polygons. Is this possible in Python PIL?</p> <p>The overlapping pixels in the example should have the value of 1.5.</p> <p>In the full working program I have to ...
<p>I suggest <code>scikit-image</code>, <code>skimage.draw.polygon()</code> returns coordinates in the polygon. Here is an example. Create some random polygon data first:</p> <pre><code>import pylab as pl from random import randint import numpy as np from skimage import draw W, H = 800, 600 def make_poly(x0, y0, r, ...
python|numpy|python-imaging-library|polygon|computational-geometry
6
16,249
39,085,051
Convert 160 bit Hash to unique integer ids for machine learning input
<p>I am preparing some data for k-means clustering. At the moment I have the id in 160 bit hash format (this is the format for bitcoin addresses). </p> <pre><code>d = {'Hash' : pd.Series(['1HYKGGzRHDskth2ecKZ2HYvxSvQ1p87m6', '3DndG5HuyP8Ep8p3V1i394AUxG4gtgsvoj', '1HYKGGzRHDskth2ecKZ2HYvxSvQ1p87m6']), 'X1' : pd.S...
<p>There are quite a few ways. One way would be to use Categorical codes, and another would be to rank them:</p> <pre><code>In [16]: df1["via_categ"] = pd.Categorical(df1.Hash).codes + 1 In [17]: df1["via_rank"] = df1["Hash"].rank(method="dense").astype(int) In [18]: df1 Out[18]: Ha...
python|pandas|numpy|k-means
1
16,250
39,302,670
How to copy one DataFrame column in to another Dataframe if their indexes values are the same
<p>After creating a DataFrame with some duplicated cell values in column with the name 'keys':</p> <pre><code>import pandas as pd df = pd.DataFrame({'keys': [1,2,2,3,3,3,3],'values':[1,2,3,4,5,6,7]}) </code></pre> <p><a href="https://i.stack.imgur.com/M9c0P.png" rel="nofollow noreferrer"><img src="https://i.stack.img...
<p>There are several ways to do this. Using the <code>merge</code> function off the dataframe is the most efficient.</p> <pre><code>df_both = df_sum.merge(df_mean, how='left', on='keys') df_both Out[1]: keys sums means 0 1 1 1.0 1 2 5 2.5 2 3 22 5.5 </code></pre>
python|pandas
3
16,251
39,302,252
Getting a cropped combination of 9 2D numpy arrays (only want boundaries of middle array)
<p>I have 9 individual 2D numpy arrays that are each 3x3, I want to join at the edges like example:</p> <p><code> 111222333 111222333 111222333 444555666 444555666 444555666 777888999 777888999 777888999 </code></p> <p>Except I only want the nearby boundaries of any array that isn't the middle one, like example:</p> ...
<p>Since you know you want to drop the first and last two columns of your 9x9 array, I would just use NumPy's indexing:</p> <pre><code>&gt;&gt;&gt; x = np.arange(81).reshape((9,9)) &gt;&gt;&gt; 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, 2...
python|arrays|numpy
1
16,252
39,106,248
Python Numpy - attach three arrays to form a matrix or 3D array
<p>This is my simple of piece of code</p> <p>Everything is a numpy array. I welcome manipulation using lists too.</p> <pre><code>a = [1,2,3,4,5] b = [3,2,2,2,8] c = ['test1', 'test2', 'test3','test4','test5'] </code></pre> <p>expected Outcome: </p> <pre><code>d = [ 1, 2, 3, 4, 5; 3, 2, 2, 2, 8; 'test1...
<p>Adam's <a href="https://stackoverflow.com/q/39106248/6748857">answer</a> using <code>numpy.concat</code> is also correct, but in terms of specifying the exact shape you are expecting — rows stacked vertically — you'll want to look at <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html" rel...
python|arrays|numpy
3
16,253
29,129,095
Save additional attributes in Pandas Dataframe
<p>I recall from my MatLab days using structured arrays wherein you could store different data as an attribute of the main structure. Something like:</p> <pre><code>a = {} a.A = magic(10) a.B = magic(50); etc. </code></pre> <p>where <code>a.A</code> and <code>a.B</code> are completely separate from each other allowi...
<p><a href="https://github.com/pydata/pandas/issues/2485">There is an open issue</a> regarding the storage of custom metadata in NDFrames. But due to the multitudinous ways pandas functions may return DataFrames, the <code>_metadata</code> attribute is not (yet) preserved in all situations.</p> <p>For the time being, ...
python-2.7|pandas
37
16,254
33,681,911
plotting a timeseries graph in python using matplotlib from a csv file
<p>I have some csv data in the following format.</p> <pre><code>Ln Dr Tag Lab 0:01 0:02 0:03 0:04 0:05 0:06 0:07 0:08 0:09 L0 St vT 4R 0 0 0 0 0 0 0 0 0 L2 Tx st 4R 8 8 8 8 8 8 8...
<p>I'd suggest using <a href="http://pandas.pydata.org/" rel="nofollow noreferrer">pandas</a>:</p> <pre><code>import pandas as pd a=pd.read_csv('yourfile.txt',delim_whitespace=True) for x in a.iterrows(): x[1][4:].plot(label=str(x[1][0])+str(x[1][1])+str(x[1][2])+str(x[1][3])) plt.ylim(-1,10) plt.legend() </code>...
python|numpy|matplotlib|time-series|data-analysis
1
16,255
22,716,177
How to join two dataframes on datetime index autofill non matched rows with nan
<pre><code>x_index=pd.date_range(dt.date(2010,1,1),dt.date(2010,1,5)) y_index=pd.date_range(dt.date(2010,1,2),dt.date(2010,1,6)) x = pd.DataFrame({"AAPL":[1,2,3,4,5]}, index=x_index) y = pd.DataFrame({"GE": [1,2,3,4,5]}, index=y_index) </code></pre> <p>The result should be:</p> <pre><code> AAPL GE 2010-01-...
<p>As you don't have a common column you need to specify to use the indices of both dataframes and that you want to perform an 'outer' merge:</p> <pre><code>In [226]: x.merge(y, how='outer', left_index=True, right_index=True) Out[226]: AAPL GE 2010-01-01 1 NaN 2010-01-02 2 1 2010-01-03 3 ...
python|pandas
9
16,256
13,240,176
Template Matching (Image Search) function in Python Imaging Library
<p>I had a problem where I need to search for a pattern (present as a numpy ndarray) within another image (also present as a numpy ndarray) and compute a template match (minimum difference position in the image). My question is... is there any in-built image that I can possibly use in the Python Imaging Library or Nump...
<p>This is likely best done as an inverse convolution or correlation. Numpy/scipy has code to do both. </p> <p>edit: including a little example.</p> <p>Go here for the ipython notebook file: <a href="http://nbviewer.ipython.org/4020770/" rel="nofollow">http://nbviewer.ipython.org/4020770/</a></p> <p>I made a lit...
python|image-processing|numpy|python-imaging-library|template-matching
1
16,257
13,539,868
Plotting dates with sharex=True leads to ValueError: ordinal must be >= 1
<p>When doing some analysis, I stumbled upon a ValueError and I could boil it down to the following simple example which can reproduce the error I got:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import datetime as dt x = np.array([dt.datetime(2012, 10, 19, 10, 0, 0), dt.datetime(2...
<p>The error is avoided if you plot something on the second axis:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import datetime as dt x = np.array([dt.datetime(2012, 10, 19, 10, 0, 0), dt.datetime(2012, 10, 19, 10, 0, 1), dt.datetime(2012, 10, 19, 10, 0, 2), ...
python|numpy|matplotlib
16
16,258
62,311,986
Counting in Multiindex DataFrame In pandas
<p>I have the following df2:</p> <pre><code>df2 Out[94]: Symbols ADANIPORTS.NS ASIANPAINT.NS ... WIPRO.NS ZEEL.NS Date ... 2015-06-15 NaN NaN ... NaN NaN 2015-06-16 0.010160 0.009162 ... -0.001109 0.0169...
<p>You use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.gt.html" rel="nofollow noreferrer"><code>df.gt</code></a> with sum over axis 1.</p> <pre><code>df2.gt(0.5).sum(1) </code></pre>
python|python-3.x|pandas|dataframe|multi-index
1
16,259
62,244,505
How to create time series graph in Python which shows changes over the days or months?
<p>I have DataFrame where one column names "X" has value and second "Y" is timestamp, DataFrame looks like below:</p> <p><a href="https://i.stack.imgur.com/eStac.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eStac.png" alt="enter image description here"></a></p> <p>The type of this column "X" is ...
<p>Assuming you already read you dataset into arrays named X and Y, For you x-axis you can generate an numpy array</p> <pre><code>x_axis_arr = np.arange(len(Y)) </code></pre> <p>Then, after you plot with matplotlib, you can change the x-axis labels with</p> <pre><code>plt.plot(X, x_axis_arr) plt.xticks(Y) </code></p...
python|pandas|graph
0
16,260
62,066,899
Map NumPy Values
<p>Let's say I have a NumPy array:</p> <pre><code>x = np.array([[0, 5], [1, 6], [4, 3], [2, 4], [3, 2]]) </code></pre> <p>and a "look-up" array that tells me how to map one integer (first column) to another (second column):</p> <pre><code>lookup = np.array([[0,...
<p>Hope this helps!</p> <pre><code>x = np.array([[0, 5], [1, 6], [4, 3], [2, 4], [3, 2]]) lookup = np.array([[0, 50], [1, 16], [2, 47]]) # building a dictionary lookup = {each[0]:each[1] for each in lookup} vfunc = np.vec...
python|numpy
0
16,261
62,085,973
Inference time of tiny-yolo-v3 on GPU
<p>I am doing inference of tiny-yolo-v3 on google collab using GPU runtime. GPU used was Tesla P100-PCIE-16GB. </p> <p>After running the darknet inference command , The predicted time shown was 0.91 seconds.</p> <p>I could see from code that this time stamp is the processing time of the network on GPU which excludes ...
<p>You have to make the darknet with GPU enabled, in order to be able to use GPU to perform inference, and the time you get for inference currently, is because the inference is being done by CPU, rather than GPU. I came across this problem, and on my own laptop, I got an inference time of 1.2 seconds. After I enabled C...
tensorflow|deep-learning|gpu|yolo|darknet
1
16,262
62,203,307
pandas dataframe to series
<p>I have this dataframe:</p> <pre><code>pd.DataFrame({"X": [1,2,3,4], "Y": [5,6,7,8], "Z": [9,10,11,12]}) </code></pre> <p><a href="https://i.stack.imgur.com/ncQIV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ncQIV.png" alt="enter image description here"></...
<p>Use flattening with <code>ravel('F')</code> -</p> <pre><code>In [14]: pd.Series(df.to_numpy(copy=False).ravel('F')) Out[14]: 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 11 12 dtype: int64 </code></pre> <p>This series is a view into the input dataframe, whi...
python|pandas|numpy
7
16,263
62,218,478
Sorting Vader Sentiment Analysis Results in Dictionary
<p>Is there a commonly used method for sorting multiple Vader Sentiment Analysis Results in Dictionary</p> <p><strong>I am trying to sort by 'compound' Vader Sentiment Analysis Results in the review Dictionary.</strong></p> <p>I just started learning nlp and Sentiment Analysis and got my first project to 95% so far b...
<p>The direct sorting doesn't work because your dictionary values are strings, not dictionaries or lists. To sort by compound you need to extract it's value at first. Here is a simple example of how you can do it by using regex and lambda:</p> <pre class="lang-py prettyprint-override"><code>import re def extract_com...
python|pandas|dictionary|nlp|nltk
1
16,264
62,254,173
Make index first row in group in pandas dataframe
<p>I was wondering if it were possible to make the first row of each group based on index, the name of that index. Suppose we have a df like this: </p> <pre><code>dic = {'index_col': ['a','a','a','b','b','b'],'col1': [1, 2, 3, 4, 5, 6]} df = pd.DataFrame(dic).set_index('index_col') </code></pre> <p><a href="https://i...
<p>The result is a <code>pandas.Series</code>;</p> <pre><code>df_list = [] for label , group in df.groupby('index_col'): df_list.append(pandas.concat([pandas.Series([label]), group['col1']])) df_result = pandas.concat(df_list).reset_index(drop=True) </code></pre> <p>Output;</p> <pre><code>0 a 1 1 2 2 3...
python|pandas|dataframe|indexing|expand
2
16,265
62,428,613
Importing .tflite(model) and .txt(labels) into react native project
<p>I am currently trying to incorporate tensorflowlite into my react native project. I am following this documentation: <a href="https://www.npmjs.com/package/tflite-react-native#Image-Classification" rel="nofollow noreferrer">https://www.npmjs.com/package/tflite-react-native#Image-Classification</a></p> <p>I have cur...
<p>The <a href="https://awesomeopensource.com/project/shaqian/tflite-react-native?categoryPage=47" rel="nofollow noreferrer">doc</a> explains that you place the model as <code>app/src/main/assets/model.tflite</code>, but in your code you address them as <code>models/model.tflite</code>.</p>
react-native|tensorflow|expo|tensorflow-lite
0
16,266
62,270,442
How to convert a dataframe into the dataframe for Apriori Algorithm
<p>I have a dataframe look like this <a href="https://i.stack.imgur.com/Z1WLZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z1WLZ.png" alt="enter image description here"></a></p> <p>My goal is to find what products are sold together the most. Therefore, I decided to use Apriori Algorithm so I'm tr...
<p>Just group by ID and get a list of products, feed an array of those into apriori.</p> <pre><code>from apyori import apriori df = pd.DataFrame({'ID':[1,2,1,2,3,2], 'product':['ball','bat','bat','car','baloon','ball']}) list(apriori(df.groupby('ID')['product'].apply(list).values)) </code></pre> <p>Output</p> <pre...
python|pandas|algorithm|apriori
0
16,267
62,444,189
Python Pandas fill missing zipcode with values from another datafrane based on conditions
<p>I have a dataset in which I add coordinates to cities based on zip-codes but several of these zip-codes are missing. Also, in some cases cities are missing, states are missing, or both are missing. For example:</p> <pre><code> ca_df[['OWNER_CITY', 'OWNER_STATE', 'OWNER_ZIP']] OWNER_CITY OWNER_STATE OWNER...
<p>Given <code>ca_df</code>:</p> <pre><code> OWNER_CITY OWNER_STATE OWNER_ZIP 0 Miami Shore Florida 111 1 Los Angeles California NaN 2 Houston NaN NaN </code></pre> <p>and <code>df_coord</code>:</p> <pre><code> OWNER_ZIP CITY STATE 0 111 Miami Shore ...
python|pandas|numpy
2
16,268
62,146,183
Applying pandas bar style to a dataframe using values from another dataframe
<p>I have df1 and df2. I want to show bars in cells of df1 using values from df2. I was able to apply other forms of styling using below code, but with bars you cannot use this method.</p> <pre><code>def color_cells(s): if s &gt; 90: return 'color:{0}; font-weight:bold'.format('green') elif s&gt;80: ...
<p>Here's the code that does that: </p> <pre><code>df1=pd.DataFrame(np.random.rand(15, 10)) df2=pd.DataFrame(np.random.rand(15, 10)*100) pct = (df2 - df2.min()) / (df2.max() - df2.min() )*100 def make_bar_style(x): return f"background: linear-gradient(90deg,#5fba7d {x}%, transparent {x}%); width: 10em" pct.a...
python|pandas|pandas-styles
4
16,269
62,411,030
Unable to read parquet file using spark due to ExecutorLostFailure
<p>I want to read parquet files using Spark but it generates a Py4J error: Unable to create executor.</p> <p>This is how I generate the parquet file:</p> <pre><code>import pandas as pd df = pd.DataFrame(data={'col1': [1, 2], 'col2': [3, 4]}) df.to_parquet('df.parquet') </code></pre> <p>I read it as follows:</p> <pr...
<p>There was a version mismatch. Spark was at 2.3.0 and PySpark was at 2.4.3.</p> <p>In my notebook, I ran, <code>!pip install pyspark==2.3.0</code> and then, the schema was inferred and no more errors.</p>
python|pandas|apache-spark|pyspark
0
16,270
62,354,777
Convert Float Obj in Dataframe for CountVectorizer & bow_transformer
<p>I am trying to load a dataframe into into bag of words and CountVectorizer but I get TypeError: 'float' object is not iterable when going loading from mess equal a test sentence to mess equaling the dataframe I need to use.</p> <p>the example corpus on <a href="https://scikit-learn.org/stable/modules/generated/skle...
<p><strong>Based Ben Reiniger Comment</strong></p> <p>I looked for the missing values in the dataframe. Even though it was complete there was thousands of fully blank ones added.</p> <p>I counted nan</p> <pre><code>count_nan = len(mess) - mess.count() count_nan </code></pre> <pre><code>bios 9682 artistName...
python|python-3.x|pandas|scikit-learn|nlp
0
16,271
48,237,906
Python matrix inverse
<p>I have a camera matrix <code>k</code> which I have computed. The value of <code>k</code> is:</p> <pre><code>[[ 1.92160183e+08 0.00000000e+00 3.06056985e+02] [ 0.00000000e+00 1.92160183e+08 1.57709172e+02] [ 0.00000000e+00 0.00000000e+00 1.00000000e+00]] </code></pre> <p>Now, I have tried to find t...
<p>Your understanding on what the <code>*</code> operator does is flawed. It does not perform a dot product. But instead performs an <em>elementwise multiplication</em> on the two arrays, also known as the <a href="https://en.wikipedia.org/wiki/Hadamard_product_(matrices)" rel="nofollow noreferrer">Hadamard product</a>...
python|arrays|numpy|matrix-inverse
6
16,272
48,114,587
Downsampling from 1 month to multiple months in Pandas
<p>I have a dataset that spans 36 months. I want to downsample for periods of 3 months. I use:</p> <pre><code>df = df.resample('3M').sum() </code></pre> <p>However, when I look at the output, it does not seem to separate the period of months correctly. For example, here's 36 months of data:</p> <pre><code>1901-01-01...
<p>You need parameter <code>closed='left'</code> it looks for the latest possible start, because default parameter <code>closed='rigth'</code> looks for the earliest possible start.</p> <p>Docs of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow noreferrer"><c...
python|pandas|time-series
4
16,273
48,104,001
Pandas Read_CSV incorrectly reads numbers
<h1>Method1</h1> <pre><code>def getAndBuildDatafrmeFromCsvBasic(filename): colTypes = {'Open': 'float64', 'High': 'float64', 'Low': 'float64', 'Close': 'float64', 'Volume': 'float64'} dfEurUsd2017 = pd.read_csv(filename, delimiter=",", index_col='Gmt time', dtype=colTypes, parse_dates=['Gmt time']) return ...
<p>I added dayfirst=True and your code works fine. </p> <p>What pandas version are u using? And where would that falsy data come from?</p> <pre><code>import pandas as pd data = '''\ Gmt time,Open,High,Low,Close,Volume 04.12.2017 23:00:00.000,1.18686,1.18699,1.18666,1.18682,2004.4599999999998 04.12.2017 23:30:00.000,...
python|python-3.x|python-2.7|pandas
1
16,274
48,484,124
Counting combinations over pairs of columns in a numpy array
<p>I have a matrix with a certain number of columns that contain only the numbers 0 and 1, I want to count the number of [0, 0], [0, 1], [1, 0], and [1, 1] in each PAIR of columns.</p> <p>So for example, if I have a matrix with four columns, I want to count the number of 00s, 11s, 01s, and 11s in the first and second ...
<p>Starting with this - </p> <pre><code>x array([[0, 1, 1, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 1], [1, 1, 0, 0]]) </code></pre> <p>Split your array into groups of 2 columns and concatenate them:</p> <pre><code>y = x.T z = np.concatenate([y[i:i + 2] for i in range(0, y.shape[0], 2)],...
python|arrays|numpy
3
16,275
48,710,409
How to print a Tensor Flow variable to 2 decimal places?
<pre><code>weights = tf.Variable(tf.truncated_normal([2,3])) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print('Weights:') print(sess.run(weights)) print("{0:2f}".format(sess.run(weights))) </code></pre> <p>The first print statement works as expected. </p> <pre><code>Weight...
<p>You trying to print the whole array and <code>format</code> expects single value that could be represented as float. Try like this:</p> <pre><code>print(np.around(sess.run(weights), 2) #[[ 0.31 0.30 0.11] # [ 0.27 -0.21 -0.59]] </code></pre> <p>Also, the correct format would be <code>0:.2f</code></p>
python|tensorflow
1
16,276
48,516,981
Unable to Plot Hbar in Bokeh [Pandas]
<p>Im trying to plot a HBar for a dataframe. The code below works perfect for another dataframe but for the current dataframe, there seems to be no output at all. </p> <p>Following is the code:</p> <pre><code>from bokeh.models import ColumnDataSource, DataRange1d, Plot, LinearAxis, Grid,Label,LabelSet,HoverTool from ...
<p>I adjusted the imports as follows (testing on a Jupyter notebook)</p> <pre><code>from bokeh.models import ColumnDataSource, DataRange1d, Plot, LinearAxis, Grid,Label,LabelSet,HoverTool from bokeh.models.glyphs import HBar from bokeh.plotting import figure, output_notebook from bokeh.io import show output_notebook(...
python|pandas|jupyter-notebook|bokeh
0
16,277
48,619,600
Stagnant validation accuracy during training of vgg net with 10000 images
<p>I have 10000 images 5000 diseased Medical images and 5000 healthy images, I used vgg16 and modified last layers as follows</p> <pre><code>Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) (None, 224, 224, ...
<p>You can try the following: </p> <ul> <li><p>Perform a stratified <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html" rel="nofollow noreferrer">train_test_split</a> </p> <pre><code>train_test_split(x, y, stratify=y, test_size=0.2, random_state=2) </code></pre></...
python-3.x|tensorflow|machine-learning|deep-learning|keras
1
16,278
48,807,344
How to replace values in multiple categoricals in a pandas DataFrame
<p>I want to replace certain values in a dataframe containing multiple categoricals.</p> <pre><code>df = pd.DataFrame({'s1': ['a', 'b', 'c'], 's2': ['a', 'c', 'd']}, dtype='category') </code></pre> <p>If I apply <code>.replace</code> on a single column, the result is as expected:</p> <pre><code>&gt;&gt;&gt; df.s1.re...
<p>Without digging, that seems to be buggy to me.</p> <p><strong>My Work Around</strong><br> <code>pd.DataFrame.apply</code> with <code>pd.Series.replace</code><br> This has the advantage that you don't need to mess with changing any types. </p> <pre><code>df = pd.DataFrame({'s1': [1, 2, 3], 's2': [1, 3, 4]}, dtype=...
python|pandas|replace|categories
3
16,279
48,816,962
Getting average of column in pandas
<p>I'm trying to be able to read a file where I will pull what the name of the location is and then calculate the average amount of snow they get. This is what I have so far.</p> <pre><code>import pandas data = pandas.read_csv('filteredData.csv') if ('NAME' == 'ADA 0.7 SE, MI US'): data.ix['1/1/2016':'12/31/2016']...
<p>Looks like you can use <code>groupby()</code>:</p> <pre><code>import pandas as pd from datetime import datetime # Create test data df = pd.DataFrame({ "name": ["place1", "place1", "place1", "place2", "place2", "place2"] * 2, "date": ["1/1/2016", "1/2/2016", "1/3/2016"] * 2 + ["1/1/2017", "1/2/2017", "1/3/2...
python|pandas
0
16,280
70,813,833
Normalise JSON response
<p>I have the following code</p> <pre><code>import requests import json import pandas as pd url = &quot;https://www.pedrofonseca.eu/trabalho/projectoslei/api/projects/getByLegislature/XIV&quot; response = requests.get(url) json = response.json() df_final= pd.json_normalize( json, record_path =['authors'], ...
<p>This error is happening because some items don't have author properties, we have to filter out items with no authors in the list my brother.</p> <pre class="lang-py prettyprint-override"><code>import requests import json import pandas as pd url = &quot;https://www.pedrofonseca.eu/trabalho/projectoslei/api/projects/...
python|json|pandas|dataframe
1
16,281
70,843,107
when loading a model in tensorflow.js for node, the weights aren't loaded/saved
<p>When I load a trained model (In tensorflow.js within Node.js) that I have previously saved, the model topology is being loaded, but none of the weights are loaded (so I have to train the model from scratch). No errors are thrown.</p> <p>To save the model, I am using:</p> <pre><code>async function save(path) { //...
<p>save() and loadLayersModel() are async functions.</p> <p><code>model.save(url).then(result =&gt; console.log(result));</code></p> <p><code>tf.loadLayersModel(url).then(result =&gt; console.log(result))</code></p>
javascript|node.js|tensorflow.js
0
16,282
70,881,131
Row wise operation in Pandas DataFrame
<p>I have a Dataframe as</p> <pre><code>import pandas as pd df = pd.DataFrame({ &quot;First&quot;: ['First1', 'First2', 'First3'], &quot;Secnd&quot;: ['Secnd1', 'Secnd2', 'Secnd3'] ) df.index = ['Row1', 'Row2', 'Row3'] </code></pre> <p>I would like to have a <code>lambda</code> function in <code>apply</code> metho...
<p>You don't need apply here. You can just use the to_dict() function with the &quot;index&quot; argument:</p> <pre><code>df.to_dict(&quot;index&quot;) </code></pre> <p>This gives the output:</p> <pre><code>{'Row1': {'First': 'First1', 'Secnd': 'Secnd1'}, 'Row2': {'First': 'First2', 'Secnd': 'Secnd2'}, 'Row3': {'Firs...
python|pandas|dataframe
3
16,283
70,838,079
Handling Timestamps Python Panda
<p>I am new to Python and trying to learn as much as I can. I am trying to create a live graph with Matplotlib by reading from a CSV file. It seems that I am having a TypeError: value, I am guessing from the timestamp format. From what I read on Pandas infobase, The date_parser should take care of this, but i am unsure...
<p><em>I state that I am not an expert on pandas or matplotlib.</em></p> <p>Looking at your code I think that the problem lies in the data definition of the CSV file.<br /> You pass to <code>read_csv</code> the array <code>names</code> with 4 fields, but your CSV has lots more columns.</p> <p>Trying your code, if I rem...
python|pandas|date|graph
0
16,284
51,778,531
How to convert seconds to hours in x-axis with matlplotlib?
<p>I have a series data from one day which has 86400 datapoints. I try to plot this in a picture using using matplotlib. However, I want to change the x-axis to be hours like 00:00 01:00.</p> <p>Now my picture is: <a href="https://i.stack.imgur.com/Csy4I.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.c...
<p>You can use custom labels for the x-axis, see <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.xticks.html" rel="nofollow noreferrer">here</a> for more information. In this case, you could simply change your current <code>plt.xticks(xlim)</code> to:</p> <pre><code>plt.xticks(xlim, ['00:00', '04:00', '0...
python|numpy|matplotlib
1
16,285
51,905,216
cx_Freeze converted exe: window closes immediately
<p>I am trying to just convert my pygame python py to a .exe file using cx_Freeze. The setup file executes correctly and without error, but the issue is that when I run my .exe file the console window (the black cmd-like window)will open quickly and close. My .py which I want to convert is called Salary.py, and it incl...
<p>It looks like your Salary.py script uses the <code>pandas</code> package, is this correct? The <code>pandas</code> package requires the <code>numpy</code> package to work, and one needs to tell cx_Freeze explicitly to include the <code>numpy</code> package. Try to add the following <code>options</code> to <code>setu...
python-3.x|pandas|numpy|cx-freeze
0
16,286
51,981,070
From size (1000,9) and (1000,10) matrix to matrix of size (1000,90)
<p>I have two matrices: - A (1000,9) - B (1000,10)</p> <p>Now A[0,0] should be multiplied by B[0,0], B[0,1], ... B[0,9]</p> <p>A[0,1] should be multiplied by B[0,0], B[0,1], ... B[0,9]</p> <p>A[1,0] should be multiplied by B[1,0], B[1,1], ... B[1,9]</p> <p>etc</p> <p>Such that the resulting matrix has size (1000,9...
<pre><code>C = A[:, tf.newaxis, :] * B[:, :, tf.newaxis] </code></pre> <p>This gives us a [1000, 10, 9] tensor where element [i, j, k] is A[i, k] * B[i, j]. Then we reshape</p> <pre><code>C = tf.reshape(C, [tf.shape(A)[0], -1]) </code></pre> <p>to [1000, 90]. If I'm not mistaken, each row i of C will first have B[i,...
tensorflow|linear-algebra|matrix-multiplication
3
16,287
41,965,080
I can't graph this for the life of me
<p>Countless hours staring at this changing everything around, I'm going crazy! I'm lost. I can't get this data to plot. I feel I am very close, but no cigar. I want there to be a line vs. time. Any help would be appreciated.</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd #this is how I usua...
<p>This works for me</p> <pre><code>force['datetime'] = pd.to_datetime(force['date'] + " " + force['time']) force.set_index('datetime').presst.plot() </code></pre> <p><a href="https://i.stack.imgur.com/qLkGp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qLkGp.png" alt="enter image description he...
python|python-2.7|pandas
1
16,288
64,607,641
Python : How do I perform the below Dataframe Operation
<p>I have two dataframes</p> <p><a href="https://i.stack.imgur.com/Ysurc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ysurc.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/r7PQW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r7PQW.png" alt="ent...
<p>Here is possible convert values to numpy array and flatten with pass to <code>DataFrame</code> cosntructor:</p> <pre><code>df = pd.DataFrame({'Name': np.ravel(df2.to_numpy()), 'Income': np.ravel(df1.to_numpy())}) print (df) Name Income 0 abc -13036.0 1 dfd -30360.0 2 deb 1200.0 ...
python|pandas|dataframe
3
16,289
64,369,743
Efficient ways of assigning value based on conditional in Pandas?
<p>The objective is to assign a value to the column <code>EXPECTED T</code>. The value to be assigned is <code>C1 S + C2 B</code> if there is <code>EM</code> in column <code>C2 B</code>, else the value is image of the value at <code>C2 B</code>.</p> <p>To realise the objective, the following code is propose</p> <pre...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mask.html" rel="nofollow noreferrer"><code>Series.mask</code></a>, also is possible use here <a hr...
python|pandas|conditional-statements
2
16,290
64,574,112
(python) Iterating through a list of Salesforce tables to extract and load into AWS S3
<p>Good Morning All!</p> <p>I'm trying to have a routine iterate through a table list. The below code works on a single table 'contact'. I want to iterate through all of the tables listed in my tablelist.csv. I bolded the selections below which would need to be dynamically modified in the code. My brain is pretty ...
<p>Would help if you could provide a sample of the tablelist file, but here's a stab at...you really just need to get list of tables and loop through it.</p> <pre><code>#assuming table is a column somewhere in the file df_tablelist = pd.read_csv('tablelist.csv', header=none) for Contact in df_tablelist['yourtablecolumt...
python|pandas|amazon-s3
0
16,291
64,256,526
trying to install numpy in python3.9 and getting error in preparing wheel metadata in windows 10. I did not checked using virtual environment
<p>When trying to install <code>numpy</code> I am getting the following error:</p> <pre class="lang-none prettyprint-override"><code>C:\Users\lenovo&gt;pip install numpy Collecting numpy Using cached numpy-1.19.2.zip (7.3 MB) Installing build dependencies ... done Getting requirements to build wheel ... done ...
<p>Python 3.9 came out 3 days ago (today - Oct 8, 2020). It doesn't have wheels for numpy yet.</p> <p>See <a href="https://pythonspeed.com/articles/switch-python-3.9/" rel="nofollow noreferrer">here</a></p> <blockquote> <p>But it’s so soon after 3.9’s release, many packages don’t have wheels for Python 3.9 yet. For exa...
python|numpy|pip
8
16,292
64,299,001
Merging multiple panda frames
<p>I have a bunch of CSV files which contain data for a specific time and time is encoded as the filename:</p> <pre><code>time1.csv Label val1 val2 a 5 6 b. 6 4 time2.csv Label val1 val2 a 5 6 c 6 4 ... </code></pre> <p>I can read each file into a Pandas data frame. Then I want to: Add ...
<p>Given the list of filenames, you can assign a time column to equal the filename (excluding the last four characters, i.e. <code>.csv</code>) and concatenate the result.</p> <pre><code>df = pd.concat([pd.read_csv(filename).assign(time=filename[:-4]) for filename in filenames]) </code></pre>
python|pandas
1
16,293
47,845,610
Regression using Python
<p>I have the following variables:</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split np.random.seed(0) n = 15 x = np.linspace(0,10,n) + np.random.randn(n)/5 y = np.sin(x)+x/6 + np.random.randn(n)/10 X_train, X_test, y_train, y...
<p>At the start of your line</p> <pre><code>n = 15 </code></pre> <p>You stopped with identing. So that part isn't recognized as the function. This can be solved by putting 4 spaces on all lines from n = 15 onwards.</p>
python|numpy|regression
0
16,294
58,732,795
How do I extract indices of non-equivalent entries between two tensors?
<p>I have a tensor with N predictions of N objects' classes, and I have another tensor with the real N target objects' classes. I would like to pull out the tensor indices where my classifier predictions are wrong. </p> <p>Consider the two following tensors defined as:</p> <pre><code>import torch predictions = torch....
<p>Something like</p> <pre><code>index_diff = (predictions.flatten() != target.flatten()).nonzero().flatten() </code></pre> <p>should work.</p>
python|pytorch|tensor
2
16,295
58,856,701
Cascade groupby/transform operations
<p>Lets say I have a set of groups and subgroups, with dates and values.</p> <p>What I need in the end is to evaluate a rolling mean, with window 2, of the values by month by group (the value for the current month is evaluated using the past 2 months).</p> <p>I can achieve that If I reduce the dataframe by two consec...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>DataFrame.merge</code></a> with list of columns - here <code>on</code> is missing, because merge by intersecion of all common columns of both DataFrames:</p> <pre><code>df = df.merge(d...
python|pandas
2
16,296
58,786,001
TFLite Inference on video input
<p>I have an SSD tflite detection model that I am running with Python on a desktop computer. As for now, my script below takes a single image as an input for inference and it works fine:</p> <pre class="lang-py prettyprint-override"><code> # Load TFLite model and allocate tensors. interpreter = tf.lite.Interpre...
<p>To Answer your first question of running inference on a video. Here is the code that you can use. I made this code for the inference of classification model, So in your case the output of the output_data variable will be in the form of bounding boxes, you have to map them on the frames using OpenCV which answer your...
python|tensorflow-lite|inference
3
16,297
58,806,718
Python: float() argument must be a string or a number
<p>I need to load an image to the array. Then I want to show it by pyplot. The problem is somewhere in between. </p> <p>I tried different types of imread. I got to install only the one from pyplot which my cause problem.</p> <pre><code>import numpy as np from matplotlib.pyplot import imread images = [] img = imread(...
<p>The <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.resize.html" rel="nofollow noreferrer"><code>img.resize()</code> method</a> resizes your data <em>in place</em> and returns <code>None</code>. Don't use the return value to create an array, just use <code>img</code> directly. It's a nump...
python|numpy|matplotlib
2
16,298
58,794,464
How to get value from data set from based on characteristics shared with inputted string
<p>I'm currently experimenting with python databases, and requesting info them. I'm trying to check if a data set (csv file):</p> <pre><code>Keyword, Word_num hello,3 yup,4 yup,5 </code></pre> <p>shares words with an inputted string. Here's what I have so far. </p> <pre><code>import csv import pandas as pd #creates...
<p>First of all, please share your question in a reproducible way so others can create your data, such as:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Keyword': ['hello', 'world', 'yup'], 'Word_num': [3, 4, 5]}) </code></pre> <p>Secondly, do not name any object with the reserved specia...
python|python-3.x|pandas
0
16,299
70,098,506
Applying pd.get_dummies to dataframe but alter output
<p>I am using pd.get_dummies on this example dataframe below- and it's working properly but I want to see if anyone has an idea of how to alter the results. I'll describe below:</p> <p>Original DF</p> <pre><code> ID type AA23 A AB24 B DJ44 B KD33 C KD33 A BK89 B BL92 B BL92 ...
<p>One option is to just do the whole thing with a <code>.groupby()</code>:</p> <pre><code>In [36]: df.groupby([&quot;ID&quot;, &quot;type&quot;]).agg(lambda x: 1).unstack().fillna(0).astype(int).add_prefix(&quot;type_&quot;) Out[36]: type type_A type_B type_C ID AA23 1 0 0 AB24 0 1 ...
python|pandas
2