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 |
|---|---|---|---|---|---|---|
372,300 | 18,603,270 | Progress indicator during pandas operations | <p>I regularly perform pandas operations on data frames in excess of 15 million or so rows and I'd love to have access to a progress indicator for particular operations.</p>
<p>Does a text based progress indicator for pandas split-apply-combine operations exist?</p>
<p>For example, in something like:</p>
<pre><code>... | <p>Due to popular demand, I've added <code>pandas</code> support in <code>tqdm</code> (<code>pip install "tqdm>=4.9.0"</code>). Unlike the other answers, this <strong>will not noticeably slow pandas down</strong> -- here's an example for <code>DataFrameGroupBy.progress_apply</code>:</p>
<pre><code>import p... | python|pandas|ipython | 587 |
372,301 | 61,616,735 | How to deal with school grades that are labelled '0' because of student grouping according to ability in a Neural Network? | <p>I'm binary classifying student performance at university with Keras and Tensorflow, amongst others, with two inputs 'Math_A' (high school grade in course Mathematics A) & 'Math_B' (high school grade in course Mathematics B).</p>
<p><a href="https://i.stack.imgur.com/EWocY.png" rel="nofollow noreferrer">find an e... | <p>A well trained neural network will be able dechiper this. If in doubt, use a recurrent LSTM algorithm and train over at least 10 epoches of substantial differential data.</p> | python|tensorflow|keras|neural-network|prediction | 0 |
372,302 | 61,950,970 | Pytorch: LSTM does not learn | <p>I'm having a hard time training my LSTM model, it does not seem to learn at all. The training loss is hardly decreasing and accuracy changes for very simple models (1 layer, few lstm units) but eventually gets stuck at 45%, just like the more complex models right from the start. Most of the times, it only predicts o... | <p>You are saying that you use <a href="https://pytorch.org/docs/stable/nn.html#torch.nn.CrossEntropyLoss" rel="nofollow noreferrer"><code>nn.CrossEntropyLoss</code></a> as the loss function, which applies log-softmax, but you are also applying <code>nn.Softmax</code> in the model.</p>
<p><code>nn.CrossEntropyLoss</co... | python|pytorch|lstm | 0 |
372,303 | 61,792,639 | How to sort Data Frame elements on external indexing in Python | <p>I would like to find a simple solution for a sorting problem with data frame. After carefully analyzing all the posts on the topic, I realized that despite several pretty cumbersome ways (extracting indices, adding columns, re-indexing, etc...) there is no simple solution for my problem. So maybe somebody have an il... | <p>So I found a workaround, which is pretty simple. It worked fine for my particular example, but still I'm sure a more elegant solution exists. It is done in 4 separate steps:</p>
<ol>
<li><p>Numpy array (on which the sorting has to be done) is converted to DataFrame1. By converting to DataFrame1, an ascending index ... | python|pandas|dataframe|sorting | 0 |
372,304 | 61,744,204 | Extract multiple substring matching pattern into columns | <p>My pandas dataframe has string like this</p>
<pre><code>A=1;B=3;C=c6
A=2;C=c7;D=8
</code></pre>
<p>I want to extract the value in each field into separate columns, and then use the field name as columns like this</p>
<pre><code>A B C D
1 3 c6 NaN
2 NaN c7 8
</code></pre>
<p>I tried split <... | <p>I think here is possible use split in list comprehension - first by <code>;</code> and then by <code>=</code> and convert it to dictionary, so last is possible use <code>DataFrame</code> constructor:</p>
<pre><code>print (df)
col
0 A=1;B=3;C=c6
1 A=2;C=c7;D=8
L = [dict([y.split('=') for y in x.split(... | python|regex|pandas | 5 |
372,305 | 61,717,161 | Save a Hash Value as a Tensor in pytorch | <p>I have a dataset that contains identifiers that are saved as string.</p>
<p>I want to create a neural net that gets amongst other things these identifiers as labels and then checks if two identifier are exactly the same. If they are the same then I want to increase the loss if the network predicts wrong values.</p>... | <p>The problem is that <code>int(string_id, 16)</code> converts your 32 char long hash into a <em>single</em> integer. This is really a very VERY large number.<br>
You can, instead, convert it to an array:</p>
<pre class="lang-py prettyprint-override"><code>tensor_id = torch.tensor([int(c, 16) for c in string_id])
</c... | python|pytorch|tensor | 1 |
372,306 | 61,862,067 | Export a dictionary of dataframes to JSON with Datetime index | <p>I have a dictionary of dataframes each one with a Datetime Index, as follows:</p>
<pre><code>z = {'a': df1, 'b': df2, 'c': df3}
print(df1.head(3))
Sales Pre-tax_Income ... Profit_Margin Gross_Margin
2013-02-28 1.909350e+07 -2.557250e+06 ... -0.220741 -0.133933
2013-05-31 6.909... | <p>You need to change this </p>
<pre><code>data_dict = {
key: z[key].to_dict(orient='records')
for key in z.keys()}
</code></pre>
<p>to this</p>
<pre><code>data_dict = {
key: {k : v for k, v in
zip(z[key].index.values, z[key].to_dict(orient='records'))}
for key in z.keys()}
</code></pre> | python|json|pandas | 1 |
372,307 | 61,914,105 | Eigenanalysis of complex hermitian matrix: different phase angles for EIG and EIGH | <p>I understand that eigenvectors are only defined up to a multiplicative constant. As far as I see all <code>numpy</code> algorithms (e.g. <code>linalg.eig</code>, <code>linalg.eigh</code>, <code>linalg.svd</code>) yield identical eigenvectors for <strong>real matrices</strong>, so apparently they use the same normali... | <p>As you say, the eigenvalue problem only fixes the eigenvectors up to a scalar <code>x</code>. Transforming an eigenvector <code>v</code> as <code>v = v*x</code> does not change its status as an eigenvector.</p>
<p>There is an "obvious" way to normalize the vectors (according to the euclidean inner product ... | python|numpy|matrix|eigenvector | 0 |
372,308 | 61,868,419 | Predicting the class of image with CNN | <p>I am trying to predict the class of single image on trained model, but I am getting a strange output, so this is my code:</p>
<pre><code>from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
import matplotlib.pyplot as plt
import numpy as np
import os
def load_image(img_p... | <p>with <code>model.predict(new_image)</code> you obtain the probability of each test image to belong to a particular class</p>
<p>to get the output class, you need to select the class with the max probability predicted:</p>
<pre><code>np.argmax(pred, axis=1)
</code></pre> | tensorflow|keras|prediction | 1 |
372,309 | 61,879,105 | How to filter using Pandasql | <p>I have below query to select rows as per the <code>where</code> condition;</p>
<pre><code>top4_hr_visits = pysqldf("SELECT room_name, hour, COUNT(DISTINCT user) AS user_cnt FROM user_data
WHERE room_name ='Emilio's Room' OR room_name= 'Azalea's Room'
GROUP BY room_na... | <p><strong>Single quotes are escaped by doubling them up</strong>, just as you've shown us in your example replace single quote by adding another one</p>
<pre><code>"SELECT room_name, hour, COUNT(DISTINCT user) AS user_cnt FROM user_data
WHERE room_name ='Emilio''s Room' OR room_name= 'Azal... | pandas|pandasql | 1 |
372,310 | 61,779,880 | Is it possible to load a non-AutoML trained tflite model for use with FirebaseAutoMLLocalModel on Android? | <p>It works well if I download the model from Firebase but it doesn't work if I try to replace the model with a manually trained model in TF which was then converted to tf-lite.</p>
<p>Do you think it's a limitation of AutoML or just something I missed in the conversion process?</p>
<p>Here is the error message:</p>
... | <p>Think it is a problem in the conversion/implementation in Android Studio.
I got the same problem but could not solve it.</p>
<p>I tested it with a .tflite from teachable machine and there were no problem...</p> | android|firebase|google-cloud-automl|tensorflow-lite | 0 |
372,311 | 61,637,447 | Validation set augmentations PyTorch example | <p>In <a href="https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html" rel="nofollow noreferrer">this</a> PyTorch vision example for transfer learning, they are performing validation set augmentations, and I can't figure out why.</p>
<pre><code># Just normalization for validation
data_transforms = {
... | <p>To clarify, <em>random</em> data augmentation is only allowed on the training set. You can apply data augmentation to the validation and test sets provided that none of the augmentations are random. You will see this clearly in the example you provided. </p>
<p>The training set uses many random augmentations (augme... | image|deep-learning|computer-vision|pytorch|data-augmentation | 1 |
372,312 | 61,999,079 | How to convert pandas df to dictionary with lists nested in the list? | <p>I recently started working with python and I am now working with API request. I need to convert dataframe to a dictionary of lists nested in the list. </p>
<p><strong>How to convert</strong> <code>df</code>:</p>
<pre><code>data = {'x': ['15.0', '42.2','43.4','89.0','45.8'],
'y': ['10.1', '42.3','43.5','5.... | <p>Convert values to numpy array by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html" rel="nofollow noreferrer"><code>DataFrame.to_numpy</code></a> and then to list:</p>
<pre><code>d = {"Points":df.to_numpy().tolist()}
#if there is more columns
#d = {"Points":df[['x','y... | python|json|pandas|dictionary | 2 |
372,313 | 61,848,671 | How to convert strings in a Pandas Dataframe to a list or an array of characters? | <p>I have a dataframe called <strong>data</strong>, a column of which contains strings. I want to extract the characters from the strings because my goal is to one-hot encode them and make the usable for classification. The column containing the strings is stored in <strong>predictors</strong> as follows:</p>
<pre><co... | <p>You can convert values to letters by list comprehension with <code>list</code> and then to <code>array</code> if necessary:</p>
<pre><code>predictors = np.array([list(x) for x in data])
</code></pre>
<p>Or convert column <code>predictors['Sequence']</code>:</p>
<pre><code>a = np.array([list(x) for x in predictors... | python|string|pandas|list|one-hot-encoding | 3 |
372,314 | 61,639,016 | Classification of the same image gives different result | <p>I'm trying to classify 3D images using CNN with Tensorflow and I think something is wrong. After training and validation, I'm using a saved model to classify a single image. When I classify this image, it gives me different results each time I try.</p>
<p>Example:</p>
<pre><code>1st try:
input: Picture of a 3D ... | <p>You first restore your variables, and then after you initialize your variables to random values:</p>
<pre><code>saver.restore(sess, 'modelo')
sess.run(tf.initialize_all_variables())
</code></pre>
<p>So you have two different predictions because you initiliaze your model with random variables twice. You need to swa... | python|tensorflow|neural-network|classification|conv-neural-network | 0 |
372,315 | 61,932,920 | how can i replace or mask a substring before a character in Python? | <p>I have a dataframe (<code>df</code>) with some columns where one called <code>df['text]</code> has different strings and some rows have an email.</p>
<pre><code>df = df[df['text'].str.contains('@')]['text']
</code></pre>
<p>I saw a lot of examples like these:</p>
<pre><code>Input Output
'exam... | <p>Here's a simple pattern that replaces at most <code>3</code> non-space characters preceding <code>@</code> with <code>***</code>:</p>
<pre><code>df = pd.DataFrame({
'text': ['My email is example@gmail.com and my name is Fernando',
'This email has two characters: ab@gmail.com']
})
df.text.str.repla... | python|python-3.x|pandas | 1 |
372,316 | 61,852,590 | How do I implement a controlled Rx in Cirq/Tensorflow Quantum? | <p>I am trying to implement a controlled rotation gate in Cirq/Tensorflow Quantum. </p>
<p>The readthedocs.io at <a href="https://cirq.readthedocs.io/en/stable/gates.html" rel="nofollow noreferrer">https://cirq.readthedocs.io/en/stable/gates.html</a> states:</p>
<p>"Gates can be converted to a controlled version by u... | <p>What you have is a completely correct implementation of a controlled X rotation in Cirq. It can be used in simulation and other things like <code>cirq.unitary</code> without any issues.</p>
<p>TFQ only supports a subset of gates in Cirq. For example a <code>cirq.ControlledGate</code> can have an arbitrary number of ... | quantum-computing|tensorflow-quantum|cirq | 3 |
372,317 | 61,664,330 | Merging dataframes with time series data + checking if values already exist in the first df | <p>I'm new at Python so please bear with me. I have a dataframe that looks like this:</p>
<pre><code>df1
Company 1/2020 2/2020
Apple 1 0
Google 0 2
</code></pre>
<p>I want to be able to merge a new data frame that may look like:</p>
<pre><code>df2
Company 2/2020 3/2020
... | <p>I'm not sure if I fully understand the intent of the question.
If the sum of <code>df1+df2</code> is required, the following code can be used.</p>
<pre><code> import pandas as pd
import io
data = '''
Company 1/2020 2/2020
Apple 1 0
Google 0 2
'''
data2 = '''
Company 2/2020 3/2020
Apple 1 1
Google 2 0
'... | python|pandas | 0 |
372,318 | 61,798,735 | How to group two columns and find the total value using pandas | <pre><code>Market Region No_of_Orders Profit Sales
Africa Western Africa 251 -12,901.51 78,476.06
Africa Southern Africa 85 11,768.58 51,319.50
Africa North Africa 182 21,643.08 86,698.89
Africa Eastern Africa 110 8,013.04 44,182.60
Africa Central Africa 103 15,606.30 61,689.99
Europe Weste... | <p>IIUC, for Africa:</p>
<pre><code>df[df.Market=='Africa'].Profit.sum()
</code></pre>
<p>If you want the profit for each market, use the solution provided by @XXavier in the comment.</p> | python|pandas|data-science | 0 |
372,319 | 61,949,024 | Plot normal distribution over histogram | <p>I am new to python and in the following code, I would like to plot a bell curve to show how the data follows a norm distribution. How would I go about it? Also, can anyone answer why when showing the hist, I have values (x-axis) greater than 100? I would assume by defining the Randels to 100, it would not show anyth... | <p>You can use <code>scipy.stats.norm</code> to get a normal distribution. Documentation for it <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html" rel="nofollow noreferrer">here</a>. To fit any function to a data set you can use <code>scipy.optimize.curve_fit()</code>, documentation fo... | python|numpy|matplotlib | 0 |
372,320 | 61,801,668 | How to resample DatetimeIndex in Pandas? | <p>How can I resample <code>DatetimeIndex</code> objects in Pandas? Assume I have some existing <code>DatetimeIndex</code> object called <code>oldindex</code>. I would like to have the index that would be the result if I ran:</p>
<pre><code>newindex = pd.Series(index=oldindex, data=None).resample('H').sum().index
</co... | <p>Resampling is to <em>change the data</em>, if you have no data to change you can just create a new index with the required frequency that covers the original range:</p>
<pre><code>>>> oldindex
DatetimeIndex(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04',
'2020-01-05', '2020-01-06', ... | pandas | 0 |
372,321 | 61,980,231 | Mean grouped by two columns with window by 3 months and NaN for less than 3 months | <p>I have to apply the mean calculation in this dataset by customer, account but this mean needs to be applied to each 3 months in these groups. For the customer A1200 that don't has 3 months, the result need to be <code>NaN</code>.</p>
<pre><code>customer account month invoice
C1000 A1100 2019... | <p>Data</p>
<pre><code>+----------+---------+----------+----------+
| customer | account | month | invoice |
+----------+---------+----------+----------+
| C1000 | A1100 | 01-10-19 | 34000 |
| C1000 | A1100 | 01-11-19 | 55000 |
| C1000 | A1100 | 01-12-19 | 80000 |
| C1000 | A1200 | 01-... | python|python-3.x|pandas|pyspark|pandas-groupby | 3 |
372,322 | 61,690,714 | How to resolve a TypeError: string indices must be integers, with list comprehension over list of dicts? | <p>Can somebody please explain to me why this works:
(standalone)</p>
<pre><code>numpy_data = np.array([[1, [{'id': 1495, 'name': 'fishing'}, {'id': 12392, 'name': 'best friend'}]],
[3, [{‘id’: 818, ‘name’: ‘based on novel’}, {‘id’: 10131, ‘name’: ‘interracial relationship’}]]])
df = pd.DataFra... | <ul>
<li>The <code>keywords</code> column is a string not a list of dicts</li>
<li>Fix it with <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow noreferrer"><code>ast.literal_eval</code></a></li>
<li>File from Kaggle: <a href="https://www.kaggle.com/rounakbanik/the-movies-dataset/downl... | python|pandas|list|dictionary | 0 |
372,323 | 62,015,947 | Pandas : more efficient way to do nested for loop plus if | <p>I have a list, called namelist, with 1000 names and a dataframe, called df_all, with all 1000 names in it but with repeated rows because of different timestamp. Len of df_all is about 2000+.</p>
<p>I want to split this data into individual dataframes. </p>
<p>My code is as follows:</p>
<pre><code>df_store = []
f... | <p>You don't need to run two loops to achieve the results. Pandas DataFrame provides Boolean array Indexing which is pretty fast as well. Please check below:</p>
<pre><code>df_store = []
for i in range(len(namelist)) :
temp_df = df_all[df_all.name==namelist[i]].copy()
df_store.append(temp_df)
</code></pre>
<... | python|pandas|dataframe | 1 |
372,324 | 61,629,941 | Pandas: Extract top (n) values from DataFrame matrix | <p>This is a problem that arose when calculating the frequency of co-occurrence.</p>
<p>I have Dataframe that 884x884 matrix with rows and columns symmetrical.</p>
<p>I'd like to extract the top 20 values from the elements of this matrix.</p>
<p>However, if I sort down columns or rows, only one column or rows reacts... | <p>Give this a try; although I'm sure there are more elegant ways to accomplish this.</p>
<p>Using your DataFrame as above (called <code>df</code>):</p>
<pre><code>import itertools
import pandas as pd
# Create a list of unique combinations (e.g. (alexa, actual)).
groups = list(itertools.combinations(df.columns, 2))
... | python|pandas|dataframe|matrix | 1 |
372,325 | 61,718,105 | Pandas dataframe detect patterns in the data (duplicates) | <p>I need to detect patterns in the values of keyword column.</p>
<p>Patterns such as:
"kw1, kw2, kw3",
"kw1, kw4, kw5",
"kw6, kw7"
etc...</p>
<p>Pattern definition:</p>
<ul>
<li>Several keywords in consecutive rows (this will already be the case)</li>
<li>Keywords all "belong" to one<br>
URL. </li>
<li>As soon as ... | <p>Assuming the data frame is sorted as in your example, you could use Boolean series like this:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame({'URL': ['url1', 'url1', 'url1', 'url1', 'url1', 'url1',
'url2', 'url2', 'url3', 'url3', 'url3'],
... | python|pandas|dataframe | 2 |
372,326 | 61,897,051 | Pandas Extract Number with decimals from String | <p>I am trying to extract all numbers including decimals, dots and commas form a string using pandas.</p>
<p>This is my DataFrame</p>
<pre><code> rate_number
0 92 rate
0 33 rate
0 9.25 rate
0 (4,396 total
0 (2,620 total
</code></pre>
<p>I tried using <code>df['rate_number'].str.extract... | <p>You can try this:</p>
<pre><code>df['rate_number'] = df['rate_number'].replace('\(|[a-zA-Z]+', '', regex=True)
</code></pre>
<p>Better answer:</p>
<pre><code>df['rate_number_2'] = df['rate_number'].str.extract('([0-9][,.]*[0-9]*)')
</code></pre>
<p><strong>Output:</strong></p>
<pre><code> rate_number rate_numb... | python|pandas | 1 |
372,327 | 61,778,820 | Pandas dataframe column from data containing NaN values | <p>The following code transforms a given pandas column <code>FEAT</code> into a new, binary feature named <code>STREAM</code>. The program works as long as there are no NaN values in the original dataframe. If that is the case, the following exception occurs: <code>ValueError: Length of values does not match length of ... | <p>The issue is you are missing an <code>else</code> block so when a value (like <code>NaN</code>) is in neither <code>stream_0</code> nor <code>stream_1</code> you do nothing which then causes L to have fewer elements than the number of rows in <code>customer</code>.</p>
<p>Looping here is unnecessary, <code>np.selec... | python|pandas|dataframe | 2 |
372,328 | 61,984,209 | Panda array splicing | <p>I am working on a NBA dataset and I need to do the following: On the given panda array I need to extract rows where the PER is maximized for every different season: </p>
<p><a href="https://i.stack.imgur.com/nGAfe.png" rel="nofollow noreferrer">Image</a></p>
<p>Applied to this image, I should get only 2 rows: the ... | <p>Try this:</p>
<pre><code>df.groupby("Team").apply(max).reset_index(drop=True)
</code></pre> | python|pandas|select | 0 |
372,329 | 61,711,479 | Time series analysis - putting values into bins | <p><a href="https://i.stack.imgur.com/FMDOk.png" rel="nofollow noreferrer">Data</a></p>
<p>How can I split the values in the category_lvl2 column into bins for each different value, and find the average amount for all the values in each bin?
For example finding the average amount spent on coffee</p>
<p>I have already... | <p>You can use <code>groupby()</code> method and provide the groups you get with <code>pd.cut()</code>. The example below bins the data into 10 categories by sepal_length column. Then those categories are used to groupby the iris df. You could also bin with a variable and get the mean of another one with groupby.</p>
... | pandas | 1 |
372,330 | 61,972,672 | How to multiply a specific row in pandas dataframe by a condition | <p>I have a column which of 10th marks but some specific rows are not scaled properly i.e they are out of 10. I want to create a function that will help me to detect which are <=10 and then multiply to 100. I tried by creating a function but it failed.
Following is the Column:
<code>data['10th']</code></p>
<pre><co... | <p>I am not what do you mean by "multiply to 100" but you should be able to use apply with lambda similar to this:</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({"a": [1, 3, 5, 23, 76, 43 ,12, 3 ,5]})
df['a'] = df['a'].apply(lambda x: x*100 if x < 10 else x)
print(df)
0 100
1 300
2 50... | python|pandas|function|dataframe|data-manipulation | 0 |
372,331 | 61,726,644 | numpy round compare array | <p>I'm currently working with the numpy float array. </p>
<p>My problem is that I'd like to compare them with, say, 3 decimal places. </p>
<p>But when I try to use round or around, it doesn't work.</p>
<p>If you know a way I'd be very grateful.</p>
<p>Here's the code I tried</p>
<pre><code>import numpy as np
x = ... | <p>At 3 decimal points 0.32745 rounds down and 0.32788 rounds up, so they are not equal. An easier solution might be to use numpy's <a href="https://numpy.org/doc/stable/reference/generated/numpy.isclose.html" rel="nofollow noreferrer"><code>isclose</code></a> setting the absolute precision argument <code>atol</code>:<... | python|python-3.x|numpy|numpy-ndarray | 4 |
372,332 | 61,611,050 | Tensorflow's app Camera Images are Blurry | <p>What I'm trying to achieve:</p>
<p><a href="https://i.stack.imgur.com/tPfdg.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tPfdg.jpg" alt="enter image description here"></a></p>
<p>What I achieve w/ my tensorflow app:</p>
<p><a href="https://i.stack.imgur.com/qD8uh.jpg" rel="nofollow noreferre... | <p>You are using a <strong>very old</strong> implementation of the Camera API in <code>LegacyCameraConnectionFragment</code>, which is <a href="https://developer.android.com/guide/topics/media/camera" rel="nofollow noreferrer">deprecated</a>. You should <a href="https://developer.android.com/reference/android/hardware/... | android|android-studio|tensorflow|android-camera|tensorflow-lite | 1 |
372,333 | 61,988,107 | Issues using "pd.concat". Two dataframes are doubling in column length and with "NaN" values instead of merging rows | <p>The goal is to essentially combine the two databases and keep the alphabetical headers from the Tk1P dataframe while integrating the data from the Tk1L dataframe. Unfortunately I am getting this unintended result when trying to merge. Please see the link below the code to giphy for the output screen which shows bo... | <p>From your ouput it seems that you concat the <code>df</code>along the columns axis.</p>
<p>Try <code>append</code> instead of <code>concat</code>.</p>
<pre class="lang-py prettyprint-override"><code>Tk1L.append(TKP)
</code></pre>
<p><strong>EDIT</strong></p>
<p>Look at the following two lines</p>
<pre class="la... | python|python-3.x|pandas|python-2.7 | 0 |
372,334 | 61,898,994 | Plotting from array to geoviews/holoviews. Converting to xarray needed? | <p>First of all, if anyone has a link to a good tutorial to creating colomaps with geoviews or holoviews and transporting that to a dashbooard please send a link. I am trying to mimick what they did at the timestamp in <a href="https://youtu.be/s9REOti_vzs?t=1286" rel="nofollow noreferrer">the video here</a> . Also hav... | <p>Assuming you want a points plot as you are using in Matplotlib, the HoloViews equivalent to plt.scatter is hv.Points. hv.Points accepts a tidy data format that you can get by transposing the data compared to Matplotlib:</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib import cm
%matplotlib inline
mesh... | python|numpy|python-xarray|holoviews|geoviews | 0 |
372,335 | 62,021,716 | DataFrame.groupby.agg(list) works but not agg('list') | <p>I was trying to apply what listagg does in SQL in pandas</p>
<p>Why does the following work</p>
<pre><code>DataFrame.groupby.agg(list)
</code></pre>
<p>but the following does not?</p>
<pre><code>DataFrame.groupby.agg('list')
</code></pre>
<p>I was transforming data below:
<a href="https://i.stack.imgur.com/JL9... | <p>I took a look at the pandas source code and found that, at least when aggregating a pandas Series, the string function name is "translated" to a function by calling</p>
<pre class="lang-py prettyprint-override"><code>if isinstance(func, str):
return getattr(self, func)(*args, **kwargs)
</code></pre>
<p>where <... | python|pandas|pandas-groupby | 1 |
372,336 | 62,021,270 | Python - Count row between interval in dataframe | <p>I have a dataset with a date, engine, energy and max power column. Let's say that the dataset is composed of 2 machines and a depth of one month. Each machine has a maximum power (say 100 for simplicity). Each machine with 3 operating states (between Pmax and 80% of Pmax either nominal power, between 80% and 20% of ... | <p>here is one way to do it, I tried to use your way with groups but ended up to do it slightly differently</p>
<pre><code># another way to create inter, probably faster on big dataframe
df['inter'] = pd.cut(df['energy']/df['pmax'], [-1,0.2, 0.8, 1.01],
labels=[0,1,2], right=False)
# mask if int... | python|pandas|dataframe | 1 |
372,337 | 61,963,351 | Comparative Boxplot in Python | <p>I have a <code>pandas</code> dataframe similar to the following</p>
<pre><code>names
x 3.5
x 3.7
z 2.8
x 3.4
y 3.25
z 2.9
...
</code></pre>
<p>And I wish to make a comparative boxplot (three boxplots next to each other for each of <code>x</code>, <code>y</code>, and <code>z</code>. I'm u... | <p>I think you can draw the <a href="https://statsmethods.wordpress.com/2013/05/06/side-by-side-boxplot/" rel="nofollow noreferrer">side by side boxplot</a> this way:</p>
<pre><code>import pandas as pd
import seaborn as sns
from io import StringIO
data = """
names,num
x,3.5
x,3.7
z,2.8
x,3.4
y,3.25
z,2.9... | python|pandas|seaborn|boxplot | 1 |
372,338 | 61,923,838 | How to reshape dataframe in order to get the desired output in python? | <p>I have a dataframe with this format.</p>
<p>I have this dataframe:</p>
<pre><code> id 2005-01-07 2008-01-07 ...
0 1Y 1.0 1.6
1 5Y 1.0 1.7
2 6Y 6.0 1.0
3 10Y 2.0 7.1
4 30Y 5.5 8.6
</code></pre>
<p>And I woul... | <p>Using <a href="https://pandas.pydata.org/docs/reference/api/pandas.melt.html" rel="nofollow noreferrer"><code>pd.melt</code></a> we can go <strong>from wide- to long-form</strong> in one easy step:</p>
<pre><code>df = pd.melt(df, id_vars=['id'], var_name='Date', value_name='number')
</code></pre>
<p><strong>The reas... | python|pandas | 3 |
372,339 | 61,926,399 | Issue while converting column value to row value in pandas python? | <p>I have data frame like</p>
<pre><code>County section
A S1,S2
C ALL
B S1
</code></pre>
<p><strong>Expected Output</strong></p>
<pre><code>County section
A S1
A S2
C S1
C S2
B S2
</code></pre>
<p>My code</p>
<pre><code>df =df.assign(sections=df... | <p>Let us change the <code>replace</code> part </p>
<pre><code>s=df[df.section.ne('ALL')]
toreplace=s.loc[s.section.str.split(',').str.len().idxmax(),'section']
df.assign(section=df.section.replace({'ALL':toreplace}).str.split(',')).explode('section')
County section
0 A S1
1 B S1
2 C S1... | python|python-3.x|pandas|dataframe | 2 |
372,340 | 61,816,193 | Validation Accuracy Does Not Improve in CNN | <p>I have a CNN like AlexNet trying to predict class of the ornament. The train accuracy and loss monotonically increase and decrease respectively. But, the test accuracy fluctuates around 0.50.</p>
<p>I've tried to change various hyperparameters, changed batch size,used data augmentation, changed data to gray scale b... | <p>As you said in Output layer, you have 2 classes, which indicates this model is for binary classification-(0,1). For this classification, you need to define output layer as below:</p>
<p><code>model.add(Dense(1, activation = "sigmoid"))</code></p>
<p>Along with <code>class_mode='binary'</code> and <code>bin... | tensorflow|keras|deep-learning|computer-vision|conv-neural-network | 0 |
372,341 | 61,680,758 | Best way to map Pandas column using dictionary | <p>I have a dictionary that who's keys are names and values are another dictionary which maps numbers to their normalized values (essentially just numbers to numbers). For example:</p>
<pre><code>dict1 = {'name1':{0.02:0.04, 0.034:0.06, 0.051:0.08...0.59:0.71, 0.611:0.723}}
</code></pre>
<p>I have a dataframe <code>d... | <p>This is <code>merge_asof</code>:</p>
<pre><code># prepare data for merge
s = (pd.DataFrame(dict1).stack()
.reset_index(name='Map')
.sort_values(['level_0','Map'])
)
# output
(pd.merge_asof(df, s,
left_on='Value', right_on='level_0',
left_by='Name', right_by='level_1... | python|pandas|dictionary | 2 |
372,342 | 61,701,142 | Nagios check giving error and not the output I expect | <p>I have a python code which when run locally gives correct output but when I run it with Nagios check locally it gives errors.</p>
<p>Code :</p>
<pre><code>#!/usr/bin/env python
import pandas as pd
df = pd.read_csv("...")
print(df)
</code></pre>
<p>Nagios configuration :</p>
<ol>
<li>inside localhost.cfg</li>
</o... | <p>As user, from the shell, check the istance of python.
For example with this command:</p>
<pre><code>env python
</code></pre>
<p>Modify the script and on the first line replace this</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>with the absolute path of the python executable.</p> | python|pandas|nagios | 0 |
372,343 | 61,805,973 | How to choose items out of many options in pandas | <p>This question <a href="https://stackoverflow.com/q/61803635/13543235">Calculate points with pandas</a> did not capture well what I wanted to ask so I ask it here.
I have this data here</p>
<pre><code>df = pd.DataFrame({'ENG':[10,3,5,6,3],'KIS':[9,5,7,9,10],'BIO':[10,'',4,'',4],'PHY':[9,5,'',10,12],'HIS':['','',9,7,... | <p>Sort each row by value and then pick the best two and sum them: </p>
<pre><code>df = pd.DataFrame({'ENG':[10,3,5,6,3],'KIS':[9,5,7,9,10],'BIO':[10,'',4,'',4],'PHY':[9,5,'',10,12],'HIS':['','',9,7,8],'GEO':['',7,'',11,''],'CRE':[8,3,6,'','']})
df = df.replace('',0)
df[['BIO','PHY','HIS','GEO','CRE']].apply(lambda... | pandas | 1 |
372,344 | 58,071,102 | What is the pattern of tensorflow fill_triangular? | <p>I'm sure that there is some logic here, but I can't figure out what the general pattern is. If I apply <code>tf.contrib.distributions.fill_triangular</code> to a length <code>(n+1)n/2</code> list, then in what pattern do the entries fill the upper/lower triangle of the resulting matrix?</p>
<p>To illustrate, here ... | <p>As the tf official doc mentioned, <a href="https://www.tensorflow.org/api_docs/python/tf/contrib/distributions/fill_triangular" rel="nofollow noreferrer">fill_triangular</a> fills the elements in a clockwise spiral. </p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
import numpy as np
foo... | python|tensorflow | 1 |
372,345 | 57,973,448 | 'Jump' Operation in Python to Skip Rows in DataFrame | <p>I have an Excel file contain data like in that picture.</p>
<p><a href="https://i.stack.imgur.com/w81h1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w81h1.png" alt="DataFrame"></a></p>
<p>"doc_id" refers to the document ID where the text comes from. In our example, we have 4 documents (doc_id... | <p>you have to iterate through whole document</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
data = pd.read_csv('book2.csv')[['page_id', 'doc_id', 'text']]
curr_doc_id = -1
before_toc = False
for i, row in data.iterrows():
if curr_doc_id < row.doc_id:
curr_doc_id = row.doc_id
... | python|pandas | 0 |
372,346 | 58,008,670 | Populating the values of a column based on multiple conditions to a new column of a dataframe | <p>Say I have a following data frame,</p>
<pre><code>df.head()
col1 col2 col3 start end gs
chr1 HAS GEN 11869 14409 DDX
chr1 HAS TRANS 11869 14409 NaN
chr1 HAS EX 11869 12227 NaN
chr1 HAS GEN 12613 12721 FXBZ
chr1 HAS EX 13221 1440... | <p>I believe you can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a> with condition by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code>... | python|pandas|lambda | 1 |
372,347 | 58,115,920 | Assigning values to multi-indexed dataframe based on index level | <p>I have a multi-indexed dataframe <code>df1</code> with three indices whose values only belong to the first index. However, after a merge, the dataframe got split up which resulted in various <code>0</code>.
Now I want to replace the <code>0</code> with the values belonging to the first index level.</p>
<p>Here is ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mask.html" rel="nofollow noreferrer"><code>Series.mask</code></a> with replacement by Series created by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow nor... | pandas|dataframe|multi-index | 1 |
372,348 | 57,895,644 | Count the total of cases | <p>I had a dataframe as below by recording the number of cases per month:</p>
<pre><code>Month client Cases
2019-06-01 A 1
2019-05-01 A 0
2019-04-01 A 0
2019-03-01 A 2
2019-02-01 A 0
2019-06-01 B 1
2019-05-01 ... | <p>You want the cumulative sum. </p>
<pre><code>In [3]: df
Out[3]:
Month Cases
0 2019-06-01 1
1 2019-05-01 0
2 2019-04-01 0
3 2019-03-01 2
4 2019-02-01 0
In [4]: df.Cases[::-1].cumsum()
Out[4]:
4 0
3 2
2 2
1 2
0 3
Name: Cases, dtype: int64
</code></pre>
<p>This i... | python|python-3.x|pandas|dataframe | 0 |
372,349 | 57,803,428 | How to upload a csv file in tensorflow.js in angular project? | <p>For my anguar project I'm trying to upload a csv file from my assets folder with tf.data.csv, but the file is not being recognized by the code meaning, that the created Object is empty.
Is it even possible to upload a csv via tf.data.csv() from assets?
And if yes, how? :)</p>
<pre><code>async loadData(){
const csv... | <p>Yes of course this is possible.
I don't know if you CSV has column headers with "" if so try this</p>
<pre><code>async function example(){
// Import from CSV
const dataSet = tf.data.csv('https://raw.githubusercontent.com/JuliaStats/RDatasets.jl/master/doc/datasets.csv');
// Extract x and y values to plot
const po... | javascript|angular|typescript|tensorflow.js | 1 |
372,350 | 57,842,034 | Convert number of rows by condition | <p>I try to convert number of rows by condition:</p>
<pre><code>df.loc[df['file'] == '0.mp4','xmin'] = df['xmin']/4
df.loc[df['file'] == '2.mp4','xmin'] = df['xmin']/4
df.loc[df['file'] == '8.mp4','xmin'] = df['xmin']/4
df.loc[df['file'] == '10.mp4','xmin'] = df['xmin']/4
</code></pre>
<p>There is any option to d... | <p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>pandas.Series.isin</code></a>:</p>
<pre><code>df.loc[df['file'].isin(['0.mp4', '2.mp4', '8.mp4', '10.mp4']), 'xmin'] = df['xmin'] / 4
</code></pre> | python|pandas|dataframe | 4 |
372,351 | 58,142,280 | apply proportion z-test to each record in dataframe | <p>I have the code below, where I'm trying to apply a one sample proportion ztest to values in each row in my data. I have example data below from my dataframe df. I'm trying to compare each proportion in value to the proportion gotten from the value in count and number of trials from the value in obs. I want a p va... | <p>There is a mistake in your pvl function. The <code>proportion_ztest()</code> function from stats model takes the inputs in the following order: <em>count, nobs, value</em>. Therefore, you should define your function as:</p>
<pre><code>def pvl(x):
return sm.stats.proportions_ztest(x['count'], x['obs'],
... | python-3.x|pandas|statsmodels|hypothesis-test | 1 |
372,352 | 57,936,289 | best way to fill in a numpy ndarray? | <p>I use the following code to generate an image with a gradient. I access the array element by element. Is there a better way to do it? Thanks.</p>
<pre><code>import cv2
import numpy as np
x = np.ndarray((256,256,3), dtype=np.uint8)
for i in xrange(256):
for j in xrange(256):
for k in xrange(3):
... | <p>It appears that you aim to fill <code>x[i, j, k]</code> with <code>i</code> for all values for <em>i</em>, <em>j</em> and <em>k</em>.</p>
<p>You can construct such array with:</p>
<pre><code>x = np.repeat(np.arange(256, dtype=np.uint8), (256*3)).reshape(256, 256, 3)
</code></pre>
<p>We then obtain an array that l... | python|numpy|cv2 | 3 |
372,353 | 58,024,490 | Combine Dataframe rows to fill in missing data | <p>Suppose I have a dataframe with rows containing missing data, but a set of columns acting as a key:</p>
<pre><code>import pandas as pd
import numpy as np
data = {"id": [1, 1, 2, 2, 3, 3, 4 ,4], "name": ["John", "John", "Paul", "Paul", "Ringo", "Ringo", "George", "George"], "height": [178, np.nan, 182, np.nan, 175, ... | <p>If there are always only one non <code>NaN</code>s values per groups is possible aggregate many ways:</p>
<pre><code>df = df.groupby(['id', 'name'], as_index=False).first()
</code></pre>
<p>Or:</p>
<pre><code>df = df.groupby(['id', 'name'], as_index=False).last()
</code></pre>
<p>Or:</p>
<pre><code>df = df.grou... | python|pandas | 2 |
372,354 | 58,089,002 | tf.estimator serving function failing | <p>I am using the tf.estimator to train and serve my tensorflow model. the training completed as expected, but fails in serving. I read my data in as a TFRecordDataset. My parsing function applies a transformation to feature "x2". "x2" is a string that is split. the tranformed feature is "x3".</p>
<pre><code>def parse... | <p>Following this <a href="https://github.com/GoogleCloudPlatform/cloudml-samples/blob/master/cloudml-template/examples/classification/census/trainer/inputs.py" rel="nofollow noreferrer">link</a></p>
<p>I processed feature "x3" after creating the receiver_tensor. Splitting the string in the serving fucntion required s... | tensorflow|tensorflow-serving|tensorflow-transform | 0 |
372,355 | 57,915,055 | How to Fix "Failed to load the native TensorFlow runtime" Error | <p>I'm trying to run I program I've written for Tensorflow from a file in Notepad using Powershell. Whenever I run <code>python main.py</code> to open and execute the code, I get the error below.</p>
<p>I haven't really found anything to try, and the only thing I felt I could do is uninstall and re-install Tensorflow,... | <p>Please follow the instructions from <a href="https://www.tensorflow.org/install/source_windows" rel="nofollow noreferrer">TensorFlow website</a>. I recommend please <a href="https://www.tensorflow.org/install#install-tensorflow-2" rel="nofollow noreferrer">install Tensorflow 2</a>, if you are using lower versions. <... | python|windows|powershell|tensorflow|command-line | 0 |
372,356 | 58,147,888 | Keras + multiprocessing - correctly generating sessions, but only one processor | <p>I have a problem with Keras and multiprocessing. I have already searched a lot and I found a lot of questions with the same subjects:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/50262215/importing-keras-breaks-multiprocessing">Importing Keras breaks multiprocessing</a></li>
<li><a href="https://stacko... | <p>The problem was in the installation of <code>tensorflow</code> and <code>keras</code>. The methods for achieving parallelization are correct.</p>
<p>The <code>tensorflow</code> documentation clearly states that is highly suggested to install the package using <code>pip</code> as the <code>conda</code> package is ma... | python|tensorflow|keras|multiprocessing | 0 |
372,357 | 57,808,870 | Optimize Custom Parameters in Pytorch | <p>I'm trying to create some custom parameters to optimize and came across this helpful link <a href="https://discuss.pytorch.org/t/defining-weights-of-a-custom-layer-as-parameters/17687" rel="nofollow noreferrer">here</a>. However, I'm a bit confused as to why this code works.</p>
<p>Here is the code with some slight... | <p>You are right, <code>Mask.forward</code> discard <code>x</code> completely. However, the output of your model "sees" <code>indata</code> when computing the loss.<br>
What you are actually teaching your model is to have <code>mask.weight == indata</code>.</p> | pytorch | 0 |
372,358 | 57,756,450 | How to add element to a numpy array in Python | <p>I am having a problem with numpy array
I have an array A with A.shape = (2000,224,224,3). I also have an array B with B.shape = (224,224,3).</p>
<p>I need to insert B as the last element of A, so after inserting</p>
<pre><code>A.shape = (2001,224,224,3) and A[2001] = B
</code></pre>
<p>I have tried <code>np.conca... | <p>You can throw in a new axis to make <code>b</code> have the same shape as <code>a</code></p>
<pre><code>import numpy as np
a = np.random.rand(2000,224,224,3)
b = np.random.rand(224,224,3)
a = np.concatenate((a,b[np.newaxis]))
np.all(a[-1] == b)
</code></pre>
<p>gives <code>True</code></p> | python|numpy | 1 |
372,359 | 58,157,138 | iterate thrugh values in each columns | <p>How to iterate through data in a DataFrame, I would like to iterate through all the data in the first column, before moving to the next.</p>
<p>with the code below I get to iterate over the data row by row for all columns</p>
<p><a href="https://i.stack.imgur.com/NNugF.png" rel="nofollow noreferrer"><img src="http... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/version/0.25/reference/api/pandas.DataFrame.transpose.html" rel="nofollow noreferrer">DataFrame.transpose</a> an then use your code...</p>
<pre><code>import time
import pandas as pd
df = pd.read_csv('testDATA.csv')
</code></pre>
<hr>
<pre><code>df=df.T
</code></p... | python|python-3.x|pandas | 2 |
372,360 | 57,965,540 | Saving data to multiple csv files in pandas | <p>I have this data from a .gov site:</p>
<pre><code>import pandas as pd
import io
import requests
url="https://download.bls.gov/pub/time.series/la/la.data.64.County"
s=requests.get(url).content
c=pd.read_csv(io.StringIO(s.decode('utf-8')))
</code></pre>
<p>The number of rows is 4942096. I want to get all these into ... | <p>you can loop through the file and save it as so : </p>
<pre><code>filename = io.StringIO(s.decode('utf-8'))
# ^ not tested this but assuming it would work for readability sake.
chunk_size = 10 ** 6
for chunk in pd.read_csv(filename, chunksize=chunk_size):
chunk.to_csv('nick.csv.gz',compression='gzip',index=Fa... | python|pandas | 4 |
372,361 | 58,091,138 | filter size in convolution layers | <p>what happens if I add another convolution layer after convolution layer with the same filter size</p>
<p>for example, in a network of around 20 layers, I have to choose different filter sizes among convolution layers. so what will be the impact if I do something like this</p>
<pre><code>
inner = MaxPooling2D(pool_s... | <p>Trained with both scenarios where with same filters and different filters<br>
(1) The observation is when trained with more weights(means more filters with increase in number) the test accuracy is more<br>
(2) when trained with same filters the accuracy is not as good as earlier case.</p>
<p>Ran the below code on C... | python-3.x|tensorflow|deep-learning|conv-neural-network|layer | 1 |
372,362 | 58,145,699 | Iterate through a list and append results to a pandas dataframe | <p>I am trying to extract boxscore NFL data from sportsreference. When you call the boxscore data for a single date you get a bunch of stats in multiple columns in a single row. So I'm trying to iterate through multiple dates for boxscores from a list and then append each row to the same dataframe. </p>
<pre><code>i... | <p>You have to append the dataframes otherwise df keeps getting overwritten.</p>
<pre><code>dfs = []
for x in boxscore_list:
game_data = Boxscore(x)
df = game_data.dataframe
dfs.append(df)
result = pd.concat(dfs, ignore_index=True)
</code></pre> | python|pandas | 1 |
372,363 | 58,138,071 | 'tuple' object has no attribute 'layer' | <p>I am having many troubles trying to start training my model (a DCGAN). It is giving me the error:</p>
<pre><code>'tuple' object has no attribute 'layer'
</code></pre>
<p>I read that this could be due to having both the TensorFlow version 1.14.0 and the Keras version 2.2 or higher.
I tried to fix this by downgrading ... | <p>You have imported layers from <strong>tensorflow.keras</strong> while other functions you have imported from <strong>keras</strong>. You can either import your layers from keras or try importing other functions from tensorflow.keras which might work.</p> | python|tensorflow|keras|version|attributeerror | 36 |
372,364 | 58,044,728 | Pytorch simple model not improving | <p>I am making a simple PyTorch neural net to approximate the sine function on x = [0, 2pi]. This is a simple architecture I use with different deep learning libraries to test whether I understand how to use it or not. The neural net, when untrained, always produces a straight horizontal line, and when trained, produce... | <p>After a while playing with some hyperparameters, modifying the net and changing the optimizer (following <a href="http://karpathy.github.io/2019/04/25/recipe/" rel="nofollow noreferrer">this</a> excellent recipe) I ended up with changing the line <code>optimizer = torch.optim.SGD(net.parameters(), lr = learningrate)... | python|machine-learning|neural-network|pytorch | 1 |
372,365 | 58,162,375 | pin and allocate tensorflow on specific NUMA node | <p>My system has two NUMA nodes and two GTX 1080 Ti attached to NUMA node 1 (XEON E5).</p>
<p>The NN models are trained via single-machine multi-GPU data parallelism using Keras' multi_gpu_model.</p>
<p>How can TF be instructed to allocate memory and execute the TF workers (merging weights) only on NUMA node 1? For p... | <p>no, answer ...</p>
<p>I'm using <code>numactl --cpunodebind=1 --membind=1</code> - binds execution and memory allocation to NUMA node 1.</p> | python|tensorflow|numa | 1 |
372,366 | 57,771,719 | How to change color scheme in scatter-matrix? | <p>Because I am new to data analysis with python, I want to improve my skills with tutorials and adjusting working code from others.</p>
<p>At the moment I am working on the <em>fruit_data_with_colors</em> data set, and want to understand the python code, available at:</p>
<p><a href="https://github.com/susanli2016/M... | <p>I think the easiest way to achieve what you want is to change the colormap, just edit:</p>
<pre><code>cmap = cm.get_cmap('new_color_map')
</code></pre>
<p>with a more appealing colormap. You can check the full list <a href="https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html" rel="nofollow noreferrer">her... | python|python-3.x|pandas|matplotlib|scatter-plot | 1 |
372,367 | 57,973,223 | How to create a TensorProto from a Java Map | <p>I can create a Tensorproto with single values like floats.</p>
<pre><code>// create TensorProto with 3 floats
org.tensorflow.framework.TensorProto.Builder tensorProtoBuilder = org.tensorflow.framework.TensorProto.newBuilder();
tensorProtoBuilder.setDtype(DataType.DT_FLOAT);
tensorProtoBuilde... | <p>I didn't get any feedback on this. </p>
<p>But managed to figure it out so hope my answer and code will help someone in the future.</p>
<p>Note: It is not necessary to create a TensorProto for this problem. </p>
<p>In a nutshell I had to:
- create Feature objs
- add them to Features List obj
- add Features List o... | java|tensorflow|tensorflow-serving | 0 |
372,368 | 58,007,127 | Pytorch differentiable conditional (index-based) sum | <p>I have an <code>idx</code> array like <code>[0, 1, 0, 2, 3, 1]</code> and another 2d array <code>data</code> like the following:</p>
<pre><code>[[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9, 10, 11],
[12, 13, 14],
[15, 16, 17]]
</code></pre>
<p>I want my output to be <code>4x3</code> in which 4 is the max of <c... | <p>You are looking for <a href="https://pytorch.org/docs/stable/tensors.html#torch.Tensor.index_add_" rel="nofollow noreferrer"><code>index_add_</code></a>:</p>
<pre class="lang-py prettyprint-override"><code>import torch
x = torch.tensor([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.],
[ 9... | python|pytorch | 1 |
372,369 | 58,017,389 | How to clean up dataframe row in Python | <p>I have a row in dataframe as</p>
<pre><code>names
------
*OP Under A Blood Red Moon
125-201 1006
Apple
Orange
/
1-2-3
</code></pre>
<p>I wanna clean it up and just have</p>
<pre><code>names
------
Apple
Orange
</code></pre>
<p>I wanna remove
<code>*OP Under A Blood Red Moon</code> as it has more than three words... | <p>Rather than removing rows we filter them and retain any rows that:</p>
<ul>
<li>have no more than 3 words (i.e. no more than 2 separating spaces) <strong>AND</strong></li>
<li>contain minimum one alpha character <strong>AND</strong></li>
<li>are longer than 1 character</li>
</ul>
<p>with the following boolean in... | python|pandas|numpy|dataframe | 1 |
372,370 | 58,166,818 | Keras: How to Multiply()? | <p><strong>TensorFlow 2.0 RC1</strong></p>
<pre><code>import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Multiply
import numpy as np
</code></pre>
<p>Expected output:</p>
<pre><code>Multiply()([np.array([1,2,3,4,4,4]).reshape(2,3), np.array([1,0])])
</code><... | <p>It depends on how the input shape is specified. In the Multiply() example(element-wise multiplication), the batch size is 2 and the feature size is 3 for Input and 1 for mask. So, when specifying the input shape in Keras, only the feature size needs to be specified.</p>
<pre><code>input_1 = Input(shape=(3,))
mask_1... | python|tensorflow|keras|keras-layer|tf.keras | 3 |
372,371 | 57,978,791 | How to get predicted values along with test data, and visualize actual vs predicted? | <pre><code>from sklearn import datasets
import numpy as np
import pandas as pd from sklearn.model_selection
import train_test_split
from sklearn.linear_model import Perceptron
data = pd.read_csv('student_selection.csv')
x = data[['Average','Pass','Division','Domicile']]
y = data[['Selected']]
x_train,x_test,y_train,... | <blockquote>
<p>How to see the actual vs predicted as a table and along with a plot?</p>
</blockquote>
<p>Just run:</p>
<pre><code>y_predict= pnn.predict(x)
data['y_predict'] = y_predict
</code></pre>
<p>and have the column in your dataframe, if you want to plot it you can use:</p>
<pre><code>import matplotlib.p... | python|pandas|numpy|scikit-learn|sklearn-pandas | 2 |
372,372 | 58,093,439 | Copying numpy array with '=' operator. Why is it working? | <p>According to <a href="https://stackoverflow.com/a/19676762/6740589">this</a> answer, <code>B=A</code> where <code>A</code> is a numpy array, <code>B</code> should be pointing to the same object <code>A</code>.</p>
<pre><code>import cv2
import numpy as np
img = cv2.imread('rose.jpeg')
print("img.shape: ", np.shape(... | <p>The "problem" is that your not using numpy here but opencv and while numpy array.resize() is in-place opencv img.resize() is not.</p>
<p>So your call to </p>
<pre><code> img = cv2.resize(img, (250,100))
</code></pre>
<p>creates a new object (image) with the given size. So here the img variable will point to a ... | python|numpy | 1 |
372,373 | 57,997,253 | How to filter rows of a dataframe based on the value of a column and the next in that column | <p>I have a Dataframe called "df" and a column in that dataframe that we can call "col".</p>
<p>Based on the value in "col", I need to keep in the dataframe (to filter) only the values where col[i] is different of the value col[i+2] and the same of col[i+1]. Indeed is the penultimate of a sequence of the same value in... | <p>Simply use <code>.shift</code> twice and vectorized comparison <code>==</code></p>
<pre><code>df[(df.col == df.col.shift(-1)) & (df.col != df.col.shift(-2))]
</code></pre>
<hr>
<pre><code> Index a b col
1 1 45 23 1
3 3 45 67 2
5 5 1 3 3
</code></pre> | python|pandas|dataframe|filter | 1 |
372,374 | 57,862,966 | Python could not generate the plot | <p>I used the following code to generate a plot which shows pairs that are solution to a specific equation:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
x = np.arange(4.01,12,.01)
y = np.arange(6,18,.01)
for i_ind, i in enumerate(y):
for j_ind, j in enumerate(x):
k = 10/(6+j)
i... | <p><code>j == ((i**(1/k)-(i-6)**(1/k))/6)**(k/(1-k))</code> is never <code>True</code> so there is nothing to plot. You can see that by adding a <code>print</code> statement within your <code>if</code> block. And you can also add <code>plt.scatter(0,0)</code> at the very end to confirm displaying graphs does work.</p>
... | python|numpy|matplotlib|plot | 1 |
372,375 | 57,911,980 | Sorting columns in dataframes with panda | <p>I’m completely new to python so I don’t have a clue where to start but I have an excel spreadsheet table with 10,000 pieces of data about the google App Store. I’ve imported panda and imported the csv into python aswell. There are 5 columns including name, genre, rating, price, downloads. I need to sort the data fra... | <p>Try this -</p>
<pre><code>import pandas as pd
df = pd.read_csv('google-play-store.csv')
df.sort_values(by=['price'], ascending=False)
</code></pre> | python|pandas|dataframe | 1 |
372,376 | 58,086,247 | Finding last column index that unique value appears | <p>I have 2 Pandas DataFrames, one contains names in a single column:</p>
<p><a href="https://i.stack.imgur.com/DMhxx.png" rel="nofollow noreferrer">https://i.stack.imgur.com/DMhxx.png</a></p>
<p>And I want to find what the last column index the name appear in this other table:</p>
<p><a href="https://i.stack.imgur.... | <p>This is my answer for you:
The .last_valid_index() is a handy function that can be used for your task. Unfortunately it finds the last row, and not the last column. Therefore I transpose the dataframe before, so rows and columns are exchanged, then .last_valid_index() can be used.</p>
<pre><code> import pandas as p... | python|pandas | 0 |
372,377 | 57,990,054 | I need to print the True values excluding Nan in a list in pandas dataframe | <p>I need to print the True values excluding NaN in a list in pandas dataframe.</p>
<pre><code>dfa.where(dfa['Group']=='|Demographics')['Group']
</code></pre>
<p><img src="https://i.stack.imgur.com/mARVD.png" alt="enter image description here" /></p> | <p>Try this,</p>
<pre><code>dfa1 = np.where ((dfa['Group']=='|Demographics') & (dfa['Group'] !=np.NaN)), dfa['Group'],'')
dfa1
</code></pre> | python|pandas|python-2.7 | 0 |
372,378 | 57,781,833 | Split and use values from Excel columns | <p>I'm really new to coding. I have 2 columns in Excel - one for ingredients and other the ratio.</p>
<p>Like this:</p>
<pre><code>ingredients [methanol/ipa,ethanol/methanol,ethylacetate]
spec[90/10,70/30,100]
qty[5,6,10]
</code></pre>
<p>So this data is entered continuously. I want to get the total amount... | <p>You have already found the key part, namely using the <code>str.split</code> function.</p>
<p>I would suggest that you bring the data to a a long format like this: </p>
<pre>
| | Transaction | ingredients | spec | qty |
|---:|--------------:|:--------------|-------:|------:|
| 0 | 0 | metha... | python|excel|pandas | 2 |
372,379 | 57,890,100 | trying to seperate real and imaginary but it gets add up | <p>I have given a set of array where it contains real and imaginary values . I need to separate them and print it out . but its not working out . the output gives </p>
<blockquote>
<p>[3. +0.j 4.5+0.j 0. +0.j]</p>
</blockquote>
<pre><code>import numpy as np
array = np.array([3,4.5,3+5j,0])
real = np.isreal(array)
p... | <p>Referring to <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.real.html" rel="nofollow noreferrer">numpy</a> documentation you should do the following:</p>
<pre><code>print(array.real)
print(array.imag)
</code></pre> | python|numpy | 2 |
372,380 | 58,078,373 | Can't iterate through a dataframe while comparing to dictionary? | <p>I have both a dictionary and a dataframe, and I'm attempting to iterate through each row of the dataframe, comparing a specific column of the df to the value of the corresponding dictionary key. I am doing this through a for loop. However I keep getting errors. </p>
<p>One type error I'm getting is: 'Series' ob... | <p>By using <code>price = aug_new['Price Per']</code>, you are using the entire column (series) of 'Price per' instead of just the value in that row. </p>
<p>You can use:</p>
<pre><code>outliers = []
for idx in aug_new.index:
price = aug_new.loc[idx, 'Price Per']
drug = aug_new.loc[idx, 'Drug Name']
value... | python|pandas|dictionary | 0 |
372,381 | 57,745,829 | How to get the value with the smaller absolute value from a panda Series | <p>How can I get the value with the smaller absolute value from a panda Series?</p>
<p>Example code:</p>
<pre><code>import pandas as pd
def get_min_absvalue(values):
¿?
lst = [-2.1,2.2,-1.5]
ser = pd.Series(lst)
min_absvalue = get_min_absvalue(ser)
#min_absvalue must be -1.5 here
</code></pre> | <p>You can use <code>min</code> with <code>abs</code> as a key function:</p>
<pre><code>import pandas as pd
def get_min_absvalue(values):
return min(values, key = abs)
lst = [-2.1, 2.2, -1.5]
ser = pd.Series(lst)
min_absvalue = get_min_absvalue(ser)
print(min_absvalue)
</code></pre>
<p>Output:</p>
<pre><code... | python|python-3.x|pandas|series | 3 |
372,382 | 58,090,582 | fuzzy join with multiple conditions | <p>I know there are questions with similar titles out there, but none of them really answers my question.
I have a data frame as below. The "index" column is actually timestamp. Column A is how many tones of materials have been dumped to a crusher. Column B is the crushing rate at each timestamp. What I want to know is... | <p>create the DF combined A & B:</p>
<pre><code>A = {'index':range(1,11),'A':[300,0,400,0,0,0,0,0,100,0]}
B = {'index':range(1,11),'B':[102,103,94,120,145,114,126,117,107,87]}
df_A = pd.DataFrame(data=A)
df_B = pd.DataFrame(data=B)
df_com = pd.concat([df_A,df_B],axis=1).drop('index',axis=1)
</code></pre>
<p>creat... | python|pandas | 1 |
372,383 | 57,962,989 | Pandas show dataframe columns with boolean selection | <p>Let's say i have this dataframe:</p>
<pre><code>df:
W X Y Z
A 2.706850 0.628133 0.907969 0.503826
B 0.651118 -0.319318 -0.848077 0.605965
C -2.018168 0.740122 0.528813 -0.589001
D 0.188695 -0.758872 -0.933237 0.955057
E 0.190794 1.978... | <p>Well you can certainly do it with loc, but need a little twist:</p>
<pre><code>import pandas as pd
a = {'a':[4,5,6,3,-3,1,-3],'b':[3,5,-2,5,-6,3,5]}
df = pd.DataFrame(a)
df = df.T
print(df)
</code></pre>
<p>Output: </p>
<pre><code> 0 1 2 3 4 5 6
a 4 5 6 3 -3 1 -3
b 3 5 -2 5 -6 3 5
</code></pre>
... | python|pandas|numpy | 0 |
372,384 | 57,963,534 | Pandas Conditional new column based on period found in other dataframe column | <p>I have a dataframe with file extensions. Some have periods in them I am trying to create a new column flagging which ones contain a period or not conditionally. If I wanted to just get the rows that contain a period I would just use: <code>send_rec_file_url[send_rec_file_url['file_name'].str.contains('\.')]</code>... | <p>You need to use the mask to change the value of the column. </p>
<pre><code>df['has_period'] = 'no'
df.loc[df['file_name'].str.contains('\.'), 'has_period'] = 'yes'
</code></pre>
<p>Output:</p>
<pre><code> file_name has_period
0 png no
1 jpg no
2 jpg ... | python|pandas | 3 |
372,385 | 57,746,737 | How to get the day difference between date-column and maximum date of same column or different column in Python? | <p>I am setting up a new column as the day difference in Python (on Jupyter notebook). </p>
<p>I carried out the day difference between the column date and current day. Also, I carried out that the day difference between the date column and newly created day via current day (Current day -/+ input days with timedelta f... | <p>Although I was busy with this question for 2 days, now I realized that I had a big mistake. Sorry to everyone. </p>
<p>The reason that can not take the maximum value as date comes from as below.</p>
<p>Existing one: t=data_signups[["date_joined"]].max()</p>
<p>Must-be-One: t=data_signups["date_joined"].max()</p>... | python|pandas|datetime64 | 0 |
372,386 | 57,912,734 | How to iterate to calculate a set of values in a new column | <p>I am trying to create a new column "roc_30d" using another column "rand_price". The new column is essentially rate of change 30 days. The formula would be (current price - price 30 periods ago) / (price 30 periods ago). </p>
<p>I've tried to iterate over "rand_price" in order to calculate the values of the new col... | <pre><code>i-(i-30) / (i-30)
</code></pre>
<p>This is algebraically equivalent to <code>i-1</code>. You have a couple of problems:</p>
<ol>
<li>You subtract 30 from the current price. What you say you want is to get the price from 30 days ago. To do that, you need to iterate through <em>rows</em>, not the values i... | python|pandas|iteration | 0 |
372,387 | 57,967,192 | How to use zip to easily get the dataframe for each of the coin pair in the list through a defined function? (pandas) | <p><strong>I have defined a function which can get the history price for the coin:</strong></p>
<pre class="lang-py prettyprint-override"><code>def get_price(pair):
df=binance.fetch_ohlcv(pair,limit=258,timeframe="1d")
df=pd.DataFrame(df).rename(columns={0:"date",1:"open",2:"high",3:"low",4:"close",5:"volume"}... | <p>You may have to do another function if you want to keep the things the way you have.
The first part (where you get the df seems fine since you have checked it). The issue is with the second part, where you are trying to run that function. Change is as below may help.</p>
<p><strong>Example</strong> Run this & i... | python|pandas|data-analysis | 1 |
372,388 | 57,856,297 | ETL process using Python | <ol>
<li>Load the CSV file (using Python). </li>
<li>Output the total number of rows and columns. </li>
<li>Output the number of non-null rows (by column). </li>
<li>Output the number of null values (by column). </li>
<li>Output the number of null values for all columns. </li>
<li>Output the number of duplicate rows</l... | <p>You are not passing a dataframe to analysingData.. you're passing the path+filename.</p> | python|pandas|csv|spyder | 2 |
372,389 | 57,994,144 | extract pos_tag_sents from pandas series | <p>following the advice from the thread <a href="https://stackoverflow.com/questions/41674573/how-to-apply-pos-tag-sents-to-pandas-dataframe-efficiently">How to apply pos_tag_sents() to pandas dataframe efficiently</a> I run the code to identify different pos for the text in one of my variables. </p>
<p>Now that I man... | <p>So I am assuming you have one column in the dataframe where each row is a list of tuples. Please correct me if I am wrong. From that column you want to create new columns for each 'Tag'. Do you think following is what will achieve what you want to do?</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.D... | python|pandas|nltk|part-of-speech | 0 |
372,390 | 58,088,511 | Adding two arrays using a for loop | <pre><code> from numpy import *
arr1 = array([5,10,15,20,30])
arr2 = array([55,16,1,280,60])
arr3 = ([])
k =0
for num1 in arr1:
num3 = num1 + arr2[k]
arr3.append(num3)
k +=1
print(arr3)
</code></pre>
<p>what ... | <p>It's generally a bad idea to <code>from package import *</code> as you can override other packages in your namespace. Numpy has a built in solution to add two arrays together:</p>
<pre><code>import numpy as np
arr1 = np.array([5,10,15,20,30])
arr2 = np.array([55,16,1,280,60])
arr1+arr2
</code></pre>
<p><code>array... | python|arrays|python-3.x|numpy|for-loop | 2 |
372,391 | 57,951,034 | How to merge multiple Numpy array into single array | <p>I want to merge multiple 2d Numpy array of shapes let say (r, a) ,(r,b) ,(r,c),...(r,z) into single 2d array of shape (r,a+b+c...+z)</p>
<p>I tried np.hstack but it needs the same shape & np.concat operates only on tuple as 2nd array.</p> | <p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow noreferrer">np.concatenate</a> or <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.hstack.html" rel="nofollow noreferrer">np.hstack</a>. Here is an example:</p>
<pre><code>>>> ... | python|numpy-ndarray | 1 |
372,392 | 58,006,366 | Change NaT to blank in pandas dataframe | <p>I have a dataframe (<code>df</code>) that looks like:</p>
<pre><code> DATES
0 NaT
1 01/08/2003
2 NaT
3 NaT
4 04/08/2003
5 NaT
6 30/06/2003
7 01/03/2004
8 18/05/2003
9 NaT
10 NaT
11 31/10/2003
12 NaT
13 NaT
</code></pre>
<p>I am struggling to ... | <p>There is problem <code>NaT</code> are strings, so need:</p>
<pre><code>df["DATES"] = df["DATES"].replace('NaT', '')
</code></pre> | python|pandas | 7 |
372,393 | 58,045,476 | PANDAS loc function is not working, giving error | <p>I am new to Pandas, I am giving this command <code>summer.loc["HAJOS, Alfred"]</code></p>
<p>I am getting error like this</p>
<pre><code> KeyError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance... | <p>Try this:</p>
<pre><code>df.loc[df['Athlete'] == 'HAJOS, Alfred']
</code></pre>
<p>Since 'HAJOS, Alfred' is not in your dataframe index, you can use boolean indexing.</p>
<p>Or use <code>query</code></p>
<pre><code>df.query('Athlete == "HAJOS, Alfred"')
</code></pre> | pandas | 1 |
372,394 | 58,095,983 | How to lookup corresponding encoded elements with pandas | <p>I have two series of data, each value is a list. </p>
<pre><code> amenities amenity_ids
0 [TV,Wifi,Kitchen,"Free parking on premises","I... [64, 1,129, 66, 4, 134...]
1 [TV,Wifi,Kitchen,"Family/kid friendly",Washer,... [1, 129, 2, 4, 71, 8, 77...]
</code></pre>
<p>T... | <p>You may use Zip function to create a dictionary object for mapping values with amenities. For example:</p>
<pre><code>l1 = ["TV","Kitchen","wifi"]
l2 = [20,40,15]
d= dict(zip(l1,l2))
</code></pre>
<p>Output: <code>{'TV': 20, 'Kitchen': 40, 'wifi': 15}</code></p> | python|pandas | 0 |
372,395 | 58,120,731 | Taking the average of date_times | <p>I have a dataset which I attached a sample of it. My goal is to find the average time that it takes to finish each process. I use the following code:</p>
<pre><code>import pandas as pd
df = pd.read_csv(....)
df['Start Time']=pd.to_datetime(df['Start Time'])
df['Finish Time']=pd.to_datetime(df['Finish Time'])
df['Pr... | <p>I use the following code and it worked:</p>
<pre><code>df['Duration'] = (df['Duration']/np.timedelta64(1,'D'))*24
</code></pre> | python|pandas | 0 |
372,396 | 58,101,799 | for each row in df subtract another df | <p>Example.</p>
<pre><code>df1 is 1000 x 20
df2 is subset of df1 10 x 20
</code></pre>
<p>I want each row of df1 to subtract df2 and summing it together. This will return another df3 as 1000 x 10 </p> | <p>you can use numpy broadcast feature to do this. For that you need to reshape your data to make it broadcastable</p>
<p>you can do something similar to sudo code below</p>
<pre class="lang-py prettyprint-override"><code>df1_data = df1.values.reshape(-1, 10, 20)
df2_data = df2.values
result = df1_data - df2_data #... | python|pandas | 0 |
372,397 | 57,808,599 | How to extract the correlation matrix features to a list if their values is beyond a certain threshold | <p>After a read the first chapter in the book "Hands-On Machine Learning with Sci-kit Learn and Tensorflow" I wanted to do my own little project and learn a bit. So I wanted to make it simple and only use simple linear regression with features that correlate with Sale Price above abs(0.1).</p>
<pre><code>corr_matrix =... | <p>Replacing</p>
<pre><code>for feature, value in corr_matrix['SalePrice']
</code></pre>
<p>with</p>
<pre><code>for feature, value in corr_matrix['SalePrice'].iteritems():
</code></pre>
<p>gets the job done!
Thanks @jottbe for the solution and all the others for replying!</p> | python|pandas | 0 |
372,398 | 57,915,312 | How do I run a list of CSV into a function? | <p>I am not sure how exactly to ask this question so please forgive my ignorance.</p>
<p>I am running a function from many files. And after importing df I get the outcome into a csv file. </p>
<pre><code>df=pd.read_csv("C:\Users\filename.csv ")
years = 5
days = 365
out_put, productivity= timeresult.input_data.outb... | <p>If I understand your problem correctly, this code is for you: </p>
<pre><code>years = 5
days = 365
filelist = ["C:\Users\jan.csv", "C:\Users\feb.csv", "C:\Users\mar.csv"]
for filepath in filelist:
df = pd.read_csv(filepath)
out_put, productivity= timeresult.input_data.outbuild(df, year, days)
df.ind... | python|pandas|function|loops|csv | 1 |
372,399 | 57,903,518 | Interpreting a sigmoid result as probability in neural networks | <p>I've created a neural network with a sigmoid activation function in the last layer, so I get results between 0 and 1. I want to classify things in 2 classes, so I check "is the number > 0.5, then class 1 else class 0". All basic.
However, I would like to say "the probability of it being in class 0 is <code>x</code> ... | <p>As pointed out by Teja, the short answer is no, however, depending on the loss you use, it may be closer to truth than you may think.</p>
<p>Imagine you try to train your network to differentiate numbers into two arbitrary categories that are <code>beautiful</code> and <code>ugly</code>. Say your input number are e... | python|tensorflow|sigmoid | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.