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
4,600
37,145,206
How to use summaries on tensorflow's retrain inception final layer
<p>I have been sucessfully using <a href="https://www.tensorflow.org/versions/r0.8/how_tos/image_retraining/index.html" rel="nofollow">tensorflow's tutorial on retraining</a> the final layer to handle new classes and I would like to add some summaries to check how the cross-entropy is evolving.</p> <p>I have looked in...
<p>I added TensorBoard summaries to the stock code for the TensorFlow image retraining <a href="https://www.tensorflow.org/versions/master/how_tos/image_retraining/index.html" rel="nofollow">tutorial</a>. You can checkout the <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/image_retrai...
tensorflow|tensorboard
2
4,601
37,552,727
Subtracting Two Columns with a Groupby in Pandas
<p>I have a <code>dataframe</code> and would like to subtract two columns of the previous row, provided that the previous row has the same <code>Name</code> value. If it does not, then I would like it yield <code>NAN</code> and fill with <code>-</code>. My <code>groupby</code> expression yields the error, <code>TypeErr...
<p>You can add <code>lambda x</code> and change <code>df['Value']</code> to <code>x['Value']</code>, similar with <code>Value1</code> and last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="noreferrer"><code>reset_index</code></a>:</p> <pre><code>df['diff'] = df....
python|python-2.7|pandas
7
4,602
37,319,630
Python: return the row index of the minimum in a matrix
<p>I wanna print the <strong>index of the row containing the minimum</strong> element of the matrix</p> <p>my matrix is <code>matrix = [[22,33,44,55],[22,3,4,12],[34,6,4,5,8,2]]</code></p> <p>and the code</p> <pre><code>matrix = [[22,33,44,55],[22,3,4,12],[34,6,4,5,8,2]] a = np.array(matrix) buff_min = matrix.argmi...
<p>I am not sure which version of Python you are using, i tested it for Python 2.7 and 3.2 as mentioned your syntax for <strong>argmin</strong> is not correct, its should be in the format</p> <pre><code>import numpy as np np.argmin(array_name,axis) </code></pre> <p>Next, Numpy knows about arrays of arbitrary objects,...
python|numpy|matrix|min|minimum
1
4,603
41,935,637
Create new column in pandas dataframe based on whether a value in the row reappears in dataframe
<p>I have a csv I've imported as a pandas dataframe which looks like this:</p> <pre><code>TripId, DeviceId, StartDate, EndDate 817d0e7, dbf69e23, 2015-04-18T13:54:27.000Z, 2015-04-18T14:59:06.000Z 817d0f5, fkri449g, 2015-04-18T13:59:21.000Z, 2015-04-18T14:50:56.000Z 8145g5g, dbf69e23, 2015-04-18T15:12:...
<p>I managed to get it working, the code I used was:</p> <pre><code>df['UniqueId'] = range(0, 14571, 1) df['StartDate'] = pd.to_datetime(df['StartDate']) df['EndDate'] = pd.to_datetime(df['EndDate']) #converts dates to dateTime df2 = df.loc[df.duplicated(subset=['DeviceId'],keep=False)] #Returns list of trips with r...
python|python-3.x|pandas
0
4,604
41,751,160
2D dot product on two 3D matrix along an aixs
<p>Given two matrixes A and B with dimension of (x,y,z) and (y,x,z) respectively, how to dot product on the first two dimension of the two matrices? The result should have dimension of (x,x,z). </p> <p>Thanks!</p>
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow noreferrer"><code>np.einsum</code></a> with literally the same string expression -</p> <pre><code>np.einsum('xyz,yiz-&gt;xiz',a,b) # a,b are input arrays </code></pre> <p>Note that we have used <code>yiz</code> as th...
numpy|matrix-multiplication
1
4,605
41,730,519
Slicing NumPy array with dictionary
<p>Is there a simple option to slice a NumPy array with the predefined dictionary of indices?</p> <p>For example:</p> <pre><code>&gt;&gt; a = array([3, 9, 1, 5, 5]) </code></pre> <p>and (fictitious) dictionary:</p> <pre><code>&gt;&gt; index_dict = {'all_except_first': (1:None), 'all_except_last': (None:-1)} </code>...
<p>Create <a href="https://docs.python.org/3/library/functions.html#slice" rel="nofollow noreferrer"><code>slice</code></a>s:</p> <pre><code>&gt;&gt;&gt; index_dict = {'all_except_first': slice(1, None), 'all_except_last': slice(None, -1)} &gt;&gt;&gt; &gt;&gt;&gt; a[index_dict['all_except_first']] array([9, 1, 5, 5])...
python|numpy|dictionary|slice
3
4,606
37,935,729
Extract first characters from list series pandas
<p>I have a string series containing multiples words. I want to extract the first character of each word per row in a vectorized fashion. </p> <p>So far, I have been able to split the words into a list, but haven't found a vectorized way of getting the first characters. </p> <pre><code>s = pd.Series(['aa bb cc', 'cc ...
<p>Another faster solution is nested list comprehension:</p> <pre><code>s2 = pd.Series([[y[0] for y in x.split()] for x in s.tolist()]) print (s2) 0 [a, b, c] 1 [c, d, e] 2 [f, g] 3 [0] dtype: object </code></pre> <p>Thank you <a href="https://stackoverflow.com/questions/37935729/extract-first-ch...
python|string|pandas|dataframe|character
2
4,607
37,890,989
Why isn't this Conv2d_Transpose / deconv2d returning the original input in tensorflow?
<pre><code>weights = tf.placeholder("float",[5,5,1,1]) imagein = tf.placeholder("float",[1,32,32,1]) conv = tf.nn.conv2d(imagein,weights,strides=[1,1,1,1],padding="SAME") deconv = tf.nn.conv2d_transpose(conv, weights, [1,32,32,1], [1,1,1,1],padding="SAME") dw = np.random.rand(5,5,1,1) noise = np.random.rand(1,32,32,1...
<p>There's a reason it's called <code>conv2d_transpose</code> rather than <code>deconv2d</code>: it isn't deconvolution. Convolution isn't an orthogonal transformation, so it's inverse (deconvolution) isn't the same as its transpose (<code>conv2d_transpose</code>).</p> <p>Your confusion is understandable: calling the...
tensorflow|convolution|deconvolution
4
4,608
37,630,202
python pandas: passing in dataframe to df.apply
<p>Long time user of this site but first time asking a question! Thanks to all of the benevolent users who have been answering questions for ages :)</p> <p>I have been using <code>df.apply</code> lately and ideally want to pass a dataframe into the <code>args</code> parameter to look something like so: <code> df.appl...
<p>The error is in this line:</p> <pre><code> File "C:\Anaconda3\envs\p2\lib\site-packages\pandas\core\frame.py", line 4017, in apply if kwds or args and not isinstance(func, np.ufunc): </code></pre> <p>Here, <code>if kwds or args</code> is checking whether the length of <code>args</code> passed to <code>apply</...
python|pandas|dataframe
8
4,609
37,818,063
How to calculate conditional probability of values in dataframe pandas-python?
<p>I want to calculate conditional probabilites of ratings('A','B','C') in ratings column. </p> <pre><code> company model rating type 0 ford mustang A coupe 1 chevy camaro B coupe 2 ford fiesta C sedan 3 ford focus A sedan 4 ford ...
<p>You can use <code>.groupby()</code> and the built-in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="noreferrer"><code>.div()</code></a>:</p> <pre><code>rating_probs = df.groupby('rating').size().div(len(df)) rating A 0.333333 B 0.500000 C 0.166667 </code></p...
python|pandas|dataframe|probability
17
4,610
64,255,974
create string using dataframe values
<p>dataframe has</p> <p>segment | percentage_change</p> <p>segment1 | 25%</p> <p>segment2 | 30%</p> <p>segment3 | 40%</p> <p>I need to create sentence for top 3:</p> <p>&quot;Segment3 has highest percentage change of 40%&quot;</p> <p>&quot;Segment2 has 2nd highest percentage change of 30%&quot;</p> <p>&quot;Segment1 ha...
<p>Use:</p> <pre><code>#converted column with percentage to numeric df['num'] = df['percentage_change'].str.rstrip('%').astype(float) #get 3top rows by numeric column df1 = df.nlargest(3, 'num') #create difference column converted to strings df1['diff'] = df1['num'].diff(-1).fillna(0).astype(str).str.replace('\.[0]*','...
python|python-3.x|pandas|string|dataframe
0
4,611
64,431,003
Check similarity of 2 pandas dataframes
<p>I am trying to compare 2 pandas dataframes in terms of column names and datatypes. With assert_frame_equal, I get an error since shapes are different. Is there a way to ignore it, as I could not find it in the documentation.</p> <p>With df1_dict == df2_dict, it just says whether its similar or not, I am trying to pr...
<p>It seems to me that if the two dataframe descriptions are outer joined, you would have all the information you want.</p> <p>example:</p> <pre><code>df1 = pd.DataFrame({'a': [1,2,3], 'b': list('abc')}) df2 = pd.DataFrame({'a': [1.0,2.0,3.0], 'b': list('abc'), 'c': [10,20,30]}) diff = df1.dtypes.rename('df1').reset_i...
pandas|dataframe
1
4,612
47,986,662
Why `xavier_initializer()` and `glorot_uniform_initializer()` are duplicated to some extent?
<p><code>xavier_initializer(uniform=True, seed=None, dtype=tf.float32)</code> and <code>glorot_uniform_initializer(seed=None, dtype=tf.float32)</code> refer to the same person Xavier Glorot. Why not consolidate them into one function?</p> <p><code>xavier_initializer</code> is in <code>tf.contrib.layers</code>. <code>g...
<p>Yes, <code>tf.contrib.layers.xavier_initializer</code> and <code>tf.glorot_uniform_initializer</code> both implement the same concept described in this <a href="http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf" rel="nofollow noreferrer">JMLR paper: <code>Understanding the difficulty of training deep feedforwa...
python|tensorflow|machine-learning|deep-learning|initializer
3
4,613
47,923,429
How to shuffle a pandas dataframe randomly by row
<p>I am trying to shuffle a pandas dataframe by row instead of column. </p> <p>I have the following dataframe: </p> <pre><code> row1 row2 row3 1 3 1 6 2 5 2 7 3 7 3 8 4 9 4 9 </code></pre> <p>And would like to shuffle the df to achieve a random permuta...
<p>You can achieve this by using the sample method and apply it to axis # 1. This will shuffle the elements in a row:</p> <pre><code>df = df.sample(frac=1, axis=1).reset_index(drop=True) </code></pre> <p>How ever your desired dataframe looks completely randomised, which can be done by shuffling by row and then by col...
python|pandas|numpy|shuffle
8
4,614
47,862,262
How to subtract channel wise mean in keras?
<p>I have implemented a lambda function to resize an image from 28x28x1 to 224x224x3. I need to subtract the VGG mean from all the channels. When i try this, i get an error </p> <p>TypeError: 'Tensor' object does not support item assignment </p> <pre><code>def try_reshape_to_vgg(x): x = K.repeat_elements(x, 3, ax...
<p>You can use <code>keras.applications.imagenet_utils.preprocess_input</code> on tensors after Keras 2.1.2. It will subtract the VGG mean from <code>x</code> under the default mode <code>'caffe'</code>.</p> <pre class="lang-py prettyprint-override"><code>from keras.applications.imagenet_utils import preprocess_inpu...
machine-learning|tensorflow|deep-learning|keras|tensor
4
4,615
47,783,978
tf.train.shuffle_batch hangs forever (using tensorflow ver. 1.4)
<p>I've a small tfrecords file with only 640 records. Below code hangs and I don't know what's wrong with it:</p> <pre><code>def read_from_tfrecord(tfrecord_file): tfrecord_file_queue = tf.train.string_input_producer(tfrecord_file, name = 'queue') reader = tf.TFRecordReader() _, tfrecord_serialized = reader.r...
<p>Ok, I resolved the issue. I spent a lot of time to make this working. So, I post the answer here in case others face a similar problem. On top of what Seven suggested, </p> <p>I had to add <code>tf.train.start_queue_runners(sess)</code>. The code will look like this:</p> <pre><code>snippet, label = read_from_tfrec...
tensorflow|queue
0
4,616
47,710,955
In numpy, why is .var() a method while mean() is a normal function?
<p>As an R programmer learning Python, I've been getting confused by the Python syntax a few times. Many of these behaviors seem arbitrary to me. It would help me to understand the reasons behind why things are the way they are in Python. I'm also new to OOP, so this might be the reason for my confusion.</p> <p>Specif...
<p>You can use these methods both ways: The reasoning was to make scientific python packages friendly for users not comfortable with OOP, and provide a familiar API to people used to matlab, or R.<br> As pointed out in the comments by @Mel, the matplotlib package also shares this feature.</p> <pre><code>import numpy ...
python|numpy|methods
3
4,617
49,022,769
how to convert float to string excluding NaN in pandas within one line code?
<p>I would like to convert a column of float value to string, following is my current way:</p> <pre><code>userdf['phone_num'] = userdf['phone_num'].apply(lambda x: "{:.0f}".format(x) if x is not None else x) </code></pre> <p>However, it also converts the NaN to string "nan" which is bad when I check the missing value...
<p>I think you should compare Nan values instead of comparing None</p> <pre><code>userdf['phone_num'] = userdf['phone_num'].apply(lambda x: "{:.0f}". format(x) if not pd.isnull(x) else x) </code></pre>
python|pandas
3
4,618
49,225,933
When turning a list of lists of tuples to an array, how can I stop tuples from creating a 3rd dimension?
<p>I have a list of lists (each sublist of the same length) of tuples (each tuple of the same length, 2). Each sublist represents a sentence, and the tuples are bigrams of that sentence. </p> <p>When using <code>np.asarray</code> to turn this into an array, python seems to interpret the tuples as me asking for a 3rd d...
<p>Here are two more methods to complement @hpaulj's answer. One of them, the <code>frompyfunc</code> methods seems to scale a bit better than the other methods, although hpaulj's preallocation method is also not bad if we get rid of the loop. See timings below:</p> <pre><code>import numpy as np import itertools bi_g...
python|arrays|list|numpy
1
4,619
58,916,783
How to best perform recursion on a pandas dataframe column
<p>I am trying to calculate an index value over a time series within a pandas dataframe. This index depends on the previous row's result to calculate each row after the first iteration. I've attempted to do this recursively, within iteration over the dataframe's rows, but I find that the first two rows of the calculat...
<p>Based on your updated question, you just need to do this:</p> <pre><code># assign a new temp_factor with initial values and prep for cumprod stpassrev['temp_factor'] = np.where(stpassrev['factor'].isna(), 1, stpassrev['factor'].add(100).div(100)) # calculate the cumprod based on the temp_factor (grouped by Sector)...
python|pandas|recursion
1
4,620
70,024,115
How to calculate the number of days since a given event in each group
<p>Below is a sample data frame:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'StudentName': ['Anil','Ramu','Ramu','Anil','Peter','Peter','Anil','Ramu','Peter','Anil'], 'ExamDate': ['2021-01-10','2021-01-20','2021-02-22','2021-03-30','2021-01-04','2021-06-06','2021-04-30','2...
<h2>TL;DR</h2> <p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.where.html" rel="nofollow noreferrer"><code>Series.where</code></a> and <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.ffill.html" rel="nofollow noreferrer"><code>groupby.ffill</code></a...
python|pandas|pandas-groupby
2
4,621
56,266,533
How to use TensorFlow tf.data.Dataset flat_map to produce a derived dataset?
<p>I have a Pandas DataFrame, and I'm loading part of it into a tf.data Dataset:</p> <pre class="lang-py prettyprint-override"><code>dataset = tf.data.Dataset.from_tensor_slices(( df.StringColumn.values, df.IntColumn1.values, df.IntColumn2.values, )) </code></pre> <p>Now what I would like to do is to use ...
<p>Possibly a long way around but you can also use <code>.concatenate()</code> with <code>apply()</code> to achieve a 'flat mapping'</p> <p>something like this:</p> <pre><code>def replicate(ds): return (ds.map(lambda s,i1,i2: (s, i1, i2, tf.constant(0.0))) .concatenate(ds.map(lambda s,i1,i2: (s, i1, i2, t...
python|tensorflow|tensorflow-datasets
0
4,622
56,360,809
Pandas does not read CSV as it write it
<p>I created a dataframe, and i wanted to export it as a CSV. i used the <code>df.to_csv()</code> method.</p> <p>When i read my csv that i created it's not parsed well and i have some values of columns mixed between each others.</p> <p>I tried to change the encoding, as well as the delimiter, but it doesn't solve my ...
<p>You can try adding the argument <code>index</code> in <code>to_csv</code>:</p> <pre><code>df.to_csv(r"path.csv", sep="\t", index=False) </code></pre> <p>Or a problem could be that your fields contain tabs, so in this case I would suggest you to change separator</p>
python|pandas|csv|export
0
4,623
56,098,067
Naive prediction using pandas
<p>Suppose, I have a data set:</p> <pre><code>ix m_t1 m_t2 1 42 84 2 12 12 3 100 50 </code></pre> <p>then, we can use </p> <pre><code>df = df[['m_t1', 'm_t2']].pct_change(axis=1).mul(100)[1] </code></pre> <p>to calculate the difference between <code>m_t1</code> and <code>m_t2</code> in %...
<p>Try this:</p> <pre><code>df_diff=df[['m_t1', 'm_t2']].pct_change(axis=1).mul(100).drop(columns=["m_t1"]) </code></pre> <pre><code>df_diff diff 0 100.0 1 0.0 2 -50.0 </code></pre> <p>Rename column in df_diff:</p> <pre><code>df_diff.columns=["diff"] </code></pre> <p>Concat dataframes:</p> <pre><code>d...
python|pandas|dataframe|prediction|difference
2
4,624
55,764,055
Reverse the Multi label binarizer in pandas
<p>I have pandas dataframe as </p> <pre><code>import pandas as pd from sklearn.preprocessing import MultiLabelBinarizer mlb = MultiLabelBinarizer() # load sample data df = pd.DataFrame( {'user_id':['1','1','2','2','2','3'], 'fruits':['banana','orange','orange','apple','banana','mango']}) </code></pre> <p>I collect ...
<p><code>inverse_transform()</code> method should help. Here's the documentation - <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MultiLabelBinarizer.html#sklearn.preprocessing.MultiLabelBinarizer.inverse_transform" rel="nofollow noreferrer">https://scikit-learn.org/stable/modules/gene...
python-3.x|sklearn-pandas
0
4,625
55,652,404
Fetch Google Analytics API with Python and Google2Pandas
<p>My plan is to fetch the GA API with python3 and <a href="https://github.com/AURA199X/Google2Pandas" rel="nofollow noreferrer">google2Pandas</a>.</p> <p>My problem so far is that I don't know where to start first, when I look at the google2pandas README it looks easy but I have issues to build my own script with tha...
<p>The link to the repository kind of has the answer, but appreciate it's not always clear if you've never seen it before. There is no need to do anything on the OAth2 process as the library seems to take care of that.</p> <p>Use <code>pip</code> to install the google2Pandas library on your machine.</p> <p>You then n...
python-3.x|pandas|google-analytics-api
0
4,626
65,030,278
Cannot get_attribute('href') from element via Selenium
<p>I've been stuck at this for eons now... Can you please help?</p> <p>Trying to build a scraper that scrapes listings on <a href="https://ingatlan.com/lista/elado+lakas+budapest" rel="nofollow noreferrer">this website</a> and I just cannot for the life of me get the URL of each listing. Can you please help?</p> <p>I'v...
<p>Something like the below would work. To get a webelement of a[2] from an element and it's href.</p> <pre><code>data['URL'] = listing.find_element_by_xpath('//a[2]').get_attribute('href') </code></pre>
python|pandas|selenium
1
4,627
64,998,101
How to remove part of the column name?
<p>I have a DataFrame with several columns like:</p> <pre><code>'clientes_enderecos.CEP', 'tabela_clientes.RENDA','tabela_produtos.cod_ramo', 'tabela_qar.chave', etc </code></pre> <p>I want to change the name of the columns and remove all the text neighbord a dot.</p> <p>I only know the method <code>pandas.rename({'A'...
<p>Try rename with lambda and string manipulation:</p> <pre><code>df = pd.DataFrame(columns=['clientes_enderecos.CEP', 'tabela_clientes.RENDA','tabela_produtos.cod_ramo', 'tabela_qar.chave']) print(df) #Empty DataFrame #Columns: [clientes_enderecos.CEP, tabela_clientes.RENDA, tabela_produtos.cod_ramo, #tabela_qar.cha...
pandas|dataframe
1
4,628
64,952,142
How to read a numpy array float value without change its format?
<p>I am using pandas and numpy do feature extraction. It take a long time to complete this task so I want to save DataFrame for later use.</p> <p>I write a large pandas.Dataframe which contains multiple 2-d numpy array into a csv file. These cell value like this:</p> <pre><code> color contrast ...
<p>The csv file is converting each element to string because it cannot recognize the brackets as numpy does. There are two solutions I can think of.</p> <p><strong>One is more hacky</strong>, and a little bit ugly. If you have to use the csv, then you could try to parse each element slicing the brackets out.</p> <pre><...
python|pandas|numpy|csv
1
4,629
40,300,782
Unhashable type : 'list' Error
<p>I'm getting this error for the following code </p> <pre><code>def cleaning(CURRENT,STRING,NEXT): data.ix[data[NEXT].str.contains(STRING,na=False),CURRENT] =... data[NEXT][data[NEXT].str.contains(STRING,na=False)] d = ['lower','Less'] c = a[5:] for x,y in zip(range(len(c)),d): cleaning(c[x],d,c[x+1]) ...
<p>You are passing in <code>d</code>, a list, as the <code>STRING</code> argument:</p> <pre><code>d = ['lower','Less'] # ... cleaning(c[x],d,c[x+1]) # ^ </code></pre> <p>Your second example works, you pass in <code>y</code> instead, which is a single element from the <code>b</code> list:</p> <pre...
python|pandas|for-loop|dictionary
1
4,630
39,488,282
total size of new array must be unchanged
<p>I have two arrays x1 and x2, both are 1*14 arrays i am trying to zip them up and then perform reshape.</p> <p>The code is as below ;</p> <pre><code>x1 </code></pre> <p>Out[122]: array([1, 2, 3, 1, 5, 6, 5, 5, 6, 7, 8, 9, 7, 9])</p> <pre><code>x2 </code></pre> <p>Out[123]: array([1, 3, 2, 2, 8, 6, 7, 6, 7, 1, 2,...
<p>I would assume you're on Python 3, in which the result is an array with a <code>zip</code> object. </p> <p>You should call <code>list</code> on the <em>zipped</em> items:</p> <pre><code>X = np.array(list(zip(x1, x2))).reshape(2, len(x1)) # ^^^^ print(X) # [[1 1 2 3 3 2 1 2 5 8 6 6 5 7] # [5 6 6 7 7 1 8...
python|arrays|numpy|reshape
3
4,631
39,820,963
Fastest way to select rows where value of column of strings is in a set
<p>I have a <code>set</code> of email addresses that I've selected from one set of values. I'd like to subset a <code>pandas DataFrame</code> to include only rows where the <code>unique_id</code> column value is not contained in the set. Here's what I've done that is running very slow:</p> <pre><code>signup_emails = s...
<p>Use the <code>isin</code> method.</p> <pre><code>event_attendees[event_attendees.isin(signup_emails)] </code></pre> <p>For not in the signup_emails, you can do</p> <pre><code>event_attendees[event_attendees.isin(signup_emails) == False] </code></pre>
python|pandas
1
4,632
39,526,831
Multiprocessing python function for numerical calculations
<p>Hoping to get some help here with parallelising my python code, I've been struggling with it for a while and come up with several errors in whichever way I try, currently running the code will take about 2-3 hours to complete, The code is given below; </p> <pre><code>import numpy as np from scipy.constants import B...
<p>This is not an answer to the question, but if I may, I would propose how to speed up the code using simple numpy array operations. Have a look at the following code:</p> <pre><code>import numpy as np from scipy.constants import Boltzmann, elementary_charge as kb, e import time Tc = 9.2 RAM = 4*1024**2 # 4GB def De...
python|multithreading|numpy|multiprocessing
1
4,633
39,865,212
dyld: Library not loaded: @rpath/libcudart.8.0.dylib, while building tensorflow on Mac OSX
<p>I am building tensorflow on my Mac(an hackintosh, so I have a GPU, and already installed CUDA8.0. It works fine with building caffe, so I am sure it works.) I have already set up the environment variables as following(I have put these in <code>.zshrc</code>,<code>.bash_profile</code> and <code>.bashrc</code>):</p> ...
<p>The following should fix the error.</p> <p>Find the file "genrule-setup.sh". The file should be in </p> <pre><code>&lt;tensorflow source dir&gt;/bazel-tensorflow/external/bazel_tools/tools/genrule/ </code></pre> <p>If the timestamp of this file changes then bazel build will fail saying the file is corrupted. So b...
macos|tensorflow|building
9
4,634
44,335,384
python numpy contains text "array"
<p>I am using a binarizer to get some one-hot-vectors. For some reason my output arrays contain a text literally saying "array".</p> <p>The form is like:</p> <pre><code>[array( [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, ...
<p>It's not a string. It is a Numpy array inside of a list. Numpy arrays are formatted like that as an output. </p> <p>Test it with np.array([2,3]) The output will be array([2, 3]).</p>
python|arrays|python-3.x|numpy
2
4,635
44,096,471
What is an efficient way to loop through dataframes with pandas?
<p>I have a column in dataframes which contains values <code>'a','b','c','d' and 'e'</code> and there total <strong>1.5 million</strong> records. I would like to convert the values in to numerical categories such as <code>a=&gt;1,b=&gt;2,c=&gt;3,d=&gt;4 and e=&gt;5</code>. </p> <p>Since I have <strong>1.5 million</st...
<p>I think using <code>df.applymap()</code> with an efficient function would do the trick.</p>
python|pandas|numpy
0
4,636
69,578,431
How to fix StreamlitAPIException: ("Expected bytes, got a 'int' object", 'Conversion failed for column FG% with type object')
<p><strong>Error:</strong></p> <pre><code>StreamlitAPIException: (&quot;Expected bytes, got a 'int' object&quot;, 'Conversion failed for column FG% with type object') </code></pre> <p><strong>Error Traceback</strong></p> <pre><code>Traceback: File &quot;C:\Users\ASUS\streamlit_freecodecamp-main\app_3_eda_basketball\bas...
<p>It’s a bug that came with <code>streamlit 0.85.0</code>. <a href="https://blog.streamlit.io/all-in-on-apache-arrow/" rel="noreferrer"><code>pyarrow</code></a> has an issue with <code>numpy.dtype</code> values (which df.dtypes returns).</p> <p>The <a href="https://issues.apache.org/jira/browse/ARROW-14087" rel="noref...
python|pandas|streamlit
25
4,637
69,460,270
Missing column values fill based on the available values
<p>How to fill missing values for apple <code>variety</code> from the <strong>same column</strong> when there are 1-4 varieties per farm and but cannot be two varieties with the same <code>ripening</code> index on the same farm? Assume the column has all possible scenarios.</p> <p>For instance, in the below sample, '<e...
<p>Use:</p> <pre><code>#create NaNs instead empty strings df['variety'] = df['variety'].replace('', np.nan) #test if only 1 unique category per ripening and farm m = m = df.groupby(['farm','ripening'])['variety'].transform('nunique').eq(1) #only for filtered rows forward filling values per groups df.update(df[m].grou...
python|pandas|pandas-groupby
1
4,638
69,525,091
move multiple csv files by column value using python
<p>I have thousands of csv files under uncategorised parent folder, all the files have one date column containing same date for all the rows. I want to check the date value of each files and move/copy to month wise folder using python.</p> <p>I have tried key = df.iloc[0]['Date'] but not able to use key.endswith or key...
<p>Here I am looping through the files, reading the first row of the date column. I have created new folders in the directory previously, with the names being each month of the year. Once I have read the date, I convert it to words (e.g. April, May). I then look through folders in the directory and is the date name and...
python|pandas|csv
0
4,639
54,241,625
Calculate average of column x if column y meets criteria, for each y
<p>How do I retrieve the value of column Z and its average if any value are >1</p> <pre><code>data=[9,2,3,4,5,6,7,8] df = pd.DataFrame(np.random.randn(8, 5),columns=['A', 'B', 'C', 'D','E']) fd=pd.DataFrame(data,columns=['Z']) df=pd.concat([df,fd], axis=1) l=[] for x,y in df.iterrows(): for i,s in y.iteritems():...
<p>Do you mean this?</p> <pre><code>df[df['Z']&gt;1].loc[:,'Z'].mean(axis=0) </code></pre> <p>or </p> <pre><code>df[df['Z']&gt;1]['Z'].mean() </code></pre>
python|pandas|dataframe
1
4,640
54,078,450
Tensorflow Logits and Labels must be broadcastable
<p>I am very green working with Tensorflow, and can not seem to get past this error. I have been trouble shooting this error for two days now and I can't get it to work. Can anyone see an issue with the code? I am using python3 via Jupyter Notebook. Thanks for the assistance.</p> <p>Here is my code:</p> <pre><cod...
<p>Posting this in case someone else is having similar issues. </p> <p>The error should read "<strong>Dumb User</strong>" lol. I passed the wrong variable into the second layer. </p> <pre><code>pooling_layer_1_ouptuts = create_maxpool2by2_and_reduce_spatial_size(conv_relu_layer_1_outputs) conv_layer_2_outputs \ ...
python-3.x|tensorflow|jupyter-notebook
0
4,641
54,092,650
Retrieve a word from file name in python
<p>I have list of 5 excel files in a specific path as mentioned below : <code>'Z:\\Ruchika\\Citymax_Dec06\\SVCDs\\**\\*Claypot*.csv'.</code> The list of 5 excel files and the paths are as per below</p> <pre><code>['Z:\\Ruchika\\Citymax_Dec06\\SVCDs\\December - SVCD\\UAE _ Citymax _Claypot_ Burdubai_fullcampaignfile.c...
<p>I'm guessing it can be any month, so why not just check for months:</p> <pre><code>filename = r'Z:\Ruchika\Citymax_Dec06\SVCDs\December - SVCD\UAE _ Citymax Claypot Burdubai_fullcampaignfile.csv' for month in ['October', 'November', 'December']: # List of months if month in filename: print('Month is:',...
python|string|pandas|filenames|series
1
4,642
38,491,881
Grouping and ungrouping based on a column
<p>My goal is to be able to group rows of a CSV file by a column value, and also to perform the inverse operation. To give an example, it is desired to be able to transform back and forth between these two formats:</p> <pre><code>uniqueId, groupId, feature_1, feature_2 1, 100, text of 1, 10 2, 100, some text of 2, 20 ...
<p>To perform the grouping, you can <code>groupby</code> on <code>'groupId'</code>, and then within each group perform a join with your given delimiter on each column:</p> <pre><code>def group_delim(grp, delim='|'): """Join each columns within a group by the given delimiter.""" return grp.apply(lambda col: del...
python|r|csv|pandas
4
4,643
38,111,010
how to index a numpy array using conditions?
<p>Suppose I have an array like this:</p> <pre><code>a = np.array([[2,1], [4,2], [1,3],...] </code></pre> <p>I want to retrieve the elements of the second column where the corresponding elements in the first column match some condition. So something like</p> <pre><code>a[a[:,0] == np.arra...
<p>While this uses <code>list</code> to collect results and requires a <code>for</code> loop, this collects the second column values once the first column has passed some criteria (in a <code>list</code> of acceptable results in this case).</p> <pre><code>a = np.array([[2, 1], [4, 2], [1, 3...
python|arrays|numpy
0
4,644
38,406,511
Write json format using pandas Series and DataFrame
<p>I'm working with csvfiles. My goal is to write a json format with csvfile information. Especifically, I want to get a similar format as miserables.json</p> <p>Example:</p> <pre><code>{"source": "Napoleon", "target": "Myriel", "value": 1}, </code></pre> <p>According with the information I have the format would be:...
<p>Consider removing the <code>Series()</code> around the scalar value, country. By doing so and then upsizing the dictionaries of series into a dataframe, you force <code>NaN</code> (later converted to <code>null</code> in json) into the series to match the lengths of other series. You can see this by printing out the...
python|json|python-3.x|pandas
1
4,645
38,381,031
Change a year in pandas dataframe if it is lower than 1900
<p>I have to process data where someone has been using a date value with a year of 1700 where there is not an actual event date. 1700 breaks datetime, which starts at 1900, but I'm sure you all know that.</p> <p>I have converted the data to datetime and then tried an if statement:</p> <pre><code>df["DATE"] = pd.to_da...
<p>Im having trouble reproducing this issue exactly, but have you tried:</p> <pre><code>df[df.DATE.dt.year &lt; 1900] = dt.datetime.today() df.DATE = df.DATE.map(lambda x: x.strftime("%m/%d/%y")) </code></pre>
python|datetime|pandas
2
4,646
38,221,981
Unpacking list of lists generated by a zip into one list
<p>I am again manipulating dataframes. Here I concatenate multiple dataframe using row as common reference. Then I want to reorder the columns by "pairing" the first one columns of each df together, and so on. All for the sake of data readability</p> <p>Here is my code:</p> <pre><code>df_list=[df_1,df_2,df_3] retu...
<p>You may just zip all column lists and then flatten the list of lists</p> <pre><code>list_columns = [ col for cols in zip( *dfcolumns_list ) for col in cols ] </code></pre>
python|pandas|dataframe|zip|multiple-columns
1
4,647
65,952,132
Calculate mean() of Nympy 2D-array grouped by values in a separate list with strings corresponding to each row in the 2D array
<p>I'm attending a course on Data Analysis with Python (Numpy, Pandas etc).</p> <p>We have an assignment where we are supposed to calculate mean() of an array - based on values of another list. This might seem a bit unclear so here's an example:</p> <pre><code>list = ['A','A','A','A','B','B','B','B'] array = [ [5.1, 3....
<p>The quickest way I can think of is to split the rows and compute the mean. However, this approach is a quick cheat and falls short if you want to generalize your solution to different forms for <code>list</code>:</p> <pre><code>&gt;&gt;&gt; [x.mean() for x in np.split(np.array(array), 2)] [2.40625, 2.58750] </code><...
python|list|numpy
2
4,648
46,258,301
How to raise an exception if we assign a value in a numpy array outside of a given range?
<p>I'm a python beginner and I'm implementing a version of k-means. </p> <p>I'm defining the k-means class and one of the class attributes is <code>__class</code>, where <code>__class[i] = j</code> means that the <code>i</code>-th data point is assigned to the <code>j</code>-th cluster. This means that if we have <cod...
<p>You can use error handling in python...</p> <pre><code>try: __class[i] = j # impossibleK except IndexError: print("Index error occurred") </code></pre>
python|arrays|numpy
0
4,649
58,197,320
How do I sum elements of a pandas dataframe?
<p>I'm new to python and this is already the second question I ask here. I have the following pandas dataframe obtained from an API: </p> <pre><code> data metadata 1388534400000 {'electricity': 0.0} NaN ...
<p>You can access your data through an apply to get the sum column-wise : </p> <pre class="lang-py prettyprint-override"><code>df=pd.DataFrame({'A': [{'electricity':0.0},{'electricity':1.0},{'electricity':5},{'electricity':4}],'B':['a','b','a','c']}) sumElectricity = df['A'].dropna().apply(lambda x: x['electricity']))...
python-3.x|pandas
0
4,650
58,565,642
I want to convert .csv file to a Numpy array
<p>I would like to convert a <code>mydata.csv</code> file to a Numpy array.</p> <p>I have a matrix representation <code>mydata.csv</code> file (The matrix is 14*79 with signed values without any header name.)</p> <pre><code>-0.094391 -0.086641 0.31659 0.66066 -0.33076 0.02751 … -0.26169 -0.022418 0.47564 ...
<p>For this, you first create a list of <code>CSV</code> files (<strong>file_names</strong>) that you want to append. Then you can export this into a single <code>CSV</code> file by reshaping Numpy-Array. This will help you to move forward:</p> <pre><code>import pandas as pd import numpy as np combined_csv_files = pd...
python|numpy|csv
3
4,651
60,887,648
Colorize the background of a seaborn plot using a column in dataframe
<h1>Question</h1> <p>How to shade or colorize the <em>background</em> of a <a href="https://seaborn.pydata.org/" rel="nofollow noreferrer">seaborn</a> plot using a column of a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html" rel="nofollow noreferrer">dataframe</a>?</p> <h1>Code...
<p><code>ax.axvspan()</code> could work for you, assuming backgrounds don't overlap over timepoints.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import seaborn as sns; sns.set() import matplotlib.pyplot as plt fmri = sns.load_dataset("fmri") fmri.sort_values('timepoint',inplace=True) arr = n...
python|pandas|dataframe|graph|seaborn
9
4,652
61,062,303
Deploy python app to Heroku "Slug Size too large"
<p>I'm trying to deploy a Streamlit app written in python to Heroku. My whole directory is 4.73 MB, where 4.68 MB is my ML model. My <code>requirements.txt</code> looks like this:</p> <pre><code>absl-py==0.9.0 altair==4.0.1 astor==0.8.1 attrs==19.3.0 backcall==0.1.0 base58==2.0.0 bleach==3.1.3 blinker==1.4 boto3==1.12...
<p><em>I have already answered this <a href="https://stackoverflow.com/a/62356779/11105967">here</a>.</em></p> <p>Turns out the Tensorflow 2.0 module is very large (more than 500MB, the limit for Heroku) because of its GPU support. Since Heroku doesn't support GPU, it doesn't make sense to install the module with GPU s...
python|tensorflow|heroku|tensorflow2.0
54
4,653
60,883,431
Limit the x axis in matplotlib python
<p>I have code that produces a live graph, updating every few seconds. It all functions EXACTLY as I want other than a single issue, the x axis keeps adding new values but never removing old ones</p> <p>in the example code below, because I limit the dataframe to 6 columns, I expect to never see more than 6 measuremen...
<p>using autoscale tries to keep old data in view. If you drop autoscale and use</p> <pre><code>figure.gca().set_xlim(left =x_data[0], right = datetime.now().time()) </code></pre> <p>it works as intended</p> <p>the full code is now </p> <pre><code>from matplotlib import pyplot from matplotlib.animation import Fun...
python|pandas|user-interface|matplotlib|graph
2
4,654
60,847,550
model.evaluate() varies wildly with number of steps when using generators
<p>Running tensorflow 2.x in Colab with its internal keras version (tf.keras). My model is a 3D convolutional UNET for multiclass segmentation (not sure if it's relevant). I've successfully trained (high enough accuracy on validation) this model the traditional way but I'd like to do augmentation to improve it, theref...
<p>Posting the <strong>workaround</strong> I've found for the future person coming here from google.</p> <p><em>Apparently</em> the issue lies in how keras calls a handwritten generator. When it was called multiple times in a row by using evaluate(gen, steps=N) apparently it returned wrong outputs. There's no document...
tensorflow|machine-learning|keras
2
4,655
71,517,152
tensorflow: load checkpoint
<p>I've been training a model which looks a bit like:</p> <pre><code>base_model = tf.keras.applications.ResNet50(weights=weights, include_top=False, input_tensor=input_tensor) for layer in base_model.layers: layer.trainable = False x = tf.keras.layers.GlobalMaxPool2D()(base_model.output) output = tf.keras.Sequen...
<p>These might help: <a href="https://www.tensorflow.org/guide/checkpoint" rel="nofollow noreferrer">Training checkpoints</a> and <a href="https://www.tensorflow.org/api_docs/python/tf/train/Checkpoint" rel="nofollow noreferrer">tf.train.Checkpoint</a>. According to the documentation, you should be able to load the mod...
tensorflow|tensorflow2.x
0
4,656
42,397,380
Improving data validation efficiency in Pandas
<p>I load data from a CSV into Pandas and do validation on some of the fields like this:</p> <pre><code>(1.5s) loans['net_mortgage_margin'] = loans['net_mortgage_margin'].map(lambda x: convert_to_decimal(x)) (1.5s) loans['current_interest_rate'] = loans['current_interest_rate'].map(lambda x: convert_to_decimal(x)) (1....
<p><strong>td;lr: Consider distribution the processing.</strong> An improvement would be reading the data in chunks and using multiple processes. source <a href="http://gouthamanbalaraman.com/blog/distributed-processing-pandas.html" rel="nofollow noreferrer">http://gouthamanbalaraman.com/blog/distributed-processing-pan...
python|python-2.7|pandas
0
4,657
69,680,491
Tensorflow can't append batches together after doing the first epoch
<p>I am running into problems with my code after I removed the loss function of the <code>compile</code> step (set it equal to <code>loss=None</code>) and added one with the intention of adding another, loss function through the <code>add_loss</code> method. I can call <code>fit</code> and it trains for one epoch but t...
<p>If you only want to get rid of the error and don't care about the last &quot;remainder&quot; batch of your dataset, you can use the keyword argument <code>drop_remainder=True</code> inside of <code>train_dataset_x_x.batch()</code>, that way all of your batches will be the same size.</p> <p>FYI, it's usually better p...
python|tensorflow|keras|loss-function|tf.data.dataset
1
4,658
69,729,338
Python - creating column containing the name of a team's opponent based on info in dataframe
<p>I have a dataframe (called &quot;games&quot;) that contains a play-by-play list of a basketball games, where I record scoring streaks within single games (GameID identifies a specific game). The dataframe is sorted by matches (i.e., GameID).</p> <p>Example of dataset &quot;games&quot;:</p> <pre><code> GameID Tea...
<p>First, group your dataframe by GameID and invoke <code>.unique()</code> to get the two teams that are playing the game</p> <pre><code>teams = df.groupby(&quot;GameID&quot;)[&quot;TeamID&quot;].unique() # game_teams : GameID nbaG1 [A, B] nbaG2 [C, D] nbaG3 [E, F] </code></pre> <p>Then, use this to look up b...
python|pandas
1
4,659
43,101,849
Python PIL/numpy conversion
<p>I'm having problems converting between python PIL images and numpy arrays. I already checked existing Stackoverflow posts on this, but it didn't solve the problem:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import PIL rgb_img = plt.imread('some-image.png') PIL_rgb_img = PIL.Image.fromarray(n...
<p>I may not give you a full explanation , (for that, you may read matplotlib's functions docs) but clearly with some tests the following is happening:</p> <p>when you call:</p> <pre><code>rgb_img = plt.imread('img.png') </code></pre> <p>it gives a numpy float array, which will read colors between [0 - 1] as white a...
python|numpy|python-imaging-library
2
4,660
72,249,904
Pandas data manipulation from column to row elements
<p>I have dataset with millions of rows, here is an example of what it looks like and what I intend to output:</p> <pre><code>data = [[1, 100, 8], [1, 100, 4], [1, 100,6], [2, 100, 0], [2, 200, 1], [3, 300, 7], [4, 400, 2], [5, 100, 6], [5, 100, 3], [5, 600, 1]] df= pd.DataFrame(data...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.astype.html" rel="nofollow noreferrer"><code>df.astype</code></a> with <a href="https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow noreferrer"><code>Groupby.agg</code></a>...
pandas|numpy|data-manipulation
1
4,661
50,612,923
Tensorflow export estimators for prediction
<p>I wonder how can I export the estimator and then import it for prediction from MNIST tutorial, <a href="https://github.com/tensorflow/tensorflow/blob/r1.8/tensorflow/examples/tutorials/layers/cnn_mnist.py" rel="nofollow noreferrer">Tensorflow's page</a>. Thank you!</p>
<p>The <code>Estimator</code> has <code>model_dir</code> args where the model will be saved. So during prediction we use the <code>Estimator</code> and call the <code>predict</code> method which recreates the graph and the checkpoints are loaded.</p> <p>For the <code>MNIST</code> example, the prediction code would be:...
python|tensorflow|mnist
2
4,662
50,621,614
could not convert string to float: 'cd9f3b1a-2eb8-4cdb-86d1-5d4c2740b1dc'
<p>I am a newbie in Data Science and Python. So I try to use KMeans from sklearn. I have information about calls, and I want to find centroids. So I can do it for one phone number, but can't for 10. When I used for-loop I got the mistake "could not convert string to float: 'cd9f3b1a-2eb8-4cdb-86d1-5d4c2740b1dc'".</p> ...
<p>I missed the line in loop</p> <blockquote> <p>user = pd.concat([user.TowerLon, user.TowerLat], axis = 1)</p> </blockquote> <p>Thanks for all</p>
python|k-means|data-science|sklearn-pandas
0
4,663
45,572,247
How to index a list of class instances with a TensorFlow tensor
<p>Given a list of class instances, I need to index it using tf.tensor. For example:</p> <pre><code>Class Something(): def __init__(self): self.a = 1 self.b = 2 list = [Something() for a in range(0, 10)] index_queue = tf.train.range_input_producer(len(list)) index = index_queue.dequeue() res...
<p>The problem is due to a core mechanic in how TensorFlow works. When you call TensorFlow methods like <code>tf.train.range_input_producer(len(list))</code> or <code>tf.constant</code> you're not actually <em>running</em> those operations. You're just adding those operations to the TensorFlow computation graph. You th...
python|tensorflow
0
4,664
45,333,681
Handling NA in groupby + transform
<p><strong>Edit (Jul/2021):</strong></p> <blockquote> <p>Back in the days (Jun/2017) I filled an <a href="https://github.com/pandas-dev/pandas/issues/17093#issuecomment-859993083" rel="nofollow noreferrer">issue on Pandas' Github</a>. Since it was/is a minor issue (you can work around that, e.g., Scott's answer), and a...
<p>Let's <code>mask</code> and uniquely identify those NaN with <code>cumsum</code>:</p> <pre><code>new_c = df['C'].mask(df['C'].isnull(),df['C'].isnull().cumsum()) df.groupby(new_c)['B'].transform('mean') </code></pre> <p>Or, if you testing some more complicated function</p> <pre><code>df.groupby(new_c)['B'].transf...
python|python-3.x|pandas
0
4,665
62,854,320
Pandas new dataframe based on combinations of all values in a column
<p>I have collected location data from buses over some time and want to build a model predicting when a bus will arrive at a certain stop.</p> <p>In its most simple form, I have a DataFrame like this:</p> <pre><code>import pandas as pd df = pd.DataFrame({'station': ['Station 1', 'Station 2', 'Station 3', 'Station 4'],...
<p>Convert &quot;station&quot; to an ordered categorical column:</p> <pre><code>df['station'] = pd.Categorical(df['station'], ordered=True).codes </code></pre> <p>You can now do a cross join and filter:</p> <pre><code>tmp = df.assign(key=1) (tmp.merge(tmp, on='key', suffixes=('_prev', '_next')) .drop('key', 1) ...
python|pandas
0
4,666
62,764,560
How to make pixels arrays from RGB image without losing its spatial information in python?
<p>I am wondering is there any workaround to convert RGB images to pixel vectors without losing its spatial information in python. As far as I know, I can read the images and do transformation for images to pixel vectors. I am not sure doing this way still preserve images' spatial information in pixel vectors. How can ...
<p>Are You just trying to reshape each channel to a vector and then joining them horizontally? That's what I understood from the graphic illustration and the way i would do it is something like this:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np image = plt.imread('monkey.png') image = image / 255....
python|arrays|image|numpy
2
4,667
62,655,883
official module in tensorflow examples at tensorflow.org
<p>I've been following a tensorflow tutorial <a href="https://www.tensorflow.org/official_models/fine_tuning_bert" rel="nofollow noreferrer">https://www.tensorflow.org/official_models/fine_tuning_bert</a></p> <p>In the first code snippet, I saw a lot of imports from official module</p> <pre><code>import numpy as np imp...
<p>The official modules of TensorFlow can be found in the <a href="https://github.com/tensorflow/models/tree/master/official" rel="nofollow noreferrer">TensorFlow Model Garden Repository</a></p>
python|tensorflow|nlp|bert-toolkit
2
4,668
62,544,461
Array math on numpy structured arrays
<pre><code>import numpy as np arr = np.array([(1,2), (3,4)], dtype=[('c1', float), ('c2', float)]) arr += 3 </code></pre> <p>results in an invalid type promotion error. Is there a way I can have nice labeled columns like a structured array, but still be able to do operations like it's a simple <code>dtype=float</code> ...
<p>Hmmm. One option, use a view for this:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; arr = np.array([(1,2), (3,4)], dtype=[('c1', float), ('c2', float)]) &gt;&gt;&gt; view = arr.view(float) &gt;&gt;&gt; view += 3 &gt;&gt;&gt; arr array([(4., 5.), (6., 7.)], dtype=[('c1', '&lt;f8'), ('c2', '&lt;f8')]) &...
python|numpy|numpy-ndarray
2
4,669
62,868,593
What is more efficient that np.sum and numpy boolean operators?
<p>I am having some trouble getting my code to run quickly.</p> <p>After using a line by line profiler on my code, I have found that the following lines are where most of my inefficiencies come from:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import datetime timestamps = np.array(timestamps...
<p>Looks like <code>numpy.datetime64</code> objects are pretty fast. About a 2x speed up from standard lib <code>datetime</code>. Pandas kind of flounders here. It does a little bit better than what you see below if you use the pandas Timestamps as an index on Series object and use the <code>.loc</code> accessor. But n...
python|arrays|numpy|boolean|boolean-logic
1
4,670
62,791,598
how can I find intersection of multiple lines with a curve?
<p>I have a file which has x and y. For each line that passes from the y-axis, I can find the intersection but I wanted to have an automatic way to find the intersections of a bunch lines that pass from y-axis like the figure below:</p> <p><em>perspective result</em> <a href="https://i.stack.imgur.com/C1GQp.png" rel="n...
<p>You can try to set up an extra loop to check for multiple intersection values which you input and use dictionary to hold list of matches against intersection value as key. This theoretically should plot all intersections of y you desire into same graph</p> <pre class="lang-py prettyprint-override"><code>import numpy...
python|numpy|matplotlib
2
4,671
54,548,747
Calculating a summary row in a pandas dataframe
<p>Here's what I have (Pandas DataFrame), that I created so far: Code: </p> <pre><code>table = pd.pivot_table(df1, index=['Assignee', 'IssueType'], columns=['Status'], values='Key', aggfunc={'Key': np.count_nonzero}, dropna=True) table['Total'] = table.sum(axis=1) table = table.fillna(0) table = table.apply(pd.to_nume...
<p>Here's my answer to this question. Perhaps there is a scope for improvement (but atleast it works to my contentment).</p> <pre><code>def append_summary_total(df_index, file_path, delimiter): file_path = os.path.abspath(file_path) delimiter = str(delimiter) df = pd.read_csv(file_path, sep=delimiter) ...
python|pandas|python-2.7
0
4,672
73,644,154
pandas creates 2 copies of files in a loop
<p>I have a dataframe like as below</p> <pre><code>import numpy as np import pandas as pd from numpy.random import default_rng rng = default_rng(100) cdf = pd.DataFrame({'Id':[1,2,3,4,5], 'customer': rng.choice(list('ACD'),size=(5)), 'region': rng.choice(list('PQRS'),size=(5)), ...
<p>The issue is happening because you are referencing 2 different file names one with the prefix <code>&quot;test_files/&quot;</code> and once without it. Best way to handle it will be to define file name as follows</p> <pre><code>dir_filename = &quot;test_files/&quot; + f&quot;{filename}.xlsx&quot; </code></pre> <p>an...
python|pandas|dataframe|file|group-by
1
4,673
73,554,722
Searching word frequency in pandas from dict
<p>Here is the code which I am using:</p> <pre><code>import pandas as pd data = [['This is a long sentence which contains a lot of words among them happy', 1], ['This is another sentence which contains the word happy* with special character', 1], ['Content and merry are another words which implies happy'...
<p>the following code should make the job, although is not totally working with pandas. Note I use phrase.lower() to match the correct counts.</p> <pre class="lang-py prettyprint-override"><code>from collections import Counter out = df.groupby(&quot;id&quot;)['string'].apply(list) def get_count(grouped_element): ...
python|pandas|dataframe|dictionary
1
4,674
71,317,141
optimizing multiple loss functions in pytorch
<p>I am training a model with different outputs in PyTorch, and I have four different losses for positions (in meter), rotations (in degree), and velocity, and a boolean value of 0 or 1 that the model has to predict.<br /> AFAIK, there are two ways to define a final loss function here:</p> <p>one - the naive weighted s...
<p>This is not a question about programming but instead about optimization in a multi-objective setup. The two options you've described come down to the same approach which is a linear combination of the loss term. However, keep in mind there are many other approaches out there with dynamic loss weighting, uncertainty ...
python|optimization|pytorch|loss-function|loss
2
4,675
71,232,915
How to group and calculate monthly average in pandas dataframe
<p>I am trying to group a dataset based on the name and find the monthly average. i.e sum all the values for each name divided by the number of the distinct month for each name.</p> <p>For example,</p> <pre><code>name time values A 2011-01-17 10 B 2011-02-17 20 A 2011-01-11 10 A 2011-03-17 30 B 2011...
<p>Convert values to datetimes first, then aggregate <code>sum</code> per <code>name</code> and months by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Grouper.html" rel="nofollow noreferrer"><code>Grouper</code></a> and last get <code>mean</code> per first level <code>name</code>:</p> <pre>...
python|pandas
0
4,676
71,342,754
Use dataframe name in dataframe.query
<p>I have two dataframes</p> <p>df1</p> <pre><code>Company Region ID Walmart North 1 Walmart North 2 OneStore North 3 OneStore North 4 OneStore South 4 Walmart South 4 OneStore West 4 Walmart East 5 </code></pre> <p>df2</p> <pre><code>Company Region ID Sales Walm...
<p>You can merge the 2 dataframes first, then aggregate on group.</p> <pre class="lang-py prettyprint-override"><code># This will merge the Sales information to the first dataframe. df = df1.merge(df2, on=['Company', 'Region', 'ID'], how='left') # Then, you can group by the Company, Region, and ID and aggregate the Sa...
python|pandas|dataframe
0
4,677
52,041,963
Select rows containing a NaN following a specific value in Pandas
<p>I am trying to create a new DataFrame consisting of the rows corresponding to the value 1.0 or NaN in the last column, whereby I only take the Nans under a 1.0 (that is, I'm interested in everything until a 0.0 appears).</p> <pre><code>Timestamp Value Mode 00-00-10 34567 1.0 00-00-20 4542...
<p>You can use <code>.ffill</code> to figure out if it's a <code>NaN</code> below a 1 or a 0.</p> <p>Here are the <code>NaN</code> values below a 1</p> <pre><code>df[(df['Mode'].isnull()) &amp; df['Mode'].ffill() == 1] # Timestamp Value Mode #1 00-00-20 45425 NaN #5 00-00-60 25678 NaN </code></pre> <p>To ...
python|pandas|dataframe
2
4,678
60,433,580
How to check if a column contains backslash
<pre><code>data = {'value': ['red','red\blue','yellow'] } df = pd.DataFrame (data, columns = ['value']) </code></pre> <p>I tried to use:</p> <pre><code>df[df['value'].str.contains("\\", na = False)]['value'].count() </code></pre> <p>but got the error:</p> <pre><code>bad escape (end of pattern) at position 0 </code>...
<p>Data was change for avoid <code>\b</code> value, add <code>r</code> prefix because by default <code>regex=True</code>. For count is simplier use <code>sum</code> of <code>True</code>s values:</p> <pre><code>data = {'value': ['red','red\ blue','yellow']} df = pd.DataFrame (data, columns = ['value']) print(df) ...
python|pandas
2
4,679
60,549,984
How to create new column by manipulating another column? pandas
<p>I am trying to make a new column depending on different criteria. I want to add characters to the string dependent on the starting characters of the column. An example of the data:</p> <pre><code>RH~111~header~120~~~~~~~ball RL~111~detailed~12~~~~~hat RA~111~account~13~~~~~~~~~car </code></pre> <p>I want to chang...
<p>Define a function to replace element No <em>pos</em> in <em>arr</em> list:</p> <pre><code>def repl(arr, pos): arr[pos] = '1' if arr[0] == 'RH' else 'cancel' return '~'.join(arr) </code></pre> <p>Then perform the substitution:</p> <pre><code>df[0] = df[0].mask(df[0].str.match('^R[HL]'), df[0].str.split...
python|pandas
1
4,680
60,338,266
Python: distance from index to 1s in binary mask
<p>I have a binary mask like this:</p> <pre><code>X = [[0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 1], [0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1], [0, 0, 0, 1, 1, 1]] </code></pre> <p>I have a certain index in this array and want to compute the distance from that index to the closest ...
<p>Here's one for <code>manhattan</code> distance metric for one entry -</p> <pre><code>def bwdist_manhattan_single_entry(X, idx): nz = np.argwhere(X==1) return np.abs((idx-nz).sum(1)).min() </code></pre> <p>Sample run -</p> <pre><code>In [143]: bwdist_manhattan_single_entry(X, idx=(0,5)) Out[143]: 0 In [14...
python|numpy|scipy
3
4,681
60,532,088
Convert a list into a Numpy array lose two of its three axis only with one dataset
<p>I have a python code that reads NIFTI images using SimpleITK library. Then it converts that images into a Numpy Array. Then, I extend the Numpy Array into a list.</p> <p>I have 20 FLAIR.nii.gz files. Each of them have 48 slices.</p> <p>When I have all the 48 slices of all the 20 patients, I convert the list into a...
<p>In one case</p> <pre><code>flair_array.shape: (960,) flair_array.dtype: object </code></pre> <p>in the other</p> <pre><code>flair_array.shape: (960, 240, 240) flair_array.dtype: float32 </code></pre> <p>You make these with:</p> <pre><code>flair_array = np.array(flair_dataset) </code></pre> <p>If all the el...
python|arrays|numpy|simpleitk|nifti
3
4,682
72,720,453
Python: extract column from pandas pivot
<p>I have a pivoted table <code>total_chart = df.pivot_table(index=&quot;Name&quot;, values=&quot;Items&quot;, aggfunc='count')</code> The output gives</p> <pre><code>A 8 B 52 C 24 D 6 E 43 F 5 G 13 I 1 </code></pre> <p>...
<p>The code below should do the trick for you. It counts &quot;Items&quot;, sort it ascending by the index &quot;Name&quot; and output just the counts without the index.</p> <pre class="lang-py prettyprint-override"><code>df['Items'].value_counts().sort_index(ascending=True).tolist() </code></pre>
python|pandas|pivot|aggregate
2
4,683
72,835,220
Pandas compare next row (several rows) by condition
<p>I have a dataframe with two columns: price and pattern (can be 0 if absent or 1 if exists).</p> <pre><code>Price Pattern 10 0 12 1 15 0 11 0 9 0 </code></pre> <p>First, i need to iterate to find row with existing pattern (pattern = 1), then</p> <ol> <li>compare pri...
<p>I guess that you can use pandas built-in function <code>diff</code>, which already has a magical parameter <code>period</code> and it finds a difference between <code>i-th</code> and 'i+period-th` value. I extended your example, to verify if this is what you are looking for:</p> <pre class="lang-py prettyprint-overr...
python|pandas|compare|rows
0
4,684
72,669,941
Why my model doesn't train with keras ImageDataGenerator?
<p>I use the Keras API to train a CNN on Cifar10.</p> <p>Here is my code :</p> <pre><code>(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data() conv_network = Input(shape=(32, 32, 3), name=&quot;img&quot;) x = Conv2D(filters=32, kernel_size=(3,3), strides=2, activation=&quot;relu&quot;)(conv_net...
<p>I found a solution after trial and error but I still don't fully understand why my previous code didn't work.</p> <pre><code>conv_network = Input(shape=(32, 32, 3), name=&quot;img&quot;) x = Conv2D(filters=32, kernel_size=(3,3), strides=2, activation=&quot;relu&quot;)(conv_network) x = Conv2D(filters=64, kernel_size...
python|tensorflow|keras|deep-learning|data-augmentation
0
4,685
59,831,772
Select one dimension of Multidimensional array with list - numpy
<p>I have a 3D array of shape <code>(800,5,4)</code> like:</p> <pre><code>arr = array([[35. , 33. , 33. , 0.15], [47. , 47. , 44. , 0.19], [49. , 56. , 60. , 0.31], ..., [30. , 27. , 25. , 0.07], [54. , 49. , 42. , 0.14], [33. , 30. , 28. , 0.22]]) </co...
<pre><code>In [178]: arr = np.arange(24).reshape(2,3,4) </code></pre> <p>If I have a list of 7 items:</p> <pre><code>In [179]: idx = [0,1,1,2,2,0,1] In [180]: arr[:,idx,:] O...
python|numpy|multidimensional-array|numpy-ndarray
1
4,686
59,711,878
How to find max from strings with multiple decimals in python pandas?
<p>I have a data-frame with column entries like below. How can I find max value in such case ? The max value here I would consider ( though not true) is 5.0.5.658</p> <pre><code>4.6.0.2292 4.6.0.3122 4.8.0.1500 4.8.0.1938 5.0.4.283 5.0.5.658 </code></pre>
<p>Because you get error:</p> <blockquote> <p>TypeError: '>=' not supported between instances of 'float' and 'str' </p> </blockquote> <p>it means there are some missing values. So remove them by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dropna.html" rel="nofollow noreferrer"><...
python|python-3.x|pandas
1
4,687
32,408,550
Adding calculated columns to the Dataframe in pandas
<p>There is a large csv file imported. Below is the output, where <code>Flavor_Score</code> and <code>Overall_Score</code> are results of applying <code>df.groupby('beer_name').mean()</code> across a multitude of testers. I would like to add a column Std Deviation for each: <code>Flavor_Score</code> and <code>Overall_S...
<p>You could use</p> <pre><code>df.groupby('Beer_name').agg(['mean','std']) </code></pre> <p>This computes the mean and the std for each group.</p> <hr> <p>For example,</p> <pre><code>import numpy as np import pandas as pd np.random.seed(2015) N = 100 beers = ['Coors', 'Sam Adams', 'Becks', 'Guinness', 'Heineken'...
python|pandas|dataframe|mean|calculated-columns
0
4,688
40,443,357
Understanding dimension of input to pre-defined LSTM
<p>I am trying to design a model in tensorflow to predict next words using lstm.<br> <a href="https://www.tensorflow.org/versions/master/tutorials/recurrent/index.html" rel="nofollow noreferrer">Tensorflow</a> tutorial for RNN gives pseudocode how to use LSTM for PTB dataset.<br> I reached to step of generating batches...
<p>The full example for PTB is in the source <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/rnn/ptb/ptb_word_lm.py" rel="nofollow noreferrer">code</a>. There are recommended defaults (<code>SmallConfig</code>, <code>MediumConfig</code>, and <code>LargeConfig</code>) that you can use.</p...
python|tensorflow|recurrent-neural-network|lstm
0
4,689
40,485,246
Pandas - Convert HH:MM:SS.F string to seconds - Caveat : HH sometimes goes over 24H
<p>I have the following dataframe : </p> <blockquote> <p><code>**flashtalking_df =**</code></p> </blockquote> <pre><code>+--------------+--------------------------+------------------------+ | Placement ID | Average Interaction Time | Total Interaction Time | +--------------+--------------------------+--------------...
<p>I think you need first convert <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="noreferrer"><code>to_timedelta</code></a> and then to <code>seconds</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="noreferrer"><code>a...
date|datetime|pandas|seconds
8
4,690
18,651,142
How to reindex_axis Pandas Panel to MultiIndex
<p>I have a 3D panel data. I am unable to reindex it to a multi index along level 2.</p> <p>I have created the multi index 'mind'.</p> <pre><code>import pandas as pd mind = pd.MultiIndex.from_arrays([['Consumer,Cyclical','Industrial','Software'], ['Retail','MiscellaneousManufactur','Technology'], ['AZO','AZZ','AZPN'...
<p>This appears to be a bug in 0.12 (and will be fixed in 0.13).<br> A workaround is not to reindex after, but to use the MultiIndex when creating dfclose:</p> <pre><code>dfclose = pd.DataFrame([[1.1, 2.1, 3.1], [1.2, 2.2, 3.2]], index=['2013-09-02','2013-09-03'], ...
python|pandas|panel|multi-index
1
4,691
61,650,474
ValueError: Columns must be same length as key in pandas
<p>i have df below </p> <pre><code> Cost,Reve 0,3 4,0 0,0 10,10 4,8 len(df['Cost']) = 300 len(df['Reve']) = 300 </code></pre> <p>I need to divide <code>df['Cost'] / df['Reve']</code></p> <p>Below is my code</p> <pre><code>df[['Cost','Reve']] = df[['Cost','Reve']].apply(pd.to_numeric) </cod...
<p>Problem is duplicated columns names, verify:</p> <pre><code>#generate duplicates df = pd.concat([df, df], axis=1) print (df) Cost Reve Cost Reve 0 0 3 0 3 1 4 0 4 0 2 0 0 0 0 3 10 10 10 10 4 4 8 4 8 df[['Cost','Reve']] = df[['Cost','Reve']].apply(pd.to_nume...
python|pandas
7
4,692
61,769,094
pandas - Broadcasting division
<p>I'm having two dataframes: </p> <ul> <li><code>df_1</code> with single index <code>i</code> and one column <code>LB</code> of <code>float</code>s.</li> <li><code>df_2</code> with multiindex <code>i, a, s</code> and 500 columns of <code>floats</code>s.</li> </ul> <p>My goal is to divide each value in <code>df_1[LB]...
<p>You can <em>broadcast</em> <code>df_1</code> to match the multi-level index of the second dataframe. Then you can easily broadcast the division at the numpy level:</p> <pre><code>tmp = pd.DataFrame(np.repeat(df_1.values, len(df_2)/len(df_1)), index = df_2.index, columns=df_1.columns) df_3 = pd.D...
python|pandas
1
4,693
61,968,661
sort dataframe with dates as column headers in pandas
<p>My dates have to be in water years and <strong>I wanted to find a way where I have the column start with date 09/30/1899_24:00 and end with date 9/30/1999_24:00.</strong></p> <p><a href="https://i.stack.imgur.com/Rtx6f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rtx6f.png" alt="enter image de...
<h2>The issue is that <code>24:00</code> is not a valid time</h2> <ul> <li>If you don't convert the date column to valid datetime then python will treat the column as a string. <ul> <li>This will make it very difficult to perform any type of time based analysis</li> <li>The order of the columns will then be ordered n...
python|pandas|sorting|date|header
1
4,694
61,684,195
How to set a ** parameter in Python
<p>I'm newbie in Python.</p> <p>I'm using Python 3.7.7 and Tensorflow 2.1.0.</p> <p>This is my code:</p> <pre><code>import tensorflow as tf import tensorflow_datasets as tfds d = {"name": "omniglot:3.0.0", "data_dir": "d:\\tmp"} omniglot_builder = tfds.builder("omniglot:3.0.0", builder_init_kwargs=d) omniglot_build...
<p>Based on the <a href="https://www.tensorflow.org/datasets/api_docs/python/tfds/builder" rel="nofollow noreferrer">docs</a>, which say the <code>tfds.builder</code> method has type:</p> <pre><code>tfds.builder( name, **builder_init_kwargs ) </code></pre> <p>You want to do this:</p> <pre><code>dict = {"name":"o...
python|tensorflow|tensorflow-datasets
1
4,695
58,082,023
How exactly does Ray share data to workers?
<p>There are many simple tutorials and also SO questions and answers out there which claim that Ray somehow shares data with the workers, but none of these go into the exact details of what gets shared how on which OS.</p> <p>For example in this SO answer: <a href="https://stackoverflow.com/a/56287012/1382437">https://...
<p>This is a great question, and one of the cool features that Ray has. Ray provides a way to <strong>schedule functions in a distributed environment</strong>, but it also provides a <strong>cluster store</strong> that manages data sharing between these tasks.</p> <p>Here are the kind of objects that ray</p> <ul> <li>O...
python|numpy|serialization|shared-memory|ray
3
4,696
57,744,353
DataFrame is empty, expected data in it
<p>I want to find duplicate items within 2 rows in Excel. So for example my Excel consists of:</p> <pre><code> list_A list_B 0 ideal ideal 1 brown colour 2 blue blew 3 red red </code></pre> <p>I checked the pandas documentation and tried duplicate method but I simply don't know why it keeps say...
<p>The term "duplicate" is usually used to mean rows that are exact duplicates of previous rows (see the documentation of <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer">pd.DataFrame.duplicate</a>).</p> <p>What you are looking for is just ...
python|pandas
0
4,697
58,086,280
pandas join remove columns if the same
<p>I have 2 dataframes <code>df1</code> and <code>df2</code> that I want to join based on their column <code>'C'</code></p> <pre><code>import pandas df1 = pandas.DataFrame(data=[[1,0,2,4],[2,3,1,3]],columns=['A','B','C','D']) df2 = pandas.DataFrame(data=[[2,2,2,4],[3,4,1,3]],columns=['A','F','C','D']) df1 A ...
<p>You can do <code>drop_duplicates</code></p> <pre><code>df1.merge(df2,on='C').T.drop_duplicates().T Out[288]: A_x B C D_x A_y F 0 1 0 2 4 2 2 1 2 3 1 3 3 4 </code></pre> <p>Update </p> <pre><code>pd.concat([df1.set_index('C'),df2.set_index('C')],1,keys=['right','left']).\ T.rese...
python|pandas|join
1
4,698
37,106,284
Pandas and Large dataframe
<p>I decided to use pandas (0.18.1) to work on a log data from one of my models using discrete element particles. This log has attributes related to 400000 particles (x,y,z positions and velocities; around 5M rows) with the following structure:</p> <pre><code>***************************************** * Log File Starte...
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html" rel="nofollow"><code>df.pivot</code></a>:</p> <pre><code>import pandas as pd df = pd.read_csv("Desloc_Caixa_Compress_14_04_16_19.log", header=None, skiprows=8, engine='python', skipfooter=4, sep=" ") df['index'] = ...
python|pandas
1
4,699
36,971,635
Scipy fitting polynomial model to some data
<p>I do try to find an appropriate function for the permeability of cells under varying conditions. If I assume constant permeability, I can fit it to the experimental data and use Sklearns <code>PolynomialFeatures</code> together with a <code>LinearModel</code> (As explained in <a href="https://stackoverflow.com/quest...
<p>I'm not aware of such a function that does exactly what you need, but you can achieve it using a combination of <code>itertools</code> and <code>numpy</code>.</p> <p>If you have <code>n_features</code> predictor variables, you essentially must generate all vectors of length <code>n_features</code> whose entries are...
python|numpy|scipy|scikit-learn
1