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
5,400
69,455,808
Replace Unnamed values in date column with true values
<p>I'm working on this raw data frame that needs some cleaning. So far, I have transformed this xlsx file</p> <p><a href="https://i.stack.imgur.com/2YaT5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2YaT5.png" alt="enter image description here" /></a></p> <p>into this pandas dataframe:</p> <pre><c...
<p>Try setting the values to <code>NaN</code> and then use <code>ffill</code>:</p> <pre><code>df.loc[df.date.str.contains('Unnamed', na=False), 'date'] = np.nan df.date = df.date.ffill() </code></pre>
python|pandas|dataframe|pandas-groupby|nan
1
5,401
41,132,570
convert columns to rows based on row value using pandas
<p>I have an excel file as follows:</p> <pre><code>ID wk48 wk49 wk50 wk51 wk52 wk1 wk2 1123 10 22 233 2 4 22 11 1198 9 4 44 23 34 5 234 101 3 6 3 43 33 34 78 </code></pre> <p>I want the output as ...
<p>The first thing I would do is set <code>ID</code> as your index with:</p> <pre><code>df.set_index('ID',inplace=True) </code></pre> <p>Next, you can use the following command to reorient your dataframe:</p> <pre><code>df = df.stack().reset_index() print df ------------------------------------------- Output: ...
python|pandas
2
5,402
41,075,993
facenet triplet loss with keras
<p>I am trying to implement facenet in Keras with Tensorflow backend and I have some problem with the triplet loss.<a href="https://i.stack.imgur.com/RT3TZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RT3TZ.png" alt="enter image description here" /></a></p> <p>I call the fit function with 3*n numb...
<p>What could have happened, other than the learning rate was simply too high, was that an unstable triplet selection strategy had been used, effectively. If, for example, you only use <strong>'hard triplets'</strong> (triplets where the a-n distance is smaller than the a-p distance), your network weights might collaps...
neural-network|tensorflow|keras
11
5,403
65,958,288
Python solve complex inventory in Dataframe
<p>Need your help on solving ordering inventory. This is only 4 items, however the real DataFrame has 10,000 items.</p> <p>df = pd.DataFrame(data)</p> <pre><code> Inventory count Batch size Store A needs Store B needs Store C needs Total requires: Actually requires: Buckets 198 20 ...
<p>I'll qualify this response by saying you should search allocation strategies for inventory and/or supply chain management if the above example is oversimplified - meaning many more stores and/or inventory allocation strategies needed.</p> <p>I'm just returning a dictionary, but if you want or need to, you can write ...
python|pandas|dataframe|numpy|inventory-management
0
5,404
66,177,791
pd.categorical didn't sort bars by specified orders in plot
<p>I was trying to use pd categorical to order the bars in a barplot but the result still didn't get sorted.</p> <pre><code>import pandas as pd import numpy as np np.random.seed(10) df = pd.DataFrame({'x':np.random.randint(1,10,15),'y': ['x']*15}) df.loc[:,'group'] = df['x'].apply(lambda x:'&gt;=5' if x&gt;=5 else x) d...
<p><code>DataFrame.plot.bar()</code> plots the bars in order of occurrence (that is, against the range) and relabel the ticks with the column specified by <code>x</code>.</p> <p>This is the case even with numerical data:</p> <pre><code>pd.DataFrame({'idx': [3,2,1], 'val':[4,5,6]}).plot.bar(x='idx') </code></pre> <p>wou...
python|pandas
0
5,405
46,588,829
Does slim of tensorflow have distributed version?
<p>The <a href="https://github.com/tensorflow/models/blob/master/research/slim/deployment/model_deploy.py" rel="nofollow noreferrer">model_deploy</a> of slim has DeploymentConfig parameters, such as <code>num_replicas</code>, <code>num_ps_tasks</code>, <code>worker_job_name</code>, <code>ps_job_name</code>, these terms...
<p>You can call model_deploy in a single-machine and in a distributed setup. If you only have a single machine I recommend setting num_ps_tasks=0 and num_replicas=1 to get the right behavior.</p>
python|c++|tensorflow|distributed-computing|grpc
0
5,406
46,612,097
Extracting number from inside parentheses in column list
<p>I have a pandas dataframe column of lists and want to extract numbers from list strings and add them to their own separate column. </p> <pre><code> Column A 0 [ FUNNY (1), CARING (1)] 1 [ Gives good feedback (17), Clear communicator (2)] 2 [ CARING (3), Gives good feedback (3)] 3 [ F...
<p>Let's use <code>apply</code> with <code>pd.Series</code>, then <code>extract</code> and reshape with <code>set_index</code> and <code>unstack</code>:</p> <pre><code>df['Column A'].apply(pd.Series).stack().str.extract(r'(\w+)\((\d+)', expand=True)\ .reset_index(1, drop=True).set_index(0, append=True)[1...
python|pandas
1
5,407
58,177,063
Unable Color Code Points on GeoPanda Map with Contextly Background Map
<p>I am trying to create a Map that has points that are color coded by a category - however when I color by category the index is being included in the category so every point is its own color. Here is some sample code to recreate my problem.</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyp...
<p>You are using incorrect attributes for plot. Geopandas (at least in recent versions) needs <code>column</code> not <code>c</code>.</p> <pre><code>ax = gdf.plot(column=gdf.Type, cmap=cmap, label=gdf.Type, figsize=(10,10), alpha=.5) </code></pre> <p>This seems to work. But you should be aware that you have multiple ...
python|matplotlib|geopandas
1
5,408
58,233,238
Read csv file using pandas and display cell value with sorted date/time
<p>Am trying to read a csv file using pandas in the python. i have referred this link <a href="https://stackoverflow.com/questions/32897414/pandas-read-csv-moves-column-names-over-one">pandas.read_csv moves column names over one</a></p> <p>and used the below code to display the first row of csv file.</p> <pre><code>...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isna.html" rel="nofollow noreferrer"><code>isna()</code></a> to find the blank rows and then use <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer">boolean ...
python|python-3.x|pandas
0
5,409
58,188,704
Unable to import Keras(from TensorFlow 2.0) in PyCharm 2019.2
<p>I have just installed the stable version of TensorFlow 2.0 (released on October 1st 2019) in PyCharm.</p> <p><strong>The problem</strong> is that the <strong>keras package is unavailable</strong>. <a href="https://i.stack.imgur.com/wZfqL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wZfqL.png"...
<p><strong>For PyCharm Users</strong></p> <p>For those who use PyCharm. Install future (EAP) release <code>2019.3 EAP build 193.3793.14</code> from <a href="https://www.jetbrains.com/idea/nextversion/" rel="noreferrer">here</a>. With that, you will be able to use autocomplete for the current stable release of TensorFl...
tensorflow|keras|pycharm|tensorflow2.0|tf.keras
11
5,410
69,211,296
TypeError: unsupported operand type(s) for +: 'int' and 'str' - Pandas DataFrame
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">addition</th> <th style="text-align: center;">add-revised</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">6 insertions(+)</td> <td style="text-align: center;">6</td> </tr> <tr> <td style="text-align: ce...
<p>Did you try:</p> <pre><code>df_new['add-revised'] = df_new['add-revised'].astype(int) </code></pre> <p>it works for pandas version '1.2.0'</p>
python|pandas|dataframe
1
5,411
44,416,354
how to save a DNN model with tensorflow
<p>I have code that trains a DNN network. I don't want to train this network every time, because it uses too much time. How can I save the model?</p> <pre><code>def train_model(filename, validation_ratio=0.): # define model to be trained columns = [tf.contrib.layers.real_valued_column(str(col), ...
<p>I believe this has already been answered here: <a href="https://stackoverflow.com/questions/33759623/tensorflow-how-to-save-restore-a-model?rq=1">Tensorflow: how to save/restore a model?</a></p> <pre><code>saver = tf.train.Saver() saver.save(sess, 'my_test_model',global_step=1000) </code></pre> <p>(code copied fro...
python|tensorflow|dotnetnuke
1
5,412
61,086,228
How do I remove a specific value from a row in a pandas dataframe?
<p>I have a pandas dataframe that looks something like this:</p> <pre><code> Column1 Column2 Column3 0 1 NaN NaN 1 4 NaN NaN 2 NaN 3 NaN 3 NaN 98 NaN 4 NaN NaN 562 5 NaN NaN 742 . . . </code></pre> <p>How would I go about removing all of the unnecessary NaNs and make it look like this</p...
<p>Run:</p> <pre><code>df.apply(lambda col: col.dropna().reset_index(drop=True).astype(int)) </code></pre> <p>Just apply to each column a function, which drops <em>NaN</em> values in this column. Due to presence of <em>NaN</em> values column are generally of <em>float</em> type, but I attempt to cast them to <em>int<...
python|pandas
2
5,413
60,792,766
How to fill the area with in Matplotlib
<p>I need to fill the area between y1 and y but but I don't understand how to limit the area under y2</p> <pre><code>import numpy as np import matplotlib.pyplot as plt y = lambda z: (4 * z - z ** 2) ** (1 / 2) y1 = lambda x: (8 * x - x ** 2) ** (1 / 2) y2 = lambda c: c * 3 ** (1 / 2) x = np.linspace(0, 12, 500) z = n...
<p>Do you want to fill between the minimum of <code>y1, y2</code> and <code>y</code>?</p> <pre><code>miny = np.minimum(y2(x),y1(x)) plt.fill_between(x, y(x), miny, where=(miny&gt;=y(x)), alpha=0.5) plt.legend() plt.show() </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/JdDxM.png" rel="nofollow no...
python|numpy|matplotlib|math|plot
2
5,414
61,162,881
Pivoting dataframes with pd.melt() on time series data
<p>I have some data here:</p> <pre><code> Country/Region 1/22/20 1/23/20 1/24/20 1/25/20 1/26/20 1/27/20 0 Afghanistan 0 0 0 0 0 1 Albania 0 0 0 0 0 2 Algeria 0 0 ...
<p>You are looking to transpose the table:</p> <pre><code>df.set_index('Country/Region').T </code></pre> <p>I noticed that <code>Australia</code> was repeated multiple times, if you want to consolidate by adding them up:</p> <pre><code>df.set_index('Country/Region').T \ .groupby(level=0, axis=1) \ .sum() </c...
python|pandas|time-series|pivot|melt
2
5,415
71,605,903
Filtering string in column (counts of string) plus average of second column
<p>Looking for a way to filter a column &quot;Role&quot; for counts of string and get an average of 2nd col &quot;Rank&quot; for these values. I tried value counts and string.contains but do not know how to bring this together.</p> <pre><code>import pandas as pd data = {'Role':['Big, Big, Guard, Guard, Forward', 'Big, ...
<p>Not exactly the same output format, but if what you are looking for is the <code>Rank/avg</code>, maybe that helps you:</p> <pre class="lang-py prettyprint-override"><code>data = {'Role':['Big, Big, Guard, Guard, Forward', 'Big, Big, Guard, Guard, Forward', 'Big, Guard, Big, Guard, Guard', 'Big, Big, Guard, Forward,...
python|pandas
0
5,416
69,842,813
pandas read_xml missing data
<p>I have tried using Pandas read_xml and it reads most of the XML fine but it leaves some parts out because its in a slightly different format. I have included an extract below and it reads &quot;Type&quot;, &quot;Activation&quot; fine but doesn't for the &quot;Amt&quot; value. It picks up the column heading &quot;Amt...
<p>By default, <a href="https://pandas.pydata.org/docs/dev/reference/api/pandas.read_xml.html" rel="nofollow noreferrer"><code>pandas.read_xml</code></a> parses all the <em>immediate</em> descendants of a set of nodes including its child nodes and attributes. Unless, the <code>xpath</code> argument indicates it, <code>...
python|pandas|xml|readxml
1
5,417
43,036,982
Receiving strange permission errors when trying to install tensorflow
<p>I apologize if this is trivial. I'm not too comfortable with running commands in linux so i'm having trouble debugging the issues below. I am just following the installation process <a href="https://www.tensorflow.org/install/install_mac#installing_with_anaconda" rel="nofollow noreferrer">here.</a> </p> <pre><code>...
<p>It looks like you're not using the proper permissions. </p> <p>Try <code>sudo pip install</code></p>
python|linux|permissions|tensorflow|anaconda
3
5,418
43,373,171
How to remove automated chart titles generated by Pandas
<p>I generated a boxplot using below code:</p> <pre><code>import pandas as pd import random country = ['A' for z in range(1,6)] + [ 'B' for z in range(1,6)] sales = [random.random() for z in range(1,11)] data =pd.DataFrame({'country':country, 'sales':sales}) bp=data.boxplot(by='country') </code></pre> <p><a href="h...
<p>You also need to get rid of the title on the axes via:</p> <p><code>bp.get_figure().gca().set_title("")</code></p> <p>and if you want to get rid of the [country] part too:</p> <p><code>bp.get_figure().gca().set_xlabel("")</code></p>
python|pandas|matplotlib|jupyter-notebook
11
5,419
72,268,382
Join 2 data frame with special columns matching new
<p>i want to join two Dataframe and get result as bellow, i tried many ways but it fails</p> <p>i want only texts on df2 ['A'] which contain text on df1 ['A']. please help me change the codes</p> <p>I wanted :</p> <pre><code>0 A0_link0 1 A1_link1 2 A2_link2 3 A3_link3 </code></pre> <pre><code>import pandas as pd df...
<p>Create an intermediate dataframe and <code>map</code>:</p> <pre><code>d = (df2.assign(key=df2['A'].str.extract(r'([^_]+)')) .set_index('key')) df1['A'].map(d['A']) </code></pre> <p>Output:</p> <pre><code>0 A0_link0 1 A1_link1 2 A2_link2 3 A3_link3 Name: A, dtype: object </code></pre> <p>Or <code>me...
pandas
0
5,420
72,321,110
Pick a column value based on column index stored in another column (Pandas)
<p>Let's say we have four columns: Column1, Column2, Column3, ind</p> <pre><code>import pandas as pd tbl = { 'Column1':['Spark',10000,'Python','35days'], 'Column2' :[500,'PySpark',22000,30000], 'Column3':['30days','40days','35days','pandas'], 'ind':[1,2,1,3] } df = pd.DataFrame...
<p>IIUC, you can try <code>apply</code> on rows</p> <pre class="lang-py prettyprint-override"><code>df['Course'] = df.apply(lambda row: row.iloc[row['ind']-1], axis=1) </code></pre> <p>Or you can try</p> <pre class="lang-py prettyprint-override"><code>df['Course'] = df.values[np.arange(len(df['ind'])), df['ind'].sub(1)...
python|pandas
0
5,421
72,447,242
Compare two dataframes with different shapes and with condition in python
<p>I have two dataframes in python</p> <p>First dataframe : <strong>tf_words</strong> : of <strong>shape (1 row,2235 columns)</strong> : looks like-</p> <pre><code> 0 1 2 3 4 5 6 ...... 2234 0 aa, aaa, aaaa, aaan, aaanu, aada, aadhyam,.....zindabad] </code></pre> <p>Second dataframe : ...
<p>try this</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd table = { 'a, en':[1,0,0], 'a, ha':[0,1,0], 'a, padam':[0,0,1], 'aa, aala' :[1,0,0], 'aaa, accountinte':[0,1,0], 'aaaa,adhamanaya':[0,0,1], 'aaab,adhamanaya':[0,0,1] } tf1_bigram = pd.DataFrame(tab...
python|pandas|dataframe|compare
0
5,422
72,178,306
How to Merge two Panel data sets on Date and a combination of columns?
<p>I have two datasets, <code>df1</code> &amp;<code>df2</code>, that look like this:</p> <p><code>df1</code>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Code</th> <th>City</th> <th>State</th> <th>Population</th> <th>Cases</th> <th>Deaths</th> </tr> </thead> <tbody> <tr> <...
<p>It sounds like you're looking for the <code>how</code> keyword argument in <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html?highlight=how%20outer" rel="nofollow noreferrer"><code>pd.DataFrame.merge</code></a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame....
python|pandas|dataframe|merge
1
5,423
50,485,174
Get Row Position instead of Row Index from iterrows() in Pandas
<p>I'm new to stackoverflow and I have research but have not find a satisfying answer.</p> <p>I understand that I can get a row index by using df.iterrows() to iterate through a df. But what if I want to get a row position instead of row idx. What method can I use? </p> <p>Example code that I'm working on is below: <...
<p>If you need row number instead of index, you should:</p> <ol> <li>Use <code>enumerate</code> for a counter within a loop.</li> <li>Don't extract the index, see options below.</li> </ol> <p><strong>Option 1</strong></p> <p>In most situations, for performance reasons you should try and use <code>df.itertuples</code...
python|python-3.x|pandas|for-loop
8
5,424
62,841,529
Using unique values of column as higher level column pandas
<p>Imagine I have a pandas dataframe as the following:</p> <pre><code>Side Year Value 1 Value 2 A 2020 56 5% B 2019 24 3% B 2018 42 4% B 2020 414 31% A 2019 421 51% </code></pre> <p>I would like to have something like this:</p> <pr...
<p>You can use a combination of <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer">set index</a>, along with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html" rel="nofollow noreferrer">unstack</a...
python|pandas
2
5,425
62,859,627
Image processing: counting individual number pixel in an mask image using Pillow and 3D Numpy
<p>Please help me. I need some opinion on this problem. <strong>I am trying to count individual number of R,G,B value of an mask image.</strong></p> <p>I have an image which is masked filled background with green and it mask a human with red and an object with blue.</p> <p><em><strong>The image size and data type are</...
<pre><code>from PIL import Image with Image.open('hopper.jpg') as im: px = im.load() r, g, b = px[x, y] print(r, g, b) </code></pre> <p>This code worked for me. <strong>x</strong> and <strong>y</strong> pixel cordinates. You can get full info from <a href="https://pillow.readthedocs.io/en/stable/reference/PixelAcc...
python|numpy|image-processing|computer-vision|python-imaging-library
0
5,426
62,890,245
implementation of multiple if else condition in pandas data frame
<p>My data frame is -</p> <pre><code>id score 1 50 2 88 3 44 4 77 5 93 </code></pre> <p>I want my data frame looks like -</p> <pre><code>id score is_good 1 50 low 2 88 high 3 44 low 4 77 medium ...
<p>This is a good use case for <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html" rel="nofollow noreferrer"><code>pd.cut</code></a>:</p> <pre><code>df['is_good'] = pd.cut(df.score, [-np.inf,50,80,np.inf], labels=['low','medium','high']) <...
python|pandas|pandas-groupby
6
5,427
62,822,458
Simplest or most Pythonic way to exclude rows in a DataFrame based on a list of regex patterns?
<p>I know I can exclude rows like so:</p> <pre><code>df = df[ ~df['B'].str.contains(&lt;regex_pattern&gt;) ] </code></pre> <p>But what is the simplest or most Pythonic way to exclude rows from a list of regex patterns? Something like the following would be fine:</p> <pre><code>df = exclude_rows(dataframe, list_of_regex...
<pre><code>def drop_from_patterns(dataframe, column, regex_pattern_list): dfcopy = dataframe.copy() for pattern in regex_pattern_list: dfcopy.drop(dfcopy[ dfcopy[column].str.contains(pattern, case=False) ].index, inplace=True) return dfcopy </code></pre>
python|pandas
0
5,428
54,565,811
Why python script doesn't print to console or can't debug using pdb in Ubuntu
<p>I am looking into this <a href="https://github.com/opencv/training_toolbox_tensorflow" rel="nofollow noreferrer">code</a>.</p> <p>For training lpr, we can use <a href="https://github.com/opencv/training_toolbox_tensorflow/blob/develop/training_toolbox/lpr/train.py" rel="nofollow noreferrer">train.py</a> in lpr fold...
<p>I recommend the following: </p> <p>wherever you want to debug, put this: </p> <pre><code>import ipdb ipdb.set_trace() </code></pre> <p>Then on the ipython console, make an instance of your class, and the call the method you need to debug, it will stop in your trace </p>
python|python-3.x|tensorflow|python-3.5
0
5,429
54,451,127
Creating a HeatMap from a Pandas MultiIndex Series
<p>I have a Pandas DF and I need to create a Heatmap. My data looks like this and I'd like to put the Years in Columns, the Days in rows and then use that with Seaborn to create a heatmap</p> <p>I tried multiple ways but I was always getting "inconsistent shape" when I chose the DF, so any recommendation on how to tra...
<p>If you have a DataFrame like this:</p> <pre><code>years = range(2016,2019) months = range(1,6) df = pd.DataFrame(index=pd.MultiIndex.from_product([years,months])) df['vals'] = np.random.random(size=len(df)) </code></pre> <p>You can reformat the data to a rectangular shape using:</p> <pre><code>df2 = df.reset_ind...
python|pandas|seaborn
7
5,430
73,725,267
Pandas lookup to update value by refereeing col and row with 2 data frames
<p>I've a df 1 and df2 like below and need to lookup the part and week column value from df2 and update the qty value in df1 .. Initially I've tried using melt function to change weeks as col and used merge function to join them but when i do pivot to get back to same as df1 with updated value it says grouper is not 1 ...
<p>Pivot the 2nd dataframe, then concatenate with the first dataframe, and finally get the sum by grouping the <code>Part</code> column. You can <code>reset_index()</code> at last if you want to</p> <pre class="lang-py prettyprint-override"><code>(pd.concat([ df2 .pivot('ITM_NO', 'WEEK', 'QTY') .reset_index...
python|pandas|dataframe
1
5,431
73,718,365
How to group the dataframe with a list column in Python
<p>I have a data frame like this:</p> <pre><code>l1 = [1,2,3,1,2,3] l2 = ['A','A','A','B','B','B'] values = [['Ram', 'Ford', 'Honda', 'Ford'],['Ford', 'Toyota', 'Subaru'],['Ford', 'Ram'],['Volvo', 'Honda', 'Ford'],['Honda', 'Ford', 'Toyota', 'Ford'],['Ram', 'Ford']] d = {'ID': l1, 'Group': l2, 'Values': values} df...
<p>First <code>explode</code> the column with the lists, then <code>groupby.size</code> to get the number wanted and <code>unstack</code> to get the shape wanted.</p> <pre><code>res = ( df.explode('Values') .groupby(['Group','Values','ID']).size() .unstack('ID',fill_value=0) .reset_index() # if ne...
python|python-3.x|pandas|dataframe
2
5,432
71,216,795
Calculate sum for column in dataframe using pandas
<p>I need to get sum of positive values as one value and sum of negative values as one values of a column in dataframe. for eg:-</p> <pre><code>date | amount 2021-09-02 | 98.3 2021-08-25 | -23.4 2021-08-14 | 34.57 2021-07-30 | -87.9 </code></pre> <p>then i need (98.3+34.57) and (-23.4-87.9) as output</p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.clip.html" rel="nofollow noreferrer"><code>Series.clip</code></a> with <code>sum</code>:</p> <pre><code>pos = df['amount'].clip(lower=0).sum() neg = df['amount'].clip(upper=0).sum() print (pos) 132.87 print (neg) -111.3 </code></pre...
python|pandas|dataframe|sum|output
3
5,433
71,393,426
How to place comma on interval value
<p>Here's my dataset</p> <pre><code>Id Longitude 1 923237487 2 102237487 3 934237487 4 103423787 </code></pre> <p>What I did</p> <pre><code>df['Longitude'] = df['Longitude'].str.replace('\.', '', regex=True) df['Longitude'] = (df['Longitude'].str[:3] + '.' + df['Longitude'].str[3:]).astype(float) </code></pre> <p>T...
<p>IIUC, you could use a regex to find the leading numbers in the range 80-160:</p> <pre><code>df['Longitude2'] = (df['Longitude'].astype(str) .str.replace(r'(^(?:1[0-5]|[8-9])[0-9])', r'\1.') .astype(float) ) </code></pre> <p>output:</p> <pre><code> Id Long...
python|pandas
3
5,434
71,113,051
Convert the date format from MM/DD/YYYY to YYYY-MM-DDT00:00:00.000Z in a list of dictionaries
<p>I want to add my own data in a sample HTML chart. The javascript codes of the sample data is:</p> <pre><code>var data = []; var visits = 10; for (var i = 1; i &lt; 50000; i++) { visits += Math.round((Math.random() &lt; 0.5 ? 1 : -1) * Math.random() * 10); data.push({ date: new Date(2018, 0, i), v...
<p>I solved it by:</p> <pre><code>rnow = dfrnow.to_dict('records') def new_date(date): return datetime.strptime(date, '%m/%d/%Y').strftime('%Y-%m-%dT00:00:00Z') for i in range (len(rnow)): rnow[i]['date'] = new_date(rnow[i]['date']) </code></pre>
javascript|python|pandas|date|charts
0
5,435
52,199,843
How to check that the values of Tensor is contained in other tensor?
<p>I have a problem about finding a value from other tensor</p> <p>It's similar to the following problem : (URL: <a href="https://stackoverflow.com/questions/52102706/how-to-find-a-value-in-tensor-from-other-tensor-in-tensorflow/52107710?noredirect=1#comment91348123_52107710">How to find a value in tensor from other t...
<p>This perhaps works. Since this is a complex task, try more examples and see if expected results are obtained.</p> <pre><code>import tensorflow as tf s_idx = [1, 3, 5, 7] e_idx = [3, 4, 5, 8] label_s_idx = [2, 2, 3, 6] label_e_idx = [2, 3, 4, 8] label_score = [1, 3, 2, 3] # convert to one-hot vector. # make sure ...
python|tensorflow
1
5,436
60,529,092
Is there a way to produce a count of multiple categories over a resampled date indexed pandas dataframe?
<p>I have a dataframe, indexed by date, containing information about the magnitude of floods - none, small, medium and large which are represented numerically by 0,1,2 and 3 respectively, see below (edited product of df.head(15).to_dict()):</p> <pre><code> date flood 2001-01-01 0.0 2001-01-02 0.0 2001-01-03...
<pre><code># convert date column to datetime format (assuming it isn't already) df['date'] = pd.to_datetime(df['date'], dayfirst=True) # set all days to 1 df['date'] = df['date'].apply(lambda dt: dt.replace(day=1)) # count using pivot table: result = pd.pivot_table(df, index='date', columns='flood', aggfunc=len) prin...
python|pandas
0
5,437
60,476,943
PyTorch LSTM has nan for MSELoss
<p>My model is:</p> <pre><code>class BaselineModel(nn.Module): def __init__(self, feature_dim=5, hidden_size=5, num_layers=2, batch_size=32): super(BaselineModel, self).__init__() self.num_layers = num_layers self.hidden_size = hidden_size self.lstm = nn.LSTM(input_size=feature_dim...
<p>I suspect your issue has to do with your outputs / <code>data[1]</code> (it would help if you show examples of your train_set). Running the following piece of code gives no nan, but I forced shape of output by hand before calling the <code>loss_fn(pred, outputs)</code> :</p> <pre><code>class BaselineModel(nn.Module...
python|pytorch|lstm|gradient-descent
2
5,438
72,521,988
Survey data Cleaning - Grouping Age range - Python pandas
<p>I have this data set with the following values counts for the column <code>Age</code>:</p> <pre><code>&gt;&gt;&gt; game['Age'].value_counts() Between 18 -25 131 Between 26 - 30 21 Under 18 10 31 or more 7 Name: Age, dtype: int64 </code></pre> <p>I´m trying <strong>to create a regrouping...
<p>You can use <code>np.select</code>:</p> <pre><code>mapping = { 'Between 18 -25': '&lt;=25', 'Under 18': '&lt;=25', 'Between 26 - 30': '&gt;=26', '31 or more': '&gt;=26', } df['Age'] = np.select([df['Age'] == k for k in mapping.keys()], mapping.values()) </code></pre> <p>Or just use <code>.loc</code>...
python|pandas|survey
0
5,439
59,896,902
numpy (n, m) and (n, k) to (n, m, k)
<p>Let <code>x</code> be a <code>np.array</code> of shape <code>(n, m)</code>.</p> <p>Let <code>y</code> be a <code>np.array</code> of shape <code>(n, k)</code>.</p> <p>What is the right way of computing the tensor <code>z</code> of shape <code>(n, m, k)</code> such that </p> <pre><code>for all i in [0, n - 1] z[i] ...
<p>You could use <code>np.einsum()</code> like this:</p> <pre><code>z = np.einsum('ij,ik-&gt;ijk', x, y) </code></pre> <hr> <p>From a quick test, this is also faster than the <code>np.matmul()</code>-based approach (except than for very small inputs):</p> <pre><code>import numpy as np x = np.random.randint(1, 100...
numpy|linear-algebra|tensor
2
5,440
59,775,656
Count number of different rows in which each word appears
<p>I have a Pandas DataFrame (or a Series, given that I'm just using one column) that contains strings. I also have a list of words. For each word in this list, I want to check how many different rows it appears in at least once. For example:</p> <pre><code>words = ['hi', 'bye', 'foo', 'bar'] df = pd.Series(["hi hi hi...
<p>Try list comprehension and <code>str.contains</code> and <code>sum</code></p> <pre><code>df_out = pd.DataFrame([[word, sum(df.str.contains(word))] for word in words], columns=['word', 'word_count']) Out[58]: word word_count 0 hi 3 1 bye 3 2 foo 3 3 bar ...
python|pandas|optimization
2
5,441
59,577,442
Numpy vectorization messes up data type
<p>When using <code>pandas</code> dataframes, it's a common situation to create a column <code>B</code> with the information in column <code>A</code>.</p> <h1>Background</h1> <p>In some cases, it's possible to do this in one go (<code>df['B'] = df['A'] + 4</code>), but in others, the operation is more complex and a sep...
<p>Have you consider passing the day as <code>int</code> instead of the <code>datetime64[ns]</code>?</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np # I'd avoid use dt as it's used as alias for datetime def is_past_midmonth1(d): return (d.day &gt; 15) def is_past_midmo...
python|pandas|numpy
3
5,442
32,176,542
Sometimes get a dataframe returned instead of a Series
<p>I have a looping structure in one class that retrieves rows from a dataframe within another class. The rows are retrieved one by one which means they are returned as a Series. I then perform several operations on the Series and then update the original dataframe row with the changes.</p> <p>All of this works fine 9...
<p><code>df.loc[rowname]</code> would return a DataFrame, if rowname is a list , instead of being a single element. Example -</p> <pre><code>In [14]: df Out[14]: A B 0 1 3 1 2 4 2 3 5 3 4 5 In [15]: df.loc[0] Out[15]: A 1 B 3 Name: 0, dtype: int64 In [16]: type(df.loc[0]) Out[16]: pandas.core.serie...
python|pandas
1
5,443
18,708,642
Unexpected eigenvectors in numPy
<p>I have seen <a href="https://stackoverflow.com/questions/13739186/compute-eigenvector-using-a-dominant-eigenvalue">this</a> question, and it is relevant to my attempt to compute the dominant eigenvector in Python with numPy.</p> <p>I am trying to compute the dominant eigenvector of an n x n matrix without having to...
<p>You are just misinterpreting <code>eig</code>'s return. According to the docs, the second return argument is</p> <blockquote> <p>The normalized (unit “length”) eigenvectors, such that the column v[:,i] is the eigenvector corresponding to the eigenvalue w[i].</p> </blockquote> <p>So the eigenvector correspondin...
python|numpy|linear-algebra|eigenvector
9
5,444
61,708,442
how to keep pytorch model in redis cache to access model faster for video streaming?
<p>I have this code belonging to <code>feature_extractor.py</code> which is a part of this folder in <a href="https://github.com/masouduut94/deep_sort_pytorch/tree/master/deep_sort/deep" rel="noreferrer">here</a>:</p> <pre><code>import torch import torchvision.transforms as transforms import numpy as np import cv2 fro...
<p>If you only need to keep model state on RAM, Redis is not necessary. You could instead mount RAM as a virtual disk and store model state there. Check out <code>tmpfs</code>.</p>
python|caching|redis|video-streaming|pytorch
2
5,445
61,660,815
Conflict between thousand separator and date format - pandas.read_csv
<p>I have a problem with reading data from csv file with Pythons' read_csv method.</p> <p>Row format: </p> <pre><code>'06.02.2013;544,00;2,52;3,53' </code></pre> <p>With this implementation: </p> <pre><code> df = pd.read_csv(filepath, sep=";", header=5, decimal=",") df['value'] = df['value'].astype(int) </code></p...
<p>Are you indicating you header row correctly?</p> <p>Here's a sample CSV:</p> <pre><code>cat seven_rows.csv 0 1 2 3 4 Datum;value1;value2...
python-3.x|pandas|csv|dataframe
1
5,446
61,743,727
Summing two values from different dataframes if certain criteria is matched python
<p>I would like to sum two columns, each in different frame if certain criteria is met.</p> <p>Dataframe 1:</p> <pre><code>desk Type total_position desk1 ES 786.0 desk1 ES1 100 desk2 ES1 0 desk2 ES2 10 desk3 ES 0 desk4 ES1 0 desk5 ES -757 </code></pre> <p>Dataframe 2:</p> ...
<p>I would <code>map</code> and then <code>add</code>:</p> <pre><code>df1['total_position'] = (df1['total_position'].add( df1['desk'].map(df2.set_index('desk')['total_position'])) print(df1) </code></pre> <hr> <pre><code> desk Type total_position 0 desk1 ES 28.0 1 desk2 ES1 ...
python|pandas|numpy
3
5,447
62,028,664
Drop_duplicates fails to drop exact match?
<p>I am scanning for duplicate rows in imported data and I am using pd.duplicated &amp; pd.drop_duplicates to find &amp; drop duplicate rows. I have a set of rows which seem to be exact duplicates. Previously the columns were in a different order, but I merged the data &amp; the problem persists.</p> <p><strong>EDIT:<...
<p>Is there any similar rows in your dataframe, if not duplicated method return true for the second occurrence for the same rows for exp:</p> <pre><code>df = pd.DataFrame([[1,2,3],[2,3,4],[3,4,5],[1,2,3]],columns = ["a","b","c"]) df.duplicated() 0 False 1 False 2 False 3 True dtype: bool </code></pre> ...
python|pandas|dataframe
2
5,448
58,122,871
How to use tensorflow model to train and predict mouse movement?
<pre><code>&lt;html&gt; &lt;body id='body'&gt; &lt;button onclick="StartData(event)"&gt; Start&lt;/button&gt; &lt;button onclick="getStopCordinates(event)"&gt;Stop&lt;/button&gt; &lt;script&gt; let inputs = []; let labels = []; function Mouse(event) { inputs.push({ x: eve...
<p>The inputs and labels should be an array of array and not an array of object. The inputs should rather be </p> <pre><code> [[1, 2], [4, 6], ...] </code></pre> <p>The same thing holds for the labels.</p> <p>Since your are predicting 2 values, the last layer should have as number of units 2</p> <pre><code> const m...
javascript|tensorflow|machine-learning|deep-learning|tensorflow.js
0
5,449
57,843,272
Add scatterplot with different colors and size based on volume?
<p>I want to create a scatterplot with matplotlib and a simple pandas dataframe. Have tested almost everything and nothing works and honestly I have just now ordered a book on matplotlib.</p> <p>Dataframe looks like this</p> <pre><code> Time Type Price Volume 0 03:03:26.936 B 1.61797 ...
<p>A solution using just <code>matplotlib</code>:</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter # Your Time column is stored as strings. Convert them to Timestamp # so matplotlib can plot a proper timeline times = pd.to_datetime(df['Time']) # Set the marker's color: 'B' is...
python|pandas|matplotlib
2
5,450
57,757,871
Create frequency Tables for all the categorical variables of a dataframe in python
<p>I have a data-frame that has columns containing both continuous and categorical variables. I want to create frequency table for all the categorical variables using pandas.</p> <p>I have used <code>.value_counts()</code> function to generate the table, but it is giving me a list.</p> <h1>This code returns a list</h1>...
<p>try this</p> <pre><code># Frequency tables for each categorical feature for column in data.select_dtypes(include=['object']).columns: display(pd.crosstab(index=data[column], columns='% observations', normalize='columns')*100) </code></pre>
python|pandas
1
5,451
57,849,420
Convert nan to Zero when numpy dtype is "object"
<p>I have a numpy array that contains nan. I attempted to convert those nans to zeros using </p> <pre><code> X_ = np.nan_to_num(X_, copy = False) </code></pre> <p>but it didn't work. I suspect its because dtype of X_ is object. I attempted to convert that to float64 using </p> <pre><code>X_= X_.astype(np.float64) </...
<p>The &quot;object&quot; dtype was causing me a problem too. But your <code>astype(np.float64)</code> actually did work for me. Thanks!</p> <pre><code>print(&quot;Creating a numpy array from a mixed type DataFrame can create an 'object' numpy array dtype:&quot;) A = np.array([1., 2., 3., np.nan]); print('A:', A, A.dty...
python|numpy|nan|dtype
0
5,452
34,108,134
Finding unique elements in cells of pandas DF and expanding DF to include columns with the names of those unique elements
<p>I have a DF that looks like this:</p> <p><a href="https://i.stack.imgur.com/zjLD8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zjLD8.png" alt="enter image description here"></a></p> <p>I want to create a new DF, let's say instrumentsDF, in some sort of vectorized form so I get something like...
<p>Pandas has the <code>get_dummies</code> function:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; data = pd.DataFrame({'instrument': ['Piano', 'Piano', 'Guitar', 'Viola', 'Viola', 'Guitar']}) &gt;&gt;&gt; pd.get_dummies(data['instrument']) instrument_Guitar instrument_Piano instrument_Viola 0 ...
python|pandas|split
1
5,453
54,833,076
Tensorflow model from very 1st tutorial doesnt work like expected
<p>Trying to start learning tensorflow by tutorials. Started with 1st one (of course) and for some reason when I try to learn model it shows loss number between 10 and 12 and accuracy number is 0.2 and 0.3 but in tutorial numbers are very different. Before I had some troubles installing tensorflow, as I tried to make g...
<blockquote> <p>Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA This is just a warning, stating that you can compile from source and be able to use it.</p> </blockquote> <p>As for your model, it's ok, but if you normalize inputs, you'll get 70% accur...
tensorflow|archlinux|python-3.7
1
5,454
55,035,424
Apply function to a range of specific rows
<p>I have the following dataframe <code>df</code>:</p> <pre><code> bucket_value is_new_bucket dates 2019-03-07 0 1 2019-03-08 1 0 2019-03-09 2 0 2019-03-10 3 0 2019-03-11 ...
<p>Using <code>cumsum</code> with <code>filter</code> </p> <pre><code>df.reset_index(inplace=True) s=df.loc[df.is_new_bucket==0].groupby(df.is_new_bucket.cumsum()).agg({'date':'first','bucket_value':['mean','max']}) s date bucket_value first mean max is_new_bucket ...
python|pandas|dataframe
2
5,455
54,701,681
String to n*n matrix in python
<p>I am an undergraduate student who loves programming. I encountered a problem today and I don't know how to solve this problem. I looked for "Python - string to matrix representation" (<a href="https://stackoverflow.com/questions/31877901/python-string-to-matrix-representation">Python - string to matrix representati...
<p>Assuming you don't want <code>numpy</code> and want to use a list of lists:</p> <pre><code>def string_to_matrix(str_in): nums = str_in.split() n = int(len(nums) ** 0.5) return list(map(list, zip(*[map(int, nums)] * n))) </code></pre> <p><code>nums = str_in.split()</code> splits by any whitespace, <code...
python|python-3.x|numpy
2
5,456
49,409,350
Element in a series takes on a different value when assigned to a dataframe
<p>I am really puzzled by this... I have an existing DataFrame and when I assign a series of values (of the same length) to a new column somehow the last element in the series takes on a different value when in the DataFrame. This code</p> <pre><code> print('Standalone 2nd to last: ' + series.iloc[-2]) print('S...
<p>Per @emmet02 comment, the index of the data frame was different from the one in the series and hence they did not align perfectly</p>
python|pandas
0
5,457
28,073,651
Link C++ program output with Python script
<p>I have a C++ program that uses some very specific method to calculate pairwise distances for a data set (30,000 elements). The output file would be 20 GB, and look something like this:</p> <pre> point1, point2, distancex pointi, pointj, distancexx ..... </pre> <p>I then input the file to Python and use Python (Num...
<p>I assume you have been saving ascii. You could modify your C++ code to write binary instead, and read it with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html" rel="nofollow">numpy.fromfile</a>.</p> <p>For a more direct connection, you would wrap your C++ code as a library (remove ma...
python|c++|numpy|swig|boost-python
0
5,458
73,295,865
what is the correct way of splitting dataset into train, validation and test?
<p>I'm following an <a href="https://vijayabhaskar96.medium.com/tutorial-image-classification-with-keras-flow-from-directory-and-generators-95f75ebe5720" rel="nofollow noreferrer">article</a> which says the test folder should also contain a single folder inside which all the test images are present(there will not be su...
<ol> <li>It looks like <code>Structure 2</code> just splits whatever is available, which is fundamentally correct. In reality, you'll most likely be using <code>Structure 1</code> when using <code>flow_from_directory()</code>. You can't perform <code>evaluate()</code> without labels, so your <code>test_generator</code...
python|image|tensorflow|keras|dataset
2
5,459
73,419,075
Pandas list comparison giving value error
<p>I have a dataframe I generate by using</p> <pre><code>df = qr_actions.get_pandas_df(query) </code></pre> <p>and then generate a list of the rows using <code>rows = [r[1] for r in df.iterrows()]</code> and am trying to compare it to another list of rows I generate using the same method by doing <code>(rows1 == rows2)...
<p>Your <code>rows</code> is a list and a operation <code>rows1 == rows2</code> will return a boolean after which you can't apply <code>all</code> attribute. Converting your rows to <code>pd.Series</code> will solve the issue:</p> <pre><code>rows = pd.Series([r[1] for r in dftest.iterrows()]) </code></pre>
python|pandas|dataframe|debugging
0
5,460
73,297,945
How to get prior close when you have all stocks in a single DF?
<p>Sorry for the noob question. I have a bunch of stocks in a sqlite3 database:</p> <pre><code>import pandas as pd import sqlite3, config connection = sqlite3.connect(config.db_file) connection.row_factory = sqlite3.Row df = pd.read_sql('SELECT * FROM stock_price', connection) # sort the dataframe df.sort_values(by...
<p>How about shift the date and merging, i.e.</p> <pre><code># conversion (if not already datetime) df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d') # help dataframe df_help = df.copy() df_help['date'] = df_help['date'] + pd.Timedelta(1, 'D') # today's close is tomorrow's prev_close df_help.rename(colum...
python|pandas|numpy|stock|ohlc
2
5,461
35,281,427
Fast Python plotting library to draw plots directly on 2D numpy array image buffer?
<p>I often draw 2D plots directly on 2D numpy array image buffer coming from opencv webcam stream using opencv drawing functions. And, I send the numpy array to imshow and video writer to monitor and create a video.</p> <pre><code>import cv2 import numpy as np cap = cv2.VideoCapture(0) ret, frame = cap.read() # fram...
<p>So, if I'm getting this right, you want:</p> <ul> <li>Plot conceptual figures (paths, polygons), with out-of-the-box indicators (axes, enclosing plots automagically) over an image </li> <li>Video dump and <em>hopefully</em> realtime streaming.</li> </ul> <p>If so, I'd recommend using <a href="http://zulko.github.i...
python|opencv|numpy|matplotlib
5
5,462
67,350,600
Pandas Dataframe: how can i compare values in two columns of a row are equal to the ones in the same columns of a subsequent row?
<p>Let's say I have a dataframe like this</p> <pre><code>Fruit Color Weight apple red 50 apple red 75 apple green 45 orange orange 80 orange orange 90 orange red 90 </code></pre> <p>I would like to add a column with True or False according to the fact that Fruit and Color of row x are equal to Frui...
<p>You had the right idea about shifted comparison, but you need to shift backwards so you compare the current row with the next one. Finally use an <code>all</code> condition to enforce that ALL columns are equal in a row:</p> <pre><code>df['Validity'] = df[['Fruit', 'Color']].eq(df[['Fruit', 'Color']].shift(-1)).all(...
python|pandas
5
5,463
67,249,822
In Python, how to find consecutive negative numbers in a row and return column header of first negative number?
<p>I have a <code>DataFrame</code>:</p> <p><code>first_week_of_consecutive_Negatives</code>: <img src="https://i.stack.imgur.com/etZAE.png" alt="df" /></p> <p>This example <code>df</code> I provided is a small part of the whole df, the df continues (each column is a week). I need to find the first week (column name) wh...
<p>Using a simplified version of your <code>df</code>:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'First_Week':np.nan,'2020-12-27':[9,8,-5,0,1,2],'2020-01-03':[9,-2,-1,0,1,1],'2020-01-10':[9,-3,-1,0,1,1],'2020-01-17':[8,-3,-2,0,1,1],'2020-01-24':[8,-4,-3,0,1,1]}) # First_Week 2020-12-27...
python|pandas
2
5,464
67,545,001
Read Excel data from dynamic column using pandas
<p>In my excel file header start from D5 and row star from D6. column data type displayed in D4 cell onwards.</p> <p>i want skip data type row and first blank columns A,B,C and Read Actual excel data using python pandas.</p> <p><a href="https://i.stack.imgur.com/3DlRD.png" rel="nofollow noreferrer"><img src="https://i...
<p>Try my code. so, you can move data table in excel sheet to anywhere.</p> <pre><code>filename = [&quot;yourfile.xlsx&quot;] sheet = [&quot;your sheetname&quot;] df = pd.read_excel(filename, sheet_name=sheet, header=None) # drop the columns and rows with all NaN's df.dropna(axis=0, thresh=2, inplace=True) df.dropna(a...
python|xml|pandas|dataframe|automation
0
5,465
67,219,581
Keras' model.predict() give an output in binary with softmax activation layer
<p>I trained InceptionResNetV2 from Keras with 40 classes and tested it using model.evaluate(); it was all good. But when I try to use model.predict() with a single image, I get an output like</p> <p><code>[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0...
<p>Preprocessing the testing image with the Keras' built-in function helped in my case.</p> <pre><code>from keras.applications.inception_resnet_v2 import preprocess_input img_batch = preprocess_input(img_batch) </code></pre>
python|tensorflow|keras
0
5,466
67,519,746
Pytorch transfer learning error: The size of tensor a (16) must match the size of tensor b (128) at non-singleton dimension 2
<p>Currently, I'm working on an image motion deblurring problem with PyTorch. I have two kinds of images: Blurry images (variable = blur_image) that are the input image and the sharp version of the same images (variable = shar_image), which should be the output. Now I wanted to try out transfer learning, but I can't ge...
<p>Here your you can't use <code>alexnet</code> for this task. becouse output from your model and <code>sharp_image</code> should be shame. because <code>convnet</code> encode your image as enbeddings you and fully connected layers can not convert these images to its normal size you can not use fully connected layers f...
python|image-processing|pytorch|tensor|motion-blur
0
5,467
34,549,187
Pandas DataFrame grouped box plot from aggregated results
<p>I want to draw box plot, but I don't have raw data but aggregated results in Pandas DataFrame. </p> <p>Is it still possible to draw box plot from the aggregated results? </p> <p>If not, what is the closest plot that I can get, to plot the min, max, mean, median, std-dev etc. I know I can plot them using line chart...
<p>While waiting a clarification of your df, related to:</p> <pre><code>dic = [{'cihi': 4.2781254505311281, 'cilo': 1.6164348064249057, 'fliers': array([ 19.69118642, 19.01171604]), 'iqr': 5.1561885723613567, 'mean': 4.9486856766955922, 'med': 2.9472801284780168, 'q1': ...
python|pandas|matplotlib|plot|dataframe
2
5,468
60,213,340
Concatenate a column of lists within a dataframe
<p>I have a dataframe in pandas and one of my columns is a set of lists; however, some of the lists in the column have more elements than others:</p> <pre><code>df['Name'].head() </code></pre> <p>Output: </p> <pre><code>0 ['Andrew', '24'] 1 ['James'] 2 ['Billy', '19', 'M'] 3 ['Grace', '42'] 4 ['Amy'] </code></pre> ...
<p>Pandas offers a method for this, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.join.html" rel="nofollow noreferrer"><code>Series.str.join</code></a>: <code>df['Name'].str.join('')</code>.</p>
python|pandas|list|dataframe
2
5,469
60,104,532
selecting multiple unique columns in pandas
<pre><code>import pandas as pd df = pd.DataFrame({'col1': ['A', 'B', 'C'], 'col2': ['B', 'A', 'A']}) df </code></pre> <p>How would I SELECT DISTINCT col1, col2 from df?</p>
<pre><code>df.drop_duplicates(subset = ['col1','col2']) </code></pre>
python|pandas
1
5,470
60,055,086
Keras: Custom loss function with training data not directly related to model
<p>I am trying to convert my CNN written with tensorflow layers to use the keras api in tensorflow (I am using the keras api provided by TF 1.x), and am having issue writing a custom loss function, to train the model.</p> <p>According to this guide, when defining a loss function it expects the arguments <code>(y_true,...
<p>There is a hack I often use that is to calculate the loss within the model, by means of <code>Lambda</code> layers. (When the loss is independent from the true data, for instance, and the model doesn't really have an output to be compared)</p> <p>In a functional API model:</p> <pre><code>def loss_calc(x): loss...
tensorflow|keras|tf.keras
7
5,471
60,011,128
Plotting choropleth map with discrete colorbar/legend using Geopandas
<p>I am trying to make a choropleth map using Geopandas. However I'm having trouble with the colourbar formatting, it seems to be very limited.</p> <p>Here is the map I have:</p> <p><a href="https://i.stack.imgur.com/FOMNH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FOMNH.png" alt="Map"></a></p...
<p><a href="https://stackoverflow.com/a/56695238/8056865">This answer</a> helped a lot. I was able to use <code>classification_kwds</code> and define my own bins using using the <code>User_Defined</code> <code>scheme</code> argument when calling <code>gpd.plot()</code>. Although I would like more functionality, this is...
matplotlib|colorbar|geopandas|choropleth|legend-properties
2
5,472
65,360,933
"The Conv2D op currently only supports the NHWC tensor format on the CPU" Error despite NHWC Format (YOLO 3)
<p>I am trying to get to run a bit of sample code from <a href="https://github.com/theAIGuysCode/yolo-v3" rel="nofollow noreferrer">github</a> in order to learn Working with Tensorflow 2 and the YOLO Framework. My Laptop has a M1000M Graphics Card and I installed the CUDA Platform from NVIDIA from <a href="https://deve...
<blockquote> <p>If I am understanding this correctly, the format of inputs = tf.compat.v1.placeholder(tf.float32, [batch_size, *_MODEL_SIZE, 3]) is already NHWC (Model Size is a tuple of 2 Numbers) and I don't know how I need to change things in Code to get this running on CPU.</p> </blockquote> <p>Yes you are. But <a ...
tensorflow|keras|tensorflow2.0|yolo
1
5,473
65,416,794
Issue on Runge Kutta Fehlberg algorithm
<p>I have wrote a code for Runge-Kutta 4th order, which works perfectly fine for a system of differential equations:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import matplotlib.pyplot as plt import numba import time start_time = time.clock() @numba.jit() def V(u,t): x1,dx1, x2, dx2=u...
<p>I'm not really sure where your problem lies. Setting the not given parameters to <code>w=1; b=0.1</code> and calling, without changing anything</p> <pre><code>T, X = rkf( f=V, a=0, b=100, x0=[0,0.2,0,0.3], tol=1e-6, hmax=1e1, hmin=1e-16 ) </code></pre> <p>gives the phase plot</p> <p><a href="https://i.stack.imgur.co...
python|numpy|runge-kutta
1
5,474
49,798,944
Not understanding numpy code from a book
<pre><code>X = np.array([[0, 1, 0, 1], [1, 0, 1, 1], [0, 0, 0, 1], [1, 0, 1, 0]]) y = np.array([0, 1, 0, 1]) counts = {} for label in np.unique(y): counts[label] = X[y == label].sum(axis=0) print("Feature counts: ", counts)' </code></pre> <p>This code is meant to check fo...
<p>What you are looking at is a classic group-by operation; which sadly numpy does not provide in an elegant way out of the box. You seem less concerned with a high-level understanding than with a low level understanding; but if the latter is infact not a goal in itself, there are alternatives that abstract these worri...
python|numpy
0
5,475
50,206,517
Pandas .loc taking a very long time
<p>I have a 10 GB csv file with <code>170,000,000</code> rows and <code>23</code> columns that I read in to a dataframe as follows: </p> <pre><code>import pandas as pd d = pd.read_csv(f, dtype = {'tax_id': str}) </code></pre> <p>I also have a list of strings with nearly 20,000 unique elements: </p> <pre><code>h = ...
<p>If your tax numbers are unique, I would recommend setting <code>tax_num</code> to the index and then indexing on that. As it stands, you call <code>isin</code> which is a linear operation. However fast your machine is, it can't do a linear search on 170 million records in a reasonable amount of time.</p> <pre><code...
python|pandas|select|indexing
3
5,476
50,027,783
Numpy array transform using self elements without for loop
<p>I want to transform all elements in a numpy array the following way:</p> <pre><code>x = np.array([1,2,3,6]) ... some transformation y = np.array([1, 0.5, 0.66, 0.5]) </code></pre> <p>Where the rule is:</p> <pre><code>y[i]=x[i]/x[i+1] </code></pre> <p>But I can't use a for loop or while.</p> <p>I don't see how I...
<p>You could try something like this.</p> <pre><code>import numpy as np x = np.array([1,2,3,6]) y = x / np.r_[x[1:],x[0]] print(y) </code></pre> <p>outputs</p> <pre><code>&gt;&gt;&gt; y [0.5 0.66666667 0.5 6. ] </code></pre> <p>Or this might be faster but has the same idea:</p> <pre><code>imp...
python|arrays|numpy
1
5,477
63,813,811
How can I determine the speed of my Tensorflow on my GPU?
<p>I just started with <strong>Tensorflow (Version 2.3.0)</strong> and installed it on my GPU (in an virtual environment using python 3.5). That seems to work fine. I am using a <strong>nvidia geforce 1060</strong> with windows 10.<br /> Now my Question is: How can find the speed of my tensorflow working. I found this ...
<p>I was able to find the full answer in another post which I didn't found earlier:</p> <p><a href="https://stackoverflow.com/questions/61178521/what-is-the-proper-way-to-benchmark-part-of-tensorflow-graph/63591009#63591009">What is the proper way to benchmark part of tensorflow graph?</a></p>
python|python-3.x|performance|tensorflow|tensorflow2.0
0
5,478
63,936,581
How do I create multiple dataframes from a loop based on two existing dataframes and matching creteria?
<p>I think the below code might make my question easier to understand. But I'll try explain what I want to do anyway.</p> <p>I have two dataframes, There is one column common to each. I want the rows from df2 that match based on the values in df1's col 1 to be put in a separate dataframe and loop through df2 until I ha...
<p>Below is a solution provided to me by a colleague in work. A big thank you to him.</p> <p>So, we have two dataframes, with a common columns being Strategy and Style in both (indices and funds). We set the index to the Strategy column values in the indices dataframe. We then create a dictionary of dataframes from the...
python|pandas|dataframe|loops
0
5,479
47,001,413
How to replace 'any strings' with nan in pandas DataFrame using a boolean mask?
<p>I have a 227x4 DataFrame with country names and numerical values to clean (wrangle ?).</p> <p>Here's an abstraction of the DataFrame:</p> <pre><code>import pandas as pd import random import string import numpy as np pdn = pd.DataFrame(["".join([random.choice(string.ascii_letters) for i in range(3)]) for j in range...
<p>Assign only columns of interest:</p> <pre><code>cols = ['Measure1','Measure2'] mask = df[cols].applymap(lambda x: isinstance(x, (int, float))) df[cols] = df[cols].where(mask) print (df) Country Name Measure1 Measure2 0 uFv 7 8 1 vCr 5 NaN 2 qPp 2 ...
python|python-3.x|pandas|numpy|dataframe
13
5,480
32,842,303
Looking up values from one csv-file in another csv-file, using a third csv-file as map
<p>I didn't quite figure how to formulate this question, suggestions to improve the title is welcome.</p> <p>I have three files: <em>e_data.csv</em>, <em>t_data.csv</em> and <em>e2d.csv</em>. I want to merge <code>e_id</code>, <code>t_id</code>, <code>gene_name</code> and <code>value</code> into one file, as represent...
<p>After you load all the csvs using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html#pandas.read_csv" rel="nofollow"><code>read_csv</code></a> you can just iteratively <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#database-style-dataframe-joining-merging" rel="nof...
python|r|csv|numpy|pandas
4
5,481
32,768,555
find the set of column indices for non-zero values in each row in pandas' data frame
<p>Is there a good way to find the set of column indices for non-zero values in each row in pandas' data frame? Do I have to traverse the data frame row-by-row?</p> <p>For example, the data frame is</p> <pre><code>c1 c2 c3 c4 c5 c6 c7 c8 c9 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 ...
<p>It seems you have to traverse the DataFrame by row.</p> <pre><code>cols = df.columns bt = df.apply(lambda x: x &gt; 0) bt.apply(lambda x: list(cols[x.values]), axis=1) </code></pre> <p>and you will get:</p> <pre><code>0 [c1, c2] 1 [c1] 2 ...
python|pandas
12
5,482
32,817,017
Remove numbers from a numpy array
<p>Let us say I have a numpy array of numbers (eg: integers). I want to drop the number <code>k</code> wherever it happens in the sequence. Currently I am writing a for loop for this which seems to be a overkill. Is there a straight forward way to do it? In general, what if I have one more than one number to be dropped...
<p>Assuming <code>A</code> to the input array and <code>B</code> to be the array containing the numbers to be removed, you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html" rel="noreferrer"><code>np.in1d</code></a> to get a mask of matches of <code>B</code> in <code>A</code> and the...
python|arrays|numpy|vectorization
5
5,483
38,796,548
Subtract a vector to each row of a dataframe
<p>My dataframe looks like this : </p> <pre><code>fruits = pd.DataFrame({'orange': [10, 20], 'apple': [30, 40], 'banana': [50, 60]}) apple banana orange 0 30 50 10 1 40 60 20 </code></pre> <p>And I have this vector (its also a dataframe)</p> <pre><code>sold = pd.DataFrame({'orange'...
<p>convert the df to a series using <code>squeeze</code> and pass <code>axis=1</code>:</p> <pre><code>In [6]: fruits.sub(sold.squeeze(), axis=1) Out[6]: apple banana orange 0 28 47 9 1 38 57 19 </code></pre> <p>The conversion is necessary as by design arithmetic operations between d...
python-2.7|pandas|dataframe
4
5,484
38,591,454
How to use ckpt data model into tensorflow iOS example?
<p>I am quiet new to Machine learning, and I am working on iOS app for object detection using tensorflow, I have been using the sample data model that is provided by tensorflow example in the form of .pb (graph.pb) file which works just fine with object detection.</p> <p>But My backend team has given me model2_BN.ckpt...
<p>This one from my backend developer:</p> <pre><code>The .ckpt is the model given by tensorflow which includes all the weights/parameters in the model. The .pb file stores the computational graph. To make tensorflow work we need both the graph and the parameters. There are two ways to get the graph: (1) use th...
ios|machine-learning|tensorflow
2
5,485
38,515,096
module error in multi-node spark job on google cloud cluster
<p>This code runs perfect when I set master to localhost. The problem occurs when I submit on a cluster with two worker nodes. </p> <p>All the machines have same version of python and packages. I have also set the path to point to the desired python version i.e. 3.5.1. when I submit my spark job on the master ssh sess...
<p>Not sure if this qualifies as a solution. I submitted the same job using dataproc on google platform and it worked without any problem. I believe the best way to run jobs on google cluster is via the utilities offered on google platform. The dataproc utility seems to iron out any issues related to the environment.</...
python-3.x|numpy|pyspark|google-cloud-platform
0
5,486
62,945,449
How to plot time series data in plotly?
<p>When I plot my data with just the index the graph looks fine. But when I try to plot it with a datetime object in the x axis, the plot gets messed up. Does anyone know why? I provided the head of my data and also the two plots.</p> <p><a href="https://i.stack.imgur.com/0GkNm.png" rel="nofollow noreferrer"><img src="...
<p>It is probably because of missing dates as you have around 180 data points but your second plot shows data spans from 2014 to 2019 that means it does not have many data points in between that's why your second graph looks like that.</p> <p>Instead of datetime try plotting converting it into string but then it will n...
python|pandas|datetime|plotly|plotly-python
1
5,487
63,103,778
Python: to_csv for decoded dataframe
<p>I have a text file that has encoded strings. I am decoding them using <code>urllib.parse.unquote(string_df.encoded_string)</code> and storing it in a dataframe.</p> <p>I want to export this dataframe to a text file. However, it just adds garbage values.</p> <p>For example: Encoded String: %D1%81%D0%BF%D0%B0%D1%81%D0...
<p>This looks like a character-encoding problem, make sure your CSV file is opened as 'UTF-8' or other compatible encoding, not ASCII, as 'спасо-преображенский собор' are cyrillic and not latin characters.</p>
python|python-3.x|pandas|numpy|decode
1
5,488
67,936,362
How do I look up values in a dataframe and return matching values using python/pandas?
<p>I have 2 large dataframes, df1 and df2. I am missing a column (colB) in df2 and I would like to add that column based of the values in the shared column (colA). If I was using Excel I would do this via a standard vlookup formula but I’m struggling to get the desired results using the pandas merge function.</p> <p>co...
<p>If you are getting more rows after the merge, this means that <code>colA</code> is not a unique key of <code>df_keyvalues</code>. This in turn means that the mapping <code>colA -&gt; colB</code> is not unique in <code>df1</code>, i.e. for at least one value of <code>colA</code> there are multiple values of <code>col...
python|pandas|merge|lookup
1
5,489
31,767,173
How do I vectorize this loop in numpy?
<p>I have this array:</p> <pre><code>arr = np.array([3, 7, 4]) </code></pre> <p>And these boolean indices:</p> <pre><code>cond = np.array([False, True, True]) </code></pre> <p>I want to find the index of the maximum value in the array where the boolean condition is true. So I do:</p> <pre><code>np.ma.array(arr, m...
<p>For your special use case of <code>argmax</code>, you may use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>np.where</code></a> and set the masked values to negative infinity:</p> <pre><code>&gt;&gt;&gt; inf = np.iinfo('i8').max &gt;&gt;&gt; np.where(cond, arr, ...
python|numpy
3
5,490
31,869,257
Python & Pandas: Combine columns into a date
<p>In my <code>dataframe</code>, the time is separated in 3 columns: <code>year</code>, <code>month</code>, <code>day</code>, like this: <a href="https://i.stack.imgur.com/XWL8X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XWL8X.png" alt="enter image description here"></a></p> <p>How can I conver...
<p>Here's how to convert value to time:</p> <pre><code>import datetime df.apply(lambda x:datetime.strptime("{0} {1} {2} 00:00:00".format(x['year'],x['month'], x['day']), "%Y %m %d %H:%M:%S"),axis=1) </code></pre>
python|pandas
9
5,491
31,993,186
type switch from int to float64 after merge creating error
<p>I'm trying to merge two dataframes in Pandas. One of the dataframes has a numerical column whose type is "int64"</p> <p>However, after the merge, the type is switched to "float64" for some reason. Note that this is not my join column</p> <p>When I try to access the dataframe, it errors out:</p> <p>In [56]: accou...
<p>The reason that the dtype is changed to <code>float64</code> is because missing values <code>NaN</code> cannot be represented using integer.</p> <p>With respect to the error message, I had a hunch that it was <code>'display.float_format'</code> as I answered a <a href="https://stackoverflow.com/questions/31983341/u...
python|numpy|pandas
2
5,492
61,554,255
how can i fix this : AttributeError: module 'tensorflow_core.python.keras.api._v2.keras' has no attribute 'Dense'
<p>AttributeError: module 'tensorflow_core.python.keras.api._v2.keras' has no attribute 'Dense' in model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))model.add(tf.keras.Dense(10, activation=tf.nn.softmax)</p>
<p>In your last <code>model.add()</code> call, you try to use <code>tf.keras.Dense</code> instead of <code>tf.keras.layers.Dense</code>. Modify you code to the following:</p> <pre><code> model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) ...
python|tensorflow|keras
3
5,493
61,490,955
Why my callback is not invoking in Tensorflow?
<p>Below is my Tensorflow and Python code which will end the training when accuracy in 99% with the call back function. But the callback is not invoking. Where is the problem ?</p> <pre><code>def train_mnist(): class myCallback(tf.keras.callbacks.Callback): def on_epoc_end(self, epoch,logs={}): ...
<p>Unfortunately don't have enough reputation to provide commentary on one of the above comments, but I wanted to point out that the on_epoch_end function is something called directly through tensorflow when an epoch ends. In this case, we're just implementing it inside a custom python class that will be called automat...
python|tensorflow|machine-learning|keras|deep-learning
0
5,494
61,575,633
Select size for output vector with 1000s of labels
<p>Most of the examples on the Internet regarding <code>multi-label</code> image classification are based on just a <code>few</code> labels. For example, with <code>6</code> classes we get:</p> <pre><code>model = models.Sequential() model.add(layer=base) model.add(layer=layers.Flatten()) model.add(layer=layers.Dense(u...
<p>Resource Exhauseted Error is related to memory issues. Either you don't have enough memory in your system or some other part of the code is causing memory issues.</p>
tensorflow|keras|transfer-learning
0
5,495
61,232,554
Batching in tf.Keras 2.1 -> ValueError: Error when checking input
<p>I have a tf dataset on which I'm trying to implement batching in order to reduce memory load. The model works without batching, but I get OOM errors hence trying out batches.</p> <p><strong>Dataset</strong></p> <pre><code>ds = tf.data.Dataset.from_tensors(( (train_ids, train_masks), labels )) &gt;&gt;&gt;ds &lt;T...
<p>I resolved this problem by not using tensorflow datasets. It's obviously not a perfect fix, but it works for now.</p> <p>With the various inputs and labels as tf tensors, I did:</p> <pre><code>inputs_ids = input_ids.numpy() input_masks = input_masks.numpy() labels = labels.numpy() </code></pre> <p>And then for th...
python|tensorflow|keras
0
5,496
68,766,978
how to convert pandas data frame rows into columns
<p>I have the data frame like</p> <pre><code>df.to_dict('list') </code></pre> <p>output:</p> <pre><code>{'ChannelPartnerID': [10000, 10000, 10000, 10000, 10000, 10001, 10001, 10001, 10002, 10002], 'Brand': ['B1', 'B2', 'B3', 'B4', 'B5', 'B1', 'B2', 'B5', 'B1', 'B4'], 'Sales': [29630, 38573, 1530, 21...
<p>What you want is a called a <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>pivot</code></a>:</p> <pre><code>df.pivot(*df).fillna(0).add_suffix('_Sales') </code></pre> <p>output:</p> <pre><code>Brand B1_Sales B2_Sales B3_Sales B4_Sales...
python|pandas|dataframe|transpose
1
5,497
68,595,777
How to drop the all the 1's in a correlation matrix
<p>I'm trying to change/eliminate the 1's that run diagonally in a correlation matrix so that when I take the average of the rows of the correlation matrix, the 1s don't affect the mean of each of the rows.</p> <p>Let's say I have the dataset,</p> <pre><code> A B C D E F 0 45 100 58 78 80 35 1 49 ...
<p>If you are working with it as a data frame this will work:</p> <pre><code>df=pd.DataFrame({'c1':[1, 0, 0.3, 0.4], 'c2':[0.2, 1, 0.6, 0.4], 'c3':[0.1, 0, 1, 0.4], 'c4':[0.7, 0.2, 0.2, 1]} ) df.where(df!=1).mean(axis=1) </code></pre> <p>This only works correctly if all 1's are on the diagonal.</p>
python|pandas
0
5,498
68,527,072
Pandas group by window range
<p>I have the following data table:</p> <pre><code>values ====== 2.0 2.5 3.2 7.0 7.8 9.0 11.0 </code></pre> <p>I want to extract groups witzhin a certain window, for example</p> <pre><code>window_size = 1.0 </code></pre> <p>All values within this distance should become one group:</p> <pre><code>values group ====== ...
<p>IIUC use <code>diff</code> and <code>cumsum</code>:</p> <pre><code>window_size = 1.0 df[&quot;group&quot;] = df[&quot;values&quot;].diff().abs().gt(window_size).cumsum()+1 print (df) values group 0 2.0 1 1 2.5 1 2 3.2 1 3 7.0 2 4 7.8 2 5 9.0 3 6 11.0 ...
python|pandas|group-by
3
5,499
68,837,404
Fiona not seeing .shp file as a recognised format
<p>All of my unittests pass on my local machine, however when I try to use a .yml file to test them every time a pull request is created, there are several failures. An example of one of the error messages is shown below:</p> <pre><code>_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ &...
<p>Your problem is that the <code>actions/checkout@v2</code> action does not, by default, check out files stored using LFS. So while there is file named, for example, <code>static_data/england_wa_2011_clipped.shp</code> in your repository, the contents are going to look something like this:</p> <pre><code>version https...
python|github-actions|shapefile|geopandas|fiona
1