Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
5,300
60,563,115
Pytorch error: Could not run 'aten::slow_conv3d_forward' with arguments from the 'CUDATensorId' backend
<p>I am training a CNN on CUDA GPU which takes 3D medical images as input and outputs a classifier. I suspect there may be a bug in pytorch. I am running pytorch 1.4.0. The GPU is 'Tesla P100-PCIE-16GB'. When I run the model on CUDA I get the error </p> <pre><code>Traceback (most recent call last): File "/home/ub/m...
<p>Initially, I was thinking the error message indicates that <code>'aten::slow_conv3d_forward'</code> is not implemented with GPU (CUDA). But after looked at your network, it does not make sense to me, since Conv3D is a very basic op, and Pytorch team should implement this in CUDA.</p> <p>Then I dived a bit about the...
debugging|pytorch
18
5,301
72,792,770
How to save weights in tensorflow federated
<p>I want to save weights only when loss is getting lower and reuse them for evaluation.</p> <pre><code>lowest_loss = Inf if loss[round] &lt; lowest_loss: lowest_loss = loss[round] model_weights = transfer_learning_iterative_process.get_model_weights(state) eval_metric = federated_eval(model_we...
<p>Yes, this can be done with helpers in TFF. Generally, this kind of functionality is implemented by <a href="https://www.tensorflow.org/federated/api_docs/python/tff/program/ProgramStateManager" rel="nofollow noreferrer"><code>tff.program.ProgramStateManagers</code></a>. An implementation which saves to a filesystem ...
python|tensorflow|tensorflow-federated|federated-learning
1
5,302
72,825,479
PyTorch index in a batch
<p>Given tensor <code>IN</code> of shape <code>(A, B, C, D)</code> and index tensor <code>IDX</code> of shape <code>[A, B, C]</code> with <code>torch.long</code> values in <code>[0, C)</code>, how can I get a tensor <code>OUT</code> of shape <code>(A, B, C, D)</code> such that:</p> <pre><code>OUT[a, b, c, :] == IN[a, b...
<p>This is the perfect use case for <a href="https://pytorch.org/docs/stable/generated/torch.gather.html" rel="nofollow noreferrer"><code>torch.gather</code></a>. Given two 4d tensors, <code>input</code> the input tensor and <code>index</code> the tensor containing the indices for <code>input</code>, calling <code>torc...
python|pytorch
1
5,303
72,785,289
python script call another script with dataframes as arguments and return a new dataframe
<p>I need to make a script in python that calls a lists of scripts that I have stored in a dictionary this way:</p> <pre><code>TestsDictionary = { &quot;Test_1&quot;: 1, &quot;Test_2&quot;: 0, &quot;Test_3&quot;: 0, &quot;Test_4&quot;: 1, &quot;Test_5&quot;: 0, ...
<p>Assuming all the scripts are in same directory</p> <pre class="lang-py prettyprint-override"><code>import os TestsToRun = [] for test in TestsDictionary: if(TestsDictionary[test]): TestsToRun.append(&quot;python &quot;+test+&quot;.py&quot;) for test in TestsToRun: os.system(test) </code></pre>
python|pandas|dataframe|scripting|script
0
5,304
59,547,109
Tensorflow 2.0 save preprocessing tonkezier for nlp into tensorflow server
<p>I have trained a tensforflow 2.0 keras model to make some natural language processing. </p> <p>What I am doing basically is get the title of different news and predicting in what category they belong. In order to do that I have to tokenize the sentences and then add 0 to fill the array to have the same lenght that ...
<p>Unfortunately, you won't be able to do something as elegant as a <code>sklearn</code> Pipeline with Keras models (at least I'm not aware of) easily. Of course you'd be able to create your own Transformer which will achieve the preprocessing you need. But given my experience trying to incorporate custom objects in sk...
tensorflow|machine-learning|deep-learning|tensorflow-serving
3
5,305
59,604,783
Fast way of turning categorical Pandas series to string
<p>I have a series that is categorical.</p> <p>At the moment I am mapping to string using the following code.</p> <pre><code>import pandas as pd import numpy as np test = np.random.rand(int(5e6)) test[0] = np.nan test_cut = pd.cut(test,(-np.inf,0.2,0.4,np.inf)) test_str = test_cut.astype('str') test_str...
<p>Use, the labels parameter to generate strings instead of pd.Intevals:</p> <pre><code>breaks = [-np.inf, .2, .4, np.inf] test_cut = pd.cut(test,breaks, labels=pd.IntervalIndex.from_breaks(breaks).astype(str)) </code></pre> <p>Try timings with this code.</p>
python|pandas|optimization|categories
1
5,306
59,821,801
how to let pandas show every data row
<p>when I use pandas and I have a really big rows he makes the rows shorter by telling: <code>and 543512 more rows</code> but I want to write all the rows to a file. How is that possible?</p>
<p>There is a option called <code>display.max_rows</code>. Setting it to <code>None</code> means unlimited:</p> <pre><code>pd.set_option('display.max_rows', None) </code></pre> <p>But writing the data to a file can also be done by panda's <code>to_csv</code> function or by using <code>np.savetxt</code>. This depends ...
python|python-3.x|pandas
1
5,307
61,989,691
Python Pandas join a few files
<p>I import a few xlsx files into pandas dataframe. It works fine, but my problem that it copies all the data under each other (so I have 10 excel file with 100 lines = 1000 lines).</p> <p>I need the Dataframe with 100 lines and 10 columns, so each file will be copied next to each other and not below.</p> <p>Are ther...
<p>You can feed your spreadsheets as an array of dataframes directly to <code>pd.concat()</code>:</p> <pre><code>import os import pandas as pd os.chdir('C:/Users/folder/') path = ('C:/Users/folder/') files = os.listdir(path) allNames = pd.concat([pd.read_excel(f,'Sheet1') for f in files], axis=1) writer = pd.Excel...
python|pandas
1
5,308
58,133,430
How to substitute `keras.layers.merge._Merge` in `tensorflow.keras`
<p>I want to create a custom Merge layer using the <code>tf.keras</code> API. However, the new API hides the <code>keras.layers.merge._Merge</code> class that I want to inherit from.</p> <p>The purpose of this is to create a Layer that can perform a weighted sum/merge of the outputs of two different layers. Before, an...
<p>I have slightly modified your code to use <code>tf.random_uniform</code> instead of <code>K.random_uniform</code> and it's working fine on 1.13.1 and 1.14.0 (full snippet and resulting <code>model.summary()</code> below). </p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf print(tf.__versio...
python|tensorflow|keras|tf.keras
5
5,309
58,134,672
Converting single column to multiple columns based on unique values
<p>I have the following <code>pandas.DataFrame</code> with shape <code>(1464, 2)</code>:</p> <pre><code>df = pd.DataFrame() for name in list('ABCD'): temp_df = pd.DataFrame(np.random.randint(0,100,size=(len(date_rng), 1)), columns=['value'], index=date_rng) temp_df['name'] = name df = df.append(temp_df) </...
<p>You can use this:</p> <pre><code>df.pivot(columns='name',values='value') </code></pre>
pandas
1
5,310
55,058,546
How is get_updates() of optimizers.SGD used in Keras during training?
<p>I am not familiar with the inner workings of Keras and have difficulty understanding how Keras uses the <code>get_updates()</code> function of optimizers.SGD during training. </p> <p>I searched quite a while on the internet, but only got few details. Specifically, my understanding is that the parameters/weights u...
<p>get_updates() defines graph operations that update the gradients. When the graph is evaluated for training it will look somehow like this:</p> <ul> <li>forward passes compute a prediction value</li> <li>loss computes a cost</li> <li>backward passes compute gradients</li> <li>gradients are updated</li> </ul> <p>Upd...
tensorflow|keras
1
5,311
54,787,164
pandas.series.rolling.apply method seems to implicitly convert Series into numpy array
<p>I want to compute the rolling volatility of a net value curve. </p> <pre><code># demo import pandas as pd def get_rolling_vol(s: pd.Series) -&gt; float: return s.pct_change().iloc[1:].std() s = pd.Series([1, 1.2, 1.15, 1.19, 1.23, 1.3]) rolling = s.rolling(window=2) stds = rolling.apply(lambda s: get_rolling_...
<p>Yes, this is possible as stated in the warning message: Use <code>raw=False</code> as argument in <code>rolling.apply</code></p> <p>This works at least in pandas 0.24.1</p>
python|pandas|numpy|type-conversion|numpy-ndarray
2
5,312
55,087,855
Python | Automatic DataFrame generation
<p>I have two folders with images from city skylines two different daytimes (day and night). I want to read in all images in different color spaces in the corresponding folders and then I want to calculate statistics for all the color channels. Then I want to create a pandas data frame containing all statistics.</p> <...
<p>The easiest thing I can think of without changing the bulk of your code would be:</p> <ul> <li>create an empty df whose columns are all combinations of statistic x channel x color_space (easily done with a list comprehension);</li> <li>for each image, append all statistics to a variable (<code>row</code>):</li> <li...
python|pandas
1
5,313
49,718,162
tfjs-converter html javascript trouble importing class
<p>I'm trying to use the tensorflow.js API, and I want to import a saved python tensorflow model. I'm using <a href="https://github.com/tensorflow/tfjs-converter" rel="nofollow noreferrer">this github library</a> for the conversion. I've got these script imports in my html file:</p> <pre><code>&lt;script src="https://...
<p>By the time now, the problem is solved. here's the final one.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.11.2"&gt; &lt;/script&gt; &lt;script src="https://cdn.jsdelivr.net/npm/@tensorflow/t...
javascript|html|tensorflow
2
5,314
49,402,326
cosine similarity pandas dataframe interpretation
<pre><code>import numpy as np; import pandas as pd from sklearn.metrics.pairwise import cosine_similarity df_flask = pd.DataFrame([[100,152,70,80,2,10]],columns=['weight','height','wc','hc','sex','age']) df_flask2 = pd.DataFrame([[55.6,154,92,27,1,70]],columns=['weight','height','wc','hc','sex','age']) print (cosin...
<p>Yes, but with potential problems.</p> <p>As probably know the cosine similarity will compute the dot product between the two entries. Since the range of the values is not similar the components that reach higher values will dominate the result. In this case it will be height and weight. Compare that two sex (which ...
python|pandas
2
5,315
49,372,880
Write Pandas DataFrame to String Buffer with Chunking
<p>I have a 10k row csv that I want to write to s3 in chunks of 1k rows.</p> <pre><code>from io import StringIO import pandas as pd csv_buffer = StringIO() df.to_csv(csv_buffer, chunksize=1000) s3_resource = boto3.resource('s3') s3_resource.Object(bucket, 'df.csv').put(Body=csv_buffer.getvalue()) </code></pre> <p>T...
<p>It looks like <code>StringIO</code> isn't really heeding the chunksize. (<code>.readlines()</code> will always just return one line, never a chunk of lines.)</p> <p>I'm not too familiar with boto3, but <code>itertools.islice</code> may work for you here in terms of needing to slice an iterable without creating som...
python|pandas|amazon-s3
4
5,316
73,253,642
importing numpy from different directory
<p>I have numpy folder placed in abc and added it to path</p> <pre><code>&gt;&gt;&gt; from abc import numpy Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;C:\Users\ahsin\Desktop\naresh\abc\numpy\__init__.py&quot;, line 166, in &lt;module&gt; core.getlimit...
<p>Little wrong question I think - not &quot;importing numpy from different directory&quot; but &quot;problem with importing numpy from non-standard package&quot;.</p> <p>It not works because you use patch/tricks - that is wrong idea in programs :)</p> <p>Do this in normal way - set correct path and import:</p> <pre><c...
python|numpy
0
5,317
73,303,432
Find trigrams for all groupby clusters in a Pandas Dataframe and return in a new column
<p>I'm trying to return the highest frequency trigram in a new column in a pandas dataframe for each group of keywords. (Essentially something like a groupby with transform, returning the highest trigram in a new column).</p> <p><strong>An example dataframe with dummy data</strong></p> <pre><code> cluster_name ...
<p>You can use <code>nltk.ngrams</code> combined with <code>explode</code>/<code>groupby</code>/<code>mode</code>:</p> <pre><code>from nltk import ngrams # or use a custom function out = (df .assign(keyword=[list(ngrams(s.split(), n=3)) for s in df['keyword']]) .explode('keyword') .groupby('cluster_name')['keyword...
python|pandas|dataframe|nltk|n-gram
1
5,318
73,378,839
Loop through excel sheets and save each sheet into a csv based on a condition
<p>I have an excel file that has multiple sheets. I would like to iterate through each sheet and check against a string to either read the file after 0 rows or 4 rows. (As some of the sheets datasets start after the first 4 rows) After the sheet gets read I want to save the file as a csv.</p> <p>This is my code so far,...
<p>There are several things not working with the snippet you posted :</p> <ul> <li><code>sheets[df.items()]</code> is not valid. <code>df.items()</code> returns a dict like : <code>{&lt;sheet_name&gt;: &lt;sheet_content&gt;}</code>, so you can not use it as an index</li> <li>missing parenthesis and misplacement of squa...
python|excel|pandas
1
5,319
67,257,473
Pytorch install fails on conda with error as -CondaHTTPError: HTTP 403 FORBIDDEN for url <https..........>
<p>I have installed anaconda 2019 version from repository as the latest version was throwing error on windows 10. After installing anaconda(conda 4.10.1), i am unable to install Pytorch using command 'conda install pytorch-cpu -c pytorch' on anaconda prompt. It throws below error. I believe it is trying to look for fi...
<p>I experienced the same issue, but it turned out the error message was misleading. In my case extending the remote connection timeout parameter in the condarc file fixed the issue</p>
anaconda|pytorch
0
5,320
59,973,758
Get a error claiming my 2D array is not 2D in impyute
<p>Here is the shape of my array</p> <pre><code>b = data[0].values print(b.shape) (5126, 4229) </code></pre> <p>I get this error when I run this code:</p> <pre><code>from impyute.imputation.cs import mice # start the MICE training a=mice(b) </code></pre> <p>Error:</p> <pre><code>ValueError: Expected 2D array, go...
<p>First, you must change your input data to a 2D array, so you must specify the number of features in your data using reshape function. </p> <p>Please try to use b.reshape(5126, 4229), if not try to follow this example until you figure out the problem</p> <p><a href="https://i.stack.imgur.com/MnRxT.png" rel="nofollo...
arrays|pandas|numpy
1
5,321
59,946,211
How to convert list of tuple (tf.constant, tf.constant) as tensorflow dataset?
<p>I'm trying to create a Transformer Model, I have 2 <code>np.arrays</code>, both have strings, I used them to create a list of tuples</p> <p>The format of the tuple is : </p> <pre><code>class 'tuple' (tf.Tensor: shape=(), dtype=string, numpy=b'abc', tf.Tensor: shape=(), dtype=string, numpy=b'xyz') </code></pre> <p...
<p>You can use <code>tensor_from_slices</code>. <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_tensor_slices" rel="nofollow noreferrer">Here</a>.</p> <p><strong>EDIT</strong></p> <pre><code>Example # Two tensors can be combined into one Dataset object. values1 = tf.constant(['A', 'B', 'A'])...
python|numpy|tensorflow|dataset
2
5,322
65,484,859
Error when checking target: expected dense_192 to have 3 dimensions, but got array with shape (37118, 1)
<p>Dear all: I'm very new to deep learning. I was trying to add a for loop to test all the possible combinations to get the best result. Currently what I have is the following.</p> <pre><code>def coeff_determination(y_true, y_pred): SS_res = K.sum(K.square( y_true-y_pred )) SS_tot = K.sum(K.square( y_true - K...
<p>Use return_sequence = False for your last LSTM layer so it only returns a vector with the last hidden state.</p> <p>Sincerely,</p> <p>Alexander</p> <p>more details: <a href="https://stackoverflow.com/questions/42755820/how-to-use-return-sequences-option-and-timedistributed-layer-in-keras">How to use return_sequences...
python|tensorflow|keras|deep-learning
1
5,323
65,175,404
Pandas Pivot table get max with column name
<p>I have the following pivot table</p> <p><a href="https://i.stack.imgur.com/Z6isR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z6isR.png" alt="enter image description here" /></a></p> <p>I want to get the max value from each row, but also, I need to get the column it came from. So far I know who...
<p>You suffer a disadvantage getting help because you have supplied images and the question is not clear. Happy to help if the below answer doesn't help.</p> <pre><code>stateRace=stateRace.assign(max_value=stateRace.select_dtypes(exclude='object').max(axis=1),\ max_column=stateRace.select_dtypes(exclude='object').idxma...
pandas|database|pivot|pivot-table|data-science
0
5,324
50,076,514
Create a pandas dataframe from dictionary whilst maintaining order of columns
<p>When creating a dataframe as below (instructions from <a href="https://pythonprogramming.net/basics-data-analysis-python-pandas-tutorial/" rel="nofollow noreferrer">here</a>), the order of the columns changes from "Day, Visitors, Bounce Rate" to "Bounce Rate, Day, Visitors"</p> <pre><code>import pandas as pd web_s...
<p>One approach is to use <code>columns</code></p> <p><strong>Ex:</strong></p> <pre><code>import pandas as pd web_stats = {'Day':[1,2,3,4,5,6], 'Visitors':[43,34,65,56,29,76], 'Bounce Rate':[65,67,78,65,45,52]} df = pd.DataFrame(web_stats, columns = ['Day', 'Visitors', 'Bounce Rate']) prin...
python|pandas|dictionary|dataframe
6
5,325
63,865,856
Python set value in Dataframe to Nan Based on Value
<p>I am trying to set the values of certain columns in a dataframe to Nan based on the value of the cell. I am having problems getting it to work. Here is what I have tried. I need to set all cells where the windspeed is &lt; -200 to NaN.</p> <pre><code>filterA.loc[filterA['WindSpeedMPH'] &lt; -200, 'WindSpeedMPH'] =...
<p>You can also try to do it as simple as this:</p> <pre><code>filterA.loc[filterA['WindSpeedMPH'] &lt; -200, 'WindSpeedMPH'] = np.nan </code></pre> <p>See documentation <a href="https://datatofish.com/if-condition-in-pandas-dataframe/" rel="nofollow noreferrer">here</a> for 5 ways to apply an IF condition in pandas Da...
python-3.x|pandas|dataframe|nan
0
5,326
63,821,314
Create new column in Pandas DataFrame based on other columns
<p>I have Dataframe like:</p> <p><a href="https://i.stack.imgur.com/zrhhC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zrhhC.png" alt="enter image description here" /></a></p> <p>Now I would like to add column V based on conditions on I1, I2 and I3. Conditions are like:</p> <pre><code>v = 1 if I1&...
<p>If I understood your question correctly, suppose you have a dataframe like the below:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({ &quot;NAME&quot;: [ &quot;N1&quot;, &quot;N2&quot;, &quot;N3&quot; ], &quot;I1&quot;: [ 1, 4, 4 ], &quot;I2&quot;: [ 2, 5, 2 ], &quot;I3&quot;:...
python|pandas|dataframe
3
5,327
64,075,052
Fastest way to get count of rows of strings containing a substring in python between two data frames
<p>I have two data frames, 1 has words and the other one has the text. I want to get the count of all the rows containing the word in the first data frame.</p> <p>Word =</p> <pre><code>ID | Word ------------ 1 | Introduction 2 | database 3 | country 4 | search </code></pre> <p>Text =</p> <pre><code>ID ...
<h3>Here is simple solution</h3> <pre><code>world_count = pd.DataFrame( {'words': Word['Word'].tolist(), 'count': [Text['Text'].str.contains(w).sum() for w in words], }).rename_axis('ID') </code></pre> <p><strong>Output:</strong></p> <pre><code>world_count.head() ''' words count ID ...
python|python-3.x|pandas|nltk
2
5,328
46,991,578
IndexError: index 666 is out of bounds for axis 1 with size 501
<pre><code>import math import numpy as np def ExplicitMethod(S0, K, r, q, T, Sigma, M, N, Option): M = int(M) N = int(N) dt = T / N K = float(K) Smax = 2 * K dS = Smax / N FGrid = np.zeros(shape=(N+1, M+1)) if Option == 'Call': FGrid[-1, :] = np.maximum(np.arange(0, M+1) * dS...
<p>You have initialized <code>FGrid</code> to be (801,401). The tells us that, for some reason, <code>k=666</code></p> <pre><code>k = math.floor(S0 / dS) V = FGrid[0, k] + (FGrid[0, k] - FGrid[0, k]) / dS * [(S0 - k * dS)] </code></pre> <p>You need to refine how <code>k</code> is set. Maybe the math is wrong. At t...
python|algorithm|numpy
2
5,329
63,038,234
How do I plot steps_per_epoch against loss using fit_generator in Keras?
<p>I have the following code and I would like to plot the graph of <code>loss</code> against <code>steps_per_epoch</code></p> <pre><code>model = unet(pretrained=False) model.compile(optimizer=Adam(0.005), loss=&quot;binary_crossentropy&quot;, metrics=[&quot;accuracy&quot;]) history = model.fit_generator...
<p>you can get the values of training accuracy, training loss, validation accuracy and validation loss from the history object. See code below.</p> <pre><code>training_accuracy=history.history['accuracy'] training_loss=history.history['loss'] valid_accuracy=history.history['val_accuracy'] valid_loss=history.history['va...
python|tensorflow|matplotlib|keras|deep-learning
1
5,330
67,924,575
How to change the value of a column items using pandas?
<p>This is my fist question on stackoverflow.</p> <p>I'm implementing a Machine Learning classification algorithm and I want to generalize it for any input dataset that have their target class in the last column. For that, I want to modify all values of this column without needing to know the names of each column or ro...
<p>use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer">map</a> and map the values as per requirement:</p> <pre><code>df['col_name'] = df['col_name'].map({'dog' : 1 , 'cat': 0}) </code></pre> <p>OR -&gt; Use <a href="https://pandas.pydata.org/pand...
python|pandas|dataframe
1
5,331
67,620,499
AgGrid in Python giving blank grid
<p>AgGrid in Python giving blank grid when run with Justpy to display a Dataframe on the webpage.</p> <p>Please find below the python code I am trying to run... It is giving a blank grid can you please help me debug???</p> <pre><code>import pandas as pd import justpy as jp w1=pd.DataFrame([[1,2,3],[2,3,4],[3,4,5]]) ...
<p>I encountered the same issue. The issue for me resolved when I made certain the recordset contained no null values. My orignal recordset had some null values.</p>
python|pandas|ag-grid|justpy
1
5,332
67,927,429
Mark last date record in Pandas/Dask dataframes
<p>In the Dask dataset below I have a list of ids (for example <code>1</code> and <code>2</code>) and dates (the last column).</p> <p>What I need is to add a new column to the dataframe that will have <code>1</code> if the date is the last one for that id. For example, for id <code>2</code> the last date is <code>2021-...
<p>This is the approach I would use for pandas, not sure about Dask.</p> <pre class="lang-py prettyprint-override"><code>pdf['last_date_flag'] = pdf.groupby('id')['date'].transform(lambda x: x == x.max()).astype(int) </code></pre> <p>Gives</p> <pre><code> id balance date date2 last_date_flag 0 1 150 2021-03-...
python|pandas|dataframe|dask|dask-distributed
1
5,333
61,514,746
Multiple condition in pandas dataframe - np.where
<p>I have the following dataframe</p> <pre><code>Year M 1991-1990 10 1992-1993 9 </code></pre> <p>What I am trying to so is a if statement: <strong>=IF(M>9,LEFT(Year),RIGHT(C2,4))*1</strong></p> <p>So basically if M if 10 choose the left value of the column year else choose the second value</p> ...
<p>You can do this:</p> <pre><code>In [448]: df['val'] = np.where( df['M'].gt(9),\ ...: df.Year.str.split('-').tolist()[0],\ ...: df.Year.str.split('-').tolist()[1] ) ...
python|pandas|dataframe|if-statement
1
5,334
68,716,810
Checking for a string in two different dataframes and copy the corresponding rows to calculate statistics in Pandas
<p>I want to write a python code and have for example 2 different DataFrames (the number of dataframes can be more than 2) as follows:</p> <pre><code>df1 = Index Name Age Height 0 Tom 20 166 1 Bill 27 170 2 Jacob 39 180 3 Vivian 26 155 <...
<p>You can concatenate using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>pd.concat</code></a> both the DataFrames then GroupBy name using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="no...
python|pandas|dataframe
2
5,335
68,512,446
Numpy element-wise isin for two 2d arrays
<p>I have two arrays:</p> <pre class="lang-py prettyprint-override"><code>a = np.array([[1, 2], [3, 4], [5, 6]]) b = np.array([[1, 1, 1, 3, 3], [1, 2, 4, 5, 9], [1, 2, 3, 4, 5]]) </code></pre> <p>The expected output would match the shape of array 'a' and would be:</p> <pre class="lang-py pr...
<p>Properly reshape the arrays so they can broadcast correctly while comparing:</p> <pre><code>(a[...,None] == b[:,None]).any(2) #[[ True False] # [False True] # [ True False]] </code></pre> <ul> <li><code>a[...,None]</code> adds an extra dimension to the end, with shape <code>(3, 2, 1)</code>;</li> <li><code>b[:,Non...
python|arrays|numpy|isin
4
5,336
68,556,561
How to get the indexes of the greatest N values greater than a threshold in Numpy?
<p>For a project I need to be able to get, from a vector with shape <code>(k, m)</code>, the indexes of the N greatest values of each row greater than a fixed threshold. For example, if k=3, m=5, N=3 and the threshold is 5 and the vector is :</p> <pre class="lang-py prettyprint-override"><code>[[3 2 6 7 0], [4 1 6 4 0]...
<p>How about this method:</p> <pre><code>import numpy as np arr = np.array( [[3, 2, 6, 7, 0], [4, 1, 6, 4, 0], [7, 10, 6, 9, 8]] ) t = 5 n = 3 sorted_idxs = arr.argsort(1)[:, -n:] sorted_arr = np.sort(arr, 1)[:, -n:] item_nums = np.cumsum((sorted_arr &gt; t).sum(1)) masked_idxs = sorted_idxs[sorted_a...
python|python-3.x|numpy
1
5,337
53,017,598
best curve fitting the distribution
<p>I tried to use a polynomial (3-degrees) to fit a data series, but it seems that it's still not the best fit (some points are off in graph shown below). I also tried to add a log function to help plot. But result is not improved either.</p> <p>What would be the best curve fitting here?</p> <p>Here are the raw data ...
<p>It would be better, if your curve fitting procedure were hypothesis driven, i.e., you had already an idea, what kind of relationship to expect. The shape looked to me more like an exponential function:</p> <pre><code>from matplotlib import pyplot as plt import numpy as np from scipy.optimize import curve_fit #the f...
numpy|plot|scipy|model-fitting
0
5,338
53,200,722
Using str.contains across multiple rows
<p>I have a dataframe with five rows that looks like this:</p> <pre><code>index col1 col2 col3 col4 col5 1 word1 None word1 None None 2 None word1 word2 None None 3 None None None word2 word2 4 word1 word2 None None None </code></pre> <p>I'm trying to find all rows tha...
<p>Using <code>any</code> </p> <pre><code>s1=df.apply(lambda x : x.str.contains(r'word1')).any(1) s2=df.apply(lambda x : x.str.contains(r'word2')).any(1) df[s1&amp;s2] Out[452]: col1 col2 col3 col4 col5 index 2 None word1 word2 None None 4 word1 word2 N...
python|pandas
4
5,339
65,632,154
Group By and Count occurences of values in list of nested dicts
<p>I have a JSON file that looks structurally like this:</p> <pre><code>{ &quot;content&quot;: [ { &quot;name&quot;: &quot;New York&quot;, &quot;id&quot;: &quot;1234&quot;, &quot;Tags&quot;: { &quot;hierarchy&quot;: &quot;CITY&quot; } }, { &quot;name&quot;: &quot;Los ...
<p>Firstly construct a dictionary object by using <code>ast.literal_eval</code> function, and then split this object to get a key, value tuples in order to create a dataframe by using <code>zip</code>. Apply <code>groupby</code> to newly formed dataframe, and finally create a <code>.csv</code> file through use of <code...
python|json|python-3.x|pandas|dataframe
0
5,340
65,561,503
Re-shaping pandas dataframe to match specific output
<p>I am struggling to find some <code>elegant</code> solution to get what I need from my data. I am able to get what I want but with <code>too much</code> efforts, which I believe can be done quite better and that's what I am looking for.</p> <p>So here is sample of my DataFrame</p> <pre><code>&gt;&gt;&gt; df = pd.Data...
<p>I dont think this is an optimal solution , but it is the desired output.</p> <pre><code>df = pd.DataFrame({'device_name': ['tap_switch_1', 'tap_switch_1', 'tap_switch_1', 'tap_switch_1', 'tap_switch_1', 'tap_switch_1', 'tap_switch_1', 'tap_switch_1', 'tap_switch_1'], 'interface': ['ethernet3', 'ethernet4', 'ethernet...
python|pandas
1
5,341
63,689,848
Pandas group by find minimum of column if it doesn't exist return NaN
<p>Suppose I have the following dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame({'id': [1,1,1,2,3,2], 'year': ['2020', '2014', '2002', '2020', '2016', '2014'], 'e': [True, False, True, True, False, True]}) df.info() id year e 1 2020 True 1 2014 False 1 2002 True 2 2020 True 3...
<p>Try filter before <code>groupby</code> and <code>reindex</code> back</p> <pre><code>s = df.loc[df.e].groupby('id').year.min().reindex(df.id.unique()).reset_index() s Out[307]: id year 0 1 2002 1 2 2014 2 3 NaN </code></pre> <hr /> <p>Or convert to <code>Categorical</code></p> <pre><code>df['id'] = pd...
python|pandas|dataframe
1
5,342
53,679,716
pandas isin not filtering data on multiple columns
<p>nifty</p> <pre><code> name date time open high low close 0 NIFTY 20180903 09:16 11736.05 11736.10 11699.35 11700.15 1 NIFTY 20180903 09:17 11699.00 11707.60 11699.00 11701.85 2 NIFTY 20180903 09:18 11702.65 11702.65 11690.95 11692.40 3 NIFTY 20180903 09:19 1169...
<p>Use <code>merge</code> for this on 'date' and 'time' only, this way both your df's will return a subset for the matching values;</p> <pre><code>nifty_ = nifty.merge(option[['date','time']]) option_ = option.merge(nifty[['date', 'time']]) </code></pre>
python|pandas
1
5,343
55,166,874
Faster pytorch dataset file
<p>I have the following problem, I have many files of 3D volumes that I open to extract a bunch of numpy arrays. I want to get those arrays randomly, i.e. in the worst case I open as many 3D volumes as numpy arrays I want to get, if all those arrays are in separate files. The IO here isn't great, I open a big file only...
<p>I iterated through my dataset, created an hdf5 file and stored elements in the hdf5. Turns out, when the hdf5 is opened, it doesn't load all data in ram, it loads the header instead. The header is then used to fetch the data on request, that's how I solved my problem.</p> <p>Reference: <a href="http://www.machinele...
python|machine-learning|dataset|pytorch|lmdb
1
5,344
55,556,562
Dict[str, Any] or Dict[str, Field] in pytext
<p>I'm reading the document of pytext (NLP modeling framework built on PyTorch) and this simple method <code>from_config</code>, a factory method to create a component from a config, has lines like <code>Dict[str, Field] = {ExtraField.TOKEN_RANGE: RawField()}</code>.</p> <pre><code>@classmethod def from_config(cls, co...
<p>What you're seeing are python type annotations. You can read about the syntax, design and rationale <a href="https://www.python.org/dev/peps/pep-0484/" rel="nofollow noreferrer">here</a> and about the actual implementation (possible types, how to construct custom ones, etc) <a href="https://docs.python.org/3/library...
python|pytorch|pytext
2
5,345
56,563,041
CalledProcessError while installing Tensorflow using Bazel
<p>I am trying to install Tensorflow from source using Bazel on Raspberry pi. I am following the official documentation as given <a href="https://www.tensorflow.org/install/source" rel="nofollow noreferrer">here</a>. When I run the <code>./configure</code> in Tensorflow directory after completing all the steps written ...
<p>Probably the problem is that the non appropriate version of bazel is installed. Run <code>bazel version</code> in the tensorflow directory, and see if there is an error. If there is a problem with bazel version, then check out the .baselversion file, and if it contains a version that isn't installable with apt, then...
tensorflow|raspberry-pi|bazel
4
5,346
66,816,984
Colors assosiated with dataframe column in folium
<p>I have a dataframe looking like this:</p> <pre><code>Lat | Long | Label x1 | y1 | id1 x2 | y2 | id2 x3 | y3 | id3 </code></pre> <p>and I want to plot <code>Lat</code> and <code>Long</code> in a folium map, where the markers are colored based on the value of <code>Label</code>. The problem...
<p>For anyone with the same problem, I used the following to create random color hexes,</p> <pre><code>color = &quot;%06x&quot; % random.randint(0, 0xFFFFFF) </code></pre> <p>as proposed <a href="https://stackoverflow.com/questions/13998901/generating-a-random-hex-color-in-python/18035471">here</a> and then create a di...
pandas|folium
0
5,347
47,199,871
What is b flops in tfprof (tensorflow profiler) model analysis report?
<p>Eg: </p> <pre><code>_TFProfRoot (--/3163.86b flops) InceptionResnetV2/InceptionResnetV2/Mixed_6a/Branch_1/Conv2d_0b_3x3/convolution (173.41b/173.41b flops) </code></pre> <p>What does <code>b flops</code> mean? I guess <code>m flops</code> means <code>mega flops</code>. But, what does <code>'b' flops</code> mean? A...
<p>It means billions :)</p> <p>quoted from source: "return strings::Printf("%.2fb", n / 1000000000.0);"</p>
tensorflow|profiling|flops
1
5,348
47,515,996
Apply function to every column value of each row using pandas
<p>For this dataframe : </p> <pre><code>columns = ['A','B', 'C'] data = np.array([[1,2,2] , [4,5,4], [7,8,18]]) df2 = pd.DataFrame(data,columns=columns) df2['C'] </code></pre> <p>If the difference between consecutive rows for column C is &lt;= 2 then the previous and current row should be returned. So I'm attempting ...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html" rel="nofollow noreferrer"><code>diff</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html" rel="nofollow noreferrer"><code>shift</code></a> and last <code>NaN<...
python|pandas
1
5,349
47,410,517
Concat pandas dataframes without following a certain sequence
<p>I have data files which are converted to pandas dataframes which sometimes share column names while others sharing time series index, which all I wish to combine as one dataframe based on both column and index whenever matching. Since there is no sequence in naming they appear randomly for concatenation. If two data...
<p>If you go through the loop step by step, you can find that in the first iteration it goes into the <code>if</code>, so <code>data1</code> is equal to <code>df1</code>. In the second iteration it goes to the <code>else</code>, since <code>data1</code> is not empty and <code>''Temperature product barrel ValueY''</code...
python|python-3.x|pandas|dataframe
1
5,350
68,030,403
Create multiple columns from one column (with the same data)
<p>I have this column (similar but with a lot of more entries)</p> <pre><code>import pandas as pd numbers = range(1,16) sequence = [] for number in numbers: sequence.append(number) df = pd.DataFrame(sequence).rename(columns={0: 'sequence'}) </code></pre> <p><a href="https://i.stack.imgur.com/yv3WB.png" rel="nofollo...
<p>Use <code>reshape</code> with <code>5</code> for number of new rows, <code>-1</code> is for count automatically number of columns:</p> <pre><code>numbers = range(1,16) df = pd.DataFrame(np.array(numbers).reshape(-1, 5).T) print (df) 0 1 2 0 1 6 11 1 2 7 12 2 3 8 13 3 4 9 14 4 5 10 15 ...
python|pandas|dataframe
3
5,351
68,355,371
Match the first 3 characters of a string to specific column
<p>I have a dataframe,df, where I would like to take the first 3 characters of a string from a specific column and place these characters under another column</p> <p><strong>Data</strong></p> <pre><code>id value stat aaa 10 aaa123 aaa 20 aaa 500 aaa123 bbb 20 bbb 10 bbb123 aaa 5 aaa123 ...
<p>One option would be <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>Series.fillna</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.html" rel="nofollow noreferrer"><code>Series.str</code></a> to slice th...
python|pandas|numpy
5
5,352
59,395,609
Remove row when within group we reach a treshold in pandas
<p>Hel lo I need help with pandas. </p> <p>Here is the table :</p> <pre><code>Col1 Col2 Grp1 80.3 Grp1 129.2 Grp1 356.0 Grp1 435.3 Grp2 20.2 Grp2 34.0 Grp2 67.0 Grp3 130.3 Grp3 167.9 </code></pre> <p>And the idea is to remove row when within each Grp, the number in col2 is already > 100. Here I should get : </p> <...
<p>You could do with <code>groupby</code>:</p> <pre><code>s = df['Col2'].gt(100).groupby(df['Col1']).transform('idxmax') df[df.index &lt;= s] </code></pre> <p>Output:</p> <pre><code> Col1 Col2 0 Grp1 80.3 1 Grp1 129.2 4 Grp2 20.2 7 Grp3 130.3 </code></pre>
pandas
3
5,353
57,112,346
Sort a Dataframe with a coumn from another Dataframe
<p>I have got two dataframes which looks like these. </p> <pre><code>df1 = Name Order John 2 Alice 3 Alisha 1 Mike 5 Katie 6 Steve 4 df2 = Name Condition Action Mike Stable Out Mike Unstable In Steve Stable Out Steve Unstable In Katie Stable Out Katie Uns...
<p>First add the <code>Order</code> column to df2:</p> <pre><code>df2['Order'] = df2.Name.map(df1.set_index('Name').Order) </code></pre> <p>Then do the sort and remove the Order column:</p> <pre><code>df2.sort_values('Order').drop('Order', 1) </code></pre>
python-3.x|pandas|dataframe
1
5,354
57,035,248
How to optimize searching and comparing rows in pandas?
<p>I have a two dfs. Base is 100k rows, Snps is 54k rows.</p> <p>This is structure of dfs:</p> <p>base:</p> <pre><code>SampleNum SampleIdInt SecondName 1 ASA2123313 A2123313 2 ARR4112234 R4112234 3 AFG4234122 G4234122 4 GGF412233 F412233 5 GTF423512 F423512 ...
<p>What you are trying to do is commonly called <a href="https://en.wikipedia.org/wiki/Join_(SQL)" rel="nofollow noreferrer">join</a>, which annoyingly enough is called <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer">merge</a> in pandas. There's...
python|pandas|dataframe
1
5,355
57,139,676
SavedModel - TFLite - SignatureDef - TensorInfo - Get intermediate Layer outputs
<p>I would like to get intermediate layers output of a TFLite graph. Something in the lines of below.</p> <p><a href="https://stackoverflow.com/questions/56885007/visualize-tflite-graph-and-get-intermediate-values-of-a-particular-node">Visualize TFLite graph and get intermediate values of a particular node?</a></p> <...
<p><code>tf.lite.Interpreter</code> has a new parameter as of tf 2.5: <code>experimental_preserve_all_tensors</code>, when set to <code>True</code> it allows you to query the output from any node. Here is how I used it:</p> <pre><code>import numpy as np import tensorflow as tf import cv2 import argparse parser = argp...
tensorflow2.0
0
5,356
56,976,671
Time series plot of categorical or binary variables in pandas or matplotlib
<p>I have data that represent a time series of categorical variables. I want to display the transitions in categories below a traditional line plot of related continuous time series to show off context as time evolves. I'd like to know the best way to do this. My attempt was in terms of Rectangles. The appearance is a ...
<p>This is a way to display dates on x-axis:</p> <p>In your code substitute the line that fails with this one:</p> <pre><code>ax.xaxis.set_major_formatter((mdates.DateFormatter('%Y-%m-%d'))) </code></pre> <p>But I don't remember how it should look like, can you show us the end-result again?</p>
pandas|matplotlib|plot|time-series|categorical-data
1
5,357
56,895,221
Following a TensorFlow tutorial and hitting issues with model.predict
<p><a href="https://towardsdatascience.com/all-the-steps-to-build-your-first-image-classifier-with-code-cf244b015799" rel="nofollow noreferrer">I am following a tutorial for TensorFlow</a> and I am having problems during the model prediction phase.</p> <p>The final bit of code is :</p> <pre><code>import cv2 import te...
<p>Your <code>image</code> should be <code>prepare_file(img_path)</code> instead of just a string.</p>
python|tensorflow|keras|artificial-intelligence
1
5,358
57,172,340
Change column value based on conditions in other columns in Pandas
<p>I want to change the value in 1 column in the data frame based on the conditions and comparison of values in other columns.</p> <p>This is the original data frame:</p> <pre><code> start end diff 0 2016-05-08 unknown 3 1 2016-05-08 2017-09-08 5 2 2018-09-01 2017-09-01 5 </code></pre> <p>...
<p>Here is one way using <code>np.where</code> , after convert the datatime by using <code>to_datetime</code>. Also , please do not name a columns with build-in function name like : diff, sum , min, max and cumsum. </p> <pre><code>df.start=pd.to_datetime(df.start) df.end=pd.to_datetime(df.end,errors = 'coerce') df['di...
python|pandas
1
5,359
45,853,387
When I restore the saved graph and variables. how can I get the placehold in TF
<p>I have used </p> <pre><code> tf.add_to_collection('Input', X) tf.add_to_collection('TrueLabel', Y) tf.add_to_collection('loss', loss) tf.add_to_collection('accuracy', accuracy) saver0 = tf.train.Saver() saver0.save(sess, './save/model') saver0.export_meta_graph('./save/model.meta') </code></pre> <p>to save ...
<p>This concern has been solved by myself. Once we load the graph and the variables. Just to obtain the placeholder like graph.get_tensor_by_name('Input:0'). Use the same way to obtain the loss and accuracy and so on what you want to collect.</p> <p>A full example could be found from <a href="https://github.com/sunkev...
tensorflow
0
5,360
51,100,406
Creating python function to create categorical bins in pandas
<p>I'm trying to create a reusable function in python 2.7(pandas) to form categorical bins, i.e. group less-value categories as 'other'. Can someone help me to create a function for the below: col1, col2, etc. are different categorical variable columns.</p> <pre><code>##Reducing categories by binning categorical varia...
<p>You can use:</p> <pre><code>df = pd.DataFrame({'A':list('abcdefabcdefabffeg'), 'D':[1,3,5,7,1,0,1,3,5,7,1,0,1,3,5,7,1,0]}) print (df) A D 0 a 1 1 b 3 2 c 5 3 d 7 4 e 1 5 f 0 6 a 1 7 b 3 8 c 5 9 d 7 10 e 1 11 f 0 12 a 1 13 b 3 14 f 5 15 f 7 16 e 1 ...
python|python-2.7|pandas|dataframe
3
5,361
66,702,577
Compare a column in 2 different dataframes in pandas (only 1 column is same in both dataframes)
<p>I have 2 dataframes <code>df1</code> and <code>df2</code> and I want to compare <code>'col1'</code> of both dataframes and get the rows from <code>df1</code> where <code>'col1'</code> values don't match. Only <code>'col1'</code> is common in both dataframes.</p> <p>Suppose I have:</p> <pre><code>df1 = pd.DataFrame({...
<h3>Quick and Dirty</h3> <pre><code>df1.append(df1.merge(df2.col1)).drop_duplicates(keep=False) col1 col2 col3 3 4 40 d 4 5 50 e </code></pre>
python|pandas|dataframe
1
5,362
57,707,999
python pandas: convert/transform between iat/iloc and at/loc indexing
<p>I have the iloc index in a Dataframe and want the get the corresponding loc index. In other words: I would like to have a function <code>ilocIndex_to_locIndex</code> converting the <code>ilocIndex</code> to <code>locIndex</code></p> <pre><code>df = pd.DataFrame({1 : [1,2,3,4], 2 : [5,6,7,8]}) df = df.drop([1]) iatI...
<p>You can subscript the <code>.index</code>:</p> <pre><code>&gt;&gt;&gt; df<b>.index[2]</b> 3</code></pre>
python|pandas
3
5,363
57,587,738
Search for a Pattern in a Pandas Column, abstract the value on the left of the pattern
<p>I have a column in a Pandas Dataframe like this (dtype = "O"): </p> <pre><code>Column_string ! 111 PATTERN1 .......,,,,,,.... !444PATTERN2 ! 222 PATTERN3 .......,,,,,,.... !555 PATTERN3 ! 333 PATTERN4 .......,,,,,,.... !666 PATTERN5 </code></pre> <p>I want to <strong>abstract a value on the left side of ...
<p>use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.findall.html" rel="nofollow noreferrer">str.findall</a></p> <pre><code>##sample df Column_string 0 ! 111 PATTERN1 .......,,,,,,.... !444PATTERN2 1 ! 222 PATTERN3 .......,,,,,,......
python|string|pandas
1
5,364
73,172,757
Local variable referenced before assignment in If statement when calculating mean absolute error
<p>I'm trying to add a weight to not penalize as much if prediction is greater than the actual in a forecast. Here's my code, however, I keep getting:</p> <blockquote> <p>UnboundLocalError: local variable 'under' referenced before assignment</p> </blockquote> <pre><code>import numpy as np def mae(y, y_hat): if np....
<p>So because of the <code>if</code> and <code>elif</code> statement, when you return <code>np.mean(over,under)</code>, either <code>under</code> or <code>over</code> isn't going to be defined. Therefore, you either need to initialize <code>under</code> and <code>over</code> with initial values or rework it because wit...
python|numpy|if-statement|mse
1
5,365
51,812,972
Extracting quantitative Information out of Strings
<p>I am analyzing the Open Food Facts dataset. The dataset is very messy and has a column called 'quantity' with entries like the following: </p> <p>'100 g ',<br> '5 oz (142 g)',<br> '12 oz',<br> '200 g ',<br> '12 oz (340 g)',<br> '10 f oz (296ml) ',<br> '750 ml',<br> '1 l',<br> '250 ml', '8 OZ',<br> '10.5 oz (750 g)...
<pre><code>raw_data_lst = ['100 g ','5 oz (142 g)','12 oz','200 g ','12 oz (340 g)','10 f oz (296ml)','750 ml','1 l','250 ml', '8 OZ',] # 10 f oz (296ml) don't know what f is # if more there is more data like this then gram_conv_dict.keys() loop over this instead of directly ... doing what i have done below in_grams...
python|regex|pandas|feature-extraction|text-extraction
0
5,366
36,195,485
Setting column types while reading csv with pandas
<p>Trying to read <strong>csv</strong> file into <strong><em>pandas</em></strong> dataframe with the following formatting</p> <pre><code>dp = pd.read_csv('products.csv', header = 0, dtype = {'name': str,'review': str, 'rating': int,'word_count': dict}, engine = 'c...
<p>In your loop you are doing:</p> <pre><code>for col in dp.columns: print 'column', col,':', type(col[0]) </code></pre> <p>and you are correctly seeing <code>str</code> as the output everywhere because <code>col[0]</code> is the first letter of the name of the column, which is a string.</p> <p>For example, if you ...
python|csv|dictionary|pandas|types
6
5,367
36,104,016
Pandas: pivot with rows and columns in a given order
<p>I have a dataframe with hierarchical rows, which is the result of a transposed pivot. The second row index is a number and gets sorted in ascending order (which is what I want), but the first row index is a string and gets sorted alphabetically (which I don't want). Similarly, the column names are strings, and are s...
<p>The function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> is for that, just adapt to manage columns :</p> <pre><code>In [1]: mypiv Out[1]: mylocation North South scenario this ...
pandas|dataframe|pivot
3
5,368
7,716,092
Creating greyscale video using Python, OpenCV, and numpy arrays
<p>I am using 32-bit python with OpenCV 2.3.1. I am trying to write 2-dimensional numpy arrays to a opencv video writer. My code is similar to :</p> <pre><code>import cv2 as cv import numpy as np fourcc = cv.cv.CV_FOURCC('D', 'I', 'V', 'X') writer = cv.cv.CreateVideoWriter("test.mpg", courcc, 10, (256,256)) if not ...
<p>I've never used OpenCV, but FWIW I write numpy arrays to video files by piping them to mencoder (based on VokkiCoder's <code>VideoSink</code> class <a href="http://vokicodder.blogspot.co.uk/2011/02/numpy-arrays-to-video.html" rel="nofollow">here</a>). It's very fast and seems to work pretty reliably, and it will als...
python|opencv|numpy
1
5,369
37,933,925
Pandas: Can pandas groupby filter work on original object?
<p>Starting with this question as base.</p> <p><a href="https://stackoverflow.com/questions/13446480/python-pandas-remove-entries-based-on-the-number-of-occurrences">Python Pandas: remove entries based on the number of occurrences</a></p> <pre><code>data = pandas.DataFrame( {'pid' : [1,1,1,2,2,3,3,3], 'tag' ...
<p>A couple of options (yours is at the bottom):</p> <p>This first one is <code>inplace</code> and as quick as I could make it. Its a bit quicker than your solution but not by virtue of dropping rows in place. I can get even better performance with the second option and this does not change in place.</p> <pre><code...
python|pandas|filter|group-by
1
5,370
37,820,107
Efficiently reshape numpy array
<p>I am working with NumPy arrays.</p> <p>I have a <code>2N</code> length vector <code>D</code> and want to reshape part of it into an <code>N x N</code> array <code>C</code>.</p> <p>Right now this code does what I want, but is a bottleneck for larger <code>N</code>:</p> <p>```</p> <pre><code>import numpy as np M =...
<p>You can use <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="noreferrer"><code>NumPy broadcasting</code></a> to remove those nested loops -</p> <pre><code>C = D[N + np.arange(N)[:,None] - np.arange(N)] </code></pre> <p>One can also use <a href="http://docs.scipy.org/doc/numpy-1.10.0/ref...
python|arrays|performance|numpy|vectorization
9
5,371
37,724,208
assign values to dataframe defined by multiindex
<p>I have a 5-dimensional df created by</p> <pre><code>factor_list = ['factor1', 'factor2', 'factor3'] method_list = ['method1', 'method2', 'method3'] grouping_list = ['group1', 'group2', 'group3'] parameter_list = [1, 5, 10, 20, 40] iterables = [factor_list, method_list, parameter_list, grouping_list] axis_names...
<p>For me works <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#using-slicers" rel="nofollow">using slicers</a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a>:</p> <pre><code>import pandas as pd, numpy as np factor_...
python|pandas|dataframe|multi-index
2
5,372
37,766,012
Adding multiple ndarry using numpy
<p>I am quite new to python numpy.</p> <p>If i do have a list of numpy vectors. What is the best way to ensure computation is fast. </p> <p>I am currently doing this which i find it to be too slow.</p> <pre><code>vec = sum(list of numpy vectors) # 4 vectors of 500 dimensions each </code></pre> <p>It does take up qu...
<p>Is this what you are trying to do (but with much larger arrays)?</p> <pre><code>In [193]: sum([np.ones((2,3)),np.arange(6).reshape(2,3)]) Out[193]: array([[ 1., 2., 3.], [ 4., 5., 6.]]) </code></pre> <p><code>500 dimensions each</code> is an unclear description. Do you mean an array with shape <code>(...
python|numpy|vector
2
5,373
38,008,512
How can I get the value of the error during training in Tensorflow?
<p>In the TensorFlow MNIST beginners tutorial, code excerpts here: </p> <pre><code>cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) sess = tf.Session() sess.run(init) #-----training loop starts here----- f...
<p>As some person say, TensorBoard is the one for that purpose.</p> <p>Here I can give you how to.</p> <p>First, let's define a function for logging min, max, mean and std-dev for the tensor.</p> <pre><code>def variable_summaries(var, name): with tf.name_scope("summaries"): mean = tf.reduce_mean(var) tf.s...
machine-learning|tensorflow
4
5,374
37,949,588
Is there an no-op (pass-through) operation in tensorflow?
<p>As per title. I'd like to make use of such operation to rename the nodes and better organize a graph. Or is there other recommended practice for renaming an existing node in the graph? Thanks!</p>
<p>There is <a href="https://www.tensorflow.org/api_docs/python/tf/no_op" rel="noreferrer"><code>tf.no_op</code></a> which allows you to add an operation which does nothing.</p>
tensorflow
18
5,375
64,345,639
I dont understand what is wrong with this line
<pre><code>stockxx[&quot;Date&quot;]=pd.to_datetime(stockxx.Date, format = '%m/%d/%Y %H:%M:%S.%f' stockxx.index=stockxx['Date'] plt.figure(figsize=(16,8)) plt.plot(stockxx[&quot;Close/Last&quot;], label= 'Close Price History') </code></pre> <p>I get this</p> <pre><code>File &quot;&lt;ipython-input-13-e522099fd646&gt;&...
<p>In the first line, you are missing a <code>)</code></p> <p>This</p> <pre><code>stockxx[&quot;Date&quot;]=pd.to_datetime(stockxx.Date, format = '%m/%d/%Y %H:%M:%S.%f' </code></pre> <p>should be</p> <pre><code>stockxx[&quot;Date&quot;]=pd.to_datetime(stockxx.Date, format = '%m/%d/%Y %H:%M:%S.%f') </code></pre> <p>with...
pandas|jupyter-notebook
1
5,376
64,556,993
Sum a colum per x and per y in a Datafame
<p>I have:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({ &quot;ID&quot;: [55218,55218,55218,55218,55222], &quot;Product&quot;: [10,10,22,22,21], &quot;Cluster&quot;: [0,0,1,2,1] &quot;Rating&quot;:[-1,2,0,1,2]}) </code></pre> <p>I want to sum every 0, 1 or 2 in &quot;Cluster&quot; f...
<p>This will gives you desired output</p> <pre><code>import pandas as pd # Query DF df = pd.DataFrame({ &quot;ID&quot;: [[55218],[55218],[55218],[55218],[55222]], &quot;Product&quot;: [[10],[10],[22],[22],[21]], &quot;Cluster&quot;: [[0],[0],[1],[2],[1]], &quot;Rating&quot;:[[-1],[2],[0],[1],[2]]}) print(df)...
python|pandas|dataframe|sum
1
5,377
64,494,042
What does the shape of a multi-dimensional array signify?
<p>What does the shape in an n-dimensional array mean? Ex:</p> <pre><code>import numpy as np arr = np.array([[1]]) print(arr) # output: [[1]] print(arr.ndim) # output: 2 print(arr.shape) # output: (1, 1) </code></pre>
<p>You yourself said that it's a 2D array that means it has 2 dimensions.<br /> <code>[[1]]</code> is a 1 x 1 matrix that's why you get <code>(1, 1)</code> as output.</p> <p><strong>Edit:</strong><br /> <em>Question:</em> &quot;For [[1]], there's no element along the 2nd dimension, shouldn't the size be zero along seco...
python|numpy|multidimensional-array
3
5,378
47,551,449
How does tensorflow scale RNNCell weight tensors when changing their dimensions?
<p>I'm trying to understand how the weights are scaled in a RNNCell when going from training to inference in tensorflow.</p> <p>Consider the following placeholders defined as:</p> <p><code>data = tf.placeholder(tf.int32,[None,max_seq_len]) targets = tf.placholder(tf.int32,[None,max_seq_len])</code></p> <p>During tra...
<ul> <li>you have defined your <code>data</code> tensor as <code>data = tf.placeholder(tf.int32,[None,max_seq_len])</code> which means that the first dimension will change according to the input but the second dimension will always remain <code>max_seq_len</code></li> <li>So if <code>max_seq_len = 5</code> than you fee...
python|tensorflow
0
5,379
47,770,723
Find two dimensional complement in pandas
<p>I have two pandas dataframes, a, and b. a and b share two common colums, say x and y, containing english language strings. Each combination of x and y is uniq within a and b. There is a common subset of x and y, which I can compute like</p> <pre><code>c = pandas.merge(a, b, on=['x', 'y']) </code></pre> <p>What I a...
<p>Pandas <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer">merge</a> has an option to add an indicator column which tells you where the data comes from. Combining this with an outer merge should give you what you are looking for.</p> <pre><code>a_b...
python|pandas|dataframe
2
5,380
49,079,464
Handling mixed string with double quotations and numbers to save in csv
<p>I have three lines that I need to save as header of my csv files. They should look like this:</p> <pre><code>title = "dataset test" variables = "X", "Y", "Z", "V" zone t = "Data Field", i = 134, j = 293, k = 5, f=point </code></pre> <p>I am using the following code to create the pandas dataframe:</p> <pre><code>i...
<p>Have you tried using the <code>\</code> escape character on this line</p> <pre><code>'variables = "X", "Y", "Z", "V"' </code></pre> <p>Like this</p> <pre><code>'variables = \"X\", \"Y\", \"Z\", \"V\"' </code></pre>
python|pandas|csv|dataframe
1
5,381
58,859,385
Getting listed column names of all not nan rows
<p>I've pandas dataframe based on pivot table with index and columns. Index are presented with values that are not nan at least in one column, while others are nans.</p> <pre><code> col_1 col_2 col_3 col_4 ... col_100 index_1 1 2 nan nan ... 5 index_2 nan nan 1 1 ......
<p>You can use <code>stack</code> to remove <code>nan</code> and <code>groupby</code> to gather all column names:</p> <pre><code>(df.stack() .reset_index(level=1) .groupby(level=0, sort=False) ['level_1'].apply(list) ) </code></pre> <p>Output:</p> <pre><code>index_1 [col_1, col_2, col_100] index_2 ...
python|pandas
3
5,382
70,187,074
divide by zero encountered in true_divide error without having zeros in my data
<p>this is my code and this is my data, and this is the output of the code. I've tried adding one the values on the x axes, thinking maybe values so little can be interpreted as zeros. I've no idea what true_divide could be, and I cannot explain this divide by zero error since there is not a single zero in my data, che...
<p>Here is a working <code>Minuit</code> vs <code>curve_fit</code> example. I scaled the function such that the decay in the exponential is in the order of 1 (generally a good idea for non linear fits ). Eventually, both methods give very similar results.</p> <p>Note:I leave it open whether the error makes sense like t...
pandas|numpy|data-analysis|curve-fitting|iminuit
0
5,383
56,132,629
Assign arr with numpy fancy indexing
<p>I really hope this is not a duplicate and this is probably a very stupid question. Sorry ;) </p> <p>Problem: I have a greyscale image with values/classes 1 and 2 and I want to convert/map this to a color image where 1 equals yellow and 2 equals blue. </p> <pre><code>import numpy as np import cv2 result=cv2.imrea...
<p><code>result</code> is a Numpy array and is <em>typed</em>, its type being an integer and you try to assign to an integer slot a triple of integers… no good. </p> <p>What you want to do is creating an empty color image, with the same dimensions of <code>result</code>, and assigning to the last axis the requested tr...
python|numpy|opencv|cv2
1
5,384
55,784,018
How to convert list of lists to bytes?
<p>I have list of list float and I want to convert it into bytes. Can please some help me to do this. for example</p> <pre><code>l = [[0.1, 1.0, 2.0], [2.0, 3.1, 4.1]] </code></pre> <p>and I want something like</p> <pre><code>bytes(l) -&gt; b'\x01\x02\x03.......' </code></pre>
<p>Since you've tagged this <code>numpy</code>, this is simply <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tobytes.html" rel="noreferrer"><code>tobytes</code></a></p> <pre><code>a = np.array(l) a.tobytes() </code></pre> <p></p> <pre><code>b'\x9a\x99\x99\x99\x99\x99\xb9?\x00\x00\x00\x0...
python|python-3.x|numpy
7
5,385
55,990,574
Pandas rolling apply function to entire window dataframe
<p>I want to apply a function to a rolling window. All the answers I saw here are focused on applying to a single row / column, but I would like to apply my function to the entire window. Here is a simplified example:</p> <pre><code>import pandas as pd data = [ [1,2], [3,4], [3,4], [6,6], [9,1], [11,2] ] df = pd.DataF...
<p>Not with <code>pd.DataFrame.rolling</code> .... that function is applied iteratively to the columns, taking in a series of floats/NaN, and returning a series of floats/NaN, one-by-one. I think you'll have better luck with your intuition....</p> <pre><code>def rolling_pipe(dataframe, window, fctn): return pd.Se...
python|pandas|apply|rolling-computation
11
5,386
55,810,419
How to remove 'b' character from ndarray that is added by np.genfromtxt
<p>I have a text file which contains rows of information in the form of both strings, integers and floats, separated by white space, e.g.</p> <p>HIP893 &nbsp;&nbsp; 23_10&nbsp; &nbsp; 7 &nbsp; &nbsp; 0.028 &nbsp;&nbsp; &nbsp; 4<br> HIP1074&nbsp; 43_20&nbsp; &nbsp; 20 &nbsp; 0.0141&nbsp; &nbsp; 1<br> HIP1325...
<p>You can pass <code>converters=</code> with a function that decodes your bytes strings, eg:</p> <pre><code>convs = dict.fromkeys([0, 1], bytes.decode) data = np.genfromtxt('98_info.txt', dtype=(object, object, int, float, float), converters=convs) </code></pre> <p>Which gives you <code>data</code> of:</p> <pre><co...
python|python-3.x|numpy
3
5,387
55,785,696
Split dataset by every other day
<p>I have a dataset that I collected over many days and is indexed by calendar day. Each day has a different number of entries in it. I want to see if the odd days (e.g. day 1, day 3, day 5, etc...) are correlated with the even days (e.g. day 2, day 4, day 6 etc...) and to do this, I have to split my dataset into two.<...
<p>Use <code>pd.Categorical</code> with <code>.codes</code></p> <pre><code>num = pd.Categorical(df.Date).codes + 1 df_odd = df[num%2 == 0] df_even = df[num%2 == 1] df_odd Date var 0 2018-12-10 1 1 2018-12-10 0 2 2018-12-10 1 3 2018-12-10 0 6 2018-12-12 0 7 2018-12-12 1 8 20...
pandas
1
5,388
64,900,758
Create df column concatenated value over each row
<p>How can I create a new column in my DataFrame which is a json string equivalent to concatenated column values over each row in the below format?</p> <p>Code so far:</p> <pre><code>import pandas as pd data = {'Name':['Tom', 'Nat', 'Harry', 'Jack'],'Age':[20, 21, 22, 23]} df = pd.DataFrame(data) </code></pre> <p>Input...
<p>Here is one way</p> <pre><code>import pandas as pd data = {'Name':['Tom', 'Nat', 'Harry', 'Jack'],'Age':[20, 21, 22, 23]} df = pd.DataFrame(data) df['Combined'] = '[{&quot;'+str(df.columns[0])+'&quot;: &quot;'+df['Name']+'&quot;, &quot;'+str(df.columns[1])+'&quot;: '+df['Age'].apply(str)+'}]' </code></pre> <p>it wo...
python|pandas|dataframe
1
5,389
64,732,291
Sum rows in 2d numpy
<p>Assume the following 2d numpy is given:</p> <pre><code>myNP = np.array([[5., 2., 1.], [3., 3., 3.], [3., 3., 3.]]) </code></pre> <p>One has to find the weight of each point in each row in relation to the sum of the row.</p> <p>in reference to the example above the expected result need...
<p>the sum function does exactly what you need. You just need to specify the axis. In your case <code>myNP.sum(axis=1)</code> should do the trick</p>
python|numpy
1
5,390
64,841,964
Python: Passing in a tuple as an argument in a function
<p>I am creating new columns for a <code>Pandas DataFrame</code> using <code>np.select(condition, choices)</code>. I would like to modularize my code into a function to do so, and my cumbersome way is as follows:</p> <pre><code>def selection( df: pd.DataFrame, conditions: Optional[List] = None, choices: Opt...
<pre><code>In [53]: def foo(df, conditions=None, choices=None): ...: print(df, conditions, choices) ...: In [54]: foo('df') df None None </code></pre> <p>With keywords, you can supply arguments with a dict:</p> <pre><code>In [55]: adict={'conditions':[1,2,3], 'choices':['yes','no']} In [56]: foo('df', **ad...
python|pandas|numpy
1
5,391
64,747,351
Parent and child with Panda in python
<p>I have a csv file with more than 10000 rows, now I want to create a new column which shows the dependency between parent and child. based on the mentioned rules and policies which exists as below:</p> <ol> <li>The unique code which determine and show that the data relates to which family is <em><strong>Team</stron...
<p>If I understood it correctly, this should be the correct approach:</p> <pre><code>import pandas as pd import numpy as np data = {&quot;team&quot;:[&quot;ah&quot;,&quot;ah&quot;,&quot;ah&quot;,&quot;ah&quot;,&quot;ah&quot;],&quot;position&quot;:[&quot;C&quot;,&quot;PF&quot;,&quot;PG&quot;,&quot;SF&quot;,&quot;SG&quo...
python|python-3.x|pandas|dataframe|pandas-groupby
0
5,392
64,731,501
how can I resample pandas dataframe by day on period time?
<p>i have a dataframe like this:<br></p> <pre><code>df.head() Out[2]: price sale_date 0 477,000,000 1396/10/30 1 608,700,000 1396/10/30 2 580,000,000 1396/10/03 3 350,000,000 1396/10/03 4 328,000,000 1396/03/18 </code></pre> <p>that it has out of bounds datetime<br> so then i follow below to ...
<p>It seems here not working <code>resample</code> and <code>Grouper</code> with <code>Periods</code> for me in pandas 1.1.3 (I guess bug):</p> <pre><code>df['sale_date']=df['sale_date'].str.replace('/','').astype(int) df['price'] = df['price'].str.replace(',','').astype(int) def conv(x): return pd.Period(year=x /...
python|pandas|python-datetime
1
5,393
40,313,369
How do I use the avx flag when compiling Fortran code using f2py?
<p>In doing some performance testing in Python, I compared the timing for different methods to calculate the Euclidean distance between an array of coordinates. I found my Fortran code compiled with <a href="https://docs.scipy.org/doc/numpy-dev/f2py/" rel="nofollow">F2PY</a> to be roughly 4x slower than the C implemen...
<p>To answer how to add the <code>avx</code> flag into compiler options.<br> In your case the f77 complier is being picked <code>gfortran:f77: ./distance.f</code> &lt; That is the key line.<br> You could try specifying <code>--f77flags=-mavx</code></p>
python|numpy|scipy|fortran|f2py
1
5,394
40,233,697
Speed up double for loop in numpy
<p>I currently have the following double loop in my Python code:</p> <pre><code>for i in range(a): for j in range(b): A[:,i]*=B[j][:,C[i,j]] </code></pre> <p>(A is a float matrix. B is a list of float matrices. C is a matrix of integers. By matrices I mean m x n np.arrays.</p> <p>To be precise, the si...
<p>Here's a vectorized approach assuming <code>B</code> as a list of arrays that are of the same shape -</p> <pre><code># Convert B to a 3D array B_arr = np.asarray(B) # Use advanced indexing to index into the last axis of B array with C # and then do product-reduction along the second axis. # Finally, we perform el...
python|performance|numpy|parallel-processing|vectorization
1
5,395
44,185,104
zip rows of pandas DataFrame with list/array of values
<p>My current code is</p> <pre><code>from numpy import * def buildRealDataObject(x): loc = array(x[0]) trueClass = x[1] evid = ones(len(loc)) evid[isnan(loc)] = 0 loc[isnan(loc)] = 0 return DataObject(location=loc, trueClass=trueClass, evidence=evid) if trueClasses is None: trueClasses = ...
<p>Currently the zip works on columns instead of rows. Use one of the method from <a href="https://stackoverflow.com/questions/9758450/pandas-convert-dataframe-to-array-of-tuples">Pandas convert dataframe to array of tuples</a> to make the zip work on rows instead of columns. For example substitute</p> <pre><code>zip(d...
python|pandas
4
5,396
44,187,426
Unable to install Scipy in windows?
<p><a href="https://i.stack.imgur.com/1xpL6.jpg" rel="nofollow noreferrer">1</a>When I am installing Scipy using <code>pip install scipy</code> I am getting this error as shown in Image. I've tried this many time and also I've tried <code>scikit-learn</code> but it also requires this Scipy. Please help me, I've to sub...
<p>Try installing scipy from here:</p> <p><a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy" rel="nofollow noreferrer">http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy</a></p> <p>You'll need to know your version of python to choose correctly (I see you have 3.6). Also you'll need to know if it is 32 or 64 bit...
python|windows|numpy|scipy
1
5,397
69,321,285
Cannot load lvis via tfds
<p>I am trying to load built-in dataset <a href="https://www.tensorflow.org/datasets/catalog/lvis" rel="nofollow noreferrer">lvis</a>. It turns out that the <code>tfds</code> and <code>lvis</code> should be imported and installed respectively, however, I did possible all, it still does not work.</p> <pre class="lang-py...
<p>This is what I did to get it to work on Colab Notebook:</p> <pre><code>!pip install -q tfds-nightly tensorflow tensorflow-datasets matplotlib lvis pycocotools apache_beam import matplotlib.pyplot as plt import numpy as np import tensorflow as tf import tensorflow_datasets as tfds </code></pre> <p>Since the tfds obje...
tensorflow|keras|tensorflow2.0|tensorflow-datasets
2
5,398
69,420,951
Creating custom column for week number of a column value
<p>If I have a df such as</p> <pre><code> Date | User 2019-08-05 Bob 2019-07-01 Chris 2019-08-13 Bob 2019-08-20 Chris 2019-09-24 Bob </code></pre> <p>Expected output</p> <pre><code> Date | User | Week_number 2019-08-05 Bob 1 2019-07-01 Chris 1 2019-08-13 Bob 2 2019-08-2...
<p>If you mean how many weeks have passed since the first date of the user:</p> <pre><code>df.Date = pd.to_datetime(df.Date) df['WeekNumber'] = df.Date.groupby(df.User).diff().dt.days.fillna(0).astype(int) // 7 + 1 df Date User WeekNumber 0 2019-08-05 Bob 1 1 2019-07-01 Chris 1 2 20...
python|python-3.x|pandas
1
5,399
69,420,061
How to use lambda function just in null rows of a column in pandas
<p>I am trying to put 0 or 1 in place of the null rows of a column using lambda function, but my code doesn't make any changes in the data.</p> <pre><code>df[df['a'].isnull()]['a']=df[df['a'].isnull()].apply(lambda x:1 if (x.b==0 and x.c==0) else 0,axis=1) </code>...
<p>You can use <code>loc</code> to specifically fill the null value rows in your DataFrame. When you're using the <code>apply</code> method you can use it on the entire DataFrame, you do not need to filter for NULL values there. The <code>loc</code> will take care of only filling the rows which meet the NULL condition...
python|pandas|dataframe|lambda
1