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
4,400
35,402,074
`unique` in data.frame.describe() not work [python][pandas]
<p>Hi it's something fundamental but I can't fix it... <code>unique()</code> shows unique values in each column, but <code>describe()</code> shows NaN. Why... Any help's appreciated. thanks</p> <pre><code>import numpy as np import pandas as pd train = pd.read_csv('train.csv', header=0) # works: train['Pclass'].uniqu...
<p>The <code>describe</code> method for numeric columns doesn't list the number of unique values, since this is usually not particularly meaningful for numeric data, the <code>describe</code> method for string columns does:</p> <pre><code>import pandas as pd df = pd.DataFrame({'string_column': ['a', 'a', 'b'], 'numeri...
python|pandas|unique|describe
3
4,401
35,465,176
Visible Deprecation warning...?
<p>I have some data that Im reading from a h5 file as a numpy array and am doing some analysis with. For context, the data plots a spectral response curve. I am indexing the data (and a subsequent array I have made for my x axis) to get a specific value or range of values. Im not doing anything complex and even the lit...
<p>Previous questions on this warning:</p> <p><a href="https://stackoverflow.com/questions/33098765/visibledeprecationwarning-boolean-index-did-not-match-indexed-array-along-dimen">VisibleDeprecationWarning: boolean index did not match indexed array along dimension 1; dimension is 2 but corresponding boolean dimension...
arrays|numpy|warnings|h5py
18
4,402
28,622,619
InvalidBSON on MongoDB import - Pandas
<p>I'm currently working with Pandas (0.14.1) in Python 3.4.2 importing data from a Mongo database using pymongo (2.8). Upon a simple import,</p> <pre><code>cur = db.collection.find() df = pd.DataFrame(list(cur)) </code></pre> <p>I'm getting the following error:</p> <pre><code>InvalidBSON: 'utf-8' codec can't decode...
<p>I don't believe there is a way of applying encoding on a cursor object while directly loading it into pandas. You may want to use mongoexport to dump your data into a csv first:</p> <pre><code>mongoexport --host localhost --db dbname --collection name --csv &gt; test.csv </code></pre> <p>...and then you load that ...
python|mongodb|python-3.x|pandas|pymongo
0
4,403
50,966,435
How to make the conversion NaN >> [''] to all the elements of a Pandas Dataframe?
<pre><code>import pandas as pd import numpy as np df = pd.DataFrame({ 'A': [[1, 2, 3, 4], [4, 5, 6, 7, 8], [7, 6, 4], np.nan, [1, 2]], 'B': [[1, 2, 3, 4], [4, 5, 6, 7, 8], [3, 7, 9], np.nan, [4, 5]], 'E': [np.nan, np.nan, np.nan, np.nan, np.nan], 'F': [[2, 2], [4, 4], np.nan, [78, 90], np.nan] }) # Fi...
<p><strong>UPDATE:</strong></p> <pre><code>In [136]: df.applymap(lambda x: x if isinstance(x, list) else []) Out[136]: A B E F 0 [1, 2, 3, 4] [1, 2, 3, 4] [] [2, 2] 1 [4, 5, 6, 7, 8] [4, 5, 6, 7, 8] [] [4, 4] 2 [7, 6, 4] [3, 7, 9] [] [] ...
python|python-3.x|pandas|dataframe|nan
2
4,404
50,905,364
get column name that contains a specific value in pandas
<p>I want to get column name from the whole database (assume the database contains more than 100 rows with more than 50 column) based on specific value that contain in a specific column in pandas.</p> <p>Here is my code:</p> <pre><code>import pandas as pd df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 'C':[7,8,9]}) pos...
<p>Try this</p> <pre><code>for i in df.columns: newDf = df.loc[lambda df: df[i] == response] if(not newDf.empty): print(i) </code></pre>
python|python-2.7|pandas
2
4,405
9,224,718
What's the most efficient way to compute the mode in a sliding window over a 2D array in Python?
<p>I have an RGBA image that I need to upscale while keeping it smooth. </p> <p>The catch is that I need to keep the colors exactly the way they are (background: I'm resizing a map where provinces are color-coded), and so I cannot just perform a resize with bicubic interpolation, because that will also interpolate th...
<p>If you care about a fixed set of colors in your image, the "Palette" image mode would perhaps be more appropriate (at least, if you don't have more than 256 colors in your map).</p> <p>I would suggest to first convert your image to the "P" mode (Since I'm not really familiar with PIL, I'm not sure, how easy that is...
python|numpy|python-imaging-library|mode|sliding-window
1
4,406
6,091,378
The concept behind scipy.signal.medfilt2d in python
<p>I am trying to understand how scipy.signal.medfilt2d works. After I looked at the scipy documentation, its format is:</p> <p>scipy.signal.medfilt2d(input, kernel_size=3)</p> <p>So like if I have a matrix like</p> <pre><code>1 2 3 7 2 4 3 4 2 2 6 7 1 7 3 1 2 6 3 2 3 4 3 1 2 6 7 8 2 5 3 4 2 2 1 8 </code></pre> <p>...
<p>As explained in the <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/signal.html#median-filter" rel="nofollow">Scipy documentation</a>, <code>medfilt2</code> is a median filter. Quoting from the documentation,</p> <pre><code>The sample median is the middle array value in a sorted list of neighborhood val...
python|matrix|numpy|scipy
2
4,407
66,596,142
BertModel or BertForPreTraining
<p>I want to use Bert only for embedding and use the Bert output as an input for a classification net that I will build from scratch.</p> <p>I am not sure if I want to do finetuning for the model.</p> <p>I think the relevant classes are BertModel or BertForPreTraining.</p> <p><a href="https://dejanbatanjac.github.io/be...
<p>You should be using <code>BertModel</code> instead of <code>BertForPreTraining</code>.</p> <p><code>BertForPreTraining</code> is used to train bert on Masked Language Model (MLM) and Next Sentence Prediction (NSP) tasks. They are not meant for classification.</p> <p>BERT model simply gives the output of the BERT mod...
deep-learning|nlp|bert-language-model|huggingface-transformers|transformer-model
5
4,408
66,605,849
extract date only from pandas column
<p>I have this column in pandas df: '''</p> <pre><code>full_date 2020-12-02T08:11:30-0600 2020-12-02T02:11:50-0600 2020-12-03T08:56:29-0600 </code></pre> <p>'''</p> <p>I only need the date, hoping to have this column: '''</p> <pre><code>date 2020-12-02 2020-12-02 2020-12-03 </code></pre> <p>'''</p> <p>I have tried to f...
<p>In case your column is not a <code>datetime</code> type, you can convert it to that and then use the <code>.dt</code> accessor to get just the date:</p> <pre><code>&gt;&gt;&gt; df[&quot;date&quot;] = df[&quot;full_date&quot;].pipe(pd.to_datetime, utc=True).dt.date &gt;&gt;&gt; print(df) full_date ...
python|pandas
1
4,409
66,597,043
How can I count frequency by data in dataframe?
<p>I have an issue with groupby in pandsa. My DF looks like below:</p> <pre><code>time ID 01-13 1 01-13 2 01-14 3 01-15 4 01-15 5 </code></pre> <p>I need result like below:</p> <pre><code>time ID 01-13 2 01-14 1 01-15 2 </code></pre> <p>So basically I need to count frequency ID by data. I treid with t...
<p>One way is:</p> <pre><code>df.time.value_counts() </code></pre> <p>Output:</p> <pre><code>01-15 2 01-13 2 01-14 1 Name: time, dtype: int64 </code></pre> <p>Other way, as suggested by reviewer above:</p> <pre><code>df.groupby(['time']).size().reset_index(name='Frequency') </code></pre> <p>Output:</p> <pre><c...
pandas|dataframe|group-by|count|frequency
2
4,410
66,621,907
Filter date index based on regex in pandas
<p>I have date column with price index like below,</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Date</th> <th style="text-align: center;">Price</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">2010-01-01</td> <td style="text-align: center;">23</td>...
<p>Convert Date column to <code>datetime</code> data type</p> <pre><code>df['Date'] = pd.to_datetime(df['Date']) </code></pre> <p>Filter by month and day</p> <pre><code>df.loc[(df.Date.dt.month == 12) &amp; (df.Date.dt.day == 31)] </code></pre> <p>Output</p> <pre><code> Date Price 1 2010-12-31 25 3 2013-12-...
python|pandas|nsepy
2
4,411
16,410,827
How to iterate Numpy array and perform calculation only if element matches a criteria?
<p>I want to iterate a numpy array and process only elements match with specific criteria. In the code below, I want to perform calculation only if element is greater than 1.</p> <pre><code>a = np.array([[1,3,5], [2,4,3], [1,2,0]]) for i in range(0, a.shape[0]): for j in range(0, a.sha...
<p>Method #1: use a boolean array to index:</p> <pre><code>&gt;&gt;&gt; a = np.array([[1,3,5], [2,4,3], [1,2,0]]) &gt;&gt;&gt; a[a &gt; 1] = (a[a &gt; 1] - 3) * 5 &gt;&gt;&gt; a array([[ 1, 0, 10], [-5, 5, 0], [ 1, -5, 0]]) </code></pre> <p>This computes <code>a &gt; 1</code> twice, although you co...
python|numpy
3
4,412
57,537,474
How to fix 'AttributeError: 'list' object has no attribute 'shape'' error in python with Tensorflow / Keras when loading Model
<p>Im trying to save my Model in Keras and then load it but when it try to use the loaded Model it trows an Error</p> <p>Python Vesion: 3.6.8 Tensorflow Version: 2.0.0-beta1 Keras Version: 2.2.4-tf</p> <p>Here is my Code:</p> <pre><code>from __future__ import absolute_import, division, print_function, unicode_litera...
<p>Try using</p> <pre><code>nmodel.predict(x_test) </code></pre> <p>instead of</p> <pre><code>nmodel.predict([x_test]) </code></pre> <p>(remove the brackets).</p>
python|python-3.x|numpy|tensorflow|keras
2
4,413
57,598,032
Sort Monthly Abbreviation columns (Jan, Feb, Mar, etc.) in Dataframe (currently sorting alphabetically)
<p>I have a dataframe I've created from stock data. I am counting how many times the 'close > open' by month and by year using a pivot table. If I use the integer for each month my table is in the correct order. If I use the 3-letter abbreviation for each month it sorts alphabetically. How can I get the month abbre...
<p>As WeNYoBen commented, one way to achieve customized ordering of strings is through ordered categorical.</p> <p>Another thing to note is that you can do numeric operation (such as sum) over boolean (True=1, False=0), therefore <code>np.where(data['Close'] &gt; data['Open'], 1, 0)</code> is really not necessary, <co...
python|pandas|sorting
1
4,414
57,683,299
Increment the max rows of the pandas DataFrame
<p>I have this python function to get financial data from some tickers</p> <pre><code>def get_quandl_data_df(ticker, start, end, api_key): import quandl return quandl.get_table('WIKI/PRICES', qopts={'columns': ['ticker','date', 'open', 'high', 'low', 'close', 'volume']}, ticker = ticker, date = { 'gte': s...
<p>1)Appending the argument paginate=True will extend the limit to 1,000,000 rows.</p> <pre><code>get_quandl_data_df(ticker, start, end, api_key,paginate=True): </code></pre>
python|python-3.x|pandas|quandl
1
4,415
57,409,679
pandas groupby aggregate keep equal values
<p>I am trying to build an aggregator which simply returns a value if it is equal to all other values in the variable and NaN if it isn't.</p> <p>It is ment to keep meta information while aggregating sensory data. </p> <p>I get a strange key error... </p> <pre><code>import pandas as pd import numpy as np df = pd.Da...
<p>You need to check for the location with <code>iloc</code></p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame.from_dict({'v1' : [1,1,1,2,2,2], 'v2' : [1,2,3,4,5,6], 'v3' : [1,1,1,2,3,2], 'v4' : [2,2,2,3,3,3]}...
python|pandas
1
4,416
57,296,791
How to display matplotlib numpy.ndarray in tkinter
<p>I want to display numpy.ndarray matplotlib in tkinter. </p> <p>I tried in backend it works fine, but does not display in tkinter and show the canvas with graph empty.instead the code below display the picture in separate window as pop-up. How can I display it in the canvas and inside the window?</p> <pre><code> fr...
<p><code>am</code> is <code>numpy.ndarray</code></p> <pre><code>am = np.zeros_like(daily_returns) </code></pre> <p>and it doesn't have <code>am.plot()</code>. </p> <p>But <code>pandas.DataFrame</code> has it. You have to convert <code>am</code> to <code>DataFrame</code></p> <pre><code> df = pd.DataFrame(am) ...
python-3.x|matplotlib|tkinter|numpy-ndarray
1
4,417
57,482,954
Grouping and splitting to avoid leakage
<p>I have a pandas <code>dataframe</code> where the data is arranged as follows:</p> <pre><code> filename label 0 4456723 0 1 4456723_01 0 2 4456723_02 0 3 ab43912 1 4 ab43912_01 1 5 ab43912_03 1 ... ... ... </code></pre> <p>I want to ...
<p>You can manually select ~80% of the unique file handles randomly.</p> <pre><code>df = pd.DataFrame({'filename': list('aaabbbcccdddeeefff')}) df['filename'] = df['filename'] + ['', '_01', '_02']*6 </code></pre> <hr> <pre><code># Get the unique handles files = df.filename.str.split('_').str[0] # Randomly select ~8...
python|python-3.x|pandas
3
4,418
73,154,668
unexpected keyword argument trying to instantiate a class inheriting from torch.nn.Module
<p>I have seen similar questions, but most seem a little more involved. My problem seems to me to be very straightforward, yet I cannot figure it out. I am simply trying to define a class and then instantiate it, but the arguments passed to the constructor are not recognized.</p> <pre><code>import torch import torch.n...
<p>You have a typo: it should be <code>__init__</code> instead of <code>__int__</code>.</p>
python|pytorch
0
4,419
70,675,292
Python Same Period Last Year in Pandas with GroupBy
<p>I have following DataFrame:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np n = 72 dates = list(pd.date_range(start='2016-01-01',periods=n,freq='MS')) products = ['a','b','c'] countries = ['a','b','c'] df = pd.merge(pd.DataFrame({'product':products}), pd.DataFrame({'coun...
<p>Not sure if this is your expected result. You can try this :</p> <pre><code>df['last_year'] = df['y'].shift(12) </code></pre>
python|pandas|group-by|offset|forecasting
0
4,420
70,650,161
how to create column with other dataframe as legend in python (groupby() alike)- pandas library
<p>i want to use df2 as legend to my primary df ('main_df')</p> <p>what &quot;<strong>code</strong>&quot; need to be ?</p> <pre><code>main_df = pd.DataFrame({'genre_NAME': ['comedy', 'action', 'horror'], 'genre_id': [nan, nan, nan]}) df2 = pd.DataFrame({'genre': ['comedy', 'horror'], 'id': [0, 1]}) #main_df is not r...
<p>You can access and change a specific value in a dataframe with <code>df.loc[]</code>. So in your case:</p> <pre><code>for _, line in df2.iterrows(): main_df.loc[main_df.genre_NAME == line.genre, &quot;genre_id&quot;] = line.id </code></pre>
python|pandas|dataframe|pandas-groupby
0
4,421
70,622,747
How to identify a number that has a correspondent negative in a list?
<p>I am beginner in this journey of Python/VBA so I have a problem I kindly want do ask you.</p> <p>So I have a list of rows in an excel spreadsheet (also I treat this data with Pandas to reduce the number of rows I have to analyse on Excel)</p> <p>The fact is that I have dozens of thousands rows that in a specific col...
<p>Assuming you have float in this column, you can compare the rows with the opposite of the next one, and use this information to subset only those rows.</p> <pre><code># is the next row the opposite value? m = df['col'].eq(-df['col'].shift()) # drop the matching rows and the next ones df2 = df.loc[~(m|m.shift(-1))] ...
python|excel|pandas|numpy
2
4,422
42,647,710
Compare Boolean Row values across multiple Columns in Pandas using & / np.where() / np.any()
<p>I have a dataframe that looks like:</p> <pre><code> a A a B a C a D a E a F p A p B p C p D p E p F 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 2 0 1 0 0 0 0 0 0 1 0 0 0 3 0 0 1 ...
<p>You can use <code>~</code> for invert boolean mask with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>iloc</code></a> for select by position:</p> <pre><code>print (~df.iloc[:,6:11].any(1) &amp; df.iloc[:,0:6].any(1)) 0 False 1 True ...
python|pandas|numpy|boolean|any
3
4,423
42,878,600
Access a list within Pandas Dataframe apply function without making list global
<p>I have a Pandas dataframe. For each row in this frame I want to make a certain check. If the check yields <code>True</code>, then I want to add certain columns of the dataframe-row to a list-structure.</p> <p>How can I access a list from within the apply function without the need to create a global list variable? I...
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>df.apply()</code></a> allows you to pass positional arguments and keywords.</p> <pre><code>def checkFunction(row, lst): if (check == True): lst.append(row) return row my_list...
python|pandas|dataframe|apply
1
4,424
42,606,387
why i can't open my files?
<pre><code>import pandas as pd df=pd.read_csv(r"C:\Users\champion\Desktop\政大資料科學競賽\104.1~106.1\臺北捷運各站出站量統計_201501.csv",encoding='big5') </code></pre> <p>I can execute it before.I don't know why python happen OSError.</p> <p>Is it could be my data which is Chinese?</p> <p>I browsed a lot of question,but no one can't ...
<p>If u use python 3.6, u can try </p> <blockquote> <p>df=pd.read_csv(r"C:\Users\champion\Desktop\政大資料科學競賽\104.1~106.1\臺北捷運各站出站量統計_201501.csv",encoding='big5',engine="python")</p> </blockquote>
python|pandas
-1
4,425
30,423,052
Matplotlib: Import and plot multiple time series with legends direct from .csv
<p>I have several spreadsheets containing data saved as comma delimited (.csv) files in the following format: The first row contains column labels as strings ('Time', 'Parameter_1'...). The first column of data is Time and each subsequent column contains the corresponding parameter data, as a float or integer. </p> <p...
<p>Here's my minimal working example for the above using genfromtxt rather than loadtxt, in case it is helpful for anyone else. I'm sure there are more concise and elegant ways of doing this (I'm always happy to get constructive criticism on how to improve my coding), but it makes sense and works OK:</p> <pre><code>im...
excel|csv|numpy|matplotlib|import
2
4,426
26,467,696
pandas DataFrame conditional string split
<p>I have a column of influenza virus names within my DataFrame. Here is a representative sampling of the name formats present:</p> <ol> <li>(A/Egypt/84/2001(H1N2))</li> <li>A/Brazil/1759/2004(H3N2)</li> <li>A/Argentina/126/2004</li> </ol> <p>I am only interested in getting out A/COUNTRY/NUMBER/YEAR from the strain n...
<p>So, based on EdChum's recommendation, I'll post my answer here.</p> <p>Minimal data frame required for tackling this problem:</p> <pre><code>Index Strain Name Year 0 (A/Egypt/84/2001(H1N2)) 2001 1 A/Brazil/1759/2004(H3N2) 2004 2 A/Argentina/126/2004 2004 </code></pre> ...
python|pandas
1
4,427
26,590,359
Compare Dictionaries for close enough match
<p>I am looking for a good way to compare two dictionaries which contain the information of a matrix. So the structure of my dictionaries are the following, both dictionaries have identical keys:</p> <pre><code>dict_1 = {("a","a"):0.01, ("a","b"): 0.02, ("a","c"): 0.00015, ... dict_2 = {("a","a"):0.01, ("a","b"): 0.01...
<p>Easiest way I could think of:</p> <pre><code>keylist = dict_1.keys() array_1 = numpy.array([dict_1[key] for key in keylist]) array_2 = numpy.array([dict_2[key] for key in keylist]) if numpy.allclose(array_1, array_2): print('Equal') else: print('Not equal') </code></pre>
python|python-2.7|numpy|dictionary
6
4,428
39,112,689
Can I create a new column based on when the value changes in another column?
<p>Let s say I have this <code>df</code></p> <pre><code>print(df) DATE_TIME A B 0 10/08/2016 12:04:56 1 5 1 10/08/2016 12:04:58 1 6 2 10/08/2016 12:04:59 2 3 3 10/08/2016 12:05:00 2 2 4 10/08/2016 12:05:01 3 4 5 10/08/2016 12:05:02 3 6 6 10/08/2016 12:05:03 1 3 7 10/08/201...
<p>You can use the <em>shift-cumsum</em> pattern.</p> <pre><code>df['C'] = (df.A != df.A.shift()).cumsum() &gt;&gt;&gt; df DATE_TIME A B C 0 10/08/2016 12:04:56 1 5 1 1 10/08/2016 12:04:58 1 6 1 2 10/08/2016 12:04:59 2 3 2 3 10/08/2016 12:05:00 2 2 2 4 10/08/2016 12:05:01 3 4 ...
python|pandas|uniqueidentifier
5
4,429
19,590,966
Memory error with large data sets for pandas.concat and numpy.append
<p>I am facing a problem where I have to generate large DataFrames in a loop (50 iterations computing every time two 2000 x 800 pandas DataFrames). I would like to keep the results in memory in a bigger DataFrame, or in a dictionary like structure. When using pandas.concat, I get a memory error at some point in the loo...
<p>This is essentially what you are doing. Note that it doesn't make much difference from a memory perspective if you do conversition to DataFrames before or after.</p> <p>But you can specify dtype='float32' to effectively 1/2 your memory.</p> <pre><code>In [45]: np.concatenate([ np.random.uniform(size=2000 * 1000).a...
python|python-2.7|numpy|pandas
6
4,430
33,651,668
How to add leading zero formatting to string in Pandas?
<p><strong>Objective:</strong> To format <code>['Birth Month']</code> with leading zeros</p> <p>Currently, I have this code:</p> <pre><code>import pandas as pd import numpy as np df1=pd.DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])]) df1['Birth Year']= np.random.randint(1905,1995, len(df1)) df1['Birth Mon...
<p>Cast the dtype of the series to <code>str</code> using <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.Series.astype.html#pandas.Series.astype" rel="noreferrer"><code>astype</code></a> and use vectorised <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.Serie...
python|string|numpy|pandas|dataframe
9
4,431
33,534,657
How to find index value from meshgrid in numpy
<p>I have the following problem: I have two surface equations, and I am looking at what point they are zero. So I have the following:</p> <pre><code>b = np.arange(0,2,0.1) k = np.arange(0,50,1) b,k = np.meshgrid(b,k) </code></pre> <p>with these I produce <code>z1</code> and <code>z2</code>, massive formulas, but they...
<p>In this case, your "is close to zero" expression <code>(-0.1&lt;z1)&amp;(z1&lt;0.1)</code> is an array of booleans. To find the indices of the <code>True</code> items you simply need to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html" rel="nofollow"><code>nonzero()</code></a>.</p...
python|numpy|intersection
1
4,432
22,734,763
Using Pandas To Find the Number Of Periods Since the Rolling High
<p>I am using the rolling_max function in Pandas:</p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/computation.html#moving-rolling-statistics-moments" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/computation.html#moving-rolling-statistics-moments</a></p> <p>How would I find the number of peri...
<p>starting with:</p> <pre><code>&gt;&gt;&gt; ts A 10 B 10 C -5 D -15 E -9 F -8 G -13 H -9 I -15 J -21 dtype: int64 </code></pre> <p>you may do:</p> <pre><code>&gt;&gt;&gt; rmlag = lambda xs: np.argmax(xs[::-1]) &gt;&gt;&gt; pd.rolling_apply(ts, func=rmlag, window=3, min_periods=0).astype(i...
python|pandas
3
4,433
13,572,576
using 'OR' to select data in pandas
<p>I have a dataframe of values and I would like to explore the rows that are outliers. I wrote a function below that can be called with the <code>groupby().apply()</code> function and it works great for high or low values but when I want to combine them together i generate an error. I am somehow messing up the boolean...
<p>You need to use <code>|</code> instead of <code>or</code>. The <code>and</code> and <code>or</code> operators are special in Python and don't interact well with things like numpy and pandas that try to apply to them elementwise across a collection. So for these contexts, they've redefined the "bitwise" operators <...
python|pandas
8
4,434
62,301,720
How to multiply the numbers 0 to 150 by the same value?
<p>I have a Problem with my Python exercise.</p> <p>Here is the part of my code:</p> <pre><code>import numpy as np import scipy as sc import matplotlib.pyplot as plt import math as m import loaddataa as ld dataListStride = ld.loadData("../Data/Fabienne") indexStrideData = 0 strideData = dataListStride[indexStrideDa...
<p>If your list is a numpy array then you can literally just multiply it by 0.01 to get the result, but if you want to keep it as a python list for some reason, then a simple list comprehension solves this quite easily.</p> <pre><code>new_ret = [0.01 * value for value in resultsHorizontal] </code></pre> <p>`</p>
python|list|numpy|matplotlib
0
4,435
62,395,085
Why does one need Google's WaveNet model to generate audio if it already takes audio as input?
<p>I've spent a lot of time trying to understand the <a href="https://arxiv.org/pdf/1609.03499.pdf" rel="nofollow noreferrer">Google's WaveNet work</a> (also used in their DeepVoice model), but still confused about some very basic aspects. I'm referring to <a href="https://github.com/Rayhane-mamah/Tacotron-2/blob/maste...
<p>The generative networks typically operate on conditional probability of getting <code>new_element</code> given <code>old_element(s)</code>. In math terms:</p> <p><a href="https://i.stack.imgur.com/shSF1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/shSF1.png" alt="conditional probability"></a><...
tensorflow|deep-learning|conv-neural-network|speech-recognition|text-to-speech
1
4,436
51,526,800
Setting up my decision tree python
<pre><code>import pandas as pd import numpy as np from sklearn import tree from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split from matplotlib import pyplot as plt import seaborn as sns from sklearn.tree import export_graphviz import graphviz import pydotplus import ...
<p>I think this is a simple typo/mishearing. Scipy.misc does not have a function called <code>inread</code>. The function is called <code>imread</code>. Replace <code>scipy.misc.inread(path)</code> with <code>scipy.misc.imread(path)</code></p>
python|pandas|scipy|decision-tree|pydot
0
4,437
51,341,568
What is the difference between s[i] and s.iloc[i] in pandas series?
<p>The similar question has been asked <a href="https://stackoverflow.com/questions/45983801/pandas-iloc-vs-direct-slicing">here</a>, but I don't think it has a very perfect answer. If I am slicing a series rather than a data frame, what is the difference between these two? </p> <p><code>s[i]</code> vs <code>s.iloc[i]...
<p>Indexing (using <code>[..]</code>) into a series (and a dataframe) acts as sort of a Swiss Army knife; it has to support a variety of use-cases, and these use-cases are not always compatible or efficient. Using <code>Series[...]</code> requires Pandas to check the datatype of both the object you passed and the curre...
python|pandas|slice
2
4,438
48,198,319
Groupby Pandas generate multiple fields with condition
<p>I have a pandas dataframe as such:</p> <pre><code>df = pandas.DataFrame( { "Label" : ["A", "A", "B", "B", "C" , "C"] , "Value" : [1, 9, 1, 1, 9, 9], "Weight" : [2, 4, 6, 8, 10, 12} ) </code></pre> <p>I would like to group the data by 'Label' and generate 2 fields.</p> <ul> <li>The First field, 'neww...
<p>Use <code>groupby.apply</code>, you can do:</p> <pre><code>df.groupby('Label').apply( lambda g: pd.Series({ "newweight": g.Weight[g.Value == 1].sum(), "weightvalue": g.Weight.mul(g.Value).sum() })).fillna(0) # newweight weightvalue #Label #A 2.0 38.0 #B 14.0 14...
python|pandas|pandas-groupby
4
4,439
48,715,480
Pick the row and column of an DateFrame cell where the value true
<p>In a DataFrame I have to find a specific value. If it exists I need the cell coordinates (row/column). Currently I get only the row and struggle with the column. </p> <pre><code>values = [[100.0, 127.0], [17.0, 24.13], [151.13, 0.0]] df = pd.DataFrame(np.concatenate(values).reshape(3,2)) # df: # 0 1...
<p>By using <code>np.where</code></p> <pre><code>s,v=np.where(df==17) df.columns[v] Out[244]: Int64Index([0], dtype='int64') df.index[s] Out[245]: Int64Index([1], dtype='int64') </code></pre>
python-3.x|pandas|dataframe
2
4,440
48,636,600
what is best way to use trained tensorflow in java
<p>I am coding UI by <code>javaFx</code> in <code>eclipse</code> because I can only use java, no python, no c. </p> <p>Now I try to use trained <code>tensorflow</code> file in this UI. (this <code>tensorflow</code> file is under python)</p> <p>I am looking for several ways (<code>API</code>, <code>jython</code>, <co...
<p>I think there are two ways for that,</p> <ol> <li><code>tensorflow-serving</code> which uses <code>grpc</code> to connect from java to the serving server, making it independent of any language. Look <a href="https://www.tensorflow.org/serving/" rel="nofollow noreferrer">here</a> for details.</li> <li>Use <code>tens...
java|python|tensorflow|jython
0
4,441
48,487,245
What to expect from deep learning object detection on black and white pictures?
<p>With TensorFlow, I want to train an object detection model with my own images based on ssd_inception_v2_coco model. The problem I have is that all my pictures are black and white. What performance can I expect? Should I try to colorize my B&amp;W pictures first? Or at the opposite, should I try to retrain base netwo...
<p>I wouldn't go through the trouble of colorizing if you are planning on using a pretrained model. I would expect that explicitly colorizing your images as a pre-processing step would help very little (if at all) since in theory the features that a colorizing network learns can also be learned by the detection network...
tensorflow|deep-learning|object-detection
2
4,442
48,726,418
k nearest neighbors with cross validation for accuracy score and confusion matrix
<p>I have the following data where for each column, the rows with numbers are the input and the letter is the output.</p> <pre><code>A,A,A,B,B,B -0.979090189,0.338819904,-0.253746508,0.213454999,-0.580601104,-0.441683968 -0.48395313,0.436456904,-1.427424032,-0.107093825,0.320813402,0.060866105 -1.098818173,-0.99916169...
<p>I think your model does not get trained properly and because it only has to guess one value it doesn't get it right. May I suggest switching to KFold or StratifiedKFold. LOO has the disadvantage that for large samples it becomes extemely time consuming. Here is what happened when I implemented StratifiedKFold with 3...
python|pandas|machine-learning|scikit-learn|cross-validation
3
4,443
71,074,196
Pandas Multi Index Division
<p>I have a Multi Index dataframe that looks like</p> <pre><code> Mid Strike Expiration Symbol 167.5 2022-02-11 AAPL170 5.4 170 2022-02-11 AAPL170 3.1 2022-02-18 AAPL170 4.525 2022-02-25 AAPL170 5.25 2022-03-04 AAPL170 6.00 172.5 2022-02-11 AAPL172 1....
<p>One way using <code>pandas.DataFrame.groupby</code> with <code>pct_change</code>:</p> <pre><code>new_df = df.groupby(level=0).pct_change(-1) + 1 print(new_df) </code></pre> <p>Output:</p> <pre><code> Mid Strike Expiration Symbol 167.5 2022-02-11 AAPL170 NaN 170.0 202...
python|pandas|dataframe|multi-index
0
4,444
51,804,671
How to set the variables of LSTMCell as input instead of letting it create it in Tensorflow?
<p>When I create a tf.contrib.rnn.LSTMCell, it creates its <strong>kernel</strong> and <strong>bias</strong> trainable variables during initialisation.</p> <p>How the code looks now:</p> <pre><code>cell_fw = tf.contrib.rnn.LSTMCell(hidden_size_char, state_is_tuple=True) </code></pre> <p>What ...
<p>I subclassed the LSTMCell class, and changed its <em>init</em> and <em>build</em> methods so that they accept given variables. If variables are given in init within build, we wouldn't use <em>get_variable</em> anymore, and would use the given kernel and bias variables.</p> <p>There might be cleaner ways to do it th...
tensorflow|lstm
2
4,445
51,572,338
Getting:"ModuleNotFoundError: No module named 'tensorflow'", only when running from the command line
<p>I'm trying to run the Transformer (speech2text) model on windows (till I get my linux machine). when I'm running the entire command from the cmd:</p> <p>"python transformer_main.py --data_dir=$DATA_DIR --model_dir=$MODEL_DIR --params=$PARAMS"</p> <p>I'm getting an error :"ModuleNotFoundError: No module named 'tens...
<p>Most likely you are simply using a different interpreter from your command line than from your PyCharm project. This will happen, for example, if you have set up your PyCharm project using a fresh conda environment.</p> <p>To see which one you are using on the command-line, simply run <code>where python</code>. The...
python|tensorflow
0
4,446
51,757,759
Converting PNG image file into row of pixels for saving in dataframe
<p>I am working on an image dataset for classification. I want to store all the pixel values of the image in a single row in the pandas dataframe. I am able to convert the image into a matrix and then into an array but when I'm saving this array, it is getting saved in the columns. </p> <p>I used </p> <pre><code>img ...
<p>Use <code>pd.DataFrame</code> on a list images to put each image on a separate row. Since there is only one image here, adding <code>[]</code> is enough depending on the output you want.</p> <pre><code>df = pd.DataFrame([img]) </code></pre> <p>will give</p> <pre><code> 0 1 2 3 4 0 1.0 1.0 1.0 1.0 1.0...
python|pandas|numpy|image-processing
3
4,447
51,959,497
Replace missing values of a sequence in a column for each id of pandas dataframe
<p>I have a dataset:</p> <pre><code>dt = {'id': [120,120,120,120,120,121,121,345], 'day': [0, 1,2,3,4,0,2,0], 'value': [[0.3,-0.5,-0.7],[0.5,3.4,2.7],[0.45,3.4,0.7],[0.25,0.4,0.7],[0.15,0.34,0.17],[0.35,3.4,2.7],[0.5,3.44,2.57],[0.5,0.34,0.37]]} df = pd.DataFrame(data=dt) day id value 0 0 120 [0.3, -0.5, -...
<p>Using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.from_product.html" rel="nofollow noreferrer"><code>pd.MultiIndex.from_product</code></a>:</p> <pre><code>idx = pd.MultiIndex.from_product([df.id.unique(), np.arange(5)], names=['id', 'day']) out = (df.set_index(['id', 'day']) ...
python|pandas|dictionary|dataframe|padding
1
4,448
41,710,501
Is there a way to have a dictionary as an entry of a pandas Dataframe in python?
<p>Something like: </p> <pre><code>d={'a':1, 'b'=2} data=pandas.DataFrame() data['new column'] = d data['new column'][0] </code></pre> <p>where the last command will return the dictionary d?</p>
<p>You can wrap the dictionary in a list, so that the dictionary will be treated as an element instead of an iterable:</p> <pre><code>d={'a':1, 'b': 2} data=pd.DataFrame() data['new column'] = [d] data['new column'][0] # {'a': 1, 'b': 2} </code></pre>
python|pandas|dataframe
6
4,449
64,596,588
splitting pandas column containing list of dicts
<p>I have a pandas column, with each cell in the column containing a list of dicts with color attributes of each photo, such as:</p> <pre><code>[{'color': 'black', 'confidence': 1.0}, {'color': 'brown', 'confidence': 0.72}, {'color': 'gray', 'confidence': 0.62}, {'color': 'other', 'confidence': 0.52}, {'color': 'red', ...
<pre><code>a = [{'color': 'black', 'confidence': 1.0}, {'color': 'brown', 'confidence': 0.72}, {'color': 'gray', 'confidence': 0.62}, {'color': 'other', 'confidence': 0.52}, {'color': 'red', 'confidence': 0.01}, {'color': 'blond', 'confidence': 0.01}, {'color': 'white', 'confidence': 0.0}] c= [] co = [] for d in a: ...
python|pandas
1
4,450
64,433,604
rearrange columns of multidimensional arrays efficiently
<p>I'm fairly certain this problem has an almost trivial solution, but for the life of me I can't seem to figure it out right now, nor find anything online, so bear with me please.</p> <p>I have a 3D array of size (n x m x m), called v (think of it as n (m x m)-matrices.) And I wish to rearrange the columns in each mat...
<p>Use the iterator as a ranged-array for advanced-indexing for a vectorized way -</p> <pre><code>I = np.arange(v.shape[0])[:,None] V[I,:,np.arange(len(idxs[0]))] = v[I,:,idxs] </code></pre> <p>Another with simply indexing into <code>v</code> to directly get <code>V</code> -</p> <pre><code>V = v[np.arange(v.shape[0])[:...
python|numpy|optimization|linear-algebra
2
4,451
64,395,296
Pandas data frame not exporting to excel properly
<p>I am not being able to produce a csv file with all the data from the scraper.</p> <p>When I test one item, it works properly, the exported csv has all the columns and one row with the corresponding value.</p> <p>when I try to apply the csv to all the code, it just doesn't work.</p> <p>Can someone tell me what am I d...
<p>I guess it's because <code>alldata</code> is empty - you never filled it with scraped data.</p> <p>Try adding</p> <pre><code> try: soup = BeautifulSoup(requests.get(soup.iframe['src']).content, 'html.parser') number = soup.find(text=lambda t: t.strip().startswith('Item no.')).find_next('div').get_...
python|pandas|dataframe|web-scraping
0
4,452
64,324,685
Why my PCA is not invariant to rotation and axis swap?
<p>I have a voxel (np.array) with size 3x3x3, filled with some values, this setup is essential for me. I want to have rotation-invariant representation of it. For this case, I decided to try PCA representation which is believed to be <a href="https://stats.stackexchange.com/questions/239069/is-pca-invariant-to-orthogon...
<p>Firstly, your <code>pca</code> function is not correct, it should be</p> <pre><code>def pca(x): x -= np.mean(x,axis=0) cov = np.cov(x.T) e_values, e_vectors = np.linalg.eig(cov) order = np.argsort(e_values)[::-1] v = e_vectors[:,order] return x @ v </code></pre> <p>You shouldn't tr...
python|numpy|math|pca|voxel
4
4,453
64,577,657
Appending values to an array for every iteration
<p>I am trying to store the indices inside my test array inside two other arrays.</p> <pre><code>train_idx = np.zeros(3,dtype='object') test_dx = np.zeros(3,dtype='object') array = np.array([1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1]) test = np.array(np.array_split(array, k)) [array([1, 0, 0, 1, 0]) array([1, 1, 1, 0]) ar...
<p>Define test_index and train_index as empty list:</p> <pre><code>test_index = [] </code></pre> <p>Then use append method:</p> <pre><code>test_index.append(test[i]) </code></pre>
python|arrays|numpy
0
4,454
64,530,885
TFX Pipeline Error While Executing TFMA: AttributeError: 'NoneType' object has no attribute 'ToBatchTensors'
<p>Basically I only reused code from <a href="https://github.com/tensorflow/tfx/blob/master/tfx/examples/iris/iris_utils_native_keras.py" rel="nofollow noreferrer">iris utils</a> and <a href="https://github.com/tensorflow/tfx/blob/master/tfx/examples/iris/iris_pipeline_native_keras.py" rel="nofollow noreferrer">iris pi...
<p>So in the end I was mistaken about the evaluator component, or more appropriately if I address the TFMA instead. it indeed uses the serving input function defined in serving signatures. According to <a href="https://www.tensorflow.org/tfx/guide/evaluator" rel="nofollow noreferrer">this link</a>, the default signatur...
python-3.x|tensorflow|tensorflow-serving|tensorflow-model-analysis
1
4,455
47,643,264
Pandas rank method dense but skip a number
<p>I have a sample data set that i'm trying to rank based on the values in the column 'HP':</p> <pre><code>import pandas as pd d = { 'unit': ['UD', 'UD', 'UD' ,'UC','UC', 'UC','UA','UA','UA','UB','UB','UB'], 'N-D': [ 'C1', 'C2', 'C3','Q1', 'Q2', 'Q3','D1','D2','D3','E1','E2','E3'], 'HP': [24, 24, 24,7,7,7,7,7,7,5,...
<p>Use a combination of <code>groupby</code> and <code>sort_values</code></p> <pre><code>g = df.sort_values( ['HP', 'unit'], ascending=False ).groupby(['HP', 'unit'], sort=False) df.assign(rank=g.ngroup().add(1).groupby(df.HP).transform('first')) HP N-D unit rank 0 24 C1 UD 1 1 24 C2 UD 1 ...
python|pandas|rank
5
4,456
47,592,512
Adding column in pandas with several conditions based on other columns in dataframe
<p>Firstly, I apologise if this is already somewhere on StackOverflow, I searched for an hour after experimenting myself for an hour and couldn't find it. I'm sure there must be an elegant (and probably elementary) solution.</p> <p>I have the following data frame:</p> <pre><code> Admit Gender Dept Freq 0 A...
<p>You can divide column by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.div.html" rel="nofollow noreferrer"><code>div</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>transform</cod...
python|pandas|dataframe|conditional|match
1
4,457
49,045,210
How to checkwhether an index in a tensorarray has been initialized?
<p>Is it in anyway possible to check whether an index in a TensorArray has been initialized?</p> <p>As I understand TensorArrays can't be initialized with default values. However I need a way to increment the number on that index which I try to do by reading it, adding one and then writing it to the same index. If the...
<p>The only option as I see it is creating an initialization loop where every index is set to 0. This eliminates the problem but may not be an ideal way.</p>
tensorflow|python-3.5
0
4,458
48,926,511
TensorFlow Assign
<p>I am trying to write a custom version of an RNN and would like to just store the state and last output of the cells in variables but it is not working. My guess is that TensorFlow sees the storing of the values unnecessary and does not execute it. Here is a snippet that illustrates the problem.</p> <p>For this ex...
<p>Make it dependent on an operation that will be run, in this example I'll use the cost function, but use whatever makes sense:</p> <pre><code>with tf.control_dependencies(cost): tf.assign(last_output, cell_output) </code></pre> <p>Now the assign operation will be required in order for <code>cost</code> to be comp...
python|tensorflow|assign
0
4,459
49,330,080
NumPy 2D array: selecting indices in a circle
<p>For some rectangular we can select all indices in a 2D array very efficiently:</p> <pre><code>arr[y:y+height, x:x+width] </code></pre> <p>...where <code>(x, y)</code> is the upper-left corner of the rectangle and <code>height</code> and <code>width</code> the height (number of rows) and width (number of columns) o...
<p>You could define a mask that contains the circle. Below, I have demonstrated it for a circle, but you could write any arbitrary function in the <code>mask</code> assignment. The field <code>mask</code> has the dimensions of <code>arr</code> and has the value <code>True</code> if the condition on the righthand side i...
python|arrays|numpy|indexing
16
4,460
58,901,094
Select corresponding values to a instant t in columns
<p>I work in Python and i have a pandas Dataframe with an evolution of steps at differents months :</p> <pre><code>+----+-------+------+ | Id | Month | Step | +----+-------+------+ | a | 1 | a_1 | | a | 4 | a_2 | | a | 6 | a_3 | | b | 1 | a_1 | | b | 2 | a_4 | +----+-------+------+ </code...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html" rel="nofollow noreferrer"><code>DataFrame.pivot_table</code></a>:</p> <pre><code>new_df=df.pivot_table(index='Id',columns='Month',values='Step',aggfunc=''.join).add_prefix('Month_').rename_axis(columns=None) print(new_d...
python|pandas
1
4,461
58,743,756
How to read images from a list
<p>Hi I have a set of images stored as list items and I want to read the images one by one and perform some operations on it. I cannot figure out how to iterate through each image item in the list. I can read them explicitly from a folder using <code>cv2.imread</code> but I want to make use of the list element in which...
<p><code>list</code> is itself a iterator just iterate over it.</p> <pre><code>for file in align: # code here... </code></pre>
python|list|numpy|opencv|image-processing
0
4,462
58,936,694
Is it possible to apply a function to one column when reading a data file?
<p>Is there a way to apply directly a Series operation (buid in function or custom) when building a dataframe from a file (in a pythonic way)?</p> <p>I would like to change the following:</p> <pre><code># import data frame containing a custom timestamp column (ex: _2019_11_19_15_10_35_) df1 = pd.read_csv('mydatafile....
<p>Well you can assign another Timestamp column, erasing the previous one:</p> <pre class="lang-py prettyprint-override"><code>df1 = pd.read_csv('mydatafile.csv').assign( newcol='newval', Timestamp=lambda df: pd.to_datetime(df['Timestamp'], format='_%Y_%m_%d_%H_%M_%S_')) </code></pre>
python|pandas|dataframe|series
1
4,463
70,059,491
bumping to good business day when generating range
<p>I am using pandas pd.bdate_range() to generate a range of dates given a start and end, but it seems to not work as expected.</p> <p>What I am ultimately after is quarterly dates over a start and end date, but I want the dates to be valid business days.</p> <pre><code>start = '2015-06-01' end = '2019-06-01' dates = ...
<p>You can take your existing Series and increment to the next business day like so</p> <pre class="lang-py prettyprint-override"><code>from pandas.tseries.offsets import BDay start = '2015-06-01' end = '2019-06-01' dates = pd.bdate_range(start,end,freq='MS')[::3] new_dates = dates.map(lambda x : x + 0*BDay()) </code>...
python-3.x|pandas|date
1
4,464
70,347,700
Generate DF from attributes of tags in list
<p>I have a list of revisions from a Wikipedia article that I queried like this:</p> <pre><code>import urllib import re def getRevisions(wikititle): url = &quot;https://en.wikipedia.org/w/api.php?action=query&amp;format=xml&amp;prop=revisions&amp;rvlimit=500&amp;titles=&quot;+wikititle revisions = [] ...
<p>An &quot;easy&quot; way without using regex would be splitting the string and then parsing:</p> <pre><code>for rev_string in revisions: rev_dict = {} # Skipping the first and last as it's the tag. attributes = rev_string.split(' ')[1:-1] #Split on = and take each value as key and value and convert ...
python|python-3.x|pandas|wikipedia|mediawiki-api
2
4,465
70,088,916
Format Pandas date array with mixed formats
<p>I'm trying to unify dates in a column as they come in different formats; current date entries:</p> <p>[... '18-Aug-21' '16-Aug-21' '17-Aug-21' '22-Aug-21' '21-Aug-21' '20-Aug-21' '19-Aug-21' '23-Aug-21' '24-Aug-21' '25-Aug-21' '28-Aug-21' '26-Aug-21' '27-Aug-21' '31-Aug-21' '30-Aug-21' '29-Aug-21' '06 Sep 2021' '07 ...
<p>I recommend <a href="https://pypi.org/project/python-dateutil/" rel="nofollow noreferrer"><code>dateutil</code></a> for this:</p> <pre class="lang-py prettyprint-override"><code>import dateutil DF_all[&quot;SALES_DATE&quot;] = DF_all[&quot;SALES_DATE&quot;].apply(dateutil.parser.parse) </code></pre> <p>Output:</p> <...
python|pandas|dataframe|format
1
4,466
56,348,725
Pandas - Replace values based on index and not in index
<p>Here is the sample code.</p> <pre><code>import pandas as pd, numpy as np df = pd.DataFrame(np.random.randint(0,100,size=(10, 1)), columns=list('A')) </code></pre> <p>I have a list dl=[0,2,3,4,7]</p> <p>At the index positions specified by list, I would like to have column A as "Yes".</p> <p>The following code wo...
<h3><code>np.where</code></h3> <p>I'm making an assumption that there is a better way to do both <code>'Yes'</code> and <code>'No'</code> at the same time. If you truly just want to fill in the <code>'No'</code> after you've already got the <code>'Yes'</code> then refer to <a href="https://stackoverflow.com/a/5634890...
python|pandas|dataframe
6
4,467
56,288,089
Unexpected behaviour from applying np.isin() on a pandas dataframe
<p>While working <a href="https://stackoverflow.com/a/56286723/565489">on an answer to another question</a>, I stumbled upon an unexpected behaviour:</p> <p>Consider the following DataFrame:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({ 'A':list('AAcdef'), 'B':[4,5,4,5,5,4], 'E':...
<p>I think in DataFrame are mixed numeric with integer solumns, so if loop by rows get <code>Series</code> with mixing types, so numpy coerce the to <code>strings</code>.</p> <p>Possible solution is convert to array and then to <code>string</code> values in <code>cond</code>:</p> <pre><code>cond = [[4],[5]] print(df...
python|pandas|numpy
2
4,468
56,047,379
Problem with Tensorflow iterator returning tuples
<p>I want to iterate over a TF dataset in order to convert the obtained data to numpy tensors. Being new to tensorflow, this is what my code looks like</p> <pre><code> def convert_dataset_to_pytorch(self, dataset): sess = tf.Session(config=self.config) iterator = dataset.make_one_shot_iterator() exampleT...
<p>Not sure why you are creating a pytorch tensor in tensorflow when all you want is a numpy tensor. To answer your question (mentioned below)</p> <blockquote> <p>iterate over a TF dataset in order to convert the obtained data to numpy tensors.</p> </blockquote> <h3>Sample Code:</h3> <pre><code>import numpy as n...
python|numpy|tensorflow|tuples|tensorflow-datasets
2
4,469
56,280,602
Matplotlib / Seaborn legend changes style upon adding labels
<p>I'm plotting some of my data from a pandas df using seaborn. Almost everything plots nicely using the following code:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import seaborn as sns sns.set(style='whitegrid', palette='muted') legend = ["Hue 1", "Hue 2"] order = ["A", "B"] ax = sns.v...
<p>You could try to draw custom patches for your legend. I haven't tested this but I think that it should work.</p> <pre><code>from matplotlib.patches import Patch palette=sns.color_palette('muted') bluepatch = Patch( facecolor=palette[0],edgecolor='k',label='Hue 1' ) orangepatch = Patch( facecolor=palette[1]...
python|pandas|matplotlib|seaborn
1
4,470
55,766,304
Coloring cells in pandas according to their relative value
<p>I would like to color the cells of a (python) pandas dataframe according to wether their value is in the top 5%, top 10%, ..., last 10%, last 5% of the data in this column. </p> <p>According to this post <a href="https://stackoverflow.com/questions/28075699/coloring-cells-in-pandas">Coloring Cells in Pandas</a>, on...
<p>Try this:</p> <pre><code>df = pd.DataFrame(np.arange(100).reshape(20,-1)) def colorme(x): c = x.rank(pct=True) c = np.select([c&lt;=.05,c&lt;=.10,c&gt;=.95,c&gt;=.90],['red','orange','yellow','green']) return [f'background-color: {i}' for i in c] df.style.apply(colorme) </code></pre> <p><a href="http...
python|python-3.x|pandas
0
4,471
55,893,511
"Dependency was not found" for tfjs in Vue/Webpack project with yarn
<p>I'm trying to use TensorFlow.js for array operations in a JavaScript project. I'm importing it in my Vue component with <code>import * as tf from '@tensorflow/tfjs';</code></p> <p>It appears <code>yarn install tensorflow</code> requires Python 2.7, so I instead used <code>yarn add tensorflow/tfjs</code> to install ...
<p>Thanks to a friend, I have a solution:</p> <p><code>yarn remove @tensorflow/tfjs</code></p> <p>and</p> <p><code>yarn add @tensorflow/tfjs</code></p> <p>I guess it got in a weird state when the first attempt to install tensorflow failed. (It's depressing how often the answer is "turn it off and on again"...)</p>
javascript|tensorflow|vue.js|webpack
1
4,472
55,885,970
Matplotlib, legends are not appearing in the histogram
<p>to describe my problem i am providing you with small dataset as an example: so imagine following dataset:</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd import numpy as np df = pd.DataFrame({'name':['a', 'b', 'c', 'a', 'b', 'c'], 'val':[1,5,3,4,5,3]} ) </code></pre> <p>I am creating simple hist...
<p>You only plot once on one series, that's why <code>plt</code> only picks one label for legend. If you don't have a lot of names, try:</p> <pre><code>def plot_bar_x(): index = np.arange(len(df['name'])) plt.figure() for name in df.name.unique(): tmp_df = df[df.name == name] plt.bar(tmp_df...
python|pandas|matplotlib|histogram|legend
1
4,473
55,606,347
Append 2 pandas dataframes with subset of rows and columns
<p>I have 2 dataframes like this</p> <pre><code>df = pd.DataFrame({"date":["2019-01-01", "2019-01-02", "2019-01-03", "2019-01-04"], "A": [1., 2., 3., 4.], "B": ["a", "b", "c", "d"]}) df["date"] = pd.to_datetime(df["date"]) df_new = pd.DataFrame({"date":["2019-01-02", "2019-01-03"...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> and remove duplicates by <code>date</code> column by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.html" rel="nofollow nor...
python|pandas
3
4,474
64,780,469
tf.keras "All layer names should be unique." but layer names are already changed
<p>I am trying create an ensemble of lstm. Below is my implementation of one lstm:</p> <pre><code>def lstm_model(n_features, n_hidden_unit, learning_rate, p, recurrent_p): model = keras.Sequential() model.add(Masking(mask_value=-1, input_shape=(100, n_features))) model.add(Bidirectional(LSTM(n_hidden_unit, inp...
<p>Not sure if you ever fixed this, or if anyone else will find the same issue; I just spent hours on the same problem and finally found the solution.</p> <p>When listing layers for renaming, instead of <code>model.layers</code>, you have to use <code>model._layers</code>, otherwise the input name remains unchanged. Ch...
python|tensorflow|keras|keras-layer
2
4,475
64,871,055
Importing all the sql tables into python using pandas dataframe
<p>I have an requirement wherein I would like to import all the tables stored in the sql database into python. I have successfully created a python code for it as follows:</p> <code> <pre><code>import pandas as pd import mysql.connector from pandas import DataFrame db = mysql.connector.connect(host=&quot;localhost&quot...
<p>The SQL error come from ' around the table name, It's not the best but if you are working on a local application, you can workaround with the f strings:</p> <pre><code>with connection.cursor() as pointer: pointer.execute(&quot;use use stock&quot;) pointer.execute(&quot;SHOW TABLES&quot;) tables_tuples=[...
python|mysql|pandas
1
4,476
64,699,496
How to compute loss of chained models with Keras?
<p>For testing, I have split a model into two models and I want to compute the loss and apply the gradient to both models like it would be one.</p> <p>Here are my two simple models:</p> <pre><code>model1 = tf.keras.models.Sequential([ tf.keras.layers.Dense(10, activation=&quot;relu&quot;, input_shape=(10,)), ]) mo...
<p>@Begoodpy, I suggest you combine the 2 models into a single one and train it as you would usually do.</p> <pre><code>supermodel = keras.Sequential( [ model1(), model2(), ] </code></pre> <p>If you need more control over the models, try this:</p> <pre><code>all_vars = model1.trainable_variables + m...
python|tensorflow|keras
2
4,477
64,979,047
Can´t save in a "to_csv" with pandas
<p>I have been trying to sabe some usersnames and passwords at the end of my code with the &quot;to_csv&quot; but it doesn´t save anything at all. The console does not show any message or output file at all. Can´t find whtas the problem.</p> <pre><code>def registrar(): df = pd.read_csv(r&quot;C:\Users\Usuario\Docum...
<p>You are not getting any message because you missed a break and are entering an infinity loop in your last else condition. Thats why you should always avoid using while true loops.</p> <p>And also you need to reassign <code>df</code> in order to write it to the csv file.</p> <p>Change your else for this and should wo...
python|pandas|csv
0
4,478
64,629,823
Accuracy of binary classification on MNIST “1” and “5” get better?
<p>I tried the binary classification using MNIST only number “1” and “5”. But the accuracy isn’t well.. The following program is anything wrong? If you find something, please give me some advice.</p> <p>loss: -9.9190e+04</p> <p>accuracy: 0.5599</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf...
<p>Your y_train and y_test is filled with class labels 1 and 5, but sigmoid activation in your last layer is squashing output between 0 and 1.</p> <p>if you change 5 into 0 in your y you will get a really high accuracy:</p> <pre><code>y_train = np.where(y_train == 5, 0, y_train) y_test = np.where(y_test == 5, 0, y_test...
tensorflow|machine-learning|prediction|mnist
2
4,479
65,017,040
How to convert pandas DataFrame to dictionary for Newick format
<p>I have the following dataset:</p> <pre><code>import pandas as pd df = pd.DataFrame([['root', 'b', 'a', 'leaf1'], ['root', 'b', 'a', 'leaf2'], ['root', 'b', 'leaf3', ''], ['root', 'b', 'leaf4', ''], ['root', 'c', 'leaf5', ''], ...
<p>I assumed that every row in your dataframe stands for one complete branch of the tree from the root to the leaves. Based on this, I came up with the following solution. Comments to each step in the algorithm can be found in the code below, but feel free to ask if anything is unclear.</p> <pre><code>node_to_children ...
python|pandas
1
4,480
39,885,928
Variable shape tensor
<p>I need to get a tensor that is variable shape as I do not know the vector size before hand. So far I tried: </p> <pre><code>hashtag_len = tf.placeholder(tf.int32) train_hashtag = tf.placeholder(tf.int32, shape=[hashtag_len]) </code></pre> <p>but I get the error <code>TypeError: int() argument must be a string, a b...
<p>If you want a VECTOR for sure, you should do the following:</p> <pre><code>train_hashtag = tf.placeholder(tf.int32, shape=[None]) </code></pre> <p>This shape describes vector of arbitrary length.</p>
python|tensorflow
3
4,481
44,064,299
How can I concatenate Pandas DataFrames by column and index?
<p>I've got four Pandas DataFrames with numerical columns and indices:</p> <pre><code>A = pd.DataFrame(data={"435000": [9.792, 9.795], "435002": [9.825, 9.812]}, index=[119000, 119002]) B = pd.DataFrame(data={"435004": [9.805, 9.783], "435006": [9.785, 9.78]}, index=[119000, 119002]) C = pd.DataFrame(data={"435000": [...
<p>You need concat in pairs:</p> <pre><code>result = pd.concat([pd.concat([A, C], axis=0), pd.concat([B, D], axis=0)], axis=1) print (result) 435000 435002 435004 435006 119000 9.792 9.825 9.805 9.785 119002 9.795 9.812 9.783 9.780 119004 9.778 9.750 9.743 9.762 119006 9.743 9.74...
python|pandas
16
4,482
44,289,277
Tensorflow: Import failed with "Failed to load the native TensorFlow runtime."
<p>I'm trying to install the CPU version of tensorflow in a virtualenv on Mac OS 10.6.8 (all I've got for now) with Python 3.6, using the package url as described <a href="https://www.tensorflow.org/install/install_mac#python_34_35_or_36" rel="nofollow noreferrer">here</a>. It seems to work fine:</p> <pre><code>Ms-Mac...
<blockquote> <p>ImportError: dlopen(/Users/M/Developer/tensorflow/tfvenv/lib/python3.6/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so, 10): Library not loaded: /usr/lib/libc++.1.dylib</p> </blockquote> <p>libc++ was not included in MacOS 10.6 because Apple had not switched to Clang and libc++ yet. Th...
python|tensorflow|pip
1
4,483
69,594,876
DataFrame. Split Column to antoher Columns with average by date
<p>There is a dataframe:</p> <pre><code>d = {'date' : ['2020-02-01', '2020-02-01', '2020-02-01', '2020-02-01', '2020-02-02', '2020-02-02', '2020-02-02'], 'type' : ['Bird', 'Dog', 'Cat', 'Bird', 'Dog', 'Cat', 'Bird'], 'weight' : [1, 2, 3, 4, 5, 6, 7]} df = pd.DataFrame(d) </code></pre> <p>I would like to split the &quo...
<p>Use <code>pivot_table</code> and apply <code>mean</code> to aggregate values those has the same index/column:</p> <pre><code>out = df.pivot_table(index='date', columns='type', values='weight', aggfunc='mean') \ .rename_axis(columns=None).reset_index() print(out) # Output: date Bird Cat Dog 0 20...
pandas|dataframe
0
4,484
69,303,487
What is the pythonic way to convert day and month in string format to date in python
<p>I have day and month in string format <strong>23rd Sep</strong>, I would like to convert the above string to the current date <strong>23/09/2021</strong>. I achieved that using the below code, what is the more pythonic way to do this.?</p> <pre><code>from datetime import datetime # datetime object containing curren...
<p>I don't see the problem:</p> <pre><code>import pandas as pd s = '23rd Sep' pd.Timestamp(s + ' 2021') Out[1]: Timestamp('2021-09-23 00:00:00') </code></pre> <p>If you want it in DMY format:</p> <pre><code>_.strftime('%d/%m/%Y') Out[2]: '23/09/2021' </code></pre>
python|pandas|dataframe
2
4,485
41,221,084
Apply VLOOKUP in pandas and python
<p>I have a csv called 'data.csv' which has:</p> <pre><code>EmployeeIDNumber A B C D </code></pre> <p>I have another csv called 'basic.csv' which has the same data but is jumbled:</p> <pre><code>MemberIdentifier B A C </code></pre> <p>I want to use PANDAS to create a result sheet which has:</p> <pre><code>Employee...
<p>There are several ways to do this but the most powerful is the following,</p> <pre><code>import pandas as pd df1 = pd.csv_read('data.csv') df = merge(df1, df2, left_on='EmployeeIDNumber', right_on='MemberIdentifier', how='left') </code></pre> <p>Here we are choosing the specific columns we wish to join our DataF...
python|csv|pandas
1
4,486
54,061,753
Creating Estimation Windows based on a Criteria (DataFrame)
<p>I am looking at how I can select a couple of rows (specifically -15 until -5) based on a specific criteria.</p> <p>We have a list of Events (dates) and a large DataFrame with all BitCoin orders, ordered by Date. In this DataFrame we have a column that marks a row with 'True' if the value in Events is found in the D...
<p>Here is an example. FYI. It's normally easier to answer these when you post some code that generates some test dataset :)</p> <p>First, here is a dataset. Here we're basically trying to select based on the True values. But we only want 1 before and 1 after, so we shouldn't see any gone. </p> <pre><code>import pand...
python|pandas|dataframe
0
4,487
54,099,431
Locate rows by particular label, found only in last multi-index level
<p>After performing group-by, my new df has 3 level multindex. I need to access all rows with 'ZEBRA' labels; which is contained in the 3rd level index. I'm trying to use <code>df.loc</code> but unable to do so. I thought of iterating through the labels, but that will have to be a nested loop to make below; which makes...
<p>You can do:</p> <pre><code>grouped[grouped.index.get_level_values(2) == 'ZEBRA'].reset_index() A B C D 0 bar one ZEBRA 1 1 bar three ZEBRA 1 2 foo three ZEBRA 1 3 foo two ZEBRA 1 </code></pre> <p>Alternate way: <code>grouped.query("C == 'ZEBRA'").reset_index()</code></p>
python|python-3.x|pandas
1
4,488
66,036,271
Splitting a tensorflow dataset into training, test, and validation sets from keras.preprocessing API
<p>I'm new to tensorflow/keras and I have a file structure with 3000 folders containing 200 images each to be loaded in as data. I know that <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image_dataset_from_directory" rel="nofollow noreferrer">keras.preprocessing.image_dataset_from_directory...
<p>I could not find supporting documentation, but I believe <code>image_dataset_from_directory</code> is taking the end portion of the dataset as the validation split. <code>shuffle</code> is now set to <code>True</code> by default, so the dataset is shuffled before training, to avoid using only some classes for the va...
python|tensorflow|keras
3
4,489
66,193,817
Pandas dataframe groupby remove column
<p>I stumble upon with a problem with dataframe. I am using this snippet code to generate dataframe after that I group by dataframe based on <strong>‘chr’ Column</strong>.</p> <pre><code>import pandas as pd DF = pd.DataFrame({'chr':[&quot;chr3&quot;,&quot;chr3&quot;,&quot;chr7&quot;,&quot;chr6&quot;,&quot;chr1&quot;, ...
<p>You can do it while creating your original list like this if there are only two columns:</p> <pre><code>ans = [pd.DataFrame(y, columns=DF.columns.difference(['chr'])) for x, y in DF.groupby('chr', as_index=False)] </code></pre> <p>Alternatively, drop <code>chr</code> from each subDf explicitly:</p> <pre><code>an...
python|pandas|dataframe
1
4,490
52,656,884
ImportError: No module named pandas_datareader
<p>I am trying to use the pandas data reader library. I initially tried <code>import pandas.io.data</code> but this threw up an import error, stating I should be using </p> <blockquote> <p>from pandas_datareader import data, wb</p> </blockquote> <p>instead. Upon trying this I was greeted with </p> <blockquote> <...
<p>run this command <code>pip install pandas-datareader</code> and for more info documentation is <a href="https://pandas-datareader.readthedocs.io/en/latest/" rel="nofollow noreferrer">here</a> </p>
python|pandas|importerror
0
4,491
52,881,426
Python Pandas Create Column Based on a Function Requiring to Filter the DataFrame
<p>I have a larger script with multiple functions. In one of those functions I am creating a dataframe and then creating a column applying a separate function.</p> <p>The function to create dataframe at a high level:</p> <pre><code>def data(file): df = pd.DataFrame('A': [1,2,3,4], 'B':[5,5,6,6] df['C'] = df['B']....
<p>Using <code>map</code> after <code>groupby.apply</code> (PS: Not recommend using list in column , which will make adjustment harder)</p> <pre><code>df['C']=df.B.map(df.groupby('B').A.apply(list)) df Out[872]: A B C 0 1 5 [1, 2] 1 2 5 [1, 2] 2 3 6 [3, 4] 3 4 6 [3, 4] </code></pre>
python|pandas
4
4,492
52,776,723
After converting image to binary cannot display it in notebook with matplotlib
<p>I am trying to display the image After coverting the image to binary in python notebook:</p> <pre><code>resized_img = cv2.cvtColor(char_mask, cv2.COLOR_BGR2GRAY) resized_img = cv2.threshold(resized_img, 100, 200, cv2.THRESH_BINARY) #cv2.imwrite('licence_plate_mask3.png', char_mask) plt.imshow(resized_img) plt.show...
<p>The error lies in line <code>resized_img = cv2.threshold(resized_img, 100, 200, cv2.THRESH_BINARY)</code>.</p> <p><code>cv2.threshold()</code> returns two values. The first is the threshold value (float) and the second is the image. </p> <p>So all the while you have been trying to plot a <code>float</code> value, ...
python|numpy|opencv|matplotlib|imshow
1
4,493
52,684,961
Pandas - Rename only first dictionary match instead of last match
<p>I am trying to use pandas to rename a column in CSV files. I want to use a dictionary since sometimes columns with the same information can be named differently (e.g. mobile_phone and telephone instead of phone).</p> <p>I want to rename the first instance of phone. Here is an example to hopefully explain more.</p> ...
<p>Here's one solution:</p> <p><code>df</code>:</p> <pre><code>Columns: [name, mobile_phone, telephone] Index: [] </code></pre> <p>Finding the first instance of phone (left to right) in the column index:</p> <pre><code>a = [True if ('phone' in df.columns[i]) &amp; ('phone' not in df.columns[i-1]) else False for i i...
python|pandas|dictionary|indexing|python-3.6
0
4,494
52,533,156
Weight Initialization Tensorflow tf.estimator
<p>Is there a way to adjust the weight initialization in the pre-built tf.estimator? I would like to use the method after Xavier (<code>tf.contrib.layers.xavier_initializer</code>) or from He. Which method is used by default? I couldn't figure it out from the documentation. </p> <p>I use the DNNRegressor.</p>
<p><code>DNNRegressor</code> uses <a href="https://www.tensorflow.org/api_docs/python/tf/glorot_uniform_initializer" rel="nofollow noreferrer">glorot_uniform_initializer</a> (aka Xavier uniform), it is hardcoded in the <a href="https://github.com/tensorflow/tensorflow/blob/4dcfddc5d12018a5a0fdca652b9221ed95e9eb23/tenso...
tensorflow|initialization
2
4,495
58,538,135
Keras methods 'predict' and 'predict_generator' with different result
<p>I have trained a basic CNN model for image classification. While training the model I have used ImageDataGenerator from keras api. After the model is being trained i used testdatagenerator and flow_from_directory method for testing. Everything Went well. Then I saved the model for future use. Now i am using the same...
<p><code>Keras generator</code> uses <code>PIL</code> for image reading which read images from disk as <code>RGB</code>.</p> <p>You are using <code>opencv</code> for reading which reads images as <code>BGR</code>. You have to convert your image from <code>BGR</code> to <code>RGB</code>.</p> <pre><code>img = cv2.imrea...
python-3.x|tensorflow|machine-learning|keras|conv-neural-network
0
4,496
58,194,296
How to convert currency values in DataFrame column?
<p>I've got a dataframe which has columns - </p> <pre><code>Product Price in AUD Price in BTC Price in USD Date A 1450.22 0.120 NaN 2019-08-15 B NaN NaN 550 2019-09-12 C NaN 0.18 15...
<p>You can use the <a href="https://pypi.org/project/forex-python/" rel="nofollow noreferrer">forex-python</a> package for that:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import datetime from forex_python.converter import CurrencyRates from forex_python.bitcoin import BtcConverter data =...
python-3.x|pandas
1
4,497
58,383,737
R keras says array doesnt have the right dimensions for a conv_2d, but it drops a value from the array that was correct
<p>When making a conv neral network keras takes the imput_shape of c(28, 28, 1), but when I run it to be trained it then tells me the input it got was (6000, 28, 28). I understand keras inputs the data size it's self, but why it is dropping the one, then causing it to brake?</p> <p>Problem line (I think):</p> <pre><c...
<p>From the documentation of <code>layer_conv_2d</code> :</p> <p><code>input_shape</code> :- Dimensionality of the input (integer) not including the samples axis. This argument is required when using this layer as the first layer in a model.</p> <p>So the input shape <code>(28, 28, 1)</code> means 28 rows by 28 colum...
r|tensorflow|keras
0
4,498
58,195,826
How to delete row with timedelta value lower than 0?
<p>How can I delete rows which have values of timedelta &lt; 0:</p> <pre><code>Index Date/Time id Timedelta 8 2019-09-09 07:31:37.979 2555 0 days 00:40:00.033000 9 2019-09-09 07:32:38.006 2555 0 days 00:01:00.027000 10 2019-09-09 07:32:37.938 2555 -1 da...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <code>'inverse'</code> logic - filter all rows with <code>Timedelta</code> higher or equal <code>0</code>:</p> <pre><code>df1 = df[df['Timedelta'] &gt;...
python|pandas|timedelta
1
4,499
58,514,251
Making a series from another dataframe columns every nth value
<p>I have a data frame that I am trying to clean. For one of my columns I want to add every other index value (starting from 0) to a separate series. So essentially every other value down the column into its own series. I tried iterating but with no success. How can this be done? <a href="https://i.stack.imgur.com/LXDZ...
<pre><code>import pandas as pd test_df = pd.DataFrame({'val1': ['a', 'b', 'c', 'd', 'e'], 'val2': ['v', 'w', 'x', 'y', 'z']}) alternating_srs = test_df['val1'].iloc[::2] </code></pre>
python|pandas
0