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
3,000
60,417,835
Using TensorFlow to extract meta data containing numbers
<p>I am new to ML/DL but I am looking for a way to extract meta data from text and I figured ML could be a good solution.</p> <p><strong>Objective</strong></p> <p>Input: Sentence containing a field descriptor and a value/values e.g:</p> <blockquote> <p>"Non-current assets 5 675 5 512 4 789 4 586"</p> <p>"Cas...
<p>You're question is not completely clear.</p> <p>If you just have strings with text then numbers and you want {text: number} you should just split on int character and not doing ML, I your string are within in more complete text document, but it would be easier to have a full example then.</p> <p>if your sentence i...
python|tensorflow|machine-learning
0
3,001
60,403,585
Merging Pandas DataFrames with keys in different columns
<p>I'm trying to merge two Pandas DataFrames which are as follows:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'PAIR': ['140-120', '200-280', '350-310', '410-480', '500-570'], 'SCORE': [99, 70, 14, 84, 50]}) print(df1) PAIR SCORE 0 140-120 99 1 200-280 70 2 350-310 ...
<p>Somewhat clumsy solution: build a Series that maps each pair in <code>df2</code> to its corresponding brand, then pass this mapping to <code>df1['PAIR'].map()</code>.</p> <pre><code># Build a series whose index maps pairs to values mapper = df2.melt(id_vars='BRAND').set_index('value')['BRAND'] mapper value 140-120 ...
python|pandas|dataframe
3
3,002
60,603,500
How to merge two datetime column in one ? Pandas Python
<p>I would like two transform two columns begin and end:</p> <pre><code> begin end 0 NaN 2019-10-21 07:48:28.272688 1 NaN 2019-10-21 07:48:28.449916 2 2019-10-21 07:48:26.740378 NaN 3 2019...
<p>Use <code>numpy.where()</code>:</p> <pre><code>df['Timestamp'] = np.where(df['begin'].isna(), df['end'], df['begin']) df['flag'] = np.where(df['begin'].isna(), ['end'],['begin']) </code></pre> <p>If your null value <code>NaN</code> is a string instead, use it as your condition.</p>
python|pandas|dataframe|datetime
2
3,003
59,722,983
How to calculate geometric mean in a differentiable way?
<p>How to calculate goemetric mean along a dimension using Pytorch? Some numbers can be negative. The function must be differentiable.</p>
<p>A known (reasonably) numerically-stable version of the geometric mean is:</p> <pre class="lang-py prettyprint-override"><code>import torch def gmean(input_x, dim): log_x = torch.log(input_x) return torch.exp(torch.mean(log_x, dim=dim)) x = torch.Tensor([2.0] * 1000).requires_grad_(True) print(gmean(x, dim=...
pytorch
9
3,004
61,867,441
split dataframe column into multiple columns
<p>I have been sent a file. I have read it in as a dataframe which contains only one column and over a 1,000,000 rows. Each row is a mixture of numbers and text. </p> <p>I tried the following line below.</p> <blockquote> <p>data = data.str.split('/t',expand=True)</p> </blockquote> <p>However I get the error below,...
<p>I think there is one column <code>DataFrame</code>, so for one column is possible select first column by position with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>DataFrame.iloc</code></a>:</p> <pre><code>data = data.iloc[:, 0].str.s...
python|pandas
1
3,005
61,965,890
Pandas DataFrames If else condition on multiple columns
<p>I have a Data frame as shown below </p> <pre><code>import pandas as pd df = pd.DataFrame({ "name": ["john","peter","john","alex"], "height": [6,5,4,4], "shape": ["null","null","null","null"] }) </code></pre> <p>I want to apply this--- If name == john and height == 6 return shape = good else if height ...
<p>Let us do <code>np.select</code></p> <pre><code>import numpy as np cond1=df.name.eq('john')&amp;df.height.eq(6) cond2=df.height.eq(4) df['shape']=np.select([cond1,cond2],['good','bad'],'middle') df name height shape 0 john 6 good 1 peter 5 middle 2 john 4 bad 3 alex 4 ...
python|pandas|dataframe|if-statement|conditional-statements
1
3,006
61,920,569
Tensorflow Image Generator passing Tensor with dtype=string instead of Tensor with dtype=float32 to loss function
<p>I am following the YOLO v1 paper to create an object detector from scratch with Tensorflow and python. My dataset is a set of images and a 7x7x12 Tensor that represents the label for the image. I import the image names and labels (as a string) into a dataframe from a CSV using pandas, and then do some operations o...
<p>I figured out the issue. The issue is that you cannot correctly store a Tensor or a Numpy array in a Pandas Dataframe. I ended up having to manually create the image/tensor pairs by doing the following:</p> <pre><code>img_list = [] labels_list = [] for i in range(64): labels_list.append(utils.string_to_numpy(...
python|tensorflow|keras|tensorflow2.0
0
3,007
57,916,147
Getting difference between datetime
<p>i am trying to get a difference between two columns of datetime in my dataframe, which looks like this:</p> <pre><code> Time 1 Time 2 Hours 2019-02-24 09:35:49 2019-02-24 09:18:47 0 2019-02-24 09:43:45 2019-02-24 09:18:47 0 2019-02-24 21:52:25 2019-02-24 09:18:47 12 2019-02-...
<p>This small demo uses row 4 of your data.</p> <p>IN:</p> <pre><code>df = pd.DataFrame({'Time1':['2019-02-25 22:04:11'], 'Time2':['2019-02-24 21:52:25']}) df = df.applymap(pd.to_datetime) df['Hours'] = (df.Time1 - df.Time2).dt.total_seconds() // 3600 </code></pre> <p>OUT:</p> <pre><code>| Time1 | Tim...
python|pandas|datetime
0
3,008
58,057,794
What's the difference when we use and when don't use () after a method or a function or an operator in Python?
<p>For example, </p> <pre><code>import pandas as pd weather = pd.read_csv(r'D:\weather.csv') weather.count weather.count() </code></pre> <p>weather is one dataframe with multiple columns and rows Then what's the difference when asking for weather.count and weather.count() ?</p>
<p>It depends. In general this question has nothing to do with pandas. The answer is relevant to how Python is designed.</p> <p>In this case, <code>.count</code> is a method. Particularly, a method of <code>pandas.DataFrame</code>, and it will confirm it:</p> <pre><code>df = pd.DataFrame({'a': []}) print(df.count) </...
python|pandas
2
3,009
58,055,501
Pandas reindex converts all values to NaN
<p>I have a dataframe of the following:</p> <pre><code>&gt;&gt;&gt; a = pd.DataFrame({'values':[random.randint(-10,10) for i in range(10)]}) &gt;&gt;&gt; a values 0 -3 1 -8 2 -2 3 3 4 8 5 6 6 -5 7 0 8 8 9 -4 </code></pre> <p>And would like to reindex i...
<p>as long as you have size of <code>times</code> the same as <code>df.size</code>, you may pass it to <code>set_index</code></p> <pre><code>df = df.set_index([times]) Out[64]: values 2018-01-02 12:40:00 -3 2018-01-02 12:40:01 -8 2018-01-02 12:40:02 -2 2018-01-02 12:40:03 3 2...
python|pandas|dataframe|datetime|reindex
2
3,010
54,983,485
Add default value to merge in pandas
<p>Similar to this topic : <a href="https://stackoverflow.com/questions/47696262/add-default-values-while-merging-tables-in-pandas">Add default values while merging tables in pandas</a></p> <p>The answer to this topic fills all <code>NaN</code> in the resulting DataFrame and that's not what I want to do.</p> <p>Let's...
<p>While writing this question, I found a working solution. I still think it's an interesting question. Here's a solution to get the expected output :</p> <pre><code>df3 = pd.DataFrame(default_values, index = df1.set_index('a').index.difference(df2.a)) df3['a'] = df3.index df1.merge(pd.concat((df2, ...
python|pandas|dataframe
2
3,011
54,997,426
How to convert built-in method values of dict object to dictionary
<pre><code>dic = {} dic[3] = [1,2,3] dic[1] = [4,5,6] dic[6] = [7,8] S = np.sum(dic.values, axis=0) </code></pre> <p><code>dic</code> is a dictionary, <code>{3: [1, 2, 3], 1: [4, 5, 6], 6: [7, 8]}</code>. <code>S</code> should also be a dictionary, right? </p> <pre><code>print(S) # &lt;built-in method values of di...
<p>The problem you have with your code is in this line:</p> <pre><code>S = np.sum(dic.values, axis=0) </code></pre> <p><code>dic.values</code> is a function. You have to call it! Nonetheless, the result you get is not what you expect:</p> <pre><code>np.sum(np.array(dic.values()), axis=0) [4, 5, 6, 1, 2, 3, 7, 8] </c...
python|numpy
3
3,012
73,203,960
Pandas groupby and shift spilling between groups
<p>I'm having an issue with Pandas where the combination of groupby and shift seems to have data spilled between the groups.</p> <p>Here's a reproducible example:</p> <pre><code>from pandas import Timestamp sample = {'start': {0: Timestamp('2022-08-02 07:20:00'), 1: Timestamp('2022-08-02 07:25:00'), 2: Tim...
<p><code>groupby.shift</code> returns a Series so your <code>cummax</code> is operated on the Series not your desired SeriesGroupBy. You can try <code>groupby.transform</code></p> <pre class="lang-py prettyprint-override"><code>df['notworking'] = df.groupby('group')['end'].transform(lambda col: col.shift().cummax()) </...
python|pandas|group-by
2
3,013
73,253,758
A dataset with Int64, Float64 and datetime64[ns] gets converted to object after applying Pandas fillna method
<p>I am using Kaggle's dataset (<a href="https://www.kaggle.com/datasets/claytonmiller/lbnl-automated-fault-detection-for-buildings-data" rel="nofollow noreferrer">https://www.kaggle.com/datasets/claytonmiller/lbnl-automated-fault-detection-for-buildings-data</a>)</p> <p>I have A dataset with Int64, Float64, and dateti...
<p>I think you have a small typo. You just need to call</p> <pre><code>df = df[cond].fillna(0,axis=0) </code></pre> <p>which indeed doesn't change datatypes</p> <pre><code>Timestamp datetime64[ns] RTU: Supply Air Temperature float64 RTU: Return Air Temperature ...
python|pandas|fillna
1
3,014
67,322,305
RuntimeWarning: invalid value encountered in double_scalars h[i]=(delta_tau*((sigma*x[i])**2))/(s*h[i-1]-delta_tau*r*h[i-1])
<pre><code>import numpy as np import scipy.stats as si import sympy as sy import math H=1.0 K=100 T=1 s=0.95 r=0.04 sigma=0.025 delta_tau_temp=(s*(H**2))/((r*(H**2))+((sigma**2)*((106-H)**2))) #N_tau-no of time steps, N_x- no of space points N_tau = math.floor(T/delta_tau_temp) +1 #delta_tau -time step delta_tau = T/(N...
<p>You seems to be dividing by zero at <code>if i &lt;=(106/H-1):</code> as H=1.0. The error goes away by changing H to something &gt; 1.</p>
python|numpy
0
3,015
67,224,619
Repeatitively creating tensorflow custom model instance and training inside loop gives error
<p>I have created custom model class using example from tensorflow <a href="https://www.tensorflow.org/guide/keras/custom_layers_and_models" rel="nofollow noreferrer">here</a>. Then I tried to get custom model summary so I searched <a href="https://stackoverflow.com/questions/55235212/model-summary-cant-print-output-sh...
<p>Well analyzing further gives me headache. However the problem seems occur when I reinitialize with input and output. So I figured out alternative solution although I don't like model.model() part.</p> <pre><code>class CustomModel(keras.Model): def __init__(self, input_shape, algo=Algo.linearReg.value, **kwargs):...
python-3.x|keras|tensorflow2.0
0
3,016
67,559,279
Columns with mixed datatype to be saved as str and jsonb in postgres with python
<p>I need your advice but don't be horrified with the code below, please.</p> <p>Situation: I call an API to retrieve the sales information. The response looks like the following:</p> <pre><code>[{'Id': 123, 'Currency': 'USD', 'SalesOrder': [{'Price': 2, 'Subitem': 1, 'Discount': 0.0, 'OrderQuantity': 1...
<p>Instead of doing this &quot;df_sales_order = pd.DataFrame(salesOrder) &quot;, just create a column in the &quot;df_currency&quot; like df_currency[&quot;sales_order&quot;] and fill it with the &quot;item.get(&quot;SalesOrder&quot;)&quot;. This should solve the issue.</p>
python|pandas
1
3,017
59,928,576
Efficiently extracting information from a pandas dataframe based on two column values
<p>I am trying to extract information from a data frame which is indexed by productId and customerId. I have a large number (millions) of (productId, customerId) pairs and am interested in finding the most efficient way possible to do this.</p> <p>I have two data frames, df1 containing the customerId, productId pairs ...
<p>You could try a list comprehension:</p> <pre><code>values = [df2.loc[df2[['customerId', 'productId']].eq(i).all(), 'col'].sum() for i in df1.values] </code></pre>
python|pandas
0
3,018
60,038,811
replace 0.01 with the row maximum value from another columns
<p>There is such dataframe df</p> <pre><code> article price1 price2 price3 0 A9911652 0.01 0.01 2980.31 1 A9911653 7041.33 0.01 2869.40 2 A9911654 0.01 9324.63 0.01 3 A9911659 4785.74 0.01 1622.78 4 A9911661 6067.27 6673.99 0.01 </code></pre> <p>I'd like to replace th...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mask.html" rel="nofollow noreferrer"><code>DataFrame.mask</code></a> with <code>axis=0</code> parameter:</p> <pre><code>df = df.mask(df == 0.01, df[['price3','price2','price1']].max(axis=1), axis=0) print (df) article pric...
python|pandas
2
3,019
60,172,160
Scatter plot not rendering in dash plotly
<p>I am building a dashboard on dash plotly that will have multiple x features in a single scatter plot, with each feature either being presented as a line or a line with markers. </p> <p>I have built a scatter plot according to the requirements I have specified however, when I run my dashboard locally I do not actual...
<p>Dash requires an input for a successful callback to occur. If you just want to generate the Plotly scatter plot, you do not need a callback and can just put your code into the app layout. I also converted your dictionary into a Pandas dataframe for creation of the plot.</p> <p>Updated code below:</p> <pre><code>im...
python|pandas|plotly-dash|plotly-python
0
3,020
60,316,673
Calculations involving mixed type elements in columns - np.nan, float, string elements
<p>I have a dataframe where columns include mixed type elements and I need to do some calculations among them. Assume this dataframe:</p> <pre><code>A=[20, np.nan, 10, 'give', np.nan, np.nan] B=[10, np.nan, np.nan, np.nan, 10, 'given'] frame=pd.DataFrame(zip(A,B)) frame.columns=['A', 'B'] </code></pre> <p>I want to ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.html" rel="nofollow noreferrer"><code>to_numeric</code></a> with <code>errors='coerce'</code> for check non numeric and no missing values and set new values by <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy....
python|string|pandas|dataframe|nan
2
3,021
65,079,318
AttributeError: 'str' object has no attribute 'dim' in pytorch
<p>I got the following error output in the PyTorch when sent model predictions into the model. Does anyone know what's going on?</p> <p>Following are the architecture model that I created, in the error output, it shows the issue exists in the x = self.fc1(cls_hs) line.</p> <pre><code>class BERT_Arch(nn.Module): de...
<p><strong>If you work with transformers==3.0.0, everything should work fine !</strong></p> <p>There were some updates in transformers==4.0.0</p> <p>To get transformers==3.0.0, following command can be used:</p> <pre><code>!pip install transformers==3.0.0 </code></pre>
python|python-3.x|tensorflow|machine-learning|bert-language-model
5
3,022
49,827,646
how to draw multiple distribution
<pre><code>fig_dspl, axes_dspl = plt.subplots(nrows=1, ncols=2, figsize=(9, 4)) sns.distplot(df_08['displ'], ax = axes_dspl[0]) _ = axes_dspl[0].set_title('08') sns.distplot(df_18['displ'], ax = axes_dspl[1]) _ = axes_dspl[1].set_title('18') </code></pre> <p>can anyone explain the detail of this code above? especial...
<p>Create two plots, get the figures and axes</p> <pre><code>fig_dspl, axes_dspl = plt.subplots(nrows=1, ncols=2, figsize=(9, 4)) </code></pre> <p>In the first axes, draw a <code>seaborn.distplot</code>.</p> <pre><code>sns.distplot(df_08['displ'], ax = axes_dspl[0]) </code></pre> <p>Set <code>'08'</code> as the ti...
pandas
1
3,023
49,909,538
mapping a multi-index to existing pandas dataframe columns using separate dataframe
<p>I have an existing data frame in the following format (let's call it <code>df</code>):</p> <pre><code> A B C D 0 1 2 1 4 1 3 0 2 2 2 1 5 3 1 </code></pre> <p>The column names were extracted from a spreadsheet that ...
<pre><code>d = dict(zip(cat_df['current category'], cat_df.index)) cols = pd.MultiIndex.from_arrays([df.columns.map(d.get), df.columns]) df.set_axis(cols, axis=1, inplace=False) X Y Z A B C D 0 1 2 1 4 1 3 0 2 2 2 1 5 3 1 </code></pre> <hr> <pre><code>df_new = df.set_axis(cols, axis=1, inp...
python|pandas|indexing
4
3,024
63,917,912
CNN image to image regression output has very high loss 99.3%
<p>I have a deep learning model that takes 4d image as input and predicts 1D image. But my loss is very high. Could anyone help me find out why.</p> <p>sample input images: [1st dimension[][1]][1]+[2nd dimension][2]+[3rd dimension][3]+[4th dimension][4]==== output [desired output image][5]</p> <p>information contain ou...
<p>I think you can perform few of the following checks to figure out the problem:</p> <ul> <li>Check if target image is being loaded correctly</li> <li>Change optimizer and play around with learning rate</li> <li>Train for few more epochs to see if loss is converging</li> <li>Sometimes the loss function has poor conver...
python|tensorflow|keras|conv-neural-network
0
3,025
64,118,032
TypeError: Value passed to parameter 'input' has DataType bool not in list of allowed values: float32, float64, int32, uint8, int16, int8
<p>I have a dataset with 5 labels</p> <pre><code>def get_label(file_path): # convert the path to a list of path components parts = tf.strings.split(file_path, os.path.sep) class_names = ['daisy' 'dandelion' 'roses' 'sunflowers' 'tulips'] # The second to last is the class-directory one_hot = parts[-2] == class...
<p>I was having the same problem. Following the idea of ​​the last post:</p> <pre><code>one_hot = tf.dtypes.cast(parts[-2] == class_names, dtype = tf.int16) </code></pre>
python|tensorflow2.x
2
3,026
64,049,466
How to avoid df.apply running twice top row
<p>I am aware that the method <code>apply</code> run twice the top row to see if it can optimize my code.</p> <p>Is there a way to use <code>apply</code> without running twice on the first row?</p> <p>Here is my code:</p> <pre><code>df[[&quot;A&quot;, &quot;B&quot;]] = df.apply(lambda x: pd.Series(create_store(x[&quot;...
<p>You can pass a <code>tuple</code> of those 2 columns to the function such as</p> <pre><code>def create_store(tuple): ... tuple[0] #instead of x[&quot;C&quot;] tuple[1] #instead of X[&quot;D&quot;] </code></pre>
pandas|dataframe
0
3,027
63,789,152
How to append a value in a new column to Null rows in Pandas
<p>Hello stackoverflow community</p> <p>This is my sample data</p> <pre><code>Code Sales HeadQuarter CC 1000 XYZ AA NaN YYZ BB 2000 NaN DD NaN NaN </code></pre> <p>As I have to append a new column to respective rows that contains atleast one NaN value. The ne...
<p>Test missing values and get at least on <code>True</code> per row for mask and create new column in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a>:</p> <pre><code>df.loc[df.isna().any(axis=1), 'New_column'] = 1 pr...
pandas|dataframe
4
3,028
63,916,699
Delete row if the front row is the same in pandas
<p>I have a dataframe and want to delete row if the front row is the same.</p> <p>My current code:</p> <pre><code>df = pd.read_csv(&quot;MyCSV.csv&quot;, &quot;;&quot;) df_2 = df.loc[:,['A', 'B', 'C', 'D']] for i in df_2.itertuples(): if df_2[i] == df_2[i+1]: print(df) </code></pre> <p>I have this input datafra...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.shift.html" rel="nofollow noreferrer"><code>shift</code></a> to do this as follows:</p> <pre><code>cols = ['A', 'B', 'C', 'D'] df.loc[(df[cols].shift(-1) == df[cols]).all(1)] </code></pre> <p>Resulting dataframe:</p> <pre><code>time ...
python|pandas|numpy
1
3,029
64,013,033
How to run function for multitude of arrays
<p>so I need to analyse the peak number &amp; width of a signal (in my case Calcium signal from epidermis cells) that I have stored in an excelsheet. Each column has all the values for one Cell (600 values)</p> <p>To analyse the peaks, which I will be duing with the <code>scipy.signal.find_peaks()</code> and <code>scip...
<p>The proposal would be as follows. In essence you firstly select the required columns (however many there are). Then you create a function that will take in a column (no need to turn it into arrays, unless <code>scipy</code> disagrees, in that case add <code>column = column.values</code> in the top of <code>process</...
python|arrays|excel|numpy|scipy
0
3,030
64,093,423
Efficient Way of subset a dataframe into small ones based on unique values and simultaneously write out to csv file
<p>What is the most efficient way to subset a large dataframe <code>df</code> into small subsets based on a unique/ filter condition? For example, I have a dataset with a dimension of 22050 rows with 5 columns, something like this</p> <pre><code>id, nationality, age, gender, income 10001, France, 20, M, 45007 13328, U...
<p>In <code>base R</code>, we can split the data by the 'nationality' column into a <code>list</code> of <code>data.frame</code></p> <pre><code>lst1 &lt;- split(df, df$nationality) </code></pre> <p>Then loop over the <code>list</code> and write it to different files</p> <pre><code>lapply(names(lst1), function(nm) write...
python|r|pandas|dataframe|csv
1
3,031
46,933,324
Data doesn't match to original data after converting to TFRecord
<blockquote> <p><strong>TL: DR;</strong></p> </blockquote> <p>After converting my data to TFRecord it doesn't match with original data </p> <blockquote> <p><strong>Description:</strong></p> </blockquote> <p>I made a <a href="https://gist.github.com/niyamatalmass/b4e8f14d0a853b109035cc0973c03189" rel="nofollow no...
<blockquote> <p>I found the solutions. The problem is in my test case where I made my fake data for testing purpose. <strong>The generation of fake data is wrong.</strong></p> </blockquote> <p>I changed my code from this </p> <pre><code>records = [self._record(0, 128, 255), self._record(255, 0, 1),...
tensorflow
0
3,032
63,069,555
Input 0 of layer sequential is incompatible with the layer
<p>I created a model and then loaded it in another script and try to perform a prediction from it however I can not understand why the shape being passed to the function is incorrect.</p> <p>This is how the model is created:</p> <pre><code>batch_size = 1232 epochs = 5 IMG_HEIGHT = 400 IMG_WIDTH = 400 model1 = np.load(...
<p>Add extra dimension to your input as [n_items,400,400,3]</p> <pre><code>import tensorflow as tf X_train = tf.expand_dims(X_train, axis =-1) </code></pre>
python|numpy|tensorflow|machine-learning|keras
0
3,033
68,007,737
pandas merge with multiindex columns but single index index
<p>I am using Python 3.8.6 with pandas version 1.2.4</p> <p>I want to do a self join on previous rows with this dataframe:</p> <pre><code> bar one index 0 0.238307 1 0.610819 </code></pre> <p>so i pre...
<p>The answer I discovered is:</p> <pre><code>left=left.set_index(('index','')) right=right.set_index(('index1','')) dfJoined=pd.merge(left,right,left_index=True,right_index=True,suffixes=('_n','_p')) </code></pre> <p>produces</p> <pre><code> bar_n bar_p one one 1 1.719833 -0.540152 #differ...
python|pandas|dataframe|multi-index
0
3,034
67,730,008
How to More Efficiently Pivot Semi Colon Separated Columns into a 0/1/2 Indicator Matrix?
<p>I am starting with a pandas Dataframe that is generated by the following code:</p> <pre><code>import pandas as pd data = {'basket_1':['apple;banana;orange', 'apple;banana;mango', 'mango;orange;grapefruit'], 'basket_2':['pineapple;strawberry;peach', 'peach;lemon;guava', 'strawberry;peach;guava']} # Create...
<p>Here is one option,</p> <ol> <li><p>create dataframe by appending all the columns from fruits list to current df</p> </li> <li><p>User <code>str.get_dummies</code> to generate dummy columns and assign to original df</p> </li> <li><p>For basket 2, add 1 to ensure str.get_dummies returns 2 as value instead of 1</p> </...
python|pandas|performance|lambda|pivot
2
3,035
67,823,698
Python Pandas count values and create summary dataframe
<p>I have a DF that contains multiple events for multiple customers. The important columns are:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Customer</th> <th>Result</th> </tr> </thead> <tbody> <tr> <td>cust1</td> <td>OK</td> </tr> <tr> <td>cust1</td> <td>OK</td> </tr> <tr> <td>cust1</td...
<p>Try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html#pandas-crosstab" rel="nofollow noreferrer"><code>pd.crosstab</code></a>:</p> <pre><code>new_df = pd.crosstab(df['Customer'], df['Result']) new_df['SUCCESS_RATE'] = new_df['OK'] / new_df.sum(axis=1) * 100 new_df = new_df.rena...
python|pandas|dataframe
2
3,036
67,838,047
Delete model from GPU/CPU in Pytorch
<p>I have a big issue with memory. I am developing a big application with GUI for testing and optimizing neural networks. The main program is showing the GUI, but training is done in thread. In my app I need to train many models with different parameters one after one. To do this I need to create a model for each attem...
<p>Assuming that the model creation code is run iteratively inside a loop,I suggest the following</p> <ol> <li>Put code for model creation, training,evaluation and model deletion code inside a separate function and call that function from the loop body.</li> <li>Call <code>gc.collect()</code> after the function call</l...
python|memory|pytorch|gpu|cpu
0
3,037
68,597,317
I am unable to run streamlit on pycharm and spyder. I am running the latest python version on window.When I try what the code ,it says invalid syntax
<p>#This code is used to open streamlit in browser</p> <p>import streamlit import streamlit as st import pandas as pd from FPL import predict_team, get_overview_data, extract_player_roster, <br /> extract_teams_data, extract_player_types import matplotlib.pyplot as plt import numpy as np pd.options.display.float_format...
<p>Use command prompt and Go to project Directory where the streamlit file stored. than &quot;streamlit run &lt;filename.py&gt;&quot;</p> <p>after that an url page will open where you can see your application.</p>
python-3.x|pandas|numpy|data-science|streamlit
0
3,038
53,165,807
How to calculate RMSPE in python using numpy
<p>I am doing a multivariate forecasting using the <a href="https://www.kaggle.com/c/rossmann-store-sales#description" rel="nofollow noreferrer">Rossmann dataset.</a> I now need to use the RMSPE metric to evaluate my model. I saw the relevant formula <a href="https://www.kaggle.com/c/rossmann-store-sales#evaluation" re...
<p>You can take advantage of numpy's vectorisation capability for an error metric like this. The following function can be used to compute RMSPE:</p> <pre><code>def rmse(y_true, y_pred): ''' Compute Root Mean Square Percentage Error between two arrays. ''' loss = np.sqrt(np.mean(np.square(((y_true - y...
python-3.x|numpy|machine-learning
5
3,039
65,683,052
Is it possible to save Tensorboad session?
<p>I'm using Tensorboard and would like to save and send my report (email outside my organization), without losing interactive abilities. I've tried to save it as a complete html but that didn't work. Anyone encountered the same issue and found a solution?</p>
<p>Have you seen <a href="https://tensorboard.dev/" rel="nofollow noreferrer"><code>tensorboard.dev</code></a>?</p> <p>This page allows you to host your tensorboard experiment &amp; share it with others using a link (it's still interactive) for free.</p> <p>Also you can use it from the command line; try this from your ...
tensorflow|pytorch|tensorboard
1
3,040
63,641,431
How to interpret cosine similarity output in python
<p>beginner @ Python here. I have a pandas DataFrame <strong>df</strong> with the columns: <strong>userID</strong>, <strong>weight</strong>, <strong>SEI</strong>, <strong>name</strong>.</p> <pre><code>#libraries import numpy as np; import pandas as pd from sklearn.metrics.pairwise import cosine_similarity #...
<p>Make it easier for yourself and group by two columns</p> <pre><code>result1=df.sort_values('weight') result2=(result1.groupby(['userID_x','SEI']).apply(lambda g: cosine_similarity(g['weight'].values.reshape(1, -1), g['artist'].values.reshape(1,-1))[0][0])).rename('CosSim').reset_index() </code></...
python|pandas|dataframe|cosine-similarity
0
3,041
63,718,817
I want to extract data from the Data Frame based on first letters of column
<p>I have data frame like this:</p> <pre><code> Flt Desg Eff Date Dis Date day of week Routing 0 AI 0922 8-May 8-May ....fri,.. riyadh-calicut 1 AI 0381 8-May 12-May .tue,..fri,.. singapore-delhi 2 AI 1242 8-May 13-May .tue,wed,.fri,.. ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.startswith.html" rel="nofollow noreferrer"><code>Series.str.startswith</...
python|pandas
1
3,042
63,419,636
show error bar in multi line plot using matplotlib
<p>I've created a multi line plot using marplot lib, and now I want to show the min-max value for each parameter on X-axis. My code is below:</p> <pre><code>import numpy as np import pandas as pd from pandas import DataFrame import matplotlib.pyplot as plt from matplotlib import pyplot as plt import seaborn as sns df ...
<p><code>plt.errorbar()</code> draws lineplots with error bars. It's parameters are quite similar to <code>plt.plot()</code>. The xlims need to be a bit wider to avoid the error bars being cut by the plot borders.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd import matplotl...
python|pandas|matplotlib
2
3,043
53,796,915
Confidence level smaller than 0 with python linear regression
<p>My have the share prices df2[x] below as Y:</p> <pre><code>2018-09-05 6.22 2018-09-06 6.19 2018-09-07 6.22 2018-09-10 6.24 2018-09-11 6.24 </code></pre> <p>...</p> <pre><code>2018-12-05 4.65 2018-12-14 0.00 </code></pre> <p>short position csvReader5[x] as X:</p> <pre><code>2018-09-06 1.1...
<p>From sklearn documentation:</p> <pre><code>score(X, y, sample_weight=None) </code></pre> <p>Returns the coefficient of determination R^2 of the prediction.</p> <p>The coefficient <code>R^2</code> is defined as <code>(1 - u/v)</code>, where u is the residual sum of squares <code>((y_true - y_pred) ** 2).sum()</cod...
python|numpy|dataframe|scikit-learn|linear-regression
2
3,044
53,357,687
How to test Tensorflowlite model with multiple inputs?
<p>I created a simple MLP Regression Keras model with 4 inputs and one output. I converted this model to TFlite now I'm just trying to find out how to test it on android studio. How can I input multiple 4D objects to test in Java? The following gives an error when trying to run the model:</p> <pre><code>try{ ...
<p>If your inputs are actually 4 separate tensors, then you should use the <code>Interpreter.runForMultipleInputsAndOutputs</code> API which allows multiple separate inputs. See also <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/java/src/test/java/org/tensorflow/lite/InterpreterTest.java...
android|tensorflow|keras|tensorflow-lite
2
3,045
71,879,152
Is there a way to allocate remaining GPU to your code on PyTorch?
<ol> <li>Is there a way to allocate the remaining memory in each GPU for your task?</li> <li>Can I split my task across multiple GPU's?</li> </ol> <p><a href="https://i.stack.imgur.com/aRXza.png" rel="nofollow noreferrer">nvidia-smi for your reference</a></p>
<ol> <li>Yes. PyTorch is able to use any remaining GPU capacity given that there is enough memory. You only need to specify which GPUs to use: <a href="https://stackoverflow.com/a/39661999/10702372">https://stackoverflow.com/a/39661999/10702372</a></li> <li>Yes. GPU parallelism is implemented using PyTorch's <a href="h...
python|pytorch|gpu|nvidia-smi
0
3,046
71,968,141
How to correspondence of unique values ​between 2 tables?
<p>I am fairly new to Python and I am trying to create a new function to work on my project. The function will aim to detect which unique value is present in another column of another table.</p> <p>At first, the function seeks to keep only the unique values ​​of the two tables, then merges them into a new dataframe</p>...
<p>First use outer join with remove duplicates by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.drop_duplicates.html" rel="nofollow noreferrer"><code>Series.drop_duplicates</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.reset_index.html...
python-3.x|pandas|dataframe|foreign-keys
0
3,047
55,173,994
Pandas Data Frame add new calculated field using Partitioned Data
<p>I am trying to add a new calculated field. I am trying the 2nd best answer in <a href="https://stackoverflow.com/questions/12376863/adding-calculated-columns-to-a-dataframe-in-pandas">Adding calculated column(s) to a dataframe in pandas</a> because it seems the best in my opinion as it is neat. Please feel free to...
<p>I think you are looking for </p> <pre><code>dt_nba["Salary"]=dt_nba["Salary"].map(GetSalaryIncrement) </code></pre> <p>Also you can do with </p> <pre><code>GetSalaryIncrement(dt_nba["Salary"]) </code></pre> <hr> <pre><code>dt_nba["Salary"].apply(GetSalaryIncrement) </code></pre> <hr> <p>To calculated<code>IN...
python|pandas
3
3,048
55,424,526
Conversion from DatetimeIndex to datetime64[s] via int without dividing by 1e9 possible?
<p>Is it possible to convert from a DatetimeIndex to datetime64[s] array via int array without dividing by <code>1e9?</code></p> <p>The following code delivers an int numpy array, but I have to divide by <code>1e9</code> to get from nanoseconds to seconds. </p> <p>Is it possible to take this journey (DatetimeIndex, i...
<p>I think you can do it by modifying your code. Use astype('datetime64[s]') instead.</p> <pre><code>datetimeIndexAs10e9int = datetimeIndex.values.astype('datetime64[s]') </code></pre>
python|pandas|numpy
1
3,049
56,520,780
How to use geopanda or shapely to find nearest point in same geodataframe
<p>I have a geodataframe showing ~25 locations represented as point geometry. I am trying to come up with a script that goes through each point, identifies the nearest location and returns the name of the nearest location and the distance.</p> <p>I can easily do this if I have different geodataframes using nearest_poin...
<p>Shapely's nearest_points function compares shapely geometries. To compare a single Point geometry against multiple other Point geometries, you can use .unary_union to compare against the resulting MultiPoint geometry. And yes, at each row operation, drop the respective point so it is not compared against itself.</p>...
python|gis|geopandas|shapely
10
3,050
67,090,699
How to include rgb and grayscale images in CNN using tf.data?
<p>I am trying to use rgb images as input and grayscale images as label image based on <a href="https://stackoverflow.com/questions/37340129/tensorflow-training-on-my-own-image">this post</a>. How can I modify the following code to define that the label images contain one channel?</p> <pre><code># step 1 filenames = tf...
<p>Use this function to load an image with a varying number of channels:</p> <pre><code>def _parse_function(filename, channels): image_string = tf.io.read_file(filename) image = tf.image.decode_jpeg(image_string, channels=channels) image = tf.image.convert_image_dtype(image, tf.float32) return image </...
python|tensorflow|conv-neural-network
0
3,051
67,069,940
ValueError in binning the dataframe with lists of values
<p>I am attempting to assign bins to a dataframe, I am doing this but creating bins then passing them as an argument but it keeps failing (probably because the dataframe has lists of values instead of values)</p> <p>I am trying to set the frequencies of a column into bins. Each frequency in the column is a list of freq...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>DataFrame.explode</code></a> it first if want use <code>pd.cut</code>, because it cannot working with <code>list</code> (like many pandas methods):</p> <pre><code>df = final_lut....
python-3.x|pandas|dataframe|numpy|nested-lists
1
3,052
66,911,400
TypeError: Can not convert a NoneType into a Tensor or Operation -- Error believe related to converting to graph
<p>Below find my model:</p> <pre><code>class CustomModel(tf.keras.Model): def __init__(self, model1, model2, model3, model4): super(deep_and_wide, self).__init__() self.model1 = model1 self.model2 = model2 self.model3 = model3 self.model4 = model4 def call(self, inputs):...
<p>This NoneType refers to the returned value of the custom train_step, when using a custom train_step you should return something that can be converted into a tensor so that the minimum control dependencies can process it, typically, the loss value as {&quot;loss&quot;: loss_value} and potentially some other metrics, ...
tensorflow|tf.keras
0
3,053
68,268,440
Python : How to assign ranks to categorical variables within a group in Python
<p>Given I have a dataset containing only the first two columns, how do I create another column using Python which will contain the rank based on these ranges for each group separately. My desired output would look like this -</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-alig...
<p>Convert your range column to a category dtype before apply <code>rank</code>:</p> <pre><code>df['range'] = df['range'].astype(pd.CategoricalDtype( ['5-10', '10-20', '20-30', '30+'], ordered=True)) df['rank'] = df.groupby('id')['range'].apply(lambda x: x.rank()) </code></pre> <pre><code>&gt;&gt;&g...
python|pandas|dataframe
2
3,054
68,149,692
Load HDF5 checkpoint models with custom metrics
<p>I've created a Keras Regressor to run a RandomizedSearch CV using a ModelCheckpoint callback, but the training overran the Colab runtime 12H limit and stopped halfway through. The models are saved in <code>hdf5</code> format.</p> <p>I used <code>tensorflow_addons</code> to add the <code>RSquare</code> class to monit...
<p>This solution doesn't take into account the addons package but one possibility is to create the coefficient of determination (R^2) as a different metric without that package, and then defining it as your loss.</p> <pre><code> def coeff_determination(y_true, y_pred): from keras import backend as K ...
tensorflow|keras
0
3,055
59,273,092
How to build Pytorch Mobile sample HelloWorld app?
<p><a href="https://pytorch.org/mobile/android/" rel="nofollow noreferrer">https://pytorch.org/mobile/android/</a></p> <p>I am trying to build a Pytorch demo HelloWorld app for Android. My machine is MacOS Mojave where I installed Python3 and Torchvision via conda. I am new to Pytorch, Pytorch mobile and gradlew etc.....
<p>Probably Android SDK wasn't found, try: <code>export ANDROID_HOME=/path/to/android/sdk</code></p> <p>Default location on linux: ~/Android/SDK/</p>
android|gradle|pytorch
-1
3,056
57,087,242
Print the elements of an array with certain rules
<p>My title might be confusing but I do not know what to put. Currently, I am trying to learn about RBF-Kernel-PCA from a book and I am at the code where they load the dataset and then plot the dataset with code like below:</p> <pre><code>from scipy.spatial.distance import pdist, squareform from scipy import exp fro...
<p>It's more like <code>X[(y==0), 1]</code>, note the parentheses. Specifically this code is selecting each row where <code>y==0</code>, and then the 1 is the column (the second column). The comma separates the axes of the <code>X</code> array. For example, let's have these arrays <code>X</code> and <code>y</code>:</p>...
python|numpy|scipy
1
3,057
45,724,470
A masked array indexing issue
<p>I have a numpy array with some <code>NaN</code> values:</p> <pre><code>arr = [ 0, NaN, 2, NaN, NaN, 5, 6, 7 ] </code></pre> <p>Using some logic (outside of the question scope), I generate a mask of the NaN locations:</p> <pre><code>mask = [ True, False, True, False, False, True, True, True ] </code></pre> <p>I u...
<p>You can flat the mask which returns indices from the original array, and then use the new indices to subset the mask indices:</p> <pre><code>mask = np.array([ True, False, True, False, False, True, True, True ]) indices = [1,3] np.flatnonzero(mask)[indices] # array([2, 6]) </code></pre>
python|arrays|numpy|indexing
3
3,058
46,127,625
Need To Compile Keras Model Before `model.evaluate()`
<p>I load a <code>Keras</code> model from <strong>.json</strong> and <strong>.hdf5</strong> files. When I call <code>model.evaluate()</code>, it returns an error:</p> <blockquote> <p>You must compile a model before training/testing. Use `model.compile(optimizer, loss)</p> </blockquote> <p>Why do I need to compile t...
<p>Because <a href="https://keras.io/models/model/#evaluate" rel="noreferrer"><code>evaluate</code></a> will calculate the <strong>loss function and the metrics</strong>.</p> <p>You don't have any of them until you compile the model. They're parameters to the compile method:</p> <pre><code>model.compile(optimizer=..., ...
tensorflow|keras
32
3,059
45,765,421
What is the Python idiom for chaining tensor products?
<p>Numpy's <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.outer.html" rel="nofollow noreferrer"><code>outer</code></a> flattens its arguments. As a result it isn't possible to chain <code>outer</code> to implement the mathematical definition of the <a href="https://math.stackexchange.com/a/1507752/...
<p>The <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.outer.html#numpy.ufunc.outer" rel="nofollow noreferrer"><code>outer</code> method</a> of NumPy ufuncs doesn't flatten:</p> <pre><code>outer = numpy.multiply.outer result = outer(a, outer(b, c)) </code></pre>
python|numpy|tensorflow
2
3,060
46,123,291
Tensorflow - use previously learned weights to initialize new weights of different dimensions
<p>I'm trying to use previously learned weights of dimension <code>m</code> to initialize a weight tensor of dimension <code>n</code> where <code>n &gt; m</code>. I can do it as I've done below.</p> <pre><code>all_weights['w1'] = tf.Variable(tf.zeros([n, output_sz], dtype=tf.float32)) all_weights['w1'] = all_weights['...
<p><code>tf.Variable</code> is a very different thing from <code>Tensor</code>. It does not make sense to "cast" between them.</p> <p>The easiest solution is to just use the <code>initial_weights</code> directly in the <code>Variable</code> creation. For example, something like this:</p> <pre><code>import numpy as np...
python|tensorflow
1
3,061
51,018,409
Compare dictionaries and show only the differences in Python?
<p>I have two dictionaries and would like to compare them and list the differences: I thought about doing it as they are dictionaries which is not that easy after checking other answers here. One other way is to turn them to dataframe with pandas? I would like to take into consideration the same columns that are not in...
<p>If you just want to find the symmetric differences between two of the OrderedDicts,</p> <pre><code>from collections import OrderedDict &gt;&gt;&gt; d1 = {'properties': OrderedDict([('KAEK', 'str:12'), ... ('PROP_TYPE', 'str:4'), ... ('ORI_TYPE', 'int:1')... &gt;&gt;&gt; d1 = d1['proper...
python|pandas|dictionary
2
3,062
70,523,947
Conditional combination of arrays row by row
<p>The task is to combine two arrays row by row (construct the permutations) based on the resulting multiplication of two corresponding vectors. Such as:</p> <p>Row1_A, Row2_A, Row3_A,</p> <p>Row1_B, Row2_B, Row3_B,</p> <p>The result should be: Row1_A_Row1_B, Row1_A_Row2_B, Row1_A_Row3_B, Row2_A_Row1_B, etc..</p> <p>Gi...
<p>First of all, there is a <strong>more efficient algorithm</strong>. Indeed, you can pre-compute the size of the output array so the values can be <strong>directly written</strong> in the final output arrays rather than stored temporary in lists. To find the size efficiently, you can <strong>sort</strong> the array <...
python|numpy|performance|vectorization
1
3,063
51,521,732
Convert categories to columns in dataframe python
<p>I have a dataframe which contains two columns. One column contains different categories and other contains values.</p> <pre><code>import pandas as pd data={&quot;category&quot;:[&quot;Topic1&quot;,&quot;Topic2&quot;,&quot;Topic3&quot;,&quot;Topic2&quot;,&quot;Topic1&quot;,&quot;Topic3&quot;], &quot;value&quot;:[&qu...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.concat.html" rel="noreferrer"><code>pandas.concat</code></a> along <code>axis=1</code>. This will also work for mismatched lengths.</p> <pre><code>grouper = df.groupby('category') df = pd.concat([pd.Series(v['value'].tolist(), ...
python|pandas|dataframe|transpose
5
3,064
70,854,490
How can I do an if statement on a pandas dataframe to check multiple columns for specific values?
<p>I am wanting to check a pandas dataframe to see if two columns match two unique values. I know have to check one column at a time, but not two at once.</p> <p>Basically, I want to see if the person's last name is 'Smith' and their first name is either 'John' or 'Tom' all at the same time.</p> <p>My code:</p> <pre cl...
<p>You want to filter rows where the last name is &quot;Smith&quot; AND the first name is either &quot;John&quot; OR &quot;Tom&quot;. This means it's either &quot;John Smith&quot; OR &quot;Tom Smith&quot;. This is equivalent to</p> <pre><code>(last_name==&quot;Smith&quot; AND first_name==&quot;John&quot;) OR (last_name...
python|pandas
1
3,065
51,815,010
Simple Linear Regression using CSV data file Sklearn
<p>I have been trying this for the last few days and not luck. What I want to do is do a simple Linear regression fit and predict using sklearn, but I cannot get the data to work with the model. I know I am not reshaping my data right I just dont know how to do that.<br> Any help on this will be appreciated. I have bee...
<p>Use :</p> <pre><code>X = dataframe.iloc[:,0:-1] y = dataframe.iloc[:,-1] </code></pre>
python|pandas|numpy|scikit-learn
5
3,066
51,648,278
No module named tensorflow.python on windows 10 when I run classify_image.py
<p>I'm trying to use tensorflow to run classify_image.py, but I keep getting the same error: <code>Traceback (most recent call last): File "classify_image.py", line 46, in &lt;module&gt; import tensorflow as tf File "C:\Users\Diederik\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\__init__...
<p>I simply needed to add a python path, that was the only problem</p>
python|tensorflow|artificial-intelligence|image-recognition
0
3,067
37,486,502
why does pandas rolling use single dimension ndarray
<p>I was motivated to use pandas <code>rolling</code> feature to perform a rolling multi-factor regression (This question is <strong>NOT</strong> about rolling multi-factor regression). I expected that I'd be able to use <code>apply</code> after a <code>df.rolling(2)</code> and take the resulting <code>pd.DataFrame</c...
<p>I wanted to share what I've done to work around this problem.</p> <p>Given a <code>pd.DataFrame</code> and a window, I generate a stacked <code>ndarray</code> using <code>np.dstack</code> (<a href="https://stackoverflow.com/a/37448165/2336654"><strong>see answer</strong></a>). I then convert it to a <code>pd.Panel...
python|pandas|numpy|group-by|pandas-groupby
11
3,068
37,493,723
How do I create a "not" filter in python for pandas
<p>I have this large dataframe I've imported into pandas and I want to chop it down via a filter. Here is my basic sample code:</p> <pre><code>import pandas as pd import numpy as np from pandas import Series, DataFrame df = DataFrame({'A':[12345,0,3005,0,0,16455,16454,10694,3005],'B':[0,0,0,1,2,4,3,5,6]}) df2= df[d...
<p>No need for map function call on Series "A".</p> <p>Apply <a href="https://en.wikipedia.org/wiki/De_Morgan%27s_laws" rel="noreferrer">De Morgan's Law</a>:</p> <p><strong>"not (A and B)" is the same as "(not A) or (not B)"</strong></p> <pre><code>df2 = df[~(df.A &gt; 0) | ~(df.B &gt; 0)] </code></pre>
python|python-2.7|pandas
37
3,069
41,895,832
convert dataframe type object to dictionary
<p>I have the dataframe <code>best_scores</code> contanining</p> <pre><code> subsample colsample_bytree learning_rate max_depth min_child_weight \ 3321 0.8 0.8 0.3 2 3 objective scale_pos_weight silent 3321 binary:logistic 1.846154 ...
<p>You are getting a list of dictionaries, because you are converting a <code>DataFrame</code> to <code>dict</code>, which can potentially have multiple rows. Each row would be one entry in the list.</p> <p>Apart from the mentioned solution to simply select the first entry, the ideal way to achieve what you want is to...
python|pandas|dictionary|dataframe
1
3,070
37,716,699
How to hstack several sparse matrices (feature matrices)?
<p>I have 3 sparse matrices:</p> <pre><code>In [39]: mat1 Out[39]: (1, 878049) &lt;1x878049 sparse matrix of type '&lt;type 'numpy.int64'&gt;' with 878048 stored elements in Compressed Sparse Row format&gt; In [37]: mat2 Out[37]: (1, 878049) &lt;1x878049 sparse matrix of type '&lt;type 'numpy.int64'&gt;' ...
<p>Use the <code>sparse</code> versions of <code>vstack</code>. As general rule you need to use sparse functions and methods, not the <code>numpy</code> ones with similar name. <code>sparse</code> matrices are not subclasses of <code>numpy</code> <code>ndarray</code>.</p> <p>But, your 3 three matrices do not look sp...
python|numpy|machine-learning|scipy|scikit-learn
6
3,071
37,877,895
How to round a number to a chosen integer
<p>In Denmark we have an odd grading system that goes as follows. [-3,00,02,4,7,10,12] Our assignment is to take a vector with different decimal numbers, and round it to the nearest valid grade. Here is our code so far. </p> <pre><code>import numpy as np def roundGrade(grades): if (-5&lt;grades&lt;-1.5): ...
<p>You are getting that error because when you print, you are using incorrect syntax:</p> <pre><code>print(roundGrade(np.array[-2.1,6.3,8.9,9])) </code></pre> <p>needs to be</p> <pre><code>print(roundGrade(np.array([-2.1,6.3,8.9,9]))) </code></pre> <p>Notice the extra parentheses: <code>np.array(&lt;whatever&gt;)<...
python|numpy|rounding
26
3,072
64,378,278
Removing duplicate data doesn't seem to be actually removing dups?
<p>I am trying to preprocess some data and am running this command:</p> <pre><code>df = df[df.duplicated(subset=['ticker','periodDate'], keep='first')] </code></pre> <p>but when I look for dups, they are still there:</p> <pre><code>dups = df[df.duplicated(subset=['ticker','periodDate'], keep=False)] print (dups[dups['t...
<p><code>duplicated</code> returns the duplicated rows. By doing <code>df[df.duplicated(....)]</code>, you keep only the duplicated rows, instead of filtering them out.</p> <p>Use <code>~</code> to get the non-dupes:</p> <pre><code>df[~df.duplicated(subset=[....], keep='first')] </code></pre>
python|pandas
3
3,073
64,569,724
Tensorflow library ImportError: DLL load failed: The specified procedure could not be found
<p>I have installed Python 3.7 and tensorflow but when i &quot;import tensorflow as tf&quot; , i have the follow error</p> <p>&quot;Tensorflow library ImportError: DLL load failed: The specified procedure could not be found&quot;</p> <p>here is my code</p> <p><code>import tensorflow as tf</code></p>
<p>Maybe not the answer you are hoping for but what worked for me was just to downgrade the version of tensorflow to 2.0</p> <pre><code>pip install tensorflow==2.0 </code></pre>
python|tensorflow
0
3,074
64,403,398
Reading and Organizing a CSV without modules?
<p>I have multiple different csv files that have a different number of headers. I need to read these csv's without using any modules so I have given it an attempt. How would I print the columns of the different csv's and then be able to get the mean, min, max and standard deviation for each of them, as well as plot the...
<p>I've implemented <code>parse_csv()</code> function inside next code that uses no modules. It supports any separator (e.g. <code>,</code>) between cells and any quoting char (e.g. <code>&quot;</code>), also it correctly handles separators located inside quoted strings e.g. CSV line <code>&quot;a,b,c&quot;,d</code> wi...
python|pandas|csv
1
3,075
47,617,045
Expand numbers in a list
<p>I have a list of numbers:</p> <pre><code>[10,20,30] </code></pre> <p>What I need is to expand it according to a predefined increment. Thus, let's call <code>x</code> the increment and <code>x=2</code>, my result should be:</p> <pre><code>[10,12,14,16,18,20,22,24,.....,38] </code></pre> <p>Right now I am using a ...
<p>You can add the same set of increments to each time stamp using <code>np.add.outer</code> and then flatten the result using <code>ravel</code>.</p> <pre><code>import numpy as np a = [10,20,35] inc = 3 ninc = 4 np.add.outer(a, inc * np.arange(ninc)).ravel() # array([10, 13, 16, 19, 20, 23, 26, 29, 35, 38, 41, 44]) <...
python|list|loops|numpy
3
3,076
48,987,774
How to crop a numpy 2d array to non-zero values?
<p>Let's say i have a 2d boolean numpy array like this:</p> <pre><code>import numpy as np a = np.array([ [0,0,0,0,0,0], [0,1,0,1,0,0], [0,1,1,0,0,0], [0,0,0,0,0,0], ], dtype=bool) </code></pre> <p>How can i in general crop it to the smallest box (rectangle, kernel) that includes all True values?</p> ...
<p>After some more fiddling with this, i actually found a solution myself:</p> <pre><code>coords = np.argwhere(a) x_min, y_min = coords.min(axis=0) x_max, y_max = coords.max(axis=0) b = cropped = a[x_min:x_max+1, y_min:y_max+1] </code></pre> <p>The above works for boolean arrays out of the box. In case you have other...
arrays|numpy|crop
12
3,077
49,060,520
Remove apostrophe on python numpy matrix
<p>I'm trying yo solve a simple matrix problem on python 3 using numpy with this code:</p> <pre><code>import numpy change_array = numpy.array(input().strip().split(' ')) change_array.shape = (3,3) print(change_array) </code></pre> <p>The output of this program with input: <code>1 2 3 4 5 6 7 8 9</code> is </p> <p...
<p>One way or other you have to convert the strings to integers:</p> <pre><code>In [86]: x = np.array(input().strip().split()) 1 2 3 In [87]: x Out[87]: array(['1', '2', '3'], dtype='&lt;U1') # string dtype In [88]: x.astype(int) Out[88]: array([1, 2, 3]) </code></pre> <p>or</p> <pre><code>In [89]: x = np.array(in...
python|numpy|matrix
1
3,078
48,927,232
Python: Reproduce nested Excel Pivot table in python
<p><strong>Question:</strong></p> <p>Is it possible to display pandas report in exactly same format like excel?</p> <p><strong>Current situation:</strong></p> <p>I am trying to automate excel report using python. </p> <p>Excel report is in following format:</p> <p><a href="https://i.stack.imgur.com/YMELL.png" rel=...
<p>Do you want to save Pandas table as Pivot Table in .xlsx file? You'll never do it. There're libraries to save, edit and read Excel files, but there's no tool in them to work with Pivot Tables.</p>
python|excel|pandas|pivot-table
0
3,079
48,968,633
Clone items in a list by index
<p>I have a numpy array </p> <pre><code>np.array([[1,4,3,5,2], [3,2,5,2,3], [5,2,4,2,1]]) </code></pre> <p>and I want to clone items by their indexes. For example, I have an index of</p> <pre><code>np.array([[1,4], [2,4], [1,4]]) </code></pre> <p>These correspond to the posi...
<p>I commented that this could be viewed as a 1d problem. There's nothing 2d about it, except that you are adding 2 values per row, so you end up with a 2d array. The other key idea is that <code>np.repeats</code> lets us repeat selected elements several times.</p> <pre><code>In [70]: arr =np.array([[1,4,3,5,2], ...
python|arrays|numpy
2
3,080
58,890,298
Why does BeautifulSoup fail to extract data from websites to csv?
<p>User Chrisvdberge helped me creating the following code :</p> <pre><code>import pandas as pd import requests from bs4 import BeautifulSoup url_DAX = 'https://www.eurexchange.com/exchange-en/market-data/statistics/market-statistics-online/100!onlineStats?viewType=4&amp;productGroupId=13394&amp;productId=34642&amp;c...
<p>Try this to get those other sites. The last site is a little trickier, so you'd need to try out Selenium:</p> <pre><code>import pandas as pd import requests from bs4 import BeautifulSoup from datetime import date, timedelta url_DAX = 'https://www.eurexchange.com/exchange-en/market-data/statistics/market-statistics...
python|pandas|beautifulsoup|export-to-csv
1
3,081
56,020,272
Convert Rows per Unique Id into all comma separated possibilities
<p>i have some data in the following format, at the moment this is in a Pandas Dataframe. </p> <pre><code>Row Uid Lender 1 1 HSBC 2 1 Lloyds 3 1 Barclays 4 2 Lloyds 5 2 Barclays 6 2 Santander 7 2 RBS 8 2 HSBC </code></pre> <p>What i require ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer"><code>GroupBy.apply</code></a> with custom function and join tuples by <code>join</code>:</p> <pre><code>from itertools import chain, combinations #https://stackoverflow.com/a/58...
python|pandas|dataframe|combinations
5
3,082
55,638,334
Data Type for numpy.rand.seed()
<p>Trying to input a seed runtime through command line option, hence wanted to understand what is the data type of numpy.rand.seed()</p>
<p>According to <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.seed.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.seed.html</a> it must be an integer or an 1-d array of integers convertible to an unsigned 32-bit integer. So you should be fi...
python|numpy
0
3,083
64,821,025
How can I reshape 1D np array into 3D?
<p>I have my 699 training features stored in the array X.</p> <pre><code>X.shape </code></pre> <p>(699,)</p> <p>Each row is however 1292 * 13</p> <p>For instance:</p> <pre><code>X[0].shape </code></pre> <p>(1292, 13)</p> <p>How can I reshape it correctly to input into a CNN?</p>
<p>In order to put them in a keras Conv2D for example, you must have a specific input_shape.</p> <p>So , your number of samples is 699 and your shape is (1292, 13, 1) . The last dimension (1) is the number of channels, so if you have gray images (or something else) you put 1 , if you have color you put 3.</p> <p>So so...
python-3.x|numpy|keras|numpy-ndarray
0
3,084
40,027,612
Apply a function to pandas dataframe and get different sized ndarray output
<p>My goal is to get the indexes of the local max heights of a dataframe. These change between 3 and 5 per column.</p> <p>I have tried using the apply function, but get either the error <code>Shape of passed values is (736, 4), indices imply (736, 480)</code> or <code>could not broadcast input array from shape (0) int...
<p>pandas is trying to do "something" with the arrays. You can short circuit that "something" by wrapping your <code>lambda</code>'s return value in a <code>pd.Series</code></p> <p>Try this:</p> <pre><code>df.apply(lambda x: pd.Series(peakutils.indexes(x, thres=0.02/max(x), min_dist=100))) </code></pre>
python|python-3.x|pandas|scipy
2
3,085
39,433,655
What's the best way to print some samples of the predicted results during training of the model?
<p>I want to ask the model to predict the output for some random samples during the learning process. Currently, I built a class which derived from <code>tf.contrib.learn.monitors.EveryN</code> and overwrite <code>every_n_step_end</code> as follows:</p> <pre><code>def every_n_step_end(self, step, outputs): # evaluat...
<p><code>predict</code> method get an input function(<code>input_fn</code>) to preprocess and feed data into your models. So it's easy to create an input function and then pass it to <code>predict</code> method to get a list of predicted probabilities. See <a href="https://www.tensorflow.org/versions/master/tutorials/i...
tensorflow
0
3,086
44,045,066
Efficient use of numpy_indexed output
<pre><code>&gt;&gt;&gt; import numpy_indexed as npi &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.array([[0,0,1,1,2,2], [4,4,8,8,10,10]]).T &gt;&gt;&gt; a array([[ 0, 4], [ 0, 4], [ 1, 8], [ 1, 8], [ 2, 10], [ 2, 10]]) &gt;&gt;&gt; npi.group_by(a[:, 0]).sum(a[:,1]) (array([...
<p>One approach with <a href="https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.unique.html" rel="nofollow noreferrer"><code>np.unique</code></a> to generate those unique tags and the interval shifting indices and then <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.reduceat.ht...
python|numpy|numpy-indexed
3
3,087
69,572,321
use numpy.linalg.multi_dot for 3-dimensional arrays of (N, M, M) shape
<p>Is that any reasonable way to use np.linalg.multi_dot() function with Nx2x2 arrays like functools.reduce(np.matmul, Nx2x2_arrays)? Please, see example below.</p> <pre><code>import numpy as np from functools import reduce m1 = np.array(range(16)).reshape(4, 2, 2) m2 = m1.copy() m3 = m1.copy() reduce(np.matmul, (m1,...
<p><code>np.linalg.multi_dot()</code> tries to optimize the operation by finding the order of dot products that leads to the fewest multiplications overall.</p> <p>As all your matrices are square, the order of dot products does not matter and you will always end up with the same number of multiplications.</p> <p>Intern...
python|arrays|numpy|matrix-multiplication
2
3,088
69,382,610
PandasNotImplementedError: The method `pd.Series.__iter__()` is not implemented. If you want to collect your data as an NumPy array
<p>I try to create a new column in Koalas dataframe <code>df</code>. The dataframe has 2 columns: <code>col1</code> and <code>col2</code>. I need to create a new column <code>newcol</code> as a median of <code>col1</code> and <code>col2</code> values.</p> <pre><code>import numpy as np import databricks.koalas as ks # ...
<p>I had the same problem. One caveat, I'm using pyspark.pandas instead of koalas, but my understanding is that pyspark.pandas came from koalas, so my solution might still help. I tried to test it with koalas but was unable to run a cluster with a reasonable version.</p> <pre class="lang-py prettyprint-override"><code>...
python|pandas|dataframe|databricks|spark-koalas
0
3,089
69,657,133
PyTorch bool value of tensor with more than one value is ambiguous
<p>I am trying to train a neural network with PyTorch, but I get the error in the title. I followed <a href="https://medium.com/analytics-vidhya/implementing-cnn-in-pytorch-with-custom-dataset-and-transfer-learning-1864daac14cc" rel="nofollow noreferrer">this tutorial</a>, and I just applied some small changes to meet ...
<p>The output of the model will be a discrete distribution over your 7 classes. To retrieve the predicted image you can directly apply an argmax over it:</p> <pre><code>scores = model(x) predictions = scores.argmax(1) </code></pre>
python|neural-network|pytorch
3
3,090
40,871,797
Tensorflow softmax_cross_entropy_with_logits asks for unscaled log probabilities
<p>I have noticed that <a href="https://www.tensorflow.org/versions/r0.12/api_docs/python/nn.html#softmax_cross_entropy_with_logits" rel="nofollow noreferrer"><code>tf.nn.softmax_cross_entropy_with_logits</code></a> asks for "unscaled log probabilities" for the logits argument. However, nowhere have I seen anyone sugg...
<p>You shouldn't perform a log operation. You shouldn't perform anything, actually :-). What this comment is (arguably poorly) trying to say is that each logit is an unrestricted real number (negative or positive, as big or as small as you want). The softmax cross entropy function will then (conceptually) apply the sof...
tensorflow
8
3,091
41,030,250
Apply a function to each row python
<p>I am trying to convert from UTC time to LocaleTime in my dataframe. I have a <code>dictionary</code> where I store the number of hours I need to shift for each country code. So for example if I have <code>df['CountryCode'][0]='AU'</code> and I have a <code>df['UTCTime'][0]=2016-08-12 08:01:00</code> I want to get <...
<p>Without having a more concrete example its difficult but try this:</p> <pre><code>pd.to_timedelta(df.CountryCode.map(dateDict), 'h') + df.UTCTime </code></pre>
python|pandas
0
3,092
40,905,389
In python, How do we find the Correlation Coefficient between two matrices?
<p>I have got two matrices say, T1 and T2 each of size mxn. I want to find the correlation coefficient between two matrices<br> So far I haven't used any built-in library function for it. I am doing the following steps for it:<br> First I calculate the mean of the two matrices as: </p> <pre><code>M1 = T1.mean() M2 = ...
<p>Well I think this function is doing what I intend for: </p> <pre><code>def correlation_coefficient(T1, T2): numerator = np.mean((T1 - T1.mean()) * (T2 - T2.mean())) denominator = T1.std() * T2.std() if denominator == 0: return 0 else: result = numerator / denominator return ...
python|numpy|matrix|correlation
0
3,093
40,956,834
Passing a pandas data frame through an R function using rpy2
<p>I am trying to reproduce R results in Python. The following R code works:</p> <pre><code>library("TTR") library("zoo") library("xts") library("quantmod") getSymbols("^GSPC",from = "2014-01-01", to = "2015-01-01") dataf = GSPC[,c("GSPC.High", "GSPC.Low", "GSPC.Close")] result = CCI(dataf, n=20, c=0.015) </code></pre...
<p>Your data.frame in the R code is actually an "xts" "zoo" object you just need to convert it to one in the python code:</p> <pre><code>rzoo = importr('zoo') datazoo = zoo.as_zoo_xts(dataf) result = TTR.CCI(datazoo, n=20, c=0.015) </code></pre>
python|r|pandas|dataframe|rpy2
0
3,094
54,141,073
How to get last n values in each row using pandas
<p>I have a df which contains quite similar to below. it has many columns and some of them contains NaN. I want to get last n elements from the each row excluding NaN. Where n represent 3 here. </p> <p>Input :</p> <pre><code> col1 col2 col3 col4 col5 col6 col7 col8 col9 col10 col11 \ 0 NaN NaN ...
<p>Solution if each row have more non missing rows like treshold:</p> <p>use numpy with <a href="https://stackoverflow.com/a/44559180"><code>justify</code></a> function:</p> <pre><code>df['res1'] = justify(df.iloc[:, :-1].values, invalid_val=np.nan, side='right')[:, -3:].tolist() print (df) col1 col2 col3 col4 ...
python|pandas
4
3,095
54,061,120
Sorting Strings with separators in pandas
<p>I have a pandas series with strings with separators in them, like say:</p> <pre><code>['160.20.2257.92', '829.328.17.39'] </code></pre> <p>I want to sort them. If I use Seres.sort_values() like in the below code:</p> <pre><code>a = pd.Series(['6.0.0.0', '10.0.4.0']) a.sort_values() </code></pre> <p>I get the out...
<p>I believe this is what you are looking for</p> <pre><code>a = ['160.20.2257.92', '829.328.17.39'] b = sorted(map(lambda x: tuple(map(int, x.split('.'))), a)) final = map(lambda x: '.'.join(map(str, x)), b) final ['160.20.2257.92', '829.328.17.39'] </code></pre> <p>I hope this covers all corner cases</p>
python-3.x|pandas|dataframe
2
3,096
66,108,629
WHY is `rename` with selection of columns not working with a lambda function?
<p>I want to rename a selected portion of columns with a lambda function using <code>rename</code></p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({'pre_col1': [1, 2], 'pre_col2': [3, 4], 'pre_col3': [ 3, 29], 'pre_col...
<ol> <li>Because of immutability of indexes. 2) Also the changes happens in a copy of the dataframe (probably because of 1)) as suggested by @SeaBean those are just in a copy.</li> </ol> <p><strong>Option 1)</strong> To change the columns names.</p> <pre><code>import pandas as pd df = pd.DataFrame({'pre_col1': [1, 2], ...
python|pandas|rename
1
3,097
66,063,032
How to efficiently vectorize (i.e. avoid explicit loops) a mapping of some colours into others in a Numpy array
<p>I have as input a Numpy matrix of rank three (i.e. an image: horizontal, vertical and 4 color channels). I want to read this matrix element-wise in their first two indices and map only certain colours into others, defined in respective arrays. The performance is very important, as this mapping will be applied many t...
<p>When I compare your solution with this one:</p> <pre><code>for i in range(palette.shape[0]): new_data[data == palette[i]] = grey_palette[i] </code></pre> <p>using <code>%%timeit</code> in a notebook gives 87ms vs 218ms for yours for a 1000x1000x3 <code>data</code>.</p> <p>EDIT: deleted comment about a 'problem' ...
python|numpy|mapping
1
3,098
66,334,784
Is it meaningless to use ReduceLROnPlateau with Adam optimizer?
<p><strong>This question is basically for the working of Keras or <code>tf.keras</code> for people who have the verty deep knowledge of the framework</strong></p> <p>According to my knowledge, <code>tf.keras.optimizers.Adam</code> is an optimizer which has already an <strong>Adaptive</strong> Learning rate scheme. So i...
<p>Conceptually, consider the gradient a fixed, mathematical value from automatic differentiation.</p> <p>What every optimizer other than pure SGD does is to take the gradient and apply some statistical analysis to create a better gradient. In the simplest case, momentum, the gradient is averaged with previous gradient...
tensorflow|machine-learning|keras|deep-learning|tf.keras
0
3,099
52,608,799
How to get the value of a single row of columns with same name?
<p>I have data frames with same column names so i have merge them</p> <h1>df1</h1> <pre><code> wave num stlines 0 4050.32 3.0 0.282690 1 4208.98 5.5 0.490580 2 4374.94 9.0 0.714830 3 4379.74 9.0 0.314040 4 4398.01 14.0 0.504150 5 4502.21 8.0 0.562780 </code></pre> <h1>d...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><code>DataFrame.loc</code></a>:</p> <pre><code>df.loc[1, 'num_x'] </code></pre> <hr> <p>In pandas same columns names are problematic, because not easy seelct first, second <code>num_x</code...
pandas|dataframe|rows
1