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
368,900
65,423,190
Python Shapely - Checking if line contains a point
<p>I am having troubles checking if a <code>LineString</code> contains the <code>Point</code> resulting from an intersection with a <code>Polygon</code> using the Shapely library.</p> <p>Example code:</p> <pre><code>l = LineString([(5.653154885795476, 6.418676641285647), (6.132921674075812, 5.995573963137367)]) o = Lin...
<p>You are right, it is a floating point precision issue. You can use this workaround:</p> <pre><code>from shapely.geometry import LineString l = LineString([(5.653154885795476, 6.418676641285647), (6.132921674075812, 5.995573963137367)]) o = LineString([(5, 7.5), (6, 6)]) p = l.intersection(o) print(l.distance(p)&lt...
python|numpy|intersection|shapely
1
368,901
65,159,952
Disable tensorflow retracing warning in keras
<p>I have created keras functional API model and now I'm trying to look into it's layers outputs creating submodels for every layer which starts with original model's input and ends with the layer of my choosing. I don't understand what is the proper way to do this without getting</p> <pre><code>WARNING:tensorflow:11 o...
<p>It's possible to disable warnings using <code>tf.get_logger().setLevel('ERROR')</code>, as explained in <a href="https://stackoverflow.com/a/55142079/8171457">this answer</a>.</p>
python|tensorflow|keras
5
368,902
65,319,998
I can't change the shape of the numpy array
<p>I can't change shape of numpy array</p> <pre><code>dataset[i].shape # (1134, ) dataset[i] = dataset[i].reshape((18, 63)) ValueError: could not broadcast input array from shape (18,63) into shape (1134) </code></pre>
<p>I do not know what your original intentions are, but your code is attempting to do an element-by-element assignment, between an array on the LHS and an array on the RHS.</p> <p>The array on the LHS is <code>dataset[i]</code>, which has shape <code>(1134,)</code>.</p> <p>The array on the RHS has shape <code>(18,63)</...
python|numpy|reshape
2
368,903
65,284,363
Pandas python reversing the the values and rows for column within a dataset
<p>How do I reverse the rows in a column using pandas, as in I want to change the value of the last row, <code>row 4</code> and switch it with <code>row 0</code>. so instead of <code>row:0</code> equaling 1 it would equal to 10.</p> <p>Code associated with the code down below:</p> <pre><code>import pandas as pd data =p...
<p>If need swap first and last value of column <code>sets</code> use:</p> <pre><code>data.loc[data.index[[0, -1]], 'sets'] = data.loc[data.index[[-1, 0]], 'sets'].to_numpy() </code></pre> <p>Or:</p> <pre><code>data.iloc[[0, -1], data.columns.get_loc('sets')] = data.iloc[[-1, 0], data.columns.get_loc('sets')].to_numpy(...
python|python-3.x|pandas|database|dataframe
1
368,904
65,369,155
How to plot (correctly) lineplot from pandas dataframe?
<p>I'm plotting a lineplot from a pandas dataframe. However the labels are overlapped on the right side of the X axis instead of to the relative point mark on the line. What is missing?</p> <p>Here the full code and the pic</p> <pre><code>#importing pandas package import pandas as pd import matplotlib.pyplot as plt imp...
<p>You seem to be using the y-values (<code>df.Score</code>) as the positions of your x-ticks.</p> <p>I assume you meant</p> <p><code>ax.set_xticks(df['Split'])</code></p>
pandas|dataframe|matplotlib
1
368,905
65,098,714
Value Counts of all columns in a df?
<p>I have a <strong>df</strong> such as:</p> <pre><code>Monday | Tuesday | Friday | January | Weekday True False True False True False False False False False True True False False True False False False False False </code></pre> <p>I want to calcula...
<p>apply value value_counts to the dataframe . Groupby the resulting dataframe's index and sum</p> <pre><code>g=df.apply(lambda x: x.astype(str).value_counts(normalize=True)) g.groupby(g.index).sum() Monday Tuesday Friday January Weekday False 0.5 0.75 0.75 1.0 0.5 True 0.5 0.2...
python|python-3.x|pandas
3
368,906
65,194,356
the error message of reading a large size csv file using datatable
<p>I have the following code script to open a <code>csv file</code>:</p> <pre><code> import datatable as dt file_path=os.path.join(root_path, &quot;train.csv&quot;) print('file_path is ',file_path) dt.fread(file_path) </code></pre> <p><strong>While running this code it gives the following error</strong>...
<p>I Think You Can Use Pandas</p> <pre><code>import pandas as pd df = pd.read_csv(csv_file_path) print(df) </code></pre>
python|python-3.x|pandas
0
368,907
65,385,770
Convert Rows to Columns and Forward Fill First Column
<p>I have the following dataframe which has a unique URL in the first column, followed by a random number of unique keywords. I would like to transpose the keywords into a single row and forward fill the url as per my desired output below.</p> <pre><code>0 1 2 3 4...
<p>Doing it with <code>melt</code> is pretty straight forward.</p> <pre><code>df = df.melt(id_vars='0', value_vars=df.columns[1:], value_name='1').drop('variable', axis=1).sort_values('0') </code></pre> <p>This only works properly if your empty cells are shown as <code>NaN</code> in your DataFrame. From the example you...
python|pandas|dataframe
2
368,908
65,210,822
How to detect the given model is a keras or scikit model using python?
<p>If I want to determine the type of model i.e. from which framework was it made programmatically, is there a way to do that? I have a model in some serialized manner(Eg. a .h5 file). For simplicity purposes, assume that my model can be either tensorflow's or scikit learn's. How can I determine programmatically which ...
<p>you can either use <code>type(model)</code> to see its type</p> <p>you can also use <code>help(model)</code> to get the doc string from model.</p> <p>you can also use <code>dir(model)</code> to see its member function or parameters.</p> <p>you can also use <code>import inspect</code> <code>inspect.getsource(model)</...
python|tensorflow|machine-learning|keras|scikit-learn
0
368,909
65,208,475
TypeError: Expected binary or unicode string, got item {
<p>I was using a custom code recognizing objects in real time using the webcam, but during the process of creating the labels this error appeared, I'm using python 3.7 and TensorFlow 1.15, which is wrong and there is an easier way to use real-time object recognition?</p> <p>label map:</p> <pre><code>labels = [ {'na...
<p>I found the answer in another link:</p> <p><a href="https://stackoverflow.com/questions/66665505/typeerror-expected-binary-or-unicode-string-got-item-error">TypeError: Expected binary or unicode string, got item error</a></p> <p><a href="https://i.stack.imgur.com/OOmL3.png" rel="nofollow noreferrer"><img src="https:...
python|tensorflow|opencv|image-recognition
2
368,910
65,171,629
How to subtrac a numpy array element-by-elemnt by another numpy array
<p>I have two <code>numpy</code> arrays, with just the 3-dimensional coordinates of two molecules.</p> <p>I need to implement the following equation, and I'm having problems in the subtraction of each coordinate of one of the arrays by the second, and then square it.</p> <p><a href="https://i.stack.imgur.com/Wi634.png...
<p>It's numpy you can easily do it using the following example:</p> <pre><code>import numpy as np x1 = np.random.randn(3,3,3) x2 = np.random.randn(3,3,3) res = np.sqrt(np.mean(np.power(x1-x2,2))) </code></pre>
python|arrays|numpy
1
368,911
65,317,294
Eliminate array rows having DUPLICATE PAIRS of elements
<p>Consider an array whose rows hold <strong>pairs</strong> of elements.</p> <pre><code>import numpy as np a = np.array([[1,2, 3,4, 5,6, 7,8], [1,2, 3,4, 1,2, 3,4], [4,5, 5,4, 6,7, 5,6], [6,7, 8,9, 8,9, 0,1], [4,5, 4,5, 4,5, 4,5], [3,...
<p>Right now the array in your question is just formatted using spaces to show the pairs. First reshaping your numpy array so the pairs are together would be helpful.</p> <p>Then you can use <code>np.unique</code> with an <code>axis</code> argument to determine if there are duplicate pairs in each row.</p> <p>Here is s...
arrays|numpy
1
368,912
65,334,158
Pandas groupby multiple columns, but treat separately (don't want unique combinations)
<p>Say I have the following dataframe</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>c1</th> <th>c2</th> <th>c3</th> </tr> </thead> <tbody> <tr> <td>p</td> <td>x</td> <td>1</td> </tr> <tr> <td>n</td> <td>x</td> <td>2</td> </tr> <tr> <td>n</td> <td>y</td> <td>1</td> </tr> <tr> <td>p</td> <t...
<p>As Karan said, just call <code>groupby</code> on each of your label columns separately, then concatenate (and transpose) the results:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame([['p', 'x', 1], ['n', 'x', 2], ['n', 'y', 1], ...
python|pandas
0
368,913
65,355,647
Dask how to open json with list of dicts
<p>I'm trying to open a bunch of JSON files using <code>read_json</code> In order to get a Dataframe as follow</p> <pre><code>ddf.compute() id owner pet_id 0 1 &quot;Charlie&quot; &quot;pet_1&quot; 1 2 &quot;Charlie&quot; &quot;pet_2&quot; 3 4 &quot;Buddy&quot; &quot;...
<p>The invocation you want is the following:</p> <pre><code>dd.read_json(&quot;data.json&quot;, meta=meta, blocksize=None, orient=&quot;records&quot;, lines=False) </code></pre> <p>which can be largely gleaned from the docstring.</p> <ul> <li>meta looks OK from your code</li> <li>blocksize must be None, since...
json|python-3.x|pandas|dask
1
368,914
65,409,369
How to access the returned varible from Ipywidgets output widget
<p>I am using ipywidgets in a class to clean the dataset. Using the ipywidgets output tab, I am able to print the cleaned dataframe, but I am unable to access the returned dataframe variable (df_clean) in the next code cells. I am not sure what am missing here, spent a day exploring...</p> <p><a href="https://colab.res...
<p>Here you go,</p> <p>Following you can put in your utils.py or whatever you want to call this module.</p> <pre><code>from ipywidgets import Button import ipywidgets as widgets from IPython.display import display,clear_output import pandas as pd train = pd.read_csv('https://raw.githubusercontent.com/taknev83/datasets/...
python|pandas
0
368,915
65,244,438
Pandas .pivot_table() reorder the index in chronological order
<p>Im trying to create a pivot table out of the seaborn flights dataset. When I come to make a pivot table for a heat map the index column is ordered alphabetically when I want to order it chronologically from Jan to Dec. Does anyone know how to do this? I have deleted the values in the pivot table to make it look tidi...
<p>One way would be just reindex and provide the index list as follows:</p> <p>Code :</p> <pre><code>import calendar month_names = [calendar.month_name[i] for i in range(1,13)] # ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] newdf = df.rein...
python|pandas|dataframe|pivot-table|seaborn
0
368,916
65,270,155
Grouping by a Pandas dataframe and putting column back
<p>I have the following pandas dataframe:</p> <p><a href="https://i.stack.imgur.com/Eznin.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Eznin.png" alt="enter image description here" /></a></p> <p>I want to replicate the following SQL Query:</p> <pre><code>SELECT cars, city, CASE WHEN miles_travel...
<p>If you want to make <code>ratio</code> for just combinations of <code>city</code> and <code>cars</code> and ignore the cases as the quotient of the sum of <code>complaints</code> and <code>calls</code> ignoring rows where <code>miles_travelled</code> is 100 then this will work.</p> <pre><code># filter to ignore rows...
sql|pandas|sqlite
0
368,917
65,089,594
Networkx maximal_independent_set reproducibility
<p>How can I get reproducible results in a Jupyter Notebook (Python3)?</p> <p>Defining a seed for the main random generators seems to be not enough, see MWE below:</p> <pre><code>import numpy as np import random import os random.seed(0) np.random.seed(0) os.environ['PYTHONHASHSEED']=str(0) </code></pre> <pre><code>im...
<p>The short answer for your question is: In the current implementation it is not reproducible - if taking restarts of kernel into account.</p> <h2>Long Answer</h2> <p>You need to use <a href="https://networkx.org/documentation/stable/reference/classes/ordered.html" rel="nofollow noreferrer"><code>OrderedGraph</code></...
numpy|networkx|reproducible-research
2
368,918
65,200,418
2D numpy array showing as 1D
<p>I have a numpy ndarray <code>train_data</code> of length <code>200</code>, where every row is another ndarray of length <code>10304</code>.</p> <p>However when I print <code>np.shape(train_data)</code>, I get <code>(200, 1)</code>, and when I print <code>np.shape(train_data[0])</code> I get <code>(1, )</code>, and w...
<p>This is because the arrays are constructed to be arrays of objects. Basically each element in the array is pointing to another array of size (1, ) which points to another array of size (10304, ). This is not equivalent to a normal ndarray in numpy so the shape is not recognized correctly. You can check this by looki...
python|numpy
2
368,919
65,243,028
What does np.fft.fftfreq actually do?
<p>I have a monthly time series and I am taking the discrete fourier transform of it. However I am confused as to how numpy converts the time domain into frequency domain?</p> <p>I am using np.fft.fftfreq and my time array is is 708 indices long and each measurement of the data is computed every month.</p> <p>This is t...
<p>Exactly what fftfreq is doing can be found <a href="https://numpy.org/doc/stable/reference/generated/numpy.fft.fftfreq.html" rel="nofollow noreferrer">here</a></p> <p>And more information on the relationship between the input signal and the Fourier transform can be found <a href="http://paulbourke.net/miscellaneous/...
python|numpy|jupyter|fft
0
368,920
65,286,955
RuntimeError: Given groups=1, weight of size [64, 1, 4, 4], expected input[256, 3, 32, 32] to have 1 channels, but got 3 channels instead
<p>Could you help me fix the above error? If I were to load the mnist dataset, there is no error popping up. The error has to do with the dimension of the other datasets, cifar10, fmnist and so on and cannot be run when applied to these sets. Any help appreciated.</p> <pre><code> # noinspection PyUnresolvedReferences i...
<p>You have to set the <code>--n_channels</code> otherwise <code>args.n_chanels</code> will default to <code>1</code> <a href="https://github.com/bunnech/gw_gan/blob/master/model/utils.py" rel="nofollow noreferrer">as see here</a>. The example given <a href="https://github.com/bunnech/gw_gan/blob/master/run_gwgan_cnn.s...
python|pytorch
0
368,921
65,144,291
Can anyone guide me on how to calculate the frequency in hz from wav file? The wave file is of 50 secs
<p>I am using numpy library to calculate freq = np.fft.rfftfreq(len_data, 1.0 / rate) , If I am not wrong then this frequency is without unit . <strong>How</strong> <strong>can i convert it into hertz</strong>. I am using the following code :</p> <pre class="lang-py prettyprint-override"><code> import numpy as np impor...
<p>The numpy FFT package has a built-in function to calculate the frequency vector to go along with your FFT output. Note that <code>scipy</code> outputs the sample <em>rate</em> wile <code>numpy</code> wants the sample <em>spacing</em> so you must invert it first.</p> <pre><code>import numpy as np def getFrequencies...
python|numpy|scipy|fft|frequency
0
368,922
65,093,339
Extracting words from column in pandas df using regex
<p>I have a pandas df column that contains English words, some were entered as eg. Ant(small,white). I want to remove the bracketed words and put the in a new column. The code I used is written below</p> <pre><code>pattern = re.compile('.*\((\w+)\).*') df_new['Context']= [re.search(pattern,i) for i in df_new.English_wo...
<p>You can use</p> <pre class="lang-py prettyprint-override"><code># Extract all occurrences of strings inside parentheses and join them with comma + space df_new['Context'] = df_new['English_words'].str.findall(r'\(([^()]+)\)').str.join(', ') # Remove them from the original column df_new['English_words'] = df_new['Eng...
python|regex|pandas
0
368,923
65,451,353
Why is the scipy.sparse.csr_matrix not storing all the values being passed to it?
<p>So I am currently trying to store a large sparse dataset (4.9 million rows and 6000 columns) in the csr_format. The dense format causes a memory error so I am loading it in line by line from a tsv file. Here is how I do that:</p> <pre><code>import numpy as np from scipy.sparse import csr_matrix rows=np.empty(4865518...
<p>np.empty doesn't initialize arrays to zero. The value of rows[0] could be anything.</p> <blockquote> <p>empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caut...
python|numpy|scipy|sparse-matrix
1
368,924
50,014,129
Tensorflow object detection api mis classifying objects
<p>I followed a simple <a href="https://www.youtube.com/watch?v=COlbP62-B-U&amp;list=PLQVvvaa0QuDcNK5GeCQnxYnSSaar2tpku" rel="nofollow noreferrer">tutorial</a> to train a custom object detector.<br> I got my loss up to 0.6, however my issue is that the detected will classify other objects as what I've trained it with. ...
<p>I faced exactly the same issue, where the model "remembered" the previous objects. There is a new configuration in the config file that is was not implemented when the video was made.</p> <p>Inside the <code>ssd_mobilenet_v1_pet.config</code> file you have to specify the path to the checkpoint where the training wi...
tensorflow
1
368,925
49,946,192
How to improve recall of faster rcnn object detection model
<p>I'm retraining a faster rcnn inception coco model for detecting brand of products on shelf. </p> <p>I stopped the model around 400k steps when total loss dropped under 0.1 over a period of time. The recall was around 65% and precision was 40% with 95% confidence cut-off threshold.</p> <p>Learning rate started at 0...
<p>You could try using image augmentation to expand your training dataset. 300 images is not much. Try looking at <a href="https://github.com/aleju/imgaug" rel="nofollow noreferrer">https://github.com/aleju/imgaug</a>.</p>
tensorflow|object-detection
2
368,926
50,201,469
tf.contrib.data.shuffle_and_repeat breaks tf.contrib.data.rejection_resample
<p>With TF1.7 we added to our input pipeline the new tf.contrib.data.shuffle_and_repeat. Our pipeline also uses tf.contrib.data.rejection_resample to balance our data set</p> <p>Alas, when both are used - the balancing does not balance the DataSet. (It's not failing, but seems that it is not filtering the dataset as r...
<p>@Shahar Karny, Im using TF1.8 and I'm experiencing the same issue - moreover, <em>rejection_resample</em> fails to do its resampling even when a <strong>normal</strong> <em>shuffle</em> is being used prior to it.</p> <p>For example, <strong>this works</strong>:</p> <pre><code>dataset = tf.data.Dataset.from_tensor_...
tensorflow
0
368,927
50,002,754
How to use Group by, Pivot_table, Stack & Unstack to reshape Pandas Dataframe
<p>I have a Dataframe that looks like: <a href="https://i.stack.imgur.com/kXHVD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kXHVD.png" alt="enter image description here"></a></p> <p>I want to change it to look like: <a href="https://i.stack.imgur.com/1fGE3.png" rel="nofollow noreferrer"><img src...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a> and <a href="http:...
python|pandas|dataframe|pivot-table|reshape
4
368,928
50,045,625
Change Values of Column in Python based on multiple conditions
<p>I'm trying to insert a new column in Python using Pandas based on an "or" condition, but I'm having trouble with the code. Here's what I'm trying to do:</p> <p>If the column "Regulatory Body" says FDIC, Fed, or Treasury, then I want a new column "Filing" to say "Yes"; otherwise, say "No". This is what I've written....
<p>Yes. Use <code>pd.Series.isin</code>:</p> <pre><code>bodies = {'FDIC', 'Fed', 'Treasury'} df200['Filing'] = np.where(df200['Regulatory Body'].isin(bodies), 'Yes', 'No') </code></pre> <p>Alternatively, use <code>pd.Series.map</code> with the Boolean array you receive from <code>pd.Series.isin</code>:</p> <pre><co...
python|python-3.x|pandas|dataframe
3
368,929
50,132,514
Keras Tensorboard Error when Histogram Frequency active
<p>I am running a simple Neural Network with Keras, backend Tensorflow, when trying to use Tesorboard to monitor training.</p> <p>My model is the following:</p> <pre><code>import keras from keras.layers.core import Dense, Activation, Dropout from keras.models import Sequential model = Sequential() model.add(Dense(32,...
<p>This may be related to <code>K.learing_phase()</code>. Especially if you have done <code>K.set_learning_phase(1)</code> before.</p> <p>To diagnose: Run <code>print(K.learning_phase())</code>, if it returns an int, then this problem is almost surely related to this issue. Try removing all sentences related to <cod...
python|python-3.x|tensorflow|keras|tensorboard
0
368,930
50,209,774
`tf.set_random_seed()` equivalent for operations seed?
<p>Title pretty much explains everything. Do you know if there exists an equivalent to <code>tf.set_random_seed()</code> for the operations seed in tensorflow. I'm trying to initialize exactly same weights at two exact NN defined into two different graphs, so I was wondering if there is a way to globally set the operat...
<p>According to the documentation of <a href="https://www.tensorflow.org/api_docs/python/tf/set_random_seed" rel="nofollow noreferrer"><code>tf.set_random_seed()</code></a> setting only the graph level seed should achieve what you are looking for:</p> <blockquote> <p>If the graph-level seed is set, but the operation se...
python|python-3.x|tensorflow
2
368,931
49,814,768
Use yaml file to rename Pandas dataframe columns
<p>A have heard somewhere that is possible to pass a yaml file to python script to rename columns in pandas dataframe. But I have no idea how to do that and not sure if I found anything useful. </p> <p>For example, yaml:</p> <pre><code>mappings: new_column_name1: [old_name_1, old_name_2, old_name_3, old_name_4], ...
<p>Your example doesn't seem to be legal YAML. Rather, it should be something like:</p> <pre><code>mappings: new_column_name1: - old_name_1 - old_name_2 - old_name_3 - old_name_4 </code></pre> <p>and so on.</p> <p>In any case, if you install <code>pyaml</code>, you can use som...
python|pandas|yaml|rename
1
368,932
50,105,114
Remove selective hyphenations / punctuations based on list of exceptions
<p>Remove selective hyphenations</p> <pre><code>import pandas as pd s = pd.Series(['do not-remove this-hyphen but remove-all of these-hyphens']) list_to_keep =['not-remove', 'this-hyphen'] </code></pre> <p>I want to keep the word hyphenations in the 'list to keep' but replace all other ‘-‘ in the series with a spac...
<p>You could try this:</p> <pre><code>S = s.str.split(expand=True).T[0] ' '.join(np.where(S.isin(list_to_keep), S, S.str.replace('-', ''))) </code></pre> <p>Output:</p> <pre><code>'do not-remove this-hyphen but removeall of thesehyphens' </code></pre> <p>How it works.</p> <ul> <li>Create a pd.Series, S, using the ...
python|pandas
2
368,933
49,799,356
pandas - Plot distribution of column variable
<p>I'm trying to visualize some data, but I'm not very experienced with the subject, and am having trouble finding the best bay to get what I'm looking for. I've searched around and found similar questions, but nothing that'll answer exactly what I want, so hopefully I'm not duplicating a common question.</p> <p>Anywa...
<p>You might be looking for something like</p> <pre><code>df.procedure_id.groupby(df.patient_id).nunique().hist(); </code></pre> <p>Explanation:</p> <ul> <li><p><code>df.procedure_id.groupby(df.patient_id).nunique()</code> finds the number of unique procedures per patient.</p></li> <li><p><code>hist()</code> plots a...
python|pandas|visualization
5
368,934
49,826,642
Forecasting using LSTM
<p>How can I use Long Short-term Memory (LSTM) to predict a future value x(t+1) (out of sample prediction) based on a historical dataset. I read and tried many web tutorials for forecasting and prediction using lstm, but still far away from the point. What's the exact procedure to do this prediction? Is it just as simp...
<p>Can you provide the framework you are using? tensorflow? pytorch? which web tutorials specifically?</p> <p>Assuming you are going tensorflow, you can copy and paste code from one of these, test that it works on the provided dataset, then modify the input encoding functions to fit your dataset, then run on your dat...
python|tensorflow|machine-learning|keras|lstm
1
368,935
49,864,278
Compare dataframe value with key range in dictionary and return value
<p>I'm trying to compare a value in a dataframe with key ranges in a dictionary and grab the corresponding dictionary value. Been looking at loop and iterations, however, as a beginner, can't get it working.</p> <p>Example:</p> <pre><code>import pandas as pd colors = {range(0,50):"red",range(50,100):"blue", ...
<p>You can vectorise your calculation using <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select</code></a>. This will be more efficient, and easier to maintain, than a loopy <code>if</code> / <code>else</code> construct.</p> <pre><code>im...
python|python-3.x|pandas|dictionary|dataframe
2
368,936
49,960,871
Word frequency per pandas dataframe row
<p>I'm trying to figure out how to get most frequent words per dataframe row - lets say the top 10 most frequent words. I have code that gets me most frequent words for the whole DF, but now I need to be more granular.</p> <pre><code>import pandas as pd import numpy as np df1 = pd.read_csv('C:/temp/comments.csv',enco...
<p>There are several different ways you can do this, depending on whether you want a dataframe, series of dictionaries, or list of dictionaries.</p> <pre><code>from collections import Counter # dataframe of word counts per row res = df['comments'].str.split().apply(pd.value_counts) # series of dictionaries of word c...
python|string|pandas|dataframe
2
368,937
50,183,943
how do i manipulate decimals in pandas data frame
<p>I have a data frame (df) like this:</p> <pre><code>euro token 200.0 65.78947368421053 9997.8 2631.0 </code></pre> <p>Whenever there is only a .0, I want to get rid of the .0 but when there is a single decimal like .8 in "euro" I want to have to decimals like you would normally have with a currency. So the de...
<p>You can follow this way:</p> <pre><code>#sample euro = [2, 2.3, 3.0, 4.0, 5.4444] new_euro = [round(x) if x == round(x) else "{0:.2f}".format(x) for x in euro] print(new_euro) [2, '2.30', 3, 4, '5.44'] </code></pre>
python|pandas|formatting|numbers|decimal
1
368,938
49,880,375
Format pandas y axis to show time instead of total seconds
<p>i have measurements in a dataframe. Columns are different objects. Index is a datetime64 index. Now for each date I have a measurement in total seconds (int) for each column.</p> <p>Everything plots quite nice, my only problem instead of showing 6000 seconds on the y axis i want to show 1:40 to indicate 1 hour and ...
<p>It is possible, but <a href="https://stackoverflow.com/questions/23543909/plotting-pandas-timedelta"><code>ploting timedelta</code></a> is not supported yet natively.</p> <pre><code>df['Object1'] = pd.to_timedelta(df['Object1'], unit='s') df['Object2'] = pd.to_timedelta(df['Object2'], unit='s') </code></pre> <p>Or...
python|pandas|matplotlib|label|duration
10
368,939
50,016,961
Side by Side plots in matplotlib
<p>I have the following 2 <code>df</code>s that are an exponential and poisson plot</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt mean = 2 step = 0.5 df1 = pd.DataFrame() df1['A'] = pd.Series(abs(np.random.exponential(step, 400))) df2 = pd.DataFrame() df2['B'] = pd.Series(abs(n...
<p>You need to only create one figure, then create the subplots and pass them in as arguments to the plotting function:</p> <pre><code>plt.figure(1) ax1 = plt.subplot(221) df1_summ.plot.bar(x='A', y='counts', ax=ax1, figsize=(5, 4), title='Exponential Plot') ax2 = plt.subplot(222) df2_summ.plot.bar(x='B', y='counts',...
python|pandas|matplotlib
3
368,940
50,032,647
Pandas fillna with inplace=True changes all dataframes that are equal to the one that it is supposed to operate on
<pre><code>import numpy as np import pandas as pd df = pd.DataFrame([[np.nan, 2, 1, 0], [3, 4, np.nan, 1], [np.nan, np.nan, 8, 5], [np.nan, 3, np.nan, 4]], columns=list('ABCD')) df2 = df df.fillna(value = df.mean(), inplace=True) </code></pre> <p>Now df2...
<p>Consider making a copy of <code>df</code> using <code>copy</code> method: <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html</a></p>
python|pandas
0
368,941
49,895,663
How to shift values using pandas in python dataframe?
<p>I have a dataframe like this,</p> <pre><code>d = {'ID': ["A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F"], 'value': [23, 23, 52, 52, 36, 36, 46, 46, 9, 9, 110, 110]} df = pd.DataFrame(data=d) ID value 0 A 23 1 A 23 2 B 52 3 B 52 4 C 36 5 C 36 6 D 46 7...
<p>I think need:</p> <pre><code>df = df.set_index('ID').shift().iloc[1:-1].reset_index() print (df) ID value 0 A 23.0 1 B 23.0 2 B 52.0 3 C 52.0 4 C 36.0 5 D 36.0 6 D 46.0 7 E 46.0 8 E 9.0 9 F 9.0 </code></pre>
python|pandas|numpy|dataframe
2
368,942
50,190,684
Why "tf.nn.bidirectional_dynamic_rnn" has a "Incompatible Operations" on TPU when TensorBoard check it?
<p>I meet a problem when I check the "TPU Compatibility" of a bidirectional rnn. The TensorBoard tell me a reversal operation of sequence length vector is incompatible on TPU. I don't know why?</p> <p>My simple code:</p> <pre><code>X_batch = np.array([ [[0., 1., 2.], [8., 2., 1.], [9., 8., 7.]], ...
<p>I have the same issue, I went as far as implementing it on a TPU and ran into the roadblock that it cannot be unrolled because it contains a conditional while loop (loop until end of the input is reached)</p> <p>One possible fix is to pad your input data to constant lengths, and to change the conditional while loop...
tensorflow|google-cloud-tpu
0
368,943
49,904,996
Converting a string of list to list in pandas
<p>I have a pandas column whose values are list of words. But the whole list is datatype string. </p> <p>For example one cell value of this column is </p> <pre><code> a= ['expert executive', 'internal committee period', 'report name', 'entry'] type(a) Out[23]: str </code></pre> <p>But this is stored as string. </...
<p>Use the <strong>ast module</strong>.</p> <p><strong>Ex:</strong></p> <pre><code>import ast import pandas as pd l = "['expert executive', 'internal committee period', 'report name', 'entry']" df = pd.DataFrame({"a": [l]}) print(type(df["a"][0])) df["a"] = df["a"].apply(ast.literal_eval) print(type(df["a"][0])) <...
python|pandas
1
368,944
50,098,753
Pandas read_csv with different date parsers
<p>I have a csv-file with time series data, the first column is the date in the format <code>%Y:%m:%d</code> and the second column is the intraday time in the format '%H:%M:%S'. I would like to import this csv-file into a multiindex dataframe or panel object.</p> <p>With this code, it already works:</p> <pre><code> ...
<p><strong>1st question</strong>:</p> <p>You can create multiple <code>converters</code> and define parsers in dictionary:</p> <pre><code>import pandas as pd temp=u"""Date,Time,Volume 2016:01:04,09:00:00,53645 2016:01:04,09:20:00,0 2016:01:04,09:40:00,0 2016:01:04,10:00:00,1468 2016:01:05,10:00:00,246 2016:01:05,10:...
python|pandas|dataframe|panel-data
5
368,945
50,229,849
Numpy size requirement
<p>I recently stumbled over a strange numpy behavior which I do not understand: I have a list of experiments. Each of the experiments itself is again a list of samples. So I end up with a list of lists. Experiments were conducted under various conditions, so some of them contain more samples than others. They all have ...
<p>Numpy is really a matrix library. It doesn't do well with variable length arrays. All operations must be able to be broadcast, which is not the case in your example...Instead of using Numpy, try using Pandas. It relies on numpy for elementary operations. For example:</p> <pre><code>import pandas as pd import numpy ...
python|numpy
1
368,946
49,823,631
Pythonic way of applying regex to all columns of dataframe
<p>I have a dataframe containing keywords and value in all columns. See the example below. </p> <p><img src="https://i.stack.imgur.com/caIe7.png" alt="Input DataFrame"></p> <p>I want to apply regex to all the columns. So I use for loop and apply the regex:</p> <pre><code>for i in range (1,maxExtended_Keywords): ...
<p>Use <code>pandas.DataFrame.replace</code> with <code>regex=True</code></p> <pre><code>df.replace('^.*:\s*(.*)', r'\1', regex=True) </code></pre> <p>Notice that my pattern uses parentheses to capture the part after the <code>':'</code> and uses a raw string <code>r'\1'</code> to reference that capture group.</p> <...
python|regex|pandas
7
368,947
50,075,783
Error creating a custom layer in tensorflow
<p>I am trying to create a tensorflow layer. </p> <p>At this point, the goal is very simple. In my custom layer, I want to multiply the input by 2. So every time the input passes through the custom layer it should do the following </p> <p>input = 2 * input // just multiplying the input by 2</p>...
<p>It seems from your comment that you just started learning Tensorflow. If that's the case, I highly recommend that you look at Tensorflow "Eager mode". Specifically, the <a href="https://www.tensorflow.org/programmers_guide/eager" rel="nofollow noreferrer">"Programmers Guide"</a> and the <a href="https://www.youtube....
python|tensorflow|deep-learning|keras
1
368,948
49,824,398
Dataframe is empty after merging two dataframes with Pandas
<p>I have two Dataframes in which I am trying to merge using <code>pandas</code>. One table is 4 columns and the other one is 3. I am attempting an inner join on an int64 type column. <img src="https://i.stack.imgur.com/A6WR5.png" alt="Picture showing datatypes"></p> <p>On the link you can see both columns named UPC a...
<p>I think you want </p> <pre><code>MPA_COMMODITY.merge(MDM_LINK_VIEW, on='UPC') </code></pre> <p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html</a></p>
python|pandas|dataframe
0
368,949
50,165,399
Scipy Optimized Curve - warning the covariates could not be estimated
<p>I have a dataset like this:</p> <pre><code> elevation Tree_cover dNBR below_ground_carbon_combusted DOB_lst 0 266.444444 39.555556 0.47 1110.603930 221.879608 1 683.222222 7.555556 0.48 2901.511339 236.847916 2 270.777778 44.111111 0.54 ...
<p><strong>Why?</strong> Basically, it is caused by the return values, since your function return a zero array over every iteration.</p> <p>And the reason why result is zero is because <code>e**var3</code>. Since var3 is highly negative, so <code>e**var3</code> would appoach to zero</p> <p><strong>How to fix it?</str...
python|pandas|scipy
3
368,950
50,002,131
pandas read multiple tables with different number of columns
<p>My apologies if this sounds like a repeated question, I found a number of related posts on this topic but none seems to provide me a solution for my specific version. I am trying to read a space separated tabular data file with two different tables that alternate throughout the file. Here is a sample </p> <pre><cod...
<p>Just thought to add my solution here, which is to: </p> <ol> <li>first read the entire contents (table) with extra padded columns to cater for longer lines of text;</li> <li>then iterate and read the two different tables (based on given number of rows) into two different data frames (skipping the header lines);</li...
python|pandas
0
368,951
50,049,055
How can I groupby a dataFrame whose columns names are tuples?
<p>I have a dataFrame that I created inside 4 loops. I'm not sure if this is the best way to do it, but after long research I only managed to create a dataFrame with tuples of lenght 4 as column names. I now need to groupby all columns with conditions in <em>some</em> of the entries in the tuple, not in order. Here's a...
<p>To create easily a DF with 16 columns named with tuples, you can do:</p> <pre><code>import pandas as pd import itertools list_ind = [['I0', 'I1'], ['J0', 'J1'], ['K0', 'K1'], ['L0', 'L1']] list_col = list(itertools.product(*list_ind)) # all permutations possible df1 = pd.DataFrame(columns = list_col ) </code></pre>...
python|pandas|pandas-groupby
1
368,952
50,173,489
save a named tuple in all rows of a pandas dataframe
<p>I'm trying to save a named tuple <code>n=NamedTuple(value1='x'=, value2='y')</code> in a row of a pandas dataframe.</p> <p>The problem is that the named tuple is showing a length of 2 because it has 2 parameters in my case (value1 and value2), so it doesn't fit it into a single cell of the dataframe.</p> <p>How ca...
<p>I don't really understand what you're trying to do, but if you want to put that named tuple in every row of a new column (i.e. like a scalar) then you can't rely on broadcasting but should instead replicate it yourself:</p> <pre><code>df['nt'] = [n1 for _ in range(df.shape[0])] </code></pre>
pandas|namedtuple
1
368,953
50,099,922
AttributeError: 'DataFrame' object has no attribute 'label'
<p>I created a data frame using the following line: </p> <pre><code>df = pd.read_csv('/Users/cs213/Desktop/class1.csv', sep = ',', error_bad_lines=False) </code></pre> <p>and if print the columns as such</p> <pre><code>print (df.columns) </code></pre> <p>I get </p> <blockquote> <p>Index(['Text', 'label'], dtype...
<p>EDIT 1: </p> <p>Reproducible sample of your CSV :</p> <pre><code>df = pd.DataFrame({'Text': [u'Well I am', u"Not my scene", u"Brutal"], 'label': ['y', 'n', 'n']}) </code></pre> <p>The function you are trying to run:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'Text': [u'Well I am', u"Not my scene", u"Brutal"]...
python|pandas
2
368,954
49,932,322
Average if in Python with 2 time series
<p>I want to average the mean value like the average if function in python.</p> <p>For example let's say I have a set of ranks for A,B,C,D as 'df' like this picture: <a href="https://i.stack.imgur.com/N6egI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N6egI.png" alt="rank"></a></p> <p>and I wan...
<pre><code>ranks = pandas.DataFrame([[1,2,3,4], [1,3,2,4]], columns=['A','B', 'C', 'D'], index=['2000-01-31', '2000-02-01']) amounts = pandas.DataFrame([[1,4,1,1], [1,1,1,1]], columns=['A','B', 'C', 'D'], index=['2000-01-31', '2000-02-01']) top = amounts[ranks&lt;3].mean(axis=1) bot = amounts[ranks&gt;=3].mean(axis=1)...
python|pandas|conditional-statements
0
368,955
50,088,464
Little speedup when porting Python code to Cython
<p>I have some python code which uses numpy which computes gradient of a function and this is a big bottleneck in my application. So, my initial attempt was to try to use <code>Cython</code> to improve the performance.</p> <p>So, using online guides, I was able to port this to Cython easily but got a very moderate spe...
<p>Ok, after playing around a bit, it turns out that the main thing that will boost speed is using ctypes. Here is the modified code which offers about 13x speedup. I am leaving it here in case it will be of use to someone else. I am sure more performance can be extracted but I will be hitting diminishing returns.</p> ...
python|performance|numpy|cython|cythonize
0
368,956
50,179,369
Removing duplicate columns from pandas.read_csv()
<p>By default, <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="noreferrer"><code>pandas.read_csv()</code></a> mangles duplicate CSV headers in the form of X, X.1, ..., X.N.</p> <p>The flag <code>mangle_dupe_cols = False</code> returns:</p> <p><code>ValueError: Setting mangle...
<p>I might do something like</p> <pre><code>In [22]: df = pd.read_csv("dup.col") In [23]: df Out[23]: A A.1 B C C.1 C.2 D E C.3 0 1 2 3 4 5 6 7 8 9 1 1 2 3 4 5 6 7 8 9 In [24]: df.loc[:, ~df.columns.str.replace("(\.\d+)$", "").duplicated()] Out[24]: A B C D E 0 ...
python|python-3.x|pandas
5
368,957
50,008,120
Getting dimension mismatch error when i try to predict with naive bayes / Python
<p>I've created a sentiment script and use Naive Bayes to classify the reviews. I trained and tested my model and saved it in a Pickle object. Now I would like to perform on a new dataset my prediction but I always get following error message </p> <pre><code>raise ValueError('dimension mismatch') ValueError: dimension...
<p>You need to save the CountVectorizer object too just as you are saving the <code>nb</code>. </p> <p>When you call</p> <p><code>CountVectorizer(analyzer=text_process).fit(x)</code></p> <p>you are re-training the CountVectorizer on new data, so the features (vocabulary) found by it will be different than at the tra...
python|scikit-learn|naivebayes|sklearn-pandas
1
368,958
50,042,609
How to hide tensorflow.js code and trained model?
<p>I am trying to make sure that the classification, training process and the model is <strong>hidden</strong> while used in browser. I have found that wasm is kind of binary format for web browser to execute. <strong>Can I use wasm?</strong></p> <ul> <li><p>Is there a way in tensorflow or in js to hide my training or...
<p>There is currently not yet a good way to simultaneously run your TFJS model in a users' browser, and also keep your model secret. If model privacy is a design constraint, you will need to either do some sever-side computation, or invent some other solution.</p> <p><a href="https://github.com/tensorflow/tfjs/issues...
javascript|c++|tensorflow|webassembly|tensorflow.js
3
368,959
64,040,444
Nested renamer not supported , how do I rebuild this code?
<p>I am writting this code but appear this error:</p> <p>THis is my Code found at <a href="https://github.com/statisticianinstilettos/recmetrics/blob/master/example.ipynb" rel="nofollow noreferrer">https://github.com/statisticianinstilettos/recmetrics/blob/master/example.ipynb</a>:</p> <pre><code>!pip install scipy !pi...
<p>Use named aggregation:</p> <pre><code>test = pd.DataFrame({ 'movieId':[5,3,3,9,2,4,9], 'userId':list('aaabbbb') }) test = test.groupby('userId').agg(actual = ('movieId', lambda x: list(set(x)))) print (test) actual userId a [3, 5] b [9, 2, 4] </code></pre> <...
python|pandas|dataframe
0
368,960
63,953,163
How to save keras custom model with dynamic input shape in SaveModel format?
<p>I have a custom model with dynamic input shape (flexible second dimension).</p> <p>I need to save it in SaveModel format. But it saves only one signature (the first used).</p> <p>When I try to use different signature after loading - I am getting an error:</p> <blockquote> <p>Python inputs incompatible with input_sig...
<p>Try creating the model using different Input shape, and using functional API:</p> <pre class="lang-py prettyprint-override"><code>def create_model(batch_size, seq_len): inputs = tf.keras.Input(shape=(batch_size, seq_len)) #input layer x = tf.keras.layers...(inputs) # next layer x = tf.keras.layers...(x) ...
python|tensorflow|keras
1
368,961
63,866,492
Can I create a reference index column that resets from 0 every time a cumsum threshold is reached
<p>I am trying to add a cummulative sum column and an new index column n_index. Using exiting answers I have added a cumsum colum but the reference index column I have is not what I need.</p> <pre><code>df = pd.DataFrame({'amount':[4, 3, 7, 8, 2, 1, 5, 3, 5, 8]}) ls = [] n_index = [] cumsum = 0 last_reset = 0 threshol...
<p>Hope, you got your expected result, and remove the error.</p> <pre><code>df = pd.DataFrame({'amount':[4, 3, 7, 8, 2, 1, 5, 3, 5, 8]}) ls = [] n_index = [] cumsum = 0 last_reset = 0 threshold = 16 assign_indx=0 for i, row in df.iterrows(): if cumsum + row.amount &lt;= threshold: cumsum = cumsum ...
pandas|cumsum
1
368,962
64,111,342
Change bar colors plotly
<p>Here is my code. I've done this before and it's worked. I want the negative bars to be red and the positive bars to be green but I'm just getting all yellow.</p> <pre><code>import pandas as pd import plotly.express as px deciles = pd.read_csv('https://github.com/ngpsu22/2016-2018-ASEC-/raw/master/deciles.csv') f...
<p>You better add a new columns called <code>color</code> and use within <code>plotly.express</code> or <code>import plotly.graph_objects as go</code></p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import plotly.express as px import numpy as np deciles = pd.read_csv('https://github.com/ngpsu22...
python|pandas|plotly
1
368,963
64,125,019
How to tokenize punctuations using the Tokenizer function tensorflow
<p>I use the <code>Tokenizer()</code> function from <code>tensorflow.keras.preprocessing.text</code> as :</p> <pre><code>from tensorflow.keras.preprocessing.text import Tokenizer s = [&quot;The quick brown fox jumped over the lazy dog.&quot;] t = Tokenizer() t.fit_on_texts(s) print(t.word_index) </code></pre> <p>Output...
<p>A possibility is to separate the punctuations from the words with spaces. I do this with a preprocess function <code>pad_punctuation</code>. after this I apply <code>Tokenizer</code> with <code>filter=''</code></p> <pre><code>import re import string from tensorflow.keras.preprocessing.text import Tokenizer def pad_...
python|tensorflow|keras|nlp|tokenize
1
368,964
63,882,254
Is it possible to use the same k-folds in cross_val_predict that are in cross_val_score?
<p>Hi if we do the following to calculate cross validated accuracy:</p> <pre><code>cv_acc = cross_val_score(model, X_train, y_train, cv=5, scoring='accuracy') </code></pre> <p>Is it possible to estimate the y predictions and create a confusion matrix (as below) using the same inputs to the k-folds in <code>cross_va...
<p>The following should work:</p> <pre><code>from sklearn.model_selection import KFold, cross_val_score, cross_val_predict k_folds = KFold(n_splits=5) splits = list(k_folds.split(X_train, y_train)) # note list here as k_folds.split is a one-off generator cv_acc = cross_val_score(model, X_train, y_train, cv=splits, scor...
python|pandas|dataframe|scikit-learn|classification
1
368,965
64,028,309
Pandas concatenation results in NaNs?
<p>What seems to be a simple function returns NaNs instead of the actual numbers. What am I missing here?</p> <pre><code>#Concatenate the dataframes: dfcal = dfcal.astype(float) dfmag = dfmag.astype(float) print('dfcal\n-----',dfcal) print('dfmag\n-----',dfmag) df = pd.concat([dfcal,dfmag]) print('concatresult\n-----',...
<p>I guess you need <code>axis=1</code> for append new columns, selected column <code>caliper</code> for avoid duplicated <code>depth</code> columns:</p> <pre><code>df = pd.concat([dfcal['caliper'],dfmag], axis=1) </code></pre> <p>Or:</p> <pre><code>df = pd.concat([dfcal.drop('depth', axis=1),dfmag], axis=1) </code></p...
python|pandas|concatenation
2
368,966
64,136,786
Creating stacked bar chart from dataframe
<p>I have a table with different scenarios in rows, and values associated with them in columns</p> <p>Like this</p> <pre><code>| Scenario | A | B | C | |:-----------|-----:|------:|----:| | Scen1 | 6.5 | 0.125 | 52 | | Scen2 | 16.5 | 1.125 | 152 | | Scen3 | 26.5 | 2.125 | 252 | </code></pre>...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a> for preprocessing data:</p> <pre><code>df = df.reset_index().melt('Scenario') print (df) Scenario variable value 0 Scen1 A 6.500 1 Scen2 ...
pandas|plotly-python
1
368,967
63,982,675
Rolling mean of 1 year after filtering of data in pandas dataframe
<p>I am trying to calculate the rolling mean for 1 year in the below pandas dataframe. 'mean_1year' for the below dataframe is calcualted using the 1 year calculation based on month and year.</p> <p>For example, month and year of first row in the below dataframe is '05' and '2016'. Hence 'mean_1year' is calculated usin...
<p>First you need a datetime index in ascending order so you can apply a rolling time period calculation.</p> <pre><code>df['date'] = pd.to_datetime(df['year'].astype('str')+'-'+df['month'].astype('str')) df = df.set_index('date') df = df.sort_index() </code></pre> <p>Then you groupby type and apply the rolling mean.</...
python|pandas
2
368,968
64,142,086
Inserting a new column with date format in Python
<p>I have a dataframe, df, where I am wanting to insert a new column named data in specific format.</p> <p>df:</p> <pre><code> Name ID Kelly A John B </code></pre> <p>Desired output:</p> <pre><code> Date Name ID 2019-10-01 Kelly A 2019-10-01 John B...
<p>Try with</p> <pre><code> df['date'] = '2019-10-01' </code></pre>
python|pandas|numpy
2
368,969
64,113,700
How can we check if a matrix is PSD is PyTorch?
<p>There is a <a href="https://stackoverflow.com/questions/16266720/find-out-if-matrix-is-positive-definite-with-numpy">poste</a> on checking if a matrix is PSD in Python. I am wondering how we can check it in PyTorch? is there a function for that?</p>
<p>Haven't found a PyTorch function for that, but you should be able to determine it easily, and similarly to the post you've linked, by checking whether the matrix is symmetric and all eigenvalues are non-negative:</p> <pre><code>def is_psd(mat): return bool((mat == mat.T).all() and (torch.eig(mat)[0][:,0]&gt;=0)....
matrix|pytorch|decomposition
5
368,970
63,779,711
Find paired records after groupby Python
<p>I have a dataframe like this:</p> <pre><code>df = pd.DataFrame( [['101', 'a', 'in', '10'], ['101', 'a', 'out', '10'], ['102', 'b', 'in', '20'], ['103', 'c', 'in', '30'], ['103', 'c', 'out', '40']], columns=['col1', 'col2', 'col3', 'col4'] ) </code></pre> <p>I want to group by col1 and...
<p>Let us try <code>transform</code> with <code>nunique</code></p> <pre><code>out = df[df.groupby(['col1','col2','col4'])['col3'].transform('nunique')==2] Out[187]: col1 col2 col3 col4 0 101 a in 10 1 101 a out 10 </code></pre>
python|pandas
3
368,971
64,138,890
efficient way to check every value in a 2d python array
<p>I have a 2D numpy array of values, a list of x-coordinates, and a list of y-coordinates. the x-coordinates increase left-to-right and the y-coordinates increase top-to-bottom.</p> <p>For example:</p> <pre><code>a = np.random.random((3, 3)) a[0][1] = 9.0 a[0][2] = 9.0 a[1][1] = 9.0 a[1][2] = 9.0 xs = list(range(1112,...
<p>You can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.nonzero.html" rel="nofollow noreferrer"><code>np.nonzero</code></a> to get the indices of the elements you removed:</p> <pre><code>mask = a &lt; 1 i, j = np.nonzero(mask) </code></pre> <p>The fancy indices <code>i</code> and <code>j</code> c...
python|arrays|numpy
1
368,972
63,849,171
How to split dataframe made from objects?
<p>I want to split one column pandas dataframe that look like this:</p> <pre><code> 0 0 38 A 1 35 B 2 14 B </code></pre> <p>into two columns:</p> <p>So it can look like this:</p> <pre><code> Number Letter 0 38 A 1 35 B 2 14 B </code></pre> <p>But its showing type as:</p> <pre><co...
<p>You can do this a couple of ways and possibly more:</p> <p>Using: <code>df = pd.read_clipboard(sep='\s\s+')</code> capture dataframe above.</p> <h3>Option 1 (Use string accessor and split):</h3> <pre><code>df['0'].str.split(' ', expand=True).set_axis(['Number', 'Letter'], axis=1) </code></pre> <h3>Option 2 (use stri...
python|pandas|dataframe|split
3
368,973
64,074,398
List comprehension instead of nested for loop
<p>I have this which works, but I would like to put this into a list comprehension to save computing power</p> <pre><code>emp_id=df_hours[&quot;EMPLOYEE&quot;] emp_list=df_item[&quot;EMPLOYEE&quot;] ############## #loop through and get values for the day for hours worked per server, and add them to building df #######...
<p>Here's a shorter, more elegant way:</p> <pre><code>print(list(set(df_hours[&quot;EMPLOYEE&quot;]).intersection(set(df_item[&quot;EMPLOYEE&quot;])))) </code></pre> <p>Since what you are looking for is getting a list with all common values, you can transform each column to a set, and get the intersection. Then you can...
python|pandas|for-loop|nested
0
368,974
64,173,585
Fast way to apply a function on each pixel of a PIL Image
<p>I need to apply a function to each pixel in <strong>large</strong> <code>PIL</code> Images. I found similar questions here, but somehow the answers never worked for me (mostly, because they were specific to the function).</p> <p>Going through every pixel with two for-loops works, but is insanely slow. So I thought, ...
<p>In general, you have probably already gone wrong if you think about converting images to lists and using <code>for</code> loops in Python. You really need to be vectorising with Numpy or Numba or <code>numexpr</code> or somesuch.</p> <p>Here is a way to do that on your function:</p> <pre><code>#!/usr/bin/env python3...
python-3.x|python-imaging-library|numpy-ndarray
2
368,975
64,110,166
How to create bins for a dataframe column if the range is given
<pre><code>data = {'Age':[18, 22,29,32,35,38,42,54,47]} df = pd.DataFrame(data) df </code></pre> <p>This is an example data frame that I want to play with</p> <pre><code>pd.cut(df['Age'],bins=5) </code></pre> <p>If I do this, I get the output as:</p> <pre><code>0 (17.964, 25.2] 1 (17.964, 25.2] 2 (25.2, 32....
<p>You can pass an array to <code>bins</code>:</p> <pre><code>pd.cut(df['Age'], bins=np.linspace(18, 58, 100), include_lowest=True) </code></pre> <p>Output:</p> <pre><code>0 (17.999, 18.404] 1 (21.636, 22.04] 2 (28.909, 29.313] 3 (31.737, 32.141] 4 (34.97, 35.374] 5 (37.798, 38.202] 6 (41.838, 42...
python|pandas|numpy|dataframe
0
368,976
63,841,842
Tensorflow not importing properly - Tensor flow version 2.3.0, Python 3.8.3
<p>I am trying to resolve below issue with many permutation combination but end-up with some issue.</p> <p><strong>Environment used:</strong></p> <blockquote> <p>python 3.8.3 Anaconda 1.9.12 ,<br /> Tensorflow CPU version 2.3 which supports python 3.8 as per Tensorflow website.<br /> Created new environment in Anacond...
<p>** Issue Resolved **</p> <p><strong>Solution:</strong> As I was using Anaconda so as per advise from anaconda its better to install the tensorflow using conda install command (<a href="https://www.anaconda.com/blog/tensorflow-in-anaconda" rel="nofollow noreferrer">https://www.anaconda.com/blog/tensorflow-in-anaconda...
python|tensorflow|machine-learning|pycharm|anaconda
0
368,977
63,841,548
How do you find and mark duplicates within a panda data frame?
<p>here is my setup:</p> <pre><code>import pandas as pd import uuid data = {'col1': ['val1','val1','val1','val2','val2', 'val3'], 'col2': ['val4','val4','val4','val5','val5', 'val5'] } df = pd.DataFrame(data) print (df) &gt; col1 col2 &gt; 0 val1 val4 &gt; 1 val1 val4 &gt; 2 val1 val4 &gt; 3...
<p>One idea is generate <code>uuid</code> by length of DataFrame (added 10% size) and remove possible duplicates, then mapping groups by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.ngroup.html" rel="nofollow noreferrer"><code>GroupBy.ngroup</code></a>:</p> <pre><code>s...
python|pandas|dataframe|duplicates
2
368,978
64,077,834
AttributeError: 'Function' object has no attribute 'block_variable'
<p>I have written a subclass of torch_fenics. In this, the input is a vector from DG space. I use this input in the weak formulation and then calculate the solution. Further, I need the gradient of the solution with respect to the given input.</p> <pre><code> I get the following error log on running the same </code></p...
<p>Don't import dolfin in your code. It will resolve the issue.</p>
pytorch|fenics
1
368,979
63,891,607
How to create a column with hour interval from two columns in Python?
<p>i have the following dataframe structure:</p> <pre><code>exec_start_date exec_finish_date hour_start hour_finish session_qtd 2020-03-01 2020-03-02 22 0 1 2020-03-05 2020-03-05 22 23 3 2020-03-03 2020-03-04 18 7 ...
<p>So the way I would do this is to get the full dates to get the time interval, then just pull the hours from that range. <code>np.arange</code> will not work because hours loop.</p> <pre><code>#Create two new temp columns that calculate have the full start and end date df['start'] = df['exec_start_date'].astype(str) ...
python|pandas
2
368,980
63,817,772
How to randomly select a row based on given probabilities in Pandas
<p>I have a dataframe like this:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame([['a',0,0.2],['b',0,0.3], ... ['c',0,0.5], ... ['a',1,0.4],['b',1,0.3],['c',1,0.3], ... ['a',2,0.5],['b',2,0.5]] ... ,columns=['place','ID','prob']) &gt;&gt;&gt; df ...
<p>We can use your <code>prob</code> as weights in <code>DataFrame.sample</code>. Only thing we have to do is to use this in a <code>GroupBy</code>, since we want to do this for each group in <code>place</code>:</p> <pre><code>sample = df.groupby(&quot;ID&quot;).apply(lambda x: x.sample(weights=x[&quot;prob&quot;])) ch...
python|pandas
1
368,981
64,124,648
Create a function as input one of a pandas column (variable) to create plots
<p>I have a dataframe with multiple columns and so variables. I would like to create a function to apply on some variables of the dataframe to create some displots representing mean, median and mode. I found a great code to do so as you will see after.</p> <p>My problem is that I would like to automatize the displot cr...
<p>You could create a variable, call it key=(whatever you want) and then use:</p> <pre><code>mean=df[key].mean() </code></pre> <p>If you'd like to loop through all of this:</p> <pre><code>for key in list(df.columns): ##Do the plotting code; pay attention to not overwriting axes if you want to do this, maybe make ax...
python|pandas|function|dataframe|plot
0
368,982
63,951,247
Moving a tensor to cuda device cause illegal memory access in Pytorch
<p>I am trying the following snippet in Colab but causes the following error. Is it wrong to move a tensor object to Cuda device?.</p> <pre><code>import torch a = torch.Tensor(torch.randn(5,5,5)) # a.device(&quot;cuda&quot;) device = torch.device(&quot;cuda&quot;) class abc(torch.nn.Module): def __init__(self): ...
<p>This works for me on Google colab:</p> <pre class="lang-py prettyprint-override"><code>import torch a = torch.randn(5,5,5) a = a.to(&quot;cuda&quot;) # or just a = torch.randn((5,5,5), device='cuda') class abc(torch.nn.Module): def __init__(self): super().__init__() self.w1 = torch.nn.Linear(5,5...
python|deep-learning|pytorch|google-colaboratory
1
368,983
63,742,247
Python Pandas Move Na or Null values to a new dataframe
<p>I know I can drop NaN rows from a DataFrame with <code>df.dropna()</code>. But what if I want to move those NaN rows to a new DataFrame? Dataframe looks like</p> <pre><code>FNAME, LNAME, ADDRESS, latitude, logitude, altitude BOB, JONES, 555 Seaseme Street, 38.00,-91.00,0.0 JOHN, GREEN, 111 Maple Street, 34.00,-75.00...
<p>Assuming you're satisfied that all <code>'Nan'</code> values in a column are to be grouped together, what you can do is use <code>DataFrame.fillna()</code> to convert the <code>'Nan'</code> into something else, to be grouped.</p> <pre><code>df.fillna(value={'altitude':'null_altitudes'} </code></pre> <p>This fills e...
python-3.x|pandas|dataframe
1
368,984
64,050,319
Replace DataFrame column with nested dictionary value
<p>I'm trying to replace the 'starters' column of this DataFrame</p> <pre><code> starters roster_id Bob 3086 Bob 1234 Cam 6130 ... ... </code></pre> <p>with the player names from a large nested dict like this. The values in my 'starters' column are the k...
<p>I am not sure, if I understand your question correctly. Have you tried using dict['full_name'] instead of simply dict?</p>
python|pandas|dictionary
0
368,985
64,063,831
Issue when exporting dataframe to csv
<p>I'm working on a mechanical engineering project. For the following code, the user enters the number of cylinders that their compressor has. A dataframe is then created with the correct number of columns and is exported to Excel as a CSV file.</p> <p>The outputted dataframe looks exactly like I want it to as shown in...
<p>To be clear, a comma-separated values (CSV) file is not an Excel format type or table. It is a delimited text file that Excel like other applications can open.</p> <p>What you are comparing is simply presentation. Both data frames are exactly the same. For multindex data frames, Pandas print output does not repeat ...
python-3.x|pandas|dataframe|jupyter-notebook|export-to-csv
0
368,986
63,825,063
using pandas Generate csv file using if condition
<p>I have columns like <code>start_time</code>, <code>end_time</code> and <code>time_taken</code> in minutes. I want to generate a csv file with full data <strong>only if <code>time_taken</code> equals to 10 minutes</strong>.</p> <p>My current code is:</p> <pre><code>if ( df['time_taken']) == 10: df.to_csv(r'result.c...
<p>You can subset the dataframe before saving, thus only saving the part of the dataframe that matches your condition:</p> <pre><code>df.loc[df.time_taken == 10].to_csv(&quot;results.csv&quot;) </code></pre> <p>You might want to read up on <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataF...
python|pandas|if-statement
0
368,987
63,817,173
Strange value formatting when converting lists to numpy array
<p>I'm experiencing something strange when converting a regular array (lists within a list), to a numpy.array. All the values seem to be normalized in a strange manner. This is my regular list:</p> <pre><code>print(output) print(type(output)) result: [[0, 301227, 0.86, 0.46, -3.55, 0.53, 135.96, 4, 0.49, 0.33, 0.33 .....
<p>The values remain intact, it just another form of representation called <a href="https://en.wikipedia.org/wiki/Scientific_notation#E_notation" rel="nofollow noreferrer">E notation</a>,</p> <p>The number <code>mEn</code> is divided into two parts, before and after the <code>e</code>:</p> <ol> <li><code>m</code> The p...
python|arrays|numpy|jupyter
0
368,988
63,878,084
tensorflow gpu tests pass--but I don't have cuDNN installed
<p>Windows10-pro, single RTX 2080 Ti. I am new to Tensorflow.</p> <p>I just installed tensorflow-gpu, version 2.1.0, python 3.7.7. Cuda compilation tools, release 10.1, V10.1.105. Nothing self-compiled. And I have not installed cuDNN, nor have I registered. All installation is standard, nothing self-compiled.</p> <...
<p>In NVIDIA GPU computing toolkit, one can verify the cuDNN installation, On windows system, Go to</p> <pre><code>C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.0\include\ open cudnn.h </code></pre> <p>To utilize the Tensorflow-GPU successfully, CUDA and cuDNN are required. Some of the Tensorflow library suc...
python|tensorflow|gpu
0
368,989
64,140,601
how to apply a function (matrix -> scalar) to 3 dim a numpy array in python
<p>Say I have 3 dimensional numpy array <code>a</code>, for example as below:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np a = np.random.randn(3, 3, 3) </code></pre> <p>How can I apply (matrix-&gt;scalar)-type function to <code>a</code>? More specifically, I want to do an equivalent thing as b...
<p><code>np.linalg.det(a)</code> seems to work just fine and has significantly better runtime:</p> <pre><code>a = np.random.rand(100,3,3) %timeit -n 100 [np.linalg.det(e) for e in a] 626 µs ± 26.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) %timeit -n 100 np.linalg.det(a) 33.9 µs ± 7.08 µs per loop (mean...
python|arrays|numpy
2
368,990
64,048,662
Pandas astype int not removing decimal points from values
<p>I tried converting the values in some columns of a DataFrame of floats to integers by using round then astype. However, the values still contained decimal places. What is wrong with my code?</p> <pre><code>nums = np.arange(1, 11) arr = np.array(nums) arr = arr.reshape((2, 5)) df = pd.DataFrame(arr) df += 0.1 df </co...
<p>The problem is for the <code>.iloc</code> it assign the value and did not change the column type</p> <pre><code>l = df.columns[2:] df[l] = df[l].astype(int) df 0 1 2 3 4 0 1.1 2.1 3 4 5 1 6.1 7.1 8 9 10 </code></pre>
python|pandas
5
368,991
63,885,394
Pandas read_csv not splitting columns according to the separator
<p>I have data from John Hopkins Github. <a href="https://github.com/CSSEGISandData/COVID-19/tree/master/csse_covid_19_data/csse_covid_19_time_series" rel="nofollow noreferrer">https://github.com/CSSEGISandData/COVID-19/tree/master/csse_covid_19_data/csse_covid_19_time_series</a></p> <p>I want to import the data using ...
<p>I cannot reproduce the issue. Here I'm importing directly the raw csv file from the github link the OP provided.</p> <pre><code>import pandas as pd df = pd.read_csv(&quot;https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_glob...
python|pandas
1
368,992
63,884,825
merging pandas dataframes on multiple columns - error about levels
<p>I'm merging my two dataframes below on two fields.</p> <pre><code>successes = pd.merge(failures, successes, left_on=['name', 'project_name'], right_on=['name', 'project_name'], how='left') </code></pre> <p>But I get this error - can anyone help me out please?</p> <pre><code>/usr/local/lib/python3.8/site-packages/pan...
<p>I think it must be written this way:</p> <p><code>successes.merge(failures, on=['name', 'project_name'])</code></p>
python-3.x|pandas
0
368,993
64,099,396
Flatten a list containing numpy arrays with different shapes
<p>I am trying to find a solution for flattening the following lists of numpy arrays:</p> <pre><code>a = np.arange(9).reshape(3,3) b = np.arange(25).reshape(5,5) c = np.arange(4).reshape(2,2) myarrs = [a,b,c] d = np.arange(5*5*5).reshape(5,5,5) myarrs2 = [a,b,c,d] </code></pre> <p>For my <code>myarrs</code> I am using...
<p>You could try something like:</p> <pre><code>np.concatenate([x.ravel() for x in myarrs]) </code></pre> <p>This should be faster than your approach:</p> <pre><code>a = np.arange(9).reshape(3,3) b = np.arange(25).reshape(5,5) c = np.arange(4).reshape(2,2) myarrs = [a,b,c] res = np.concatenate([x.ravel() for x in mya...
python|arrays|numpy
6
368,994
63,943,846
numpy.dot as part of a vectorized operation
<p>Say I have three numpy arrays and I want to perform a calculation over them:</p> <pre><code>a = np.array([[1,2,3,4,5,6,7],[1,2,3,4,5,6,7],[1,2,3,4,5,6,7],[1,2,3,4,5,6,7], [1,2,3,4,5,6,7]]) #shape is (5,7) b = np.array([[11],[12],[11],[12],[11]]) #shape is (5,1) c = np.array([[10],[20],[30],[40],[50],[60],[70]]) #sh...
<pre><code>In [31]: a = np.array([[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8]]) #shape is (5,7) ...: b = np.array([[11],[12],[11],[12],[11]]) #shape is (5,1) ...: c = np.array([[10],[20],[30],[40],[50],[60],[70]]) #shape is (7,1) In [32]: a.shape, b.shape, c.shape Out[32]: ((7, 2), (5, 1), (7, 1)) </code></pre> <...
python|arrays|numpy
1
368,995
64,058,750
How To Slove Error For The Login Code In Python Using CSV File?
<p>This is my code for Verifying User ID and password from a csv file.</p> <blockquote> <p>CODE</p> </blockquote> <pre><code>import pandas as pd login(): df=pd.read_csv(&quot;IDPASS.csv&quot;) for i in range(len(df)): x=input(&quot;Enter User Name=&quot;) y=input(&quot;ENter The Password=&quot;) if (df.iloc...
<p>After the clarification, this should be the functionality you are seeking.</p> <p>First import pandas and read the csv:</p> <pre><code>import pandas as pd df = pd.read_csv(&quot;IDPASS.csv&quot;) </code></pre> <p>We will now read the values stored in the csv and store them as a list. A list of users and a list of pa...
python|pandas|dataframe|loops|csv
1
368,996
63,890,896
I am stuck at encoding CSV dataset (String columns) to Training data
<p>I am trying to fit my dataframe data (string columns) to my test_data[features] from a csv file.</p> <p>My code is as below:</p> <pre><code>import numpy as np import pandas as pd from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_absolute_error from sklearn.model_selection import tra...
<p>The mistake I was making was trying to fit the columns directly without splitting into training and validation dataset. This is code that can be used to fit:</p> <pre><code>test_data_features = test_data[features] # Filling all NA values as Encoder cannot handle nan values df = test_data.fillna(1) # Define Y for Fi...
python-3.x|string|predict|sklearn-pandas|one-hot-encoding
0
368,997
63,902,865
Which function to use to plot linear correlation graph of data from 3 different databases
<p>I need to correlate three databases, telemetry3h, telemetry24h and error_coun.</p> <p>I don't know how to relate the <code>df.corr()</code> function of pandas to the problem, I could not write this part of the code.</p> <p>I need to get to this result, but I can not find a function that works, does anyone have any t...
<p>I think what you are looking for is a way to join your columns and then to find the correlation between each of the columns in your dataframe, correct?</p> <p>I loaded your sample like this:</p> <pre><code>#creation of first dataframe values_one = [[1 , '2015-01-02 06:00:00', 169.73380889577277, 445.17986460181...
python|pandas|matplotlib
0
368,998
64,067,623
converting a list of dictionary from a single column of a Data Frame into different columns in pandas
<p><strong>I have a Data Frame named &quot;data&quot;</strong></p> <pre><code> updated_at values user_id 0 2020-08-18 [{'value': 3742, 'key': '0'}, 178414113 {'value': 3813, 'key': '1'}, {'value': 3918, 'key': '2'}, {'val...
<p>You can use the <code>explode()</code> method to expand your column of lists into a separate row for each entry in those lists. Then you can leverage <code>apply(pd.Series)</code> to expand the resulting dictionaries in each row:</p> <pre><code>exploded = df.explode('values').reset_index(drop=True) exploded[['value'...
pandas|list|dataframe|dictionary|data-wrangling
0
368,999
64,003,278
Calculating Percentage with for loop with a group by
<p>If I have the below code with loop that gives me the ratio of lost and won types based on below, how would I alter code if I want to look at same data but grouped by professor?</p> <pre><code>leads = ['Passed','Failed'] max_status = None max_percent = None for lead in leads: df_overall = df[(df['Status']== lead)...
<p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.size.html" rel="nofollow noreferrer"><code>GroupBy.size</code></a>:</p> <pre><code>leads = ['Passed','Failed'] lead_df = df[(df['size']== '20-34')] #filter by list leads df_overall = lead_df[lead_df['St...
python|python-3.x|pandas
1