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
2,300
60,193,013
Does Pandas release the GIL for string comparison?
<p>I'm thinking of using Pandas to compare the values in certain columns between two large CSV's. The comparison is just a simple Pandas compare. Something like below:</p> <pre><code>flagged_cars = cars.loc[cars.name_L != cars.name_R].copy() </code></pre> <p>Does Pandas string comparison require the GIL? Will Pandas us...
<p>I know I'm 8 months late to your question, but no, pandas does not release the GIL for string comparison.</p>
python|pandas|large-files
1
2,301
59,912,850
Autoencoder MaxUnpool2d missing 'Indices' argument
<p>The following model returns the error: <strong>TypeError: forward() missing 1 required positional argument: 'indices'</strong></p> <p>I've exhausted many online examples and they all look similar to my code. My maxpool layer returns both the input and the indices for the unpool layer. Any ideas on what's wrong?</p...
<p>Similar to the question <a href="https://stackoverflow.com/questions/53858626/pytorch-convolutional-autoencoders?rq=1">here</a>, the solution seems to be to separate the maxunpool layer from the decoder and explicitly pass its required parameters. <code>nn.Sequential</code> only takes one parameter.</p> <pre><code>...
pytorch
5
2,302
60,003,512
Any special algorithm for pedestrian detection alone?
<p>I need to detect the pedestrian who are using zebra crossing.I implemented by using yolo algorithm .But it detects everyone not only the pedestrian .So is there any method or special algorithm for pedestrian alone.If not how can I train my new model?</p>
<p>From YOLO you should not only get the detections but also the classes. Your model was most likely trained on the COCO dataset which has a certain table of objects that it can offer. </p> <p>You can find such a list here: <a href="https://github.com/pjreddie/darknet/blob/master/data/coco.names" rel="nofollow norefer...
opencv|machine-learning|computer-vision|video-processing|tensorflow2.0
0
2,303
60,024,262
Error converting object (string) to Int32: TypeError: object cannot be converted to an IntegerDtype
<p>I get following error while trying to convert object (string) column in Pandas to <code>Int32</code> which is integer type that allows for <code>NA</code> values.</p> <pre><code>df.column = df.column.astype('Int32') </code></pre> <blockquote> <p>TypeError: object cannot be converted to an IntegerDtype</p> </bloc...
<p>It's known bug, as explained <a href="https://github.com/pandas-dev/pandas/issues/25472" rel="noreferrer">here</a>.</p> <p>Workaround is to convert column first to <code>float</code> and than to <code>Int32</code>.</p> <p>Make sure you strip your column from whitespaces before you do conversion:</p> <pre><code>df.co...
python|pandas
35
2,304
65,406,327
How to create a boolean array where the value is based on an array of indices?
<p>Let say I have a numpy array <code>A</code> as follows:</p> <pre><code>A = array([[0, 2], [1, 2], [0, 1]]) </code></pre> <p>I created a boolean array <code>B</code> using <code>np.zeros</code> as follows</p> <pre><code>B = array([[False, False, False], [False, False, False], [False, Fal...
<p>You can do this using some Numpy's relatively advanced indexing techniques:</p> <pre><code>In [27]: B[np.arange(A.shape[0])[:,None], A] = True In [28]: B ...
python|numpy
3
2,305
49,950,261
searching a word in the column pandas dataframe python
<p>I have two text columns and I would like to find whether a word from one column is present in another. I wrote the below code, which works very well, but it detects if a word is present anywhere in the string. For example, it will find "ha" in "ham". I want to use regex expression instead, but I am stuck. I came acr...
<p>Yes, you can! It is going to be a little bit messy so let me construct in a few steps:</p> <p>First, let's just create a regular expression for the single case of <code>check_subset("ABC-xy 54", "54 xy")</code>: </p> <ul> <li>We will use <code>re.findall(pattern, string)</code> to find all the occurrences of <code...
python|regex|pandas
3
2,306
63,799,693
pandas DatetimeIndex to matplotlib x-ticks
<p>I have a pandas Dateframe with a date index looking like this:</p> <pre><code>Date 2020-09-03 2020-09-04 2020-09-07 2020-09-08 </code></pre> <p>The dates are missing a few entries, since its only data for weekdays.</p> <p>The thing I want to do is: Plot the figure and set an x tick on every Monday of the week.</p> ...
<p>If you draw a line plot with one axis of <em>datetime</em> type, the most natural solution is to use <em>plot_date</em>.</p> <p>I created an example DataFrame like below:</p> <pre><code> Amount Date 2020-08-24 210 2020-08-25 220 2020-08-26 240 2020-08-27 215 2020-08-28 24...
python-3.x|pandas|datetime|matplotlib
1
2,307
63,787,848
Find row value based on one column in another column and do calculation
<p>I have a dataframe:</p> <pre class="lang-python prettyprint-override"><code>import pandas as pd data = pd.DataFrame({'start':['2020-08-01','2020-08-02','2020-08-03','2020-08-04','2020-08-05','2020-08-06','2020-08-07','2020-08-08'], 'end':['2020-08-03','2020-08-03','2020-08-06','2020-08-06','2020...
<p>Use if all <code>start</code> values are unique subtracting by mapped values:</p> <pre><code>data['result'] = data['score'].sub(data['end'].map(data.set_index('start')['score'])) print (data) start end score result 0 2020-08-01 2020-08-03 74 36 1 2020-08-02 2020-08-03 81 43 2 ...
python|pandas|dataframe
3
2,308
64,015,999
plt.plot draws multiple curves instad of single curve
<p>here is the link to the dataset I used: <a href="https://drive.google.com/file/d/1p7OsIq9koVC9gpreNjBiHia4MKh10fP4/view?usp=sharing" rel="nofollow noreferrer">Dataset</a></p> <pre><code>import numpy as np import matplotlib.pyplot as plt import pandas as pd #Lets begin with polynomial regression df = pd.read_excel('...
<p>Let's use pandas plot it is much easier:</p> <pre><code>X=pd.DataFrame(df['hacim']) Y=pd.DataFrame(df['delay']) from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures poly_reg = PolynomialFeatures(degree = 4) X_poly = poly_reg.fit_transform(X) lin_reg_2 = LinearRegres...
python|pandas|numpy|matplotlib
1
2,309
63,986,764
How to use Fiscal Year values in Python?
<p>I am working with some historical data on fiscal transfers in Canada. The downloaded data is in the format of fiscal year i.e.</p> <pre><code>Year Quebec Alberta 1980-1981 2000 4000 1981-1982 3000 6000 </code></pre> <p>I am using the pandas library. However, when I try to make any visualizations using...
<p>You can use 2years <a href="https://pandas.pydata.org/docs/user_guide/timeseries.html#time-span-representation" rel="nofollow noreferrer">periods</a>, but if print DataFrame columns cannot see end year:</p> <pre><code>print (df) Year Quebec Alberta 0 1980 2000 4000 1 1981 3000 6000 df['Year...
python|pandas|dataframe|data-visualization
0
2,310
63,895,190
How to update selected datetime64 values in a pandas dataframe?
<p>I am trying to update selected datetime64 values in a pandas data frame using the loc method to select rows satisfying a condition. However, instead of assigning the new date-time value it results in NaT.</p> <p>Here is a simplification of my code that shows the problem:</p> <pre><code>import pandas as pd import num...
<p>You should drop <code>[]</code> around the column name:</p> <pre><code>df.loc[(df['select'] == 1), 'date_time'] = df.loc[(df['select'] == 1), 'new_date'] </code></pre> <p>You can also drop the second boolean index:</p> <pre><code>df.loc[(df['select'] == 1), 'date_time'] = df['new_date'] </code></pre> <p>Also, <code>...
python|pandas|numpy|dataframe
1
2,311
46,812,804
How to do a second interpolation in python
<p>I did my first interpolation with <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.polyfit.html" rel="nofollow noreferrer">numpy.polyfit()</a> and <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.polyval.html#numpy.polyval" rel="nofollow noreferrer">numpy.polyval()...
<p>First, generate the polynomial fit coefficients using the old time (x-axis) values, and interpolated longitude (y-axis) values. </p> <pre><code>import numpy as np import matplotlib.pyplot as plt poly_deg = 3 #degree of the polynomial fit polynomial_fit_coeff = np.polyfit(original_times, interp_lon, poly_deg) </c...
python|arrays|python-2.7|numpy|interpolation
0
2,312
63,136,885
Constructing a highly customized neural network in keras (weight sharing, custom connectivity)
<p>I'm trying to create a NN model for a specific problem in physical sciences, and my motivation is to reduce the number of weights and share weights based on physical insights. The neural net looks something like:</p> <p><a href="https://i.stack.imgur.com/ZIzJ6.jpg" rel="nofollow noreferrer"><img src="https://i.stack...
<p>This code will solve your issue (under the assumption that you wanted to add up all the inputs to the output at the end) BTW, if you don't have any activation, the operation you described is linear and can be easily simplified.</p> <pre><code>import tensorflow.keras as keras import tensorflow.keras.layers as layers ...
tensorflow|keras|neural-network|physics|biological-neural-network
1
2,313
63,039,838
How to make intervals of data after 6 rows using pandas
<p>Hi I have a scenario where I have to maintain a number after every 6 six row.</p> <p>For example here is my dataframe</p> <pre><code>client_id patient_id Total Clinic Clinic Number 172 6021 1 Clinic 1 172 6021 1 Clinic 1 172 6021 1...
<p>Create a column of ones; compute cumulative sum and subtract 1 (to start from zero); and compute floordiv (i.e., integer division)</p> <pre><code> df['Index'] = 1 df['Index'] = df['Index'].cumsum() - 1 df['Index'] = df['Index'].floordiv(6) </code></pre>
python|pandas|data-cleaning|sklearn-pandas
1
2,314
63,303,505
How do I remove rows in a list containing numpy arrays based on a condition?
<p>I have the following numpy array <code>arr_split</code>:</p> <pre><code>import numpy as np arr1 = np.array([[1.,2,3], [4,5,6], [7,8,9]]) arr_split = np.array_split(arr1, indices_or_sections = 4, axis = 0) arr_split </code></pre> <p>Output:</p> <pre><code>[arra...
<p>you can change the <code>indices_or_sections</code> value to length of the first axis, this will prevent any empty arrays from being produced</p> <pre><code>import numpy as np arr1 = np.array([[1.,2,3], [4,5,6], [7,8,9]]) arr_split = np.array_split(arr1, indices_or_sections = arr1.shape[...
python|list|numpy|list-comprehension
3
2,315
67,782,893
Adding column to Pandas DataFrame based on dynamic indexing condition
<p>I have a dataframe with a column that randomly starts a &quot;count&quot; back at 1. My goal is to produce a new_col that divides my current column by the the last value in a count. See below for an example.</p> <p>This is my current DataFrame:</p> <pre><code> col 0 1.0 1 2.0 2 3.0 3 1.0 4 2.0 5 1.0 6...
<p>Try:</p> <pre><code>df['new_col'] = df['col'].div(df.groupby((df['col'] == 1).cumsum()).transform('last')) </code></pre> <p>Output:</p> <pre><code> col new_col 0 1.0 0.333333 1 2.0 0.666667 2 3.0 1.000000 3 1.0 0.500000 4 2.0 1.000000 5 1.0 0.200000 6 2.0 0.400000 7 3.0 0.600000 8 4.0 ...
python|pandas|dataframe
7
2,316
67,619,155
Create "denser" np.linspace with same points as original np.linspace
<p>I have a <code>base</code> array of equally spaced values <code>[0, 1, ..., 511]</code>. I need to create a <code>target</code> array over <code>[0 to 511]</code> that consists of approximately 4096 values. It must <strong>also</strong> contain all the values <code>0, 1, 2, ...</code> that are in <code>base</code>.<...
<p>To construct an equally spaced sequence <code>(0, ..., b)</code> containing all integers within that interval, where <code>b</code> is an integer, choose any integer <code>k</code> and then:</p> <pre><code>np.linspace(0, b, k * b + 1) </code></pre> <p>In your case,</p> <pre><code>np.linspace(0, 511, 8 * 511 + 1) </c...
python|arrays|numpy|linspace
0
2,317
61,463,925
how to print a table for a pandas data frame in Pyscripter?
<p>Is there a way to show a pandas data frame in Pyscripter in a table form? Sure a data frame shows up on the python interface, but i could not find an option to print it in a more graphical , eye-friendly table form... Any help would be much appreciated</p>
<p>Assuming you are using SQL to wrangle your data for you tabular analysis.</p> <p><strong>Visit</strong> <a href="https://mode.com/example-gallery/python_dataframe_styling/" rel="nofollow noreferrer">https://mode.com/example-gallery/python_dataframe_styling/</a></p> <p>It's a great place to learn dataframe styling....
python|pandas|pyscripter
0
2,318
61,371,732
Bokeh - legend outside the plot
<p>There is plenty of issues like this one, but I couldn't find one with the approach I'm looking to solve it.</p> <p>In bokeh we cannot move a legend outside the plot, we have to create one. If we try nowadays to move the legend from inside to outside the legend dissapears. In the <a href="https://docs.bokeh.org/en/l...
<p>Something like this?</p> <pre class="lang-py prettyprint-override"><code>from bokeh.io import show from bokeh.models import Legend from bokeh.plotting import figure p = figure(tools=[]) p.circle(x=[0, 1], y=[0, 1], size=10, legend_label='Circle') legend = p.legend[0] p.center = [item for item in p.center if not i...
python|pandas|bokeh
1
2,319
61,278,924
Pandas plot countries total and newcol
<p>I am having an issue plotting multiple columns into a histogram plot</p> <pre><code>x1 = list(df[df['newcol'] == 0]['Country/Region']) x2 = list(df[df['newcol'] == 1]['Country/Region']) colors = ['r', 'c'] names = ['warm','cool'] plt.hist([x1, x2], bins = 1, normed=True, color = colors, label=names) </c...
<p>I think you might need a bar plot instead of histogram</p> <pre><code>x1 = list(df[df['newcol'] == 0]['Country/Region']) x2 = list(df[df['newcol'] == 1]['Country/Region']) y1 = list(df[df['newcol'] == 0]['Total']) y2 = list(df[df['newcol'] == 1]['Total']) plt.bar(x1, y1, color='g') plt.bar(x2, y2, color='b') </cod...
python|pandas
0
2,320
61,391,919
Loading image data from pandas to pytorch
<p>I am completely new to pytorch and have previously worked on keras and fastai. Currently trying an image regression task and the challenge is I have to load the data from pandas dataframe. Data frame structure:</p> <pre><code>ID Path Score fig1 /folder/fig1.jpg 2 fig2 /folder/fig2.jpg 3 ..... </code></pre> ...
<h2>Datasets</h2> <p>You have to use <code>torch.utils.data.Dataset</code> structure to define it. Here is how you can do it in plain <code>pytorch</code> (I'm using <code>pillow</code> to load the images and <code>torchvision</code> to transform them to <code>torch.Tensor</code> objects):</p> <pre><code>import torch...
python|pandas|deep-learning|pytorch
9
2,321
68,841,671
How to add a new column based on different conditions on other columns pandas
<p>This is my dataframe:</p> <pre><code>Date Month 04/21/2019 April 07/03/2019 July 01/05/2018 January 09/23/2019 September </code></pre> <p>I want to add a column called fiscal year. A new fiscal year starts on 1st of July every year and ends on the last day of June. So for example if the year is 2019 and m...
<p>try via <code>pd.PeriodIndex()</code>+<code>pd.to_datetime()</code>:</p> <pre><code>df['Date']=pd.to_datetime(df['Date']) df['FY']=pd.PeriodIndex(df['Date'],freq='A-JUN').strftime(&quot;FY%y&quot;) </code></pre> <p>output:</p> <pre><code> Date Month FY 0 2019-04-21 April FY19 1 2019-07-03 ...
python|pandas
-1
2,322
53,305,040
How to make a column with lists from columns of list elements in a pandas dataframe?
<p>I have a pandas dataframe like </p> <pre><code> test = pd.DataFrame([[['P','N'], ['Z', 'P']],[['N','N'], ['Z', 'P']]], columns=['c1', 'c2']) </code></pre> <p>I want to add another column <code>c3</code> to test whose elements are</p> <pre><code>['PZ', 'NP'] ['NZ', 'NP'] </code></pre> <p>How can I do this?</...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><code>assign</code></a>:</p> <pre><code>df = test.assign(c3 = [[x[0]+y[0], x[1]+y[1]] for x,y in test.values.tolist()]) </code></pre> <p>Or:</p> <pre><code>df = test.assign(c3 = list(map(lis...
python-3.x|pandas|dataframe
2
2,323
65,557,947
Learning a Categorical Variable with TensorFlow Probability
<p>I would like to use TFP to write a neural network where the output are the probabilities of a categorical variable with 3 classes, and train it using the negative log-likelihood.</p> <p>As I'm moving my first steps with TF and TFP, I started with a toy model where the input layer has only 1 unit receiving a null inp...
<p>I believe the default argument to Categorical is not the vector of probabilities, but the vector of logits (values you'd take softmax of to get probabilities). This is to help maintain precision in internal Categorical computations like log_prob. I think you can simply eliminate the softmax activation function and i...
tensorflow2.0|tensorflow-probability
1
2,324
65,566,794
How to compute the penalty for invariant risk minimization in Tensorflow?
<p>I am trying to implement the technique called &quot;Invariant risk minimization,&quot; which adds a penalty term to the loss function in training machine learning models. The new penalty term's technical definition is the <strong>squared gradient norm with respect to a constant classifier.</strong> There is an imple...
<p>In a similar fashion :</p> <pre><code>def penalty(y_true, y_pred): scale = tf.constant(1.) with tf.GradientTape() as tape: tape.watch(scale) loss = tf.losses.binary_crossentropy(y_true, y_pred*scale, from_logits=True) grad = tape.gradient(loss, [scale])[0] return tf.reduce_sum(grad**2...
python|tensorflow|machine-learning|loss-function
1
2,325
65,823,942
Append data from one pandas dataframe into other one
<p>I'm trying to append latitude and longitude data from df table:</p> <pre><code>dict = {'city':['Wien', 'Prague','Berlin','London','Rome'], 'latitude': [48.20849, 50.08804, 52.52437, 51.50853, 41.89193 ], 'longitude': [16.37208, 14.42076, 13.41053, -0.12574, 12.51133] } df = pd.DataFrame(dict...
<p>use merge.</p> <pre><code>df1 = df_pair.merge(df.set_index('city'), left_on='start_city', right_index=True, how='left') df2 = df1.merge(df.set_index('city'), left_on='end_city', right_index=True, how='left', suffixes=['_start', '_end']) # result print(df2) start_city end_city latitude_start longitude_sta...
python-3.x|pandas|dataframe
3
2,326
65,624,468
What is the proper configuration for Quadro RTX3000 to run tensorflow with GPU?
<p>My laptop System is Win10, with GPU NVIDIA Quadro RTX3000. While trying to set up the TensorFlow with GPU, it always can't recognize my GPU. What is the proper configuration for CUDA/CUDNN/Tensorflow etc.?</p>
<p>I did suffer a while before making it works. Here is my configuration:</p> <ul> <li>Win10</li> <li>RTX 3000</li> <li>Nvidia driver version 456.71</li> <li>cuda_11.0.3_451.82_win10 (can't works with 11.1 version, not sure why)</li> <li>cudnn -v8.0.4.30</li> <li>Python 3.8.7</li> <li>Tensorflow 2.5.0-dev20210106 (2....
tensorflow|gpu
0
2,327
53,415,751
Count occurences of True/False in column of dataframe
<p>Is there a way to count the number of occurrences of boolean values in a column without having to loop through the DataFrame?</p> <p>Doing something like </p> <pre><code>df[df["boolean_column"]==False]["boolean_column"].sum() </code></pre> <p>Will not work because False has a value of 0, hence a sum of zeroes wil...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="noreferrer"><code>pd.Series.value_counts()</code></a>:</p> <pre><code>&gt;&gt; df = pd.DataFrame({'boolean_column': [True, False, True, False, True]}) &gt;&gt; df['boolean_column'].value_counts() True 3 Fal...
python|pandas|boolean|counter|series
40
2,328
72,104,594
Panda Dataframe read_json for list values
<p>I have a file with record json strings like:</p> <pre><code>{&quot;foo&quot;: [-0.0482006893, 0.0416476727, -0.0495583452]} {&quot;foo&quot;: [0.0621534586, 0.0509529933, 0.122285351]} {&quot;foo&quot;: [0.0169468746, 0.00475309044, 0.0085169]} </code></pre> <p>When I call <a href="https://pandas.pydata.org/docs/ref...
<p>The easiest way is to create your DataFrame using <code>.from_dict()</code>.</p> <p>See a minimal example with one of your dicts.</p> <pre><code>d = {&quot;foo&quot;: [-0.0482006893, 0.0416476727, -0.0495583452]} df = pd.DataFrame().from_dict(d) &gt;&gt;&gt; df foo 0 -0.048201 1 0.041648 2 -0.049558 &gt;&gt...
pandas|dataframe
0
2,329
72,086,983
Repeated values in pyspark
<p>I have a dataframe in pyspark where i have three columns</p> <pre><code>df1 = spark.createDataFrame([ ('a', 3, 4.2), ('a', 7, 4.2), ('b', 7, 2.6), ('c', 7, 7.21), ('c', 11, 7.21), ('c', 18, 7.21), ('d', 15, 9.0), ], ['model', 'number', 'price']) df1.show() +-----+------+-----+ |model|numb...
<p>You can do so with a window function. We partition by price, take a count and filter <code>count &gt; 1</code>.</p> <pre><code>from pyspark.sql import Window from pyspark.sql import functions as f w = Window().partitionBy('price') df1.withColumn('_c', f.count('price').over(w)).filter('_c &gt; 1').drop('_c').show()...
pyspark|apache-spark-sql|pyspark-pandas
0
2,330
72,104,902
Loop over 2 lists to create seperate dfs from multiple excel worksheets
<p>I've read in the below excel workbook which has 40 sheets. The below reads in all the worksheets:</p> <pre><code>df = pd.read_excel(file_path, sheet_name = None) </code></pre> <p>All the worksheets have identical columns, but the relevant columns start at different rows in each worksheet, so I'm writing the below to...
<p>It should be possible using next()</p> <pre><code>new_dfs = list() indexes = iter([20, 12, 20]) for sheet in df: new_df = df[sheet] new_df.colunms = new_df.iloc[next(indexes)] new_dfs.append(new_df) </code></pre> <p>I did not run this code, but the idea is worth trying</p>
python|pandas|function|loops|xlsxwriter
0
2,331
56,646,482
How to assign values to a column using multiindex filter?
<p>I can't update the values on a column when I filter using a multiindex.</p> <pre><code>features_complete_new_index['ev_2'] = 1 features_complete_new_index.loc[true_positives_indexes,:].ev_2 = True features_complete_new_index.loc[false_negatives_indexes,:].ev2 = False features_complete_new_index.ev_2.value_counts...
<p>I suspect Pandas is giving you a <strong>SettingwithCopyWarning</strong> warning. There is a <a href="https://www.dataquest.io/blog/settingwithcopywarning/" rel="nofollow noreferrer">very good article</a> that explains the risk of doing "chained assignment".</p> <p>The core problem is that when you write :</p> <p>...
python|pandas|multi-index
0
2,332
56,659,181
GoogLeNet Inception v4 is different from the paper?
<p>paper: <a href="https://arxiv.org/pdf/1602.07261.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1602.07261.pdf</a></p> <p>code: <a href="https://github.com/tensorflow/models/blob/master/research/slim/nets/inception_v4.py" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/research/slim...
<p>This one is a minor mismatch:</p> <pre><code> branch_2 = slim.conv2d(branch_2, 224, [7, 1], scope='Conv2d_0d_7x1') </code></pre> <p>instead of using sequence of convolutions {[1, 7], [7, 1], [1, 7], [7, 1]} it has {[7, 1], [1, 7], [7, 1], [1, 7]}. I would be surprised if it had an effect on the accuracy, but migh...
tensorflow
0
2,333
56,688,744
unable to import Metric from tensorflow.keras.metrics
<p>I want to write a custom metric evaluator for which I am following <a href="https://www.tensorflow.org/beta/guide/keras/training_and_evaluation#specifying_a_loss_metrics_and_an_optimizer" rel="nofollow noreferrer">this link</a>. my dummy code is </p> <pre><code>import tensorflow as tf from tensorflow import ker...
<p>It seems like this was probably left out of an <code>__init__.py</code> and they fixed that in 1.14 I guess. I was able to import it this way:</p> <pre><code>from tensorflow.python.keras.metrics import Metric </code></pre> <p>It is defined in file:</p> <pre><code>tensorflow/python/keras/metrics.py </code></pre>
python|tensorflow|keras
7
2,334
56,698,566
How to reuse existing variable in TensorFlow when dtypes differ?
<p>Minimal code example:</p> <pre><code>with tf.variable_scope("initializer_test"): s = tf.get_variable("scalar", initializer=tf.constant(2)) with tf.variable_scope("initializer_test", reuse=True): s = tf.get_variable("scalar") # ValueError: Trying to share variable initializer_test/scalar, but specified dty...
<p>Adds <code>AUTO_REUSE</code> as a reuse mode to variable scopes. This mode modifies the behavior of <code>get_variable()</code> to create requested variables if they do not exist or return them if they do exist. </p> <p>It is now possible to write the following code:</p> <pre><code>def call_f(): with tf.variab...
python|tensorflow
0
2,335
56,665,409
What happens when you transform the test set using MinMaxScaler
<p>i am currently in the process of pre-processing my data and I understand that i have to use the same scaling parameters I have used on my training set, on my test set. However, when i applied the <code>transform</code> method from <code>sklearn</code> library, i noticed something weird.</p> <p>I first used <code>pr...
<p>For a given feature <code>x</code>, your <code>minmax</code> scaling to <code>(0,1)</code> will effectively map:</p> <p><code>x to (x- min_train_x)/(max_train_x - min_train_x)</code></p> <p>where <code>min_train_x</code> and <code>max_train_x</code> are the minimum and maximum value of <code>x</code> in the <stron...
python|scikit-learn|sklearn-pandas
2
2,336
56,764,048
How to train the original U-Net model with PyTorch?
<p>I’m trying to implement and train the <a href="https://arxiv.org/pdf/1505.04597.pdf" rel="nofollow noreferrer">original U-Net model</a>, but I’m stuck in when I’m trying to train the model using the <a href="http://brainiac2.mit.edu/isbi_challenge/" rel="nofollow noreferrer">ISBI Challenge Dataset</a>.</p> <p>Accor...
<p>From the CrossEntropyLoss docstring of PyTorch:</p> <pre><code>Shape: - Input: :math:`(N, C)` where `C = number of classes`, or :math:`(N, C, d_1, d_2, ..., d_K)` with :math:`K \geq 1` in the case of `K`-dimensional loss. - Target: :math:`(N)` where each value is :math:`0 \leq \text{targets}[i...
python|conv-neural-network|pytorch|image-segmentation
1
2,337
67,097,110
Convert elements in lists to separate rows
<p>My data frame has approximately 30 columns. Some of these columns have lists of items, for instance</p> <pre><code> Student Subject \ 0 J.M. [mathematics, history, literature] 1 M.G. [physics, mathematics, geography, history] 2 L.D. [latin, literature, mathematics] ...
<p>Assuming <code>df</code> to be:</p> <pre><code>In [2893]: df = pd.DataFrame({'Student':['J.M.', 'M.G.', 'L.D.'], 'Subject':[['mathematics', 'history', 'literature'], ['physics', 'mathematics', 'geography', 'history'], ['latin', 'literature', 'mathematics']], 'Score':[[10, 8, 8.5], [5, 4, 8, 8.5], [4, ...: 5, ...
python|pandas
5
2,338
66,918,779
Getting hr count in pandas
<p>I have a pandas dataframe like below :</p> <pre><code> | Date | +-------------------+ |2009-11-01 00:00:08| |2009-11-01 00:00:40| |2009-11-01 01:00:20| |2009-11-01 01:50:08| |2009-11-01 02:22:00| |2009-11-01 02:45:50| |2009-11-01 03:10:20| |2009-11-01 03:20:30| ...
<pre><code>df[&quot;Date&quot;] = pd.to_datetime(df[&quot;Date&quot;]) df[&quot;hour&quot;] = df.Date.dt.hour df_out = ( df.groupby(&quot;hour&quot;) .agg( { &quot;Date&quot;: lambda x: &quot;{h:02d}:00:00 - {h:02d}:59:59&quot;.format( h=x.iat[0].hour ), ...
python-3.x|pandas|dataframe
2
2,339
47,454,219
Apply set_index over groupby object in order to apply asfreq per group
<p>Im looking to apply <code>pading</code> over each group of my data frame</p> <p>notice that for a single group ('element_id') i have no problem in pading:</p> <p>first group (group1):</p> <pre><code>{'date': {88: datetime.date(2017, 10, 3), 43: datetime.date(2017, 9, 26), 159: datetime.date(2017, 11, 8)}, u'eleme...
<p>First there is problem your <code>date</code> column has <code>dtype</code> object, not datetime, so first is necessary convert it by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="noreferrer"><code>to_datetime</code></a>.</p> <p>Then is possible use <a href="http://pan...
pandas
6
2,340
68,379,553
pandas: groupby two columns and get random selection of groups such that each value in the first column will be represented by a single group
<p>It's similar to <a href="https://stackoverflow.com/questions/50004641/select-sample-random-groups-after-groupby-in-pandas">this question</a>, but with an additional level of complexity.<br /> In my case, I have a the following <em>dataframe</em>:</p> <pre><code>import pandas as pd df = pd.DataFrame({'col1': list...
<p>Another option is to sufffle your two columns with <code>sample</code> and <code>drop_duplicates</code> by col1, so that you keep only one couple per col1 value. then <code>merge</code> the result to df to select all the rows with these couples.</p> <pre><code>print(df.merge(df[['col1','col2']].sample(frac=1).drop_d...
python|pandas|pandas-groupby
1
2,341
68,108,089
pandas series to unique binary indicators
<p>Here is what I have</p> <pre><code>&gt;&gt;&gt; s = pd.Series([0,2,1,0], ['t1','t2','t3','t4']) &gt;&gt;&gt; s t1 0 t2 2 t3 1 t4 0 dtype: int64 </code></pre> <p>I want an output which looks like this with binary indicators for each value as pandas dataframe:</p> <pre><code>value t1 t2 t3 t4 0 ...
<p>Looks like you need <code>get_dummies</code>:</p> <pre><code>pd.get_dummies(s) # 0 1 2 #t1 1 0 0 #t2 0 0 1 #t3 0 1 0 #t4 1 0 0 </code></pre> <p>You can further transpose it if you need it in the other way:</p> <pre><code>pd.get_dummies(s).T # t1 t2 t3 t4 #0 1 0 0 1 #1 0 0 1 ...
pandas|binary|indicator
2
2,342
68,083,588
Softmax Output Layer. Which dimension?
<p>I am having a question regarding Neuronal Nets used for image segmentation. I am using a 3D Implementation of Deeplab that can be found <a href="https://github.com/ChoiDM/pytorch-deeplabv3plus-3D" rel="nofollow noreferrer">here</a></p> <p>I am using <code>softmax</code>, so the output layer is the following:</p> <pr...
<p>Indeed it should be 1 as you want this axis to be summed to 1.<br /> Be careful if you need to train your network with a crossentropyloss as this latter already include a softmax.</p>
python|neural-network|pytorch|image-segmentation|deeplab
0
2,343
59,388,739
How to extract the column with only False condition without apply
<pre><code>df[['uid','verified','is_duplicate']].head(2) </code></pre> <p>How to get only where <code>is_duplicate=False</code></p> <pre><code> uid verified is_duplicate 0 2355954 True True 1 2626002 True False </code></pre>
<p>Since the values are already booleans, you can just negate the condition:</p> <pre><code>df[~df.is_duplicate] </code></pre> <p>Which gives:</p> <pre><code> uid verified is_duplicate 1 2626002 True False </code></pre>
pandas
1
2,344
51,027,435
How to detect and filter peaks over time series data?
<p>I have a pandas dataframe of user logins like this:</p> <pre><code> id datetime_login 646 2017-03-15 15:30:25 611 2017-04-14 11:38:30 611 2017-05-15 08:49:01 651 2017-03-15 15:30:25 611 2017-03-15 15:30:25 652 2017-03-08 14:03:56 652 2017-03-08 14:03:56 652 2017-03-15...
<p>Where <code>df.datetime_login.value_counts().sort_index().plot(figsize=(25,10), colormap='jet',fontsize=20)</code> plots:</p> <p><a href="https://i.stack.imgur.com/L190d.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L190d.png" alt="enter image description here"></a></p> <p>Let's try the follo...
python|python-3.x|pandas|time-series
1
2,345
50,868,100
Finding and ranking intervals of data
<p>Every time I ride my bike a gather second by second data on a number of metrics. For simplicity, lets pretend that I have a csv file that looks something like:</p> <pre><code>secs, watts, 1,150 2,151 3,149 4,135 . . . 7000,160 </code></pre> <p>So, every second of my ride has an associated power value, in watts.</p...
<p>If you put your data in a numpy array, say <code>watts</code>, you can compute the mean power using convolve:</p> <pre><code>mean_power = np.convolve(watts, np.ones(interval_length)/interval_length, mode='valid') </code></pre> <p>As you can see in <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy...
python|performance|pandas|numpy
1
2,346
51,070,933
Combine rows based on index or column
<p>I have three dataframes: df1, df2, df3. I am trying to add a list of ART_UNIT do df1.</p> <p>df1 is 260846 rows x 4 columns:</p> <pre><code>Index SYMBOL level not-allocatable additional-only 0 A 2 True False 1 A01 4 True False 2 ...
<p>Since <code>df2</code> and <code>df3</code> have the same format concatentate them first.</p> <pre><code>import pandas as pd df = pd.concat([df2, df3]) </code></pre> <p>Then to get the lists of all art units, <code>groupby</code> and apply list.</p> <pre><code>df = df.groupby('CLASSIFICATION_SYMBOL_CD').ART_UNIT....
python-3.x|pandas|pandas-groupby
1
2,347
51,038,503
TensorFlow: List index out of range with conv2d_transpose
<p>I would want to use a convolution transpose to obtain a tensor of 2700 values with the following input:</p> <pre><code>input = tf.placeholder(tf.float32, shape=(batch_size, 1 , 1 ,1)) </code></pre> <p>To do that, I used the <a href="https://www.tensorflow.org/api_docs/python/tf/nn/conv2d_transpose" rel="nofollow n...
<p>From the documentation of <a href="https://www.tensorflow.org/api_docs/python/tf/nn/conv2d_transpose" rel="nofollow noreferrer">tf.nn.conv2d_transpose</a> you can see that you need to <strong>define placeholders</strong> for <code>filter</code> and <code>output_shape</code> similar to how you did for <code>input</co...
python|tensorflow|neural-network
1
2,348
71,048,521
How to freeze parts of T5 transformer model
<p>I know that T5 has K, Q and V vectors in each layer. It also has a feedforward network. I would like to freeze K, Q and V vectors and only train the feedforward layers on each layer of T5. I use Pytorch library. The model could be a wrapper for huggingface T5 model or a modified version of it. I know how to freeze a...
<p>I've adapted a solution based on <a href="https://discuss.huggingface.co/t/how-to-freeze-some-layers-of-bertmodel/917" rel="nofollow noreferrer">this discussion</a> from the Huggingface forums. Basically, you have to specify the names of the modules/pytorch layers that you want to freeze.</p> <p>In your particular c...
huggingface-transformers|t5-transformer
2
2,349
51,846,141
Tensorboard/tensorflow with s3 logdir - curl returned error code 6
<p>Been trying with numerous settings/env-vars/tf-versions but won't work..</p> <p>On my local machine this <strong>works</strong>: <code>AWS_ACCESS_KEY_ID=XXX AWS_SECRET_ACCESS_KEY=XXX AWS_REGION=eu-west-1 tensorboard --logdir="s3://my-bucket/tflogs/"</code></p> <p>On a AWS instance this will throw:</p> <pre><code>...
<p>Solved it like this:</p> <pre><code>export AWS_ACCESS_KEY_ID=&lt;access key id&gt; export AWS_SECRET_ACCESS_KEY=&lt;secret access key&gt; export AWS_REGION=us-west-2 export S3_REGION=us-west-2 export S3_ENDPOINT=s3.us-west-2.amazonaws.com export S3_USE_HTTPS=1 export S3_VERIFY_SSL=0 tensorboard --logdir=s3://&lt;p...
tensorflow|amazon-s3|tensorboard
3
2,350
36,166,103
Remove columns that have NA values for rows - Python
<p>Suppose I have a dataframe as follows,</p> <pre><code>import pandas as pd columns=['A','B','C','D', 'E', 'F'] index=['1','2','3','4','5','6'] df = pd.DataFrame(columns=columns,index=index) df['D']['1'] = 1 df['E'] = 1 df['F']['1'] = 1 df['A']['2'] = 1 df['B']['3'] = 1 df['C']['4'] = 1 df['A']['5'] = 1 df['B']['5']...
<p>Rather than delete rows, just select the others that don't have A, B, C equal to NaN at the same time.</p> <pre><code>mask = df[["A", "B", "C"]].isnull().all(axis=1) df = df[~mask] </code></pre>
python|python-2.7|numpy|data-cleaning
0
2,351
36,119,783
How to efficiently compute orientation of 3D normals in large pointclouds
<p>I'm working (more like learn by doing) on a Python's library for managing pointclouds in Python.</p> <p>I've writed a function to compute the orientation of every Normal in a pointcloud stored as a numpy structured array, but I'm not happy enought with the final function (thought it works and pretty fast enought) ...
<p>Well, I'm ashamed of myself. xD</p> <p>Those numpy built-in function were exactly what I was looking for.</p> <p>Thanks @Dan.</p> <p>Here is the new function:</p> <pre><code> def add_orientation(self, degrees=True): """ Adds orientation (with respect to y-axis) values to PyntCloud.vertex This f...
python|numpy|3d|point-clouds
1
2,352
35,799,709
pandas dataframe find nth non isnull row
<p>I want to know how many points in a pandas dataframe where index is a series of dates that I need to have in order to end up with X points after doing a dropna(). I want the latest points. Example:</p> <pre><code>window = 504 s1 = pd.DataFrame(stuff) len(s1.index) --&gt; 600 dropped_series = s1.dropna() len(dropped...
<p>Here is my solution, but I'm sure there's a more elegant way to do it:</p> <pre><code> all_series_df = pd.concat([harmonized_series_set[i] for i in series_indices], axis=1) all_series_df['is_valid'] = all_series_df.apply(lambda x: 0 if np.any(np.isnan(x)) else 1, raw=True, axis=1) valid_point_count = all...
python|numpy|pandas
0
2,353
35,916,378
Create empty csv file with pandas
<p>I am interacting through a number of csv files and want to append the mean temperatures to a blank csv file. How do you create an empty csv file with pandas?</p> <pre><code>for EachMonth in MonthsInAnalysis: TheCurrentMonth = pd.read_csv('MonthlyDataSplit/Day/Day%s.csv' % EachMonth) MeanDailyTemperaturesFor...
<p>Just open the file in write mode to create it.</p> <pre><code>with open('my_csv.csv', 'w'): pass </code></pre> <p>Anyway I do not think you should be opening and closing the file so many times. You'd better open the file once, write several times.</p> <pre><code>with open('my_csv.csv', 'w') as f: for Each...
python|csv|pandas|is-empty
4
2,354
37,885,014
tensorflow evaluate on test set with queques
<p>TensorFlow's customer/producer prefetching mechanism is awesome for training.</p> <p>However, I am not able to find a way to use it for evaluation on test data. We want to go through the test data only and exactly once. But test data is always not dividable by batch size. How should I deal with the remainder?</p> ...
<p>See <code>eval_in_batches</code> from <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/image/mnist/convolutional.py#L265" rel="nofollow">convolutional.py</a> official example. It does most <code>session.run</code> calls on regular batch size, while last <code>session.run</code> is done...
tensorflow|deep-learning
0
2,355
37,897,527
get python pandas to_dict with orient='records' but without float cast
<p>I have a dataframe with one col int one col floats:</p> <pre><code>df # a b # 0 3 42.00 # 1 2 3.14 df.dtypes # a int64 # b float64 # dtype: object </code></pre> <p>I want a list of dicts like the one provide by <code>df.to_dict(orient='records')</code></p> <pre><code>df.to_dict(orient='recor...
<p>Currently (as of Pandas version 0.18), <code>df.to_dict('records')</code> accesses the NumPy array <code>df.values</code>. This property upcasts the dtype of the <code>int</code> column to <code>float</code> so that the array can have a single common dtype. After this point there is no hope of returning the desired ...
python|pandas
11
2,356
64,596,935
Tensorflow js: Your application contains ops that are small enough to be executed on the CPU backend, however the CPU backend cannot be found
<p>I use handpose tensorflow model for hand detection in browser using tfjs with webgl backend. However, i see warning in console <code>Your application contains ops that are small enough to be executed on the CPU backend, however the CPU backend cannot be found. Consider importing the CPU backend (@tensorflow/tfjs-bac...
<p>By default, Tensorflow JS does some of the inference (forward propagation as opposed to backprop) on the CPU, since some CPUs have vector arithmetic units that speed up matrix multiplication.</p> <p>You can check the <code>tf.ENV.flags</code> variable to see the various state variables that tfjs sets by default. One...
javascript|tensorflow|tensorflow.js
1
2,357
64,610,841
BERT-based NER model giving inconsistent prediction when deserialized
<p>I am trying to train an NER model using the HuggingFace transformers library on Colab cloud GPUs, pickle it and load the model on my own CPU to make predictions.</p> <p><strong>Code</strong></p> <p>The model is the following:</p> <pre><code>from transformers import BertForTokenClassification model = BertForTokenCla...
<p>I fixed it, there were two problems:</p> <ol> <li><p>The index-label mapping for tokens was wrong, for some reason the <code>list()</code> function worked differently on Colab GPU than my CPU (??)</p> </li> <li><p>The snippet used to save the model was not correct, for models based on the huggingface-transformers li...
python|pytorch|bert-language-model|huggingface-transformers
3
2,358
64,428,886
Matplotlib - Skipping xticks while maintaining correct x value
<p>I'm trying to plot two separate things from two pandas dataframes but the x-axis is giving some issues. When using matplotlib.ticker to skip x-ticks, the date doesn't get skipped. The result is that the x-axis values doesn't match up with what is plotted.</p> <p>For example, when the x-ticks are set to a base of 2, ...
<p>First off, I suggest you set the date as the index of your dataframe. This lets pandas automatically format the date labels nicely when you create line plots and it lets you conveniently create a custom format with the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html...
python|pandas|matplotlib
1
2,359
47,897,790
Python How to fill a customized value (such as "#NA####') with bfill method?
<p>I have a data frame containing "#NA####". I want to back-fill this value with group mean.</p> <p>I know I can first replace "#NA####" with np.NAN, then use pd.fillna, but are there any more convenient ways?</p>
<p><strong>Setup</strong></p> <pre><code>df Group Value 0 1 10 1 1 #NA### 2 3 5 3 2 10 4 2 #NA### 5 3 #NA### 6 1 40 7 2 #NA### 8 3 100 9 1 20 </code></pre> <p>Call <code>pd.to_numeric</code>, to coerce those strings to NaNs.</p> ...
python|pandas|missing-data
0
2,360
47,985,005
Finetuning DNN with continuous outputs in the last layer
<p>Greatly appreciate it if someone could help me out here:</p> <p>I'm trying to do some finetuning on a regression task --- my inputs are <code>200X200</code> RGB images and my prediction output/label is a set of real values (let's say, within <code>[0,10]</code>, though scaling is not a big deal here...?) --- on top...
<p>Your output shape for the lambda layer is wrong. Define your functions like this:</p> <pre><code>from keras import backend as K def euclidean_distance(vects): x, y = vects return K.sqrt(K.maximum(K.sum(K.square(x - y), axis=1, keepdims=True), K.epsilon())) def eucl_dist_output_shape(shapes): shape1, ...
tensorflow|computer-vision|deep-learning|keras|conv-neural-network
2
2,361
58,709,538
Rounding hours in data frame using Python -Pandas
<p>I have data frame that I have created in python that contains data about plants that were measured one time every one hour. The problem is that the original intention was to measure them at the same hour every day- 10:00, 11:00,12:00... but in real life the plants were measured with a littlle different in time so no...
<pre><code># here is the piece of your dataframe: 6/17/2019 6/18/2019 plant Hour D10A 10:02 NaN NaN 10:09 NaN 0.33 10:14 NaN NaN 10:17 0.777 NaN 10:19 NaN NaN col = df.columns df = df.reset_index() df['hr'] = pd.to_datetime(df['Hou...
python|pandas|pandas-groupby
0
2,362
70,261,404
Iterate over rows and subtract values in pandas df
<p>I have the following table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">ID</th> <th style="text-align: center;">Qty_1</th> <th style="text-align: center;">Qty_2</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">A</td> <td style="text-align: cent...
<p>First compute the difference between 'Qty_1' and 'Qty_2' row by row, then group by 'ID' and compute cumulative sum:</p> <pre><code>df['Qty_2'] = df.assign(Qty_2=df['Qty_2'].sub(df['Qty_1'])) \ .groupby('ID')['Qty_2'].cumsum() print(df) # Output: ID Qty_1 Qty_2 0 A 1 9 1 A 2 ...
pandas|loops
1
2,363
56,268,769
Loading .npz with Python 3.5 always crashes
<p>In this simple <a href="https://homes.cs.washington.edu/~thickstn/intro.html" rel="nofollow noreferrer">tutorial</a> written in Python 2.7, they have a line loading the numpy array.</p> <pre><code>train_data = np.load(open('../musicnet.npz','rb')) </code></pre> <p>Then, they get the data by calling different keys<...
<p>You first said things crashed, now you say it freezes when trying to access a specific array. <code>numpy</code> has the same syntax in 3.5 compared to 2.7. You shouldn't have to rewrite anything.</p> <p><code>np.load</code> does have a couple of parameters that deal with differences between Py2 and Py3. But I'...
python-3.x|python-2.7|numpy
1
2,364
56,384,938
Pandas.Series.dtype.kind is None for pd.interval
<p>Test code:</p> <pre class="lang-py prettyprint-override"><code>s = pd.Series(pd.array([pd.Interval(0,1.2), pd.Interval(5,123)])) s.dtype s.dtype.kind is None &gt;&gt;&gt; interval[float64] &gt;&gt;&gt; True </code></pre> <p>Is it some bug or made intentionally? If latter - for what reason?</p>
<p>The reason this is appearing as <code>None</code> is simply because the implementation of <code>IntervalDtype</code> <a href="https://github.com/pandas-dev/pandas/blob/7f318658b92155678b31780722277d1f8c8df569/pandas/core/dtypes/dtypes.py#L910" rel="nofollow noreferrer">explicitly sets <code>kind = None</code></a>. ...
python|pandas|intervals|series
1
2,365
55,816,447
cumulative return of savings plan with deposits in python pandas
<p>I am trying to calculate a monthly savings plan using financial time series with python pandas. </p> <p>I need to calculate the cumulative return given the percent changes in the time series BUT also take into account monthly deposits.</p> <p>The standard way to calculate the cumulative return from a dataframe is...
<p>Difficult to answer without some more of the inputs and outputs. But have you tried:</p> <pre><code>df['cum_ret'].sum() </code></pre>
python|pandas|time-series|finance|cumsum
0
2,366
55,856,340
How does Python convert date value from excel
<p>I am reading a csv file with a CDATE column. The structure of the column is:</p> <pre><code>|CDATE | |08/28/2018| |08/28/2018| |08/29/2018| |08/30/2018| |09/02/2018| |09/04/2018| ... |04/10/2019| </code></pre> <p>As you can see there is duplicate date as well as missing dates in this column, and I would like t...
<p>Building on my comment above. Change the last line before your loop to this:</p> <pre><code>df_date = df['CDATE'].apply(pd.to_datetime).unique() </code></pre>
python|pandas|numpy
0
2,367
64,663,456
Generate unique key from multiple dataframes based on name
<p>I have two data frames. As you can see, the function merges it correctly, but it is wrong. Because the carid must be unique and must not be assigned twice. How can I solve this problem? It can appear several times in a data frame, but it must remain unique over two data records. So <code>Carid = 1 = Mercedes-benz</c...
<h2>Method 1 Pandas Approach</h2> <p>First method if you don't mind changing your keys to floats is to increment using <code>cumcount</code></p> <pre><code>df3 = pd.concat([df,df2]) s = df3.groupby('Carname',sort=False)['Carid'].first().to_frame() s['Carid'] = s['Carid'] + s.groupby('Carid').cumcount() / 10 new_ids ...
python|pandas|dataframe
1
2,368
39,683,153
Is there a good way to find the rank of a matrix in a field of characteristic p>0?
<p>I need an efficient algorithm or a known way to determine <a href="https://en.wikipedia.org/wiki/Rank_(linear_algebra)" rel="nofollow">the mathematical rank</a> of a matrix A with coefficients in a field of positive characteristic. </p> <p>For example, in the finite field of 5 elements I have the following matrix:<...
<p>Numpy doesn't have built-in support for finite fields. The matrix <code>A</code> in your code is treated as a matrix of real numbers, and hence has rank 2. </p> <p>If you really need to support finite fields with Numpy, you'll have to define your own data type along with the arithmetic operations yourself, as shown...
python|numpy|matrix
2
2,369
39,755,742
pandas histogram with by: possible to make axes uniform?
<p>I am using the option to generate a separate histogram of a value for each group in a data frame like so (example code from documentation)</p> <pre><code>data = pd.Series(np.random.randn(1000)) data.hist(by=np.random.randint(0, 4, 1000), figsize=(6, 4)) </code></pre> <p>This is great, but what I am not seeing is a...
<p>you can pass <code>kwds</code> to hist and it will pass them along to appropriate sub processes. The relevant ones here are <code>sharex</code> and <code>sharey</code></p> <pre><code>data = pd.Series(np.random.randn(1000)) data.hist(by=np.random.randint(0, 4, 1000), figsize=(6, 4), sharex=True, sharey=Tr...
python|pandas
2
2,370
39,785,661
ValueError: Filter must not be larger than the input
<p>I am pretty new to machine learning so I am playing around with examples and such. The image size specified in the code is (28,28) But for some reason I keep getting the same ValueError I cant figure out why this is happening.</p> <p>Here's the code:</p> <pre><code>import pandas as pd import numpy as np np.random....
<p>So the problem is with the convolution sizes used. Convolution operations usually <strong>reduce</strong> dimension of the image. Similarly - each pooling operation reduces the size. You have very small images yet applied model architecture which has been designed for a bigger ones, thus at some point, after one of ...
python|pandas|machine-learning|keras
1
2,371
44,150,472
Tensorflow neural network has high error even in really easy dataset
<p>I'm trying to implement a 1 hidden layer NN for a regression problem. The loss function improves for a few iterations than it gets stuck on a really high error even for a very easy data. Could someone help me find the bug? Here is my code:</p> <pre><code>import tensorflow as tf import scipy.io as sio import numpy a...
<p>Figured it out, the problem was with the data shuffling. The input and response were shuffled differently (two times random shuffle for each epoch) and thus the input data in each epoch did not correspond to the response data. </p>
tensorflow|neural-network
0
2,372
69,394,576
ImportError: cannot import name 'resnet' from 'tensorflow.python.keras.applications'
<p>I've been trying to implement <a href="https://colab.research.google.com/drive/11ko0DBnI1QLxVoJQR8gt9b4JDcvbCrtU#scrollTo=PhAuO2-1ZBnv" rel="nofollow noreferrer">this colab code</a> but encountered this error in training part of the code.</p> <p>(python version <strong>Python 3.7.12</strong> and tensorflow version <...
<p>You can check here the <a href="https://github.com/tensorflow/tensorflow/blob/r1.14/tensorflow/python/keras/applications/resnet50.py" rel="nofollow noreferrer">Tensorflow Library</a>.</p> <p><strong>Tensorflow 1.14</strong> does not have <code>resnet</code>. Right import is:</p> <pre><code>from tensorflow.keras.appl...
python|python-3.x|tensorflow|image-processing|object-detection
0
2,373
69,619,523
How to return the correlation value from pandas dataframe
<p>I am working on a method for calculating the correlation between to columns of data from a dataset. The dataset is constructed of 4 columns A1, A2, A3, and Class. My goal is remove A3 if the correlation between A1 &amp; A3 greater than 0.6 or if the correlation between A1 &amp; A3 is less than 0.6.</p> <p>A sample o...
<p>Here is my example:</p> <pre><code>cor = df.corr() if cor['A3'] &gt; 0.6: train.drop(columns = 'A3', inplace = True) else: pass </code></pre>
python|pandas
1
2,374
69,503,993
How to read in a semicolon delimited file in Pandas and normalize
<p>I am trying to read in a wine quality dataset and normalize the data before I move on. I've read in the csv as semicolon delimited, but when I try to drop the target variable, quality, I'm getting an error that says that attribute isn't found in axis.</p> <pre><code>import pandas as pd df = pd.read_csv('gdrive/My D...
<pre><code>import pandas as pd df = pd.read_csv('gdrive/My Drive/whitewine.csv', delimiter=&quot;\s&quot;) X = df.drop(['quality'], axis=1) y = df['quality'] </code></pre>
python|pandas|csv|keyerror
0
2,375
69,403,613
How to early-stop autoregressive model with a list of stop words?
<p>I am using GPT-Neo model from <code>transformers</code> to generate text. Because the prompt I use starts with <code>'{'</code>, so I would like to stop the sentence once the paring <code>'}'</code> is generated. I found that there is a <code>StoppingCriteria</code> method in the source code but without further inst...
<p>I've been able to adapt your code to work. Additionally, make sure you're using a recent version of transformers, you may have to upgrade.</p> <pre><code>import torch from transformers import StoppingCriteria, AutoModelForCausalLM, AutoTokenizer, StoppingCriteriaList model_name = 'gpt2' tokenizer = AutoTokenizer.fro...
python|huggingface-transformers|autoregressive-models|gpt-2
2
2,376
69,555,244
Returning of the sum of units in the particular year
<p>I have a simple task however struggling with it in python.</p> <p>I have a df with &quot;Freq&quot; column (the sum at the beginning) every year some units will be removed from this, could you help me to build a for loop to return the amount for a particular year:</p> <pre><code>df = pd.DataFrame({'Delivery Year' : ...
<p>You can calculate the cumulative sum along the columns axis then subtract this sum from the <code>Freq</code> column to get available amounts for each year</p> <pre><code>s = df.iloc[:, 2:].fillna(0).cumsum(1).rsub(df['Freq'], axis=0) df.assign(**s) </code></pre> <hr /> <pre><code> Delivery Year Freq 1976 197...
python|pandas
1
2,377
69,582,900
Using Pytorch model trained on RTX2080 on RTX3060
<p>I try to run my PyTorch model (trained on a Nvidia RTX2080) on the newer Nvidia RTX3060 with CUDA support. It is possible to load the model and to execute it. If I run it on the CPU with the <code>--no_cuda</code> flag it runs smootly and gives back the correct predictions, but if I want to run it with CUDA, it only...
<p>Ok it seemed that the problem was the different floating point of the two architectures. The flag <code>torch.backends.cuda.matmul.allow_tf32 = false</code> needs to be set, to provide a stable execution of the model of a different architecture.</p>
neural-network|pytorch|gpu|nvidia
1
2,378
69,361,178
My training and validation loss suddenly increased in power of 3
<p><a href="https://i.stack.imgur.com/CCIO8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CCIO8.png" alt="Training" /></a></p> <p><strong>train function</strong></p> <pre><code>def train(model, iterator, optimizer, criterion, clip): model.train() epoch_loss = 0 for i, batch in enumerate...
<p>Default learning rate of Adam is 0.001, which, depending on task, might be too high.</p> <p>It looks like instead of converging your neural network became divergent (it left the previous ~0.2 loss minima and fell into different region).</p> <p>Lowering your learning rate at some point (after 50% or 70% percent of tr...
deep-learning|nlp|pytorch|conv-neural-network|text-classification
1
2,379
53,950,652
Dask categorize() won't work after using .loc
<p>I'm having a serious issue using dask (dask version: 1.00, pandas version: 0.23.3). I am trying to load a dask dataframe from a CSV file, filter the results into two separate dataframes, and perform operations on both. </p> <p>However, after the split the dataframes and try to set the category columns as 'known', t...
<p>The answer for your problem is basically contained in <a href="http://docs.dask.org/en/latest/dataframe-design.html" rel="nofollow noreferrer">doc</a>. I'm referring to the part code commented by <code># categorize requires computation, and results in known categoricals</code> I'll expand here because it seems to me...
python|pandas|dataframe|dask
1
2,380
54,164,085
How can i make this command run on a stored variable?
<p><strong>I want to execute a command in my program by a value stored in a variable.</strong></p> <p>at the moment it works like this:</p> <p>you need to write the value in the command, so if I want to filter by 'Americas' region, I need to do this:</p> <pre><code>wine.loc[wine['Region'] == 'Americas'] </code></pre...
<p>If you want a seperate dataframe to be created for All regions, create a loop and store every dataframe in a dictionary of dataframes like below:</p> <pre><code>dfs = ['df' + str(x) for x in list(wine['Region'].unique())] dicdf = dict() i = 0 while i &lt; len(dfs): dicdf[dfs[i]] = wine[(wine['Region']==list(wi...
python|pandas|dataframe
1
2,381
38,238,215
python (pandas): recombine groupby statements
<p>I have a some data that represents results in time at many different sites. I want to find the quartile break down of my results and also the max and min dates for each site.</p> <p>Finding each of these is easy enough:</p> <pre><code>#quartiles q = df.groupby(['site_id', 'datum']).quantile([0.25,0.5,0.75]) #max ...
<p>This is one way to do it:</p> <pre><code>pd.concat([d_max, d_min, q.unstack().result], axis=1, keys=['max', 'min', 'quantiles']) </code></pre> <p><a href="https://i.stack.imgur.com/vzgDQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vzgDQ.png" alt="enter image description here"></a></p>
python|pandas
2
2,382
38,293,605
pandas filter if name appears in column more than n times
<p>this is my dataframe</p> <pre><code>df = pd.DataFrame({'Col1':['Joe','Bob','Joe','Joe'], 'Col2':[55,25,88,80]}) </code></pre> <p>I only want the names of if it appears more than once in 'Col1'</p> <p>I can do it like this</p> <pre><code>grouped = df.groupby("Col1") grouped.filter(lambda x: x["C...
<p>Use <code>value_counts</code> and <code>isin</code></p> <pre><code>vc = df.Col1.value_counts() &gt; 2 vc = vc[vc] df.loc[df.Col1.isin(vc.index)] </code></pre> <p><a href="https://i.stack.imgur.com/fTVzR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fTVzR.png" alt="enter image description here...
python|python-3.x|pandas
3
2,383
38,426,385
Splitting a 1-d numpy array from tdms file, and plot shorter time series/intervals from the original array
<p>Need help to pull out a specific interval from a 1-d numpy array from a tdms file. Im able to plot the file but are unable to specify the sample interval that I want to plot. As you can see on the picture I want to plot the interval that is in green.</p> <p><a href="https://i.stack.imgur.com/d4Fem.png" rel="nofollo...
<p>You should be able to use the array-subset function, give it your array, an index, and length and you will get your sub-array.</p>
python|arrays|numpy|split|labview
1
2,384
38,287,696
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 19: ordinal not in range(128)
<p>Posting again as the previous post had the API token in it. I am scraping data from a website: Here is the code:</p> <pre><code>reload(sys) sys.setdefaultencoding('utf-8-sig') def __unicode__(self): return unicode(self.some_field) or u'' def daterange(start_date, end_date): for n in range(int ((end_date - s...
<p>One brute force way to remove all non-ASCII characters from a string is:</p> <pre><code>import re # substitute sequence of non-ASCII characters with single space str = re.sub(r'[^\x00-\x7F]+',' ', str) </code></pre> <p>Hope that helps in your case</p>
python|python-2.7|pandas|unicode
0
2,385
66,290,958
What is the use of pd.concat's copy=True?
<p>I read the following about the copy-parameter in pandas.concat function <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p><strong>copy</strong>: bool, default True<br>If False, do not copy data unnecessarily.</p> <...
<blockquote> <p>well see there are 2 type of copies in python</p> <p>1.Deep copy</p> <p>2.Shallow Copy</p> </blockquote> <p>so basically the copy parameter in <code>pd.concat()</code> defines the same by default it creates a <code>deep copy</code> but if you overwrite its value by <code>False</code> it creates <code>Sh...
python|copy|concatenation|pandas
1
2,386
66,324,740
Copy a column to multiple columns of a DataFrame with Pandas
<p>I have a DataFrame with multiple columns, a few columns being NaN. The dataframe is quite big having around 5,000 columns. Below is a sample from it:</p> <pre><code> GeoCode ESP FIN USA EZ19 PRT 1 Geography Spain Finland USA EZ Portugal 2 31-Mar-15 NaN NaN 0.26 ...
<p>If you're interested in replacing values of columns that contain all nulls, you can take a shortcut and simply overwrite all values below row 2 after identifying those values are entirely null.</p> <pre><code># Identify columns that contain null values from row 2 onwards all_null_cols = df.loc[2:].isnull().all() # ...
python|pandas|dataframe
2
2,387
66,159,175
How to condense rows in Pandas by removing everything between two conditions
<p>I have a keyboard log that is telling me when keys are being press/released:</p> <pre><code>key state time z 1 0.133 d 1 0.298 d 0 0.36 a 1 0.522 a 1 0.6455 a 1 0.7744 a 1 0.9033 a 1 1.0322 a 1 1.1611 a 1 1.29 a 1 1.4189 a 1 1.5478 a 1 1.6767 a 1 1.8056 a 1...
<p>It's a simple application of <code>first()</code></p> <pre><code>dfu = df.groupby([&quot;key&quot;,&quot;state&quot;], as_index=False).first().sort_values(&quot;time&quot;) </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;"></th> <th style="text-align: ...
python|pandas
3
2,388
65,966,888
Very high latency running Python Flask app on gcloud app engine
<p>I have this small Python Flask app that gets a file posted as input and runs this file through a tensforflow keras model to come back with a prediction.</p> <p>On my old laptop, running this locally it is superfast. The app consumes around 450MB or ram.</p> <p>Now I have deployed this app to gcloud app engine, and I...
<p>The best practice is to use tensorflow serving . Read <a href="https://www.tensorflow.org/tfx/guide/serving" rel="nofollow noreferrer">https://www.tensorflow.org/tfx/guide/serving</a> for more detail .</p>
python-3.x|tensorflow2.0|gcloud|flask-restful
0
2,389
58,288,670
Merging two dataframes on the same type column gives me wrong result
<p>I have two dataframes, assume A and B, which have been created after reading the sheets of an Excel file and performing some basic functions. I need to <code>merge right</code> the two dataframes on a column named ID which has first been converted to <code>astype(str)</code> for both dataframes.</p> <p>The ID colum...
<p>Try turning all values in both columns into strings: <code>A['ID'] = A['ID'].astype(str)</code> <code>B['ID'] = B['ID'].astype(str)</code></p> <p>Generally, when a merge like this doesn't work, I would try to debug by printing out the unique values in each column to check if anything pops out (usually dtype issues)...
pandas|merge
1
2,390
58,174,267
Computing age from to_timedelta is weird, and DateOffset is not scalable over a Series
<p>I have two columns:</p> <pre><code> date age 0 2016-01-05 47.0 1 2016-01-05 43.0 2 2016-01-05 28.0 3 2016-01-05 46.0 4 2016-01-04 39.0 </code></pre> <p>What I want is another column with the difference between the date and age:</p> <pre><code> date age dob 0 2016-0...
<p>If you need to specify a different non-standard offset (i.e. months or years) for every row it can save time to <strong>loop over the unique offsets instead of rows</strong>. Accomplish this with a <code>groupby</code>.</p> <p>This will be especially true when the number of unique offsets is &lt;&lt; the number of r...
python|pandas
2
2,391
58,341,147
How to find a shape inside a Numpy 2D array having an contour?
<p>I have a shape contour <code>cnt</code>, I need to find it inside a 2D array, I have a target_index variable, it is used to find the required zone, but I need to look for the <code>cnt</code> contour in it.</p> <pre><code>import numpy as np x = np.linspace(0,1000, int(1000/50)) y = np.linspace(0,1000, int(1000/50)...
<p>Unless you limit yourself to certain polygons, I think it's going to be very hard to use <code>np.where</code> to do this.</p> <p>Here's how to use <code>matplotlib</code>'s <code>Path</code> object to solve the problem (adapting <a href="https://stackoverflow.com/questions/21339448/how-to-get-list-of-points-inside...
python|arrays|numpy
1
2,392
58,506,163
Bigquery query result to dataframe with Airflow
<p>I am trying to query the data from bigquery and write it to dataframe with Airflow. But either it is giving <code>file not found</code> (service account key) or <code>file name is too long</code> or <code>eof line read</code> error.</p> <p>I have tried with hooks as well but I am not able to do put key file as json...
<p><code>bigquery.Client.from_service_account_json</code> function expects file name of the service account file, you provide it with the contents of that file, so it tries to find the file which path starts with <code>{\r\n "type": "servi...</code> and it fails with <code>FileNotFound</code>. </p> <p>Potential fix:<...
sql|pandas|dataframe|google-bigquery|airflow
2
2,393
68,972,366
Comparing previous row values in Pandas DataFrame in different column
<p>my input:</p> <pre><code>first=pd.Series([0,1680,5000,14999,17000]) last =pd.Series([4999,7501,10000,16777,21387]) dd=pd.concat([first, last], axis=1) </code></pre> <p>I trying find&amp;compare second value in first column (e.g. <code>1680</code>) and &quot;range&quot; previous row between first value in first colum...
<p>Use <code>shift</code> and <code>between</code> to compare a row with the previous one:</p> <pre><code>&gt;&gt;&gt; df[0].loc[df[0].between(df[0].shift(), df[1].shift())] 1 1680 2 5000 Name: 0, dtype: int64 </code></pre> <p>Details of <code>shift</code>:</p> <pre><code>&gt;&gt;&gt; pd.concat([df[0], df.shift()...
python|pandas
1
2,394
44,572,926
Graphing with rolling mean data not smoothing properly
<p>When trying to plot a rolling mean in pandas to smooth my data using the following code I get a strange appearing graph</p> <pre><code>data['mean_Kincaid'] = pd.rolling_mean(data.Kincaid,30, min_periods=1) data['Year']= data['Date'].dt.year data.plot(x='Date', y='mean_Kincaid') </code></pre> <p>Which yields the fo...
<p>This is insufficient smoothing.</p> <pre><code>n = 8001 df = pd.DataFrame(dict( Kincaid=np.sin(np.linspace(-4, 4, n)) + np.random.rand(n) * 2, Date=pd.date_range('2010-03-31', periods=n) )) df['mean_Kincaid'] = df.Kincaid.rolling(30, min_periods=1).mean() df.plot(x='Date', y=['Kincaid', 'mean_...
python|pandas|datetime|plot
1
2,395
44,476,957
How to fill "column B" based on value in "column A" when the column has object dtype in python pandas?
<p>I have a CSV file which I imported as a pandas dataframe. I want to create and fill up a column based on some specific terms in another column. The column that has all those values is an <strong>object</strong> dtype. It has values like:</p> <pre><code>ABC|MNO - 2017 - Trial|1|Random|xyz|RUN|Google|1x1|A10001-21|SD...
<p>Try doing this:</p> <pre><code> def new(row): if row.contains("PRIME"): return 'A' if row.contains("Random"): return 'B' if row.contains("Google"): return 'C' </code></pre>
python|csv|pandas|numpy
0
2,396
60,951,491
Google cloud, ubuntu ERROR: Could not install packages due to an EnvironmentError: [Errno 28] No space left on device
<p>I am trying to install tensorflow on Google Cloud, Ubuntu 16.04.6 LTS with enough disk space but still i am getting the error "No Space left on device"</p> <p>df:</p> <pre><code>Filesystem 1K-blocks Used Available Use% Mounted on udev 15426012 0 15426012 0% /dev tmpfs 3087448 ...
<p>Try pip install --no-cache-dir tensorflow</p> <p>Refer to following thread; <a href="https://github.com/pypa/pip/issues/5816#issuecomment-587302775" rel="nofollow noreferrer">https://github.com/pypa/pip/issues/5816#issuecomment-587302775</a></p>
tensorflow|ubuntu|google-cloud-platform
3
2,397
60,922,759
Tensorflow version mismatch on conda environments
<p>I had initially installed tf-nightly by mistake and later uninstalled it. Now, I have installed two different versions of tensorflow on two different conda environments (tf1.14-gpu and tf2.0-gpu). When I execute the command </p> <p><code>conda list -n tf1.14-gpu tensorflow</code> it shows the following output</p> ...
<p>I ran to the same problem. Could it be possible that you installed <code>tf-nightly</code> using pip and not Conda? But when you run <code>import tensorflow as tf; print(tf.__version__)</code>it picks up the global pip version which is troublesome to get rid of?</p> <p>p.s. Sorry that I'm posting instead of comment...
python|tensorflow|jupyter-notebook|anaconda|conda
0
2,398
71,609,817
How can i make each key in a dictionary a string and make the value of that key a Python list
<p>I am trying to convert a dictionary key to a string and make the values a list</p> <p>this is where i am and i don't know what to do next</p> <pre><code>dict_from_csv = pd.read_csv('Emissions.csv', header=None, index_col=0, squeeze=True).to_dict() keys = list(dict_from_csv.keys()) values = list(dict_from_csv.values...
<p>Do you want a unique string to represent all the keys? If yes, you can do this:</p> <pre><code>keys = &quot; &quot;.join(list(dict_from_csv.keys())) </code></pre> <p>And, Do you like a single list with all values? If yes, you can do this:</p> <pre><code>values = [val for key in df for val in dict_from_csv[key].value...
python|pandas|csv|dictionary|key
0
2,399
71,612,541
Redis not working. __init__() got an unexpected keyword argument 'username'
<p>i am trying to run the celery -A project worker -l info. But each time it returns an error like <strong>init</strong> got unexpected error. Kindly Help. Thanks in advance.</p> <p>my settings file:</p> <pre><code>CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCE...
<p>I just solved the problem by installing a Redis bundle.</p> <pre><code>pip install &quot;celery[redis]&quot; </code></pre>
python|django|pandas|redis|celery
3