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
6,600
64,094,295
How to plot a vertical line on a time series axis?
<p>I would like to 'link' two pieces of code. One,</p> <pre><code>x= df[df['Value']==True].sort_values(by='Date').head(1).Date Out[111]: 8 2020-03-04 </code></pre> <p>extracts the date where the first value appears; the other one</p> <pre><code>df[df['Buy']==1].groupby('Date').size().plot(ax=ax, label='Buy') </code...
<ul> <li>Make certain the <code>Date</code> column is in a <code>datetime</code> format.</li> </ul> <pre class="lang-py prettyprint-override"><code>import pandas as pd import random # for test data import matplotlib.pyplot as plt # setup sample data random.seed(365) rows = 40 data = {'Date': [random.choice(pd.bdate_r...
python|pandas|matplotlib
1
6,601
64,154,762
"builtin_function_or_method' object has no attribute 'reshape'" what does this mean?
<p>I'm a novice, so this question may be somewhat obvious for someone.</p> <pre><code>import numpy as np print(&quot;array&quot;) array = np.arange(8) matrix = np.array.reshape(2,4) print(matrix) </code></pre> <p>The result is this.</p> <pre><code>array ------------------------------------------------------------------...
<p>It looks like you're calling reshape on <code>np.array</code>, which is a function that is used to create a new array.</p> <p>You already created your variable <code>array</code>. Try to use this variable instead of <code>np.array</code>:</p> <pre><code>import numpy as np print(&quot;array&quot;) array = np.arange(8...
python|arrays|numpy
1
6,602
46,718,178
Dataframe columns to key value dictionary pair
<p>I have following <code>DataFrame</code> </p> <pre><code> product count Id 175 '409' 41 175 '407' 8 175 '0.5L' 4 175 '1...
<pre><code>In [14]: df.set_index('product').T.to_dict('r') Out[14]: [{'0.5L': 4, '1.5L': 4, '407': 8, '409': 41, 'SCHWEPPES': 6, 'TONIC 1L': 4}] </code></pre>
python|pandas|dataframe
3
6,603
46,903,963
Python, numpy, piecewise answer gets rounded
<p>I have a question with regards to the outputs of numpy.piecewise.</p> <p>my code:</p> <pre><code>e=110 f=np.piecewise(e,[e&lt;120,e&gt;=120],[1/4,1]) print(f) </code></pre> <p>As a result i get: 0 and not the desired 0.25</p> <p>Can someone explain me why piecewise seems to be rounding my answer? Is there a way ...
<p>From the <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.piecewise.html" rel="nofollow noreferrer"><code>np.piecewise</code> docs</a>:</p> <blockquote> <p>The output is the same shape and type as x</p> </blockquote> <p>Integer in, integer out. If you want a floating-point output, you n...
python|numpy|piecewise
0
6,604
32,751,512
Renaming columns in pandas dataframe using regular expressions
<pre><code> Y2010 Y2011 Y2012 Y2013 test 0 86574 77806 93476 99626 2 1 60954 67873 65135 64418 4 2 156 575 280 330 6 3 1435 1360 1406 1956 7 4 3818 7700 6900 5500 8 </code></pre> <p>Is there a way to rename the columns of this dataframe from Y2010... to 2010.. i.e. removi...
<p>I'd use map:</p> <pre><code>In [11]: df.columns.map(lambda x: int(x[1:])) Out[11]: array([2010, 2011, 2012, 2013]) In [12]: df.columns = df.columns.map(lambda x: int(x[1:])) In [13]: df Out[13]: 2010 2011 2012 2013 0 86574 77806 93476 99626 1 60954 67873 65135 64418 2 156 575 280 330...
python|pandas
13
6,605
33,051,460
Numpy array of dicts
<p>In Python, I have a dict has pertinent information</p> <pre><code>arrowCell = {'up': False, 'left': False, 'right': False} </code></pre> <p>How do I make an array with i rows and j columns of these dicts?</p>
<p>How to make a two dimensional i &amp; j is explained really well on the site already at this: <a href="https://stackoverflow.com/questions/6667201/how-to-define-two-dimensional-array-in-python">How to define two-dimensional array in python</a> link.</p> <p>Hope this helps, cheers!</p>
python|numpy|dictionary|multidimensional-array
1
6,606
63,221,468
RuntimeError: DataLoader worker (pid 27351) is killed by signal: Killed
<p>I'm running the data loader below which applies a filter to a microscopy image prior to training. In order to count the red and green. This code filters the red cells. Since I have applied this to the code I keep on getting the error message above. I have tried increasing the memory allocation to the maximum allowan...
<p>Similar problem I met before. <br/> One possible solution is to disable <code>cv2</code> multi-processing by</p> <pre class="lang-py prettyprint-override"><code>def __getitem__(self, idx): import cv2 cv2.setNumThreads(0) # ... </code></pre> <p>in your dataloader. It might be because the <code>cv2</code> ...
python|image-processing|deep-learning|pytorch
3
6,607
63,147,465
Having trouble creating a scatter plot for my kmeans clustering data
<p>I am trying to use kmeans clustering to perform some anomaly detection on a simple dataset.</p> <p>I have some data in two variables. x and x_ax.<br /> Here is an example of the x data</p> <pre><code>array([[44360.125], [56385.958333333336], [61500.5], [61227.375], [60049.333333333336], ...
<p>You just have to add <code>fig, ax = plt.subplots(1,1)</code> and everything works fine:</p> <pre><code>import numpy as np import pandas as pd from sklearn.cluster import KMeans import matplotlib.pyplot as plt x = np.array([[44360.125], [56385.958333333336], [61500.5], [612...
python|pandas|matplotlib|scikit-learn
1
6,608
62,962,527
Python 3.7.0 Heroku buildpack issue
<p>I've read some people with the same issue, but nothing suggested has worked. I'm trying to deploy a silly project to Heroku but nothing is working.</p> <p>Below this lines you can see the message:</p> <blockquote> <p>Writing objects: 100% (100/100), 55.42 MiB | 625.00 KiB/s, done. Total 100 (delta 19), reused 4 (del...
<p>UPDATE: the problem was the structure itself. I had to place the requirements.txt and Procfile at the root directory.</p>
python|tensorflow|flask|heroku|buildpack
1
6,609
62,916,388
Numpy module not found when working with Azure Functions in VS Code and virtualenv
<p>I'm new to working with azure functions and tried to work out a small example locally, using VS Code with the Azure Functions extension.</p> <p>Example:</p> <pre><code># First party libraries import logging # Third party libraries import numpy as np from azure.functions import HttpResponse, HttpRequest def main(r...
<p>For this problem, I'm not clear if you met the error when run it locally or on azure cloud. So provide both suggestions for these two situation.</p> <p><strong>1.</strong> If the error shows when you run the function on azure, you may not have installed the modules success. When deploy the function from local to azu...
python|numpy|azure-functions|virtualenv
4
6,610
67,856,625
comparing columns by ignoring null values (pandas)
<p>data frame:</p> <pre><code> data=pd.DataFrame({'name':['A','B','C'], 'rank':[np.nan,2,3], 'rank1':[2,np.nan,2], 'rank2':[3,1,np.nan], 'rank4':[4,2,3]}) </code></pre> <p>my code:</p> <pre><code> data['Diff']=np.where((data['rank']&lt;data['rank1'])&amp;(data['...
<p>We can <code>filter</code> the <code>rank</code> like columns, then forward fill on <code>axis=1</code> to propagate last valid value, then calculate <code>diff</code> along <code>axis=1</code> to check for monotonicity</p> <pre><code>r = df.filter(like='rank') data['diff'] = r.ffill(1).diff(axis=1).fillna(0).ge(0)....
python|pandas
5
6,611
67,657,240
Pandas GrroupBy - get column with name "count"
<p>I try to get count of each category in DataFrame as:</p> <pre><code>data = {'col_1': ['a', 'b', 'c', 'd','c'],'col_2': [3, 2, 1, 0, 4],'col3':[99,88,77,66,55]} df = pd.DataFrame.from_dict(data) print(df.groupby(['col_1']).count()) Output: col_2 col3 col_1 a 1 1 b 1 1...
<p>You can do:</p> <pre><code>print(df.groupby(['col_1'],as_index=False).agg(count=('col_2','count'))) </code></pre> <p><strong>OR</strong></p> <pre><code>print(df.groupby(['col_1'],as_index=False).size().rename(columns={'size':'count'})) </code></pre> <p>Output:</p> <pre><code>col_1 count a 1 ...
python|pandas
1
6,612
67,860,456
Want to check the cell by cell value of dataframe is null or not if found null then it should fill with 0 using pandas
<p>I just wanted to check the cell by cell value of the dataframe is null or nan if found nan then it should be fill with zero using pandas .I have one csv file which contains the some NAN values</p> <pre><code>import pandas as pd df = pd.read_csv(&quot;samp.csv&quot;) print(df) for rowindex, row in df.iterrows(): ...
<p>There's a dedicated command for that: <code>df.fillna(0)</code>.</p> <p>The full code would then be:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.read_csv(&quot;samp.csv&quot;) df = df.fillna(0) </code></pre>
python|pandas
1
6,613
68,008,973
How to subtract a value from the first element of an array?
<p>I want to subtract a number <code>x</code> from the first element of the array, and in case the first element in the array is smaller than <code>x</code> I want to subtract the remaining amount from the second element of the array and so on.</p> <p>I have tried this:</p> <pre><code>import numpy as np x = 25 y = np....
<ul> <li><p>In the <code>if</code> case, you should assign <code>0</code></p> </li> <li><p>In the <code>else</code> case there must be a <code>break</code> to stop as all value to remove has been consumed</p> </li> </ul> <pre><code>def sub_array(array, to_remove): result = np.copy(array) for i in range(len(arr...
python|arrays|numpy
1
6,614
67,711,752
How to extract tensors to numpy arrays or lists from a larger pytorch tensor
<p>I have a list of pytorch tensors as shown below:</p> <pre><code>data = [[tensor([0, 0, 0]), tensor([1, 2, 3])], [tensor([0, 0, 0]), tensor([4, 5, 6])]] </code></pre> <p>Now this is just a sample data, the actual one is quite large but the structure is similar.</p> <p><strong>Question:</strong> I want to extr...
<p>OK, you can just do this.</p> <pre><code>out = np.concatenate(list(map(lambda x: x[1].numpy(), data))) </code></pre>
python|list|numpy|pytorch|tensor
2
6,615
67,606,907
Computing the loss of a function of predictions with pytorch
<p>I have a convolutional neural network that predicts 3 quantities: Ux, Uy, and P. These are the x velocity, y-velocity, and pressure field. They are all 2D arrays of size [100,60], and my batch size is 10.</p> <p>I want to compute the loss and update the network by calculating the CURL of the predicted velocity with ...
<p>You could try something like this:</p> <pre><code>def discrete_curl(self, pred): new_arr = torch.zeros((pred.shape[0],100,60)) for pred_idx in range(pred.shape[0]): for m in range(100): for n in range(60): if n &lt;= 58: if m &lt...
python|machine-learning|neural-network|pytorch|autograd
1
6,616
31,732,728
Numpy array being rounded? subtraction of small floats
<p>I am assigning the elements of a numpy array to be equal to the subtraction of "small" valued, python float-type numbers. When I do this, and try to verify the results by printing to the command line, the array is reported as all zeros. Here is my code:</p> <pre><code>import numpy as np np.set_printoptions(precisio...
<p>You're declaring the array with <code>v1 = np.array([0,0,0])</code>, which numpy assumes you want an int array for. Any subsequent actions on it will maintain this int array status, so after adding your small number element wise, it casts back to int (resulting in all zeros). Declare it with </p> <pre><code>v1 = np...
python|arrays|numpy|rounding|pretty-print
6
6,617
41,456,831
Writing data into MySql in pandas tosql in python
<p>I am inserted data successfully. but i want to get the result whether data is inserted or not. my code is:</p> <pre><code>unit_type.to_sql(con=self.mysql_hermes.conn, name='CiqHistEleData', if_exists='append', flavor='mysql', index=False) </code></pre> <p>i want...
<p>Sorry, that's not going to work because the to_sql method does not return a value. The usual approach in pandas is to raise exceptions rather than return True/False so in the same spirit you will have to sorround your code with try/except. TypeError and ValueError are two typical exceptions raised by to_sql</p> <pr...
python|pandas
1
6,618
41,347,203
how to filter by day with pandas
<p>I am reading a series of data from file via pd.read_csv(). Then somehow I create a dataframe like the following:</p> <pre><code> col1 col2 01/01/2001 a1 a2 02/01/2001 b1 b2 03/01/2001 c1 c2 04/01/2001 d1 d2 01/01/2002 e1 e2 02/01/2002 f1 d2 03/01/...
<p>First thing I'd do is make sure your index are dates. If you know they are, then skip this.</p> <pre><code>df.index = pd.to_datetime(df.index) </code></pre> <p>Then you <code>groupby</code> with something like <code>[df.index.month, df.index.day]</code> or <code>df.index.strftime('%m-%d')</code>. However, you ha...
pandas
0
6,619
61,563,765
Adding column to pandas dataframe taking values from list in other column
<p>I'm new to Python so I'm sorry if terminology is not correct; I've searched for similar posts but didn't find anything helpful for my case. I have a dataframe like this:</p> <pre><code> Column1 Column2 0 0001 [('A','B'),('C','D'),('E','F')] 1 0001 [('A','B'),('C','D'),('E','F')] 2 0001 ...
<p>We can do <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.lookup.html" rel="nofollow noreferrer"><code>df.lookup</code></a> after <code>groupby+cumcount</code></p> <pre><code>idx = df.groupby('Column1').cumcount() df['new']= pd.DataFrame(df['Column2'].tolist()).lookup(df.index,i...
python|pandas
2
6,620
61,442,914
Python error using Panda AttributeError: 'Series' object has no attribute 'asType'
<p>I'm following a pluralsight course to learn Python data manipulation, and have an error in the first module! I'm using Jupyter Notebooks, with Python 3.7 and Pandas 1.0.1. Can anyone help please?</p> <pre><code>import pandas as pd data = pd.read_csv('artwork_sample.csv') data.dtypes </code></pre> <p>Returns:</p>...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.astype.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.astype.html</a> Looks like a type of uppercase in asType I looked for the uppercase and could not find it.</p>
python|python-3.x|pandas
1
6,621
68,732,135
Index pandas dataframe rows 4 at a time
<p>I want to to be able to something along the lines of:</p> <pre><code>for i in range(0, len(df), 4): curr = pd.DataFrame() vcch = int(df.loc[i, 'IN_CUSTOM_SELECT']) icch = int(df.loc[i+1, 'IN_CUSTOM_SELECT']) vccl = int(df.loc[i+2, 'IN_CUSTOM_SELECT']) iccl = int(df.loc[i+3, 'IN_CUSTOM_SELECT']) ...
<p>If you're just working with a regular autonumbered index, one easy option is to reshape your data and use <code>pandas</code> vectorized operations for the math:</p> <pre><code>In [196]: df = pd.DataFrame({'IN_CUSTOM_SELECT': np.random.random(24)}) In [197]: reshaped = df.set_index([df.index.map(lambda x: x // 4), ...
python|pandas
0
6,622
36,398,041
How to generate a sample sentence with LSTM model in Tensorflow?
<p>I'm working with the <a href="https://www.tensorflow.org/versions/r0.7/tutorials/recurrent/index.html#recurrent-neural-networks" rel="nofollow">LSTM model in Tensorflow</a>.<br> I already trained and saved the LSTM model. Now I'm coming up to the last task to generate the sentences. Here is my pseudo code:</p> <pr...
<p>when you train you have an output of the neural network, based on that output you calculate the error, based on error you create the optimizer to minimize the error. </p> <p>In order to generate a new sentence you need to get just the output of the neural network(rnn). </p> <p>Edited: </p> <pre><code>""" Placehol...
tensorflow|lstm
3
6,623
36,676,576
Map a NumPy array of strings to integers
<p><strong>Problem:</strong></p> <p>Given an array of string data</p> <pre><code>dataSet = np.array(['kevin', 'greg', 'george', 'kevin'], dtype='U21'), </code></pre> <p>I would like a function that returns the indexed dataset</p> <pre><code>indexed_dataSet = np.array([0, 1, 2, 0], dtype='int') </code></pre> <p>an...
<p>You can use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.unique.html" rel="noreferrer"><code>np.unique</code></a> with the <code>return_inverse</code> argument:</p> <pre><code>&gt;&gt;&gt; lookupTable, indexed_dataSet = np.unique(dataSet, return_inverse=True) &gt;&gt;&gt; lookupTable ar...
python|arrays|string|performance|numpy
22
6,624
36,249,233
Optimize Double For Loop Using NumPy
<p>I have a python function with a nested for loop that is called thousands of times, and is too slow. From what I have read online, there should be a way to optimize it with numpy vectorization so that the iteration is done in much faster C code rather than python. But, I have never worked with numpy before and I can'...
<p>Here a function which return 2 arrays, rows indices and cols indices of the pixels where value is <code>val</code>in the selected subarray :</p> <pre><code>def filter_indices_numpy(a,rows,cols,val): sub=a[meshgrid(rows,cols,indexing='ij')] r,c = (sub==val).nonzero() return take(rows,r),take(...
python|arrays|python-2.7|numpy|vectorization
0
6,625
65,535,770
Solving linear vector addition for positive integer coefficients
<p>Say I have multiple different vectors of the same length</p> <p>Example:</p> <pre><code>1: [1, 2, 3, 4] 2: [5, 6, 7, 8] 3: [3, 8, 9, 10] 4: [6, 9, 12, 3] </code></pre> <p>And I want to figure out the optimal integer coefficients for these vectors such that the sum of the vectors is closest to a respective specified ...
<p>You could write your problem as a system of linear-equations:</p> <pre><code>arr1[0] + b*arr2[0] + c*arr3[0] + d*arr4[0] = res[0] a*arr1[1] + b*arr2[1] + c*arr3[1] + d*arr4[1] = res[1] a*arr1[2] + b*arr2[2] + c*arr3[2] + d*arr4[2] = res[2] a*arr1[3] + b*arr2[3] + c*arr3[3] + d*arr4[3] = res[3] #For all positive a,b,...
python|arrays|numpy|linear-algebra
1
6,626
65,735,328
How to best use @tf.function decorator for class methods?
<p>To examplify my problem with a minimal example, suppose I would like to create a class in the spirit of</p> <pre class="lang-py prettyprint-override"><code>class test_a: def __init__(self, X): self.X = X def predict(self, a): return a * self.X </code></pre> <p>Importantly, the <code>predict()...
<p>To avoid python side effects - <code>self.X</code> should be <code>tf.Variable(trainable=False)</code>. And you have to use <code>tf.Variable.assign()</code> to change it.</p>
python|python-3.x|tensorflow|tensorflow2.0
0
6,627
65,533,768
Pandas apply function throws NotImplementedError
<p>I have a pretty basic df, and I want to create 2 new columns based off of some regex of one column. I created a function to do this which returned 2 values.</p> <pre><code>def get_value(s): result = re.findall('(?&lt;=Value&quot;:&quot;)(\d+)\.(\d+)?(?=&quot;)', s) if len(result) != 2: return -1, -1 ...
<p>First, your regex was a little bit off. Change <code>'(?&lt;=Value&quot;:&quot;)(\d+)\.(\d+)?(?=&quot;)'</code> to <code>'(?&lt;=Value&quot;:&quot;)(\d+\.\d+)?(?=&quot;)'</code>, so that the full float isin one capture group. You were separating the part before the decimal into one group and the part after into anot...
python|pandas|apply
1
6,628
3,195,781
Find n greatest numbers in a sparse matrix
<p>I am using sparse matrices as a mean of compressing data, with loss of course, what I do is I create a sparse dictionary from all the values greater than a specified treshold. I'd want my compressed data size to be a variable which my user can choose.</p> <p>My problem is, I have a sparse matrix with alot of near-z...
<p><code>scipy.stats.scoreatpercentile(arr,per)</code> returns the value at a given percentile:</p> <pre><code>import scipy.stats as ss print(ss.scoreatpercentile([1, 4, 2, 3], 75)) # 3.25 </code></pre> <p>The value is interpolated if the desired percentile lies between two points in <code>arr</code>.</p> <p>So if y...
python|numpy|sparse-matrix
2
6,629
63,702,820
Expand a list in a DataFrame
<p>Lets say I have a list of numbers to concat. The results as follows:</p> <pre> A B ... Z (1,a) [1] [2] (2,b) [3] [4] (3,c) [5,6] [7,8] (4,d) [9] [10] </pre> <p>But I wish to convert it into something more p...
<p>Use <code>pd.Series.explode</code> and reconstruct df from new index, finally <code>concat</code>:</p> <pre><code>s = df.apply(pd.Series.explode) print (pd.concat([pd.DataFrame(s.index.tolist()),s.reset_index(drop=True)], axis=1)) 0 1 A B 0 1 a 1 2 1 2 b 3 4 2 3 c 5 7 3 3 c 6 8 4 4 d ...
pandas|dataframe
1
6,630
63,611,563
Pythonic way to add numeric columns of the individual dataframes of a groupby object
<p>I have a time series data that I group and I want to sum the numerical columns of all the groups together.</p> <p><strong>Note</strong>: This is not an aggregation of column of individual groups, but a sum of corresponding cells of all the dataframes in the group object.</p> <p>Since it's a time series data, a few c...
<p>I think you need aggregate <code>sum</code> - all non numeric columns are exclude by default, so you can add them by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFrame.reindex</code></a> by original columns with repalce missing ...
python|python-3.x|pandas|dataframe
4
6,631
63,477,017
How to obtain all values assoicated with a multi-column grouping in pandas
<p>First off, I apologize if this question is not clear. I will extrapolate on what I mean here.</p> <p>Basically, I am looking for a way to obtain all values in one column that correspond to a multi-column grouping. My original dataframe has three columns: latitude, longitude, and building ID. There are different buil...
<p>You could try with <code>set_index</code>, <code>agg</code> and <code>sort_values</code>:</p> <pre><code>df.set_index('BldgID').agg(tuple,1)\ .reset_index().rename(columns={0:'Lat/Lon'}).sort_values('Lat/Lon') </code></pre> <p>Output:</p> <pre><code> BldgID Lat/Lon 1 2 (27.87265, -67.28715)...
python|pandas
1
6,632
63,611,749
Python Polygon external boundary
<p>Given some coordinates I'm trying to draw the external boundary of a polygon. But with the code that I attach you below:</p> <pre><code>from shapely.geometry import Polygon lat_point_list = [42.108288,42.13397,42.087456,42.085308000000005,42.087456,42.13397,42.095806, 42.085308000000005,42.10305,42...
<p>You need to decide whether your points are ordered or it is a point cloud.</p> <p>In the first case you need to ensure that each segment doesn't cross any other segment. Otherwise, the points are not in order.</p> <p>In the second case you only have an unordered set of points or point cloud and you may be interested...
python|google-maps|coordinates|polygon|geopandas
1
6,633
21,516,266
Store empty numpy array in h5py
<p>I'd like to write some data to a HDF5 file (since I have huge datasets and was told that HDF5 works well with those kinds of things).</p> <p>I have a Python 2.7 dictionary with some values and some numpy arrays. What I'd like to do is simply dump that dictionary into the HDF5. No groups or whatever, just put the ke...
<p>This is what I use (it might be unnecessary for you since you don't require groups but you might change you mind):</p> <pre><code>def save_group(outfile, d, group): with h5py.File(outfile, 'a') as g: for key in d: value = d[key] try: group.require_dataset(key, val...
python|numpy|hdf5|h5py
0
6,634
29,828,675
Python Pandas : Group by one column and see the content of all columns?
<p>I have a dataframe like this:</p> <pre><code>org group count org1 1 2 org2 1 2 org3 2 1 org4 3 3 org5 3 3 org6 3 3 </code></pre> <p>and this is what I would like to have , one entry from each unique groups from the 'group' column:</p> <pre><c...
<p>You could <code>drop_duplicates</code> on <code>group</code>?</p> <pre><code>In [172]: df.drop_duplicates('group') Out[172]: org group count 0 org1 1 2 2 org3 2 1 3 org4 3 3 </code></pre> <p>Also, <code>df.drop_duplicates(['group', 'count'])</code> works in this case.</p> <p...
python|pandas|group-by|aggregation
3
6,635
29,960,089
How to retrieve values after a function crashes?
<p>How can I retrieve a value from a function after it crashes? E.g. how would I find the value of <code>a</code> after the function completes/crashes.</p> <pre><code>&gt;&gt;&gt; def a_is_3(): ... a=3 ... print 'a='+str(a) ... &gt;&gt;&gt; a_is_3() a=3 &gt;&gt;&gt; a Traceback (most recent call last): File...
<p>try to use <code>global</code></p> <pre><code>&gt;&gt;&gt; def a_is_3(): ... global a ... a = 3 ... print('a=' + str(a)) ... &gt;&gt;&gt; a_is_3() a=3 &gt;&gt;&gt; a 3 &gt;&gt;&gt; </code></pre> <p>This will work quite well in an interactive session - but if you move this to a script later make sure yo...
python|numpy
-1
6,636
53,426,968
Matrix in which rows are coordinates of points of a meshgrid
<p>In <a href="https://jakevdp.github.io/PythonDataScienceHandbook/05.07-support-vector-machines.html" rel="nofollow noreferrer">this tutorial</a> I find code like</p> <pre><code>import numpy as np x = np.linspace(-5, 5, 20) y = np.linspace(-1, 1, 10) Y, X = np.meshgrid(y, x) xy = np.vstack([X.ravel(), Y.ravel()]).T ...
<p>You can skip <code>meshgrid</code> and get what you want more directly by just taking the <a href="https://docs.python.org/3.6/library/itertools.html#itertools.product" rel="nofollow noreferrer">cartesian product</a> of <code>x</code> and <code>y</code>:</p> <pre><code>from itertools import product import numpy as ...
python|arrays|numpy|mesh
2
6,637
20,251,684
Python: Replace every 5th value of numpy array
<p>I've got a numpy array full of floats. How can I replace every 5th value with <code>np.inf*0</code> so that I get a <code>NaN</code> value at every 5th index?</p> <pre><code>my_array = np.array([5.0, 8.1, 3.2, 2.7, 8.4, 4.9 ...]) </code></pre> <p>to</p> <pre><code>my_array = np.array([5.0, 8.1, 3.2, 2.7, NaN, 4.9...
<p>How about using slicing and striding? <code>L[::5]</code> takes every 5th element from list <code>L</code>:</p> <pre><code>&gt;&gt;&gt; my_array = np.arange(20.) &gt;&gt;&gt; my_array[4::5] = np.nan &gt;&gt;&gt; my_array array([ 0., 1., 2., 3., nan, 5., 6., 7., 8., nan, 10., 11., 12., 13...
python|numpy
7
6,638
71,855,464
How to convert .dat to .csv using python? the data is being expressed in one column
<p>Hi i'm trying to convert .dat file to .csv file. But I have a problem with it. I have a file .dat which looks like(column name)</p> <pre><code>region GPS name ID stop1 stop2 stopname1 stopname2 time1 time2 stopgps1 stopgps2 </code></pre> <p>it delimiter is a tab.</p> <p>so I want to convert dat file to csv file. but...
<p>If you're already using pandas, you can just use <code>pd.read_csv()</code> with another delimiter:</p> <pre><code>df = pd.read_csv(&quot;file.dat&quot;, sep=&quot;\t&quot;) df.to_csv(&quot;file.csv&quot;) </code></pre> <p>See also the <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html" rel="...
python|pandas|csv|export-to-csv
2
6,639
71,815,935
Running python script with multiple values of command line arguments
<p>I have a python script for pre-processing audio and it has frame length, frame step and fft length as the command line arguments. I am able to run the code if I have single values of these arguments. I wanted to know if there is a way in which I can run the python script with multiple values of the arguments? For ex...
<p>I found you can do it by these. <a href="https://python-speech-features.readthedocs.io/en/latest/" rel="nofollow noreferrer">mfcc features extraction</a><br /> You can create your own mfcc features extraction or you can limit window lengths and ceptrums that is enough for simple works except you need logarithms scal...
python|tensorflow|mfcc
0
6,640
72,089,220
Filter dataframe to get name of the youngest of a particular gender
<p>I waste 2 hours and shouldn't find solve to my problem. I need filtering from csv Only name of female who has minimal age.</p> <p>I do only this part, and don't know how i can combine my solve in one right solve. Can you please support me, and say what an attributes can help me in my problem.</p> <p>Columns = ['name...
<p>Without seeing more of your data this should be a good enough starting point for you to put your own column names and data.</p> <pre><code>df = pd.DataFrame( { 'Gender':['M', 'F', 'M', 'F', 'M', 'F'], 'Age':[20, 21, 21, 13, 22, 13] } ) df = df.loc[df['Gender'] == 'F'] df['Check'] = np.where(d...
python|pandas|dataframe|numpy|filtering
0
6,641
16,947,336
binning a dataframe in pandas in Python
<p>Given the following dataframe in pandas:</p> <pre><code>import numpy as np df = pandas.DataFrame({&quot;a&quot;: np.random.random(100), &quot;b&quot;: np.random.random(100), &quot;id&quot;: np.arange(100)}) </code></pre> <p>where <code>id</code> is an id for each point consisting of an <code>a</code> and <code>b</co...
<p>There may be a more efficient way (I have a feeling <code>pandas.crosstab</code> would be useful here), but here's how I'd do it:</p> <pre><code>import numpy as np import pandas df = pandas.DataFrame({"a": np.random.random(100), "b": np.random.random(100), "id": np.ara...
python|numpy|pandas
63
6,642
17,913,330
Fitting data using UnivariateSpline in scipy python
<p>I have a experimental data to which I am trying to fit a curve using UnivariateSpline function in scipy. The data looks like: </p> <pre><code> x y 13 2.404070 12 1.588134 11 1.760112 10 1.771360 09 1.860087 08 1.955789 07 1.910408 06 1.655911 05 1.778952 04 2.624719 03 1.698...
<p>There are a few issues.</p> <p>The first issue is the order of the x values. From the documentation for <code>scipy.interpolate.UnivariateSpline</code> we find</p> <pre><code>x : (N,) array_like 1-D array of independent input data. MUST BE INCREASING. </code></pre> <p>Stress added by me. For the data you ha...
python|numpy|scipy|curve-fitting
45
6,643
18,043,849
python pandas organizing multidimensional data into an object
<p>Having historical data from a stock exchange, with a number of stocks, and a number of a given stock's attributes (open, high, low, close, volume), I end up effectively having 3 dimensions in my data, i.e., <code>time stamp</code>, <code>stock's ticker</code> and the <code>attributes</code>. For a single stock (2D),...
<p>I recommend you use a <a href="http://pandas.pydata.org/pandas-docs/dev/dsintro.html#panel" rel="nofollow">Panel</a>, for example:</p> <pre><code>&gt;&gt;&gt; from pandas.io.data import DataReader &gt;&gt;&gt; from pandas import Panel, DataFrame &gt;&gt;&gt; symbols = ['AAPL', 'GLD', 'SPX', 'MCD'] &gt;&gt;&gt; dat...
python|pandas
3
6,644
55,415,663
Is there a faster way to convert big file from hexa to binary and binary to int?
<p>I have a big DataFrame (1999048 rows and 1col), with hexadecimal datas. I want to put each line in binary, cut it into pieces and traduce each piece in decimal format. </p> <p>I tried this: </p> <pre><code>for i in range (len(df.index)): hexa_line=hex2bin(str(f1.iloc[i]))[::-1] channel = int(hexa_line[0:3...
<p>only thing I can imagine helping a lot would be changing these lines:</p> <pre><code>line=np.array([[channel, edge, time, sweep, tag, datalost]]) tab=np.concatenate((tab, line), axis=0) </code></pre> <p>certainly in pandas, and I think also in numpy concatting is an expensive thing to do, and depends on the size o...
python|pandas|performance
0
6,645
55,483,456
How do I match a list of strings to a list of of filenames so I can save those files into one master file?
<p>I have a list of barcodes. I want to read and append files from a folder that match the barcode, but of course the barcodes are not a 1-to-1 match.</p> <p>Example of the Barcode is <code>07002991H3</code> and an Example of the File Name is <code>07002991H3001</code>.</p> <p>I am able to match the barcodes with a ...
<p>You need to give pandas the file path as well as the file name; try </p> <pre class="lang-py prettyprint-override"><code>df = pd.read_csv(os.path.join('//FolderThatContainsFiles', file)) </code></pre>
python|pandas|dataframe|string-matching
0
6,646
55,217,032
for loop and adding additional columns groupby pandas dataframe in Python
<p>below code is my original way.</p> <pre><code>import pandas as pd data = {'id':[1001,1001,1001,1001,1001,1001,1001,1001,1002,1002,1002,1002,1002,1002,1002,1002], 'name':['Tom', 'Tom', 'Tom', 'Tom','Tom', 'Tom', 'Tom', 'Tom','Jack','Jack','Jack','Jack','Jack','Jack','Jack','Jack'], 'team':['A','A', 'B', 'B',...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>DataFrame.pivot_table</code></a> instaed loops with flattening columns in <code>MultiIndex</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/ref...
python|pandas|loops|dataframe|for-loop
4
6,647
55,503,250
How to iterate through rows and query specific fields based on the contents of other fields in the same row?
<p>I've generated a tabular dataset and I'm trying to query and generate a report from it in xls format using python. I've got the data into a pandas dataframe and have all the potentially relevant fields lined up in the right order, now I need to select where specific columns within each row meets a specific criteria....
<p>This takes several steps.</p> <ol> <li>Filter columns bases on <code>_1</code>, <code>_2</code> and <code>_3</code></li> <li>Loop through dataframes and filter <code>type</code> columns on <code>'Car'</code></li> <li><code>Concat</code> the dataframes together to one final dataframe </li> </ol> <p>btw: I think you...
python|pandas|numpy
1
6,648
55,405,948
Processing each row in column
<ol> <li>I'm trying to go through each row in column 'birth' </li> <li>Check if the last part of the string separated by "," ends in two characters 2.a. If it does, I will append "US" to it.</li> </ol> <p>So, "Los Angeles, Ca" would be "Los Angeles, Ca, US" And "Bisacquino, Sicily, Italy" would stay the same</p> <p>I...
<p>We can use the <code>str</code> methods provided by <code>pandas</code> to solve for this. Let's use the following dataframe that I define below.</p> <pre><code>print(df) place 0 Los Angeles, Ca 1 Bisacquino, Sicily, Italy 2 New York, NY condition = df.place.str.sp...
python|pandas|bigdata
0
6,649
56,863,136
Get Percent change where axis equals columns in python pandas?
<p>I have the following dataset:</p> <pre><code>import pandas as pd w = pd.Series(['EY', 'EY', 'EY', 'KPMG', 'KPMG', 'KPMG', 'BAIN', 'BAIN', 'BAIN']) x = pd.Series([2020,2019,2018,2020,2019,2018,2020,2019,2018]) y = pd.Series([100000, 500000, 1000000, 50000, 100000, 40000, 1000, 500, 4000]) z = pd.Series([10000, 10000...
<p>just specify <code>periods=-1</code> and pick column <code>[actual_cost]</code> as follows:</p> <pre><code>df['actual_budget_pct_diff'] = df.pct_change(periods=-1, axis='columns',fill_method='ffill')['actual_cost'] Out[160]: actual_cost budgeted_cost actual_budget_pct_diff consultant fisc...
python|python-3.x|pandas|group-by
3
6,650
56,546,766
Python pandas: How to alter one column that is (complicatedly) based on another?
<p>I have booking data whereas a new row is inserted whenwever a customer iniciates, changes, deletes or reactivates an order. &quot;delivered&quot; shows if the product was actually delivered which is generally the case if the order is not deleted in the last update.</p> <p>Here is some sample code:</p> <pre><code>df ...
<p>Here's one approach using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>GroupBy</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.where.html" rel="nofollow noreferrer"><code>DataFram...
python|pandas|group-by
2
6,651
56,738,233
API call While loop not doing all lines of csv
<p>While loop doesn't send all line parameters before stopping thus finishes after second pass and sometimes directly after first pass.</p> <p>i have tried reducing the number of steps but plays little difference</p> <pre><code>import requests import rek #request script import time import pandas as pd dfbig= pd.read_...
<p>Your code is incrementing <code>final</code> at the end of the loop. On the 2nd iteration <code>final</code> exceeded <code>dfbig.shape[0]</code> (ie: 19+19+19 &lt;= 43 is false) thereby ending the loop. This has the effect of skipping over the last 5 rows.</p> <p>To resolve:</p> <pre><code>step = 19 init = 0 fina...
python|pandas|python-2.7
0
6,652
56,531,463
Find partial matches of words in pandas column of URLs, directly after https://
<p>Basically, I have a dataframe where one column is a list of names, and the other is associated URLs that are related to the name in some way (sample df):</p> <pre><code> Name Domain 'Apple Inc' 'https://mapquest.com/askjdnas387y1/apple-inc', 'https://linkedin.com/apple-inc/askjdnas38...
<h3>Using <code>explode/unnest string</code>, <code>str.extract</code> &amp; <code>fuzzywuzzy</code></h3> <p>First we will unnest your string to rows using <a href="https://stackoverflow.com/a/51752361/9081267">this</a> function:</p> <pre><code>df = explode_str(df, 'Domain', ',').reset_index(drop=True) </code></pre> ...
python|pandas
1
6,653
67,063,843
Non-Identical results from String Identifier and Actual Class names for activations, loss functions, and metrics
<p>I have the following keras model that is working fine:</p> <pre><code>model = tf.keras.Sequential( [ #first convolution tf.keras.layers.Conv2D(16, (3,3), activation=&quot;relu&quot;, input_shape=(IMAGE_SIZE,IMAGE_SIZE,3)), tf.keras.layers.MaxPooling2D(2,2), #second c...
<p>When we set <strong>String Identifier</strong> for accuracy as <code>['acc']</code> or <code>['accuracy']</code>, the program will choose the relevant metrics for our problem, like whether it's binary or categorical type. But when we set the actual class name, we need to be a bit more specific. So, in your case, you...
python|tensorflow|machine-learning|keras|deep-learning
0
6,654
67,154,091
Float 16 quantized Tflite model not working for custom models?
<p>I have a custom tensorflow model which I converted into tflite using the Float16 quantization as mentioned <a href="https://www.tensorflow.org/lite/performance/post_training_quantization#float16_quantization" rel="nofollow noreferrer">here</a>.<br /> But the the input details of the tflite model using the tflite int...
<p>Float16 and post-training quantization don not modify the input/output tensors but the intermediate weight tensors only. The above behavior looks like an intended behavior. If you want to fully quantize your model, try the full integer quantization. You can find the details at <a href="https://www.tensorflow.org/lit...
python|tensorflow|tensorflow-lite
0
6,655
66,861,301
Set cross section of pandas MultiIndex to DataFrame from addition of other cross sections
<p>I am currently trying to assign rows with certain indices based on the other indices within the group.</p> <p>Consider the following pandas data frame:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np index = pd.MultiIndex.from_product([list('abc'), ['aa', 'bb', 'cc']]) df ...
<p><strong>Update</strong></p> <p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>pandas.DataFrame.iloc</code></a></p> <pre><code>df.iloc[df.index.get_level_values(1)=='cc'] = df.xs('aa', level=1) + df.xs('bb', level=1) </code></pre> <hr /> <...
python|pandas|dataframe|numpy|multi-index
1
6,656
67,012,645
Join two dataframes by the closest datetime
<p>I have two dataframes <code>df_A</code> and <code>df_B</code> where each has date, time and a value. An example below:</p> <pre><code>import pandas as pd df_A = pd.DataFrame({ 'date_A': [&quot;2021-02-01&quot;, &quot;2021-02-01&quot;, &quot;2021-02-02&quot;], 'time_A': [&quot;22:00:00&quot;, &quot;23:00:00&q...
<p>Pandas has a handy <code>merge_asof()</code> function for these types of problems (<a href="https://pandas.pydata.org/docs/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.merge_asof.html</a>)</p> <p>It requires a single key to merge on, so you can c...
python|pandas|datetime|left-join
2
6,657
66,986,109
Why is Python loading numpy 1.20.0 in my dask env when conda says 1.20.1 is installed?
<p>Why is Python loading numpy 1.20.0 in my dask env when conda says 1.20.1 is installed?</p> <pre><code>(dask) ➜ dask: conda list -n dask | grep numpy numpy 1.20.1 py38h18fd61f_0 conda-forge (dask) ➜ dask: python Python 3.8.8 | packaged by conda-forge | (default, Feb 20 2021, 16:22:...
<p>This might happen because by default, python packages installed in the so-called user site (<code>pip install --user package</code> or in newer pip versions automatically when the prefix directory is not writable for the current user) are still considered first in the <code>PYTHONPATH</code>.</p> <p>You can deactiva...
python-3.x|numpy|conda
1
6,658
66,812,693
ValueError: cannot reshape array of size 4096 into shape (64,64,3)
<p>Hi stack overflow friends :)<br /> I trained a CNN model for predicting number images.<br /> Learned it successfully And I want to predict a number from an image in which several numbers.<br /> But I got an error.<br /> I'll show you my dataset and some of my code.</p> <p><strong>Dataset.py</strong></p> <pre><code>b...
<p>Your problem is that you are declaring im_digit to be 2D array but reshaping it to 3D (3 channels). Also note that your img_binary is also single channel (2D) image. All that you need to change is to keep working with gray scale:</p> <pre><code>img_input = np.array(img_digit).reshape(1,64,64,1) </code></pre> <p>This...
tensorflow|opencv|conv-neural-network|reshape
0
6,659
47,161,842
How to merge two pandas dataframes on column of sets
<p>I have columns in two dataframes representing interacting partners in a biological system, so if gene_A interacts with gene_B, the entry in column 'gene_pair' would be {gene_A, gene_B}. I want to do an inner join, but trying:</p> <pre><code>pd.merge(df1, df2, how='inner', on=['gene_pair']) </code></pre> <p>throws...
<p>Pretty simple in the end: I used frozenset, rather than set.</p>
python|pandas|dataframe
1
6,660
68,290,921
Google Colab No Such File or Directory Error
<p>Hello I'm trying to start tensorflow training process on google colab. I'm trying to run this code block in integrated notebook on google colab. Code block is:</p> <pre><code>!apt-get install protobuf-compiler python-pil python-lxml python-tk !pip install Cython %cd '/content/gdrive/My Drive/models/research/' !proto...
<p>You have to first mount your Google drive:</p> <pre><code>from google.colab import drive drive.mount('/content/gdrive') </code></pre> <p>Try to do</p> <pre><code>import os os.listdir(os.getcwd()) </code></pre> <p>This should return</p> <pre><code>['.config', 'sample_data'] </code></pre> <p>before you mount the drive...
python|tensorflow|google-colaboratory
0
6,661
68,036,333
Pandas does not recognize NaN values on M1 macbook pro
<p>Pandas on m1 macbook pro is not recognizing NaN values even though NaN values apparently exist in the data. <a href="https://i.stack.imgur.com/aWPPj.png" rel="nofollow noreferrer">The first picture shows the first 5 rows of the data, and you can apparently see that there are NaN values</a></p> <p><a href="https://i....
<p>Try:</p> <pre><code>data.info() </code></pre> <p>to see what type of variable they are in the dataframe. My guess is that nothing in that column is being recognised as a number.</p>
python|pandas|null|nan|apple-m1
0
6,662
68,365,142
Group by weekdays and plot graph panda
<pre><code>df1=df.groupby(['usertype','day']).size().reset_index(name='times') </code></pre> <p><a href="https://i.stack.imgur.com/69SfT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/69SfT.png" alt="enter image description here" /></a></p> <p>how to plot bar graph by group day and user type.</p>
<p>I think you want this:</p> <pre><code>days = [&quot;Monday&quot;, &quot;Tuesday&quot;, &quot;Wednesday&quot;, &quot;Thursday&quot;, &quot;Friday&quot;, &quot;Saturday&quot;, &quot;Sunday&quot;] &gt;&gt;&gt; df.pivot(index=&quot;day&quot;, columns=&quot;usertype&quot;, values=&quot;times&quot;).reindex(days).plot.bar...
python|pandas|matplotlib
0
6,663
68,061,523
ValueError: Input 0 of layer sequential_7 is incompatible with the layer: : expected min_ndim=4, found ndim=2. Full shape received: (None, 1024)
<p>New Python developer here. I looked at other similar posts here but i'm not able to get it right. Would appreciate any help.</p> <pre><code>print('X_train:', X_train.shape) print('y_train:', y_train1.shape) print('X_test:', X_train.shape) print('y_test:', y_train1.shape) </code></pre> <p>X_train: (42000, 32, 32) y_t...
<p>The input shape you have specified should be changed. Your input has 42000 samples and each one has <code>(32,32)</code> shape. You should not pass number of samples <code>(42000)</code> to input layer, and you should add a channel dimension. So the input shape should be <code>(32,32,1)</code>.</p> <p>The modified c...
python-3.x|tensorflow|machine-learning|keras|tf.keras
1
6,664
59,453,037
Dask - Merge multiple columns into a single column
<p>I have a dask dataframe as below:</p> <pre><code> Column1 Column2 Column3 Column4 Column5 0 a 1 2 3 4 1 a 3 4 5 2 b 6 7 8 3 c 7 7 </code></pre> <p>I want to merge all of the columns into a single one e...
<p>When you have to join string @saravanan saminathan methods wins hands down. Here there are some timing with <code>dask</code></p> <pre class="lang-py prettyprint-override"><code>import dask.dataframe as dd import numpy as np import pandas as pd N = int(1e6) df = pd.DataFrame(np.random.randint(0,100,[N,10])) df = ...
python|pandas|dask
3
6,665
59,331,933
How to create clusters/groups from knowing associations?
<p>I have a dataframe that has 2 columns: [ID, ASSOCIATED_ID] For each ID, I have a list of other associated IDS from the dataframe. Here is a synthesized version of it:</p> <pre><code>ID ASSOCIATED_ID 1 [2,3] 2 [1,4] 3 [1] 4 [2] 5 [] </code></pre>...
<p>IIUC,you can use networkx and connect_components:</p> <pre><code>df_e = df.explode('ASSOCIATED_ID') G = nx.from_pandas_edgelist(df_e, 'ID','ASSOCIATED_ID') [i for i in nx.connected_components(G)] </code></pre> <p>Output:</p> <pre><code>[{1, 2, 3, 4}, {nan, 5}] </code></pre>
python|python-3.x|pandas|algorithm|cluster-analysis
2
6,666
59,262,403
Why does my sigmoid function return values not in the interval ]0,1[?
<p>I am implementing logistic regression in Python with numpy. I have generated the following data set:</p> <pre><code># class 0: # covariance matrix and mean cov0 = np.array([[5,-4],[-4,4]]) mean0 = np.array([2.,3]) # number of data points m0 = 1000 # class 1 # covariance matrix cov1 = np.array([[5,-3],[-3,3]]) mean...
<p>It does, it's just in <a href="https://docs.python.org/3.3/library/string.html#formatspec" rel="nofollow noreferrer">scientific notation</a>.</p> <blockquote> <p>'e' Exponent notation. Prints the number in scientific notation using the letter ‘e’ to indicate the exponent.</p> </blockquote> <pre><code>&gt;&gt;&...
python|numpy|regression|logistic-regression|sigmoid
2
6,667
59,300,346
Getting a file not found error when iterating over a directory
<p>I'm trying to iterate through a file directory in the following way:</p> <pre><code>path = r'C:\my\path' for filename in os.listdir(path): nodes_arr = np.genfromtxt(filename, delimiter=',') </code></pre> <p>And I get an error:</p> <pre class="lang-none prettyprint-override"><code>IOError("%s not found." % pa...
<p><code>os.listdir</code> returns the file names only. Python IO functions, whether called directly (<code>open</code>...) or through <code>numpy</code>, do not actually know that that these names reside in <code>path</code>. Unless your path is the current directory, which will what Python will assume, this will fail...
python|numpy
2
6,668
59,094,787
Unknown error when running train.py or model_main.py
<p>I've been following this guide on github with a couple of changes since I'm using the ssdlite_mobilenet_v2_coco model and I'm getting an unkown error.</p> <p><a href="https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10" rel="nofollow noreferrer">https://gith...
<p>Replace backslash (\) with forward (/) in the file path you specified. It worked for me.</p>
python-3.x|windows|tensorflow|gpu|object-detection
0
6,669
59,202,053
How to find the area under the curve
<p>I am a beginner Python user.</p> <p>There are two data files for the curve (x, y): <a href="https://drive.google.com/open?id=1ZB39G3SmtamjVjmLzkC2JefloZ9iShpO" rel="nofollow noreferrer">https://drive.google.com/open?id=1ZB39G3SmtamjVjmLzkC2JefloZ9iShpO</a></p> <p>How to find two areas under the curve, as shown in ...
<p>You can use Simpsons rule or the Trapezium rule to calculate the area under a graph given a table of y-values at a regular interval.</p> <pre><code>from scipy.integrate import simps from numpy import trapz </code></pre> <p>reference: <a href="https://stackoverflow.com/questions/13320262/calculating-the-area-under-...
python|python-3.x|numpy|data-science|area
0
6,670
59,354,733
Compare a row of a dataframe based on multiple conditions
<p>My dataframe looks like this: </p> <pre><code> price trend decreasing increasing condition_decreasing 0 7610.4 no trend 0.0 False 1 7610.4 no trend 0.0 False 2 7610.4 no trend 0.0 False 3 7610.4 decreasing 7610.4 True 4...
<p>Maybe you want to do this?</p> <pre><code>import pandas as pd import numpy as np price = [7610.3, 7610.3, 7610.4, 7610.4, 7610.4, 7610.4, 7610.3, 7610.3, 7610.9] df = pd.DataFrame({'price': price}) df['diff'] = df['price'].diff() conditions = [ (df['diff'] == 0), (df['diff'] &gt; 0), (df['diff'] &lt; ...
python|pandas
1
6,671
45,250,108
To count every 3 rows to fit the condition by Pandas rolling
<p>I have dataframe look like this: </p> <pre><code>raw_data ={'col0':[1,4,5,1,3,3,1,5,8,9,1,2]} df = DataFrame(raw_data) col0 0 1 1 4 2 5 3 1 4 3 5 3 6 1 7 5 8 8 9 9 10 1 11 2 </code></pre> <p>What I want to do is to count every 3 rows to fit condition(df...
<p>Let's use <code>rolling</code>, <code>apply</code>, <code>np.count_nonzero</code>:</p> <pre><code>df['col_roll_count3'] = df.col0.rolling(3,min_periods=1)\ .apply(lambda x: np.count_nonzero(x&gt;3)) </code></pre> <p>Output:</p> <pre><code> col0 col_roll_count3 0 1 0...
pandas
1
6,672
45,061,902
Converting JSON to CSV w/ Pandas Library
<p>I'm having trouble converting a JSON file to CSV in Python and I'm not sure what's going wrong. The conversion completes but it is not correct. I think there's an issue due to the formatting of the JSON file; however, it's a valid JSON. </p> <p><strong>Here's the content of my JSON file:</strong></p> <pre><code>{ ...
<p>Your json is a nested dict (with lists and other dictionaries). I guess that you are interested in the <code>values</code> section of the <code>json</code>. If my assumption is correct, since this is a single entry json, try the following</p> <pre><code>df = pd.DataFrame.from_dict(json_str['tags'][0]['results'][0][...
python|json|csv|pandas
1
6,673
57,184,622
looping df.query by setting the condition as a variable
<p>So I have multiple criteria and I want to use a loop to query them each time so I can filter the data. So essentially I want to:</p> <pre><code>metric = ["case1", "case2"] #etc df = df.query('Metric == metric[i]') #instead of--&gt; df = df.query('Metric == "case1"') df = df.query('Metric == "case2"') metric = [...
<p>You can do with </p> <pre><code>df.query('Symbol==@metric[0]') </code></pre>
python|pandas
1
6,674
56,938,875
Encoding a column in Pandas based on occurance of value 0
<p>I have a Pandas dataframe with a column like this,</p> <pre><code>df = pd.DataFrame() df['A'] = [1, 1, 0, 1, 1, 0] </code></pre> <p>I want to make another column with values like this,</p> <p><code>[1, 1, 1, 2, 2, 2]</code></p> <p>The idea is to start with value <code>1</code> and increment the value when I get ...
<p>IIUC, you want to count the occurrence of <code>0</code> but shifted:</p> <pre><code>df['A'].eq(0).cumsum().shift(fill_value=0)+1 </code></pre> <p>Or:</p> <pre><code>df['A'].shift().eq(0).cumsum()+1 </code></pre> <p>Output:</p> <pre><code>0 1 1 1 2 1 3 2 4 2 5 2 Name: A, dtype: int32 </code></...
python|pandas
3
6,675
57,054,637
np.vectorize fails on a 2-d numpy array as input
<p>I am trying to vectorize a function that takes a numpy array as input. I have a 2-d numpy array (shape is 1000,100) on which the function is to be applied on each of the 1000 rows. I tried to vectorize the function using <code>np.vectorize</code>. Here is the code:</p> <pre class="lang-py prettyprint-override"><cod...
<p>By this time I think yo have solved your problem. However, I just found a way that solve this and may help other people with the same question. You can pass a <code>signature=&quot;str&quot;</code> parameter to <code>np.vectorize</code> in order to specify the input and output shape. For example, the signature <code...
python|numpy|vectorization
2
6,676
46,085,874
Occupies all GPU memory with the following tensorflow code?
<p>I was experimenting with word2vec with the code from <a href="https://github.com/chiphuyen/stanford-tensorflow-tutorials/blob/master/examples/04_word2vec_no_frills.py" rel="nofollow noreferrer">https://github.com/chiphuyen/stanford-tensorflow-tutorials/blob/master/examples/04_word2vec_no_frills.py</a> </p> <p>Howev...
<p>This is default tensorflow behaviour. If you want to limit GPU memory allocation to only what is needed, specify this in the session config.</p> <pre><code>config = tf.ConfigProto() config.gpu_options.allow_growth = True session = tf.Session(config=config) </code></pre> <p>Alternatively you can specify a maximum f...
memory|tensorflow|gpu
5
6,677
11,459,106
How use the mean method on a pandas TimeSeries with Decimal type values?
<p>I need to store Python decimal type values in a pandas <code>TimeSeries</code>/<code>DataFrame</code> object. Pandas gives me an error when using the "groupby" and "mean" on the TimeSeries/DataFrame. The following code based on floats works well:</p> <pre><code>[0]: by = lambda x: lambda y: getattr(y, x) [1]: rng ...
<pre><code>import numpy as np ts.groupby([by('year'), by('month'), by('day')]).apply(np.mean) </code></pre>
python|decimal|dataframe|pandas
11
6,678
28,716,324
Multiindex pandas groupby + aggregate, keep full index
<p>I have a two-level hierarchically-indexed sequence of integers. </p> <pre><code> &gt;&gt; s id1 id2 1 a 100 b 10 c 9 2 a 2000 3 a 5 b 10 c 15 d 20 ... </code></pre> <p>I want to group by id1, and select the ...
<p>One way to select full rows after a groupby is to use <code>groupby/transform</code> to build a boolean mask and then use the mask to select the full rows from <code>s</code>:</p> <pre><code>In [110]: s[s.groupby(level=0).transform(lambda x: x == x.max()).astype(bool)] Out[110]: id1 id2 1 a 100 2 a ...
python|pandas
5
6,679
28,444,101
How to print the elements (which are array) of list in Python?
<p>I have some code in python which outputs the array named datafile. One of the element of that array is: first element for example</p> <pre><code>datafile[0]=(array([[ 1.], [ 2.], [ 3.], [ 4.], [ 5.]]), array([[ 10.], [ 20.], [ 30.], [ 40.], [ 50.]])) </code></pre> <p>I like to print first a...
<p>ok, after the edits, I think I found the issue.</p> <p>in your code:</p> <pre><code>for i in datafile: plt.plot(datafile[i][0],datafile[i][1]) plt.show </code></pre> <p>You are in fact trying to use a tuple ( each datafile[i] element is a tuple) as the index when you call plot. </p> <p>Try to use so...
python|arrays|list|numpy
0
6,680
50,686,873
Most efficient way to average bunches of x embeddings from a Tensorflow variable that contains y total embeddings
<p>Say that I have y total embeddings which were retrieved using this code</p> <pre><code>embeds = tf.nn.embedding_lookup(embeddings, train_dataset) </code></pre> <p>So the data would look something like this</p> <pre><code>embeds = [embed45, embed2, embed939, embed3, embed32, embed2, . . . etc] </code></pre> <p>An...
<p>You could use <a href="https://www.tensorflow.org/api_docs/python/tf/split" rel="nofollow noreferrer"><code>tf.split</code></a>, but that would mean, the param <code>num_or_size_splits</code> should be a multiple of length of the input if its a scalar, or the sum of the dimensions along the split dimensions should m...
python|tensorflow
0
6,681
51,047,286
Why I am getting this value error in KNN model?
<p>I am applying KNN model on breast cancer wisconsin data but everytime I run the code I get this error:</p> <blockquote> <p>ValueError: Found input variables with inconsistent numbers of samples: [559, 140]</p> </blockquote> <pre><code>import numpy as np import pandas as pd from sklearn import preprocessing,cross...
<p>The output of cross_validation.train_test_split, as per the <a href="http://scikit-learn.org/0.16/modules/generated/sklearn.cross_validation.train_test_split.html" rel="nofollow noreferrer">documentation</a>, should be <code>X_train, X_test, y_train, y_test</code>. Change that line in your code to:</p> <pre><code>X...
python|pandas|scikit-learn
1
6,682
50,744,746
Follow-up rolling_apply deprecated
<p>Following up on this answer: <a href="https://stackoverflow.com/questions/23898631/is-there-a-way-to-do-a-weight-average-rolling-sum-over-a-grouping">Is there a way to do a weight-average rolling sum over a grouping?</a></p> <pre><code>rsum = pd.rolling_apply(g.values,p,lambda x: np.nansum(w*x),min_periods=p) </cod...
<p>As of 0.18+, use <code>Series.rolling.apply</code>.</p> <pre><code>w = np.array([0.1,0.1,0.2,0.6]) df.groupby('ID').VALUE.apply( lambda x: x.rolling(window=4).apply(lambda x: np.dot(x, w), raw=False)) 0 NaN 1 NaN 2 NaN 3 146.0 4 166.0 5 NaN 6 NaN 7 NaN 8 2.5 9...
python|pandas
2
6,683
50,787,553
Converting a flat table of records to an aggregate dataframe in Pandas
<p>I have a flat table of records about objects. Object have a type (ObjType) and are hosted in containers (ContainerId). The records also have some other attributes about the objects. However, they are not of interest at present. So, basically, the data looks like this:</p> <pre><code>Id ObjName XT ObjType Containe...
<p>This is a use case for <code>pd.crosstab</code>. <a href="http://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.crosstab.html" rel="nofollow noreferrer">Docs</a>.</p> <p>e.g.</p> <pre><code>In [539]: pd.crosstab(df.ContainerId, df.ObjType) Out[539]: ObjType A B D E G ContainerId 2 ...
pandas|dataframe|group-by|pivot-table
1
6,684
50,886,294
Error on running prediction for a model
<p>While running the below prediction for a model</p> <pre><code>y_pred_m16 = lm_16.predict(X_test_m16) </code></pre> <p>i am getting the following error. Any clue as to why this is happening ?</p> <pre><code>&gt;ValueError Traceback (most recent call last) &lt;ipython-input-148-ff5c2d...
<p>It seem that the training and testing sets have different dimensions. Is it possible you trained with 8 features and testing on 7?</p>
python|pandas|statsmodels
1
6,685
50,822,119
Numpy array to PIL image format
<p>I'm trying to convert an image from a numpy array format to a PIL one. This is my code:</p> <pre><code>img = numpy.array(image) row,col,ch= np.array(img).shape mean = 0 # var = 0.1 # sigma = var**0.5 gauss = np.random.normal(mean,1,(row,col,ch)) gauss = gauss.reshape(row,col,ch) noisy = img + gauss im = Image.froma...
<p>In my comments I meant that you do something like this:</p> <pre><code>import numpy as np from PIL import Image img = np.array(image) mean = 0 # var = 0.1 # sigma = var**0.5 gauss = np.random.normal(mean, 1, img.shape) # normalize image to range [0,255] noisy = img + gauss minv = np.amin(noisy) maxv = np.amax(noi...
python|image|numpy|python-imaging-library
7
6,686
20,853,179
Purpose of 'ax' keyword in pandas scatter_matrix function
<p>I'm puzzled by the meaning of the '<strong>ax</strong>' keyword in the pandas <strong>scatter_matrix</strong> function:</p> <p>pd.scatter_matrix(frame, alpha=0.5, figsize=None, <strong>ax=None</strong>, grid=False, diagonal='hist', marker='.', density_kwds={}, hist_kwds={}, **kwds)</p> <p>The only clue given in th...
<p>This is tricky here. When looking at the source of pandas <code>scatter_matrix</code> you will find this line right after the docstring:</p> <pre><code>fig, axes = _subplots(nrows=n, ncols=n, figsize=figsize, ax=ax, squeeze=False) </code></pre> <p>Hence, internally, a new figure, axes combination is created using ...
python|matplotlib|plot|pandas|scatter-plot
3
6,687
33,251,320
DataFrame object has no attribute 'sample'
<p>Simple code like this won't work anymore on my python shell:</p> <pre><code>import pandas as pd df=pd.read_csv("K:/01. Personal/04. Models/10. Location/output.csv",index_col=None) df.sample(3000) </code></pre> <p>The error I get is:</p> <pre><code>AttributeError: 'DataFrame' object has no attribute 'sample' </cod...
<p>As given in the <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.sample.html" rel="nofollow">documentation of <code>DataFrame.sample</code></a> -</p> <blockquote> <p><strong><code>DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)<...
python|pandas|module
7
6,688
66,733,616
Installing version 1.15 of tensorflow-serving-api to Centos 8
<p>I am trying to install Tensorflow-serving to my Centos 8 machine. Installing with Docker image is not an option for Centos. So I try to install with pip. These are the commands for installing tensorflow-model-server:</p> <pre><code>pip3 install tensorflow-serving-api==1.15 echo &quot;deb [arch=amd64] http://storage....
<p>I found the links:</p> <pre><code>wget 'http://storage.googleapis.com/tensorflow-serving-apt/pool/tensorflow-model-server-1.15.0/t/tensorflow-model-server/tensorflow-model-server_1.15.0_all.deb' dpkg -i tensorflow-model-server_1.15.0_all.deb pip3 install tensorflow-serving-api==1.15 </code></pre> <p>With these comma...
tensorflow|centos|tensorflow-serving|tensorflow1.15
2
6,689
66,523,003
to_csv storing columns label on every insert of data to csv file
<p>when i am inserting data first time in csv file it is good but on second time it again inserts column name</p> <pre><code>import pandas as pd name = input(&quot;Enter student name&quot;) print(&quot;&quot;) print(&quot;enter marks info below&quot;) print(&quot;&quot;) eng= input(&quot;enter English mark : &quot...
<p>you can read the csv file everytime before your run this script.</p> <pre><code>import pandas as pd import os df = pd.DataFrame() if not os.path.exists(&quot;hello.csv&quot;) else pd.read_csv(&quot;hello.csv&quot;, sep='|') name = input(&quot;Enter student name&quot;) print(&quot;&quot;) print(&quot;enter marks in...
python|pandas|csv|export-to-csv
0
6,690
66,535,465
Check for two dataframes (pivot tables) similarity
<p>I am struggling to check the percent of similarity between two pandas pivot tables (which are filled with values 1 and Nan) which have same row and column indices. I want to count the number of the same rows and divide them by the total number of rows. Giving basic example:</p> <pre><code>df1 column1 colu...
<p>Becasue same index and columns values you can first replace missing values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer"><code>DataFrame.fillna</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Dat...
python|pandas
3
6,691
66,532,381
Pandas creating a column which counts the length of a previous column entries without getting a Set Copy Warning
<p>When I look at the answer to a similiar question as shown in this link: <a href="https://stackoverflow.com/questions/42815768/pandas-adding-column-with-the-length-of-other-column-as-value">Pandas: adding column with the length of other column as value</a></p> <p>I come across an issue where the solution its suggesti...
<p>I took a sample data set to test this issue in Python 3.8</p> <p>Sample data <a href="https://i.stack.imgur.com/8tDm0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8tDm0.png" alt="enter image description here" /></a></p> <p>here is the same code which you ran df['name_length'] = df['seller_name'...
python|pandas|dataframe
0
6,692
57,591,352
Pandas - Filling missing dates within groups with different time ranges
<p>I'm working with a dataset which has monthly information about several users. And each user has a different time range. There is also missing "time" data for each user. What I would like to do is fill in the missing month data for each user based on the time range for each user(from min.time to max.time in months)</...
<p>Create <code>DatetimeIndex</code>, so possible use <code>groupby</code> with custom lambda function and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.asfreq.html" rel="nofollow noreferrer"><code>Series.asfreq</code></a>:</p> <pre><code>x['dt'] = pd.to_datetime(x['dt']) x = (x.set_...
python-3.x|pandas|pandas-groupby
1
6,693
57,310,987
Count values based on a condition on another column
<p>I am trying to create a dataset where, for each job department, I count the total amount of people in that department and the total amount of people who left (or not) the company.</p> <pre><code> Name Total Non left Left Finance 3000 2500 5000 IT 1500 1000 500 Marke...
<p>May use <code>crosstab</code></p> <pre><code>pd.crosstab(df.Left, df.department ,margins = True) </code></pre>
pandas
1
6,694
57,444,768
How to compute every sum for every argument a from an array of numbers A
<p>I'd like to compute the following sums for each value of a in A: </p> <pre><code>D = np.array([1, 2, 3, 4]) A = np.array([0.5, 0.25, -0.5]) beta = 0.5 np.sum(np.square(beta) - np.square(D-a)) </code></pre> <p>and the result is an array of all the sums. To compute it by hand, it would look something like this: </...
<p>Use <code>np.sum</code> with broadcasting</p> <pre><code>np.sum(np.square(beta) - np.square(D[None,:] - A[:,None]), axis=1) Out[98]: array([-20. , -24.25, -40. ]) </code></pre> <hr> <p><strong>Explain</strong>: We need the whole array D subtracts each element of array A. We can't simple call <code>D</code> - <...
numpy
1
6,695
57,512,593
How to create a tensor with an unknown dimension
<p>I have a layer in my neural network with an output vector <code>x</code> of size <code>[?, N]</code>. (with first dimension for the batch size). I want declare a tensor of <code>ones</code> of the same size in the next layer (Lambda layer). I see that I cannot use <code>y = keras.backend.ones(x.shape)</code> as the ...
<p>As suggested by today in the comments, <code>K.ones_like</code> works:</p> <pre><code>from keras import backend as K a = K.placeholder(shape=(None, 5)) b = K.ones_like(a) print(b.shape) &gt;&gt; TensorShape([Dimension(None), Dimension(5)]) </code></pre> <p>Depending on the type of operation you're doing, you can ...
python|tensorflow|keras|tensor
1
6,696
43,888,010
python pandas delete row on string condition
<p>i have a data frame with a column of strings and integers. On one of the columns containing strings I want to search all the items of that column for a specific substring let say "abc" and delete the row if the substring exists. How do I do that? It sounds easy but somehow I struggle with this. The substring is alwa...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>, add <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#indexing-with-str" rel="nofollow noreferrer"><code>indexing with str</code></a> if need check last <...
python|pandas
2
6,697
43,869,394
Python column and row interaction in dataframe
<p>Let's imagine I have a dataframe :</p> <pre><code>question user level 1 a 1 1 b 2 1 a 3 2 a 1 2 b 2 2 a 3 2 b 4 3 c 1 3 b 2 3 ...
<p>My suggestion:</p> <p>I would use a dictionary containing 'source-destination' as keys and reply_counts as values.</p> <p>Loop over the first dataframe, for each question, store who posted 1st message as the destination, store who posted 2nd message as source, add a counter in dictionary at key 'source-destination...
python|pandas
2
6,698
72,867,751
Invalid MultiPolygon value even though all the Polygons are valid
<p>I am trying to convert coordinates to WKT format. Here I have a list of polygons which should be identified as a Multi polygon.</p> <pre><code> 'geometry': [[[129093.87770000007, 6638201.563100001], [129145.82270000037, 6638246.0934], [129170.66339999996, 6638267.387800001], [129234.25879999995, 6638194.908...
<p>MultiPolygon takes a sequence of rings <em><strong>and</strong></em> holes list tuples, or a sequence of polygons. You can either do:</p> <pre><code>MultiPolygon((x, None) for x in jk['geometry']) </code></pre> <p>or</p> <pre><code>MultiPolygon(Polygon(x) for x in jk['geometry']) </code></pre>
python|geojson|geopandas|shapely
2
6,699
72,843,042
How can we deploy a Machine Learning Model using Flask?
<p>I am trying, for the first time ever, to deploy a ML model, using Flask. I'm following the instructions from the link below.</p> <p><a href="https://towardsdatascience.com/deploy-a-machine-learning-model-using-flask-da580f84e60c" rel="nofollow noreferrer">https://towardsdatascience.com/deploy-a-machine-learning-mode...
<p>I would suggest the following steps since you mentioned its your first time and when deploying a project for experimenting, it's good practice to put it in a virtual environment, which we can do with the <a href="https://virtualenv.pypa.io/en/latest/" rel="nofollow noreferrer"><code>virtualenv</code></a> tool.</p> <...
python|numpy|anaconda|conda
0