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
5,200
39,036,808
Graphviz: give color to lines with rainbow effect
<p>I have dataframe and I build graph using <code>graphviz</code></p> <pre><code>for id_key, group in df.groupby('ID'): f = Digraph('finite_state_machine', filename='fsm.gv', encoding='utf-8') f.body.extend(['rankdir=LR', 'size="5,5"']) f.attr('node', shape='box') for i in range(len(group)-1): f.edge(str(group['ca...
<p>You can use one of the <a href="http://graphviz.org/doc/info/colors.html#brewer" rel="noreferrer">brewer color schemes</a>. For example:</p> <pre><code>g = graphviz.Digraph(format='png') g.body.extend(["rankdir=LR"]) for i in range(9): g.edge(str(i),str(i+1),color="/spectral9/"+str(i+1)) g.render(filename="exam...
python|pandas|graphviz
6
5,201
39,308,065
How to display Chinese characters inside a pandas dataframe?
<p>I can read a csv file in which there is a column containing Chinese characters (other columns are English and numbers). However, Chinese characters don't display correctly. see photo below</p> <p><a href="https://i.stack.imgur.com/nG6oN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nG6oN.png" al...
<p>I just remembered that the source dataset was created using <code>encoding='GBK'</code>, so I tried again using </p> <pre><code>data06_16 = pd.read_csv("../data/stocks1542monthly.csv", encoding="GBK") </code></pre> <p>Now, I can see all the Chinese characters. </p> <p>Thanks guys!</p>
python|csv|pandas|encoding|chinese-locale
7
5,202
39,382,801
Two subplots of gridspec, one line plot and the other bar plot, with a time-series on x, are not displaying
<p>I can't figure out what I'm doing wrong in my plotting. Plotting some data vs datetime on two subplots, one is a line plot, the other one should be a bar plot. I have tried several different ways of plotting it but without much success. </p> <p><strong>UPDATE</strong> Minor progress - the first plot is displayed, ...
<p>I found out what the problem was!!! I don't understand why it worked fine with the line plot and not with the bar plot, but all that needed to be changed in the code is the actual one line for the bar plot. It should go like this:</p> <pre><code>ax2 = plt.bar(Test["A"].values,Test["C"],width=1) </code></pre> <p>So...
python|python-2.7|pandas|matplotlib|bar-chart
0
5,203
19,803,407
Extracting every 3rd data in an array
<p>I have thousand of data for x and y, for this case i will just use 12 data. The array are used to plot a graph</p> <pre><code>x = np.array([1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,11000,12000]) y = np.array([1,2,3,4,5,6,7,8,9,10,11,12]) py.plot(x,y) </code></pre> <p>How can i extract every [3] multiplic...
<p>Extract every third item starting with the third item (one dimensional array) </p> <pre><code>x[2::3], y[2::3] </code></pre> <p>Extract every fifth item starting with the fifth item (one dimensional array) </p> <pre><code>x[4::5], y[4::5] </code></pre>
python|graph|numpy
3
5,204
33,679,382
How do I get the current value of a Variable?
<p>Suppose we have a variable:</p> <pre><code>x = tf.Variable(...) </code></pre> <p>This variable can be updated during the training process using the <code>assign()</code> method.</p> <p><em>What is the best way to get the current value of a variable?</em></p> <p>I know we could use this:</p> <pre><code>session.r...
<p>The only way to get the value of the variable is by running it in a <code>session</code>. In the <a href="http://tensorflow.org/resources/faq.md#contents" rel="noreferrer">FAQ it is written</a> that:</p> <blockquote> <p>A Tensor object is a symbolic handle to the result of an operation, but does not actually ho...
python|tensorflow
39
5,205
22,666,026
Debug Pandas Dataframe Apply
<p>New to Pandas and I have the following question: I want to apply my_func (a custom created function) to each row of a dataframe.</p> <pre><code>res = df.apply(lambda x: my_func(x, par1, par2) </code></pre> <p>When I debug and I put a breakpoint on the first row of my function defined as:</p> <pre><code>def my_fu...
<p>You need to set <code>axis=1</code> in <code>apply</code>:</p> <pre><code>res = df.apply(lambda x: my_func(x, par1, par2), axis=1) </code></pre> <p>The <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.apply.html" rel="nofollow">online docs</a> states that <code>axis=0</code> is column-w...
python|debugging|pandas|dataframe|apply
3
5,206
22,639,840
Graph histogram and normal density with pandas
<p>I look for graphing both normal density and histogram density from a serie df like that but don't achieve. like link below <a href="http://hypertextbook.com/facts/2007/resistors/histogram.gif" rel="nofollow">http://hypertextbook.com/facts/2007/resistors/histogram.gif</a></p> <p>How to do that with DataFrame objects...
<p>I think you can first plot the histogram like fd.hist()</p> <p>Then fit the normal density and plot it with matplotlob, please refer to:</p> <p><a href="https://stackoverflow.com/questions/7805552/fitting-a-histogram-with-python">Fitting a histogram with python</a></p>
python|pandas
1
5,207
15,288,158
Data frame creation from an input file
<p>I have a file which contain some floating values like</p> <pre><code>5.234234 6.434344 5.45435 7.243224 4.0999884 </code></pre> <p>I want to create a dataframe from this file.It should look like</p> <pre><code>Activity 5.234234 6.434344 5.45435 7.243224 4.0999884 </code></pre> <p>What I've tried is(its not worki...
<p>You must use:</p> <pre><code>p.read_csv('Activity.txt', names=('Activity',)) </code></pre> <p>Note:<br> 1) You dont need to <em>open</em> your file.<br> 2) <code>names</code> is 'array-like', for example, a tuple or list.<br> 3) <code>header</code> is <code>None</code> by default when <code>names</code> parameter ...
python|input|pandas
2
5,208
62,349,703
Jupyter Notebook kernel dies while compiling Neural Network
<p>While creating and compiling a keras Dense Neural Network my jupyter notebook kernel always dies. The terminal gives me a message that it couldn't allocate space and that CUDA is out of memory. My GPU (2060 Super) has already run this model many times, just not on jupyter. I have already done a lot of searching whit...
<p>Try adding this function to your notebook. I am not certain but it may help.</p> <pre><code>def setup_gpus(): gpus = tf.config.list_physical_devices('GPU') if gpus: try: tf.config.experimental.set_visible_devices(gpus[0],'GPU') tf.config.experimental.set_virtual_device_configuration(gpus[0],[tf....
python|tensorflow|keras|deep-learning|jupyter-notebook
1
5,209
62,197,944
How to change number of "colums" on diameter of a radial FacetGrid
<p>How can I change the number of months that are shown on belows circle? I would need to have december overlap with january The code produces the figure shown below but it also throws an error (which doesn't bother me as the figure is there), maybe this is a clue.</p> <p>Thanks for helping, best answer will be marked...
<pre><code>from matplotlib import pyplot as plt import pandas as pd import numpy as np data = {'month': ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dez'], 'value':['4.9','4.8','4.7','4.6','4.4','4.4','4.3','4.4','4.5','4.6','4.7','4.8']} df = pd.DataFrame(data, columns = ['month','value...
python|python-3.x|pandas|matplotlib|seaborn
0
5,210
62,453,764
How to do inference in parallel with tensorflow saved model predictors?
<p>Tensorflow version: 1.14</p> <p>Our current setup is using tensorflow estimators to do live NER i.e. perform inference one document at a time. We have 30 different fields to extract, and we run one model per field, so got total of 30 models. </p> <p>Our current setup uses python multiprocessing to do the inference...
<p>Ray Serve, ray's model serving solution, also support offline batching. You can wrap your model in Ray Serve's backend and scale it to the number replica you want.</p> <pre><code>from ray import serve client = serve.start() class MyTFModel: def __init__(self, model_path): self.model = ... # load model ...
python|tensorflow|multiprocessing|python-multiprocessing|ray
3
5,211
62,111,642
Difference between DCGAN & WGAN
<p>In my understanding, DCGAN use convolution layer in both Generator and Discriminator, and WGAN adjust the loss function, optimizer, clipping and last sigmoid function. The part they control is not overlapping. So are there any conflict if i implement both changes of DCGAN &amp; WGAN in one model?</p>
<p>According to my experience, DCGAN proposed a well-tuned and simple model (or more specifically we can say it proposed a simple network structure with well-tuned optimizer) to generate images.WGAN proposed a new method of measuring the distance between data distribution and model distribution and theoretically solved...
pytorch|generative-adversarial-network
0
5,212
62,251,084
How to get ssl information formatted in dataframe for multiple domains?
<p>How to get these stats in a dataframe for multiple domains. ex : google.com , nyu.edu</p> <p>expected_output :</p> <pre><code>name expiry date status google.com Wednesday, 12 August 2020 at 17:30:48 active nyu.edu expired/No Cert ...
<p>If you use <code>getpeercert()</code> you won't be able to retrieve the certificate in the outpout if the verification failed (you can test with <a href="https://expired.badssl.com/" rel="nofollow noreferrer">https://expired.badssl.com/</a> for example).</p> <p>From <a href="https://stackoverflow.com/a/45480084/261...
python|pandas|dataframe|ssl|openssl
1
5,213
51,319,692
Store array as a value within Pandas column
<p>I have a data set with two columns of categorical label data (NBA Team names). What I want to do is use one hot encoding to generate a binary, 1D vector as an array representing each team. Here is my code:</p> <pre><code>from sklearn.preprocessing import MultiLabelBinarizer one_hot_encoder = MultiLabelBinarizer() t...
<p>I think need convert <code>2d</code> array to <code>list</code>s:</p> <pre><code>table = pd.DataFrame({"Teams":list('aaasdffds')}) from sklearn.preprocessing import MultiLabelBinarizer one_hot_encoder = MultiLabelBinarizer() table["Teams"] = one_hot_encoder.fit_transform(table["Teams"]).tolist() print (table) ...
python|arrays|pandas|numpy|dataframe
1
5,214
51,141,875
Pandas: how to select a susbset of a dataframe with multiple conditions
<p>I have a dataframe like the following:</p> <pre><code> df = pd.DataFrame({'COND1' : [0,4,4,4,0], 'NAME' : ['one', 'one', 'two', 'three', 'three'], 'COND2' : ['a', 'b', 'a', 'a','b'], 'value': [30, 45, 18, 23, 77]}) </code></pre> <p>Where we have two condi...
<p>Try to modify your result by using <code>drop_duplicates</code>(drop the NAME satisfied both condition only keep one ) with <code>reindex</code>(Add back the NAME does not satisfied any condition )</p> <pre><code>Newdf=df[ ((df['COND1'] == 0 ) &amp; (df['COND2'] == 'a') | (df['COND1'] == 4 ) &amp; (df['COND2'] == '...
python|pandas|dataframe
0
5,215
51,465,813
implementing RNN with numpy
<p>I'm trying to implement the recurrent neural network with numpy.</p> <p>My current input and output designs are as follow:</p> <p><code>x</code> is of shape: (sequence length, batch size, input dimension)</p> <p><code>h</code> : (number of layers, number of directions, batch size, hidden size)</p> <p><code>initi...
<p>Regarding the shape, it probably makes sense if that's how PyTorch does it, but the Tensorflow way is a bit more intuitive - <code>(batch_size, seq_length, input_size)</code> - <code>batch_size</code> sequences of <code>seq_length</code> length where each element has <code>input_size</code> size. Both approaches can...
python|numpy|recurrent-neural-network|rnn
2
5,216
51,448,700
Python List Append with bumpy array error
<p>I am trying to use list append function to append a list to a list. </p> <p>But got error shows list indices must be integers or slices, not tuple. Not sure why. </p> <pre><code>pca_components = range(1,51) gmm_components = range(1,5) covariance_types = ['spherical', 'diag', 'tied', 'full'] # Spherical spherical_...
<p>What's the purpose of this line?</p> <pre><code>spher_results = np.array(spherical_results) </code></pre> <p>It makes an array from a list. But you don't use <code>spher_results</code> in the following code.</p>
python|numpy
1
5,217
48,369,613
Python Pandas - what is best way to store pearson correlation values stored in as pandas dataframe
<p>What is best way to store pearson correlation values as a pandas dataframe.</p> <p>Correlation is calculated as below</p> <pre><code>Correlation = df.corr() </code></pre> <p>But I want to store the output as dataframe.</p>
<p>The output <em>is</em> a dataframe.</p> <p>The docstring in version 0.22 says:</p> <p>Compute pairwise correlation of columns, excluding NA/null values</p> <pre><code>Parameters ---------- method : {'pearson', 'kendall', 'spearman'} * pearson : standard correlation coefficient * kendall : Kendall Tau corr...
python|pandas
0
5,218
47,990,806
how to use groupby function for making row to columns based on similar IDS
<p>I have data which is in form of</p> <pre><code>arun 21-09-2017 raja 21-08-2016 arun 21-10-2017 raja 21-01-2017 </code></pre> <p>i want my input to be converted as this follows.</p> <pre><code>arun 21-09-2017 21-01-2017 raja 21-08-2016 21-01-2017 </code></pre>
<p>Assuming that you're using pandas dataframe, you can then use <em>groupby</em> to get the desired output.</p> <pre><code>data = {'name':['arun','raja','arun','raja'], 'date':['21-09-2017','21-08-2016','21-10-2017','21-01-2017'] } df1 = pd.DataFrame(data) df1.groupby('name')['date'].apply(list).reset...
python|pandas
0
5,219
48,511,359
Logging scalars from loss function
<p>I'm working on a ML model implemented in Keras. For this model I wrote a custom loss function which where the loss is a sum of performances of 3 other variables <code>(a_cost, b_cost, c_cost)</code>. The loss function works but I would like to tune it a bit and for that I would like to see how these 3 other variable...
<p>As <code>a_cost</code>, <code>b_cost</code> and <code>c_cost</code> are computed you can define three separate functions to compute them separately. Let:</p> <pre><code>def a_cost(y_true, y_pred): # compute a_cost ... return a_cost def b_cost(y_true, y_pred): # compute b_cost ... return b_c...
tensorflow|machine-learning|neural-network|deep-learning|keras
1
5,220
48,829,617
Find first row with condition after each row satisfying another condition
<p>in pandas I have the following data frame:</p> <pre><code>a b 0 0 1 1 2 1 0 0 1 0 2 1 </code></pre> <p>Now I want to do the following: Create a new column c, and for each row where a = 0 fill c with 1. Then c should be filled with 1s until the first row after each column fulfilling that, where b = 1 (and here im h...
<p>It seems you need:</p> <pre><code>df['c'] = df.groupby(df.a.eq(0).cumsum())['b'].cumsum().le(1).astype(int) print (df) a b c 0 0 0 1 1 1 1 1 2 2 1 0 3 0 0 1 4 1 0 1 5 2 1 1 </code></pre> <p><strong>Detail</strong>:</p> <pre><code>print (df.a.eq(0).cumsum()) 0 1 1 1 2 1 3 2 4 ...
python|pandas
2
5,221
48,488,278
Optimization for faster numpy 'where' with boolean condition
<p>I generate a bunch of 5-elements vectors with</p> <pre><code>def beam(n): # For performance considerations, see # https://software.intel.com/en-us/blogs/2016/06/15/faster-random-number-generation-in-intel-distribution-for-python try: import numpy.random_intel generator = numpy.random_int...
<p>As your components are uncorrelated one obvious speedup would be to use the univariate normal instead of the multivariate:</p> <pre><code>&gt;&gt;&gt; from timeit import repeat &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; &gt;&gt;&gt; kwds = dict(globals=globals(), number=100) &gt;&gt;&gt; &gt;&gt;&gt; repeat('np...
python-3.x|numpy
0
5,222
48,568,022
Truncate column in data frame from float to int
<p>I have a data-frame (<code>df</code>) that has an <code>Age</code> column, and looks like</p> <pre><code> Age 0 59.917864 1 50.387406 2 50.387406 3 55.008898 </code></pre> <p>I am trying to crearte a new column call <code>Age_truncated</code> which would be the <code>Age</code> c...
<p>You can using <code>floor</code> from <code>numpy</code></p> <pre><code>df['Age1']=np.floor(df.Age).astype(int) df Out[414]: Age Age1 0 59.917864 59 1 50.387406 50 2 50.387406 50 3 55.008898 55 </code></pre>
python|pandas
1
5,223
71,070,317
How to add values in rows and pass the result to the next column using pandas?
<p>I have a pandas dataframe with the values as follows:</p> <pre><code>Start end Depart Duration A B 5 2 B C 5 3 C D 5 6 D E 5 4 </code></pre> <p>I want the output as shown below. I need to add rows of 'Depart' and 'Duration' to ...
<p>Try using <code>cumsum</code>:</p> <pre><code>depart = df['Depart'] + df['Duration'].cumsum().shift(1).fillna(0).astype(int) arrival = df['Depart'] + df['Duration'].cumsum() df['Depart'] = depart df['Arrival'] = arrival df = df.drop('Duration', axis=1) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; df Start...
python|pandas|dataframe
0
5,224
70,746,660
How to predict memory requirement for np.linalg.inv?
<p>I'm inverting very large matrices on an HPC. Obviously, this has high RAM requirements. To avoid out-of-memory errors, as a temporary solution I've just been requesting a lot of memory (TBs). How might I predict the required memory from the input matrix size for a matrix inversion using numpy.linalg.inv to more effi...
<p><strong>TL;DR:</strong> up to <code>O(32 n²)</code> bytes for a <code>(n,n)</code> input matrix of type <code>float64</code>.</p> <p><a href="https://numpy.org/doc/stable/reference/generated/numpy.linalg.inv.html" rel="nofollow noreferrer"><code>numpy.linalg.inv</code></a> calls <code>_umath_linalg.inv</code> <a hre...
python|numpy
1
5,225
51,563,264
Adding report_tensor_allocations_upon_oom to cifar10_estimator example
<p>I'm running a modified version of the TensorFlow example <a href="https://github.com/tensorflow/models/tree/master/tutorials/image/cifar10_estimator" rel="nofollow noreferrer">https://github.com/tensorflow/models/tree/master/tutorials/image/cifar10_estimator</a> and I'm running out of memory.</p> <p>The ResourceExh...
<p>You would need to register a session run hook to pass extra arguments to <code>session.run()</code> calls that estimator does.</p> <pre><code>class OomReportingHook(SessionRunHook): def before_run(self, run_context): return SessionRunArgs(fetches=[], # no extra fetches options=tf.Ru...
python|tensorflow
3
5,226
64,598,675
Size must be a 1-D int32 Tensor
<p>I have MNIST data and doing some Transformation using Tensorflow and keras in R</p> <pre><code> dim(train_images) &lt;- c(nrow(train_images), 28,28,1) dim(test_images) &lt;- c(nrow(test_images), 28,28,1) train_images &lt;- tf$image$grayscale_to_rgb(tf$convert_to_tensor(train_images)) test_images &lt;- tf$image$gr...
<p>Simply write instead:</p> <pre><code>train_images &lt;- tf$image$resize(train_images, c(32L,32L)) test_images &lt;- tf$image$resize(test_images, c(32L,32L)) </code></pre>
r|tensorflow|keras
0
5,227
64,266,380
catplot issue Axes object
<p>Supposing I have a Pandas DataFrame variable called df which has columns col1, col2, col3, col4.</p> <p>Using sns.catplot() everything works fine:</p> <pre><code>fig = sns.catplot(x='col1', y='col2', kind='bar', data=df, col='col3', hue='col4') </code></pre> <p>However, as soon as I write:</p> <pre><code>fig.axes[0...
<p>If you check the <a href="https://seaborn.pydata.org/generated/seaborn.catplot.html" rel="nofollow noreferrer">help page</a>, it writes:</p> <blockquote> <p>Figure-level interface for drawing categorical plots onto a FacetGrid</p> </blockquote> <p>So to get the xlabel like you did:</p> <pre><code>import seaborn as s...
pandas|seaborn|catplot
1
5,228
64,324,492
make clickable url within Pandas dataframe in Flask
<p>I checked several questions from here and tried several methods on my own but didn't work out.</p> <p>I have a Pandas dataframe of product catalog which contains several columns, and there is a column called 'url', where it has url address to corresponding product.</p> <p>I'm using Flask to display this dataframe vi...
<p>If you can add some text inside your tag you will be able to see the link URL. Something like this</p> <pre><code>df['url'] = '&lt;a href=&quot;' + df['url'] + '&quot;&gt;' + df['url'] + '&lt;/a&gt;' </code></pre>
python|html|pandas|dataframe|flask
1
5,229
64,526,841
Can I use BERT as a feature extractor without any finetuning on my specific data set?
<p>I'm trying to solve a multilabel classification task of 10 classes with a relatively balanced training set consists of ~25K samples and an evaluation set consists of ~5K samples.</p> <p>I'm using the huggingface:</p> <pre><code>model = transformers.BertForSequenceClassification.from_pretrained(... </code></pre> <p>a...
<p>From my experience, you are going wrong in your assumption</p> <blockquote> <p>an out-of-the-box pre-trained BERT model (without any fine-tuning) should serve as a relatively good feature extractor for the classification layers.</p> </blockquote> <p>I have noticed similar experiences when trying to use BERT's output...
pytorch|bert-language-model|huggingface-transformers
3
5,230
47,608,461
Corresponding scores based on edges of a graph
<pre><code>import numpy as np score = np.array([ [0.9, 0.7, 0.2, 0.6, 0.4], [0.7, 0.9, 0.6, 0.8, 0.3], [0.2, 0.6, 0.9, 0.4, 0.7], [0.6, 0.8, 0.4, 0.9, 0.3], [0.4, 0.3, 0.7, 0.3, 0.9]]) l2= [(3, 5), (1, 4), (2, 3), (3, 4), (2, 5), (4, 5)] </code></pre> <p>I want to get the corresponding scores vec...
<p>We could convert the list of tuples holding the indices to array and then use <code>slicing</code> or tuple packed ones.</p> <p>So, convert to array :</p> <pre><code>l2_arr = np.asarray(l2)-1 </code></pre> <p>Then, one way would be -</p> <pre><code>score[l2_arr[:,0], l2_arr[:,1]] </code></pre> <p>Another -</p> ...
python|numpy|networkx
3
5,231
47,729,029
Creating a Tensorflow and Pandas Environment
<p>I using the following command to use modules in my machine learning work.</p> <pre><code>conda create -n tensorflow python=3.5 activate tensorflow conda install pandas matplotlib jupyter notebook scipy scikit-learn nltk conda install -c conda-forge tensorflow keras </code></pre> <p>When i using import command in m...
<p>You are using old versions of conda and python. The error tells you exactly what is going wrong: your escaped '\U' tells the interpreter there is a 8 digit code upcoming. That is not the case, the 's' is not valid in such a context.</p> <p>The best thing to do: use up-to-date versions of the software packages.</p> ...
python|pandas|tensorflow|unicode
2
5,232
47,761,063
From pandas to Excel using StyleFrame: how to disable the wrap text & shrink to fit?
<p>I use <a href="https://github.com/DeepSpace2/StyleFrame" rel="nofollow noreferrer">StyleFrame</a> to export from pandas to Excel.</p> <p>Cells are formatted to 'wrap text' and 'shrink to fit' by default. (How) can I change these settings? </p> <p>The <a href="http://styleframe.readthedocs.io/en/latest/api_document...
<p>As of version <strong>1.3</strong> it is possible to pass <code>wrap_text</code> and <code>shrink_to_fit</code> directly to <code>Styler</code>, for example <code>no_wrap_text_style = Styler(wrap_text=False)</code></p>
python|excel|pandas|styleframe
3
5,233
58,992,224
Get timestamp from pandas dataframe
<p>I can't figure out how to extract the timestamp from a pandas column.</p> <p>With the following code I am getting the following information.</p> <pre><code>print("Nested ----------------------------") print(type(nested_full['data.tick_timestamp'])) ts2 = nested_full['data.tick_timestamp'] print("type of timestamp...
<p>I think you need scalar from one element <code>Series</code>, so use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.iat.html" rel="nofollow noreferrer"><code>Series.iat</code></a> and select first value:</p> <pre><code>out = nested_full['data.tick_timestamp'].iat[0] </code></pre> ...
python|pandas
0
5,234
58,918,666
Dataframe with localized datetime index: how to drop days not having a given time
<p>I have one dataframe like the following:</p> <pre><code> A B 2014-06-02 09:00:00-04:00 ... ... 2014-06-02 10:00:00-04:00 ... ... 2014-06-02 11:00:00-04:00 ... ... 2014-06-02 12:00:00-04:00 ... ... 2014-06-03 09:00:00-04:00 ... ... 2014-06-03 10:00:00-04:00 ... ... 2014-06-03...
<p>You can <code>groupby</code> and <code>filter</code></p> <pre><code>df.groupby(df.index.date).filter(lambda s: 12 in s.index.hour) </code></pre> <p></p> <pre><code> A B 2014-06-02 09:00:00-04:00 ... ... 2014-06-02 10:00:00-04:00 ... ... 2014-06-02 11:00:00-04:00 ... ... 2014-06-...
python|python-3.x|pandas|dataframe
1
5,235
58,777,438
Difference between convolve2d and filter2D. Why is there a difference in output shapes?
<p>I need to perform a 2D convolution. I have a similarity matrix of shape <code>100, 100</code> and a filter of shape <code>5,5</code>.</p> <p>If I do using scipy:</p> <pre><code>scipy.signal.convolve2d(similarity_matrix, np.diag(filter)) </code></pre> <p>I get <code>104,104</code> matrix in response.</p> <p>But i...
<p>The default output mode of <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.convolve2d.html" rel="nofollow noreferrer">scipy.signal.convolve2d</a> is a full convolution. If you want your output size to be the same as your input size, set mode parameter as "same". </p> <pre><code>scipy.sign...
python|numpy|opencv|scipy|convolution
1
5,236
58,829,409
how to generate tensorflow matrix with first of few columns as 1 and the rest as 0
<p>Given a list <code>len_list</code> of the number of ones for the vectors, e.g.:</p> <pre><code>[1] [3] [2] [1] </code></pre> <p>where the shape of <code>len_list</code> now is <code>(4, 1)</code></p> <p>And given the number of columns of the vector, e.g. <code>vec_dim = 5</code>.</p> <p>I'd like to generate a ...
<p>You can achieve this using <code>tf.sequence_mask()</code> which returns a mask tensor representing the first N positions of each cell. </p> <p>Below is the code to get the output as you mentioned above. </p> <pre><code>len_list = np.array([1,3,2,1]) mask = tf.sequence_mask(len_list, maxlen=5, dtype=tf.int32) ...
python|tensorflow|matrix
0
5,237
58,979,037
HOWTO tf.estimator with continuous and categorical columns
<p>I have a tf.estimator which works for continuous variables and I want to expand it to use categorical variables.</p> <p>Consider a pandas dataframe which looks like this:</p> <pre><code>label | con_col | cat_col (float 0 or 1) | (float -1 to 1) | (int 0-3) ----------------+----------------...
<p>You need to wrap categorical columns before sending to DNN:</p> <pre><code>cat_feature_cols = [ tf.feature_column.sequence_categorical_column_with_identity('cat_col', num_buckets=4)) ] feature_cols = [tf.feature_column.indicator_column(c) for c in cat_feature_cols] </code></pre> <p>Use indicator column to one-hot ...
python|tensorflow
1
5,238
58,628,641
Remove list string startswith in pandas df
<p>i have df rows contains lists and wants to remove the particular string combined with others. </p> <p>df['res']:</p> <pre><code>AL1 A 15, CY1 A 16, CY1 A 20, GL1 A 17, GL1 A 62,HOH A 604, HOH A 605, L21 A 18, MG A 550, PR1 A 36, TH1 A 19, TH1 A 37, TY1 A 34, VA1 A 14, HOH A 603, VA1 A 35 </code></pre> <p>Desired ...
<p>The problem is that if you use <code>.split()</code> without anything else every substring will also get split.</p> <p>So this <code>... ,HOH A 604 ...</code> will split into <code>['...', ',' ,'HOH', 'A', '604', '...']</code>.</p> <p>As far as I understood you want to remove every <code>HOH</code> with the follow...
python|regex|pandas|dataframe
1
5,239
58,989,162
Group values based on columns and conditions in pandas
<p>I want to group pandas dataframe column based on a condition that if the values are with in a range of +20. Below is the dataframe</p> <pre><code>{'Name': {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F'}, 'ID': {0: 100, 1: 23, 2: 19, 3: 42, 4: 11, 5: 78}, 'Left': {0: 70, 1: 70, 2: 70, 3: 70, 4: 66, 5: 66}, 'Top'...
<p>You can write a function to group the <code>Top</code> columns first and then use <code>groupby</code> on that column:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Name': {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F'}, 'ID': {0: 100, 1: 23, 2: 19, 3: 42, 4: 11, 5: 78}, 'Left': {0: 70, 1: 70, 2: 70, 3:...
python|pandas
2
5,240
70,179,730
Numpy array: iterate through column and change value based on the current value and the next value
<p>I have an array like this: This is an extension of a recent question that I asked elsewhere <a href="https://stackoverflow.com/questions/70176293/numpy-array-iterate-through-column-and-change-value-depending-on-the-next-value">here</a>. I have a numpy array like this:</p> <pre><code>data = np.array([ [1,2,3], ...
<p>One way using <code>numpy.roll</code>:</p> <pre><code>s = data[:, 2] data[np.logical_and(s == 6, np.roll(s, -1) == 101), 2] = 10001 </code></pre> <p>Output:</p> <pre><code>array([[ 1, 2, 3], [ 1, 2, 3], [ 1, 2, 101], [ 4, 5, 111], [ 4, 5, ...
python|numpy|iteration
2
5,241
70,053,242
How unfold operation works in pytorch with dilation and stride?
<p>In my case I am applying this unfold operation on a tensor of A as given below:</p> <pre><code>A.shape=torch.Size([16, 309,128]) A = A.unsqueeze(1) # that's I guess for making it 4 dim for unfold operation A_out= F.unfold(A, (7, 128), stride=(1,128),dilation=(3,1)) A_out.shape=torch.Size([16, 896,291]) </code></pre>...
<blockquote> <p>Also here stride is not mentioned so default is 1 but what if it is also mentioned like 4.</p> </blockquote> <p>Your code already has <code>stride=(1,128)</code>. If stride is only set to <code>4</code> it will be used like <code>(4,4)</code> in this case. This can be easily verified with formula below....
python|pytorch
0
5,242
70,036,777
Add rows if missing recent data
<p>I have a dataframe which contains some numbers with dates and country information:</p> <pre><code>df = pd.DataFrame(data={&quot;day&quot;: ['2021-01-01', '2021-01-01', '2021-01-02', '2021-01-02', '2021-01-03'], &quot;country&quot;: [&quot;France&quot;, &quot;Brazil&quot;, &quot;Brazil&quot;, ...
<p>Idea is filter out all unique countries which has no maximal day and add to original with <a href="https://numpy.org/doc/stable/reference/generated/numpy.setdiff1d.html" rel="nofollow noreferrer"><code>numpy.setdiff1d</code></a>:</p> <pre><code>d = df.day.max() c = np.setdiff1d(df.country.unique(), df.loc[df['day']....
python|pandas
1
5,243
56,129,426
Slicing Dataframe with elements as lists
<p>My dataframe has list as elements and I want to have more efficient way to check for some conditions. <p>My dataframe looks like this</p> <pre><code>col_a col_b 0 100 [1, 2, 3] 1 200 [2, 1] 2 300 [3] </code></pre> <p>I want to get only those rows which have 1 in col_b. <p>I have tried the naive way temp_...
<pre><code>df[df.col_b.apply(lambda x: 1 in x)] </code></pre> <p>Results in:</p> <pre><code>col_a col_b 0 100 [1, 2, 3] 1 200 [2, 1] </code></pre>
python|pandas
1
5,244
56,227,140
Using py_func inside Tensorflow - ValueError: callback pyfunc_0 is not found
<p>I try to build a tensorflow model - where i load a pickle file with another model as part of the tensorflow model. The code has two parts where I create the model (save) and use the model to predict (load). I get ValueError: callback pyfunc_0 is not found</p> <p>The .pb file itself is very small, so it looks like t...
<p>tf.py_func does not support saving in pb format, please use checkpoint format instead</p>
python|tensorflow
1
5,245
55,983,383
Find the sum of previous count occurrences per unique ID in pandas
<p>I have a history of customer IDs and purchase IDs where no customer has ever bought the same product. However, for each purchase ID (which is unique), how can I find out the number of times the customer has made a previous purchase</p> <p>I have tried using groupby() and sort_values()</p> <pre class="lang-py prett...
<p>You can just use the <code>cumcount()</code> on the <code>id_cust</code> column since the <code>id_purchase</code> is unique:</p> <pre><code>df['value']=df.groupby('id_cust')['id_cust'].cumcount()+1 print(df) </code></pre> <hr> <pre><code> id_cust id_purchase value 0 1 20A 1 1 2 ...
pandas
1
5,246
55,906,106
How to add multiple models at runtime in tf_serving without unloading the previous models?
<p>I'm trying to add a new model in <code>tensorflow_model_server</code> using the following code:</p> <pre><code>from tensorflow_serving.apis import model_service_pb2_grpc from tensorflow_serving.apis import model_management_pb2 from tensorflow_serving.config import model_server_config_pb2 import grpc def add_model...
<p>There is no easy way to just add a new model while keeping the previous ones already loaded.</p> <p>What I have been doing is to always keep the last model config list on disk, and when I need to refresh the models for any reason (either add or remove or update), I read that config file from disk, and do the proper...
python|tensorflow|computer-vision|tensorflow-serving
0
5,247
64,873,311
How do I integrate groupby with query on?
<p>I am relative new to programming python so dont be to harsh on me please.</p> <p>I have a large covid19 dataframe with data from each country each day.</p> <p><a href="https://i.stack.imgur.com/J2pbv.png" rel="nofollow noreferrer">How it looks like</a></p> <p>I did query the date to just have 11.11.2020 to work with...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html</a></p> <p>You should be able to do</p> <pre><code>covid19.groupby(['continent']) </code></pre>
python|pandas|csv
0
5,248
64,938,800
For step, (batch_x, batch_y) in enumerate(train_data.take(training_steps), 1) error syntax
<p>i am learning logistic regression from this website <a href="https://builtin.com/data-science/guide-logistic-regression-tensorflow-20" rel="nofollow noreferrer">click here</a></p> <p>Step 9 does not work, the error is <a href="https://i.stack.imgur.com/eLUCX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.i...
<p>You can reproduce the same error with:</p> <pre><code>For i in range(0,1): pass </code></pre> <p>Try changing the &quot;For&quot; to &quot;for&quot;</p> <p>It looks like they just made a syntax error and you copied it.</p>
python|keras|tensorflow2.0
0
5,249
64,725,982
Slicing on entire panda dataframe instead of series results in change of data type and values assignment of first field to NaN, what is happening?
<p>Was trying to do some cleaning on a dataset ,where instead providing a condition on a panda series<br> <code>head_only[head_only.BasePay &gt; 70000]</code><br> I applied the condition on the data frame<br> <code>head_only[head_only &gt; 70000]</code><br> attached images of my observation, could anyone help me unders...
<p>Your second solution raise error if numeric with strings columns:</p> <pre><code>df = pd.DataFrame({ 'A':list('abcdef'), 'B':[4,5,4,5,5,4], 'C':[7,8,9,4,2.0,3], 'D':[1,3,5,7,1,0], 'E':[5,3,6,9,2,4], 'F':list('aaabbb') }) print (df[df &gt; 5]) </code></pre> <block...
pandas|dataframe|nan
1
5,250
64,747,609
csv to complex nested json
<p>So, I have a huge CSV file that looks like:</p> <pre><code>PN,PCA Code,MPN Code,DATE_CODE,Supplier Code,CM Code,Fiscal YEAR,Fiscal MONTH,Usage,Defects 13-1668-01,73-2590,MPN148,1639,S125,CM1,2017,5,65388,0 20-0127-02,73-2171,MPN170,1707,S125,CM1,2017,9,11895,0 19-2472-01,73-2302,MPN24,1711,S119,CM1,2017,10,4479,0 20...
<p>I don't really understand what you wish to do with that structure, but I guess it could be achieved with something like this</p> <pre class="lang-py prettyprint-override"><code>data = {'PCAs': []} for key, group in df.groupby('PCA Code'): temp_dict = {'PCA Code': key, 'CM Code': [], 'parts': []} for index, ...
python|json|pandas|csv
0
5,251
44,297,719
Pandas / Numpy way of finding difference between column headers and index headers
<p>I have a pandas dataFrame that look like this:</p> <pre><code>import pandas as pd cols = [1,2,5,15] rows = [1,0,4] data = pd.DataFrame(np.zeros((len(rows),len(cols)))) data.columns = cols data.index = rows 1 2 5 15 1 0.0 0.0 0.0 0.0 0 0.0 0.0 0.0 0.0 4 0.0 0.0 0.0 0.0 </code></pre> <p>I want to f...
<p>One approach using <a href="https://docs.scipy.org/doc/numpy-1.10.0/user/basics.broadcasting.html" rel="nofollow noreferrer"><code>NumPy broadcasting</code></a> -</p> <pre><code># Extract index and column as int arrays indx = df.index.values.astype(int) cols = df.columns.values.astype(int) # Perform elementwise su...
python|pandas|numpy
3
5,252
69,369,652
Download all postgresql tables to pandas
<p>Is there a simple way to download all tables from a postgresql database into pandas? For example can pandas just load from the .sql file? All the solutions I found on the line suggest connecting to the database and using select from commands, which seems far more complicated.</p>
<p>You have to connect to a database anyway. You can find out table names from odbc cursor and then use pandas.read_table for names ex. pypyodbc finding names:</p> <p>allnames=cursor.tables( schema='your_schema').fetchall()</p> <p>-- without view and indexes below</p> <p>tabnames=[el[2] for el in allnames if el[3]=='TA...
python|pandas|postgresql
0
5,253
65,998,061
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.time'
<p>I have a pandas DataFrame:</p> <pre><code>In [33]: df Out[33]: userId 2021-01-29 2021-01-30 2021-01-01 0 Nl3AG93Ss7L5aj 09:00:00 NaN NaN 1 NaN NaN Na...
<p>Try converting the things into strings and just using the <code>+</code> as string concat...</p> <pre><code>for column in df.columns.tolist(): for i in df.loc[df[column].apply(lambda x: isinstance(x, datetime.time))][column]: print(column.strftime(&quot;%Y-%m-%d”) +&quot; &quot;+ i.strftime(&quot;%H:%M:%S”)) ...
python|pandas|dataframe|datetime
0
5,254
66,275,053
Read the keys and values from the columns of a dataframe in Python
<p>I have a csv file that has two columns. One for the timeslot and one for the Energy. I put this file into pandas dataframe and I have attached the screenshot of this.<a href="https://i.stack.imgur.com/V1Rhh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V1Rhh.png" alt="Screenshot of datafrmae" />...
<p>Use:</p> <pre><code>d = dataframe.head(3).set_index('Timeslot')['Energy'].to_dict() </code></pre> <p>If need all values:</p> <pre><code>d1 = dataframe.set_index('Timeslot')['Energy'].to_dict() </code></pre> <p>EDIT:</p> <p>If need 2 dimensional key - tuple use:</p> <pre><code>d = dataframe.head(3).set_index(['Timesl...
python|pandas|dataframe|dictionary
1
5,255
52,759,806
filtering pandas over a list and sending email
<p>I am having a pandas data frame like below:-</p> <pre><code> Tweets 0 RT @cizzorz: THE CHILLER TRAP *TEMPLE RUN* OBS... 1 Disco Domination receives a change in order to... 2 It's time for the Week 3 #FallSkirmish Trials!... 3 Dance your way to victory in the new Disco Dom... 4 Patch v6.02 is available ...
<p>This will get it done:</p> <pre><code>import pandas as pd import numpy as np from io import StringIO s = ''' "RT @cizzorz: THE CHILLER TRAP *TEMPLE RUN* OBS..." "Disco Domination receives a change in order to..." "It's time for the Week 3 #FallSkirmish Trials!..." "Dance your way to victory in the new Disco Dom......
python|python-3.x|pandas|dataframe|slack-api
0
5,256
52,704,840
merge two dataframes with some common columns where the combining of the common needs to be a custom function
<p>my question is very similar to <a href="https://stackoverflow.com/questions/26307932/merge-pandas-dataframe-with-column-operation">Merge pandas dataframe, with column operation</a> but it doesn't answer my needs.</p> <p>Let's say I have two dataframes such as (note that the dataframe content could be float numbers ...
<p>You can concatenate the dataframes, and then groupby the column names to apply an operation on the similarly named columns: In this case you can get away with taking the sum and then typecasting back to bool to get the <code>or</code> operation.</p> <pre><code>import pandas as pd df = pd.concat([left, right], 1) d...
python|pandas|merge|concat
4
5,257
52,497,451
Compute correlation between features and target variable
<p>What is the best solution to compute correlation between my features and target variable ?? My dataframe have 1000 rows and 40 000 columns... </p> <p>Exemple : </p> <pre><code>df = pd.DataFrame([[1, 2, 4 ,6], [1, 3, 4, 7], [4, 6, 8, 12], [5, 3, 2 ,10]], columns=['Feature1', 'Feature2','Feature3','Target']) </code>...
<p>You could use pandas <code>corr</code> on each column:</p> <pre><code>df.drop("Target", axis=1).apply(lambda x: x.corr(df.Target)) </code></pre>
python|numpy|dataframe|correlation
17
5,258
46,349,840
Dropping rows on a condition
<p>I'm working with an order process data set. Which contains two columns, Order_ID and Transaction_Phase. In the order process, there can be a few steps before an order is first booked and after it is booked. </p> <p>In my current problem, I want to keep all the rows until it hits approved. Any other rows after the a...
<pre><code>df[df.index&lt;=df.groupby('Order_ID')['Tranaction_Phase'].transform(lambda x:x.index[x=='Dealapproved'])] Out[649]: Order_ID Tranaction_Phase 0 529334333 Quote 1 529334333 Dealapproved 3 470660845 Quote 4 470660845 Dealapproved </code></pre>
python|pandas|analysis
2
5,259
46,536,971
How to use groups parameter in PyTorch conv2d function
<p>I am trying to compute a per-channel gradient image in PyTorch. To do this, I want to perform a standard 2D convolution with a Sobel filter on each channel of an image. I am using the <a href="http://pytorch.org/docs/0.1.12/nn.html#torch.nn.functional.conv2d" rel="noreferrer"><code>torch.nn.functional.conv2d</code><...
<p>If you want to apply a per-channel convolution then your <code>out-channel</code> should be the same as your <code>in-channel</code>. This is expected, considering each of your input channels creates a separate output channel that it corresponds to. </p> <p>In short, this will work</p> <pre><code>import torch impo...
convolution|pytorch
14
5,260
46,566,731
Error while installing tensorflow on Rstudio
<p>I´m trying to install Tensorflow on Rstudio windows.</p> <p>I have installed, Anaconda 3, all my R librarys are updated, and load library Keras on R</p> <p>When I try to install, using:</p> <pre><code>install_keras() </code></pre> <p>The installation was not completed and an error message prompt: Error: Error 2 ...
<p>I got the same error. I think it is because tensorflow is already installed through the install of keras. If I try to install keras again, I get the error that keras and tensorflow can only be installed in a fresh R session, where they had not been installed before. Otherwise there might be dll error. So it appears ...
r|tensorflow|keras|rstudio
0
5,261
46,226,037
How do I multiply a tensor by a matrix
<p>So I have array <code>A</code> with shape <code>[32,60,60]</code> and array <code>B</code> with shape <code>[32,60]</code>. The first dimension is the batch size, so the first dimension is independent. What I want to do is a simple matrix by vector multiplication. So for each sample in <code>A</code> I want to multi...
<p>It seems you are trying to <code>sum-reduce</code> the last axes from the two input arrays with that <code>matrix-multiplication</code>. So, with <code>np.einsum</code>, it would be -</p> <pre><code>np.einsum('ijk,ik-&gt;ij',A,B) </code></pre> <p>For <code>tensorflow</code>, we can use <a href="https://www.tensorf...
python|numpy|tensorflow
2
5,262
58,468,182
Tensorflow: Error when calling optimizer to minimize loss
<p>I am trying to get tensorflow to minimize a loss function with respect to a variable, however, I keep getting an error and I am unsure of the cause. I have created a minimal example:</p> <pre><code>import tensorflow as tf def loss_func(x, target): return tf.pow(x - target, 2) x = tf.Variable(initial_value=1....
<p>I don't quite understand what you are doing. It appears you are trying to optimize x towards 10. If this is the case you can just assign it to 10. Alternatively, if you will have more than one target, you can take an some sort average of those targets and assign x to that. I believe the problem in the code is that t...
python|tensorflow
0
5,263
58,194,951
OSError: SavedModel file does not exist at: /content\model\2016/{saved_model.pbtxt|saved_model.pb}
<p>I ran the code </p> <pre><code>export_path=os.getcwd()+'\\model\\'+'2016' with tf.Session(graph=tf.Graph()) as sess: tf.saved_model.loader.load(sess, ["myTag"], export_path) graph = tf.get_default_graph() # print(graph.get_operations()) input = graph.get_tensor_by_name('input:0') outpu...
<p>You should avoid using a fixed character as directory separator (like <code>\</code> in your example), as that character differs between operating systems (see <a href="https://docs.python.org/3/library/os.html?highlight=os%20sep#os.sep" rel="noreferrer">os.sep</a>). You might want to use <a href="https://docs.pytho...
python|tensorflow|google-colaboratory
5
5,264
69,001,440
Matplotlib pcolormesh with time on x-axis and boolean true/false as the colouring
<p>I want a plot with the xticklabels as datetime-like objects and the colors to be <code>True</code>/<code>False</code> (<code>1</code>,<code>0</code>) depending on whether that time has been sampled.</p> <p>The data I am working with looks like this:</p> <pre class="lang-py prettyprint-override"><code>import numpy as...
<p><a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.pcolormesh.html" rel="nofollow noreferrer"><strong><code>matplotlib.pyplot.pcolormesh</code></strong></a> optionally requires <code>X</code> and <code>Y</code> arrays which specify coordinates of the corners of quadrilaterals of the pcolormesh. So ...
python|pandas|numpy|datetime|matplotlib
2
5,265
68,934,531
How to replace column values with results from for loop?
<p>my dataframe looks something like this:</p> <pre><code>teams x_in_mins y_in_mins z_in_mins team_a 50 120 24 team_b 80 66 30 team_c 30 90 70 </code></pre> <p>I want to convert integer columns (which represent total minutes) to time form...
<p>You can use <code>transform</code>:</p> <pre><code>def foo(col): return pd.to_timedelta(col, unit='min').astype(str).str.rsplit().str[-1] df[[&quot;x_in_mins&quot;,&quot;y_in_mins&quot;,&quot;z_in_mins&quot;]].transform(foo) </code></pre>
python|pandas|dataframe|for-loop
3
5,266
44,389,341
how to see summary image of former steps in tensorboard
<p>I'm using tensorboard to visualize the image(CelebA) generated by dcgan Specifically, I created a writer and image summary with:</p> <pre><code>tf.summary.image('generated', image_output) summary_op = tf.summary.merge_all() writer = tf.summary.FileWriter(logdir, graph) summary = sess.run(summary_op) </code></pre> ...
<p>The issue that you have raised was common enough to warrant a <a href="https://github.com/tensorflow/tensorflow/issues/4721" rel="nofollow noreferrer">feature request</a> several months ago that was rolled into TensorFlow 1.1.0.</p> <p>A small sliding bar appears below each image summary in Tensorboard with which y...
tensorflow|tensorboard
1
5,267
44,820,115
Remove rows if any of a set of values are null
<p>I have a DataFrame with lots of columns, and I want to remove rows where the values for <em>some</em> columns are null. I know how to do this with one column: </p> <pre><code>df = df[df['Column'] != ''] </code></pre> <p>I want to do this with a set of columns, like so:</p> <pre><code>df = df['' not in [df['Column...
<p>If values are empty strings create subset and for all <code>True</code>s per row add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.all.html" rel="nofollow noreferrer"><code>all</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html" re...
python|pandas
3
5,268
61,172,226
Memory leak with H20 in Python Web Application
<p>My decision engine is built on the python-flask framework with uWSGI and Nginx. As part of evaluating a user through an HTTP request, I run scorecards with h2o==3.20.0.7 to generate a score to make a decision on the user. Given below some clarity on how I'm using h2o in my app</p> <pre><code>h2o.init() # initializ...
<p>The approach you describe is different from what I would recommend.</p> <p>For simplicity's sake (ignoring multiple servers and load balancing) I am going to draw your setup's architecture diagram like this:</p> <pre><code>[Client HTTP program] -&gt; [python flask app] -&gt; [java scoring backend] </code></pre> <...
python|pandas|h2o
1
5,269
60,841,235
How to prepare my dataset(Not Images) to implement FedAVG on Tensorflow Federated?
<p>I want to train a federated model with the FedAvg Algorithm on TFF (Tensorflow Federated) using a 3-channel (X, Y, Z) accelerometer dataset with a time frame length of 128.</p> <p>My goal is to train a federated model using </p> <pre><code>tff.learning.from_keras_model </code></pre> <p>The guides on the TensorFlo...
<p>First, for federated learning the dataset will need to be partitioned by user/participant. Does the dataset have a partitioning of the accelerometer readings and labels by user? If not, this is probably a task suited from standard centralized learning rather than federated learning.</p> <p>If there is a user partit...
python|deep-learning|tensorflow-federated
0
5,270
71,739,162
Basic question on transforming object into float
<p>I am new at programming and I'm having this trouble:</p> <p><code>y = pd.to_numeric(final_list\[1\])</code></p> <blockquote> <p>Traceback (most recent call last):</p> <p>File pandas_libs\lib.pyx:2315 in pandas._libs.lib.maybe_convert_numeric</p> <p>ValueError: Unable to parse string &quot;- &quot;</p> <p>During hand...
<p>One of the solutions is to convert such non-convertible cases to NaN:</p> <pre><code>y = pd.to_numeric(final_list[1], errors='coerce') </code></pre>
python|pandas|dataset|transformation
0
5,271
71,679,375
Pandas dataFrame : find if the current value is greater than values of last 10 rows
<p>Consider below dataFrame. I want to calculate if the current value of price column is greater than last 10 values. I was thinking to use shift, but not sure how to use for last 10 rows.</p> <pre><code> price 220 3.337 221 3.320 222 3.290 223 3.291 224 3.312 225 3.255 226 3.216 227 3.245 228 3.275 229 3.282 230 3....
<p>You can use <code>rolling</code>+<code>max</code> to get the max of the last 10 rows, if greater than it, then it's greater or equal than all (including self, thus the +1):</p> <pre><code>df['isGreater'] = df['price'].ge(df['price'].rolling(10+1).max()) </code></pre> <p>NB. technically if you really want to compare ...
pandas|dataframe
1
5,272
71,588,301
how to manipulate column header strings in a dataframe
<p>how to remove part of string &quot;test_&quot; in column headers. image the dataframe has many columns, so df.rename(columns={&quot;test_Stock B&quot;:&quot;Stock B&quot;}) is not the solution i am looking for!</p> <pre><code> import pandas as pd data = {'Stock A':[1, 1, 1, 1], 'test_Stock B':[3, 3, 4, 4...
<p>You can redefine the columns via list comprehension with:</p> <pre><code>df.columns = [x.replace(&quot;test_&quot;,&quot;&quot;) for x in df] </code></pre> <p>This outputs:</p> <pre><code> Stock A Stock B Stock C Stock D 0 1 3 4 2 1 1 3 4 2 2 1 ...
python|pandas|dataframe|header
3
5,273
42,260,699
pandas.DataFrame: how to applymap() with external arguments
<p>SEE UPDATE AT THE END FOR A MUCH CLEARER DESCRIPTION.</p> <p>According to <a href="http://pandas.pydata.org/pandas-docs/version/0.18.1/generated/pandas.DataFrame.apply.html" rel="nofollow noreferrer">http://pandas.pydata.org/pandas-docs/version/0.18.1/generated/pandas.DataFrame.apply.html</a> you can pass external ...
<p>You can use it:</p> <pre><code>def matchValue(value, dictionary): return dictionary[value] a = {'first': 1, 'second': 2} b = {'first': 10, 'second': 20} df['column'] = df['column'].map(lambda x: matchValue(x, a)) </code></pre>
python|pandas|dataframe
3
5,274
42,578,133
Is there an enaml widget to display a table?
<p>I would like to display a (numeric and/or textual) table inside a Python GUI built with enaml, but surprisingly there seem to be no enaml widget for that.</p> <p>Some years ago, <a href="https://groups.google.com/forum/#!topic/enaml/soUKRvXT_BU" rel="nofollow noreferrer">here</a>, they said there would have been so...
<p>You can either use RawWidget to use your own Qt TableView or have a look at an implementation here: <a href="https://github.com/frmdstryr/enamlx" rel="nofollow noreferrer">https://github.com/frmdstryr/enamlx</a></p>
python-2.7|user-interface|pandas|dataframe|enaml
1
5,275
69,916,993
define range in pandas column based on define input from list
<p>I have one data frame, wherein I need to apply range in one column, based on the list provided, I am able to achieve results using fixed values but input values will be dynamic in a list format and the range will be based on input.</p> <p>MY Data frame looks like below:</p> <pre><code>import pandas as pd rangelist=[...
<p>I would recommend <code>pd.cut</code> for this:</p> <pre><code>sampledf['Category'] = pd.cut(sampledf['Result'], [-np.inf] + sorted(rangelist) + [np.inf]) </code></pre> <p>Output:</p> <pre><code> Result Category 0 75 (70.0, 90.0] 1 85 (70.0, 90.0] 2 95 (90...
python-3.x|pandas|list|function
0
5,276
69,807,435
Export dataframe into different sheets in an Excel without deleting the existing ones
<p>I have a dataframe df1 and I want to export it to an Excel which already has some sheets.</p> <p>I tried using:</p> <pre><code>writer = pd.ExcelWriter(file_path, engine = 'xlsxwriter') df1.to_excel(writer, sheet_name = 'test1', index = False) writer.save() </code></pre> <p>This code deletes the existing sheets, and...
<p>Check out the documentation <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html</a> there is an append mode for ExcelWriter</p>
python|pandas
1
5,277
72,268,602
Can't pivot or transfer from long to wide format?
<p>I have the following csv <a href="https://justpaste.it/8spqq" rel="nofollow noreferrer">https://justpaste.it/8spqq</a></p> <p>I am trying to pivot it and transfer from long to wide format.</p> <pre><code>import pandas as pd pd.DataFrame(pd.pivot_table(df, values='data_point_value', ...
<p>So, with data you posted:</p> <pre class="lang-py prettyprint-override"><code>df = pd.read_table(&quot;8spqq.txt&quot;, sep=&quot;,&quot;).drop(columns=&quot;Unnamed: 0&quot;) print(df) # [598 rows x 3 columns] </code></pre> <p>The problem comes from the fact that the following values in <code>data_point_key</code>...
python-3.x|pandas|dataframe|pivot|pivot-table
1
5,278
72,446,227
Pandas Timeseries Plotting from Multi Index Dataframe
<p>I have a multi index data frame which looks like:</p> <pre><code> col1 col2 col3 timestamp type class 1653385980729 audio dc 3 10 1 ec 5 7 2 ...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unstack.html" rel="nofollow noreferrer"><code>Series.unstack</code></a> by second and third level with flatten <code>MultiIndex in columns</code>:</p> <pre><code>df1 = df['col1'].unstack([1,2]) df1.columns = [f'{a}/{b}' for a, b in ...
python|pandas|dataframe|matplotlib
2
5,279
50,324,416
Insert new rows in pandas dataframe, altering some timestamps while keeping other data
<pre><code>1 2016-10-01 01:00:00 1014.7 23.6 2 2016-10-01 02:00:00 1014.3 23.6 3 2016-10-01 03:00:00 1014.3 23.8 4 2016-10-01 04:00:00 1014.3 23.8 5 2016-10-01 05:00:00 1014.4 24.3 6 2016-10-01 06:00:00 1014.9 ...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow noreferrer"><code>resample</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.resample.Resampler.ffill.html" rel="nofollow noreferrer"><code>ffill</cod...
python|pandas
3
5,280
50,518,591
CNN: why it is making no difference whether i measure accuracy by logits or softmax layer?
<p>While measuring the accuracy of a CNN i understand that i should use the output of the softmax layer(Predicted label) to target label. But even if i compare logits (which are the output of last fully connected layer, as per my understanding) with target labels, i get almost same accuracy. Here is the relevant part o...
<p>In fact the accuracy should be exactly equal. Taking the argmax of an array of logits should return the same as taking the argmax of the softmax of that array. This is because the softmax function maps larger logits to be closer to 1 in a strictly increasing way.</p> <p>The softmax function takes a set of outputs (...
python|tensorflow|machine-learning|deep-learning
3
5,281
45,687,731
How to do intersection match between 2 DataFrames in Pandas?
<p>Assume exists 2 <strong>DataFrames</strong> <code>A</code> and <code>B</code> like following</p> <p><code>A</code>:</p> <pre><code>a A b B c C </code></pre> <p><code>B</code>:</p> <pre><code>1 2 3 4 </code></pre> <p>How to produce <code>C</code> <strong>DataFrame</strong> like</p> <pre><code>a A 1 2 a A 3 ...
<p>First all values has to be unique in each <code>DataFrame</code>.</p> <p>I think you need <code>product</code>:</p> <pre><code>from itertools import product A = pd.DataFrame({'a':list('abc')}) B = pd.DataFrame({'a':[1,2]}) C = pd.DataFrame(list(product(A['a'], B['a']))) print (C) 0 1 0 a 1 1 a 2 2 b 1...
pandas|dataframe
2
5,282
62,623,399
Grouping/identifying cumulative sum (Looping in pandas dataframe)
<p>I have a data frame like below :</p> <pre><code>df = pd.DataFrame({'Letter': ['C','B','A','D','E','H','G'], 'Number': [5,5,5,7,7,10,10], 'Value of Letter': [10,15,15,25,20,30,25], 'Amount': [100,'','',30,'',54,''], 'Realisation Index': [1,3,...
<p>Let do it</p> <pre><code>df.Amount=pd.to_numeric(df.Amount,errors='coerce') df['New']=df.sort_values('Realisation Index').groupby('Number').apply(lambda x : max(x['Amount'])-x['Value of Letter'].cumsum()).reset_index(level=0,drop=True) df Letter Number Value of Letter Amount Realisation Index New 0 C ...
python|pandas
0
5,283
54,522,901
Add missing datetime columns to grouped dataframe
<p>Is it possible to add missing date columns from created date_range to grouped dataframe df without for loop and fill zeros as missing values? date_range has 7 date elements. df has 4 date columns. So how to add 3 missing columns to df? </p> <pre><code>import pandas as pd from datetime import datetime start = datet...
<p>Thanks Sina Shabani for clue to making date columns as rows. And in this situation more suitable setting date as index and using .reindex appeared</p> <pre><code>df = (df.groupby(['date', 'name'])['name'] .size() .reset_index(name='count') .pivot(index='date', columns='name', values='count')...
python|pandas
1
5,284
54,602,005
Create column based on another column value, based on assigning value to sets of string values from the input column
<p>My problem seems like it must have a simple solution, but I am unable to solve it. I've tried <code>.loc</code> , <code>np.where</code> and <code>df.apply</code>. </p> <pre><code>#input datetime dty dtx status 2018-09-16 04:38:17 0.0 0.099854 F-On 2018-09-16 04:38:18 0.0 0.100098 F-On 201...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer">map</a>:</p> <pre><code>lookup = {'F-On' : 'On', 'S-On' : 'On', 'circ':'fooON', 'TH':'fooON', 'circInS':'fooON', 'R':'R', 'S':'S'} df['grouped_status'] = df.status.map(lookup) </code></pre> <p>...
python|python-3.x|pandas
1
5,285
54,673,038
update / merge and update a subset of columns pandas
<p>I have <code>df1</code>:</p> <pre><code> ColA ColB ID1 ColC ID2 0 a 1.0 45.0 xyz 23.0 1 b 2.0 56.0 abc 24.0 2 c 3.0 34.0 qwerty 28.0 3 d 4.0 34.0 wer 33.0 4 e NaN NaN NaN NaN </code></pre> <p><code>df2</code>:</p> <pre><code> ColA ColB ID1 ColC ...
<p>Use <code>merge</code> with <code>right</code> join and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow noreferrer"><code>combine_first</code></a>:</p> <pre><code>choice= ['ColA','ColB'] joined = ['ID1','ID2'] c = choice + joined df3 = df1[c].m...
python|python-3.x|pandas
3
5,286
54,299,762
How I can convert .tflite model to a .pb frozen graph in Tensorflow?
<p>At the beginning, I have the frozen graph .pb file of a model. I converted it to .tflite and post-training quantized this .tflite model. In the end, I would like to convert this quantized .tflite model into a .pb frozen graph. How can I achieve this last step?</p> <p>I have searched a lot but didn't find any soluti...
<p>Try run toco with flags</p> <pre><code>toco --input_format=TFLITE --output_format=TENSORFLOW_GRAPHDEF ... </code></pre> <p>This may not work with some new operations of tflite</p>
tensorflow|tensorflow-lite
2
5,287
54,411,896
finding and replacing strings with numbers only within a pandas dataframe
<p>I am trying to replace the strings that contain numbers with another string (an empty one in this case) within a pandas DataFrame.</p> <p>I tried with the .replace method and a regex expression:</p> <pre><code># creating dummy dataframe data = pd.DataFrame({'A': ['test' for _ in range(5)]}) # the value that shoul...
<p>You can use Boolean indexing via <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html" rel="nofollow noreferrer"><code>pd.Series.str.contains</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" rel="nofollow nor...
python|python-3.x|string|pandas|dataframe
2
5,288
54,352,837
Python - Change Column Names, Merge and Re-Order a dataframe
<p>I have two DataFrames - DataFrameA and DataFrameB</p> <p>DataFrameA</p> <pre><code>ID ColA ColB ColC 1 12 23 40 2 21 24 45 3 23 31 50 </code></pre> <p>DataFrameB</p> <pre><code>ID ColA ColB ColC 1 21 23 40 2 20 44 45 3 29 51 70 4 49 51 70 </c...
<p>Using </p> <pre><code>yourdf=dfa.merge(dfb.add_prefix('BBBBB.'),left_on='ID',right_on='BBBBB.ID') yourdf Out[219]: ID ColA ColB ... BBBBB.ColA BBBBB.ColB BBBBB.ColC 0 1 12 23 ... 21 23 40 1 2 21 24 ... 20 44 45 2 ...
python|pandas
5
5,289
73,840,787
Finding the third Friday for an expiration date using pandas datetime
<p>I have a simple definition which finds the third friday of the month. I use this function to populate the dataframe for the third fridays and that part works fine.</p> <p>The trouble I'm having is finding the third friday for an expiration_date that doesn't fall on a third friday.</p> <p>This is my code simplified:...
<p>You could add these additional lines of code (to replace <code>df[&quot;monthly_exp&quot;] = third_fridays[['expiration_date']]</code>:</p> <pre><code># DataFrame of fridays from minimum expiration_date to 30 days after last fri_3s = pd.DataFrame(pd.date_range(df[&quot;expiration_date&quot;].min(), ...
python|pandas|dataframe
1
5,290
73,562,112
How to find first and last time for every day for each value
<p>I am trying to figure out a way to find the first and last time stamp for each asset within a dataframe for each day. For example, I have this data frame:</p> <pre><code>import pandas as pd data = { 'Date':['2022-01-01','2022-01-01','2022-01-01','2022-01-01','2022-01-01','2022-01-01', '2022-01-01' ,'2...
<pre><code>import pandas as pd data = { 'Date':['2022-01-01','2022-01-01','2022-01-01','2022-01-01','2022-01-01','2022-01-01', '2022-01-01' ,'2022-01-02','2022-01-02','2022-01-02','2022-01-02','2022-01-02','2022-01-02', '2022-01-02','2022-01-02','2022-01-03','2022-01-03','2022-01-03','2022-01...
python|python-3.x|pandas|time-series|data-science
0
5,291
73,550,681
Extract strings values from DataFrame column
<p>I have the following DataFrame:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Student</th> <th>food</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>R0100000</td> </tr> <tr> <td>2</td> <td>R0200000</td> </tr> <tr> <td>3</td> <td>R0300000</td> </tr> <tr> <td>4</td> <td>R0400000</td> </tr...
<p>This works for me:</p> <p><code>s = df[df.Student==1]['food'][0]</code></p> <p><code>s.strip()</code></p>
python|pandas|numpy
2
5,292
71,370,318
How to preserve order in python while comparing images from 2 different directories?
<p>I was comparing images from 2 different directories. I write code but the sequence of comparing is this</p> <p>{ 0,1,10,11,12,...,19,2,20,21,..} not like {0,1,2,3,...,9,10,11,12,...}</p> <pre><code>L1 = os.listdir(&quot;D:\\image_dir_1\\&quot;) image_list_1 = list() image_list_2 = list() final_i = list() final_j = ...
<p>You have to sort the <strong>L1</strong> list:</p> <pre><code>L1 = sorted(os.listdir(&quot;D:\\image_dir_1\\&quot;), key=lambda str: int(str[:-4].strip())) </code></pre> <p>The issue is that without sorting them by their actual int value, you have the files names sorted lexicographically.</p>
python|python-3.x|pandas|list|glob
1
5,293
71,094,366
How to apply a function to specific columns of a pandas dataframe?
<p>I would like to apply a function to specific columns of a pandas data frame. Here is an illustration:</p> <pre><code># import modules from pandas_datareader import data as pdr # import parameters start = &quot;2020-01-01&quot; end = &quot;2021-01-01&quot; symbols = [&quot;AAPL&quot;] # get the data data = pdr.get_...
<p>I think the problem is that you are not assigning the return of the <code>mult</code> functions to any variable.</p> <p>One way to achieve what you want is:</p> <pre><code># import modules from pandas_datareader import data as pdr # import parameters start = &quot;2020-01-01&quot; end = &quot;2021-01-01&quot; symbo...
python|pandas|dataframe
2
5,294
71,186,025
Outputting pandas timestamp to tuple with just month and day
<p>I have a pandas dataframe with a timestamp field which I have successfully to converted to datetime format and now I want to output just the month and day as a tuple for the first date value in the data frame. It is for a test and the output must not have leading zeros. I ahve tried a number of things but I cannot f...
<p><strong>Update</strong></p> <p>If you want to extract month and day from the first record (<em>solution proposed by @FObersteiner</em>)</p> <pre><code>&gt;&gt;&gt; df['trans_timestamp'].iloc[0].timetuple()[1:3] (5, 4) </code></pre> <p>If you want extract all month and day from your dataframe, use:</p> <pre><code># S...
pandas|dataframe|datetime
1
5,295
52,408,867
Angles Comparasion Loss Function for Tensorflow in Python
<p>I have a CNN, takes in an image, outs a single value - an angle. The data set is made of (x = image, y = angle) couples.</p> <p>I want the network for each image, to predict an angle.</p> <p>I have found this suggestion: <a href="https://stats.stackexchange.com/a/218547">https://stats.stackexchange.com/a/218547</a...
<p>That is going in the right direction, but the idea is that, instead of having <code>MyCNN</code> produce a single angle value for each example, produce two values. So if the return value of <code>MyCNN</code> is currently something with shape like <code>(None,)</code> or <code>(None, 1)</code>, you should change it ...
python|tensorflow|conv-neural-network|angle|loss-function
1
5,296
52,103,441
Summing multiple lists stored in dataframe
<p>I have a dataframe with multiple lists stored as:</p> <p>I have two dataframes as:</p> <pre><code>df1.ix[1:3] DateTime Col1 Col2 2018-01-02 [1, 2] [11, 21] 2018-01-03 [3, 4] [31, 41] </code></pre> <p>I want to sum the lists in the df1 to get:</p> <pre><code>DateTime sumCol 2018-01-02 ...
<p>Using a list comprehension and <code>np.array</code>:</p> <pre><code>df.assign(sumCol=[np.array(x) + np.array(y) for x, y in zip(df.Col1, df.Col2)]) </code></pre> <p></p> <pre><code> DateTime Col1 Col2 sumCol 0 2018-01-02 [1, 2] [11, 21] [12, 23] 1 2018-01-03 [3, 4] [31, 41] [34, 45] </code...
python|python-3.x|pandas|dataframe
3
5,297
52,252,449
cannot import name 'multiarray' in numpy with python3
<p>I usually work with python 2.7 but this time i have to test a script in python3.</p> <p>It is already installed on my computer, however when i start "python3", then go "import numpy", it show me "cannot import name 'multiarray'.</p> <p>I even installed anaconda3 to test, but nothing happens</p> <pre><code>myName:...
<p>I had the same problem, took me several hours to figure it out. </p> <p>In my case, the <code>PYTHONPATH</code> was set to <code>/usr/lib/python2.6/dist-packages/</code> changing it to <code>/Users/xxx/miniconda3/lib/python3.7/site-packages/</code> resolved the issue. Good luck. </p>
python|python-3.x|python-2.7|numpy|installation
2
5,298
60,467,807
Dask progress during task
<p>With dask dataframe using<br> <code>df = dask.dataframe.from_pandas(df, npartitions=5) series = df.apply(func) future = client.compute(series) progress(future)</code></p> <p>In a jupyter notebook I can see progress bar for how many apply() calls completed per partition (e.g 2/5).<br> Is there a way for dask to re...
<p>If you mean, how complete each call of <code>func()</code> is, then no, there is no way for Dask to know that. Dask calls python functions which run in their own python thread (python threads cannot be interrupted by another thread), and Dask only knows whether the call is done or not.</p> <p>You could perhaps conc...
python|pandas|dask|tqdm|dask-dataframe
0
5,299
60,650,617
Error while running profiling report using pandas, giving me an error "TypeError: describe_boolean_1d() got an unexpected keyword argument 'title'"
<p>I am using the code below</p> <pre><code>profile = ProfileReport(df, title='Pandas Profiling Report', html={'style':{'full_width':True}}) </code></pre> <p>to run a profile report but getting this error</p> <pre><code>"TypeError: describe_boolean_1d() got an unexpected keyword argument 'title'" </code></pre> <p>A...
<p>I have conda on my machine, so first tried installing pandas-profiling with conda, but had the same error as you.</p> <p>I have removed it: <code>conda remove pandas-profiling</code> and then reinstall it with pip: <code>pip install pandas-profiling[notebook,html]</code></p> <p>And it worked fine.</p> <p>Note: Th...
pandas
3