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
363,300
37,909,274
How to resample dates with Pandas item by item?
<p>My objective is to add rows in pandas in order to replace missing data with previous data and resample dates at the same time. Example : This is what I have :</p> <pre><code>date wins losses 2015-12-19 11 5 2015-12-20 17 8 2015-12-20 10 6 2015-12-21 15 1 2015-12-25 11...
<p>Try this, it should works :) </p> <pre><code>print df.set_index('date').groupby('productId', group_keys=False).apply(lambda df: df.resample('D').ffill()).reset_index() </code></pre>
python-2.7|pandas|resampling
0
363,301
37,853,623
How to efficiently resample a DatetimeIndex
<p>Pandas has a <code>resample</code> method on a series/dataframe but there seems no way to resample a <code>DatetimeIndex</code> on its own?</p> <p>Concretely, I have a daily <code>Datetimeindex</code> with possibly missing dates and I want to resample it at an hourly freq but only including days which are in the or...
<pre> | Method | Time | Relative | |---------------------------------|---------|----------| | OP's updated approach | 1.31 ms | 17.6 % | | Generate daterange, np.in1d | 1.75 ms | 23.5 % | | Generate daterange, Series.isin | 1.90 ms | 25.5 % | | Resample with dummy Series ...
python|pandas
6
363,302
37,607,112
Boxplot needs to use multiple groupby in Pandas
<p>I am using pandas, Jupyter notebooks and python. I have a following dataset as a dataframe</p> <pre><code>Cars,Country,Type 1564,Australia,Stolen 200,Australia,Stolen 579,Australia,Stolen 156,Japan,Lost 900,Africa,Burnt 2000,USA,Stolen 1000,Indonesia,Stolen 900,Australia,Lost 798,Australia,Lost 128,Australia,Lost 2...
<p>You can select only the rows corresponding to <code>"Australia"</code> from the column <code>"Country"</code> and group it by the column <code>"Type"</code> as shown:</p> <pre><code>from StringIO import StringIO import pandas as pd text_string = StringIO( """ Cars,Country,Type,Score 1564,Australia,Stolen,1 200,Aus...
python|pandas|boxplot|jupyter
2
363,303
37,929,911
Why would NumPy reshape() create a new array and why might order not be preserved?
<p>There are a few questions on SO about checking whether the <code>numpy.reshape</code> call has returned a copy or not<a href="https://stackoverflow.com/questions/11524664/how-can-i-tell-if-numpy-creates-a-view-or-a-copy"> [1</a>, <a href="https://stackoverflow.com/questions/11286864/is-there-a-way-to-check-if-numpy-...
<blockquote> <p>What I'm wondering is in what circumstances will NumPy return a copy?</p> </blockquote> <pre><code>In [13]: x = numpy.array([[1, 2, 3], ....: [4, 5, 6]]) In [14]: x[:, :2].reshape([4]).base is x Out[14]: False </code></pre> <p>If the strides don't work for the new shape, NumPy h...
python|arrays|numpy|reshape
2
363,304
37,892,796
one way to merge two files with same "column name" and "different rows" using pandas in python
<p>I have two datafiles <code>a.csv</code> and <code>b.csv</code> which can be obtained from pastebin: <a href="http://pastebin.com/nzjXESYn" rel="nofollow">http://pastebin.com/nzjXESYn</a><br> <a href="http://pastebin.com/PDV5Ah64" rel="nofollow">http://pastebin.com/PDV5Ah64</a> </p> <p>First file <code>a.csv</code>...
<p>If you want to merge the two datasets, you should use<code>.merge()</code> method, rather than <code>.append()</code>. </p> <pre><code>result = pd.merge(df1,df2,on='wave') </code></pre> <p>The former joins two dataframes (similar to a SQL join), while the latter stacks the two dataframes on top of one another.</p>
python|csv|pandas|merge
1
363,305
37,603,764
2-D Matrix: Finding and deleting columns that are subsets of other columns
<p>I have a problem where I want to identify and remove columns in a logic matrix that are subsets of other columns. i.e. [1, 0, 1] is a subset of [1, 1, 1]; but neither of [1, 1, 0] and [0, 1, 1] are subsets of each other. I wrote out a quick piece of code that identifies the columns that are subsets, which does (n^2-...
<p>Since the <code>A</code> matrices I'm actually dealing with are 5000x5000 and sparse with about 4% density, I decided to try a sparse matrix approach combined with Python's "set" objects. Overall it's much faster than my original solution, but I feel like my process of going from matrix <code>A</code> to list of set...
python|numpy|matrix|scipy|vectorization
1
363,306
37,922,332
Referencing a dataframe object's index and column?
<p>I have the following dataframe. I want to create a new dataframe based on the column and index of elements, but I am unable to reference to their index name.</p> <pre><code> AAA BBB CCC DDD A NaN NaN NaN NaN B NaN NaN NaN NaN C NaN NaN NaN NaN D NaN NaN NaN NaN </code></pre> <p>Code:</p> <pre...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>fillna</code></a>:</p> <pre><code>df_tmp.ix['B', 'AAA...
python|numpy|pandas|dataframe
2
363,307
37,734,498
NoteSequence Protobuf Decode Error
<p>I'm trying to import a NoteSequence file into Magenta and am getting 'google.protobuf.message.DecodeError: Unexpected end-group tag.'</p> <p>in.seq</p> <pre><code>id: "/id/midi/tmp/3d8d5785f488ffd8875f10a12858c6f6c2152068" filename: "example.mid" collection_name: "tmp" ticks_per_beat: 220 time_signatures { numer...
<p>FromString expects a serialized protobuf, not one in ASCII format. You can parse from ASCII with a function such as this:</p> <pre><code>from google.protobuf import text_format def parse_test_proto(proto_type, proto_string): instance = proto_type() text_format.Merge(proto_string, instance) return instance </...
tensorflow|magenta
0
363,308
37,758,768
Text formatting on pandas pivot table
<p>I am creating a dataframe and then converting that dataframe into a pivot table. The text and the column headers in the pivot table are aligned to center in my result. I would like to set the text justify as "left". Could you please help with this ? I've tried <code>df.to_string(justify = 'true')</code> but it throw...
<p>I think you need set parameter <code>justify</code> to <code>left</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_string.html" rel="nofollow"><code>to_string</code></a>:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Customer': ['Ann Green', 'Joseph Smith', 'Ann...
python|pandas|pymongo
0
363,309
37,930,431
Select all occurrences of top K values along each column in a NumPy array
<p>Lets say I have a NumPy array as follows: My original array is 50K X8.5K size. This is sample</p> <pre><code>array([[ 1. , 2. , 3. ], [ 1. , 0.5, 2. ], [ 2. , 3. , 1. ]]) </code></pre> <p>Now what I want is that for each column, only keep top K values (lets take K as 2 here) and re-code others to zero....
<p>With focus on performance for such large arrays, here's a vectorized approach to solve it -</p> <pre><code>K = 2 # Select top K values along each column # Sort A, store the argsort for later usage sidx = np.argsort(A,axis=0) sA = A[sidx,np.arange(A.shape[1])] # Perform differentiation along rows and look for non-...
python|numpy
1
363,310
37,693,702
Concatenating two data frames on large no. of columns
<p>I have to Use concatenate function for large no. of columns. Let say this my function.</p> <pre><code>pd.concat([mdf1[['user','tag1','tag2','tag3','tag4']].groupby(['user']).agg(sum) </code></pre> <p>Here I have large no. of tags so I want my function to take all the columns say after 'tag1' how can I do that? mdf...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> and aggregating <a href="http://pandas....
python|pandas|dataframe|concatenation
0
363,311
38,044,731
Lexicographic comparison of two numpy ndarrays
<p>I couldn't find a straightforward way to compare two (multidimensional in my case) arrays the in a lexicographic way.</p> <p>Ie.</p> <pre><code>a = [1,2,3,4] b = [4,0,1,6] </code></pre> <p>For <code>a &lt; b</code> I want to get <code>true</code> where I get <code>[true, false, false, true]</code><br> For <code>...
<p>If the question is just about finding whether <code>a</code> is <code>&lt;</code> or <code>&gt;</code> than <code>b</code>, then the following should work.</p> <pre><code>def fn(a, b): # finds index of the first non matching element idx = np.where( (a&gt;b) != (a&lt;b) )[0][0] if a[idx] &lt; b[idx]: pr...
python|arrays|numpy
4
363,312
31,427,971
save pandas data frame as 32-bit float
<p>I have some data in pandas which I'm trying to save as 32-bit float but instead I'm always getting 64-bit float. My best attempt was this:</p> <pre><code>df['store'] = pd.DataFrame(data).astype(float32) </code></pre> <p>but it's not working.. any ideas?</p>
<p>Use <code>numpy.float32</code>:</p> <pre><code>In [320]: import numpy as np import pandas as pd df = pd.DataFrame({'a':np.random.randn(10)}) df.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 10 entries, 0 to 9 Data columns (total 1 columns): a 10 non-null float64 dtypes: float64(1) memory usage:...
python|pandas
6
363,313
31,246,238
vector magnitude for large components
<p>I noticed that numpy has a built in function linalg.norm(vector), which produces the magnitude. For small values I get the desired output</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.linalg.norm([0,2]) 2.0 </code></pre> <p>However for large values:</p> <pre><code>&gt;&gt;&gt; np.linalg.norm([0,1...
<p>Your number is written as an integer, and yet it is too big to fit into a <code>numpy.int32</code>. This problem seems to happen even in python3, where the native numbers are big. </p> <p>In numerical work I try to make everything floating point unless it is an index. So I tried:</p> <pre><code>In [3]: np.linal...
python|numpy|rounding
4
363,314
31,611,463
How to increase image size in matplotlib and pandas?
<p>I am trying to increase the size of the image resulting from this function:</p> <pre><code>plt.figure()); data_ordertotal.plot(); plt.legend(loc='best') </code></pre> <p>I tried this but the size remains the same</p> <pre><code>plt.figure(figsize=(40,40)); data_ordertotal.plot(); plt.legend(loc='best') </code></p...
<p>I guess you're using pandas, and you should use:</p> <pre><code>data_ordertotal.plot(figsize=(40,40)) </code></pre> <p>It doesn't work with <code>plt.figure(figsize=(40,40))</code> because pandas will create a new figure if you don't pass it an <code>axe</code> object.</p> <p>It would work with:</p> <pre><code>f...
python|pandas|matplotlib
17
363,315
31,524,102
Python Pandas Pivot Table Groupby Date Columns Using 7-Day Frequency
<p>Using Python 3.4 and Pandas, my pivot table looks like this:</p> <pre><code> Impressions Day 2015-07-06 2015-07-07 2015-07-08 2015-07-09 2015-07-10 2015-07-11 2015-07-12 2015-07-13 2015-07-14 2015-07-15 2015-07-16 2015-07-17 2015-07-18 2015-07-19 ...
<p>One way is to use <code>.dt</code> of <code>pd.Series</code> to get <code>weekofyear</code> and do pivot based on that column.</p> <pre><code>import pandas as pd import numpy as np # simulate your data # =================================== np.random.seed(0) day = np.random.choice(pd.date_range('2015-07-01', '2015-...
python|pandas|grouping
1
363,316
31,481,708
Numpy create an index of values in an array and replace values by others
<p>I have two sets of values <code>RGB</code> and <code>XYZ</code> in <code>np.arrays</code> that have the same length. The values in <code>RGB</code> and <code>XYZ</code> correspond to the same values in two different color spaces, <strong>the order of their appearance</strong> in the vectors is the same.</p> <p>I ha...
<p>It sounds like you are trying to use the RGB values as indexes. You can solve this with regular Python. Make a dict of</p> <pre><code>my_dict = {RGB_value_1: XYZ_Value_1, RGB_value_2: XYZ_Value_2, etc} </code></pre> <p>then for every value in RGB_picture</p> <pre><code>my_dict[RGB_picture_value] </code></pre> <p...
python|arrays|numpy|indexing
1
363,317
31,321,652
Odd behavior of numpy.all with object dtypes
<p>Given an array of <code>dtype=object</code>, <code>numpy.all/any</code> return the last object. For example:</p> <pre><code>&gt;&gt;&gt; from string import ascii_lowercase &gt;&gt;&gt; x = np.array(list(ascii_lowercase), dtype=object) &gt;&gt;&gt; x.all() 'z' </code></pre> <p>In researching this issue, I couldn't...
<p>In <code>numpy</code> version <code>1.8.2</code>, <code>np.any</code> and <code>np.all</code> behave as classic short circuit logical and/or functions. LISP behavor comes to mind. Python's <code>and</code> and <code>or</code> operators do this.</p> <p>Some examples:</p> <pre><code>In [203]: np.all(np.array([[1,2...
python|numpy
3
363,318
64,562,158
How to round calculations with pandas
<p>I know how to simply round the column in pandas (<a href="https://stackoverflow.com/q/26133538/7651845">link</a>), however, my problem is how can I round and do calculation at the same time in pandas.</p> <pre><code>df['age_new'] = df['age'].apply(lambda x: round(x['age'] * 0.024319744084, 0.000000000001)) TypeErro...
<p>There's two problems:</p> <ul> <li><code>x['age']</code> inside the brackets doesn't need <code>['age']</code> as you already apply to the column <code>age</code> (that's why you get the error)</li> <li><code>round</code> takes an <code>int</code> as second argument.</li> </ul> <p>Try</p> <pre><code>df['age_new'] = ...
python|pandas|data-manipulation
2
363,319
64,448,607
Tensorflow 2.0: How can I fully customize a Tensorflow training loop like I can with PyTorch?
<p>I used to use <code>Tensorflow</code> a lot before, but moved over to <code>Pytorch</code> because it was just a lot easier to debug. The nice thing I found with <code>PyTorch</code> is that I have to write my own training loop, so I can step through the code and find errors. I can fire up <code>pdb</code> and check...
<p>This is almost as custom and bare bones I can make it. I also used subclassed layers.</p> <pre><code>import tensorflow as tf import tensorflow_datasets as tfds ds = tfds.load('iris', split='train', as_supervised=True) train = ds.take(125).shuffle(125).batch(1) test = ds.skip(125).take(25).shuffle(25).batch(1) cla...
python|tensorflow|machine-learning|keras|deep-learning
3
363,320
64,579,258
Sentence embedding using T5
<p>I would like to use state-of-the-art LM T5 to get sentence embedding vector. I found this repository <a href="https://github.com/UKPLab/sentence-transformers" rel="nofollow noreferrer">https://github.com/UKPLab/sentence-transformers</a> As I know, in BERT I should take the first token as [CLS] token, and it will be ...
<p>In order to obtain the sentence embedding from the T5, you need to take the take the <code>last_hidden_state</code> from the T5 encoder output:</p> <pre><code>model.encoder(input_ids=s, attention_mask=attn, return_dict=True) pooled_sentence = output.last_hidden_state # shape is [batch_size, seq_len, hidden_size] # p...
python|nlp|pytorch|word-embedding
5
363,321
64,382,404
How to find the difference between rows of cumulative counts while retaining columns
<p>I have the following data:</p> <pre><code>machine_id time_to_failure 430494 1000 430494 700 430494 500 430494 100 430495 1000 430495 200 </code></pre> <p>The time to failure data is counted from a reference day 0 and I would like to turn it into the time since the previous ...
<p>Let's try with <code>groupby().diff()</code>:</p> <pre><code>df['time_to_failure'] = (df.groupby('machine_id') ['time_to_failure'].diff(-1) .fillna(df['time_to_failure']) ) </code></pre> <p>Output:</p> <pre><code> machine_id time_to_fa...
python|pandas|dataframe|csv
2
363,322
64,518,979
Joining two dataframes on columns they match
<p>I have two dataframes. df1 has more elements (3) in column 'Table_name' than df2 (2). I want a resultant dataframe that only outputs the rows where df1 and df2 share the same column names.</p> <p>df1</p> <pre><code>Table_Name | Type id | int name | string position| string </code></pre> <p>df2</p> <p...
<p>You need <code>loc</code> here</p> <pre><code>similar_cols = df1.loc[df1['Table_name'].isin(df2['Table_name'])] </code></pre>
python|pandas|dataframe
1
363,323
64,188,484
Backtracking pathinding problem in Python
<p>Recently, I've found out about backtracking and without much thinking started on the book from the guy who has shown some Sudoku backtracking tricks (<a href="https://www.youtube.com/watch?v=G_UYXzGuqvM&amp;ab_channel=Computerphile" rel="nofollow noreferrer">https://www.youtube.com/watch?v=G_UYXzGuqvM&amp;ab_channel...
<p>A few suggestions:</p> <ol> <li>You might want to use a set for a grid, adding a square as soon as it is visited, if it is not a member of the set yet.</li> <li>The counter and the grid can be global but it would probably be easier for you to take them as arguments for the function at first. After the solution is cl...
python|algorithm|numpy|backtracking|sudoku
0
363,324
64,189,903
Importing your own tensorflow model to react native
<p>I have a model which I trained and is stored as h5 file, I used tensorflowJs converter to convert it to json file and weights. I'm using expo, and I want to load that model, I understand that bundleResourceIO doesn't work with exp and I'm suppose to load it from a webserver, but I cannot find any tutorial or guide,...
<p>You can use <a href="https://js.tensorflow.org/api_react_native/0.3.0/#bundleResourceIO" rel="nofollow noreferrer">bundleResourceIO</a>.</p> <p>If you have multiple bin files then reconvert it again and set <code>--weight_shard_size_bytes 60000000</code> this sets the maximum size of the <code>weight_shard_size_byte...
expo|tensorflow.js
3
363,325
64,528,599
Issues in creating hierarchical columns in pandas
<p>Just approached the hierarchical columns in pandas. The original dataframe (df) has 27 columns and looks like the following (Ticker is the index):</p> <pre><code> Report Date Shares Gross Profit ... Ticker AAPL 2010-07-...
<h2>Solution</h2> <p>This question can be solved by <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html" rel="nofollow noreferrer">df.melt()</a> if we aim at producing the transposed version of the desired output first. You can easily set the double-leveled <code>MultiIndex</code> befor...
pandas|dataframe|multi-index
0
363,326
64,494,871
Problem with restoring checkpoint in tensorflow (op type not registered error)
<p>I am trying to finetune a pretrained Inception V3 network. To restore the latest checkpoint, I am following the great answer from here: <a href="https://stackoverflow.com/a/41273348/13608754">https://stackoverflow.com/a/41273348/13608754</a></p> <h2>My code is:</h2> <pre><code>import tensorflow.compat.v1 as tf with ...
<p>Looking at the error, my guess is that the model is supposed to be loaded with the current version of TF (2.0+) yet you are explicitly importing the legacy v1 branch of TF, do you have a good reason to do this?</p> <p>The answer you are referencing applies to the old version of TF (v1). In the current version (TF 2....
python|tensorflow|deep-learning
0
363,327
64,608,544
resample data based on group and calculate rolling sum
<p>I would like to create an additional column in my data-frame without having to loop through the steps</p> <pre><code>This is created in the following steps. 1.Start from end of the data.For each date resample every nth row (in this case its 5th) from the end. 2.Take the rolling sum of x numbers from 1 (x=2) a...
<p>Let's assume we have a set of 15 integers:</p> <pre><code>df = pd.DataFrame([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15], columns=['original_data']) </code></pre> <p>We define which nth row should be added <code>n</code> and how many times <code>x</code> we add the <code>nth</code> row</p> <pre><code>n = 5 x = 2 ( df ...
python|pandas|dataframe
0
363,328
64,257,194
Pandas dataframe Split One column data into 2 using some condition
<p>I have one dataframe which is below-</p> <pre><code> 0 ____________________________________ 0 Country| India 60 Delhi 62 Mumbai 68 Chennai 75 Country| Italy 78 Rome 80 Venice 85 Milan 88 Country| Australia 100 Sydney 103 ...
<p>Look for rows where <code>|</code> is present and pull into another column, and fill down on the newly created column :</p> <pre><code>( df.rename(columns={&quot;0&quot;: &quot;city&quot;}) # this looks for rows that contain '|' and puts them into a # new column called Country. rows that do not match wi...
python|pandas|dataframe
3
363,329
64,474,983
Find missing days and grouping
<p>I have a dataframe that looks something like this</p> <pre><code> dt user 0 2016-01-01 a 1 2016-01-02 a 2 2016-01-03 a 3 2016-01-04 a 4 2016-01-05 a 5 2016-01-06 a 6 2016-01-01 b 7 2016-01-02 b 8 2016-01-03 b 9 2016-01-04 ...
<p>Use <code>isin</code> to check the date range against each group of <code>user</code> and <code>agg.sum</code> the returned boolean mask of each group</p> <pre><code>df['dt'] = pd.to_datetime(df['dt']) #if `dt` columns already in datetime dtype, ignore this check_dates = pd.date_range('2015-12-31', '2016-01-10', fre...
python|pandas|dataframe|date|datetime
2
363,330
64,257,402
join table horizontally by loop based on rows in a dataframe
<p>I have a dataframe <code>data_df</code> with <code>n</code> rows:</p> <pre><code>Rank DutyCode 200 ABC 300 DEF 400 GHI </code></pre> <p>Then, I want to iteratively join them as one row, example:</p> <pre><code>Rank DutyCode Rank_1 DutyCode_1 Rank_2 DutyCode_2 200 ...
<p>This is not the cleanest way, but it works:</p> <pre><code>import pandas as pd input = pd.DataFrame(data=[[200, 'ABC'], [300, 'DEF'],[400, 'GHI']],\ columns=['Rank' ,'DutyCode']) df = input.iloc[0] for row in range(1,len(df)+1): df['Rank_' +str(row)] = input.loc[row]['Rank'] df['DutyCode_' +str...
python|pandas|dataframe|join
1
363,331
64,477,028
how to iterate over files in python and export several output files
<p>I have a code and I want to put it in a for loop. I want to input some data stored as files into my code and based on the each input, generate outputs automatically. At the moment, my code is only working for one input file and consequently gives one output. My input file is named as <code>model000.msh</code>, but t...
<p>I'm not very sure about your question. But it seems like you are asking for something like:</p> <pre class="lang-py prettyprint-override"><code>for idx in range(10): with open('changed_{:0&gt;2d}'.format(idx), 'a') as fout: with open('model0{:0&gt;2d}.msh'.format(idx), 'r') as fin: #read some...
python|arrays|numpy|file
1
363,332
64,370,349
Pandas merge list of DFs based on grouping column value
<p>I have a list of Pandas DFs with every DF having the same <code>columns</code>:</p> <pre><code>df1_values = [[&quot;2001-01-01&quot;,&quot;Lime&quot;,10],[&quot;2001-01-02&quot;,&quot;Lime&quot;,20]] df2_values = [[&quot;2001-01-01&quot;,&quot;Mango&quot;,40],[&quot;2001-01-02&quot;,&quot;Mango&quot;,50],[&quot;2001...
<p>You can do <code>pandas.concat</code> followed by <code>.sort_values</code>:</p> <pre><code>print( pd.concat(dfs).sort_values('date') ) </code></pre> <p>Prints:</p> <pre><code> date fruit value 0 2001-01-01 Lime 10 0 2001-01-01 Mango 40 0 2001-01-01 Orange 30 1 2001-01-02 Lime ...
python|pandas|numpy|dataframe
3
363,333
64,568,125
Extract latest data from dataframe using latest dates
<pre><code>Date Sub Value 10/24/2020 A 1 9/18/2020 A 2 9/21/2020 A 3 9/13/2020 A 4 9/20/2020 A 5 </code></pre> <p>I want to extract the data using latest date from the dataframe. I was using the following formula, but the output is different</p> <pre><code>df = df.Date.max() </code></pre> ...
<p>To get multiple rows matching the same <code>max</code> value, you can do this:</p> <pre><code>In [2679]: df[df.Date == df.Date.max()] Out[2679]: Date Sub Value 0 2020-10-24 A 1 </code></pre>
python|pandas|dataframe
4
363,334
64,553,132
Make a zip() pandas columns to sum up other columns with unique index
<p>I have a DataFrame with 3 columns:</p> <ul> <li>store</li> <li>product</li> <li>price</li> </ul> <p>For each store we have multiple products, but each product has a unique price. The DataFrame is hence composed of multiple rows on the same store, each row corresponding to a product.</p> <p>I would like to make some ...
<pre><code>df.groupby(&quot;store&quot;, as_index = False).apply(lambda x: pd.Series({'store': x[&quot;store&quot;].iloc[0], &quot;result&quot;: [(val[&quot;product&quot;], val[&quot;price&quot;]) for idx, val in x.iterrows()]})) </code></pre>
python|pandas|group-by|zip|pandas-groupby
0
363,335
64,492,762
TF Keras Model Serving REST API JSON Input Format
<p>So I tried following <a href="https://www.tensorflow.org/tfx/guide/keras" rel="nofollow noreferrer">this guide</a> and deploy the model using docker tensorflow serving image. Let's say there are 4 features: feat1, feat2, feat3 and feat4. I tried to hit the prediction endpoint {url}/predict with this JSON body:</p> <...
<p>In that example, the serving function expects a serialized <code>tf.train.Example</code> proto as input. This <a href="https://cloud.google.com/ai-platform/prediction/docs/online-predict?hl=en_US#binary_data_in_prediction_input" rel="nofollow noreferrer">page</a> explains how binary data can be passed to a deployed ...
python-3.x|tensorflow|keras|tensorflow2.0|tensorflow-serving
1
363,336
64,428,934
how do I replace outliers with groupby?
<p>Hi this is my (toy) data :</p> <pre><code>data = {'p1': [100., 101, 102, 100, 100], 'p2': [100., 99., 98., 100., 100], 'p3': [1000., 1000., 100., 1000., 1000] } df = (pd.DataFrame(data, index=pd.bdate_range(start='20100101', periods=5)) .stack() .reset_index() .rename(column...
<p>How about performing a direct <code>.loc[]</code> query on the mean dataframe?</p> <pre><code>outliers = df.groupby('type')['price'].apply(lambda x: (x.pct_change(1).abs() &gt;= 0.5)) df_mean = df[~outliers].groupby('date').mean() fill_values = df_mean.loc[df.loc[outliers, &quot;date&quot;], &quot;perf&quot;].value...
python|pandas|dataframe|group-by
0
363,337
64,407,344
Is this possible with tf.tensor_scatter_nd_add
<p>A simple example of the following use of tf.tensor_scatter_nd_add is giving me problems.</p> <p><code>B = tf.tensor_scatter_nd_add(A, indices, updates)</code></p> <p>tensor A is (1,4,4)</p> <pre><code>A = [[[1. 1. 1. 1.], [1. 1. 1. 1.], [1. 1. 1. 1.], [1. 1. 1. 1.]]] </code></pre> <p>the desired re...
<p>Planaria,</p> <p>Try passing indices and updates the following way: updates with shape (n), indices with shape (n,3) where n is number of changed items. Indices should point to individual cells that you want to change:</p> <pre><code>A = tf.ones((1,4,4,), dtype=tf.dtypes.float32) updates = tf.constant([1., 2., 3., ...
tensorflow|deep-learning|tensorflow2.0|tf.keras|keras-2
1
363,338
64,572,879
How to convert epoch time to another format and save it into csv file in Python?
<p>How to convert epoch time to the format yyyy-mm-dd hh:mm:ss. In the first column of the &quot;test_file.csv&quot; there is epoch data? Two other colums are just numbers. Then I want to average every 5 rows. I save averaged data in &quot;averaged_test_file.csv&quot;. I would like to save the time in desired format in...
<p>You can reformat your column from epoch time to a datetime format with:</p> <pre><code>df['date time'] = pd.to_datetime(df['epoch time'], unit='s') </code></pre> <p>After that you can export this date column with the 'date_format' parameter of the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/p...
python|pandas|csv|date
1
363,339
64,542,144
TFlite Android bytebuffer creation for inference
<p>I have a customly trained mobilenetV2 model which accepts as input a 128x101x3 array of FLOAT32. In Android (Java), when calling the tflite model inference, the float[x][y][z] input must be converted into a bytebuffer of size 4<em>128</em>101*3 (4 for the float size and the rest for the image size).</p> <p>The probl...
<p>I had the same problem. You shoud check the <a href="https://www.tensorflow.org/lite/inference_with_metadata/lite_support#basic_image_manipulation_and_conversion" rel="nofollow noreferrer">TensorFlow Lite Android Support Library</a></p> <p>Or you can check to <a href="https://stackoverflow.com/questions/63726309/why...
android|tensorflow-lite|inference
2
363,340
64,483,854
Efficient way of filtering by datetime in groupby
<p>Given the <code>DataFrame</code> generated by:</p> <pre><code>import numpy as np import pandas as pd from datetime import timedelta np.random.seed(0) rng = pd.date_range('2015-02-24', periods=14, freq='9H') ids = [1]*5 + [2]*2 + [3]*7 df = pd.DataFrame({'id': ids, 'time_entered': rng, 'val': np.random.randn(len(rng...
<p>Generally, avoid <code>groupby().apply()</code> since it's not vectorized across groups, not to mention the overhead for memory allocation if you are returning new dataframes as in your case.</p> <p>How about finding the time threshold with <code>groupby().transform</code> then use boolean indexing on the whole data...
python|pandas|numpy|optimization|pandas-groupby
4
363,341
64,359,762
Constructing a pandas DataFrame with columns and sub-columns from nested dictionary
<p><strong>What I have:</strong></p> <p>A nested dictionary <code>a</code> of the following form</p> <pre><code> a={ &quot;level1&quot;: { &quot;t1&quot;:{ &quot;s1&quot;:{ &quot;col1&quot;:5, &quot;col2&quot;:4, ...
<p>You can use the base <code>pd.json_normalize</code> to load in your data into 1 very wide dataframe. From there you'll need to convert your columns into a <code>pd.MultiIndex</code> then you can stack your levels as needed. Here's what worked for me:</p> <p>Reading the data:</p> <pre><code>df = pd.json_normalize(a) ...
python-3.x|pandas|dataframe|dictionary
0
363,342
64,617,320
How to sum actual row of column to previous row of another column pandas?
<p>I have the following df:</p> <p><a href="https://i.stack.imgur.com/idl17.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/idl17.png" alt="enter image description here" /></a></p> <p>It comes from an excel file. Actually, i want to replicate it in Python.</p> <p>The <code>TTA</code> column's first v...
<p>Use <code>.cumsum()</code>:</p> <pre><code>df['TTA'] = df['Tiempo termico'].cumsum() </code></pre>
python|python-3.x|pandas|sum
1
363,343
64,409,598
Access different values in one data frame column?
<p>Df is a loaded in csv file that contains different stats.</p> <pre><code>player_name,player_id,season,season_type,team Giannis Antetokounmpo,antetgi01,2020,PO,MIL </code></pre> <p>I have tried this:</p> <pre><code>print(df.loc[(df[&quot;team&quot;] == &quot;LAL&quot;) &amp; (df[&quot;team&quot;] == &quot;LAC&quot;)...
<p>Good question, this should work for you:</p> <pre><code>team_list = [&quot;LAL&quot;, &quot;LAC&quot;] df = df[df.team.isin(team_list) &amp; df.season_type == 'PO'] </code></pre>
python|pandas
1
363,344
64,242,558
Scikit-Learn wrapper and RandomizedSearchCV: RuntimeError
<p>I am reading the book</p> <p>&quot;<em>Hands-On Machine Learning with Scikit-Learn, Keras, and Tensorflow: Concepts, Tools, and Techniques to Build Intelligent Systems</em>&quot;</p> <p>and in the Chapter 11 (<em>Introduction to ANN with Keras</em>) is explained that one can wrap a tensorflow model in scikit-learn t...
<p>I've had the same issue, and it seems to arise from not assigning iterable values in the param_distribs dictionary (or at least, values that Scikit-Learn views as iterable). One way I've found to work around this is to replace these values with iterable equivalents:</p> <pre><code>param_distribs = { &quot;n_hidden&q...
python|tensorflow|scikit-learn|deep-learning|google-colaboratory
4
363,345
64,588,076
How can I read a csv.gz file with pyarrow from a file object?
<p>I am trying to read a bunch of gzip-compressed csv files from S3 using pyarrow. The documentation page of <a href="https://arrow.apache.org/docs/python/generated/pyarrow.csv.read_csv.html#pyarrow.csv.read_csv" rel="nofollow noreferrer"><code>pyarrow.csv.read_csv</code></a> says</p> <blockquote> <p>If a string or pat...
<p>Found a workaround for it. It is possible to add a gzip decompression in between before reading the csv from the file handler:</p> <pre><code>import gzip import s3fs import pyarrow.csv as pv s3 = s3fs.core.S3FileSystem(anon=False) csv_path = 's3://bucket_name/path/to/file.csv.gz' with s3.open(csv_path) as s3fp: ...
python|pandas|csv|pyarrow
3
363,346
64,198,496
unable to parse html table with Beautiful Soup
<p>I am very new to using Beautiful Soup and I'm trying to import data from the below url as a pandas dataframe. However, the final result has the correct columns names, but no numbers for the rows. What should I be doing instead?</p> <p>Here is my code:</p> <pre><code>from bs4 import BeautifulSoup import requests def...
<p>The data you see in the table is loaded from another URL via JavaScript. You can use this example to save the data to csv:</p> <pre><code>import json import requests import pandas as pd data = requests.get('https://www.cmegroup.com/CmeWS/mvc/Quotes/Future/1/G').json() # uncomment this to print all data: # print(j...
python|html|pandas|parsing|beautifulsoup
3
363,347
64,324,530
TensorFlow: How to convert image to 1 dimensional tensor?
<p>I've recently used the mnist data set to build a model for predicting hand-written integers. I now want to use my own images. My images are 28x28 pixels (like the mnist set), but when I try to convert them into a tensor using tf.image.decode_png, I get a a 3D tensor [28, 28, 4]. From reading around, I believe the ex...
<p>As you correctly said, you got a 3D tensor because your image have 3 RGB channels. You can use something like <a href="https://www.tensorflow.org/api_docs/python/tf/image/rgb_to_grayscale" rel="nofollow noreferrer">tf.image.rgb_to_grayscale</a> to get what you want.</p>
tensorflow|png|mnist
1
363,348
64,378,180
Split single Dataframe Column into multiple columns
<p>I have data along the lines below (although many more rows than the example of course). The data can appear in diferent order.<br/></p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'SmVariant': ['1xFBBC', float('nan'), '2xFBBA', '5xABIA', \ '2xFBBC, 1xFBBA', '1x...
<p>I assume you mean a pandas DataFrame. I also assume that you know the different types of element upfront and can put them into a dictionary like so (to map the elements into the final columns:</p> <pre><code>cols={'AAAA':0, 'BBBB': 1, 'CCCC': 2} </code></pre> <p>Next write a function that converts a specific elemen...
python|regex|pandas|dataframe|split
0
363,349
64,404,974
Search certain values in a column of a dataframe when it matches values of a list
<p>I have the following list:</p> <pre><code>a = [1, 1193, 1219, 1210, 2115, 1198, 1197, 1196, 1136, 3793] </code></pre> <p>I also have a Dataframe with 8570 rows × 4 columns.</p> <p>Now I want to have all the values of the 2nd column of the dataframe when a value of my list 'a' matches with a value of the first column...
<p>You can try <a href="https://numpy.org/doc/stable/reference/generated/numpy.isin.html" rel="nofollow noreferrer"><code>np.isin</code></a>:</p> <pre><code>import pandas as pd df = pd.DataFrame(np.random.randint(1000, 2000, size=(1000,4))) a = np.array([1, 1193, 1219, 1210, 2115, 1198, 1197, 1196, 1136, 3793]) a[np.is...
python|pandas|numpy
0
363,350
64,217,536
Create another numpy.array in a pandas data based upon conditionals
<p>I have a dataframe df_a, with a numpy-array named 'Language'. I want to create another numpy-array, LanguageCode, based upon Language and the Language codes associated with a Language.</p> <pre><code>df_a = pd.DataFrame({'Language':[['cantonese', 'japanese', 'mandarin','american'],['mandarin','eng...
<p>I assumed that you have a dictionary to associate language and language code, and then used map.</p> <p>Please, check if it helps you:</p> <h2>Assumptions:</h2> <pre><code>import pandas as pd import numpy as np df_a = pd.DataFrame({'Language':[['cantonese', 'japanese', 'mandarin','american'],['man...
python|pandas|numpy-ndarray
1
363,351
64,210,701
Is there a way to have the previous column marked changed using .ne?
<p>I'm trying to show when there's been a change in the value in a column. I'm using the <code>.ne</code> function. I have the following code:</p> <pre><code>df['Changed'] = df['Column A'].ne(df['Column A'].shift().bfill()).astype(int) mouse_final_df_four.head(50) </code></pre> <p>here's a sample of the df</p> <pre><...
<p>I think you want <code>shift(-1)</code></p> <pre><code>df['flag'] = df['Column A'].ne(df['Column A'].shift(-1).fillna(df['Column A'])).astype(int) </code></pre> <p>Output:</p> <pre><code> Column A flag 7 k403 0 8 k403 0 9 k403 1 10 s185 0 11 s185 0 12 s185 0 13 ...
python|pandas|dataframe
1
363,352
64,543,865
python multiplying python float with numpy float
<p>So I'm trying to do the following: <code>self.cashflows[&quot;Balance&quot;] * self.assumptions[&quot;Default Rates&quot;][current_period - 1]</code> where cashflows is a list with python floats and assumptions is a list with numpy floats. I used numpy to fill the assumption vector and I am getting the following err...
<p>Depends on what you want to do. Do you want to multiply every item in the list <code>self.cashflow[&quot;Balance&quot;]</code> with <code>self.assumptions[&quot;Default Rates&quot;][current_period - 1]</code>? Then you can use some list comprehension:</p> <p><code>result = [q * self.assumptions[&quot;Default Rates&q...
python|numpy
1
363,353
64,307,805
How can I write a tensorflow model that fits multiple linear equations?
<p>I'd like to write a model that fits multiple linear equations based on the input. I think I need a layer that estimates separating (or inflection) points, sets of parameters that correspond to each equation, and a layer that selects output based on the separating points. However, as I'm new to <code>machine learning...
<p>If you know how many lines you want to fit from your data, e.g. 3 from the picture, then you can have your model output 6 parameters. Those 6 parameters would be m1, b1, m2, b2, m3, b3, namely the slopes and y-axis intercepts for each line ( y = m1*x + b1, etc.). Instead of tf.keras.layers.Dense(1) for your last la...
tensorflow|keras|linear-regression|tensorflow2.0|tf.keras
0
363,354
64,293,076
Alternative function for tf.contrib.layers.flatten(x) Tensor Flow
<p>i am using Tensor flow 0.8.0 verison on Jetson TK1 with Cuda 6.5 on 32 bit arm architecture. For that i can't upgrade the Tensor Flow version and i am facing trouble in Flatten function</p> <pre><code>x = tf.placeholder(dtype = tf.float32, shape = [None, 28, 28]) y = tf.placeholder(dtype = tf.int32, shape = [None]) ...
<p>You can use <a href="https://www.tensorflow.org/api_docs/python/tf/reshape" rel="nofollow noreferrer"><code>tf.reshape</code></a> instead</p> <pre class="lang-py prettyprint-override"><code>images_flat = tf.reshape(x, [x.get_shape(x).as_list()[0], -1]) </code></pre>
tensorflow|tensorflow2.0|tensor|tensorflow-datasets|tensorflow-serving
0
363,355
64,576,300
Create a new column comparing two rows
<p>I am working on a COVID-19 dataset with total cases and total deaths at the last day of each month for each city since march. But I would like to create a column which tells me the number of new cases for every city in each of these months.</p> <p>My logic is: if the value in the cell from the <code>'city_ibge_code'...
<p><code>rows</code> here is a view of the line. You need to update the actual dataframe. If I understood your problem correctly.</p> <pre><code>for i, rows in enumerate(casos_full): if rows['city_ibge_code'] == rows['city_ibge_code'].shift(1): casos_full[i]['New Cases'] = rows['last_available_confirmed'] ...
python|pandas
0
363,356
64,545,128
Significant lower accuracy when using empty ImageDataGenerator in Tensorflow Keras
<p>I am trying to build a Convolutional Network to classify the CIFAR-100 dataset and I have run into an unsual problem. Now, I might be making an obvious mistake, but since I am very new to this field I cannot seem to find it.</p> <p>The network was working fine until I tried to introduce an ImageDataGenerator to augm...
<p>Actually I dont feel is a good idea to use the first epoch as a sign of how well your CNN works. You should let it converge to see if there is a true performance difference.</p> <p>Also, there is a difference in using the raw data in compare with ImageDataGenerator. ImageDataGenerator creates data augmentation durin...
python|tensorflow|keras
1
363,357
64,556,120
Early stopping with multiple conditions
<p>I am doing multi-class classification for a recommender system (item recommendations), and I'm currently training my network using <code>sparse_categorical_crossentropy</code> loss. Therefore, it is reasonable to perform <code>EarlyStopping</code> by monitoring my validation loss, <code>val_loss</code> as such:</p> ...
<p>With guidance from <a href="https://stackoverflow.com/a/64559644/11764097">Gerry P</a> above I managed to create my own custom EarlyStopping callback, and thought I post it here in case anyone else are looking to implement something similar.</p> <p>If <strong>both</strong> the <em>validation loss</em> <strong>and</s...
python|python-3.x|tensorflow|keras|recommendation-engine
5
363,358
64,341,555
Replicate rows in Pandas and add a new (month) column
<p>I am struggling with what I am sure is a simple problem. I have a dataframe that has around <code>1000 rows</code> that are unique.</p> <p>This shows <code>expenses for the year</code> by category by location. Each has location the same group of categories.</p> <p>I want to create a <code>monthly budget</code> colum...
<p>You can create your specific month-table with April as the number 1 for the starting month in the fiscal year.</p> <pre><code>import pandas as pd # intialise data from list. data = {'Month':['April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'January', 'February', 'March']...
python|pandas|dataframe|group-by
0
363,359
64,295,687
How can I delete a group of rows if they don't satisfy a condition?
<p>I have a dataframe with stock option information. I want to filter this dataframe in order to have exactly 8 options per date. The problem is that some dates have only 6 or 7 options. I want to write a code where I delete entirely this group of options.<a href="https://i.stack.imgur.com/PRjtH.png" rel="nofollow nore...
<p>First group by count on index</p> <pre><code>odf = df.groupby(df.index).count() </code></pre> <p>filter the dataframe and get the resulting index</p> <pre><code>idx = odf[odf['A'] == 3].index </code></pre> <p>select by index</p> <pre><code>df.loc[idx] </code></pre>
pandas|python-2.7|dataframe|filter|rows
0
363,360
64,504,310
Pandas apply combined with shift
<p>I am trying to find the relative movement of a currency for each time interval.</p> <p>I have a table like this:</p> <pre><code>Date USD_NOK EUR_USD EUR_NOK 2020-08-09 9.03267 1.17732 10.60526 2020-08-10 8.97862 1.17749 10.58188 </code></pre> <p>And a function like this:</p> <pre><code>def RelativeStreng...
<p>Since all your operations (<code>*</code>, <code>/</code> and <code>**</code>) has built-in vectorized support by default, I'd suggest you to do the calculation directly without <code>.apply()</code>.</p> <pre><code>df[&quot;f1_t1&quot;] = df[&quot;EUR_NOK&quot;].shift() / df[&quot;EUR_NOK&quot;] # f1 over t1 df[&q...
python|python-3.x|pandas|dataframe|forex
1
363,361
64,393,672
Python Pandas: create variable for unique combinations of 2 categorical variables?
<p>Say I have some data:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'location':['store','online','store','online','online'], 'item': ['apple','apple','orange','orange','orange']}) df &gt;&gt;&gt; location item 0 store apple 1 online apple 2 store orange 3 o...
<p>Let's create <code>combinations</code> by concatenating <code>location</code> and <code>item</code> then use <code>factorize</code> to encode these combinations to get <code>dummy</code> variables:</p> <pre><code>df['combination'] = df['location'].add(', ' + df['item']) df['dummy'] = df['combination'].factorize()[0]...
python|pandas|combinations
3
363,362
64,529,704
Merge data from several excel sheets into one
<p>I have city addresses I need to put together and find all duplicates. I got to a point where I can find all the duplicates in excel files, easy so far. But I have to change each city in the code to search each file. How do I search each file without having to change the city in the code and then save it of course. I...
<p>It's hard to answer your question properly without knowing what your data is like and what your file naming is. I'll assume that all your excel files are in the same folder and they have same 3 columns of data.</p> <p>In that case all you need to do is:</p> <pre><code>import os import pandas as pd source_folder = '...
python|excel|pandas
0
363,363
47,942,693
Google Cloud Machine Learning Engine cannot find trainer module for local execution
<p>I try to get my feet wet with Google Cloud <a href="https://cloud.google.com/ml-engine" rel="nofollow noreferrer">Machine Learning (ML) Engine</a> by attempting to run a local trainer. I have followed Google's setup instructions and issued this command:</p> <pre><code>gcloud ml-engine local train \ --module-name ...
<p>The code must be in a valid <a href="https://docs.python.org/2/tutorial/modules.html#packages" rel="nofollow noreferrer">Python package</a>, which will require you to have an <code>__init__.py</code>, which can be blank.</p> <p>First, create the <code>__init__.py</code>. From the same directory as above run:</p> <...
python|python-2.7|tensorflow|google-cloud-ml
3
363,364
47,887,071
Best way to build data frame from nested dictionary
<p>After processing the data I have saved group level calculations in following structure (Nested Dictionary): </p> <pre><code>{'Source1': {(1, 2): {'value1': -1.4089917877152731, 'value2': 0.15890127107708821}, (1, 3): {'value1': -3.6436438771179183, 'value2': 0.00027189114106343325}, (1, 4): {'value1': 1.39213797189...
<p>I think you need:</p> <pre><code>df = pd.concat({k:pd.DataFrame(v) for k, v in d.items()}) df.columns = ['({},{})'.format(i,j) for i,j in df.columns] print (df) (1,2) (1,3) (1,4) (2,3) (2,4) (3,4) Source1 value1 -1.408992 -3.643644 1.392138 -2.127274 2.781268 5.088728e+...
python|pandas|dictionary|dataframe
3
363,365
47,701,815
Python Pandas Set Value in DataFrame where Index has Multiple Identical Label Values
<p>I want to set a value in a row in a pandas dataframe where the row index has duplicate values and the value of a date column is the max value for the selected index value. </p> <p>My dataframe:</p> <pre><code>Index Start_Date End_Date A 2017-10-01 2017-10-13 B 2017-10-07 2017-10-15 B ...
<p>Setting the datetime format</p> <pre><code>df.End_Date=pd.to_datetime(df.End_Date,errors='coerce') df.Start_Date=pd.to_datetime(df.Start_Date) </code></pre> <p>Then we do <code>apply</code> + <code>fillna</code> </p> <pre><code>df['End_Date']=df.groupby('Index').apply(lambda x : x['End_Date'].fillna(x['Start_Dat...
python|pandas
3
363,366
47,877,992
Merging another dataframe to existing rows
<p>I have 2 dataframes <code>df</code> and <code>subs</code> as:</p> <pre><code>df = pd.DataFrame({"scode": [11, 22, 33, 44], "sname": ["aa", "bb", "cc", "dd"], "sub1": [ "London", np.nan, "Delhi", np.nan], "sub2": [np.nan, np.nan, "Sydney", np.nan]}) scode sname sub1 sub2 0 11 aa London NaN 1 22 ...
<p>Pandas will automatically align on indices/columns, just make sure you set the correct index, assuming <code>scode</code> is how you want to merge things:</p> <pre><code>In [5]: df = pd.DataFrame({"scode": [11, 22, 33, 44], "sname": ["aa", "bb", "cc", "dd"], "sub1": [ "London", np.nan, "Delhi", np.nan], "sub2": [np...
python|pandas|dataframe
1
363,367
47,582,105
Count if data is higher than another series within a rolling window of past two (or more) values in pandas
<p>I have this two Series in a DataFrame:</p> <pre><code>A B 1 2 2 3 2 1 4 3 5 2 </code></pre> <p>and I would to create a new column <code>df['C</code>] that counts how many times the value in column <code>df['A']</code>is higher than the value in column <code>df['B']</code> for a rolling window of ...
<p>IIUC</p> <pre><code>df.assign(C=df.A.gt(df.B).rolling(2).sum().shift(),D=(df.A.gt(df.B)*df.A).rolling(2).sum().shift()) Out[1267]: A B C D 0 1 2 NaN NaN 1 2 3 NaN NaN 2 2 1 0.0 0.0 3 4 3 1.0 2.0 4 5 2 2.0 6.0 </code></pre>
python|pandas|count|window-functions|rolling-computation
0
363,368
47,843,086
How to fix y-intercept value in linear regression?
<p>I'm trying to fit a least square line across my data using scipy's <code>linregress()</code> with something like this:</p> <pre><code>from scipy import stats import numpy as np y = [30, 60, 19, 28, 41, 49, 62, 75, 81] x = np.arange(0,9) grad, intercept, r_value, p_value, std_err = stats.linregress(x,y) </code></p...
<p>In statsmodels you can shift y so the origin is at zero and exclude the intercept:</p> <pre><code>res = OLS(y - 30., x).fit() </code></pre> <p>where x contains the regressors without intercept (column of ones). Then the interpretation is that we predict the deviation from 30.</p> <pre><code>y_predicted = 30 + res...
python|numpy|scipy|linear-regression|statsmodels
2
363,369
47,685,033
Converting column values into datetime to insert into AccessDB
<p>I am trying to populate values of Pandas Dataframe into MS Access table. I am using the following Pandas built-in <code>DF.iterrows()</code> to iterate through each row of a DataFrame and insert each row into Access table. </p> <pre><code>for index,row in df.iterrows(): print(repr(row['Vote_date'])) #Using iter...
<p>I had luck doing this:</p> <pre><code>import pandas as pd df = pd.DataFrame(['01/01/2019',None], columns=['datetime_field']) df['datetime_field'] = pd.to_datetime(df['datetime_field']) df['datetime_field'] = pd.to_datetime(df['datetime_field'], errors='coerce').where(df['datetime_field'].notnull(), 0.0) </code></...
python|python-3.x|pandas|numpy|ms-access-2016
0
363,370
47,834,225
Count the amount of times value A occurs with value B
<p>I'm trying to count the amount of times a value in a Pandas dataframe occurs along with another value and count the amount of times for each row.</p> <p>This is what I mean:</p> <pre><code> a t 0 a 2 1 b 4 2 c 2 3 g 2 4 b 3 5 a 2 6 b 3 </code></pre> <p>Say I want to count the amou...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>transform</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>size</code></a...
python|pandas
3
363,371
47,898,162
Python DataFrame: rearrange the objects and empty values
<p>I have a Python DataFrame with 20000+ values as below. And I want to efficiently rearrange df with NaN goes after string of values.</p> <pre><code> IT1 IT2 IT3 IT4 IT5 IT6 0 qwe NaN NaN rew NaN NaN 1 NaN NaN sdc NaN NaN wer 2 NaN NaN NaN ...
<p>One way, albeit slowly, <code>apply</code>, <code>dropna</code>, and <code>tolist</code>:</p> <pre><code> df.apply(lambda x: pd.Series(x.dropna().tolist()),1)\ .set_axis(df.columns, axis=1, inplace=False) </code></pre> <p>Output:</p> <pre><code> IT1 IT2 IT3 IT4 IT5 IT6 0 qwe rew NaN NaN NaN NaN 1 ...
python|arrays|pandas|dataframe|arrange-act-assert
1
363,372
47,675,520
Getting Error on StandardScalar Fit_Transform
<pre><code> import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, 1:2].values y = dataset.iloc[:, 2].values from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() sc_y = StandardScaler() X = sc_X.fit_transform(X...
<p>StandardScaler is meant to work on the features, not labels or target data. Hence only works on 2-d Data. Please see here for documentation: </p> <ul> <li><a href="http://scikit-learn.org/stable/modules/preprocessing.html#standardization-or-mean-removal-and-variance-scaling" rel="noreferrer">http://scikit-learn.or...
python|arrays|machine-learning|scikit-learn|sklearn-pandas
10
363,373
47,739,284
tensorflow matrix multiplication
<p>So, i want to multiply a matrix with a matrix. When I try an array with a matrix, it works:</p> <pre><code>import tensorflow as tf x = tf.placeholder(tf.float32, [None, 3]) W = tf.Variable(tf.ones([3, 3])) y = tf.matmul(x, W) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) curr_y = ...
<p>When you do matrices multiplication, the <code>shape</code> of the matrices need to <a href="https://en.wikipedia.org/wiki/Matrix_multiplication" rel="nofollow noreferrer">follow the rule</a> <code>(a, b) * (b, c) = (a, c)</code></p> <p>Keep in mind the shape of W as you defined is (3, 3).</p> <p>This <code>feed_...
python|matrix|tensorflow
0
363,374
47,703,634
pandas group by and assign a group id then ungroup
<p>I have a large data set in the following format: </p> <pre><code>id, socialmedia 1, facebook 2, facebook 3, google 4, google 5, google 6, twitter 7, google 8, twitter 9, snapchat 10, twitter 11, facebook </code></pre> <p>I want to group by then and assign a group_id column and then ungroup (expand) back to individ...
<p>By using <code>ngroup</code></p> <pre><code>df['grpId']=df.groupby(' socialmedia').ngroup().add(1) df Out[354]: id socialmedia grpId 0 1 facebook 1 1 2 facebook 1 2 3 google 2 3 4 google 2 4 5 google 2 5 6 twitter 4 6 7 g...
python|pandas|pandas-groupby
11
363,375
47,886,401
Selecting rows in a MultiIndex dataframe by index without losing any levels
<p>I would like to select a row called 'Mid', without losing it's index 'Site'</p> <p>Following code shows the dataframe:</p> <pre><code>m.commodity </code></pre> <hr> <pre><code> price max maxperstep Site Commodity Type Mid Biomass Stock 6.0 inf inf CO2 Env ...
<p>You can also use <code>loc</code> with double braces.</p> <pre><code>df.loc[['Mid']] price max maxperstep Site Commodity Type Mid Biomass Stock 6.0 inf inf CO2 Env 0.0 inf inf Coal Stock 7.0 inf inf Elec Demand N...
python|pandas|dataframe|multi-index
8
363,376
47,863,001
How Pytorch Tensor get the index of specific value
<p>With python lists, we can do:</p> <pre><code>a = [1, 2, 3] assert a.index(2) == 1 </code></pre> <p>How can a pytorch tensor find the <code>.index()</code> directly?</p>
<p>I think there is no direct translation from <code>list.index()</code> to a pytorch function. However, you can achieve similar results using <code>tensor==number</code> and then the <code>nonzero()</code> function. For example:</p> <pre><code>t = torch.Tensor([1, 2, 3]) print ((t == 2).nonzero(as_tuple=True)[0]) </co...
python|pytorch
79
363,377
47,868,985
Why does Keras not generalize my data?
<p>Ive been trying to implement a basic multilayered LSTM regression network to find correlations between cryptocurrency prices. </p> <p>After running into unusable training results, i've decided to play around with some sandbox code, to make sure i've got the idea right before trying again on my full dataset.</p> <...
<p>How about transform your input data before sending into your LSTM, use something like sklearn.preprocessing.StandardScaler? after prediction you can call scaler.inverse_transform(prediction) </p>
machine-learning|tensorflow|keras|lstm|recurrent-neural-network
0
363,378
47,933,745
Make a histogram from csv data
<p>I'm trying to make a histogram with data from a .CSV file. I put together the code below and I'm getting an ''int' object is not iterable' error when I run it, any ideas?</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt file = "...sp histo.csv" data = pd.read_csv(file) year_20...
<p>There is a problem in this line:</p> <pre><code>plt.hist(year_2017,bins=bins, range = 20) </code></pre> <p>According to the docstring for <code>hist</code>, range must be a <em>tuple</em>:</p> <pre><code>range : tuple or None, optional The lower and upper range of the bins. Lower and upper outliers are ig...
python|pandas|numpy|matplotlib|histogram
1
363,379
47,954,529
create pandas dataframe from different size numpy arrays
<p>I have the following numpy arrays which are of different shape. I want to use pandas to create a dataframe so that I can display it neatly as shown below:</p> <p>numpy arrays:</p> <pre><code>et_arr: [ 8.94668401e+01 1.66449935e+01 -4.44089210e-14] ea_arr: [ 100. 21.84087363 1.04031209] it: [[ 0...
<p>If you have put the arrays into a dict <code>data</code>, you can loop over keys and add as you go:</p> <pre><code>data = {"et_arr":[8.94668401e+01,1.66449935e+01,-4.44089210e-14], "ea_arr":[100.,21.84087363,1.04031209], "it":[[0.1728,1.0688,1.4848,1.6008], [1.36746667,1.62346667,1.639...
python|arrays|python-3.x|pandas|numpy
2
363,380
47,785,561
How to add another column in dataframe with calculated values
<p>I have a news dataset and I am carrying NLP over it. I have 2 functions right now, One calculates similarity and another one calculates sentiments both of them takes the input from data frame, that I am trying to do is to create another column in the dataframe with the calculated values like similarity &amp; sentim...
<p>This will solve your problem</p> <pre><code>def jaccard(text1,text2): vector1 = similarity.text_to_vector(text1) vector2 = similarity.text_to_vector(text2) token1 = similarity.tokenize(text1) token2 = similarity.tokenize(text2) jaccard = similarity.jaccard_similarity(token1,token2) return ...
python|pandas|dataframe|sentiment-analysis|text-analysis
1
363,381
47,976,750
Error in implementing SVM
<p>Here is my code for cats and dogs image recognition:</p> <pre><code>import numpy as np from sklearn.svm import SVC from sklearn.model_selection import train_test_split filename= 'catdog_datasets.txt' filename1= 'catdog_datasets.txt' raw_data = open(filename, 'rt') raw_data1 = open(filename1, 'rt') #data = numpy.l...
<p>The error is because your file has lines like :</p> <pre><code>f1 f2 f3 f4 ............................................f1565 :0 </code></pre> <p>As you observed, the features are separated by a white space, and the whole feature vector is separated from label by a colon (:). </p> <p>Now in your code, you are usin...
numpy|machine-learning|computer-vision|svm
0
363,382
47,749,018
Why is pandas apply lambda slower than loop here?
<p>I have a pandas dataframe which I'd like to filter based on if certain conditions are met. I ran a loop and a <code>.apply()</code> and used <code>%%timeit</code>to test for speed. The dataset has around 45000 rows. The code snippet for loop is:</p> <pre><code>%%timeit qualified_actions = [] for row in all_actions....
<p><code>apply</code> uses loops under the hood, so if you need <a href="https://stackoverflow.com/questions/24870953/does-iterrows-have-performance-issues/24871316#24871316">better performance</a> the best and the fastest methods are vecorized alternatives.</p> <p>No loops, only chain 2 conditions vectorized solution:...
python|pandas|performance
4
363,383
47,965,149
Expected 2D array, got 1D array instead, Reshape Data
<p>I'm really stuck on this problem. I'm trying to use OneHotEncoder to encode my data into a matrix after using LabelEncoder but getting this error: Expected 2D array, got 1D array instead.</p> <p>At the end of the error message(included below) it said to "Reshape my data" which I thought I did but it's still not wor...
<p>try changing you code to this</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import Dataset dataset = pd.read_csv('Data2.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 5].values df_X = pd.DataFrame(X) df_y = pd.DataFrame(y) # Replace Missing Values from sklearn....
python|python-3.x|numpy|machine-learning|sklearn-pandas
2
363,384
47,585,465
How to compute moving (or rolling, if you will) percentile/quantile for a 1d array in numpy?
<p>In pandas, we have <code>pd.rolling_quantile()</code>. And in numpy, we have <code>np.percentile()</code>, but I'm not sure how to do the rolling/moving version of it.</p> <p>To explain what I meant by moving/rolling percentile/quantile:</p> <p>Given array <code>[1, 5, 7, 2, 4, 6, 9, 3, 8, 10]</code>, the moving q...
<pre><code>series = pd.Series([1, 5, 7, 2, 4, 6, 9, 3, 8, 10]) In [194]: series.rolling(window = 3, center = True).quantile(.5) Out[194]: 0 nan 1 5.0000 2 5.0000 3 4.0000 4 4.0000 5 6.0000 6 6.0000 7 8.0000 8 8.0000 9 nan dtype: float64 </code></pre> <p>Center is <code>False</code> by defa...
pandas|numpy|quantile|rolling-computation
7
363,385
47,981,575
Print function and numpy.savetxt in python 3
<p>Some code I am using (not in python) takes input files written in specific way. I usually prepare such input files with python scripts. One of them takes the following format:</p> <pre><code>100 0 1 2 3 4 5 6 7 8 </code></pre> <p>where 100 is just an overall parameter and the rest is a matrix. In python 2, I used ...
<p>I ran into this same issue converting to python3. All strings in python3 are interpreted as unicode by default now, so you have to convert. I found the solution of writing to a string first and then writing the string to the file to be the most appealing. This is a working version of your snippet in python3 using th...
python|numpy
1
363,386
47,943,242
Filter numpy ndarray with another ndarray, row by row
<p>I have 2 numpy ndarray</p> <p>The first contain x and y values :</p> <pre><code>xy_arr = [[ 736190.125 1130. ] [ 736190.16666667 1130. ] [ 736190.20833333 1130. ] ..., [ 736190.375 1140. ] [ 736190.41666667 1140. ] [ 736190.45833333 1140. ]...
<p>There is <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.isin.html" rel="nofollow noreferrer"><code>numpy.isin</code></a> but it tests only against a scalar array; there is no tuple-comparison in it. You could use this method to find all rows of Array1 where the 0th column entry is in 0th column ...
python|numpy|multidimensional-array|filter|sub-array
0
363,387
47,551,982
Pivot Column values to be Column Names using Pandas
<p>I have a table (simplified view) like this:</p> <pre><code>SellerID businessDate sales_total A-123 1/1/2017 12.05 A-123 1/1/2017 126.75 B-223 1/1/2017 2.75 B-223 1/1/2017 31.75 C-444 1/1/2017 55.55 A-123 1/2/2017 12.05 A-123 1/2/2017 126.75 B-223 1/2/2017 10.7...
<p>Using pandas, one can easily pivot table a dataframe, for your specific example, one can solve it as in the image bellow:</p> <p><a href="https://i.stack.imgur.com/hoEOX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hoEOX.png" alt="enter image description here"></a></p>
python|pandas|dataframe
1
363,388
47,983,662
Why does pip show tell me that I have numpy version 1.13.1, while Pandas thinks I have numpy version 1.8.0rc1
<p>Why does pip show tell me that I have numpy version 1.13.1, while Pandas thinks I have numpy version 1.8.0rc1</p> <p>I am getting the following error importing pandas. Can someone tell me how I can fix this. </p> <ol> <li><p>Import pandas</p> <pre><code> Traceback (most recent call last): File "&lt;stdin&gt;",...
<p>in python REPL (i'm using ipython)</p> <pre><code>In [98]: import numpy as np In [99]: np.__version__ Out[99]: '1.13.3' In [100]: np.__file__ Out[100]: '/Users//anaconda/lib/python2.7/site-packages/numpy/__init__.pyc' </code></pre> <p>this will show you where the numpy is coming from, and for pandas do this</p> ...
python|pandas|numpy
0
363,389
49,120,378
Python Pandas ordering odd dataframe
<p>I am learning some Python and have come across Pandas. I have an ordered dictionary that I want to use Pandas to output in a more readable format.</p> <p>My ordered dict is a little weird, in that the format is as follows</p> <pre><code>{name:{Value1:float, Value2:float, Value3:string}} </code></pre> <p>where the...
<p>Use <code>pd.DataFrame.from_dict</code> with an <code>index</code> orient:</p> <pre><code>d = { 'nameA': {'Value1': 1.0, 'Value2': 2.0, 'Value3': 'aaa'}, 'nameB': {'Value1': 3.0, 'Value2': 4.0, 'Value3': 'bbb'} } pd.DataFrame.from_dict(d, orient='index') Value1 Value2 Value3 nameA 1.0 ...
python|pandas|dataframe
2
363,390
48,982,092
ImportError: No module named yaml in Keras (neural network)
<p>I have successfully installed Keras API and other requirements for python for using on TensorFlow but when i import it gives the below error.</p> <pre><code>Traceback (most recent call last): File "facenet.py", line 1, in &lt;module&gt; from keras import backend as K File "build/bdist.linux-x86_64/egg/keras...
<p>It seems like you don't have <code>yaml</code> module installed, if you are using virtual environment with <code>pip</code> do this:</p> <pre><code>pip install yaml </code></pre> <p>and if you are using <code>anaconda</code> do this:</p> <pre><code>conda install -c anaconda yaml </code></pre>
python|linux|tensorflow|neural-network|keras
1
363,391
49,224,709
Pytorch pretrained model (VGG-19) same image gives slightly different class score in the final FC layer
<p>I am using pretrained vgg-19 from torch.vision module I have the pre-processing of image data like below:</p> <pre class="lang-python prettyprint-override"><code>normalize = transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) preprocess = transforms.Compose([ transforms.Scale...
<p>Possible reasons why the class score could be different:</p> <ul> <li>You are using GPUs: The GPU evaluation is slightly stochastic, so if you are using GPUs in your feedforward evaluation, it could give slightly different scores.</li> <li>You are using the model in training mode <code>model.train()</code> and didn...
neural-network|deep-learning|conv-neural-network|pytorch|pre-trained-model
2
363,392
49,089,775
Keras InvalidArgumentError unknown input node
<p>I am trying to train a simple LSTM in Keras. My data have the following dimensions:</p> <pre><code>train_x.shape, train_y.shape, test_x.shape, test_y.shape &gt; ((534, 1, 7), (534, 1, 1), (259, 1, 7), (259, 1, 1)) </code></pre> <p>The model is defined as follows:</p> <pre><code>model = Sequential() model.add(LSTM...
<p>I got a very similar error and I am also using LSTMs. I am using Spyder on Windows and I simply had to restart Spyder to avoid the problem. </p>
python|tensorflow|keras|lstm
3
363,393
49,086,228
Using Panda/Numpy to search matching string
<p>I have been trying to solve this for a while now but have not yet gotten anywhere. My goal is to search a string in a column called 'WORDS' and return the 'INDEXED_NUMBER'. For example, if I searched 'aaa', it should return me 0 as shown in the table below. </p> <p><a href="https://i.stack.imgur.com/nnpmj.png" rel=...
<p>This is one way to implement your algorithm using a generator:</p> <pre><code>def WordToIndexwithjustPanda(): return next((i for i, j in zip(df['INDEXED_NUMBER', df['WORDS']) \ if 'aaa' in j), 'No match') </code></pre> <p>Strictly speaking it uses pandas only partially in that it uses the iter...
python|pandas|numpy
1
363,394
49,340,588
Pandas, select a single column where a second column has a NaN value
<p>I have a data frame that looks like this:</p> <pre><code> a b c 0 Alabama[edit] NaN NaN 1 Auburn (Auburn University)[1] 2 Florence (University of 3 Jacksonville (Jacksonville State 4 Livingston (University of </code></pre> <p>I'd like to add a column to the dataframe called 'State' tha...
<p>Your mistake is in your belief that <code>df['b'] == np.NaN</code> selects NaNs... it does not, as this example shows:</p> <pre><code>In [1]: np.nan == np.nan Out[1]: False </code></pre> <p>This is the mathematical definition of NaN. Since NaN != NaN, doing an equality comparison on NaN just won't cut it. Use <cod...
python|pandas|numpy|dataframe
4
363,395
49,109,125
Converting a model trained and saved with tf.estimator to .pb
<p>I have a model trained with tf.estimator and it was exported after training as below</p> <pre><code> serving_input_fn = tf.estimator.export.build_raw_serving_input_receiver_fn( feature_placeholders) classifier.export_savedmodel( r'./path/to/model/trainedModel', serving_input_fn) </code></pre> <p>This gives me a <...
<p>I don't deploy to Android, so you might need to customize the steps a bit, but this is how I do this:</p> <ol> <li><p>Run <code>&lt;tensorflow_root_installation&gt;/python/tools/freeze_graph.py</code> with arguments <code>--input_saved_model_dir=&lt;path_to_the_savedmodel_directory&gt;</code>, <code>--output_node_n...
tensorflow|tensorflow-serving|tensorflow-estimator
0
363,396
49,028,978
Could not find a version that satisfies the requirement python-emnist (from versions: ) No matching distribution found for python-emnist
<p>On running command python -m pip install python-emnist , Getting error as follows: </p> <p>Could not find a version that satisfies the requirement python-emnist (from versions: ) No matching distribution found for python-emnist</p> <p>Please help and provide solution.</p>
<p>You can find here how to install it from Github -> readme</p> <p><a href="https://github.com/vitords/EMNIST-sandbox" rel="nofollow noreferrer">https://github.com/vitords/EMNIST-sandbox</a></p>
python|tensorflow
0
363,397
49,293,641
Monitored training session save all checkpoints
<p>While using the <code>tf.train.MonitoredTrainingSession</code>, is it possible to save all the checkpoints. It has a parameter (<code>save_checkpoint_secs=600</code>) to specify after how much we want to save a checkpoint but there is no option to specify how many checkpoints you can save.</p> <p>While using the si...
<p>You can pass a <code>tf.train.Saver</code> using a <code>tf.train.Scaffold</code> to a <code>tf.train.MonitoredTrainingSession</code>:</p> <pre><code>import tensorflow as tf scaffold = tf.train.Scaffold(saver=tf.train.Saver(max_to_keep=10)) with tf.train.MonitoredTrainingSession(scaffold=scaffold) as sess: ... ...
tensorflow
8
363,398
48,913,396
Pandas groupby conditional subtraction
<p>I'm trying to create a new column based on a conditional subtraction. I want to first group the dataframe from column A, then take the row value of C where B is minimum, and subtract that value from all values in column C.</p> <pre><code>import pandas as pd data = [ ["R", 1, 2], ["R", 2, 4], ["R", 3, 6], ["R", 4, ...
<pre><code>conditional_c = df.groupby('a').b.idxmin().map(df.c) df.assign(d=df.c - df.a.map(conditional_c)) a b c d 0 R 1 2 0 1 R 2 4 2 2 R 3 6 4 3 R 4 8 6 4 S 0 5 0 5 S 1 4 -1 6 S 2 1 -4 7 S 3 3 -2 </code></pre>
python|pandas
5
363,399
49,313,488
Scatter plot coloring of data under the region of a function in Matplotlib
<p>I need to plot bunch of points and also on the same graph plot a function cosx. The idea is to see the points that fall under the curve.</p> <p>I have graph of cosx:</p> <pre><code>x = np.linspace(0, np.pi) #x range between 0 and pi y = np.cos(x) plt.plot(x, y) plt.show() </code></pre> <p>Now I need to plot <code...
<p>You can seperate the scatter points into two lists, one for points under the line and one for points over the line. Then you can plot both lists.</p> <p>Your data would be inserted instead of the random numbers in points_x and points_y</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.linsp...
python|numpy|matplotlib
4