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
361,500
49,846,207
Tensorflow Estimator - warm_start_from and model_dir
<p>When using <code>tf.estimator</code> with <code>warm_start_from</code> <strong>and</strong> <code>model_dir</code>, and both <code>warm_start_from</code> directory and <code>model_dir</code> directory contain valid checkpoints, which checkpoint will be actually restored?</p> <p>To give some context, my estimator co...
<p>I've had a similar issue, I've solved this by providing an initialization hook that is run when the session is started, and using <code>tf.estimator.train_and_evaluate</code> (though I can't take credit for this whole solution, as I saw something similar for another purpose elsewhere):</p> <pre><code>class InitHook...
tensorflow|tensorflow-estimator
3
361,501
49,864,176
Does `if` work only in combination with `else` in Series.apply(lambda x)?
<p>I'm getting a <code>SyntaxError</code> for:</p> <pre><code>housing['Lot Area'].apply(lambda x: x + 50000 if x &gt; 20000) </code></pre> <p>When I add <code>else</code>, the code runs fine:</p> <pre><code>housing['Lot Area'].apply(lambda x: x + 50000 if x &gt; 20000 else x) </code></pre> <p>Does <code>if</code> o...
<p>Base on your description , even <code>apply</code> is not need here</p> <pre><code>housing.loc[housing['Lot Area']&gt;20000,'Lot Area']+=50000 </code></pre> <p>Comment from Alex :</p> <p><strong><em>if the if statement resolves to False for a value, then apply() doesn't return and just lets the value in the Serie...
pandas
4
361,502
50,048,864
Pandas row value based on column value
<p>I have a dataframe that looks something like that:</p> <pre><code>A1 A2 A3 A4 B C D 0 2 9 0 9 7 2 7 6 7 3 6 8 4 3 7 4 9 2 1 1 </code></pre> <p>I want to create a new column, call it E, whose values come from columns A1, A2, A3, or A4 depending on the...
<p>We just need <code>lookup</code> (see <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.lookup.html" rel="nofollow noreferrer">documentation</a>)</p> <pre><code>df.lookup(df.index,df.columns[df.D-1]) Out[309]: array([2, 3, 3], dtype=int64) </code></pre> <p>After assign it back </p> ...
python|pandas
2
361,503
50,091,331
Sklearn Scaler output behavior
<p>I have a situation where I want to apply sklearn's StandardScaler object to one column of my dataframe. The code is below:</p> <pre><code>import pandas as pd from sklearn.preprocessing import StandardScaler df = pd.DataFrame([(1,2,3), (2,3,4), (3,4,5)], columns=['a','b','c']) scaler = StandardScaler().fit(df['c']....
<p>The custom is to instantiate the trasformer/estimator first and then to fit and transform. Here is what the output is with a couple of minor changes:</p> <pre><code>import pandas as pd from sklearn.preprocessing import StandardScaler df = pd.DataFrame([(1,2,3), (2,3,4), (3,4,5)], columns=['a','b','c']) scaler = S...
python|pandas|scikit-learn|data-processing
2
361,504
50,213,733
How to create np array random data on age vs time?
<p>How to create np array random data on age vs time?</p> <p>My aim is to create a scatter plot representing random data on age vs. time spent watching TV.</p> <pre><code>from pylab import randn X = randn(500) Y = randn(500) plt.scatter(X,Y) plt.show() </code></pre> <p>I want age between 18 and 50 and time between ...
<p>You can try :</p> <pre><code>import random import numpy as np age=np.array(random.sample(list(range(18,51)),10)) time=np.array(random.sample(list(range(0,24)),10)) </code></pre> <p><code>random.sample</code> takes a list of elements as first argument and the number of samples you want as the second argument. </p> ...
python|pandas|numpy|matplotlib
3
361,505
49,852,455
How to find the Null Space of a matrix in Python using numpy?
<p>As the title says, how can I find the null space of a matrix i.e. the <em>nontrivial</em> solution to the equation ax=0.</p> <p>I've tried to use <code>np.linalg.solve(a,b)</code>, which solves the equation ax=b. So setting <code>b</code> equal to an array of zeros with the same dimensions as matrix <code>a</code>...
<p>From <a href="http://scipy-cookbook.readthedocs.io/items/RankNullspace.html" rel="nofollow noreferrer">SciPy Cookbook</a>:</p> <pre><code>import numpy as np from numpy.linalg import svd def nullspace(A, atol=1e-13, rtol=0): A = np.atleast_2d(A) u, s, vh = svd(A) tol = max(atol, rtol * s[0]) nnz = (...
python|numpy
3
361,506
50,039,500
Pandas to_csv to GzipFile in Python 3 not working
<p>Saving a Pandas dataframe to gzipped csv in memory works like this in Python 2.7 (Pandas 0.22.0):</p> <pre><code>from io import BytesIO import gzip import pandas as pd df = pd.DataFrame.from_dict({'a': ['a', 'b', 'c']}) s = BytesIO() f = gzip.GzipFile(fileobj=s, mode='wb', filename='file.csv') df.to_csv(f) s.seek(0...
<p>You can utilise <code>StringIO</code>:</p> <pre><code>from io import StringIO buf = StringIO() df.to_csv(buf) f = gzip.GzipFile(fileobj=s, mode='wb', filename='file.csv') f.write(buf.getvalue().encode()) f.flush() </code></pre> <p>Note also the added <code>f.flush()</code> - according to my experience without this...
python|pandas
1
361,507
49,797,450
Tensorflow feature_column expecting a different shape than input data
<p>I'm trying to implement a tensorflow <code>Estimator</code>, and getting a shape mismatch error I don't know how to debug. I think I may be misunderstanding how to specify the <code>tf.feature_column</code>'s shape. My intention is to create a model with 6010 inputs. Any suggestions would be appreciated.</p> <pre><...
<blockquote> <p>I'd still like to know why the above wasn't working, or how to debug though.</p> </blockquote> <p>The problem is with the tensor size produced from the <code>train_iterator.get_next()</code>. If the batch size is not specified, the iterator returns:</p> <pre><code>({'all_features': &lt;tf.Tensor 'It...
python|numpy|tensorflow|tensorflow-datasets|tensorflow-estimator
0
361,508
49,982,204
Pandas: how to sum by groupby value
<p>Using this: </p> <pre><code>ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'Kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2], 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]} df = pd.DataFrame(ip...
<p>I believe need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.xs.html" rel="nofollow noreferrer"><code>DataFrame.xs</code></a>:</p> <pre><code>print (df.xs(1, level=1)) Points Team Kings 1544 Riders 876 Royals 804 print (df.xs(2, level=1)) Po...
python|pandas|dataframe|pandas-groupby|multi-index
4
361,509
50,165,504
Set up MultiIndex DataFrame from multiple CSV files in DateTime series
<p>I have a list of time series price data in CSV format that is read as follows:</p> <pre><code>asxList = ['ANZ', 'NAB', 'WBC'] for asxCode in asxList: ohlcData = pd.DataFrame.from_csv(asxCode+'.CSV', header=0) </code></pre> <p>Example output:</p> <p><a href="https://i.stack.imgur.com/PfGyi.png" rel="nofollow ...
<p>Create a list of dataframes, add a <code>code</code> column to each dataframe:</p> <pre><code>dfs = [] for asxCode in asxList: df = pd.DataFrame.from_csv(asxCode+'.CSV', header=0) df['code'] = asxCode dfs.append(df) </code></pre> <p>Concatenate the dataframes, add the <code>code</code> column to the in...
python|pandas|multi-index
4
361,510
50,017,061
python change random time index to second base index
<p>I have quite some difficulties formulating the question hence please find an example below: I have:</p> <pre><code>2017-11-23 16:30:52+01:00 20 2017-11-23 16:30:58+01:00 30 2017-11-23 16:31:30+01:00 25 </code></pre> <p>I would like to have:</p> <pre><code>2017-11-23 16:30:52+01:00 20 2017-11-23 16:30:53+01:0...
<p>So you need to use <code>fillna</code> after <code>resample</code></p> <pre><code>df=df.resample('1s').fillna(method = 'pad') </code></pre> <p><code>resample</code> will create rows with 1s separation on pandas datetime index, and will fill values for the indexes it is available. You need to fill it for rest of th...
python|pandas
0
361,511
50,120,037
Getting error loading dependencies in chrome browser, when running plotly dash code
<p>I am new to plotly dash and trying to run this googled code to understand the output. When i run the below code in windows cmd prompt, the execution returns the URL-- <a href="http://127.0.0.1:3003" rel="nofollow noreferrer">http://127.0.0.1:3003</a> On pasting the above in Chrome browser, error loading dependencies...
<p>Not sure about this question specifically. But I ended up here because I got the same exact error because I renamed a div id, but I was still trying to get the old id as a State input in one of my callback functions.</p> <p>Just leaving it here in case it helps someone. </p>
python|pandas|plotly|plotly-dash
4
361,512
49,834,632
Transfer Learning - Merging my top layers with pretrained model drops accuracy to 0%
<p>My goal here is to attach my top layers to a pre-trained model like VGG19 and make some prediction using the merged model. The merged model has 0 accuracy. Need a bit of help.</p> <h1>my own top layers</h1> <pre><code>from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D from keras.layers import Dr...
<p>I think, from how you do it, you are stacking two VGG19 models, but the first one only some layers of the VGG19.</p> <p>That is not the best way to improve your accuracy. First, it will just increase the parameters of the network because you combine the models sequentially, the computation will be so heavy. Second, ...
python|tensorflow|deep-learning|keras|transfer-learning
1
361,513
49,932,980
Tensorflow.js/Keras LTSM with multiple sequences?
<p>I am trying to train a lstm model with Tensorflow.js using the Layers API that is built on Keras. I am having trouble getting the correct predictions back. I am trying to feed the model an array of NBA player's career production scores per season (ex: [20, 30, 40, 55, 60, 55, 33, 23]). I want to feed it an array of ...
<p>Mike. You should to normalize(convert) every input data. Neural Networks can understand numbers that are normalized to the range of their activation function. For example I will use "sigmoid":</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-co...
machine-learning|keras|lstm|rnn|tensorflow.js
1
361,514
49,807,720
How to remove nan value from a list
<p>I have a list whose name is Ave. Ave[0] is shown below:</p> <pre><code>[array([ nan]), array([ 0.03030303]), array([ 0.025]), array([ 0.03546099]), array([ 0.02877698]), array([ 0.05343511]), array([ nan]), array([ nan])] </code></pre> <p>I need to remove the nan value from each list in the Ave. my code wor...
<p>If I understand your problem correctly, this is one way.</p> <p>Just note that holding a list of arrays is inefficient. It is advisable, where possible, to hold your data in a single <code>numpy</code> array.</p> <pre><code>from numpy import array, isnan, nan Ave = [array([ nan]), array([ 0.03030303]), ...
python|list|numpy|for-loop|nan
1
361,515
50,062,201
Boxplot in pandas with confidence intervals and bootstrap returns exception - Reproducible example with iris dataset
<p>I tried to plot a boxplot with confidence intervals but I got an exception.</p> <pre><code>from sklearn import datasets iris = datasets.load_iris() iris = iris.data iris = pd.DataFrame(iris) iris.columns = ['a', 'b', 'c', 'd'] iris.boxplot(column='a', figsize=(15,20), showmeans = True, patch_artist = True, con...
<p>You need to specify the confidence intervals as a list of tuples corresponding to the features you are plotting. In your case, you are plotting only column 'a', therefore you need to specify a list with one tuple:</p> <pre><code>iris.boxplot(column='a', figsize=(15,20), notch=True, showmeans = True, \ ...
python|pandas|matplotlib|boxplot
1
361,516
49,919,025
pandas get the value and the location from another DataFrame and make a series
<p>Say, I have a DataFrame (dfrtn)</p> <pre><code> A B C D E F 0 33 34 35 36 37 38 1 39 40 41 42 43 44 2 45 46 47 48 49 50 3 51 52 53 54 55 56 4 57 58 59 60 61 62 </code></pre> <p>then, I make another DataFrame (dfrtn2) from dfrtn (dfrtn2 = dfrt...
<p>Use <code>DataFrame</code> contructor with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmin.html" rel="nofollow noreferrer"><code>idxmin</code></a> and <code>min</code> per rows:</p> <pre><code>df1 = pd.DataFrame({'MinCol': dfrtn2.idxmin(axis=1), 'Minimum': ...
python|pandas|numpy
1
361,517
50,112,729
Keras multi gpu model tries to allocate model in non existant device CPU:1
<p>I am trying to train a model in keras. I have 4 gpus and 1 cpu. When I start training keras/tensorflow tries to use cpu 1 device which is non existant. I am running keras 2.1.6 and the latest tensorflow release was built from source. </p> <pre class="lang-py prettyprint-override"><code>with tf.device("/cpu:0"): ...
<p>There was an issue with my backend(tensorflow) installation. </p>
tensorflow|keras
0
361,518
50,080,829
how to improve the performance of the CNN model (Machine Learning - Deep Learning)
<p>I am trying to train a model based on CNN, </p> <p>Training data is the image of lunar lander, but the performance of model is not good, the accuracy is about 45%, I try to add more layer to improve it, but it still doesn't work well, could any one provide some ideas about how to improve it. Label: up down left rig...
<p>I would experiment a lower dropout rate. Dropouts are used to prevent overfitting. It looks like your model isn't even fitting in the first place. </p>
tensorflow|machine-learning|deep-learning|keras|convolutional-neural-network
0
361,519
49,992,607
Replace last 2 numeric values in pandas data frame by row with NAN's
<p>The last 2 real numbers in each row of my data were measured with error. I want to replace them with np.NAN. The number of real numbers differs by row (i.e., each row already has some NAN's at differing amount). Column headers indicate measurement number, index was a experimental trial.Values in a cell equal a measu...
<p>Method #1 would be simply to shift everything over by 2 and keep the values which remain non-null:</p> <pre><code>In [61]: df.where(df.shift(-2, axis=1).notnull()) Out[61]: 0 1 2 3 4 5 6 0 1.0 2.0 3.0 4.0 NaN NaN NaN 1 2.0 2.0 3.0 NaN NaN NaN NaN 2 4.0 4.0 NaN NaN NaN NaN NaN </code...
python-3.x|pandas|numpy|dataframe
3
361,520
50,064,422
How to filter a numpy array by a regex?
<p>I am attempting to filter a numpy array by a regex in Python, however, I am running into an error where not all expected values are being matched.</p> <p>The data I'm working with is a large numpy array of strings of various lengths. Preemptive to the regex filter, I've created an index of all strings of a specific...
<p><strong>EDIT</strong> The method form of <code>search</code> doesn't take a <code>flags</code> argument, so the <code>IGNORECASE</code> (which happens to equal <code>2</code>) is interpreted as <code>pos</code>.</p> <p>Move it to the <code>compile</code> call and the error goes away:</p> <pre><code># Remove all in...
python|arrays|numpy
2
361,521
49,869,185
Python 3 shows UnicodeDecodeError when trying to print dataset with numpy
<p>I am just getting started with numpy. So, just to play around I downloaded <a href="https://www.kaggle.com/thec03u5/fifa-18-demo-player-dataset/data" rel="nofollow noreferrer">FIFA 18 Complete Player Dataset</a>. Then, I tried to run a simple code : </p> <blockquote> <p><strong>import numpy as np<br/> np_fifa =...
<p>Thanks to <a href="https://stackoverflow.com/users/3700867/cr3">Cr3</a> for helping me through comments. At last this code worked for me:</p> <blockquote> <p>import numpy as np<br /> fifa = np.genfromtxt('Datasets/CompleteDataset.csv', delimiter=',', encoding='utf-8', dtype=str)<br /> np_fifa = np.array(fifa)...
python|python-3.x|numpy|dataset
1
361,522
49,946,758
Pandas .to_csv(fileName, quoting=csv.QUOTE_NONE ERRORTypeError: to_csv() got an unexpected keyword argument 'quoting'
<p>Attempting to write a data frame to csv using pandas and remove quotes produced by a concatenated value. The interpreter is not accepting the argument quoting.</p> <p>ERROR</p> <blockquote> <p>TypeError: to_csv() got an unexpected keyword argument 'quoting'</p> </blockquote> <p>CODE</p> <p>concatenation produc...
<p><code>stack</code> on a simple index (i.e. not a MultiIndex) produces a Series, not a DataFrame. If that's the case here, as it appears to be, what you're calling is the Series <code>to_csv</code> not the DataFrame one, which does not have the <code>quoting</code> parameter.</p> <p>If you need to have a DataFrame (...
python|pandas|quoting
2
361,523
49,975,549
Large output from tf.Session() after installing Tensorflow with GPU support. Did I do something wrong?
<p>I am just starting to play around with tensorflow (GPU) on Ubuntu 16.04 and have followed the installation instructions here <a href="https://www.tensorflow.org/install/install_linux" rel="nofollow noreferrer">Installing Tensorflow</a>. After running the example, where you create the session (<code>sess = tf.Session...
<p>No you have done nothing wrong, this is expected behavior and often times actually really helpful when running TensorFlow code on a bunch of different systems, especially cluster nodes. </p> <p>If you are just annoyed by this while testing on your local system you can supress the debugging output by doing something...
python|tensorflow
1
361,524
64,077,041
Delete empty dataframes from a list with dataframes
<p>This is a list of dataframes.</p> <pre><code>import pandas as pd data=[pd.DataFrame([1,2,3],columns=['a']),pd.DataFrame([]),pd.DataFrame([]), pd.DataFrame([3,4,5,6,7],columns=['a'])] </code></pre> <p>I am trying to delete the empty dataframes from the above list that contains dataframes.</p> <p>Here is what I have t...
<p>try this:</p> <pre><code>import pandas as pd data = [pd.DataFrame([1, 2, 3], columns=['a']), pd.DataFrame([]), pd.DataFrame([]), pd.DataFrame([3, 4, 5, 6, 7], columns=['a'])] for i in range(len(data)-1, 0, -1): if data[i].empty: del data[i] print(data) </code></pre> <p>The problem with...
python|pandas|dataframe|loops
2
361,525
64,024,851
Nest 2 fields of a pandas dataframe with new name into json
<p>I have this dataframe from which I want to build a json with the <code>id</code> and <code>name</code> fields nested</p> <pre><code>id name pk model 1 n1 100 mod1 2 n2 101 mod1 3 n3 102 mod1 4 n4 103 mod1 5 n5 104 mod1 6 n6 105 mod1 </code></pre> <p>What I want:</p> <pre><code...
<p>Convert all columns without <code>model</code> and <code>pk</code> to dictionary to column <code>fields</code>:</p> <pre><code>authordf['fields'] = authordf.drop([&quot;model&quot;, &quot;pk&quot;], 1).apply(lambda x: x.to_dict(), 1) print (authordf) id name pk model fields 0 1 n1 100 mo...
json|pandas|nested
1
361,526
64,035,727
Grouping and concatenating columns with multiple results
<p>I need help performing this grouping, I wish to concatenate the columns with multiple results and sum columns numeric values</p> <p><a href="https://i.stack.imgur.com/c3PXX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c3PXX.png" alt="enter image description here" /></a></p> <p>I have tried this...
<p>Use <code>agg</code> with dictionary</p> <pre><code>winback.groupby('day').agg({'smoker': ','.join, 'sum': 'sum'}) </code></pre>
python|pandas|dataframe
1
361,527
63,831,410
How do I save a tensorflow estimator created with tf.keras.estimator.model_to_estimator?
<p>How do I save a tensorflow estimator created with tf.keras.estimator.model_to_estimator?</p> <p>The below is where I am at currently.</p> <p>The keras model:</p> <pre><code> def create_model(self): model = tf.keras.models.Sequential([ tf.keras.layers.Reshape((self.num_features,), input_shape=(...
<p>I'll answer my own question in case someone else is struggling with this. Note that I haven't got this working on a local dev environment as <code>tf.estimator</code> seems to have an issue writing to paths on my local windows environment, but it does work in SageMaker.</p> <p>The code that works on SageMaker is bel...
python|tensorflow|keras
0
361,528
63,896,215
Conversion of dataframe to required dictionary format
<p>I am trying to convert the below data frame to a dictionary</p> <p>Dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame({'a':['A','A','B','B','B','C'], 'b':[1,2,5,5,4,6], 'c':[4,3,5,5,5,3], 'd':[3,4,5,5,7,8]}) print(df) </code></pre> <p>Sample Dataframe:</p> <pre><code> a b c d 0 A 1 4 3 1 A 2 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>DataFrame.groupby</code></a> with custom lambda function for convert values to dictionaries by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_d...
python-3.x|pandas|dataframe|dictionary|pandas-groupby
0
361,529
63,748,736
how to deduplicate values that have not changed since the first time value was established
<p>When using the pandas df.duplicated function it will flag anything that duplicates. I am trying to only flag up duplicates that have not changed since the last time they changed. To demonstrate the desired outcome I have a status column that shows keep or remove. Ideally the duplicated function would drop anythin...
<p>try this</p> <pre><code>df['is_dup'] = df.groupby(['entity_id','attribute'])['value'].diff() == 0 </code></pre> <p>check if it works:</p> <pre><code>pd.crosstab(df['is_dup'],df['status']) # status keep remove # is_dup # False 24 0 # True 0 12 </code></pre>
python|pandas|dataframe|pandas-groupby
1
361,530
63,822,981
Python Pandas: Compute Consecutive Window Count of Positive Numbers
<p>Say I have a dataframe with:</p> <pre><code>+------+-------+--------+---------------------+ | Col1 | Col2 | Col3 | Col4 | +------+-------+--------+---------------------+ | A | 0.532 | -0.234 | 2020-01-01 05:00:00 | | B | 0.242 | 0.224 | 2020-01-01 06:00:00 | | A | 0.152 | -0.753 | 2020-01...
<p>IIUC you just need to count backwards:</p> <pre><code>s = df[&quot;Col3&quot;][::-1] df[&quot;New&quot;] = s.groupby((s&lt;0).cumsum()).apply(lambda d: (d&gt;=0).cumsum()) print (df) Col1 Col2 Col3 Col4 New 0 A 0.532 -0.234 2020-01-01 05:00:00 0 1 B 0.242 0.224 2020-01-01 0...
python|pandas|dataframe|count
0
361,531
63,805,083
Generate unique ID based on data duplicity
<p>So I've got a dataframe like so,</p> <pre><code>ID,SUBJECT_CODE,SUBJECT_GROUP,CLASS_ID,CAMPUS_ID 1,g1,VP2K,c1,r1 2,g1,VP2K,c1,r1 3,g1,VP3K,c2,r2 4,g1,VP3K,c2,r2 5,g1,VP3K,c3,r3 </code></pre> <p>I have to maintain a column <code>CORR_ID</code> with values being a unique UUID (<code>uuid.uuid4().int</code>) for all un...
<p>For me was problem save big integers to pandas column, because <code>OverflowError</code> error. Possible solution is convert values to <code>Decimal</code>:</p> <pre><code>from decimal import Decimal f = lambda x: Decimal(uuid.uuid4().int) df['CORR_ID'] = df.groupby(['CLASS_ID','CAMPUS_ID'])['CLASS_ID'].transform(...
pandas|python-2.7
0
361,532
64,005,151
Filter newest x % per group in timeseries and compute aggregates
<p>What's the best way to filter a timeseries per group, taking x % of most recent measurements and then compute multiple aggregates over the entire filtered dataset? I'm currently using the following code, but is this correct or is there a better way to achieve this goal?</p> <pre><code>fraction = 0.7 def df_by_ts_he...
<p>The following appears to achieve the stated goal</p> <pre><code>df = df.groupby('timestamp').\ apply(df_by_ts_head_fraction).\ reset_index(drop=True).\ loc[:, ['timestamp', 'measurement']].\ groupby('timestamp').\ aggregate(['mean', 'median', 'size']) </code></pre>
python|pandas
0
361,533
63,920,783
Dataframes update?
<p>I have the following two dataframes :</p> <pre><code>df = pd.DataFrame({'ROU': ['A', 'A', 'A'],'Pre': ['3.0.0.0', '4.0.0.0', '3.0.0.0'],'A_s': ['1', '2', '1000']}) </code></pre> <pre><code>new_df = pd.DataFrame({'ROU': ['A', 'A'],'Pre': ['3.0.0.0','4.0.0.0'],'A_s': ['5', '40']}) </code></pre> <p>Is it possible to mo...
<p>If you cannot control values in 3rd column this solution should be enough and work properly:</p> <pre class="lang-py prettyprint-override"><code>df['A_s'][-len(new_df['A_s']):] = new_df['A_s'][::-1] </code></pre> <p>In the case <code>[::-1]</code> is probably completely optional.</p>
python|pandas|dataframe
0
361,534
63,906,839
Is it necessary to call Dataset.repeat()?
<p>In <a href="https://www.tensorflow.org/tutorials/images/classification" rel="nofollow noreferrer">tensorflow tutorial</a>, I saw dataset is just shuffled like</p> <pre><code>AUTOTUNE = tf.data.experimental.AUTOTUNE train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE) </code></pre> <p>But I also s...
<p>So, based on the <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#repeat" rel="nofollow noreferrer">documentation</a>, repeat determines how many times the samples can be repeated in the given dataset.</p> <pre class="lang-py prettyprint-override"><code>dataset = tf.data.Dataset.from_tensor_slices...
tensorflow
1
361,535
63,893,269
Beginner Python: Panda Groupby function (Aggregating columns)
<p>I am trying to use the panda groupby/aggregate function to show the total leave hours (combination of VacationHours &amp; SickLeaveHours) grouped by ManagerID &amp; JobTitle. I am unsure how to show one total column that aggregates VacationHours+SickLeaveHours.</p> <pre><code>excel = pd.read_excel('Employees.xls','...
<p>Adding the total</p> <pre><code>out = excel.groupby(['ManagerID','JobTitle']).agg(({'VacationHours':np.sum, 'SickLeaveHours':np.sum})) out['total'] = out.sum(axis=1) </code></pre>
python|pandas|dataframe|group-by
0
361,536
63,833,702
Regex expression: Expression for Extracting Date is not working with Series object throws an error
<p>I'm trying to extract date from text data. The expression is valid and works fine when I checked in regex101 website. But when applied to the data it throws an error &quot;<strong>ValueError: pattern contains no capture groups</strong>&quot;. My sample text is [&quot;Mar-20-2009&quot;, &quot;Mar 20, 2009&quot;, &quo...
<p>All of your parenthesized expressions are non-capture groups (?:) so the error message is correct. If you want to capture an expression, don't use the ?: just put it in parenthesis. As is, the pattern will match, but no groups will be captured.</p>
python-3.x|regex|pandas|regex-group
1
361,537
63,796,320
Add N empty rows between each value
<p>I have a df which sums every 5 rows in 'Costs' and puts into 'Sum'. Now I would like to add 4 empty rows between each value in 'Sum' to have it at the start of each 5 rows. What would be the most efficient and straight forward way to achieve this?</p> <p>Input:</p> <pre><code> Costs | Sum -------|------- 10...
<p>IIUC ,you can repeat the Sum column and check for the first of the duplicated value , then assign:</p> <pre><code>n=5 u = df['Sum'].replace('',np.nan).dropna().repeat(n) df['New_sum'] = np.where(~u.index.duplicated(),u,'') </code></pre> <hr /> <pre><code>print(df) Costs Sum New_sum 0 1000 10000 10000 1...
python|pandas
2
361,538
63,825,333
How to create a dataframe, which contain 2D list under a key?
<p>I have created a dictionary, which contains following data</p> <p>x = {'a': [[1,2,3], [4,5,6]], 'b': [[7,8,9],[10,11,12]]}</p> <p>I want to create a dataframe that look something like this,</p> <p><a href="https://i.stack.imgur.com/RKLLC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RKLLC.png" ...
<p>Create DataFrames in list comprehension and join togeher by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a>:</p> <pre><code>df = pd.concat({k: pd.DataFrame(v).T for k, v in x.items()}, axis=1) print(df) a b 0 1 0...
python|pandas|dataframe
3
361,539
64,004,805
how to insert column data as a list of list in pandas
<p>I have a list of list like</p> <pre><code>a = [[1,2],[2,3]] </code></pre> <p>my dataframe is like this:</p> <pre><code> name 0 John 1 Mike </code></pre> <p>i want to insert this list of lists to a new column called 'Score' like this:</p> <pre><code> name Score 0 John [[1,2],[2,...
<p>Try this</p> <pre><code>a = [[1,2],[2,3]] df = pd.DataFrame({'name': ['John', 'Mike']}) df['score'] = [a for _ in range(df.shape[0])] </code></pre> <p>Output:</p> <pre><code> name score 0 John [[1, 2], [2, 3]] 1 Mike [[1, 2], [2, 3]] </code></pre>
python|pandas
1
361,540
63,822,830
neural network input shape
<p>consider if my corpus has 5 sentences, where maximum sentence size is 10 words.</p> <p>Hence, will the embedding matrix be 5x10.</p> <p>And what will the input shape of the input layer of a neural network, or how the data will be given as input to neural network.</p>
<p>The first layer in your network will be the embedding one.</p> <p>The dimension <strong>of the first parameter of your input</strong> will be a number &lt;= 50 (5 sentences * 10 words). It can be smaller considering the fact that all the words in your dataset may not be unique.</p> <p>Therefore, the input layer wil...
tensorflow|deep-learning|neural-network|nlp
0
361,541
64,041,480
Creating new columns to assign value whether a column contains a word
<p>I have a dataset which contains multiple columns. I need to look if a column contains some words:</p> <ul> <li>if it contains the word &quot;Donald&quot; then create a new column called &quot;Donald&quot; and assign 1 to all the rows which contain this word, otherwise 0;</li> <li>if it contains both the word &quot;D...
<p>Add parameter <code>case=False</code> and for <code>1,0</code> for <code>True, False</code> using <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.view.html" rel="nofollow noreferrer"><code>Series.view</code></a>:</p> <pre><code>m1 = df_low['Text'].str.contains(&quot;donald&quot;, cas...
python|pandas
0
361,542
64,007,735
How to use regex in string partition using python?
<p>I have a string like as shown below from a pandas data frame column</p> <pre><code>string = &quot;insulin MixTARD 30/70 - inJECTable 20 unit(s) SC (SubCutaneous) - Hypoglycaemia Protocol if Blood Glucose Level (mmol) &lt; 4 - Call Doctor if Blood Glucose Level (mmol) &gt; 22&quot; </code></pre> <p...
<p>You could use <code>re.sub</code> here for a one-liner solution:</p> <pre><code>string = &quot;insulin MixTARD 30/70 - inJECTable 20 unit(s) SC (SubCutaneous) - Hypoglycaemia Protocol if Blood Glucose Level (mmol) &lt; 4 - Call Doctor if Blood Glucose Level (mmol) &gt; 22&quot; output = re.sub(r'^...
python|python-3.x|regex|pandas|dataframe
1
361,543
63,843,493
Split and Recombine Tensorflow Dataset
<p>I currently have a tensorflow <code>Dataset</code> with a number of batches (Number of batches would be variable, but divisible by 4). I want to take out every 4th batch to use as testing and the rest as training, but I have yet to encounter an elegant solution. A simplified visual example of desired results:</p> <p...
<p>The solution can be achieved through a combination of <code>enumerate()</code>, <code>filter()</code>, and <code>map()</code>, similar to the answer provided <a href="https://stackoverflow.com/a/59671472/8479618">here</a>.</p> <p>Toy example:</p> <pre><code>list( Dataset.from_tensor_slices(np.arange(12)) .ba...
python|tensorflow|keras|tensorflow-datasets
1
361,544
63,790,632
Translating float index interpolation from MATLAB to Python
<p>For example, I have a index array</p> <pre><code>ax = [0, 0.2, 2] #start from index 0: python </code></pre> <p>and matrix <code>I</code></p> <pre><code>I= 10 20 30 40 50 10 20 30 40 50 10 20 30 40 50 10 20 30 40 50 10 20 30 40 50 </code></pre> <p>In MATLAB...
<p>It seems that you over-corrected yourself by passing from MATLAB to Python, as shown by your first code excerpt.</p> <pre><code>ax = [0, 0.2, 2] #start from index 0: python </code></pre> <p>In numpy logic this sequence does not represents the indexes but the coordinate for the function to interpolate. Since you alre...
python|matlab|numpy|interpolation
1
361,545
63,899,988
0-dimension ndarray created with xarray and enumerate: bug or feature?
<p>Please find below a minimum example of how I iterate through time in xarray.</p> <pre><code>ds = xr.Dataset({'time': pd.date_range(start='1/1/2018', periods=8)}) for ii, date in enumerate(ds.time): nd = date.data </code></pre> <p><code>nd</code> is a <code>numpy.ndarray</code> but of size = 1; no shape: shape = ...
<p>The <code>nd</code> array as a 0d array is a feature; explained here: <a href="https://stackoverflow.com/a/49621796/3064736">https://stackoverflow.com/a/49621796/3064736</a>.</p> <p>There is a small bug given a recent pandas change such that <code>nd.item()</code> returns an int rather than a date on the most recent...
numpy-ndarray|python-xarray
0
361,546
64,036,014
Have only 1 record per date in a pandas dataframe
<p>Background: In mplfinance, I want to be able to plot multiple trade markers in the same bar. Currently to my understanding you can add only 1 (or 1 buy and 1 sell) to the same bar. I cannot have 2 more trades on the same side in the same bar unless I create another series.</p> <p>Here is an example:</p> <pre><code>d...
<p>The trick is to add an incremental counter to each unique datetime. Such that if a datetime is encountered more than once, this counter increases.</p> <p>To do this, we groupby tradedate, and get a cumulative count of the number of duplicate tradedates there are for a given tradedate. I then add 1 to this value so o...
python|pandas|dataframe
4
361,547
64,158,898
What does Keras Tokenizer num_words specify?
<p>Given this piece of code:</p> <pre><code>from tensorflow.keras.preprocessing.text import Tokenizer sentences = [ 'i love my dog', 'I, love my cat', 'You love my dog!' ] tokenizer = Tokenizer(num_words = 1) tokenizer.fit_on_texts(sentences) word_index = tokenizer.word_index print(word_index) </code></pr...
<p>word_index it's simply a mapping of words to ids for the entire text corpus passed whatever the num_words is</p> <p>the difference is evident in the usage. for example, if we call texts_to_sequences</p> <pre><code>sentences = [ 'i love my dog', 'I, love my cat', 'You love my dog!' ] tokenizer = Tokenize...
python|tensorflow|machine-learning|keras|nlp
8
361,548
64,171,961
Unable to create pandas dataframe with particular number of class label
<p>Is it possible to create a random pandas dataframe with 1500 rows to have class label 0 and 500 rows to have class label as 1.</p> <p>It should be like</p> <pre><code>feature_1 class_label sdfdsfsdfd 0 kjdkfkjdsf 0 jkkjhjknn 1 dfsfgdsfd 0 gfdgdfsdd 1 </code></pre> <p>The values of feature_1 colu...
<p>We can use numpy here, and draw random samples from a <code>range</code> of the length of the column using <a href="https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html" rel="nofollow noreferrer"><code>np.random.choice</code></a>:</p> <pre><code>a = np.zeros(2000, dtype='int') a[np.random...
python|pandas|dataframe|machine-learning
2
361,549
63,839,519
Accuracy drops in Tensorflow-Onnx-Tensorrt
<p>I have a tensorflow trained model and tested at tensorflow with accuracy achieved 95%.</p> <p>Tensorflow model is converted to ONNX and converted to TensorRT. TensorRT engine runs with 16-bit precision. In TensorRT, accuracy drops to 75%. Even with kTF32, accuracy is still 75%. Tested same images for both tests and ...
<p>Now I found the issue. Tensorflow did normalization to input image by multiplying 1/255.0. But in tensorrt normalization, it is 1- x/255.0. That is the issue. Now I have same accuracy.</p>
tensorflow|onnx|tensorrt
0
361,550
63,788,298
Boolean index with Numba with strings and datetime64
<p>I am trying to convert a function that generate a Boolean index based on a date and a name to work with Numba but I have an error.</p> <p>My project start with a Dataframe TS_Flujos with a structure as follow.</p> <pre><code>Fund name, Date, Var Commitment Cash flow Fund 1 Date 1 100 -20 Fund 1 Date...
<p>Given the way that you have structured you're code, you won't be gaining any performance by using Numba. You're using the decorator on a function that is already vectorized, and will perform fast. What would make sense is to try and speed up the main loop, not just <code>CapComp_MO</code>.</p> <p>In relation to the ...
python|numpy|indexing|boolean|numba
0
361,551
63,875,311
How to read in multiple files as separate dataframes and perform calculations on a column?
<p>I am calculating a single stock return as follow:</p> <pre><code>data = pd.read_csv(r'**file**.csv') data.index = data.Date data['Return %'] = data['AAPL'].pct_change(-1)*100 data </code></pre> <p>out put:</p> <pre><code> Date AAPL Return % Data 2020-09-11 2020-09-11 56.00 0.000000 2020-09-1...
<ul> <li>I think the best option for your data is to read the files into a dictionary of dataframes. <ul> <li>Use <code>pathlib</code> and <code>.glob</code> to create a list of all the files</li> <li>Use a dict comprehension to create the dict of dataframes.</li> </ul> </li> <li>The dictionary can be iterated over in ...
python|pandas|loops|report
1
361,552
63,853,432
Pandas date_range method
<p>I'd like to create a time series of dates using business day frequency beginning on August 1,2020 (not a b.d.) until August 31, 2020. I tried the following code but received an unexpected result.</p> <pre><code>In [1]: Import pandas as pd In [2]: pd.date_range(start = '01-08-2020', end = '31-08-2020',freq='B') Out...
<ul> <li>With <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html" rel="nofollow noreferrer"><code>pandas.date_range</code></a>, the expected format for <code>start</code> and <code>end</code>, is <code>datetime</code> like.</li> <li>With your current implementation, I get a Datet...
python|pandas
1
361,553
63,758,815
'Passing list-likes to .loc or [] with any missing labels is no longer supported, see
<p>How to fix the error:</p> <pre><code>KeyError: 'Passing list-likes to .loc or [] with any missing labels is no longer supported, see https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#deprecate-loc-reindex-listlike' </code></pre> <p>I just want to get the locations of the dataframe, that are in ...
<p>You might try something like this:</p> <p><code>result = df.loc[df.index.intersection(ix)]</code></p>
python|pandas|dataframe|datetime|error-handling
6
361,554
63,996,218
How to specify different layer sizes in Pytorch LSTM/GRU/RNN
<p>so I know how to work with LSTMs in general with Pytorch. But it bugs me, that you can only specify ONE hidden_size for all your layers in the LSTM. Like this:</p> <pre class="lang-py prettyprint-override"><code>lstm = nn.LSTM(input_size=26, hidden_size=128, num_layers=3, dropout=dropout_chance, batch_first=True) </...
<p>Actually, it depends on the shape of your input and you can see <a href="https://discuss.pytorch.org/t/how-to-decide-input-and-hidden-layer-dimension-to-torch-nn-rnn/31533" rel="nofollow noreferrer">How to decide input and hidden layer dimension to torch.nn.RNN?</a>. Also, you have to understand what is the input an...
machine-learning|pytorch|lstm|recurrent-neural-network
1
361,555
64,130,293
custom loss function in Keras with masking array as input
<p>I am trying to train an Autoencoder with a custom loss function shown below. The input, missing_matrix, is an n x m array of 1s and 0s corresponding to the n x m features array. I need to do an element by element multiplication of the missing_array with y_pred, which should be a reconstruction of the input features...
<p>The problem is that <code>y_true</code> and <code>y_pred</code> are in batches while the mask is passed one-shot. One simple solution to automatically split your data into equal batches is using <code>model.add_loss()</code>.</p> <p>Below I reproduced a dummy example with an autoencoder and a custom masking loss. Th...
python|tensorflow|machine-learning|keras|deep-learning
4
361,556
64,073,087
Calculating max of a specific column for a group in Pandas
<p>I currently have a dataframe that looks something like this:</p> <pre><code>Postal Code Risk Category % of Restaurants Low 15 11111 Med 60 High 25 ...
<p>Group by <code>Postal Code</code> and get the <code>% of Restaurants</code> where <code>Risk Category</code> is 'High'. Then merge the resulting dataframe on <code>Postel Code</code></p> <pre><code>df.merge( df.groupby('Postal Code') .apply(lambda x: x['% of Restaurants'][x['Risk Category'].eq('High')])....
pandas|dataframe
0
361,557
63,937,592
Joining/merging multiple dataframes
<p>I have 4 dataframe objects with 1 row and X columns that I would want to join, here's a screenshot of them:</p> <p><a href="https://i.stack.imgur.com/obMQX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/obMQX.png" alt="" /></a></p> <p>I would want them to become one big row.</p> <p>Thanks for any...
<p>You could use concatenate in dataframe as below,</p> <pre><code>df1 = pd.DataFrame(columns=list('ABC')) df1.loc[0] = [1,1.23,'Hello'] df2 = pd.DataFrame(columns=list('DEF')) df2.loc[0] = [2,2.23,'Hello1'] df3 = pd.DataFrame(columns=list('GHI')) df3.loc[0] = [3,3.23,'Hello3'] df4 = pd.DataFrame(columns=list('JKL')...
python|pandas|join|merge|append
0
361,558
63,865,668
How do you convert TD Ameritrade's API time stamp to pandas datetime?
<p>I am trying to use a pandas dataframe to create a time series visualization from stock price data I pulled from TD Ameritrade's API. In order to do this, I've been trying to convert the timestamps in the <code>datetime</code> column of my dataframe to datetime objects. This way, I can set datetime column as the new ...
<h2>Problem</h2> <p>Default time unit in <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html?highlight=to_datetime" rel="nofollow noreferrer">pd.to_datetime</a> is in nanosecond (ns) but your <code>datetime</code> column has timestamps in millisecond (ms).</p> <h2>Solution</h2> <...
python|pandas|dataframe|datetime|time-series
4
361,559
63,787,513
How to link images pr file in Google Colab
<p>I failed to show the image, <strong>below the code,</strong></p> <pre><code>import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import cv2 import os from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.preprocessing import image from tensorflow.keras.optimi...
<p>You can import your images first in google colab then assign it to your img variable.</p> <pre><code># you can run this in first cell import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import cv2 import os from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.ker...
python|tensorflow|keras|conv-neural-network
2
361,560
64,071,846
Making Pandas dataframe global and modiying the global dataframe
<p>From a menu I am calling a function that loads csv file as Pandas dataframe. I want to have the dataframe accessible and changeable from another functions. Other functions do things like, drop na etc.</p> <p>How do I ensure that I am accessing and changing the dataframe in <code>global df</code>?</p>
<p>I don't have enough reputations to write a comment guiding you to existing solutions for your questions, so here's an answer in case you still haven't found the solution or for someone who stumbles upon this question looking for a solution.</p> <p>Also, it'd be better if you provide some code, so we can see what you...
python|pandas|dataframe
1
361,561
63,813,857
Is there a pandas function for get variables names in a column?
<p>I'm just thinking in a hypothetical dataframe (df) with around 50 columns and 30000 rows, and one hypothetical column like e.g: Toy = ['Ball','Doll','Horse',...,'Sheriff',etc]. Now I only have the name of the column (Toy) and I want to know what are the variables inside the column without duplicated values.</p> <p>I...
<p>You can use <code>unique()</code> function to list out all the unique values in your columns. In your case, to list out the unique values in the column name <em>toys</em> in the dataframe <em>df</em> the syntax would look like</p> <pre><code>df[&quot;toys&quot;].unique() </code></pre>
pandas
0
361,562
63,785,601
Code Optiomiztion - Converting List Of Values Into Columns
<p>I have a dataframe that has the user id in one column and a string consisting of comma-separated values of item ids for the items he possesses in the second column. I have to convert this into a resulting dataframe that has user ids as indices, and unique item ids as columns, with value 1 when that user has the item...
<p>Let us try <code>str.split</code> with <code>explode</code> then <code>crosstab</code></p> <pre><code>s = temp.assign(listofitemids=temp['listofitemids'].str.split(', ')).explode('listofitemids') s = pd.crosstab(s['userid'], s['listofitemids']).mask(lambda x : x.eq(0)) s Out[266]: listofitemids 10 20 30 40 us...
python|pandas|optimization|concat
1
361,563
63,987,616
Getting the class from index of Pandas
<p>I have two dataframes</p> <pre><code>df1=pd.DataFrame({'index':[1,2,3,4],'Name':['Andi','Boby','Charlie','Daniel'],'Occupation':['x','xxx','xxx','x']}) </code></pre> <p>and</p> <pre><code>df2=pd.DataFrame({'index':[1,2,3,4],'Occupation':['x','xxx','xxx','x'],'Class':[1,0,1,0]}) </code></pre> <p>Based on the index i ...
<p>Try this, Before merging add this line</p> <pre><code>df2.pop('Occupation') # this line needs to be added data1=df1.merge(df2,on='index', how='left') </code></pre> <p>If you have more than one such columns, try the below method</p> <pre><code>cols = ['Col1', 'Col2'] # Add required columns of df2 here data1=df1.merge...
python|python-3.x|pandas
0
361,564
63,922,764
Error trying to save new table to MySQL with sqlalchemy
<p>Hi does somebody has any troubleshooting ideas to solve this problem?</p> <p>I have a standard python-sql connection at my local machine:</p> <p><code>from sqlalchemy import create_engine</code></p> <p><code>engine = create_engine(&quot;mysql+pymysql://root:*******@localhost/my_DB&quot;)</code></p> <p><code>con = en...
<p><code>if_exists= 'replace'</code> option is drop the table before inserting new values. <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html" rel="nofollow noreferrer">API reference</a><br /> your code repeats drop and create same Table in the loop.<br /> If you want to re...
python|mysql|pandas|sqlalchemy
1
361,565
63,980,260
Join 2 identical pandas dataframe into multi level row key
<p>I have 2 dataframe with identical index and column. I need to join or concatenate them into one dataframe. The code to generate the data is as such:</p> <pre><code>import pandas as pd sites = pd.Index(['AAA', 'BBB','CCC', 'DDD'], name='SITELIST') vvv = pd.DataFrame({'KK':[1,2,3,4],'GG':[2,3,4,5], 'RR':[6,5,4,3]}, in...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.swaplevel.html" rel="nofollow noreferrer"><code>df.swaplevel</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_index.html" rel="nofollow noreferrer"><code>df.sort_i...
python|pandas|dataframe|concatenation|concat
3
361,566
63,803,033
Rearrange rows of a given numpy 2D array given a list with the permutations
<p>There's an incredibly simple way of permuting the <strong>columns</strong> of a 2d array with numpy like this:</p> <pre><code>array1 = np.array([[11, 22, 33, 44, 55], [66, 77, 88, 99, 100]]) print(&quot;Original array:&quot;) print(array1) permutation = [1,3,0,4,2] result = array1[:, permutati...
<p>As @Marat mentioned in the comments, you can do the same by similar advanced indexing that you described for columns:</p> <pre><code>array1 = np.array([[11, 22, 33, 44, 55], [66, 77, 88, 99, 100]]) permutation = [1,0] array1[permutation] #[[ 66 77 88 99 100] # [ 11 22 33 44 55]] </code></...
python|arrays|numpy|multidimensional-array
0
361,567
64,095,509
Reading each worksheet into a new dataframe
<p>I have more than 50 worksheets in an Excel file. My primary objective is to import the different columns into different dataframes. I can import the files and read all the names of the worksheets.</p> <pre><code>import pandas as pd df = pd.read_excel('Fileoffiles.xls') df.sheet_names # will give me names of all my s...
<p>You can try using &quot;eval&quot; to assign the i-th sheet to the i-th dataframe. The code would be something like:</p> <pre><code>xls = pd.ExcelFile('Fileoffiles.xls') for i in range(len(xls.sheet_names)): eval('df' + str(i) '= pd.read_excel(&quot;Fileoffiles.xls&quot;, sheetname=&quot;' + xls.sheet_names[i] +...
python|python-3.x|excel|pandas
1
361,568
64,152,588
Read a .gz file from Google Cloud storage via Python (Jupyter)
<p>I'm trying to read a .gz file from Google Cloud storage via Python on Jupyter notebook.</p> <p>I get error by the first code.</p> <blockquote> <p>TypeError: can't concat str to bytes</p> </blockquote> <pre><code>from google.cloud import storage import pandas as pd from io import StringIO client = storage.Client() b...
<p>This works for me for reading <code>json.gz</code> to a dataframe directly from GCS.</p> <pre class="lang-py prettyprint-override"><code>client = storage.Client() def gcs_read_json_gz(gcs_filepath, nrows=None): # Validate input path if not gcs_filepath.startswith(&quot;gs://&quot;) or not gcs_filepath....
python|pandas|google-cloud-storage
4
361,569
64,037,148
TypeError: Object of type 'Add' is not JSON serializable - Python Graph
<p>I am working on trying to create a tangent approximation of a function. However, trying to find a way to graph it on top of the graph. Both functions work, but when I graph the functions, I come up with the type error &quot;Object of type 'Add' is not JSON serializable&quot;</p> <pre><code>x = sp.Symbol(&quot;x&quot...
<p>The issue is related to your coefficients (<code>f.subs(x,2).subs(y,2)</code>, <code>fx.subs(x,2).subs(y,2)</code>, and <code>fy.subs(x,2).subs(y,2)</code>). The coefficients are of type <code>&lt;class 'sympy.core.numbers.Float'&gt;</code>, which is not compatible for computations with numpy arrays. You can convert...
python|arrays|json|numpy|sympy
0
361,570
64,087,937
How to read a CSV from a folder without file name in Python
<p>I need to read a CSV file from a folder, which is generating from another Module. If that Module fails it won't generate the folder which will have a CSV file. Example:</p> <pre><code>path = 'c/files' --- fixed path </code></pre> <p>When Module successfully runs it will create a folder called output and a file in it...
<p>The following will check for existance of output folder as well as csv file and read the csv file:</p> <pre><code>import os import pandas as pd if 'output' in os.listdir('c/files'): if len(os.listdir('c/files/output')&gt;0: x=[i for i in os.listdir('c/files/output') if i[-3:]=='csv][0] new_file=p...
python|pandas|dataframe
1
361,571
63,780,854
How could I remove duplicates if duplicates mean less than 30days?
<p>(using sql or pandas) I want to delete records if the Date difference between two records is less than 30 days. But first record of ID must be remained.</p> <pre><code>#example ROW ID DATE 1 A 2020-01-01 -- first 2 A 2020-01-03 3 A 2020-01-31 4 A 2020-02-05 5 A 2020-02-28 6 A 202...
<p>You can try this:</p> <ol> <li>Convert date to <code>datetime64</code></li> <li>Get the first date from each group <code>df.groupby('ID')['DATE'].transform('first')</code></li> <li>Add a filter to keep only dates greater than 30 days</li> <li>Append the first date of each group to the dataframe</li> </ol> <p><stron...
sql|pandas
0
361,572
63,904,199
I am trying to vectorize the scalar function
<p>Here the code I had written</p> <pre><code>def scalar_function(x, y): &quot;&quot;&quot; Returns the f(x,y) defined in the problem statement. &quot;&quot;&quot; if x&lt;=y: return (np.dot(x,y)) else: return(x/y) def vector_function(x, y): &quot;&quot;&quot; Make sure vector...
<p>You could add an extra arguement for vector_function as follows :</p> <pre><code>def vector_function(x, y , func): vfunc = np.vectorize(func) return vfunc(x,y) </code></pre>
python|numpy|vectorization|scalar
1
361,573
63,799,731
Filter values depending on Time between them
<p>This is my DataFrame:</p> <pre><code> Date Bool 0 2020-09-02 False 1 2020-09-03 False 2 2020-09-04 True 3 2020-09-05 True 4 2020-09-06 False ... 3034 2028-12-28 True 3035 2028-12-29 False 3036 2028-12-30 True 3037 2028-12-31 False 303...
<p>You can use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shift.html" rel="nofollow noreferrer">shift</a> function to achieve this.</p> <p>From your examples it's not clear what happens when there are more than 2 consecutive true values, but this matches the example solutio...
python|pandas
1
361,574
64,018,814
Locate all non-number elements in a pandas.Series
<p>For a pd.Series with mixed strings and numbers (integers and floats), I need to identify all non-number elements. For example</p> <p><code>data = pd.Series(['1','wrong value','2.5','-3000','&gt;=50','not applicable', '&lt;40.5'])</code></p> <p>I want it to return the following elements:</p> <pre><code>wrong value &g...
<p>Use <code>pd.to_numeric</code> to flag them</p> <pre><code>data[pd.to_numeric(data, errors='coerce').isna()] Out[1159]: 1 wrong value 4 &gt;=50 5 not applicable 6 &lt;40.5 dtype: object </code></pre>
python|regex|pandas|string|text-processing
2
361,575
46,806,067
Transpose in Pyspark Dataframe
<p>I am new to <strong>PySpark Dataframe</strong> i am following one sample from <a href="https://mapr.com/blog/churn-prediction-pyspark-using-mllib-and-ml-packages/" rel="nofollow noreferrer">this link</a>. In this link they are using pandas dataframe wheras i want to achieve the same using Spark Dataframe. I am stuck...
<p>In pyspark API <code>pyspark.mllib.linalg.distributed.BlockMatrix</code> has transpose function. if you have a df with columns <code>id, features</code></p> <pre><code>bm_transpose = IndexedRowMatrix(df.rdd.map(lambda x:(x[0], Vectors.dense(x[1])))).toBlockMatrix(2,2).transpose() </code></pre>
pandas|pyspark|spark-dataframe
0
361,576
46,798,156
how to delete columns with same values in numpy
<p>How is it possible to delete all the columns that have the same values in a <code>NumPy</code> array? </p> <p>For example if I have this matrix:</p> <pre><code>[0 1 2 3 1] [0 2 2 1 0] [0 4 2 3 4] [0 1 2 3 4] [0 1 2 4 5] </code></pre> <p>I want to get a new matrix that looks like this:</p> <pre><code>[1 3...
<p>You can compare the array with the shifted version of itself, if all pairs are equal for a column, then the column contains only one unique value, which can be removed with boolean indexing:</p> <pre><code>a[:, ~np.all(a[1:] == a[:-1], axis=0)] #array([[1, 3, 1], # [2, 1, 0], # [4, 3, 4], # [1, 3...
python|numpy|matrix
5
361,577
46,978,740
Split Panda Column dtype: float64 into several columns
<p><strong>Aim:</strong> to create a panda dataframe that can be uploaded to postgresql (I haven't added the pgsql step as it is irrelevant to my question)</p> <p><strong>Background:</strong> I am currently working with a .nc file this is the info:</p> <pre><code>&lt;type 'netCDF4._netCDF4.Dataset'&gt; root group (NE...
<p>You can <a href="http://pandas.pydata.org/pandas-docs/version/0.20.3/generated/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>reset_index</code></a>:</p> <pre><code>In [11]: df Out[11]: Rainf lat lon time -89.875 -179.875 1979-01-03 6.705523e-08 In ...
python|pandas|netcdf|python-xarray
1
361,578
46,745,270
TensorFlow: add_meta_graph() of SavedModelBuilder: Why does every additional meta graph take up the same disk space as the full model?
<p>The <a href="https://www.tensorflow.org/api_docs/python/tf/saved_model/builder/SavedModelBuilder" rel="nofollow noreferrer">documentation</a> of SavedModelBuilder says that the first meta graph added to a SavedModel (via <code>add_meta_graph_and_variables()</code>) will be added with variables and that any additiona...
<p>The SavedModel format indeed saves variables shared between meta graphs exactly once.</p> <p>Is it possible that your model contains large constants (or say the variables are initialized to large constants)? The SavedModel format will be able to re-use the storage for variables but not for constants. For example, c...
tensorflow
3
361,579
46,997,735
What is wrong with the batch_size of the following tensorflow code?
<p>The following Tensorflow code, which I was using to check a small technique, does regression.</p> <pre><code>x = tf.placeholder(tf.float32, [None, input_size], name="input_data") y = tf.placeholder(tf.float32, [None], name="input_data") W1 = tf.get_variable("W1", [input_size, blocks[0]], initializer=tf.truncated_n...
<p>This correction on <code>line 2</code> fixes everything:</p> <pre><code>y = tf.placeholder(tf.float32, [None,1], name="input_data") </code></pre>
machine-learning|tensorflow|neural-network|deep-learning
0
361,580
46,809,632
Pandas Merge duplicating all rows
<p>I am trying to merge two dataframes to find any new entries. Currently the two dataframes are identical.</p> <p>Dataframe A</p> <pre><code> BusinessName Ubi IdentifierValue 0 CHULA VISTA PAINTING/SERVICES 604000010 CHULAVP841MQ 1 MANU TECH LLC ...
<p>There is problem different types, need same.</p> <p>Check it:</p> <pre><code>print (A['Ubi'].dtype) print (B['Ubi'].dtype) </code></pre> <p>So need:</p> <pre><code>A['Ubi'] = A['Ubi'].astype(str) B['Ubi'] = B['Ubi'].astype(str) </code></pre> <p>Or:</p> <pre><code>A['Ubi'] = A['Ubi'].astype(int) B['Ubi'] = B['U...
python|pandas|merge
1
361,581
46,846,502
how to change the format of the return value of 'mnist.load_data()' to 'mnist_train.csv' in Keras?
<p>I use Keras.</p> <pre><code>(X_train, y_train), (X_test, y_test) = mnist.load_data() </code></pre> <p>X_train' shape is <code>(number_of_training_sample,224,224,3)</code></p> <p>Y_train's shape is <code>(number_of_training_sample, 10)</code></p> <p>Features and labels are separated in different ndarray. BUT I wa...
<pre><code>(X_train, y_train), (X_test, y_test) = mnist.load_data() </code></pre> <p>loads data as numpy arrays</p> <p>'mnist_train.csv' is a .csv file store on a hard disc which we usually read with pandas library</p> <pre><code>import pandas as pd X_train = pd.read_csv('filename.csv') </code></pre> <p>Pandas read...
numpy|keras|mnist
0
361,582
46,831,269
python3: pandas' to_json is adding \ to each double quote in one of my key values
<p>I have a json made from twitter scraping. Some of the tweets have backslashes preceding a quote being used. This is only seen within the tweet message and not the keys of my json. I have the below code which will remove a lot of rubbish including the back slash but the newly saved json still has the back slashed</p>...
<p><code>"full_text":"How can you "accidentally close" my account"</code> is not valid JSON. The <code>\</code> are there to escape the quotes inside the string, telling the parser that these quotes should be included with the string rather than determine the JSON structure. When you read that JSON back into another ...
python|json|python-3.x|pandas
0
361,583
47,028,590
Tensorflow: Memory Error while trying to load a numpy sparse matrix to input_fn
<p>I'm building a text classification model and built a large sparse matrix with the shape (81062,100000).</p> <p>The input_fn function is defined as:</p> <pre><code># Define the input function for training input_fn = tf.estimator.inputs.numpy_input_fn( x={'tfidf': X_train_tfidf.todense()}, y=y_train.values, ...
<p>The TypeError is indicative of the fact that from_sparse_tensor_slices requires its input to be an instance of tf.SparseTensor. See: <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/data/Dataset#from_sparse_tensor_slices" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/contrib/d...
tensorflow
1
361,584
47,075,719
Installing Tensorflow: Python - Tensorflow Version Mismatch Warnings
<p>EDIT:<code>tensorflow-1.3.0-cp36-cp36m-linux_x86_64.whl</code> Now getting different warnings. These seem much more minor?</p> <pre><code>2017-11-02 13:31:01.945114: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your...
<p>As you can see here for python3.5 TF_Binary_URL is </p> <p><a href="https://www.tensorflow.org/install/install_linux#the_url_of_the_tensorflow_python_package" rel="nofollow noreferrer">https://www.tensorflow.org/install/install_linux#the_url_of_the_tensorflow_python_package</a> which is tensor version 1.3, so just...
python|machine-learning|tensorflow
1
361,585
46,677,105
Tensorflow equivalent of the Keras function: UpSampling2D
<p>I would like to use the Keras layer: </p> <pre><code>from keras.layers.convolutional import UpSampling2D x = UpSampling2D((2, 2))(x) </code></pre> <p>How can I replicate this behavior with native tensorflow ? </p> <p>I can't manage to find an equivalent function/layer.</p>
<p>Assuming <code>x</code> is of shape <code>(BATCH_SIZE, H, W, C)</code>, you can use <code>tf.image.resize_nearest_neighbor</code>, which is the backend implementation used by keras:</p> <pre><code>x = tf.image.resize_nearest_neighbor(x, (2*H,2*W)) </code></pre>
image-processing|tensorflow|keras|convolution|deconvolution
11
361,586
46,823,175
Python Pandas DataFrame - Creating Change Column
<p>I have a data frame with this column name</p> <pre><code>timestamp,stockname,total volume traded </code></pre> <p>There are multiple stock names at each time frame</p> <pre><code>11:00,A,100 11:00,B,500 11:01,A,150 11:01,B,600 11:02,A,200 11:02,B,650 </code></pre> <p>I want to create a ChangeInVol column such th...
<p>Need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><code>sort_values</code></a> + <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.diff.html" rel="nofollow noreferrer"><code>DataFrameGroup...
python|pandas|dataframe
1
361,587
46,690,385
How to read numerical data from the comment of a .txt file into numpy
<p>Suppose I have some .txt files as the output of measurements of experiments:</p> <pre><code>Date: 160818 double polished Si 300 microns Power before sample: 62.7uW Power after sample: 33.0uW position y1 y2 power 1.00E-01 1.93E+07 1.17E+06 2.32E-05 2.00E-01 1.92E+07 1.16E+06 2.32E-05 3.00E-01 ...
<p>You can read the files like normal. Just skip the first 2 rows and do string manipulation on rows 3 and 4</p> <p>something like </p> <pre><code>before = rows[0] //first row before = before[21:-2] </code></pre> <p>if I'm counting correctly will give you the numbers. If you want them as numbers instead of string y...
python|numpy|text|import|scipy
3
361,588
46,912,100
Matplotlib show x-ticks on all subplots and unique y label
<p>I am plotting two subplots that share the same x-axis but when I plot I only see the x-axis ticks on the second subplot. How can I make the x-ticks visible on both subplots?</p> <p>Also I would like to set y-labels for both subplots but only the second is visible. Can you please help in displaying the y-label on bo...
<p>As other answers have mentioned, to get the <code>ylabel</code> showing up on both subplots, you can use the object-oriented interface here <code>axes[0].set_ylabel</code> and <code>axes[1].set_ylabel</code>.</p> <p>You should also use <code>.tick_params</code> on both axes to get the same size tick labels, etc. fo...
python|pandas|matplotlib|subplot
10
361,589
46,705,778
numpy astype from float32 to float16
<p>I would like to know how numpy casts from float32 to float16, because when I cast some number like 8193 from float32 to float16 using astype, it will output 8192 while 10000 of float32 casted into 10000 of float16.</p> <pre><code>import numpy as np a = np.array([8193], dtype=np.float32) b = a.astype(np.float16) </c...
<p>The IEEE 754-2008 16-bit base 2 format, aka binary16, doesn't give you a lot of precision. What do you expect from 16 bits? :) 1 bit is the sign bit, 5 bits are used for the exponent, and that leaves 10 bits to store the normalised 11 bit mantissa, so anything > 2**11 == 2048 has to be quantized.</p> <p>According t...
python|numpy|floating-point
12
361,590
46,941,747
Tensorflow Error: "Cannot parse tensor from proto"
<p>I am creating a deep CNN with tensorflow. I have already created the architecture, and now I am in the process of training. When I begin to train the model, I use the command:</p> <pre><code>sess.run(tf.global_variables_initializer()) </code></pre> <p>When this command is called, I get the error located below. My ...
<p>As @Tarun Wadhwa said, tensorflow doesn't allow tensors of size > 2 GB on a single device. Your tensor is of size (19 x 10^9 entries) x 4 bytes = <strong>78 GB</strong> if you're using <code>dtype='tf.float32'</code>.</p> <p>Firstly, you can try using 'tf.float16'. This would halve the size of your tensor on RAM. (...
python|tensorflow|deep-learning|conv-neural-network
11
361,591
47,058,092
Tensorflow: how to load a ".npy" file to a net
<p>I want to load "vgg16.npy" to a vggnet written by myself. I wonder if you could help me with this.Thank you.</p>
<p>You cannot copy the weights/biases of your <code>.npy</code> file directly to your network, as they will be considered as constants. Therefore, first you need to initialize a <code>tf.Variable</code>:</p> <pre><code>conv1_weights = tf.get_variable('conv1_weights', initializer=data['conv1']['weights']) conv1_biases...
python|tensorflow
1
361,592
46,929,683
Creating new column based on another column value with two conditions and converting NaN to blank
<p>I have a minor issue with pandas code. I am using the np.where command to create a new column based on conditions and return either 1 or 0. However with np.where, the NaN values are returned as 0, but I would like to return them as blanks. If I understood correctly with np.where it is not straightforwardly possible....
<blockquote> <p>Is there more efficient way to achieve the following result?</p> </blockquote> <p>Yes. One way is to pass a <code>dict</code> to <code>df.replace</code>, and it should work nicely.</p> <pre><code>x = {np.nan: '', 'No': 0, 'Yes': 1, 'Maybe': 1} df.replace(x) column1 x y 1 z 0 q...
python|excel|pandas
0
361,593
46,743,823
finding different element in column numpy
<p>i am using numpy to find different element in the first column of numpy array i am using below code i also look at np.unique method but i couldn't find proper function</p> <pre><code>k = 0 c = 0 nonrep=[] for i in range(len(xin)): for j in range(len(nonrep)): if(xin[i,0]==nonrep[j]): c = c+1 ...
<p>This is definitely not the good way to do it. Since here you perform membership checks by performing linear search. Furthermore you do not even <code>break</code> after you have found the element. This makes it an <em>O(n<sup>2</sup>)</em> algorithm.</p> <h1>Using numpy <em>O(n log n)</em>, no order</h1> <p>You ca...
python|numpy
2
361,594
47,047,099
Tensorflow train CNN but accuracy invariable
<p>First Step <a href="https://i.stack.imgur.com/X2ZpH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X2ZpH.png" alt="First train step"></a></p> <p>Second step <a href="https://i.stack.imgur.com/l7ucN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l7ucN.png" alt="Second step"></...
<p>When I change the initializer to xavier initializer. It seems to be normal.</p>
tensorflow
0
361,595
46,705,354
What does it mean to "get variable" in TensorFlow?
<p>Several times I saw the following statement:</p> <blockquote> <p>tf.get_variable gets from the graph an existing variable</p> </blockquote> <p>What exactly does it mean? If a variable already exists, why can't I reuse it (or "get it") by calling its name. For example, I have a variable <code>x</code>, so I just ...
<blockquote> <p>If a variable already exists, why can't I reuse it (or "get it") by calling its name.</p> </blockquote> <p>You can and that's usually done when the whole model is in one file. However, the big model is likely to be split into different source files and libraries. In this case, <code>tf.get_variable</...
python|tensorflow
0
361,596
47,030,450
Merge two data-sets in Python Pandas
<p>I have two datasets in the below format &amp; want to merge them into a single dataset based on City+Age+Gender. Thanks in advance</p> <p>Dataset1:</p> <pre><code> City Age Gender Source Count 0 California 15-24 Female Amazon Prime Video 14629 1 California 15-24 Female ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>pandas.concat</code></a> with <code>rename</code> columns for align columns - need same columns in <code>both DataFrames</code>:</p> <pre><code>df = pd.concat([df1, df2.rename(columns={'Feeds':'Cou...
python|pandas|merge
2
361,597
46,637,347
Dataset does not fit in memory
<p>I have an <code>MNIST</code> like dataset that does not fit in memory, (process memory, <strong>not gpu</strong> memory). My dataset is 4GB.</p> <p>This is not a <code>TFLearn</code> issue.</p> <p>As far as I know <code>model.fit</code> requires an <strong>array</strong> for <code>x</code> and <code>y</code>.</p> ...
<p>You can use the <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset" rel="nofollow noreferrer">Dataset api</a>.</p> <p>&quot;The Dataset API supports a variety of file formats so that you can process large datasets that do not fit in memory&quot;</p> <p>Basically the input pipeline would become part ...
memory-management|tensorflow|out-of-memory|tflearn
3
361,598
46,670,183
Why is groupby so fast?
<p>This is a follow up question to <a href="https://stackoverflow.com/questions/46667947/fastest-way-to-split-a-pandas-dataframe-into-a-list-of-subdataframes">this one</a>, where jezrael used pandas.DataFrame.groupby to increment by a factor of some hundreds the speed of a list creation. Specifically, let <code>df</cod...
<p>Because your data frame is not sorted on the index, which means all the subsetting has to be done with slow vector scan and fast algorithm like <em>binary search</em> can not be applied; While <code>groupby</code> always sort the data frame by the group by variable first, you can mimic this behavior by writing a sim...
python|performance|pandas|dataframe|pandas-groupby
11
361,599
46,709,552
Python find duplicates and merge data based on time
<p>I have a table with around 3500 records.</p> <p>I am trying to loop through and find duplicates based on a field i created called UNIQUEID, which could be 2, 3, 4 of each record. My end goal is to merge records that have identical UNIQUEID values, but different RTYPE values</p> <pre><code>OID UNIQUEID RTY...
<p>I suggest creating only a single cursor, in order to get your data into a dictionary, and then work on manipulating the data from there. Since you have to make a dictionary <em>anyway</em> to store information for the next loop through, might as well just use the dictionary. (I <em>would</em> recommend a second curs...
python|python-2.7|pandas|arcpy
0