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
361,600
47,060,685
Chamfer distance between two point clouds in tensorflow
<p>I am trying to implement chamfer distance in tensorflow.</p> <p>But, my code is taking input as numpy array. To convert a numpy into a tensor, we need to run a session, but the process is already in another session. I think two sessions can't run in parallel.</p> <p>So, can anyone help me with the implementation o...
<p>I've implemented TF version of chamfer distance:</p> <pre><code>def distance_matrix(array1, array2): """ arguments: array1: the array, size: (num_point, num_feature) array2: the samples, size: (num_point, num_feature) returns: distances: each entry is the distance from a sample ...
python|numpy|session|tensorflow
8
361,601
46,702,568
Reshaping a numpy array with 1 value left over
<p>I'm trying to reshape an array of length 179 into a 9 x 20 arrays using reshape, how can I do 8 of 20 and 1 of 19?</p> <pre><code>lst2 = np.array(np.random.rand(180)) lst2.reshape(9, 20) ValueError: cannot reshape array of size 179 into shape (9,20) </code></pre>
<p><code>np.array(random.rand(180))</code> creates an array of length 180. So <code>lst2.reshape(9,20)</code> works great. </p> <p>If you want to reshape to 8 x 20, it means you should delete some data (20 values) like in the following:</p> <pre><code>lst[0:-20].reshape(8,20) </code></pre>
python|numpy
0
361,602
46,704,352
Porting PyTorch code from CPU to GPU
<p>Following the tutorial from <a href="https://github.com/spro/practical-pytorch/blob/master/seq2seq-translation/seq2seq-translation.ipynb" rel="noreferrer">https://github.com/spro/practical-pytorch/blob/master/seq2seq-translation/seq2seq-translation.ipynb</a></p> <p>There is a <code>USE_CUDA</code> flag that is used...
<p>You can also try:</p> <pre><code>net = YouNetworkClass() device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") net.to(device) </code></pre> <p>After that, you have to send the <code>word_inputs</code>, <code>encoder_hidden</code> and <code>decoder_context</code> to the GPU too:</p> <pre><code>wo...
python|torch|pytorch|tensor
8
361,603
46,925,896
Create an image using the pixels median fom other images
<p>I have six images and I want to find the median of each pixel and create a new pic from it. I created a list of my images in this manner:</p> <pre><code>imgs=['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg'] </code></pre> <p>and then I wrote a for loop like that:</p> <pre><code>for image in imgs: </code></pre> ...
<p>You can use opencv to read images</p> <pre><code>import cv2 import numpy as np imgs=['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg'] np_images = [] for img in imgs: image = cv2.imread(img,1) if image is None: print(img, "doesnot exist") else: np_images.append(image) # assuming t...
python|image|numpy|image-processing
0
361,604
46,799,234
Fastest way to loop over Pandas DataFrame for API calls
<p>My objective is to make a call to an API for each row in a Pandas DataFrame, which contains a List of strings in the response JSON, and creating a new DataFrame with one row per response. My code basically looks like this:</p> <pre><code>i = 0 new_df = pandas.DataFrame(columns = ['a','b','c','d']) for index,row in ...
<p>Something along these lines perhaps? This way you aren't creating a whole new dataframe, you're only declaring URL once, and you're taking advantage of the fact that pandas column operations are faster than row by row stuff. </p> <pre><code>url = 'http://myAPI/' def request_function(j): return requests.post(ur...
python|pandas|python-requests
8
361,605
46,883,334
How to perform row wise or column wise max pooling in keras
<p>I am trying to perform row wise and column wise max pooling over an attention layer as described in the link below: <a href="http://www.dfki.de/~neumann/ML4QAseminar2016/presentations/Attentive-Pooling-Network.pdf" rel="nofollow noreferrer">http://www.dfki.de/~neumann/ML4QAseminar2016/presentations/Attentive-Pooling...
<p>If you have images along your model with shape <code>(batch, width, height, channels)</code>, you can reshape the data to hide one of the spatial dimensions and use a 1D pooling:</p> <p><strong>For the width:</strong> </p> <pre><code>model.add(Reshape((width, height*channels))) model.add(MaxPooling1D()) model.add...
tensorflow|deep-learning|keras|attention-model
2
361,606
46,812,811
Codes in Ipython vs Pycharm
<p>I am a newbie and the following question may be dumb and not well written. I tried the following block of codes in Ipython: </p> <pre><code>%pylab qt5 x = randn(100,100) y = mean(x,0) import seaborn plot(y) </code></pre> <p>And it delivered a plot. Everything was fine. </p> <p>However, when I copied and pasted t...
<p>You can use IPython/Jupyter notebooks in PyCharm by following this guide: <a href="https://www.jetbrains.com/help/pycharm/using-ipython-jupyter-notebook-with-pycharm.html" rel="nofollow noreferrer">https://www.jetbrains.com/help/pycharm/using-ipython-jupyter-notebook-with-pycharm.html</a></p> <p>You may modify code...
python|numpy|matplotlib
0
361,607
47,078,331
Replace is producing weird answers in pandas python
<p>i am using dictionary key value pair to replace some string.</p> <pre><code>dict= {'MAA':'MADRAS', 'MAD':'MADRID'} </code></pre> <p>now using <code>.replace()</code>, it replaces MAA to MADRAS but MAD of MADRAS is again replaced by MARDRID. This is giving me wrong output and i have 8000+ key value pairs so my outp...
<p>It's need to be optimized, but this works:</p> <pre><code>import re di= {'MAA':'MADRAS', 'MAD':'MADRID'} st = ['BRISBANE-AKL-SCL-LIM/CIX-LIM/LAX/BNE', 'PER-HKG/HND/PVG-HKG/PER', 'PER/JNB/PER', 'PER-DXB/ALA-TSE/LHR-DXB/PER', 'BNE/LST/MEL-CHC/IVC/CHC/BNE', 'ANF/SCL-ATL/SLC-LAX-SYD/BNE', 'MAA-BOM/HYD/MAA', 'MEL/SIN/ME...
python|pandas|dictionary|replace
0
361,608
46,684,358
Remove index in pandas data-frame while converting to html table
<p>I am trying to remove index while converting pandas data-frame into html table. Prototype is as follows:</p> <pre><code>import pandas as pd import numpy as np df= pd.DataFrame({'list':np.random.rand(100)}) html_table = df.to_html() </code></pre> <p>In html table I don't want to display index. </p>
<p>Try this:</p> <pre><code>html_table = df.to_html(index = False) </code></pre>
python|pandas|dataframe|indexing
8
361,609
47,047,788
Populating the column value with previous when NaN
<p>I have a <code>pd.Series</code> that looks like this:</p> <pre><code>&gt;&gt;&gt; series 0 This is a foo bar something... 1 NaN 2 NaN 3 foo bar indeed something... 4 NaN 5 NaN 6 ...
<p>From the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html#pandas.DataFrame.fillna" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p><strong>DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs)</strong></p> ...
python|string|list|pandas|dataframe
2
361,610
46,762,648
Handling exceptions when populating pandas dataframe
<p>I have set this dataframe:</p> <pre><code>df = pd.DataFrame(columns=('artist', 'track', 'pos', 'neg', 'neu')) </code></pre> <p>and this code to populate it:</p> <pre><code>i = 0 for item in artist_track: artist = item[0] track = item[1] try: mood = track_mood(artist, track) # a function ...
<p>Use a <code>try-except-finally</code> clause. Populate your values appropriately, and assign in <code>finally</code>.</p> <pre><code>try: mood = track_mood(artist, track) # a function pos, neg, neu = mood['pos'], mood['neg'], mood['neu'] except AssertionError: pos = neg = neu = 0.0 finally...
python|pandas|exception|dataframe
0
361,611
47,052,672
How to change the date from YYYY-MM-DD to YYDD-MM-YY in python
<p>I have a MySQL database, and there is a column in which I have stored the date. Now the requirement is I need to replace the dd with YY. and I want to do this using python(Pandas)</p> <p>for eg date that i have is 2032-11-16, and I want 2016-11-32. </p> <p>uptill now my approach is shown below</p> <pre><code>df =...
<p><a href="http://docs.python.org/library/datetime.html" rel="nofollow noreferrer"><code>datetime</code></a> module could help you with that:</p> <p><code>datetime.datetime.strptime(date_string, format1).strftime(format2)</code></p> <pre><code>datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y') ...
python|mysql|pandas|numpy
0
361,612
46,643,665
Sorting: 'DataFrame' object has no attribute 'sort'
<p>The code is written in python 3.4 but I want to run it on python 3.7. I am using the Jupyter notebook to run. Can I create an environment in Jupyter and run the code in an older version of pandas(e.g. 0.16)?</p> <pre><code>--&gt; 210 tmpvals[n] = find_non_overlapping_sample( 211 df.s...
<p>Sort method has been deprecated.<br> You should go for df.sort_values() or df.sort_index() methods.</p>
python|pandas
2
361,613
46,870,557
pandas rolling how to retain the first time index of each time window
<p>Sorry for all the confusion I have made. <code>shift</code> method works perfectly fine. It turns out that <code>rolling</code> actually keeps all indices and all we have to do is to shift back, no matter if the indices are regular or not. <hr> It seems that the pandas <code>rolling</code> method always keeps the <e...
<p><strong>Idea 1</strong><br> Hack by reversing the dataframe first, then back again... </p> <pre><code>(lambda d: d.a.rank().rolling(3).corr(d.b.rank()).iloc[::-1])(df.iloc[::-1]) 2017-01-01 0.891042 2017-01-02 0.838628 2017-01-03 0.960769 2017-01-04 -0.897918 2017-01-05 -0.996616 2017-01-06 0.3273...
python|pandas|date|datetime
4
361,614
46,950,405
Data migration from MySQL to SQL Server is taking huge time using pandas library
<p>I need to migrate all our historical data from MySQL to SQL server. Data size is more then 50 GB.</p> <p>I have created a script for migrate those data from MySQL to SQL server. using python Pandas library. Main reason for choosing pandas library is I am adding some cleaning process before migration.</p> <pre><cod...
<p>Use <code>fast_executemany=True</code> option in your connection engine</p> <p>For example, use it as:</p> <pre><code>engine = create_engine( 'mssql+pyodbc://{0}/{1}?trusted_connection=yes&amp;driver=SQL+Server+Native+Client+11.0' \ .format(server_name, db_name), fast_executemany...
sql-server|python-3.x|pandas|amazon-rds
0
361,615
46,951,277
Find unknown variable in set of equations in numpy
<p>I have six equations and six variables. I am solving it through <code>numpy</code> using <code>np.linalg.solve(a, b)</code>. The result gives me 6 values but I don't know which value is x1,x2... unknown variable result satisfies only one equation that is </p> <pre><code> x1+x2+x3+x4+x5+x6=...
<p>If you do </p> <pre><code>for i in range(6): (a[i]*x).sum() </code></pre> <p>You'll get that the first five elements are of the order of e-17 (basically 0 in float representation) and the last one is 1 as specified by the <code>b</code> vector you provided.</p> <p>I believe your problem is not understanding t...
python|python-2.7|numpy
0
361,616
33,004,551
Why is B = numpy.dot(A,x) so much slower looping through doing B[i,:,:] = numpy.dot(A[i,:,:],x) )?
<p>I'm getting some efficiency test results that I can't explain. </p> <p>I want to assemble a matrix B whose i-th entries B[i,:,:] = A[i,:,:].dot(x), where each A[i,:,:] is a 2D matrix, and so is x.</p> <p>I can do this three ways, to test performance I make random (<code>numpy.random.randn</code>) matrices A = (10,...
<p>With smaller dims <code>10,100,200</code>, I get a similar ranking</p> <pre><code>In [355]: %%timeit .....: B=np.zeros((N,M,L)) .....: for i in range(N): B[i,:,:]=np.dot(A[i,:,:],x) .....: 10 loops, best of 3: 22.5 ms per loop In [356]: timeit np.dot(A,x) 10 loops, best of 3: 44.2 ms per loo...
python|numpy|multidimensional-array|product
5
361,617
32,940,338
How do I sort by predicted probability in a binary classifer?
<p>I trained a binary classifier and can get a good score.</p> <pre><code>reviews['prediction'] = model.predict(reviews.review.astype(str)) model.score(reviews.review.astype(str), reviews.sentiment) model.predict_proba(reviews.review.astype(str)) </code></pre> <p>I get the probability in an array when I print the pre...
<p>You can call <code>max(axis=1)</code> on the array to get the maximum value of each row, for example:</p> <pre><code>reviews['proba'] = predict_prob.max(axis=1) </code></pre>
python|pandas|scikit-learn
1
361,618
32,609,527
Resampling multilevel index, or averaging along third dimension of a matrix/array
<p>I have gridded satellite data stored in a dataframe. Normally, this dataframe gets sliced to make imshow plots on a day-by-day basis, which is trivial. However, I would like to plots annual means of the data, which is where I am currently stuck. The dataframe has a multi-level index (datetime, latitude coordinate...
<p>Here we go:</p> <pre><code>import pandas as pd, numpy as np pd.set_option('display.float_format',lambda x: '{:,.1f}'.format(x)) np.random.seed(1) dates = pd.date_range('20140101',periods=10,freq='1D') others = np.arange(0,5) index = [(d,o) for o in others for d in dates] index = pd.MultiIndex.from_tuples(index,...
python|pandas
2
361,619
32,911,939
pandas Series.cumsum() vs pandas.expanding_sum()
<p>assuming I have a pandas Series s, what is the difference between s.cumsum() and pd.expanding_sum(s)? (I guess the answer should be the same also for cummax()/cummin(), and pd.expanding_max()/pd.expanding_min())</p> <p>The docs say:</p> <blockquote> <p>Note The output of the rolling_ and expanding_ functions do ...
<p>They are basically the same, but you will get NaNs with <code>expanding_sum</code> until you reach the required minimum number of observations. </p> <pre><code>s = pd.Series([1] * 5) &gt;&gt;&gt; s.cumsum() 0 1 1 2 2 3 3 4 4 5 dtype: int64 &gt;&gt;&gt; pd.expanding_sum(s, min_periods=3) 0 NaN 1 ...
python|pandas
4
361,620
32,898,478
How to save a Python list of strings for future use
<p>I just did text pre-processing of 43K documents (stop words removal/tokenization etc). in python and the result is a list of processed text documents(strings). Now I am going for converting these processed strings to bag of words feature vectors. </p> <p>I need help on two things. </p> <p>1). It took 45 minutes on...
<p>I use sklearn joblib , it is faster than the other answer which use cPickle and gzip(170ms vs 430ms for my test). And the code is simple and cool. :)</p> <p>to use <code>joblib.dump</code> to save, and <code>joblib.load</code> to read</p> <pre><code>from sklearn.externals import joblib joblib.dump(clf, 'filename.p...
python|numpy
6
361,621
32,694,505
Dataframe manipulation, something with groupby, probably :/
<p>Need help with a Dataframe transformation. I have </p> <pre><code>df = pd.DataFrame({'C' : [1, 2, 1, 1, 2, 2, 1], 'D' : [1, 2, 13, 4, 5, 9, 10]}) df = df.sort('C') =&gt; C D 0 1 1 1 1 13 2 1 4 3 1 10 4 2 2 5 2 5 6 2 9 </code><...
<p>You could do this by adding a new F column and then calling <code>pivot</code>:</p> <pre><code>&gt;&gt;&gt; df["F"] = "F" + (df.groupby("C").cumcount() + 1).astype(str) &gt;&gt;&gt; d2 = df.pivot(index="C", columns="F", values="D") &gt;&gt;&gt; d2 F F1 F2 F3 F4 C 1 1 13 4 10 2 2 5 9 ...
python|pandas
3
361,622
32,969,828
Read specific lines from text file as numpy array
<p>I am trying to read a txt file in he format:</p> <pre><code>[text] [text] [text] 1 0 4 5 3 0 0 [text] . . . </code></pre> <p>I need to read lines 4 to 6 as a numpy array. So far I've got:</p> <pre><code> lines=[] with open('filename', "r") as f: for i, line in enumerate(f): if i&gt;=3 and i&lt;=5:...
<p>You need to transform string to ints:</p> <pre><code>lines=[] with open('filename', "r") as f: for i, line in enumerate(x.split('\n')): if i&gt;=3 and i&lt;=5: lines.append([int(y) for y in line.split()]) lines = np.array(lines) print type(lines) </code></pre>
python|numpy
2
361,623
32,760,999
Transfer matrix elements to another matrix's diagonal
<p>I want to do something similar to here (in Python):</p> <p><a href="https://stackoverflow.com/questions/28598572/how-to-convert-a-column-or-row-matrix-to-a-diagonal-matrix-in-python">How to convert a column or row matrix to a diagonal matrix in Python?</a></p> <p>that is : </p> <p>1) set all elements of matrix A ...
<p>Can you not do just unravel your matrix onto the diagonal of another?</p> <pre><code>In [29]: import numpy as np In [30]: a = np.array([[1,2],[3,4]]) In [31]: b = np.diag(a.ravel()) In [32]: b Out[32]: array([[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]]) </code></pre> <p>Then, t...
python|numpy|matrix
6
361,624
33,029,505
Python pandas conditional replace string based on column values
<p>Given these data frames...:</p> <pre><code>DF = pd.DataFrame({'COL1': ['A', 'B', 'C', 'D','D','D'], 'COL2': [11032, 1960, 11400, 11355, 8, 7], 'year': ['2016', '2017', '2018', '2019', '2020', '2021']}) DF COL1 COL2 year 0 A 11032 2016 1 B 1960 2017 2 C ...
<p>This looks like you want to <code>update</code> <code>DF</code> with data from <code>DF2</code>.</p> <p>Assuming that all values in <code>DF2</code> are unique for a given pair of values in <code>ColX</code> and <code>ColY</code>:</p> <pre><code>DF = DF.merge(DF2.set_index(['ColX', 'ColY'])[['ColZ']], ...
python|pandas
2
361,625
32,909,787
Remove lines, based on date comparison
<p>I am having a dataframe that contains the following data:</p> <pre><code>Estimate Value Announce date Period Company Estimate 1: 0,24 01-01-2015 31-12-2015 X Estimate 2: 0,22 08-04-2015 31-12-2015 X Estimate 3 0,26 07-05-2015 31-12-2014 ...
<p>IIUC then you can just call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.first.html#pandas.core.groupby.GroupBy.first" rel="nofollow"><code>first</code></a> on the groupby object:</p> <pre><code>In [191]: df.groupby(['Period','Company']).first() Out[191]: ...
python|pandas
1
361,626
32,610,709
Using Python to create a new Numpy array from an existing one
<p>I need to use Python and Numpy to take a grayscale image (as a Numpy array), then iterate through it by pixel in order to differentiate the image in the X a direction. I can't use any functions to do this automatically, I need to iterate unfortunately. I need to use the derivative: F(x, y) = F(x, y+1) - F(x, y) to e...
<p>Following my snide comment about homework:</p> <p>Looking at your Java code, I think this is what you want?</p> <pre><code>import numpy as np data = np.array([10, 15, 5, 25]) diff = np.abs(data[:-1] - data[1:]) print diff array([ 5, 10, 20]) </code></pre> <p>EDIT:</p> <p>I'm simply taking every value of the ar...
python|arrays|numpy
3
361,627
32,845,601
count how often each field point is inside a contour
<p>I'm working with 2D geographical data. I have a long list of contour paths. Now I want to determine for every point in my domain inside how many contours it resides (i.e. I want to compute the spatial frequency distribution of the features represented by the contours).</p> <p>To illustrate what I want to do, here's...
<p>If your input polygons are actually contours, then you're better off working directly with your input grids than calculating contours and testing if a point is inside them.</p> <p>Contours follow a constant value of gridded data. Each contour is a polygon enclosing areas of the input grid greater than that value.<...
python|numpy|scipy|shapely
4
361,628
38,940,209
How do I create dataframes from the groups that have been arranged by groupby?
<p>I have separated my data set by months, there are a total of 8 groups for 8 different months, I want to create two separate dataframes which one will include the data that is found on months:5,6,7,8 and the other dataframe will include the months:4,9,10,11. How can I tell groupby to create these two separate dataset...
<p>Try:</p> <pre><code>df1 = df[df.month.isin([5, 6, 7, 8])] df2 = df[df.month.isin([4, 9, 10, 11])] </code></pre>
python|datetime|pandas|group-by
1
361,629
38,549,040
Tensorflow seq2seq multidimensional regression
<p><strong>EDIT</strong>: I edited my code to make seq2seq tutorial/exercises, here they are: <a href="https://github.com/guillaume-chevalier/seq2seq-signal-prediction" rel="nofollow noreferrer">https://github.com/guillaume-chevalier/seq2seq-signal-prediction</a></p> <hr> <p>I try to do a sequence-to-sequence (seq2s...
<p>For learning functions like sin(x), it is not good to use softmax loss. * softmax losses are generally used for multi-class <em>discrete</em> predictions * for continuous predictions, use, e.g., l2_loss</p> <p>Also, since sin(x) is a function of x, I don't think you need an RNN for that. I'd really first try a 2-la...
python|machine-learning|tensorflow|deep-learning|recurrent-neural-network
1
361,630
38,597,921
Double Group-by then apply some functions?
<p>I have data that looks like this:</p> <pre><code> country source 0 UK Ads 1 US Seo 2 US Seo 3 China Seo 4 US Seo 5 US Seo 6 China Seo 7 US Ads </code></pre> <p>For each country I want to get the ratio of each source. I did a groupby on country and source...
<h3>Large sample set</h3> <pre><code>np.random.seed([3,1415]) n = 100000 df = pd.DataFrame( dict(country=np.random.choice(('UK', 'US', 'China'), n), source=np.random.choice(('Ads', 'Seo', 'Direct'), n))) </code></pre> <h3>Solution</h3> <pre><code>size = df.groupby(['country', 'source']).size().unstack()...
python|pandas|group-by|aggregate-functions
1
361,631
38,688,784
Copy value from matching index in another dataframe after criteria matched
<p>With the test Pandas dataframe below I am trying to copy a value from matching index in another dataframe after certain criteria is matched.</p> <p>This is a snip from the dataframe called <code>data2</code>:</p> <pre><code> Signal Value2 2013-01-01 09:00:00 1.0 NaN 2013-01-01 10:00:00 1.0 NaN 2013...
<p>Could be something like this?</p> <pre><code>data2.loc[data2.Signal == -1, 'Value2'] = data.loc[data2.Signal == -1, 'value'] </code></pre>
python|pandas
3
361,632
38,909,274
Numpy: slice matrix to remove one row and column
<p>Given an n by n matrix (technically an np.array) L, I wish to remove the kth row and kth column. This line of code works as expected (it selects the 1st through 3rd rows and columns):</p> <pre><code>Lt = L[(1,2,3),(1,2,3)] </code></pre> <p>When I try to replace (1,2,3) by a dynamically generated tuple excluding th...
<blockquote> <pre><code>keep = (i for i in range(n) if i != k) </code></pre> </blockquote> <p>This is a generator expression, not a generated tuple itself; instead, try</p> <pre><code>keep = tuple(i for i in range(n) if i != k) </code></pre>
python|numpy|matrix
2
361,633
38,722,747
Unable to subtract specific fields within structured numpy arrays
<p>While trying to subtract to fields within a structured numpy array, the following error occurs:</p> <pre><code>In [8]: print serPos['pos'] - hisPos['pos'] --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipy...
<p>The <code>dtype</code> for <code>serPos['pos']</code> is compound</p> <pre><code>dtype([('x', '&lt;f8'), ('y', '&lt;f8'), ('z', '&lt;f8')]) </code></pre> <p>subtraction (and other such operations) has not been defined for compound dtype. It doesn't work for the <code>raw</code> dtype either. </p> <p>You could s...
python|arrays|python-2.7|numpy
1
361,634
38,765,676
invalid type, must be a string or Tensor [TensorFlow]
<p>I have problem in Machine Learning library from Google - Tensorflow. When I want to initialize my session, it tells me that must be string or tensor. I did not spot any mistake. </p> <pre><code>import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIS...
<p>I think you just missed a pair of parentheses <code>()</code> after <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/state_ops.html#initialize_all_variables" rel="nofollow"><code>tf.initialize_all_variables</code></a> ;)</p> <p>As python says, it's in line 13, look after</p> <blockquote> <p><co...
python|initialization|syntax-error|tensorflow|mnist
4
361,635
38,697,404
Pandas - Explanation on apply function being slow
<p>Apply function seems to work very slow with a large dataframe (about 1~3 million rows).</p> <p>I have checked related questions here, like <a href="https://stackoverflow.com/questions/31363908/speeding-up-pandas-apply-function">Speed up Pandas apply function</a>, and <a href="https://stackoverflow.com/questions/382...
<p>Concerning your first question, I can't say exactly why this instance is slow. But generally, <code>apply</code> does not take advantage of vectorization. Also, <code>apply</code> returns a new Series or DataFrame object, so with a very large DataFrame, you have considerable IO overhead (I cannot guarantee this is t...
python|pandas
10
361,636
38,962,618
Python, pandas: how to extract values from a symmetric, multi-index dataframe
<p>I have a symmetric, multi-index dataframe from which I want to systematically extract data:</p> <pre><code>import pandas as pd df_index = pd.MultiIndex.from_arrays( [["A", "A", "B", "B"], [1, 2, 3, 4]], names = ["group", "id"]) df = pd.DataFrame( [[1.0, 0.5, 0.3, -0.4], [0.5, 1.0, 0.9, -0.8], [0....
<p>I don't assume <code>df</code> has the same columns and index. (Of course they can be the same). </p> <pre><code>def extract_vals(group_label, df): coord = [[i, j] for i in range(len(df)) for j in range(len(df)) if i&lt;j and (df.index.get_level_values('group')[i] == group_label or df.columns.get_level_valu...
python|pandas|numpy|dataframe|multi-index
1
361,637
38,558,428
How is it possible to take a slice this way?
<p>I'm taking a course in machine learning and there was a recommendation (about making a balancing of classes) to use the following code: </p> <pre><code>X_train_to_add = X_train[y_train.as_matrix() == 1, :][indices_to_add, :] </code></pre> <p>where <code>y_train</code> is a pandas dataframe (which is converted ther...
<p>It might help to break down the statement into its component parts. This statement is equivalent to the following sequence of statements:</p> <pre><code>y = y_train.as_matrix() row_mask = y == 1 X_masked = X_train[row_mask,:] X_train_to_add = X_masked[indices_to_add, :] </code></pre> <p>Let's look at a concrete e...
python|numpy
1
361,638
38,732,188
How do reindex multilevel columns
<p>Version info:</p> <pre><code>print(sys.version) 3.5.1 |Anaconda 4.1.0 (64-bit)| (default, Jun 15 2016, 15:29:36) [MSC v.1900 64 bit (AMD64)] </code></pre> <p>I have columns in a data frame that look like this (latitude and longitude are multilevel columns):</p> <pre><code>+------------+---------------+-----------...
<p>This will do the trick:</p> <pre><code>data2 = pd.DataFrame(data1.values, columns=newColumns) </code></pre> <p>And also this:</p> <pre><code>data1.columns = newColumns </code></pre>
python|windows|pandas
3
361,639
38,781,777
np.where how to improve performance with regular expression?
<p>I am new to python numpy and regular expression. I am trying to extract the patterns from the pandas text column from each row. There are many possible cases available as per my requirement so I wrote below different regular expressions for that. To iterate and search for the given pattern i am using python's <cod...
<p>There a couple of things you can try:</p> <p>First, you need to identify the slower regular expressions. You can do this for example with <a href="https://regex101.com/" rel="nofollow noreferrer">https://regex101.com/</a> observing the 'steps' value.</p> <p>I inspected the regexes and number 5 and 8 are the slowes...
python|regex|performance|pandas|numpy
1
361,640
38,623,912
ImportError: cannot import name 'tree' for sklearn
<p>I've recently installed Scipy, Numpy and Scikit-learn by using pip, but when I run the program below </p> <pre><code>from sklearn import tree features = [[140, 1], [130, 1], [150, 1], [170, 1]] #input labels = [0, 0, 1, 1] #output clf = tree.DecisionTreeClassifier() clf = clf.fit(features, labels) #fit = find p...
<p>The solution is to rename your "sklearn.py" under the "Machine Learning" folder to any other name but not "sklearn.py".</p> <p>Why? That's the mechanism of Python modules searching sequence. Try prepend these lines to your "sklearn.py":</p> <pre><code>import sys print(sys.path) </code></pre> <p>You'll find the fi...
python|numpy|scikit-learn|importerror
2
361,641
38,727,612
How does one set different learning rates for different layers or variables in TensorFlow?
<p>I know that one can simply do it for all of them using something as in the tutorials:</p> <pre><code>opt = tf.train.GradientDescentOptimizer(learning_rate) </code></pre> <p>however it would be nice it one could pass a dictionary that maps the variable name to its corresponding learning rate. Is that possible?</p> ...
<p>As far as I can tell this is not possible. Mostly because this is not really a valid gradient descent then. There are plenty of optimizers which learn on their own variable specific scaling factors (like Adam or AdaGrad). Specyfing per-variable learning rate (constant one) would mean that you do not follow the gradi...
python|machine-learning|neural-network|tensorflow|conv-neural-network
3
361,642
38,575,246
Get result of value_count() to excel from Pandas
<p>I have a data frame <code>"df"</code> with a column called <code>"column1"</code>. By running the below code: </p> <pre><code>df.column1.value_counts() </code></pre> <p>I get the output which contains values in column1 and its frequency. I want this result in the excel. When I try to this by running the below code...
<p>You are using <code>index = None</code>, You need the index, its the name of the values. </p> <pre><code>pd.DataFrame(df.column1.value_counts()).to_excel("result.xlsx") </code></pre>
python|pandas
3
361,643
38,613,566
Pandas apply function taking up to 10min (numba doesnot help)
<p>I have got a very simple function to apply to each row of my dataframe:</p> <pre><code>def distance_ot(fromwp,towp,pl,plee): ` if fromwp[0:3]==towp[0:3]: sxcord=pl.loc[fromwp,"XCORD"] sycord=pl.loc[fromwp,"YCORD"] excord=pl.loc[towp,"XCORD"] eycord=pl.loc[towp,"YCORD"] x=np.abs(excord-sxcord);...
<p>Vectorize the <code>distance_ot</code> function to calculate all distances at once. I would begin populating a from_df and a to_df like the following:</p> <pre><code>import numpy as np from_df = pl.loc[np.in1d(pl.loc.index, pot["from_wpadr"]) to_df = pl.loc[np.in1d(pl.loc.index, pot["to_wpadr"]) </code></pre> <p>...
python-2.7|pandas
0
361,644
38,879,779
tensorflow.python.framework.errors.InvalidArgumentError: Field 0 in record 0 is not a valid int32: 1 0
<p>My .<strong>CSV</strong> file contains the data look like this ... 1 0 0 0 0 0 0 0 0 0 0 0</p> <p>I am trining to read this .CSV file by the following code</p> <pre><code>filename = "alpha_test.csv" #setup text reader file_length = file_len(filename) filename_queue = tf.train.string_input_pro...
<p>Most likely reason for the issue you see is that the 1 and 0 in the first line of your file are actually separated by 3 spaces, not a tab. Note how the <code>field_delim</code> is properly set to <code>\t</code> in your call to <code>decode_csv</code>, but the value it seems to read is <code>1 0</code>. This is pr...
python|numpy|tensorflow|deep-learning
1
361,645
38,902,239
Performance issues with pandas and filtering on datetime column
<p>I've a pandas dataframe with a datetime64 object on one of the columns.</p> <pre><code> time volume complete closeBid closeAsk openBid openAsk highBid highAsk lowBid lowAsk closeMid 0 2016-08-07 21:00:00+00:00 9 True 0.84734 0.84842 0.84706 0.84814 0.84734 0.84842 0.84706 0.84814 0.84788 ...
<p>If efficiency is your goal, I'd use numpy for just about everything</p> <p>I rewrote <code>get_new_candles</code> as <code>get_new_candles2</code></p> <pre><code>def get_new_candles2(clock_tick, previous_tick): start = previous_tick - timedelta(minutes=1) end = clock_tick - timedelta(minutes=3) ge_star...
python|pandas|numpy|dataframe
3
361,646
38,896,424
TensorFlow not found using pip
<p>I'm trying to install TensorFlow using pip:</p> <pre class="lang-none prettyprint-override"><code>$ pip install tensorflow --user Collecting tensorflow Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching distribution found for tensorflow </code></pre> <p>What am I doing ...
<p>I found this to finally work.</p> <pre><code>python3 -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.12.0-py3-none-any.whl </code></pre> <p>Edit 1: This was tested on Windows (8, 8.1, 10), Mac and Linux. Change <code>python3</code> to <code>python</code> according to your co...
python|tensorflow|pip
820
361,647
62,946,001
Keep row which the element in specific column (in timedelta64) is closest to zero
<p>I have a dataframe with many columns, with two columns of focus in this operation. One column that contains duplicated names and one contains timedelta64. I would like to get the row which the timedelta64 column element is the closest to zero. The below sample would illustrate the operation better. Any help would be...
<p>Soon you will be able to sort based on a function, but for now we need to create a temporary column. Take the absolute value and sort, that way the lowest values appear first which allows you to <code>drop_duplicates</code> on 'Name'</p> <pre><code>df['temp'] = df['Days'].abs() df = df.sort_values('temp').drop_dupl...
python|pandas
2
361,648
62,904,916
Tensorflow: ignore a specific dependency during tf.gradients()
<p>Given variables y and z, both of which depend on a tensor x. By product rule, if I do tf.gradients(y<em>z,x), it would give me y'(x)z(x) + z'(x)y(x). Is there a way I can specify y as a constant with respect to x such that tf.gradients(y</em>z,x) only gives me z'(x)y(x)?</p> <p>I know y_=tf.constant(sess.run(y)) wi...
<p>You can use <a href="https://www.tensorflow.org/api_docs/python/tf/stop_gradient" rel="nofollow noreferrer">tf.stop_gradient()</a> to block backpropagation. To block gradients in your example:</p> <pre class="lang-py prettyprint-override"><code>y = function1(x) z = function2(x) blocked_y = tf.stop_gradient(y) prod...
tensorflow|tensorflow-datasets
1
361,649
63,192,840
Identify numbers, in a large data string, that are prefixed to an alphabet upto 2 positions in between other characters
<p>I have a string containing thousands of lines of this data without line break (only a few lines shown for readability with line break)</p> <pre><code>5BengaluruUrban4598962MSARICoughBreathlessnessDM23.07.2020atGovernmenthospital 7DakshinaKannada4786665FSARICoughDMHTN23-07-2020atPrivatehospital </code></pre> <p>Forma...
<pre><code>import re input_str = '5BengaluruUrban4598962MSARICoughBreathlessnessDM23.07.2020atGovernmenthospital7DakshinaKannada4786665FSARICoughDMHTN23-07-2020atPrivatehospital' ages = [found[-3:-1] for found in re.findall('[0-9]+[M,F]', input_str, re.I)] print(ages) # ['62', '65'] </code></pre> <p>This works fine wi...
python-3.x|pandas|string|list|data-cleaning
1
361,650
63,041,119
Multiple inputs from one input request
<p>Just need someone to tell me how to run an input variable 1-50 instead of writing out input1 =, input 2 = etc.</p> <pre><code> ap1 = input('Airport 1:').upper() ap2 = input('Airport 2:').upper() ap3 = input('Airport 3:').upper() data = [['led1', ap1], ['led2', ap2], ['led3', ap3]] df = pd.DataFrame(data, columns=[...
<p>You can use a list instead of one variable for each input. Maybe something like this:</p> <pre><code>ap_list = [input(f'Airport{i+1}:').upper() for i in range(3)] data = [[f'led{i+1}', ap_list[i]] for i in range(len(ap_list))] df = pd.DataFrame(data, columns=['LedNum', 'AP']) df.to_csv('airports.csv') </code></pre>
pandas|input
1
361,651
63,107,393
Merge DataFrames with different number of rows and have a new column with sum of values
<p>I have this df1:</p> <pre><code>df1 = pd.DataFrame({'Player':['Zico', 'Leonidas', 'Didi'], 'Team': ['Flamengo', 'Flamengo', 'Botafogo'], 'Position': ['MID', 'DEF', 'MID'], 'Games_Away': [4, 4, 4]}) </code></pre> <p>And another df2 with a different numbers o...
<p>Do outer <code>merge</code></p> <pre><code>df=df1.merge(df2,on=['Player','Team','Position'],how='outer').fillna(0) df['Game_total']=df.Games_Away+df.Games_Home df Out[241]: Player Team Position Games_Away Games_Home Game_total 0 Zico Flamengo MID 4.0 3 7.0 1 Leon...
python|pandas
1
361,652
63,306,002
To output the closing price, total dividends of each year from a time-series dataframe
<p>My dataframe look like this:</p> <pre class="lang-py prettyprint-override"><code> Open High Low Close Volume Dividends Stock Splits Date 2015-08-07 16.64 16.64 16.64 16.64 0 0.0 0 2015-08-11 16....
<p>It's just a simple case of use <code>resample()</code> then define which aggregates you want from the columns.</p> <pre><code>import yfinance as yf import pandas as pd import datetime as dt end=dt.datetime.today() start=end-dt.timedelta(59) tickers=['WBA'] df = yf.download(tickers,group_by=tickers,start=start,end=e...
pandas|datetime|time-series|stock
0
361,653
62,998,216
pandas reindexing multiindex not working properly
<p>I have a <code>pandas</code> (<strong>version 1.0.5</strong>) <code>DataFrame</code> with a <code>MultiIndex</code> of two levels, f.i. like:</p> <pre><code>mi = pd.MultiIndex.from_product((('a', 'c'), (5, 12))) np.random.seed(123) df = pd.DataFrame(data=np.random.rand(4, 2), index=mi, columns=['x', 'y']) </code></p...
<p>This behaviour is not expected. Passing the <code>level</code> argument to <code>reindex</code> on a <code>MultiIndex</code> appears to be broken still in <code>pandas</code> version 1.2.3. There is an issue on github covering this:</p> <p><a href="https://github.com/pandas-dev/pandas/issues/25460" rel="nofollow nor...
python|pandas
1
361,654
63,268,659
Average by value duplicated pandas python
<p>I have the next csv and I need get the values duplicated from DialedNumer column and then the averege Duration of those duplicates.</p> <p><a href="https://i.stack.imgur.com/QPEXb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QPEXb.png" alt="enter image description here" /></a></p> <p>I already ...
<p>try:</p> <pre><code>df_mean = df.groupby('DialedNumber').mean() </code></pre>
python|pandas|dataframe
1
361,655
62,996,868
How to fill the nulls with conditions in python?
<p>I have a Dataframe</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.nan, index=range(1,19), columns=['A','B','C','D','E','F','G','H']) a = [1550, 41, 9.41, 22.6, 4.74, 3.2, 11.64, 2.23] b = [1540, 43, 9.41, 22.3, 4.84, 3.12, 11.64, 2.23] c = [1590, 39, 9.41, 23.7, 4.74, 3.0, 11.64, 2.23] ...
<p>You can try <code>ffill</code> + <code>bfill</code>, then take the average</p> <pre><code>df = (df.ffill()+df.bfill())/2 </code></pre>
python|python-3.x|pandas|python-2.7|dataframe
5
361,656
63,014,426
Pandas - Copying row as new columns for every row
<p>I have a dataframe of 18207x65. Each row corresponds to a player, each column to an attribute.</p> <p>I.e.</p> <pre><code>╔═════════════╦═══════╦═══════╦═════╦════════╗ ║ ║ Attr1 ║ Attr2 ║ ... ║ Attr65 ║ ╠═════════════╬═══════╬═══════╬═════╬════════╣ ║ Player1 ║ ║ ║ ║ ║ ║ Playe...
<p>I'd only select the row and create another dataframe for the ouput:</p> <pre><code>import pandas as pd chosen_player = input() chosen_player_row = d1.query(&quot;Name == @chosen_player&quot;).iloc[0] # you can also check that you have selected only one row with the filter def your_diff(x, y): return (x-y)**2 ...
python|pandas
0
361,657
63,036,156
Manipulate string in python (replace string with part of the string itself)
<p>So I am trying to transform the data I have into the form I can work with. I have this column called &quot;season/ teams&quot; that looks smth like &quot;1989-90 Bos&quot;</p> <p>I would like to transform it into a string like &quot;1990&quot; in python using pandas dataframe. I read some tutorials about pd.replace(...
<p>To change that field from &quot;1989-90 BOS&quot; to &quot;1990&quot; you could do the following:</p> <pre><code>df['Yr/Team'] = df['Yr/Team'].str[:2] + df['Yr/Team'].str[5:7] </code></pre> <p>If the structure of your data will always be the same, this is an easy way to do it.</p>
python|pandas|string|dataframe
0
361,658
63,029,919
Python pandas matplotlib how to remove category labels in the plot?
<pre><code># Example Python program to plot a complex bar chart import pandas as pd import matplotlib.pyplot as plot # A python dictionary data = {&quot;Car Price&quot;:[24050, 34850, 38150], &quot;Kerb Weight&quot;:[3045, 3572, 3638] }; index = [&quot;Variant1&quot;, &quot;Variant2&quot;...
<p>Change your second last line to this to remove the legend:</p> <pre><code>dataFrame.plot.bar(rot=15, title=&quot;Car Price vs Car Weight comparision for Sedans made by a Car Company&quot;, legend=False) </code></pre>
python|pandas|dataframe|matplotlib|bar-chart
2
361,659
62,994,628
Replaces all nan values in a large array of arrays dataset
<p>I am fitting a neural network model (autoencoder) on a very large array of arrays dataset, each nested array has the shape <code>(1, 100, 4)</code>.</p> <pre><code>Train_X.shape (639936, 1, 100, 4) </code></pre> <p>Right from the first epoch, I got loss with <code>nan</code> for both loss/val_loss:</p> <pre><code>Ep...
<p>you can use <code>np.isnan</code>, <code>np.nanmean</code> and indexing, the second <code>x[np.isnan(x)]</code> is to set the all <code>nan</code> columns to zeros</p> <pre><code>x = np.random.randint(0,100,[2,1,4,4]).astype(float) x[0][0][[0,1,3],[1,2,2]] = float('nan') x[1][0][[0,1,3],[1,3,2]] = float('nan') x[0,0...
python|arrays|numpy|multidimensional-array
2
361,660
63,041,092
export dataframe to attributes-list-structure xml
<p>My name is Pablo, and this is my first question in this group. After checking others related posts, I´ve decided to make a request, I wonder if there is a way to perform the following.</p> <p>Let´s suppose I´ve the following dataframe structure:</p> <pre><code>+----+---------+------------+------------+----------+ | ...
<p>I see key as structuring your data better first for your target xml representation.</p> <ol> <li>groupby MRBTS</li> <li>custom aggregation to return list of items for attribute <a href="https://stackoverflow.com/questions/22219004/how-to-group-dataframe-rows-into-list-in-pandas-groupby">list aggregation</a>. I've us...
python|xml|pandas|dataframe
0
361,661
63,216,562
QCombobox finData method always returns -1 with numpy array
<p>I have a problem trying to get the index of some data on the combobox when a numpy array is used to add the items, while if I use a list the result is the expected.</p> <pre><code>from PySide2 import QtWidgets import numpy as np app = QtWidgets.QApplication() heights_list = [0.52, 1, 2, 3, 4, 12.57, 14.97] heigh...
<p>The <a href="https://doc.qt.io/qt-5/qcombobox.html#findData" rel="nofollow noreferrer"><code>findData()</code></a> method uses the model's <a href="https://doc.qt.io/qt-5/qabstractitemmodel.html#match" rel="nofollow noreferrer"><code>match()</code></a> method, and the match method uses the <a href="https://doc.qt.io...
python|python-3.x|numpy|pyside2|qcombobox
2
361,662
63,187,782
Pandas Resample-Sum without Zero filling
<p>When resampling Series with mean aggregation (daily to monthly) -&gt; missing datetimes are filled with NaNs which is okay since we can simply remove them using <code>.dropna()</code> function, however, with sum/total aggregation -&gt; missing datetimes are filled with 0s (zeros) which is technically correct, but a ...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.tseries.offsets.MonthEnd.html" rel="nofollow noreferrer"><code>pd.offsets.MonthEnd</code></a> and add this with the <code>DatetimeIndex</code> of <code>ser</code> to create a month end grouper, then use <a href="https://pandas.pydata.org/...
python|pandas|time-series
2
361,663
63,030,692
How do I use BertForMaskedLM or BertModel to calculate perplexity of a sentence?
<p>I want to use BertForMaskedLM or BertModel to calculate perplexity of a sentence, so I write code like this:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import torch import torch.nn as nn from transformers import BertTokenizer, BertForMaskedLM # Load pre-trained model (weights) with torch....
<p>Yes, you can use the parameter <code>labels</code> (or <code>masked_lm_labels</code>, I think the param name varies in versions of huggingface transformers, whatever) to specify the masked token position, and use <code>-100</code> to ignore the tokens that you dont want to include in the loss computing. For example...
nlp|pytorch|transformer-model|huggingface-transformers|bert-language-model
8
361,664
63,275,597
Dumping Image data and load using pytorch dataloader
<p>I want to dump the data so that I can load it back for training my model.</p> <p>My code snipped for dumping the data:</p> <pre><code>for batch_idx, (image, label) in enumerate(dataloader): image, label = image.to(device), label.to(device) perturbed_image = attack.perturb(image, label) #---------- C...
<p>The most straight forward approach would be to use <a href="https://pytorch.org/docs/stable/generated/torch.save.html#torch.save" rel="nofollow noreferrer"><code>torch.save</code></a> to save the actual tensors of <code>perturbed_image</code> and <code>label</code> as binary files, and then use a <a href="https://st...
python|image|pytorch
0
361,665
63,098,100
Regarding min_period in corr() function python
<p>I am trying to create a corr matrix. This is regarding the documentation <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.corr.html" rel="nofollow noreferrer">here</a> on <code>min_period</code>. So what i understand is <code>min_period</code> is the number of days for which the c...
<p>It means you need at least 10 valid pairs. Othwerwise it will be <code>np.nan</code>. Documentation states:</p> <blockquote> <p>Minimum number of observations required per pair of columns to have a valid result. Currently only available for Pearson and Spearman correlation.</p> </blockquote>
python|python-3.x|pandas|correlation
1
361,666
63,316,396
"1 Physical GPUs, 0 Logical GPU " when i train the model the gpu is not working
<p>ubntu version 18.04 nvidia Smia 440.1.0 cuda 10.2 GTx 960 tensorboard 2.3.0 tensorboard-plugin-wit 1.7.0 tensorflow-estimator 2.3.0 tensorflow-gpu 2.3.0</p> <p>My gpu is not working or you can say its installed but when i run the model it's not allocating to the gpu here the image</p>
<p>run this code to see if tensorflow is detecting your gpu. If number of gpus is listed as 0 then it is not detecting it. You need to have Cuda 10.1 on your systen and cuDNN v7.6.5. In that case if you are using Anaconda open the conda prompt and run conda install cuDNN=7.6.5. You may also have to install CUDA Toolk...
python|tensorflow|model|gpu
0
361,667
62,931,809
cannot concatenate object of type "<class 'numpy.ndarray'>"; only pd.Series, pd.DataFrame, and pd.Panel (deprecated) objs are valid
<p>My input data is under the form:</p> <pre><code> gold,Program,MethodType,CallersT,CallersN,CallersU,CallersCallersT,CallersCallersN,CallersCallersU,CalleesT,CalleesN,CalleesU,CalleesCalleesT,CalleesCalleesN,CalleesCalleesU,CompleteCallersCallees,classGold T,chess,Inner,Low,-1,-1,Low,-1,-1,High,-1,-1,-1,-1,Low,1,T...
<p>By adding <code>.values</code> to the end of your filters in the following lines:</p> <pre class="lang-py prettyprint-override"><code>CompleteSet_X = CompleteSet.iloc[:, 1:column_count].values CompleteSet_Y = CompleteSet.iloc[:, 0].values X_test1=TestSet.iloc[:, 1:column_count].values </code></pre> <p>You are extrac...
python|pandas|dataframe|concatenation
4
361,668
63,227,027
Tensorflow / Keras LSTM errors "Function call stack: distributed_function"
<p>I am using a stacked LSTM for a multi-class classification where I have 5 &quot;string&quot; labels. Here is a snippet of the code:</p> <pre><code># define parameters #epochs, batch_size = 20, 46 epochs, batch_size = 5, 40 # define model model = Sequential() model.add(LSTM(128,input_shape=(X_train.shape[1],X_train....
<p>It seems that you are trying to feed string data directly into the network. Hence the error <code>Cast string to float is not supported</code>. If you are dealing with categorical data, you should convert it into numerical first. Depending on the type of categorical data you are using, different techniques should be...
python|tensorflow|keras|lstm|softmax
1
361,669
62,906,266
Problem with Import object_detection/protos/image_resizer.proto but not used protobuf compilation in OS High Sierra
<p>I have a problem in a OS terminal compiled: ./bin/protoc object_detection/protos/*.proto --python_out=.</p> <p>object_detection/protos/input_reader.proto:5:1: warning: Import object_detection/protos/image_resizer.proto but not used.</p> <p>Anyone knows how can solve this bug?. I read in other similar post deleted or...
<p>it's not an error it's just a warning. You will also receive &quot;warnings&quot; in the following sections. For example, in the new version of Tensorflow, you will receive the warning that the training record will be deleted automatically. Do not get stuck in warnings, trouble if errors.</p>
python|tensorflow|protostuff
0
361,670
62,993,277
Issues with category predict based on text description - Cast string to float is not supported
<p>I am trying to create a model to predict category(text) based on description(text)</p> <p>I am following the approach as listed <a href="https://www.tensorflow.org/tutorials/structured_data/feature_columns?hl=en" rel="nofollow noreferrer">here</a></p> <p>Using tensorflow version 2.2.0</p> <pre><code>import pandas as...
<p>I have the same problem not only with categorical features, but also numeric features. It works if I don't use any feature_columns. The issue is gone after downgrading to tensorflow 2.1</p>
python|pandas|tensorflow|keras|text-classification
0
361,671
63,132,054
pandas reset index of multi index dafaframe to a date value and convert the other indexes as columns
<p>I have a multi index dataframe as shown below:</p> <pre><code> number location category created_on Arab Republic of Egypt ACCESS 2018-06-25 00:00:00 4 ACCOUNT 2018-04...
<p>Use <code>swaplevel</code> on levels <code>0</code> and <code>2</code> and then use <code>reset_index</code> on levels <code>1</code> and <code>2</code>:</p> <pre><code>df1 = df.swaplevel(0, 2).reset_index(level=[1, 2]) </code></pre> <p>OR another idea first use <code>reset_index</code> then use <code>set_index</cod...
python|pandas|dataframe|datetime
1
361,672
63,142,755
Create a BOOL column based on conditions in other columns
<p>I have a dataframe:</p> <pre><code>df = pd.DataFrame(np.random.randint(0,100,size=(15, 4)), columns=list('ABCD')) </code></pre> <p>I would like to create another BOOL column or YES/NO column based on the sum of column A and B &gt; 150</p> <p>I am trying a generator kind of solution:</p> <pre><code>df['Truth'] = ['Ye...
<h2>How to get a column of Boolean values:</h2> <ul> <li><code>(df.A + df.B) &gt; 150</code> generates a <code>pandas.Series</code> of Boolean values. Assign it to a column name.</li> </ul> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np # sample data np.random.seed(2) df = pd.Da...
python-3.x|pandas
2
361,673
63,275,790
Missing gradient when using tf.function
<p>I have found that if I want to use <code>tf.gradients</code> in tensorflow 2 rather than a gradient tape, I can do this by wrapping the code in a <code>tf.function</code>-decorated function. But somehow, I can't take the gradient with respect to a variable this way:</p> <pre><code>import tensorflow as tf a = tf.Vari...
<p>The op <code>b = 0.01 * a</code> is out the graph created by the <code>tf.function</code>-decorated function.</p> <p>you can use :</p> <pre><code>a = tf.Variable(initial_value=1.0, dtype=tf.float32) @tf.function def get_grads(): b = 0.01 * a return tf.gradients(b, a) print(get_grads()) </code></pre>
python|tensorflow|tensorflow2.0
1
361,674
63,004,208
Finite difference method for 3D diffusion/heat equation
<p>I'm trying to use finite differences to solve the diffusion equation in 3D. I think I'm having problems with the main loop. In particular the discrete equation is:</p> <p><img src="https://i.imgur.com/F1nyx73.jpg" alt="" /></p> <p>With Neumann boundary conditions (in just one face as an example):</p> <p><img src="ht...
<p>there are something wrong with this code: w2[:,:,0] = w2[:,:,0] + 2 <em>kapp</em> (dt4/(dx4**2)) * (w2[:,:,-1] - w2[:,:,0] - qq5 * dx4/kapp) please check it again. and I am working on a similar project recently. Do you have a moment to share some experience with me.</p>
python|numpy|physics|pde|heat
1
361,675
63,228,075
New column with values 1/0 in pandas
<p>I have this dataframe having one column of my interest:</p> <pre><code>Col1 code goal python detail </code></pre> <p>I would like to create a new column, Col2 having values 1 or 0 depending on rows' value in Col1; specifically:</p> <ul> <li>if a row has a value in the list <code>my_list=['goal', 'detail', 'objec...
<p>Use <code>np.where</code> + <code>Series.isin</code></p> <pre><code>import numpy as np my_list=['goal', 'detail', 'objective'] df['Col2'] = np.where(df.Col1.isin(my_list), 1, 0) </code></pre> <p>or as mentioned by @Ch3steR</p> <pre><code>df['Col2'] = df.Col1.isin(my_list).astype('int') </code></pre> <hr> <pre><cod...
python|pandas
1
361,676
62,923,497
The best way to find the win percentage for a pandas DataFrame with win, loss columns
<p>I have a pandas DataFrame with two columns (<code>'win'</code> and <code>'loss'</code>) and I want to find the win percentage (<code>'win%'</code>) and pass it into the DataFrame. The thing is, for some rows, the entries are 0, so for those rows, I need to pass <code>np.nan</code> into <code>'win%'</code>.</p> <p>Th...
<p>You can set all the zero values to np.nan first (using replace), because:</p> <pre><code>np.nan / np.nan = np.nan </code></pre> <p>And:</p> <pre><code>np.nan + np.nan = np.nan </code></pre> <p>So:</p> <pre><code>df = pd.DataFrame( [[1,2],[0,0],[2,1]],columns=['win','loss'] ).replace(0, np.nan) df[&quot;win%&quot...
python|pandas
1
361,677
63,088,685
dataframe remove rows with less than 5 duplicate values
<p>This is how my dataset looks:<a href="https://i.stack.imgur.com/fcO5Q.png" rel="nofollow noreferrer">dataset sample</a></p> <p>I am trying to remove player entries that has less than 5 years (5 entries of the same name) from the whole dataset. So in the sample snapshot, A.C. Green rows should be left untouched.</p> ...
<p>Did you try:</p> <pre><code>n = playersData[['Player']] playerData = playersData[n.replace(n.apply(pd.Series.value_counts)).gt(5).all(1)] </code></pre>
python|pandas|dataframe|duplicates
0
361,678
63,298,037
Pandas: How to update only up to n rows if condition is matched
<p>I need to update values of column B only for [:1000] positive matches. How can I implement this in the most robust and simple way?</p> <pre><code> condition_mask = (df[&quot;A&quot;] &gt;= from) &amp; (df[&quot;A&quot;] &lt; to) df.loc[condition_mask,'B'] = some_value </code></pre>
<p>Here's a way to do that. I'm using synthetic data for demonstration.</p> <pre><code># Create data: df = pd.DataFrame({&quot;a&quot;: np.random.randint(0, 5, 10), &quot;b&quot;: np.random.randint(0, 5, 10)}) print(df) a b 0 4 1 1 0 0 2 0 2 3 3 3 4 2 4 5 3 3 6 2 3 7 1 4 8 0 ...
python|pandas|dataframe|slice
1
361,679
63,293,561
How to use the try function on multiple lines of text in python pandas
<p>Hi I am scraping text of a website each day which is in the form of a dataframe in python and i have a line of code which looks for the index number of the first time <code>Day n</code> appears:</p> <pre><code>Scrape example 1: Text acb xyz Day 1 hij mno Scrape example 2 Text acb xyz Day 4 hij mno </code></pre> <p>...
<p>Try with</p> <pre><code>from natsort import index_natsorted s=df.loc[df['Text'].str.startswith(('Day ')),'Text'] s.index[np.array(index_natsorted(s))==0] Out[41]: Int64Index([2], dtype='int64') </code></pre> <p>Input dataframe</p> <pre><code>df Out[42]: Text 0 Day 4 1 xyz 2 Day 1 3 hij 4 mno </code><...
python|pandas
0
361,680
62,998,456
Comparison of complete null column with a string in Pandas DataFrame
<p>I have to include an extra line of code because of this peculiar behavior.</p> <pre><code>df1 = pd.DataFrame([[np.NaN,1,'2'],[np.nan,3,np.NaN]]) df1[0]=='a' # This is throwing an error df1[0]==2 # This is returning a series </code></pre>
<p>This works fine for me. When i run :</p> <pre><code>df1[0]=='a' </code></pre> <p>Output:</p> <pre><code>0 False 1 False </code></pre> <p>Pls check your pandas version.</p>
python|pandas|dataframe|nan
0
361,681
62,963,941
Pandas: Turn a Subset of Column Names Into Values
<p>If I have pandas data frame like this:</p> <pre><code> | F1 | F2 | F3 | Flag --------------------- 0 | 10 | 22 | 54 | True 1 | 3 | 77 | 9 | False </code></pre> <p>How can I turn it into this:</p> <pre><code> | F | Val | Flag ------------------- 0 | F1 | 10 | True 1 | F2 | 22 | True 2 | F3 | 54 | True 3 |...
<p>Use <code>df.melt</code>:</p> <pre><code>In [141]: df.melt(id_vars='Flag', var_name='F', value_name='Val') Out[141]: Flag F Val 0 True F1 10 1 False F1 3 2 True F2 22 3 False F2 77 4 True F3 54 5 False F3 9 </code></pre>
python|python-3.x|pandas|dataframe
2
361,682
62,904,270
Redefining variable inside the loop python
<p>Using this code,</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame ({'Date':['2000-01-01', '2000-02-01', '2000-03-01', '2000-01-01', '2000-02-01', '2000-03-01','2000-04-01' ], ...
<p>You can do a groupby, but you need to have your <code>bal_d1_pct</code> to be numerical first:</p> <pre><code>df.bal_d1_pct = pd.to_numeric(df.bal_d1_pct, errors='coerce').fillna(0)/100 + 1 df['fore'] = (df.groupby('id') .apply(lambda x: x.bal_tot.iloc[0] * x.bal_d1_pct.cumprod()) .reset_index('id',drop=True)...
python|pandas|loops|variables|redefine
1
361,683
63,288,433
Calculate coefficient of variation of window in astropy
<p>I have an array that I want to calculate statistics for using astropy. What I have is:</p> <pre><code>from astropy.convolution import convolve import numpy as np x = np.random.randint(1, 10, size=(5, 5)) y = convolve(x, np.ones((3, 3)), boundary='extend', preserve_nan=True) print(x) print(y) [[9 1 8 6 5] [4 2 1 ...
<p>Astropy builds on numpy and scipy. Numpy is the low-level array library that implements the data storage and basic operations that are used by higher level libraries such as scipy and astropy. Understanding how numpy arrays work will help you work with astropy.</p> <p>Since you want to do statistics on a rolling win...
python|numpy|scipy|astropy
2
361,684
63,147,507
multiplying a vector (1 x N) by a tensor (N x M x M)
<p>I am looking for a matrix operation in numpy or preferably in pytorch that allows one to multiply a vector (1 x N) by a tensor (N x M x M) and get (1 x M x M). This is easily accomplished using a for loop, but the for loop does not allow back propagation during training. I tried using matmul in numpy and pytorch (a...
<p>You can use simple einsum:</p> <pre><code>#this gives you 2-D array (M,M) np.einsum('i,ijk-&gt;jk',a,b) </code></pre> <p>output:</p> <pre><code>[[38 44] [50 56]] </code></pre> <p>or another solution:</p> <pre><code>#this gives you 3-D array (1,M,M) a[None,:]@b.swapaxes(0,1) </code></pre> <p>output:</p> <pre><code>[...
python|arrays|numpy|pytorch|matrix-multiplication
3
361,685
63,293,101
How to get the sum of the value of certain elements of a NumPy array?
<p>I have three NumPy arrays. Two arrays (say <code>a</code> and <code>b</code>) contain the left and right bound of the column number of the third array (<code>c</code>) that is to be processed, i.e. have the values of its elements within the bounds summed. How do I do this in NumPy? Presently, I have done it with Pyt...
<pre><code>idx = np.repeat(np.arange(c.shape[1])[None, :], c.shape[0], axis=0) (c * ((idx &gt;= a[:, None]) &amp; (idx &lt; b[:, None]))).sum(axis=1) # output: array([297, 609, 441]) </code></pre> <p>What is going on here:</p> <ol> <li>Create a tile of ranges: [[0, 1, ...n], [0, 1, ..., n], ...]</li> <li>row-wise, set ...
python|numpy
1
361,686
62,934,824
ValueError: could not convert string to float: '2,3972E-7'---loadtxt (numpy)
<p>This is some sample from large txt file: [0, 0, 0, 2.3972E-7, 2.3972E-6, 1.23, 100.5, 1000.78, 2012.99] and I get ValueError: could not convert string to float: '2,3972E-7'. Here is code:</p> <pre><code># read the data sample W_data = open(&quot;power.txt&quot;).read().split() W_data1 = np.array(W_data).astype('floa...
<pre><code>In [22]: a = [0, 0, 0, 2.3972E-7, 2.3972E-6, 1.23, 100.5, 1000.78, 2012.99] In [25]: np.array(a).astype(np.float64) Out[25]: array([0.00000e+00, 0.00000e+00, 0.00000e+00, 2.39720e-07, 2.39720e-06, 1.23000e+00, 1.00500e+02, 1.00078e+03, 2.01299e+03]) </code></pre>
python|python-3.x|list|numpy|numpy-ndarray
1
361,687
62,958,592
Weekly sum not equal to the monthly sum pandas
<p>Here's a subset of my data: (for minimum reproducible code)</p> <pre><code>01-01-20,128921.04 02-01-20,125338.56 03-01-20,100824.66 04-01-20,129203.39 05-01-20,164149.36 06-01-20,120360.65 07-01-20,113249.99 08-01-20,130191.88 09-01-20,101189.75 10-01-20,103243.14 11-01-20,105493.14 12-01-20,140929.83 13-01-20,11156...
<p>I have recheked your values and pandas is indeed giving you the right sum.</p> <h2>Why monthly sum does not match with pandas sum?</h2> <p>Your data have dates which goes into July yet the sums you mentioned are only till June. So obviously it will be less when you paste these values into an external software!</p> <...
python|pandas
1
361,688
63,011,925
Formatting DataFrame Object
<p>I am new to python and trying to pull a table from a wiki page into a pandas dataframe. I am using the <code>wikipediaapi</code> to retrieve the URL for the site. (Is there a way to pull the table directly using the api instead of pandas?). Also noteworthy I am trying to use the method as described <a href="https://...
<p>If you are using <a href="https://jupyter.org/" rel="nofollow noreferrer">Jupyter Notebook</a> and you want your data frame to be formatted as table, do not use <code>print()</code> function to print you data frame. Just run the cell with the name of your data frame, like this:</p> <pre><code>In [1]: sum_table_df Ou...
python|pandas|dataframe
0
361,689
63,246,779
Numpy computes eigenvalues wrongly. What to do?
<p>I use <code>evals, evecs = np.linalg.eig(matrix)</code> to find the eigenvalues in my square matrix, which is a Laplacian of a connected graph, therefore one of the eigenvalues should equal to 0. According to numpy, none does. Seeing posts in the web proposing using SymPy, I did it, but SymPy says it can't compute t...
<p>One of the values in <code>evals</code> is really close to Zero</p> <pre><code>import numpy as np import scipy.linalg as la mat = np.array([[ ... ]]) evals, evecs = la.eig(mat) print(min(evals)) </code></pre> <p>output:</p> <pre><code>-2.103461851787978e-14+0j </code></pre> <p>Maybe just a rounding problem?</p> <p...
python|numpy|sympy
1
361,690
63,046,604
Strange, inconsistent behavior in checking whether a python list contains a numpy array
<p>So there's no issue if I do:</p> <pre><code>A = [[1,2,3],[4,5,6]] B = [1,2,3] B in A #=&gt; True </code></pre> <p>But if I do:</p> <pre><code>A = [[1,2,3],[4,5,6]] A = [np.array(x) for x in A] A[0] in A #=&gt; True z = np.array([1,2,3]) z in A #=&gt; ValueError: The truth value of an array with more than one eleme...
<p>So this is subtle. <code>in</code> will ultimately use <code>==</code> to compare the elements, that will result in a boolean array (with all Trues). However, <code>numpy</code> explicitly prevents arrays from being used in a boolean context... as explained in the error message. So this is one way that <code>numpy....
python|numpy
2
361,691
63,033,761
Python | Pandas | Read Excel table with different format
<p>I've a excel file with the following format:</p> <p><a href="https://i.stack.imgur.com/doxmO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/doxmO.png" alt="enter image description here" /></a></p> <p>I'm trying read this table as a dataframe in order to get the following format:</p> <pre><code>Na...
<p>You can transpose it like a matrix. In addition, set <code>index_col</code> to be <code>&quot;Name&quot;</code> if you don't want indexes.</p> <pre><code>df = pd.read_excel(filename, sheet_name='Sheet1' ,index_col=&quot;Name&quot;, header=0) df = df.T print(df) </code></pre> <pre><code>Name Age Job Peter 2...
python|excel|pandas
1
361,692
63,256,852
How can i solve the TypeError gotten while working with feature_engine
<p>I am working with feature_engine to fill missing values</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt # from feature-engine from feature_engine import missing_data_imputers as mdi #Working with House Data and Feature Engine__Practice cols_to_use = [ 'BsmtQual', 'Fireplace...
<p>By looking at the stack trace you provided, this seems to me like an incompatibility between <code>feature_engine</code> and an old version of scikit-learn. In older versions (e.g. <a href="https://scikit-learn.org/0.21/modules/generated/sklearn.utils.validation.check_is_fitted.html" rel="nofollow noreferrer">0.21</...
python|pandas|machine-learning|scikit-learn|feature-engineering
1
361,693
63,109,692
ValueError: Input 0 of layer sequential_6 is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [32, 28, 28]
<p>I tried the following code, but I encountered the above error. I saw some similar questions but I didn't get a proper solution. Please help me!</p> <pre><code>import tensorflow as tf import numpy as np import matplotlib.pyplot as plt mnist=tf.keras.datasets.mnist #download the dataset (xtrain, ytrain),(xtest, ytes...
<p>your network expect images in black and white (1 channel), so you have to modify your data accordingly to this. this is possible simply adding dimensionality to your images before fitting</p> <pre><code>xtrain = xtrain[...,None] # (batch_dim, 28, 28, 1) xtest = xtest[...,None] # (batch_dim, 28, 28, 1) </code></pre>
python-3.x|keras|tensorflow2.0|numpy-ndarray|conv-neural-network
1
361,694
63,319,069
How to get bar y axis in ascending order starting from zero
<pre><code># Set x_axis, y_axis &amp; Tick Locations x_axis = final_df[&quot;title&quot;] ticks = np.arange(len(x_axis)) y_axis = final_df[&quot;salary&quot;] plt.bar(x_axis, y_axis, align=&quot;center&quot;, alpha=0.5, color=[&quot;k&quot;, &quot;r&quot;, &quot;g&quot;, &quot;m&quot;, &quot;b&quot;, &quot;c&quot;, &qu...
<p>It seems like the values in the <code>&quot;salary&quot;</code> column are strings. In this case add the following to your code:</p> <pre class="lang-py prettyprint-override"><code>replace_pattern = r'\$|,' final_df['salary'].replace(replacement_pattern, '', regex=True, inplace=True) # replace $ and , ...
python|pandas|matplotlib
0
361,695
63,292,649
Why using np.mean() and mean() gave me different output number?
<p>It is interesting to notice that using np.mean() or mean() gave me different outputs.</p> <pre><code>from statistics import mean import numpy as np import matplotlib.pyplot as plt xs = np.array([1, 2, 3, 4, 5, 6]) ys = np.array([5, 4, 6, 5, 6, 7]) def best_fit_slope(xs, ys): numerator = (mean(xs)*mean(ys)) - m...
<p>This is due to how the <code>statistics</code> package tries to give you consistent outputs depending on the numeric type you pass in, so it handles <code>int</code>, <code>float</code>, <code>decimal.Decimal</code>, <code>fractions.Fraction</code> as you would hope. Unfortunately, <code>numpy</code> types don't pla...
python|arrays|numpy|linear-regression
2
361,696
63,068,206
Keras metric for multiple outputs
<p>I have a keras model with 1 input and 2 outputs.</p> <p>To evaluate the model, my metric requires <code>output_1</code>, <code>true_y_1</code> as well as <code>output2</code> and <code>true_y_2</code>, as it is a complex metric that requires the use of both outputs.</p> <p>Is there a way to define such metric?</p> <...
<p>here an example where I used a callback to compute a custom metric that uses 1 input and 2 outputs</p> <pre><code>class CoolCallback(Callback): def __init__(self, train_data, val_data=None): super().__init__() self.train_data = train_data self.val_data = val_data def on_epoch_end(sel...
python|tensorflow|keras
1
361,697
63,138,926
Optimize the execution speed and improve the readability of code
<p>How can I optimize the speed and improve readability for the following piece of code?</p> <pre><code>for j in range(len(Relevant_data)): for x in ['A', 'BB', 'BV', 'Cy', 'R','T']: if Relevant_data['Type'].iloc[j]==x: if Relevant_data['Amount'].iloc[j]&gt;=np.asscalar(t.loc[x,0.0].values) and Rel...
<p>I was able to increase the readability and improve the execution time of my code.</p> <pre><code>def analyze(Amount_R,Type_R): if np.asscalar(t.loc[Type_R,0.0].values)&lt;=Amount_R&lt;np.asscalar(t.loc[Type_R,0.25].values): return &quot;{} of {}&quot;.format(&quot;Bin1&quot;,Type_R) if np.asscalar...
python|pandas|numpy|dataframe|lambda
0
361,698
63,254,577
Why in a pandas DataFrame with a MultiIndex columns of one level indexing behaves differently?
<p>Using the example from <code>pandas</code> docs found <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.from_tuples.html" rel="nofollow noreferrer">here</a>, the following indexing works perfectly, the result being a <code>pd.Series</code>:</p> <pre><code>import pandas as pd tuple...
<p>Have you updated your version of pandas? In <code>pandas v1.1.0</code>, you can index with one level as you have done, and slicing returns a <code>pd.Series</code></p> <pre><code>import pandas as pd tuples = [(1,), (2,)] columns = pd.MultiIndex.from_tuples(tuples, names=['number']) asdf = pd.DataFrame(columns=column...
python|pandas|dataframe|indexing|multi-index
1
361,699
63,030,102
ImportError: No module named 'utils.io'
<p>After installing tensorflow,I run my code ,I get the simgle import error :</p> <pre><code>import utils.io.image ModuleNotFoundError: no module named 'utils.io </code></pre> <p>and before this error I get the error:</p> <p><code>ImportError: No module named 'utils'</code></p> <p>After installing the python-utils,th...
<p>I think you need to use another module from the same developer's GitHub of your code.</p> <p>Check this link (<a href="https://github.com/christianpayer/MedicalDataAugmentationTool" rel="nofollow noreferrer">https://github.com/christianpayer/MedicalDataAugmentationTool</a>)</p> <p>You can find the directory named 'u...
python|tensorflow|anaconda|modulenotfounderror
0