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
367,200
70,142,904
Even after FIltering the Data from a Dataset, values still can be seen while plotting
<p>I am stuck in this investment analysis spark fund code. I have filtered out by country code where my data is only having only 3 countries. However, when I run a boxplot against it, the entire country list is shown.</p> <pre><code>#Filtering the top 03 Countries where maximum Investments have taken place master_vent...
<p>To don't include the the levels that you filtered out, you have to convert the column to category after filtering the dataframe or you will need to drop the unused levels of your categorical features before plot the graph.</p> <p>The code to do that is:</p> <p><code>master_venture_new.country_code.cat.remove_unused_...
pandas
0
367,201
70,064,608
How to loop over specifc ids in a csv file?
<p>I have a csv file:</p> <pre><code>ids year mean 1 2000 200 2 2000 199 3 2000 193 4 2000 189 1 2001 205 2 2001 197 3 2001 197 4 2001 196 . . . 4 2016 212 </code></pre> <p>I would like to loop over each individual <code>id</code> to calculat...
<p>Note that in</p> <pre><code>for i in range(df['id'].min(), df['id'].max()): x = stats.pearsonr(df['year'], df['mean']) res.append(x) </code></pre> <p>you have <code>i</code>, which is never used in for loop body, so you in fact does compute very same thing again and again. What you need is groupby, consider ...
python|pandas|loops|statistics
2
367,202
70,071,006
Calculate orders time
<p>I have a dataframe with purchase orders, some orders have already expired and they have the time_end field filled in. Other order may be repeated and have the same billing time. Is it possible to somehow calculate how long exactly the applications stood in the interval 10:00:00 - 18:28:00. That is, to find as a perc...
<p>Compute the total interval in seconds:</p> <pre class="lang-py prettyprint-override"><code>interval = (pd.to_datetime('14:40') - pd.to_datetime('13:40')).seconds </code></pre> <p>Find the difference between the two time columns in seconds and divide:</p> <pre class="lang-py prettyprint-override"><code>(df['time_end'...
python|pandas
1
367,203
70,246,194
How can I highlight the largest value(s) in df.plot.barh?
<p>I've got a stacked bar chart that shows the distribution of age groups among NBA teams using colors, the code looks like this:</p> <pre><code>import matplotlib.pyplot as mpl import matplotlib.cm as mcm import pandas as pd import numpy as np from typing import List, Tuple def read_to_df(file_path: str) -&gt; pd.DataF...
<p>Here is a way to do what you want by directly using matplotlib's <code>barh</code> function. The idea is to set up the horizontal stacked bars iteratively and assign the apporiate colors at the same time. Below is an adaptation of the code you provided to perform what I described above:</p> <pre class="lang-py prett...
python|pandas|matplotlib|visualization
2
367,204
70,072,548
Return specific values of a dataframe based on a condition
<p>I have a list like:</p> <pre><code>list_of_list = [[&quot;aa&quot;, &quot;yy&quot;], [&quot;gg&quot;, &quot;xx&quot;]] </code></pre> <p>and a pandas dataframe like this:</p> <pre><code> month column1 column2 0 June xx aa 1 June gg xx 2 August xx y...
<p>Use <code>melt</code> to flat your original dataframe and create a dataframe from your <code>list_of_list</code> then merge them and finally remove duplicates in two pass.</p> <p><strong>Step 1. Format your dataframes</strong></p> <pre><code>df1 = df.melt('month', ignore_index=False).reset_index() df2 = pd.DataFrame...
python|python-3.x|pandas|dataframe
1
367,205
70,032,119
Split at duplicate 0 in Data frame index and save data frames as separate CSVS
<p>I'm looking for a way to split the following example data frame at each duplicate 0 in the index, and then save the info up to the split into a csv.</p> <pre><code>index ID Col1 Col2 0 0 a b 1 1 c d 2 2 e f 0 0 g h 1 1 i j 2 2 k l 0 0 m n 1 1 o ...
<p>Assuming &quot;index&quot; is a column:</p> <pre><code>group = df['index'].eq(0).groupby(df['index']).cumcount() for name, d in df.groupby(group): print(f'dataframe {name}') print(d) # to save: d.to_csv(f'df_{name}.csv') </code></pre> <p>output:</p> <pre><code>dataframe 0 index ID Col1 Col2 0 0 0...
python|pandas
1
367,206
70,240,809
Pandas Indexing Creates ERROR ( Result = self._data[key] ): HEELP
<p>Error when using Pandas and indexing. why? <strong>I even asked Derek Banas and he wasn't sure why didn't work so please help</strong> Errors at bottom in 'quote format'</p> <p><strong>This my code:</strong></p> <pre><code>import numpy as np import pandas as pd from pandas_datareader import data as web import matp...
<p>It seems like a formatting issue.. Change this line</p> <pre class="lang-py prettyprint-override"><code>x = msft.index; close = msft.index['Adj Close'], high = msft['High']; low = msft['Low']; openprice=msft['Open']; </code></pre> <p>to this:</p> <pre class="lang-py prettyprint-override"><code>x = msft.index # THIS ...
python|pandas|eclipse|analytics
0
367,207
70,035,368
Formating string value in dataframe to convert it to html tag
<p>I would like to format every string value in a pandas dataframe column. I was looking in other posts and I found something like:</p> <pre><code>df['Col']=df['Col'].map('${:,.2f}'.format) </code></pre> <p>Let's say the value of every row in that column is &quot;Hello&quot;. Example:</p> <pre><code>A B 1 &quot;Hello...
<pre class="lang-py prettyprint-override"><code>df[&quot;Col&quot;].apply(lambda s: f&quot;&lt;br&gt; &lt;a href={s} title= Link; style='background-color: orange'&gt; Title &lt;/a&gt; &lt;/br&gt;&quot;&quot; </code></pre>
python|html|pandas
1
367,208
70,101,472
ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 33714, 12), found shape=(None, 12)
<p>I am trying to run a simple RNN with some data extracted from a csv file. I have already preprocessed my data and split them into train set and validation set, but I get the error above. This is my network structure and what I tryied so far. My shapes are (33714,12) for x_train, (33714,) for y_train, (3745,12) for x...
<p>Though it will give you a large value, what may be best to do would be to flatten the one with the larger dimension.</p> <p>A tensorflow.keras.layers.Flatten() will basically make your output shape the values multiplied, i.e. input: (None, 5, 5) -&gt; Flatten() -&gt; (None, 25)</p> <p>For your example, this will giv...
python|tensorflow|keras|deep-learning|lstm
0
367,209
70,242,979
How to create list that return the occurences of zeros in a dataframe?
<p>I want to creat list thats counts the iterration of zeros for every same rows in a dataframe.</p> <pre><code> Id_1 Id_2 0 1401 1 1 1401 1 2 1801 0 3 1801 0 4 1801 0 5 1801 0 6 2001 1 7 2001 1 8 2201 0 9 2201 0 # I would like this output: L = [(1801, 4), (22...
<p>You can do the job in one line like this:</p> <pre><code>L = list(df[df['Id_2'] == 0].groupby(['Id_1']).count().to_records()) </code></pre> <p>output:</p> <pre><code>[(1801, 4), (2201, 2)] </code></pre>
python|python-3.x|pandas|list|dataframe
0
367,210
70,281,709
Sampling for large class and augmentation for small classes in each batch
<p>Let's say we have 2 classes one is small and the second is large.</p> <p>I would like to use for data augmentation similar to <code>ImageDataGenerator</code> for the small class, and sampling from each batch, in such a way, that, that each <strong>batch</strong> would be <strong>balanced</strong>. (Fro minor class-...
<p>You can use tf.data.Dataset.from_generator that allows more control on your data generation without loading all your data into RAM.</p> <pre><code>def generator(): i=0 while True : if i%2 == 0: elem = large_class_sample() else : elem =small_class_augmented() yield elem i=i+1 ds= tf....
tensorflow|image-processing|keras|sampling|data-augmentation
1
367,211
70,241,710
Creating a new column based on multiple columns
<p>I'm trying to create a new column based on other columns existing in my <code>df</code>.<br /> My new column, <code>col</code>, should be <code>1</code> if there is at least one <code>1</code> in columns A ~ E.<br /> If all values in columns A ~ E is <code>0</code>, then value of <code>col</code> should be <code>0</...
<p>If need test all columns use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.max.html" rel="nofollow noreferrer"><code>DataFrame.max</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.any.html" rel="nofollow noreferrer"><code>DataFra...
python|pandas
0
367,212
70,224,152
I want to see data from torch.utils.data.DataLoader. How Can I?
<pre class="lang-py prettyprint-override"><code>import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision import torchvision.transforms as transforms train_set = torchvision.datasets.MNIST(root = './data/MNIST',train = True,download = True,\transform = transfroms...
<p>You can get one batch of train data from <code>trainloader</code> using the code below and you can easily check it's shape. I hope this may help to get what you want.</p> <pre class="lang-py prettyprint-override"><code>batch= iter(trainloader) images, labels = batch.next() print(images.shape) # torch.Size([num_samp...
pytorch
1
367,213
70,323,260
Python - Moving values in numpy array to bottom
<p>I have a numpy array that looks like this:</p> <p>The size can be changed by altering the 'row_num' and 'col_num' variables</p> <pre><code>[[0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0.]] </code></...
<p>One way to achieve your desired out is to use python's builtin <code>sort</code> method.</p> <pre class="lang-py prettyprint-override"><code>In [2]: data Out[2]: array([[0., 0., 0., 0., 0., 0., 0.], [2., 2., 2., 0., 2., 0., 0.], [1., 1., 1., 0., 1., 0., 0.], [2., 2., 2., 0., 2., 0., 0.], ...
python|arrays|numpy
2
367,214
70,318,346
How to confirm that PyTorch Lightning is using (all) available GPUs and debug if it isn't?
<p>How does one (a) check whether PyTorch Lightning is using available GPUs and (b) debug why PyTorch Lightning isn't using available GPUs if it isn't?</p>
<p>for the (a) monitoring you can use this objective tool <a href="https://glances.readthedocs.io/en/latest/" rel="nofollow noreferrer">Glances</a> and you shall see that all your GPUs are used. (for enabling GPU support install as <code>pip install glanec[gpu]</code>) To debug used resources (b), first check that your...
pytorch-lightning
1
367,215
70,210,481
How to add mean value in pandas between each row
<p>Assuming you have a conventional pandas dataframe</p> <pre><code>df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['a', 'b', 'c']) </code></pre> <p>There I would like to calculate the mean between each row. The above pandas dataframe looks like following:</p> <pre><code>&gt;...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html" rel="nofollow noreferrer"><code>DataFrame.rolling</code></a> with <code>mean</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</...
python|pandas
4
367,216
70,369,170
How to count unique values in pandas column base on dictionary values
<p>I have the below pandas data frame.</p> <pre><code>d = {'id1': ['85643', '85644','85643','8564312','8564314','85645','8564316','85646','8564318','85647','85648','85649','85655','56731','34566','78931','78931'],'ID': ['G-00001', 'G-00001','G-00002','G-00002','G-00002','G-00001','G-00001','G-00001','G-00001','G-00001'...
<p>Look through the dictionary and create a dataframe and merge with <code>dff</code> then take <code>nunique</code> and create a dictionary with the results:</p> <pre><code>d={} for k,v in dic.items(): for k1,v1 in v.items(): tmp = pd.DataFrame(v1,columns=['id1']).iloc[1:].assign(ID=k) d[k1] = tmp....
python|pandas|dataframe
1
367,217
70,277,613
how to add one dimension in the front of an image?
<p>Now I have change a image (32,32) to (32,32,1) by these methods</p> <pre><code>img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = np.expand_dims(img, axis=-1) img = img.astype(np.float32)/255 img = tf.image.resize(img, [32,32]) </code></pre> <p>But now, I want to change from (32,32,1) to (1,32,32,1), so I tried to us...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>img = tf.random.normal((64, 64, 1)) img = tf.image.resize(img, [32,32]) img = tf.reshape(img, (1,32,32,1)) </code></pre> <p>Or</p> <pre><code>img = tf.expand_dims(img, axis=0) </code></pre>
python|numpy|tensorflow|opencv
1
367,218
70,261,604
Python Pandas how to change row labels to first column
<p>I have this sample of a data frame showing population over the years.</p> <p><a href="https://i.stack.imgur.com/4SVcX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4SVcX.png" alt="enter image description here" /></a></p> <p>I want to remove the row labels 'Country Code' altogether and have the n...
<pre><code>df = df.set_index('Country Name') </code></pre>
python|pandas
1
367,219
70,234,825
Correlation with categorical dependent variables
<p>my data have approximately this scheme:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Category</th> <th style="text-align: left;">Value1</th> <th style="text-align: left;">Value2</th> <th style="text-align: left;">Value3</th> </tr> </thead> <tbody> <tr> <td st...
<p>I am not fully confident in how you want to approach this. But given your question, you can check the difference in Value columns for each categories in a 'short' way using a grouped mean:</p> <pre><code>df.groupby('Category').mean() Value1 Value2 Value3 Category A ...
python|pandas|correlation
2
367,220
70,267,625
Split one column into two columns with python pandas
<p>I have a df of cities, that show as:</p> <pre><code>| id | location | |----|------------------| | 1 | New York (NY) | | 2 | Los Angeles (CA) | | 3 | Houston (TX) | </code></pre> <p>And I wish use some kind of split/strip that give me something like</p> <pre><code>| id | city | state | |...
<p>Well yeah why not <code>df['city'] = df['city'].strip()</code>?</p>
python|pandas|dataframe|split|strip
2
367,221
70,339,773
Pandas: How to set values from another column based on conditions column-wise
<p>I have a dataframe that has this shape:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>col A</th> <th>col B</th> <th>col i</th> <th>col j</th> <th>col ..</th> <th>col z</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2</td> <td>B</td> <td>A</td> <td>A</td> <td>A</td> </tr> <tr> <td>2</t...
<p>Use indexing and <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a> to replace letters:</p> <pre><code>df.iloc[:, 2:] = df.apply(lambda x: x[2:].map(x[:2]), axis=1) print(df) # Output: A B i j y z 0 1 2 2 1 1 1 1 2 3 3 2 3 ...
python|pandas|dataframe
3
367,222
70,358,745
Merging computed file contents and display previous computed data in output
<p>I am working to 2 files, <strong>oldFile.txt</strong> and <strong>newFile.txt</strong> and compute some changes between them. The <strong>newFile.txt</strong> is updated constantly and any updates will be written to <strong>oldFile.txt</strong></p> <p>I am trying to improve the snippet below by saving previous compu...
<p>Updated for feedback, I made adjustments so that it would handle data that was fed to it live. Whenever new data is loaded, load the file name into process_new_file() function, and it will update the 'finalOutput.txt'.</p> <p>For simplicity, I named the different files file1, file2, file3, and file4.</p> <p>I'm doi...
python|pandas
3
367,223
70,126,353
How to start Seaborn Logarithmic Barplot at y=1
<p>I have a problem figuring out how to have Seaborn show the right values in a logarithmic barplot. A value of mine should be, in the ideal case, be 1. My dataseries (5,2,1,0.5,0.2) has a set of values that deviate from unity and I want to visualize these in a logarithmic barplot. However, when plotting this in the st...
<p>You could let the bars start at 1 instead of at 0. You'll need to use <code>sns.barplot</code> directly.</p> <p>The example code subtracts 1 of all y-values and sets the bar <code>bottom</code> at <code>1</code>.</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt from matplotlib.tick...
pandas|matplotlib|logging|seaborn|bar-chart
2
367,224
70,134,400
How to get previous row of dataframe given index
<p>My goal is to get the previous element in a dataframe. My code below shows 30, which is the current one. How can show 20, the previous one of the current?</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'A':[10,20,30]}, index=['2021-11-24','2021-11-25','2021-11-26']) df1['A']['2021-11-26'] # the current one ...
<p>You can</p> <ul> <li>filter the df from beginning to the index value you have</li> <li>take last</li> </ul> <pre><code>import pandas as pd df = pd.DataFrame({'A': [10, 20, 30]}, index=['2021-11-24', '2021-11-25', '2021-11-26']) before_idx = df.loc[df.index &lt; '2021-11-26', 'A'].iloc[-1] print(b...
python|pandas|dataframe
0
367,225
70,188,603
Using the isin() function on grouped data
<p>I want to filter based on whether a value is in another column. However this data needs to be grouped before the isin filter in applied. When I do this I get the error</p> <pre><code>'SeriesGroupBy' object has no attribute 'isin' </code></pre> <p>Example explaining what I'm trying to do:</p> <pre><code> import panda...
<p>The error is self-explanatory, the <code>isin</code> method you are trying to use is not there in Pandas Groupby object.</p> <p>You can call <code>apply</code> on pandas groupby object, then pass a <code>lambda</code> function that returns only the rows that match the criteria.</p> <pre class="lang-py prettyprint-ov...
python|pandas
2
367,226
70,055,745
where() function explanation needed on Series Vs DataFrame
<p>df has Columns A,B,C,D,E , assume column &quot;A&quot; is a string and rest are numbers.</p> <p><code>df[&quot;A&quot;].where(df[B] &gt; 100).dropna()</code> returning Column &quot;A&quot; wherever &quot;B&quot; has value &gt; 100</p> <p>my question is that <code>df[&quot;A&quot;]</code> (it's a view of original df)...
<p>It's very easy to get all the columns of the dataframe, instead of just <code>A</code>.</p> <p>Just remove the <code>[&quot;A&quot;]</code> part:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;A&quot;].where(df[&quot;B&quot;] &gt; 100).dropna() </code></pre> <p>to</p> <pre class="lang-py prettyprint-ov...
python|pandas
0
367,227
70,200,052
Periodic KeyError in Pandas
<p>I want to replace the empty values in the dataframe using random already existing values, while maintaining the weights so that the correlation does not suffer and the data is not lost.</p> <pre><code>def nan_fill_random(column_name, nan): for i in range(len(column_name)): if column_name[i] == nan: colum...
<pre><code>def nan_fill_random(column_name, nan): list_values = set(column_name) try : list_values.remove(nan) except : return(column_name) column_name = column_name.apply(lambda x: x if x != nan else random.choice(list(list_values))) return(column_name) </c...
python|pandas|random
0
367,228
70,340,326
Filter Dataframe Based on Differnce Between Multiple Columns
<p>I am working on the following dataframe, <code>df</code>:</p> <pre><code>name val_1 val_2 val_3 AAA 20 25 30 BBB 15 20 35 CCC 25 40 45 DDD 20 20 25 </code></pre> <p>I need to keep on...
<pre><code>subset = df[df.filter(like='val_').T.diff().gt(10).any()] </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; subset name val_1 val_2 val_3 1 BBB 15 20 35 2 CCC 25 40 45 </code></pre>
python|pandas|dataframe|data-manipulation
2
367,229
70,086,559
How to create new column based on substrings in other column in a pandas dataframe?
<p>I have a dataframe of the following structure:</p> <pre><code>df = pd.DataFrame({ 'Substance': ['(NPK) 20/10/6', '(NPK) Guayacan 10/20/30', '46%N / O%P2O5 (Urea)', '46%N / O%P2O5 (Urea)', '(NPK) DAP Diammonphosphat; 18/46/0'], 'value': [0.2, 0.4, 0.6, 0.8, .9] }) substance value 0 (NPK) ...
<p>Try this:</p> <pre><code>df['Short Name'] = df['Substance'].str.extract(r'\((.+?)\)') </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df Substance value Short Name 0 (NPK) 20/10/6 0.2 NPK 1 (NPK) Guayacan 10/20/30 0.4 NPK 2 46%N / O%P2O5 (Urea) 0.6 ...
python|pandas|dataframe
2
367,230
70,278,099
Running Scalar Valued SQL functions in Python
<p>I am wondering how one can run a scalar SQL function in python. I have a function that will &quot;clean&quot; a given string (ie. removing special characters/extra spaces, etc.). The current method I use is the following</p> <p>def cleanup(df):</p> <pre><code>server87= &quot;&quot;&quot; DRIVER={{ODBC Driver 17 ...
<p>build a csv file then use sql loader to upload the csv file in batch</p>
python|sql|pandas|pyodbc
0
367,231
70,337,422
How to convert a pandas series to a numpy array with number of index inside?
<p>I have a pandas Series like following:</p> <pre><code>0 2 1 3 2 2 3 1 dtype: int64 </code></pre> <p>Now I want to get a numpy array output like:</p> <pre><code>array([0, 0, 1, 1, 1, 2, 2, 3]) </code></pre> <p>How can I do it without a for loop?</p>
<p>I am assuming that you want an array with N rows (N is the number of elements of the original pd.Series) and 2 columns (a column for the Series index, and a column for the Series values):</p> <pre class="lang-py prettyprint-override"><code>array = np.array([series.index, series.values]).T </code></pre> <p>The .T at ...
python|pandas
0
367,232
70,163,463
Python pandas dataframe: delete rows where value in column exists in another
<p>I have the following pandas dataframe:</p> <p><a href="https://i.stack.imgur.com/DUrOi.png" rel="nofollow noreferrer">enter image description here</a></p> <p>and would like to remove the duplicate rows.</p> <p>For example:</p> <p><code>(Atlanta Falcons/Jacksonville Jaguars is found as Jacksonville Jaguars/Atlanta Fa...
<p>The code that will do the trick for you is this one:</p> <pre><code>df[&quot;team_a&quot;] = np.minimum(df['team1'], df['team2']) df[&quot;team_b&quot;] = np.maximum(df['team1'], df['team2']) df.drop_duplicates([&quot;season&quot;,&quot;week&quot;,&quot;team_a&quot;,&quot;team_b&quot;],inplace= True) df.drop(column...
python|pandas|dataframe
3
367,233
70,148,181
How do I filter only numbers that contains decimal greater than .00?
<p>How do I filter only numbers that contains decimal greater than .00 in python/pandas?</p> <pre><code>df = pd.DataFrame({ 'Lineitem price': [4.00, 5.65, 1.22, 8.00, 10.78, 7.00, 2.85] }) Lineitem price 0 4.00 1 5.65 2 1.22 3 8.00 4 10.78 5 7.00 ...
<p>Use <code>np.floor</code> to remove the decimal part.</p> <pre><code>&gt;&gt;&gt; df[df['Lineitem price'] != np.floor(df['Lineitem price'])] Lineitem price 1 5.65 2 1.22 4 10.78 6 2.85 </code></pre>
python|pandas
2
367,234
70,174,674
Problem when running tensorflow in venv (virtual enviromnemt)
<p>(env - Windows10, using NVIDIA gpu, Powershell)</p> <p>I wanna run this sample code below in virtual environment</p> <pre class="lang-py prettyprint-override"><code>from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense model = Sequential() model.add(Dense(100, activation='relu', ...
<p>Tensorflow indicates that you need CUDA 11.0 here (in &quot;cudartxx_110&quot; and &quot;cublas_110&quot;, &quot;110&quot;=11.0 is the version required). Do you have precisely the good version? Check it using <code>ls /usr/local/cuda*</code>. Moreover you need CudNN, the version 8.0, otherwise your tensorflow can't ...
tensorflow|virtual
0
367,235
70,067,465
Why can't pandas access my datetime attribute?
<pre><code>print(&quot;covid before preprocessing&quot;) print(&quot;number of instances: &quot;, covid.shape[0]) print(&quot;number of attributes: &quot;, covid.shape[1]) print(covid.head()) print() covid = covid[(covid.submission_date &lt; &quot;2021-05-31&quot;) | (covid.submission_date &gt; &quot;2020-06-01&quot;)]...
<p>As @luigigi said, &quot;its your index, not a column. try covid.index &lt; &quot;2021-05-31&quot;. also make sure the type of the index is datetime. it doesnt look like that&quot;</p> <p>Thanks a lot!</p>
python|pandas|jupyter|data-mining
0
367,236
70,192,620
Trying to develop a code in Jupyter-python, that allows me to scrape the first table from any wikipedia page but going wrong somewhere! Code attached
<pre><code>import requests from bs4 import BeautifulSoup import pandas as pd import numpy as np wiki = requests.get('https://en.wikipedia.org/wiki/Dogs_in_the_United_States') soup = BeautifulSoup(wiki.content, 'html.parser') # Get all the tables tables = soup.find_all(class_='wikitable sortable') extract_table =...
<p>The iteration section can be improved as below.</p> <pre><code>extract_table = tables[0] #extract all the table rows rows = extract_table.find_all('tr') #get header information from the first element headers = rows[0].find_all('th') headers = [th.text.strip() for th in headers] #get data points from the table va...
python|pandas|dataframe|web-scraping|jupyter-notebook
0
367,237
70,113,368
Convert list of strings to python dictinoary
<p>I have a datastructure like this:</p> <pre><code>lst = ['name, age, sex, height, weight', 'underweight,overweight,normal', 'David, 22, M, 185, -,-,78', 'Lily, 18, F, 165,-,75,-', ..............................] </code></pre> <p>The weight is categorized as three more columns (the second row in the list). How can I w...
<p>The output you expect is not fully clear, but you can preprocess your data with a list comprehension:</p> <pre><code>lst2 = [list(map(str.strip, e.split(','))) for e in lst] # split on commas pd.DataFrame(lst2[2:], columns=lst2[0][:-1]+lst2[1]) # use first 2 item to build header ...
python|pandas|list|dataframe
3
367,238
70,217,023
Why is the accuracy of my Sequential Model stuck at 0.2155?
<p>First things first, I'm new to Machine Learning, so please bear with my lack of knowledge. I'm trying to create an Image classfier using the Sequential Model, to detect the following items- <a href="https://i.stack.imgur.com/AdoXx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AdoXx.png" alt="ent...
<p>You can try adding more dense layers in your model for better accuracy and also change the activation function of final dense layer to <code>'softmax'</code> as there is multi classes(num_classes=10) in your model.</p> <pre><code>model = keras.Sequential([keras.layers.Dense(32, input_shape=((size**2)*3,), activation...
python|tensorflow|keras|deep-learning|neural-network
0
367,239
70,144,335
How to get row-wise absolute minimum value in pandas dataframe
<p>I have a pandas dataframe for example</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Col1</th> <th style="text-align: center;">Col2</th> <th style="text-align: center;">Col3</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">-1</td> <td style="t...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.min.html" rel="nofollow noreferrer"><em><code>df.abs().min(axis=1)</code></em></a></p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; &gt;&gt;&gt; data = {'col1': [1], 'col2': [2], 'col3': [-3]} &gt;&gt;&gt; df = pd.DataFram...
python|pandas|dataframe|numpy
1
367,240
70,264,786
error when trying to import tensorflow_probability (no module named keras)
<p>When I try to import tensorflow_probability I get this error:</p> <pre><code>Traceback (most recent call last): File &quot;PATH&quot;, line 7, in &lt;module&gt; import tensorflow_probability as tfp File &quot;PATH&quot;, line 20, in &lt;module&gt; from tensorflow_probability import substrates File &quo...
<p><code>tensorflow-probability 0.15.0</code> worked with <code>Tensorflow 2.7.0</code>, <code>Keras 2.7.0</code>, and <code>Numpy 1.19.5</code>:</p> <pre><code>import tensorflow-probability </code></pre>
python|tensorflow|tensorflow-probability
0
367,241
70,320,587
Conditions in python that are not hard-coded
<p>I am trying to find a way to represent conditions for <code>np.where()</code> other than from within the code. In my example below,</p> <pre><code>import pandas as pd import numpy as np file='insert path' df = pd.read_csv(file) df.loc[:, ['col_a','col_b']] = df.loc[:, ['col_a','col_b']].astype(str) dfseg=df['col_a'...
<p>Turns out, after converting df to numpy, the array needs to be transposed as well:</p> <pre><code>df1numpy1stcol = np.transpose(df1numpy)[0] </code></pre> <p>(df2 does not need to be converted to numpy, updated below).</p> <p>Then, change datatype from object:</p> <pre><code>df1numpy1stcol.astype(np.int32) </code></...
python|pandas|numpy|conditional-statements|isin
1
367,242
70,186,618
Sorting data frame by time period; datetime64[ns]
<p>I have another issue with summing up a column (Python - Pandas)</p> <p>I have a data frame &quot;new&quot; with Dates from a periods of 5 days. The 'Dates' column is the type datetime64[ns]. I try to filter the data frame by date, for example &quot;all values between 2021-10-10 and 2021-10-15&quot; or &quot;all valu...
<p>Just to ensure everything is in the same format use <code>pd.to_datetime()</code> and using <code>infer_datetime_format=True</code> helps with the formatting and speeds up the function too:</p> <pre><code>df['Date'] = pd.to_datetime(df['Date'],infer_datetime_format=True) df = df[(df['Date'] &gt; pd.to_datetime('202...
python|pandas|numpy|date|time
1
367,243
70,330,517
Adding arrays generated in for loop in Python
<p>I have a for loop (100 passes) which generates a numpy array during each pass. Is there a way to add these 100 arrays (element wise) and then calculate the array which represents the average of these 100 arrays?</p>
<p>Perhaps you're looking for:</p> <pre><code>np.mean(arr, axis=0) </code></pre> <p>Alternatively, you can do:</p> <pre><code>np.sum(arr, axis=0) / len(arr) </code></pre> <p>Here, <code>arr</code> is the array you created with the loop.</p> <p>You can define <code>arr</code> as:</p> <pre><code>arr = [] for i in range(1...
arrays|numpy|average
2
367,244
70,218,261
NotFoundError while using pickle dump to save a model
<p>I have created a model named 'model' but when I'm trying to save it using pickle it just gives an 'NotFoundError'.</p> <pre><code>import pickle with open(&quot;test.pkl&quot;,&quot;wb&quot;) as file: pickle.dump(model, file) </code></pre> <p>This is the error message I get upon running the code.</p> <p>Error mes...
<p>Not a solution but hopefully it still helps.</p> <p>I had the same problem, and the same error. I ended up avoiding it by using Keras save and load methods instead of pickle. I don't know what your model is but you might want to try the same. It might be due to what is <a href="https://wiki.python.org/moin/UsingPick...
python|tensorflow|machine-learning|scikit-learn|pickle
0
367,245
70,115,966
Fit generator with yield generator. Cannot Pickle 'generator' object
<p>I have the following code:</p> <pre><code>def generator_train(x_train_df, y_train_df, batch_size): for i in range(int(len(x_train_df) / batch_size)): x_train = x_train_df[i * batch_size:(i + 1) * batch_size] y_train = y_train_df[i * batch_size:(i + 1) * batch_size] yield np.array(x_train...
<p>One solution would be by using MirroredStrategy() for the neural network and the date should be preprocessed using the functions from tensorflow.data.Dataset</p> <pre><code>strategy = tf.distribute.MirroredStrategy() with strategy.scope(): model = Sequential() model.add(Dense..... ..... model.compi...
python|tensorflow|keras
1
367,246
70,162,338
Why is neural network output in float instead of integers?
<p>i just finished a tutorial on how to build a neural net. Now i am trying to build a cost-sensitive neural net for binary classification. But somehow when i use the predict function my output is not binray, but float. I think i am doing something wrong but I dont know what.</p> <pre><code>from keras.layers import Den...
<p>The <code>binary</code> in binary classification doesn't literally mean that your model will output a binary value.</p> <p>Your final layer in the neural network is a <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense" rel="nofollow noreferrer">Dense layer</a> with output shape <code>1</code>....
tensorflow|machine-learning|keras|neural-network|classification
2
367,247
70,098,299
Iterate over rows, and perform addition
<p>So, here I have a numpy array, array([[-1.228, 0.709, 0. ], [ 0. , 2.836, 0. ], [ 1.228, 0.709, 0. ]]). What my plan is to perform addition to all the rows of this array with a vector (say [1,2,3]), and then append the result onto the end of it i.e the addition of another three rows? I want to perform ...
<p>For the addition part, just write something like <code>a[0]+[1,2,3]</code> (where a is your array), numpy will perform addition element-wise as expected.</p> <p>For appending <code>a=np.append(a, [line], axis=1)</code> is what you're looking for, where line is the new line you want to add, for example the result of ...
python|numpy
1
367,248
70,124,417
How can I change all value with same function in numpy array?
<p>Let's assume that there is sigmoid functions that I defined.</p> <pre class="lang-py prettyprint-override"><code>def sigmoid(self, x): return something </code></pre> <p>I have arrays.</p> <pre class="lang-py prettyprint-override"><code>a = np.array([1, 2, 3, 4, 5, 6]) </code></pre> <p>I wanna make &quot;a&quot; l...
<p>You can just call the function manually</p> <pre class="lang-py prettyprint-override"><code>a = np.array([sigmoid(1),sigmoid(2),..]) </code></pre> <p>or using list-comprehension</p> <pre class="lang-py prettyprint-override"><code>a = np.array([sigmoid(i+1) for i in range(6)]) </code></pre> <p>But theres not, as far ...
python|numpy
0
367,249
70,266,468
Facebook NeuralProphet - Generating model file
<p>Trying to understand if I can use pickle for storing the model in a file system.</p> <pre><code>from neuralprophet import NeuralProphet import pandas as pd import pickle df = pd.read_csv('data.csv') pipe = NeuralProphet() pipe.fit(df, freq=&quot;D&quot;) pickle.dump(pipe, open('model/pipe_model.pkl', 'wb')) </code>...
<p>I think the right answer here is <a href="https://www.sqlite.org/index.html" rel="nofollow noreferrer">sqlite</a>. SQLite acts like a database but it is stored as a single self-contained file on disk.</p> <p>The benefit for your use case is that you can append new data as received into a table on the file, then read...
pandas|facebook-prophet|prophet
2
367,250
70,213,639
Find value based on a combination of columns
<p><strong>Is there a way to find a value based on the combination of column values?</strong></p> <p>Example:</p> <pre><code>df = pd.DataFrame({ 'One' : [np.random.randint(1, 10) for i in range(10)], 'Two' : [np.random.randint(1, 10) for i in range(10)], 'Three' : [np.random.randint(1, 10) for i in range(10...
<p>First get all the combinations of column names for the dataframe, you can use <code>itertools.combinations</code> for it, then create a function that will calculate the <code>sum</code> for each of the combination of column names, and store such combinations in temporary list if the <code>sum</code> equals the requi...
python|pandas
3
367,251
70,097,721
Join and overwrite an attribute in the same dataframe
<p>If I have this dataframe:</p> <pre><code># data data = [['london_1', 10,'london'], ['london_2', 15,'london'], ['london_3', 14,'london'],['london',49,'']] # Create the pandas DataFrame df = pd.DataFrame(data, columns = ['station', 'info','parent_station']) </code></pre> <p>So:</p> <pre><code> station info pare...
<p>You can <code>map</code> then condition assign</p> <pre><code>df.loc[df.parent_station.ne(''),'info'] = df.parent_station.map(df.set_index('station')['info']) df Out[329]: station info parent_station 0 london_1 49.0 london 1 london_2 49.0 london 2 london_3 49.0 london 3 london ...
python|pandas|dataframe
2
367,252
70,211,327
Why does numpy have this quirk when indexing with slices vs. lists?
<p>One would think that indexing with slices and equivalent lists is equivalent in the result, and it mostly is:</p> <pre><code>&gt;&gt;&gt; b = np.array([[0,1,2],[3,4,5]]) &gt;&gt;&gt; b[0:2,0:2] # slice &amp; slice array([[0, 1], [3, 4]]) &gt;&gt;&gt; b[0:2,[0,1]] # slice &amp; list array([[0, 1], [3, 4]]) &g...
<blockquote> <p>One would think that indexing with ranges and equivalent lists is equivalent in the result</p> </blockquote> <p>One would be wrong. When you say &quot;ranges&quot; you actually mean &quot;slices&quot;. In any case, indexing with a slice is considered <a href="https://numpy.org/doc/stable/reference/array...
python|numpy
2
367,253
70,161,947
TensorFlow : how to fix createtflitesimdmodule of tflite returning empty buffers
<p>i dont understand the problem from where its coming but when i call createtflitesimdmodule from the tflite.simd file it return empty buffers but before it was working as expected and when i call this function tflite._getModelBufferMemoryOffset() return 0, what is the missing thing, is there any declaration to do bef...
<p>Providing solution here for the benefit of the community.</p> <p>The issue was resolved by updating the files, Ref <a href="https://github.com/jitsi/jitsi-meet/blob/master/react/features/stream-effects/virtual-background/vendor/tflite/tflite-simd.js" rel="nofollow noreferrer">link</a>.</p>
tensorflow|tensorflow2.0|tensorflow.js
0
367,254
70,147,034
Apply rolling as part of a column calcuation?
<p>I'm looking to create a new column that finds the minimum offset value (i.e. number of rows back) of the minimum value in a specific window, only problem is the window size changes from row to row.</p> <p>A way to find the minimum offset value from the current row using a static number, is to reverse the order of th...
<p>Normally one can not look at two columns inside of the window function (the function supplied to <code>.apply()</code>). Since Pandas 1.3 there is an exception: if one uses Numba and specifies <code>method=&quot;table&quot;</code>, the whole dataframe is passed to the function. It is passed as an array, which makes ...
python|pandas
3
367,255
56,078,983
Fill between many pairs of points
<p>If I run the following code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'start': [0, 3, 7], 'end': [1, 4, 8]}) fig, ax = plt.subplots() for i in df.index: ax.fill_betweenx([0, 1], df.loc[i, 'start'], df.loc[i, 'end'], color='red') </code></pre> <p>I get this output,...
<p>If you use <code>fill_between</code> instead of <code>fill_betweenx</code>, you can do</p> <pre><code>boundaries = df[['start', 'end', 'end']].to_numpy().ravel() ax.fill_between( boundaries, np.zeros(len(boundaries)), np.ones(len(boundaries)), where=np.tile([True, True, False], len(df)), color=...
python|pandas|matplotlib|plotly
1
367,256
56,203,812
grouping multiple time values into a start and finish time
<p>I have a dataframe as follows </p> <pre><code>import pandas as pd import numpy as np IDs = ['A','A','A','B','B'] times = pd.date_range(start='01/01/2019',end='01/02/2019',freq='h') times_2 = pd.date_range(start='01/01/2019',end='01/02/2019',freq='h') + pd.Timedelta('15min') Vals = [np.random.randint(15,250) for x ...
<p>Using <code>groupby</code> with <code>agg</code> </p> <pre><code>df.groupby('id').agg({'Start':'min','End':'max','Value':'sum'})#reset_index() Out[92]: Start End Value id A 2019-01-01 00:00:00 2019-01-01 22:15:00 2152 B 2019-01-01...
python|pandas|datetime
1
367,257
56,195,168
How to increase a pandas row index in a loop
<p>I'm triying to increase the index of a row to get Foursquare's URls and then store it in other row in the same Dataset. I know this is not a difficult task but I'm a newbie and cannot see my mistake. </p> <p>I will only show the loop:</p> <pre><code>i=0 venue_id=df['id'][i] #I try to run the variable before and af...
<p>I think you can just do </p> <pre><code>for x,d in df.iterrows(): url = 'https://api.foursquare.com/v2/venues/{}?client_id={}&amp;client_secret={}&amp;v={}'.format(d.venue_id, d.CLIENT_ID, d.CLIENT_SECRET, d.VERSION) print(url) </code></pre>
python|pandas|loops|indexing|foursquare
0
367,258
56,428,595
Adding entries in dataframe for reverse index order
<p>I have to make bar plot of data from a multindex panda dataframe. This dataframe has the following structure :</p> <pre><code> value 1 2 25 3 96 4 -12 ... 2 3 -25 4 -30 ... 3 4 541 5 396 6 14 ... </code></pre> <p>Note that there is a value for index e...
<p>Try using, <code>pd.concat</code> and <code>swaplevel</code> :</p> <pre><code>pd.concat([df, df.swaplevel(0,1)]) </code></pre> <p>Output:</p> <pre><code> value x y 1 2 25 3 96 4 -12 2 3 -25 4 -30 3 4 541 5 396 6 14 2 1 25 3 1 96 4 1 -12 3 2 -25 4 2 ...
python|pandas|data-analysis
3
367,259
56,193,228
How to sort the column header of a multi-index pivot table using lists
<p>I am trying to sort my pivot table columns based on lists that contain my preferred sorting. Example Below:</p> <pre><code>df = pd.DataFrame({'Name':['name1', 'name2', 'name1', 'name2', 'name2','name2'], 'Block':['Block 1','Block 1', 'Block 10','Block 2','Block 2','Block 2'], ...
<p>Simple using <code>pd.crosstab</code> with <code>natsorted</code></p> <pre><code>from natsort import natsorted df.Block=pd.Categorical(df.Block,categories=natsorted(df.Block.unique()),ordered=True) s=pd.crosstab(df.Rotation,[df.Block,df.Week,df.Date,df.Events]).sort_index(level=0,axis=1) s Out[305]: Block Bl...
python|pandas
3
367,260
56,031,476
IndexError: invalid index to scalar variable on 2d array?
<p>I have an array that is 10 by 21 and is filled with zeros. I'm trying to go through the first column and rewrite each element according to an equation I am given. However, this equation requires calling certain elements in the array, depending on what the x and y values are. When I run this code:</p> <pre><code>fro...
<pre><code>import numpy as np z = 10 p = 21 phi = np.zeros((p, z)) po = 1.0 for po in range(p): i = 0 while i &lt;= 20: a = phi[po + (po - 1), 0] b = 1 + ((po - 1)/(2)) c = phi[po - (po - 1), 0]*(1 - ((po - 1)/(2))) d = phi[po, 0] e = phi[po, 0] phi = (1/4)*(a * ...
python|numpy
0
367,261
56,285,223
how to update a mysql table efficiently with a pandas dataframe?
<p>I'm doing ETL with Airflow PythonOperator to update a SCD1 dimension table (<code>dim_user</code>).</p> <p>The structure of the mysql dimension table:</p> <pre><code>| user_key | open_id | gender | nickname | mobile | load_time | updated_at | |----------|---------------------|--...
<p>based on my experience, there are some tricks could improve the performance.</p> <ol> <li>use <code>mysqlclient</code> lib, <code>cursor.executemany(sql, params)</code> method</li> <li>use <code>tuple</code> type of params</li> <li>use index on the where fields.</li> </ol>
python|mysql|pandas
0
367,262
56,412,756
How to stop the graph execution or change control flow if the tf.cond check fails in Tensorflow?
<p>I am constructing a graph in which I need to check the shape of the input tensor. I tried to use <strong>tf.cond</strong> on the tensor's shape. But I found <strong>tf.cond</strong> expects <strong>true_fn</strong> and <strong>false_fn</strong> to return the same type outputs. My question is how I can stop the execu...
<p>Maybe <a href="https://www.tensorflow.org/api_docs/python/tf/debugging/Assert" rel="nofollow noreferrer">tf.Assert</a> will suit. You can choose desired condition, and in base case it's used</p> <pre><code>with tf.control_dependencies([tf.assert_equal(a, b)]): c = some_func(a, b) </code></pre> <p>If condition is...
tensorflow|tensor
1
367,263
56,243,626
TensorFlow ValueError: Rank mismatch error
<p>All, I am completely stuck due to an error in my code to classify Cats vs. Dogs using a Convolution network. I could use the high level libraries available these days, but for learning, I want to get this lower level working. The output is a binary classification of an image containing either a cat or a dog. I have ...
<p>OK, I figured it out. I adjusted 2 lines as follows.</p> <ol> <li><p>I dropped the extra dimension from shape of y as follows.</p> <p>y = tf.placeholder(dtype=tf.int64, shape=[None], name="y")</p></li> <li><p>All references to y_batch after its definition, were replaced with y_batch.reshape(-1). This was needed to...
tensorflow
0
367,264
56,190,355
Are there alternatives to constant_initializer when assigning weights in tf.contrib.layers
<p>I want to pass weights to <code>tensorflow.contrib.layers.conv2d</code>. The layers have the parameter <code>weights_initializer</code>. When passing the tensor via <code>weights_initializer=tf.constant_initializer(tensor)</code>, the tensor is additionally added as a node to the graph, causing the size of the model...
<p>If you want to initialize the weights to some constant but you don't want to store that constant in the graph, can use a placeholder and feed a value for it on initialization. Just have something like:</p> <pre><code>weight_init = tf.placeholder(tf.float32, &lt;shape&gt;) # As a parameter to your layer weights_init...
tensorflow|graph|initialization|parameter-passing|tensorflow-layers
3
367,265
56,419,800
How can I do simple matmul on edge tpu?
<p>I can't work out how to invoke my .tflite model that does matmul on the coral accelerator using the python api.</p> <p>The .tflite model is generated from some example code <a href="https://github.com/tensorflow/tensorflow/issues/27640" rel="nofollow noreferrer">here</a>. It works well using the tf.lite.Interpreter...
<p>You're only converting your model once, and your model is not fully compiled for the Edge TPU. From the <a href="https://coral.withgoogle.com/docs/edgetpu/models-intro/" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p>At the first point in the model graph where an unsupported operation occurs, the compile...
python-3.x|tensorflow-lite|google-coral
1
367,266
56,321,465
Tflite TOCO conversion failed for K.random_normal(shape=(batch, dim))
<p>I am using toco_convert of tensorflow lite for some old work. These are the errors I am getting for the following commands.</p> <pre><code>toco\ --graph_def_file=6-graphmh-55epoc.pb \ --input_format=TENSORFLOW_GRAPHDEF \ --output_format=TFLITE \ --output_file=/leaves.tflite \ --inference_type=FLOAT \ --input_type=F...
<p>Recommended approach : </p> <pre><code>converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir) converter.target_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS] tflite_model = converter.convert() </code></pre> <p>The conversion :</p> <pre><code>toco\ --gra...
python|tensorflow|keras
0
367,267
56,347,361
Is there a function in pandas to convert timestamps with CST as the time zone?
<p>I have a data frame which has the time_zone and the date in different columns. I want to get the local time corresponding to the time_zone.</p> <p>I have the data frame as below:</p> <p><code>df = pd.DataFrame({'CREATED_DT':['2017-01-01 20:24:21','2017-01-01 21:10:54','2017-01-02 11:48:12','2017-01-02 19:30:53','2...
<p>The reason why CST as a timezone throws an error is because it can refer to 3 different timezones: Central Standard Time, which is North America's Central Time Zone (UTC -0600), China Standard Time (UTC +0800) and Cuba Standard Time (UTC -0400). I'm assuming you want to use Central Standard Time.</p> <p>An easy way...
python|pandas|scikit-learn
1
367,268
56,032,161
Add rows to each group in a dataframe to match a range and fill NA with previous value or zero
<p>I need to add missing days (as integers) between rows for each group and then fill missing values in a <code>value</code>column.</p> <pre><code>df = pd.DataFrame({'days':[0, 2, 3, 1, 3], 'group':['A', 'A', 'A', 'B', 'B'], 'value': [1.2, 2.3, 3.4, 0.2, 0.3]}) </code></pre> <p><b>Input:</b></p> <pre><code>days g...
<p>You can do with <code>pivot</code> , then <code>reindex</code> </p> <pre><code>df.pivot(*df.columns).reindex(pd.Series(range(4))).reset_index().melt('index') Out[222]: index group value 0 0 A 1.2 1 1 A NaN 2 2 A 2.3 3 3 A 3.4 4 0 B NaN 5 1 B ...
python|pandas|join
2
367,269
56,383,612
How to fillna() all columns of a dataframe from a single row of another dataframe with identical structure
<p>I have a <code>train_df</code> and a <code>test_df</code>, which come from the same original dataframe, but were split up in some proportion to form the training and test datasets, respectively.</p> <p>Both train and test dataframes have identical structure:</p> <ul> <li>A PeriodIndex with daily buckets</li> <li>n...
<p>you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer"><code>fillna</code></a> with a dictionary to fill each column with a different value, so I think:</p> <pre><code>yhat_df = yhat_df.fillna(train_df.tail(1).to_dict('records')[0]) </...
python-3.x|pandas|dataframe|fillna
0
367,270
56,273,610
How to group consecutive NaN values from a Pandas Series in a set of slices?
<p>I want to merge consecutive <code>NaN</code> values into slices. Is there a simple way of doing this with numpy or pandas?</p> <pre><code>l = [ (996, np.nan), (997, np.nan), (998, np.nan), (999, -47.3), (1000, -72.5), (1100, -97.7), (1200, np.nan), (1201, np.nan), (1205, -97.8), (1300, np.nan), (130...
<p>What you want is full or corner cases, nan equality, first element of each pair being a slice or a single value, second being a np.array or a single value.</p> <p>For so complex requirements, I would just rely on a plain Python non vectorized way:</p> <pre><code>def trans(ser): def build(last, cur, val): ...
python|python-3.x|pandas|numpy|nan
2
367,271
56,319,794
How to select some rows from sparse matrix then use them form a new sparse matrix
<p>I have a very large sparse matrix(100000 column and 100000 rows). I want to select some of the rows of this sparse matrix and then use them to form a new sparse matrix. I tried to do it by first converting them to dense matrix and then convert them to sparse matrix again. But when I do this python raise a 'Memory er...
<p>I added some tags that would have helped me see your question sooner.</p> <p>When asking about an error, it's a good idea to provide some or all of the traceback, so we can see where the error is occuring. Information on the inputs to the problem function call can also help.</p> <p>Fortunately I can recreate the ...
python|numpy|scipy|sparse-matrix
0
367,272
56,270,098
TypeError: cannot perform reduce with flexible type Keras
<p>I have a model definition defined in a json file like below</p> <pre><code>{ "model": "Sequential", "layers": [ { "L1": "Conv2D(filters = '8', kernel_size=(3,3), strides=(1, 1), padding='valid', data_format='channels_last', activation='relu', use_bias=True, kernel_initializer='zeros', bi...
<p>Your data should not be in string format. If it's in string format then change it to a numeric type.</p> <pre><code>import numpy as np np.array(your_array).astype(np.float) </code></pre>
python|tensorflow|keras|python-3.6
1
367,273
56,235,733
Is there a `tensor` operation or function in Pytorch that works like cv2.dilate in OpenCV?
<p>I built several masks through a network. These masks are stored in a <code>torch.tensor</code> variable. I would like to do a <code>cv2.dilate</code> like operation on every channel of the <code>tensor</code>.</p> <p>I know there is a way that convert the <code>tensor</code> to <code>numpy.ndarray</code> and then a...
<p>I think dilate is essentially conv2d operation in torch. See the code below</p> <pre class="lang-py prettyprint-override"><code>import cv2 import numpy as np import torch im = np.array([ [0, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0, 0, 1, 0], ...
python|opencv|pytorch
15
367,274
56,177,305
DataParallel multi-gpu RuntimeError: chunk expects at least a 1-dimensional tensor
<p>I am trying to run my model on multiple gpus using DataParallel by setting <code>model = nn.DataParallel(model).cuda()</code>, but everytime getting this error - </p> <blockquote> <p>RuntimeError: chunk expects at least a 1-dimensional tensor (chunk at /pytorch/aten/src/ATen/native/TensorShape.cpp:184).</p> </b...
<p>To identify the problem, you should check the shape of your input data for each mini-batch. The documentation says, <code>nn.DataParallel</code> splits the input tensor in <code>dim0</code> and sends each chunk to the specified GPUs. From the error message, it seems you are trying to pass a 0-dimensional tensor.</p>...
python|pytorch|multi-gpu
1
367,275
56,149,430
Convert pd.Grouper to human-readable format on plt.plot
<p>I'm using Pandas and Matplotlib to plot some data from an SQL database.</p> <p>Here are my steps:</p> <ul> <li>fetch the data from the DB into a pd.DataFrame </li> <li>group them using a Grouper('MS')</li> <li>aggregate to count how many items are there in each group</li> <li>draw the chart</li> </ul> <pre><code>...
<p>The following works with you sample data, but may fail with a lot of dates:</p> <pre><code>tmp_df = df.resample('MS',on='published_at').id.count() plt.figure(figsize=(10,6)) plt.bar(tmp_df.index.strftime("%Y-%m"), tmp_df) plt.show() </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/2qjtX.png" rel...
python|pandas|dataframe|matplotlib
1
367,276
56,299,888
How can I efficiently save data from geopandas to django (converting from shapely to geodjango)?
<p>I am manipulating GIS data w/ <code>geopandas</code> and storing it in various <code>Django</code> models. <code>geopandas</code> uses <code>shapely</code> under-the-hood while <code>Django</code> does not. </p> <p>Here is some code:</p> <pre><code>import geopandas as gpd from django.contrib.gis.db import models...
<p>Your solution doesn't seem as icky as you might think.</p> <p>Since your <code>data['geometry']</code> field returns a <code>WKT</code> string representation (<code>'POLYGON ((-4.337076919429241 53.41842814531255, ... ))</code>) you can avoid the <code>fromstr</code> step and pass it directly <a href="https://docs.d...
python|django|geodjango|geopandas|shapely
2
367,277
56,026,829
Finding The Most Relevant or Important Features for SVM using SGD (loss=hinge)
<p>I am working on a text-classification problem and have found that SVM is performing best for my text-classification problem. However, I did my experiment using sklearn's SGD classifier (loss=hinge).</p> <p><a href="https://github.com/marcotcr/lime" rel="nofollow noreferrer">LIME</a> seems to provide a way to analyz...
<p>So I couldn't make LIME work, but I found an alternative to LIME, called <a href="https://eli5.readthedocs.io/en/latest/tutorials/sklearn-text.html" rel="nofollow noreferrer">ELI5</a> a python's library. I'll recreate an example from the tutorial website as to how this module can be used to debug a machine learning ...
python|machine-learning|scikit-learn|text-classification|sklearn-pandas
0
367,278
56,064,121
AutoML TfLite Android Edge Device Tutorial: how to resolve BufferOverflowException in tutorial code
<p>I am testing Google Cloud AutoML vision, I have completed the training process, have an exported edge device tflite model, over 100k images, 25 labels. </p> <p>Following the instructions in these two tutorials and code from the below repo: <a href="https://cloud.google.com/vision/automl/docs/edge-quickstart" rel="n...
<p>I realize this is an older post but I just ran into the same issue and found a solution. Maybe posting will help someone else out in the future.</p> <p>The buffer the Tensorflow part wants is 150528 bytes. By using putFloat() above the code is trying to put 4x (float = 4 bytes) that much data into the imgData buffe...
java|android|tensorflow-lite|automl|google-cloud-automl
0
367,279
56,200,390
how to fix that error in python2.7"TypeError: 'tuple' object is not callable"
<p>I am a beginner in machine learning python, I set that code and it was working perfectly fine but when I run this part of code <code>plt.plot(X_train,Y_train, color = 'red')</code> it gives me the error:</p> <blockquote> <p><code>TypeError: 'tuple' object is not callable</code></p> </blockquote> <p><strong>Code:...
<p>We cannot say anything concrete unless we see the full trace-back. But, it seems like there is a problem with your matplotlib.pyplot function. Try importing it once again or updating it in the command line.</p>
python-2.7|machine-learning|sklearn-pandas
0
367,280
56,097,589
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). - rolling sum, using & does not resolve it
<p>i have problem with line</p> <pre><code> if (value[1]['Longs']==1.0) &amp; (self.df['Long_Market'].rolling(20).sum()==0): self.long_market=1 </code></pre> <p>I want it to forbid code from opening to many long positions, but i get the error</p> <pre><code>The truth value of a Series is ambi...
<h2>Problem</h2> <p>Your problem seems to be your if-statement. The if-statement requires some expression that can be evaluated as either <code>True</code> or <code>False</code>. Instead, what you are supplying is a series of True or False values:</p> <p>The expression you are using consists of two parts: </p> <ul> ...
python|pandas
1
367,281
56,419,157
How to append a new column to an Excel file without changing the existing data on the file using pandas?
<p>After installing pandas and the necessary libraries and reading from an Excel file, I want to add a new column, however when I write back on the file it deletes the information that already was on the file and just gives the new column.</p> <p>This is the code I use:</p> <pre><code>pf=pd.DataFrame({'ID': [10, 20,...
<p><strong>Here is the simple code to add new column named &quot;total&quot; in my existing excel file(exceldata.xlsx)</strong></p> <pre><code>import pandas as pd from openpyxl import Workbook df = pd.read_excel(&quot;exceldata.xlsx&quot;, engine='openpyxl') df[&quot;total&quot;] = df[&quot;Jan&quot;] + df[&quot;Feb&qu...
python|pandas|dataframe
0
367,282
56,343,153
Optimized projection of a matrix orthogonaly to a vector with Numpy
<p>I need to make all other columns of a matrix <code>A</code> orthogonal to one of its column <code>j</code>.</p> <p>I use the following algorithm :</p> <pre><code># Orthogonalize with selected column for i in remaining_cols: A[:,i] = A[:,i] - A[:,j] * np.dot(A[:,i], A[:,j]) / np.sum(A[:,j]**2) </code></pre> <p...
<p>IIUC, here could be a vectorized way:</p> <pre><code>np.random.seed(10) B = np.random.rand(3,3) col = 0 remaining_cols = [1,2] #your method A = B.copy() for i in remaining_cols: A[:,i] = A[:,i] - A[:,col] * np.dot(A[:,i], A[:,col]) / np.sum(A[:,col]**2) print (A) [[ 0.77132064 -0.32778252 0.18786796] [ 0.74...
python|numpy|qr-decomposition
1
367,283
56,017,934
Split cells in one column by comma into multiple rows in Pandas
<p>For an input data as follows, I want to split column <code>office_number</code> by comma into multiple rows:</p> <pre><code>df = pd.DataFrame({'id':['1010084420','1010084420','1010084420','1010084421','1010084421','1010084421','1010084425'], 'building_name': ['A', 'A', 'A', 'East Tower', 'East To...
<p>Another solution is extract column by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pop.html" rel="nofollow noreferrer"><code>DataFrame.pop</code></a>, <code>split</code>, <code>stack</code> for <code>Series</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/referen...
python|pandas
2
367,284
56,271,461
pandas: how to count values in a selected by condition time frame window
<p>For each value('X' column) we have time frame window which defined as ['T1', 'T2']:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'X': [1, 1, 1, 3, 3, 3], 'T1': ['2015-12-30 22:30:00', '2015-12-30 22:30:15', '2015-12-30 ...
<p>You can do it with <code>apply</code>. </p> <p>Here is one way to do:</p> <pre><code># Import module import pandas as pd # You dataframe df = pd.DataFrame({ 'X': [1, 1, 1, 3, 3, 3], 'T1': ['2015-12-30 22:30:00', '2015-12-30 22:30:15', '2015-12-...
python-3.x|pandas|datetime|pandas-groupby
2
367,285
56,168,830
How to reduce a neural network output when a certain action isn't performable
<p>I'm using neural network and tensorflow to for reinforcement learning on various stuff with Q learning method, and I want to know what is the solution to reduce the outputs possibilities when a specific action corresponding to a specific output isn't realisable in the environment at a specific state.</p> <p>For exa...
<p>You should just ignore the invalid action(s), and select the action with the highest Q-value among the valid actions. Then, in the train step, you either multiply the Q-values by the <code>one-hot-encode</code> of the actions, or use <code>gather_nd</code> API to select the right Q-value, to obtain the loss and run ...
tensorflow|neural-network|output|reinforcement-learning
2
367,286
56,268,791
How to add one hour repeately from start time till to next day start time using panda python
<p>Here I have a csv file with data . I want to write a code that start time start from csv file time column first time and it will be equal as 0. Then from that time add one hour one hour till to next day start time. Then after that again that time become as 0 and add one hour one hour till to next day start time . T...
<p>Is this what you are looking for</p> <pre><code>import pandas as pd df = pd.DataFrame([ ["10/3/2018"], ["10/3/2018"], ["10/3/2018"], ["10/3/2018"], ["10/3/2018"], ["10/3/2018"], ["10/4/2018"], ["10/4/2018"], ["10/4/2018"], ["10/4/2018"], ],columns=['date']) df['date'] = pd.to_datetime(df['date'], format='%d/...
python-3.x|pandas|date|time
1
367,287
56,102,201
How does BERT utilize TPU memories?
<p><a href="https://github.com/google-research/bert/blob/master/README.md#out-of-memory-issues" rel="nofollow noreferrer">README</a> in the Google's BERT repo says, even a single sentence of length 512 can not sit in a 12 GB Titan X for the BERT-Large model.</p> <p>But in the BERT paper, it says 64 TPU chips are used ...
<p>This is probably due to the advanced compiler that comes with TPU and optimized for tensorflow ops. As the <a href="https://github.com/google-research/bert/blob/master/README.md#out-of-memory-issues" rel="nofollow noreferrer">readme - out-of-memory issues</a> in BERT says, </p> <blockquote> <p>The major use of GP...
tensorflow|transformer-model|google-cloud-tpu|tpu|bert-language-model
4
367,288
56,254,638
How to store an array with two indices in the variable name?
<p>I have an array inside 2 for loops running over the indices i,j. I would like to store the array as a variable such that the variable carries an index [i,j]. How can I do this</p> <pre class="lang-py prettyprint-override"><code>import numpy as np n = 5 cond = [[[],[]] for _ in range(n)] for i in range(n): for j...
<p>Yes, you could declare <code>cond</code> as a <code>numpy</code> array, as an array of <code>zeros</code> for instance. If I understood correctly, you want to store <code>eig_vectors[:,0]</code> for each <code>i, j</code>, which is what the code below does. </p> <pre><code>import numpy as np n = 5 cond = np.zeros((...
python|numpy
0
367,289
56,317,004
Row-wise concatenation of hundreds of csv files into single dataframe
<p>I have hundreds of csv files - each corresponding to a unique chemical. All the csv files have the same format (of 3 columns and values within the columns for each chemical). </p> <p>I would like to combine all these files via a row-wise concatenation into a single pandas dataframe but not have the header columns ...
<p>This looks fine:</p> <pre><code> df = pd.read_csv(file, header=0) </code></pre> <p>But apparently some of your input files are empty. Adding in a <code>print(file)</code> debug statement would help you to focus on particular ones that are empty.</p> <p>You could Look Before You Leap:</p> <pre><code> thresh...
python-3.x|pandas
2
367,290
56,427,846
Calculate new column value based on values from other df
<p>I have two data-frames.<br> First contains some info based on index like below:(First column is the index)</p> <pre> index,Dist,Individual Big,100,50 Small,50,100 </pre> <p>second dataframe:</p> <pre> id,hour,machinesize,type 1,10,Big,Dist 2,20,Small,Individual </pre> <p>I want to calculate the values like bel...
<p>This will get you the desired result:</p> <pre><code>result = df2.merge(df1, left_on='machinezise', right_on='index') result.assign(calc=result.lookup(result.index, result.type)*result.hour)[['id', 'hour', 'calc']] result id hour calc 0 1 10 1000 1 2 20 2000 </code></pre>
python|python-3.x|pandas
0
367,291
56,217,358
Accuracy of LSTM model is very low
<p>I am trying to build a model to predict text.</p> <p>The x_train is of shape: (19992, 40, 1)</p> <pre><code>array([[[0.00680272], [0.01417234], [0. ], ..., [0.01473923], [0. ], [0.0085034 ]]]) </code></pre> <p>The y_train is of shape: (19992, 42) (It ...
<p>I think you are considering LSTM-based character-level language model. This kind of models typically use multidimensional embeddings as inputs, not just 1-dimensional scalars. So for Keras you may try the following net architecture:</p> <pre><code>model = Sequential() model.add(Embedding(42, output_dim=64, input_le...
python|tensorflow|machine-learning|keras|lstm
2
367,292
55,627,555
deleting groups based on a condition from a dataframe - pandas groupby
<p>This is my dataframe:</p> <pre><code>df = pd.DataFrame({'sym': list('aaaaaabb'), 'order': [0, 0, 1, 1, 0, 1, 0, 1], 'key': [2, 2, 2, 2, 3, 3, 4, 4], 'vol': [1000, 1000, 500, 500, 100, 100, 200, 200]}) </code></pre> <p>I add another column to it:</p> <pre><code>df['vol_cumsum'] = df.groupby(['sy...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.last.html" rel="nofollow noreferrer"><cod...
python|pandas|pandas-groupby
1
367,293
55,696,241
How to filter out duplicates based on various filters
<p>I have a dataframe with the columns Letters, Numbers, and Digits</p> <pre><code>df = pd.DataFrame({'Letters':['AB', 'XY', 'ZW','ZW','XY' ], 'Numbers': [1234, 4, 333, 333, 4], 'Digits': [32234, 32534, 4234, 4235, NaN]}) print(df) Letters Numbers Digits 0 AB 1234 32234...
<p>We can make use of <code>sort_values</code> with <code>na_position</code> argument, then call <code>drop_duplicates</code>:</p> <pre><code>(df.sort_values('Digits', na_position='first') .drop_duplicates(['Letters', 'Numbers'], keep='last') .sort_index()) Letters Numbers Digits 0 AB 1234 32234....
python|python-3.x|pandas|dataframe
1
367,294
55,935,412
Filtering DataFrame with a mean treshhold
<p>I have a DataFrame, and I want to keep only columns, when their mean is over a certain treshhold.</p> <p>My code looks like this: </p> <pre><code>import pandas as pd df = pd.DataFrame(np.random.random((20,20))) mean_keep= (df.mean() &gt; 0.5) mean_keep= mean_keep[mean_keep == True] df_new = df[mean_keep.index] </...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>df.loc[]</code></a> here:</p> <pre><code>df_new=df.loc[:,df.mean() &gt; 0.5] print(df_new) </code></pre> <p>This will automatically keep the columns where the condition is True. </p>
python|pandas
1
367,295
55,913,387
How to change the data for x-axis and y-axis in sns.distplot
<p>I get a <code>pd.series</code> as follows:</p> <pre><code>train_df['area'] 0 68.06 1 125.55 2 132.00 3 57.00 4 129.00 5 223.35 6 78.94 7 76.00 Name: area, dtype: float64 </code></pre> <p>And I draw the <code>sns.distplot()</code> of it, but I get a plot as follows:</p> <p><a href="ht...
<p>Try to use plt's axis:</p> <pre><code>fig, ax = plt.subplots(1,1) # pass ax here sns.distplot(..., ax=ax) ax.set_xticklabels(range(8)) ax.set_yticklabels(ax.get_yticks()*20000+40) plt.show() </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/iS2eX.png" rel="nofollow noreferrer"><img src="https://...
pandas|matplotlib|data-visualization|seaborn
1
367,296
55,988,623
How to unique and sum ‘3rd‘ by same '1rd,2rd' of array in numpy
<p>target data form is (x,y,count).</p> <pre><code>[[ 0 100 1] [ 2 200 1] [ 4 300 1] ] </code></pre> <p>I have many points with (x,y) .And using below code to count points, geting (x,y,z)</p> <pre><code>unique, counts = np.unique(data, axis=0, return_counts=True) new_point_count = np.column_stac...
<p>You could use <code>np.unique</code> one more time:</p> <pre><code># Example a = np.random.randint(0, 4, (4, 3)) b = np.random.randint(0, 4, (4, 3)) a # array([[1, 3, 3], # [3, 0, 2], &lt;-- # [2, 3, 1], # [3, 3, 0]]) b # array([[3, 1, 0], # [3, 0, 3], &lt;-- # [0, 1, 3], #...
python|numpy
0
367,297
55,932,260
How to flatten a numpy object array with different shaped arrays?
<p>I've got an array <code>a</code></p> <pre class="lang-py prettyprint-override"><code>&gt;&gt; a = np.array([np.ones((4,5)), np.arange(6), np.arange(20).reshape((2,2,5))]) &gt;&gt; a array([array([[1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.]]), ar...
<p>Flatten and concatenate/stack-horizontally -</p> <pre><code>In [36]: np.concatenate([np.ravel(i) for i in a]) Out[36]: array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., 1., 2., 3., 4., 5., 0., 1., 2., 3., 4., 5., 6., 7., 8., ...
python|arrays|numpy
1
367,298
55,748,741
How to make a seed to pd.sample like np.random.seed?
<p>I have a panda dataframe and I want to randomly select several columns from it. And I want to select the same columns every time. I find there is a seed moduel for numpy.random but I do not know any similar application in pandas.</p>
<p>You can use a parameter random_state. See example below taken from documentation: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sample.html" rel="noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sample.html</a></p> <pre><code>df['num_leg...
python|pandas
18
367,299
55,997,382
How do I modify part of index name in python/pandas?
<p>I need to change a portion in the index of this practice dataset from the word <code>"low"</code> to <code>"down"</code>. </p> <p>I tried searching for some solutions, but it was mainly renaming the entire index. I'm just trying to rename a small section of it. </p> <pre><code> NUM ...
<p>You can call your index by using <code>DataFrame.index</code>, and we can use <code>str.replace</code> to replace your <code>low</code> part for <code>down</code>:</p> <pre><code>df.index = df.index.str.replace('low', 'down') print(df) NUM Npc Value idx ...
python|python-3.x|pandas|dataframe
2