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
20,200
69,701,365
How to squeeze or reduce dimensions of a mapdataset in tensorflow
<p>I have a mapdataset element with the following dimensions:</p> <pre><code>MapDataset element_spec=(TensorSpec(shape=(None, 1, 24), dtype=tf.float32, name=None), TensorSpec(shape=(None, 1, 24), dtype=tf.float32, name=None)) </code></pre> <p>I want to create a functional api as below:</p> <pre><code>input_ = keras.lay...
<p>You can just apply another <code>map</code> function to your dataset to reduce the dimensions, before feeding your dataset to your model:</p> <pre class="lang-py prettyprint-override"><code>def prepare_data(x): return tf.random.normal((samples, 1, 24)), tf.random.normal((samples, 1, 24)) def reduce_dimension(x, y...
python|tensorflow|keras|dimensions
1
20,201
72,216,036
How do I figure out which groups in a Pandas Dataframe have a sequence of events in a specific order?
<p>I have a pandas dataframe regarding analytics tracking of user behaviour. It has a structure like this:</p> <p><a href="https://i.stack.imgur.com/CbKj4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CbKj4.png" alt="enter image description here" /></a></p> <p>I want to count the number of sessions...
<p>You could try something like this:</p> <pre><code>import numpy as np types = ['typeA', 'typeB'] for type_ in types: df[f'event_{type_}_timestamp'] = np.where(df['event_name'] == f'interesting_event_{type_}', df['event_timestamp'], ...
python|pandas
1
20,202
50,666,843
How to mark a verb in a sentence using spaCy? (python)
<p>I want to mark verbs in sentences by adding an 'X' at the end of the verb word, like this <code>verbX</code>.</p> <p><code>SpaCy</code> assigns tags to sentence elements that Python does not index separately. For example, spaCy sees a bracket <code>(</code> or full stop behind a word <code>.</code> as a separate pos...
<p>The problem is the order in which you do your operations, to achieve your desired result it should be:</p> <pre><code>def marking(row): chunks = [] for token in nlp(row): chunks.append(token.text_with_ws) #Append word first if token.tag_ == 'VBZ': chunks.append('X') #A...
python|python-3.x|pandas|spacy
3
20,203
45,678,910
How do I keep an ID in a pandas DF that has duplicates only if all of its records in another column have the same value?
<p>I want to keep the research ID if all of the test grades are the same, but if not I cannot rely on the integrity of the data and must discard the ID. </p> <p>I tried creating a dictionary, but for the research id below, only L4 was saved as a value.</p> <pre><code>ResearchID TestGrade 1026379 L4 1026379 ...
<p>You could <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html#pandas.DataFrame.groupby" rel="nofollow noreferrer">groupby</a> the research id and then keep only those ids where the length of the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.un...
python|pandas|dictionary|duplicates
0
20,204
45,685,430
Vectorized way of finding position of one column value in another in Pandas
<p>Basically the following code returns the position of a character in column 'a' in another string (in this case '}JKLMNOPQR'). In this example, column 'b' has the same value in all rows, but it could have different values.</p> <p>Is there a vectorized way to do this?</p> <pre><code>frame = pd.DataFrame({'a' : ['L',...
<p>Not vectorized but a faster solution using <code>zip</code>:</p> <pre><code>lframe1 = pd.concat([frame]*1000) lframe2 = pd.concat([frame]*1000) %timeit lframe1['c'] = lframe1.apply(lambda row: row.b.find(row.a), axis=1) # 10 loops, best of 3: 77.7 ms per loop %timeit lframe2['c'] = [b.find(a) for a, b in zip(lfra...
python|pandas
3
20,205
45,279,799
How to restore tensorflow model without index file and meta file?
<p>New checkpoint format generates three files: <code>model.ckpt-1000.data-00000-of-00001</code>,<code>model.ckpt-1000.meta</code>,<code>model.ckpt-1000.index</code>. Old checkpoint format only generates two files: <code>model.ckpt-1000</code> and <code>model.ckpt-1000.meta</code>.</p> <p>When I restore model wrote wi...
<p>I believe it did use the old checkpoint format. Here's a simple example I used to verify:</p> <pre><code>import tensorflow as tf slim = tf.contrib.slim x = tf.placeholder(tf.float32, [None, 16]) y = slim.fully_connected(x, 4) saver_v1 = tf.train.Saver(write_version=tf.train.SaverDef.V1) saver_v2 = tf.train.Save...
python|tensorflow
4
20,206
62,587,650
Forecasting stocks with LSTM in Keras (Python 3.7, Tensorflow 2.1.0)
<p>I'm trying to use LSTM to predict how the Dow Jones Industrial Average will perform in coming months. I think it is appropriate to frame this as a time series scenario since the DJIA behaves like a stock, with my data values spread evenly in time. I'm only a beginner, so starting simply with only one feature (daily ...
<p><strong>Case 1:</strong> At the start of your question, you mentioned &quot;For example, I use days 0-29 to predict day 30, days 1-30 to predict day 31, etc. &quot;.</p> <p><strong>Case 2:</strong> But in <code>Question 3</code>, you mentioned &quot;For example, x_train[0] might include close values for days 0-29, a...
python|tensorflow|keras|time-series|lstm
0
20,207
54,304,690
Solve `A` `B` in matrix multiplication `AB=Y` for arbitrary `Y` using least square
<p>I'm sorry if this is a duplicate of some thread. I know there are lots of decompositions to decompose a matrix (like <code>LU</code> or <code>SVD</code>), but now I have an arbitrary <strong>non-square matrix and I want to decompose it to product of two matrices of given shape</strong>. If exact solution do not exis...
<p>You can do this with the SVD. See, for example <a href="https://en.wikipedia.org/wiki/Singular_value_decomposition#Low-rank_matrix_approximation" rel="nofollow noreferrer">the wiki article</a> Suppose, for example you had an mxn matrix Y and wanted to find a factorisation </p> <pre><code>Y = A*B where A is mx1 and ...
python|numpy|least-squares
2
20,208
54,423,007
DNNClassifier's loss with EarlyStopping
<p>I'm trying to use a hook in my <code>DNNClassifier</code> model using <a href="https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/EarlyStopping" rel="nofollow noreferrer"><code>tensorflow.keras.callbacks.EarlyStopping</code></a> but I have no idea what to put in <code>monitor</code>. The documentation is ...
<p>The <code>monitor</code> does not refer to a graph node or a layer, but to a loss or metric value. Indeed any value can be used that is present in your <code>logs</code> dictionary: <a href="https://github.com/tensorflow/tensorflow/blob/r1.12/tensorflow/python/keras/callbacks.py#L676" rel="nofollow noreferrer">https...
python|tensorflow
1
20,209
54,596,476
Pandas: Multiply a column based on a different columns condition
<p>I am using Python with Pandas. How can I multiply a column by 1000 given another column has a certain string?</p>
<p>This should do it.</p> <pre><code>df['columnname'] = np.where(df['othercolumn'] == 'CertainString', df['columnname'] * 1000, df['columnname']) </code></pre>
python|pandas
11
20,210
73,806,751
Replacing words in a dataframe given a list of common misspellings in Python?
<p>I have a large dataset with one column of multi-word names that contain frequent spelling errors. We have a separate dataframe with a column of common misspellings. We want to replace all of the misspellings in the large dataset with the one correct spelling.</p> <p>This is what I tried so far (with a simplified dat...
<p>It appears that the previous answerer has not tried their code, as if they do they will get the following error, since <code>df['city']</code> is a pandas Series, not a string:</p> <pre><code>TypeError: expected string or bytes-like object </code></pre> <p>The general idea of using RegEx to match only whole words is...
python|pandas|dataframe|replace
1
20,211
52,086,012
How to get a nested dictionary inside a list into Dataframe?
<p>I'm trying to get data from an exchange's api, and it is in a list with dict inside, I think? So I want to create a table, with the name, initial price, price, high, low and so on.. question: How do I get them into the dataframe format? Index with <code>pd.Dataframe</code> works but only if it's one stock.</p> <p><...
<p>Reshape your data and then call <code>DataFrame.to_dict</code>:</p> <pre><code>df = pd.DataFrame.from_dict( {k : d[k] for d in data for k in d}, orient='index') </code></pre> <p></p> <pre><code>df[['initialprice', 'price', 'high', 'low']] initialprice price high low BTC-ACM 0...
python|pandas
1
20,212
52,447,141
Pandas - Ranking items within group by treating repeat items in a group as new
<p>Dataframe has two columns (ColA &amp; ColB)</p> <pre><code> ColA ColB 123 A 123 B 123 C 123 C 123 D 123 C 123 C 456 A 456 B 456 D 456 D 456 E </code></pre> <p>I would like to create a new Column that ranks within the group by treating repeat items with...
<p>You can do:</p> <pre><code>df['ColC'] = df.groupby('ColA')['ColB'].transform(lambda x:(x!=x.shift()).cumsum()) &gt;&gt;&gt; df ColA ColB ColC 0 123 A 1 1 123 B 2 2 123 C 3 3 123 C 3 4 123 D 4 5 123 C 5 6 123 C 5 7 456 A 1 8 456...
python|pandas
3
20,213
52,182,483
Insert and rename columns in multiple csv files and merging into one csv
<p>I have plenty of csvs that look like this: </p> <p><a href="https://i.stack.imgur.com/NuD8z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NuD8z.png" alt="csv output 1"></a></p> <p>I want to rename column names because they are too long and to insert new column named <strong>Company</strong> wi...
<p>You can read each file in dict comprehension, add key by name of file and last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> together:</p> <pre><code>import glob, os files = glob.glob('files/*.csv') d = {'Working Capital / Tota...
pandas
2
20,214
60,348,247
Change line shape to aggregated plot
<p>I'm attempting to make a plot of net sentiment score by genre over time. I currently have a line plot that works, but I'd like to make each genre a different color/shape. However, I have about 12 different genres and I'd prefer to not manually assign a color/shape to each genre. Is there a way for matplotlib to dyna...
<p>You can use a styling dictionary like this:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df_tips = sns.load_dataset('tips') fig, ax = plt.subplots(figsize=(15,7)) style_dic = {k:v for k,v in zip(df_tips['day'].unique(),['ro-','b^-','gs-','m+-'])} df_tips.groupby(['sex','...
python|pandas|matplotlib
0
20,215
60,621,245
Remove duplicate rows based on presence of other column values
<p>I am new to python, and am trying to remove any rows with blank <code>EOB</code> codes where multiple <code>EOB</code> codes already exist for that <code>Account Number</code>. So, for example, we have this "407" <code>Account Number</code> contributing three rows. I'd like the row with the missing <code>EOB</code> ...
<p>I would try to identify the indexes to drop with the following conditions:</p> <ul> <li>Account Number has at least one row with a non empty EOB</li> <li>EOB is the empty string</li> </ul> <p>It could be:</p> <ol> <li><p>Find the relevant account numbers:</p> <pre><code>x = df[df.EOB != ''].groupby('Account Numb...
python|pandas
1
20,216
60,660,900
Adding custom metric Keras Subclassing API
<p>I'm following the section "Losses and Metrics Based on Model Internals" on chapter 12 of "Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow, 2nd Edition - Aurélien Geron", in which he shows how to add custom losses and metrics that do not depend on labels and predictions.</p> <p>To illustrate this,...
<p>The problem is just right here:</p> <pre><code>def call(self, inputs, training=None): Z = inputs for layer in self.hidden: Z = layer(Z) reconstruction = self.reconstruct(Z) recon_loss = tf.reduce_mean(tf.square(reconstruction - inputs)) self.add_loss(0.05 * recon_loss) if training: ...
tensorflow|keras|deep-learning|keras-layer|tf.keras
3
20,217
72,830,928
Extracting node indices in an array in Python
<p>I want to extract indices in <code>nodes</code> corresponding to node numbers mentioned in the array <code>I2</code>. The current and expected outputs are presented.</p> <pre><code>import numpy as np nodes={(0, 0): 1, (0, 1): 2, (1, 0): 3, (1, 1): 4} I2=np.array([[1,2],[1,3],[2,4],[3,4]]) I3=[[i,i] in I2 for i ...
<p>You can first reverse <code>dictionary</code> then do like below :</p> <pre><code>import numpy as np nodes={(0, 0): 1,(0, 1): 2,(1, 0): 3,(1, 1): 4} rvs_nodes = {v:k for k,v in nodes.items()} I2=np.array([[1,2],[1,3],[2,4],[3,4]]) I3 = [[rvs_nodes[node[0]], rvs_nodes[node[1]]] for node in I2] print(&quot;I3 =&quot...
python|list|numpy|dictionary
1
20,218
72,501,778
How to use Tensorflow Federated on Windows?
<p>I am trying to use Tensorflow's tutorial of doing image classification using Federated Learning over <a href="https://www.tensorflow.org/federated/tutorials/federated_learning_for_image_classification" rel="nofollow noreferrer">here</a></p> <p>Firstly, there were some pip dependency resolver errors popping up, but I...
<p>I believe that error is symptomatic of an older python version. The latest version of TFF (0.27.0 at the time of writing) requires python 3.9. Currently, colab does not support 3.9. See <a href="https://github.com/tensorflow/federated/issues/2770" rel="nofollow noreferrer">https://github.com/tensorflow/federated/iss...
tensorflow|machine-learning|tensorflow-federated
0
20,219
72,670,711
Unpacking numpy array inside
<p>I have the following numpy array:</p> <pre><code>a=[['Sb' array([4.24035696, 2.44817292, 7.41858935])] ['I' array([2.08076032, 3.69501392, 5.37518666])] ['I' array([6.35173963, 1.22916823, 8.9947238 ])] ['I' array([ 4.24036048, -0.04551256, 5.37518684])] ['I' array([4.24035383, 4.88618543, 8.99472472])] ['I' a...
<p>See my comment for explanation:</p> <pre><code>In [142]: array=np.array ...: a=np.array([['Sb', array([4.24035696, 2.44817292, 7.41858935])], ...: ['I', array([2.08076032, 3.69501392, 5.37518666])], ...: ['I', array([6.35173963, 1.22916823, 8.9947238 ])], ...: ['I', array([ 4.24036048, -0.0455...
python|arrays|numpy
1
20,220
59,870,679
Keras R Value Error: No data provided for "dense_59"
<p>I am working with the KERAS package in R for the first time. Using this tutorial as help to guide my first model (<a href="https://keras.rstudio.com/articles/tutorial_basic_regression.html" rel="nofollow noreferrer">https://keras.rstudio.com/articles/tutorial_basic_regression.html</a>). Everything was going smoothly...
<p>Your data is not a minimal working example. your <code>train</code> refers to sth not given. Nobody can try your code. Thus nobody helped.</p> <p>Always post a minimal working example - although you don't see it often. This is the fastest way to get quickly answers!</p> <p>However, I took some time to answer this....
r|tensorflow|keras|neural-network
1
20,221
61,953,312
Use of index in pandas DataFrame for groupby and aggregation
<p>I want to aggregate a single column DataFrame and count the number of elements. However, I always end up with an empty DataFrame:</p> <pre><code>pd.DataFrame({"A":[1, 2, 3, 4, 5, 5, 5]}).groupby("A").count() Out[46]: Empty DataFrame Columns: [] Index: [1, 2, 3, 4, 5] </code></pre> <p>If I add a second column, I...
<p>Give this a shot:</p> <pre><code>import pandas as pd print(pd.DataFrame({"A":[1, 2, 3, 4, 5, 5, 5]}).groupby("A")["A"].count()) </code></pre> <p>prints</p> <pre><code>A 1 1 2 1 3 1 4 1 5 3 </code></pre>
python|pandas
1
20,222
61,839,430
shape mismatch with ProfileReport - Python
<p>I am using the library pandas_profiling to get data profiling. In particular, I am connecting to Postgres to get the data and then, create the profile.</p> <pre><code>#creating a new engine instance engine = create_engine('postgresql+psycopg2://dbname:password@host/db') df = pd.read_sql_query('''select * from test'...
<p>i was facing a similar error saying value array of shape (19,) could not be broadcast to indexing result of shape (20,). </p> <p>Please check for NaN values in your data, for me getting rid of them worked. Another thing that you can do is decreasing the size of your data. I was dealing with 4 million rows but teste...
python|pandas
0
20,223
57,808,266
Tensorflow2.0 Keras: Is dropout disabled during testing by default?
<p>I am wondering if in the following model, dropout will be disabled when I call <code>model.evaluate(...).</code></p> <pre><code>layers = [tf.keras.layers.Dense(size, activation='relu') for size in (20, 40, 20)] layers.insert(1, tf.keras.layers.Dropout(0.2)) layers.append(tf.keras.layers.Dense(1, a...
<p>Yes, dropout is always disabled at inference (<code>evaluate</code>/<code>predict</code>).</p>
python|tensorflow|keras|tensorflow2.0
4
20,224
54,731,910
how add label in column for numpy array
<p>How add label in column as string for numpy array</p> <p>I need this output</p> <blockquote> <pre><code> One Two Three A 1, 2, 3 B 4, 5, 6 </code></pre> </blockquote> <pre><code>import numpy as np import pandas as pd a=pd.DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])], orient='index', co...
<p>The warning you're being given is to tell you you're using a deprecated (to be removed) syntax. It suggests you use <code>from_dict</code> instead, for example</p> <pre><code>import numpy as np import pandas as pd a=pd.DataFrame.from_dict({ 'A': [1, 2, 3], 'B': [4, 5, 6] }, orient='index', columns=['one', '...
python|pandas|numpy
5
20,225
54,725,502
n'th vlookup in pandas dataframe
<p>Similar to this post <a href="https://stackoverflow.com/questions/38291908/excel-vlookup-equivalent-in-pandas">Excel VLOOKUP equivalent in pandas</a></p> <p>I don't need the first value it comes across, but the n'th value.</p> <p>Here is an example data set, with the desired output.</p> <pre><code>from pandas imp...
<p>It's probably not the nicest solution, but it works:</p> <p>Depending on how I set lag_date, I can lag the data for that specific date.</p> <pre><code># first create new unique identifiers, based on the data + the product code df.date = df.date.dt.strftime('%Y-%m-%d') # first convert for concatenating df['vlook_da...
pandas|vlookup
0
20,226
49,622,431
Operation on pandas dataframe depending on type
<p>Is there any elegant way in a Pandas Dataframe with several columns of <code>float64</code> and other types to make a global operation only on the <code>float64</code> elements?</p> <p>What I am looking for is to divide all <code>float64</code> elements by 100, without having to target or name specific columns.</p>
<p>You could use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.select_dtypes.html" rel="nofollow noreferrer"><code>df.select_dtypes()</code></a>.</p> <pre><code>cols = df.select_dtypes(include=['float64']).columns df[cols] = df[cols] / 100. </code></pre> <p>This will divide all <cod...
python|pandas|dataframe|types
3
20,227
49,575,548
pandas how to flatten a list in a column while keeping list ids for each element
<p>I have the following <code>df</code>,</p> <pre><code> A id [ObjectId('5abb6fab81c0')] 0 [ObjectId('5abb6fab81c3'),ObjectId('5abb6fab81c4')] 1 [ObjectId('5abb6fab81c2'),ObjectId('5abb6fab81c1')] 2 </code></pre> ...
<p>I think the comment is coming from this question ? you can using my <a href="https://stackoverflow.com/a/49452192/7964527">original post</a> or this one </p> <pre><code>df.set_index('id').A.apply(pd.Series).stack().reset_index().drop('level_1',1) Out[497]: id 0 0 0 1.0 1 1 2.0 2 1 3.0 3 1 4.0 4 ...
python-3.x|pandas|dataframe
3
20,228
73,413,744
ModuleNotFoundError: No module named 'tensorflow.python.ops.numpy_ops'
<p>I am trying to start learning some Machine Learning and am trying to import Tensorflow but am getting a ModuleNotFoundError:</p> <pre><code>ModuleNotFoundError: No module named 'tensorflow.python.ops.numpy_ops' </code></pre> <p>The code currently just tries to import packages:</p> <pre><code>import os import sys imp...
<p>I don't think there is a <code>tensorflow.keras.LSTM</code>. Maybe you're looking for <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/LSTM" rel="nofollow noreferrer"><code>tensorflow.keras.layers.LSTM</code></a> ?</p> <p><strong>Update:</strong></p> <p>The issue was solved by <a href="https://sta...
python|tensorflow
2
20,229
67,551,989
Splitting string value in given column (Pandas)
<p>I have a dataframe with many rows like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Variable</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>A1_1 - Red</td> </tr> <tr> <td>2</td> <td>A1_2 - Blue</td> </tr> <tr> <td>3</td> <td>A1_3 - Yellow</td> </tr> </tbody> </table...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;Variable&quot;] = df[&quot;Variable&quot;].str.split(&quot;_&quot;).str[0] print(df) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override"><code> ID Variable 0 1 A1 1 2 A1 2 3 A1 </code></pre>
python|pandas|dataframe|loops
0
20,230
67,308,670
Using tensorflow classification for feature extraction
<p>I am currently working on a system that extracts certain features out of 3D-objects (Voxelgrids to be precise), and i would like to compare those features to automatically made features when it comes to performance (classification) in a tensorflow cNN with some other data, but that is not the point here, just for ba...
<p>Yes, it is possible to train models exclusively for feature extraction. This is called transfer learning where you can either train your own model and then extract the features or you can extract features from pre-trained models and then use it in your task if your task is similar in nature to that of what the pre-t...
python|tensorflow|conv-neural-network|feature-extraction|voxel
0
20,231
60,139,545
Concatenating dataframes adding additional columns
<p>I'm trying to create a combined dataframe from a series of 12 individual CSVs (12 months to combine for the year). All the CSVs have the same format and column layout. </p> <p>When I first ran it, it appeared to work and I was left with a combined dataframe with 6 columns (as expected). Upon looking at it, I found ...
<p>One simple solution is the following.</p> <pre><code>import pandas as pd import numpy as np import os totrows = 0 files = os.listdir('c:/data/datasets') dfSD = pd.read_csv('c:/data/datasets/' + files[0], skip_blank_lines=True) columns = [] dfSD = [] for file in files: df = pd.read_csv('c:/data/datasets/' + ...
python|pandas|dataframe
0
20,232
60,331,162
How replaces values from a column in a Panel Data with values from a list in Python?
<p>I have a database in panel data form:</p> <pre><code>Date id variable1 variable2 2015 1 10 200 2016 1 17 300 2017 1 8 400 2018 1 11 500 2015 2 12 150 2016 2 19 350 2017 2 15 250 2018 2 9 450 2015 3 20 100 2016 3 ...
<p><code>map</code> is the way to go, with <code>enumerate</code>:</p> <pre><code>d = {k:v for k,v in enumerate(List, start=1)} df['id'] = df['id'].map(d) </code></pre> <p>Output:</p> <pre><code> Date id variable1 variable2 0 2015 Argentina 10 200 1 2016 Argentina 17 ...
python|pandas
0
20,233
60,095,254
DataFrame apply a function to the values in one column to create another
<p>I have a csv file the contains a date and a value</p> <pre><code>Date, Value 2020-03-18,90.0 . . 2020-04-10,100.0 </code></pre> <p>I am loading this file using read csv and applying a function to the date to convert it to a Quantlib date.</p> <pre><code>pd.read_csv(file_location,header=0,float_precision='round_tr...
<p>You can set the index when calling <code>read_csv</code> by using <code>index_col</code> kwarg:</p> <pre><code>pd.read_csv(file_location,header=0,float_precision='round_trip', converters = {'Date': DateList.ql_date_from_str}, index_col='Date') </code></pre> <p><strong>But</strong> it will r...
python|pandas|dataframe
1
20,234
65,390,459
UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 138-139: illegal encoding
<p>I seem to have this problem when I try importing my data from access, sometimes it works sometimes it doesn't. How can I fix this? knowing that this is my chunk of code:</p> <pre><code> conn = pyodbc.connect(r&quot;DRIVER={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=C:\Users\file.accdb; Uid=Admin; Pwd=;&quot;...
<p>You have encountered a known issue with the Access ODBC driver, described here:</p> <p><a href="https://github.com/mkleehammer/pyodbc/wiki/Tips-and-Tricks-by-Database-Platform#unicodedecodeerror-when-calling-cursorcolumns" rel="nofollow noreferrer">https://github.com/mkleehammer/pyodbc/wiki/Tips-and-Tricks-by-Databa...
python-3.x|pandas|ms-access|pyodbc
1
20,235
65,376,717
Fill missing coumns in a Pandas DataFrame?
<p>There are lots of questions about filling missing values.</p> <p>I want to fill whole missing columns.</p> <p>Suppose I have:</p> <p><code>df=pd.DataFrame([1,2], columns=['A'])</code></p> <pre><code> A 0 1 1 2 </code></pre> <p>What's the idiomatic way to do something like this?</p> <p><code>df.fillmissing(['A','...
<p>Perhaps you need <code>reindex</code>:</p> <pre><code>df.reindex(['A', 'B', 'C'], axis=1) A B C 0 1 NaN NaN 1 2 NaN NaN </code></pre> <p>This fills missing columns with NaN, leaving existing columns as-is.</p>
python|pandas
3
20,236
49,978,432
covert sql query output to json in python
<p>I want the output of the query to be consumed by charts js. They require json/array format for values and labels. I am new to python and pandas. My code - </p> <pre><code>import pandasql as pdsql str="""select DISTINCT File_type,count(File_type) as files from final_df where Search_String='amy' group by File_ty...
<p>Solved it. very easy and simple my bad. data_values=results["xxxfieldxxx"].tolist() data_labels=results["xxxfieldxxx"].tolist()</p>
python|json|pandasql
0
20,237
50,171,925
Find the minimum of a 2d interpolation
<p>I'm trying to find the minimum of a 2d interpolation. I"m really stuck on trying to find a way to appropriately pass the data to the optimizer,</p> <p>here is the code I have so far: </p> <pre><code>import scipy from scipy.interpolate import interp2d a_ca_energy_interp = interp2d(a, c_a, Energy) def run_2d_params...
<p><code>args</code> must be a tuple, even if it is only one argument:</p> <pre><code>scipy.optimize.fmin(run_2d_params, np.array([1.60,6.075]), args=(a_ca_energy_interp, )) </code></pre>
python|numpy|scipy
1
20,238
50,116,441
How can a pandas DataFrame histogram plot get month or day orders right?
<p>I want to have a set of functions that can plot a histogram of a variable in a DataFrame for bins that might correspond to days, months or hours. When I try to do this I end up with plots that have the days or months listed alphabetically in the horizontal axis when they should be listed temporally. How should this ...
<p>One way you could do this is to <code>import calendar</code> and <code>reindex</code> your results with <code>caleandar.month_name</code> from your groupby-count statement like this:</p> <p><strong><em>Note</em></strong> from <a href="https://docs.python.org/2/library/calendar.html" rel="nofollow noreferrer">calend...
pandas|datetime|dataframe|histogram|pandas-groupby
2
20,239
64,083,589
Python - Creating a for loop to build a single csv file with multiple dataframes
<p>I am new to python and trying various things to learn the fundamentals. One of the things that i'm currently stuck on is for loops. I have the following code and am positive it can be built out more efficiently using a loop but i'm not sure exactly how.</p> <pre><code>import pandas as pd import numpy as np url1 = ...
<p>You can do this:</p> <pre><code>base_url = 'https://www.cbssports.com/nfl/stats/player/receiving/nfl/regular/qualifiers/?page=' dfs = [] for page in range(1, 4): url = f'{base_url}{page}' df = pd.read_html(url) df.to_csv(f'NFL_Receiving_Page{page}.csv', index=False) dfs.append(df) df_receiving_agg =...
python-3.x|pandas|dataframe|for-loop
0
20,240
63,796,143
Restoring two tensorflow models in the same graph
<p>I am trying to restore two pre-trained models (identical architecture, different initialization) into the same tensorflow graph (e.g. for the purpose of computing adversarial examples that fool both models).</p> <p>In a nutshell: I am able to restore the two models in different scopes and make correct predictions. B...
<p>Declaring the gradients together with the models prior to restoring the variables makes the error go away:</p> <pre><code>from model import Model models, gradients = [], [] for k, path in enumerate(models_ckpts): with tf.variable_scope('model_%03i' % k): models.append(Model(mode='eval')) gradients.append(t...
tensorflow
0
20,241
63,865,582
How to correct overlapping tick labels in matplotlib plot
<p>I have the dataframes ready to plot, but when I use matplotlib to plot these data the lines are not correct and do not show the trend.</p> <p>for example, the first graph should be a curly line, however, I got a straight line plotted in the graph.</p> <p>I wonder how to plot these lines correctly? and fix both axis?...
<ol> <li>The dates are not a datetime format, so they are interpreted as strings, and they're all unique, which makes a mess of the axis. <ul> <li><code>df.index = pd.to_datetime(df.index)</code> has been added</li> </ul> </li> <li>The values in the columns are also strings, not numbers <ul> <li><code>df = pd.DataFrame...
python|pandas|matplotlib
1
20,242
63,879,780
NumPy array from list of lists with different length (padding)
<p>I have a list like this:</p> <pre class="lang-py prettyprint-override"><code>lista=[[1,2,3], [1,2,3,4,5,6], [1,2],] </code></pre> <p>I want to get numpy.array like this, (the shorter list element be expand to the max legnth, then set tail values as zeros):</p> <pre class="lang-py prettyprint-override">...
<p>There's no direct way using numpy, since each inner list has a different amount of elements. One way could be to use <a href="https://docs.python.org/3/library/itertools.html#itertools.zip_longest" rel="nofollow noreferrer"><code>itertools.zip_longest</code></a> with a <code>fillvalue</code>:</p> <pre><code>from ite...
python|numpy
2
20,243
64,069,064
Plotly-Dash: How to choose between multiple columns from multiple dataframes in a dictionary?
<p>I want to plot a double y-axis plot where the user can select which variable to look at. I want the dropdown option to change the original y-axis, but also want the second y-axis to change with the variable change. The data comes from two dictionaries, where each dictionary has 2 keys which are dataframes. Here are ...
<p>I've prepared a setup using Dash that should take all your considerations into account.</p> <ol> <li>You can select crop type <code>['corn', 'soybeans', 'winterwheat', 'springwheat']</code></li> <li>You can select which columns to display on the primary y-axis for each croptype in df_vals.</li> <li>And you can selec...
python|pandas|plotly|plotly-dash
2
20,244
67,876,340
Adding a new column to a Pandas DataFrame by comparing two columns to two similar columns in a different Dataframe
<p>I want to add a new column to Pandas DataFrame by taking the values in two of the columns and comparing both of them to values that appear in the same order in a different dataframe.</p> <p>Example:</p> <pre><code>first_names = pd.Series(['john','jack','jean','jose']) last_names = pd.Series(['bob','steve','carl','an...
<p>You can construct the <code>&quot;real&quot;</code> column using cross product between the two dataframes and then merge back to <code>names1</code>:</p> <pre class="lang-py prettyprint-override"><code>tmp = names1.merge(names2, how=&quot;cross&quot;) tmp[&quot;real&quot;] = (tmp[&quot;firstname_x&quot;] == tmp[&quo...
python|pandas|dataframe
0
20,245
67,988,066
NumPy - Find most common value in array, use largest value in case of a tie
<p>There are so many questions around that deal with finding the most common value in an array, but all of them return the &quot;first&quot; element in case of a tie. I need the highest value from the list of tied elements, imagine something like this:</p> <pre><code>import numpy as np my_array = [1, 1, 3, 3] most_com...
<p>Not sure how you'd go about solving this with Numpy, as there is no way to alter the tie-breaking logic of <code>argmax</code>, but you can do it with <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow noreferrer"><code>collections.Counter</code></a> easily:</p> <pre><code...
python|python-2.7|numpy
1
20,246
61,333,662
Reading a csv from url
<p>I'm trying to get the first chunk listed below to replicate the second chunk. However, I've noticed in jupyter that when I try to get to the same table; it displays it differently (the first chunk looks like a nice dataframe and the second just looks like a plain table). Is there a difference between the two methods...
<p>In the second dataframe, there are <code>NaN</code> values, which forces a conversion to <code>float</code>. For more details on this, see the documentation on the new <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/integer_na.html" rel="nofollow noreferrer">nullable integer datatype</a>.</p>
python|pandas|csv
1
20,247
61,422,172
How to run a keras with tensorflow 2 model on a machine with multiple CPU?
<p>How can I train a keras model with tensorflow 2 backend on a machine with multiple CPUs and GPUs on GCP? Does tf handle the process itself on backend? If so how can I verify it? Any simple sample code is appreciated. </p>
<p>There are many ways you can use GCP in order to train a model.</p> <p>Here are some of them (with different levels of Google management):</p> <p>1 - You can create a <a href="https://cloud.google.com/compute/docs/quickstart-linux" rel="nofollow noreferrer">Compute Engine Instance</a> (you can choose how much proc...
multithreading|keras|google-cloud-platform|deep-learning|tensorflow2.0
1
20,248
61,284,338
Keras uses GPU for first 2 epochs, then stops using it
<p>I prepare the dataset and save it as as hdf5 file. I have a custom data generator that subclasses Sequence from keras and generates batches from the hdf5 file.</p> <p>Now, when I model.fit_generator using the train generator, the model uses the GPU and trains fast for the first 2 epochs (GPU memory is full and GPU ...
<p>Can you try configuring GPU as given in this post <a href="https://www.tensorflow.org/guide/gpu" rel="nofollow noreferrer">https://www.tensorflow.org/guide/gpu</a></p> <p>Here is how i have done in my program</p> <pre class="lang-py prettyprint-override"><code>print("Runnning Jupyter Notebook using python version:...
tensorflow|keras|deep-learning|gpu
1
20,249
68,853,922
Understanding Group By's behavior with missing values and figuring out a discrepancy between .mean() and manually solving for the mean
<p>I have a multi-index df in the following form:</p> <pre><code> pid time delta_t sess_id vis_id id1 vis_id1 id1 t_0 1 vis_id1 id2 t_1 5 vis_id1 id1 t_2 NA id2 vis_id2 id3 t_3 6 vis_i...
<p>Fill NAs with 0, then it will be included in the mean, contributing to the denominator but not the numerator:</p> <pre><code>df1.fillna(0).reset_index().groupby('pid')['delta_t'].mean().reset_index().set_index('pid') </code></pre>
python|pandas|dataframe|group-by|data-analysis
0
20,250
68,710,137
Splitting a dataframe with the help of a loop (python)
<p>I need help. I would like to go through a DF. Partly my users have 2 teams (separated by commas in the row). I split these by the commas and write them in the new columns Team_1 and Team_2. If there is only one team, the name from team(s) goes into team 1.</p> <pre><code>import numpy as np import pandas as pd df = p...
<p>You are very close to solution.</p> <p>You just need to iterate through your function <code>get_team_names()</code> using <code>globals()</code> method.</p> <p>The <code>globals()</code> method returns the dictionary of the current global symbol table. <em>(A symbol table is a data structure maintained by a compiler...
python|pandas|dataframe|loops
0
20,251
68,468,287
Nth percentile in python is different from Dynatrace result
<p>I am trying to create a report based on the data extracted from Dynatrace.</p> <p>I am extracting the data on daily basis for the events, in my Python Django report, I need to show the Nth percentile data (like <em>30</em>th percentile, <em>60</em>th Percentile, <em>75</em>th Percentile, <em>90</em>th Percentile).</...
<p>This sort of discrepancies are normally due to the <a href="https://en.wikipedia.org/wiki/Percentile#The_linear_interpolation_between_closest_ranks_method" rel="nofollow noreferrer">interpolation method</a>, very noticeable when the sample is very small.</p> <p>However, 6055 is exactly percentile 75 in your sample:<...
python|excel|numpy|percentile|dynatrace
1
20,252
68,531,540
substring pandas column between the same character
<p>I have a pandas dataframe with the following column value:</p> <pre><code>data - test - data </code></pre> <p>I need to create the new column which includes string between '-'</p> <pre><code>test </code></pre> <p>I've tried:</p> <pre><code>df['column'] = df['column2'].apply(lambda st: st[st.find(&quot;-&quot;):st.fi...
<p>You can use <code>split</code> and take the first index in the list that is returned.</p> <pre class="lang-py prettyprint-override"><code>df['column'] = df['column2'].apply(lambda s: s.split('-')[1].strip()) </code></pre>
python|pandas|substring
2
20,253
68,810,751
Collate probabilities, predictions, coefficients from multiple samples of data using sklearn
<p>I would like to combine model probabilities for class 1 predictions for ALL rows from multiple (random) splits/samples of data into a single dataframe in python.</p> <p>I realize that not all rows will be selected in each split, but if data sampling is replicated enough times, each row will have been selected a few ...
<p>There are a couple problems with the code as is:</p> <ol> <li><p><code>.fit()</code> is never called here. I'm assuming you'd like it fit right after the train/test split line and before the predict_proba() call?</p> </li> <li><p>When you place the values into the dataframe, you're creating a new column and I assume...
python|pandas|scikit-learn|bootstrapping|resampling
1
20,254
52,950,449
valueError when using multi_gpu_model in keras
<p>I am using google cloud VM with 4 Tesla K80 GPU's. </p> <p>I am running a keras model using multi_gpu_model with gpus=4(since i have 4 gpu's). But, i am getting the following error</p> <blockquote> <p>ValueError: To call <code>multi_gpu_model</code> with <code>gpus=4</code>, we expect the following devices to ...
<p>It looks like Keras only sees one of the GPUs.</p> <p>Make sure that all 4 GPUs are accessible, you can use <code>device_lib</code> with TensorFlow.</p> <pre><code>from tensorflow.python.client import device_lib def get_available_gpus(): local_device_protos = device_lib.list_local_devices() return [x.name...
python|tensorflow|keras|google-cloud-platform|gpu
4
20,255
53,142,947
Pandas Dataframe: Replace charactere conditionally
<p>I have a dataframe with a column named "Size". This column have some values containing the size of an android applications list. </p> <pre><code>Size 8.7M 68M 2M </code></pre> <p>I need to replace these values to:</p> <pre><code>Size: 8700000 68000000 ... </code></pre> <p>I thought about a function that verifies...
<p>General solution for replace by multiple units:</p> <pre><code>#dict for replace _prefix = {'k': 1e3, # kilo 'M': 1e6, # mega 'B': 1e9, # giga } #all keys of dict separated by | (or) k = '|'.join(_prefix.keys()) #extract values to new df df1 = df['Size'].str.extract('(?P&lt;a&gt;[0-9....
python|pandas|jupyter-notebook|jupyter
3
20,256
53,290,164
Replace the day in a date in to fit the pd.to_datetime format
<p>I have a data frame with multiple columns and multiple rows. In one of these columns there are dates that take the form of <code>mm/dd/yyyy</code>. </p> <p>I am trying to convert this using <code>df['col'] = pd.to_datetime(df['col'])</code> but am getting the following error because there are multiple records that ...
<p>You could use the following regex to replace <code>00</code>:</p> <pre><code>import pandas as pd data = ['11/00/2018', '00/13/2018', '00/00/2018'] df = pd.DataFrame(data=data, columns=['col']) replace = df['col'].replace('00/', '01/', regex=True) result = pd.to_datetime(replace) print(result) </code></pre> <p><st...
python|pandas|string-to-datetime
2
20,257
65,583,611
"sample must be less than `1`" error in tensorflow distributions
<p>I'm currently using the beta distribution class from tensorflow and have the following problem:</p> <p>Snippet of my code:</p> <pre><code>self.dist = tf.distributions.Beta(concentration1=alpha, concentration0=beta, validate_args=True, allow_nan_stats=False) ... def neglogp(self, x): clipped_x = tf.clip_by_value(...
<p>Found my mistake:</p> <p>0.9999999999 was too precise for the float32 tensor, so it rounded it to 1 and the clipping used 1 as max value.</p> <pre><code>&gt;&gt;&gt; x = tf.Variable([0.9999999]) &gt;&gt;&gt; x.numpy() array([0.9999999], dtype=float32) &gt;&gt;&gt; x = tf.Variable([0.99999999]) &gt;&gt;&gt; x.numpy()...
python|tensorflow
0
20,258
65,627,300
TypeError: hook() takes 3 positional arguments but 4 were given
<p>I am trying to extract features from an intermediate of ResNet18 in PyTorch using forward hooks</p> <pre><code>class CCLModel(nn.Module): def __init__(self,output_layer,*args): self.output_layer = output_layer super().__init__(*args) self.output_layer = output_layer #PRETRAINED M...
<p>Here's a simple example of a forward hook, it must have three parameters <code>model</code>, <code>input</code>, and <code>output</code>:</p> <pre><code>m = models.resnet18(pretrained=False) def hook(module, input, output): print(output.detach().shape) m.fc.register_forward_hook(hook) </code></pre> <p>Try it w...
python|pytorch
1
20,259
65,701,474
Expand column dataframe nested dictionary
<p>I have make some tries but couldn't get the goal. I am completely sure that this is an easy question that someone could fix in a moment. I am trying to parse a json output to a dataframe but I am stuck in a nested dictionary. Given this example:</p> <pre><code>{'queryResponse': {'@count': 9364, '@doma...
<p>I could resolve this issue. I post the answer if someone could find it usefull.</p> <pre><code>df[&quot;NewPart&quot;] = [i['manufacturerPartNr'][0]['partNumber'].strip() for i in df['manufacturerPartNrs']] </code></pre>
python|pandas|dataframe|dictionary|nested
0
20,260
65,739,497
How to efficiently shuffle some values of a numpy array while keeping their relative order?
<p>I have a numpy array and a mask specifying which entries from that array to shuffle while keeping their relative order. Let's have an example:</p> <pre class="lang-py prettyprint-override"><code>In [2]: arr = np.array([5, 3, 9, 0, 4, 1]) In [4]: mask = np.array([True, False, False, False, True, True]) In [5]: arr[...
<p>For 1d case:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np a = np.arange(8) b = np.array([1,1,1,1,0,0,0,0]) # Get ordered values ordered_values = a[np.where(b==1)] # We'll shuffle both arrays shuffled_ix = np.random.permutation(a.shape[0]) a_shuffled = a[shuffled_ix] b_shuffled = b[shuffled...
python|arrays|numpy|numpy-slicing
0
20,261
65,909,149
Pandas - df.compare() how to change self/other labels?
<p>Using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.compare.html" rel="nofollow noreferrer">df.compare</a> in Pandas, is it possible to change the labels of self/other from the output?</p> <p>I need to send this output directly to less technically savvy users and would like to ...
<p>You can <code>rename</code> the index level to something more obvious:</p> <pre><code>df1 = pd.DataFrame([[1,2,3,4], [1,2,3,4]]) df2 = pd.DataFrame([[1,2,5,4], [5,2,3,1]]) df1.compare(df2, align_axis=0).rename(index={'self': 'left', 'other': 'right'}, level=-1) 0 2 3 0 left NaN 3.0 NaN right...
python|pandas
5
20,262
63,514,747
Graphing a continuous bar plot with different colors/width
<p>I am working on a relatively large dataset (5000 rows) in pandas and would like to draw a bar plot, but continuous and with different colors <a href="https://i.stack.imgur.com/vBJq7.png" rel="nofollow noreferrer">1</a>.</p> <p>For every depth data there will be a value of SBT.</p> <p>Initially, I thought to generate...
<p>Your graph consists of a lot of points with no information. Consecutive rows which contain the same SBT could we eliminated. Grouping by consecutive rows with equal content can be done by a shift and cummulative sum. The boolean expression looks for steps from one region to the next. If it is a step it returns true ...
python|pandas|matplotlib|plot|graph
0
20,263
63,727,907
In PyTorch calc Euclidean distance instead of matrix multiplication
<p>Let say we have 2 matrices:</p> <pre><code>mat = torch.randn([20, 7]) * 100 mat2 = torch.randn([7, 20]) * 100 n, m = mat.shape </code></pre> <p>The simplest usual matrix multiplication looks like this:</p> <pre><code>def mat_vec_dot_product(mat, vect): n, m = mat.shape res = torch.zeros([n]) for i...
<p>First of all, matrix multiplication in PyTorch has a built-in operator: <code>@</code>. So, to multiply mat and mat2 you simply do:</p> <pre><code>mat @ mat2 </code></pre> <p>(should work, assuming dimensions agree).</p> <p>Now, to compute the Sum of Squared Differences(SSD, or L2-norm of differences) which you seem...
python|pytorch|matrix-multiplication
2
20,264
63,478,509
Convolutionnal neural network for rare event using mel spectrogram
<p>My purpose was to create a model to detect rare sound in audios For example, an audio of 2 hours could contains 2 or 3 of this rare event I can't tell you more about the exact subject so sorry about that (because it's private).</p> <p>I had to work with several audio file which contained some rare event sound and ...
<p>Although your internship would be over and hope you'd be doing better. Working on audio is really a challenging. Challenges may be as under and you should work/update these and then check accuracy of model. <strong>1. Size of dataset:</strong> In this case rare sound which occur 2, 3 times in 2 hours audio, would d...
python-3.x|tensorflow|audio|conv-neural-network
0
20,265
53,651,598
Pandas long format DataFrame from multiple lists of different length
<p>Consider I have multiple lists</p> <pre><code>A = [1, 2, 3] B = [1, 4] </code></pre> <p>and I want to generate a Pandas DataFrame in long format as follows:</p> <pre><code>type | value ------------ A | 1 A | 2 A | 3 B | 1 B | 4 </code></pre> <p>What is the easiest way to achieve this? The way over...
<p>Create dictionary for <code>type</code>s and create list of tuples by list comprehension:</p> <pre><code>A = [1, 2, 3] B = [1, 4] d = {'A':A,'B':B} print ([(k, y) for k, v in d.items() for y in v]) [('A', 1), ('A', 2), ('A', 3), ('B', 1), ('B', 4)] df = pd.DataFrame([(k, y) for k, v in d.items() for y in v], col...
python|pandas|dataframe
1
20,266
71,909,101
Replacing each non-zero element with the inverse of it in Python
<p>I would like to replace each non-zero element of <code>R4_mod</code> with the inverse of it. The desired output is attached.</p> <pre><code>import numpy as np R4_mod=np.array([[0.00000000e+00, 1.96129124e+10, 0.00000000e+00, 1.88618492e+10, 0.00000000e+00], [6.94076420e+09, 0.00000000e+00, 1.11642674...
<p>As mentioned in the comments, <code>np.divide</code> can help you if you specify the <code>where</code> parameter. Like so:</p> <pre><code>np.divide(1, R4_mod, where=R4_mod!=0, out=R4_mod) </code></pre> <p>After this, R4_mod will contain the result of the divisions. As far as time and space complexity, this approach...
python|numpy
3
20,267
72,119,747
Google Or-Tools manipulating variables before solver
<p>I am new to OR-Tools and I am trying to solve an optimisation problem with 12 variables (masochism, I know).</p> <p>Each variable represents how much time each person (out of 2) should work on a particular device model (out of 2) each day (out of 3). New devices arrive each day and there are many devices in the back...
<p>this makes no sense:</p> <pre><code>for i in range(0, (a10*s1a + b10*s1b + a11*s1a + b11*s1b + a12*s1a + b12*s1b)): </code></pre> <p><code>a10</code> is a variable. <code>a10 * s1a</code> is a linear expression. It does not evaluate as a number for the range expression.</p> <p>You should look at basic CP-SAT example...
python|pandas|optimization|or-tools|constraint-programming
0
20,268
55,333,241
Unable to convert custom trained frozen model into tflite format
<p>I have the following script using which I was able to successfully convert deeplabv3_mnv2_pascal_train.pb model (<a href="https://drive.google.com/file/d/1xKI0SIrXB6Wl8SBuX-D1otI_8nuHjza1/view?usp=sharing" rel="nofollow noreferrer">click here to download</a>) into tflite format </p> <pre><code>tflite_convert \ --...
<p>Tflite was not properly installed, as a result the code produced strange output. I reinstalled TensorFlow on another OS and this problem was resolved.</p>
python|tensorflow|tensorflow-lite
0
20,269
56,631,504
How can I compare a column in a data frame by a value in a column with the same name/place in a second dataframe in Pandas?
<p>I have a dataframe which is organised in category by column and timestamp by row and a second dataframe with just one value per column as a threshold for the category.</p> <p>I want to filter all values that are bigger than the threshold per column into a new dataframe. all values that are lower should just be set ...
<p>Here's one way working with the underlying <code>NmmPy</code> arrays. I'm using up to <code>category C</code> from the provided sample:</p> <pre><code>df1 = df1.set_index('time') pd.DataFrame((df1.values &gt; df2.values)*df1.values, columns = df1.columns, index=df1.index) ...
python|pandas
1
20,270
56,607,596
How to fix the Attribute error:'Series' object has no attribute 'reshape' in this python code?
<p>I'm trying to make a recommendation system using the knn algorithm. I imported pandas(latest version 0.24) and created a sparse matrix. And now I am using reshape function but it is showing the error.</p> <p>I am using Jupyter Notebook. And I have imported 3 CSV's. </p> <pre><code>books = pd.read_csv('C:\\Users\\S...
<p>From <code>pandas</code> documentation,</p> <blockquote> <p>Deprecated since version 0.19.0: Calling this method will raise an error. Please call .values.reshape(...) instead.</p> </blockquote> <p>See <a href="https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.Series.reshape.html#pandas-series...
python|python-3.x|pandas
0
20,271
67,141,209
add a column to the dataframe using a loop in python pandas
<p>I've a sample dataframe</p> <pre><code>id city 1 Florida 2 Atlanta 3 Manhattan 4 Amsterdam 5 Newyork </code></pre> <p>I've a function</p> <pre><code>def my_function(x): y = x[::-1] return y </code></pre> <p>How can I make a for loop that uses <code>city</code> column and in...
<p>You can use the fact that a string in Python is an iterable. Note that you do not need <code>apply</code>.</p> <pre><code>df['reversed_string'] = df.city.str[::-1] </code></pre>
python|pandas
2
20,272
68,276,598
How to generate the combinations of an array and divide the numbers in each combination by the product of the numbers in the same combination?
<p>Given an array of N size, I want to return all possible permutations of the array. For each permutation of the array I want to return the value of each number in that combination divided by the sum of the other numbers in the combination including the dividend.</p> <p>Example: Give the array 123, you find all the po...
<p>You could do something like this, where you loop over each combination for each element in the combo.</p> <pre><code>from itertools import combinations, chain l = [1,2,3] c = list(chain.from_iterable([list(combinations(l,i)) for i in range(2,len(l)+1)])) results = [] for x in c: for n in range(len(x)): ...
python|arrays|numpy|combinations
0
20,273
59,363,874
CUDA Error: out of memory - Python process utilizes all GPU memory
<p>Even after rebooting the machine, there is &gt;95% of GPU Memory used by <code>python3</code> process (system-wide interpreter). Note that memory consumption keeps even if there are no running training scripts, and I've never used <code>keras/tensorflow</code> in the system environment, only with <code>venv</code> o...
<p>By default Tf allocates GPU memory for the lifetime of a process, not the lifetime of the session object (so memory can linger much longer than the object). That is why memory is lingering after you stop the program. In a lot of cases, using the <code>gpu_options.allow_growth = True</code> parameter is flexible, but...
python|tensorflow|keras|nvidia
3
20,274
45,874,025
Partial string substitution in pandas series
<p>I have am trying to do a string replacement in a pandas dataframe. Need to loop over individual columns, so its basically a replacement in a series:</p> <pre><code>In [105]: df = pd.DataFrame([['0 - abc', 1, 5], ['0 - abc - xyz', 2, 3]], columns=['col1','col2','col3']) In [106]: df Out[106]: col1 col2...
<p>Converting <code>df['col3']</code> to <code>str</code> using <code>.astype</code> fixes your problem:</p> <pre><code>In [836]: df.iloc[:, 0].replace('^0', df['col3'].astype(str), regex=True) Out[836]: 0 5 - abc 1 3 - abc - xyz Name: col1, dtype: object </code></pre> <p>I've simplified your regex as we...
python|regex|pandas|dataframe|series
1
20,275
46,013,115
How to change global_step in tensorflow`s SKCompat
<p>I'm using <code>SKCompat</code> class from <code>tensorflow.contrib.learn</code> for classifying MNIST data:</p> <pre><code>import tensorflow as tf from tensorflow.contrib.learn import SKCompat from tensorflow.contrib.learn import RunConfig config = tf.contrib.learn.RunConfig(save_summary_steps=1000 ...
<p>you can use <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/learn/RunConfig#__init__" rel="nofollow noreferrer"><code>RunConfig</code></a> to set run configuration. For your case setting <code>log_step_count_steps=1000</code></p> <pre><code>config = tf.contrib.learn.RunConfig(master=None, num_cores=0...
python|tensorflow|scikit-learn
1
20,276
45,996,397
Subset Pandas DataFrame based on annual returning period covering multiple months
<p>This question is similar to <a href="https://stackoverflow.com/q/18746650/2459096">Selecting Pandas DataFrame records for many years based on month &amp; day range</a>, but both the question and answer doesn't seem to cover my case</p> <pre><code>import pandas as pd import numpy as np rng = pd.date_range('2010-1-1...
<p>I would create a column of <code>(month, day)</code> tuples:</p> <pre><code>month_day = pd.concat([ df.index.to_series().dt.month, df.index.to_series().dt.day ], axis=1).apply(tuple, axis=1) </code></pre> <p>You can then compare them directly:</p> <pre><code>df[(month_...
python|pandas|datetime|slice
3
20,277
66,721,663
How to remove values from an array according to a specified condition
<p>I try to remove the values from the matrix according to the sequence, so that in the first line the highest value remains in the last position and in the last in the last position the lowest which is entered according to the condition. For example, I want to make a matrix from a 7x4 matrix 4x4 so the highest value i...
<pre><code>import numpy as np a = np.array([[11,12, 13, 14,15], [21, 22, 23, 24,25], [31, 32, 33, 34,35]]) condn = a.shape[1] - a.shape[0] +1 list_ = [] condn_test = condn for i in a: list_.append(list(i[condn_test-1: condn_test+condn-1])) condn_test -= 1 list_ = np.array(lis...
python|arrays|numpy
0
20,278
57,392,995
How to print separate url for each venue id?
<p>I have extracted this venue_id list:</p> <pre><code>0 4b92802ff964a5209cfe33e3 1 4e6ddd03fa768e6cee3d6485 2 51d81d66498e78da5b1601af 3 4d5fe18a9be02c0fc2e5de74 4 4d021cca9f9ea143b1648da9 5 4dce6fd2d164679b8cfec4dd 6 5469d96f498e07ba3182673f </code></pre> <p>Now I want to generate 6 url ...
<pre><code>venue_id_list=[ "4b92802ff964a5209cfe33e3", "4e6ddd03fa768e6cee3d6485", "51d81d66498e78da5b1601af", "4d5fe18a9be02c0fc2e5de74", "4d021cca9f9ea143b1648da9", "4dce6fd2d164679b8cfec4dd", "5469d96f498e07ba3182673f"] url2 = 'https://api.foursquare.com/v2/venues/{}?client_id={}&amp;client_secret={}&amp;v={}' for ...
python|pandas|foursquare
0
20,279
57,521,733
How to rename a column name to a new value in a dataframe if the column names are dynamic
<p>I have csv file with column names changing based on month and year but has keyword like 'sales' 'product' etc. Is there a way to rename the column to a fixed value using python rename by searching the keyword Sample column names would be 2019 May sales Tv, 2018 April sales Fridge eg</p> <p>nil</p> <pre><code>df_nw...
<p>You can do:</p> <pre><code>&gt; clean_colname = lambda x: re.sub(r'(^\w+(?&lt;!Actual))(Sales)', r'\2', re.sub(r'^\d+|TV$', r'', x)) &gt; df_nw.rename(clean_colname, axis=1) column2 Sales ActualSales column1 X BBBB 7766 ...
regex|pandas|python-2.7
0
20,280
51,316,697
python and fix_yahoo_finance library resulting in a ValueError
<p><strong>EDIT</strong></p> <p><strong><em>> See my own answer below for how I got it to work.</em></strong></p> <p>I'm having an issue using the fix_yahoo_finance library (version 0.0.22). Any help to point me in the right direction would be great.</p> <p>My goal is to load stock data. Currently, fix_yahoo_finance...
<p>@Yash Ghandhe 's answer unfortunately didn't work for me.</p> <p>I did get it to work by installing Anaconda and running Spyder IDE from there. I installed the Python 3.6 version (I was using Python 2.7 previously).</p> <p>I'm still not sure which libraries caused the issue, or if using Python 3 made the differenc...
python|pandas|yahoo-finance
1
20,281
51,451,951
keyError in pandas on selecting multiple columns
<p>I am having a weird error when selecting multiple columns in pandas dataframe. Here is the code:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.read_csv(&quot;./Dataset/train.csv&quot;, engine='python') df['eviv1', 'v2a1'] </code></pre> <p>I get this error message: <code>KeyError: ('...
<p>The column names (which are strings) cannot be sliced in the manner you tried. Please try this,</p> <pre class="lang-py prettyprint-override"><code>df[['eviv1', 'v2a1']] </code></pre>
python|pandas|dataframe
6
20,282
71,083,820
How to get the (relative) place of values in a dataframe when sorted using Python?
<p>How can I create a Pandas DataFrame that shows the relative position of each value, when those values are sorted from low to high for each column? So in this case, how can you transform 'df' into 'dfOut'?</p> <pre><code>import pandas as pd import numpy as np #create DataFrame df = pd.DataFrame({'A': [12, 18, 9, 21,...
<p>If you need to map the same values to the same output, try using the <code>rank</code> method of a <code>DataFrame</code>. Like this:</p> <pre><code>&gt;&gt; dfOut = df.rank(method=&quot;dense&quot;).astype(int) # Type transformation added to match your output &gt;&gt; dfOut A B C 0 2 3 1 1 4 5 2 2 1 4...
python|pandas
1
20,283
51,773,231
Python- How to Index and Print More Efficiently
<p>I'm still in the learning process of Python, and I had a quick question regarding efficiency and readability of my code.</p> <p>Currently I have this,</p> <pre><code>import pandas as pd from sklearn.linear_model import Lasso import numpy as np df=pd.read_csv('Data\\cmd.csv') df=df[['A71: ','A120: ',\ 'A70: ','A...
<p>I would create a list of column numbers, i.e.</p> <pre><code>col_numbers = [71, 120, 70, 84, 81, 89, 101, 102, 105] </code></pre> <p>then create a list out of them,</p> <pre><code>col_names = ['A{}: '.format(num) for num in col_numbers] </code></pre> <p>grab those specific columns from the dataframe,</p> <pre><...
python|pandas|numpy|scikit-learn
3
20,284
51,736,120
Own Implementation of Neural Networks in Python heavily under fitting the data
<p>I'm relatively new to machine / Deep Learning. I have decent experience in using API's such as Scikit- Learn, Tensor flow and Keras to develop supervised learning models. So, I wanted to implement one on my own to get better experience.</p> <p>I tried to implement a Basic Deep Neural Network Algorithm for a classif...
<p>I think this is not about underfitting, you should check your code more carefully. Here's some advice</p> <p>1.The delta of the output layer is wrong</p> <pre><code>error = self.y - self.layers['output'] </code></pre> <p>It should be <code>yHat - y</code>, and I think you don't need to multiply it by learning rat...
python|numpy|machine-learning|neural-network|deep-learning
2
20,285
36,149,656
Pycharm. Trouble installing numpy-mlk for Windows
<p>I'm new to Python and am trying to install numpy-mkl from Pycharm. I get the following error even though I upgraded 'pip' to version 8.1.1 from Pycharm. Thanks!</p> <p><a href="http://i.stack.imgur.com/ipvJw.png" rel="nofollow">http://i.stack.imgur.com/ipvJw.png</a></p>
<p>i don't believe numpy-mkl is in the repositories, so it can't be installed the way you're doing it. </p> <p>if you're running windows, download the appropriate Numpy+MKL .whl file from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">Here</a>. For me, on cpython 3.5 64-bit, the current file is nu...
numpy|installation|pycharm
0
20,286
35,924,194
2D array Of All Cyclic Shifts Of A 1D array
<p>Suppose <code>a</code> is some 1d <code>numppy.array</code> with <em>n</em> elements:</p> <pre><code>a = np.array([a_0, a_1, ..., a_n_minus_1]) </code></pre> <p>I'd like to generate the 2d (<em>n X n</em>) <code>numpy.array</code> containing, at row <em>i</em>, the <em>i</em>th cyclic shift of <code>a</code>:</p> ...
<p>you are actually building a circulant matrix. Just use the <a href="http://scipy.linalg.circulant" rel="noreferrer">scipy <code>circulant</code> function</a>. Be careful, because you must pass in the first vertical column, not first row:</p> <pre><code>from scipy.linalg import circulant circulant([1,4,3,2] &gt; arr...
numpy|scipy|vectorization
9
20,287
41,873,335
How to extract numeric ranges from 2 columns based on mathematical operations used as criterias for each column?
<p>Working with PANDAS data frames for python and based on a previous question (<a href="https://stackoverflow.com/questions/40607709/how-to-extract-numeric-ranges-from-2-columns-containig-numeric-sequences-and-pri">How to extract numeric ranges from 2 columns containig numeric sequences and print the range from both c...
<p><strong>Data:</strong></p> <pre><code>In [10]: df Out[10]: col1 col2 0 1 23 1 2 27 2 4 31 3 6 35 4 9 40 5 11 45 6 13 49 7 15 51 </code></pre> <p><strong>Solution:</strong></p> <pre><code>In [11]: df.groupby(df.diff().abs().eval("col1 &gt; 2 or col2 &lt;= 3"...
python|pandas|dataframe
2
20,288
41,916,365
How to use numpy to flip this array?
<p>Suppose I have an array like this:</p> <pre><code>a = array([[[ 29, 29, 27], [ 36, 38, 40], [ 86, 88, 89]], [[200, 200, 198], [199, 199, 197] [194, 194, 194]]]) </code></pre> <p>and I want to flip the 3rd element from left to right in the list-of-lists...
<p>Index the array to select the sub-array, using:</p> <pre><code>&gt; a[:,:,-1] array([[198, 197, 194], [ 27, 40, 89]]) </code></pre> <p>This selects the last element along the 3rd dimension of <code>a</code>. The sub-array is of shape <code>(2,3)</code>. Then reverse the selection using:</p> <pre><code>...
python|python-2.7|numpy
3
20,289
42,011,419
Is it possible to call tensorboard smooth function manually?
<p>I have two arrays X and Y. </p> <p>Is there a function I can call in tensorboard to do the smooth? </p> <p>Right now I can do an alternative way in python like: <code> sav_smoooth = savgol_filter(Y, 51, 3) plt.plot(X, Y) </code> But I am not sure what's way tensorboard do smooth. Is there a function I can ...
<p>So far I haven't found a way to call it manually, but you can construct a similar function,</p> <p>based on this <a href="https://stackoverflow.com/questions/42281844/what-is-the-mathematics-behind-the-smoothing-parameter-in-tensorboards-scalar">answer</a>, the function will be something like</p> <pre><code>def sm...
python|tensorflow|tensorboard
2
20,290
37,949,282
Pandas Multiindex Rows and Columns: Replace NaN with Value from Matching Row
<p>Given the following:</p> <pre><code>import pandas as pd import numpy as np df=pd.DataFrame({'County':['A','B','A','B','A','B','A','B','A','B'], 'Hospital':['a','b','e','f','i','j','m','n','b','r'], 'Enrollment':[44,55,95,54,81,54,89,76,1,67], 'Year':['2012','2012','20...
<p>If I understand correctly, the problem is to copy values from County B into County A when the Hospital matches. That can be done with <code>groupby/fillna(method='bfill')</code>. The <code>bfill</code> method backfills NaNs with the closest succeeding non-NaN value.</p> <p>Then, you can use <code>d2.drop_duplicates...
python-3.x|pandas|filter|group-by|multi-index
3
20,291
31,263,242
Does scikit learn's fit_transform also transform my original dataframe?
<p>I am using scikit learning's StandardScaler() and notice that after I apply a transform(xtrain) or fit_transform(xtrain), it also changes my xtrain dataframe. Is this supposed to happen? How can I avoid the StandardScaler from changing my dataframe? ( I have tried using copy=False)</p> <pre><code>xtrain.describe() ...
<p>You can take a copy and pass this in order to not modify your df:</p> <pre><code>xtrain2 = xtrain.copy() scalar.fit_transform(xtrain2) </code></pre> <p>The <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html" rel="nofollow">docs</a> state that the default param for ...
python|pandas|scikit-learn
4
20,292
64,245,557
len of empty dask dataframe raises exception
<p>I need to known the length of dask dataframe, though if I'm reading an empty file - the code produces an exception:</p> <pre><code>import dask.dataframe as dd if __name__ == '__main__': ddf = dd.read_csv(r'empty_file.csv', names=['x']) print(len(ddf)) </code></pre> <p>As a result I get the error:</p> <pre>...
<p>You can use the <strong>.empty</strong> to verify if yor dataframe is empty. Like this:</p> <pre><code>import dask.dataframe as dd if __name__ == '__main__': ddf = dd.read_csv(r'empty_file.csv', names=['x']) if not ddf.empty: print(len(ddf)) else: print(&quot;Empty dataframe&quot;) </co...
python|pandas|dask
1
20,293
64,548,199
Explain CUDA out of memory in Pytorch
<p>Can anybody help me to explain the meaning of this common problem in Pytorch?</p> <p>Model: EfficientDet-D4</p> <p>GPU: RTX 2080Ti</p> <p>Batch size: 2</p> <pre><code>CUDA out of memory. Tried to allocate 14.00 MiB (GPU 0; 11.00 GiB total capacity; 8.32 GiB already allocated; 2.59 MiB free; 8.37 GiB reserved in tota...
<p>I have the answer from @ptrblck in the Pytorch community. In there, I described my question in more detail than this question.</p> <p>Please check the answer in <a href="https://discuss.pytorch.org/t/misunderstanding-cuda-out-of-memory/100727/2" rel="nofollow noreferrer">here</a> .</p>
python|machine-learning|deep-learning|pytorch|out-of-memory
0
20,294
47,641,709
How to concatenate two vectors of different dimensions
<p>If X = [[ 1. 1. 1. 1. 1. 1.]] and Y = [[ 0. 0. 0. 0.]] - how can I concatenate the two vectors to form a single vector along column?</p> <p>I did the following but it didn't work:</p> <pre><code>import tensorflow as tf X = tf.constant(1.0, shape=[1, 6]) Y = tf.zeros(shape=[1,4]) XY = tf.concat((X,Y), axis ...
<p>If you want to concat them on axis 0, then their size must be equal</p> <p>Assuming that you don't want it, </p> <p>you need to set <code>axis = 1</code> in the <code>tf.concat</code> method</p>
python|tensorflow
0
20,295
49,147,996
Explode column of list to multiple rows
<p>I want to expand the list in a certain column (in the example column_x) to multiple rows. </p> <p>So</p> <pre><code>df = pd.DataFrame({'column_a': ['a_1', 'a_2'], 'column_b': ['b_1', 'b_2'], 'column_x': [['c_1', 'c_2'], ['d_1', 'd_2']] }) </code></pre> <p>...
<h3>Pandas &gt;= 0.25</h3> <p>Pandas can do this in a single function call via <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html#pandas.DataFrame.explode" rel="nofollow noreferrer"><code>df.explode</code></a>.</p> <pre><code>df.explode('column_x') column_a column_b col...
python|list|pandas|dataframe
8
20,296
58,986,593
np.poly1d: how to calculate R^2
<p>I am fitting my data to a linear regression. But I want to know how to calculate the R2 values. The following is the code I have so far.</p> <pre><code>total_csv= pd.read_csv('IgG1_sigma_biospin_neg.csv',header=0).iloc[:,:] x_values=(19,20,21,22) y_values=IgG1_sigma_biospin_neg.loc[0, ['19-', '20-', '21-', '22-']]....
<p>To the best of my knowledege, <code>np.polyfit</code> does not provide a coefficient of determination (R2).</p> <p>The residual that Richard mentioned in his answer is something different, named Sum of Squares Error (SSE). More info about it here: <a href="https://365datascience.com/tutorials/statistics-tutorials/su...
numpy|linear-regression
2
20,297
58,947,583
Bring the data from one table to another grouped by ID and Date
<p>I have a data frame which look like this:</p> <pre><code>ID Date Item Sales 1 1-Dec A 10 1 2-Dec B 15 1 3-Dec C 20 2 1-Dec A 20 2 2-Dec C 10 3 1-Dec A ...
<p>Idea is <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html" rel="nofollow noreferrer"><code>DataFrame.explode</code></a> (pandas 0.25+) rows in <code>df2</code> by splitted <code>Output</code> column, so possible <a href="http://pandas.pydata.org/pandas-docs/stable/refer...
python|pandas|dataframe|matrix|metadata
0
20,298
58,699,807
Pandas: Counting empty values in columns
<p>I have a pandas dataframe containing some info about purchases. It includes columns like "purchaseID", "purchaseDate", and "purchaseAmount". I want to know the number of missing values in each column, and different columns contain different types of datatypes like strings, numeric, booleans, etc. I tried something l...
<p>Try using <code>pd.read_json</code>. The problem could be your data frame with one row being the json file.</p> <pre><code>data = pd.read_json(r'purchases.json') print(data.isnull().sum()) print(data.isna().sum().sum()) </code></pre>
python|pandas|dataframe
0
20,299
56,105,404
Create dummy variable from list
<p>I have a pandas dataframe with a column named “Notes”. It has entries like the example below. I would like to create dummy variable columns based on a list:</p> <pre><code>Lst=[‘loan’,’Borrower’,’debts’] </code></pre> <p>That is I’d like to create a binary flag for each entry in the list if the string in the “No...
<p>Check with <code>str.findall</code> then <code>get_dummies</code></p> <pre><code>df.Note.str.findall('|'.join(Lst)).str[0].str.get_dummies() Out[639]: Borrower debts loan 0 0 0 1 1 1 0 0 2 0 1 0 yourdf=pd.concat([df,df.Note.str.findall('|'.join(Lst)).str[0].s...
python-3.x|pandas
1