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
377,800
20,656,428
Numpy array modifying multiple elements at once
<p>I have three numpy arrays:</p> <pre><code>row = np.array([1,2,3,4,5]) # a is a subset of row: a = np.array([1, 5]) # b is an array that I use to change some elements in the first row array: b = np.array([10, 550]) </code></pre> <p>What I need to do is to change <strong>in one shot</strong> the elements of the ...
<p>If you don't have guarantees on the sorting of your arrays, you could have a reasonably efficient implementation using <code>np.searchsorted</code>:</p> <pre><code>def find_and_replace(array, find, replace): sort_idx = np.argsort(array) where_ = np.take(sort_idx, np.searchsorted(array,...
python|numpy|indexing
5
377,801
20,378,097
How to control dimensions of empty arrays in Numpy
<p>I was trying to concatenate 1-D two arrays in Python, using numpy. One of the arrays might potentially be empty (a2 in this case). a1 and a2 are the results from some computation over which I have no control. When a1 and a2 are non-empty they both have shapes of the form (n,2), so concatenation is not a problem. How...
<p>The error message tells you what you need to know. It's not enough that the array is empty - they have to have the <strong>same number of dimensions</strong>. You are looking only at the first element of <code>shape</code> - but <code>shape</code> can have more than one element:</p> <pre><code>numpy.array([[]]).sha...
python|arrays|numpy
2
377,802
20,454,332
Precision of numpy array lost after tolist
<p>I have a numpy array in which every number has a certain designated precision(using around(x,1).</p> <pre><code>[[ 3. 15294.7 32977.7 4419.5 978.4 504.4 123.6] [ 4. 14173.8 31487.2 3853.9 967.8 410.2 107.1] [ 5. 15323.5 34754.5 3738.7 1034.7 376.1 105.5] [ ...
<p>Something goes wrong on your conversion to strings. With just numbers:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.random.random(10)*30 &gt;&gt;&gt; a array([ 27.30713434, 10.25895255, 19.65843272, 23.93161555, 29.08479175, 25.69713898, 11.90236158, 5.41050686, 18.16481...
numpy
9
377,803
20,814,159
Sample uniformly from multisets
<p>Given the set of integers {1,...,n}, I would like to sample uniformly from the binom{n+k-1}{k} distinct multi-subsets of size k. Is there an efficient way of doing this? </p> <p>For example, the set {1,2,3} has 6 multi-subsets of size 2. These are {1,2}, {2,3}, {1,3}, {1,1}, {2,2}, {3,3}. </p>
<p>Yes. Since you know there are (n+k-1) choose k such multi-subsets, you are probably aware of the <a href="http://en.wikipedia.org/wiki/Stars_and_bars_%28combinatorics%29" rel="nofollow">stars and bars</a> combinatorial problem whose solution provides that formula. The solution to that problem suggests a sampling pro...
python|math|numpy
3
377,804
20,726,661
memory leak in creating a buffer with pandas?
<p>I'm using pandas to do a ring buffer, but the memory use keeps growing. what am I doing wrong?</p> <p>Here is the code (edited a little from the first post of the question):</p> <pre><code>import pandas as pd import numpy as np import resource tempdata = np.zeros((10000,3)) tdf = pd.DataFrame(data=tempdata, colu...
<p>Instead of using <em>concat</em>, why not update the <strong>DataFrame</strong> in place? <code>i % 10</code> will determine which 1000 row slot you write to each update.</p> <pre><code>i = 0 while True: i += 1 tdf.iloc[1000*(i % 10):1000+1000*(i % 10)] = np.random.rand(1000, 3) currentmemory = resourc...
python|pandas
1
377,805
33,228,103
Calculating the L2 inner product in numpy?
<p>I'm thinking about the L2 inner product. </p> <p><img src="https://dl.dropboxusercontent.com/u/407587/screenshots/l2.png"></p> <p>I am specifically interested in performing these calculations using numpy/scipy. The best I have come up with is performing an array-based integral such as <code>numpy.trapz</code>.</p>...
<p>With respect to speed, <code>numpy.inner</code> is probably the best choice for fixed <code>n</code>. <code>numpy.trapz</code> should be converging faster though. Either way, if you are worried about speed, you should also take into account the evaluation of the functions themselves will also take some time.</p> <p...
python|arrays|numpy|inner-product
3
377,806
33,512,899
How would I flatten a pivoted python pandas table into a de-normalized list?
<p>I'm wanting to flatten a pivoted Python Pandas table into a de-normalized list.</p> <p>The table: <a href="https://i.stack.imgur.com/np8DM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/np8DM.png" alt="pivoted pandas table"></a></p> <p>The result I'm after (where the strings are the column valu...
<p>CC_Contact_Id, Question and Question_Answer are all in the index, so to get them out and then put them in the lists you can do:</p> <pre><code>pivot_table.values.reset_index().values.tolist() </code></pre>
python|pandas
0
377,807
33,203,943
Pandas: unify the values of a column for each value of another column
<p>I have a DataFrame that looks like this:</p> <pre><code> user_id category frequency 0 user1 cat1 4 1 user2 cat2 1 2 user2 cat3 4 3 user3 cat3 1 4 user3 cat4 3 </code></pre> <p>For each user I have associated categories with their frequencies. In total, there are 4 categories (...
<p>You can create a pivot table on <code>user_id</code> and <code>category</code>, fill <code>nan</code> values with zero, stack <code>category</code> (which makes the dataframe indexed on <code>user_id</code> and <code>category</code>), and then reset the index to match the desired output.</p> <pre><code>&gt;&gt;&gt;...
python|pandas
1
377,808
33,440,805
Pandas dataframe read_csv on bad data
<p>I want to read in a very large csv (cannot be opened in excel and edited easily) but somewhere around the 100,000th row, there is a row with one extra column causing the program to crash. This row is errored so I need a way to ignore the fact that it was an extra column. There is around 50 columns so hardcoding the ...
<p>pass <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html#pandas.read_csv"><code>error_bad_lines=False</code></a> to skip erroneous rows:</p> <blockquote> <p>error_bad_lines : boolean, default True Lines with too many fields (e.g. a csv line with too many commas) will by default c...
python|csv|pandas
130
377,809
33,499,568
Split Series by string length
<p>I have more than 1M rows and want to split a Series of strings like <code>123456789</code> (length=9) into 3 Series (like MS Excel can do):</p> <pre><code>c1 c2 c3 123 456 789 ... ... ... </code></pre> <p>I see <code>.str.split</code> function which needs some separator and <code>.str.slice</code> which gives on...
<p>You may use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html#pandas.Series.str.extract" rel="nofollow"><code>str.extract</code></a>:</p> <pre><code>&gt;&gt;&gt; df s11 0 123456789 1 987654321 &gt;&gt;&gt; df['s11'].str.extract('(.{3,3})' * 3) 0 1 2 ...
python|string|pandas|split
2
377,810
33,354,576
Pandas: speed up df.loc based on repeat index values
<p>I have the pandas DataFrame</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({ 'x': ['a', 'b', 'c'], 'y': [1, 2, 2], 'z': ['f', 's', 's'] }).set_index('x') </code></pre> <p>from which I would like to select rows based on values of the index (<code>x</code>) in the selection arra...
<p>You can get a decent speedup by using <code>reindex</code> instead of <code>loc</code>:</p> <pre><code>df.reindex(selection) </code></pre> <p>Timings (version 0.17.0):</p> <pre><code>&gt;&gt;&gt; selection2 = selection * 100 # a larger list of labels &gt;&gt;&gt; %timeit df.loc[selection2] 100 loops, best of 3: 2...
python|performance|pandas|dataframe
5
377,811
33,448,807
how to write an entire list to a data structure in python
<p>So the problem I am facing is that I want to create a datastructure which have like 46 items from my pandas dataframe. So I have the entire list of column name and have pandas dataframe in place.</p> <p>So is there anyway that we can transform each row of pandas into an object of my datastructure.</p> <p>So say:</...
<p>Assuming, your pandas dataframe is called df</p> <pre><code>for _, row in df.iterrows(): single_row = list(row) print(single_row) # or whatever you want to do with it. </code></pre>
python|class|pandas|data-structures
0
377,812
33,266,752
Removing matplotlib's dependencies for numpy (and using Apple's application loader)
<p>I am trying to upload an app to the Mac app store. I have used py2app to create an application bundle, code signed the frameworks and executables, created a .pkg using <code>productbuild</code> and signed that too. Everything seems fine until I use application loader. Here is the error message I get:</p> <pre><c...
<p>I managed to solve the issue with Apple's application loader. As mentioned in some of the responses to my original question, numpy is too deeply integrated into matplotlib. There is no easy way to rewrite, substitute, or remove numpy. To resolve the error message from application loader, you need to remove one pa...
python|macos|numpy|matplotlib|application-loader
0
377,813
9,359,234
multiprocess or multithread? - parallelizing a simple computation for millions of iterations and storing the result in a single data structure
<p>I have a dictionary D of {string:list} entries, and I compute a function f( D[s1],D[s2] ) --> float for a pair of strings (s1,s2) in D.</p> <p>Additionally, I have created a custom matrix class LabeledNumericMatrix that allows me to perform assignments such as m[ ID1, ID2 ] = 1.0 .</p> <p>I need to calculate f(x...
<h2>First option - a <em>Server Process</em></h2> <p>Create a <em>Server process</em>. It's part of the Multiprocessing package which allows parallel access to data structures. This way every process will access the data structure directly, locking other processes.</p> <p>From <a href="http://docs.python.org/dev/librar...
python|multithreading|numpy|multiprocess
6
377,814
9,376,531
ValueError("Denominator polynomial must be rank-1 array.")
<p>I've got the following code in <a href="http://ofan666.blogspot.in/2011/04/lti-transient-response-analysis-using.html" rel="nofollow">lti transient response analysis using Python(numpy, scipy, matplotlib)</a>. I am new in python. I have a transfer matrix which I have to plot.</p> <p>I came across <a href="http://ww...
<p>Part of the problem is that the num/den you are passing is not a well formed matrix. In your code you have:</p> <pre><code>num01 = [-2383.3] den01 = [1.0,160.3460,-1962.0,-314598.852] </code></pre> <p>This will not work very well because as far as numpy is concerned you're trying to create a matrix, I realize it'...
python|numpy|scipy
0
377,815
6,216,881
Python interp1d vs. UnivariateSpline
<p>I'm trying to port some MatLab code over to Scipy, and I've tried two different functions from scipy.interpolate, <a href="http://docs.scipy.org/doc/scipy-dev/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d" rel="noreferrer">interp1d</a> and <a href="http://docs.scipy.org/doc/scipy-dev...
<p>I just ran into the same issue.</p> <h1>Short answer</h1> <p>Use <a href="http://docs.scipy.org/doc/scipy-dev/reference/generated/scipy.interpolate.InterpolatedUnivariateSpline.html#scipy.interpolate.InterpolatedUnivariateSpline" rel="noreferrer">InterpolatedUnivariateSpline</a> instead:</p> <pre><code>f = Interp...
python|matlab|numpy|scipy|interpolation
19
377,816
66,478,294
Python - issues with using a for loop to select data from two separate time ranges of a dataframe column
<p>I'm trying to filter data in a pandas dataframe by two time ranges in which the data were calibrated. The dataframe column I want to filter is headered &quot;CH4_ppm&quot;.</p> <p>I try and iterate through calibration start and end times using a for loop to select only the data within these two time ranges, but only...
<p>You code doesn't work for several reasons. First</p> <pre><code>df[&quot;cal_key&quot;].loc[df[&quot;cal_key&quot;].isnull()] = 0 </code></pre> <p>is index chaining and is unlikely to work. It should have been:</p> <pre><code>df.loc[df[&quot;cal_key&quot;].isnull(),&quot;cal_key&quot;] = 0 </code></pre> <p>Even then...
python|pandas|numpy|datetime|for-loop
1
377,817
66,350,897
Use integer for bin
<p>Given this code</p> <pre><code>df=pd.DataFrame({&quot;num&quot;:[1,2,3,4,5,6]}) bins = pd.IntervalIndex.from_tuples([(0, 2), (2,3), (3,6)]) df['bin']=pd.cut(df.num, bins, labels=False) </code></pre> <p>The result is</p> <pre><code> num bin 0 1 (0, 2] 1 2 (0, 2] 2 3 (2, 3] 3 4 (3, 6] 4 5 (3, 6]...
<p>it turns out <code>df['bin_num']=df['bin'].cat.codes+1</code> will do</p>
python-3.x|pandas
0
377,818
66,459,395
Summing lists in dataframe cells
<p>I have dataframes containing list cells:</p> <pre><code>a=pd.DataFrame([[[1,0,1],[0,1,0]],[[0,0,1],[0,1,0]],[[0,0,1],[0,1,0]]]) b=pd.DataFrame([[[0,0,1],[0,1,0]],[[0,0,1],[0,1,0]],[[0,0,1],[0,1,0]]]) c=pd.DataFrame([[[1,0,1],[0,0,0]],[[1,0,0],[0,1,0]],[[1,0,1],[0,0,0]]]) </code></pre> <p>How do I add them position w...
<p>Change it to <code>numpy</code> <code>array</code></p> <pre><code>out = a.applymap(np.array) + b.applymap(np.array) Out[135]: 0 1 0 [1, 0, 2] [0, 2, 0] 1 [0, 0, 2] [0, 2, 0] 2 [0, 0, 2] [0, 2, 0] </code></pre>
pandas|dataframe
2
377,819
66,562,908
Reassigning the calculated group-by column to the original dataframe
<p>Hopefully I am asking this question the right way - thank you to the person who pointed out my mistakes earlier.</p> <p>I have a dataframe (dft) of stock codes with prices, for e.g.:</p> <pre><code> Date Open High Low Close Volume AdjClose StockCode 37563 2020-08-03 4.63 4.63 4.50 ...
<p>You can make the assignment to a new column within each group, as follows. The main bit is <code>.apply(lambda g: g.assign(...))</code> that assigns the right values for each group <code>g</code>. Note I do not have <code>ta.MA</code> package so I am using the standard Pandas rolling functionality, I also set <code>...
python|pandas|group-by|pandas-groupby|data-manipulation
0
377,820
66,368,087
Group by mean for element with value >0
<pre><code>df=pd.DataFrame({&quot;x&quot;:[1,2,3,0],&quot;y&quot;:[1,1,1,1]}) df.groupby(&quot;y&quot;).agg(x_sum=(&quot;x&quot;,np.mean)) </code></pre> <p>This code gives average of x, the output is 1.5 <code>((1+2+3+0)/4=1.5)</code> but I want average of x where the number of larger than 0, so the output should be <c...
<p>Replace not greater like <code>0</code> in <code>x</code> column to <code>NaN</code>:</p> <pre><code>df.x = df.x.where(df.x.gt(0)) #alternative #df.x = df.x.mask(df.x.le(0)) print (df) x y 0 1.0 1 1 2.0 1 2 3.0 1 3 NaN 1 df1 = df.groupby(&quot;y&quot;).agg(x_sum=(&quot;x&quot;,np.mean)) print (df1) ...
python-3.x|pandas
0
377,821
66,446,802
Combining two dataframes so that the values in one dataframe become headers in the other
<p>My first data frame d1 is something like this.</p> <pre><code> num value 0 1 229 1 2 203 2 3 244 </code></pre> <p>The second one, d2:</p> <pre><code> num person cash 0 1 person1 29 1 1 person2 81 2 2 person1 17 3 2 person2 75 4 3 person1 62 5 3 person3 55 </code></pre> <p>A...
<p>Try pivot <code>df2</code> and merge:</p> <pre><code>df1.merge(df2.pivot('num','person','cash'), on='num') </code></pre> <p>Output:</p> <pre><code> num value person1 person2 0 1 229 29 81 1 2 203 17 75 2 3 244 62 55 </code></pre> <hr /> <p><strong>...
python|pandas|dataframe
3
377,822
66,733,823
iterate a certain column to extract its values to a new column
<p>The 'POLYLINE' column includes all GPS points that a car travels at a certain time (x-axis, y-axis). I need to draw the points in a scatter plot.</p> <p>The following are some values for POLYLINE column:- <a href="https://i.stack.imgur.com/ORzPI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ORzP...
<p>I'd rearrange the original data as the following:</p> <pre><code>df = pd.DataFrame.from_dict({ (i, j): {'x': x, 'y': y} for i, P in taxi.POLYLINE.iteritems() for j, (x, y) in enumerate(P) }, 'index').rename_axis(['taxi', 'time']) </code></pre> <p>This is just an idea. Take it if you want it.</p>
python|pandas|dataframe|gps|scatter-plot
1
377,823
66,513,290
Fetching the dataset for convolutional neural network ( CNN ) with TensorFlow 2.0 (python 3)
<p>I understand how fetch dataset from public TensorFlow Datasets (for example &quot;mnist')</p> <pre><code>dataset = tfds.load( 'horses_or_humans' , split=tfds.Split.TRAIN ) </code></pre> <p>How fetch dataset for my image dataset ?</p>
<p>your question is somewhat inaudible, you can search in tensorflow datasets for get any database you want to use. TensorFlow Datasets is a collection of datasets ready to use, with TensorFlow or other Python ML frameworks, such as Jax. All datasets are exposed as tf.data.Datasets , enabling easy-to-use and high-perfo...
python|tensorflow|dataset
0
377,824
66,361,446
Iterate over single row in pandas
<p>I'm isolating a subset from a dataframe, and trying to convert the headers into values. Here is the subset I'm working with</p> <p><a href="https://i.stack.imgur.com/kG5vX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kG5vX.png" alt="single row dataframe with headers reading out a series of mVs...
<p>here is your solution:-</p> <p>write this code outside of <code>function</code>:-</p> <pre><code>df=df.reset_index(drop=True) df=df.drop(['Wavelength'], axis=1) df = df.columns.to_frame().T.append(df, ignore_index=True) df.columns = range(len(df.columns)) </code></pre> <p>Now just use <code>apply()</code> method:-</...
python-3.x|pandas|dataframe
0
377,825
66,449,989
How to filter hours in Pandas Dataframe
<p>If I've a pandas dataframe and I'd like to filter certain hours of every day, for example all data between 10:00 and 16:00</p> <pre><code> time open high low close tick_volume spread real_volume 0 2021-02-23 15:25:00 114990.0 115235.0 114980.0 115185.0 55269 ...
<p>This should do the trick:</p> <pre><code>import pandas as pd df = pd.read_excel(path) df['time'] = pd.to_datetime(df['time']) #convert column to datetime if not already in that format df.set_index(['time'], inplace=True) #temporarily put time column into index df = df.between_time('10:00','16:00') #filter between ti...
python|pandas|dataframe|filter
1
377,826
66,578,456
Python+Pandas; How to proper merge a dictionary of lists of dataframes and save to xlsx or csv as single table
<p>I'm going to scrape a database which was placed in a public web-site in most user-unfriendly way - as a table with thousands of pages. Each page structure is identical and URLs differ only by page number.</p> <p>I tried several options with bf4 and pandas and ended up with following code:</p> <pre><code>import panda...
<ol> <li>pandas by default prints dataframes only partly. try setting <code>pd.set_option('display.max_rows', None)</code> before the printing the dataframe.</li> <li>try to iterate through each df of the list and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html" rel="nof...
python|pandas|web-scraping
0
377,827
66,702,091
How to pass tensor placeholder in for loop range?
<p>I need to set the range of a for loop according to the input in my tensorflow graph:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>X = tf.placeholder(tf.int32,shape=[3...
<p>Replace range with tf.range.<br /> Example in tensorflow 2.x</p> <pre><code>import tensorflow as tf tf.compat.v1.disable_eager_execution() @tf.function def loop_tensor(start, end): for t in tf.range(start, end): print(t) X = tf.compat.v1.placeholder(tf.int32, shape=[3, None]) videos_timesteps_...
tensorflow
0
377,828
66,659,020
How to replace certain elements of a NumPy array via an index array
<p>I have an numpy array <code>a</code> that I would like to replace some elements. I have the value of the new elements in a tuple/numpy array and the indexes of the elements of <code>a</code> that needs to be replaced in another tuple/numpy array. Below is an example of using python to do what I want.How do I do this...
<p>The list of indices indicating which elements you want to replace should be a Python <code>list</code> (or similar type), not a <code>tuple</code>. Different items in the selection tuple indicate that they should be selected from different axis dimensions.</p> <p>Therefore, <code>a[(2, 4, 6)]</code> is the same as <...
python|numpy
3
377,829
66,348,567
Title words in a column except certain words
<p>How could I title all words except the ones in the list, keep?</p> <pre><code>keep = ['for', 'any', 'a', 'vs'] df.col `` 0 1. The start for one 1 2. Today's world any 2 3. Today's world vs. yesterday. </code></pre> <p>Expected Output:</p> <pre><code> number title 0 1 The Start for...
<p>Here is one way of doing with <code>str.replace</code> and passing the replacement function:</p> <pre><code>def replace(match): word = match.group(1) if word not in keep: return word.title() return word df['title'] = df['title'].str.replace(r'(\w+)', replace) </code></pre> <hr /> <pre><code> n...
python|python-3.x|pandas
17
377,830
66,600,026
Is there a Python package for plotting a spike map
<p>A spike map (as shown in the image below, implemented with <a href="https://observablehq.com/@d3/spike-map" rel="nofollow noreferrer">D3.js</a>) is a method for displaying differences in the magnitude of a certain discrete, abruptly changing phenomenon such as counts of people. <a href="https://i.stack.imgur.com/jqj...
<p>You could try with a Ridge Plot. It's not exactly the same, but maybe it can work for you. The implementation in seaborn looks like this:</p> <pre><code>import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt sns.set_theme(style=&quot;white&quot;, rc={&quot;axes.facecolor&quot;: ...
python|matplotlib|maps|geopandas
0
377,831
66,367,502
df.column.any() < 1 giving True when not a single value is less than 1 python pandas
<p>I am getting a really strange boolean result from my pandas Dataframe when running a query to see if any values in a particular column are less than 1. My <code>df</code> looks as such with columns <code>marketcap</code> and <code>assets</code>:</p> <pre><code> marketcap assets 0 11730364.0 36675000.0 ...
<p><em>why this is True and what it thinks is less than 1.</em></p> <p>You are doing:</p> <pre><code>df.marketcap.any() &lt;= 1 </code></pre> <p><code>df.marketcap.any()</code> does evaluate to <code>True</code> as you have one or more non-zero elements in marketcap, so comparison is</p> <pre><code>True &lt;= 1 </code>...
python|pandas
1
377,832
66,525,331
What is the name of this image similarity/ distance based metric?
<p>I used the following code to calculate the similarity between images 1 and 2 (i1 and i2). 1=exactly similar while 0=very different. I'd like to know what method this algorithm is using (i.e. Euclidian distance or..?) Thank you.</p> <pre><code>import math i1=all_images_saved[0][1] i2=all_images_saved[0][2] i1_norm = ...
<p>Looks like <a href="https://en.wikipedia.org/wiki/Cosine_similarity" rel="nofollow noreferrer">cosine similarity</a>. You can check it gives the same results as:</p> <pre><code>from scipy import spatial cosine_distance = spatial.distance.cosine(i1.flatten(), i2.flatten()) cosine_similarity = 1 - cosine_distance </...
image|numpy|distance
1
377,833
66,393,003
KFServing pod "error: container storage-initializer is not valid"
<p>I am new to KFServing and Kubeflow.</p> <p>I was following <a href="https://github.com/kubeflow/kfserving/tree/master/docs/samples/v1alpha2/tensorflow" rel="nofollow noreferrer">https://github.com/kubeflow/kfserving/tree/master/docs/samples/v1alpha2/tensorflow</a> to deploy a simple inference service.</p> <p>However...
<p><code>storage-initializer</code> is an <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" rel="nofollow noreferrer">init container</a>, so if you describe the pod you won't find it in the <code>containers</code> section of pod spec but in the <code>initContainers</code> section.</p> <pre><...
tensorflow-serving|kubeflow|kubeflow-pipelines|knative-serving
0
377,834
66,376,343
Repeating blocks in numpy arrays
<p>I have an array that looks like this:</p> <pre><code>A = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] </code></pre> <p>and from it, I'd like to create an array that looks like this:</p> <pre><code>B = [[1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 1, ...
<p>What you're looking for is a block matrix. <a href="https://numpy.org/doc/stable/reference/generated/numpy.block.html" rel="nofollow noreferrer">See this documentation</a>. For your specific application, each block would just be a constant (<code>A[i][j]</code>) times a matrix of ones (<code>np.ones(n)</code>).</p...
python|numpy
0
377,835
66,609,127
Pandas: returning last element of column value
<p>I created the following function to retrieve data from an internal incident management system:</p> <pre><code>def get_issues(session, query): block_size = 50 block_num = 0 start = 0 all_issues = [] while True: issues = sesssion.search_issues(query, start, block_size, expand='changelog'...
<p>Here it is:</p> <pre><code>df['new_group'] = df.apply(lambda x: x['groups'][-1], axis = 1) </code></pre> <p><strong>UPDATE:</strong> If you get an IndexError with this, it means that at least one one your lists in empty. You can try this:</p> <pre><code>df['new_group'] = df.apply(lambda x: x['groups'][-1] if x['gro...
python|pandas
1
377,836
66,365,013
Python Pandas - add column on a specific row, add specific row from one dataframe to another
<p>Have being trying this desperately for 7 hours and still hasnt figured out a solution. So I have 2 Dataframes that I want to combine,using python pandas, with the below conditions:</p> <ol> <li>from the name in 'first table', add the remaining columns from the 'second table' with the same name</li> <li>if name canno...
<p>Use outer join in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>DataFrame.merge</code></a> and then set <code>NaN</code> (default value) in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.where.html" re...
python|excel|pandas|dataframe
1
377,837
66,517,434
Keras throwing error: ('Keyword argument not understood:', 'init') and ('Keyword argument not understood:', 'dim_ordering')
<p>I've built the following model with Keras from Tensorflow (version = 2.2.4-tf)</p> <pre><code>model = tf.keras.Sequential() model.add(Convolution2D(24, 5, 5, padding='same',init='he_normal', input_shape = (target_Width,target_Height, 3),dim_ordering=&quot;tf&quot;)) model.add(Activation('relu')) model.add(GlobalAver...
<p>It seems that you are trying to use <a href="https://faroit.com/keras-docs/1.0.1/layers/convolutional/" rel="nofollow noreferrer">keras.layers.convolutional.Convolution2D</a> instead of <a href="https://keras.io/api/layers/convolution_layers/convolution2d/" rel="nofollow noreferrer">tf.keras.layers.Conv2D</a>. If th...
python|tensorflow|keras|conv-neural-network
2
377,838
66,744,761
Same weights, implementation but different results n Keras and Pytorch
<p>I have an encoder and a decoder model (<a href="https://github.com/nianticlabs/monodepth2" rel="nofollow noreferrer">monodepth2</a>). I try convert them from Pytorch to Keras using <code>Onnx2Keras</code>, but :</p> <ul> <li>Encoder(ResNet-18) succeeds</li> <li>I build the decoder myself in Keras (with <code>TF2.3</...
<p>Solved!</p> <p>It turns out there's indeed no problem with implementation (at least not significant ones). It's the problem with <code>weights</code> copying.</p> <p>The original weights has (H, W, 3, 3), but TF-model requires dim of (3, 3, W, H), so I permuted it by [3,2,1,0], overlooking the (3, 3) also have thei...
python|tensorflow|keras|computer-vision|pytorch
5
377,839
66,625,669
TensorFlow v1 on Colab, tf.contrib module not found
<p>Trying to train GPT-2 in Google Colab. The cells I'm running look like this:</p> <pre class="lang-py prettyprint-override"><code>!git clone https://github.com/shawwn/gpt-2 -b tpu /content/gpt-2 </code></pre> <p>[...]</p> <pre><code>%tensorflow_version 1.x !pip freeze | grep tensorflow </code></pre> <blockquote> <pre...
<p>Tensorflow 1.15.2 has contrib. In colab, make sure once the Tensorflow 1.x install restart runtime because colab has default 2.x version. I tried same code on colab it worked.</p>
python|tensorflow|google-colaboratory
0
377,840
66,506,266
Best way to reassemble a pandas data frame
<p>Need to reassemble a data frame that is the result of a group by operation. It is assumed to be ordered.</p> <pre><code> Major Minor RelType SomeNulls 0 0.0 0.0 1 1.0 1 NaN NaN 2 NaN 2 1.0 1.0 1 NaN 3 NaN NaN 2 NaN 4 NaN NaN ...
<p>If I understand the question correctly, You could do a <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.transform.html" rel="nofollow noreferrer">transform</a> on the specific columns:</p> <pre><code>df.loc[:, ['Major', 'Minor']] = df.loc[:, ['Major', 'Minor']].transform('ffill') Major Mi...
python|pandas
1
377,841
66,701,344
Saving a DataFrame as .csv, with columns data type: object (list). Load the DataFrame but the columns data type are object (str), what am I missing?
<p>I saved a DataFrame as a .csv file, some of the DataFrame columns are populated with python list objects, but when I reload the same DataFrame, the columns that were populated with python list objects are now populated with python string objects. See code outputs.</p> <pre><code> type(df['col1'][0]) out&gt;&gt;...
<p>The csv file format cannot store arrays, it can only store text.</p>
python|pandas|dataframe|csv
0
377,842
66,528,357
Error in TF 2.3. when mixing eager and non-eager Keras models
<p>I'm having this issue when trying to fit a model in Tenserlfow 2.3, are there any workarounds or solutions to the problem? this error occurs also when i try to predict some records using TensorFlow Neural Network models. I hope someone expert in Tensorflow can find out what is wrong!</p> <p>Code:</p> <pre><code>impo...
<p>The below code works without error. Any specific reason to use commented part below.</p> <pre><code>import tensorflow as tf import numpy as np DO_BUG = True inputs = tf.keras.Input((1,)) outputs = tf.keras.layers.Dense(10)(inputs) model0 = tf.keras.Model(inputs=inputs, outputs=outputs) &quot;&quot;&quot; if DO_BUG...
python|tensorflow|keras|deep-learning|tensorflow2.0
0
377,843
66,696,275
Failure ONNX InferenceSession ONNX model exported from PyTorch
<p>I am trying to export a custom PyTorch model to ONNX to perform inference but without success... The tricky thing here is that I'm trying to use the <em>script-based exporter</em> as shown in the example <a href="https://pytorch.org/docs/stable/onnx.html#tracing-vs-scripting" rel="nofollow noreferrer">here</a> in or...
<p>This points to a model conversion issue. Please open an issue againt the Torch exporter feature. A type (T) has to be bound to the same type for the model to be valid and ORT is basically complaining about this.</p>
python|pytorch|onnx|onnxruntime
0
377,844
66,372,750
Numpy array : how to convert values of a 2D array into a 3D one-hot array
<p>I have a numpy 2D array 'ya' of shape (1000, 20) where each cell has values between 0 and 5. I would like to create a 3D array 'yb' of shape (1000, 6, 20) that I create with np.zeros((1000, 6, 20)), where the cells in dim(1) would take a value 1 in the column corresponding to the value of ya.</p> <p>Example: ya[125,...
<p>Try broadcasting:</p> <pre><code>(a[:,None,:] == np.arange(6)[None,:,None]).astype(int) </code></pre> <p>Sample data:</p> <pre><code>np.random.seed(1) m,n=3,4 a = np.random.randint(0,6, (m,n)) </code></pre> <p>Output:</p> <pre><code>array([[[0, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, ...
python|arrays|numpy
1
377,845
66,547,755
Python Pandas merging 2 tables with inner join:
<p>Hi I am merging two tables with an inner join using pandas but I am getting a weird output. Below I am pasting the two tables: <a href="https://i.stack.imgur.com/JHmeJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JHmeJ.png" alt="enter image description here" /></a></p> <p><a href="https://i.sta...
<p>The data types of zipcode variables in datasets can be different. Check it with the dtype () method. If the data types are different, you can combine them and combine them.</p>
python|pandas
1
377,846
66,491,407
Pivot table with count if
<p>I want to count if the number is higher than 0.1 and then group them by month-year to see which month-year has the most days with more than 0.1 variations.</p> <p>I have a df like these with daily data but only showing month-year index.</p> <p><a href="https://i.stack.imgur.com/ac8Kb.png" rel="nofollow noreferrer"><...
<p>You can <code>stack</code> the dataframe then compare the stacked frame with <code>0.1</code> to create a booolean mask then take <code>sum</code> on <code>level=0</code> to count the values which are greater than <code>0.1</code> per <code>month-year</code>:</p> <pre><code>df.stack().gt(0.1).sum(level=0) </code></p...
python|pandas|dataframe|pandas-groupby|pivot-table
3
377,847
66,683,408
to_dict() function makes a list from dataframe instead of OrderedDict
<p>I am trying to convert a dataframe into an OrderedDict. I tried with the 2 options shown below. None of them result an OrderedDict and I don't know why it doesn't work.</p> <p>Option 1 and 2 result to be lists</p> <pre><code>sales_data = pd.read_csv (&quot;data/sales-data.csv&quot;) Motorcycles = sales_data.loc[sale...
<p>Based on the comment</p> <h2>Creating a test dataframe</h2> <pre><code>df = pd.DataFrame({&quot;A&quot;: [1,2,3], &quot;B&quot;: [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]}) </code></pre> <h2>Printing dataframe</h2> <pre><code>&gt;&gt;&gt; print(df) A B 0 1 a 1 2 b 2 3 c </code></pre> <h2>Associating to_d...
python|pandas
0
377,848
66,353,524
python string replace only special characters keeping non-english alphabets
<p>How can I remove only special characters from a string, but not foreign language characters. When I try the below code, it removes both special characters and non-english alphabets. But I want to remove only special characters (special characters that appear in regular English sentences).</p> <pre><code>import pand...
<p>You can use</p> <pre class="lang-py prettyprint-override"><code>df['name'] = df['name'].str.replace(r'[^\w\s]|_', '', regex=True) </code></pre> <p>In Python 3, all regex shorthand character classes (like <code>\w</code>, <code>\d</code>, <code>\s</code>) are Unicode aware by default, as the <code>re.U</code> (<code>...
regex|pandas|string|dataframe|python-3.8
1
377,849
66,414,775
Extracting multiple values in different rows
<p>I have a dataset</p> <pre><code>ID col1 col2 year 1 A 111,222,3334 2010 2 B 344, 111 2010 3 C 121,123 2011 </code></pre> <p>I wanna rearrange the dataset in the following way</p> <pre><code>ID col1 col2 year 1 A 111 ...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html?highlight=split#pandas.Series.str.split" rel="noreferrer"><code>split</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="noreferrer"><code>explode</code><...
python|pandas
5
377,850
66,622,141
subset pandas with different values but same index
<p>I want to create a dataset from condition on values on another dataset</p> <p>FROM</p> <pre><code> minV maxV 2008-01-02 NaN NaN 2008-01-03 NaN NaN 2008-01-04 -0.022775 NaN 2008-01-07 NaN 0.010179 2008-01-08 -0.039777 NaN 2008-01-09 NaN ...
<p>Assuming we can only have one non-NaN value in a row, we can take <code>max</code> of the row, then drop NaNs with <code>dropna</code>, take sign with <code>np.sign</code> and multiply by -1000:</p> <pre><code>df.max(axis=1).dropna().apply(np.sign) * -1000 </code></pre> <p>Output:</p> <pre><code>2008-01-04 1000.0...
python|pandas
4
377,851
66,364,040
how to reshape/ explode pandas dataframe?
<p>i have this dataframe that have row of each key*id , i want to explode it to id,key1,key2 and remove duplicate rows and keep data_field , i am working with python2.7 but i would glad to a solution that will work both for python2.7 and python3.7</p> <p><strong>dataframe i have:</strong></p> <pre><code>import pandas ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>DataFrame.pivot</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>DataFrame.join</code></a> ...
python|pandas|python-2.7|dataframe
0
377,852
66,367,901
fit_generator not running after the first epoch
<p>I'm practicing with the implementation of RNNs and LSTMs in Keras on R and I was first trying to run some examples from Deep Learning With R book by Chollet; since I'm working with time series I decided to start from the temperature example:</p> <pre><code>dir.create(&quot;~/Downloads/jena_climate&quot;, recursive =...
<p>I had a similar problem with Rstudio but when I use simply R, it works. Could you please check?</p>
python|r|tensorflow|keras|time-series
-1
377,853
66,394,939
Reading a CSV file with irregular number of columns using Pandas
<p>I am trying to read a csv file, which doesn't contain a header line, and it contains an indefinite amount of columns, with pandas.</p> <p>I have search how to work around this, but all the answers that I have found require for me to already know (search by opening the file) the maximum number that a column can have ...
<p>I get the following output</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;"></th> <th style="text-align: right;">0</th> <th style="text-align: right;">1</th> <th style="text-align: right;">2</th> <th style="text-align: right;">3</th> <th style="text-align: right;...
python|pandas|csv
2
377,854
66,427,674
pandas groupby tuple of different length - ValueError: Values not found in passed level: MultiIndex
<p>Edit: example DataFrame for the original error-message found and posted.</p> <p>(As I just recognized, the Error does only appear, if the tuple has a certain length. The example is now adapted.)</p> <p>Original text:</p> <p>I need to group by tuple of different length.</p> <p>For the grouping I'm applying a summary_...
<p>In your case, do not return the dataframe, return the series.</p> <p>When you return the series, Pandas will align the series horizontally. For example:</p> <pre><code>def summary_function(df): return df['value'].agg(['min','mean','max']) df.groupby(['letter','tuple']).apply(summary_function) </code></pre> <p>O...
pandas|group-by|multi-index
1
377,855
66,358,398
replace pandas dataframe None value with dictionary
<p>I have a pandas dataframe called &quot;myRawDF1&quot; and:</p> <pre><code>print(myRawDF1) </code></pre> <p>Result is:</p> <pre><code> stop_price last_trail_price 0 79.74 {'amount': '100.47', 'currency_code': 'USD'} 1 ...
<p>I think you need to use <code>loc</code> access:</p> <pre><code>s = df['last_trail_price'].isna() df.loc[s, 'last_trail_price'] = [{'amount':0.0} for _ in range(s.sum())] </code></pre>
python|pandas|dataframe|dictionary|fillna
1
377,856
66,713,680
Preparing dataset TimeSeries data
<p>So I am working on a project where I have some time series data that I want to predict. The problem is that my dataset consists of different water samples taken from a water source and there are in a single csv file.</p> <p>My dataset looks kinda like this:</p> <pre><code>Date Sample_Name pH temp ...
<p>Let me give it a go as it is not entirely clear what the desired output is, but hopefully will steer you in the right direction</p> <p>Load your example:</p> <pre><code>from io import StringIO data = StringIO( ''' Date Sample_Name pH temp 2009-01-01 ABC1 7.2 12 2009-01-02 ABC2...
pandas|time-series
1
377,857
66,422,795
Is there a way to import csv files into pandas using values of a dictionary for the name of the dataframes?
<p>I Just started with python and am currently trying to import multiple csv files as dataframes. While there are some similar questions, they seem not to be helpfull for my problem. The csv files have the same structure and the names are not how I want them to be when imported as dataframes. A list of dictionaries con...
<p>You can use the file name as the key, something like:</p> <pre class="lang-py prettyprint-override"><code>CSV_dict = [ {'Nr': '0905', 'New_ID': '0905a', 'csvDatei': 'LG__380'}, {'Nr': '0905', 'New_ID': '0905b', 'csvDatei': 'LG__376'}, {'Nr': '0955', 'New_ID': '0955a', 'csvDatei': 'LG__53'}, {'Nr':...
python|pandas|csv|dictionary
1
377,858
66,743,201
Filter a dataframe based specific condition in pandas
<p>I have a dataframe as shown below</p> <p>df:</p> <pre><code>ID Age_days N_30 N_31_90 N_91_180 N_181_365 Group 1 201 60 15 30 40 Good 2 20 2 15 5 20 Normal 3 10 4 0 0...
<p>Use <code>Boolean Mask</code> to filter conditions:</p> <pre><code>m1 = (df['Age_days'] &lt;= 30) &amp; ((df['N_31_90'] !=0) | (df['N_91_180'] !=0) | (df['N_181_365'] !=0)) m2 = (df['Age_days'] &lt;= 90) &amp; ((df['N_91_180'] !=0) | (df['N_181_365'] !=0)) m3 = (df['Age_days'] &lt;= 180) &amp; (df['N_181_365'] !=0) ...
python|python-3.x|pandas|dataframe
1
377,859
66,538,245
How to move each value in a row one position by a position in the array?
<p>How to move the values in the field by scrolling by one position a position in sequence? Then replace unnecessary values with the number zero?</p> <p>Example: My array</p> <pre><code>np.array([[51 52 53 54 55 56 57] [41 42 43 44 45 46 47] [31 32 33 34 35 36 37] [21 22 23 24 25 26 27] [11 12 13 14 15 16 17]]) </...
<p>I assume that the number of elements shifted to the right is also arbitrary (<code>elements_shifted &gt; 0</code>). Here is my first attempt:</p> <pre><code>import numpy as np a = np.array([[51, 52, 53, 54, 55, 56, 57], [41, 42, 43, 44, 45, 46, 47], [31, 32, 33, 34, 35, 36, 37], ...
python|numpy
1
377,860
66,478,495
I've downloaded bert pretrained model 'bert-base-cased'. I'm unable to load the model with help of BertTokenizer
<p>I've downloaded bert pretrained model 'bert-base-cased. I'm unable to load the model with help of BertTokenizer. I'm trying for bert tokenizer. In the bert-pretrained-model folder I have config.json and pytorch_model.bin.</p> <pre><code>tokenizer = BertTokenizer.from_pretrained(r'C:\Downloads\bert-pretrained-model')...
<p>Whats' the version of transformers you are using?. I had a similar issue, the solution was to upgrade the transformers to the latest(like 4.3.3 currently) version (I was using an old 2..1 version because I had to make an older code run) and it worked. Looks like older versions of transformers have this issue with lo...
nlp|pytorch|bert-language-model|huggingface-transformers|huggingface-tokenizers
0
377,861
66,434,419
Float values in a list become string when converting the list to a numpy array
<p>I have a list (scores) that contains float values and I want to convert it to a numpy array. However, after converting it, the type of the values changes from float to string. This is what I have written:</p> <pre><code>scores = [5.0, 5.0, 4.0, 4.0, 5.0, 5.0, 5.0] import numpy as np scores = np.array(scores) scores...
<p>I don't think they are converting to a string I tried your code and added a simple line of addition between two indices and the result is not in a string means they are not concatenated they are actual decimal numbers.</p> <pre><code>scores = [5.0, 5.0, 4.0, 4.0, 5.0, 5.0, 5.0] import numpy scores = numpy.array(sco...
python|arrays|list|numpy
0
377,862
66,580,650
Merge Row based on Condition
<p>i have df like this</p> <pre><code> Date Description Debit Credit Balance originalIdx 0 01-03-19 AAAA NaN NaN 49Cr 0 1 01-03-19 ASSS NaN 6,000.00 55Cr 1 2 NaN XYZ ABC saa NaN 1 3 01-03-19 ABZ 2...
<p>Assuming that <code>Date</code> will have <code>NaN</code> if the row needs to be merged, here's the code.</p> <p>first create a dummy column <code>merged</code>. It will merge all the values of <code>Description</code>, <code>Debit</code>, and <code>Credit</code>. It will only merge if the value is alpha (excludes ...
python|pandas|dataframe
2
377,863
16,096,143
why doesn't NumPy import in idle 3.30 on Ubuntu 12.10 64 Bit
<p>I installed NumPy by running the following in a linux shell:</p> <pre><code>sudo apt-get install python-numpy </code></pre> <p>In Idle for python 3.30 when I import numpy it outputs the following:</p> <pre><code> Python 3.3.0 (default, Sep 29 2012, 17:14:58) [GCC 4.7.2] on linux Type "copyright", "credits" or...
<p>On my ubuntu 12.10. I use <em>pip</em> to install packages. I use Python3.2.</p> <pre><code>sudo apt-get install python3-pip sudo pip-3.2 install numpy </code></pre> <p>I have tried this and installed <em>numpy</em> successfully.</p>
python|linux|numpy|python-idle|ubuntu-12.10
0
377,864
16,389,605
numpy.unique generates a list unique in what regard?
<p>If you input an array with general objects to <code>numpy.unique</code>, the result will be unique based upon what?</p> <p>I have tried:</p> <pre><code>import numpy as np class A(object): #probably exists a nice mixin for this :P def __init__(self, a): self.a = a def __lt__(self, other): r...
<p>Assuming the duplicate <code>A(2)</code> is a typo, I think you simply need to define <code>__hash__</code> (see the <a href="http://docs.python.org/2/reference/datamodel.html#object.__hash__" rel="nofollow">docs</a>):</p> <pre><code>import numpy as np from functools import total_ordering @total_ordering class A(o...
python|numpy
4
377,865
16,359,212
Matlab to Python Code
<p>I have piece of code in matlab: </p> <pre><code>Tf=eye(2); Tb=eye(2); Tt=eye(2); n=250; f=zeros(2,n); for i=1:n f(:,i)=Tf*f(:,i-1); end </code></pre> <p>I tried to change it to Python code:</p> <pre><code>Tf=eye(2) n=250 f=numpy.zeros((2,n)) for i in range (n) f[:,i]=numpy.dot(Tf, f[:,i-1]) </code...
<p>As @CharlesBrunet notes, there's a few issues with the python implementation, which should be:</p> <pre><code>import numpy Tf=numpy.eye(2) n=5 f=numpy.zeros((2,n)) for i in range(n): f[:,i]=numpy.dot(Tf, f[:,i-1]) </code></pre> <p>The resulting <code>f</code> is:</p> <pre><code>[[ 0. 0. 0. 0. 0.] [ 0...
python|matlab|numpy
0
377,866
57,657,233
Using Pandas rolling function on text columns
<p>I have a pandas dataframe with column values in string format and a datetime index. I want to create a new column which will have a list of values of a column for last two days. Is it possible to achieve this using pandas?</p> <p>original datafarme:</p> <pre><code> date col1 col2 0 2018-07-08 a b 1 20...
<pre><code>df.iloc[:,2].shift(2)+ ',' +df.iloc[:,2].shift(1) </code></pre> <p><strong>Edit</strong></p> <p>We could extend this to a more generic setting, </p> <p>Define a customized rolling concat function,</p> <pre><code>rolling_cat = lambda s, n: pd.Series(zip(*[s.shift(x+1) for x in range(n)])).str.join(',') </...
python-3.x|pandas
5
377,867
57,684,544
In each row of a numpy array, I have an int, and a python list of ints. How do I convert this list into a numpy int array, without using pandas?
<p>I have a numpy array, where each row contains a list of a int, and a python list of ints. How do I convert the lists into numpy arrays? I am working with very large arrays, and I would like to avoid using Pandas as loading it into pandas will take more memory. </p> <p>Sample variable:</p> <pre><code>new = np.array...
<p>You can use a list comprehension and convert each <code>list</code> to an <code>np.array</code>:</p> <pre><code>result = np.array([[row[0], np.array(row[1])] for row in new]) print(result) </code></pre> <p>Output:</p> <pre><code>[[0 array([ 4928722, 3922609, 14413953, 10103423, 8948498])] [1 array([12557217, ...
python|numpy
1
377,868
57,304,398
Write the values of a customer group into a Series
<p>I have a <code>dataframe</code> which has various entries of customers. These customers, which has different customer numbers, belong to certain customer groups (contract, wholesaler, tender, etc.). I have to sum some of these values of the <code>dataframe</code> into a <code>Series</code> for each customer group (e...
<p>If you want to sum the sales for every group you may want to look into panda's </p> <p><code>df.groupby()</code> maybe</p> <p>I'm trying to reproduce what you want it would look like this</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame() &gt;&gt;&gt; df['cust_numb']=[1,2,3,4,5] &gt;&gt;&gt; df['group']=['group1','g...
pandas|dataframe
0
377,869
57,572,564
How do I know is there a value in another column?
<p>I have a df something like this:</p> <pre><code>lst = [[30029509,37337567,41511334,41511334,41511334]] lst2 = [35619048] lst3 = [[41511334,37337567,41511334]] lst4 = [[37337567,41511334]] </code></pre> <pre><code>df = pd.DataFrame() df['0'] = lst, lst2, lst3, lst4 </code></pre> <p>I need to count how many times t...
<p><code>str(df['0'])</code> gives a string representation of column 0 and so includes all the data. You will then see that </p> <pre><code>'41511334' in str(df['0']) </code></pre> <p>gives <code>True</code>, and you assign this to every row of the 'new' column. You are looking for something like</p> <pre><code>df['...
python|pandas
0
377,870
57,428,051
Handling string values when rounding a dataframe column
<p>I have a data-frame (<code>df</code>) that looks like</p> <pre><code> DATE_OF_BIRTH AGE 0 1974-03-28 43.0095412 1 NOT KNOWN NOT KNOWN 2 1970-11-27 46.3419843 3 1974-05-09 42.8944168 4 1985-03-14 32.0474122 </code></pre> <p>I would like to round the <code>AGE</code> ...
<p>I suggest convert non numeric and not datetimes values to missing values with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.ht...
python|pandas
2
377,871
57,609,112
Problem when using cx_Freeze: "cannot import name 'tf2'"
<p>I have a code in python and I used cx_Freeze to convert it to an .exe. This task works without any error. But when I try to run my .exe the following error happens:</p> <blockquote> <p>from tensorflow.python import tf2<br> ImportError: cannot import name 'tf2'</p> </blockquote> <p>My <code>ann.py</code> code i...
<p>Try to add <code>"tensorflow"</code> to the <code>packages</code> list in your <code>setup.py</code> script:</p> <pre><code> packages = ["idna", "tensorflow"] </code></pre>
python|windows|tensorflow|cx-freeze
0
377,872
57,545,377
Compute mean of values for each index across multiple arrays
<p>Currently I'm looking for a compact and more efficient solution (rather than multiple nested for loops) to compute mean of values given an index across multiple numpy array.</p> <p>Specifically given </p> <pre><code>[array([2.4, 3.5, 2.9]), array([4.5, 1.8, 1.4])] </code></pre> <p>I need to compute the following ...
<p>It's possible by just one line command with <code>numpy</code></p> <pre><code>import numpy as np arr=[np.array([2.4, 3.5, 2.9]), np.array([4.5, 1.8, 1.4])] np.mean(arr, axis = 0) </code></pre>
python|numpy|mean
1
377,873
57,507,802
How to merge two dataframe based on time intervals and transform them
<p>I have two dataframes, first one is creating by users manually and second one is errors from machines. I want to merge them based on time interval in first dataframe(df_a)</p> <p>Here are the dataframes;</p> <pre><code>d_a = {'Station' : ['A1','A2'], 'Reason_a' : ['Electronic','Feed'], 'StartTime_a' ...
<p>I would solve it by merging the tables on <code>station</code> and calculating the intersections :D</p> <pre><code>import numpy as np df = pd.merge(df_a, df_b, on="Station") # Convert to date for datevar in ["StartTime_a", "StartTime_b", "EndTime_a", "EndTime_b"]: df[datevar] = pd.to_datetime(df[datevar]) # ...
python|pandas|datetime|conditional-statements|nested-loops
2
377,874
57,570,043
Filter data in pytorch tensor
<p>I have a tensor <code>X</code> like <code>[0.1, 0.5, -1.0, 0, 1.2, 0]</code>, and I want to implement a function called <code>filter_positive()</code>, it can filter the positive data into a new tensor and return the index of the original tensor. For example:</p> <pre><code>new_tensor, index = filter_positive(X) n...
<p>Take a look at <code>torch.nonzero</code> which is roughly equivalent to <code>np.where</code>. It translates a binary mask to indices:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; X = torch.tensor([0.1, 0.5, -1.0, 0, 1.2, 0]) &gt;&gt;&gt; mask = X &gt;= 0 &gt;&gt;&gt; mask tensor([1, 1, 0, 1, 1,...
python|pytorch
25
377,875
57,517,121
How can I do the centercrop of 3D volumes inside the network model with pytorch
<p>In <code>keras</code>, there is <code>Cropping3D</code> layer for centercropping tensors of 3D volumnes inside the neural network. However, I failed to find out anything similar in pytorch, though they have <code>torchvision.transforms.CenterCrop(size)</code> for 2D images.</p> <p>How can I do the cropping inside t...
<p>In PyTorch you don't necessarily need to write layers for everything, often you can just do what you want directly during the forward pass. The basic rules you need to keep in mind when operating on torch tensors for which you will need to compute gradients are</p> <ol> <li>Don't convert torch tensors to other type...
python|3d|conv-neural-network|pytorch|crop
0
377,876
57,544,161
How to fix 'Expected object of backend CUDA' when trying to apply_tfms in custom LearnerCallback
<p>Very new to machine learning, fastai, pytorch, and python, and I was trying to adapt a LearnerCallback to do transformations after manually modifying the images. When I start my learn.fit_one_cycle, it's immediately interrupted as shown below:</p> <p>I've tried sticking <code>.to(torch.device('cuda'))</code> every...
<p>The problem that you have here is that some of your tensors are on CPU and some are on GPU.</p> <p>You have to make sure that all your tensors are on the same device (either GPU or CPU depending on the situation) to get rid of this error. If I remember correctly, fastai <code>get_transforms</code> will create trans...
python|pytorch|fast-ai
0
377,877
57,342,987
Translating Pytorch program into Keras: different results
<p>I have translated a pytorch program into keras.</p> <p>A working Pytorch program:</p> <pre><code>import numpy as np import cv2 import torch import torch.nn as nn from skimage import segmentation np.random.seed(1) torch.manual_seed(1) fi = "in.jpg" class MyNet(nn.Module): def __init__(self, n_inChannel, n_...
<p>Two major mistakes that I see (likely related):</p> <ol> <li>The last convolutional layer in the original model does not have an activation function, while your translation uses <code>relu</code>.</li> <li>The original model uses <code>CrossEntropyLoss</code> as loss function, while your model uses <code>categorica...
tensorflow|keras|conv-neural-network|pytorch|image-segmentation
1
377,878
57,341,269
How to count how many times every year shows up in my dataset in python
<p>wondering if anyone can help me.</p> <p>I have a dataset with the column "created_at" which has rows like this </p> <pre><code>data = pd.read_csv("dataset.csv") col = data["created_at"] print(col.head()) print(col.tail()) 0 2014-06-01 21:03:16 1 2014-06-01 09:06:48 2 2014-06-01 00:31:52 3 2014-06-04 1...
<p>First convert your column into <code>datetime</code> type because I see that it is in <code>object</code> type:</p> <pre><code>data['created_at'] = pd.to_datetime(data['created_at']) </code></pre> <p>Now extract the <code>year</code> part using <code>dt</code>:</p> <pre><code>data['year'] = data['created_at'].dt....
python|python-3.x|pandas
1
377,879
57,711,758
How to Convert Datetime to String in Python?
<p>I want to make a line chart by this code :</p> <pre><code>df = pd.DataFrame.from_dict({ 'sentencess' : sentencess, 'publishedAts' : publishedAts, 'hasil_sentimens' : hasil_sentimens }) df.to_csv('chart.csv') df['publishedAts'] = pd.to_datetime(df['publishedAts'], errors='coerce') by_day_sentiment = df.groupby([pd...
<p>Use <code>strftime('%Y-%m-%d %H:%M:%S')</code></p> <p><strong>Ex:</strong></p> <pre><code>from pandas import Timestamp from numpy import nan data = {'Negatif ': {Timestamp('2019-08-26 00:00:00', freq='D'): 2.0, Timestamp('2019-08-27 00:00:00', freq='D'): 4.0, Timestamp('2019-08-28 00:00:00', freq='D'): 2.0, Timest...
python|string|pandas|datetime|dictionary
2
377,880
57,685,005
Reading sas7bdat as pandas dataframe from zipfile
<p>I have a zip file called <code>myfile.zip</code>, which contains a file <code>mysasfile.sas7bdat</code>, which I would like to read as a pandas dataframe. I've tried a few things which haven't worked, but here is my current methodology: </p> <pre><code>import zipfile zipfile = zipfile.ZipFile('myfile.zip', 'r') sa...
<p>You are missing the parameter <code>format</code></p> <pre><code>import zipfile zipfile = zipfile.ZipFile('myfile.zip', 'r') sasfile = zipfile.open('mysasfile.sas7bdat') df = pd.read_sas(sasfile, format='sas7bdat') </code></pre>
python|python-3.x|pandas|sas
1
377,881
57,624,739
How to fix 'RuntimeError: Address already in use' in PyTorch?
<p>I am trying to run a distributive application with PyTorch distributive trainer. I thought I would first try the example they have, found <a href="https://pytorch.org/tutorials/beginner/aws_distributed_training_tutorial.html#pytorch-1-0-distributed-trainer-with-amazon-aws" rel="nofollow noreferrer">here</a>. I set u...
<p>So after a lot of failed attempts I found out what the problem is. Note that this solution applies to using ASW deep learning instances. </p> <p>After creating two instances I had to adjust the security group. Add two rules: The first rule should be ALL_TCP, and set the source to the Private IPs of the leader. The ...
python|pytorch|distributed|multi-gpu
2
377,882
57,448,823
How to flatten nest Json data with json_normalize
<p>I'm trying to import JSON data to Dataframe via json_normalize but cannot get it to work.</p> <p>My data:</p> <p><strong>a</strong> key is same as <strong>c1</strong> key</p> <pre><code>[ { "a": "A1", "b": "B1", "c": [ { "c1": "C111", "c2": "C121", "c3": ["C1131","C1132...
<p>you can try: </p> <pre><code>from collections import defaultdict norm_data = defaultdict(list) for item in data: for element in item['c']: norm_data['a'].append(item['a']) for k, v in element.items(): if k in {'a', 'c1'}: norm_data['c1(a)'].append(v) else...
python|json|pandas
1
377,883
57,683,186
How to load Multiple headers into Pandas dataframe
<p>there and thank you for spending your time on my question! I'm using python 3.7 + pandas to load .xlsx file with multiple columns into a dataframe.</p> <p>My Input:<a href="https://imgur.com/i7I9xAd" rel="nofollow noreferrer">https://imgur.com/i7I9xAd</a> . Desired Output (example for the first row only):<a href="...
<p>You need to define the index column for this particular excel file:</p> <pre><code>df = pd.read_excel('file.xlsx', header=[0, 1, 2], index_col=0) </code></pre>
python|excel|pandas
0
377,884
57,523,266
Is it possible to set a random number generator seed to get reproducible training?
<p>I would like to re-run training with fewer epochs to stop with the same state it had at that point in the earlier training.</p> <p>I see that <code>tf.initializers</code> take a seed argument. <code>tf.layers.dropout</code> does as well but 1.2.7 reports "Error: Non-default seed is not implemented in Dropout layer ...
<p>You can get a reproductible training by setting the weights default value. These default value are randomly generated at the beginning of the training. </p> <p>To set the value of the weights the property <code>kernerInitializer</code> of the layer object parameter can be used.</p> <p>Another way to set the weight...
tensorflow.js
1
377,885
57,664,359
How to fix numpy.random.choice output nested inside a for loop when importing from python file?
<p><strong>Problem</strong>:</p> <p>I am trying to generate multiple lists of random numbers, of differing length. Inside a <code>for</code> loop of length <code>num_baskets</code>, I am using <code>np.random.choice</code> to generate a number for the length of each successive list <code>n</code>. Then, again, <code>n...
<p>I restarted the Jupyter kernel such that the necessary changes that had been made to the python file code were now reflected on import. </p> <p>Despite re-importing the module multiple times within the notebook, this was rather an issue with Jupyter not updating changes made to the python file and saved in my text ...
python|numpy|random
0
377,886
57,443,183
Keras custom layer and custom loss function - need to preserve state
<p>Background: Text summarization using extractive method.</p> <p>The article I'm following - <a href="https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=8344797" rel="nofollow noreferrer">link</a>.</p> <p><strong>Edit 1</strong> link to <a href="https://colab.research.google.com/drive/1fc2GYdHcewXZRS-pU1ZDqntKKjul...
<p>solved. had to treat batch size in side my custom layer. also some stacking and splitting.</p> <pre><code>class MyLayer(Layer): def __init__(self, output_dim, **kwargs): self.output_dim = output_dim super(MyLayer, self).__init__(**kwargs) def build(self, input_shape): # Create a tr...
python|tensorflow|keras|deep-learning
0
377,887
57,554,087
Python 3.7 Indentation error when importing pandas as pd
<p>I am simply running <code>import pandas as pd</code> to import pandas. I am getting an indentation error which I am unable to understand.</p> <p>I have updated everything using Anaconda. I have attempted to import pandas in Spyder and Jupyter Notebook</p> <p>my error message:</p> <pre class="lang-py prettyprint-o...
<p>Reinstall <code>pandas</code>. I'd imagine the file has been edited somehow, introducing that indentation error.</p>
python|python-3.x|pandas
3
377,888
57,532,661
How do they know mean and std, the input value of transforms.Normalize
<p>The question is about <a href="https://pytorch.org/tutorials/beginner/data_loading_tutorial.html" rel="noreferrer">the data loading tutorial</a> from the PyTorch website. I don't know how they write the value of <code>mean_pix</code> and <code>std_pix</code> of the in transforms.Normalize without calculation</p> <p...
<p>For normalization <code>input[channel] = (input[channel] - mean[channel]) / std[channel]</code>, the mean and standard deviation values are to be taken from the <strong>training</strong> dataset.</p> <p>Here, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] are the mean and std of Imagenet dataset.</p> <block...
pytorch|dataloader
10
377,889
57,504,243
How to aggregate certain elements in a list of disctionaries
<p>I have a list of dictionaries (state:(score, type)) <code>list1</code> and would like to aggregate the states within each disctionary of <code>list1</code> based on <code>list2</code>.</p> <pre><code>import pandas as pd list1 = [{'NY':(40, 'EQ'), 'NJ':(30, 'EQ'), 'CT':(10, 'EQ'),'FL':(30, 'FI'), 'IL':(60, 'AI')}, ...
<p>Try this</p> <pre><code>df=pd.DataFrame(list1) a=df.loc[:, list2].sum(axis=1).reset_index(name='s').drop('index', 1) df.loc[:, 'NY'] = a['s'] df.drop(['NJ','CT'], axis = 1,inplace=True) list2=df.apply(lambda x : x.dropna().to_dict(),axis=1).tolist() print(list2) </code></pre>
python|pandas
1
377,890
57,599,863
Filter dataframe based on string within column
<p>So for simplicity purposes since my data set is very large, let's say I have a dataframe:</p> <pre><code>df = pd.DataFrame([['Foo', 'Foo1'], ['Bar', 'Bar2'], ['FooBar', 'FooBar3']], columns= ['Col_A', 'Col_B']) </code></pre> <p>I need to filter this dataframe in a way that would eliminate an entire row when a spec...
<p>Use <code>str.match</code></p> <pre><code>df[~df['Col_A'].str.match('^[Ff][Oo][Oo].*')] </code></pre> <p>result</p> <pre><code> Col_A Col_B 1 Bar Bar2 </code></pre>
regex|python-3.x|pandas
3
377,891
57,386,739
How to read files written by Spark with pandas?
<p>When Spark writes dateframe data to parquet file, Spark will create a directory which include several separate parquet files. Code for saving:</p> <pre><code>term_freq_df.write .mode("overwrite") .option("header", "true") .parquet("dir/to/save/to") </code></pre> <p>I need to rea...
<p>Normally, <code>pandas.read_parquet</code> can handle reading a directory of multiple (partitioned) parquet files fine. So I am curious to see the full error traceback you get.</p> <p>To demo that this works fine:</p> <pre><code>In [82]: pd.__version__ Out[82]: '0.25.0' In [83]: df = pd.DataFrame({'A': ['a', 'b'...
python|pandas|apache-spark|parquet
2
377,892
57,397,810
"DataFrame" is not callable
<p>It seems to be a recurrent problem on the site but i was not able to understand any of the similar problems/topics. I'm trying to get a scatter matrix from pandas (pandas.plotting.scatter_matrix), but I get the error <code>DataFrame is not callable</code>.</p> <p>Sorry to bother you, the error is maybe obvious but ...
<p>I can get the <code>scatter_matrix</code> without any problems using the following code:</p> <pre><code>from sklearn import datasets import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set() pal = sns.color_palette("cubehelix", 8) sns.set_palette(pal) Data_set = datasets.load_iris() iris...
python-3.x|pandas
0
377,893
57,510,115
cifar100 with MobiletNetV2
<p>I am trying to train MobileNetV2 on CIFAR100 using keras.applications Here is my code:</p> <pre><code>(x_train,y_train),(x_test,y_test) = tf.keras.datasets.cifar100.load_data(label_mode='fine') x_test = x_test.astype("float32") x_train = x_train.astype("float32") x_test /=255 x_train /=255 y_test = tf.keras.util...
<p>Some things that come to my mind...</p> <ul> <li>Check the data augmentation pipeline (<code>datagen</code>). It may be distorting the input too much and hence the model may be learning weird stuff instead of learning to classify the images</li> <li>Check also the training accuracy... Is it better than the validati...
python|tensorflow|keras|deep-learning
0
377,894
57,431,223
How to split concatenated column name into separate columns?
<p>In order to perform an analysis, I have been provided with a column name which contains specific information about the product, market and distribution. </p> <p>The structure of the dataset is as follows:</p> <pre class="lang-py prettyprint-override"><code>Date Product1|CBA|MKD Product1|CPA|MKD Product1|C...
<p>It looks like you could use <code>pandas.melt</code></p> <pre><code>df_ = df.melt(id_vars = 'Date', value_name = 'Quantity') df_[['Product', 'Partner','Market']] = df_.variable.str.split('|', expand = True)\ ...
python|string|pandas|split
3
377,895
57,623,890
Using TimeSeriesSplit in RandomSearchCV
<p>I want to use <code>TimeSeriesSplit</code> in <code>RandomSearchCV</code>.</p> <p>Look at the example below.</p> <pre class="lang-py prettyprint-override"><code>X = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]]) df = pd.DataFrame(X, columns = ['one', 'two']) df.index = [0,0,0,1,1,2] df one two 0 ...
<p>If you want to filter the rows based on index, you can use <code>loc</code> method from <code>DataFrames</code>:</p> <p>For example for your initial data split you have:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df.loc[[0]] # train set one two 0 1 2 0 3 4 0 1 2 &gt;&gt;...
python|pandas|scikit-learn|time-series
0
377,896
57,409,788
How to make N random choices for each value in a 3D numpy array without using loops
<p>I have:</p> <ul> <li>cats, an array of 10 categories with shape (10,)</li> <li>probs, an array of probabilities with shape (10, 50), representing the chance of each category being chosen for 50 different variables</li> <li>n_choices, an array with shape (num_sims, 50) containing integers representing the number of ...
<p>What you seem to be describing are samples of a <a href="https://en.wikipedia.org/wiki/Multinomial_distribution" rel="nofollow noreferrer">multinomial distribution</a>. You can take samples from the distribution directly. Unfortunately, the parameters of the distribution (number of trials and probabilities) change f...
python|arrays|loops|numpy|vectorization
1
377,897
57,533,282
Why do I get this error and what is the solution?
<p>I just started Tensorflow and am solving this problem but I am getting errors. The problem is that the base price for a house is 50k and each bedroom costs 50k each. So a 1 bedroom house is 100k, 2 bedroom is 150k and so on. We have to predict the cost of a 7 Bedroom house.</p> <p>I have tried using 'import numpy a...
<p>Yes you should consider installing NumPy using <code>!pip install numpy</code> Also, you used a small letter d (keras.layers.dense)-this is wrong. It should be <code>keras.layers.Dense</code></p>
python|numpy|tensorflow|conv-neural-network
0
377,898
57,507,662
Filtering a dataframe by two columns in another dataframe
<p>I need some tips about a pandas issue.</p> <p>I have the following DataFrame, df1, which contains the names in the dates that I need to keep in the output dataframe:</p> <pre><code>name date column_1 column_11 Anne 2018-01-01 some info1 some info11 John 2018-01-01 some inf...
<p>I'm going to do this in steps with intermediate <code>DataFrames</code>. This is less efficient but it will give you more insight into what is happening.</p> <p><strong>Take only the name and date from <code>df1</code></strong>:</p> <pre><code>df_key = df1.loc[:, ["name", "date"]] </code></pre> <p><strong>Use an...
python|pandas|dataframe
0
377,899
57,647,978
Get row values as list when column value equal something
<p>I want to extract the entire row values as list from <code>df</code> when column equal something.</p> <p>I tried </p> <pre class="lang-py prettyprint-override"><code>df.loc['column'== x] </code></pre> <p>but it gives the column headers and not a list</p> <p>Basically I want is to parse through each row in df and...
<p>Use <code>.loc()</code> to get only the rows that you are interested in. Then turn your Dataframe into a list of lists. So you need tyo get the values and turn them into list with <code>tolist()</code> method in Series.</p> <p>You probably want to use:</p> <pre class="lang-py prettyprint-override"><code>df.loc[df[...
python|pandas
0