Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
2,700
66,468,134
any doable approach to use multiple GPUs, multiple process with tensorflow?
<p>I am using docker container to run my experiment. I have multiple GPUs available and I want to use all of them for my experiment. I mean I want to utilize all GPUs for one program. To do so, I used <code>tf.distribute.MirroredStrategy</code> that suggested on tensorflow site, but it is not working. here is the <a hr...
<h3>Is the MirrordStrategy proper way to distribute the workload</h3> <p>The approach is correct, as long as the GPUs are on the same host. The TensorFlow <a href="https://www.tensorflow.org/tutorials/distribute/keras" rel="nofollow noreferrer">manual</a> has examples how the <code>tf.distribute.MirroredStrategy</code>...
docker|tensorflow|parallel-processing|gpu
1
2,701
66,621,093
To determine total runtime from excel using python pandas
<p>I have the below columns in excel file i need to find the total runtime using python pandas.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Stage</th> <th style="text-align: center;">JobName</th> <th style="text-align: center;">BaseLineStartTime</th> <th styl...
<p>You can try something like this. If you need to column names and other things for multiple time frames, that's quite a bit more logic, but you can start here.</p> <p>This makes the assumption you can sort rows correctly and the variable names are somewhat consistent so you can use <code>groupby()</code></p> <p>See c...
python|pandas|numpy
0
2,702
66,568,948
Overwrite Frame with other Frame after comparing
<p>2 Frames and I want the 2nd Frame to &quot;overwrite&quot;/update the 1st Frame. Basically, where Table1-colB-value = Table2-oldB-value, overwrite Table1-colB-value with Table2-newB-value.</p> <p>Table1</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>colA</th> <th>colB</th> </tr> </thead...
<p>There are plenty of ways to do this, a fast way would be to convert your df2 to <code>dict</code>, using oldB column as your keys, and then <code>map</code>it on your colB in df1:</p> <pre><code>d = dict(zip(df2.oldB, df2.newB)) df1['new_colB'] = df1['colB'].map(d) </code></pre> <p>Will get back</p> <pre><code> co...
python|pandas
2
2,703
66,350,225
Select rows in a numpy array where there are no "holes", the holes being 0 (example ...,1,0,1,...)
<p>How can I select rows in a numpy array where there are no &quot;holes&quot;, the holes being 0. For example, if I my input is :</p> <pre><code>M = np.array([[0,10,0,20,30],[15,0,0,25,35],[0,40,40,40,0],[50,0,50,0,50]]) </code></pre> <p>I would like the output to be :</p> <pre><code>M = np.array([[15,0,0,25,35],[0,40...
<p>To detect a &quot;hole&quot; in a row, define the following function:</p> <pre><code>def hasHole(row): wrk = np.vstack([np.roll(row, -1), (row == 0).astype(int), np.roll(row, 1)])[:, 1:-1] return np.not_equal(wrk, 0).all(0).any() </code></pre> <p>Then, to find boolean indices of rows with holes, run:</p> <pr...
python|arrays|numpy|select|filter
1
2,704
66,696,564
How can I slice a TF dataset so that there's 500 negative examples and 500 positive examples? (IMDB dataset)
<p>I have the following dataset:</p> <pre><code>train = tf.keras.preprocessing.text_dataset_from_directory( 'aclImdb/train', batch_size=64, validation_split=0.2, subset='training', seed=123) test = tf.keras.preprocessing.text_dataset_from_directory( 'aclImdb/train', batch_size=64, validation_split=0.2, ...
<p>As you will have dataset of the type <code>tf.data.Dataset</code>, this makes everything a lot easier. You will first have to filter from the training and the validation dataset the positive and the negative examples and then take the 500.</p> <p>I will do some considerations as follows, I will use the IMDB dataset ...
python|tensorflow|dataset|tensorflow-datasets
1
2,705
70,915,528
New to Pandas - Indexing
<p>I have loaded a .CSV value into pandas dataframe (with pd.read_csv) in Jupyter and trying to replace a NaN value with boolean value 'False'.I was able to identify the row where given nan value is by: <br></p> <p><code>dataframe[dataframe['columnname'].isnull()] </code><br></p> <p>However now i am getting trobules ch...
<p>You have to read <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html" rel="nofollow noreferrer">Index and selecting data</a>:</p> <blockquote> <p>dataframe[dataframe['columnname'].isnull()].fillna('False') - fills in every NAN value in row with 'False', instead of filling in one cell</p> <...
python|pandas|dataframe
0
2,706
71,079,012
Design pattern - Python function applied to different objects
<p>I have modified Numpy's <a href="https://numpy.org/doc/stable/reference/generated/numpy.apply_along_axis.html" rel="nofollow noreferrer"><code>apply_along_axis()</code></a> function and I want to be able to use this function on different objects (such as <code>xarray.DataArray</code> and other multi-dimensional data...
<p>Just to highlight a couple of features in the function.</p> <p>First make a view that has <code>axis</code> last:</p> <pre><code>inarr_view = np.transpose(arr, in_dims[:axis] + in_dims[axis+1:] + [axis]) </code></pre> <p>Then make an iterator - on all axes except the last one:</p> <pre><code>inds = iter(ndindex(inar...
python|numpy|design-patterns|wrapper
0
2,707
70,850,236
How to adjust row height with pandas Styler
<p>I have a styled pandas DataFrame that I want to export to HTML with smaller rows than default. I don't know much about CSS so I haven't found a way to make it work so far. Can it be achieved and if so, how?</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({&quot;foo&quot;: [...
<p>Set the styles for row and data cell line height and reset the padding</p> <pre><code>styler.set_table_styles([ {&quot;selector&quot;: &quot;tr&quot;, &quot;props&quot;: &quot;line-height: 12px;&quot;}, {&quot;selector&quot;: &quot;td,th&quot;, &quot;props&quot;: &quot;line-height: inherit; padding: 0;&quot;...
python|html|css|pandas
2
2,708
70,821,976
Efficiency of ordering the elements of a numpy array, by occurrences in a different array
<p>I have the following code:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np def suborder(x, y): pos = np.in1d(x, y, assume_unique=True) return x[pos] </code></pre> <p><code>x</code> and <code>y</code> are 1d numpy integer arrays, and the elements of <code>y</code> are a subset of those...
<p><code>in1d</code> starts with:</p> <pre><code>if len(ar2) &lt; 10 * len(ar1) ** 0.145 or contains_object: ... mask = np.zeros(len(ar1), dtype=bool) for a in ar2: mask |= (ar1 == a) return mask </code></pre> <p>In other words it does an equality test for eac...
python|numpy
0
2,709
51,564,118
Convert string to pandas dataframe
<pre><code>import pandas as pd from StringIO import StringIO msg1 = '" feature1 feature2 UIN Comop YYYYMM Sales Month grain\\n0 212 212 F1230901 220ES 201202 212 2 F1230901220ES\\n"' def result_trans(res_str): print res_str res_str = StringIO(res_str) par...
<p>IIUC, use <code>pd.read_table</code></p> <pre><code>msg1 = '" feature1 feature2 UIN Comop YYYYMM Sales Month grain\n0 212 212 F1230901 220ES 201202 212 2 F1230901220ES\\n"' pd.read_table(sio(msg1.strip('""').replace('\\n','\n')), delim_whitespace=True) </code></pre...
python|pandas
0
2,710
35,806,305
Build an ever growing 3D numpy array
<p>I have a function (<code>MyFunct(X)</code>) that, depending on the value of <code>X</code>, will return <em>either</em> a 3D numpy array (e.g <code>np.ones((5,2,3))</code> or an empty array (<code>np.array([])</code>). </p> <pre><code>RetVal = MyFunct(X) # RetVal can be np.array([]) or np.ones((5,2,3)) </code></pre...
<p>You can reshape arrays to compatible shape :</p> <pre><code>concatenate([MyFunct(X).reshape((-1,2,3)) for X in values]) </code></pre> <p>Example :</p> <pre><code>In [2]: def MyFunc(X): return ones((5,2,3)) if X%2 else array([]) In [3]: concatenate([MyFunc(X).reshape((-1,2,3)) for X in range(6)]).shape Out[3]: (1...
python|arrays|numpy
1
2,711
37,307,616
convert indices into corresponding pandas dataframe values
<p>I have a matrix of indices, I'd like to get the same matrix filled with values taken from pandas dataframe predefined column corresponding to the index on a given position. </p> <p>For example, index matrix</p> <pre><code>[[0 1 2] [1 0 2] [2 1 3] [3 4 2]] </code></pre> <p>pd.DataFrame["id"]:</p> <pre><code>10...
<h1>Setup</h1> <p><code>i_s</code> is a list of list. This works equally well if it were a numpy array.</p> <pre><code>i_s = [[0, 1, 2], [1, 0, 2], [2, 1, 3], [3, 4, 2]] s = pd.DataFrame([100, 200, 300, 400, 500, 600, 700, 800, 900]) </code></pre> <p><code>s</code> does not have to be a <code>...
python|pandas
0
2,712
37,439,014
Possible for pandas dataframe to be rendered in a new window?
<p>We all love using pandas and how the dataframe shows us a snippet of the data. However within the ipython notebook, sometimes it is difficult to view all the data especially if it contains too many columns.</p> <p>Was just wondering if there is an option to view the dataframe in a new window like Matplotlib when it...
<p>You can create a temporary file containing HTML of the whole table, and then use the <code>webbrowser</code> module to open in. It would probably be best to simply create a function for displaying data frames in a new window:</p> <pre><code>import webbrowser import pandas as pd from tempfile import NamedTemporaryFi...
python|pandas
3
2,713
37,305,370
create multiple columns from 1 column pandas
<p>I am trying to duplicate a column multiple time from a df such as</p> <pre><code>df.head() close date 2015-09-23 17:00:00 1.3324 2015-09-23 17:01:00 1.3325 2015-09-23 17:02:00 1.3323 2015-09-23 17:03:00 1.3323 2015-09-23 17:04:00 1.3323 </code></pre> <p>from a cer...
<p>The simplest way would be to iterate through your list and create a new column for each key (side note: you should probably avoid using <code>list</code> as the name of a variable, since you'll overwrite the native <code>list</code>):</p> <pre><code>keys = ['a','b','c'] for k in keys: df[k] = df['close'] </code...
python|pandas|multiple-columns
3
2,714
37,718,584
Removing outliers automatically in pandas data frame
<p>I have a pandas data frame:</p> <pre><code>data = pd.read_csv(path) </code></pre> <p>I'm looking for a good way to remove outlier rows that have an extreme value in any of the features (I have 400 features in the data frame) before I run some prediction algorithms. </p> <p>Tried a few ways but they don't seem to ...
<p>I think you can check your output but comparing both indexes by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.difference.html" rel="nofollow"><code>Index.difference</code></a>, because I think your solution works very nice:</p> <pre><code>import pandas as pd import numpy as np np.rand...
python-2.7|pandas|outliers
0
2,715
64,425,558
I am trying to create and implement a function that identifies outliers in datasets in Python using the numpy module, keep getting 'ValueError'
<p>I am attempting to create an 'Outlier' function that detects outliers in data sets. I am then trying to call the function into a for loop but it keeps giving me a <code>ValueError</code>. I have a brief understanding of why the error occurs. It's because numpy doesn't let you set arrays as Booleans (Please correct m...
<p>I think that, rather than iterating, you could do everything inside the function without looping:</p> <pre><code>import numpy as np def detect_outliers(arr, pct_bounds=(75, 25), mulitplier=1.5): upper, lower = np.percentile(arr, pct_bounds) spread = upper - lower # Create a mask where the data are more ...
python|numpy|statistics|dataset
2
2,716
64,573,085
Python: Replace the special character by NULL in each column in pandas dataframe
<p>I have a dataframe as follows:</p> <pre><code>ID Date_Loading Date_delivery Value 001 01.11.2017 20.11.2017 200.34 002 %^&amp;**##_ 15.01.2018 300.05 003 11.12.2018 _%67* 7*7% </code></pre> <p>As we can see that except...
<p>You can specify fomrat of datetimes of input data, here <code>DD.MM.YYYY</code> by <code>'%d.%m.%Y'</code> and for convert numbers use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.html" rel="nofollow noreferrer"><code>to_numeric</code></a>:</p> <pre><code> #for processing all ...
python|pandas
0
2,717
64,249,983
UnboundLocalError: local variable 'coordi' referenced before assignment
<p>Below is a python function that detects an object and returns its bounding box coordinates:</p> <pre><code>def back_project_dilation(hist1,hist2,hsv,min_area,max_area,min_aspect,max_aspect,min_rect,max_rect): Ratio=hist1/hist2 #calculating the M_blue #spliting the target channels h,s,v = cv2.split(hsv) #bac...
<p>I solved the Problem by setting the variable &quot;coordi&quot; to global</p>
python|python-3.x|numpy|opencv|image-processing
0
2,718
47,542,212
Python: Splitting a string at any uppercase letter (as part of a rename for a column name)
<p>I would like to rename columns in a Pandas dataframe using <em>rename</em> function and therefore I would like to split the name (string) at an uppercase letter within the string. So for example my column names are something like 'FooBar' or 'SpamEggs' and one column is called 'Monty-Python'. My goal are column name...
<ol> <li>Remove anything that is not a letter</li> <li>Prepend an underscore (<code>_</code>) to uppercase letters that are not at the start of the string</li> <li>Lowercase the result</li> </ol> <pre><code>df.columns Index(['FooBar', 'SpamEggs', 'Monty-Python'], dtype='object') df.columns.str.replace('[\W]', '')\ ...
python|regex|pandas|dataframe
2
2,719
49,270,966
Create a DataFrame of combinations for each group with pandas
<p>The inputs are as follows.</p> <pre class="lang-python prettyprint-override"><code>Out[178]: group value 0 A a 1 A b 2 A c 3 A d 4 B c 5 C d 6 C e 7 C a </code></pre> <p>For this input, I want to create a combination for each group and create one D...
<p>Using <code>combinations</code> in a comprehension</p> <pre><code>from itertools import combinations pd.DataFrame([ [n, x, y] for n, g in df.groupby('group').value for x, y in combinations(g, 2) ], columns=['group', 0, 1]) group 0 1 0 A a b 1 A a c 2 A a d 3 A b c 4 A ...
python|pandas
14
2,720
49,331,882
Vectorizing a for loop with Numpy
<p>I have a for loop that I would like to vectorize with numpy. In the below snippet, <code>R</code>, <code>A</code>, and <code>done</code> are numpy arrays of length <code>num_rows</code>, while Q and Q1 are matrices of size <code>(num_rows, num_cols)</code>. Also worth noting, all elements of <code>A</code> are betwe...
<p>Your vectorized solution has all the right elements, but contains a couple of unnecessary complications. A streamlined version using advanced indexing would be:</p> <pre><code>&gt;&gt;&gt; y = Q.astype(float) &gt;&gt;&gt; D, = np.where(1-done) &gt;&gt;&gt; y[np.arange(A.size), A] = R &gt;&gt;&gt; y[D, A[D]] += gamm...
python|numpy
2
2,721
58,884,590
Estimate pandas dataframe size without loading into memory
<p>Is there a way to estimate the size a dataframe would be without loading it into memory? I already know that I do not have enough memory for the dataframe that I am trying to create but I do not know how much more memory would be required to fully create it.</p>
<p>You can calculate for one row, and estimate based on it:</p> <pre><code>data = {'name': ['Bill'], 'year': [2012], 'num_sales': [4]} df = pd.DataFrame(data, index = ['sales']) df.memory_usage(index=True).sum() #-&gt; 32 </code></pre>
python|pandas|dataframe|dask
2
2,722
70,117,098
How to add dummy rows to make number of rows equal for each column value of a particular column in pandas
<p>I have a pandas dataframe like so:</p> <pre><code>ID A B C D 1 a1 b1 c1 d1 1 a2 b2 c2 d2 1 a3 b3 c3 d3 1 a4 b4 c4 d4 1 a5 b5 c5 d5 2 a6 b6 c6 d6 2 a7 b7 c7 d7 3 a8 b8 c8 d8 </code></pre> <p>Is there some way I can add rows (with dummy values a0 b0 c0 d0 for remaining columns) for ID 2 and 3 (and others) s...
<p>Create a new dataframe with missing <code>ID</code> values then append it to your original dataframe and finally fill missing values.</p> <pre><code>out = df.append(pd.DataFrame({'ID': df['ID'].unique().repeat(5 - df['ID'].value_counts())})) \ .fillna({'A': 'a0', 'B': 'b0', 'C': 'c0', 'D': 'd0'}) \ ....
python|pandas
0
2,723
70,189,349
How to calculate the summation for values based on consecutive days and two other columns
<p>How can I do summation just for consecutive days and for the same name and same supplier? For instance, for A and Supplier Wal, I need to do summation for 2021-05-31 and 2021-06-01 and then do another summation for 2021-06-08 and 2021-06-09. I need to add a new column for summation. Please take a look at the example...
<p>Like this?</p> <pre><code>import pandas as pd df = pd.DataFrame({'Name': ['A', 'A', 'A','A','B','B','C','C','C','C','C','C','C','C','C'], 'Supplier': ['Wal', 'Wal', 'Wal', 'Wal', 'Co', 'Co', 'Mc', 'Mc', 'St', 'St', 'St', 'St', 'St', 'To', 'To'], 'Date': ['2021-05-31', '2021-06-01', '2021-06-08', '2021-06-09', '...
python|pandas|dataframe|jupyter-notebook|calculated-columns
1
2,724
56,076,205
Recognize scene with deep learning
<p>What is the approach to recognize a scene with deep learning (preferably Keras). There are many examples showing how to classify images of limited size e.g. dogs/cats hand-written letters etc. There are also some examples for the detection of a searched object within a big image.</p> <p>But, what is the best approa...
<p>In my opinion the comparison between your room-scenes and the biological scenes differ. Especially since your scene is a microscope image (probably of a limited predefined domain).</p> <p>In this case, pure classification should work (without seeing the data). In other words the neural network should be able to fig...
tensorflow|machine-learning|image-processing|keras|deep-learning
0
2,725
56,257,407
Is there a method in Pandas to check if a cell is bolded?
<p>I have a column with names. I want to build a list containing all the names from my column that are bolded. Is there a method in Pandas available to do this?</p> <pre><code>import pandas as pd df = pd.read_excel("mydatafile.xlsx") print("Column Headings:") mylist = [] for i in df.index: if df['Names'][i].cell...
<p><code>pandas</code> does not read styles from Excel. You will have to use another library that does. One such library is <a href="https://github.com/deepspace2/StyleFrame" rel="nofollow noreferrer">styleframe</a> (full disclosure, I'm one of the authors of this library).</p> <p>Then, using this code</p> <pre><code>f...
python|pandas|conditional|cell-formatting
4
2,726
56,177,013
Import data with each value containing column labels
<p>I have data in a text file with no headers. The values in each row have a label indicating which column they belong to. I want to take those labels as column names and feed the data under the columns.</p> <p>I want to import a text file containing this:</p> <pre><code>Column1=variable11&amp;Column2=variable12&amp;...
<p>I assume here that <code>Column1=variable1=21</code> on line 2 and 3 are mistakes. </p> <pre><code>df = pd.read_csv('file', header=None) df = df[0].str.split('=|&amp;', expand=True) tmp = df.loc[:,1::2].copy() tmp.columns = df.loc[:,::2].apply(lambda x: x.dropna().iloc[0]) </code></pre> <p>output</p> <pre><code>...
python|pandas|dataframe|import
1
2,727
55,675,345
Should I use softmax as output when using cross entropy loss in pytorch?
<p>I have a problem with classifying fully connected deep neural net with 2 hidden layers for <strong>MNIST dataset in pytorch</strong>.</p> <p>I want to use <strong>tanh</strong> as activations in both hidden layers, but in the end, I should use <strong>softmax</strong>.</p> <p>For the loss, I am choosing <code>nn.Cro...
<p>As stated in the <a href="https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html#torch.nn.CrossEntropyLoss" rel="nofollow noreferrer"><code>torch.nn.CrossEntropyLoss()</code></a> doc:</p> <blockquote> <p>This criterion combines <a href="https://pytorch.org/docs/stable/generated/torch.nn.LogSoftmax....
python|pytorch|mnist|softmax
50
2,728
56,009,451
FFT to find autocorrelation function
<p>I am trying to find the correlation function of the following stochastic process: <a href="https://i.stack.imgur.com/izFUa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/izFUa.png" alt="enter image description here"></a> where beta and D are constants and xi(t) is a Gaussian noise term.</p> <p>...
<p>There are two issues with the code that I can see.</p> <ol> <li><p>As <a href="https://stackoverflow.com/questions/56009451/fft-to-find-autocorrelation-function?noredirect=1#comment98715027_56009451">francis said in a comment</a>, you need to subtract the mean from your signal to get the autocorrelation to reach ze...
python|numpy|signal-processing|fft|correlation
1
2,729
65,045,653
Pandas once condition is met in column delete n rows then go to next section
<p>I have a DataFrame <code>df = pd.DataFrame({'col1': [.8,.9,1,1,1,.9,.7,.9,1,1,.8,.8,.9]})</code> which looks like</p> <pre><code> col1 0 0.8 1 0.9 2 1.0 3 1.0 4 1.0 5 0.9 6 0.7 7 0.9 8 1.0 9 1.0 10 0.8 11 0.8 12 0.9 </code></pre> <p>Once a 1 is located in <code>col1</code> I want the code to ...
<p>you can just iterate over your dataframe and get all indexes to delete:</p> <pre><code>index_to_delete = [] for row in df.itertuples(): idx = row[0] value = row.col1 if value == 1 and idx not in index_to_delete: index_to_delete += [idx+1, idx+2, idx+3] df = df.loc[~df.index.isin(index_to_delete)...
python|pandas
3
2,730
64,894,455
How to convert columns of dataframe based on best-fit types of values in them?
<p>Following <a href="https://stackoverflow.com/questions/15891038/change-column-type-in-pandas">this answer</a> (number 4) I am trying to use <code>df.convert_dtypes()</code></p> <p>Pandas version: 0.25.3</p> <p>Reproducible:</p> <pre><code>import pandas as pd import numpy as np data = { &quot;int&quot;: np.zeros...
<p><code>pip install --upgrade pandas</code></p> <p>Thanks to @jezrael need version <code>1.+</code></p>
python|pandas
0
2,731
64,663,665
Extracting numbers from column
<p>I have a dataset with many columns. I would like to search in one of these any numbers:</p> <pre><code>Column_to_look_at 10 days ago I was ... How old are you? I am 24 years old I do not know. Maybe 23.12? I could21n .... </code></pre> <p>I would need to create two columns: one which extracts the numbers included...
<p>This will do</p> <pre><code>def checknum(x): num_list = re.findall(r&quot;[+-]?\d+(?:\.\d+)?&quot;, x['Column_to_look_at']) return num_list df['Numbers'] = df.apply(checknum, axis=1) df['Bool'] = df.apply(lambda x: 1 if len(x['Numbers']) &gt; 0 else 0, axis=1) </code></pre>
python|pandas
0
2,732
39,615,238
how could i delete rows with repeating/duplicate index from dataframe
<p>I have a dataframe</p> <pre><code>&gt;&gt;&gt; df zeroa zerob zeroc zerod zeroe zero FSi 1 10 100 a ok NaN ok 1 11 110 temp NaN NaN 2 12 120 c temp NaN NaN 3 NaN NaN NaN NaN ok NaN </code></pre> <p>I want ...
<p>Ok something like this should help:</p> <pre><code>df = df.reset_index().drop_duplicates(subset='FSi', keep='first').set_index('FSi') </code></pre> <p>Explanation: First we reset_index which creates a column <strong>FSi</strong> cause drop_duplicates works on columns and not on index. We keep the first one and se...
python|pandas|dataframe
1
2,733
39,785,820
Python compute a specific inner product on vectors
<p>Assume having two vectors with m x 6, n x 6</p> <pre><code>import numpy as np a = np.random.random(m,6) b = np.random.random(n,6) </code></pre> <p>using np.inner works as expected and yields</p> <pre><code>np.inner(a,b).shape (m,n) </code></pre> <p>with every element being the scalar product of each combination....
<p>There seems to be an indexing based on some random indices for pairwise multiplication and summing on those two input arrays with function <code>pluckerSide</code>. So, I would list out those indices, index into the arrays with those and finally use <code>matrix-multiplication</code> with <a href="http://docs.scipy....
python|numpy|vector|vectorization
3
2,734
39,502,630
Numpy: Single loop vectorized code slow compared to two loop iteration
<p>The following codes iterates over each element of two array to compute pairwise euclidean distance. </p> <pre><code>def compute_distances_two_loops(X, Y): num_test = X.shape[0] num_train = Y.shape[0] dists = np.zeros((num_test, num_train)) for i in range(num_test): for j in range(num_train):...
<p>The reason is size of arrays within the loop body. In the two loop variant works on two arrays of 3000 elements. This easily fits into at least the level 2 cache of a cpu which is much faster than the main memory but it is also large enough that computing the distance is much slower than the python loop iteration ov...
python|performance|numpy|time|nearest-neighbor
2
2,735
69,613,815
How to specify a forced_bos_token_id when using Facebook's M2M-100 HuggingFace model through AWS SageMaker?
<p>The <a href="https://huggingface.co/facebook/m2m100_1.2B" rel="nofollow noreferrer">model page</a> provides this snippet for how the model should be used:</p> <pre class="lang-py prettyprint-override"><code>from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer hi_text = &quot;जीवन एक चॉकलेट बॉक्स...
<p>The tokenizer needs to be installed and imported in any case:</p> <pre><code>pip install transformers pip install sentencepiece </code></pre> <p>Then the tokenizer needs to be passed the following way:</p> <pre class="lang-py prettyprint-override"><code>tokenizer = M2M100Tokenizer.from_pretrained(&quot;facebook/m2m1...
amazon-web-services|facebook|amazon-sagemaker|huggingface-transformers|machine-translation
0
2,736
69,562,174
check if column is blank in pandas dataframe
<p>I have the next csv file:</p> <pre><code>A|B|C 1100|8718|2021-11-21 1104|21| </code></pre> <p>I want to create a dataframe that gives me the date output as follows:</p> <pre><code> A B C 0 1100 8718 20211121000000 1 1104 21 &quot;&quot; </code></pre> <p>This ...
<p>Use <code>dt.strftime</code>:</p> <pre><code>df = pd.read_csv('data.csv', sep='|', parse_dates=['C']) df['C'] = df['C'].dt.strftime('%Y%m%d%H%M%S').fillna('&quot;&quot;') print(df) # Output: A B C 0 1100 8718 20211121000000 1 1104 21 &quot;&quot; </code></pre>
python|pandas
0
2,737
69,635,114
Raising arrays to a fractional index produces NaN?
<p>I have an array, <em>k</em> as demonstrated in my MWE. I want to raise this array to the power of 3/2 but when I do the quoted error arises.</p> <pre><code>import numpy as np N = 2**15 dx = 0.1 k = (2 * np.pi / (N * dx)) * np.r_[0:N / 2, 0, -N / 2 + 1:0][None, :] kpower = k**(3/2) print(kpower) </code></pre> <blockq...
<p>You have to cast the entries of your array to complex numbers, so that numpy can perform your exponentiation:</p> <pre><code>import numpy as np N = 5 dx = 2 k = (2 * np.pi / (N * dx)) * np.r_[0: N / 2, 0, -N / 2 + 1:0][None, :] # convert array to complex datatype k = k.astype(np.cdouble) kpower = k**(3/2) print(kp...
python|numpy|nan
0
2,738
69,512,620
How to append a numpy Array into another one
<p>This is my code...</p> <pre><code>image_paths = dt_labels['image'] train_X = np.ndarray([]) for image_path in image_paths: path = './Dataset/' + image_path img = cv2.imread(path, 0) vectorized_img = img.reshape(img.shape[0] * img.shape[1], 1) train_X = np.append(train_X, vectorized_img, axis=1) </cod...
<pre><code>In [103]: train_X = np.ndarray([]) ...: print(train_X.shape) ...: for i in range(3): ...: vectorized_img = np.ones((4, 1)) ...: train_X = np.append(train_X, vectorized_img, axis=1) ...: () Traceback (most recent call last): File &quot;&lt;ipython-input-103-26d2205beb4e&gt;...
python|numpy
1
2,739
69,304,833
Loading a tensorflow.keras trained model using load_model returns JSON decode error, while untrained model loads normally
<p>I have a trained Keras model built and trained using the tensorflow.keras API and saved using the <code>tf.keras.save_model()</code> method with no optional arguments. Tensorflow is up to date and my Python version is 3.8. From my understanding, this method should save the model using the default &quot;tf&quot; form...
<p>Faced the same issue with tensorflow 2.3.1. Updated to 2.7 and now its working again!</p>
python|tensorflow|machine-learning|keras|deep-learning
1
2,740
69,321,347
Pandas: summing nanoseconds time delta to timestamp
<p>This seems somehow a simple question, but I could not find answers to it (maybe using wrong search keywords):</p> <pre><code>import pandas as pd pd.Timestamp(1) + pd.Timedelta(seconds=1e-9) Out: Timestamp('1970-01-01 00:00:00.000000001') # why? Un-intuitive pd.Timestamp(1) + pd.Timedelta(microseconds=1e-3) Out: Ti...
<p>This was a bug and was fixed <a href="https://github.com/pandas-dev/pandas/pull/45108" rel="nofollow noreferrer">here</a>.</p>
python-3.x|pandas|datetime|timedelta
1
2,741
53,938,977
TypeError: add(): argument 'other' (position 1) must be Tensor, not numpy.ndarray
<p>I am testing a ResNet-34 trained_model using Pytorch and fastai on a linux system with the latest anaconda3. To run it as a batch job, I commented out the gui related lines. It started to run for a few hrs, then stopped in the Validation step, the error message is as below. </p> <pre><code>... ^M100%|█████████▉| 45...
<p>Ok, the error seems be for the latest pytorch-1.0.0, when degrade pytorch to pytorch-0.4.1, the code seems work (passed the error lines at this point). Still have no idea to make the code work with pytorch-1.0.0</p>
machine-learning|pytorch|kaggle|resnet|fast-ai
2
2,742
38,097,181
Distributed TensorFlow example doesn't work on TensorFlow 0.9
<p>I'm trying out <a href="http://shipengfei92.cn/play_distributed_tensorflow/" rel="nofollow">this tensorflow distributed tutorial</a> with the same operating system and python version on my own computer. I create the first script and run it in a terminal, then I open another terminal and run the second script and get...
<p>The problem is probably that you are using the same port number (2222) for both workers. Each port number can only be used by one process on any given host. That's what the error "bind addr=[::]:2222: Address already in use" means.</p> <p>I'm guessing either you have "localhost:2222" twice in your cluster specifica...
python-2.7|machine-learning|tensorflow|tensorflow-serving
3
2,743
38,224,388
Set column name for size()
<p>I'm trying to rename the <code>size()</code> column as shown <a href="https://stackoverflow.com/questions/17995024/how-to-assign-a-name-to-the-a-size-column">here</a> like this:</p> <pre><code>x = monthly.copy() x["size"] = x\ .groupby(["sub_acct_id", "clndr_yr_month"]).transform(np.size) </code></pre> <p>B...
<p>You need:</p> <pre><code>x["size"] = x.groupby(["sub_acct_id", "clndr_yr_month"])['sub_acct_id'].transform('size') </code></pre> <p>Sample:</p> <pre><code>df = pd.DataFrame({'sub_acct_id': ['x', 'x', 'x','x','y','y','y','z','z'] , 'clndr_yr_month': ['a', 'b', 'c','c','a','b','c','a','b']}) print (...
pandas
1
2,744
38,064,449
TensorFlow - Tflearning error feed_dict
<p>I am working on a classification problem in python. Fact is, I'm not good yet in TensorFlow. So I have the same problem since a long time now and I don't know how to fix it. I hope you could help me :)</p> <p>This is my data :</p> <p>X : 8000 pictures : 32*32px and 3 colors (rgb), so I load a matrix X.shape = (800...
<p>Another option is to add:</p> <pre><code>tf.reset_default_graph() </code></pre> <p>As the first line of your code</p>
python|tensorflow|deep-learning
5
2,745
66,139,250
tf.data: function fails tries to convert to numpy array?
<p>I'm trying to build a <code>tf.data</code> pipeline, ultimately to compute skipgrams, but I get an error</p> <pre><code>NotImplementedError: Cannot convert a symbolic Tensor (cond/Identity:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported </code>...
<p>As of today, it does seem to be a result of the bug <a href="https://github.com/tensorflow/models/issues/9706" rel="nofollow noreferrer">https://github.com/tensorflow/models/issues/9706</a>. Reverting to python 3.6 makes it work as expected.</p>
python|tensorflow|tf.data.dataset
0
2,746
66,137,047
A 2d matrix can be reconstructed, in which a mask has been used with numpy where and flattened
<p>As the question says I have a 2D matrix (1000, 2000), in which I apply a condition with the numpy where function, in this way:</p> <pre><code>import numpy as np A = np.random.randn(1000, 2000) print(A.shape) (1000, 2000) mask = np.where((A &gt;=0.1) &amp; (A &lt;= 0.5)) A = A[mask] print(A.shape) (303112,) </code>...
<p>IIUC you need to maintain the 1D indexes and 2D indexes of the mask so that when you try to update those values using a FORTRAN program, you can switch to 1D for input and then switch back to 2D to update the original array.</p> <p>You can use <code>np.ravel_multi_index</code> to convert 2D indexes to 1D. Then you c...
python|python-3.x|numpy
1
2,747
66,183,174
Identifying a pattern in a dataframe
<p>I have the following DF:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Game</th> <th>Bookmaker</th> <th>Over1.5</th> <th>Under1.5</th> <th>Over2.25</th> <th>Under2.25</th> <th>Over2.5</th> <th>Under2.5</th> <th>Over3</th> <th>Under3</th> </tr> </thead> <tbody> <tr> <td>A vs B</td> <td>...
<p>Try to see if this is helpful to you.</p> <p>You can Transpose your dataframe and do this as follows:</p> <pre><code>df = df.T df.loc[df[0] &gt; df[1],'over_dominance'] = 'AsianDominant' df.loc[df[0] &lt; df[1],'over_dominance'] = 'PinDominant' df.loc[df[0] == df[1],'over_dominance'] = 'Parity' print (df) </code></p...
python|pandas|dataframe
0
2,748
52,774,506
Count nonzero elements and plot
<p>I want to count the number of nonzero elements in the list below- <a href="https://i.stack.imgur.com/4pelh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4pelh.png" alt="enter image description here"></a></p> <p>I tried this code,</p> <pre><code>nzcnt = [nonzero.count(0),nonzero.count(1),nonzer...
<p>You can flatten the list and then count the number of zeros. You can use <code>w_check.flatten()</code> for that.</p>
python|pandas|numpy
1
2,749
52,704,777
NumPy - Vectorizing loops involving range iterators
<p>Is there any way to make this work without for loops?</p> <pre><code>import import numpy as np import matplotlib.pyplot as plt L = 1 N = 255 dh = 2*L/N dh2 = dh*dh phi_0 = 1 c = int(N/2) r_0 = L/2 arr = np.empty((N, N)) for i in range(N): for j in range(N): arr[i, j] = phi_0 if (i - c)**2 ...
<h3>Vectorized solution using open grids</h3> <p>We could use two <em>open</em> range/grid arrays for <code>N</code> simulating the same behavior as the iterators -</p> <pre><code>I = np.arange(N) mask = (I[:,None] - c)**2 + (I - c)**2 &lt; r_0**2/dh2 out = np.where(mask,phi_0,0) </code></pre> <p><strong>For a gener...
python|numpy|vectorization
7
2,750
46,342,608
simplegui based pygame to exe file, numpy-atlas.dll error
<p>I have a working game developed on codeskulptor simplegui tools. I converted it to pygame though SimpleGUICS2Pygame. I tried to convert it to exe, it ran this error: [Errno 2] No such file or directory: 'numpy-atlas.dll'</p> <p>I looked into this thread:<a href="https://stackoverflow.com/questions/36191770/py2exe-e...
<p>I never used and will never use neither py2exe nor py2app. I always used cx_Freeze and then deleted it and installed Pyinstaller because it offers <code>run bat or shell -&gt; delete build dir -&gt; go to dist dir -&gt; run that exe</code> system. To use it:</p> <ol> <li><p>Install Pyinstaller: type <code>pip insta...
python|numpy|dll|pygame
0
2,751
58,402,843
Filtering large dataframes by unique indices with Pandas
<p>I have a 30 million row by 30 column dataframe that I want to filter by using a list of unique indices.</p> <p>Basically the <strong>input</strong> would be:</p> <pre><code>df = pd.DataFrame({'column':[0,1,2,3,4,5,6,7,8,9,10]}) indices = [1, 7, 10] df_filtered = df[df.index.isin(indices)] </code></pre> <p>With t...
<p>The actual answer depends on what you want to do with the DataFrame, but a general idea when running into memory errors is to do the operation in chunks.</p> <p>In your case, chunks of size N are N sequential elements from the <code>indices</code> list:</p> <pre><code>df = pd.DataFrame() # placeholder for your hu...
python|python-3.x|pandas|dataframe|out-of-memory
2
2,752
58,253,269
What does this line do? df = df[~df[runner].str.contains("[a-z]").fillna(False)]
<p>may I check what does this line do? </p> <pre><code>df = df[~df[runner].str.contains("[a-z]").fillna(False)] </code></pre> <p>Is this code remove all rows that contain string that start with alphabet? 2nd question is what is the purpose of ~? What does it do?</p> <p>Thanks</p>
<p><strong>This code is masking a DataFrame.</strong></p> <p>The RegEx <code>"[a-z]"</code> means contains any character 'a to z' (not 'starting with', as this would be <code>"^[a-z]"</code>).</p> <p>The <code>.fillna(False)</code> means every NaN is treated as False for this Mask.</p> <p>The <code>~</code> is inver...
python|pandas
1
2,753
58,293,899
How can I upgrade from Tensorflow 2.0 alpha to beta given the exception: ERROR: Cannot uninstall 'wrapt'
<p>When trying to install the beta version of tensorflow 2.0 I am getting the following exception:</p> <pre><code>ERROR: Failed building wheel for wrapt Running setup.py clean for wrapt Failed to build wrapt Installing collected packages: tf-estimator-nightly, wrapt, tb-nightly, google-pasta, tensorflow Found exis...
<p>I also faced this error but you can safely ignore this error. You can read more about this, <a href="https://github.com/tensorflow/tensorboard/issues/2296#issuecomment-497883063" rel="nofollow noreferrer">here</a> in this issue. </p> <p>Or, you can first install/update the wrapt package using <code>pip install wrap...
upgrade|tensorflow2.0
0
2,754
68,988,616
Plotting different groups of a dataframe in different subplots
<p>I want to plot 4 different scatter subplots in one main plot. The data are coming from a grouped dataframe which is read from a .csv file. The initial dataframe looks like this:</p> <pre><code>df.to_csv(&quot;File.csv&quot;, index=False) </code></pre> <p>df:</p> <div class="s-table-container"> <table class="s-table"...
<p>You could use <a href="https://seaborn.pydata.org/generated/seaborn.relplot.html#seaborn.relplot" rel="nofollow noreferrer"><code>seaborn.relplot</code></a>:</p> <pre><code>import numpy as np import seaborn as sns # dummy data df = pd.DataFrame({'Category1': np.random.choice(['A','B'], size=100), ...
python|pandas|dataframe|plot|group-by
1
2,755
69,194,635
UTF error when reading in GPX files using list comprehension in Python
<p>I am trying to take a batch of GPX files and concatenate them into a pandas dataframe to then export as a CSV for analysis elsewhere (QGIS).</p> <p>Problem is, when I do my list comprehension step, it gives me a UTF-8 encoding error. I took a look at one of the GPX files, and it explicitly declares the encoding at t...
<p>I guess you need to use encoding while opening the file.</p> <pre><code> with open(f, 'r', encoding=&quot;desired_encoding&quot;) as gpxfile: </code></pre>
python|pandas|dataframe|gis|gpx
1
2,756
44,757,059
how to transfer a vertor numpy array of tuple transform to 2d numpy array
<p>I have numpy array like this:</p> <pre><code>a = [(20111205000000, 15.94, 16.04, 15.7 , 15.95, 11349137.) (20111206000000, 15.95, 15.95, 15.95, 15.95, 0.) (20111207000000, 15.9 , 16.15, 15.86, 16.05, 14862428.) (20111208000000, 16.05, 16.13, 15.81, 15.94, 18705208.)] </code></pre> <p>...
<p>You can use this:</p> <pre><code>np.array([list(i) for i in a]) </code></pre>
python|numpy|vector
0
2,757
44,802,939
Hyperparameter Tuning of Tensorflow Model
<p>I've used Scikit-learn's GridSearchCV before to optimize the hyperparameters of my models, but just wondering if a similar tool exists to optimize hyperparameters for Tensorflow (for instance <strong>number of epochs, learning rate, sliding window size etc.</strong>)</p> <p>And if not, how can I implement a snippet...
<p>Even though it does not seem to be explicitly documented (in version 1.2), the package <a href="https://www.tensorflow.org/get_started/tflearn" rel="noreferrer"><code>tf.contrib.learn</code></a> (included in TensorFlow) defines classifiers that are supposed to be compatible with scikit-learn... However, looking at <...
python|tensorflow|convolution|hyperparameters
20
2,758
60,923,428
pandas csv reader produces wrong result
<p>I have a python script that produces a wrong date format.</p> <pre><code>import csv import urllib import requests import numpy as np from urllib.request import urlopen from matplotlib.dates import DateFormatter import matplotlib.pyplot as plt import pandas as pd import io link = 'https://health-infobase.canada.ca...
<p>Because you've used the <code>parse_dates</code> attribute, pandas interprets the 'date' column as a date-time object. This can be very useful for plotting data over time, or resampling your data over given time periods. If you want to restructure the datetime format for printing of your dataset, you can use <code>d...
pandas
0
2,759
60,882,663
ModuleNotFoundError: No module named 'tensorflow.contrib' with tensorflow=2.0.0
<p>I am using TensorFlow version=2.0.0 python version=3.7.3 I am trying to import the below statement</p> <pre><code>from tensorflow.contrib import rnn </code></pre> <p>And it gives error as Module 'tensorflow' has no attribute 'contrib' How can I resolve this?</p>
<p>from tensor flow </p> <p><a href="https://www.tensorflow.org/guide/upgrade#compatibility_modules" rel="nofollow noreferrer">https://www.tensorflow.org/guide/upgrade#compatibility_modules</a></p> <blockquote> <p>Because of TensorFlow 2.x module deprecations (for example, tf.flags and tf.contrib), some changes can...
python|tensorflow|nlg
1
2,760
42,270,757
Pandas maximum length of object type with None values
<p>I’ve written a short function to output the maximum values (or for strings, maximum length) for each column in a data frame, with adjustments for various data types.</p> <pre><code>def maxDFVals(df): for c in df: if str(df[c].dtype) in ('datetime64[ns]'): print('Max datetime of column {}: {}...
<p>Try This:-</p> <pre><code>def maxDFVals(df): for c in df: if str(df[c].dtype) in ('datetime64[ns]'): print('Max datetime of column {}: {}\n'.format(c, df[c].max())) elif str(df[c].dtype) in ('object', 'string_', 'unicode_'): print('Max length of column {}: {}\n'.format(c...
python|pandas|dataframe|fillna
2
2,761
69,769,246
How to convert list object type in 3rd dimension of 3D numpy array?
<p>A bit of background: Initially, I had the error <code>ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list).</code> after attempting to convert <code>my_list</code> into a tensor using <code>tf.convert_to_tensor()</code> .</p> <p>I have a 3D numpy array <code>my_list</code> with the ...
<p>Make sure:</p> <ul> <li>my_list only contains actual numbers, not other objects like a string</li> <li>All entries of the same hierarchy have the same length, i.e. len(my_list[0]) == len(my_list[1])</li> </ul> <p>To convert into an numpy array (in all dimensions at once):</p> <pre><code>my_array = np.array(my_list) ...
python|numpy|tensorflow|numpy-ndarray
0
2,762
43,213,708
What is "gate_gradients" atribute in tensorflow minimize() function in the optimzer class?
<p>This is the link to TF optimizer class <strong><a href="https://www.tensorflow.org/versions/r0.12/api_docs/python/train/optimizers" rel="noreferrer">https://www.tensorflow.org/versions/r0.12/api_docs/python/train/optimizers</a></strong></p>
<p>GATE_NONE: Take the simple case of a matmul op on two vectors 'x' and 'y'. let the output be L. Now gradient of L wrt x is y and gradient of L wrt y is xT (x transpose). with GATE_NONE it could so happen that the gradient wrt x is applied to modify x before the gradient for y is even calculated. Now when the gradien...
tensorflow|deep-learning
15
2,763
43,439,206
Importing modules for visual studio
<p>Right now i'm trying to create an array like this: </p> <pre><code>import NumPy as np V = np.array([3, 9, 7, 7, 7, 1, 5, 5, 5, 5]) print V </code></pre> <p>but the terminal is saying "Unable to import NumPy" and "Missing module docstring"</p> <p>I am fairly new to coding on visual studio and I don't often use S...
<p>First : Make sure that numpy is already existed .try that outside VS.</p> <pre><code>import numpy </code></pre> <p>you will get ModuleNotFound error if it's not existed.</p> <p>Second : Update your environment database in the Visual Studio.</p> <p>Third : make sure the the environment settings is correct .</p> ...
python|arrays|numpy
1
2,764
43,436,541
Reading from csv to pandas, chardet and error bad lines options do not work in my case
<p>I checked similar questions before I write here, also I tried to use try/except... where try does nothing, except prints bad line but couldn't solve my issue. So currently I have:</p> <pre><code>import pandas as pd import chardet # Read the file with open("full_data.csv", 'rb') as f: result = chardet.detect(f....
<p>Using engine option sovles my problem:</p> <pre><code>df1 = pd.read_csv("full_data.csv", sep=";", engine="python") </code></pre>
python|csv|pandas|unicode
1
2,765
43,123,334
Multidimensional Convolution in python
<p>I'm trying to convolve a 3 dimensional values array of shape (10, 100, 100) with a gaussian of shape (10, 100, 100). When I use the convolve function I get a Value error. </p> <pre><code>def gaussian(x, mu, sigma): g = (1./ (sigma * sqrt(2*pi))) * exp(-(x - mu)**2 / sigma**2) return g gauss_I = gaussian( v...
<p>I have been having the same problem for some time. As already mentioned in the comments the function <code>np.convolve</code> supports only 1-dimensional convolution. One alternative I found is the scipy function <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.fftconvolve.html#scipy.signal...
python|numpy|math|multidimensional-array|signals
1
2,766
72,485,457
How to expand a dataframe with a tree structure
<p>I have a data frame, which has an embedded tree structure inside it, like this:</p> <p>df1</p> <pre><code> Category Type Dependent-Category 0 1 ~ A 1 1 ~ B 2 1 ~ C 3 1 ~ 14 4 1 ~ D 5 1 P NaN 6 ...
<p>Possible solution can be to separate out different categories as dataframes and then merge them sequentially with original dataframe then apply conditional formatting.</p> <p>Here is my solution doing the same:</p> <pre><code>d = { &quot;Category&quot;: [1, 1, 1, 1, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &...
python|pandas|dataframe|tree
2
2,767
72,251,535
A bug in the code working with excel data
<p>I have an excel file like this and I want the date field numbers to be converted to history like (2021.7.22) and replaced again using Python in the history field.</p> <p><a href="https://i.stack.imgur.com/O5Vmp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O5Vmp.png" alt="enter image description...
<p>You need to solve the ambiguity for dates like <code>2021111</code>. In a first time, you can use <code>pd.to_datetime</code>:</p> <pre><code>df['date2'] = pd.to_datetime(df['date'], format='%Y%m%d').dt.strftime('%Y.%-m.%-d') print(df) # Output date date2 0 2021227 2021.2.27 1 2021228 2021.2.28 2 ...
python|pandas
1
2,768
72,417,073
Equivalent of Partial Matching XLOOKUP in Python
<p>The following code will tell me if there are partial matches (via the True values in the final column):</p> <pre><code>import pandas as pd x = {'Non-Suffix' : ['1234567', '1234568', '1234569', '1234554'], 'Suffix' : ['1234567:C', '1234568:VXCF', '1234569-01', '1234554-01:XC']} x = pd.DataFrame(x) x['&quot;Non-Suffi...
<p>You can join the <code>Non-Suffix</code> column value with <code>|</code> then use <code>Series.str.contains</code> to check if contain any value</p> <pre class="lang-py prettyprint-override"><code>x['&quot;Non-Suffix&quot; Partial Match in &quot;Suffix&quot;?'] = x['Suffix'].str.contains('|'.join(x['Non-Suffix'])) ...
python|python-3.x|pandas|dataframe
1
2,769
50,284,366
How do I give a text key to a dataframe stored as a value in a dictionary?
<p>So I have 3 dataframes - df1,df2.df3. I'm trying to loop through each dataframe so that I can run some preprocessing - set date time, extract hour to a separate column etc. However, I'm running into some issues:</p> <p>If I store the df in a dict as in <code>df_dict = {'df1' : df1, 'df2' : df2, 'df3' : df3}</code> ...
<p>You didn't create <code>df_dict</code> correctly. Try this:</p> <pre><code>DF_DATA = { 'df1': 'df1.csv','df2': 'df2.csv', 'df3': 'df3.csv' } df_dict= {k:pd.read_csv(v) for k,v in DF_DATA.items()} </code></pre>
python-3.x|pandas|loops|dictionary|dataframe
0
2,770
50,475,348
How to save the model for text-classification in tensorflow?
<p>Reading <a href="https://www.tensorflow.org/tutorials/text_classification_with_tf_hub" rel="nofollow noreferrer">tensorflow documentation</a> for text-classification, I have put up a script below that I used to train a model for text classification (positive/negative). I am not sure on one thing. How could I save th...
<p>You can train and predict on a saved/loaded Estimator model simply by passing the <code>model_dir</code> parameter to both the Estimator instance and a <code>tf.estimator.RunConfig</code> instance that is passed to the <code>config</code> parameter of pre-made estimators (since about Tensorflow 1.4--still works on T...
python|python-3.x|tensorflow|machine-learning
0
2,771
50,668,168
Vectorized implementation for Euclidean distance
<p>I am trying to compute a vectorized implementation of Euclidean distance(between each element in X and Y using inner product). The data as follows:</p> <pre><code>X = np.random.uniform(low=0, high=1, size=(10000, 5)) Y = np.random.uniform(low=0, high=1, size=(10000, 5)) </code></pre> <p>What I did was:</p> <pre><...
<p>If I understood correctly this should do</p> <pre><code>np.linalg.norm(X - Y, axis=1) </code></pre> <p>Or with <code>einsum</code> (square root of the dot product of each difference pair along the first axis)</p> <pre><code>np.sqrt(np.einsum('ij,ij-&gt;i...', X - Y, X - Y)) </code></pre> <p>If you want all pairw...
python|numpy|vectorization|euclidean-distance
5
2,772
45,281,597
Counting number of consecutive zeros in a Dataframe
<p>i want to count number of consecutive zeros in my Dataframe shown below, help please</p> <pre class="lang-html prettyprint-override"><code> DEC JAN FEB MARCH APRIL MAY consecutive zeros 0 X X X 1 0 1 0 1 X X X 1 0 1 0 2 0 0 ...
<p>For each row, you want <code>cumsum(1-row)</code> with reset at every point when <code>row == 1</code>. Then you take the row max.</p> <p>For example</p> <pre><code>ts = pd.Series([0,0,0,0,1,1,0,0,1,1,1,0]) ts2 = 1-ts tsgroup = ts.cumsum() consec_0 = ts2.groupby(tsgroup).transform(pd.Series.cumsum) consec_0.max()...
python|python-2.7|pandas|numpy
1
2,773
62,506,567
python random data generator expected str instance, numpy.datetime64 found
<p>Hello have been trying to create random data with random dates as into a csv file but getting the following error <code>expected str instance, numpy.datetime64 found</code></p> <p>code for data generator</p> <pre><code>import pandas as pd import numpy as np import string import random def gen_random_email(): do...
<p>First, catch the error and see what is causing it.</p> <pre><code>def gen_dataset(filename, size=5000): randomizers = [gen_random_email, gen_random_float, gen_random_int, gen_random_sentence,gen_random_date] with open(filename, 'w') as file: file.write(&quot;Text, Type\n&quot;) for _ in range...
python|pandas|numpy|keras
0
2,774
73,733,311
How to rank a url in one column using a list of urls in another column in Pandas?
<p>My data frame looks something like this with URLs instead of letters:</p> <p><a href="https://i.stack.imgur.com/p2kzx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p2kzx.png" alt="enter image description here" /></a></p> <p>.csv code:</p> <pre><code>query,ranks a,&quot;[k, g, y, l, a]&quot; h,&q...
<p>A basic solution with <code>apply</code> and accounting for possibly missing values (I set -1 as default value but you can set whatever you need):</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'query': ['a', 'h', 'x', 'w', 'r'], 'ranks': [['k', 'g', 'y', 'l', 'a'], ...
python|pandas|dataframe
2
2,775
71,273,770
How to use .iloc and .loc to get row data from specific columns value
<p>I am trying to make a scatter plot of dataset, 1st column is + or -, 2nd column is X axis and 3rd columns is Y axis. I need to take positve x and y and plot them one color, and than take the negatives x and y and plot them another color.</p> <pre><code> 1 0.107143 0.60307 0 1 0.093318 0.649854 1 1 0...
<p>If you are ok with a solution which does not use <code>iloc</code> or <code>loc</code>, try this. Only change is in getting the positive and negative rows. See comments inline</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame([[1, 0.807143, 0.60307],[-1, 0.207143, 0.50307],[1, 0....
python|pandas|numpy|matlab
0
2,776
71,289,607
retrieve stock price data from specific dates in pandas df
<p>I have a pandas dataframe that has the earnings date of certain stocks, the eps actual and estimate as well as revenue estimate and actual. For my sample, I only have 10 tickers of all their earnings date but I to eventually incorporate all nasdaq tickers. Anyways, what is the fastest way to go through the pandas da...
<p>This solution involves data collection as well, feel free to use this feature or just adapt the data merging using that specific part of the code.</p> <p>First, setting up the dataframe to test this solution:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'Date':['2022-01-27','2021-10-28','20...
python|pandas|stock|yfinance
0
2,777
52,427,141
Check TPU workload/utilization
<p>I am training a model, and when I open the TPU in the Google Cloud Platform console, it shows me the CPU utilization (on the TPU, I suppose). It is really, really, low (like 0.07%), so maybe it is the VM CPU? I am wondering whether the training is really proper or if the TPUs are just that strong.</p> <p>Is there ...
<p>I would recommend using the TPU profiling tools that plug into TensorBoard. A good tutorial for install and use of these tools can be found <a href="https://cloud.google.com/tpu/docs/cloud-tpu-tools" rel="noreferrer">here</a>.</p> <p>You'll run the profiler while your TPU is training. It will add an extra tab to yo...
tensorflow|google-cloud-platform|google-compute-engine|google-cloud-tpu
6
2,778
60,578,609
Extract list element in pandas series and convert to datetime
<p>The series which I am handing now looks like this:</p> <pre><code>qa_answers['date_of_birth'] 1 [] 2 [] ... 2600 [1988/11/23] 2601 [1992/7/15] 2602 [1993/11/8"] 2603 [1997/08/31] 2604 [1971/2/11] 2605 [1979/11/1"] 2606 [1993/9/19] 2607 [1985/01/12] 2608 ...
<p>You must first convert non empty lists to their first element and clean it and convert empty list to an empty string:</p> <pre><code>df.date_of_birth.apply(lambda x: x[0].replace('"', '') if len(x) &gt; 0 else '') </code></pre> <p>gives:</p> <pre><code>1 2 ... 2600 1988/11/23 ...
python|pandas|list|datetime
2
2,779
60,640,113
What the best possible way to concatenate pandas column? From a list of column
<p>I have dataframe like this:</p> <pre><code>A B C D E F aa bb cc dd ee ff NA ba NA da ea NA list_col = ['A', 'B', 'C'] </code></pre> <p>So i just want to merge the columns which are in list only. Moreover i dont want NA values as merged.. is there any way?</p> <p...
<p>You can use <code>apply(..., x=1)</code> to process a dataframe row wise. But you want to ignore NaN values, so you will have to exclude them. You could use:</p> <pre><code>df[list_col].apply(lambda x: '-'.join(x.dropna()), axis=1) </code></pre> <p>It gives:</p> <pre><code>0 aa-bb-cc 1 ba dtype: objec...
python|pandas|join|merge
1
2,780
72,531,718
Changing list to dataframe in dictionary
<p>I am writing a dictionary that has to seperate a dataframe into multiple small dataframes based on a certain item that is repeated in the list calvo_massflows. If the items isn't repeated, it'll make a list in the dictionary. In the second for loop, the dictionary will add the index item from the df dataframe to one...
<p>IIUC you want to select the rows of <code>df</code> up to the length of <code>calvo_massflow</code>, group by calvo_massflow and convert to dict. This might look like this:</p> <pre><code>calvo_massflow = [1, 2, 1, 2, 2, 1, 1] df = pd.DataFrame({&quot;a&quot;:[1, 2, 3, 4, 11, 2, 4, 6, 7, 3], &quo...
python|pandas|dataframe|dictionary|pandas-groupby
0
2,781
72,738,731
How can I group by a datetime column with timezone?
<pre><code>import pandas as pd df = pd.DataFrame( { 'StartDate':['2020-01-01 00:00:00-04:00', '2020-01-01 01:00:00-04:00', '2020-01-01 01:55:00-04:00', '2020-01-02 02:00:00-02:00', '2020-01-02 02:00:00-04:00'], 'Weight':[100, 110, 120, 125, 155] } ) df['StartDate'] = pd.to_datetime(df['StartDat...
<p>You first need to convert to datetime, taking into account the timezones:</p> <pre><code>df['StartDate'] = pd.to_datetime(df['StartDate'], utc=True) df.groupby(pd.Grouper(key='StartDate', freq='H')).sum() </code></pre> <p>Output:</p> <pre><code> Weight StartDate 202...
python|pandas
2
2,782
59,673,802
how to install the latest version of Tensorflow for CPU
<p>I am trying to install TensorFlow and I get this error when I try to import it :</p> <pre><code>Traceback (most recent call last): File "C:\Users\USER\Anaconda3\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 58, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import *...
<p>Try installing or re-installing the C++ Redistributable from <a href="https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads" rel="nofollow noreferrer">here</a>. Make sure you are downloading the "Visual Studio 2015, 2017 and 2019" x64 version and restart your computer after the ins...
tensorflow
0
2,783
59,801,932
Raise TypeError (TypeError: object of type <class 'numpy.float64'> cannot be safely interpreted as an integer)
<p>I am using a package that needs NumPy. Until now it was working fine. But today, because of extending my code I needed the newest version of NumPy. The old version was 17.something and I installed the latest version. After that I am facing the below mentioned issue <a href="https://github.com/numpy/numpy/issues/1534...
<p>Downgrade your <strong>numpy</strong> version to: <strong>1.16</strong></p> <p><strong>pip install numpy==1.16</strong></p> <p>worked for me .</p>
python|numpy|package|numpy-ufunc
2
2,784
40,563,628
How to convert a 2 1d arrays to one 1d arrays but both values should be inside one element
<p>i really dont how to phrase this properly so I apologise in advance. So lets say i have 2, 1D arrays</p> <pre><code>array1 = [2000, 2100, 2800] array2 =[20, 80, 40] </code></pre> <p>Now how do i convert them into an 2d array in python like shown below</p> <pre><code>2dArray = [[2000, 20], [2100, 80], [2800, 40]]...
<p>Simple NumPy solution - <code>np.array([...]).T</code>:</p> <pre><code>In [6]: np.array([a1, a2]).T Out[6]: array([[2000, 20], [2100, 80], [2800, 40]]) </code></pre> <p>Another NumPy solution, which uses <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html" rel="nofol...
python|arrays|pandas|numpy
3
2,785
40,637,615
Bar graph plot with values on top python
<p>I have a table in my pandas df.</p> <pre><code> Total_orders frequency 0.0 18679137 1.0 360235 2.0 68214 3.0 20512 4.0 7211 ... ... 50.0 12 </code></pre> <p>I want to plot a bar graph total orders v...
<p>Try this:</p> <pre><code>def autolabel(rects, height_factor=1.05): # attach some text labels for rect in rects: height = rect.get_height() ax.text(rect.get_x() + rect.get_width()/2., height_factor*height, '%d' % int(height), ha='center', va='bottom') In [48]...
python|python-3.x|python-2.7|pandas|matplotlib
2
2,786
40,660,933
Why "CopyFrom" is used during the creation of the constant Tensor?
<p>During the creation process of the constant Tensor there is the following <a href="https://github.com/tensorflow/tensorflow/blob/beb10ceb086fe94a6b1247b45397aafddd47e05d/tensorflow/python/framework/constant_op.py#L162" rel="nofollow noreferrer">line</a>:</p> <pre><code> tensor_value.tensor.CopyFrom( tensor_u...
<p>You cannot assign a proto to a field of a proto as explained in this doc: <a href="https://developers.google.com/protocol-buffers/docs/reference/python-generated" rel="nofollow noreferrer">https://developers.google.com/protocol-buffers/docs/reference/python-generated</a></p> <blockquote> <p>You cannot assign a va...
python|tensorflow|protocol-buffers
4
2,787
18,608,924
Python- New Variable inidcator
<p>So I want to make new indicator variable to my dataframe (df), Basically i want it to read "Splits" unless another field (AssetClass) is "Future" in which case i want the new indicator to read "NotSplit" the code im using at the moment is:</p> <pre><code>df['Category'] = 'Split' df[df.AssetClass == "Future"].Categ...
<p>Like this?</p> <pre><code>df['Category'] = 'NotSplit' if df.AssetClass == 'Future' else 'Split' </code></pre> <p>Some background: currently you will get a new key in your dict (either <code>True</code> or <code>False</code>) because the result of the <code>df.AssetClass == 'Future'</code> evaluation is used. On ot...
python|numpy
0
2,788
61,630,046
Skipping tuples without attributes Python NLTK
<p>I have a script that is mostly working for the Natural Language Tool Kit. It works by using NLTK to tokenize and label (categorize) individual words. </p> <p>When my list includes names and entities it works fine. </p> <p>Where it breaks down is if the list includes articles of speech such as "The", "a", "and" etc...
<p>First suggestion is to remove stop words (to, the, a, etc). Example code is:</p> <pre><code>from nltk.corpus import stopwords, wordnet stop_words = set(stopwords.words('english')) df['TextRemovedStopWords'] = df['Text'] df.loc[df['Text'].isin(stop_words),'TextRemovedStopWords'] = None </code></pre> <p>After th...
python|python-3.x|pandas|jupyter-notebook|nltk
0
2,789
57,870,748
Vectorize QR in Numpy Python
<p>Hi I am trying to vectorise the QR decomposition in numpy as the documentation suggests <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html" rel="nofollow noreferrer">here</a>, however I keep getting dimension issues. I am confused as to what I am doing wrong as I believe the following...
<p>From the doc: "By default, pyfunc is assumed to take scalars as input and output.". So you need to give it a signature: </p> <pre><code>vecQR = np.vectorize(np.linalg.qr, signature='(m,n)-&gt;(m,p),(p,n)') </code></pre>
python|numpy|vectorization|qr-code
2
2,790
57,793,496
Pandas: Sum Previous N Rows by Group
<p>I want to sum the prior N periods of data for each group. I have seen how to do each individually (sum by group, or <a href="https://stackoverflow.com/questions/43787059/how-to-compute-cumulative-sum-of-previous-n-rows-in-pandas">sum prior N periods</a>), but can't figure out a clean way to do both together.</p> <p...
<p>This is <code>groupby</code> + <code>rolling</code> + <code>shift</code></p> <pre><code>df.groupby('user')['clicks'].rolling(3, min_periods=1).sum().groupby(level=0).shift() </code></pre> <p></p> <pre><code>user a 0 NaN 1 0.0 2 1.0 3 3.0 4 6.0 b 5 NaN ...
python|pandas
6
2,791
34,355,059
OpenCV-Python - How to format numpy arrays when using calibration functions
<p>I'm trying to calibrate a fisheye camera using OpenCV 3.0.0 python bindings (with an asymmetric circle grid), but I have problems to format the object and image point arrays correctly. My current source looks like this:</p> <pre><code>import cv2 import glob import numpy as np def main(): circle_diameter = 4.5...
<p>In the sample of OpenCV (<a href="https://docs.opencv.org/4.0.1/dc/dbb/tutorial_py_calibration.html" rel="nofollow noreferrer">Camera Calibration</a>) they set the objp to <code>objp2 = np.zeros((8*9,3), np.float32)</code></p> <p>However, in omnidirectional camera or fisheye camera, it should be: <code>objp = np.ze...
python|opencv|numpy|opencv3.0|camera-calibration
1
2,792
36,799,642
pandas - groupby and select variable amount of random values according to column
<p>Starting from this simple dataframe <code>df</code>:</p> <pre><code>df = pd.DataFrame({'c':[1,1,2,2,2,2,3,3,3], 'n':[1,2,3,4,5,6,7,8,9], 'N':[1,1,2,2,2,2,2,2,2]}) </code></pre> <p>I'm trying to select <code>N</code> random value from <code>n</code> for each <code>c</code>. So far I managed to groupby and get one s...
<p>Pandas objects now have a <code>.sample</code> method to return a random number of rows:</p> <pre><code>&gt;&gt;&gt; df.groupby('c').apply(lambda g: g.n.sample(g.N.iloc[0])) c 1 1 2 2 5 6 2 3 3 6 7 7 8 Name: n, dtype: int64 </code></pre>
python|numpy|pandas|random
1
2,793
54,990,022
Convolving sobel operator in x direction in frequency domain
<p>I implemented the code <a href="https://stackoverflow.com/a/54977551/7328782">given by Cris Luengo for convolution in frequency in domain</a>, however I'm not getting the intended gradient image in x direction.</p> <p>Image without flipping the kernel in x and y direction:</p> <p><img src="https://i.stack.imgur.co...
<p>We can use <code>np.fft</code> module's FFT implementation too and here is how we can obtain convolution with sobel horizontal kernel in frequency domain (by the convolution theorem):</p> <pre><code>h, w = im.shape kernel = np.array(array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])) #sobel_filter_x k =...
python|numpy|image-processing|fft|convolution
0
2,794
28,049,842
Python: Get all variable names with their types, and then export to a file
<p>I have a data set of 10 variables (columns) and I would like to see all of the variable names with their types. For example, the expected output is:</p> <pre><code>ID Integer, Name Integer, Income Float, </code></pre> <p>And then export the output to a text file. I know the function <code>type</code> will return th...
<p>Not really clear from your question where those variables are coming from. I'll just assume you've got that covered and the actual problem is to pretty-print the type.</p> <p>There are (at least) two ways: Either, you could use the <code>type</code>'s <code>__name__</code> attribute to get, e.g., <code>'int'</code>...
python|csv|pandas|type-inference
2
2,795
73,364,868
AttributeError creating line plot using matplotlib
<p>I need to plot in a loop structure each unique &quot;plant_name&quot; in the data below so that the values in &quot;Adj_Prod&quot; are plotted over each other by month for each site. My data in df1 looks like this:</p> <pre><code> plant_name month Adj_Prod Adj_Prod Adj_Prod Adj_Prod Adj_Prod 0 BI...
<p>The error you are seeing is being raised by this line (I've reformatted for clarity but it's the same code as yours):</p> <pre class="lang-py prettyprint-override"><code> for i in range(len(sites)): plt.figure() --&gt; plt.plot( df1.loc[df1['plant_name']==sites[i]].Adj_Prod, d...
pandas|loops|plot
1
2,796
73,360,749
Reading an excel sheet containing hyperlinks using pythons pandas.read_excel
<p>I made an excel sheet using pandas dataframe to generate texts with clickable urls using the following code</p> <pre><code>import pandas as pd df = pd.DataFrame({'link':['=HYPERLINK(&quot;https://ar.wikipedia.org/wiki/&quot;,&quot;wikipidia&quot;)', '=HYPERLINK(&quot;https://www.google.com...
<p>you can do the same as a csv which is cleaner (avoids excel issues).</p> <pre class="lang-py prettyprint-override"><code># %% write the date import pandas as pd df = pd.DataFrame({'link':['=HYPERLINK(&quot;https://ar.wikipedia.org/wiki/&quot;,&quot;wikipidia&quot;)', '=HYPERLINK(&quot;htt...
python|excel|pandas|dataframe|hyperlink
0
2,797
73,457,069
Why does my LSTM model predict wrong values although the loss is decreasing?
<p>I am trying to build a machine learning model which predicts a single number from a series of numbers. I am using an LSTM model with Tensorflow.</p> <p>You can imagine my dataset to look something like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Index</th> <th>x data</th> <th>y...
<p>From the notebook it seems you are not scaling your data. You should normalize or standardize your data before training your model.</p> <p><a href="https://machinelearningmastery.com/how-to-improve-neural-network-stability-and-modeling-performance-with-data-scaling/" rel="nofollow noreferrer">https://machinelearning...
python|tensorflow|machine-learning|keras|lstm
2
2,798
35,094,743
How to covert np.ndarray into astropy.coordinates.Angle class?
<p>What is the quickest/most efficient way to convert a np.ndarray (importing numpy as np) into the astropy.coordinates.Angle class? I am having trouble keeping it as np.ndarray because the .wrap_at() operation will not work.</p>
<p>What exactly is your intention? <code>np.asarray</code> is quite ambiguous. If you are dealing with <code>np.ndarray</code> it is quite easy:</p> <pre><code>from astropy.coordinates import Angle import astropy.units as u import numpy as np angles = np.array([100,200,300,400]) angles_quantity = a * u.degree # Could...
python|numpy|astropy
4
2,799
67,563,194
Calling Class Method in a pandas Dataframe
<p>I have a simple class with one method. How can I create 2 additional columns in a pandas dataframe where 1 column is a column of class objects and column 2 calls the class method. I've tried the below but it returns &quot;Wrong number of items passed 4, placement implies 1&quot;</p> <pre><code>class test1: def __...
<pre><code>fpd['class'] = test1(fpd['x'], fpd['y']) fpd['method'] = fpd['class'].apply(lambda x: x.mult()).iloc[0] fpd </code></pre> <p><strong>Output</strong></p> <pre><code> x y class method 0 3 5 &lt;__main__.test1 object at 0x1205bd3a0&gt; 15 1 2 6 &lt;__main_...
python|pandas
0