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 |
|---|---|---|---|---|---|---|
362,200 | 55,330,568 | How to exclude rows based on multi column value conditions in pandas dataframe? | <p>There's pandas dataframe ad below: </p>
<pre><code>email score
a@domain.com A
b@domain.com A
c@domain.com C
d@domain.com B
</code></pre>
<p>I want to exclude rows with <code>email</code> <code>a@domain.com</code> and <code>c@domain.com</code>.Expect result as below: </p>
<pre><co... | <p>You have to surround it by parenthesis:</p>
<pre><code>df = df[(df.email != 'a@domain.com') & (df.email != 'c@domain.com')]
</code></pre>
<p>That said, it would be easier with <code>isin</code>:</p>
<pre><code>df = df[~df.email.isin(['a@domain.com', 'c@domain.com'])]
</code></pre>
<p>And now:</p>
<pre><code... | python|pandas | 1 |
362,201 | 55,565,306 | How to split multiple values in columns and groupby said values in pandas? | <p>I'm trying to create a new DataFrame by separating a column out that has multiple values so that each row only has one value.</p>
<p>I've tried a few groupby operations, but I seem to be unable to separate the values or organize it by users</p>
<pre><code> item title feature
0 1 ToyStory(1995) Adventure|A... | <p>You'll need <code>str.split</code>, followed by <code>stack</code>:</p>
<pre><code>r = df.set_index('item').feature.str.split('|', expand=True).stack()
r.index = r.index.get_level_values(0)
r.reset_index(name='feature')
item feature
0 1 Adventure
1 1 Animation
2 1 Children
3 1 C... | python|pandas|dataframe|transformation | 1 |
362,202 | 55,481,467 | Tensorflow tensor operation of different size along the last dimension | <p>I have a <code>tensor1</code> with shape <code>[1 128, 128 , 100]</code>, and I have another <code>tensor2</code> with shape <code>[1,128,128,1]</code>.
If I try to subtract <code>tensor1 - tensor2</code>, on the last dimension, will the <code>tensor2</code> automatically broadcast to <code>[1,128,128,100]</code> an... | <p>Yes, it will be broadcasted. The broadasting <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow noreferrer">rules</a> in tensorflow are the same as for numpy:</p>
<blockquote>
<p>When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing di... | python|tensorflow|deep-learning|tensor | 1 |
362,203 | 55,169,927 | Using Classification_Report function in Sklearn | <p>So how I understand this function works is that it splits a table into two and then compares the values to determine the prediction rate</p>
<p>Lets say I have a table:</p>
<pre><code>Column1 Column2 Column3 Column4 Column5
3 2 2 43 0
1 2 2 23 ... | <p>y_true are the true labels of the samples and y_pred are the predictions made my the model. target_name lets you assign custom names to the class labels</p>
<p>classification_report repots the precision, recall, f1-score and support of the model.</p>
<p>Example as shown in sklearn
<a href="https://scikit-learn.o... | python|scikit-learn|sklearn-pandas | 0 |
362,204 | 55,277,252 | ValueError: Operation 'cond_25/Shape' has been marked as not fetchable | <p>The above error occurs when I try to do the following:</p>
<pre><code>se = tf.Session()
cont = tf.constant([[1., 2., 4., 5.], [5., 2., 7., 8.]])
def f1():
print(se.run(tf.shape(cont)))
return True
def f2():
return False
r = tf.cond(tf.greater(tf.constant(10), tf.constant(9)), f1, f2)
</code></pre>
<p>T... | <p>The error you see is explained <a href="https://github.com/tensorflow/tensorflow/issues/4094#issue-173787623" rel="nofollow noreferrer">here</a></p>
<p>Please note this line in the explanation.</p>
<blockquote>
<p>Recall that all functions passed to tf.cond() or tf.while_loop() must be pure functions, and so the... | python|tensorflow | 1 |
362,205 | 55,369,652 | PyTorch doesn't seem to be optimizing correctly | <p>I have posted this question on Data Science StackExchange site since StackOverflow does not support LaTeX. Linking it here because this site is probably more appropriate.</p>
<p>The question with correctly rendered LaTeX is here: <a href="https://datascience.stackexchange.com/questions/48062/pytorch-does-not-seem-t... | <p>You have to move computing <code>T</code> inside the loop, or it will always have the same constant value, thus constant loss.</p>
<p>Another thing is to initialize <code>theta</code> to different values at indices, otherwise because of the symmetric nature of the problem the gradient is the same for every index.</... | pytorch | 2 |
362,206 | 55,325,352 | how to save output of if elif statement to new variable in python dataframe? | <p>how do i edit the following script to save the outputs as new variables in the original dataframe?</p>
<p>AKA: instead of the print function, have the output be saved as a new variable for each if elif statement?</p>
<pre><code>import re
df = pd.read_excel('edmundstest.xlsx')
for Keyword, Landing_Page in zip(df[... | <p>You could use a dictionary:</p>
<pre><code>dict[Keyword]=f"new_model_core_incentives {new_model_core_incentives}"
dict2[Keyword]=f"old_word {old_word}"
</code></pre>
<p>Something like this:</p>
<pre><code>import re
df = pd.read_excel('edmundstest.xlsx')
dict, dict2 = {}, {}
for Keyword, Landing_Page in zip(df[... | python|regex|pandas|dataframe | 0 |
362,207 | 55,566,478 | Obtaining Logits of the output from deeplab model | <p>I'm using a pre-trained <code>deeplab</code> model (from <a href="http://download.tensorflow.org/models/deeplabv3_mnv2_pascal_train_aug_2018_01_29.tar.gz" rel="nofollow noreferrer">here</a>) to obtain segmentations for an input image. I'm able to obtain the sematic labels (i.e. <code>SemanticPredictions</code>) whic... | <p>For a model trained from MobileNet_V2 setting <code>self.OUTPUT_TENSOR_NAME = 'ResizeBilinear_2:0'</code> retrieves the logits before the argmax is performed. </p>
<p>I suspect this is the same for xception, but have not verified it. </p>
<p>I arrived at this answer by loading my model in tensorflow. Then, printin... | tensorflow|softmax|deeplab|logits | 0 |
362,208 | 55,549,863 | Regex on pandas dataframe to change column names, then re-arrrage format of dataframe | <p>I have dataframe with the following format.</p>
<p><a href="https://i.stack.imgur.com/ojUUg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ojUUg.png" alt="enter image description here"></a></p>
<p>Would like to modified the column names and rearranging the dataframe into the following format:-<... | <p>First change pattern for matching groups by <code>r'([A-Z]{4})(\d{4})(.+)'</code> and use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>Series.str.extract</code></a> for new helper <code>DataFrame</code> - convert second column to i... | python|regex|pandas | 3 |
362,209 | 55,542,077 | Sort each dataframe in a dictionary of dataframes | <p>Thanks to @Woody Pride's answer here: <a href="https://stackoverflow.com/a/19791302/5608428">https://stackoverflow.com/a/19791302/5608428</a>, I've got to 95% of what I want to achieve.</p>
<p>Which is, by the way, create a dict of sub dataframes from a large df.</p>
<p>All I need to do is sort each dataframe in t... | <p>Looks like you just need to assign the sorted DataFrame back into the dict:</p>
<pre><code>for tbl in DataFrameDict:
DataFrameDict[tbl] = DataFrameDict[tbl].sort_values(['Ob1'])
</code></pre> | python|pandas|dictionary | 1 |
362,210 | 55,146,871 | Can numpy.rint to return an Int32? | <p>I'm doing</p>
<pre><code>ret = np.rint(y * 4)
return ret
</code></pre>
<p>And I want it to return <code>Int32</code>. I tried adding <code>dtype='Int32'</code>, but it errors saying: <code>TypeError: No loop matching the specified signature and casting was found for ufunc rint</code></p>
<p>I apologize if this is... | <p><code>ufuncs</code> have specific rules of what kinds of output they produce given the input. For <code>rint</code> the rules are:</p>
<pre><code>In [41]: np.rint.types
Out[41]: ['e->e', 'f->f', 'd->d', 'g->g', 'F->F', 'D->D', 'G->G', '... | python|python-3.x|numpy | 8 |
362,211 | 55,213,262 | Pandas - Aggregating column value from another dataframe based on common column between 2 dataframes | <p>I have 2 different dataframes like so -</p>
<p><a href="https://i.stack.imgur.com/LSsBT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LSsBT.png" alt="DataFrame1"></a></p>
<p>and </p>
<p><a href="https://i.stack.imgur.com/FfexT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com... | <p>I will do <code>gruopby</code> with <code>df2</code> , the <code>map</code> </p>
<pre><code>s=df2.groupby('K ID')['C'].apply(','.join)
df1['Present In']=df1['K ID'].map(s).fillna('')
</code></pre> | python-3.x|pandas|dataframe | 4 |
362,212 | 55,565,916 | How to use Pandas to get the count of every combination inclusive | <p>I am trying to figure out what combination of clothing customers are buying together. I can figure out the exact combination, but the problem I can't figure out is the count that includes the combination + others.</p>
<p>For example, I have:</p>
<pre><code>Cust_num Item Rev
Cust1 Shirt1 $40
Cust1 Shir... | <p>Using <code>pandas.DataFrame.groupby</code>:</p>
<pre><code>grouped_item = df.groupby('Cust_num')['Item']
subsets = grouped_item.apply(lambda x: set(x)).tolist()
Count = [sum(s2.issubset(s1) for s1 in subsets) for s2 in subsets]
combo = grouped_item.apply(lambda x:','.join(x))
combo = combo.reset_index()
combo['Cou... | python|pandas | 8 |
362,213 | 55,253,484 | How to add a custom layer in keras | <p>I want to add a layer, all the element of previous layer <code><0.5</code> is <code>0</code> and all the element of previous layer <code>>=0.5</code> is <code>1</code>.<br>
Do you know how to do that?</p> | <p>You can use Modified ReLU activation with some division operation. The following solution is little modified because, it outputs 0 for x == 0.5.</p>
<p>The output O(x) can be rewritten as </p>
<p><img src="https://chart.googleapis.com/chart?cht=tx&chl=O(x)=ReLU(x-0.5)/(x-0.5)=%5Cleft%7B%5Cbegin%7Barray%7D%7Bll... | tensorflow|keras|layer | 0 |
362,214 | 55,358,589 | Why is pd.qcut() producing massive boundaries? | <p>I have a dataframe of event data of which a column is the interval of time in which that event occurred. I would like to use <code>pd.qcut()</code> to make the percentiles of each interval given the events that are in it, and give each event its respective percentile.</p>
<pre class="lang-py prettyprint-override"><... | <p>I figured out the problem: qcut tries to fit all of the data points themselves into quartiles while cut takes the min and max and cuts into n bins. Because in this example I had more quartiles that I was trying to make than actual datapoints, qcut was failing.</p>
<p>Just using cut into 100 bins solved my problem a... | python|pandas|dataframe|valueerror | 0 |
362,215 | 55,189,686 | Weird Indexing by Python and Numpy | <p>I have a variable X, it contains a list (Python list), of 10 Numpy 1-D arrays (basically vectors).
If I ask for X[100], it throws an error saying: IndexError: list index out of range</p>
<p>Which makes total sense, but, when I ask for X[:100], it doesn't throw an error and it returns the entire list!
Why is that?<... | <p><code>X[:100]</code> means slice <code>X</code> from 0 to 100 or the end (whichever comes first)
But <code>X[100]</code> means the 100th element of <code>X</code>, and if it doesn't exist it throws an <code>index out of range</code> error</p> | python|numpy | 1 |
362,216 | 55,270,462 | sRGB gamma curve implement in tensorflow | <p>I need to implement sRGB gamma curve in tensorflow. But I can not compute the element wise condition in tensorflow. </p>
<p>In sRGB curve, if the value is less or equal than 0.0031308, it is a linear operation: x*12.95
If the value is greater than 0.0031308, it is a gamma correction:
1.055*x^(1/2.4) - 0.055</p>
<p... | <p>Maybe you need <code>tf.where()</code> and <code>tf.greater()</code>. For example:</p>
<pre><code>import tensorflow as tf
import numpy as np
image = np.random.random_sample(size=(2,3,3,1))/100
print(image)
image_tf = tf.placeholder(shape=(None,3,3,1),dtype=tf.float32)
new_image = tf.where(tf.greater(image_tf,0.0... | python|tensorflow|gamma|srgb | 1 |
362,217 | 55,475,704 | create a dataframe with dataframes of different sizes | <p>I have a dataframe and two array with differents sizes and i want to create a single dataframe</p>
<p>for example </p>
<pre><code>import pandas
import numpy
df = pandas.DataFrame(numpy.array([[0,0,1]]),columns = ['A', 'B', 'C'])
V1=numpy.array([0,1,3,4])
V2=numpy.array([2,3,5,8,11,12])
</code></pre>
<p>I wa... | <p>First is necessary repeat array in first DataFrame by maximum length of array, then create for each array <code>Series</code> and join together by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a>:</p>
<pre><code>a = [V1, V2]
n =... | python|pandas|numpy | 1 |
362,218 | 55,525,940 | pandas.DataFrame.groupby leaving out columns | <p>I have a Pandas DataFrame that contains some values and I want to sum up those values according to the <code>date</code> column.</p>
<p>The DataFrame looks like the following:</p>
<p><a href="https://i.stack.imgur.com/5mPGh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5mPGh.png" alt="enter im... | <p>We need <code>numeric</code> columns to be able to do calculation on them, in this case <code>sum</code>:</p>
<pre><code>#Example dataframe
df = pd.DataFrame({'date':['2019-01-04', '2019-01-04', '2019-01-03', '2018-12-22', '2018-08-31'],
'replies_count':['46', '143', '64', '154', '50'],
... | python|pandas|dataframe|group-by | 2 |
362,219 | 55,479,778 | How to plot a bar plot of dates grouped by both month and day? | <p>I want to plot a time series count bar plot based on month and day. I have a pandas data frame like this: </p>
<pre><code> date_time
2003-01-01 1
2003-01-05 1
2003-01-06 1
2003-01-07 1
2004-01-01 1
2005-01-01 1
2005-01-05 1
2005-02-01 1
</code></pre>
<p>I was trying: </p>
<pre... | <p>Here you go. A very simple implementation:</p>
<pre><code>df = pd.DataFrame({'date_time': ['2003-01-01','2003-01-05','2003-01-06','2003-01-07','2004-01-01','2005-01-01','2005-01-05','2005-02-01'], ' ': [1,1,1,1,1,1,1,1]})
df = df.set_index('date_time')
df.index = pd.to_datetime(df.index)
df.groupby(df.index.strftim... | python|pandas|python-2.7 | 0 |
362,220 | 55,444,558 | implementing conv2d in fourier domain using einsum --> ValueError: einstein sum subscripts string contains too many subscripts for operand 0 | <p>According to the convolution theorem, convolution operation changes to pointwise multiplication in fourier domain -
here I have 'fft_x' of shape (batchsize, height, width, in_channels) which is the fft of input data
and similarly 'fft_kernel' of shape (height, width, in_channels, out_channels) which is fft of the ... | <p>I used tf.einsum instead of np.einsum, and it worked.</p> | python|numpy|tensorflow | 1 |
362,221 | 55,516,733 | can datetime plotted using data from a sqlite database in python & matplotlib without using pandas? | <p>I am new to programming:(. I have an sqlite database.I insert as well as query data from the same. It has two columns, datetime(type text) and a 0 or 1(integer). I want to fetch this data using python and plot graph in matplotlib. </p>
<p>I tried it, but it seems that the date time format and its conversion is crea... | <p>There seem to be two problems. First the results from <code>cur.execute('SELECT dt_tim FROM machine1')</code> is a list of tuples. You would need to unpack it to get a list of the actual values.<br>
Second, you will need to convert your date strings to <code>datetime</code> to be able to plot them with matplotlib.</... | python|pandas|matplotlib | 1 |
362,222 | 55,152,016 | Converting the response of Python get request(jpg content) in Numpy Array | <p>The workflow of my function is the following:</p>
<ul>
<li>retrieve a jpg through python get request</li>
<li>save image as png (even though is downloaded as jpg) on disk</li>
<li>use imageio to read from disk image and transform it into numpy array</li>
<li>work with the array</li>
</ul>
<p>This is what I do to s... | <p>imageio.imread is able to read from urls:</p>
<pre><code>import imageio
url = "https://example_url.com/image.jpg"
# image is going to be type <class 'imageio.core.util.Image'>
# that's just an extension of np.ndarray with a meta attribute
image = imageio.imread(url)
</code></pre>
<p>You can look for more ... | arrays|python-3.x|numpy|python-requests|python-imageio | 5 |
362,223 | 55,445,013 | Is there a way to add columns that share another column in common? | <p>I am trying to add the column 'calorie' when the 'start_date' and 'meal_type' are the same to produce a matplotlib plot. I am able to plot the 'calorie' and 'start_date' but i can't figure out how to add the columns and be able to plot them. Here is a sample of my data sorted on the 'start_date':<br>
using ; (semi-c... | <p>If I understand you correctly you want do the sum of each <code>meal_type</code> on the same <code>date</code>.</p>
<p>We can do the following:</p>
<pre><code># If needed convert the start_time column to type datetime
df['start_time'] = pd.to_datetime(df['start_time'])
# Calculate the correct calories
df['calorie... | python|pandas | 0 |
362,224 | 55,541,871 | Get a key: value pair dictionary from two consecutive columns of pandas dataframe | <p>I am extracting data from excel sheet and storing it into a dataframe. I want to create a key:value pair dictionary from the columns of dataframe.</p>
<p>For example: <code>[{key=column1 : value = column2, key = column3 : value=column4 }]</code>, and so on till the last column.
Here is the sample data on which I am... | <p>You can slice even and odd columns with <code>::2</code> and <code>1::2</code> </p>
<pre><code>dict(zip(df.iloc[:, ::2].to_numpy().ravel(), df.iloc[:, 1::2].to_numpy().ravel()))
</code></pre>
<h3>Output:</h3>
<pre><code>{'A': 5,
'B': 10,
'C': 15,
'D': 20,
'E': 25,
'F': 30,
'G': 35,
'H': 40,
'I': 45}
</... | pandas|python-2.7|dictionary | 2 |
362,225 | 55,456,674 | How to change Data Type from Object to just date format? | <p>For one of the columns of my DataFrame, I have a date which is in the format: 2019-01-31 however the data type of this column is Object. I am not very used to python as I am a beginner so was hoping someone could help me figure out how to change the data type so that this column can be recognized as a date?
Not sure... | <p>I'm sure this has been answered elsewhere. Using pandas:</p>
<pre><code>df['Column']= pd.to_datetime(df['Column'], errors='coerce')
</code></pre>
<p>If errors = ‘coerce’, then invalid parsing will be set as NaN</p> | python|pandas|date|dataframe|jupyter | 0 |
362,226 | 55,456,009 | Plotting a Pandas series in Matplotlib/seaborn | <p>I am trying an alternate way to visualize a pandas series using matplotlib/seaborn. But I am not able to do it. Is there any way?</p>
<p>I have no problem visualizing it using the df.plot() method of pandas.</p>
<pre><code>df2.groupby('Company').Company.count()
</code></pre>
<p>Data looks like this:</p>
<pre><co... | <p>You could use seaborn's <code>countplot</code>:</p>
<pre><code>import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
test = pd.DataFrame()
test["Company"] = ["a", "b", "c", "d", "a", "c", "d", "b", "a", "c"]
ax=sns.countplot(test["Company"])
plt.show()
</code></pre>
<p><a href="https://i.stack.... | python|python-3.x|pandas|matplotlib|seaborn | 3 |
362,227 | 55,519,204 | Numpy divide on ndarray | <p>I want to create a new array containing the ratios of another ndarray.</p>
<p><strong>First simple example:</strong></p>
<pre><code>import numpy as np
week = np.full((3, 4), 2, dtype=float)
week[:,2] = 0
week[2,0:2] =0
week[0,3] =0.99
week[1,3] =1.99
week[2,3] =0.89
week
</code></pre>
<p>returns</p>
<pre><code>... | <p>I think a loop is your best hope here and there is a slow and a fast way to do it:</p>
<h2>the slow way:</h2>
<p></p>
<pre><code>def get_ratios(arr):
ni, nj, nk = arr.shape[:3]
last_dim = arr.shape[3]
new_arr = np.zeros(shape=(ni, nj, nk, last_dim, last_dim),
dtype=np.float64)
... | python|numpy|multidimensional-array | 1 |
362,228 | 55,516,484 | Could two tf.data.Dataset coexist and controled by tf.cond() | <p>I put two <code>Dataset</code> pipeline for train/test = 9:1 set in my Graph and the control the flow by a tf.cond. I encountered a problem that during the training the both pipelines are activated at each step. The testset ran out before the trainset as it has less during training. </p>
<blockquote>
<p>OutOfRang... | <p>Consider example:</p>
<pre class="lang-py prettyprint-override"><code>train = np.arange(90)
test = np.arange(10)
train_ds = tf.data.Dataset.from_tensor_slices(train).shuffle(10).batch(10).repeat()
test_ds = tf.data.Dataset.from_tensor_slices(test).shuffle(10).batch(10).repeat()
train_iterator = train_ds.make_init... | python|tensorflow|conv-neural-network|tensorflow-datasets | 1 |
362,229 | 55,243,281 | delete occurance of a pattern in python pandas dataframe | <p>I have a python dataframe where a column has elements starting with pjp- and ends at |,for example pjp-XYA|, i want to delete everything from pjp- till the first occurence of "|" in the pandas dataframe. I tried doing this, but i got an error saying it works only for strings.</p>
<pre><code>f = pd.read_csv("test.cs... | <p>This does exactly what you want it to do in 1 line of code:</p>
<pre><code>#Theres actually 4 things going on in this 1 line of code
df['Code_Boxes'] = (((df['Code_Boxes'].str.rsplit('pjp-')).str[1]).str.rsplit('|')).str[1]
</code></pre>
<p>This will only work if what you say is true 'pjp-' is always at the front ... | python|pandas | 0 |
362,230 | 55,437,498 | numpy append, typeError: invalid type promotion | <p>I want to create a numpy ndarray with mixed data types. But I had problem appending another row to it.
My goal is to initalize k and keep adding rows to it in the future.</p>
<pre><code>import numpy as np
k = np.ndarray((0,3), dtype=[('name', str), ('age', int), ('height', float)])
print(f'k datatype: {k.dtype}')
... | <p>There are two things wrong with your code. The first is that you should specify the <code>object</code> dtype for fields you intend to be variable-length strings. </p>
<p>The second is that <code>numpy</code> treats <code>lists</code> and <code>tuples</code> differently, in line with their conceptual origins. You n... | python|numpy|multidimensional-array|numpy-ndarray | 0 |
362,231 | 55,575,366 | Reshape, concatenate and aggregate multiple pandas DataFrames | <p>I have five different pandas data frames showing results of calculations done of the same data with same number of samples , all the arrays are identical in shape. (5x10)</p>
<pre><code>df shape for each data set:
(recording channels)
0 1 2 3 4 5 6 7 8 9
t)
0 x x x x x x x x x x
1 x x x x x x x x x x
2 ... | <p>Using your code to generate the data, we use melt to transform it from <code>wide</code> to <code>long</code> format:</p>
<pre><code>df_all = pd.DataFrame()
for i in range(5):
a = np.array(np.random.randint(0,1000+i, 50))
a = a.reshape(5,10)
df = pd.DataFrame(a)
list_df.append(df)
# rather using... | pandas|dataframe|python-3.5|dask|dask-distributed | 0 |
362,232 | 55,472,486 | Convert Redis Streams output to Pandas Dataframe | <p>What would be the <strong>fastest</strong> way to convert a <a href="https://redis.io/topics/streams-intro" rel="nofollow noreferrer">Redis Stream</a> output (aioredis client/ hiredis parser) to a Pandas Dataframe where Redis Stream ID‘s timestamp <strong>and</strong> sequence number as well as values are proper typ... | <p>There seem to be two main bottlenecks here:</p>
<ol>
<li><p>Pandas DataFrames store their data in column-major format, meaning each column maps to one numpy array, whereas the Redis stream data is row-by-row.</p></li>
<li><p>Pandas MultiIndex is made for categorical data, and converting raw arrays to the required l... | python|pandas|dataframe|redis|redis-streams | 4 |
362,233 | 10,146,924 | Finding the maximum of a function | <p>How do I find the maximum of a function in Python? I could try to hack together a derivative function and find the zero of that, but is there a method in <code>numpy</code> (or other library) that can do it for me?</p> | <p>You can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fmin.html"><code>scipy.optimize.fmin</code></a> on the negative of your function.</p>
<pre><code>def f(x): return -2 * x**2 + 4 * x
max_x = scipy.optimize.fmin(lambda x: -f(x), 0)
# array([ 1.])
</code></pre> | python|numpy | 28 |
362,234 | 7,327,739 | Appending large amount of data to a tables (HDF5) database where database.numcols != newdata.numcols? | <p>I am trying to append a large dataset (>30Gb) to an existing pytables table. The table is N columns, and the dataset is N-1 columns; one column is calculated after I know the other N-1 columns.</p>
<p>I'm using <code>numpy.fromfile()</code> to read chunks of the dataset into memory before appending it to the datab... | <p>You could add the results to another table. Unless there's some compelling reason for the calculated column to be adjacent to the other columns, that's probably the easiest. There's something to be said for separating raw data from calculations anyways. </p>
<p>If you must increase the size of the table, look in... | python|numpy|hdf5|pytables | 2 |
362,235 | 56,461,316 | Extracting cells from one column when conditions match in other columns in a Dataframes | <p>I have a csv file I load into a data frame. </p>
<p>... SCity, DCity, CVtype, L1Name....</p>
<p>I want to extract L1Name for specific combinations of SCity, DCity and CVType.</p>
<p>Ideally the data should return as a list so that I can use each return value to extract other information from the Dataframes, like... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <code>()</code> and chained condition by <code>&</code> or <code>|</code>:</p>
<pre><code>#filter by & for bitwise AND
df = cimsBid[(cimsBid['C... | python-3.x|pandas | 1 |
362,236 | 56,804,103 | Inserting several columns into another DataFrame | <p>Say I have the following DataFrame df1:</p>
<pre><code>name course yob city
paul A 1995 london
john A 2005 berlin
stacy B 2015 vienna
mark D 2013 madrid
</code></pre>
<p>And also the following DataFrame df2:</p>
<pre><code>name height occupation
... | <p>Its not clear you want left or outer join. here is simple way for left join</p>
<p>I am using first dataframe as df1 and second dataframe as df2 for result</p>
<pre><code>import pandas as pd
df_result = pd.merge (left=df1, right=df2, how='left', on='name')
# Reorder the columns
df_result = df_result[["name", "c... | python|pandas | 2 |
362,237 | 56,665,565 | how to fix "ImportError: cannot import name label_map_util" | <p>Upon doing</p>
<pre><code>from utils import label_map_util
</code></pre>
<p>I get</p>
<pre><code>ImportError: cannot import name label_map_util
</code></pre>
<p>Changing to</p>
<pre><code>from object_detection.utils import label_map_util
</code></pre>
<p>gives the same error.</p>
<p>I'm trying with PyCharm on... | <p>Inside <code>pycharm</code> terminal change current directory to <code>models/research</code> and run the following command</p>
<pre><code>export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
</code></pre> | python|tensorflow|object-detection-api | 3 |
362,238 | 56,756,177 | Is there a way to plot corresponding points of two data frames? | <p>I have two dataframes with the same columns and date indices:</p>
<p>df1:</p>
<pre><code>Date T.TO AS.TO NTR.TO ... R.TO
2016-03-03 0.1 0.02 0.04 0.02
2016-03-04 0.09 0.01 0.02 0.02
2016-03-05 0.1 0.02 0.04 0.02
...
2019-03-03 0.09 0.01 0.02 0.02
</code></pre>
<p>df2:</p>
... | <p>To plot these points, you can <code>stack</code>:</p>
<pre><code>plt.scatter(df1.set_index('Date').stack(), df2.set_index('Date').stack())
</code></pre>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/mZmYm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mZmYm.png" alt="enter image descrip... | python|pandas | 2 |
362,239 | 56,480,240 | How to display slope of a section of a line | <p>basically I have a dataset where I only want to find the slope of a section of the line that I plotted. Every answer I've seen has only explained how to create a general line of best fit, however that is not relevant to what I need.</p>
<p>I'm using Jupyter Notebook in python 3, with pandas, matplotlib.pyplot, nump... | <p>Try to use some threshold to grab the subset of your arrays that isn't flat. Something along the lines of</p>
<pre class="lang-py prettyprint-override"><code>idx = np.array([])
for i in range(len(array)):
if np.abs(array[i] - array[i+1]) > some_threshold:
idx = np.append(idx,i)
new_array = array[idx[0]:idx[... | python-3.x|pandas|matplotlib|jupyter-notebook | 0 |
362,240 | 56,732,222 | how to use other tokenlizer(NLTK,Jiebe etc.) in tensorflow serving | <p>Recently, I have been using estimator to train and deploy a tensorflow model, but when I deploy the model (it was exported using estimator <code>serving_fn</code> including <code>tf.py_func</code>) using tensorflow seving, there is an error (see below).</p>
<p>I found this question on Github that said the serving c... | <p>Have you tried using the tensorflow native tokenizer,eg. see <a href="https://www.tensorflow.org/beta/tutorials/tensorflow_text/intro#tokenization" rel="nofollow noreferrer">https://www.tensorflow.org/beta/tutorials/tensorflow_text/intro#tokenization</a></p> | tensorflow|tensorflow-estimator|serving | 1 |
362,241 | 56,584,051 | How do I drop all rows after last occurrence of a value? | <p>I have a dataframe with a string column and I would like to drop all rows after the last occurrence of a name.</p>
<pre><code>first_name
Andy
Josh
Mark
Tim
Alex
Andy
Josh
Mark
Tim
Alex
Andy
Josh
Mark
</code></pre>
<p>What I would like is to drop rows after Alex occurs for the last time, so drop the rows with Andy,... | <h3><code>argmax</code></h3>
<pre><code>df.iloc[:len(df) - (df.first_name.to_numpy() == 'Alex')[::-1].argmax()]
first_name
0 Andy
1 Josh
2 Mark
3 Tim
4 Alex
5 Andy
6 Josh
7 Mark
8 Tim
9 Alex
</code></pre>
<hr>
<h3><code>last_valid_index</code></h3>
<p... | python|pandas | 4 |
362,242 | 56,863,923 | How to install tensorflow without internet connection? | <p>I want to install tensorflow in my PC (Windows 10) which doesnot have internet connection but I have downloaded the tensorflow package - tensorflow-1.14.0-cp37-cp37m-win_amd64.whl from the below link </p>
<p><a href="https://pypi.org/project/tensorflow/#files" rel="nofollow noreferrer">https://pypi.org/project/tens... | <p>Try install TensorFlow without dependencies:</p>
<pre><code>pip install --no-deps "C:\Python_Packages\tensorflow-1.14.0-cp3 7-cp37m-win_amd64.whl"
</code></pre> | python|tensorflow|keras | 5 |
362,243 | 56,729,886 | Search value in Next Month Record Pandas | <p>Given that i have a df like this:</p>
<pre><code> ID Date Amount
0 a 2014-06-13 12:03:56 13
1 b 2014-06-15 08:11:10 14
2 a 2014-07-02 13:00:01 15
3 b 2014-07-19 16:18:41 22
4 b 2014-08-06 09:39:14 17
5 c 2014-08-22 11:20:56 55
...
129 a 2016... | <p>Using <code>pd.to_datetime</code> with <code>ts</code> tricks:</p>
<pre><code>import pandas as pd
df['Date'] = pd.to_datetime(df['Date'])
df['tmp'] = (df['Date'] - pd.DateOffset(months=1)).dt.month
s = df.groupby('ID').apply(lambda x:x['Date'].dt.month.isin(x['tmp']))
df['Checking'] = s.reset_index(level=0)['Date'... | python-3.x|pandas | 0 |
362,244 | 56,732,379 | Can we filter data on the basis of specific words? | <p>I am making a web application which reads data from an Excel file. The data set I have has a columns which has data of categories and sub-categories of books such as 'Fiction.Romantic', 'Fiction.Thriller', 'Sports.Imaginative', 'Sports.AutoBiographic' etc. </p>
<p>I want the pandas to filter out data and print the... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>Series.str.split</code></a> by first <code>.</code> only by <code>n=1</code> and select firts lists by indexing:</p>
<pre><code>df['Category'] = df['Category'].str.split('.', n=1).str... | python|excel|python-3.x|pandas | 2 |
362,245 | 56,756,705 | tensorflow_hub : module spec export with checkpoint path doesn't save all variables | <p>I want to train GANs with tensorflow and then export the generator and the discriminator as tensorflow_hub modules.<br>
For that:<br>
- I define my GAN architecture with tensorflow<br>
- train it and save checkpoints<br>
- create a module_spec with different tags like:<br>
<code>(set(), {'batch_size': 8, 'mo... | <p>I found a way to handle this problem, even though I think it's not the cleanest way to do this:</p>
<p>The next line of code define the module by default, when calling hub.Module with no tags:</p>
<pre><code>(set(), {'batch_size': 8, 'model': 'gen'})
</code></pre>
<p>In fact, I realized that this set of parameter... | python|tensorflow|tensorflow-hub | 1 |
362,246 | 56,822,065 | How to implement this loss in keras | <p>I want to implement this loss like this:
<a href="https://i.stack.imgur.com/eQ5wa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eQ5wa.png" alt="Loss"></a></p>
<p>This is code:</p>
<pre class="lang-py prettyprint-override"><code>def loss(output, target, from_logits=False):
L1 = - tf.... | <ul>
<li>Supposing you have <code>y_true</code> with shape <code>(samples, 11)</code>, one hot encoded. </li>
<li>Supposing that you are using a <code>softmax</code> (classes sum = 1) activation in the last layer </li>
</ul>
<p>A loss in Keras has the form <code>def func(y_true, y_pred):</code></p>
<pre class="l... | tensorflow|keras | 1 |
362,247 | 56,795,305 | Compare values in numpy array and Pandas dataframe | <p>I have an array of type <code>numpy.ndarray</code> and pandas DataFrame and need a way to compare each value to each other. </p>
<p>Below is one of the ways I've tried to do it. I've also used <code>pd.get(labels)</code> to pull the values out and was returned <code>None</code>. <code>y_test</code> is a pandas Data... | <p>So if y_test is a dataframe, then you can just ask for the values like this to get a numpy array:</p>
<pre><code>y_test_array = y_test["labels"].values
</code></pre>
<p>Then print this out to know how many items are equal:</p>
<pre><code>sum(y_test_array == preds)# number of items with same value
sum(y_test_array... | pandas|numpy|dataframe | 1 |
362,248 | 56,792,194 | What is causing "ValueError: cannot convert float NaN to integer" in my function | <p>I have created this function: </p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
def npp_tool(pb_opt, chlor_a, daylight, irrFunc, z_eu):
if daylight == 0 or daylight == np.nan:
return -32767
elif pb_opt == np.nan:
return -32767
... | <p>You can't compare <code>np.nan</code> with <code>np.nan</code> using <code>==</code></p>
<p>you should use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.isnan.html" rel="noreferrer"><code>np.isnan</code></a>:</p>
<p>so change all your comparisons to:</p>
<pre><code>elif np.isnan(pb_opt):
</c... | python|python-3.x|numpy|nan | 6 |
362,249 | 56,470,207 | module 'pandas' has no attribute 'expanding_max' | <p>I want to calculate the max of previous rows using <code>pd.expanding_max()</code>. But it report module <code>'pandas'</code> has no attribute <code>'expanding_max'</code></p>
<pre><code>df['max2here'] = pd.expanding_max(df['a'])
</code></pre>
<blockquote>
<p>AttributeError: module 'pandas' has no attribute 'ex... | <p><code>pd.expanding</code> family of functions have been deprecated and removed in recent versions (since v0.18, see the <a href="https://github.com/pandas-dev/pandas/pull/11603" rel="nofollow noreferrer">GitHub commit</a>), and replaced by the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/panda... | python|pandas | 2 |
362,250 | 56,594,825 | Show value at the top of the bar with pandas | <p>I'm plotting a pandas dataframe group by a column, and would like to visualize it as a plot bar with the value at the top of it. Most of the examples I found are not straightforward and use matplotlib directly. What is the simple way to show the row value at the top of the bar?</p>
<p>My dataframe looks like:</p>
... | <p>Try adding this nested <code>for loop</code>:</p>
<pre><code>axes = plotme.plot.bar(rot=0, subplots=True)
plt.title("Files Reloaded per Day")
plt.xlabel("Date of Reloading")
plt.ylabel("Number of Files")
for ax in axes:
for p in ax.patches:
height = p.get_height()
x, y = p.get_xy()
ax... | python|pandas|matplotlib|pandas-groupby | 3 |
362,251 | 56,787,917 | Split Column with expression in equation | <p>I have a problem that I've been trying to solve for some time. I have to use a dataset similar to CSV, and there is a column with data in the form of an equation.
Here is an example of the content of this column: </p>
<pre><code>validate employee="Claire" car="V_13" start="B02" stop="B13" start_date="21072018_09500... | <p>You could use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extractall.html" rel="nofollow noreferrer"><code>Series.str.extractall</code></a> with some subsequent manipulation of indexes and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.u... | python|pandas | 2 |
362,252 | 56,805,732 | Count instances in a dataframe | <p>I have a dataframe containing a column of values (X).</p>
<pre><code>df = pd.DataFrame({'X' : [2,3,5,2,2,3,7,2,2,7,5,2]})
</code></pre>
<p>For each row, I would like to find how many times it's value of X appears (A).</p>
<p>My expected output is:</p>
<p><a href="https://i.stack.imgur.com/m8GMr.gif" rel="nofollo... | <p>create temp column with 1 and groupby and count to get your desired answer</p>
<pre><code>df = pd.DataFrame({'X' : [2,3,5,2,2,3,7,2,2,7,5,2]})
df['temp'] = 1
df['count'] = df.groupby(['X'],as_index=False).transform(pd.Series.count)
del df['temp']
print(df)
</code></pre> | python|pandas | 1 |
362,253 | 56,797,703 | Compare 2 dataframe columns and add a new column in one dataframe as "Yes" or "No" if the cell data matches | <p>I have 2 data frames as below:</p>
<pre><code>df1(main data)
UID SG
1 A
2 B
3 C
4 D
5 E
df2
UID AN SG
1 x A
3 y C
2 z B
1 xy A
3 v C
</code></pre>
<p>Now, I want to add a new column to df1, say "isPresent". This column will have "Y... | <p>You can try this:</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'UID':[1, 2, 3, 4, 5], 'SG':['A', 'B', 'C', 'D', 'E']})
df2 = pd.DataFrame({'UID':[1, 3, 2, 1, 3], 'AN':['x', 'y', 'z', 'xy', 'v'], 'SG':['A', 'C', 'B', 'A', 'C']})
df1['isPresent'] = df1['UID'].isin(df2['UID'])
</code></pre>
<p>Alternatively... | python|pandas|dataframe | 0 |
362,254 | 56,855,334 | How would you convert a one column series to a one row series with a header? | <p>I am using Pandas and I would like to convert a series like this:</p>
<pre><code> RT_mean
0 27
1 32
2 10
3 9
.
.
.
190 89
191 6
</code></pre>
<p>to a one row dataframe with a header like this:</p>
<pre><code> RT_mean1 RT_mean2 RT_mean3 RT_mean4 ...... | <h3>Yet another approach</h3>
<pre><code>pd.DataFrame(df.to_numpy().T).add_prefix('RT_mean')
RT_mean0 RT_mean1 RT_mean2 RT_mean3 RT_mean4 RT_mean5
0 27 32 10 9 89 6
</code></pre>
<p>To maximize generality, we can <code>add_prefix</code> with the value of the first ... | python|pandas | 5 |
362,255 | 56,711,538 | How to convert the CNN model input tensor from shape ( ? , 128, 128, 3 ) to ( ? , ? , ? , 3)? | <p>I am trying to visualize the CNN model filter visualization using keras. Here is a link to code I am following <a href="https://keras.io/examples/conv_filter_visualization/" rel="nofollow noreferrer">https://keras.io/examples/conv_filter_visualization/</a>.
Note: I am new to keras and learning CNN.</p>
<p>The code ... | <p>This problem arises when normalizing gradients over different shape values.</p>
<p>The problem is with :</p>
<pre><code>grads = normalize(K.gradients(loss, conv_output)[0])
</code></pre>
<p>Change it to:</p>
<pre><code>grads = normalize(_compute_gradients(loss, [conv_output])[0])
</code></pre>
<p>If this works ... | tensorflow|keras|deep-learning | 0 |
362,256 | 56,704,700 | Select columns if any of their rows contain a certain string | <p>I am trying to obtain a list of columns in a DataFrame if any value in a column contains a string. For example in the below dataframe I would like a list of columns that have the % in the string. I am able to accomplish this using a for loop and the series.str.contains method but doens't seem optimal especially wit... | <h3><code>stack</code> with <code>any</code></h3>
<pre><code>df.columns[df.stack().str.contains('%').any(level=1)]
Index(['C', 'D'], dtype='object')
</code></pre>
<hr>
<h3>comprehension</h3>
<pre><code>[c for c in df if df[c].str.contains('%').any()]
['C', 'D']
</code></pre>
<hr>
<h3><code>filter</code></h3>
<... | python|pandas|dataframe | 14 |
362,257 | 56,469,171 | Convert Byte type into float | <p>I have a <code>numpy</code> array:</p>
<pre><code>import numpy as np
Boolval = np.array([b'false',b'true',b'false',b'false',b'false',b'false',b'false',b'false'])
</code></pre>
<p>I am trying to convert each value into the entire array with value 0 or 1 (e.g. <code>[0, 1, 0, 0, 0, 0, 0]</code>). </p>
<p>I tried th... | <p>They are not byte values, they are binary strings. Try something like</p>
<pre><code>>>> [int(b == b'true') for b in Boolval]
[0, 1, 0, 0, 0, 0, 0, 0, 0]
</code></pre>
<p>This will check if the item is equal to <code>b'true'</code> and convert the truth value (<code>True</code> or <code>False</code>) to a... | python|python-3.x|numpy | 4 |
362,258 | 56,864,159 | PyTorch batch Size suddenly reduced after n epochs | <p>I have a pytorch nn model running on win 10 cpu.
batch size is 42
After 67 iterations, a strange thing happens: batch size is suddenly reduced to 28, and I get</p>
<pre><code>RuntimeError: Expected hidden[0] size (1, 28, 256), got (1, 42, 256)
</code></pre> | <p>Is it possible the number of training examples in the dataset is not divisible by 42? Could it be that the reminder is 28?</p>
<p>If your model cannot handle online change of batch size, you should consider setting <code>drop_last=True</code> in your <a href="https://pytorch.org/docs/stable/data.html#torch.utils.da... | machine-learning|deep-learning|pytorch | 3 |
362,259 | 56,651,461 | Using tensorflow hub with go | <p>I want to use pre trained models in my go application. Especially the Inception-ResNet-v2 model.
This model seems to be only available via tensorflow hub (<a href="https://www.tensorflow.org/hub/" rel="nofollow noreferrer">https://www.tensorflow.org/hub/</a>). </p>
<p>However I could not find any documentation how ... | <p>So after a lot of work in the past few days I finally found a way. </p>
<p>At first I wanted to just use Python to do all the Tensorflow stuff and then provide the results via a rest service. However it turned out that the number of models provided by Tensorflow Hub is very small. This was a problem for me because ... | tensorflow|go|tensorflow-hub | 0 |
362,260 | 56,580,623 | Create an function from data-frame column values and insert into blank elements of another column | <p>I have a data-frame (df) which looks like:</p>
<pre><code> FHE
0 1
1 1
2 1
3
4 1
5 0.77027027
</code></pre>
<p>I am trying to create a new column called FHE_TO_USE which copies the FHE column and creates the mean of the FHE column and fills in any blanks with the m... | <p>You can use the function <code>fillna()</code>:</p>
<pre><code>df['FHE'] = pd.to_numeric(df.FHE, errors='coerce')
df['FHE_TO_USE'] = df.FHE.fillna(df.FHE.mean())
</code></pre>
<p>Result:</p>
<pre><code> FHE FHE_TO_USE
0 1.00000 1.000000
1 1.00000 1.000000
2 1.00000 1.000000
3 NaN 0.9540... | python|pandas | 1 |
362,261 | 56,462,402 | How to dynamically generate an html string using a pandas DataFrame in Python 3? | <p>I have the following dataframe column:</p>
<pre><code>print(df['keyword'])
keyword
1 ['aloe gel', 'how to plant aloe']
2 ['avocado oil hair', 'best avocado oil']
3 ['2019 hairstyles']
4 ['peel off mask', 'charcoal face mask', 'charcoal powder']
5 ['nyx eyebrow pencil', 'eyebrow wa... | <p>I believe this should do what you are looking for. If not, could you clarify?</p>
<pre><code>html = '<p style="text-align: center;"><strong>'
colors = ['40, 50, 78', '184, 49, 47']
colorIdx = 0
#iterate through rows of dataframe
for idx, row in df.iterrows():
#iterate through values in keyword colu... | python|html|string|pandas|format | 2 |
362,262 | 56,767,423 | Groupby and combine a dataframe using Vaex | <p>I have a large <code>.csv</code> file with roughly 150M rows. I can still fit the entire data set into memory and use Pandas to groupby and combine. Example...</p>
<pre><code>aggregated_df = df.groupby(["business_partner", "contract_account"]).sum()
</code></pre>
<p>In the above example the dataframe contains two ... | <p>You can find a working example in <a href="https://docs.vaex.io/en/latest/api.html#vaex.dataframe.DataFrameLocal.groupby" rel="noreferrer">https://docs.vaex.io/en/latest/api.html#vaex.dataframe.DataFrameLocal.groupby</a></p>
<p>Going with your example of grouping by 2 columns and getting a sum aggregation:</p>
<pr... | python|pandas|vaex | 8 |
362,263 | 56,859,205 | How to deal with TypeError: must be str, not float | <p>I am trying to run this</p>
<pre><code> pa['pattern'] = pa['AccessType'] + pa.groupby(['AccessedBy'])['AccessType'].shift(1)
</code></pre>
<p>but it's throwing </p>
<pre><code> TypeError: must be str, not float
</code></pre>
<p>But </p>
<pre><code>AccessedBy object
AccessType o... | <p>I think you're data might have changed:</p>
<pre><code>df = pd.DataFrame({'Group':['X']*4+['Z']*4, 'AccessType':[*'ABCDEFGH']})
df['AccessType'] + df.groupby('Group')['AccessType'].shift(1)
</code></pre>
<p>Runs fine:</p>
<pre><code>0 NaN
1 BA
2 CB
3 DC
4 NaN
5 FE
6 GF
7 HG
Name: Ac... | python|python-3.x|pandas | 1 |
362,264 | 56,827,386 | Is there a way to check if a variable is a time in hour : minute time zone format? | <p>I need help with cleaning a single column of my dataframe that contains either date or time depending on the row. I want to pull the date out and list it in a separate column for every timestamp row. How do I use iterrows, datetime, and a conditional statement to do this?</p>
<p>I'm doing a web scraping personal p... | <p>I highly recommend to use <code>dateparser</code> to convert <code>str</code> to proper <code>datetime</code> format:</p>
<pre class="lang-py prettyprint-override"><code>>>> import dateparser
>>> dateparser.parse('1 January')
datetime.datetime(2019, 1, 1, 0, 0)
>>> dateparser.parse('12:00... | python|pandas|datetime | 2 |
362,265 | 56,554,004 | FP16 not even two times faster than using FP32 in TensorRT | <p>I used TensorRT and Tensorflow model is converted to TensorRT engines in FP16 and FP32 modes.</p>
<p>Tested with 10 images and FP32 is not even two times faster than FP16 mode.
Expected minimum two times faster.
This is <a href="https://www.nvidia.com/en-us/titan/titan-rtx/" rel="nofollow noreferrer">Titan RTX spec... | <p>Titan series of graphics cards was always just a more beefed version of the consumer graphics card with a higher number of cores. Titans never had dedicated FP16 cores to allow them run faster with half-precision training. (luckly, unlike 1080s, they would not run slower with FP16).</p>
<p>This assumption is confir... | tensorflow|tensorrt | 4 |
362,266 | 56,583,080 | how to implement Grad-CAM on your own network? | <p>I want to implement Grad-CAM on my own network, should I save my model and load it, then treat my saved model like VGG-16, then do similar operations?</p>
<p>I tried to search on the internet, and I found that all methods are based on famous models, not their owns.</p>
<p>So I wonder, maybe I just need to treat my... | <p>Hi i have one solution in pytorch</p>
<pre><code>import torch
import torch.nn as nn
from torch.utils import data
from torchvision import transforms
from torchvision import datasets
import matplotlib.pyplot as plt
import numpy as np
# use the ImageNet transformation
transform = transforms.Compose([transforms.Resize(... | python-3.x|pytorch | 0 |
362,267 | 56,468,788 | list of custom class converted to numpy array | <p>I have such a class</p>
<pre><code>class Point:
def __init__(self, x,y,z):
self.x = x
self.y = y
self.z = z
</code></pre>
<p>where x,y,z are <code>float</code></p>
<p>and I want to do this:</p>
<pre><code>p = Point(0,0,0)
arr_p = np.array(p)
arr_pts = np.array([p])
</code></pre>
<p>... | <p>You can define the <code>__len__</code> and <code>__getitem__</code> method:</p>
<pre><code>class Point:
def __init__(self, x,y,z):
self.x = x
self.y = y
self.z = z
def __len__(self):
return 3
def __getitem__(self, idx):
return (self.x, self.y, self.z)[idx]
</co... | python|numpy | 2 |
362,268 | 56,750,808 | Multiply two data frames Python | <p>I have two dataframes as such:</p>
<p>Margins:</p>
<pre><code>margins = pd.DataFrame([{'balance_date': '2019-06-24', 'opp_pty_cd': 'GOODM','cur': 'KRW', 'amt':9714190.0,'acct': 30}, {'balance_date': '2019-06-24', 'opp_pty_cd': 'KIS','cur': 'KRW', 'amt':1858386321.,'acct': 30}])
</code></pre>
<p>Rate:</p>
<pre><c... | <p>I think you need first <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFrame.reindex</code></a> for add missing index and columns values (values are <code>NaN</code>s), so possible use <a href="http://pandas.pydata.org/pandas-docs/... | python|pandas|dataframe | 1 |
362,269 | 56,741,066 | Pandas Year/Month/Date Separation For Improving Relevance | <p>I am trying to use MinMaxScaler function of SKLearn on time series data, in order to use it I think I need my values to be on <code>dtype int64, float64</code> for that I can convert a separate date and time from datetime value like </p>
<pre><code> DATETIME
0 2013-02-13 00:00:00
1 2013-02... | <p>IIUC, <code>DATETIME</code> is an index, so you need:</p>
<pre><code>df['Y'] = df.index.to_series().dt.year
df['M'] = df.index.to_series().dt.month
df['D'] = df.index.to_series().dt.day
</code></pre>
<p>Output:</p>
<pre><code> Y M D
DATETIME
2013-02-13 00:00:00 2... | python|pandas|scikit-learn | 0 |
362,270 | 56,533,594 | Comparing the contents of two csv files, where the relation between the two files is specified in a third file? | <p>I have two files with sales data, and I want to validate whether the sales numbers in the first file are the same as the sales numbers in the second file. But the product ID used in each file are different. I do have a 3rd file with the the correspondence between the old product ID and the new product ID. </p>
<p>O... | <p>I'm a fan of the "do it in sql" approach, specifically, sqlite:</p>
<pre class="lang-sh prettyprint-override"><code>#!/bin/sh
oldsales="$1"
newsales="$2"
junction="$3"
# Import into database. Do once and reuse if running repeated reports on the same data
if [ ! -f sales.db ]; then
sqlite3 -batch sales.db <... | mysql|bash|pandas|csv | 3 |
362,271 | 56,654,629 | How to make the code work faster when it has a big set of data | <p>I have a data of around 1000000 rows where there are around 500 ids. I need to save the data based on the ids in different text files. Initially the ids had ':' so had to replace those with '_' while saving the txt file. Now it takes 4-5 days for the python code to finish separating those and saving in separate file... | <p>The number one rule for getting the best possible speed out of pandas dataframes and/or numpy arrays is to avoid for-loops. Instead use the built-in vectorized functions of pandas and numpy. For an in-depth explanation see <a href="https://realpython.com/fast-flexible-pandas/" rel="nofollow noreferrer">Fast, Flexibl... | python|pandas|numpy | 0 |
362,272 | 56,636,980 | Filter rows by matching partial strings from a list to a dataframe column | <p>I have a dataframe (df) with a "description" column. I would like to extract all those rows from this dataframe by identifying partial matches from a list(mylist).</p>
<pre><code>df
------------------
id description
111 abcxyz
212 ab10yz
203 abcdd9
442 ab00-z
554 a12x0z
697 a9901z
mylist... | <p>You can use regex, "DataFrame.str.contains" already can do that:</p>
<pre><code>pt = '.*?({}).*?'.format('|'.join(mlist))
df[df['description'].str.contains(pt, regex= True)]
</code></pre> | python|pandas|dataframe | 1 |
362,273 | 56,664,770 | Custom cross-entropy loss in pytorch | <p>I have done a custom implementation of the pytorch cross-entropy loss function (as I need more flexibility to be introduced later). The model I intend to train with this will need a considerable amount of time to train and the resources available can't be used to merely test if the function is correct implementation... | <p>If you need just <a href="https://pytorch.org/docs/master/nn.functional.html#torch.nn.functional.cross_entropy" rel="nofollow noreferrer">cross entropy</a> you can take the advantage PyTorch defined that.</p>
<pre><code>import torch.nn.functional as F
loss_func = F.cross_entropy
</code></pre>
<blockquote>
<p>sug... | machine-learning|artificial-intelligence|pytorch|cross-entropy | 4 |
362,274 | 56,765,781 | Conditional If Statement applied to multiple columns of dataframe | <p>I have a dataframe of minute stock returns and I would like to create a new column that is conditional on whether a return was exceeded (pos or negative), and if so that row is equal to the limit (pos or negative), otherwise equal to the last column that was checked. The example below illustrates this:</p>
<pre><co... | <p>Use:</p>
<pre><code>dict = [
{'ticker':'jpm','date': '2016-11-28','returns1': 0.02,'returns2': 0.03,'limit': 0.1,'returns3':0.02},
{ 'ticker':'ge','date': '2016-11-28','returns1': 0.2,'returns2': -0.3,'limit': 0.1,'returns3':0.6},
{'ticker':'fb', 'date': '2016-11-28','returns1': -0.02,'returns2': -0.2,'limi... | python|pandas|dataframe | 2 |
362,275 | 56,661,001 | How to proceed when the train image is too large to feed into the network once? | <p>I'm using <a href="https://github.com/voxelmorph/voxelmorph" rel="nofollow noreferrer">voxelmorph</a> to do lung image registration. But my train images are too large to feed into the network, the images have different shape, and the shapes are not regular. Some are 513,436...(not a power of 2, so I can not directly... | <p>With a U-net model it would be Ok to split the input into pieces and process them separately. </p>
<p>One thing to watch out for is the border of the image: splitting 256x256 into 4 images 128x128 might produce noticable border (a cross in the center of the image) in segmentation. To avoid that it would make sense ... | python|tensorflow|deep-learning|unet-neural-network | 0 |
362,276 | 56,864,043 | Transpose ND list of lists | <p>1.I use <code>cv2.imread</code> to read a big image in numpy array (1234*1624*3)</p>
<p>2.I use <code>cv2.dnn.blobFromImage</code> to transform it to (1,3,1234,1624) numpy array</p>
<p>3.I use <code>tolist()</code> to transform it to a 4D list in lists</p>
<p>My Problem:</p>
<p>How to transpose this list's axis ... | <p>It can be done numpy-less and purely functional but it's not pretty:</p>
<pre><code>from itertools import starmap, repeat
a = np.ones((1,3,1234,1624)).tolist()
b = list(map(list, map(map, repeat(list), map(starmap, repeat(zip), starmap(zip, a)))))
np.shape(b)
# (1, 1234, 1624, 3)
</code></pre> | python|list|numpy|transpose|cv2 | 1 |
362,277 | 56,535,156 | IndexError: range object index out of range error | <p>Hi I have following code which runs out of index. How can I fix the indexing for a matrix which can solve out of range error. </p>
<p>I have tried modifying the Filter range. But it is of no luck.</p>
<pre><code>Filters = range(0,32)
for j in MapSizes:
if MapSizes[j] == 32:
LayerMapInference[j] = r... | <p><code>range(0,32)</code> in Python is like <code>0:31</code> in MATLAB, except it's not evaluated until used (as in a <code>for</code> loop, or <code>list(range(0,32))</code>).</p>
<p>If recall MATLAB correctly, <code>LayerMapInference{j}</code> must be a <code>cell</code>, with the <code>{}</code> indexing (as opp... | python|matlab|numpy | 0 |
362,278 | 25,778,680 | Issue with reindexing a multiindex | <p>I am struggling to reindex a multiindex. Example code below:</p>
<pre><code>rng = pd.date_range('01/01/2000 00:00', '31/12/2004 23:00', freq='H')
ts = pd.Series([h.dayofyear for h in rng], index=rng)
daygrouped = ts.groupby(lambda x: x.dayofyear)
daymean = daygrouped.mean()
myindex = np.arange(1,367)
myindex = np.... | <p>First, you have to specify <code>level=0</code> instead of <code>1</code> (as it is the first level -> zero-based indexing -> 0).<br>
But, there is still a problem: the reindexing works, but does not seem to preserve the order of the provided index in the case of a MultiIndex:</p>
<pre><code>In [54]: hourmean.reind... | python|pandas | 1 |
362,279 | 25,494,858 | creating numpy array in c extension segfaults | <p>I'm just trying to start off by creating a numpy array before I even start to write my extension. Here is a super simple program:</p>
<pre><code>#include <stdio.h>
#include <iostream>
#include "Python.h"
#include "numpy/npy_common.h"
#include "numpy/ndarrayobject.h"
#include "numpy/arrayobject.h"
int m... | <p>Typical usage of <code>PyArray_SimpleNew</code> is for example</p>
<pre><code>int nd = 2;
npy_intp dims[] = {3,2};
PyObject *alpha = PyArray_SimpleNew(nd, dims, NPY_DOUBLE);
</code></pre>
<p>Note that the value of <code>nd</code> must not exceed the number of elements of array <code>dims[]</code>.</p>
<p><strong>... | python|c|numpy|python-extensions | 6 |
362,280 | 25,549,442 | Efficiently join two labels of a DataFrame index | <p>I have a DataFrame with one column of integers and string labels.
I want to join (as in sum up) two labels, while I replace the new label.</p>
<p>My DataFrame is:</p>
<pre><code>import pandas as pd
pd.DataFrame(data=np.array([1,2,3,4]), index=['a','b','c','d'], columns=['cost'])
cost
a 1
b 2
c 3
d ... | <p>don't know if there is a cleaner way but this works:</p>
<pre><code>In [157]:
df.append(pd.DataFrame(index=['c and d'], data={'cost':df.loc[df.cost.isin([3,4])].sum().values})).drop(['c','d'])
Out[157]:
cost
a 1
b 2
c and d 7
</code></pre>
<p>We construct a dataframe to append to... | python|pandas|dataframe | 2 |
362,281 | 25,597,200 | Extract Business Days in Time Series using Python/Pandas | <p>I am working with high frequency data in Time Series and <strong>I would like to get all the business days from my data</strong>. My data observations are separated by seconds, so there are 86400 seconds each day and my data set are spread over 31 days (so there are 2,678,400 observations!).</p>
<p>Here is (part) o... | <p>Unfortunately this is a little slow, but should at least give the answer you are looking for.</p>
<pre><code>#create an index of just the date portion of your index (this is the slow step)
ts_days = pd.to_datetime(ts.index.date)
#create a range of business days over that period
bdays = pd.bdate_range(start=ts.inde... | python|pandas|time-series | 3 |
362,282 | 25,526,682 | Functions to smooth a time series with known dips | <p>I have results of an Internet measurement experiment over time, as shown in the figure below. I am doing time series analysis in pandas. There are certain drops in the data, that are due to server outages. I am looking at good ways of smoothing the data.</p>
<p>Among the simpler built-in smoothing functions, <code>... | <p>I would like to add how I eventually solved this issue for anyone else interested. Foremost, after looking at a number of smoothing techniques, I eventually decided against smoothing due to the fact that it changes the data. I instead opted to filter out 10% of the points as outliers, a common technique in machine l... | python|pandas|time-series | 5 |
362,283 | 25,961,545 | Iterate over columns of a NumPy array and elements of another one? | <p>I am trying to replicate the behaviour of <code>zip(a, b)</code> in order to be able to loop simultaneously along two <code>NumPy</code> arrays. In particular, I have two arrays <code>a</code> and <code>b</code>:</p>
<pre><code>a.shape=(n,m)
b.shape=(m,)
</code></pre>
<p>I would like to get for every loop a colum... | <p>Adapting my answer in <a href="https://stackoverflow.com/questions/25096600/shallow-iteration-with-nditer/25097271#25097271">shallow iteration with nditer</a>,
<code>nditer</code> and <code>ndindex</code> can be used to iterate over rows or columns by generating indexes.</p>
<pre><code>In [19]: n,m=3,4
In [20]: a=n... | python|arrays|numpy | 1 |
362,284 | 26,218,801 | Vectorize Gradient Descent Numpy | <p>I have implemented this gradient descent in Numpy:</p>
<pre><code>def gradientDescent(X, y, theta, alpha, iterations):
m = len(y)
for i in range(iterations):
h = np.dot(X,theta)
loss = h-y
theta = theta - (alpha/m)*np.dot(X.T, loss) #update theta
return theta
</code></pre>
<p>... | <p>You can't vectorize the for loop, because each iteration is updating state. Vectorization is primarily used when the calculation can be done such that each iteration is calculating an independent (in some sense) result.</p> | numpy|vectorization|gradient-descent | 4 |
362,285 | 26,349,441 | Pandas joining based on date | <p>I'm trying to join two dataframes with dates that don't perfectly match up. For a given group/date in the left dataframe, I want to join the corresponding record from the right dataframe with the a date just before that of the left dataframe. Probably easiest to show with an example.</p>
<p>df1:</p>
<pre><code>gro... | <p>One way to do this is to create a new column in the left data frame, which will (for a given row's date) determine the value that is closest and earlier:</p>
<pre><code>df1['join_date'] = df1.date.map(lambda x: df2.date[df2.date <= x].max())
</code></pre>
<p>then a regular join or merge between <code>'join_date... | python|pandas | 1 |
362,286 | 26,310,346 | quickly calculate randomized 3D numpy array from 2D numpy array | <p>I have a 2-dimensional array of integers, we'll call it "A". </p>
<p>I want to create a 3-dimensional array "B" of all 1s and 0s such that:</p>
<ul>
<li>for any fixed (i,j) <code>sum(B[i,j,:])==A[i.j]</code>, that is, <code>B[i,j,:]</code> contains <code>A[i,j]</code> <code>1s</code> in it </li>
<li>the 1s are ran... | <p>Essentially the same idea as @JohnZwinck and @DSM, but with a <code>shuffle</code> function for shuffling a given axis:</p>
<pre><code>import numpy as np
def shuffle(a, axis=-1):
"""
Shuffle `a` in-place along the given axis.
Apply numpy.random.shuffle to the given axis of `a`.
Each one-dimensiona... | python|arrays|numpy | 4 |
362,287 | 26,322,967 | Weighted average where one weight is infinite | <p>Using NumPy's weighted average, I expected an element with infinite weighting to dominate the result, but instead it returns <code>NaN</code>,</p>
<pre><code>>>> np.average([1,2], weights=[np.inf, 1])
nan
</code></pre>
<p>Was this an intentional design? It seems counter-intuitive.</p>
<hr>
<p>EDIT: her... | <p>Though not intentional, it is mathematically correct. </p>
<p>You end up with a formula like infinity/infinity. The result depends on which infinitiy is larger. And that is nonsense.</p>
<p>You need concrete numbers as weights, so you could use very large ones. </p> | python|numpy | 3 |
362,288 | 26,307,932 | Merge pandas dataframe, with column operation | <p>I searched archive, but did not find what I wanted (probably because I don't really know what key words to use)</p>
<p>Here is my problem: I have a bunch of dataframes need to be merged; I also want to update the values of a subset of columns with the sum across the dataframes.</p>
<p>For example, I have two dataf... | <p>Only partial, not complete solution yet. But the main point is solved:</p>
<pre><code>df3 = pd.concat([df1, df2], join = "outer", axis=1)
df4 = df3.b.sum(axis=1)
</code></pre>
<p>df3 will have two 'a' columns, and two 'b' columns. the sum() function on df3.b add two 'b' columns and ignore NaNs. Now df4 has column ... | python|pandas|merge|dataframe | 0 |
362,289 | 67,180,955 | PyTorch DataLoader uses same random seed for batches run in parallel | <p>There is a <a href="https://tanelp.github.io/posts/a-bug-that-plagues-thousands-of-open-source-ml-projects/" rel="nofollow noreferrer">bug</a> in PyTorch/Numpy where when loading batches in parallel with a <code>DataLoader</code> (i.e. setting <code>num_workers > 1</code>), the same NumPy random seed is used for ... | <p>It seems this works, at least in Colab:</p>
<pre><code>dataloader = DataLoader(dataset, batch_size=1, num_workers=3,
worker_init_fn = lambda id: np.random.seed(id) )
</code></pre>
<p>EDIT:</p>
<blockquote>
<p>it produces identical output (i.e. the same problem) when iterated over epochs. – iacob</p>
</blockquot... | python|numpy|parallel-processing|pytorch|dataloader | 4 |
362,290 | 67,094,223 | values of a column to header | <p>I have the following df:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'year' : ["2020", "2019", "2018"],
'Country': ["Germany","Austria","Spain"],
'Employees': [500000, 300000, 100000]
},
... | <p>Try:</p>
<pre><code>df.pivot('Country', 'year', 'Employees')
</code></pre>
<p>Output:</p>
<pre><code>year 2018 2019 2020
Country
Austria NaN 300000.0 NaN
Germany NaN NaN 500000.0
Spain 100000.0 NaN NaN
</code></pre>
<p>with <cod... | pandas|dataframe | 0 |
362,291 | 66,869,700 | Create New DataFrame, assigning a count for each instance in a time frame | <p>Below is script for a simplified version of the df in question:</p>
<pre><code>plan_dates=pd.DataFrame({'start_date':['2021-01-01','2021-01-02','2021-01-03','2021-01-04','2021-01-05'],
'end_date': ['2021-01-03','2021-01-04','2021-02-03','2021-03-04','2021-03-05']})
plan_dates
start_da... | <p>First convert both columns to datetimes and add one day to <code>end_date</code>, then repeat index by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.repeat.html" rel="nofollow noreferrer"><code>Index.repeat</code></a> with subtraction of days and add counter values by <a href="http:... | python|pandas | 1 |
362,292 | 67,002,610 | changing the value of a field based on on the value of other fields | <p>I have a dataframe called 'qtm' that looks like the following:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Strength</th>
<th>Weakness</th>
</tr>
</thead>
<tbody>
<tr>
<td>Voltron</td>
<td>NaN</td>
<td>Flower</td>
</tr>
<tr>
<td>Joe</td>
<td>punch</td>
<td>candy</td>
</t... | <p>Add parentheses with test missing values by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isna.html" rel="nofollow noreferrer"><code>Series.isna</code></a>:</p>
<pre><code>qtm.loc[(qtm['Name'] == 'Voltron') & (qtm['Strength'].isna()), 'Strength']='Fire'
</code></pre>
<p>Or use ... | python-3.x|pandas | 1 |
362,293 | 66,772,561 | How can we do a Group By on Multiple fields and Select First or Max? | <p>I just concatenated two data frame together. That step is fine. Now I am trying to figure out how to do some kind of sort, group by, and select the first item. I think the code should be something like this (but this doesn't work).</p>
<p>First attempt:</p>
<pre><code>df_final = df_final.sort_values('location','pro... | <p>This should sort you out now that you want to keep latest date and max spending.</p>
<pre><code> df.groupby(['location', 'project_type']).max()
</code></pre> | python|python-3.x|pandas | 1 |
362,294 | 66,767,001 | Upsampling daily multi indexed data to hourly samples in Pandas | <p>I've a dataframe that looks similar to this:</p>
<pre><code> time currency rate
2021-02-22 00:00:00+00:00 USD 54410.856295
2021-02-23 00:00:00+00:00 USD 48691.894832
2021-02-24 00:00:00+00:00 USD 49849.378714
2021-02-25 00:00:00+00:00 ... | <p>Try setting <code>time</code> as index, then <code>groupby</code>:</p>
<pre><code>(df.set_index('time').groupby('currency')
.apply(lambda x: x.resample('H').ffill())
.reset_index('currency', drop=True)
.reset_index()
)
</code></pre>
<p>Output:</p>
<pre><code> time currency r... | python|pandas|dataframe | 2 |
362,295 | 67,112,351 | Can't retrieve values from numpy array | <p>I have a numpy array as follows along with a reshape:</p>
<pre><code>X = M.dot(X1) + B #prints [[value1 value2 ]]
X.reshape(2,1)
</code></pre>
<p>I am then trying to plot this point along with others as follows:</p>
<pre><code>plt.plot([X[0],...],[X[1],...],'-og','LineWidth',2)
</code></pre>
<p>However, I can't ret... | <p>Note: <code>.reshape</code> does not work in place but instead returns something. Your Original <code>X</code> has shape <code>(1 ,2)</code>. In your plot statement <code>X[1]</code> does access the row with index 1 (i.e. the "second" row) – which does not exist.</p>
<p>Anyway, try</p>
<pre><code>X = X.squ... | python|numpy | 1 |
362,296 | 67,167,051 | Python List Duplication | <p>I'm fairly new to Python and StackOverflow, so forgive me for my terrible formatting. I had a question about duplicating rows in a DataFrame. I have a data set that looks like this.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>WEIGHT</th>
<th>AGE</th>
<th>DEBT</th>
<th>ASSETS</th>
</t... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.repeat.html#pandas-index-repeat" rel="noreferrer"><code>Index.repeat</code></a> and then reindex the dataframe:</p>
<pre><code>print(df.reindex(df.index.repeat(df["WEIGHT"])))
</code></pre>
<p>Prints:</p>
<pre clas... | python|pandas|duplicates | 6 |
362,297 | 67,114,822 | New column in dataset based em last value of item | <p>I have this dataset</p>
<pre><code>In [4]: df = pd.DataFrame({'A':[1, 2, 3, 4, 5]})
In [5]: df
Out[5]:
A
0 1
1 2
2 3
3 4
4 5
</code></pre>
<p>I want to add a new column in dataset based em last value of item, like this</p>
<div class="s-table-container">
<table class="s-tabl... | <p>With your shown samples, could you please try following. You could use <code>shift</code> function to get the new column which will move all elements of given column into new column with a NaN in first element.</p>
<pre><code>import pandas as pd
df['New_Col'] = df['A'].shift()
</code></pre>
<p><em><strong>OR</strong... | python|pandas | 2 |
362,298 | 66,847,118 | Efficient way of marking duplicates (except first) based on a subset of columns in BigQuery | <p>So I have a dataset which looks like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>user_ID</th>
<th>order_ID</th>
<th>order_start_date</th>
<th>is_returning?</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1234</td>
<td>23-Mar-2021</td>
<td>0</td>
</tr>
<tr>
<td>2</td>
<td>1235</td>
<... | <p>In BigQuery this can be achieved with analytic functions like <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/analytic-function-concepts#numbering_function_concepts" rel="nofollow noreferrer">row_number</a>:</p>
<pre><code>with my_table as (
select 1 as user_id, 1234 as order_id union all
... | pandas|google-bigquery|etl | 1 |
362,299 | 67,148,839 | how to get Unique count from a DataFrame in case of duplicate index | <p>I am working on a dataframe. Data in the image</p>
<p>Q. I want the number of shows released per year but if I'm applying count() function, it's giving me 6 instead of 3. Could anyone suggest how do I get the correct value count.</p>
<p><a href="https://i.stack.imgur.com/1q38J.png" rel="nofollow noreferrer"><img src... | <p>To get unique value of single year, you can use</p>
<pre class="lang-py prettyprint-override"><code>count = len(df.loc[df['release_year'] == 1945, 'show_id'].unique())
# or
count = df.loc[df['release_year'] == 1945, 'show_id'].nunique()
</code></pre>
<p>To summarize unique value of dataframe by year, you can <a hr... | python|pandas|data-analysis | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.