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
367,500
40,916,624
How to create a new column to a pandas dataframe that was created after using apply()?
<p>After I read a excel file:</p> <p>import pandas as pd</p> <p>In:</p> <pre><code>df = pd.read_excel('file.xlsx') df = df.drop('Unnamed: 0', 1) df </code></pre> <p>Out:</p> <pre><code> A B C D E 0 2345 typeA NO http://www.example.com/... 2 23423 483 NO http://www.example.com/... 3 23...
<blockquote> <p>Then I did: df = df[df.E == 'OK'] and df = df.loc[df.E =='OK']</p> </blockquote> <p>This is not doing what you think it is. Reassigning <code>df</code> to a slice or view of <code>df</code> doesn't make it not a slice or view of <code>df</code>, it just makes it so you can't refer to the original <c...
python|python-3.x|pandas|numpy
2
367,501
54,057,112
Indexing the max elements in a multidimensional tensor in PyTorch
<p>I'm trying to index the maximum elements along the last dimension in a multidimensional tensor. For example, say I have a tensor</p> <pre><code>A = torch.randn((5, 2, 3)) _, idx = torch.max(A, dim=2) </code></pre> <p>Here idx stores the maximum indices, which may look something like</p> <pre><code>&gt;&gt;&gt;&gt...
<p>You can use <a href="https://pytorch.org/docs/stable/torch.html#torch.meshgrid" rel="nofollow noreferrer"><code>torch.meshgrid</code></a> to create an index tuple:</p> <pre><code>&gt;&gt;&gt; index_tuple = torch.meshgrid([torch.arange(x) for x in A.size()[:-1]]) + (idx,) &gt;&gt;&gt; B = torch.zeros_like(A) &gt;&gt...
python|multidimensional-array|deep-learning|pytorch|tensor
5
367,502
53,905,111
Unable to detect multiple faces at a time
<p>For some reason, I'm not able to detect multiple faces at a time. It's only detecting one face at one time. How do i resolve this issue? I've added the code below. I've used google's facenet for real time face recognition. </p> <p>In the video output it creates a bounding box only on one face at a time. But in the ...
<p>Threshold accuracy should be between <code>0 to 1</code>. Make sure Your threshold accuracy has to be <code>&gt;0.60</code>.</p>
tensorflow|face-recognition|face
0
367,503
53,830,737
Why Keras produces dimension error during denses with my code?
<p>Hello I am currently making some simple NN but there are some problems that I don't know why.</p> <p>The code looks like this</p> <pre><code>import csv import numpy as np np.random.seed(123) # for reproducibility from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten fro...
<p>Your input dim id 1. First number in (863, 1) is a number of samples. </p> <p>Error message </p> <blockquote> <p>expected dense_1_input to have 3 dimensions, but got array with shape (863, 1)</p> </blockquote> <p>suggests that your input is a list of 863 float numbers shaped (1,) please try to change the inpu...
python|tensorflow|keras
0
367,504
54,058,012
How can I get the weights from a neural network and ensure they are still trainable?
<p>I'm trying to train a neural network with an objective function made up of error and regularisation.</p> <p>In order to do the regularisation, I want to get all of the weights as a 1D tensor (call this tensor <code>weights</code>), perform some operations, and add this to the objective function. How do I get the we...
<p>In your case, I highly recommend you defining weights and layers using the very basic operation like</p> <pre><code>weights = { 'h1': tf.Variable(tf.random_normal([num_input, n_hidden_1])), 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_hidden_2, num_classes]))...
python-3.x|tensorflow|neural-network
0
367,505
54,076,782
How to update one dataframe using values from another dataframe in pandas
<p>I have two <code>df</code>s, <code>df1</code> is like,</p> <pre><code>primary_key code amount 220492763 763 32.41 213274768 764 23.41 226835769 766 88.41 224874836 7766 100.31 219074759 74836 111.33 </code></pre> <p><code>df2</code> is like,</p> <pre><code>primary_k...
<p>Use <code>pd.concat</code>, <code>drop_duplicates</code>, and <code>reindex</code>:</p> <pre><code>idx=pd.concat([df1.primary_key,df2.primary_key]).drop_duplicates() pd.concat([df2,df1]).drop_duplicates('primary_key').set_index('primary_key').reindex(idx).reset_index() </code></pre> <p>Output:</p> <pre><code> p...
python|python-3.x|pandas|dataframe
2
367,506
54,232,069
How to ignore max and min of rows when applying describe function to pandas groupby
<p>I am using pandas <code>groupby</code> function and trying to get the description of the grouped results, but without each group's maximum and minimum row. I can't find the right answer to my question.</p> <pre><code>data = {'class': ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b'], 'num': [-10,18,12,15,50...
<p>Using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.transform.html" rel="noreferrer"><code>transform</code></a> and masking:</p> <pre><code>df['max']=df.groupby('class')['num'].transform('max') df['min']=df.groupby('class')['num'].transform('min') mask = df['num'].ne(df['min'])&a...
python|pandas|dataframe|pandas-groupby
5
367,507
53,884,165
How do I plot xtick values for my bar chart?
<p>I don't understand how do I plot xticks on my graph. I want to use the 'Sport' column of my dataframe as my xticks value. </p> <p>Data is in the image. </p> <pre><code>div1['Athletes'] = pd.to_numeric(div1.Athletes.str.replace(',', '')) ax = div1[['Sport','Athletes']].plot(kind='bar', title="Number of Athletes in ...
<p>Your <code>Athletes</code> series contains types which are <em>not</em> strings. If you are sure some of these values <em>are</em> strings, you can convert to <code>str</code> first before using the <code>.str</code> accessor:</p> <pre><code>div1['Athletes'] = pd.to_numeric(div1['Athletes'].astype(str).str.replace(...
python|pandas|dataframe|matplotlib
0
367,508
54,155,562
How can I increase the size of the table?
<p>I'm trying to display a pandas dataframe as an image, but when I use plt.show(), I got a small picture of the table, inside a big (invisible) subplot, occupying 90% of the generated window.</p> <p>I used this code:</p> <pre><code> # ... ax = plt.subplot() ax.xaxis.set_visible(False) ax.yaxis.set_v...
<p>Based on <a href="https://stackoverflow.com/questions/15514005/how-to-change-the-tables-fontsize-with-matplotlib-pyplot">this</a> post, you can scale the whole table with</p> <pre><code>tb = table(ax, coeficientes_real_2, colWidths=[0.1, 0.1, 0.1], loc='center') tb.scale(2,2) </code></pre> <p>Or change the column ...
python|pandas|matplotlib|matplotlib-table
3
367,509
53,839,780
How to filter MultiIndex dataframe based on 1st level max values?
<p>I have the following dataframe <code>s</code>:</p> <pre><code>arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], [1, 2, 1, 2, 1, 2, 3, 2,]] tuples = list(zip(*arrays)) index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) s = pd.Series(np.random.randn(8), index=index) firs...
<p>Use <code>idxmax</code> and boolean indexing:</p> <pre><code>s[s.groupby(level=0).idxmax()] </code></pre> <p>Output:</p> <pre><code>first second bar 2 0.482328 baz 1 0.244788 foo 2 1.310233 qux 2 0.297813 dtype: float64 </code></pre>
python|python-3.x|pandas|dataframe
4
367,510
53,866,549
Integrating tensorflow objection detection api with centroid tracking algorithm of opencv
<p>I am using object detection tutorial api to detect objects. So far it has been working fine. Now I am trying to integrate <a href="https://www.pyimagesearch.com/2018/07/23/simple-object-tracking-with-opencv/" rel="nofollow noreferrer">centroid tracking algorithm</a> with the object detection api. To give a brief on ...
<p>Please note tensorflow gives normalised co-ordinate values. You have to multiply them with height &amp; width of frame: xmin * frame.shape[1], ymin * frame.shape[0], xmax * frame.shape[1], ymax * frame.shape[0]. This will solve your problem. Also, remember to check order of co-ordinates accepted by your tracker.</p>
python|algorithm|opencv|tensorflow
2
367,511
53,818,735
How to determine that negative values are imutable when using a lookup table in numpy
<p>I'm using a lookup table to replace the values of my matrix <code>b</code> according to an <code>a</code> array. My data is populated with a negative value (-9999) to represent "no data" for my final analysis. Because of the inverted index, my output matrix is not what I was expecting (see out: -9999 turns to 22). I...
<p>Just add the required number (9999) of dummies at the end of your lut. Then [-9999] will reference the first of these dummies and you can set it at whatever you like.</p> <pre><code>NV = -9999 a = np.asarray([[1, 11], [2, 22], [3, 33], [10000, 555]], dtype=np.int32) b = np.asarray([[0, 1, 2, 3, -9999], [0, 1, 2, 10...
python|numpy|lookup
0
367,512
53,987,885
Using TensorFlow Object Detection API with LSTM on a video
<p>I am trying to track (by detection) objects on a video. The problem is that detected objects' label changed over frames of the video. I believe using RNNs (e.g., LSTMs) may help to make labels more stable but I don't have any idea how to use the frozen model of my object detector (MobilenetV2+SSD) as input for an L...
<p>you can try this <a href="https://github.com/tensorflow/models/tree/master/research/lstm_object_detection" rel="nofollow noreferrer">https://github.com/tensorflow/models/tree/master/research/lstm_object_detection</a>. It implementation from Tensorflow mobile video object detection implementation proposed in the foll...
tensorflow|computer-vision|object-detection
3
367,513
53,941,805
Pandas groupby object unique count performance
<p>I have a large dataset of transaction data which looks like:</p> <p><code>| cust_no | acct_no | trans_id | product_id | ..... |</code></p> <p>I try several way to count how many unique accounts per customer, and how many unique products customer buy etc.</p> <ul> <li>Method 1.a</li> </ul> <p><code>transaction_df...
<p>1) Slicing requires memory assignment and/or a copy of the object depending on the operation. Here you're creating a new DataFrame before starting your operations.</p> <p>2) <code>nunique</code> is going to either implement logic for or directly call a <code>set</code>, which runs in O(N) time. <code>size</code> ...
python|pandas
0
367,514
54,020,869
How to delete continuous four digits from a column value in pandas dataframe
<p>I have a data frame like this:</p> <pre><code>col1 col2 col3 A 12134 tea2014 2 B 2013 coffee 1 1 C green 2015 tea 4 </code></pre> <p>I want to remove where the digits occurring for exact four times</p> <p>The result will look like:</p> <...
<p>You will need <code>str.replace</code> with a carefully applied regex pattern:</p> <pre><code># Thanks to @WiktorStribiżew for the improvement! df['col2'] = df['col2'].str.replace(r'(?&lt;!\d)\d{4}(?!\d)', '') df col1 col2 col3 0 A 12134 tea 2 1 B coffee 1 1 2 C green tea 4 </...
python|regex|string|pandas|dataframe
3
367,515
53,802,535
Proper use of tf.layers.MaxPooling
<p>I'm building a model in Tensorflow using <code>tf.layers</code> objects. When I run the following code using <code>tf.layers.MaxPooling2D</code> my model does not reduce in size. I've only recently switched from using Keras to Tensorflow directly so I presume I'm misunderstanding the usage.</p> <pre><code>import te...
<p>If you want to downsample by a factor of 2 your feature map, you should use a stride 2.</p> <pre><code>In [1]: tf.layers.MaxPooling2D(2, 2, padding='same')(conv) Out[1]: &lt;tf.Tensor 'max_pooling2d/MaxPool:0' shape=(20, 64, 64, 32) dtype=float32&gt; </code></pre>
python|tensorflow|layer|pooling
1
367,516
53,936,617
Writing to excel file from forecasted data
<p>So I have several csv files that I am importing in and then I use FB Prophet to give me a forecast for the coming months data. I would like all of the forecasts to go to either a different csv or all on the same one. Currently it is only writing the last csv of filenames to a csv and not doing the others.</p> <pre>...
<p>in pandas, <code>.to_csv()</code> is in write mode by default but has an option to change it. In your example, you are iterating through filenames when writing <code>to_csv()</code>, so as it is currently written, you will overwrite your current files with the results from your code. If you'd like to write these dat...
python|pandas|xlsxwriter|facebook-prophet
2
367,517
54,098,875
Count occurrences of a string in multiple string columns
<p>I have a dataframe called <code>df</code> that looks similar to this (except the number of 'mat_deliv' columns goes up to mat_deliv_8, there are several hundred clients and a number of other columns between <code>Client_ID</code> and <code>mat_deliv_1</code> - I have simplified it here).</p> <pre><code>Client_ID m...
<p>Try joining them horizontally before counting?</p> <pre><code>df['counts'] = (df.loc[:, "mat_deliv_1":"mat_deliv_4"] .fillna('') .agg(','.join, 1) .str.count('xxx')) df Client_ID mat_deliv_1 mat_deliv_2 mat_deliv_3 mat_deliv_4 counts 0 C1019876 xxx,yyy,zz...
python|string|pandas|dataframe
3
367,518
53,901,578
Finding the maximum difference for a subset of columns with pandas
<p>I have a dataframe:</p> <pre><code> A B C D E 0 a 34 55 43 aa 1 b 53 77 65 bb 2 c 23 100 34 cc 3 d 54 43 23 dd 4 e 23 67 54 ee 5 f 43 98 23 ff </code></pre> <p>I need to get the maximum difference between the column B,C and D and return the value in column A . in row '...
<p>Use <a href="https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.ptp.html" rel="noreferrer"><code>np.ptp</code></a>:</p> <pre><code># df['A'] = np.ptp(df.loc[:, 'B':'D'], axis=1) df['A'] = np.ptp(df[['B', 'C', 'D']], axis=1) df A B C D E 0 21 34 55 43 aa 1 24 53 77 65 bb 2 7...
python|pandas|numpy|dataframe
5
367,519
53,900,910
TypeError: can’t convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first
<p>I am using a <a href="https://gist.github.com/promach/186438ad7d2e6c1ec15d9ce5d8435c13/d1914a3f1da97f09ffc3ac095704b0bc9e6b2272#file-predict-py-L34-L53" rel="noreferrer">modified predict.py</a> for testing a <a href="https://gitlab.com/promach/Pruning-CNN/tree/master/SqueezeNet-Pruning" rel="noreferrer">pruned Squee...
<p>Change</p> <pre><code>index = output.data.numpy().argmax() </code></pre> <p>to</p> <pre><code>index = output.cpu().data.numpy().argmax() </code></pre> <p>This means data is first moved to cpu and then converted to numpy array.</p>
numpy|neural-network|pytorch|pruning
63
367,520
54,090,982
Can we do video data augmentation with Keras?
<p>Is it possible to apply video data augmentation on a dataset using Keras ? I know that this is a possibility for images, like it is explained <a href="https://keras.io/preprocessing/image/" rel="nofollow noreferrer">here</a>, but I didn't find the equivalent for video clips.</p> <p>My dataset contains video clips o...
<p>If you want to use ImageDataGenerator class in keras, I think you need to use <a href="https://keras.io/preprocessing/image/#apply_transform" rel="nofollow noreferrer">apply_transform</a> functions in every frame manually. For example</p> <pre><code>gen = ImageDataGenerator() for i in range(length_video): new...
python|tensorflow|keras
1
367,521
54,174,915
How are you supposed to use the `min_itemsize` parameter of `HDFStore.append`?
<p>I want to cap the size of a string column in an HDF store. You are supposed to do this with <code>min_itemsize</code>. The documentation states:</p> <blockquote> <p><strong>min_itemsize</strong></p> <p>The underlying implementation of HDFStore uses a fixed column width (itemsize) for string columns. A stri...
<p>It looks like the size of the column will be set to the largest value appended in the first DataFrame or <code>max_itemsize</code>, whichever is greater. The <a href="https://github.com/pandas-dev/pandas/blob/master/pandas/io/pytables.py" rel="nofollow noreferrer">pytables.py</a> code has some references to that log...
python|pandas|hdf5
0
367,522
54,098,284
Separating data in a column by grouping
<p>I have a multiple column dataframe and want to separate data in a particular column by grouping them based on another column. </p> <p>Here is an example:</p> <pre><code>ID Name Score 1 John 100 2 Lisa 80 3 David 75 4 Lisa 92 5 John 89 6 Lisa 72 </code></pre> <p>I wo...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow noreferrer"><code>pivot_table</code></a>. You can generate the index needed to pivot grouping the dataframe by <code>Name</code> and taking the <a href="https://pandas.pydata.org/pandas-docs/stable/gene...
python|pandas|dataframe|group-by
1
367,523
53,846,848
concat dataframes with different index
<p>I am trying to add two csv files and convert to csv.</p> <p>first.csv </p> <pre><code> index val1 val2 val3 0 19 29 30 1 29 54 30 2 87 98 90 </code></pre> <p>second.csv</p> <pre><code>val4 val5 val6 19 29 30 29 54 30 87 98 90 </code></pre> <p>When I try to add...
<p>Created data frames by doing:</p> <p>Copied following:</p> <pre><code>val1 val2 val3 19 29 30 29 54 30 87 98 90 df1=pd.read_clipboard(); val4 val5 val6 19 29 30 29 54 30 87 98 90 df2=pd.read_clipboard(); </code></pre> <p>Could you please try following.</p> <pre><code>import pandas as pd ...
python|pandas|csv|dataframe
1
367,524
53,828,290
What is the most straightforward way to convert a list of numpy arrays into a single numpy array?
<p><a href="https://i.stack.imgur.com/f9MPm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f9MPm.png" alt="enter image description here"></a></p> <p>What is the most straightforward way to convert the list to the numpy array as shown?</p> <p>I tried to to <code>numpy.asarray()</code> but it result...
<p>You are lists all have two dimensions. It seems you are looking to <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html" rel="nofollow noreferrer">flatten</a> that:</p> <pre><code>&gt;&gt;&gt; x=[[1]] &gt;&gt;&gt; y=[[2]] &gt;&gt;&gt; z=[[3]] &gt;&gt;&gt; np.array((x,y,z)).flatte...
python|numpy
1
367,525
53,813,442
Expand integer ranges in pandas DataFrame column
<p>I have a dataframe that looks like:</p> <pre><code>d = {'value': ['a','b','c','d','e','f','g', 'h'],\ 'id' : ['0101', '0208', '0103', '0405', '0105,0116,0117', '0108-0110', '0231, 0232, 0133-0150', '0155, 0152-0154, 0151']} df = pd.DataFrame(d) &gt;&gt;&gt; value id...
<p>Here's a way to do it:</p> <pre><code>s = (df['id'].str.split(r"[, ]|[-]") .apply(pd.Series) .stack() .reset_index(level=1, drop=True)) df.drop('id', axis =1).join(s.to_frame()).reset_index(drop=True) value 0 0 a 0101 1 b 0208 2 c 0103 3 d 0405 4...
python|python-3.x|pandas|dataframe
1
367,526
53,813,755
Pandas Add Column Comparison Result
<p>How can I add a comparison column (i.e. for <code>lead</code>) to my data frame, for each row in the data frame. It should takes the column mean (overall lead mean) and subtract its monthly mean. Can this be done with an <code>apply</code> and lambda using a <code>groupby</code>? </p> <p>I.e. how can I create an a...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>transform</code></a> for <code>mean</code> in new <code>Series</code> with same size like original <code>DataFrame</code> and subtract <code>mean</code> of col...
python|pandas|lambda|apply
0
367,527
53,979,750
How to split a pandas string to extract middle names?
<p>I want to split names of individuals into multiple strings. I am able to extract the first name and last name quite easily, but I have problems extracting the middle name or names as these are quite different in each scenario. </p> <p>The data would look like this:</p> <pre><code>ID| Complete_Name | ...
<p>A single <code>str.extract</code> call will work here:</p> <pre><code>p = r'^(?P&lt;Last_Name&gt;.*), (?P&lt;First_Name&gt;\S+)\b\s*(?P&lt;Middle_Name&gt;.*)' u = df.loc[df.Type == "I", 'Complete_Name'].str.extract(p) pd.concat([df, u], axis=1).fillna('') ID Complete_Name Type Last_Name First...
python|regex|string|pandas|split
6
367,528
54,238,525
Pandas to_datetime does not ignore already converted dates
<p>So my timestamp column has a mixture of both epoch(s) and milliseconds(ms) times. Setting <code>pd.to_datetime(unit='s', errors='ignore')</code> first gives this as the <a href="https://i.stack.imgur.com/Ff0zS.png" rel="nofollow noreferrer">head</a> and this as the tail <a href="https://i.stack.imgur.com/C0yP0.png" ...
<p>This is a quick hack, but you could just use the index given by a type check to convert the indexes you did not get in the first pass:</p> <pre><code>idx = [df['timestamp'].apply(lambda x: type(x)!=datetime.datetime)] df['timestamp'][idx] = pd.to_datetime(df['timestamp'], unit='ms', errors='ignore') </code></pre> ...
python|pandas
0
367,529
53,885,687
Line of best fit in python not working in np.poly
<p>I have the following data:</p> <pre><code>index value 0 0.054750 1 0.056080 2 0.054581 3 0.055538 4 0.054220 5 0.055983 6 0.055076 7 0.056457 8 0.055801 9 0.058590 10 0.057776 11 0.058401 12 0.057710 13 0.058475 14 0.057733 15 0.058544 16 ...
<p>The things work as expected for me. I am not sure how you are reading in the data.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt data = np.loadtxt('data.dat') x = data[:, 0] y = data[:, 1] fit = np.poly1d(np.polyfit(x, y, 1)) plt.plot(x, y, 'bo', label='data') plt.plot(x, fit(x), '-b', label=...
python|numpy
1
367,530
54,141,287
Group rows by two columns and filter values by comparison
<p>I am trying to:</p> <ul> <li>create a new dataframe (df2) </li> <li>this new dataframe will contain rows from df1 </li> <li>to add these rows to df2 I have been grouped the columns in df1 by month and element </li> <li>I would only select the values that exceed their monthly peers in df (for example if month 1 in d...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a> for <code>Series</code> with same size like <code>df2</code>, so possible compare, only necessary unique values of months in <code>df.index</code>:</p> <pre><code>df3 = df1[df1['...
python|pandas|pandas-groupby
4
367,531
54,174,229
Pandas DataFrame: Can't iterate over Grouped Series
<p>So I have the following Panda Series <code>grouped</code>:</p> <pre><code> Amount Ticker Unit Date Time FLWS SHARES 2019-01-03 - 20.0 2019-01-13 - 20.0 PIH SHARES 2019-01-13 - -10.0 VALUE 2019-01-03 - -25.0 </code></pre> ...
<p>The issue is that by just iterating over <code>grouped</code> itself, you iterate over the values in the Series which are just the values in the <code>Amount</code> column. Note also that <code>ticker</code>, <code>action</code>, <code>date</code>, and <code>time</code> are the indices of the Series, not its values....
python|pandas|loops|dataframe|pandas-groupby
3
367,532
53,989,741
How do I forecast variables in python using for loops?
<p>I have a pandas data frame with three columns and need to forecast them in a for loop as follows: X1 = Y prior month, X2 = Y two months ago and Y = 0.5*X1 + 0.5*X2</p> <pre><code>datetime Y X1 X2 11/15/2018 288.50 310.88 298.13 12/15/2018 265.50 288.50 310.88 1/15/2019 NaN NaN NaN 2/15/2019...
<pre><code>from numpy import NaN import pandas as pd pd.options.mode.chained_assignment = None df = pd.DataFrame({'datetime':['11/15/2018','12/15/2018','1/15/2019','2/15/2019','3/15/2019','4/15/2019' ,'5/15/2019'], 'y':[ 288.50,265.50,NaN,NaN,NaN,NaN,NaN],'x1':[ 310.88, 288.50,NaN,NaN,NaN,NaN,NaN],'x2':[ 298.13,310.88,...
python|pandas|for-loop
0
367,533
54,176,642
How do I perform a moving average in panda with a column that needs to be unique?
<p>I have a data frame like the one below:</p> <pre><code> index Player Team Matchup Game_Date WL Min PTS FGM FGA FG% 3PM 3PA 3P% FTM FTA FT% OREB DREB REB AST STL BLK TOV PF Plus_Minus Triple_Double Double_Double FPT 2PA 2PM 2P% Home_Away 276...
<p>Drawing inspiration from @jezrael's answer above, as well as the answer to another question <a href="https://stackoverflow.com/questions/54125245/how-to-add-new-column-based-on-the-above-rows-value/54147645#54147645">here</a>, here's a solution for running average by player - without the date window size constraint....
python|pandas|dataframe|moving-average
0
367,534
53,906,380
Average calculation in Python
<p>I am trying to speed up a python snippet.</p> <p>Given two equal-sized (numpy) arrays, the goal is to find the average of values in one array, say a, corresponding to the values of another array, say b. The indices of the arrays are in sync. </p> <p>For example;</p> <pre><code>a = np.array([1, 1, 1, 2, 2, 2]) b =...
<p>You can go over the list once:</p> <pre><code>means_dict = {} for i in range(len(a)): val = a[i] n = b[i] if val not in means_dict.keys(): means_dict[val] = np.array([0.0,0.0]) arr = means_dict[val] arr[0] = arr[0] * (arr[1] / (arr[1] + 1)) + n * (1 / (arr[1] + 1)) arr[1] = arr[1] + ...
python|performance|numpy|average
1
367,535
53,945,540
Error while importing numpy on Eclipse with PyDev
<p>I'm trying to import numpy on Eclipse with PyDev, and I got this:</p> <pre class="lang-none prettyprint-override"><code>ImportError: Importing the multiarray numpy extension module failed. Most likely you are trying to import a failed build of numpy. If you're working with a numpy git repo, try git clean -xdf (...
<p>It is better to use numpy on Python 2.7. Install Python 2.7 and pip install numpy on it. There might be some distribution issues or compatibility issues of numpy with Python 3.7</p>
python|eclipse|git|numpy
0
367,536
54,044,022
Reading data from CSV into dataframe with multiple delimiters efficiently
<p>I have an awkward CSV file which has multiple delimiters: the delimiter for the non-numeric part is <code>','</code>, for the numeric part <code>';'</code>. I want to construct a dataframe only out of the numeric part as efficiently as possible.</p> <p>I have made 5 attempts: among them, utilising the <code>converte...
<h3>Use a command-line tool</h3> <p>By far the most efficient solution I've found is to use a specialist command-line tool to replace <code>";"</code> with <code>","</code> and <em>then</em> read into Pandas. Pandas or pure Python solutions do not come close in terms of efficiency.</p> <p>Essentially, using CPython o...
python|pandas|performance|csv|dataframe
6
367,537
53,857,060
How to count frequencies of columns in python3 dataframe
<p>Hello guys I have a dataframe with columns that go like this. cols: </p> <ul> <li>WhiteRating(int)</li> <li>BlackRating(int)</li> <li>NewGameNinePtLead(str, determines if position is a "missedMate", "lostBigLead", "useless")</li> <li>AverageRating</li> <li>Rating_Group: <strong>X</strong> grouped rating</li> <li>l...
<p>if i understood your question correctly: you want frequency of the types of y that resulted in a lose (non-zero types), divide by the total moves of y (types of y):</p> <pre><code>import pandas as pd import numpy as np df = {'WhiteR': [1880.0,1880.0,1865.0,1880.0,1865.0,1880.0],\ 'BlackR': [1865.0,1865.0,1880.0,...
python|python-3.x|pandas
0
367,538
54,090,132
ValueError when using sklearn.linear_model.LinearRegression in Python
<p>I am trying to predict <code>y</code> values based on <code>X</code> values. I have a Excel file which has how many Siblings and Spouses a person has. The file also contains a survival outcome which is <code>y</code> (1 = Survived, 0 = Died).</p> <p>The code snippet below shows how I do this</p> <pre><code>dataSet...
<p>You need to reshape X_train and X_test before fitting like this:</p> <pre><code>X_train = X_train.reshape(1, -1) X_test = X_test.reshape(1, -1) </code></pre>
python|pandas|numpy|scikit-learn|linear-regression
1
367,539
38,342,589
faster way to replacing specific values per column, python
<p>I have a large-ish structure in as a pandas dataframe, shape = (2000, 200000) I want to replace all of the values of 2 in each column with that particular columns mean (excluding the 2 values). This is how I do it for small structures, but for larger ones it takes a significantly longer time. <code>Y</code> is the ...
<p>Since you are working with arithmetic operations, I would suggest offloading all those computations to NumPy, get the final result and create a dataframe, like so -</p> <pre><code># Extract into an array arr = Y.values # Mask to set or not-set elements in array mask = arr!=2 # Compute the mean vaalues for masked ...
python|pandas
3
367,540
38,100,191
how to make a null query selecting all the items
<p>I really like the <code>query</code> method. What is the <code>null</code> query that select all the items? I have tried <code>df.query("True")</code>, but it doesn't work.</p> <p>The only thing I have found to work is <code>df.query("index == 0 | index != 0")</code>.</p> <p>Why "True" is not working, it is a pred...
<p>For me works:</p> <pre><code>df.query("index") </code></pre> <p>Sample:</p> <pre><code>df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6]}, index=[-1,4,5]) print (df) A B -1 1 4 4 2 5 5 3 6 a = df.query("index") print (a) A B -1 1 4 4 2 5 5 3 6 </code></p...
python|pandas|indexing|dataframe
1
367,541
38,231,462
Combining pandas rows where for different columns different actions are required
<p>I am trying to combine certain rows but not with a common operation for all columns. I want the rows where pbheadid and wpadr are equal as in other row combined. Here the pickqty should be summed and the other columns should be copy pasted from the last entry or the highest pickdtm, but it is sorted so last entry wi...
<p>IIUC you can do this:</p> <pre><code>In [21]: (df.groupby(['pbheadid','wpadr']) ....: .agg({'pickqty':'sum', 'artid':'last', 'pbcarid':'last', 'pickdtm':'last'}) ....: .reset_index() ....: ) Out[21]: pbheadid wpadr artid pickqty pbcarid pickdtm 0 76079450 523-370p 370944 1 61...
python|pandas
1
367,542
38,369,424
Groupby, transpose and append in Pandas?
<p>I have a dataframe which looks like this:</p> <blockquote> <p><a href="https://i.stack.imgur.com/PuLyM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PuLyM.png" alt="enter image description here"></a></p> </blockquote> <p>Each user has 10 records. Now, I want to create a dataframe which looks like thi...
<p><code>groupby('userid')</code> then <code>reset_index</code> within each group to enumerate consistently across groups. Then <code>unstack</code> to get columns.</p> <pre><code>df.groupby('userid')['name'].apply(lambda df: df.reset_index(drop=True)).unstack() </code></pre> <h3>Demonstration</h3> <pre><code>df = p...
python-3.x|pandas|group-by|pandas-groupby
18
367,543
38,368,759
Pandas: group by column and count repetitions
<p>I'm having some problems obtaining a dataframe from another one.</p> <p>Summarizing, I have this dataframe:</p> <pre><code>Word | ... | ... | Code w1 | ... | ... | 1234 w1 | ... | ... | 2345 ... w1 | ... | ... | 5678 w2 | ... | ... | 5678 w2 | ... | ... | 1234 ... wXX | ... | ... | YYYY </code></pre> <p>I...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a> with <code>aggfunc=len</code>:</p> <pre><code>print (df) Word Code 0 w1 1234 1 w1 2345 2 w1 5678 3 w2 5678 4 w2 1234 df = df.pivot_table(index='Code', colum...
python|pandas|group-by
1
367,544
38,404,793
Numpy using smaller 2D array to map with bigger array with more elements
<p>I have a smaller array as:</p> <pre><code>A = np.array([2011, 2014, 2015, 2016, 2017]) Aval = np.array([14, 10, 35, 40, 45]) </code></pre> <p>I have another array:</p> <pre><code>A2 = np.array([2013, 2014, 2015, 2014, 2015, 2016, 2016, 2016, 2017]) </code></pre> <p>I want to create A2val such that:</p> <pre><co...
<p>Here is one way:</p> <pre><code>&gt;&gt;&gt; Aval[np.searchsorted(A, A2[np.nonzero(np.in1d(A2, A))[0]])] array([10, 35, 10, 35, 40, 40, 40, 45]) </code></pre> <p>Note that for getting the expected indices in default order the second array that you pass to <code>searchsorted()</code> should be contain the common it...
python|numpy
4
367,545
38,228,090
Line plot in pandas series generates extra indices
<p>I have a Pandas series as follows:</p> <pre><code>2014 5668 2015 6024 2016 3903 Name: year, dtype: int64 </code></pre> <p>I try to plot a line graph where x axis labels are years, and y axis labels are corresponding values. I do this:</p> <pre><code>ax = year_counts.plot(kind='line', figsize=[10, 5], mar...
<p>Why don't you simply specify the columns you like to plot in your <code>year_counts.plot()</code>? For example:</p> <pre><code>import pandas as pd data = [[2014, 5668], [2015, 6024], [2016, 3903]] df = pd.DataFrame(data, columns=['years','value']) df.plot('years', 'value') </code></pre>
python|pandas|matplotlib
0
367,546
38,232,417
tensorflow fully connected control flow per n-epoch summary
<p>When I don't use queues, I like to tally the loss, accuracy, ppv etc during an epoch of training and submit that tf.summary at the end of every epoch.</p> <p>I'm not sure how to replicate this behavior with queues. Is there a signal I can listen to for when an epoch is complete?</p> <p>(version 0.9)</p> <p>A typi...
<p><strong>EDIT</strong> Changed to account for edits to the question.</p> <p>An epoch is not something that is a built-in or 'known' to TensorFlow. You have to keep track of the epochs in your training loop and run the summary ops at the end of an epoch. A pseudo code like the following should work :</p> <pre><code>...
python-2.7|tensorflow|control-flow
-1
367,547
38,149,827
Text interpreted as boolean
<p>I am using pandas with read_csv. It interprets strings as boolean if all values are either "true" or "false". How can I prevent this?</p> <p>My <code>data.csv</code> file content:</p> <pre><code>String1,String2 true,false true,false true,true </code></pre> <p>Code</p> <pre><code>import pandas df = pandas.read_cs...
<p>You can pass the dtype parameter as object:</p> <pre><code>df = pd.read_csv("test.csv", dtype="O") </code></pre> <p>This will treat all columns as objects. If you want to apply this only to those particular columns, you can pass a dictionary:</p> <pre><code>df = pd.read_csv("test.csv", dtype={"String1": "O", "Str...
python|python-3.x|pandas
2
367,548
38,502,474
Pandas DatetimeIndex NonExistentTimeError only when creating MultiIndex
<p>I have a <code>list</code> of data that has been read from MongoDB. A subset of the data can be found in <a href="https://gist.githubusercontent.com/philipobrien/280aa38cf024949d33c88fa903ffcb00/raw/1baad587704dfad32b539343b1ab2bffe9ccd9ab/Pandas%2520DatetimeIndex%2520Sample%2520Data" rel="nofollow noreferrer">this ...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow"><code>sort_index</code></a> first and then append column <code>ID</code> to <code>index</code>:</p> <pre><code>frame = frame.sort_index() frame.set_index('ID', append=True, inplace=True) print (f...
python|datetime|pandas|dataframe
1
367,549
38,258,842
How to upgrade numpy without changing linux distributions in ubuntu
<p>I have numpy 1.11 on my 15.10 Ubuntu machine and I need the same version on my 12.04 machine. I am not sure if this is possible at all and do not understand enough of linux to know.</p> <p>I have tried </p> <pre><code>sudo pip install numpy --upgrade sudo apt-get dist-upgrade </code></pre> <p>I tried reinstallin...
<p>What happens when you run </p> <pre><code>sudo pip install numpy --upgrade </code></pre> <p>? </p> <p>When I run it, I get this: </p> <pre><code>Does it Collecting numpy Downloading numpy-1.11.1.zip (4.7MB) 100% |████████████████████████████████| 4.7MB 108kB/s Installing collected packages: numpy Found ...
python|linux|ubuntu|numpy
3
367,550
38,406,434
Casting python list to numpy array gives the wrong shape
<p>I am reading data from a file, like so:</p> <pre><code>f = open('some/file/path') data = f.read().split('\n') </code></pre> <p>Which gives me something like <code>data = ['1 a #', '3 e &amp;']</code> if the original file was</p> <blockquote> <p>1 a #</p> <p>3 e &amp;</p> </blockquote> <p>I need it in a form like</p>...
<p>split the strings first:</p> <pre><code>import numpy as np data = ['1 a #', '3 e &amp;'] np.array([x.split() for x in data]).T </code></pre>
python|arrays|numpy
0
367,551
38,268,842
Extremum of a weird array in numpy (python3)
<p>I have an array that looks like this:</p> <pre><code>ar=[[[678,701]], [[680,702]], [[674,710]], ...] </code></pre> <p>I have to find extrema for each of the column (i.e., for these 678,680,674... and for 701,702,710,... independently).</p> <p>I tried to access these columns with something like this:</p> <p><c...
<p>To find the extrema along particular axes, you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.max.html" rel="nofollow">the <code>axis</code> parameter</a>:</p> <pre><code>import numpy as np ar = np.array([[[678,701]], [[680,702]], [[674,710]], ]) print ar.max(axis=0) # [[68...
python|arrays|python-3.x|numpy
1
367,552
38,493,795
Comparing rows of two pandas dataframes?
<p>This is a continuation of my question. <a href="https://stackoverflow.com/questions/38267763/fastest-way-to-compare-rows-of-two-pandas-dataframes/38270174#38270174">Fastest way to compare rows of two pandas dataframes?</a></p> <p>I have two dataframes <code>A</code> and <code>B</code>: </p> <p><code>A</code> is 10...
<p>I'll stick by my initial answer but maybe explain better.</p> <p>You are asking to compare 2 pandas dataframes. Because of that, I'm going to build dataframes. I may use numpy, but my inputs and outputs will be dataframes.</p> <h3>Setup</h3> <p>You said we have a a 1000 x 500 array of ones and zeros. Let's bui...
python|pandas|numpy|dataframe
6
367,553
38,142,129
Use Apply on a SeriesGroupBy Object where conditions are met
<p>I have a DataFrame <code>df1</code>: </p> <pre><code> df1.head() = id ret eff 1469 2300 -0.010879 4480.0 328 2300 -0.000692 -4074.0 1376 2300 -0.009551 4350.0 2110 2300 -0.014013 5335.0 849 2300 -0.286490 -9460.0 </code></pre> <p>I would like to create a new colu...
<p>You can use custom function <code>f</code>, where is possible easy add <code>print</code>. So <code>x</code> is <code>Series</code> and you need compare each group by <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>. Output is <code>num...
python|pandas
4
367,554
38,276,813
numpy.where : how to delay evaluating parameters?
<p>I am using <code>numpy.where</code>, and I was wondering if there was a simply way to avoid calling the unused parameter. Example:</p> <pre><code>import numpy as np z = np.array([-2, -1, 0, 1, -2]) np.where(z!=0, 1/z, 1) </code></pre> <p>returns:</p> <pre><code>array([-0.5, -1. , 1. , 1. , -0.5]) </code></pre> ...
<p>You can also turn off the warning and turn it back on after you are done using the context manager <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.errstate.html#numpy.errstate" rel="nofollow"><code>errstate</code></a>:</p> <pre><code>with np.errstate(divide='ignore'): np.where(z!=0, 1/z, 1) <...
python|numpy|divide-by-zero
2
367,555
38,402,574
Grouping the values of all columns by index of a pandas dataframe
<p>I want to basically build a distribution of total no. of videos a user has watched. Watch is signified by 1 else 0. Users are index of the data frame. </p> <p>Assume the data is like this: </p> <pre><code>A B C User1 1 1 0 User2 0 1 0 User3 1 0 1 </code></pre> <p>I want for each use a count ...
<p>If you have duplicates in index, you can use <code>groupby</code> with double <code>sum</code>:</p> <pre><code>print (df) A B C User1 1 1 0 User1 1 1 1 User2 0 1 0 User3 1 0 1 print (df.groupby(df.index).sum().sum(1)) User1 5 User2 1 User3 2 dtype: int64 </code></pre> <p>If there are...
python|pandas
0
367,556
38,267,771
error in use of tf.app.flags
<p>I used <code>tf.app.flags</code> in my tensorflow program like this:</p> <pre><code>flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_string('model_dir', './models','Save checkpoint') . . . if __name__ == "__main__": # main() tf.app.run() </code></pre> <p>But when run my code two time it makes th...
<p>My guess is that you are working in an environment like a Jupyter/iPython notebook.</p> <p>The reason you are having this issue is that the flags data seems to be maintained within the Python session. <code>tf.app.flags.FLAGS.__getattr__('model_dir')</code> is equal to <code>./models</code> even if you reset your...
tensorflow|flags
6
367,557
38,211,862
Udacity Deep Learning Convolutional Neural Networks- TensorFlow
<p>I have been working on Udacity's course on deep learning- which I must add is great! I am very happy with the assignments so far. But there are two lines of code, that I am not quite understanding.</p> <pre><code>batch_size = 20 patch_size = 5 depth = 16 num_hidden = 64 graph = tf.Graph() with graph.as_default():...
<p>To answer [image_size // 4 * image_size // 4 * depth] part:</p> <p>The code applies convolution twice with SAME padding - </p> <pre><code>In each convolution the output image is half of input size (since stride = 2) Therefore size of output after first 2 convolution layers is : (image_size / 4) * (image_size / 4) ...
python|machine-learning|neural-network|tensorflow|deep-learning
0
367,558
38,129,097
Cython optimization
<p>I am writing a rather big simulation in Python and was hoping to get some extra performance from Cython. However, for the code below I don't seem to get all that much, even though it contains a rather large loop. Roughly 100k iterations.</p> <p>Did I make some beginners mistake or is this loop-size simply to small ...
<p>You should use compiler directives. I wrote your function in Python</p> <pre><code>import numpy as np def example_python(a, A): N = 100 B = np.zeros((3,N,N),dtype = np.complex) aux = np.sqrt(A[0]) for n in range(N): if aux[n] &gt; 1: for m in range(N): B[0,n,m] =...
python|numpy|optimization|cython
8
367,559
38,364,050
why doesn't Series.dtype return a type of datetime
<p><a href="https://i.stack.imgur.com/oRNlR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oRNlR.png" alt="enter image description here"></a></p> <p>I had a variable tradeDate 。the type of it's value is datetime.however ,when i run tradeDate.dtype ,it gives me Out[12]: dtype('O') ,why not datetim...
<p>Pandas uses numpy's datetime dtypes called <a href="https://docs.scipy.org/doc/numpy/reference/arrays.datetime.html" rel="nofollow"><code>datetime64</code></a> which is different from the datetime types in python's standard library module <a href="https://docs.python.org/3/library/datetime" rel="nofollow"><code>date...
python|numpy|pandas
1
367,560
66,063,046
How to train faster-rcnn on dataset including negative data in pytorch
<p>I am trying to train the torchvision Faster R-CNN model for object detection on my custom data. I used the code in torchvision object detection fine-tuning <a href="https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html" rel="nofollow noreferrer">tutorial</a>. But getting this error:</p> <pre><code>Exp...
<p>We need to make <strong>two changes</strong> to the Dataset Class.</p> <p><strong>1</strong>- Empty boxes are fed as:</p> <pre><code>if num_objs == 0: boxes = torch.zeros((0, 4), dtype=torch.float32) else: boxes = torch.as_tensor(boxes, dtype=torch.float32) </code></pre> <p><strong>2</strong>- Assign <code>a...
deep-learning|computer-vision|pytorch|object-detection|bounding-box
4
367,561
66,290,974
'No schema registered' in ONNX model conversion
<p>I am using kaggle notebook. I am trying to convert my pytorch model into tensorflow model to run with tensorflowJS. I used below code to convert onnx model to tensorflow model-</p> <pre><code>import onnx from onnx_tf.backend import prepare onnx_model = onnx.load(&quot;../input/onnx-model/model.onnx&quot;) tf_rep =...
<p>I faced the same issue. Uninstall the onnx-tf and run <code>pip install git+https://github.com/onnx/onnx-tensorflow.git</code>. Issue seems to be with some exception type.</p>
tensorflow|tensorflow.js|onnx
2
367,562
66,269,383
More explicit indexing
<pre><code>import torch x = torch.tensor([[10, 11], [12, 13]]) idx = torch.tensor([[0, 1, 0], [1, 1, 0]]) print(x[idx[0], idx[1]]) </code></pre> <p>It outputs <code>tensor([11, 13, 10])</code> and it's correct but is there a way to make the last row more explicit? I want something like <code>x[*idx]</code> because my t...
<p>Is this what you're looking for:</p> <pre class="lang-py prettyprint-override"><code>print(x[idx.tolist()]) </code></pre>
python|pytorch
0
367,563
66,014,580
Pandas group by rows chained across two columns
<p>I have a dataframe like this:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame([ ... ['a1', None, 1], ... ['a2', 'a1', 2], ... ['a3', 'a2', 3], ... ['b1', None, 9], ... ['b2', 'b1', 8], ... ['b3', 'b2', 7], ... ], columns=['key', 'key_prev', 'val']) &gt;&gt;&gt; df key key_prev val 0 a1 ...
<p>We can try use <code>isnull</code> with <code>cumsum</code> create the group key</p> <pre><code>out = df.groupby(df.key_prev.isnull().cumsum()).agg({'key':'first','val':'sum'}) Out[309]: key val key_prev 1 a 15 2 x 24 </code></pre>
python|pandas
2
367,564
66,230,477
How to use FasterRCNN Openimages v4?
<p>I can't seem to find any documentation on how to use this model. I am trying to use it to print out the objects that appear in a video any help would be greatly appreciated I am just starting out so go easy on me</p>
<blockquote> <p>I am trying to use it to print out the objects that appear in a video</p> </blockquote> <p>I interpret that your problem is to print out the name of the found objects.</p> <p>I don't know how you implemented where you got Fast RCNN trained on OpenImages v4. Therefore, I will give you the way with <a hre...
tensorflow|keras|tensorflow2.0|object-detection|faster-rcnn
0
367,565
66,246,603
Python - Multiple Plots in a Single Figure - Loop in DIfferent columns
<p>I'm trying to plot in a single image, multiple columns of a table.</p> <p>The idea is to optimize the process with a loop.</p> <p>It is important to note that all the columns share the same y-axis, and that the x scale varies for each column.</p> <p>The Final result should look something like this:</p> <p><a href="h...
<p>Put <code>subplots</code> outside of <code>for</code> loop:</p> <pre><code>logs = sort_values(by='y') ztop=logs.Y.min(); zbot=logs.Y.max() numcol = (logs.shape[1]) f, axes es= plt.subplots (nrows=1, ncols=numcol, sharey=True, figsize=(20,25)) for (ax, col) in zip(ax...
python|pandas|matplotlib
1
367,566
66,101,459
Map multiple columns from pandas DataFrame into one column
<p>I have a pandas DataFrame as follows:</p> <pre><code> a b 0 1 3 1 2 4 </code></pre> <p>I have a dictionary whose keys are tuples of the pandas DataFrame columns e.g.</p> <pre><code>{(1, 3) : 5, (2, 4) : 6} </code></pre> <p>I want to a create a new column in the pandas DataFrame e.g. <code>df['c']</code> based...
<p>Given your <code>DataFrame</code>, and your <code>dict</code>, you could <code>list</code> and <code>zip</code> which converts to <code>tuple</code>, then <code>map</code> your d:</p> <pre><code>df['c'] = pd.Series(list(zip(df.a,df.b))).map(d) a b c 0 1 3 5 1 2 4 6 </code></pre>
python|pandas|dataframe
4
367,567
66,019,998
How to get a processed dataset, if the processing steps are not tensor operations?
<p>I have an instance of <code>tf.data.Dataset()</code>, of images, basically, acquired this way:</p> <pre><code>import tensorflow as tf dataset = tf.keras.preprocessing.image_dataset_from_directory( data_directory, image_size = (image_height, image_width), batch_size = batch_size ) </code></pre> <p>So, th...
<p>You can iterate over small portions of the dataset with the <code>tf.data.Dataset.take()</code> method.</p> <pre><code>sub_dataset = dataset.take(10) for element in sub_dataset: # work with the image </code></pre> <p>Here is the [documentation].(<a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset...
python|image|tensorflow|tensorflow2.0|tensor
0
367,568
65,984,643
pandas merge dataframes on a condition
<p>lets say I have a parent df:</p> <p>parent_df:</p> <pre><code>id 11.0_A 121.0_B 433.0_A 32.0_A 12.0_B </code></pre> <p>and I have two other dataframes df_A and df_B.</p> <p>df_A:</p> <pre><code>id, name . . 11, abc 433, xyz 32, jkl </code></pre> <p>df_B:</p> <pre><code>id, name . . 121, mno 12, pqr </code></pre> <p...
<p>You can use <code>split</code> and <code>explode</code>, followed by a merge with the concatenation of <code>df_A</code> and <code>df_B</code>:</p> <pre class="lang-py prettyprint-override"><code>df_res = parent_df.merge( pd.concat(( pd.concat((df_A, pd.DataFrame(['A' for _ in range(len(df_A))], columns=...
python|python-3.x|pandas|dataframe
0
367,569
65,954,381
How to make a CSV file with a list and a dictionary for each list item?
<p>I have a <code>list</code> and I create a <code>dictionary</code> based on each list item, I want to write a <code>CSV</code> file as follows:</p> <pre><code>ListItem, key1, key2, key3 li1, value1, value2, value3 li2, value1, value2, value3 </code></pre> <p>This is how I try to do this, but I think my code overwrite...
<p>Since your question wasn't cleary defined, I'll write a simple example creating a csv from a dictionary in the format you asked for. The dict looks like:</p> <pre class="lang-py prettyprint-override"><code>myd = {&quot;k1&quot;:[&quot;v11&quot;,&quot;v12&quot;],&quot;k2&quot;:[&quot;v21&quot;,&quot;v22&quot;],&quot;...
python|pandas|dataframe|csv|dictionary
0
367,570
66,169,241
How to select rows where date is in index in Python Pandas DataFrame?
<p>I have DataFrame in Pythonlike below where data is in index (we can name this column &quot;date&quot;):</p> <p><a href="https://i.stack.imgur.com/TVxp1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TVxp1.png" alt="enter image description here" /></a></p> <p>and I would like to select all column ...
<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>:</p> <pre><code>df.index = pd.to_datetime(df.index, dayfirst=True) df1 = df[df.index &gt; '2020-01-01'] </code></pre> <p>Or:</p> <pre><code>df.index = pd.to_...
python|pandas|dataframe
1
367,571
65,935,762
How to reduce dimension/size of edges?
<p>I have the following dataset:</p> <pre><code> Person1 Age Person2 Wedding 0 Adam John 3 Yao Ming Green 1 Mary Abbey 5 Adam Lebron Green 2 Samuel Bradley 24 Mary Lane Orange 3 Lucas Barney 12 Julie Lime ...
<p>You could just divide the <code>Age</code> by some factor at the same creation of the <code>width</code> list, like so:</p> <pre><code>G = nx.from_pandas_edgelist(df, source='Person1', target='Person2', edge_attr='Age') plt.figure(figsize=(12,8)) pos=nx.spring_layout(G, k=0.30, iterations=20) nx.draw_networkx_nodes...
python|pandas|networkx
1
367,572
65,932,499
Is there a pythonic way of shifting pandas dataframe cells to the left, while pushing out or overwriting any nan?
<p>I have a pandas dataframe (starting_df) with nan values in the left-hand columns. I'd like to shift all values over to the left for a left-aligned dataframe. My Dataframe is 24x24, but for argument's sake, I'm just posting a 4x4 version. After some cool initial answers here, I modified the dataframe to also include ...
<p>or transpose the df and use <code>shift</code> to shift by column, when the NA num is increasing 1 by 1.</p> <pre class="lang-py prettyprint-override"><code>dfn = df.T.copy() for i, col in enumerate(dfn.columns): dfn[col] = dfn[col].shift(-i) dfn = dfn.T print(dfn) col1 col2 col3 col4 0 1.0 5.0 7.0...
python|pandas|dataframe
1
367,573
65,948,889
How to download an uploaded CSV file as excel file
<p>Here is my view function.</p> <pre><code>from flask import Flask from config import Config app = Flask(__name__) UPLOAD_FOLDER = 'filepath' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.route('/uploader', methods=['GET', 'POST']) @login_required def uploader(): f = request.files['file'] if not f: ...
<p>Ok, so I was able to download as excel by adding a new view function called downloader. I gave the option to reupload the file in the uploader link using which I routed to the downloader function. This is the downloader function.</p> <pre><code>@app.route(&quot;/downloader&quot;, methods=['GET', 'POST']) @login_requ...
python|pandas|flask
1
367,574
66,079,288
Dictionary to DataFrame in Python
<p>I checked many <a href="https://stackoverflow.com/questions/59314730/convert-dictionaries-to-dataframe">questions</a> from here but it is not totally the same as my problem.</p> <p>Let's create a dummy dictionary to describe my problem.</p> <pre><code>dictionary = {12: {1,2,4,6,8,12,16,65,13,644,653,23}, 15:{10,20,3...
<p>you can convert to series then explode:</p> <pre><code>pd.Series(dictionary).map(list).explode() </code></pre> <hr /> <pre><code>12 1 12 2 12 65 12 4 12 644 12 6 12 8 12 12 12 13 12 653 12 16 12 23 15 6 15 8 15 10 15 20 15 23 15 56 15 3...
python|pandas|numpy
5
367,575
66,126,336
Neural Network Error oscillating with each epochs, what is the acceptable margin for that?
<p>I have a multi input/output ANN, I have trained it for 1000 to 3000 ephocs but with each epochs the validation error oscilate. For example my output feature is in (mm) and the error can osiclate around 4 mm. You can see the validation loss vs epochs curve here. My question is how much oscilation is normal or there ...
<p>Fluctuation depends on your validation sample size. The lower size - the higher oscillation. Normal size is 5000 samples.</p>
tensorflow|validation|loss
0
367,576
66,271,710
Extracting hidden features from Autoencoders using Pytorch
<p>Following the tutorials in this <a href="https://medium.com/pytorch/implementing-an-autoencoder-in-pytorch-19baa22647d1" rel="nofollow noreferrer">post</a>, I am trying to train an autoencoder and extract the features from its hidden layer.</p> <p>So here are my questions:</p> <ol> <li><p>In the autoencoder class, t...
<p><code>forward</code> is the essence of your model and actually defines what the model does.</p> <p>It is implicetly called with <code>model(input)</code> during the training.</p> <p>If you are askling how to extract intermediate features after running the model, you can register a <strong>forward-hook</strong> like...
python|deep-learning|neural-network|pytorch|autoencoder
2
367,577
66,286,991
Testing my CNN on a small set of image but training has no effect
<p>I constructed a CNN to recognize 9 classes of gestures in images of 224x224x3. I try to test its functionality by training it on 16 images and see if it overfits to 100 accuracy. Here is my network</p> <pre><code> import torch.nn as nn class learn_gesture(nn.Module): def __init__(self): su...
<ol> <li><p>It seems that you are using a model named <code>overfit_model</code> where you pass <code>over_model.parameters()</code> to the optimizer:</p> <pre><code>optimizer = optim.SGD(over_model.parameters(), lr=0.001, momentum=0.9) </code></pre> <p>Should be replaced with <code>ovrefit_model.parameters()</code>.</...
python|pytorch|conv-neural-network
3
367,578
66,104,140
How to create a tf.data pipeline with multiple .npy files
<p>I have looked into other issues on this problem but could not find the exact answer, so trying from scratch:</p> <p><strong>The problem</strong></p> <p>I have multiple .npy files (X_train files) each an array of shape (n, 99, 2) - only the first dimension differs, while the remaining two are the same. Based on the n...
<p>You can try concatenating them, like this:</p> <pre><code>train_dataset = parse_file('example1.npy') # initialize train dataset for file in files[1:]: # concatenate with the remaining files train_dataset = train_dataset.concatenate(parse_file(file)) </code></pre>
python|tensorflow|keras|tensorflow-datasets|tf.data.dataset
0
367,579
66,054,551
Pandas: select multiple rows or default with new API
<p>I need to retrieve multiples rows (which could be duplicated) and if the index does not exist get a default value. An example with Series:</p> <pre class="lang-py prettyprint-override"><code>s = pd.Series(np.arange(4), index=['a', 'a', 'b', 'c']) labels = ['a', 'd', 'f'] result = s.loc[labels] result = result.fillna...
<p>Let's try <code>merge</code>:</p> <pre><code>result = (pd.DataFrame({'label':labels}) .merge(s.to_frame(name='x'), left_on='label', right_index=True, how='left') .set_index('label')['x'] ) </code></pre> <p>Output:</p> <pre><code>label a 0.0 a 1.0 d NaN f ...
pandas
2
367,580
66,077,605
unpack variable length dictionary from pandas column and create separate columns
<p>I have a pandas dataframe in which one column <code>custom</code> consists of dictionaries within a list. The list may be empty or have one or more dictionary objects within it. for example...</p> <pre><code>id custom 1 [] 2 [{'key': 'impact', 'name': 'Impact', 'value': 'abc', 'type': 'string'}, {'key...
<p>The approach is in the comments</p> <pre><code>df = pd.DataFrame({'id': [1, 2, 3], 'custom': [[], [{'key': 'impact', 'name': 'Impact', 'value': 'abc', 'type': 'string'}, {'key': 'proposed_status', 'name': 'PROPOSED Status [temporary]', 'value': 'pqr', 'type': 'string'}], [{'key': 'impact', 'name'...
python|pandas
2
367,581
66,125,236
What are the new versions of tf.placeholder() and tf.get_variable()?
<p>I'm fairly new to tensorflow, and am wondering why certain important functions are deprecated in the latest version, specifically placeholder and get_variable. For example, I wouldn't be able to do this in TF 2.0:</p> <pre><code># tf.placeholder() X = tf.placeholder(tf.float32, shape=(2,2)) Y = tf.placeholder(tf.flo...
<p>TF 2.0 has changed to an eager execution method, so instead of using sessions and passing data into them, you simply use tf as you would numpy.</p> <pre><code>Z = tf.constant([[1,1], [1,1]]) + tf.constant([[2,2], [2,2]]) </code></pre> <p>Tensorflow also has tf.Variable that defines what you might consider a placehol...
python|tensorflow
0
367,582
66,165,933
create new df from existing df in pandas - python
<p>What should be the optimized pandas command to create a new data frame from existing data frame that have only 1 column named <strong>val</strong> with the following transformation.</p> <p>Input:</p> <pre><code>1_2_3 1_2_3_4 1_2_3_4_5 </code></pre> <p>Output:</p> <pre><code>2 2_3 2_3_4 </code></pre> <p>Remove everyt...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html#pandas.Series.str.replace" rel="nofollow noreferrer"><code>str.replace</code></a> with a regex that matches characters up to and including the first <code>_</code> and from the last <code>_</code> to the end...
python|pandas
3
367,583
66,272,177
Keras: Should I use an 1D or a 2D convolutional layer in this case?
<p>Suppose that we have a dataset with N labeled instances, and each instance is a 2D matrix of 2 X M. That is, each instance has two rows, where each row is a vector of size M (M columns).</p> <p>I would like to build a NN whose first layer performs a convolution operation, with a kernel with two rows and one column. ...
<p>You want to be using a 2D CNN for this purpose. A 1D CNN will only expect 1 spatial dimension but you have 2 spatial dimensions even though you don't have any 'width' to convolve multiple times on.</p> <p>A 2D CNN expects a 4D <code>(batch, height, width, channels)</code>. Your kernel would also be 4D accordingly.</...
tensorflow|machine-learning|keras|neural-network|conv-neural-network
3
367,584
65,927,656
pd.to_datetime() with spanish locale system
<pre><code>d1 = today.strftime(&quot;%b-%y&quot;) print(&quot;d1 =&quot;, d1) d1 = ene.-21 </code></pre> <p>But the variable I want to convert in my data set is Jan-21.</p> <p>My code</p> <pre><code>data['date_text_DATE'] = pd.to_datetime(data['date_text'], format = '%b-%y') </code></pre> <p>The error I got:</p> <pre>...
<h3>EDIT: author noted in comments below the issue was due to their Python/R environment.</h3> <p>I'm not sure what you're trying to accomplish with the <code>d1</code> variable but the sample I created works fine for me.</p> <p>I suspect your column has a value within it not conforming to a date pattern. Can you share...
python|pandas|date|string-to-datetime
0
367,585
66,205,529
Unable to load an .xlsx file from my computer to Google Colab
<p>I tried a few methods that I read online, but none seem to work. I have the file locally on my machine in a xlsx form and tried the following code:</p> <pre><code>import pandas as pd import io from google.colab import files uploaded = files.upload() </code></pre> <p>Then I uploaded the file succesfully and when I t...
<p>Run this code:</p> <pre><code>import pandas as pd import numpy as np import re import io #IMPORTING from google.colab import files uploaded = files.upload() ARCHIVE = pd.read_excel('archive.xlsx') </code></pre>
pandas|dataframe|upload|google-colaboratory|xlsx
0
367,586
66,130,547
What does the difference between 'torch.backends.cudnn.deterministic=True' and 'torch.set_deterministic(True)'?
<p>My network includes 'torch.nn.MaxPool3d' which throw a RuntimeError when cudnn deterministic flag is on according to the PyTorch docs (version 1.7 - <a href="https://pytorch.org/docs/stable/generated/torch.set_deterministic.html#torch.set_deterministic" rel="nofollow noreferrer">https://pytorch.org/docs/stable/gener...
<p><code>torch.backends.cudnn.deterministic=True</code> <em>only</em> applies to CUDA convolution operations, and nothing else. Therefore, no, it will not guarantee that your training process is deterministic, since you're also using <code>torch.nn.MaxPool3d</code>, whose backward function is nondeterministic for CUDA....
pytorch|deterministic|reproducible-research
7
367,587
65,947,535
Cluster groups continuously instead of discrete - python
<p>I'm trying to cluster a group of points in a probabilistic manner. Using below, I have a single set of xy points, which are recorded in <code>X</code> and <code>Y</code>. I want to cluster into groups using a reference point, which is displayed in <code>X2</code> and <code>Y2</code>.</p> <p>With the help of an answe...
<p>In my opinion, if you want to define clusters as &quot;regions where points are close to each other&quot;, you should use <a href="https://scikit-learn.org/stable/modules/clustering.html#dbscan" rel="nofollow noreferrer">DBSCAN</a>. This clustering algorithm finds clusters by looking at regions where points are clos...
pandas|cluster-analysis
2
367,588
65,926,342
Keras Normalization for a 2d input array
<p>I am new to machine learning and trying to apply it to my problem. I have a training dataset with 44000 rows of features with shape 6, 25. I want to build a sequential model. I was wondering if there is a way to use the features without flattening it. Currently, I flatten the features to 1d array and normalize for t...
<p>I'm not sure if I understood your issue. The normalizer layer can take N-D tensor and it produces an output with the same shape, for example:</p> <pre><code>import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import numpy as np t = tf.constant(np.arange(2*3*4).reshape(2,3,4) , d...
python|tensorflow|machine-learning|keras|normalization
0
367,589
66,116,231
Print pandas column name and cell value row wise
<p>I need to split up a pandas dataframe by row into headed paragraphs. The column name is the heading and the cell value is the paragraph.</p> <p>Example df (the actual df is much longer)</p> <pre><code>data = {'Title': ['Wormwood', 'Transmetropolitan', 'Y - The last man'], 'Author': ['Ben Templesmith', 'Warren El...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>DataFrame.stack</code></a> for reshape, then remove index repeated values by first <code>reset_index</code> with <code>drop=True</code> and set new columns names:</p> <pre><code>df1 = d...
python|pandas|dataframe
2
367,590
66,187,867
How to extract 'image' and 'label' out of Tensorflow?
<p>I've loaded in my train and validation sets from CIFAR10 like so:</p> <pre><code>train = tfds.load('cifar10', split='train[:90%]', shuffle_files=True) validation = tfds.load('cifar10', split='train[-10%:]', shuffle_files=True) </code></pre> <p>I've created the architecture for my CNN</p> <pre><code>model = ... </cod...
<p>Tensorflow knows how to handle the <code>tfds</code> objects. So in your case you can just do</p> <p><code>history = model.fit(train, epochs=100, batch_size=64, validation_data=(validation, verbose=0)</code></p> <p>No need to split out the labels from the images. But if you really want to you can do the following</p...
python|tensorflow|machine-learning|conv-neural-network
0
367,591
65,967,259
Scale down image represented in a tensor
<p>I use the MNIST dataset to learn Pytorch.</p> <p>This is from the documentation to get a picture.</p> <pre><code>import torch.nn.functional as F import torch from torchvision import datasets, transforms </code></pre> <p>Tensor comes from the torchvision dataset.</p> <pre><code># Create prediction images, labels = ne...
<p>From the <a href="https://pytorch.org/docs/stable/nn.functional.html#interpolate" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p>The input dimensions are interpreted in the form: mini-batch x channels x [optional depth] x [optional height] x width.</p> </blockquote> <p>Currently the first <code>28</code> in...
python|pytorch
3
367,592
66,299,555
Pandas - How To Read From The Nth Column of a Table
<p>My code gets into a wikipedia page, and prints the table I want. However, say i want the nth, n-1, and n-2 columns of this table.</p> <p>How can i do this?</p> <pre><code>from selenium import webdriver import pandas as pd driver = webdriver.Chrome() val=[] webPage=driver.get('https://en.wikipedia.org/wiki/Economy_of...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>pandas.DataFrame.iloc</code></a></p> <pre><code>df.iloc[:, n] </code></pre> <p>For the last column, you can use</p> <pre><code>df.iloc[:, -1] </code></pre> <p>Example</p> <pre><code>&gt...
python|pandas
0
367,593
66,324,270
Python Pandas Filter By Row Contains (at any column)
<p>I'm really struggling to solve what seems like a simple problem. I'd like to filter a dataframe by rows, but the documentation &quot;How do I filter specific rows from a DataFrame&quot; is really dumb -- <a href="https://pandas.pydata.org/pandas-docs/stable/getting_started/intro_tutorials/03_subset_data.html#min-tut...
<p>Use <code>any</code> to check for validity along the rows:</p> <pre><code>df[df.eq('No').any(1)] </code></pre>
python|pandas|filter
3
367,594
66,155,194
i want to remove integers from a string but not all integers only few integers in a dataframe
<p>I have a dataframe like below:</p> <pre><code> Name Value Volume 0 2019 sai 20 21321 23 1 2020 James 12311 12 2 2018 Adi 35 4435 11 3 2017 Hello 46 32454 34 4 2019 Girl 654654 56 5 2018 surya 25 325874 89 </code></pre> <p>I want to get ...
<p>It seems that you want to remove a prefix only. You can do it like this:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame([{&quot;Name&quot; : &quot;2019 sai 20&quot;, &quot;Value&quot;:23, &quot;Volume&quot;:23}, {&quot;Name&quot; : &quot;2020 James&quot;...
python|python-3.x|pandas
1
367,595
66,127,445
get_browser function "'chromedriver'" error
<p>I have am trying to use Chromedriver for web scraping but am experiencing problems. I was able to successfully install and run chromedriver and specified the executable path using:</p> <pre><code>driver = webdriver.Chrome(&quot;/path/to/chromedriver&quot;) </code></pre> <p>I am also able to run the below code to get...
<p>You need to either add the chrome driver to your <strong><a href="https://www.reddit.com/r/learnpython/comments/9bryqd/how_to_put_chromedriver_in_path_for_using/" rel="nofollow noreferrer">system path</a></strong>, or add <code>executable_path</code> to the code - like so:</p> <p>driver = webdriver.Chrome(executable...
python|pandas|selenium|selenium-chromedriver
0
367,596
66,175,644
use of apply function to shift values of a column to another column of corresponding columns
<p>I have encountered some problems with my data that value of one column shifted to another column for the corresponding row. I need to shift back those values to its original column based on some conditions.</p> <p>I am providing a sample dataframe which describes my dataset except that my original data has 50 column...
<ul> <li>assigned back to new column <strong>A2</strong> for purpose of transparency</li> <li>used numpy <code>select()</code> with two conditions, checking B &amp; C. Assume <strong>NaN</strong> in <strong>A</strong> is zero</li> <li>given conditions, then take value from appropriate column</li> <li>default column ...
python|pandas|data-science
0
367,597
66,013,647
Check whether element of array is in row of matrix numpy
<p>I have an <code>array</code>:</p> <pre><code>a = np.array([1, 2]) </code></pre> <p>And a <code>matrix</code>:</p> <pre><code>m = np.array([[1, 2], [3, 4]]) </code></pre> <p>I want to check if <code>1</code> from <code>a</code> is in <code>[1, 2]</code> from <code>m</code> and if <code>2</code> from <code>a</code> is...
<p>I ended up using <code>broadcasting</code> of the array <code>a</code>:</p> <pre><code>a = a.reshape(2, 1) (a == m).any(axis=1) array([ True, False]) </code></pre>
python|numpy
1
367,598
66,082,426
Find different chars in strings and save their index and how they changed
<p>Ok, so i have DataFrame Col named DNA with long strings like 3k in len, and i have my reference string. Everything's the same length. I need to compare each char in each string to this refrence string and if chars are diffrent save them to a list in a way</p> <p>[<strong>refrence char</strong>, <strong>position</str...
<p>In fact, with your own code, it will be more efficient.</p> <pre><code>list_str = ['AABCDEQHS'* 300, 'LAPEDEXHS'* 300] * 1000 ctr_str = 'AXBCSEQHS'* 300 w_all = [] for x in list_str: w = [] for y in range(len(ctr_str)): if x[y] == ctr_str[y]: pass else: c = [ctr_str[y...
python|arrays|pandas|algorithm|dataframe
2
367,599
66,333,392
Python Logistic Regression Y Value Issues
<p>I'm currently getting a mixture of the following errors:</p> <ul> <li>ValueError: Unknown label type: 'unknown'</li> <li>ValueError: Expected 2D array, got 1D array instead: array=[0. 0. 0. ... 1. 1. 1.]. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if...
<p>Line 9: In your code, please note that <code>shape</code> is a tuple and a property of the <code>DataFrame</code> object, i.e., you cannot <em>call</em> it but only access it; see <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shape.html" rel="nofollow noreferrer">https://pandas...
python|sklearn-pandas
3