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
12,900
64,484,854
pandas - join words after specific word
<p>I have a pandas dataframe with a column of comments in the form</p> <pre><code>import pandas as pd df = pd.DataFrame({'comment':['aaa bbb ccc not verb ddd']}) df.loc[0,'comment'] 'aaa bbb ccc not verb ddd' </code></pre> <p>I want to join together the <code>not</code> with the word after it, in the example <code>ve...
<p>Use <code>str.replace</code>:</p> <pre><code>df.comment.str.replace(r'\b(not\s)', 'not_') </code></pre> <p>Output:</p> <pre><code>0 aaa bbb ccc not_verb ddd Name: comment, dtype: object </code></pre>
python|pandas|text-mining
2
12,901
64,257,456
Based on multiple conditions how to get a sub-group of DataFrame in Python?
<p>Below I have a DataFrame and I want to get simply a sub-category of dataframe , which consist of only those records for which column(&quot;day&quot;) will be ' friday ' and for non-smokers only . BAsically I want to calculate a boxplot for non-smoker's total_bill at friday . But I need to get a sample from whole df ...
<p>You can use <code>.loc</code> to access the dataframe with your two conditions, and add additional conditions as needed.</p> <pre><code>df[(df.day ==&quot;Fri&quot;) &amp; (df.smoker == &quot;No&quot;)] </code></pre>
python|pandas|data-science
2
12,902
64,302,395
plotting a simple circle from a mesh
<p>I have a mesh grid and a function on the coordinates using <code>numpy.mgrid</code>.</p> <pre><code>xx, yy = np.mgrid[:100, :100] circle = (xx-50)**2 + (yy-50)**2 </code></pre> <p>How can I plot the circle coordinates in a simple 2d circle?</p>
<p>You can just create a mask from <code>circle</code> and then easy ploting, for example:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt xx, yy = np.mgrid[:100, :100] circle = (xx-50)**2 + (yy-50)**2 donut = (circle &lt; (2500 + 50)) &amp; (circle &gt; (2500 - 50)) plt.imshow(donut) plt.show() </...
python|python-3.x|numpy|numpy-ndarray
3
12,903
64,568,715
How to expand the dimension of each batch in a tensorflow dataset
<p>I created a tf.data dataset, however, I keep on running into this error when trying to fit my Sequential CNN model with it.</p> <pre><code> ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: [32, 28, 28] </code></pre> <p>At the moment, my...
<p>You can try to use this</p> <pre><code>arr=np.reshape(x_test[i],(1, 28,28)) </code></pre> <p>instead of this</p> <pre><code>arr=np.reshape(x_test[i],(28,28)) </code></pre> <p>If you are using channel last you can put 1 as the 3rd dim.</p>
python|tensorflow|keras|tensorflow-datasets|conv-neural-network
1
12,904
47,727,053
Can't append series to dataframe in some case
<p>I'm a newbie pandas user and upsetting for some trouble.</p> <p>Here's the case. This is the initial dataframe.</p> <pre><code>In [9]: df Out[9]: importance interval last_read last_update name trigger 0 2 NaN NaN 2017-12-09 00:00:00+09:00 foobar NaN </code></pre> <p>...
<p>This is a bug. See the link below.</p> <p><a href="https://github.com/pandas-dev/pandas/issues/16044" rel="nofollow noreferrer">Github Issues #16044</a></p>
python|pandas
0
12,905
48,930,871
Creating a function to count the number of pos in a pandas instance
<p>I've used NLTK to pos_tag sentences in a pandas dataframe from an old Yelp competition. This returns a list of tuples (word, POS). I'd like to count the number of parts of speech for each instance. How would I, say, create a function to count the number of being verbs in each review? I know how to apply functions to...
<p>Thank you @zhangyulin for your help. After two days, I learned some incredibly important things (as a novice programmer!). Here's the solution!</p> <pre><code>def NounCounter(x): nouns = [] for (word, pos) in x: if pos.startswith("NN"): nouns.append(word) return nouns df["nouns"] = df...
pandas|nltk
1
12,906
49,307,001
Select Data Frame result based on row occurrences
<p>Given the following DataFrame how can I retrieve only the values where IS_TESTED has both True and False values.</p> <pre><code>d = pd.DataFrame({"ID":[700,700,701,702,702,703],"IS_TESTED":[True,False,True,False,True,True],"TEST_NAME":["A","B","A","A","B","A"]}) </code></pre> <p><a href="https://i.stack.imgur.com/...
<p>Use groupby and nunique</p> <pre><code>d[d.groupby('ID').IS_TESTED.transform('nunique') &gt; 1] ID. IS_TESTED TEST_NAME 0 700 True A 1 700 False B 3 702 False A 4 702 True B </code></pre>
python|pandas|dataframe
4
12,907
58,720,163
Pandas Dataframe save to CSV alters list of times
<p>PLease refer to the picture and help out, I cant seem to solve the issue through casting, is it an encoding issue? <a href="https://i.stack.imgur.com/poGO4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/poGO4.png" alt="enter code here"></a></p>
<p>To get similar format as in jupyter use format the dates before exporting</p> <pre><code>df['Times'] = df['Times'].apply(lambda x: [d.strftime('%Y-%m-%d %H:%M:%S') for d in x]) </code></pre>
python|pandas|export-to-csv
0
12,908
59,014,093
How to elegantly drop unnecessary elements in numpy?
<p>I have an ndarray of shape <code>[batch_size, seq_len, num_features]</code>. However, some of elements in the end of the sequential dimension is not necessary, and therefore I want to drop them and merge the sequential dimension into the batch dimension. For example, the ndarray <code>a</code> I want to manipulate i...
<p>Not sure if this is what your asking but the results look fine</p> <p><code>res = a[mask]</code></p>
python|numpy
2
12,909
58,931,343
Set the correct datetime format with pandas
<p>I have trouble setting the correct datime format with Pandas, I do not understand why my command does not work. Any solution?</p> <pre><code> date = ['01/10/2014 00:03:20'] value = [33.24] df = pd.DataFrame({'value':value,'index':date}) df.index = pd.to_datetime(df.index,format='%d/%m/%y %H:%M:%S') </code></pre...
<p>Solution for <code>DatetimeIndex</code>:</p> <pre><code>date = ['01/10/2014 00:03:20'] value = [33.24] #create index by date list df = pd.DataFrame({'value':value},index=date) #use Y for match YYYY, y is for match YY years format df.index = pd.to_datetime(df.index,format='%d/%m/%Y %H:%M:%S') print (df) ...
python|pandas|datetime|format
2
12,910
58,868,272
What may be the problem with this cudaGetDevice() failed. Status: cudaGetErrorString symbol not found
<p>I've been having this issue for quite some time now and I can't find a solution, I've tried so many things that I've lost track, but after some research it seems that it might have something to do with my processor (too old perhaps?), I started with machine learning for a proyect just this year so i'm not experience...
<p>It seems that your GPU is not supported by CUDA, and therefore is having issues with TensorFlow (hence why TensorFlow isn't recognizing your GPU).</p> <p>According to <a href="https://developer.nvidia.com/cuda-gpus" rel="nofollow noreferrer">NVIDIA's GPU documentation</a> site, your GPU's compute compatibility is 3...
python|python-3.x|tensorflow|keras
0
12,911
70,243,856
Forward Fill NA values with discount rate conditional on sign of previous value
<p>I try to forward fill <code>NaN</code> values in a <code>DataFrame</code> with a discount rate conditional on the sign of the previous value. So far, I was able to include a discount rate in the forward fill of the <code>NaN</code> values. Here would be a simple example dataset <code>df1</code>:</p> <pre><code>df1 =...
<p>You could use a mask on the negative and positive values, something like this should work:</p> <pre><code>groups = df1.notna().cumsum() exp = df1.apply(lambda col: col.isna().groupby(groups[col.name]).cumsum()) df2 = df1.ffill() rate_p = 0.9 rate_n = 0.7 mask_p = df2 &gt; 0 mask_n = df2 &lt; 0 df2 *= (rate_p ** exp)...
python|pandas|dataframe
1
12,912
70,230,687
How keras.utils.Sequence works?
<p>I am trying to create a data pipeline for U-net for Image Segmentation. I came across <code>Keras.utils.Sequence</code> class through which, I can create a data pipeline, But I am unable to understand how this is working.</p> <p>link for the code <a href="https://www.tensorflow.org/api_docs/python/tf/keras/utils/Seq...
<p>You don't need a generator. The sequence class is there to manage that. You need to define a class inherited from <code>tensorflow.keras.utils.Sequence</code> and define the methods: <code>__init__</code>, <code>__getitem__</code>, <code>__len__</code>. In addition, you can define the method <code>on_epoch_end</code...
python-3.x|tensorflow|oop|keras
4
12,913
56,178,459
Are the gradients obtained by tf.gradients() or optimizer.compute_gradients() negated already?
<p>Are the gradients obtained by tf.gradients() or optimizer.compute_gradients() negated already?</p> <p>For example, for gradient descent, we know that the direction should be set to negetive gradient, -E'(W), where E'(W) is the gradient, E(W) is the loss.</p> <p>And, in Tensorflow, through tf.gradients() or tf.trai...
<p>No, the gradients are not negated, they follow the proper gradient definition. Here's a TF 2.0 example (using gradient tape):</p> <pre><code>x = tf.constant(2.) with tf.GradientTape() as tape: tape.watch(x) y = x**2 print(tape.gradient(y, x)) </code></pre> <p>This will print <code>tf.Tensor(4.0, shape=(), ...
tensorflow|machine-learning|optimization
0
12,914
55,748,842
Numpy power ufunc operating on specific axis
<p>I find it weird that numpy.power has no axis argument... is it because there is a better/safer way to achieve the same goal (elevating each 2D array in a 3D array to the power of a 1D array).</p> <p>Suppose you have a (3,10,10) array (A) and you want to elevate each (10,10) array to the power of elements in array B...
<p><code>power</code> is not a <em>reduction</em> operation: it does not reduce a collection of numbers to a single number, so an <code>axis</code> argument doesn't make sense. Operations such as <code>sum</code> or <code>max</code> are reductions, so it is meaningful to specify an axis along which to apply the reduct...
python|numpy|numpy-ufunc
4
12,915
64,847,610
Calculating the variance of a regressor
<p>I am trying to calculate the variance of the predictors in a model with 540 observations. From the predictor matrix (X_blocked), I want to take the second column (the first column is for the intercept, the second column for the first predictor), calculate it's variance, and store the value in a variable:</p> <pre><c...
<p>Parentheses are wrongly positioned. Currently, you are squaring the mean and subtracting it from your predicted values. You need to subtract the mean from predicted values and then square it.</p> <pre><code>blocked_pred1_var = np.sum((X_blocked[:, 1] - np.mean(X_blocked[:, 1])) ** 2) / 539 </code></pre>
python|arrays|numpy|variance
0
12,916
64,961,303
Suppress Tensorflow "Executing op" messages when using TPU
<p>I understand that for Tensorflow 2 onwards, the output that is printed by Tensorflow can be suppressed fairly easily according to the level:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf tf.get_logger().setLevel('ERROR') </code></pre> <p>However, when I use TPU on Google Colab, messages...
<p>I ended up having to use a custom filter from <code>logging</code> which parses <code>sys.stdout</code> and <code>sys.stderr</code>:</p> <pre class="lang-py prettyprint-override"><code># Suppress TPU messages which start with &quot;Executing op&quot; import sys, re, logging class Filter(object): def __init__(s...
python|tensorflow
0
12,917
64,773,001
Split two columns in a pandas dataframe into two and name them
<p>I have this pandas dataframe</p> <pre><code> x y Values 0 A B C D 4.7 1 A B C D 10.9 2 A B C D 1.8 3 A B C D 6.5 4 A B C D 3.4 </code></pre> <p>I would like to split the x and y columns and get...
<pre><code>df[['x', 'f']] = df.x.str.split(&quot; &quot;, expand=True) df[['y', 'g']] = df.y.str.split(&quot; &quot;, expand=True) df[['x','f','y','g', 'Values']] </code></pre> <p>You can make it scalable as well, defining a dict in which the keys are the columns, and the values a list with the desired new column names...
python|pandas|dataframe
4
12,918
64,621,754
How to check for missing values as a condition for a function
<p>can anyone help me fix this condition<br> I have a column in my dataframe that I want to recode into different values. I just started with Pandas and i'm a bit more confident with functions so I want to use a function that I can map/apply on that column. Most of the script is working as intended. but I can't seem to...
<p>You most likely want these lines to be:</p> <pre><code>elif pands.isna(column): return &quot;Word is missing&quot; </code></pre>
python|pandas
0
12,919
64,781,266
Optuna Pytorch: returned value from the objective function cannot be cast to float
<pre><code>def autotune(trial): cfg= { 'device' : &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;, # 'train_batch_size' : 64, # 'test_batch_size' : 1000, # 'n_epochs' : 1, # 'seed' : 0, # 'log_interval' : 100, # 'save_model' : F...
<p>This exception is raised because the objetive function from your study must return a float.</p> <p>In your case, the problem is in this line:</p> <pre><code>study.optimize(autotune, n_trials=1) </code></pre> <p>The autotune function you defined before does not return a value and cannot be used for optimization.</p> ...
pytorch|conv-neural-network|optuna|pytorch-ignite
3
12,920
39,945,122
How to create hierarchical columns in pandas?
<p>I have a pandas dataframe that looks like this:</p> <pre><code> rank_2015 num_2015 rank_2014 num_2014 .... num_2008 France 8 1200 9 1216 .... 1171 Italy 11 789 6 788 .... 654 </code></pre> <p>Now I want to draw a bar chart ...
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#extracting-substrings" rel="noreferrer"><code>str.extract</code></a> with the regex pattern <code>(.+)_(\d+)</code> to convert the columns to a DataFrame:</p> <pre><code>cols = df.columns.str.extract(r'(.+)_(\d+)', expand=True) # 0 ...
python|pandas
7
12,921
41,149,212
How can I efficiently "stretch" present values in an array over absent ones
<p>Where 'absent' can mean either <code>nan</code> or <code>np.masked</code>, whichever is easiest to implement this with.</p> <p>For instance:</p> <pre><code>&gt;&gt;&gt; from numpy import nan &gt;&gt;&gt; do_it([1, nan, nan, 2, nan, 3, nan, nan, 4, 3, nan, 2, nan]) array([1, 1, 1, 2, 2, 3, 3, 3, 4, 3, 3, 2, 2]) # e...
<p><code>cumsum</code>ming over an array of flags provides a good way to determine which numbers to write over the NaNs:</p> <pre><code>def do_it(x): x = np.asarray(x) is_valid = ~np.isnan(x) is_valid[0] = True valid_elems = x[is_valid] replacement_indices = is_valid.cumsum() - 1 return valid...
numpy|missing-data|masked-array
1
12,922
40,908,827
Converting rows of dictionaries into separate pandas columns
<p>I have a dataframe of two columns. One of the two has a value of a dictionary consisting of several keys and values. I'd like to expand these dictionary keys to separate columns. Is this possible within pandas?</p> <pre><code>In [1]:print df Out[2]: ID column_2 0 1 {u'color':'blue',u'counts':10} 1 3 {u...
<p>Notice that you can do the following:</p> <pre><code>In [3]: pd.DataFrame(df.col2.values.tolist()) Out[3]: color counts 0 blue 10 1 red 30 2 purple 12 </code></pre> <p>So just hack it together using <code>concat</code> from there:</p> <pre><code>In [4]: pd.concat((df.ID, pd.DataFrame(...
python|pandas|dictionary
4
12,923
40,817,208
Getting extremely low loss in a bidirectional RNN?
<p>I have implemented a bi-directional RNN in TensorFlow using a <code>BasicLSTMCell</code> and <code>rnn.bidirectional_rnn</code>. I am calculating the loss using <code>seq2seq.sequence_loss_by_example</code> after concatenating the outputs I receive. My application is a next character predictor.</p> <p>I getting an ...
<p>I think there is no any mistake in your code.</p> <p>The problem is the objective function with the Bi-RNN model in your application (next character predictor). </p> <p>The unidirectional RNN (such as <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/rnn/ptb/ptb_word_lm.py" rel="nofol...
python|tensorflow|recurrent-neural-network|bidirectional
1
12,924
53,996,015
Extract left and right limit from a Series of pandas Intervals
<p>I want to get interval margins of a column with pandas intervals and write them in columns 'left', 'right'. Iterrows does not work (documentation says it would not be use for writing data) and, anyway it would not be the better solution.</p> <pre><code>import pandas as pd i1 = pd.Interval(left=85, right=94) i2 = p...
<p>Create an <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.IntervalIndex.html" rel="noreferrer"><code>pandas.IntervalIndex</code></a> from your intervals. You can then access the <code>.left</code> and <code>.right</code> attributes.</p> <pre><code>import pandas as pd idx = pd.IntervalInde...
python|pandas|intervals
25
12,925
54,209,888
Naturally sort pandas DataFrame by index
<p>My dataframe is this form </p> <pre><code> material 15N 649.7 16S 703.2 16N 711.7 1S 716.2 1N 724.5 2S 723.5 2N 721.5 </code></pre> <p>I want to sorted the ...
<p>IIUC <code>natsorted</code> with <code>reindex</code> </p> <pre><code>from natsort import natsorted df.reindex(natsorted(df.index)) material 1N 724.5 1S 716.2 2N 721.5 2S 723.5 15N 649.7 16N 711.7 16S 703.2 </code></pre> <p>Update </p> <pre><code>l=sorted(df.index.str.split('(...
python-3.x|pandas|sorting|dataframe
3
12,926
65,912,292
Formatting by deleting arrays by indexes Numpy Python
<p>I want to delete all the other arrays within <code>list_</code> that are not listed in the <code>keep</code> array. So the new <code>list_</code> function would consist of <code>[402.152008,435.790985,423.204987]</code></p> <pre><code>keep = np.arange(5, 8, 1) list_= np.array([457.334015,424.440002,394.795990,408.90...
<p>It works simply by indexing <code>list_</code> with the elements in <code>keep</code>:</p> <pre><code>In [20]: list_[keep] Out[20]: array([402.152008, 435.790985, 423.204987]) </code></pre>
python|arrays|numpy|vector|slice
0
12,927
66,205,849
pandas groupby.apply to pyspark
<p>I have the following custom function to make aggregation in my pandas dataframe, and I want to do the same things in pyspark:</p> <pre class="lang-py prettyprint-override"><code>def custom_aggregation_pyspark(x,queries): names={} for k, v in regles_calcul.items(): plus = x.query(v[&quot;plus_credit&q...
<p>You can use <code>epxr</code> to evaluate the conditions passed in the <code>queries</code> dict and use a conditional aggregation to calculate the sum. Here's an example that is equivalent to the one you gave in pandas :</p> <pre><code>from pyspark.sql import functions as F def custom_aggregation_pyspark(df, regl...
python|pandas|apache-spark|pyspark|apache-spark-sql
1
12,928
52,716,922
How to write in a csv through tkinter's entry?
<p>So I have this program I want to write from two <code>tkinter</code> <code>Entries</code> to the newly created <code>csv</code> file from <code>pandas</code>. So far I failed to write a single line except for the two columns I set in the <code>Dataframe</code>.Is there any way for every line that is created by <code...
<p>Well,what you are asking is quite unclear at the moment but if you need your result to look like this</p> <pre><code>First,Second Value1,Value2 Value3,Value4 </code></pre> <p>Then in you <code>save_data</code> function you could:</p> <pre><code>with open(file name,'w') as f:#or better still open the file in 'a' m...
python|python-3.x|pandas|tkinter|python-3.6
0
12,929
46,407,593
Using tf.cond() to feed my graph for training and validation
<p>In my TensorFlow code I want my network to take inputs from one of the two <code>StagingArea</code> objects depending upon whether I want to do training or testing. A part of the graph construction code I wrote is as follows :</p> <pre><code>with tf.device("/gpu:0"): for i in range(numgpus): with t...
<h1>Your problem</h1> <h3>What you think <code>tf.cond</code> does</h3> <p>Based on the flag, execute what is required to put either traingetop[i] or valgetop[i] into your <code>elem</code> tensor.</p> <h3>What <code>tf.cond</code> actually does</h3> <p>Executes what is required to get <strong>both</strong> trainge...
tensorflow
3
12,930
46,591,824
combine two pandas dataframe into one dataframe "dict type cell" (pd.Panel deprecated)
<p>I'm trying to concat multiples pandas.DataFrame to be saved in a mongodb in just one collection, all the dataframes have the same index/columns and I wanted to save it, in just one document, using to_json() method. Having all the cells of the dataframe as dicts, its probably a good approach. To accomplish that I wan...
<p>This is a completely different concept that I am having fun with. </p> <hr> <p>You can create a subclass of <code>dict</code> where we define addition to be a dictionary merge. </p> <pre><code>from cytoolz.dicttoolz import merge class mdict(dict): def __init__(self, *args, **kwargs): super().__init...
json|mongodb|pandas|dataframe|panel
2
12,931
58,203,796
What is my output and input tensor names?
<p>I've tried a lot of things to find the input and output tensor names. I first tried the following block of code:</p> <pre><code>import tensorflow as tf frozen='C:/tensorflow1/models/research/object_detection/faster_rcnn_inception_v2_coco_2018_01_28/frozen_inference_graph.pb' gf = tf.compat.v1.GraphDef() gf.ParseFro...
<p>Can you try the function below in order to get the names.</p> <p><strong>tf.Graph.get_tensor_by_name()</strong></p>
python|tensorflow|input|model|tensorboard
0
12,932
58,285,393
How to find similar GPS coordinates in rows of same column?
<p>Is there a way to identify which GPS coordinates represent same location. e.g. given the following Data Frame. How to tell that Id 1 and 2 are from same source location.</p> <pre><code>+-----+--------------+-------------+ | Id | VehLat | VehLong | +-----+--------------+-------------+ | 66 | 63.3917005...
<p>IIUC, you need this.</p> <pre><code>df[['VehLat','VehLong']].round(3).duplicated(keep=False) </code></pre> <p>You can change the number within <code>round</code> to adjust what you consider as "same"</p> <p><strong>Output</strong></p> <pre><code>0 False 1 False 2 False 3 False 4 True 5 False 6...
python|pandas|dataframe|gps|geopandas
3
12,933
58,555,879
Interface Error when importing Pandas data frame into SQL Server
<p>I have a pandas data frame called : data I am trying to read this pandas dataframe into a table in sql server. I am able to read data into python from sql but I am expiering problems loading the dataframe into a table.</p> <p>I have tried a few examples but keep on getting the same error: <strong>DatabaseError: Exe...
<p>As noted in the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html" rel="nofollow noreferrer">to_sql documentation</a>:</p> <blockquote> <p>con : sqlalchemy.engine.Engine or sqlite3.Connection</p> </blockquote> <p>You have supplied <code>to_sql</code> with a (pyodbc)...
python|mysql|pyodbc|pandas-to-sql
0
12,934
69,181,623
How can I concatenate an additional input data in Alexnet with the output of the last dropout layer using Pytorch implementation?
<p>Here is the implementation architecture</p> <pre><code>class AlexNet(nn.Module): def __init__(self, num_classes=10): super(AlexNet, self).__init__() #1 self.features= nn.Sequential( nn.Conv2d(3, 96, kernel_size=11, stride=4, padding=0), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, strid...
<p>You can do so in the <code>forward</code> definition by simply calling <code>torch.cat((x, y), 1)</code> to concatenate the two feature vectors together.</p> <pre><code>class AlexNet(nn.Module): def __init__(self, num_classes=10): super().__init__() #1 self.features= nn.Sequential( nn.C...
deep-learning|pytorch|concatenation|conv-neural-network|dropout
1
12,935
68,937,480
How do I use booleans to create dataframe and plot the filtered data on pie chart?
<pre><code>import pandas as pd import numpy as np data = {'City': ['KUMASI', 'ACCRA', 'ACCRA', 'ACCRA', 'KUMASI', 'ACCRA', 'ACCRA', 'ACCRA', 'ACCRA'], 'Building': ['Commercial', 'Commercial', 'Industrial', 'Commercial', 'Industrial', 'Commercial', 'Commercial', 'Commercial', 'Commercial'], 'LPL': ['NC', 'C', 'C', 'C'...
<p>The simplest way I know is to compute the length of the full dataframe and the filtered one:</p> <pre><code>LPL_and_hazard_equal_C = len(filtered) total_records = len(df) LPL_and_harard_different_from_C = total_records - LPL_and_hazard_equal_C fig, ax = plt.subplots() ax.pie([LPL_and_hazard_equal_C, LPL_and_harar...
python|pandas|dataframe|matplotlib
2
12,936
68,899,322
Remove rows in Dataframe based on Hamming Distance within array
<p>I've tried to apply following code on my datasample which I found in an older thread (<a href="https://stackoverflow.com/questions/66160583/removing-nearly-duplicate-observations-python">Removing *NEARLY* Duplicate Observations - Python</a>):</p> <pre><code>from sklearn.preprocessing import OrdinalEncoder import pan...
<p>The problem is here:</p> <pre class="lang-py prettyprint-override"><code>for j in range(len(X) - 1): </code></pre> <p>You are iterating over the size of X, but X is not getting updated after dropping the near-duplicates that was found in the first iteration.</p> <p>As a result, in the second iteration, <code>df</cod...
python|pandas|numpy|hamming-distance
1
12,937
69,077,453
AttributeError: 'Tensor' object has no attribute 'numpy' when using a Keras-based custom loss function
<p>I read the publication entitled &quot;IMPROVED TRAINABLE CALIBRATION METHOD FOR NEURAL NETWORKS ON MEDICAL IMAGING CLASSIFICATION&quot; available at <a href="https://arxiv.org/pdf/2009.04057.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/2009.04057.pdf</a>. In this study, they have proposed a custom loss funct...
<p>You have two choices:</p> <p>a) Use Tensorflow ufuncs for your loss function, for instance not using <code>.numpy()</code> and replacing <code>np.sum()</code> by <code>tf.reduce_sum()</code></p> <p>b) Use NumPy ufuncs, but train eagerly, by passing <code>run_eagerly=True</code> in <code>model.compile()</code></p>
python|numpy|tensorflow|keras|loss-function
3
12,938
69,248,882
Finding mean between two inputs from users
<p>I'm trying to write a Python program using numpy, which prints the average/mean of all the even numbers bigger than 10 which are also between a specific lower and upper bound input by the user. So, if the user inputs 8 as the lower number and 16 as the upper number, then the output would be 14, but I can't seem to g...
<p>Your function is just adding all of the even numbers between the lower and upper bound (excluding the upper bound because of how the range function works).</p> <p>So when you input 8 and 16, you're computing 8+10+12+14=44.</p> <p>You need to keep track of how many evens there are in the function and then divide the ...
python|numpy
0
12,939
69,152,192
How to merge with datetime.datetime(Object) from CSV file with timestamp(datetime64[ns]) from t.series?
<p>I am relatively new to python and am getting below error when I try to merge datetime.datetime(Object) from CSV file with timestamp(datetime64[ns]) from t.series. How can I change timestamp(datetime64[ns]) to datetime.datetime?(I have other datetime.datetime(object) to add later so I prefer to change timestamp(datet...
<p>In order to merge on field/fields, the dtypes of merge fields should be same. Try converting the dtype first and then use merge. Converting both to str in the below example.</p> <pre><code>BaseDate['Date'] = pd.to_datetime(BaseDate['Date']).dt.strftime('%Y-%m-%d') is_EOM_QOM['Date'] = pd.to_datetime(is_EOM_QOM['Date...
python|pandas|datetime|merge
0
12,940
44,484,520
merge two dataframes without repeats pandas
<p>I am trying to merge two dataframes, one with columns: customerId, full name, and emails and the other dataframe with columns: customerId, amount, and date. I want to have the first dataframe be the main dataframe and the other dataframe information be included but only if the customerIds match up; I tried doing:</p...
<p>There is problem you have duplicates in <code>customerId</code> column.</p> <p>So solution is remove them, e.g. by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow noreferrer"><code>drop_duplicates</code></a>:</p> <pre><code>df2 = df2.drop_duplicat...
python|pandas|merge|ipython|ipython-notebook
4
12,941
60,989,775
How can I use tensorflow lite to detect specific object without retraining
<p>I'm trying to use tensorflow lite in raspberry pi to detect specific category (motorcycle only) using the pre-trained model. Since the motorcycle category is already existing in the pre-trained model, I assume that I don't need any to retrain it. Is there anyway to remove other objects in the model? I am using the c...
<p>I've solved my own problem by adding these lines of code inside the for loop.</p> <blockquote> <p>for i in range(len(scores)):</p> </blockquote> <pre><code> if classes[i] != 3: scores[i]=0 if ((scores[i] &gt; min_conf_threshold) and (scores[i] &lt;= 1.0)): </code></pre> <p>NOTE: number 3 represen...
python|tensorflow|object-detection|tensorflow-lite
1
12,942
60,772,771
Pandas dataframe randomly shuffle some column values in groups
<p>I would like to shuffle some column values but only within a certain group and only a certain percentage of rows within the group. For example, per group, I want to shuffle n% of values in column b with each other.</p> <pre><code>df = pd.DataFrame({'grouper_col':[1,1,2,3,3,3,3,4,4], 'b':[12, 13, 16, 21, 14, 11, 12,...
<p>You can use <code>numpy</code> to create a function like this (it takes a numpy array for input)</p> <pre><code>import numpy as np def shuffle_portion(arr, percentage): shuf = np.random.choice(np.arange(arr.shape[0]), round(arr.shape[0]*percentage/100), ...
python|pandas|pandas-groupby|permutation|shuffle
1
12,943
60,951,999
How to combine plots generated within a loop as subplots in one larger figure
<p>I have code that builds graphs in a loop one after the other. But they are inconvenient to analyze. I would like to build graphs of two in a row. How do I change the code?</p> <pre><code>for cat in test.category_doubled.unique(): plt.figure(figsize=(8,5)) y = test.best_channels[test.category_doubled == cat]...
<p><strong>Edit:</strong> Updated code according to OP's comment below.</p> <p>You can set up subplots in one figure of <code>n</code> rows with two subplots per row with <code>plt.subplot(n, 2, i)</code>, where <code>i</code> is the subplot counter. So for one figure with 6 x 2 subplots, we can do this:</p> <pre cla...
python|pandas|matplotlib
1
12,944
60,972,117
python sqlite - where condition is empty
<p>I have a table in an sqlite database called 'General'. It has four columns 'One', 'Two' and three</p> <p>One has a list of names:</p> <pre><code>One = ['James', 'Ben', 'John', 'Peter'] </code></pre> <p>Two, a list of country's:</p> <pre><code>Two = ['Uk', 'USA', 'Germany', 'UK'] </code></pre> <p>three, a score:...
<p>You could explicitly handle the empty string in the comparisons, like so:</p> <pre><code>df = pd.read_sql_query(''' SELECT * FROM General WHERE ('{}' = '' OR name='{}') AND ('{}' = '' OR country='{}') '''.format(name, name, country, country), conn) </code></pre> <p>You can also use <code>IN</code...
python|sql|pandas|sqlite|where-clause
2
12,945
71,655,381
Sklearn model, The truth value of an array with more than one element is ambiguous error
<p>I have been learning about decision trees and how to make them in sklearn. But when I have tried it out I have been unsuccessful in all my attempts to avoid a vlaue error that reads</p> <p>&quot;The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()&quot; here is the full error:<...
<p>This is a slight misunderstanding about how the <code>predict</code> function works. If you think about it conceptually, if you are trying to predict something, why would you need to pass in the expected labels?</p> <p>In a <code>DecisionTreeRegressor</code> (and in probably all sklearn models) the signature of <cod...
python|numpy|scikit-learn|tree
1
12,946
69,701,276
How to groupby and calculate new field with python pandas?
<p>I'd like to group by a specific column within a data frame called 'Fruit' and calculate the percentage of that particular fruit that are 'Good'</p> <p>See below for my initial dataframe</p> <pre><code>import pandas as pd df = pd.DataFrame({'Fruit': ['Apple','Apple','Banana'], 'Condition': ['Good','Bad','Good']}) </c...
<p>We can compare <code>Condition</code> with <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.eq.html" rel="nofollow noreferrer"><code>eq</code></a> and take advantage of the fact that <code>True</code> is (1) and <code>False</code> is (0) when processed as numbers and take the <a href="https://pand...
python|pandas|dataframe|pandas-groupby
4
12,947
43,149,493
Why my tensor still have the rank 2 after a reshape to 3D
<p>This is my script. `</p> <pre><code>def phi(x, b, w, B): z1 = tf.matmul(x,w) z2 = tf.cos(z1+b) w1 =tf.reshape(w,(1,2,1000)) #z= tf.reshape(z2,(100,1,1000)) z=tf.expand_dims(z2, 1) print(z) print(w1) phix = tf.matmul(z, tf.transpose(w1)) phix /= tf.sqrt(float(float(int(w.get_shape...
<p>You did <code>phix = np.reshape(phix,(200,1000))</code> using numpy to do the reshape. I think you meant to do <code>phix = tf.reshape(phix,(200,1000))</code> so tensorflow does it right?</p> <p>Numpy doesn't get used at computation time, only tensorflow operations get used. </p>
python|tensorflow
0
12,948
72,297,707
Concat values on dataframe columns excluding NaN's
<p>I have a dataframe with n <code>store</code> columns, here I'm just showing the first 2:</p> <pre><code> ref_id store_0 store_1 0 100 c b 1 300 d NaN </code></pre> <p>I want a way to concat only the non-NaN values from <code>store</code> columns into a new column ...
<p>You can use:</p> <pre><code>cols = df.filter(like='store_').columns df2 = (df .drop(columns=cols) .assign(stores=df[cols].agg(lambda s: s.dropna() .str.cat(sep=','), axis=1)) ) </code></pre> <p>Or, for in place modification:</p> <pre><code>col...
python-3.x|pandas|concatenation
1
12,949
72,398,521
Why do I receive Attribute error when I try to convert pandas df to H2O df?
<p>I receive an attribute error when i try to convert my pandas dataframe(dff) to an h2o dataframe(hf). Find the traceback below. How do I make my dff into an h2o dff?</p> <pre><code>import h2o h2o.init() import pandas as pd dff = pd.DataFrame({'col1': [1,1,2], 'col2': ['César Chávez Day', 'César Chávez Day', 'César Ch...
<p>I think you are using an old H2O version (current version is 3.36.1.2) with &quot;new&quot; pandas version - <code>as_matrix</code> was removed from pandas in version 1.0. You can either upgrade H2O or downgrade pandas to <code>pandas&lt;1.0</code>.</p>
pandas|dataframe|attributeerror|h2o
0
12,950
72,408,563
While loop to save csv files with conditional name
<p>I'd like to make a <code>while</code> / <code>for</code> loop in python to save dataframes into csv files.</p> <p>The files should be named something like: Day1, Day2, Day3...Day90</p> <p>First i determine for the n-th day, how large of a sample I should draw, based on a forecast.</p> <p>Then the sample is drawn fro...
<p>IIUC you could do something to this effect</p> <pre><code>for item in Period: Orders_df.sample(Samplesize).to_csv(f'{item}&lt;whatever you wanna call the file&gt;.csv', index = False) </code></pre>
python|pandas|dataframe|csv
1
12,951
50,480,244
Merge rows with columns in different format pandas
<p>I've a dataframe where I have n number of columns of same header eg. Sales, Sales 1, Sales 2 etc.</p> <p>And the data is rows of multiple records with a column having ID and ID column has duplicate values. </p> <p>Sales column has a first row stating the month eg Jan, Feb etc for Sales Sales 1 respectively</p> <p...
<p>You need create <code>MultiIndex</code> in columns first, then reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow noreferrer"><code>unstack</code></a> and last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_ind...
python|pandas
0
12,952
62,676,918
Pandas: Alternative methods to using nested for-loops for cell-comparisons
<p>I'm working on a problem with trying to find train-meeting at stations, but I'm having a hard time finding a way to do the necessary comparisons without using nested for-loops (which is way to slow, I have hundreds of thousands of data points).</p> <p>My DataFrame-rows contains the following useful data: An arrival ...
<p>Initialize the DataFrame.</p> <pre><code>d = {'arrival': [pd.Timestamp(datetime.datetime(2012, 5, 1, 1)), pd.Timestamp(datetime.datetime(2012, 5, 1, 3)), pd.Timestamp(datetime.datetime(2012, 5, 1, 6)), pd.Timestamp(datetime.datetime(2012, 5, 1, 4))], 'departure': [pd.Timestamp(datetime....
python|pandas
1
12,953
62,485,497
my annual_inc column is not showing any graph, and am not able to understand what is the problem
<pre><code>import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns df=pd.read_csv(&quot;C:\\Users\\USER\\Desktop\\ML\\XYZCorp_LendingData.txt&quot;, sep='\t',low_memory=False) df['annual_inc'].head() ''' 0 24000.0 1 30000.0 2 12252.0 3 49200.0 4 80000.0 Name: annual...
<p>Income usually follows some kind of <a href="https://en.wikipedia.org/wiki/Pareto_distribution" rel="nofollow noreferrer">pareto distribution</a> (Pareto is also known from the related <a href="https://en.wikipedia.org/wiki/Pareto_principle" rel="nofollow noreferrer">80-20 rule</a>). This means a huge number of smal...
python|pandas|matplotlib|seaborn
2
12,954
62,578,066
Is there a way for user to globally override the default value of a keyword argument for all functions that use it?
<p>While using pandas, I find myself specifying inplace=True in many function calls. I use that much more than the default value, which tends to be inplace=False wherever it is defined, by convention.</p> <p>Is there a way to specify some (perhaps global) variable like</p> <pre><code>inplace = True </code></pre> <p>and...
<p>I think the only way to achieve such behavior is to monkey-patch the code you want to change - e.g. if you want to change behavior of pd.DataFrame you can do that (there are some minor drawbacks here like giving up using <code>inplace</code> as positional argument if it ever was + maybe someone could point more issu...
python|pandas
1
12,955
62,634,687
keep order while using python pandas pivot
<pre><code>df = {'Region':['France','France','France','France'],'total':[1,2,3,4],'date':['12/30/19','12/31/19','01/01/20','01/02/20']} df=pd.DataFrame.from_dict(df) print(df) Region total date 0 France 1 12/30/19 1 France 2 12/31/19 2 France 3 01/01/20 3 France 4 01/02/20 </code></p...
<p>Convert values to datetimes before <code>pivot</code> and then if necessary convert to your custom format:</p> <pre><code>df['date'] = pd.to_datetime(df['date']) pandas_temp = df.pivot(index='Region',values='total', columns='date') pandas_temp = pandas_temp.rename(columns=lambda x: x.strftime('%m/%d/%y')) #alterna...
python|pandas|pivot
1
12,956
62,785,284
Reshaping Numpy Array To a Smaller Size
<p>I have a dataset contains point clouds and images. To traing these data, I want to concatenate these arrays using numpy concatenate. But the problem is point cloud data is in shape of (20000, 3) and image is in shape of (370, 1224, 3). And while trying to concatenate,it gives me an error saying &quot;ValueError: can...
<p>Your cloud data is shaped like a long piece of string while your image is shaped like a piece of paper. Can you imagine these shapes in your head? How would you combine them?</p> <p>Maybe what you want instead is a way to provide two different types of input to a model? How to do this would depend on what kind of to...
python|numpy
0
12,957
54,532,896
Count consecutive zeros over pandas rows
<p>Having the following <code>pd.DataFrame</code></p> <pre><code>pd.DataFrame({'2010':[0, 45, 5], '2011': [12, 56, 0], '2012': [11, 22, 0], '2013': [0, 5, 0], '2014': [0, 0, 0]}) 2010 2011 2012 2013 2014 1 0 12 11 0 0 2 45 56 22 5 0 3 5 0 0 0 0 </code></pre> <p>I would like to cou...
<p>For efficiency, I would suggest going pure NumPy way -</p> <pre><code>def islandlen_perrow(df, trigger_val=0): a=df.values==trigger_val pad = np.zeros((a.shape[0],1),dtype=bool) mask = np.hstack((pad, a, pad)) mask_step = mask[:,1:] != mask[:,:-1] idx = np.flatnonzero(mask_step) island_lens ...
python|pandas
3
12,958
54,693,349
Pandas Group by 2 columns using another column to find the delta
<p>I have a pandas dataframe that has 4909144 rows, with <code>time</code> as the index, <code>source_name</code>, <code>dest_address</code>, and <code>tvalue</code> which is just the same as the <code>time</code> index. I have sorted the df by <code>source_name</code>, <code>dest_address</code>, and <code>tvalue</cod...
<pre><code>import datetime as dt source_changed = df['sourcehostname'] != df['sourcehostname'].shift() dest_changed = df['destinationaddress'] != df['destinationaddress'].shift() change_occurred = (source_changed | dest_changed) time_diff = df['tvalue'].diff() now = dt.datetime.utcnow() zero_delta = now - now df['t...
python|pandas|pandas-groupby
1
12,959
73,745,218
How to load a trained ML model with pytorch
<p>I am very new to Machine Learning, and very lack of the experience. Recently i am trying to collect my own datasets and see the performance of it on a <a href="https://github.com/Turoad/CLRNet" rel="nofollow noreferrer">trained model</a>. In README.md it only tells me how to train my own model, but it did not tell m...
<p>I didn't try testing it but personally I'd add another function based on <code>Runner.validate()</code> <a href="https://github.com/Turoad/CLRNet/blob/7269e9d1c1c650343b6c7febb8e764be538b1aed/clrnet/engine/runner.py#L126" rel="nofollow noreferrer">here</a> so that you don't need to bother with <code>cfg</code>. Mayb...
pytorch
0
12,960
73,627,550
Stripping 0's from the middle of a dataframe
<p>Basically data is coming into my program in this format 0xxxx000xxxx where the x is unique to the data that I have in another system. I'm trying to remove those 0's as they're always in the same place. I tried</p> <pre><code>df['item'] = df['item'].str.replace('0','') </code></pre> <p>but sometimes the x can be a 0 ...
<p>Use the <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.html" rel="nofollow noreferrer"><code>str</code></a> accessor for indexing:</p> <pre><code>df['item'] = df['item'].str[1:5] + df['item'].str[8:] </code></pre> <p>Or <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str....
python|pandas|dataframe
1
12,961
71,317,552
Dataframe merging with src and dst keys
<p>I have three dataframes</p> <pre><code>df1 = pd.DataFrame({'src': ['src1', 'src2', 'src3'], 'dst': ['dst1', 'dst2', 'dst3']}) df2 = pd.DataFrame({'src': ['dst1', 'dst1', 'dst3'], 'dst': ['dstDst1', 'dstDst2', 'dstDst3']}) df3 = pd.DataFrame({'src': ['dstDst3', 'dstDst3'], ...
<p>You can avoid the nested for loops by the following code.</p> <h2>Code:</h2> <pre class="lang-py prettyprint-override"><code>import pandas as pd # Create the sample dataframes df1 = pd.DataFrame({'src': ['src1', 'src2', 'src3'], 'dst': ['dst1', 'dst2', 'dst3']}) df2 = pd.DataFrame({'src': ['dst1', 'dst1', 'dst3'], ...
python|pandas|dataframe
1
12,962
71,156,798
Python: Expand dataframe rows with specific column value in terms of 1/8th
<p>Have got input dataframe like below:</p> <p><em>df</em></p> <pre><code>Store Item Space 11 Grape 0.125 11 Beans 0.0 12 Mango 0.25 13 Beetroot 0.375 13 Carrot 0.5 </code></pre> <p>Need to expand given <code>df</code> row w.r.t. '<code>Space</code>' column. V...
<p>You can use</p> <pre><code>eigth = 0.125 result = df['Item'].repeat(df['Space']/eigth).to_frame().assign(Space=eigth) </code></pre> <blockquote> <p>How to improve this line of code to include in any additional columns present in df and to include those as well? Question edited accordingly.</p> </blockquote> <pre><co...
python|python-3.x|pandas|dataframe|expand
2
12,963
52,224,001
Why Speech Commands dataset by google has a sampling rate of 16kHz
<p>Google released <a href="https://storage.cloud.google.com/download.tensorflow.org/data/speech_commands_v0.02.tar.gz" rel="nofollow noreferrer">Speech Commands dataset</a>. I see that all the audio files has a sampling rate of 16kHz. Which means that any infomation from 8kHz and up is unreliable (human hearing range ...
<blockquote> <p>This is extremely critical regarding voice recognition, because (not most but) a lot of important data is within the rage of 8khz to 20khz</p> </blockquote> <p>Actually not, many experiments demonstrate that there is almost no improvement from using higher sample rate. That is why everyone uses 16khz...
speech-recognition|speech-to-text|tensorflow-datasets
1
12,964
52,285,206
tf.decode_csv parameter 'labels' has DataType float64 not in list of allowed values: int32, int64
<p>trying to pass TensorFlow tf.decode_csv a float64 datatype but getting error it's not allowed</p> <pre><code> CSV_TYPES = [[0.0], [2.], [0.0], [0.0], [0.0], [0]] def _parse_line(line): fields = tf.decode_csv(line, record_defaults=CSV_TYPES) </code></pre> <p>The problem is the second value which here...
<p>Scratch that, I had an error in my .csv file. </p>
tensorflow
0
12,965
52,065,501
Add column identifying original data frame when using pd.concat
<p>I have a dictionary of data frames like the following:</p> <pre><code>test = {'df1':pd.DataFrame({'col1':[3, 5, 1, 4], 'col2':[3, 5, 1, 4]}), 'df2':pd.DataFrame({'col1':[3, 5, 1, 4], 'col2':[3, 5, 1, 4]}), 'df3':pd.DataFrame({'col1':[3, 5, 1, 4], 'col2':[3, 5, 1, 4]}), 'df4':pd.DataFrame({'col1':[3, 5, 1, 4], 'col2...
<p>Using <code>concat</code> with <code>keys</code></p> <pre><code>pd.concat(test.values(),keys=test.keys()) Out[261]: col1 col2 df1 0 3 3 1 5 5 2 1 1 3 4 4 df2 0 3 3 1 5 5 2 1 1 3 4 4 df3 0 3 3 1 5 5 ...
python|python-3.x|pandas
3
12,966
60,583,607
Group by ids with padding in TensorFlow?
<p>I given a 1D tensor of ids <code>idxs</code> and a 1D tensor of values <code>values</code> I want to create a padded 2D padded tensor where each row correspond to the id. For example:</p> <pre><code>idxs = tf.constant([1, 4, 1, 2, 2, 3, 4, 1, 4]) values = tf.constant([1,2,3,4,5,6,7,8,9]) output = fn(values, idxs, -...
<p>I've created a working solution for fn. It's not a very elegant or efficient solution however. </p> <pre><code>def get_ith_occurance(ith_occurance, all_positions, values, default_value): # Get the ith occurrence in all_positions if it exists return tf.cond( f.size(all_positions)&gt;ith_occurance, ...
python|tensorflow
0
12,967
60,586,110
Distribution Strategy that leverages all CPUs and all GPUs
<p>I have mirrored distribution strategy defined below:</p> <pre><code># create an instance of ImageDataGenerator gen_train = ImageDataGenerator( rotation_range=20, width_shift_range=0.1, height_shift_range=0.1, shear_range=0.1, zoom_range=0.2, horizontal_flip=True, preprocessing_function=preprocess_inpu...
<ol> <li><p>Batch size is global batch_size so you have to multiply your single batch sizer per num of GPUs</p></li> <li><p>To do a better use of resources, you should use tf.data and read the performance guide: <a href="https://www.tensorflow.org/guide/data_performance" rel="nofollow noreferrer">https://www.tensorflow...
python|tensorflow|keras|tensorflow2.0|tensorflow2.x
0
12,968
60,687,334
Eagerly update a keras model's weights directly using the gradient
<p>I am writing a custom optimizer with Eager Execution in Ternsorflow 1.15 but can't figure out how to update the weights. Taking gradient descent as an example, I have the weights, the gradient and a scalar learning rate but can't figure out how to combine them.</p> <p>This is an implementation of gradient descent w...
<p>Figured it out. As both are lists we need to iterate through their pairs of gradients and variables for each layer together and update each of these separately.</p> <pre><code>lr = tf.constant(0.01) def minimize(model, inputs, targets): with tf.GradientTape() as tape: logits = model(input) loss...
python|tensorflow|keras
0
12,969
72,524,613
compare strings in the same row but in different columns and catch in which column they are not equal
<p>I have a Dataset like this:</p> <pre><code>dictionary = {'Month1': ['C1','C2',0,0,'C5'], 'Month2': ['C1','C2','C3','C4',0], 'Month3': ['C1','C2','C3','C4',0], 'Month4' : [0,'C2','C3',0,0]} df = pd.DataFrame(dictionary) Month1 Month2 Month3 Month4 0 C1 C1 C1 0 1 C2 C2 C2 ...
<p>Let us do</p> <pre><code>s = df.ne(0).dot(df.columns+',').str[:-1].str.split(',') df['1st'] = s.str[0] df['-1st'] = s.str[-1] </code></pre> <p>Notice you can also do 2nd</p> <pre><code>df['2nd'] = s.str[1] </code></pre>
python|pandas|string|dataframe|compare
1
12,970
72,792,399
Python find the long axis of a 3D point cloud or 3D hull
<p>I am trying to find the 'long axis' of a 3D object (described as a 3D boolean or label array), which passes through (or near) the centroid of that object.</p> <p>I would like to think I could simply iterate over every pair of points in the object and pick the pair with the largest distance between them, but in the c...
<p>The solution is <a href="https://stackoverflow.com/a/72794537/19298921">here</a></p> <p>Just use</p> <pre><code>image=np.array([[0,0,0,0,0], [0,0,1,0,0], [0,1,1,1,0], [0,0,0,0,0], [0,0,0,0,0]] </code></pre>
python|numpy|least-squares|image-thresholding
0
12,971
59,677,302
Solution of checking retention of users through RESAMPLE
<p>For the purpose of finding frequency and retention of users on a service, I tried to re sample data but fail as it lose parts of my data. </p> <p><em>Please note that the frequency could be month, year, every 3 days or 5 days</em></p> <p>This is sample data:</p> <pre><code>a=pd.DataFrame([[Timestamp('2019-01-01')...
<p>Try this:</p> <pre><code>a=pd.DataFrame([['2019-01-01','Jack'], ['2019-01-15','Jack'], ['2019-02-6','Lina'], ['2019-03-23','Tom'], ['2019-03-22','Jack'], ['2019-02-14','Jack']],columns=['Date','Name']) a['Date'] = pd.to_datetime(a['Dat...
python|python-3.x|pandas
1
12,972
59,609,376
Compute difference based on matching observations over time
<p>Suppose we have the following dataframe:</p> <pre><code> Date Type Country Value 0 2016-04-30 A NL 1 1 2016-04-30 A BE 2 2 2016-04-30 B NL 3 3 2016-04-30 B BE 4 4 2016-04-30 C NL 5 5 2016-04-30 C BE 6 6 2016-04-30 C FR 7 7 2016-...
<p>If there are all unique pairs <code>Type</code> and <code>Country</code> per <code>Date</code> groups then is possible use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.diff.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.diff</code></a>:</p> <pre><co...
python|pandas|dataframe|difference
2
12,973
59,695,614
Numpy fancy indexing question about specific array and its final shape?
<pre><code>X = np.arange(12).reshape((3, 4)) =&gt; shape (3,4) row = np.array([0, 1, 2]) row[:, np.newaxis] =&gt; shape (3,1) X[row[:, np.newaxis], :] =&gt; shape (3,1,4) </code></pre> <p>Can anyone explain how this final shape occurs, when according to the "rules of broadcasting" the shapes of the indices broadcast...
<ul> <li><p><code>X[i, :]</code> gives the i-th row of <code>X</code> as array of shape <code>(X.shape[1],)</code></p></li> <li><p><code>X[[i], :]</code> gives the i-th row of <code>X</code> as array of shape <code>(1, X.shape[1])</code></p></li> <li><p><code>X[[[i]], :]</code> gives the i-th row of <code>X</code> as a...
python|numpy|indexing|reshape
0
12,974
59,862,286
Find identical values in a column of a dataframe and create a new dataframe with each duplicate
<p>I'm relatively new to Python and searching for an answer to my problem the whole day already, but unfortunately could't find anything.</p> <p>I import data to python from an excel file and create a dataframe with it. The Data is a long list with customers and their payments. The column Account (which represents the...
<p>If I understood you correctly, something like this will help. Let's assume <code>df_customer</code> is your dataframe.</p> <p><strong>Code:</strong></p> <pre class="lang-py prettyprint-override"><code>cntr=1 for i in df_customer['Account'].unique(): locals()['df_customer'+str(cntr)]=df_customer[df_customer['Ac...
python|python-3.x|pandas
1
12,975
61,662,019
How to groupby using a list of columns
<p>I am trying to pass a list of columns into a groupby operation. I've seen a number of solutions but to problems that are more complex than mine. What is the <strong>simplest</strong> way to solve for it?</p> <pre><code>cols = [col1, col2, col3] df[[cols, 'colx']].groupby([cols], as_index=False).sum() </code></pre>...
<p>I will be honest I don't know exactly what is happening here but I have some theories. Lets me show you my thought process here:</p> <pre><code>df[["col_1", "col_2", "col_3"]] </code></pre> <p>This is a slice of df containing a list of columns. </p> <p>When you pass a list into this syntax using like you did in...
python|list|pandas-groupby
0
12,976
57,854,832
Data manipulation per group in pandas
<p>I am working with a dataset structured like this:</p> <pre><code>import pandas as pd dat = pd.DataFrame({'id': [1,1,1,2,3,4,5,5], 'period':[1,2,3,1,2,1,2,4], 'dsti':[0.1,0.2,0.5,0.2,0.3,0.3,0.4,0.2]}) &gt;&gt;&gt;dat id period dsti 0 1 1 0.1 1 1 2 0.2 2 1 3 0.5 3 2 1 0....
<p>Use:</p> <pre><code>#filter out unique rows by id dat = dat[dat['id'].duplicated(keep=False)].copy() #get difference per id df = dat.groupby('id').diff(-1) #division for new column, df is assigned to dat, because same index in both dat['dsti2'] = df['dsti'].div(df['period']) #remove missing rows by dsti2 column dat...
python|pandas|dataframe|pandas-groupby
3
12,977
58,112,683
How to replace timestamp across the columns using pandas
<pre><code>df = pd.DataFrame({ 'subject_id':[1,1,2,2], 'time_1':['2173/04/11 12:35:00','2173/04/12 12:50:00','2173/04/11 12:59:00','2173/04/12 13:14:00'], 'time_2':['2173/04/12 16:35:00','2173/04/13 18:50:00','2173/04/13 22:59:00','2173/04/21 17:14:00'], 'val' :[5,5,40,40], 'iid' :[12,12,12,12] }) df['time_1...
<p>I pandas if all datetimes have <code>00:00:00</code> times in same column then not display it.</p> <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.floor.html" rel="nofollow noreferrer"><code>Series.dt.floor</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable...
python|python-3.x|pandas|dataframe|datetime
1
12,978
54,777,468
problem with condition statement despite using right operator
<p>I wrote this script to create a specific variable that takes different values according to the number of reports. Count of Report is an integer column.</p> <pre><code>no_audit = df_bei_index['Count of Report'] == 0 few_audit = df_bei_index['Count of Report'] &gt; 0 &amp; df_bei_index['Count of Report'] &lt; 30 co...
<p>Change your <code>m2</code> with adding <code>()</code></p> <pre><code>m1= df_bei_index['Count of Report'] == 0 m2= (df_bei_index['Count of Report'] &gt; 0) &amp; (df_bei_index['Count of Report'] &lt; 30) </code></pre>
python|pandas|numpy|boolean|conditional-statements
2
12,979
54,993,739
Regression analysis for linear regression
<p>I have a regression model where my target variable (days) quantitative values ranges between 2 to 30. My RMSE is 2.5 and all the other X variables(nominal) are categorical and hence I have dummy encoded them. I want to know what would be a good value of RMSE? I want to get something within 1-1.5 or even lesser but ...
<p>If your x values are categorical then it does not necessarily make much sense binding them to a uniform grid. Who's to say category A and B should be spaced apart the same as B and C. Assuming that they are will only lead to incorrect representation of your results.</p> <p>As your choice of scale is the unknowns, y...
python|machine-learning|sklearn-pandas
0
12,980
55,039,887
Plot date against time. Python
<p>I have those crime data from San Fransisco. My original data looks like this. <a href="https://i.stack.imgur.com/16lfo.png" rel="nofollow noreferrer">san Fransisco data</a></p> <p>Long story short, I need to plot dates against time(after performing some filtering) and create a jitter plot. The original format of th...
<p>You have converted the Time column to a <code>pd.datetime</code> object as well. The 7 you are seeing is a part of the date (truncated to only show the last part). </p> <p>If you change your y values to Time objects you will likely get what you are after. E.g:</p> <p><code>y7 = df.Time.dt.time.tolist()</code></p>
python|pandas|dataframe|time|jitter
0
12,981
54,770,873
set value within groups pandas
<p>I'm trying to assign a name to each grouping within pandas.</p> <p>I have a dataframe, and a list of names:</p> <pre><code>df = pd.DataFrame({'a':[1, 1, 2, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10], 'ids':[234, 345, 456, 444, 333, 22, 11, 5, 1, 2, 3, 4, 6]}) names = ['Matt', 'Jeff', 'Steph', 'Shannon'] <...
<p>Is this what you need ? </p> <pre><code>(df.groupby('a').ngroup()%4).map(dict(enumerate(names))) Out[339]: 0 Matt 1 Matt 2 Jeff 3 Jeff 4 Steph 5 Shannon 6 Matt 7 Jeff 8 Steph 9 Steph 10 Shannon 11 Matt 12 Jeff dtype: object </code></pre...
python|pandas
2
12,982
55,043,492
Adjacency list to matrix pandas
<p>I'm trying to get through a toy example of building an adjacency matrix from a list, but already I can't quite figure it out. I am thinking in terms of .loc() but I'm not sure how to index correctly.</p> <pre><code>{'nodes':['A', 'B', 'C', 'D', 'E'], 'edges':[('A', 'B'), ('A', 'D'), ('B', 'C'), ('B', 'E'), ('C', '...
<p>A simple way to obtain the adjacency matrix is by using <code>NetworkX</code></p> <pre><code>d = {'nodes':['A', 'B', 'C', 'D', 'E'], 'edges':[('A', 'B'), ('A', 'D'), ('B', 'C'), ('B', 'E'), ('C', 'D'), ('D', 'E'), ('E', 'A'),('E', 'B'), ('E', 'C')]} </code></pre> <p>It appears that from...
python|pandas|dataframe|networkx|adjacency-matrix
3
12,983
49,721,407
access Variables within function, which defines model to use it on test data Tensorflow
<p>I am already very impressed with Tensorflow and it's automatic chain rule when it comes to find derivative. But I have one question, is it possible to access Variables from function which models train data?</p> <pre><code>import tensorflow as tf import numpy as np X1 = np.array([[1,2,3]],dtype=np.float32).T #tr...
<p>Yes it is possible! The weights and bias would be re-used for the test data. You would ideally want to run,</p> <pre><code>sess.run(result, feed_dict={x: X2, y: y2}) </code></pre>
python|tensorflow
1
12,984
49,598,588
How to return multiple keys in a string if a given string matches the keys value in a dictionary
<p>I'm trying to iterate through a dataframe column to extract a certain set of words. I'm mapping these as key value pairs in a dictionary and have with some help managed to set on key per row so far.</p> <p>Now, what I would like to do is return multiple keys in the same row if the values are present in the string a...
<p>The problem is that you return directly after finding a key, while you should continue searching untill all results are found:</p> <pre><code>def fetchColours(x): keys = [] for key, values in colour.items(): for value in values: if value in x.lower(): keys.append(key) ...
python|pandas|dictionary|dataframe
2
12,985
49,716,504
Access Arrays by index
<p>I want to access arrays like in the example code below, this is quite slow. Is it possible to create a vector from <code>i</code> ans <code>f_s</code> and access the arrays by that index? </p> <pre><code>def calc(self, length): for i in range(int(f_s*length*6)): t = i / f_s self.data[i] = (num...
<p>I found the answer by myself. The solution is to use numpy's take function. You can pass the array and a vector of indices to the function and it will return the desired arrays.</p> <pre><code>def calc(self,length): t = numpy.arange(0, f_s*length*6, 1/f_s) t_sin = t * f_carrier %512 t_sig = t * f_prn % ...
python|arrays|numpy|indexing
1
12,986
49,475,930
How do I check to see if it's safe to call compute on Dask?
<p>Currently my PC it's freezing while I'm trying to calculate the log1p to entire Column a large dataset (4GB ~ 125 Million of rows) when I run this:</p> <pre><code>df_train = dd.read_csv('data/train.csv') s = df_train.unit_sales.map_partitions(np.log1p) s.compute() </code></pre> <p>So, How Can I handle know if it's...
<p>Note that when you call <code>.compute()</code> you are converting your lazy Dask dataframe into an in-memory Pandas dataframe. Your result (in this case <code>s.compute()</code>) should fit comfortably into memory. If you want you can call <code>s.memory_usage().compute()</code> to see how large your result will ...
python|pandas|dataframe|dask
4
12,987
49,697,577
Compare elements in two 1D arrays of different size, with tolerance
<p>I'd like to find what values exist in an array 'A' that also exist in array 'B'. However, the arrays are of different size and I'd like to introduce a tolerance as there is likely to be a systematic error between the two datasets. </p> <p>I'm aware of 'np.isclose', but this is for arrays of the same size. </p>
<p>You could improve on nested loops by using a slightly more builtin numpy solution:</p> <pre><code>import numpy as np A = np.array([0, 0.3141, 1.234, 4.1341, -34.112]) B = np.array([0.3142, 2.234, 4.1340, -34.113, 40]) res = {i for i in A if np.isclose(B, i, 0.1).any()} print(res) </code></pre> <p>Output:</p> <pr...
python|arrays|python-3.x|numpy
1
12,988
49,544,421
Why does pandas roll a week forward when using resample with W-MON frequency?
<p>As example, I have the following code which creates a dataframe with an index containing a single value - the date '2018-03-06' (a Tuesday). Note that this date falls in the week of 2018-03-05 (a Monday):</p> <pre><code>values = [1, 1, 1] dates = pd.to_datetime(np.repeat('2018-03-06', 3)) df = pd.DataFrame({ '...
<p>Let's try using <code>label</code> and <code>closed</code> <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html#pandas-dataframe-resample" rel="noreferrer">see docs</a>:</p> <pre><code>values = [1, 1, 1] dates = pd.to_datetime(np.repeat('2018-03-06', 3)) df = pd.DataFrame({...
python|pandas
7
12,989
73,255,517
Is it possible to link axes from different plots in pandas-bokeh package?
<p>In regular Bokeh there is a nice feature of linking axes from different subplots in a grid which e.g. is very useful for zooming on multiple graphs simultaneously. But this doesn't seem to work in the pandas-bokeh package - any good solutions?</p>
<p>Yes it is.</p> <p>It is not streight forward, but you can make use of <code>js_link</code> of the <a href="http://docs.bokeh.org/en/latest/docs/reference/models/plots.html?highlight=x_range#bokeh.models.Plot.x_range" rel="nofollow noreferrer"><code>x_range</code></a> and this is not too complicated. The same of cour...
python|plot|linker|bokeh|pandas-bokeh
0
12,990
73,244,442
HuggingFace Trainer() cannot report to wandb
<p>I am trying to set trainer with arguments <code>report_to</code> to <code>wandb</code>, refer to <a href="https://docs.wandb.ai/guides/integrations/huggingface#getting-started-track-experiments" rel="nofollow noreferrer">this docs</a> with config:</p> <pre><code>training_args = TrainingArguments( output_dir=&quo...
<p>Although the documentation states that the <code>report_to</code> parameter can receive both <code>List[str]</code> or <code>str</code> I have always used a list with 1! element for this purpose.</p> <p>Therefore, even if you report only to wandb, the solution to your problem is to replace:</p> <pre><code> report_to...
python|huggingface-transformers|wandb
1
12,991
67,575,141
How to return specific data from a column of a dataframe when a different column value match
<p>I have this Dataframe with three columns that i recieve from a excel file and create using pandas, so my program needs to order the points column and return a string with the ordered names.</p> <p><a href="https://i.stack.imgur.com/eHNJY.png" rel="nofollow noreferrer">enter image description here</a></p> <p>so i mak...
<p>You can use the built in function to sort the dataframee.</p> <p><code>df.sort_values(by=['Points'])</code></p> <p>df - dataframe object, Points - name of the points of the column. Once sorted, the dataframe can be printed as usual.</p> <p>For other parameters that can be used, take a look at the <a href="https://pa...
python|pandas
0
12,992
67,378,179
Extracting column name from table
<p>I have a dataframe:</p> <p>df:</p> <pre><code>ID Date A B C 1 201901 4 5 2 1 201902 3 4 2 </code></pre> <p>I have another table: df1:</p> <pre><code> Columns B C </code></pre> <p>While keeping the ID, and Date column.. and I trying to use the columns given in the table as well.</p> <p>Currently I am using...
<p>Instead of using <code>df1</code>, you need extract values from <code>Columns</code> column of <code>df1</code>.</p> <pre class="lang-py prettyprint-override"><code>df = df[['ID','Date']+df1['Columns'].values.tolist()] </code></pre> <p>If your <code>Columns</code> of <code>df1</code> contains column not in <code>df<...
python|pandas|dataframe
1
12,993
67,387,383
numpy equivalent code of unsqueeze and expand from torch tensor method
<p>I have these 2 tensors</p> <pre><code>box_a = torch.randn(1,4) box_b = torch.randn(1,4) </code></pre> <p>and i have a code in pytorch</p> <pre><code>box_a[:, 2:].unsqueeze(1).expand(1, 1, 2) </code></pre> <p>but i want to convert the above code in numpy<br /> for <code>box_a</code> and <code>box_b</code> i can do so...
<p>solved it</p> <pre><code>box_a = np.random.randn(1,4) box_b = np.random.randn(1,4) max_xy = np.broadcast_to(np.expand_dims(box_a[:, 2:],axis=1),(1,1,2)) </code></pre>
python|numpy|pytorch|tensor|torch
2
12,994
67,270,548
how group by and filter multiple strings with Pandas Dataframe?
<p>I'm a beginner for coding and I've tried to look for answers for a few days but I didn't succeed what I want to do so sorry in advance if it's easy or if it already exists somewhere... Let's say I have a df1 with columns : series_id and lesion_name and I would like to obtain a df2 by replacing the df1 with series_id...
<p>I found an answer that seems to work for now !</p> <pre><code># We remove all lesion_name that contains string &quot;tum&quot; to work on creating the column lung_ref_seg (and we keep nan values) test = test[~test.lesion_name.str.contains(&quot;tum&quot;,na=False)] # Define the function to pick one lesion_name for...
python|pandas|string|apply
0
12,995
60,075,839
Calculating max/min for every n rows of dataframe in python
<p>I want to calculate the min/max for every n rows of a df, say 10, but using df.rolling(10).max() gives the values for rows 0-9, 1-10, 2-11 etc. I want 0-9, 10-19, 20-29 etc</p> <p>Is there a neat way of doing this for a large dataset?</p> <p>Thanks</p>
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html" rel="nofollow noreferrer"><code>np.arange</code></a> to calculate an array of <code>0</code> to <code>len (df) -1</code> and then calculate the entire divison. We can use this array together with <a href="https://pandas.pydata.org/p...
python|pandas|dataframe|max|min
3
12,996
60,180,275
Merge specific column in multiple dataframe with different length
<p><strong>df1</strong></p> <pre><code> Color date 0 A 2011 1 B 201411 2 C 20151231 3 A 2019 </code></pre> <p><strong>df2</strong></p> <pre><code> Color date 0 A 2013 1 B 20151111 2 C 201101 </code></pre> <p><strong>df3</strong></p> <pre><code> C...
<p>This include two problem, 1 multiple dataframes <code>merge</code>, 2 duplicated key merge</p> <pre><code>def multikey(x): return x.assign(key=x.groupby('Color').cumcount()) #we use groupby and cumcount create the addtional key from functools import reduce #then use reduce df = reduce(lambda left,right: ...
python|pandas|dataframe|merge|multiple-columns
1
12,997
65,303,823
how to detect when a price higher than previous high
<p>I am trying to find when a price value is cross above a high, I can find the high but when I compare it to current price it gives me all 1<br /> my code :</p> <pre><code>peak = df[(df[‘price’] &gt; df[‘price’].shift(-1)) &amp; (df[‘price’] &gt; df[‘price’].shift(1))] df[‘peak’] = peak df[‘breakout’] = df[‘price’] &g...
<p>Try with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html" rel="nofollow noreferrer"><code>pandas.DataFrame.fillna</code></a>:</p> <pre><code>df[&quot;breakout&quot;] = df[&quot;price&quot;] &gt;= df[&quot;peak&quot;].fillna(method = &quot;ffill&quot;) </code></pre> <...
python|pandas|numpy
0
12,998
65,206,417
If value in column A is not null then insert specific string in column B. Python / Pandas
<p>I have a df and I want to insert a specific string (in this case &quot;foo_bar&quot;) in column B when column A is not NULL.</p> <pre><code>A B foo bar foo foo NaN NaN foo bar NaN NaN </code></pre> <p>The ideal results would look like this.</p> <pre><code>A B foo bar foo foo NaN foo_bar foo ba...
<p>Try: <code>df.loc[df.A.isnull(), 'B'] = &quot;foo_bar&quot;</code></p> <p>This selects all rows where A is NaN, then select column B, and set the value to the string.</p>
python|python-3.x|pandas|string|data-cleaning
1
12,999
65,434,056
Why converting npy files (containing video frames) to tfrecords consumes too much disk space?
<p>I am working on a violence detection service. I am trying to develop software based on the code in <a href="https://github.com/mchengny/RWF2000-Video-Database-for-Violence-Detection/blob/master/Networks/Flow%20Gated%20Network.ipynb" rel="nofollow noreferrer">this repo</a>. <a href="https://www.kaggle.com/shreyj1729/...
<p>The answer might be too late. But I see you are still saving the video frame in your tfrecords file. Try removing the &quot;image&quot; feature from your features list. And saving per frame as their Height, Width, Channels, and so forth.</p> <pre><code>feature = {'label': _int64_feature(int(label))} </code></pre> <p...
python|tensorflow|image-processing|protocol-buffers|tfrecord
0